@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +40 -13
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +114 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
  16. package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
  18. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +274 -56
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +5 -5
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  41. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  42. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  44. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  45. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  46. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  47. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  48. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  49. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  50. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  51. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
  54. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
  61. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +3 -3
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  74. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
  75. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  76. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  77. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  82. package/build/BluetoothSdk.types.d.ts +103 -5
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js.map +1 -1
  85. package/build/_private/BluetoothSdkModule.d.ts +42 -8
  86. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  87. package/build/_private/BluetoothSdkModule.js +1 -0
  88. package/build/_private/BluetoothSdkModule.js.map +1 -1
  89. package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  91. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  92. package/build/generated/changelogCatalog.d.ts +2 -2
  93. package/build/generated/changelogCatalog.js +2 -2
  94. package/build/generated/changelogCatalog.js.map +1 -1
  95. package/build/generated/releaseMetadata.js +5 -5
  96. package/build/generated/releaseMetadata.js.map +1 -1
  97. package/build/index.d.ts +1 -1
  98. package/build/index.d.ts.map +1 -1
  99. package/build/index.js +7 -1
  100. package/build/index.js.map +1 -1
  101. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  102. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  103. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  106. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  107. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  108. package/build/ota-transport/index.d.ts +3 -3
  109. package/build/ota-transport/index.d.ts.map +1 -1
  110. package/build/ota-transport/index.js +4 -4
  111. package/build/ota-transport/index.js.map +1 -1
  112. package/build/react/useGlassesConnection.d.ts +1 -1
  113. package/build/react/useGlassesConnection.d.ts.map +1 -1
  114. package/build/react/useGlassesConnection.js +3 -3
  115. package/build/react/useGlassesConnection.js.map +1 -1
  116. package/build/react/useMentraBluetooth.d.ts +1 -1
  117. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  118. package/build/react/useMentraBluetooth.js +1 -1
  119. package/build/react/useMentraBluetooth.js.map +1 -1
  120. package/ios/BluetoothSdkModule.swift +73 -22
  121. package/ios/LocalIPv4.swift +0 -61
  122. package/ios/MentraBluetoothSDK.podspec +7 -1
  123. package/ios/MentraOtaServerModule.swift +0 -16
  124. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  125. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  126. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  127. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  128. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  129. package/ios/Source/Bridge.swift +14 -0
  130. package/ios/Source/DeviceManager.swift +43 -22
  131. package/ios/Source/GeneratedChangelogCatalog.swift +2 -2
  132. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  133. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  134. package/ios/Source/OtaManifest.swift +1 -17
  135. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  136. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  137. package/ios/Source/audio/SpeechActivity.swift +277 -0
  138. package/ios/Source/events/BluetoothEvents.swift +41 -0
  139. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  140. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  141. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  142. package/ios/Source/sgcs/MentraLive.swift +195 -66
  143. package/ios/Source/sgcs/Nimo.swift +249 -276
  144. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  145. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  146. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  147. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  148. package/ios/Source/sgcs/SGCManager.swift +6 -0
  149. package/ios/Source/streaming/StreamModels.swift +15 -6
  150. package/ios/Source/stt/STTTools.swift +13 -31
  151. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  152. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  153. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  154. package/ios/Source/utils/BoundedWait.swift +44 -0
  155. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  156. package/ios/Source/utils/SttModelTraits.swift +62 -0
  157. package/ios/Tests/BesCrashReportTests.swift +142 -0
  158. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  159. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  160. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  161. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  162. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  163. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  164. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  165. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  166. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  167. package/ios/Tests/PcmStreamTests.swift +299 -0
  168. package/ios/Tests/SpeechActivityTests.swift +238 -0
  169. package/ios/Tests/StreamRequestTests.swift +18 -0
  170. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  171. package/package.json +2 -2
  172. package/plugin/build/withAndroid.js +9 -11
  173. package/plugin/build/withKotlinVersion.d.ts +2 -0
  174. package/plugin/build/withKotlinVersion.js +46 -0
  175. package/src/BluetoothSdk.types.ts +107 -5
  176. package/src/_private/BluetoothSdkModule.ts +45 -8
  177. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  178. package/src/generated/changelogCatalog.ts +2 -2
  179. package/src/generated/releaseMetadata.ts +5 -5
  180. package/src/index.ts +13 -1
  181. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  182. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  183. package/src/ota-transport/index.ts +4 -5
  184. package/src/react/useGlassesConnection.ts +4 -4
  185. package/src/react/useMentraBluetooth.ts +2 -2
  186. package/android/silero/LICENSE.md +0 -17
  187. package/android/silero/build.gradle +0 -50
  188. package/android/silero/proguard-rules.pro +0 -24
  189. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  190. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  191. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  198. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  199. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  202. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  203. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  204. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  206. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  207. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  210. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  211. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  212. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  213. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  214. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  215. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -155,6 +155,15 @@ class MentraLive : SGCManager() {
155
155
  private const val A2DP_CONNECT_MAX_ATTEMPTS = 5
156
156
  private const val A2DP_CONNECT_RETRY_MS = 800L
157
157
  private const val UNPAIR_FLUSH_MS = 400L
158
+ /** Classic profile disconnects this soon after the app's own teardown are the app's. */
159
+ private const val OWN_CLASSIC_TEARDOWN_MS = 10_000L
160
+ /** Classic profiles going down this close together are one disconnect of the whole device. */
161
+ private const val CLASSIC_DISCONNECT_PAIR_MS = 3_000L
162
+ /** How long after the Classic drop the glasses must still be answering over BLE. */
163
+ private const val CLASSIC_DISCONNECT_CONFIRM_MS = 2_000L
164
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers,
165
+ // the phone POST), so an unreleased name cannot be reused while its report is in flight.
166
+ internal const val INCIDENT_RELAY_OWNERSHIP_MS = 10 * 60_000L
158
167
  private const val GATT_DISCONNECT_TIMEOUT_MS = 2_000L
159
168
  private const val MTU_CALLBACK_TIMEOUT_MS = 3_000L
160
169
  private val gattTeardownBarrier = MentraLiveGattTeardownBarrier()
@@ -457,6 +466,22 @@ class MentraLive : SGCManager() {
457
466
  }
458
467
  }
