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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +40 -13
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +114 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
  16. package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
  18. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +274 -56
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +5 -5
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  41. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  42. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  44. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  45. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  46. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  47. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  48. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  49. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  50. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  51. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
  54. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
  61. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +3 -3
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  74. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
  75. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  76. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  77. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  82. package/build/BluetoothSdk.types.d.ts +103 -5
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js.map +1 -1
  85. package/build/_private/BluetoothSdkModule.d.ts +42 -8
  86. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  87. package/build/_private/BluetoothSdkModule.js +1 -0
  88. package/build/_private/BluetoothSdkModule.js.map +1 -1
  89. package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  91. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  92. package/build/generated/changelogCatalog.d.ts +2 -2
  93. package/build/generated/changelogCatalog.js +2 -2
  94. package/build/generated/changelogCatalog.js.map +1 -1
  95. package/build/generated/releaseMetadata.js +5 -5
  96. package/build/generated/releaseMetadata.js.map +1 -1
  97. package/build/index.d.ts +1 -1
  98. package/build/index.d.ts.map +1 -1
  99. package/build/index.js +7 -1
  100. package/build/index.js.map +1 -1
  101. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  102. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  103. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  106. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  107. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  108. package/build/ota-transport/index.d.ts +3 -3
  109. package/build/ota-transport/index.d.ts.map +1 -1
  110. package/build/ota-transport/index.js +4 -4
  111. package/build/ota-transport/index.js.map +1 -1
  112. package/build/react/useGlassesConnection.d.ts +1 -1
  113. package/build/react/useGlassesConnection.d.ts.map +1 -1
  114. package/build/react/useGlassesConnection.js +3 -3
  115. package/build/react/useGlassesConnection.js.map +1 -1
  116. package/build/react/useMentraBluetooth.d.ts +1 -1
  117. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  118. package/build/react/useMentraBluetooth.js +1 -1
  119. package/build/react/useMentraBluetooth.js.map +1 -1
  120. package/ios/BluetoothSdkModule.swift +73 -22
  121. package/ios/LocalIPv4.swift +0 -61
  122. package/ios/MentraBluetoothSDK.podspec +7 -1
  123. package/ios/MentraOtaServerModule.swift +0 -16
  124. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  125. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  126. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  127. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  128. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  129. package/ios/Source/Bridge.swift +14 -0
  130. package/ios/Source/DeviceManager.swift +43 -22
  131. package/ios/Source/GeneratedChangelogCatalog.swift +2 -2
  132. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  133. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  134. package/ios/Source/OtaManifest.swift +1 -17
  135. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  136. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  137. package/ios/Source/audio/SpeechActivity.swift +277 -0
  138. package/ios/Source/events/BluetoothEvents.swift +41 -0
  139. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  140. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  141. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  142. package/ios/Source/sgcs/MentraLive.swift +195 -66
  143. package/ios/Source/sgcs/Nimo.swift +249 -276
  144. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  145. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  146. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  147. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  148. package/ios/Source/sgcs/SGCManager.swift +6 -0
  149. package/ios/Source/streaming/StreamModels.swift +15 -6
  150. package/ios/Source/stt/STTTools.swift +13 -31
  151. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  152. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  153. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  154. package/ios/Source/utils/BoundedWait.swift +44 -0
  155. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  156. package/ios/Source/utils/SttModelTraits.swift +62 -0
  157. package/ios/Tests/BesCrashReportTests.swift +142 -0
  158. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  159. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  160. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  161. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  162. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  163. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  164. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  165. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  166. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  167. package/ios/Tests/PcmStreamTests.swift +299 -0
  168. package/ios/Tests/SpeechActivityTests.swift +238 -0
  169. package/ios/Tests/StreamRequestTests.swift +18 -0
  170. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  171. package/package.json +2 -2
  172. package/plugin/build/withAndroid.js +9 -11
  173. package/plugin/build/withKotlinVersion.d.ts +2 -0
  174. package/plugin/build/withKotlinVersion.js +46 -0
  175. package/src/BluetoothSdk.types.ts +107 -5
  176. package/src/_private/BluetoothSdkModule.ts +45 -8
  177. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  178. package/src/generated/changelogCatalog.ts +2 -2
  179. package/src/generated/releaseMetadata.ts +5 -5
  180. package/src/index.ts +13 -1
  181. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  182. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  183. package/src/ota-transport/index.ts +4 -5
  184. package/src/react/useGlassesConnection.ts +4 -4
  185. package/src/react/useMentraBluetooth.ts +2 -2
  186. package/android/silero/LICENSE.md +0 -17
  187. package/android/silero/build.gradle +0 -50
  188. package/android/silero/proguard-rules.pro +0 -24
  189. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  190. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  191. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  198. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  199. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  202. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  203. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  204. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  206. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  207. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  210. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  211. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  212. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  213. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  214. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  215. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -696,25 +696,28 @@ private struct BlePhotoTransfer {
696
696
  }
