@mentra/bluetooth-sdk 3.3.0-dev.944 → 3.4.0-beta.1237

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 (174) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +111 -11
  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/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +89 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +159 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +35 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +1002 -157
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  44. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  62. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  67. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  68. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  69. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  70. package/build/BluetoothSdk.types.d.ts +207 -2
  71. package/build/BluetoothSdk.types.d.ts.map +1 -1
  72. package/build/BluetoothSdk.types.js.map +1 -1
  73. package/build/_private/BluetoothSdkModule.d.ts +45 -6
  74. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  75. package/build/_private/BluetoothSdkModule.js +2 -0
  76. package/build/_private/BluetoothSdkModule.js.map +1 -1
  77. package/build/generated/changelogCatalog.d.ts +4 -1
  78. package/build/generated/changelogCatalog.d.ts.map +1 -1
  79. package/build/generated/changelogCatalog.js +5 -1
  80. package/build/generated/changelogCatalog.js.map +1 -1
  81. package/build/generated/releaseMetadata.js +6 -6
  82. package/build/generated/releaseMetadata.js.map +1 -1
  83. package/build/index.d.ts +1 -1
  84. package/build/index.d.ts.map +1 -1
  85. package/build/index.js +10 -0
  86. package/build/index.js.map +1 -1
  87. package/ios/BluetoothSdkModule.swift +84 -12
  88. package/ios/MentraBluetoothSDK.podspec +4 -0
  89. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  90. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  91. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  92. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  93. package/ios/Source/Bridge.swift +11 -3
  94. package/ios/Source/DeviceManager.swift +135 -18
  95. package/ios/Source/DeviceStore.swift +27 -0
  96. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  97. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  98. package/ios/Source/MentraBluetoothSDK.swift +51 -5
  99. package/ios/Source/TouchGesture.swift +13 -0
  100. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  101. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  102. package/ios/Source/audio/SpeechActivity.swift +277 -0
  103. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  104. package/ios/Source/events/BluetoothEvents.swift +45 -0
  105. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  106. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  107. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  108. package/ios/Source/sgcs/MentraLive.swift +1366 -212
  109. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  110. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  111. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  112. package/ios/Source/sgcs/Nimo.swift +10 -3
  113. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  114. package/ios/Source/sgcs/SGCManager.swift +13 -0
  115. package/ios/Source/sgcs/Simulated.swift +2 -0
  116. package/ios/Source/status/DeviceStatus.swift +35 -0
  117. package/ios/Source/stt/STTTools.swift +13 -31
  118. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  119. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  120. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  121. package/ios/Source/types/DeviceModels.swift +8 -1
  122. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  123. package/ios/Source/utils/BoundedWait.swift +44 -0
  124. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  125. package/ios/Source/utils/SttModelTraits.swift +62 -0
  126. package/ios/Tests/BesCrashReportTests.swift +142 -0
  127. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  128. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  129. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  130. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  131. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  132. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  133. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  134. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  135. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  136. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  137. package/ios/Tests/MentraLiveSessionReadinessTests.swift +497 -26
  138. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  139. package/ios/Tests/PcmStreamTests.swift +299 -0
  140. package/ios/Tests/SpeechActivityTests.swift +238 -0
  141. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  142. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  143. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  144. package/package.json +3 -2
  145. package/plugin/build/withAndroid.js +9 -11
  146. package/plugin/build/withKotlinVersion.d.ts +2 -0
  147. package/plugin/build/withKotlinVersion.js +46 -0
  148. package/src/BluetoothSdk.types.ts +216 -1
  149. package/src/_private/BluetoothSdkModule.ts +49 -5
  150. package/src/generated/changelogCatalog.ts +5 -1
  151. package/src/generated/releaseMetadata.ts +6 -6
  152. package/src/index.ts +24 -0
  153. package/android/silero/LICENSE.md +0 -17
  154. package/android/silero/build.gradle +0 -50
  155. package/android/silero/proguard-rules.pro +0 -24
  156. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  157. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  159. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  160. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  161. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  162. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  163. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  164. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  165. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  166. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  167. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  168. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  169. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  170. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  171. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  172. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  173. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  174. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -16,6 +16,41 @@ private final class IncidentLogTransport: MentraLive {
16
16
  }
