@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.1-beta.1409

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 (216) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +41 -14
  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 +131 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  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 +308 -60
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +14 -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 +9 -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 +5 -2
  93. package/build/generated/changelogCatalog.d.ts.map +1 -1
  94. package/build/generated/changelogCatalog.js +6 -2
  95. package/build/generated/changelogCatalog.js.map +1 -1
  96. package/build/generated/releaseMetadata.js +6 -6
  97. package/build/generated/releaseMetadata.js.map +1 -1
  98. package/build/index.d.ts +1 -1
  99. package/build/index.d.ts.map +1 -1
  100. package/build/index.js +7 -1
  101. package/build/index.js.map +1 -1
  102. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  103. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  106. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  107. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  108. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  109. package/build/ota-transport/index.d.ts +3 -3
  110. package/build/ota-transport/index.d.ts.map +1 -1
  111. package/build/ota-transport/index.js +4 -4
  112. package/build/ota-transport/index.js.map +1 -1
  113. package/build/react/useGlassesConnection.d.ts +1 -1
  114. package/build/react/useGlassesConnection.d.ts.map +1 -1
  115. package/build/react/useGlassesConnection.js +3 -3
  116. package/build/react/useGlassesConnection.js.map +1 -1
  117. package/build/react/useMentraBluetooth.d.ts +1 -1
  118. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  119. package/build/react/useMentraBluetooth.js +1 -1
  120. package/build/react/useMentraBluetooth.js.map +1 -1
  121. package/ios/BluetoothSdkModule.swift +73 -22
  122. package/ios/LocalIPv4.swift +0 -61
  123. package/ios/MentraBluetoothSDK.podspec +7 -1
  124. package/ios/MentraOtaServerModule.swift +0 -16
  125. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  126. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  127. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  128. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  129. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  130. package/ios/Source/Bridge.swift +14 -0
  131. package/ios/Source/DeviceManager.swift +52 -22
  132. package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
  133. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  134. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  135. package/ios/Source/OtaManifest.swift +1 -17
  136. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  137. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  138. package/ios/Source/audio/SpeechActivity.swift +277 -0
  139. package/ios/Source/events/BluetoothEvents.swift +41 -0
  140. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  141. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  142. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  143. package/ios/Source/sgcs/MentraLive.swift +207 -66
  144. package/ios/Source/sgcs/Nimo.swift +249 -276
  145. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  146. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  147. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  148. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  149. package/ios/Source/sgcs/SGCManager.swift +6 -0
  150. package/ios/Source/streaming/StreamModels.swift +15 -6
  151. package/ios/Source/stt/STTTools.swift +13 -31
  152. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  153. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  154. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  155. package/ios/Source/utils/BoundedWait.swift +44 -0
  156. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  157. package/ios/Source/utils/SttModelTraits.swift +62 -0
  158. package/ios/Tests/BesCrashReportTests.swift +142 -0
  159. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  160. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  161. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  162. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  163. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  164. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  165. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  166. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  167. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  168. package/ios/Tests/PcmStreamTests.swift +299 -0
  169. package/ios/Tests/SpeechActivityTests.swift +238 -0
  170. package/ios/Tests/StreamRequestTests.swift +18 -0
  171. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  172. package/package.json +2 -2
  173. package/plugin/build/withAndroid.js +9 -11
  174. package/plugin/build/withKotlinVersion.d.ts +2 -0
  175. package/plugin/build/withKotlinVersion.js +46 -0
  176. package/src/BluetoothSdk.types.ts +107 -5
  177. package/src/_private/BluetoothSdkModule.ts +45 -8
  178. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  179. package/src/generated/changelogCatalog.ts +6 -2
  180. package/src/generated/releaseMetadata.ts +6 -6
  181. package/src/index.ts +13 -1
  182. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  183. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  184. package/src/ota-transport/index.ts +4 -5
  185. package/src/react/useGlassesConnection.ts +4 -4
  186. package/src/react/useMentraBluetooth.ts +2 -2
  187. package/android/silero/LICENSE.md +0 -17
  188. package/android/silero/build.gradle +0 -50
  189. package/android/silero/proguard-rules.pro +0 -24
  190. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  191. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  198. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  199. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  202. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  203. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  204. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  206. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  207. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  210. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  211. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  212. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  213. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  214. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  215. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  216. /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()