697
697
  }
698
698
 
699
- private enum BleIncidentLogRelayKind {
699
+ enum BleIncidentLogRelayKind {
700
700
  case firmware
701
701
  case logcat
702
702
  }
703
703
 
704
- private final class BleIncidentLogRelayEntry {
704
+ final class BleIncidentLogRelayEntry {
705
705
  let fileBaseKey: String
706
706
  let incidentId: String
707
707
  let apiBaseUrl: String
708
708
  let kind: BleIncidentLogRelayKind
709
+ let reservedAt: TimeInterval
709
710
  var session: MentraLiveFileTransferSession?
710
711
 
711
712
  init(
712
- fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind
713
+ fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind,
714
+ reservedAt: TimeInterval
713
715
  ) {
714
716
  self.fileBaseKey = fileBaseKey
715
717
  self.incidentId = incidentId
716
718
  self.apiBaseUrl = apiBaseUrl
717
719
  self.kind = kind
720
+ self.reservedAt = reservedAt
718
721
  }
719
722
  }
720
723
 
@@ -783,26 +786,8 @@ extension MentraLive: CBCentralManagerDelegate {
783
786
  if !isReconnectTarget && advertisesPairingFlag(advertisementData)
784
787
  && !isPairingDiscoverable(advertisementData)
785
788
  {
786
- // Keep nearby secure units visible with pairing-mode guidance, while RN blocks
787
- // the connection until a pairable advertisement arrives.
788
- pairFlow(
789
- "discover",
790
- "name=\(name) id=\(peripheral.identifier.uuidString) saved=\(savedDeviceName ?? "-") pairingMode=false secure=true connect=false"
791
- )
792
- discoveredPeripherals[name] = peripheral
793
- rememberPeripheral(peripheral, name: name)
794
- if cacheAdvPairing(
795
- name,
796
- pairingMode: false,
797
- pairingCode: nil,
798
- securePairingCapable: true
799
- ) {
800
- emitDiscoveredDeviceFromCache(
801
- name,
802
- identifier: peripheral.identifier.uuidString,
803
- rssi: rssi?.intValue
804
- )
805
- }
789
+ // Only glasses that can pair now are listed; a closed window drops them.
790
+ unlistNotPairable(name)
806
791
  return
807
792
  }
808
793
 
@@ -828,11 +813,13 @@ extension MentraLive: CBCentralManagerDelegate {
828
813
  discoveredPeripherals[name] = peripheral
829
814
  rememberPeripheral(peripheral, name: name)
830
815
 
831
- if !partialAdvertisement, cacheAdvPairing(
816
+ if trailer.secureCapable && !trailer.pairingMode {
817
+ unlistNotPairable(name)
818
+ } else if !partialAdvertisement, cacheAdvPairing(
832
819
  name,
833
820
  // Field firmware has no pairing flag. Treat it as pairable so the
834
821
  // new Mentra App can still find old glasses.
835
- pairingMode: trailer.secureCapable ? trailer.pairingMode : true,
822
+ pairingMode: true,
836
823
  pairingCode: trailer.pairingCode,
837
824
  securePairingCapable: trailer.secureCapable
838
825
  ) {
@@ -1504,6 +1491,7 @@ class MentraLive: NSObject, SGCManager {
1504
1491
  if state == ConnTypes.DISCONNECTED {
1505
1492
  resetPendingAckState(reason: "BLE session ended")
1506
1493
  resetWireNegotiationState()
1494
+ resetReadinessExchange()
1507
1495
  resetAncsRelayState()
1508
1496
  // Queued writes are session-bound: transmitting them into the NEXT session
1509
1497
  // (e.g. a stale handshake whose reply activates v2 before the new session
@@ -1546,13 +1534,16 @@ class MentraLive: NSObject, SGCManager {
1546
1534
  func dbg1() {}
1547
1535
  func dbg2() {}
1548
1536
 
1537
+ /// Clear the saved device name so the pairing filter is not bypassed on rescan.
1538
+ static func clearSavedPeripheral() {
1539
+ secureTrailerMemory.clear()
1540
+ UserDefaults.standard.removeObject(forKey: prefsDeviceName)
1541
+ UserDefaults.standard.removeObject(forKey: prefsPeripheralIds)
1542
+ }
1543
+
1549
1544
  func forget() {
1550
1545
  Bridge.log("LIVE: Forgetting Mentra Live glasses")
1551
- Self.secureTrailerMemory.clear()
1552
-
1553
- // Clear saved device name so the pairing filter is not bypassed on rescan
1554
- UserDefaults.standard.removeObject(forKey: PREFS_DEVICE_NAME)
1555
- UserDefaults.standard.removeObject(forKey: PREFS_PERIPHERAL_IDS)
1546
+ Self.clearSavedPeripheral()
1556
1547
  pairFlow("forget", "cleared_saved_peripheral")
1557
1548
 
1558
1549
  // Stop scanning first
@@ -1642,7 +1633,11 @@ class MentraLive: NSObject, SGCManager {
1642
1633
  private var fileWriteCharacteristic: CBCharacteristic?
1643
1634
  private var activeFileTransfers = [String: MentraLiveFileTransferSession]()
1644
1635
  private var blePhotoTransfers = [String: BlePhotoTransfer]()
1645
- private var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1636
+ private(set) var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
1637
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers, the
1638
+ // phone POST), so an unreleased name cannot be reused while its report is in flight.
1639
+ static let incidentRelayOwnershipSeconds: TimeInterval = 600
1640
+ var incidentRelayClock: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
1646
1641
  private var l2capFileChannel: MentraLiveL2capChannel?
1647
1642
  private var l2capFileChannelId: UUID?
1648
1643
  private var l2capFileChannelOpening = false
@@ -1685,8 +1680,10 @@ class MentraLive: NSObject, SGCManager {
1685
1680
  private let SIGNIFICANT_BLE_TRACE_QUEUE_SIZE = 5
1686
1681
 
1687
1682
  /// Device Settings Keys
1688
- private let PREFS_DEVICE_NAME = "MentraLiveLastConnectedDeviceName"
1689
- private let PREFS_PERIPHERAL_IDS = "MentraLivePeripheralIds"
1683
+ private static let prefsDeviceName = "MentraLiveLastConnectedDeviceName"
1684
+ private static let prefsPeripheralIds = "MentraLivePeripheralIds"
1685
+ private let PREFS_DEVICE_NAME = MentraLive.prefsDeviceName
1686
+ private let PREFS_PERIPHERAL_IDS = MentraLive.prefsPeripheralIds
1690
1687
 
1691
1688
  // MARK: - Properties
1692
1689
 
@@ -1811,6 +1808,13 @@ class MentraLive: NSObject, SGCManager {
1811
1808
  // the physical connection — so a first-seen sid after an upgrade OTA cannot be
1812
1809
  // mistaken for a fresh pairing just because a not-ready heartbeat slipped in first.
1813
1810
  private var readinessCompletedThisBleSession = false
1811
+ /// Readiness exchange the phone is waiting on. Every phone_ready carries it until the
1812
+ /// matching glasses_ready arrives, so retries and the copies the BES buffers while the
1813
+ /// glasses boot are one exchange: the glasses reset their transport once for it and answer
1814
+ /// later copies without resetting. Both exchange fields are scoped to the BLE session.
1815
+ private var pendingReadyId: String?
1816
+ /// `sid` of the glasses process whose glasses_ready this BLE session last handled.
1817
+ private var readyGlassesSessionId: String?
1814
1818
  private var globalMessageId = 0
1815
1819
  private var lastReceivedMessageId = 0
1816
1820
  private var bleWriteTraceSequence = 0
@@ -2756,6 +2760,18 @@ class MentraLive: NSObject, SGCManager {
2756
2760
  }
2757
2761
 
2758
2762
  var count: Int { commands.count }
2763
+
2764
+ /// Discards the run of writes from earlier wire-session generations at the head of
2765
+ /// the queue in one pass and dequeues the first current one. Stale writes are never
2766
+ /// sent, so they must not each cost a drain tick: a burst of epoch resets would
2767
+ /// otherwise park every current write behind seconds of dead entries.
2768
+ func dequeue(currentGeneration: Int) -> (command: PendingMessage?, staleIds: [String]) {
2769
+ let firstCurrent = commands.firstIndex { $0.generation == currentGeneration } ?? commands.endIndex
2770
+ let staleIds = commands[..<firstCurrent].map(\.id)
2771
+ commands.removeSubrange(..<firstCurrent)
2772
+ return (commands.isEmpty ? nil : commands.removeFirst(), staleIds)
2773
+ }
2774
+
2759
2775
  func removeAll() {
2760
2776
  commands.removeAll()
2761
2777
  }
@@ -2768,21 +2784,25 @@ class MentraLive: NSObject, SGCManager {
2768
2784
  guard let self else { return }
2769
2785
  while true {
2770
2786
  let pendingIsNil = await MainActor.run { self.pending == nil }
2771
- if pendingIsNil {
2772
- if let command = await self.commandQueue.dequeue() {
2773
- let currentGeneration = await MainActor.run { self.wireSessionGeneration }
2774
- if command.generation != currentGeneration {
2775
- Bridge.log("LIVE: Dropping stale queued write from a previous session epoch (id: \(command.id))")
2776
- } else {
2777
- await self.processSendQueue(command)
2778
- }
2779
- }
2787
+ if pendingIsNil, let command = await self.dequeueCurrentGenerationWrite() {
2788
+ await self.processSendQueue(command)
2780
2789
  }
2781
2790
  try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
2782
2791
  }
2783
2792
  }
2784
2793
  }
2785
2794
 
2795
+ private func dequeueCurrentGenerationWrite() -> PendingMessage? {
2796
+ let next = commandQueue.dequeue(currentGeneration: wireSessionGeneration)
2797
+ if !next.staleIds.isEmpty {
2798
+ Bridge.log(
2799
+ "LIVE: Dropping \(next.staleIds.count) stale queued write(s) from a previous session epoch " +
2800
+ "(ids: \(next.staleIds.joined(separator: ", ")))"
2801
+ )
2802
+ }
2803
+ return next.command
2804
+ }
2805
+
2786
2806
  private func processSendQueue(_ message: PendingMessage) async {
2787
2807
  guard let peripheral = connectedPeripheral,
2788
2808
  let txChar = txCharacteristic
@@ -2889,7 +2909,7 @@ class MentraLive: NSObject, SGCManager {
2889
2909
 
2890
2910
  // The choose-glasses scan has to hear a later advertisement when the glasses
2891
2911
  // enter pairing mode. iOS reports each peripheral once unless duplicates are
2892
- // allowed, so the row would stay "Not in pairing mode". Reconnect scans stay
2912
+ // allowed, so the glasses would stay off the list. Reconnect scans stay
2893
2913
  // duplicate-free so a saved glasses advertisement cannot start another connect.
2894
2914
  let scanOptions: [String: Any] = [
2895
2915
  CBCentralManagerScanOptionAllowDuplicatesKey: manualDiscoveryActive,
@@ -3376,6 +3396,11 @@ class MentraLive: NSObject, SGCManager {
3376
3396
  }
3377
3397
 
3378
3398
  switch type {
3399
+ case "hotspot_keepalive":
3400
+ // Sent every few seconds while the glasses hotspot is up. Receiving it is the whole
3401
+ // point: each BLE notification lets iOS run this app a little longer, so a gallery or
3402
+ // OTA download over the hotspot keeps going while backgrounded or locked.
3403
+ return
3379
3404
  case "glasses_ready":
3380
3405
  // A queued glasses_ready from the connection just left for a pairing window
3381
3406
  // must not count as a session. Only accept readiness on a live GATT.
@@ -3383,6 +3408,16 @@ class MentraLive: NSObject, SGCManager {
3383
3408
  Bridge.log("LIVE: Ignoring stale glasses_ready during pairing pause")
3384
3409
  return
3385
3410
  }
3411
+ let sid = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3412
+ let readyId = (json["readyId"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3413
+ if let readyId, isRepeatedGlassesReady(readyId: readyId, sid: sid) {
3414
+ Bridge.log("LIVE: Ignoring repeated glasses_ready for readiness exchange \(readyId) - the glasses did not reset for it")
3415
+ return
3416
+ }
3417
+ if readyId != nil, readyId == pendingReadyId {
3418
+ pendingReadyId = nil
3419
+ }
3420
+ readyGlassesSessionId = sid
3386
3421
  // glasses_ready is a REMOTE wire-session reset: the glasses ran
3387
3422
  // onTransportReset() before sending it, so their side is back on legacy
3388
3423
  // framing regardless of what this side negotiated earlier. Start a fresh
@@ -3394,7 +3429,7 @@ class MentraLive: NSObject, SGCManager {
3394
3429
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
3395
3430
  // already runs this full remote-reset flow, so recording (not re-triggering)
3396
3431
  // is correct here; version_info detection covers the restart case.
3397
- glassesSessionId = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
3432
+ glassesSessionId = sid
3398
3433
  streamControlVersion = json["streamControlVersion"] as? Int ?? 0
3399
3434
  Bridge.sendTypedMessage(
3400
3435
  "wifi_protocol_session_ready",
@@ -3730,6 +3765,11 @@ class MentraLive: NSObject, SGCManager {
3730
3765
  Bridge.log("LIVE: 📱 Received ota_start_ack from glasses")
3731
3766
  Bridge.sendOtaStartAck()
3732
3767
 
3768
+ case "bes_crash_detected", "bes_crash_reported_ack":
3769
+ let ok = json["ok"].map { "\($0)" } ?? "-"
3770
+ Bridge.log("LIVE: \(type) incidentKey=\(json["incidentKey"] as? String ?? "") state=\(json["state"] as? String ?? "-") ok=\(ok)")
3771
+ Bridge.sendTypedMessage(type, body: json)
3772
+
3733
3773
  case "ota_status":
3734
3774
  // Short keys (sid/ts/cs/st/sq/sp/op/err) are used by new firmware to keep BLE payload small.
3735
3775
  // Verbose keys (session_id/total_steps/…) are the fallback for older firmware.
@@ -4054,12 +4094,7 @@ class MentraLive: NSObject, SGCManager {
4054
4094
  // This prevents re-initialization on every heartbeat after initial connection
4055
4095
  // The ready flag is reset on disconnect/reconnect, so this won't prevent proper reconnection
4056
4096
  if !fullyBooted {
4057
- let readyMsg: [String: Any] = [
4058
- "type": "phone_ready",
4059
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
4060
- ]
4061
- // Send it through our data channel
4062
- sendJson(readyMsg, wakeUp: true)
4097
+ sendPhoneReady(reason: "SOC ready")
4063
4098
  }
4064
4099
  }
4065
4100
  }
@@ -4476,12 +4511,14 @@ class MentraLive: NSObject, SGCManager {
4476
4511
  }
4477
4512
  let bKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "B")
4478
4513
  let lKey = MentraLive.incidentBleFileBase(incidentId: incidentId, prefix: "L")
4479
- bleIncidentLogRelays[bKey] = BleIncidentLogRelayEntry(
4480
- fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware
4514
+ let now = incidentRelayClock()
4515
+ let bRelay = BleIncidentLogRelayEntry(
4516
+ fileBaseKey: bKey, incidentId: incidentId, apiBaseUrl: base, kind: .firmware, reservedAt: now
4481
4517
  )
4482
- bleIncidentLogRelays[lKey] = BleIncidentLogRelayEntry(
4483
- fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
4518
+ let lRelay = BleIncidentLogRelayEntry(
4519
+ fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat, reservedAt: now
4484
4520
  )
4521
+ try reserveIncidentRelays([bRelay, lRelay], now: now)
4485
4522
 
4486
4523
  let auth: [String: Any] = [
4487
4524
  "type": "auth_token", "coreToken": coreToken,
@@ -4492,13 +4529,56 @@ class MentraLive: NSObject, SGCManager {
4492
4529
  sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
4493
4530
  wakeUp: true, requireAck: true, bridgeLogging: true)
4494
4531
  else {
4495
- bleIncidentLogRelays.removeValue(forKey: bKey)
4496
- bleIncidentLogRelays.removeValue(forKey: lKey)
4532
+ releaseIncidentRelay(bRelay)
4533
+ releaseIncidentRelay(lRelay)
4497
4534
  throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
4498
4535
  }
4499
4536
  Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
4500
4537
  }
4501
4538
 
4539
+ /// The 16-character relay file names keep only 15 characters of the report id, so two reports
4540
+ /// can share them. A received file goes to the report registered under its name; refuse a
4541
+ /// second report until the owner's Cloud POST is confirmed or its ownership expires.
4542
+ private func reserveIncidentRelays(_ relays: [BleIncidentLogRelayEntry], now: TimeInterval) throws {
4543
+ for relay in relays {
4544
+ if let owner = bleIncidentLogRelays[relay.fileBaseKey],
4545
+ owner.incidentId != relay.incidentId,
4546
+ now - owner.reservedAt < MentraLive.incidentRelayOwnershipSeconds
4547
+ {
4548
+ throw BluetoothSdkError(
4549
+ code: "incident_relay_busy",
4550
+ message: "BLE relay \(relay.fileBaseKey) is still owned by report \(owner.incidentId)."
4551
+ )
4552
+ }
4553
+ }
4554
+ for relay in relays {
4555
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
4556
+ }
4557
+ }
4558
+
4559
+ private func releaseIncidentRelay(_ relay: BleIncidentLogRelayEntry) {
4560
+ if bleIncidentLogRelays[relay.fileBaseKey] === relay {
4561
+ bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
4562
+ }
4563
+ }
4564
+
4565
+ func sendBesCrashReported(incidentKey: String, reportId: String) throws {
4566
+ guard incidentLogTransportReady else {
4567
+ throw BluetoothSdkError(code: "glasses_not_connected", message: "Cannot report the BES crash because the glasses BLE link is not ready.")
4568
+ }
4569
+ guard sendJson(["type": "bes_crash_reported", "incidentKey": incidentKey, "reportId": reportId],
4570
+ wakeUp: true, requireAck: true, bridgeLogging: true)
4571
+ else {
4572
+ throw BluetoothSdkError(code: "bes_crash_dispatch_failed", message: "Could not queue bes_crash_reported to the glasses.")
4573
+ }
4574
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=\(incidentKey) reportId=\(reportId)")
4575
+ }
4576
+
4577
+ static func isIncidentRelayFileName(_ fileName: String) -> Bool {
4578
+ guard fileName.count == 16, let first = fileName.first, first == "B" || first == "L" else { return false }
4579
+ return fileName.dropFirst().allSatisfy { ("a" ... "z").contains($0) || ("0" ... "9").contains($0) || $0 == "_" }
4580
+ }
4581
+
4502
4582
  private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
4503
4583
  var compact = incidentId.replacingOccurrences(of: "-", with: "").lowercased()
4504
4584
  if compact.count < 15 {
@@ -4670,6 +4750,20 @@ class MentraLive: NSObject, SGCManager {
4670
4750
 
4671
4751
  // MARK: - Message Handlers
4672
4752
 
4753
+ /// A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
4754
+ /// exchange the phone is waiting on, and any answer from a glasses process other than the
4755
+ /// one this link last handled (an asg restart resets for every exchange it first sees),
4756
+ /// followed a transport reset. Any other answer repeats an exchange that process already
4757
+ /// reset for, or one superseded by the pending exchange, whose answer is still to come.
4758
+ private func isRepeatedGlassesReady(readyId: String, sid: String?) -> Bool {
4759
+ readyId != pendingReadyId && sid == readyGlassesSessionId
4760
+ }
4761
+
4762
+ private func resetReadinessExchange() {
4763
+ pendingReadyId = nil
4764
+ readyGlassesSessionId = nil
4765
+ }
4766
+
4673
4767
  private func handleGlassesReady() {
4674
4768
  pairFlow(
4675
4769
  "glasses_ready",
@@ -5312,6 +5406,15 @@ class MentraLive: NSObject, SGCManager {
5312
5406
  if sess.isComplete {
5313
5407
  Bridge.log("LIVE: 📦 File transfer complete: \(packetInfo.fileName)")
5314
5408
 
5409
+ if Self.isIncidentRelayFileName(packetInfo.fileName) {
5410
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
5411
+ // Cloud, so success would make the glasses mark the incident uploaded.
5412
+ Bridge.log("LIVE: Incident log relay without a registered report: \(packetInfo.fileName)")
5413
+ sendTransferCompleteConfirmation(fileName: packetInfo.fileName, success: false)
5414
+ activeFileTransfers.removeValue(forKey: packetInfo.fileName)
5415
+ return
5416
+ }
5417
+
5315
5418
  if let fileData = sess.assembleFile() {
5316
5419
  saveReceivedFile(
5317
5420
  fileName: packetInfo.fileName, fileData: fileData,
@@ -5413,7 +5516,7 @@ class MentraLive: NSObject, SGCManager {
5413
5516
  ]
5414
5517
  }
5415
5518
 
5416
- private func uploadBleIncidentLogRelay(
5519
+ func uploadBleIncidentLogRelay(
5417
5520
  relay: BleIncidentLogRelayEntry, fileName: String, data: Data
5418
5521
  ) {
5419
5522
  let token = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
@@ -5464,14 +5567,24 @@ class MentraLive: NSObject, SGCManager {
5464
5567
  statusCode = nil
5465
5568
  }
5466
5569
  DispatchQueue.main.async {
5570
+ // A different report now owns this name (it was admitted after our owner finished),
5571
+ // so a completion here would mark ITS file done. Drop the stale callback.
5572
+ if let owner = self.bleIncidentLogRelays[relay.fileBaseKey], owner.incidentId != relay.incidentId {
5573
+ Bridge.log("LIVE: Dropping stale incident relay callback for \(relay.fileBaseKey)")
5574
+ return
5575
+ }
5467
5576
  if ok {
5468
5577
  Bridge.log("LIVE: ✅ Incident log BLE relay uploaded (\(relay.kind))")
5469
- self.bleIncidentLogRelays.removeValue(forKey: relay.fileBaseKey)
5470
5578
  } else if let existing = self.bleIncidentLogRelays[relay.fileBaseKey] {
5471
5579
  // Keep relay entry for glasses retry after transfer_complete:false.
5472
5580
  existing.session = nil
5473
5581
  }
5474
5582
  self.sendTransferCompleteConfirmation(fileName: fileName, success: ok)
5583
+ // Release only after the glasses' confirmation is queued, so a report that reuses
5584
+ // this name is ordered behind the owner's completion.
5585
+ if ok {
5586
+ self.releaseIncidentRelay(relay)
5587
+ }
5475
5588
  }
5476
5589
  }.resume()
5477
5590
  }
@@ -5899,7 +6012,8 @@ class MentraLive: NSObject, SGCManager {
5899
6012
  wireBytes: data.count,
5900
6013
  packetCount: Int(info.fragCount),
5901
6014
  protocolVersion: BleWireProtocol.protocolV2,
5902
- direction: "glasses_to_phone"
6015
+ direction: "glasses_to_phone",
6016
+ bridgeLogging: !BleTraceLogger.isQuietJson(jsonString)
5903
6017
  )
5904
6018
  processJsonMessage(jsonString)
5905
6019
  }
@@ -6674,12 +6788,13 @@ class MentraLive: NSObject, SGCManager {
6674
6788
  )
6675
6789
  // requestReadyK900()
6676
6790
 
6677
- let readyMsg: [String: Any] = [
6678
- "type": "phone_ready",
6679
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
6680
- ]
6681
- // Send it through our data channel
6682
- sendJson(readyMsg, wakeUp: true)
6791
+ // The timer fires on bluetoothQueue; the pending readiness exchange is main-actor state.
6792
+ // A tick queued just before glasses_ready stopped the loop must not start a new exchange.
6793
+ let check = self.readinessCheckCounter
6794
+ DispatchQueue.main.async { [weak self] in
6795
+ guard let self, self.readinessCheckDispatchTimer != nil else { return }
6796
+ self.sendPhoneReady(reason: "readiness check #\(check)")
6797
+ }
6683
6798
  }
6684
6799
 
6685
6800
  readinessCheckDispatchTimer!.resume()
@@ -6816,6 +6931,14 @@ class MentraLive: NSObject, SGCManager {
6816
6931
  return true
6817
6932
  }
6818
6933
 
6934
+ /// Drops glasses that are not in pairing mode from the search results, once per change, so the
6935
+ /// next pairable advertisement lists them again.
6936
+ private func unlistNotPairable(_ name: String) {
6937
+ if cacheAdvPairing(name, pairingMode: false, pairingCode: nil, securePairingCapable: true) {
6938
+ Bridge.removeDiscoveredDevice("Mentra Live", name)
6939
+ }
6940
+ }
6941
+
6819
6942
  private func emitDiscoveredDeviceFromCache(
6820
6943
  _ name: String,
6821
6944
  identifier: String = "",
@@ -6959,6 +7082,7 @@ class MentraLive: NSObject, SGCManager {
6959
7082
  // Stop all timers
6960
7083
  stopAllTimers()
6961
7084
  resetWireNegotiationState()
7085
+ resetReadinessExchange()
6962
7086
  commandQueue.removeAll() // stale writes die with the session
6963
7087
  closeL2capFileChannel()
6964
7088
 
@@ -7174,11 +7298,16 @@ extension MentraLive {
7174
7298
 
7175
7299
  /// Sends phone_ready to (re)start the glasses-driven readiness flow.
7176
7300
  private func sendPhoneReady(reason: String) {
7301
+ let readyId = pendingReadyId ?? UUID().uuidString
7302
+ pendingReadyId = readyId
7177
7303
  pairFlow("phone_ready", "reason=\(reason) gatt=\(txCharacteristic != nil) id=\(connectedPeripheral?.identifier.uuidString ?? "-")")
7178
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses (\(reason)) - waiting for glasses_ready response")
7304
+ Bridge.log(
7305
+ "LIVE: 📱 Sending phone_ready to glasses (\(reason), exchange \(readyId)) - waiting for glasses_ready response"
7306
+ )
7179
7307
  let readyMsg: [String: Any] = [
7180
7308
  "type": "phone_ready",
7181
7309
  "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
7310
+ "readyId": readyId,
7182
7311
  ]
7183
7312
  sendJson(readyMsg, wakeUp: true)
7184
7313
  }