17
17
  }
18
18
 
19
+ /// Stands in for Cloud so the tests observe the report each relayed file is posted to.
20
+ private final class CloudStub: URLProtocol {
21
+ nonisolated(unsafe) static var status = 200
22
+ nonisolated(unsafe) static var requests: [String] = []
23
+
24
+ override class func canInit(with request: URLRequest) -> Bool {
25
+ request.url?.host == "cloud-stub.invalid"
26
+ }
27
+
28
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest {
29
+ request
30
+ }
31
+
32
+ override func startLoading() {
33
+ var body = request.httpBody ?? Data()
34
+ if body.isEmpty, let stream = request.httpBodyStream {
35
+ stream.open()
36
+ var buffer = [UInt8](repeating: 0, count: 4096)
37
+ while stream.hasBytesAvailable {
38
+ let count = stream.read(&buffer, maxLength: buffer.count)
39
+ if count <= 0 { break }
40
+ body.append(buffer, count: count)
41
+ }
42
+ stream.close()
43
+ }
44
+ let path = request.url?.path ?? ""
45
+ DispatchQueue.main.sync { CloudStub.requests.append("\(path) \(String(decoding: body, as: UTF8.self))") }
46
+ let response = HTTPURLResponse(url: request.url!, statusCode: CloudStub.status, httpVersion: nil, headerFields: nil)!
47
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
48
+ client?.urlProtocolDidFinishLoading(self)
49
+ }
50
+
51
+ override func stopLoading() {}
52
+ }
53
+
19
54
  @MainActor
