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

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 (100) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +78 -0
  3. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +274 -0
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +13 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +8 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +79 -8
  7. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +22 -4
  11. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +832 -134
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +337 -39
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +8 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +1 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  25. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +16 -0
  26. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  30. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  37. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +564 -1
  38. package/build/BluetoothSdk.types.d.ts +110 -2
  39. package/build/BluetoothSdk.types.d.ts.map +1 -1
  40. package/build/BluetoothSdk.types.js.map +1 -1
  41. package/build/_private/BluetoothSdkModule.d.ts +6 -2
  42. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  43. package/build/_private/BluetoothSdkModule.js +1 -0
  44. package/build/_private/BluetoothSdkModule.js.map +1 -1
  45. package/build/generated/changelogCatalog.d.ts +3 -0
  46. package/build/generated/changelogCatalog.d.ts.map +1 -1
  47. package/build/generated/changelogCatalog.js +4 -0
  48. package/build/generated/changelogCatalog.js.map +1 -1
  49. package/build/generated/releaseMetadata.js +6 -6
  50. package/build/generated/releaseMetadata.js.map +1 -1
  51. package/build/index.d.ts +1 -1
  52. package/build/index.d.ts.map +1 -1
  53. package/build/index.js +4 -0
  54. package/build/index.js.map +1 -1
  55. package/ios/BluetoothSdkModule.swift +24 -4
  56. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  57. package/ios/Source/Bridge.swift +11 -3
  58. package/ios/Source/DeviceManager.swift +103 -7
  59. package/ios/Source/DeviceStore.swift +27 -0
  60. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  61. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  62. package/ios/Source/MentraBluetoothSDK.swift +41 -7
  63. package/ios/Source/TouchGesture.swift +13 -0
  64. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  65. package/ios/Source/events/BluetoothEvents.swift +4 -0
  66. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  67. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +181 -0
  68. package/ios/Source/sgcs/MentraLive.swift +1196 -173
  69. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  70. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  71. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  72. package/ios/Source/sgcs/Nimo.swift +278 -38
  73. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +77 -18
  74. package/ios/Source/sgcs/NimoCanvasSession.swift +1 -0
  75. package/ios/Source/sgcs/NimoMacResourceTransport.swift +217 -0
  76. package/ios/Source/sgcs/NimoResourceFixture.swift +384 -0
  77. package/ios/Source/sgcs/NimoResourceSession.swift +406 -0
  78. package/ios/Source/sgcs/SGCManager.swift +7 -0
  79. package/ios/Source/sgcs/Simulated.swift +2 -0
  80. package/ios/Source/status/DeviceStatus.swift +35 -0
  81. package/ios/Source/types/DeviceModels.swift +8 -1
  82. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  83. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  84. package/ios/Tests/DeviceManagerReconnectTests.swift +75 -2
  85. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +191 -0
  86. package/ios/Tests/MentraLiveAudioSetupTests.swift +215 -0
  87. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  88. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  89. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  90. package/ios/Tests/MentraLiveSessionReadinessTests.swift +328 -26
  91. package/ios/Tests/NimoCanvasTransportTests.swift +147 -0
  92. package/ios/Tests/NimoResourceSessionTests.swift +476 -0
  93. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  94. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  95. package/package.json +3 -2
  96. package/src/BluetoothSdk.types.ts +115 -1
  97. package/src/_private/BluetoothSdkModule.ts +7 -1
  98. package/src/generated/changelogCatalog.ts +4 -0
  99. package/src/generated/releaseMetadata.ts +6 -6
  100. package/src/index.ts +12 -0