@@ -348,11 +357,16 @@ class MentraLive : SGCManager() {
348
357
  * Drop A2DP/HFP + removeBond for every bonded Mentra Live unit. Safe when no SGC
349
358
  * instance exists — [DeviceManager.forget] often runs after disconnect() nulled sgc
350
359
  * (abandonAttempt), which previously skipped MentraLive.forget() entirely and left
351
- * Classic ACL up so glasses never re-advertised.
360
+ * Classic ACL up so glasses never re-advertised. With [removeBonds] false the bonds stay:
361
+ * glasses that keep former owners' keys (pairing-spec V9) take this phone back with them.
352
362
  */
353
363
  @JvmStatic
354
364
  @JvmOverloads
355
- fun unbondBondedMentraLiveDevices(context: Context?, extraAddress: String? = null) {
365
+ fun unbondBondedMentraLiveDevices(
366
+ context: Context?,
367
+ extraAddress: String? = null,
368
+ removeBonds: Boolean = true,
369
+ ) {
356
370
  if (context == null) {
357
371
  Bridge.log("LIVE: CTKD: unbondBondedMentraLiveDevices — no context")
358
372
  return
@@ -410,7 +424,11 @@ class MentraLive : SGCManager() {
410
424
  BluetoothHeadset::class.java,
411
425
  "HFP"
412
426
  )
413
- removeBondStandalone(device)
427
+ if (removeBonds) removeBondStandalone(device)
428
+ }
429
+ if (!removeBonds) {
430
+ Bridge.log("LIVE: CTKD: bonds kept, the glasses keep former owners' keys")
431
+ return
414
432
  }
415
433
  Handler(Looper.getMainLooper())
416
434
  .postDelayed({ retryUnbondIfStillPaired(context, extraAddress) }, 700)
@@ -457,6 +475,22 @@ class MentraLive : SGCManager() {
457
475
  }
458
476
  }
459
477
 
478
+ /** The one Mentra Live this phone is bonded with. Null when there is none, several, or no permission to read bonds. */
479
+ fun soleBondedMentraLive(context: Context?): BluetoothDevice? {
480
+ val adapter =
481
+ (context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)
482
+ ?.adapter
483
+ ?: return null
484
+ return try {
485
+ adapter.bondedDevices
486
+ ?.filter { isMentraLiveBluetoothName(safeBondedDeviceName(it)) }
487
+ ?.singleOrNull()
488
+ } catch (e: Exception) {
489
+ Bridge.log("LIVE: Unable to read bonded devices: " + e.message)
490
+ null
491
+ }
492
+ }
493
+
460
494
  private const val SHUTDOWN_RECENT_MS = 45_000L // Consider "recent shutdown" for 45s
461
495
 
462
496
  // Keep-alive parameters
@@ -479,9 +513,9 @@ class MentraLive : SGCManager() {
479
513
  private const val PREFS_NAME = "MentraLivePrefs"
480
514
  private const val PREF_DEVICE_NAME = "LastConnectedDeviceName"
481
515
 
482
- // Auth settings
483
- private const val AUTH_PREFS_NAME = "augmentos_auth_prefs"
484
- private const val KEY_CORE_TOKEN = "core_token"
516
+ // A Core token older builds kept in plain SharedPreferences. Deleted, never read.
517
+ private const val LEGACY_AUTH_PREFS_NAME = "augmentos_auth_prefs"
518
+ private const val LEGACY_KEY_CORE_TOKEN = "core_token"
485
519
 
486
520
  private const val MAX_BONDING_RETRIES = 3
487
521
  private const val BONDING_RETRY_DELAY_MS =
@@ -579,6 +613,13 @@ class MentraLive : SGCManager() {
579
613
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
580
614
  // after an upgrade OTA is always detected as a restart.
581
615
  private var readinessCompletedThisBleSession = false
616
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
617
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
618
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
619
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
620
+ private var pendingReadyId: String? = null
621
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
622
+ private var readyGlassesSessionId: String? = null
582
623
  // Note: appVersion, buildNumber, deviceModel, androidVersion
583
624
  // are inherited from SGCManager parent class
584
625
 
@@ -666,6 +707,13 @@ class MentraLive : SGCManager() {
666
707
  private var secureFirmwareRefreshRunnable: Runnable? = null
667
708
  /** elapsedRealtime of the last GATT link that was not an explicit pairing attempt. */
668
709
  private var lastAutoReconnectLinkAt: Long? = null
710
+ /** elapsedRealtime of the app's last own A2DP/HFP teardown. */
711
+ private var lastOwnClassicTeardownAt: Long? = null
712
+ /** elapsedRealtime when Android started disconnecting each Classic profile. */
713
+ private val classicDisconnectingAt = mutableMapOf<ClassicAudioProfile, Long>()
714
+ private var classicDisconnectCheck: Runnable? = null
715
+ /** elapsedRealtime of the last message from the glasses. */
716
+ private var lastInboundAt = 0L
669
717
  /** Hold GATT teardown until the unpair write can leave the phone. */
670
718
  private var unpairFlushPending = false
671
719
  private var unpairFlushRunnable: Runnable? = null
@@ -823,6 +871,7 @@ class MentraLive : SGCManager() {
823
871
  val apiBaseUrl: String,
824
872
  val kind: BleIncidentLogKind
825
873
  ) {
874
+ val reservedAtMs: Long = SystemClock.elapsedRealtime()
826
875
  var session: FileTransferSession? = null
827
876
  }
828
877
 
@@ -1078,6 +1127,7 @@ class MentraLive : SGCManager() {
1078
1127
  this.type = DeviceTypes.LIVE
1079
1128
  this.hasMic = true
1080
1129
  this.context = Bridge.getContext()
1130
+ forgetLegacyCoreToken()
1081
1131
 
1082
1132
  // Initialize bluetooth adapter
1083
1133
  val bluetoothManager =
@@ -1241,6 +1291,7 @@ class MentraLive : SGCManager() {
1241
1291
  if (state == ConnTypes.DISCONNECTED) {
1242
1292
  resetWireNegotiationState()
1243
1293
  resetPendingAckState()
1294
+ resetReadinessExchange()
1244
1295
  // Queued writes are session-bound: transmitting them into the NEXT session
1245
1296
  // (e.g. a stale handshake whose reply activates v2 before the new session
1246
1297
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1306,6 +1357,7 @@ class MentraLive : SGCManager() {
1306
1357
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1307
1358
  resetWireNegotiationState()
1308
1359
  resetPendingAckState()
1360
+ resetReadinessExchange()
1309
1361
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1310
1362
  // next link must be allowed to send them again.
1311
1363
  lastSentMicTuningBody = null
@@ -1607,29 +1659,17 @@ class MentraLive : SGCManager() {
1607
1659
  savedDeviceName.isNotEmpty() && savedDeviceName == deviceName
1608
1660
  val isNamedConnectTarget =
1609
1661
  isSavedGlasses && (isReconnecting || explicitConnectByName)
1610
- if (MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
1662
+ if (MentraLiveOwnerLossPolicy.shouldIgnoreNotPairable(
1611
1663
  savedGlasses = isSavedGlasses,
1612
1664
  reconnectScan = isReconnecting,
1613
1665
  secureTrailer = advertisesPairingFlag(result),
1614
1666
  pairingDiscoverable = isPairingDiscoverable(result),
1615
1667
  )
1616
1668
  ) {
1617
- // Other secure units stay visible with pairing-mode guidance, and
1618
- // the scan screen blocks the connection until they are pairable.
1669
+ // Only glasses that can pair now are listed; a closed window drops them.
1619
1670
  // The saved glasses fall through so the pause watch scan can see
1620
1671
  // 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
- )
1672
+ Bridge.removeDiscoveredDevice(DeviceTypes.LIVE, deviceName)
1633
1673
  return
1634
1674
  }
1635
1675
  val glassType = if (deviceName == "Xy_A") "Standard" else "K900"
@@ -1642,17 +1682,21 @@ class MentraLive : SGCManager() {
1642
1682
  if (secureCapable) " (pairingMode=$pairingMode)"
1643
1683
  else " (legacy firmware, pairable)"
1644
1684
  )
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
- )
1685
+ // Field firmware has no pairing flag. Treat it as pairable so the new
1686
+ // Mentra App can still find old glasses.
1687
+ if (secureCapable && !pairingMode) {
1688
+ Bridge.removeDiscoveredDevice(DeviceTypes.LIVE, deviceName)
1689
+ } else {
1690
+ Bridge.sendDiscoveredDevice(
1691
+ DeviceTypes.LIVE,
1692
+ deviceName,
1693
+ deviceAddress,
1694
+ result.rssi,
1695
+ pairingMode = true,
1696
+ pairingCode = pairingCode,
1697
+ securePairingCapable = secureCapable,
1698
+ )
1699
+ }
1656
1700
 
1657
1701
  if (savedDeviceName.isNotEmpty() && savedDeviceName == deviceName) {
1658
1702
  observeSavedGlassesAdvertisement(result)
@@ -2100,6 +2144,24 @@ class MentraLive : SGCManager() {
2100
2144
  if (isKilled) return
2101
2145
  if (isExplicitPairingAttempt()) return
2102
2146
  leaveGlassesLink()
2147
+ // Glasses that keep former owners' keys (pairing-spec V9) take this phone back with the
2148
+ // bond it has, with no pairing request. Older ones deleted this phone's keys: a bond kept
2149
+ // there would make the first Pair Again connect with them, get refused and fail; removed
2150
+ // now, Pair Again bonds afresh.
2151
+ if (MentraLiveOwnerLossPolicy.removesBondWhenGlassesLetGo(savedGlassesKeepFormerOwnerKeys())) {
2152
+ forgetRejectedBond()
2153
+ }
2154
+ }
2155
+
2156
+ private fun forgetRejectedBond() {
2157
+ val address = DeviceStore.get("bluetooth", "device_address") as? String ?: return
2158
+ if (!BluetoothAdapter.checkBluetoothAddress(address)) return
2159
+ val device = bluetoothAdapter?.getRemoteDevice(address) ?: return
2160
+ try {
2161
+ if (device.bondState == BluetoothDevice.BOND_BONDED) removeBondStandalone(device)
2162
+ } catch (e: SecurityException) {
2163
+ Bridge.log("LIVE: CTKD: removing the rejected bond was refused: " + e.message)
2164
+ }
2103
2165
  }
2104
2166
 
2105
2167
  /** Drop the link and every pending automatic attempt. Bonds and saved identity stay. */
@@ -2254,6 +2316,16 @@ class MentraLive : SGCManager() {
2254
2316
  private fun isSavedGlassesSecureFirmware(): Boolean =
2255
2317
  DeviceStore.get("bluetooth", "mentra_live_secure_firmware") as? Boolean == true
2256
2318
 
2319
+ /** `pairing_info.former_owner_keys`: the saved glasses keep this phone's keys once it loses them. */
2320
+ private fun savedGlassesKeepFormerOwnerKeys(): Boolean =
2321
+ DeviceStore.get("bluetooth", "mentra_live_former_owner_keys") as? Boolean == true
2322
+
2323
+ private fun rememberFormerOwnerKeys(kept: Boolean) {
2324
+ if (savedGlassesKeepFormerOwnerKeys() == kept) return
2325
+ DeviceStore.apply("bluetooth", "mentra_live_former_owner_keys", kept)
2326
+ Bridge.saveSetting("mentra_live_former_owner_keys", kept)
2327
+ }
2328
+
2257
2329
  /** Remember what the connected glasses reported so later rejections can be read correctly. */
2258
2330
  private fun rememberSecureFirmware(secure: Boolean) {
2259
2331
  if (isSavedGlassesSecureFirmware() == secure) return
@@ -4302,6 +4374,7 @@ class MentraLive : SGCManager() {
4302
4374
  }
4303
4375
  BleTraceLogger.logJson("glasses_to_phone", "sdk_ble_event", json, null)
4304
4376
  GlassesLinkDiagnostics.recordInbound()
4377
+ lastInboundAt = SystemClock.elapsedRealtime()
4305
4378
 
4306
4379
  if (MessageChunker.isChunkedMessage(json)) {
4307
4380
  processChunkedJsonMessage(json)
@@ -4328,6 +4401,9 @@ class MentraLive : SGCManager() {
4328
4401
  }
4329
4402
 
4330
4403
  when (type) {
4404
+ // The glasses send this every few seconds while their hotspot is up, so iPhones keep
4405
+ // running hotspot downloads in the background. Android needs nothing from it.
4406
+ "hotspot_keepalive" -> return
4331
4407
  "file_announce" -> handleFileTransferAnnouncement(json)
4332
4408
  "transfer_timeout" -> handleTransferTimeout(json)
4333
4409
  "transfer_failed" -> handleTransferFailed(json)
@@ -4484,6 +4560,7 @@ class MentraLive : SGCManager() {
4484
4560
  // Legacy firmware that omits this field is not secure-capable.
4485
4561
  val secureCapable = json.optBoolean("secure_pairing_capable", false)
4486
4562
  rememberSecureFirmware(secureCapable)
4563
+ rememberFormerOwnerKeys(json.optBoolean("former_owner_keys", false))
4487
4564
  cancelSecureFirmwareRefresh()
4488
4565
  // Decides the capability of a pairing target the scan row did not know.
4489
4566
  sessionPairingInfoSecure = secureCapable
@@ -4772,6 +4849,16 @@ class MentraLive : SGCManager() {
4772
4849
  if (json.has("bytes_downloaded")) json.optLong("bytes_downloaded", 0) else null
4773
4850
  )
4774
4851
  }
4852
+ "bes_crash_detected", "bes_crash_reported_ack" ->
4853
+ try {
4854
+ Bridge.log(
4855
+ "LIVE: $type incidentKey=${json.optString("incidentKey")} " +
4856
+ "state=${json.optString("state")} ok=${json.opt("ok")}"
4857
+ )
4858
+ Bridge.sendTypedMessage(type, jsonObjectToMap(json))
4859
+ } catch (e: JSONException) {
4860
+ Log.e(TAG, "Error converting $type to Map", e)
4861
+ }
4775
4862
  "ota_progress" -> {
4776
4863
  // Legacy glasses firmware: map to unified ota_status so JS has a single path
4777
4864
  // (Mantle / progress UI).
@@ -4943,6 +5030,16 @@ class MentraLive : SGCManager() {
4943
5030
 
4944
5031
  handleSwitchStatus(switchType, switchValue, switchTimestamp)
4945
5032
  }
5033
+ "rgb_led_control_response" -> {
5034
+ // Settles the sendRgbLedControl request this reply echoes (matches iOS).
5035
+ val requestId = json.optString("requestId", "")
5036
+ val success =
5037
+ json.optString("state", "") == "success" ||
5038
+ json.optBoolean("success", false)
5039
+ val error =
5040
+ json.optString("errorCode", "").ifEmpty { json.optString("error", "") }
5041
+ Bridge.sendRgbLedControlResponse(requestId, success, error.ifEmpty { null })
5042
+ }
4946
5043
  "sensor_data" -> {
4947
5044
  // Process sensor data
4948
5045
  // ...
@@ -4953,6 +5050,19 @@ class MentraLive : SGCManager() {
4953
5050
  Bridge.log("LIVE: Ignoring stale glasses_ready without a link")
4954
5051
  return
4955
5052
  }
5053
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
5054
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
5055
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
5056
+ Bridge.log(
5057
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
5058
+ "the glasses did not reset for it"
5059
+ )
5060
+ return
5061
+ }
5062
+ if (readyId != null && readyId == pendingReadyId) {
5063
+ pendingReadyId = null
5064
+ }
5065
+ readyGlassesSessionId = sid
4956
5066
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4957
5067
  markPairingTiming(
4958
5068
  "glasses_ready",
@@ -4970,7 +5080,7 @@ class MentraLive : SGCManager() {
4970
5080
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4971
5081
  // already runs this full remote-reset flow, so recording (not re-triggering)
4972
5082
  // is correct here; version_info detection covers the restart case.
4973
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
5083
+ glassesSessionId = sid
4974
5084
  streamControlVersion = json.optInt("streamControlVersion", 0)
4975
5085
  Bridge.sendTypedMessage(
4976
5086
  "wifi_protocol_session_ready",
@@ -6470,6 +6580,30 @@ class MentraLive : SGCManager() {
6470
6580
  }
6471
6581
  }
6472
6582
 
6583
+ /**
6584
+ * The 16-character relay file names keep only 15 characters of the report id, so two reports
6585
+ * can share them. The phone routes a received file to the report registered under its name;
6586
+ * refuse a second report until the owner's Cloud POST is confirmed or its ownership expires.
6587
+ */
6588
+ private fun reserveIncidentRelays(vararg relays: BleIncidentLogRelay) {
6589
+ synchronized(bleIncidentLogRelays) {
6590
+ val now = SystemClock.elapsedRealtime()
6591
+ for (relay in relays) {
6592
+ val owner = bleIncidentLogRelays[relay.fileBaseKey] ?: continue
6593
+ if (owner.incidentId != relay.incidentId &&
6594
+ now - owner.reservedAtMs < INCIDENT_RELAY_OWNERSHIP_MS) {
6595
+ throw BluetoothSdkException(
6596
+ "incident_relay_busy",
6597
+ "BLE relay ${relay.fileBaseKey} is still owned by report ${owner.incidentId}.",
6598
+ )
6599
+ }
6600
+ }
6601
+ for (relay in relays) {
6602
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
6603
+ }
6604
+ }
6605
+ }
6606
+
6473
6607
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6474
6608
  if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6475
6609
  throw BluetoothSdkException(
@@ -6489,10 +6623,9 @@ class MentraLive : SGCManager() {
6489
6623
  }
6490
6624
  val bKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'B')
6491
6625
  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)
6626
+ val bRelay = BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6627
+ val lRelay = BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6628
+ reserveIncidentRelays(bRelay, lRelay)
6496
6629
 
6497
6630
  val auth = JSONObject()
6498
6631
  auth.put("type", "auth_token")
@@ -6507,8 +6640,8 @@ class MentraLive : SGCManager() {
6507
6640
  sessionGeneration != bleSessionGeneration.get() ||
6508
6641
  !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6509
6642
  !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6510
- bleIncidentLogRelays.remove(bKey)
6511
- bleIncidentLogRelays.remove(lKey)
6643
+ bleIncidentLogRelays.remove(bKey, bRelay)
6644
+ bleIncidentLogRelays.remove(lKey, lRelay)
6512
6645
  throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6513
6646
  }
6514
6647
  Bridge.log(
@@ -6525,6 +6658,27 @@ class MentraLive : SGCManager() {
6525
6658
  }
6526
6659
  }
6527
6660
 
6661
+ override fun sendBesCrashReported(incidentKey: String, reportId: String) {
6662
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6663
+ throw BluetoothSdkException(
6664
+ "glasses_not_connected", "Cannot report the BES crash because the glasses BLE link is not ready.",
6665
+ )
6666
+ }
6667
+ val sessionGeneration = bleSessionGeneration.get()
6668
+ try {
6669
+ val json = JSONObject()
6670
+ json.put("type", "bes_crash_reported")
6671
+ json.put("incidentKey", incidentKey)
6672
+ json.put("reportId", reportId)
6673
+ if (!sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6674
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not queue bes_crash_reported to the glasses.")
6675
+ }
6676
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=$incidentKey reportId=$reportId")
6677
+ } catch (e: JSONException) {
6678
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not create bes_crash_reported.", e)
6679
+ }
6680
+ }
6681
+
6528
6682
  /** Query gallery status from the glasses */
6529
6683
  override fun queryGalleryStatus() {
6530
6684
  try {
@@ -6986,6 +7140,12 @@ class MentraLive : SGCManager() {
6986
7140
  return device.bondState == BluetoothDevice.BOND_BONDING
6987
7141
  }
6988
7142
 
7143
+ /**
7144
+ * Set by [DeviceManager.forget] before [forget]: the glasses keep former owners' keys
7145
+ * (`pairing_info.former_owner_keys`), so Unpair leaves this phone's bond for a later reclaim.
7146
+ */
7147
+ var keepBondsOnForget = false
7148
+
6989
7149
  override fun forget() {
6990
7150
  if (postGattLifecycle { forget() }) return
6991
7151
  Bridge.log("LIVE: Forgetting Mentra Live glasses")
@@ -7025,7 +7185,7 @@ class MentraLive : SGCManager() {
7025
7185
  // Drop GATT first. removeBond while the BLE link is still encrypted often
7026
7186
  // returns true on Samsung but the OS Bluetooth UI keeps the dual-mode pair.
7027
7187
  disconnect()
7028
- unbondBondedMentraLiveDevices(ctx, bondedAddress)
7188
+ unbondBondedMentraLiveDevices(ctx, bondedAddress, !keepBondsOnForget)
7029
7189
  }
7030
7190
  unpairFlushRunnable = flush
7031
7191
  handler.postDelayed(flush, UNPAIR_FLUSH_MS)
@@ -7897,11 +8057,56 @@ class MentraLive : SGCManager() {
7897
8057
  if (intent?.action != BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED &&
7898
8058
  intent?.action != BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) return
7899
8059
  val device = intent.bluetoothDeviceExtra() ?: return
8060
+ noteClassicDisconnecting(device, intent)
7900
8061
  refreshClassicAudioConnectionState(device)
7901
8062
  }
7902
8063
  }
7903
8064
  }
7904
8065
 
8066
+ /**
8067
+ * Android's Bluetooth settings Disconnect drops every Classic profile of the glasses (A2DP,
8068
+ * and HFP unless the unworn glasses closed it) and leaves the app's BLE link up, so Home went
8069
+ * on showing them connected. When all the connected profiles start disconnecting within
8070
+ * [CLASSIC_DISCONNECT_PAIR_MS] while the app neither asked nor lost BLE, and the glasses
8071
+ * answer over BLE within [CLASSIC_DISCONNECT_CONFIRM_MS], the person disconnected them: it
8072
+ * lasts like the app's Disconnect, even if the glasses paged their audio back meanwhile. A
8073
+ * restart, power off, pairing window or range loss takes BLE down too; turning off Media or
8074
+ * Call audio leaves the other profile up.
8075
+ */
8076
+ private fun noteClassicDisconnecting(device: BluetoothDevice, intent: Intent) {
8077
+ if (intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, -1) != BluetoothProfile.STATE_CONNECTED ||
8078
+ intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1) != BluetoothProfile.STATE_DISCONNECTING
8079
+ ) {
8080
+ return
8081
+ }
8082
+ if (isKilled || !isConnected || connectedDevice?.address != device.address) return
8083
+ if (bluetoothAdapter?.state != BluetoothAdapter.STATE_ON) return
8084
+ val now = SystemClock.elapsedRealtime()
8085
+ val ownTeardownAt = lastOwnClassicTeardownAt
8086
+ if (ownTeardownAt != null && now - ownTeardownAt < OWN_CLASSIC_TEARDOWN_MS) return
8087
+ val profile =
8088
+ if (intent.action == BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) ClassicAudioProfile.A2DP
8089
+ else ClassicAudioProfile.HEADSET
8090
+ classicDisconnectingAt[profile] = now
8091
+ val wereUp = classicAudioConnectionTracker.connectedProfiles() + profile
8092
+ if (!wholeClassicDeviceDisconnecting(wereUp, classicDisconnectingAt, now, CLASSIC_DISCONNECT_PAIR_MS)) return
8093
+ if (classicDisconnectCheck != null) return
8094
+ Bridge.log("LIVE: Classic: Android is disconnecting the glasses' audio - checking the glasses stay up")
8095
+ val session = gattEpoch
8096
+ sendJsonWithoutAck(JSONObject().put("type", "ping"))
8097
+ val check =
8098
+ Runnable {
8099
+ classicDisconnectCheck = null
8100
+ if (isKilled || !isConnected || gattEpoch != session || lastInboundAt <= now) {
8101
+ return@Runnable
8102
+ }
8103
+ Bridge.log("LIVE: Classic: Android disconnected the glasses - staying disconnected")
8104
+ DeviceManager.getInstance().disconnectByUser()
8105
+ }
8106
+ classicDisconnectCheck = check
8107
+ handler.postDelayed(check, CLASSIC_DISCONNECT_CONFIRM_MS)
8108
+ }
8109
+
7905
8110
  private fun registerClassicAudioReceiver() {
7906
8111
  val ctx = context ?: return
7907
8112
  val receiver = classicAudioReceiver ?: return
@@ -8535,6 +8740,7 @@ class MentraLive : SGCManager() {
8535
8740
  // The BLE device reference may already be cleared after a GATT drop. The tracker owns the
8536
8741
  // authoritative target address, so let it decide whether this teardown belongs to the
8537
8742
  // active Classic session instead of consulting connectedDevice.
8743
+ lastOwnClassicTeardownAt = SystemClock.elapsedRealtime()
8538
8744
  if (classicAudioConnectionTracker.invalidate(device.address)) {
8539
8745
  audioConnected = false
8540
8746
  }
@@ -9772,13 +9978,34 @@ class MentraLive : SGCManager() {
9772
9978
  wireHandshakeSentGeneration = -1
9773
9979
  }
9774
9980
 
9981
+ /**
9982
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9983
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9984
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9985
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9986
+ * superseded by the pending exchange, whose answer is still to come.
9987
+ */
9988
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9989
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9990
+
9991
+ private fun resetReadinessExchange() {
9992
+ pendingReadyId = null
9993
+ readyGlassesSessionId = null
9994
+ }
9995
+
9775
9996
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9776
9997
  private fun sendPhoneReady(reason: String) {
9777
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9998
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9999
+ pendingReadyId = readyId
10000
+ Bridge.log(
10001
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
10002
+ "waiting for glasses_ready response"
10003
+ )
9778
10004
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9779
10005
  val readyMsg = JSONObject()
9780
10006
  readyMsg.put("type", "phone_ready")
9781
10007
  readyMsg.put("timestamp", System.currentTimeMillis())
10008
+ readyMsg.put("readyId", readyId)
9782
10009
  sendJson(readyMsg, true)
9783
10010
  }
9784
10011
 
@@ -10024,13 +10251,15 @@ class MentraLive : SGCManager() {
10024
10251
  Log.w(TAG, "Rejected unsupported compact reassembled wire form")
10025
10252
  return
10026
10253
  }
10027
- logWireMetrics(
10028
- reassembled.size,
10029
- data.size,
10030
- info.fragCount,
10031
- BleWireProtocol.PROTOCOL_V2,
10032
- "glasses_to_phone"
10033
- )
10254
+ if (!BleTraceLogger.isQuietType(json.optString("type"))) {
10255
+ logWireMetrics(
10256
+ reassembled.size,
10257
+ data.size,
10258
+ info.fragCount,
10259
+ BleWireProtocol.PROTOCOL_V2,
10260
+ "glasses_to_phone"
10261
+ )
10262
+ }
10034
10263
  processJsonMessage(json)
10035
10264
  } catch (e: JSONException) {
10036
10265
  Log.e(TAG, "Failed to parse reassembled binary wire JSON", e)
@@ -11161,6 +11390,15 @@ class MentraLive : SGCManager() {
11161
11390
  // Transfer is complete - process successfully
11162
11391
  Bridge.log("LIVE: 📦 File transfer complete: " + packetInfo.fileName)
11163
11392
 
11393
+ if (IncidentLogBleRelayNaming.isRelayFileName(packetInfo.fileName)) {
11394
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
11395
+ // Cloud, so success would make the glasses mark the incident uploaded.
11396
+ Log.w(TAG, "Incident log relay without a registered report: " + packetInfo.fileName)
11397
+ sendTransferCompleteConfirmation(packetInfo.fileName, false)
11398
+ activeFileTransfers.remove(packetInfo.fileName)
11399
+ return
11400
+ }
11401
+
11164
11402
  // Assemble and save the file
11165
11403
  val fileData = session.assembleFile()
11166
11404
  if (fileData != null) {
@@ -11377,6 +11615,13 @@ class MentraLive : SGCManager() {
11377
11615
  success,
11378
11616
  message ->
11379
11617
  Handler(Looper.getMainLooper()).post {
11618
+ // A different report now owns this name (it was admitted after our owner finished),
11619
+ // so a completion here would mark ITS file done. Drop the stale callback.
11620
+ val owner = bleIncidentLogRelays[relay.fileBaseKey]
11621
+ if (owner != null && owner.incidentId != relay.incidentId) {
11622
+ Log.w(TAG, "Dropping stale incident relay callback for " + relay.fileBaseKey)
11623
+ return@post
11624
+ }
11380
11625
  if (success) {
11381
11626
  Bridge.log(
11382
11627
  "LIVE: ✅ Incident log BLE relay uploaded (" +
@@ -11384,7 +11629,6 @@ class MentraLive : SGCManager() {
11384
11629
  "): " +
11385
11630
  relay.incidentId
11386
11631
  )
11387
- bleIncidentLogRelays.remove(relay.fileBaseKey)
11388
11632
  } else {
11389
11633
  Log.e(
11390
11634
  TAG,
@@ -11397,6 +11641,11 @@ class MentraLive : SGCManager() {
11397
11641
  relay.session = null
11398
11642
  }
11399
11643
  sendTransferCompleteConfirmation(fileName, success)
11644
+ // Release only after the glasses' confirmation is queued, so a report that reuses
11645
+ // this name is ordered behind the owner's completion.
11646
+ if (success) {
11647
+ bleIncidentLogRelays.remove(relay.fileBaseKey, relay)
11648
+ }
11400
11649
  }
11401
11650
  }
11402
11651
  }
@@ -11553,20 +11802,19 @@ class MentraLive : SGCManager() {
11553
11802
  }
11554
11803
 
11555
11804
  /**
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.
11805
+ * Get the current Core access token, synced from JS into the in-memory DeviceStore
11806
+ * (BluetoothSdkModule.update). Empty when there is none: credentials are never read from
11807
+ * plain storage.
11558
11808
  */
11559
11809
  private fun getCoreToken(): String {
11560
11810
  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 ""
11811
+ return if (fromStore is String) fromStore else ""
11812
+ }
11813
+
11814
+ /** Delete the Core token older builds left in plain SharedPreferences. */
11815
+ private fun forgetLegacyCoreToken() {
11816
+ val prefs = context?.getSharedPreferences(LEGACY_AUTH_PREFS_NAME, Context.MODE_PRIVATE) ?: return
11817
+ if (prefs.contains(LEGACY_KEY_CORE_TOKEN)) prefs.edit().remove(LEGACY_KEY_CORE_TOKEN).apply()
11570
11818
  }
11571
11819
 
11572
11820
  /** Send BLE transfer completion notification */