20
55
  final class IncidentLogDispatchTests: XCTestCase {
21
56
  private let incident = "rep_01M4HBVT88DFSN8TYNZ1WTV4PB"
@@ -98,6 +133,129 @@ final class IncidentLogDispatchTests: XCTestCase {
98
133
  XCTAssertNil(queue.dequeue())
99
134
  }
100
135
 
136
+ func testCollidingReportWaitsForOwnerCloudConfirmationAndNeverReceivesItsEvidence() async throws {
137
+ try await withCloud(status: 200) {
138
+ let live = IncidentLogTransport()
139
+ let name = "Brep_01m4hbvt88d"
140
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
141
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
142
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
143
+ }
144
+ XCTAssertFalse(wire(live).contains(collidingIncident))
145
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
146
+ XCTAssertEqual(live.bleIncidentLogRelays["Lrep_01m4hbvt88d"]?.incidentId, incident)
147
+
148
+ let logcat = "Lrep_01m4hbvt88d"
149
+ try await receive(live, name, "owner")
150
+ XCTAssertEqual(CloudStub.requests, ["/api/client/reports/\(incident)/artifacts owner"])
151
+ let confirmation = try XCTUnwrap(sentMessages(live).last { $0.contains("transfer_complete") })
152
+ XCTAssertTrue(confirmation.contains(name) && confirmation.contains("\"success\":true"))
153
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
154
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
155
+ }
156
+ try await receive(live, logcat, "owner-logcat")
157
+
158
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
159
+ try await receive(live, name, "second")
160
+ XCTAssertEqual(CloudStub.requests.last, "/api/client/reports/\(collidingIncident)/artifacts second")
161
+ }
162
+ }
163
+
164
+ func testStaleCallbackOfFinishedOwnerCannotConfirmCollidingReportsFile() async throws {
165
+ try await withCloud(status: 200) {
166
+ let live = IncidentLogTransport()
167
+ let name = "Brep_01m4hbvt88d"
168
+ let logcat = "Lrep_01m4hbvt88d"
169
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
170
+ let staleRelay = try XCTUnwrap(live.bleIncidentLogRelays[name])
171
+ try await receive(live, name, "owner")
172
+ try await receive(live, logcat, "owner-logcat")
173
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
174
+ let confirmationsBefore = sentMessages(live).filter { $0.contains("transfer_complete") }.count
175
+ let requestsBefore = CloudStub.requests.count
176
+
177
+ // A late callback of the first report's request arrives while the colliding report owns the name.
178
+ live.uploadBleIncidentLogRelay(relay: staleRelay, fileName: name, data: Data("late".utf8))
179
+ try await waitFor { CloudStub.requests.count == requestsBefore + 1 }
180
+ try await Task.sleep(nanoseconds: 300_000_000)
181
+
182
+ XCTAssertEqual(sentMessages(live).filter { $0.contains("transfer_complete") }.count, confirmationsBefore)
183
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
184
+ }
185
+ }
186
+
187
+ func testFailedCloudPostKeepsOwnerUntilOwnershipExpires() async throws {
188
+ try await withCloud(status: 500) {
189
+ let live = IncidentLogTransport()
190
+ var now: TimeInterval = 1000
191
+ live.incidentRelayClock = { now }
192
+ let name = "Brep_01m4hbvt88d"
193
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
194
+ live.uploadBleIncidentLogRelay(
195
+ relay: try XCTUnwrap(live.bleIncidentLogRelays[name]), fileName: name, data: Data("owner".utf8)
196
+ )
197
+ try await waitFor { wire(live).contains("transfer_complete") }
198
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
199
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
200
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
201
+ }
202
+
203
+ now += MentraLive.incidentRelayOwnershipSeconds
204
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
205
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
206
+ }
207
+ }
208
+
209
+ func testDispatchFailureOfRefusedReportCannotReleaseOwner() throws {
210
+ try withToken("synthetic") {
211
+ let live = IncidentLogTransport()
212
+ try live.sendIncidentId(incident, apiBaseUrl: apiBase)
213
+ live.ready = false
214
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: apiBase))
215
+ XCTAssertEqual(live.bleIncidentLogRelays["Brep_01m4hbvt88d"]?.incidentId, incident)
216
+ }
217
+ }
218
+
219
+ private let collidingIncident = "rep_01M4HBVT88DZZZZZZZZZZZZZZZ"
220
+ private let cloudBase = "https://cloud-stub.invalid"
221
+
222
+ /// Each message is wrapped as {"C":"<escaped json>"}; unescape so assertions read the message.
223
+ private func sentMessages(_ live: IncidentLogTransport) -> [String] {
224
+ live.writes.map { String(decoding: $0.0, as: UTF8.self).replacingOccurrences(of: "\\\"", with: "\"") }
225
+ }
226
+
227
+ private func wire(_ live: IncidentLogTransport) -> String {
228
+ sentMessages(live).joined()
229
+ }
230
+
231
+ private func withCloud(status: Int, body: () async throws -> Void) async throws {
232
+ CloudStub.status = status
233
+ CloudStub.requests = []
234
+ URLProtocol.registerClass(CloudStub.self)
235
+ defer { URLProtocol.unregisterClass(CloudStub.self) }
236
+ let store = DeviceStore.shared.store
237
+ let saved = store.getCategory("bluetooth")["core_token"]
238
+ store.set("bluetooth", "core_token", "synthetic")
239
+ defer {
240
+ if let saved { store.set("bluetooth", "core_token", saved) }
241
+ else { store.remove("bluetooth", "core_token") }
242
+ }
243
+ try await body()
244
+ }
245
+
246
+ private func receive(_ live: IncidentLogTransport, _ name: String, _ payload: String) async throws {
247
+ let relay = try XCTUnwrap(live.bleIncidentLogRelays[name])
248
+ live.uploadBleIncidentLogRelay(relay: relay, fileName: name, data: Data(payload.utf8))
249
+ try await waitFor { live.bleIncidentLogRelays[name] !== relay }
250
+ }
251
+
252
+ private func waitFor(_ condition: () -> Bool) async throws {
253
+ for _ in 0 ..< 500 where !condition() {
254
+ try await Task.sleep(nanoseconds: 10_000_000)
255
+ }
256
+ XCTAssertTrue(condition())
257
+ }
258
+
101
259
  private func withToken<T>(_ value: String, body: () throws -> T) rethrows -> T {
102
260
  let store = DeviceStore.shared.store
103
261
  let saved = store.getCategory("bluetooth")["core_token"]
@@ -0,0 +1,209 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ @MainActor
5
+ private final class AudioSetupTransport: MentraLive {
6
+ var commands: [[String: Any]] = []
7
+
8
+ override func sendJson(_ jsonOriginal: [String: Any], wakeUp _: Bool, requireAck _: Bool) {
9
+ commands.append(jsonOriginal)
10
+ }
11
+ }
12
+
13
+ /// `GlassesStatus.audioSetup` wiring: the Mentra Live driver on iOS and the shared default for
14
+ /// every other model.
15
+ @MainActor
16
+ final class MentraLiveAudioSetupTests: XCTestCase {
17
+ private let phoneAudioKeys = ["bluetoothClassicConnected", "bluetoothClassicProfilesConnected", "bluetoothAudioRouted"]
18
+
19
+ private func withTransport(
20
+ _ body: (AudioSetupTransport, ObservableStore, _ clock: (Int) -> Void) throws -> Void
21
+ ) rethrows {
22
+ let store = DeviceStore.shared.store
23
+ let saved = ["bluetooth", "glasses"].map { ($0, store.getCategory($0)) }
24
+ let previous = DeviceManager.shared.sgc
25
+ UserDefaults.standard.removeObject(forKey: MentraLivePairingStateStore.defaultsKey)
26
+ MentraLivePairingStateStore.shared.resetForTest()
27
+ store.set("glasses", "fullyBooted", false)
28
+ for key in phoneAudioKeys {
29
+ store.set("glasses", key, false)
30
+ }
31
+ store.set("bluetooth", "pending_device_name", "")
32
+ store.set("bluetooth", "pending_device_address", "")
33
+ store.set("bluetooth", "pending_device_secure_pairing_capable", "")
34
+ store.set("glasses", "audioSetup", GlassesAudioSetupState.idle.toMap())
35
+ let transport = AudioSetupTransport()
36
+ DeviceManager.shared.sgc = transport
37
+ var nowMs = 1_000_000
38
+ transport.audioSetupNowMs = { nowMs }
39
+ defer {
40
+ transport.cleanup()
41
+ DeviceManager.shared.sgc = previous
42
+ UserDefaults.standard.removeObject(forKey: MentraLivePairingStateStore.defaultsKey)
43
+ MentraLivePairingStateStore.shared.resetForTest()
44
+ for (category, values) in saved {
45
+ for key in store.getCategory(category).keys where values[key] == nil {
46
+ store.remove(category, key)
47
+ }
48
+ for (key, value) in values {
49
+ store.set(category, key, value)
50
+ }
51
+ }
52
+ }
53
+ try body(transport, store) { nowMs = $0 }
54
+ }
55
+
56
+ private func receive(_ transport: MentraLive, _ value: [String: Any]) throws {
57
+ try transport.processReceivedData(JSONSerialization.data(withJSONObject: value))
58
+ }
59
+
60
+ private func audioSetup(_ store: ObservableStore) -> GlassesAudioSetupState? {
61
+ GlassesAudioSetupState(map: store.get("glasses", "audioSetup"))
62
+ }
63
+
64
+ /// The audioSetup visible at the moment `fullyBooted` flips to true.
65
+ private func audioSetupWhenReady(_ store: ObservableStore, _ action: () throws -> Void) rethrows -> GlassesAudioSetupState? {
66
+ var seen: GlassesAudioSetupState?
67
+ let listener = store.addListener { category, changes in
68
+ guard category == "glasses", changes["fullyBooted"] as? Bool == true else { return }
69
+ seen = GlassesAudioSetupState(map: store.get("glasses", "audioSetup"))
70
+ }
71
+ defer { store.removeListener(listener) }
72
+ try action()
73
+ return seen
74
+ }
75
+
76
+ func testAReconnectReportsConnectingWithReadinessThenFollowsTheGlassesReport() throws {
77
+ try withTransport { transport, store, clock in
78
+ var events: [[String: Any]] = []
79
+ let sink = Bridge.addEventSink { event, body in
80
+ if event == "audio_setup_changed", let state = body["state"] as? [String: Any] { events.append(state) }
81
+ }
82
+ defer { Bridge.removeEventSink(sink) }
83
+
84
+ clock(1_000_000)
85
+ let atReady = try audioSetupWhenReady(store) {
86
+ try receive(transport, ["type": "glasses_ready", "sid": "reconnect"])
87
+ }
88
+ XCTAssertEqual(atReady, .connecting, "the ready update never carries a stale idle")
89
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "connecting"])
90
+
91
+ clock(1_002_000)
92
+ try receive(transport, ["type": "classic_link", "a2dp": true, "hfp": false])
93
+ XCTAssertEqual(audioSetup(store), .connected)
94
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "connected"])
95
+ let eventCount = events.count
96
+
97
+ // The same report again is not a change.
98
+ try receive(transport, ["type": "classic_link", "a2dp": true, "hfp": false])
99
+ XCTAssertEqual(events.count, eventCount)
100
+
101
+ // Audio lost after connected: this firmware reconnects its owner's audio itself, so
102
+ // the SDK keeps waiting and never asks the user to pair in Settings.
103
+ clock(1_060_000)
104
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
105
+ XCTAssertEqual(audioSetup(store), .connecting)
106
+ clock(1_070_000)
107
+ let deadline = Date().addingTimeInterval(0.2)
108
+ while Date() < deadline {
109
+ RunLoop.main.run(until: Date().addingTimeInterval(0.01))
110
+ }
111
+ XCTAssertEqual(audioSetup(store), .connecting)
112
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "connecting"])
113
+
114
+ // The phone's own signals are enough on their own.
115
+ store.set("glasses", "bluetoothAudioRouted", true)
116
+ XCTAssertEqual(audioSetup(store), .connected)
117
+
118
+ // Session drop.
119
+ transport.cleanup()
120
+ XCTAssertEqual(audioSetup(store), .idle)
121
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "idle"])
122
+ }
123
+ }
124
+
125
+ func testAnExplicitPairOnOldFirmwareNeedsTheUserInTheReadyUpdate() throws {
126
+ try withTransport { transport, store, _ in
127
+ store.set("bluetooth", "pending_device_name", "MENTRA_LIVE_BLE_ABCD")
128
+ store.set("bluetooth", "pending_device_secure_pairing_capable", false)
129
+ let atReady = try audioSetupWhenReady(store) {
130
+ try receive(transport, ["type": "glasses_ready", "sid": "legacy"])
131
+ }
132
+ XCTAssertEqual(atReady, .needsUserConnectInSettings)
133
+ XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
134
+
135
+ store.set("glasses", "bluetoothClassicConnected", true)
136
+ XCTAssertEqual(audioSetup(store), .connected)
137
+ }
138
+ }
139
+
140
+ func testAnExplicitSecurePairWithAutoAudioWaitsForAudio() throws {
141
+ try withTransport { transport, store, clock in
142
+ store.set("bluetooth", "pending_device_name", "MENTRA_LIVE_BLE_ABCD")
143
+ store.set("bluetooth", "pending_device_secure_pairing_capable", true)
144
+ clock(2_000_000)
145
+ try receive(transport, ["type": "glasses_ready", "sid": "secure"])
146
+ XCTAssertEqual(audioSetup(store), .idle, "not ready before the owner commit")
147
+ let atReady = try audioSetupWhenReady(store) {
148
+ try receive(transport, [
149
+ "type": "pairing_info", "secure_pairing_capable": true, "owner_committed": true,
150
+ "auto_audio": true, "protocol_version": 4,
151
+ ])
152
+ }
153
+ XCTAssertEqual(atReady, .connecting)
154
+ // A both-down report does not shorten the 8 s wait.
155
+ clock(2_001_000)
156
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
157
+ XCTAssertEqual(audioSetup(store), .connecting)
158
+ clock(2_008_000)
159
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
160
+ XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
161
+ }
162
+ }
163
+
164
+ func testReadinessLostIsIdle() throws {
165
+ try withTransport { transport, store, _ in
166
+ try receive(transport, ["type": "glasses_ready", "sid": "first"])
167
+ XCTAssertEqual(audioSetup(store), .connecting)
168
+ // sr_hrt ready=0 and ASG restarts clear readiness on a live link.
169
+ DeviceStore.shared.set("glasses", "fullyBooted", false)
170
+ XCTAssertEqual(audioSetup(store), .idle)
171
+ }
172
+ }
173
+
174
+ func testModelsWithoutADriverRuleAreNotApplicableInTheReadyUpdate() {
175
+ let store = DeviceStore.shared.store
176
+ let saved = store.getCategory("glasses")
177
+ let previous = DeviceManager.shared.sgc
178
+ DeviceManager.shared.sgc = nil
179
+ defer {
180
+ DeviceManager.shared.sgc = previous
181
+ for key in store.getCategory("glasses").keys where saved[key] == nil {
182
+ store.remove("glasses", key)
183
+ }
184
+ for (key, value) in saved {
185
+ store.set("glasses", key, value)
186
+ }
187
+ }
188
+ store.set("glasses", "fullyBooted", false)
189
+ store.set("glasses", "audioSetup", GlassesAudioSetupState.idle.toMap())
190
+ var events: [[String: Any]] = []
191
+ let sink = Bridge.addEventSink { event, body in
192
+ if event == "audio_setup_changed", let state = body["state"] as? [String: Any] { events.append(state) }
193
+ }
194
+ defer { Bridge.removeEventSink(sink) }
195
+
196
+ let atReady = audioSetupWhenReady(store) {
197
+ DeviceStore.shared.apply("glasses", "fullyBooted", true)
198
+ }
199
+ XCTAssertEqual(atReady, .notApplicable)
200
+ XCTAssertEqual(events as [NSDictionary], [["state": "not_applicable"]])
201
+ let snapshot = GlassesStatus(values: store.getCategory("glasses"))
202
+ XCTAssertEqual(snapshot.audioSetup as NSDictionary?, ["state": "not_applicable"])
203
+ XCTAssertEqual(snapshot.dictionary["audioSetup"] as? NSDictionary, ["state": "not_applicable"])
204
+
205
+ DeviceStore.shared.apply("glasses", "fullyBooted", false)
206
+ XCTAssertEqual(audioSetup(store), .idle)
207
+ XCTAssertEqual(events.count, 2)
208
+ }
209
+ }
@@ -0,0 +1,35 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ @MainActor
5
+ final class MentraLiveCommandQueueTests: XCTestCase {
6
+ func testStaleGenerationRunIsDiscardedInOnePassAheadOfTheCurrentWrite() {
7
+ let queue = MentraLive.CommandQueue()
8
+ for (id, generation) in [("1", 1), ("2", 1), ("3", 2), ("4", 3), ("5", 3)] {
9
+ _ = queue.enqueue(write(id, generation: generation))
10
+ }
11
+
12
+ let next = queue.dequeue(currentGeneration: 3)
13
+ XCTAssertEqual(next.command?.id, "4")
14
+ XCTAssertEqual(next.staleIds, ["1", "2", "3"])
15
+
16
+ let following = queue.dequeue(currentGeneration: 3)
17
+ XCTAssertEqual(following.command?.id, "5")
18
+ XCTAssertEqual(following.staleIds, [])
19
+ }
20
+
21
+ func testQueueOfOnlyStaleWritesDrainsToEmpty() {
22
+ let queue = MentraLive.CommandQueue()
23
+ _ = queue.enqueue(write("1", generation: 1))
24
+ _ = queue.enqueue(write("2", generation: 2))
25
+
26
+ let next = queue.dequeue(currentGeneration: 3)
27
+ XCTAssertNil(next.command)
28
+ XCTAssertEqual(next.staleIds, ["1", "2"])
29
+ XCTAssertNil(queue.dequeue())
30
+ }
31
+
32
+ private func write(_ id: String, generation: Int) -> MentraLive.PendingMessage {
33
+ MentraLive.PendingMessage(data: Data([1]), id: id, retries: 0, generation: generation)
34
+ }
35
+ }
@@ -11,20 +11,75 @@ final class MentraLiveConnectionOptionsTests: XCTestCase {
11
11
  XCTAssertFalse(ConnectOptions(requiresAncs: false).requiresAncs)
12
12
  }