@@ -0,0 +1,215 @@
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: the reconnect wait starts again from now.
102
+ clock(1_060_000)
103
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
104
+ XCTAssertEqual(audioSetup(store), .connecting)
105
+ clock(1_069_999)
106
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
107
+ XCTAssertEqual(audioSetup(store), .connecting)
108
+
109
+ // The deadline timer gives up at the end of the wait.
110
+ clock(1_069_950)
111
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
112
+ clock(1_070_000)
113
+ let deadline = Date().addingTimeInterval(2)
114
+ while audioSetup(store) != .needsUserConnectInSettings, Date() < deadline {
115
+ RunLoop.main.run(until: Date().addingTimeInterval(0.01))
116
+ }
117
+ XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
118
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "needs_user", "action": "connect_in_settings"])
119
+
120
+ // The phone's own signals are enough on their own.
121
+ store.set("glasses", "bluetoothAudioRouted", true)
122
+ XCTAssertEqual(audioSetup(store), .connected)
123
+
124
+ // Session drop.
125
+ transport.cleanup()
126
+ XCTAssertEqual(audioSetup(store), .idle)
127
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "idle"])
128
+ }
129
+ }
130
+
131
+ func testAnExplicitPairOnOldFirmwareNeedsTheUserInTheReadyUpdate() throws {
132
+ try withTransport { transport, store, _ in
133
+ store.set("bluetooth", "pending_device_name", "MENTRA_LIVE_BLE_ABCD")
134
+ store.set("bluetooth", "pending_device_secure_pairing_capable", false)
135
+ let atReady = try audioSetupWhenReady(store) {
136
+ try receive(transport, ["type": "glasses_ready", "sid": "legacy"])
137
+ }
138
+ XCTAssertEqual(atReady, .needsUserConnectInSettings)
139
+ XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
140
+
141
+ store.set("glasses", "bluetoothClassicConnected", true)
142
+ XCTAssertEqual(audioSetup(store), .connected)
143
+ }
144
+ }
145
+
146
+ func testAnExplicitSecurePairWithAutoAudioWaitsForAudio() throws {
147
+ try withTransport { transport, store, clock in
148
+ store.set("bluetooth", "pending_device_name", "MENTRA_LIVE_BLE_ABCD")
149
+ store.set("bluetooth", "pending_device_secure_pairing_capable", true)
150
+ clock(2_000_000)
151
+ try receive(transport, ["type": "glasses_ready", "sid": "secure"])
152
+ XCTAssertEqual(audioSetup(store), .idle, "not ready before the owner commit")
153
+ let atReady = try audioSetupWhenReady(store) {
154
+ try receive(transport, [
155
+ "type": "pairing_info", "secure_pairing_capable": true, "owner_committed": true,
156
+ "auto_audio": true, "protocol_version": 4,
157
+ ])
158
+ }
159
+ XCTAssertEqual(atReady, .connecting)
160
+ // A both-down report does not shorten the 8 s wait.
161
+ clock(2_001_000)
162
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
163
+ XCTAssertEqual(audioSetup(store), .connecting)
164
+ clock(2_008_000)
165
+ try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
166
+ XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
167
+ }
168
+ }
169
+
170
+ func testReadinessLostIsIdle() throws {
171
+ try withTransport { transport, store, _ in
172
+ try receive(transport, ["type": "glasses_ready", "sid": "first"])
173
+ XCTAssertEqual(audioSetup(store), .connecting)
174
+ // sr_hrt ready=0 and ASG restarts clear readiness on a live link.
175
+ DeviceStore.shared.set("glasses", "fullyBooted", false)
176
+ XCTAssertEqual(audioSetup(store), .idle)
177
+ }
178
+ }
179
+
180
+ func testModelsWithoutADriverRuleAreNotApplicableInTheReadyUpdate() {
181
+ let store = DeviceStore.shared.store
182
+ let saved = store.getCategory("glasses")
183
+ let previous = DeviceManager.shared.sgc
184
+ DeviceManager.shared.sgc = nil
185
+ defer {
186
+ DeviceManager.shared.sgc = previous
187
+ for key in store.getCategory("glasses").keys where saved[key] == nil {
188
+ store.remove("glasses", key)
189
+ }
190
+ for (key, value) in saved {
191
+ store.set("glasses", key, value)
192
+ }
193
+ }
194
+ store.set("glasses", "fullyBooted", false)
195
+ store.set("glasses", "audioSetup", GlassesAudioSetupState.idle.toMap())
196
+ var events: [[String: Any]] = []
197
+ let sink = Bridge.addEventSink { event, body in
198
+ if event == "audio_setup_changed", let state = body["state"] as? [String: Any] { events.append(state) }
199
+ }
200
+ defer { Bridge.removeEventSink(sink) }
201
+
202
+ let atReady = audioSetupWhenReady(store) {
203
+ DeviceStore.shared.apply("glasses", "fullyBooted", true)
204
+ }
205
+ XCTAssertEqual(atReady, .notApplicable)
206
+ XCTAssertEqual(events as [NSDictionary], [["state": "not_applicable"]])
207
+ let snapshot = GlassesStatus(values: store.getCategory("glasses"))
208
+ XCTAssertEqual(snapshot.audioSetup as NSDictionary?, ["state": "not_applicable"])
209
+ XCTAssertEqual(snapshot.dictionary["audioSetup"] as? NSDictionary, ["state": "not_applicable"])
210
+
211
+ DeviceStore.shared.apply("glasses", "fullyBooted", false)
212
+ XCTAssertEqual(audioSetup(store), .idle)
213
+ XCTAssertEqual(events.count, 2)
214
+ }
215
+ }
@@ -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
  }
