@mentra/bluetooth-sdk 3.2.1-dev.314 → 3.3.0-beta.1000

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 (199) hide show
  1. package/README.md +103 -10
  2. package/android/build.gradle +15 -0
  3. package/android/lc3Lib/build.gradle +6 -1
  4. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +368 -0
  5. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +156 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +4 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +12 -2
  11. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +2 -1
  14. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +138 -26
  15. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +37 -13
  16. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
  17. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  18. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +235 -36
  19. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulator.kt +13 -2
  23. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/requests/DisplayRequests.kt +1 -1
  25. package/android/src/main/java/com/mentra/bluetoothsdk/services/Foreground.kt +33 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/services/G2ConnectionRecovery.kt +47 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1.kt +2 -2
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G2.kt +72 -21
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +261 -42
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraNex.kt +12 -8
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +314 -395
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +247 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +238 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +58 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +180 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddress.kt +17 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SerializedGattCallback.kt +5 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/G2Text.kt +7 -0
  44. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +20 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
  46. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/DashboardContentFormatterTest.kt +2 -2
  49. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceIdentityPairingTest.kt +59 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerSceneHandoffTest.kt +666 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/G2TextTest.kt +13 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
  54. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulatorTest.kt +71 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/services/G2ConnectionRecoveryTest.kt +51 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1PairingTest.kt +105 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2DisplayThreadTest.kt +120 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2PairingTargetTest.kt +90 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveFileTransferSessionTest.kt +55 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGattCallbackTest.kt +33 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingTargetTest.kt +65 -0
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraNexPairingTest.kt +151 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoBitmapAcceptanceTest.kt +105 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +233 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +348 -0
  74. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +339 -0
  75. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoMicReconnectTest.kt +93 -0
  76. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoProtocolTest.kt +11 -0
  77. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddressTest.kt +27 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +287 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +127 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +288 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +205 -0
  82. package/build/BluetoothSdk.types.d.ts +22 -1
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js +1 -0
  85. package/build/BluetoothSdk.types.js.map +1 -1
  86. package/build/_private/BluetoothSdkModule.d.ts +6 -1
  87. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  88. package/build/_private/BluetoothSdkModule.js +5 -1
  89. package/build/_private/BluetoothSdkModule.js.map +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
  91. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  92. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  93. package/build/_private/nativeLogConsole.d.ts +19 -0
  94. package/build/_private/nativeLogConsole.d.ts.map +1 -1
  95. package/build/_private/nativeLogConsole.js +12 -0
  96. package/build/_private/nativeLogConsole.js.map +1 -1
  97. package/build/generated/changelogCatalog.d.ts +5 -2
  98. package/build/generated/changelogCatalog.d.ts.map +1 -1
  99. package/build/generated/changelogCatalog.js +6 -2
  100. package/build/generated/changelogCatalog.js.map +1 -1
  101. package/build/generated/releaseMetadata.js +6 -6
  102. package/build/generated/releaseMetadata.js.map +1 -1
  103. package/build/index.d.ts +1 -1
  104. package/build/index.d.ts.map +1 -1
  105. package/build/index.js +2 -0
  106. package/build/index.js.map +1 -1
  107. package/build/ota-transport/index.d.ts +4 -0
  108. package/build/ota-transport/index.d.ts.map +1 -1
  109. package/build/ota-transport/index.js +2 -0
  110. package/build/ota-transport/index.js.map +1 -1
  111. package/ios/BluetoothSdkModule.swift +25 -4
  112. package/ios/MentraBluetoothSDK.podspec +3 -2
  113. package/ios/Source/BluetoothBackgroundMode.swift +32 -0
  114. package/ios/Source/BluetoothSdkDefaults.swift +7 -2
  115. package/ios/Source/Bridge.swift +15 -2
  116. package/ios/Source/DeviceManager.swift +106 -66
  117. package/ios/Source/DeviceStore.swift +26 -7
  118. package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
  119. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  120. package/ios/Source/MentraBluetoothSDK.swift +324 -54
  121. package/ios/Source/TouchGesture.swift +13 -0
  122. package/ios/Source/audio/GlassesMicWatchdog.swift +33 -0
  123. package/ios/Source/events/BluetoothEvents.swift +4 -0
  124. package/ios/Source/internal/BluetoothAvailability.swift +6 -0
  125. package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
  126. package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
  127. package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
  128. package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
  129. package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
  130. package/ios/Source/requests/DisplayRequests.swift +1 -1
  131. package/ios/Source/requests/VersionInfoResponseAccumulator.swift +11 -1
  132. package/ios/Source/sgcs/Ar99.swift +1 -2
  133. package/ios/Source/sgcs/G1.swift +68 -38
  134. package/ios/Source/sgcs/G1ConnectionTarget.swift +13 -0
  135. package/ios/Source/sgcs/G2.swift +261 -247
  136. package/ios/Source/sgcs/G2ConnectionSession.swift +101 -0
  137. package/ios/Source/sgcs/Mach1.swift +19 -7
  138. package/ios/Source/sgcs/MentraLive.swift +368 -220
  139. package/ios/Source/sgcs/MentraLiveFileTransferSession.swift +137 -0
  140. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +47 -0
  141. package/ios/Source/sgcs/MentraNex.swift +8 -31
  142. package/ios/Source/sgcs/NexConnectionTarget.swift +15 -0
  143. package/ios/Source/sgcs/Nimo.swift +280 -408
  144. package/ios/Source/sgcs/NimoCanvasCodec.swift +272 -0
  145. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +233 -0
  146. package/ios/Source/sgcs/NimoCanvasImage.swift +53 -0
  147. package/ios/Source/sgcs/NimoCanvasSession.swift +166 -0
  148. package/ios/Source/sgcs/NimoDiscovery.swift +49 -0
  149. package/ios/Source/sgcs/SGCManager.swift +25 -1
  150. package/ios/Source/sgcs/VuzixConnectionTarget.swift +15 -0
  151. package/ios/Source/status/DeviceStatus.swift +1 -0
  152. package/ios/Source/stt/SherpaOnnxTranscriber.swift +49 -189
  153. package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
  154. package/ios/Source/utils/DemandDrivenAudioWorker.swift +150 -0
  155. package/ios/Source/utils/G1Text.swift +2 -24
  156. package/ios/Source/utils/G1TextSanitizer.swift +27 -0
  157. package/ios/Source/utils/G2Text.swift +11 -0
  158. package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
  159. package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
  160. package/ios/Tests/BluetoothBackgroundModeTests.swift +32 -0
  161. package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
  162. package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
  163. package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
  164. package/ios/Tests/DashboardContentFormatterTests.swift +2 -2
  165. package/ios/Tests/DashboardRenderingTests.swift +31 -0
  166. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +157 -0
  167. package/ios/Tests/DeviceIdentityPairingTests.swift +49 -0
  168. package/ios/Tests/DeviceManagerReconnectTests.swift +362 -0
  169. package/ios/Tests/G1PairingTests.swift +162 -0
  170. package/ios/Tests/G1TextSanitizerTests.swift +32 -0
  171. package/ios/Tests/G2ConnectionSessionTests.swift +172 -0
  172. package/ios/Tests/G2TextTests.swift +10 -0
  173. package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
  174. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  175. package/ios/Tests/MentraLiveFileTransferSessionTests.swift +47 -0
  176. package/ios/Tests/MentraLiveReconnectPolicyTests.swift +58 -0
  177. package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
  178. package/ios/Tests/NimoCanvasCodecTests.swift +217 -0
  179. package/ios/Tests/NimoCanvasSessionTests.swift +181 -0
  180. package/ios/Tests/NimoCanvasTransportTests.swift +186 -0
  181. package/ios/Tests/NimoDeviceCommandsTests.swift +16 -0
  182. package/ios/Tests/NimoDiscoveryTests.swift +79 -0
  183. package/ios/Tests/SGCConnectionTargetTests.swift +48 -0
  184. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  185. package/ios/Tests/VersionInfoCommandTests.swift +194 -0
  186. package/ios/Tests/VersionInfoResponseAccumulatorTests.swift +65 -0
  187. package/ios/Tests/VideoRecordingCommandTests.swift +81 -0
  188. package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
  189. package/package.json +2 -2
  190. package/plugin/build/withIos.d.ts +2 -0
  191. package/plugin/build/withIos.js +12 -1
  192. package/src/BluetoothSdk.types.ts +30 -0
  193. package/src/_private/BluetoothSdkModule.ts +12 -1
  194. package/src/_private/MentraLocalNetworkModule.ts +28 -0
  195. package/src/_private/nativeLogConsole.ts +19 -0
  196. package/src/generated/changelogCatalog.ts +6 -2
  197. package/src/generated/releaseMetadata.ts +6 -6
  198. package/src/index.ts +3 -0
  199. package/src/ota-transport/index.ts +10 -1