13
13
 
14
+ func testConnectOptionsEnableTransportBridgingByDefault() {
15
+ XCTAssertTrue(ConnectOptions().enableTransportBridging)
16
+ }
17
+
18
+ func testConnectOptionsCanEnableTransportBridging() {
19
+ XCTAssertTrue(ConnectOptions(enableTransportBridging: true).enableTransportBridging)
20
+ }
21
+
14
22
  #if os(macOS)
15
23
  func testCoreBluetoothOptionsOmitAncsOnMacOS() {
16
24
  XCTAssertNil(MentraLiveConnectionOptions.coreBluetoothOptions(requiresAncs: true))
17
25
  }
26
+
27
+ func testCoreBluetoothOptionsOmitTransportBridgingOnMacOS() {
28
+ XCTAssertNil(MentraLiveConnectionOptions.coreBluetoothOptions(
29
+ requiresAncs: true,
30
+ enableTransportBridging: true
31
+ ))
32
+ }
18
33
  #else
19
34
  func testCoreBluetoothOptionsRequireAncsWhenEnabled() {
20
35
  let options = MentraLiveConnectionOptions.coreBluetoothOptions(requiresAncs: true)
21
36
 
37
+ XCTAssertEqual(options?.count, 1)
38
+ XCTAssertEqual(options?[CBConnectPeripheralOptionRequiresANCS] as? Bool, true)
39
+ XCTAssertNil(options?[CBConnectPeripheralOptionEnableTransportBridgingKey])
40
+ }
41
+
42
+ func testCoreBluetoothOptionsKeepAncsWhenTransportBridgingIsExplicitlyOff() {
43
+ let options = MentraLiveConnectionOptions.coreBluetoothOptions(
44
+ requiresAncs: true,
45
+ enableTransportBridging: false
46
+ )
47
+
22
48
  XCTAssertEqual(options?.count, 1)
23
49
  XCTAssertEqual(options?[CBConnectPeripheralOptionRequiresANCS] as? Bool, true)
24
50
  }