@@ -1,8 +1,57 @@
1
+ import CoreBluetooth
1
2
  import Foundation
2
3
  @testable import MentraBluetoothSDK
3
4
  import XCTest
4
5
 
5
6
  final class MentraLivePairingAdvertisementTests: XCTestCase {
7
+ func testKnownConnectUsesThePeripheralFoundDuringPairing() {
8
+ XCTAssertEqual(
9
+ MentraLiveKnownConnectRoute.decide(
10
+ bluetoothPoweredOn: false,
11
+ hasCachedPeripheral: true,
12
+ hasSavedIdentifier: true,
13
+ systemConnectedMatch: true
14
+ ),
15
+ .waitForPower
16
+ )
17
+ XCTAssertEqual(
18
+ MentraLiveKnownConnectRoute.decide(
19
+ bluetoothPoweredOn: true,
20
+ hasCachedPeripheral: true,
21
+ hasSavedIdentifier: true,
22
+ systemConnectedMatch: false
23
+ ),
24
+ .cachedPeripheral
25
+ )
26
+ XCTAssertEqual(
27
+ MentraLiveKnownConnectRoute.decide(
28
+ bluetoothPoweredOn: true,
29
+ hasCachedPeripheral: false,
30
+ hasSavedIdentifier: true,
31
+ systemConnectedMatch: false
32
+ ),
33
+ .savedIdentifier
34
+ )
35
+ XCTAssertEqual(
36
+ MentraLiveKnownConnectRoute.decide(
37
+ bluetoothPoweredOn: true,
38
+ hasCachedPeripheral: false,
39
+ hasSavedIdentifier: false,
40
+ systemConnectedMatch: true
41
+ ),
42
+ .alreadyConnected
43
+ )
44
+ XCTAssertEqual(
45
+ MentraLiveKnownConnectRoute.decide(
46
+ bluetoothPoweredOn: true,
47
+ hasCachedPeripheral: false,
48
+ hasSavedIdentifier: false,
49
+ systemConnectedMatch: false
50
+ ),
51
+ .scan
52
+ )
53
+ }
54
+
6
55
  func testConnectedPairingRecoveryRequiresExplicitPendingTarget() {
7
56
  XCTAssertFalse(
8
57
  MentraLivePendingPairingTarget.matches(
@@ -139,6 +188,188 @@ final class MentraLivePairingAdvertisementTests: XCTestCase {
139
188
  }
140
189
  }
141
190
 
191
+ func testCapabilityFlagDoesNotConfirmOwnership() {
192
+ XCTAssertFalse(MentraLiveConnectionAttemptPolicy.pairingInfoConfirmsOwner(ownerCommitted: false))
193
+ XCTAssertTrue(MentraLiveConnectionAttemptPolicy.pairingInfoConfirmsOwner(ownerCommitted: true))
194
+ }
195
+
196
+ func testStaleIosBondPromptsOnceUntilTheCooldownPasses() {
197
+ typealias Policy = MentraLiveConnectionAttemptPolicy
198
+ XCTAssertTrue(
199
+ Policy.shouldPromptToForgetStaleIosBond(peerRemovedPairingInformation: true, promptedAt: 0, now: 100)
200
+ )
201
+ XCTAssertFalse(
202
+ Policy.shouldPromptToForgetStaleIosBond(peerRemovedPairingInformation: true, promptedAt: 90, now: 100)
203
+ )
204
+ XCTAssertTrue(
205
+ Policy.shouldPromptToForgetStaleIosBond(
206
+ peerRemovedPairingInformation: true,
207
+ promptedAt: 100,
208
+ now: 100 + Policy.staleIosBondPromptCooldownSeconds
209
+ )
210
+ )
211
+ XCTAssertFalse(
212
+ Policy.shouldPromptToForgetStaleIosBond(peerRemovedPairingInformation: false, promptedAt: 0, now: 100)
213
+ )
214
+ }
215
+
216
+ func testOnlySecureFirmwareOutsideExplicitPairingRejectsAnOwner() {
217
+ typealias Policy = MentraLiveConnectionAttemptPolicy
218
+ XCTAssertTrue(Policy.isOwnerRejection(isAuthFailure: true, explicitPairing: false, secureFirmware: true))
219
+ XCTAssertFalse(Policy.isOwnerRejection(isAuthFailure: true, explicitPairing: true, secureFirmware: true))
220
+ XCTAssertFalse(Policy.isOwnerRejection(isAuthFailure: true, explicitPairing: false, secureFirmware: false))
221
+ XCTAssertFalse(Policy.isOwnerRejection(isAuthFailure: false, explicitPairing: false, secureFirmware: true))
222
+ }
223
+
224
+ func testASingleRejectionDoesNotStandDown() {
225
+ var streak = MentraLiveOwnerRejectionStreak()
226
+ XCTAssertFalse(streak.record(nowMs: 0))
227
+ }
228
+
229
+ func testQuickRejectionsWaitForTheStreakToSpanAboutAMinute() {
230
+ var streak = MentraLiveOwnerRejectionStreak()
231
+ XCTAssertFalse(streak.record(nowMs: 0))
232
+ XCTAssertFalse(streak.record(nowMs: 3_000))
233
+ // Third attempt, but a glasses reboot also rejects for a few seconds.
234
+ XCTAssertFalse(streak.record(nowMs: 8_000))
235
+ XCTAssertFalse(streak.record(nowMs: 24_000))
236
+ XCTAssertTrue(streak.record(nowMs: MentraLiveOwnerRejectionStreak.minSpanMs))
237
+ }
238
+
239
+ func testASuccessfulSessionEndsTheStreak() {
240
+ var streak = MentraLiveOwnerRejectionStreak()
241
+ _ = streak.record(nowMs: 0)
242
+ _ = streak.record(nowMs: 10_000)
243
+ streak.reset()
244
+ XCTAssertFalse(streak.record(nowMs: 50_000))
245
+ XCTAssertFalse(streak.record(nowMs: 60_000))
246
+ }
247
+
248
+ func testRejectionsFarApartAreNotOneStreak() {
249
+ var streak = MentraLiveOwnerRejectionStreak()
250
+ _ = streak.record(nowMs: 0)
251
+ _ = streak.record(nowMs: 10_000)
252
+ _ = streak.record(nowMs: 20_000)
253
+ let later = 20_000 + MentraLiveOwnerRejectionStreak.streakGapMs + 1
254
+ XCTAssertFalse(streak.record(nowMs: later))
255
+ XCTAssertFalse(streak.record(nowMs: later + 10_000))
256
+ XCTAssertFalse(streak.record(nowMs: later + 20_000))
257
+ }
258
+
259
+ func testOneAttemptReportingTwiceCountsOnce() {
260
+ var streak = MentraLiveOwnerRejectionStreak()
261
+ let span = MentraLiveOwnerRejectionStreak.minSpanMs
262
+ // didFailToConnect then didDisconnect for each of two attempts.
263
+ XCTAssertFalse(streak.record(nowMs: 0))
264
+ XCTAssertFalse(streak.record(nowMs: 400))
265
+ XCTAssertFalse(streak.record(nowMs: span))
266
+ XCTAssertFalse(streak.record(nowMs: span + 400))
267
+ // A genuine third attempt completes the streak.
268
+ XCTAssertTrue(streak.record(nowMs: span + 10_000))
269
+ }
270
+
271
+ func testAutomaticReconnectStandsDownWhileTheSavedGlassesAdvertisePairingMode() {
272
+ typealias Policy = MentraLiveConnectionAttemptPolicy
273
+ XCTAssertTrue(Policy.shouldStandDownInsteadOfReconnect(
274
+ pairingMode: true, savedGlasses: true, explicitPairing: false
275
+ ))
276
+ XCTAssertFalse(Policy.shouldStandDownInsteadOfReconnect(
277
+ pairingMode: true, savedGlasses: true, explicitPairing: true
278
+ ))
279
+ XCTAssertFalse(Policy.shouldStandDownInsteadOfReconnect(
280
+ pairingMode: false, savedGlasses: true, explicitPairing: false
281
+ ))
282
+ XCTAssertFalse(Policy.shouldStandDownInsteadOfReconnect(
283
+ pairingMode: true, savedGlasses: false, explicitPairing: false
284
+ ))
285
+ }
286
+
287
+ func testPauseIsTheWindowPlusTheCloseMarginWithNo300sClamp() {
288
+ typealias Policy = MentraLiveConnectionAttemptPolicy
289
+ XCTAssertEqual(Policy.yieldMs(windowMs: 120_000), 150_000)
290
+ XCTAssertEqual(Policy.yieldMs(windowMs: 900_000), 930_000)
291
+ XCTAssertEqual(Policy.yieldMs(windowMs: 5_000), 35_000)
292
+ // A missing window falls back to the spec default, not to a floor.
293
+ XCTAssertEqual(Policy.yieldMs(windowMs: 0), 150_000)
294
+ XCTAssertEqual(Policy.yieldMs(windowMs: -1), 150_000)
295
+ }
296
+
297
+ func testARestartedAppKeepsOnlyALiveDeadlineWithinThePersistedPause() {
298
+ typealias Policy = MentraLiveConnectionAttemptPolicy
299
+ let now = 1_000_000
300
+ let pause = 150_000
301
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: 0, nowWallMs: now, pauseMs: pause), 0)
302
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: now + 50_000, nowWallMs: now, pauseMs: pause), 50_000)
303
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: now - 1, nowWallMs: now, pauseMs: pause), 0)
304
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: now + pause, nowWallMs: now, pauseMs: pause), pause)
305
+ // Longer than the pause persisted with it: a clock jump, not a deadline.
306
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: now + pause + 1, nowWallMs: now, pauseMs: pause), 0)
307
+ // A long window is not clamped to the old 300 s bound.
308
+ XCTAssertEqual(
309
+ Policy.persistedYieldRemainingMs(untilWallMs: now + 600_000, nowWallMs: now, pauseMs: 930_000),
310
+ 600_000
311
+ )
312
+ XCTAssertEqual(Policy.persistedYieldRemainingMs(untilWallMs: now + 10, nowWallMs: now, pauseMs: 0), 0)
313
+ }
314
+
315
+ func testPairSelectGoesOnlyWithAnExplicitAttemptToSecureGlasses() {
316
+ typealias Policy = MentraLiveConnectionAttemptPolicy
317
+ XCTAssertTrue(Policy.shouldSendPairSelect(explicitPairing: true, securePairingTarget: true))
318
+ XCTAssertFalse(Policy.shouldSendPairSelect(explicitPairing: false, securePairingTarget: true))
319
+ XCTAssertFalse(Policy.shouldSendPairSelect(explicitPairing: true, securePairingTarget: false))
320
+ XCTAssertFalse(Policy.shouldSendPairSelect(explicitPairing: false, securePairingTarget: false))
321
+ }
322
+
323
+ func testParkedSecureReadinessAlwaysHasABondWaitDeadline() {
324
+ typealias Policy = MentraLiveConnectionAttemptPolicy
325
+ // glasses_ready parks exactly when the attempt is explicit and the target secure; the
326
+ // wait must then always run so the pair cannot hang.
327
+ XCTAssertTrue(Policy.shouldRunSecurePairingWait(explicitPairing: true, securePairingTarget: true))
328
+ XCTAssertFalse(Policy.shouldRunSecurePairingWait(explicitPairing: false, securePairingTarget: true))
329
+ XCTAssertFalse(Policy.shouldRunSecurePairingWait(explicitPairing: true, securePairingTarget: false))
330
+ }
331
+
332
+ func testTheStaleBondCodeMatchesTheAppContract() {
333
+ XCTAssertEqual(MentraLiveConnectionAttemptPolicy.iosForgetPairingCode, "ios_forget_pairing")
334
+ }
335
+
336
+ func testAuthFailureClassifierCoversError14AndInsufficientSecurityOnly() {
337
+ XCTAssertTrue(MentraLive.isPairingAuthFailure(
338
+ NSError(domain: CBErrorDomain, code: CBError.peerRemovedPairingInformation.rawValue)
339
+ ))
340
+ XCTAssertTrue(MentraLive.isPairingAuthFailure(
341
+ NSError(domain: CBATTErrorDomain, code: CBATTError.insufficientAuthentication.rawValue)
342
+ ))
343
+ XCTAssertTrue(MentraLive.isPairingAuthFailure(
344
+ NSError(domain: CBATTErrorDomain, code: CBATTError.insufficientEncryption.rawValue)
345
+ ))
346
+ // A plain remote disconnect (the glasses' 0x14 refusal) and timeouts are not.
347
+ XCTAssertFalse(MentraLive.isPairingAuthFailure(
348
+ NSError(domain: CBErrorDomain, code: CBError.peripheralDisconnected.rawValue)
349
+ ))
350
+ XCTAssertFalse(MentraLive.isPairingAuthFailure(
351
+ NSError(domain: CBErrorDomain, code: CBError.connectionTimeout.rawValue)
352
+ ))
353
+ XCTAssertFalse(MentraLive.isPairingAuthFailure(nil))
354
+ }
355
+
356
+ func testReadsTheOwnerChangedFlagAndWindowIdFromTheV4Trailer() {
357
+ var payload = securePayload(pairingFlag: 0)
358
+ payload[2 + 7] = 0x01 | 0x04
359
+ payload[2 + 12] = 9
360
+ let result = MentraLivePairingAdvertisement.parse(coreBluetoothManufacturerData: payload)
361
+ XCTAssertEqual(result?.ownerChanged, true)
362
+ XCTAssertEqual(result?.pairingGeneration, 9)
363
+ XCTAssertEqual(result?.pairingMode, false)
364
+ }
365
+
366
+ func testOwnerChangedIsFalseWithoutTheFlag() {
367
+ let result = MentraLivePairingAdvertisement.parse(
368
+ coreBluetoothManufacturerData: securePayload(pairingFlag: 1)
369
+ )
370
+ XCTAssertEqual(result?.ownerChanged, false)
371
+ }
372
+
142
373
  private func legacyPayload() -> Data {
143
374
  var data = Data(repeating: 0, count: 29)
144
375
  data[0] = 0x22
@@ -157,4 +388,100 @@ final class MentraLivePairingAdvertisementTests: XCTestCase {
157
388
  data[2 + 11] = 0x50
158
389
  return data
159
390
  }
391
+
392
+ func testAPacketWithoutTheTrailerRightAfterOneWithItIsPartialNotLegacy() {
393
+ let t0 = 1_000_000
394
+ XCTAssertTrue(
395
+ MentraLiveDiscoveryPolicy.isPartialAdvertisement(secureCapable: false, lastSecureTrailerAtMs: t0, nowMs: t0 + 500)
396
+ )
397
+ XCTAssertTrue(
398
+ MentraLiveDiscoveryPolicy.isPartialAdvertisement(
399
+ secureCapable: false, lastSecureTrailerAtMs: t0, nowMs: t0 + MentraLiveDiscoveryPolicy.secureTrailerMemoryMs
400
+ )
401
+ )
402
+ XCTAssertFalse(
403
+ MentraLiveDiscoveryPolicy.isPartialAdvertisement(secureCapable: false, lastSecureTrailerAtMs: nil, nowMs: t0),
404
+ "legacy firmware never carries the trailer and is still listed as pairable"
405
+ )
406
+ XCTAssertFalse(
407
+ MentraLiveDiscoveryPolicy.isPartialAdvertisement(secureCapable: true, lastSecureTrailerAtMs: t0, nowMs: t0 + 500)
408
+ )
409
+ XCTAssertFalse(
410
+ MentraLiveDiscoveryPolicy.isPartialAdvertisement(secureCapable: true, lastSecureTrailerAtMs: nil, nowMs: t0)
411
+ )
412
+ }
413
+
414
+ func testTheSecureTrailerMemoryIsTenSeconds() {
415
+ XCTAssertEqual(MentraLiveDiscoveryPolicy.secureTrailerMemoryMs, 10_000)
416
+ }
417
+
418
+ func testARolledBackUnitListsAsLegacyOnceTheShortMemoryExpires() {
419
+ var memory = MentraLiveSecureTrailerMemory()
420
+ let unit = UUID()
421
+ let t0 = 5_000_000
422
+ memory.recordSecureTrailer(unit, nowMs: t0)
423
+ XCTAssertTrue(memory.isPartialAdvertisement(unit, secureCapable: false, nowMs: t0 + 2_000))
424
+ // Rolled back to legacy firmware: no trailer any more. After the memory it is legacy.
425
+ XCTAssertFalse(memory.isPartialAdvertisement(unit, secureCapable: false, nowMs: t0 + 10_001))
426
+ XCTAssertFalse(memory.hasRecentSecureTrailer(unit, nowMs: t0 + 10_001))
427
+ }
428
+
429
+ func testASameNamedLegacyUnitIsNotHidden() {
430
+ var memory = MentraLiveSecureTrailerMemory()
431
+ let secureUnit = UUID()
432
+ let legacyUnitWithTheSameName = UUID()
433
+ let t0 = 5_000_000
434
+ memory.recordSecureTrailer(secureUnit, nowMs: t0)
435
+ XCTAssertTrue(memory.isPartialAdvertisement(secureUnit, secureCapable: false, nowMs: t0 + 100))
436
+ XCTAssertFalse(memory.isPartialAdvertisement(legacyUnitWithTheSameName, secureCapable: false, nowMs: t0 + 100))
437
+ }
438
+
439
+ func testForgetClearsTheSecureTrailerMemory() {
440
+ var memory = MentraLiveSecureTrailerMemory()
441
+ let unit = UUID()
442
+ memory.recordSecureTrailer(unit, nowMs: 1_000)
443
+ memory.clear()
444
+ XCTAssertFalse(memory.isPartialAdvertisement(unit, secureCapable: false, nowMs: 1_100))
445
+ }
446
+
447
+ func testSecurePairingTargetFollowsOnlyTheSelectedRow() {
448
+ typealias Policy = MentraLiveConnectionAttemptPolicy
449
+ XCTAssertTrue(Policy.isSecurePairingTarget(selectedCapability: true, securePairingInfoThisSession: false))
450
+ XCTAssertFalse(
451
+ Policy.isSecurePairingTarget(selectedCapability: false, securePairingInfoThisSession: true),
452
+ "a row listed as legacy stays legacy"
453
+ )
454
+ XCTAssertFalse(Policy.isSecurePairingTarget(selectedCapability: nil, securePairingInfoThisSession: false))
455
+ XCTAssertTrue(
456
+ Policy.isSecurePairingTarget(selectedCapability: nil, securePairingInfoThisSession: true),
457
+ "an unknown row follows this session's secure pairing_info"
458
+ )
459
+ }
460
+
461
+ func testGlassesReadyReadinessForEachTargetCapability() {
462
+ typealias Policy = MentraLiveConnectionAttemptPolicy
463
+ func readiness(
464
+ explicit: Bool = true, row: Bool?, securePairingInfo: Bool = false, confirmed: Bool = false
465
+ ) -> Policy.Readiness {
466
+ Policy.readinessAtGlassesReady(
467
+ explicitPairing: explicit,
468
+ selectedCapability: row,
469
+ securePairingInfoThisSession: securePairingInfo,
470
+ securePairingConfirmed: confirmed
471
+ )
472
+ }
473
+ // Automatic reconnect never waits.
474
+ XCTAssertEqual(readiness(explicit: false, row: nil), .ready)
475
+ XCTAssertEqual(readiness(explicit: false, row: true), .ready)
476
+ // Known rows.
477
+ XCTAssertEqual(readiness(row: false), .ready)
478
+ XCTAssertEqual(readiness(row: true), .awaitOwnerCommit)
479
+ XCTAssertEqual(readiness(row: true, confirmed: true), .ready)
480
+ // Unknown row: wait (bounded) for pairing_info unless one already decided it.
481
+ XCTAssertEqual(readiness(row: nil), .awaitPairingInfo)
482
+ XCTAssertEqual(readiness(row: nil, securePairingInfo: true), .awaitOwnerCommit)
483
+ XCTAssertEqual(readiness(row: nil, securePairingInfo: true, confirmed: true), .ready)
484
+ XCTAssertEqual(Policy.unknownCapabilityPairingInfoWaitMs, 5_000)
485
+ XCTAssertEqual(Policy.secureFirmwareRefreshMs, 15_000)
486
+ }
160
487
  }