459
468
 
469
+ /** The one Mentra Live this phone is bonded with. Null when there is none, several, or no permission to read bonds. */
470
+ fun soleBondedMentraLive(context: Context?): BluetoothDevice? {
471
+ val adapter =
472
+ (context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)
473
+ ?.adapter
474
+ ?: return null
475
+ return try {
476
+ adapter.bondedDevices
477
+ ?.filter { isMentraLiveBluetoothName(safeBondedDeviceName(it)) }
478
+ ?.singleOrNull()
479
+ } catch (e: Exception) {
480
+ Bridge.log("LIVE: Unable to read bonded devices: " + e.message)
481
+ null
482
+ }
483
+ }
484
+
460
485
  private const val SHUTDOWN_RECENT_MS = 45_000L // Consider "recent shutdown" for 45s
461
486
 
462
487
  // Keep-alive parameters
@@ -479,9 +504,9 @@ class MentraLive : SGCManager() {
479
504
  private const val PREFS_NAME = "MentraLivePrefs"
480
505
  private const val PREF_DEVICE_NAME = "LastConnectedDeviceName"
481
506
 
482
- // Auth settings
483
- private const val AUTH_PREFS_NAME = "augmentos_auth_prefs"
484
- private const val KEY_CORE_TOKEN = "core_token"
507
+ // A Core token older builds kept in plain SharedPreferences. Deleted, never read.
508
+ private const val LEGACY_AUTH_PREFS_NAME = "augmentos_auth_prefs"
509
+ private const val LEGACY_KEY_CORE_TOKEN = "core_token"
485
510
 
486
511
  private const val MAX_BONDING_RETRIES = 3
487
512
  private const val BONDING_RETRY_DELAY_MS =
@@ -579,6 +604,13 @@ class MentraLive : SGCManager() {
579
604
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
580
605
  // after an upgrade OTA is always detected as a restart.
581
606
  private var readinessCompletedThisBleSession = false
607
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
608
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
609
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
610
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
611
+ private var pendingReadyId: String? = null
612
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
613
+ private var readyGlassesSessionId: String? = null
582
614
  // Note: appVersion, buildNumber, deviceModel, androidVersion
583
615
  // are inherited from SGCManager parent class
584
616
 
@@ -666,6 +698,13 @@ class MentraLive : SGCManager() {
666
698
  private var secureFirmwareRefreshRunnable: Runnable? = null
667
699
  /** elapsedRealtime of the last GATT link that was not an explicit pairing attempt. */
668
700
  private var lastAutoReconnectLinkAt: Long? = null
701
+ /** elapsedRealtime of the app's last own A2DP/HFP teardown. */
702
+ private var lastOwnClassicTeardownAt: Long? = null
703
+ /** elapsedRealtime when Android started disconnecting each Classic profile. */
704
+ private val classicDisconnectingAt = mutableMapOf<ClassicAudioProfile, Long>()
705
+ private var classicDisconnectCheck: Runnable? = null
706
+ /** elapsedRealtime of the last message from the glasses. */
707
+ private var lastInboundAt = 0L
669
708
  /** Hold GATT teardown until the unpair write can leave the phone. */
670
709
  private var unpairFlushPending = false
671
710
  private var unpairFlushRunnable: Runnable? = null
@@ -823,6 +862,7 @@ class MentraLive : SGCManager() {
823
862
  val apiBaseUrl: String,
824
863
  val kind: BleIncidentLogKind
825
864
  ) {
865
+ val reservedAtMs: Long = SystemClock.elapsedRealtime()
826
866
  var session: FileTransferSession? = null
827
867
  }
828
868
 
@@ -1078,6 +1118,7 @@ class MentraLive : SGCManager() {
1078
1118
  this.type = DeviceTypes.LIVE
1079
1119
  this.hasMic = true
1080
1120
  this.context = Bridge.getContext()
1121
+ forgetLegacyCoreToken()
1081
1122
 
1082
1123
  // Initialize bluetooth adapter
1083
1124
  val bluetoothManager =
@@ -1241,6 +1282,7 @@ class MentraLive : SGCManager() {
1241
1282
  if (state == ConnTypes.DISCONNECTED) {
1242
1283
  resetWireNegotiationState()
1243
1284
  resetPendingAckState()
1285
+ resetReadinessExchange()
1244
1286
  // Queued writes are session-bound: transmitting them into the NEXT session
1245
1287
  // (e.g. a stale handshake whose reply activates v2 before the new session
1246
1288
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1306,6 +1348,7 @@ class MentraLive : SGCManager() {
1306
1348
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1307
1349
  resetWireNegotiationState()
1308
1350
  resetPendingAckState()
1351
+ resetReadinessExchange()
1309
1352
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1310
1353
  // next link must be allowed to send them again.
1311
1354
  lastSentMicTuningBody = null
@@ -1607,29 +1650,17 @@ class MentraLive : SGCManager() {
1607
1650
  savedDeviceName.isNotEmpty() && savedDeviceName == deviceName
1608
1651
  val isNamedConnectTarget =
1609
1652
  isSavedGlasses && (isReconnecting || explicitConnectByName)
1610
- if (MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
1653
+ if (MentraLiveOwnerLossPolicy.shouldIgnoreNotPairable(
1611
1654
  savedGlasses = isSavedGlasses,
1612
1655
  reconnectScan = isReconnecting,
1613
1656
  secureTrailer = advertisesPairingFlag(result),
1614
1657
  pairingDiscoverable = isPairingDiscoverable(result),
1615
1658
  )
1616
1659
  ) {
1617
- // Other secure units stay visible with pairing-mode guidance, and
1618
- // the scan screen blocks the connection until they are pairable.
1660
+ // Only glasses that can pair now are listed; a closed window drops them.
1619
1661
  // The saved glasses fall through so the pause watch scan can see
1620
1662
  // the pairing flag clear and reconnect.
1621
- Bridge.log(
1622
- "LIVE: Nearby $deviceName is secure firmware not in pairing mode — exposing as non-pairable"
1623
- )
1624
- Bridge.sendDiscoveredDevice(
1625
- DeviceTypes.LIVE,
1626
- deviceName,
1627
- deviceAddress,
1628
- result.rssi,
1629
- pairingMode = false,
1630
- pairingCode = null,
1631
- securePairingCapable = true,
1632
- )
1663
+ Bridge.removeDiscoveredDevice(DeviceTypes.LIVE, deviceName)
1633
1664
  return
1634
1665
  }
1635
1666
  val glassType = if (deviceName == "Xy_A") "Standard" else "K900"
@@ -1642,17 +1673,21 @@ class MentraLive : SGCManager() {
1642
1673
  if (secureCapable) " (pairingMode=$pairingMode)"
1643
1674
  else " (legacy firmware, pairable)"
1644
1675
  )
1645
- Bridge.sendDiscoveredDevice(
1646
- DeviceTypes.LIVE,
1647
- deviceName,
1648
- deviceAddress,
1649
- result.rssi,
1650
- // Field firmware has no pairing flag. Treat it as pairable so the
1651
- // new Mentra App can still find old glasses.
1652
- pairingMode = if (secureCapable) pairingMode else true,
1653
- pairingCode = pairingCode,
1654
- securePairingCapable = secureCapable,
1655
- )
1676
+ // Field firmware has no pairing flag. Treat it as pairable so the new
1677
+ // Mentra App can still find old glasses.
1678
+ if (secureCapable && !pairingMode) {
1679
+ Bridge.removeDiscoveredDevice(DeviceTypes.LIVE, deviceName)
1680
+ } else {
1681
+ Bridge.sendDiscoveredDevice(
1682
+ DeviceTypes.LIVE,
1683
+ deviceName,
1684
+ deviceAddress,
1685
+ result.rssi,
1686
+ pairingMode = true,
1687
+ pairingCode = pairingCode,
1688
+ securePairingCapable = secureCapable,
1689
+ )
1690
+ }
1656
1691
 
1657
1692
  if (savedDeviceName.isNotEmpty() && savedDeviceName == deviceName) {
1658
1693
  observeSavedGlassesAdvertisement(result)
@@ -2100,6 +2135,20 @@ class MentraLive : SGCManager() {
2100
2135
  if (isKilled) return
2101
2136
  if (isExplicitPairingAttempt()) return
2102
2137
  leaveGlassesLink()
2138
+ // The glasses deleted this phone's keys. A bond kept here would make the first Pair Again
2139
+ // connect with them, get refused and fail; removed now, Pair Again bonds afresh.
2140
+ forgetRejectedBond()
2141
+ }
2142
+
2143
+ private fun forgetRejectedBond() {
2144
+ val address = DeviceStore.get("bluetooth", "device_address") as? String ?: return
2145
+ if (!BluetoothAdapter.checkBluetoothAddress(address)) return
2146
+ val device = bluetoothAdapter?.getRemoteDevice(address) ?: return
2147
+ try {
2148
+ if (device.bondState == BluetoothDevice.BOND_BONDED) removeBondStandalone(device)
2149
+ } catch (e: SecurityException) {
2150
+ Bridge.log("LIVE: CTKD: removing the rejected bond was refused: " + e.message)
2151
+ }
2103
2152
  }
2104
2153
 
2105
2154
  /** Drop the link and every pending automatic attempt. Bonds and saved identity stay. */
@@ -4302,6 +4351,7 @@ class MentraLive : SGCManager() {
4302
4351
  }
4303
4352
  BleTraceLogger.logJson("glasses_to_phone", "sdk_ble_event", json, null)
4304
4353
  GlassesLinkDiagnostics.recordInbound()
4354
+ lastInboundAt = SystemClock.elapsedRealtime()
4305
4355
 
4306
4356
  if (MessageChunker.isChunkedMessage(json)) {
4307
4357
  processChunkedJsonMessage(json)
@@ -4328,6 +4378,9 @@ class MentraLive : SGCManager() {
4328
4378
  }
4329
4379
 
4330
4380
  when (type) {
4381
+ // The glasses send this every few seconds while their hotspot is up, so iPhones keep
4382
+ // running hotspot downloads in the background. Android needs nothing from it.
4383
+ "hotspot_keepalive" -> return
4331
4384
  "file_announce" -> handleFileTransferAnnouncement(json)
4332
4385
  "transfer_timeout" -> handleTransferTimeout(json)
4333
4386
  "transfer_failed" -> handleTransferFailed(json)
@@ -4772,6 +4825,16 @@ class MentraLive : SGCManager() {
4772
4825
  if (json.has("bytes_downloaded")) json.optLong("bytes_downloaded", 0) else null
4773
4826
  )
4774
4827
  }
4828
+ "bes_crash_detected", "bes_crash_reported_ack" ->
4829
+ try {
4830
+ Bridge.log(
4831
+ "LIVE: $type incidentKey=${json.optString("incidentKey")} " +
4832
+ "state=${json.optString("state")} ok=${json.opt("ok")}"
4833
+ )
4834
+ Bridge.sendTypedMessage(type, jsonObjectToMap(json))
4835
+ } catch (e: JSONException) {
4836
+ Log.e(TAG, "Error converting $type to Map", e)
4837
+ }
4775
4838
  "ota_progress" -> {
4776
4839
  // Legacy glasses firmware: map to unified ota_status so JS has a single path
4777
4840
  // (Mantle / progress UI).
@@ -4943,6 +5006,16 @@ class MentraLive : SGCManager() {
4943
5006
 
4944
5007
  handleSwitchStatus(switchType, switchValue, switchTimestamp)
4945
5008
  }
5009
+ "rgb_led_control_response" -> {
5010
+ // Settles the sendRgbLedControl request this reply echoes (matches iOS).
5011
+ val requestId = json.optString("requestId", "")
5012
+ val success =
5013
+ json.optString("state", "") == "success" ||
5014
+ json.optBoolean("success", false)
5015
+ val error =
5016
+ json.optString("errorCode", "").ifEmpty { json.optString("error", "") }
5017
+ Bridge.sendRgbLedControlResponse(requestId, success, error.ifEmpty { null })
5018
+ }
4946
5019
  "sensor_data" -> {
4947
5020
  // Process sensor data
4948
5021
  // ...
@@ -4953,6 +5026,19 @@ class MentraLive : SGCManager() {
4953
5026
  Bridge.log("LIVE: Ignoring stale glasses_ready without a link")
4954
5027
  return
4955
5028
  }
5029
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
5030
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
5031
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
5032
+ Bridge.log(
5033
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
5034
+ "the glasses did not reset for it"
5035
+ )
5036
+ return
5037
+ }
5038
+ if (readyId != null && readyId == pendingReadyId) {
5039
+ pendingReadyId = null
5040
+ }
5041
+ readyGlassesSessionId = sid
4956
5042
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4957
5043
  markPairingTiming(
4958
5044
  "glasses_ready",
@@ -4970,7 +5056,7 @@ class MentraLive : SGCManager() {
4970
5056
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4971
5057
  // already runs this full remote-reset flow, so recording (not re-triggering)
4972
5058
  // is correct here; version_info detection covers the restart case.
4973
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
5059
+ glassesSessionId = sid
4974
5060
  streamControlVersion = json.optInt("streamControlVersion", 0)
4975
5061
  Bridge.sendTypedMessage(
4976
5062
  "wifi_protocol_session_ready",
@@ -6470,6 +6556,30 @@ class MentraLive : SGCManager() {
6470
6556
  }
6471
6557
  }
6472
6558
 
6559
+ /**
6560
+ * The 16-character relay file names keep only 15 characters of the report id, so two reports
6561
+ * can share them. The phone routes a received file to the report registered under its name;
6562
+ * refuse a second report until the owner's Cloud POST is confirmed or its ownership expires.
6563
+ */
6564
+ private fun reserveIncidentRelays(vararg relays: BleIncidentLogRelay) {
6565
+ synchronized(bleIncidentLogRelays) {
6566
+ val now = SystemClock.elapsedRealtime()
6567
+ for (relay in relays) {
6568
+ val owner = bleIncidentLogRelays[relay.fileBaseKey] ?: continue
6569
+ if (owner.incidentId != relay.incidentId &&
6570
+ now - owner.reservedAtMs < INCIDENT_RELAY_OWNERSHIP_MS) {
6571
+ throw BluetoothSdkException(
6572
+ "incident_relay_busy",
6573
+ "BLE relay ${relay.fileBaseKey} is still owned by report ${owner.incidentId}.",
6574
+ )
6575
+ }
6576
+ }
6577
+ for (relay in relays) {
6578
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
6579
+ }
6580
+ }
6581
+ }
6582
+
6473
6583
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6474
6584
  if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6475
6585
  throw BluetoothSdkException(
@@ -6489,10 +6599,9 @@ class MentraLive : SGCManager() {
6489
6599
  }
6490
6600
  val bKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'B')
6491
6601
  val lKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'L')
6492
- bleIncidentLogRelays[bKey] =
6493
- BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6494
- bleIncidentLogRelays[lKey] =
6495
- BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6602
+ val bRelay = BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6603
+ val lRelay = BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6604
+ reserveIncidentRelays(bRelay, lRelay)
6496
6605
 
6497
6606
  val auth = JSONObject()
6498
6607
  auth.put("type", "auth_token")
@@ -6507,8 +6616,8 @@ class MentraLive : SGCManager() {
6507
6616
  sessionGeneration != bleSessionGeneration.get() ||
6508
6617
  !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6509
6618
  !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6510
- bleIncidentLogRelays.remove(bKey)
6511
- bleIncidentLogRelays.remove(lKey)
6619
+ bleIncidentLogRelays.remove(bKey, bRelay)
6620
+ bleIncidentLogRelays.remove(lKey, lRelay)
6512
6621
  throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6513
6622
  }
6514
6623
  Bridge.log(
@@ -6525,6 +6634,27 @@ class MentraLive : SGCManager() {
6525
6634
  }
6526
6635
  }
6527
6636
 
6637
+ override fun sendBesCrashReported(incidentKey: String, reportId: String) {
6638
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6639
+ throw BluetoothSdkException(
6640
+ "glasses_not_connected", "Cannot report the BES crash because the glasses BLE link is not ready.",
6641
+ )
6642
+ }
6643
+ val sessionGeneration = bleSessionGeneration.get()
6644
+ try {
6645
+ val json = JSONObject()
6646
+ json.put("type", "bes_crash_reported")
6647
+ json.put("incidentKey", incidentKey)
6648
+ json.put("reportId", reportId)
6649
+ if (!sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6650
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not queue bes_crash_reported to the glasses.")
6651
+ }
6652
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=$incidentKey reportId=$reportId")
6653
+ } catch (e: JSONException) {
6654
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not create bes_crash_reported.", e)
6655
+ }
6656
+ }
6657
+
6528
6658
  /** Query gallery status from the glasses */
6529
6659
  override fun queryGalleryStatus() {
6530
6660
  try {
@@ -7897,11 +8027,56 @@ class MentraLive : SGCManager() {
7897
8027
  if (intent?.action != BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED &&
7898
8028
  intent?.action != BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) return
7899
8029
  val device = intent.bluetoothDeviceExtra() ?: return
8030
+ noteClassicDisconnecting(device, intent)
7900
8031
  refreshClassicAudioConnectionState(device)
7901
8032
  }
7902
8033
  }
7903
8034
  }
7904
8035
 
8036
+ /**
8037
+ * Android's Bluetooth settings Disconnect drops every Classic profile of the glasses (A2DP,
8038
+ * and HFP unless the unworn glasses closed it) and leaves the app's BLE link up, so Home went
8039
+ * on showing them connected. When all the connected profiles start disconnecting within
8040
+ * [CLASSIC_DISCONNECT_PAIR_MS] while the app neither asked nor lost BLE, and the glasses
8041
+ * answer over BLE within [CLASSIC_DISCONNECT_CONFIRM_MS], the person disconnected them: it
8042
+ * lasts like the app's Disconnect, even if the glasses paged their audio back meanwhile. A
8043
+ * restart, power off, pairing window or range loss takes BLE down too; turning off Media or
8044
+ * Call audio leaves the other profile up.
8045
+ */
8046
+ private fun noteClassicDisconnecting(device: BluetoothDevice, intent: Intent) {
8047
+ if (intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1) != BluetoothProfile.STATE_CONNECTED ||
8048
+ intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1) != BluetoothProfile.STATE_DISCONNECTING
8049
+ ) {
8050
+ return
8051
+ }
8052
+ if (isKilled || !isConnected || connectedDevice?.address != device.address) return
8053
+ if (bluetoothAdapter?.state != BluetoothAdapter.STATE_ON) return
8054
+ val now = SystemClock.elapsedRealtime()
8055
+ val ownTeardownAt = lastOwnClassicTeardownAt
8056
+ if (ownTeardownAt != null && now - ownTeardownAt < OWN_CLASSIC_TEARDOWN_MS) return
8057
+ val profile =
8058
+ if (intent.action == BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) ClassicAudioProfile.A2DP
8059
+ else ClassicAudioProfile.HEADSET
8060
+ classicDisconnectingAt[profile] = now
8061
+ val wereUp = classicAudioConnectionTracker.connectedProfiles() + profile
8062
+ if (!wholeClassicDeviceDisconnecting(wereUp, classicDisconnectingAt, now, CLASSIC_DISCONNECT_PAIR_MS)) return
8063
+ if (classicDisconnectCheck != null) return
8064
+ Bridge.log("LIVE: Classic: Android is disconnecting the glasses' audio - checking the glasses stay up")
8065
+ val session = gattEpoch
8066
+ sendJsonWithoutAck(JSONObject().put("type", "ping"))
8067
+ val check =
8068
+ Runnable {
8069
+ classicDisconnectCheck = null
8070
+ if (isKilled || !isConnected || gattEpoch != session || lastInboundAt <= now) {
8071
+ return@Runnable
8072
+ }
8073
+ Bridge.log("LIVE: Classic: Android disconnected the glasses - staying disconnected")
8074
+ DeviceManager.getInstance().disconnectByUser()
8075
+ }
8076
+ classicDisconnectCheck = check
8077
+ handler.postDelayed(check, CLASSIC_DISCONNECT_CONFIRM_MS)
8078
+ }
8079
+
7905
8080
  private fun registerClassicAudioReceiver() {
7906
8081
  val ctx = context ?: return
7907
8082
  val receiver = classicAudioReceiver ?: return
@@ -8535,6 +8710,7 @@ class MentraLive : SGCManager() {
8535
8710
  // The BLE device reference may already be cleared after a GATT drop. The tracker owns the
8536
8711
  // authoritative target address, so let it decide whether this teardown belongs to the
8537
8712
  // active Classic session instead of consulting connectedDevice.
8713
+ lastOwnClassicTeardownAt = SystemClock.elapsedRealtime()
8538
8714
  if (classicAudioConnectionTracker.invalidate(device.address)) {
8539
8715
  audioConnected = false
8540
8716
  }
@@ -9772,13 +9948,34 @@ class MentraLive : SGCManager() {
9772
9948
  wireHandshakeSentGeneration = -1
9773
9949
  }
9774
9950
 
9951
+ /**
9952
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9953
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9954
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9955
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9956
+ * superseded by the pending exchange, whose answer is still to come.
9957
+ */
9958
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9959
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9960
+
9961
+ private fun resetReadinessExchange() {
9962
+ pendingReadyId = null
9963
+ readyGlassesSessionId = null
9964
+ }
9965
+
9775
9966
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9776
9967
  private fun sendPhoneReady(reason: String) {
9777
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9968
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9969
+ pendingReadyId = readyId
9970
+ Bridge.log(
9971
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
9972
+ "waiting for glasses_ready response"
9973
+ )
9778
9974
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9779
9975
  val readyMsg = JSONObject()
9780
9976
  readyMsg.put("type", "phone_ready")
9781
9977
  readyMsg.put("timestamp", System.currentTimeMillis())
9978
+ readyMsg.put("readyId", readyId)
9782
9979
  sendJson(readyMsg, true)
9783
9980
  }
9784
9981
 
@@ -10024,13 +10221,15 @@ class MentraLive : SGCManager() {
10024
10221
  Log.w(TAG, "Rejected unsupported compact reassembled wire form")
10025
10222
  return
10026
10223
  }
10027
- logWireMetrics(
10028
- reassembled.size,
10029
- data.size,
10030
- info.fragCount,
10031
- BleWireProtocol.PROTOCOL_V2,
10032
- "glasses_to_phone"
10033
- )
10224
+ if (!BleTraceLogger.isQuietType(json.optString("type"))) {
10225
+ logWireMetrics(
10226
+ reassembled.size,
10227
+ data.size,
10228
+ info.fragCount,
10229
+ BleWireProtocol.PROTOCOL_V2,
10230
+ "glasses_to_phone"
10231
+ )
10232
+ }
10034
10233
  processJsonMessage(json)
10035
10234
  } catch (e: JSONException) {
10036
10235
  Log.e(TAG, "Failed to parse reassembled binary wire JSON", e)
@@ -11161,6 +11360,15 @@ class MentraLive : SGCManager() {
11161
11360
  // Transfer is complete - process successfully
11162
11361
  Bridge.log("LIVE: 📦 File transfer complete: " + packetInfo.fileName)
11163
11362
 
11363
+ if (IncidentLogBleRelayNaming.isRelayFileName(packetInfo.fileName)) {
11364
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
11365
+ // Cloud, so success would make the glasses mark the incident uploaded.
11366
+ Log.w(TAG, "Incident log relay without a registered report: " + packetInfo.fileName)
11367
+ sendTransferCompleteConfirmation(packetInfo.fileName, false)
11368
+ activeFileTransfers.remove(packetInfo.fileName)
11369
+ return
11370
+ }
11371
+
11164
11372
  // Assemble and save the file
11165
11373
  val fileData = session.assembleFile()
11166
11374
  if (fileData != null) {
@@ -11377,6 +11585,13 @@ class MentraLive : SGCManager() {
11377
11585
  success,
11378
11586
  message ->
11379
11587
  Handler(Looper.getMainLooper()).post {
11588
+ // A different report now owns this name (it was admitted after our owner finished),
11589
+ // so a completion here would mark ITS file done. Drop the stale callback.
11590
+ val owner = bleIncidentLogRelays[relay.fileBaseKey]
11591
+ if (owner != null && owner.incidentId != relay.incidentId) {
11592
+ Log.w(TAG, "Dropping stale incident relay callback for " + relay.fileBaseKey)
11593
+ return@post
11594
+ }
11380
11595
  if (success) {
11381
11596
  Bridge.log(
11382
11597
  "LIVE: ✅ Incident log BLE relay uploaded (" +
@@ -11384,7 +11599,6 @@ class MentraLive : SGCManager() {
11384
11599
  "): " +
11385
11600
  relay.incidentId
11386
11601
  )
11387
- bleIncidentLogRelays.remove(relay.fileBaseKey)
11388
11602
  } else {
11389
11603
  Log.e(
11390
11604
  TAG,
@@ -11397,6 +11611,11 @@ class MentraLive : SGCManager() {
11397
11611
  relay.session = null
11398
11612
  }
11399
11613
  sendTransferCompleteConfirmation(fileName, success)
11614
+ // Release only after the glasses' confirmation is queued, so a report that reuses
11615
+ // this name is ordered behind the owner's completion.
11616
+ if (success) {
11617
+ bleIncidentLogRelays.remove(relay.fileBaseKey, relay)
11618
+ }
11400
11619
  }
11401
11620
  }
11402
11621
  }
@@ -11553,20 +11772,19 @@ class MentraLive : SGCManager() {
11553
11772
  }
11554
11773
 
11555
11774
  /**
11556
- * Get the core authentication token. Reads from DeviceStore first (synced from JS via
11557
- * BluetoothSdkModule.update), then falls back to SharedPreferences for backward compatibility.
11775
+ * Get the current Core access token, synced from JS into the in-memory DeviceStore
11776
+ * (BluetoothSdkModule.update). Empty when there is none: credentials are never read from
11777
+ * plain storage.
11558
11778
  */
11559
11779
  private fun getCoreToken(): String {
11560
11780
  val fromStore = DeviceStore.get("bluetooth", "core_token")
11561
- if (fromStore is String) {
11562
- val token = fromStore
11563
- if (token != null && !token.isEmpty()) {
11564
- return token
11565
- }
11566
- }
11567
- val prefs = context!!.getSharedPreferences(AUTH_PREFS_NAME, Context.MODE_PRIVATE)
11568
- val fromPrefs = prefs.getString(KEY_CORE_TOKEN, "")
11569
- return if (fromPrefs != null) fromPrefs else ""
11781
+ return if (fromStore is String) fromStore else ""
11782
+ }
11783
+
11784
+ /** Delete the Core token older builds left in plain SharedPreferences. */
11785
+ private fun forgetLegacyCoreToken() {
11786
+ val prefs = context?.getSharedPreferences(LEGACY_AUTH_PREFS_NAME, Context.MODE_PRIVATE) ?: return
11787
+ if (prefs.contains(LEGACY_KEY_CORE_TOKEN)) prefs.edit().remove(LEGACY_KEY_CORE_TOKEN).apply()
11570
11788
  }
11571
11789
 
11572
11790
  /** Send BLE transfer completion notification */
@@ -142,12 +142,12 @@ internal object MentraLiveOwnerLossPolicy {
142
142
  ): Boolean = pairingMode && savedGlasses && !explicitPairing
143
143
 
144
144
  /**
145
- * A discovery scan lists other secure glasses that are not in pairing mode as non-pairable
146
- * and does not connect to them. The saved glasses are the exception: the pause watch scan
147
- * has to read their trailer, so a cleared pairing flag ends the pause and reconnects.
148
- * Mirrors iOS, which skips this return when the advertisement is the saved device.
145
+ * A discovery scan neither lists nor connects to other secure glasses that are not in pairing
146
+ * mode. The saved glasses are the exception: the pause watch scan has to read their trailer,
147
+ * so a cleared pairing flag ends the pause and reconnects. Mirrors iOS, which skips this
148
+ * return when the advertisement is the saved device.
149
149
  */
150
- fun shouldExposeAsNonPairable(
150
+ fun shouldIgnoreNotPairable(
151
151
  savedGlasses: Boolean,
152
152
  reconnectScan: Boolean,
153
153
  secureTrailer: Boolean,