@@ -34,11 +34,13 @@ import android.os.SystemClock
34
34
  import com.mentra.bluetoothsdk.utils.NativeLog as Log
35
35
  import androidx.core.app.ActivityCompat
36
36
  import com.mentra.bluetoothsdk.BluetoothSdkDefaults
37
+ import com.mentra.bluetoothsdk.BluetoothSdkException
37
38
  import com.mentra.bluetoothsdk.Bridge
38
39
  import com.mentra.bluetoothsdk.DeviceManager
39
40
  import com.mentra.bluetoothsdk.PhotoRequest
40
41
  import com.mentra.bluetoothsdk.PhotoSize
41
42
  import com.mentra.bluetoothsdk.PhotoMode
43
+ import com.mentra.bluetoothsdk.TouchGesture
42
44
  import com.mentra.bluetoothsdk.DeviceStore
43
45
  import com.mentra.bluetoothsdk.ObservableStore
44
46
  import com.mentra.bluetoothsdk.incomingGlassesMessageAckId
@@ -141,6 +143,7 @@ class MentraLive : SGCManager() {
141
143
  private const val LC3_FRAME_SIZE = 40
142
144
  private const val VOICE_ACTIVITY_DETECTION_SWITCH_TYPE = 8
143
145
  private const val LOUDNESS_GATE_SWITCH_TYPE = 10
146
+ private const val AUTO_POWER_OFF_SWITCH_TYPE = 11
144
147
  // Mic tuning field names, matching the BES cs_mictun body.
145
148
  private val MIC_TUNING_FIELDS =
146
149
  listOf("gain", "open", "close", "attack", "hang", "sp_open", "sp_close", "sp_hold")
@@ -563,6 +566,13 @@ class MentraLive : SGCManager() {
563
566
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
564
567
  // after an upgrade OTA is always detected as a restart.
565
568
  private var readinessCompletedThisBleSession = false
569
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
570
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
571
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
572
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
573
+ private var pendingReadyId: String? = null
574
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
575
+ private var readyGlassesSessionId: String? = null
566
576
  // Note: appVersion, buildNumber, deviceModel, androidVersion
567
577
  // are inherited from SGCManager parent class
568
578
 
@@ -644,6 +654,10 @@ class MentraLive : SGCManager() {
644
654
  private var a2dpProfile: BluetoothA2dp? = null
645
655
  private var isA2dpProxyRegistered = false
646
656
  private var a2dpConnectAttempts = 0
657
+ private val classicAudioServiceDiscovery =
658
+ ClassicAudioServiceDiscovery(handler, CONNECTION_TIMEOUT_MS.toLong()) {
659
+ Bridge.log("LIVE: Classic: $it")
660
+ }
647
661
 
648
662
  private data class OutgoingBleCommandTraceInfo(
649
663
  val commandType: String,
@@ -776,7 +790,8 @@ class MentraLive : SGCManager() {
776
790
  }
777
791
 
778
792
  // Inner class to track incoming file transfers
779
- private class FileTransferSession(var fileName: String, var fileSize: Int) {
793
+ internal class FileTransferSession(var fileName: String, var fileSize: Int, flags: Int = 0) {
794
+ private val dynamicPayload = (flags and 0x0002) != 0
780
795
  // NOTE: fileSize may be "fake" (inflated) due to BES firmware workaround
781
796
  var actualPackSize =
782
797
  0 // Actual pack size from first received packet (for BES lie detection)
@@ -805,9 +820,8 @@ class MentraLive : SGCManager() {
805
820
  * Recalculate total packets based on actual pack size from received packet. Called when
806
821
  * first packet is received to handle variable pack sizes.
807
822
  *
808
- * NOTE: Due to BES firmware workaround, fileSize in header may be "fake" (inflated). We
809
- * detect this by checking if fileSize is a multiple of 400 (BES_HARDCODED_PACK_SIZE). If
810
- * so, totalPackets = fileSize / 400, regardless of actual pack size.
823
+ * Dynamic-payload headers carry the true byte count. Only legacy small packs use
824
+ * the inflated-size workaround (multiples of BES_HARDCODED_PACK_SIZE).
811
825
  */
812
826
  fun recalculateTotalPackets(actualPackSize: Int) {
813
827
  if (actualPackSize <= 0 || actualPackSize > K900ProtocolUtils.FILE_PACK_SIZE) {
@@ -818,8 +832,8 @@ class MentraLive : SGCManager() {
818
832
 
819
833
  // Detect BES lie: if fileSize is exact multiple of 400, glasses used the lie strategy
820
834
  val isBesLie =
821
- (fileSize % BES_HARDCODED_PACK_SIZE == 0) &&
822
- (actualPackSize != BES_HARDCODED_PACK_SIZE)
835
+ !dynamicPayload && (fileSize % BES_HARDCODED_PACK_SIZE == 0) &&
836
+ (actualPackSize < BES_HARDCODED_PACK_SIZE)
823
837
 
824
838
  val newTotalPackets: Int
825
839
  if (isBesLie) {
@@ -857,6 +871,10 @@ class MentraLive : SGCManager() {
857
871
  }
858
872
 
859
873
  fun addPacket(index: Int, data: ByteArray): Boolean {
874
+ if (dynamicPayload && (index < 0 || index >= totalPackets || actualPackSize <= 0 ||
875
+ data.size != minOf(actualPackSize, fileSize - index * actualPackSize))) {
876
+ return false
877
+ }
860
878
  if (index >= 0 && index < totalPackets && !receivedPackets.containsKey(index)) {
861
879
  receivedPackets[index] = data
862
880
 
@@ -1183,6 +1201,7 @@ class MentraLive : SGCManager() {
1183
1201
  if (state == ConnTypes.DISCONNECTED) {
1184
1202
  resetWireNegotiationState()
1185
1203
  resetPendingAckState()
1204
+ resetReadinessExchange()
1186
1205
  // Queued writes are session-bound: transmitting them into the NEXT session
1187
1206
  // (e.g. a stale handshake whose reply activates v2 before the new session
1188
1207
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1238,6 +1257,7 @@ class MentraLive : SGCManager() {
1238
1257
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1239
1258
  resetWireNegotiationState()
1240
1259
  resetPendingAckState()
1260
+ resetReadinessExchange()
1241
1261
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1242
1262
  // next link must be allowed to send them again.
1243
1263
  lastSentMicTuningBody = null
@@ -1703,6 +1723,7 @@ class MentraLive : SGCManager() {
1703
1723
  readinessCompletedThisBleSession = false
1704
1724
  glassesReadyReceived = false
1705
1725
  ctkdInitiatedThisGattSession = false
1726
+ classicAudioServiceDiscovery.cancel()
1706
1727
  audioConnected = false
1707
1728
  notificationsEnabled = false
1708
1729
  currentMtu = 23
@@ -1978,6 +1999,7 @@ class MentraLive : SGCManager() {
1978
1999
  readinessCompletedThisBleSession = false
1979
2000
  glassesReadyReceived = false
1980
2001
  ctkdInitiatedThisGattSession = false
2002
+ classicAudioServiceDiscovery.cancel()
1981
2003
  audioConnected = false
1982
2004
  notificationsEnabled = false
1983
2005
  processSendQueueRunnable?.let { handler.removeCallbacks(it) }
@@ -2147,7 +2169,7 @@ class MentraLive : SGCManager() {
2147
2169
  // than scanning).
2148
2170
  // Falls back to name-based scan if no address is saved.
2149
2171
  val lastDeviceAddress =
2150
- DeviceStore.get("bluetooth", "device_address") as String?
2172
+ selectedConnectionAddress()
2151
2173
  if (lastDeviceAddress != null &&
2152
2174
  !lastDeviceAddress.isEmpty() &&
2153
2175
  bluetoothAdapter != null
@@ -2345,6 +2367,7 @@ class MentraLive : SGCManager() {
2345
2367
  registerBondingReceiver()
2346
2368
  bondingRetryCount = 0
2347
2369
  ctkdInitiatedThisGattSession = false
2370
+ classicAudioServiceDiscovery.cancel()
2348
2371
  Bridge.log(
2349
2372
  "LIVE: CTKD: BLE GATT up - deferring Classic/A2DP until notifications ready"
2350
2373
  )
@@ -2393,6 +2416,7 @@ class MentraLive : SGCManager() {
2393
2416
  // Reset audio pairing flags
2394
2417
  glassesReadyReceived = false
2395
2418
  ctkdInitiatedThisGattSession = false
2419
+ classicAudioServiceDiscovery.cancel()
2396
2420
  audioConnected = false
2397
2421
 
2398
2422
  notificationsEnabled = false
@@ -2455,6 +2479,7 @@ class MentraLive : SGCManager() {
2455
2479
  glassesReadyReceived = false
2456
2480
  audioConnected = false
2457
2481
  ctkdInitiatedThisGattSession = false
2482
+ classicAudioServiceDiscovery.cancel()
2458
2483
 
2459
2484
  notificationsEnabled = false
2460
2485
 
@@ -3366,10 +3391,12 @@ class MentraLive : SGCManager() {
3366
3391
  sendJson(json, wakeup, true)
3367
3392
  }
3368
3393
 
3369
- private fun sendJson(json: JSONObject?, wakeup: Boolean, bridgeLogging: Boolean): Boolean {
3394
+ private fun sendJson(
3395
+ json: JSONObject?, wakeup: Boolean, bridgeLogging: Boolean,
3396
+ sessionGeneration: Long = bleSessionGeneration.get(),
3397
+ ): Boolean {
3370
3398
  if (json != null) {
3371
3399
  try {
3372
- val sessionGeneration = bleSessionGeneration.get()
3373
3400
  if (buildNumberInt < 5) {
3374
3401
  val jsonStr = json.toString()
3375
3402
  // Bridge.log("LIVE: 📤 Sending JSON with esoteric message ID: " + jsonStr);
@@ -4137,7 +4164,9 @@ class MentraLive : SGCManager() {
4137
4164
  "controllerId" to json.opt("controllerId"), "streamId" to json.opt("streamId"),
4138
4165
  "probeId" to json.opt("probeId"))
4139
4166
  com.mentra.bluetoothsdk.streaming.StreamControllerProbe.response(values)?.let {
4140
- sendJson(JSONObject(it))
4167
+ // BES buffers non-waking commands when MTK enters standby, even while
4168
+ // its streaming CPU lease is held. The current probe needs a live reply.
4169
+ sendJson(JSONObject(it), true)
4141
4170
  }
4142
4171
  }
4143
4172
  "pong" ->
@@ -4592,6 +4621,19 @@ class MentraLive : SGCManager() {
4592
4621
  Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
4593
4622
  return
4594
4623
  }
4624
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
4625
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
4626
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
4627
+ Bridge.log(
4628
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
4629
+ "the glasses did not reset for it"
4630
+ )
4631
+ return
4632
+ }
4633
+ if (readyId != null && readyId == pendingReadyId) {
4634
+ pendingReadyId = null
4635
+ }
4636
+ readyGlassesSessionId = sid
4595
4637
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4596
4638
  pairingYieldAwaitingReclaim = false
4597
4639
  pairingYieldActive = false
@@ -4613,7 +4655,7 @@ class MentraLive : SGCManager() {
4613
4655
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4614
4656
  // already runs this full remote-reset flow, so recording (not re-triggering)
4615
4657
  // is correct here; version_info detection covers the restart case.
4616
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
4658
+ glassesSessionId = sid
4617
4659
  streamControlVersion = json.optInt("streamControlVersion", 0)
4618
4660
  Bridge.sendTypedMessage(
4619
4661
  "wifi_protocol_session_ready",
@@ -5451,6 +5493,14 @@ class MentraLive : SGCManager() {
5451
5493
  // Bridge.log("LIVE: Processing K900 command: " + command);
5452
5494
 
5453
5495
  when (command) {
5496
+ "sr_tpdef" -> {
5497
+ val body = when (val value = json.opt("B")) {
5498
+ is JSONObject -> value
5499
+ is String -> runCatching { JSONObject(value) }.getOrNull()
5500
+ else -> null
5501
+ }
5502
+ if (body != null && body.optString("setting") == "touch_gesture_default") emitSettingsAck(body)
5503
+ }
5454
5504
  "sr_hrt" -> {
5455
5505
  try {
5456
5506
  val bodyObj = json.optJSONObject("B")
@@ -5548,7 +5598,9 @@ class MentraLive : SGCManager() {
5548
5598
  if (bodyObj != null) {
5549
5599
  val type = bodyObj.optInt("type", -1)
5550
5600
  val value = bodyObj.optInt("switch", -1)
5551
- handleSwitchStatus(type, value, System.currentTimeMillis())
5601
+ // K900 replies carry result in "S"; 0 is RC_SUCCESS.
5602
+ val resultCode = json.optInt("S", -1)
5603
+ handleSwitchStatus(type, value, System.currentTimeMillis(), resultCode)
5552
5604
  }
5553
5605
  } catch (e: Exception) {
5554
5606
  Log.e(TAG, "Error parsing sr_swit response", e)
@@ -5578,7 +5630,13 @@ class MentraLive : SGCManager() {
5578
5630
  try {
5579
5631
  val bodyObj = optK900Body(json)
5580
5632
  if (bodyObj != null) {
5581
- Bridge.sendWearState(bodyObj.optInt("on", 0) != 0)
5633
+ val extras = HashMap<String, Any>()
5634
+ if (bodyObj.has("elapsed_ms")) extras["elapsedMs"] = bodyObj.optInt("elapsed_ms")
5635
+ if (bodyObj.has("timeout_ms")) extras["timeoutMs"] = bodyObj.optInt("timeout_ms")
5636
+ if (bodyObj.has("enabled")) extras["enabled"] = bodyObj.optInt("enabled") != 0
5637
+ if (bodyObj.has("armed")) extras["armed"] = bodyObj.optInt("armed") != 0
5638
+ if (bodyObj.has("inhibited")) extras["inhibited"] = bodyObj.optInt("inhibited") != 0
5639
+ Bridge.sendWearState(bodyObj.optInt("on", 0) != 0, extras)
5582
5640
  }
5583
5641
  } catch (e: Exception) {
5584
5642
  Log.e(TAG, "Error parsing sr_wrst response", e)
@@ -5933,8 +5991,20 @@ class MentraLive : SGCManager() {
5933
5991
  Bridge.sendWearTuningState(state)
5934
5992
  }
5935
5993
 
5936
- private fun handleSwitchStatus(switchType: Int, switchValue: Int, timestamp: Long) {
5994
+ private fun handleSwitchStatus(
5995
+ switchType: Int,
5996
+ switchValue: Int,
5997
+ timestamp: Long,
5998
+ resultCode: Int = -1
5999
+ ) {
5937
6000
  Bridge.sendSwitchStatus(switchType, switchValue, timestamp)
6001
+ if (switchType == AUTO_POWER_OFF_SWITCH_TYPE) {
6002
+ val ok = resultCode == 0
6003
+ Bridge.log(
6004
+ "LIVE: 🔋 auto power-off sr_swit reply type=$switchType switch=$switchValue" +
6005
+ " result=$resultCode ok=$ok"
6006
+ )
6007
+ }
5938
6008
  if (switchType == VOICE_ACTIVITY_DETECTION_SWITCH_TYPE &&
5939
6009
  (switchValue == 0 || switchValue == 1)
5940
6010
  ) {
@@ -6048,6 +6118,17 @@ class MentraLive : SGCManager() {
6048
6118
  }
6049
6119
 
6050
6120
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6121
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6122
+ throw BluetoothSdkException(
6123
+ "glasses_not_connected", "Cannot request incident logs because the glasses BLE link is not ready.",
6124
+ )
6125
+ }
6126
+ // The JS token sync may happen after glasses_ready. Use only its current native store value.
6127
+ val coreToken = DeviceStore.get("bluetooth", "core_token") as? String
6128
+ if (coreToken.isNullOrBlank()) {
6129
+ throw BluetoothSdkException("core_token_unavailable", "Cannot request incident logs without the current Core access token.")
6130
+ }
6131
+ val sessionGeneration = bleSessionGeneration.get()
6051
6132
  try {
6052
6133
  var base = if (apiBaseUrl != null) apiBaseUrl.trim() else ""
6053
6134
  if (base.isEmpty()) {
@@ -6060,13 +6141,25 @@ class MentraLive : SGCManager() {
6060
6141
  bleIncidentLogRelays[lKey] =
6061
6142
  BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6062
6143
 
6144
+ val auth = JSONObject()
6145
+ auth.put("type", "auth_token")
6146
+ auth.put("coreToken", coreToken)
6147
+ auth.put("timestamp", System.currentTimeMillis())
6063
6148
  val json = JSONObject()
6064
6149
  json.put("type", "upload_incident_logs")
6065
6150
  json.put("incidentId", incidentId)
6066
6151
  json.put("apiBaseUrl", base)
6067
- sendJson(json, true)
6152
+ // Wake ASG with its current token before the upload command enters the same FIFO.
6153
+ if (!sendJson(auth, true, true, sessionGeneration) ||
6154
+ sessionGeneration != bleSessionGeneration.get() ||
6155
+ !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6156
+ !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6157
+ bleIncidentLogRelays.remove(bKey)
6158
+ bleIncidentLogRelays.remove(lKey)
6159
+ throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6160
+ }
6068
6161
  Bridge.log(
6069
- "LIVE: Sent incidentId to glasses for log upload: " +
6162
+ "LIVE: Queued incidentId to glasses for log upload: " +
6070
6163
  incidentId +
6071
6164
  " (BLE relay keys " +
6072
6165
  bKey +
@@ -6075,7 +6168,7 @@ class MentraLive : SGCManager() {
6075
6168
  ")"
6076
6169
  )
6077
6170
  } catch (e: JSONException) {
6078
- Log.e(TAG, "Error creating upload_incident_logs command", e)
6171
+ throw BluetoothSdkException("incident_dispatch_failed", "Could not create the glasses incident-log request.", e)
6079
6172
  }
6080
6173
  }
6081
6174
 
@@ -6140,13 +6233,27 @@ class MentraLive : SGCManager() {
6140
6233
  val json = JSONObject()
6141
6234
  json.put("type", "request_version")
6142
6235
  requestId?.let { json.put("request_id", it) }
6143
- sendJson(json, false)
6236
+ // Wake ASG so the version request and its response can finish after idle.
6237
+ sendJson(json, true)
6144
6238
  Bridge.log("LIVE: 📱 Requesting version info from glasses")
6145
6239
  } catch (e: JSONException) {
6146
6240
  Log.e(TAG, "📱 Error creating request_version command", e)
6147
6241
  }
6148
6242
  }
6149
6243
 
6244
+ fun sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Boolean) {
6245
+ val sessionGeneration = bleSessionGeneration.get()
6246
+ if (!isConnected) throw BluetoothSdkException("not_connected", "Mentra Live glasses are not connected.")
6247
+ val body = JSONObject().put("request_id", requestId).put("gesture", gesture.wireName).put("enabled", enabled)
6248
+ val command = JSONObject().put("C", "cs_tpdef").put("V", 1).put("B", body.toString())
6249
+ val packet = K900ProtocolUtils.packDataToK900(
6250
+ command.toString().toByteArray(StandardCharsets.UTF_8),
6251
+ K900ProtocolUtils.CMD_TYPE_STRING,
6252
+ k900LengthEndian(),
6253
+ ) ?: throw BluetoothSdkException("command_send_failed", "Could not encode the touch gesture setting.")
6254
+ queueData(packet, sessionGeneration = sessionGeneration)
6255
+ }
6256
+
6150
6257
  fun sendGalleryServerEnabled(requestId: String, enabled: Boolean) {
6151
6258
  val json = JSONObject()
6152
6259
  .put("type", "set_gallery_server_enabled")
@@ -6602,6 +6709,14 @@ class MentraLive : SGCManager() {
6602
6709
  return false
6603
6710
  }
6604
6711
 
6712
+ private fun selectedConnectionAddress(): String? = SelectedDeviceAddress.resolve(
6713
+ savedDeviceName,
6714
+ DeviceStore.get("bluetooth", "pending_device_name") as? String,
6715
+ DeviceStore.get("bluetooth", "pending_device_address") as? String,
6716
+ DeviceStore.get("bluetooth", "device_name") as? String,
6717
+ DeviceStore.get("bluetooth", "device_address") as? String,
6718
+ )
6719
+
6605
6720
  fun connectToSmartGlasses() {
6606
6721
  if (postGattLifecycle { connectToSmartGlasses() }) return
6607
6722
  if (pairingYieldActive) {
@@ -6636,13 +6751,7 @@ class MentraLive : SGCManager() {
6636
6751
  // var context = Bridge.getContext();
6637
6752
  // SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
6638
6753
  // String lastDeviceAddress = prefs.getString(PREF_DEVICE_NAME, null);
6639
- val pendingAddress =
6640
- (DeviceStore.get("bluetooth", "pending_device_address") as String?)?.takeIf {
6641
- it.isNotEmpty()
6642
- }
6643
- val lastDeviceAddress =
6644
- pendingAddress
6645
- ?: (DeviceStore.get("bluetooth", "device_address") as String?)
6754
+ val lastDeviceAddress = selectedConnectionAddress()
6646
6755
 
6647
6756
  if (lastDeviceAddress != null && lastDeviceAddress.length > 0) {
6648
6757
  // Connect to last known device if available
@@ -7178,7 +7287,7 @@ class MentraLive : SGCManager() {
7178
7287
  BluetoothDevice.BOND_BONDED ->
7179
7288
  run {
7180
7289
  Bridge.log(
7181
- "LIVE: CTKD: ✅ Successfully bonded with device - BT Classic connection established"
7290
+ "LIVE: CTKD: Successfully bonded - checking Classic audio services"
7182
7291
  )
7183
7292
  markPairingTiming(
7184
7293
  "ctkd_bonded",
@@ -7197,7 +7306,7 @@ class MentraLive : SGCManager() {
7197
7306
  // path does this at GATT connect).
7198
7307
  // markAudioConnected / sendAudioConnected fire
7199
7308
  // when the A2DP path completes.
7200
- connectA2dpProfile(device)
7309
+ prepareClassicAudio(device)
7201
7310
 
7202
7311
  // Safety net: if glasses_ready somehow missed
7203
7312
  // setting fullyBooted, catch up here.
@@ -7234,6 +7343,7 @@ class MentraLive : SGCManager() {
7234
7343
  }
7235
7344
  }
7236
7345
  BluetoothDevice.BOND_NONE -> {
7346
+ classicAudioServiceDiscovery.cancel()
7237
7347
  Bridge.log(
7238
7348
  "LIVE: CTKD: ❌ Bonding failed or removed for device"
7239
7349
  )
@@ -7355,6 +7465,10 @@ class MentraLive : SGCManager() {
7355
7465
  classicAudioReceiver =
7356
7466
  object : BroadcastReceiver() {
7357
7467
  override fun onReceive(context: Context?, intent: Intent?) {
7468
+ if (intent?.action == BluetoothDevice.ACTION_UUID) {
7469
+ intent.bluetoothDeviceExtra()?.let { classicAudioServiceDiscovery.onUuids(it) }
7470
+ return
7471
+ }
7358
7472
  if (intent?.action != BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED &&
7359
7473
  intent?.action != BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) return
7360
7474
  val device = intent.bluetoothDeviceExtra() ?: return
@@ -7371,6 +7485,7 @@ class MentraLive : SGCManager() {
7371
7485
  try {
7372
7486
  val filter =
7373
7487
  IntentFilter().apply {
7488
+ addAction(BluetoothDevice.ACTION_UUID)
7374
7489
  addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)
7375
7490
  addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
7376
7491
  }
@@ -7495,10 +7610,10 @@ class MentraLive : SGCManager() {
7495
7610
  when (device.bondState) {
7496
7611
  BluetoothDevice.BOND_BONDED -> {
7497
7612
  Bridge.log(
7498
- "LIVE: CTKD: Device is already bonded - connecting A2DP audio profile"
7613
+ "LIVE: CTKD: Device is already bonded - checking Classic audio services"
7499
7614
  )
7500
7615
  markPairingTiming("ctkd_already_bonded")
7501
- connectA2dpProfile(device)
7616
+ prepareClassicAudio(device)
7502
7617
  }
7503
7618
  BluetoothDevice.BOND_BONDING -> {
7504
7619
  // Secure pairing firmware may request SMP as soon as GATT connects.
@@ -7557,6 +7672,19 @@ class MentraLive : SGCManager() {
7557
7672
  return classicAudioConnectionTracker.connected
7558
7673
  }
7559
7674
 
7675
+ private fun prepareClassicAudio(device: BluetoothDevice) {
7676
+ if (!canConnectClassicAudio(device)) return
7677
+ val gatt = bluetoothGatt
7678
+ classicAudioServiceDiscovery.connectWhenDiscovered(device) {
7679
+ if (bluetoothGatt === gatt && canConnectClassicAudio(device)) connectA2dpProfile(device)
7680
+ }
7681
+ }
7682
+
7683
+ private fun canConnectClassicAudio(device: BluetoothDevice): Boolean =
7684
+ !isKilled && !pairingYieldActive && isConnected && notificationsEnabled &&
7685
+ ctkdInitiatedThisGattSession && connectedDevice?.address == device.address &&
7686
+ device.bondState == BluetoothDevice.BOND_BONDED
7687
+
7560
7688
  /** A2DP profile service listener for connecting to already-bonded devices */
7561
7689
  private val a2dpServiceListener: BluetoothProfile.ServiceListener =
7562
7690
  object : BluetoothProfile.ServiceListener {
@@ -7605,7 +7733,9 @@ class MentraLive : SGCManager() {
7605
7733
  Bridge.log("LIVE: A2DP: Skipping connectA2dpWithProxy — SGC destroyed")
7606
7734
  return
7607
7735
  }
7608
- if (a2dpProfile == null || device == null) {
7736
+ if (device == null || !canConnectClassicAudio(device) ||
7737
+ !ClassicAudioServiceDiscovery.hasAudioSink(device)) return
7738
+ if (a2dpProfile == null) {
7609
7739
  Bridge.log("LIVE: A2DP: Cannot connect - proxy or device is null")
7610
7740
  return
7611
7741
  }
@@ -7655,14 +7785,11 @@ class MentraLive : SGCManager() {
7655
7785
  "LIVE: A2DP: Retry $a2dpConnectAttempts/$A2DP_CONNECT_MAX_ATTEMPTS in " +
7656
7786
  "${A2DP_CONNECT_RETRY_MS}ms ($reason)"
7657
7787
  )
7788
+ val gatt = bluetoothGatt
7658
7789
  handler.postDelayed(
7659
7790
  Runnable {
7660
- if (isKilled || pairingYieldActive || connectedDevice == null) {
7661
- return@Runnable
7662
- }
7663
- val target = connectedDevice ?: return@Runnable
7664
- if (a2dpProfile != null) {
7665
- connectA2dpWithProxy(target)
7791
+ if (bluetoothGatt === gatt && canConnectClassicAudio(device)) {
7792
+ connectA2dpWithProxy(device)
7666
7793
  }
7667
7794
  },
7668
7795
  A2DP_CONNECT_RETRY_MS
@@ -7882,6 +8009,7 @@ class MentraLive : SGCManager() {
7882
8009
 
7883
8010
  // Mark as killed to prevent reconnection attempts
7884
8011
  isKilled = true
8012
+ classicAudioServiceDiscovery.cancel()
7885
8013
  explicitConnectByName = false
7886
8014
  pairingYieldActive = false
7887
8015
  pairingYieldAwaitingReclaim = false
@@ -7903,7 +8031,11 @@ class MentraLive : SGCManager() {
7903
8031
 
7904
8032
  // Tear down Classic (A2DP/HFP) before GATT close. Closing only the proxy left the
7905
8033
  // phone's system Bluetooth UI showing Mentra Live still connected.
7906
- val classicDevice = connectedDevice
8034
+ // BLE loss clears connectedDevice while the OS audio profiles can remain connected.
8035
+ // Use this session's existing Classic target before resetting the tracker below.
8036
+ val classicDevice = connectedDevice ?: classicAudioConnectionTracker.targetForDisconnect()?.let {
8037
+ bluetoothAdapter?.getRemoteDevice(it)
8038
+ }
7907
8039
  disconnectClassicProfiles(classicDevice)
7908
8040
  closeA2dpProxy()
7909
8041
  classicAudioConnectionTracker.reset()
@@ -7980,6 +8112,7 @@ class MentraLive : SGCManager() {
7980
8112
  glassesReadyReceived = false
7981
8113
  audioConnected = false
7982
8114
  ctkdInitiatedThisGattSession = false
8115
+ classicAudioServiceDiscovery.cancel()
7983
8116
  DeviceStore.apply("glasses", "fullyBooted", false)
7984
8117
  updateConnectionState(ConnTypes.DISCONNECTED)
7985
8118
 
@@ -8999,13 +9132,34 @@ class MentraLive : SGCManager() {
8999
9132
  wireHandshakeSentGeneration = -1
9000
9133
  }
9001
9134
 
9135
+ /**
9136
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9137
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9138
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9139
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9140
+ * superseded by the pending exchange, whose answer is still to come.
9141
+ */
9142
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9143
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9144
+
9145
+ private fun resetReadinessExchange() {
9146
+ pendingReadyId = null
9147
+ readyGlassesSessionId = null
9148
+ }
9149
+
9002
9150
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9003
9151
  private fun sendPhoneReady(reason: String) {
9004
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9152
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9153
+ pendingReadyId = readyId
9154
+ Bridge.log(
9155
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
9156
+ "waiting for glasses_ready response"
9157
+ )
9005
9158
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9006
9159
  val readyMsg = JSONObject()
9007
9160
  readyMsg.put("type", "phone_ready")
9008
9161
  readyMsg.put("timestamp", System.currentTimeMillis())
9162
+ readyMsg.put("readyId", readyId)
9009
9163
  sendJson(readyMsg, true)
9010
9164
  }
9011
9165
 
@@ -9467,7 +9621,11 @@ class MentraLive : SGCManager() {
9467
9621
  }
9468
9622
  } else {
9469
9623
  // Normal single message transmission
9470
- transportLog("LIVE: Sending data to glasses: " + wireData, bridgeLogging)
9624
+ transportLog(
9625
+ "LIVE: Sending data to glasses: " +
9626
+ loggableOutgoingPayload(wireData, commandTraceInfo.commandType),
9627
+ bridgeLogging
9628
+ )
9471
9629
 
9472
9630
  // Pack the data using the centralized utility with the negotiated endianness
9473
9631
  val packedData =
@@ -9769,6 +9927,18 @@ class MentraLive : SGCManager() {
9769
9927
  }
9770
9928
  }
9771
9929
 
9930
+ /**
9931
+ * Credentials are sent unchanged but never logged; the BLE trace redacts their fields.
9932
+ */
9933
+ private fun loggableOutgoingPayload(payload: String, commandType: String): String =
9934
+ try {
9935
+ val json = JSONObject(payload)
9936
+ if (json.has("password") || json.has("coreToken")) "<$commandType with credentials omitted>"
9937
+ else payload
9938
+ } catch (_: JSONException) {
9939
+ payload
9940
+ }
9941
+
9772
9942
  private fun summarizeOutgoingMessage(payload: String?): String {
9773
9943
  if (payload == null || payload.isEmpty()) {
9774
9944
  return "type=unknown, requestId=none, appId=none, mode=none, transferMethod=none, bleImgId=none, exposureTimeNs=none, iso=none, mId=none"
@@ -10193,7 +10363,7 @@ class MentraLive : SGCManager() {
10193
10363
  if (incidentRelay.session == null) {
10194
10364
  activeFileTransfers.remove(packetInfo.fileName)
10195
10365
  incidentRelay.session =
10196
- FileTransferSession(packetInfo.fileName, packetInfo.fileSize)
10366
+ FileTransferSession(packetInfo.fileName, packetInfo.fileSize, packetInfo.flags)
10197
10367
  incidentRelay.session!!.recalculateTotalPackets(packetInfo.packSize)
10198
10368
  Bridge.log(
10199
10369
  "LIVE: 📦 Started BLE incident log transfer: " +
@@ -10244,7 +10414,7 @@ class MentraLive : SGCManager() {
10244
10414
  // Get or create session for this transfer
10245
10415
  if (photoTransfer.session == null) {
10246
10416
  photoTransfer.session =
10247
- FileTransferSession(packetInfo.fileName, packetInfo.fileSize)
10417
+ FileTransferSession(packetInfo.fileName, packetInfo.fileSize, packetInfo.flags)
10248
10418
  // Recalculate total packets based on actual pack size (handles variable MTU)
10249
10419
  photoTransfer.session!!.recalculateTotalPackets(packetInfo.packSize)
10250
10420
  Bridge.log(
@@ -10330,7 +10500,7 @@ class MentraLive : SGCManager() {
10330
10500
  var session = activeFileTransfers[packetInfo.fileName]
10331
10501
  if (session == null) {
10332
10502
  // New file transfer
10333
- session = FileTransferSession(packetInfo.fileName, packetInfo.fileSize)
10503
+ session = FileTransferSession(packetInfo.fileName, packetInfo.fileSize, packetInfo.flags)
10334
10504
  // Recalculate total packets based on actual pack size (handles variable MTU)
10335
10505
  session.recalculateTotalPackets(packetInfo.packSize)
10336
10506
  activeFileTransfers[packetInfo.fileName] = session
@@ -10825,6 +10995,9 @@ class MentraLive : SGCManager() {
10825
10995
  // Send glasses-side loudness / Barrier gate setting.
10826
10996
  sendLoudnessGateSetting()
10827
10997
 
10998
+ // Send glasses-side auto power-off setting.
10999
+ sendAutoPowerOffSetting()
11000
+
10828
11001
  // Send mic tuning. With nothing authorized this sends a reset, which is
10829
11002
  // what returns a freshly connected pair of glasses to stock behaviour.
10830
11003
  sendMicTuningSetting()
@@ -11108,6 +11281,52 @@ class MentraLive : SGCManager() {
11108
11281
  }
11109
11282
  }
11110
11283
 
11284
+ override fun sendAutoPowerOffSetting() {
11285
+ val value = DeviceStore.get("bluetooth", "auto_power_off_enabled")
11286
+ val enabled =
11287
+ if (value is Boolean) value
11288
+ else BluetoothSdkDefaults.AUTO_POWER_OFF_ENABLED
11289
+
11290
+ Bridge.log(
11291
+ "LIVE: 🔋 Sending auto power-off setting to glasses: enabled=$enabled" +
11292
+ " (cs_swit type=$AUTO_POWER_OFF_SWITCH_TYPE)"
11293
+ )
11294
+
11295
+ if (!isConnected) {
11296
+ Bridge.log("LIVE: Cannot send auto power-off setting - not connected")
11297
+ return
11298
+ }
11299
+
11300
+ try {
11301
+ val body = JSONObject()
11302
+ body.put("type", AUTO_POWER_OFF_SWITCH_TYPE)
11303
+ body.put("switch", if (enabled) 1 else 0)
11304
+
11305
+ val cmdObject = JSONObject()
11306
+ cmdObject.put("C", "cs_swit")
11307
+ cmdObject.put("V", 1)
11308
+ cmdObject.put("B", body.toString())
11309
+
11310
+ val packedData =
11311
+ K900ProtocolUtils.packDataToK900(
11312
+ cmdObject.toString().toByteArray(StandardCharsets.UTF_8),
11313
+ K900ProtocolUtils.CMD_TYPE_STRING,
11314
+ k900LengthEndian()
11315
+ )
11316
+ if (packedData == null) {
11317
+ Bridge.log("LIVE: Failed to pack auto power-off setting command")
11318
+ return
11319
+ }
11320
+ queueData(packedData)
11321
+ Bridge.log(
11322
+ "LIVE: 🔋 Queued auto power-off cs_swit type=$AUTO_POWER_OFF_SWITCH_TYPE" +
11323
+ " switch=${if (enabled) 1 else 0}"
11324
+ )
11325
+ } catch (e: JSONException) {
11326
+ Log.e(TAG, "Error creating auto power-off setting command", e)
11327
+ }
11328
+ }
11329
+
11111
11330
  /** Send button photo settings to glasses, replaying all stored scan-tuning fields. */
11112
11331
  override fun sendButtonPhotoSettings() {
11113
11332
  val legacyZslMfnr =