51
+
52
+ func testCoreBluetoothOptionsContainBothWhenAncsAndTransportBridgingAreEnabled() {
53
+ let options = MentraLiveConnectionOptions.coreBluetoothOptions(
54
+ requiresAncs: true,
55
+ enableTransportBridging: true
56
+ )
57
+
58
+ XCTAssertEqual(options?.count, 2)
59
+ XCTAssertEqual(options?[CBConnectPeripheralOptionRequiresANCS] as? Bool, true)
60
+ XCTAssertEqual(options?[CBConnectPeripheralOptionEnableTransportBridgingKey] as? Bool, true)
61
+ }
62
+
63
+ func testCoreBluetoothOptionsContainOnlyTransportBridgingWhenAncsIsDisabled() {
64
+ let options = MentraLiveConnectionOptions.coreBluetoothOptions(
65
+ requiresAncs: false,
66
+ enableTransportBridging: true
67
+ )
68
+
69
+ XCTAssertEqual(options?.count, 1)
70
+ XCTAssertEqual(options?[CBConnectPeripheralOptionEnableTransportBridgingKey] as? Bool, true)
71
+ XCTAssertNil(options?[CBConnectPeripheralOptionRequiresANCS])
72
+ }
25
73
  #endif
26
74
 
27
75
  func testCoreBluetoothOptionsAreOmittedWhenAncsIsDisabled() {
28
76
  XCTAssertNil(MentraLiveConnectionOptions.coreBluetoothOptions(requiresAncs: false))
29
77
  }
78
+
79
+ func testCoreBluetoothOptionsAreOmittedWhenNeitherOptionIsSet() {
80
+ XCTAssertNil(MentraLiveConnectionOptions.coreBluetoothOptions(
81
+ requiresAncs: false,
82
+ enableTransportBridging: false
83
+ ))
84
+ }
30
85
  }