@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
@@ -22,6 +22,14 @@ class AudioSessionMonitor {
22
22
  static var isMonitoring = false
23
23
  static var devicePattern: String?
24
24
  static var callback: ((Bool, String?) -> Void)?
25
+ /// Last pair-audio decision line. The check runs on a timer; log only changes.
26
+ private static var lastPairFlow = ""
27
+ /// SoloAmbient hides paired HFP inputs. One short category probe per second is enough.
28
+ private static var lastBluetoothProbe: (at: Date, outputs: [AVAudioSessionPortDescription], inputs: [AVAudioSessionPortDescription]?)?
29
+ /// The glasses sent `classic_link` in the current BLE session. Their report replaces the
30
+ /// category probe, which can see a route that is not the glasses'. Old firmware never sends
31
+ /// it and keeps the probe.
32
+ static var glassesReportClassicLink = false
25
33
 
26
34
  private init() {
27
35
  Bridge.log("AudioMonitor: Initialized")
@@ -93,18 +101,134 @@ class AudioSessionMonitor {
93
101
  return false
94
102
  }
95
103
 
104
+ private struct BluetoothSessionSnapshot {
105
+ let categoryLabel: String
106
+ let outputs: [AVAudioSessionPortDescription]
107
+ let availableInputs: [AVAudioSessionPortDescription]?
108
+ }
109
+
110
+ /// The default SoloAmbient session lists only the built-in mic, so glasses that are
111
+ /// already connected in Settings look absent and pairing waits out the auto-audio timer.
112
+ /// Read HFP inputs with a category that can see them, then put the previous category back.
113
+ /// Does not activate the session or select an input.
114
+ private static func bluetoothSessionSnapshot() -> BluetoothSessionSnapshot {
115
+ if !Thread.isMainThread {
116
+ return DispatchQueue.main.sync { bluetoothSessionSnapshot() }
117
+ }
118
+ let session = AVAudioSession.sharedInstance()
119
+ if categoryShowsBluetoothInputs(session.category) {
120
+ return BluetoothSessionSnapshot(
121
+ categoryLabel: session.category.rawValue,
122
+ outputs: session.currentRoute.outputs,
123
+ availableInputs: session.availableInputs
124
+ )
125
+ }
126
+ if glassesReportClassicLink {
127
+ // Passive route observation only: never switch the category.
128
+ return BluetoothSessionSnapshot(
129
+ categoryLabel: "passive:\(session.category.rawValue)",
130
+ outputs: session.currentRoute.outputs,
131
+ availableInputs: session.availableInputs
132
+ )
133
+ }
134
+ if let lastBluetoothProbe, Date().timeIntervalSince(lastBluetoothProbe.at) < 1 {
135
+ return BluetoothSessionSnapshot(
136
+ categoryLabel: "probed:\(AVAudioSession.Category.playAndRecord.rawValue)",
137
+ outputs: lastBluetoothProbe.outputs,
138
+ availableInputs: lastBluetoothProbe.inputs
139
+ )
140
+ }
141
+ let savedCategory = session.category
142
+ let savedMode = session.mode
143
+ let savedOptions = session.categoryOptions
144
+ do {
145
+ try session.setCategory(
146
+ .playAndRecord, mode: .default, options: [.allowBluetooth, .allowBluetoothA2DP]
147
+ )
148
+ } catch {
149
+ return BluetoothSessionSnapshot(
150
+ categoryLabel: session.category.rawValue,
151
+ outputs: session.currentRoute.outputs,
152
+ availableInputs: session.availableInputs
153
+ )
154
+ }
155
+ let outputs = session.currentRoute.outputs
156
+ let inputs = session.availableInputs
157
+ lastBluetoothProbe = (Date(), outputs, inputs)
158
+ try? session.setCategory(savedCategory, mode: savedMode, options: savedOptions)
159
+ return BluetoothSessionSnapshot(
160
+ categoryLabel: "probed:\(AVAudioSession.Category.playAndRecord.rawValue)",
161
+ outputs: outputs,
162
+ availableInputs: inputs
163
+ )
164
+ }
165
+
166
+ private static func categoryShowsBluetoothInputs(_ category: AVAudioSession.Category) -> Bool {
167
+ category == .playAndRecord || category == .record || category == .multiRoute
168
+ }
169
+
170
+ /// Glasses' Classic audio facts without selecting an input or activating the session.
171
+ /// `profilesConnected` matches `isDevicePaired`; `audioRouted` is the stricter
172
+ /// "audio is flowing to the glasses" signal.
173
+ static func observeProfiles(devicePattern: String) -> BluetoothAudioRoute.ProfileObservation {
174
+ let snapshot = bluetoothSessionSnapshot()
175
+ let profiles = profileObservation(
176
+ devicePattern: devicePattern, outputs: snapshot.outputs, availableInputs: snapshot.availableInputs
177
+ )
178
+ logPairFlow(
179
+ category: snapshot.categoryLabel, devicePattern: devicePattern, outputs: snapshot.outputs,
180
+ availableInputs: snapshot.availableInputs, profiles: profiles
181
+ )
182
+ return profiles
183
+ }
184
+
185
+ private static func profileObservation(
186
+ devicePattern: String,
187
+ outputs: [AVAudioSessionPortDescription],
188
+ availableInputs: [AVAudioSessionPortDescription]?
189
+ ) -> BluetoothAudioRoute.ProfileObservation {
190
+ BluetoothAudioRoute.observeProfiles(
191
+ outputs: outputs.map { (name: $0.portName, portType: $0.portType.rawValue) },
192
+ inputs: availableInputs?.map { (name: $0.portName, portType: $0.portType.rawValue) },
193
+ target: devicePattern, isIOSAppOnMac: ProcessInfo.processInfo.isiOSAppOnMac
194
+ )
195
+ }
196
+
197
+ /// One PAIRFLOW line per transition of category, inputs availability, ports, and both facts.
198
+ /// Port names are the glasses' advertised name or other audio devices; no credentials are logged.
199
+ private static func logPairFlow(
200
+ category: String,
201
+ devicePattern: String,
202
+ outputs: [AVAudioSessionPortDescription],
203
+ availableInputs: [AVAudioSessionPortDescription]?,
204
+ profiles: BluetoothAudioRoute.ProfileObservation
205
+ ) {
206
+ let decision = profiles.audioRouted
207
+ ? "advance_active_output"
208
+ : (profiles.profilesConnected ? "advance_hfp_input" : "wait_no_route")
209
+ let outputNames = outputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")
210
+ let inputNames = (availableInputs ?? []).map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")
211
+ let pairFlow =
212
+ "PAIRFLOW: pair_audio decision=\(decision) pattern=\(devicePattern) category=\(category) inputsNil=\(availableInputs == nil) outputs=[\(outputNames)] inputs=[\(inputNames)] profilesConnected=\(profiles.profilesConnected) audioRouted=\(profiles.audioRouted)"
213
+ if pairFlow != lastPairFlow {
214
+ lastPairFlow = pairFlow
215
+ Bridge.log(pairFlow)
216
+ }
217
+ }
218
+
96
219
  /// Check if a Bluetooth device matching the pattern is paired (appears in availableInputs)
97
220
  /// Returns true if device is found (paired), WITHOUT activating it
98
221
  /// This avoids switching A2DP music playback to HFP microphone mode
99
222
  static func isDevicePaired(devicePattern: String) -> Bool {
100
- let session = AVAudioSession.sharedInstance()
101
- let outputs = session.currentRoute.outputs
223
+ let snapshot = bluetoothSessionSnapshot()
224
+ let outputs = snapshot.outputs
102
225
  let route = BluetoothAudioRoute.observe(
103
226
  outputs: outputs.map { (name: $0.portName, portType: $0.portType.rawValue) },
104
227
  target: devicePattern, isIOSAppOnMac: ProcessInfo.processInfo.isiOSAppOnMac
105
228
  )
106
229
  let activeTarget = route.matchingOutputCount > 0
107
- let availableInputs = session.availableInputs
230
+ let availableInputs = snapshot.availableInputs
231
+ let profiles = profileObservation(devicePattern: devicePattern, outputs: outputs, availableInputs: availableInputs)
108
232
  let bluetoothInput = availableInputs?.first { input in
109
233
  input.portType == .bluetoothHFP
110
234
  && input.portName.localizedCaseInsensitiveContains(devicePattern)
@@ -112,8 +236,12 @@ class AudioSessionMonitor {
112
236
 
113
237
  // NSLog messages redact the native route checks in retained Mac logs.
114
238
  // Keep categorical evidence at notice level without exposing names or
115
- // selecting an input, activating the session, or changing audio routing.
116
- readinessLog.notice("Pair audio: iosOnMac=\(ProcessInfo.processInfo.isiOSAppOnMac, privacy: .public) targetPresent=\(!devicePattern.isEmpty, privacy: .public) category=\(session.category.rawValue, privacy: .public) outputs=\(outputs.count, privacy: .public) bluetoothOutputs=\(route.bluetoothOutputCount, privacy: .public) targetNameOutputs=\(route.targetNameOutputCount, privacy: .public) inputs=\(availableInputs?.count ?? -1, privacy: .public) activeTarget=\(activeTarget, privacy: .public) hfpTarget=\(bluetoothInput != nil, privacy: .public)")
239
+ // selecting an input or activating the session.
240
+ readinessLog.notice("Pair audio: iosOnMac=\(ProcessInfo.processInfo.isiOSAppOnMac, privacy: .public) targetPresent=\(!devicePattern.isEmpty, privacy: .public) category=\(snapshot.categoryLabel, privacy: .public) outputs=\(outputs.count, privacy: .public) bluetoothOutputs=\(route.bluetoothOutputCount, privacy: .public) targetNameOutputs=\(route.targetNameOutputCount, privacy: .public) inputs=\(availableInputs?.count ?? -1, privacy: .public) activeTarget=\(activeTarget, privacy: .public) hfpTarget=\(bluetoothInput != nil, privacy: .public)")
241
+ logPairFlow(
242
+ category: snapshot.categoryLabel, devicePattern: devicePattern, outputs: outputs,
243
+ availableInputs: availableInputs, profiles: profiles
244
+ )
117
245
 
118
246
  // Check if already active (using A2DP for music or HFP for calls)
119
247
  if activeTarget {
@@ -320,6 +448,31 @@ enum BluetoothAudioRoute {
320
448
  )
321
449
  }
322
450
 
451
+ /// Separate facts about the glasses' Classic audio link. Neither implies a bond:
452
+ /// a bonded device with no connected audio profile is invisible to AVAudioSession.
453
+ struct ProfileObservation: Equatable {
454
+ /// An HFP input is available, or a matching Bluetooth output is active.
455
+ let profilesConnected: Bool
456
+ /// A matching Bluetooth output is the active route (A2DP or HFP).
457
+ let audioRouted: Bool
458
+ }
459
+
460
+ /// `inputs` is nil when `AVAudioSession.availableInputs` is nil (it depends on the session category).
461
+ static func observeProfiles(
462
+ outputs: [(name: String, portType: String)],
463
+ inputs: [(name: String, portType: String)]?,
464
+ target: String,
465
+ isIOSAppOnMac: Bool
466
+ ) -> ProfileObservation {
467
+ let audioRouted = outputs.contains {
468
+ matches(name: $0.name, portType: $0.portType, target: target, isIOSAppOnMac: isIOSAppOnMac)
469
+ }
470
+ let hfpInput = inputs?.contains {
471
+ $0.portType == "BluetoothHFP" && matchesName($0.name, target: target)
472
+ } ?? false
473
+ return ProfileObservation(profilesConnected: audioRouted || hfpInput, audioRouted: audioRouted)
474
+ }
475
+
323
476
  static func matches(name: String, portType: String, target: String, isIOSAppOnMac: Bool) -> Bool {
324
477
  matchesName(name, target: target) && isBluetoothTransport(portType, isIOSAppOnMac: isIOSAppOnMac)
325
478
  }
@@ -60,4 +60,86 @@ final class BluetoothAudioRouteTests: XCTestCase {
60
60
  ))
61
61
  }
62
62
  }
63
+
64
+ // MARK: - Profile observation
65
+
66
+ private func profiles(
67
+ outputs: [(name: String, portType: String)] = [],
68
+ inputs: [(name: String, portType: String)]? = [],
69
+ isIOSAppOnMac: Bool = false
70
+ ) -> BluetoothAudioRoute.ProfileObservation {
71
+ BluetoothAudioRoute.observeProfiles(
72
+ outputs: outputs, inputs: inputs, target: "03BE", isIOSAppOnMac: isIOSAppOnMac
73
+ )
74
+ }
75
+
76
+ func testActiveA2dpOutputIsConnectedAndRouted() {
77
+ let result = profiles(outputs: [(name: "Mentra_Live_03BE", portType: "BluetoothA2DPOutput")], inputs: nil)
78
+ XCTAssertEqual(result, .init(profilesConnected: true, audioRouted: true))
79
+ }
80
+
81
+ func testHfpInputOnlyIsConnectedButNotRouted() {
82
+ let result = profiles(
83
+ outputs: [(name: "Speaker", portType: "Speaker")],
84
+ inputs: [(name: "Mentra_Live_03BE", portType: "BluetoothHFP")]
85
+ )
86
+ XCTAssertEqual(result, .init(profilesConnected: true, audioRouted: false))
87
+ }
88
+
89
+ func testNoMatchIsNeitherConnectedNorRouted() {
90
+ let result = profiles(
91
+ outputs: [(name: "Speaker", portType: "Speaker")],
92
+ inputs: [(name: "iPhone Microphone", portType: "MicrophoneBuiltIn")]
93
+ )
94
+ XCTAssertEqual(result, .init(profilesConnected: false, audioRouted: false))
95
+ XCTAssertEqual(profiles(), .init(profilesConnected: false, audioRouted: false))
96
+ }
97
+
98
+ func testNilInputsDoNotHideActiveOutputAndAreNotAMatch() {
99
+ XCTAssertEqual(
100
+ profiles(outputs: [(name: "Speaker", portType: "Speaker")], inputs: nil),
101
+ .init(profilesConnected: false, audioRouted: false)
102
+ )
103
+ XCTAssertEqual(
104
+ profiles(outputs: [(name: "Mentra_Live_03BE", portType: "BluetoothHFP")], inputs: nil),
105
+ .init(profilesConnected: true, audioRouted: true)
106
+ )
107
+ }
108
+
109
+ func testOtherDevicesDoNotMatch() {
110
+ let result = profiles(
111
+ outputs: [(name: "Mentra_Live_023B", portType: "BluetoothA2DPOutput")],
112
+ inputs: [(name: "Mentra_Live_023B", portType: "BluetoothHFP")]
113
+ )
114
+ XCTAssertEqual(result, .init(profilesConnected: false, audioRouted: false))
115
+ }
116
+
117
+ func testIdentityAndTransportBothRequiredForInputsAndOutputs() {
118
+ let result = profiles(
119
+ outputs: [(name: "Mentra_Live_03BE", portType: "USBAudio")],
120
+ inputs: [(name: "Mentra_Live_03BE", portType: "BluetoothA2DPOutput")]
121
+ )
122
+ XCTAssertEqual(result, .init(profilesConnected: false, audioRouted: false))
123
+ }
124
+
125
+ func testIOSOnMacBluetoothPortIsRoutedOnlyOnMac() {
126
+ let output = [(name: "Mentra_Live_03BE", portType: "Bluetooth")]
127
+ XCTAssertEqual(
128
+ profiles(outputs: output, isIOSAppOnMac: true),
129
+ .init(profilesConnected: true, audioRouted: true)
130
+ )
131
+ XCTAssertEqual(
132
+ profiles(outputs: output, isIOSAppOnMac: false),
133
+ .init(profilesConnected: false, audioRouted: false)
134
+ )
135
+ }
136
+
137
+ func testEmptyTargetNeverMatches() {
138
+ let result = BluetoothAudioRoute.observeProfiles(
139
+ outputs: [(name: "Mentra_Live_03BE", portType: "BluetoothA2DPOutput")],
140
+ inputs: [(name: "Mentra_Live_03BE", portType: "BluetoothHFP")],
141
+ target: "", isIOSAppOnMac: false
142
+ )
143
+ XCTAssertEqual(result, .init(profilesConnected: false, audioRouted: false))
144
+ }
63
145
  }
@@ -5,6 +5,77 @@ import XCTest
5
5
  final class DeviceManagerReconnectTests: XCTestCase {
6
6
  private let requests = ["should_send_lc3", "should_send_pcm", "should_send_transcript", "local_stt_fallback_active"]
7
7
 
8
+ func testActualManagerHandoffCleanupDoesNotInvalidateClosedOriginalStatus() {
9
+ withRecordingDevice { manager, _ in
10
+ let original = manager.sgc as! ReconnectRecordingDevice
11
+ original.type = DeviceTypes.NIMO
12
+ let uuid = "00000000-0000-4000-8000-000000000001"
13
+ let model = NimoResourceSession(captureNonce: uuid, pair: NimoResourcePair(name: "Nimo-Test", peripheralUuid: uuid))
14
+ XCTAssertTrue(model.admit(original, instanceId: uuid, name: "Nimo-Test"))
15
+ XCTAssertTrue(model.beginRelease(nonce: uuid, cancel: true, mic: false, canvas: false))
16
+ model.proveNoTransport()
17
+ let verifiedClosed = model.settled(producers: NimoResourceProducers())
18
+ var cleanupCalls = 0, disconnectEffects = 0
19
+ original.onCleanup = {
20
+ cleanupCalls += 1
21
+ // Same original-session guard used by actual Nimo.disconnect.
22
+ if model.shouldRunOrdinaryDisconnect(original, originalClosed: verifiedClosed) { disconnectEffects += 1 }
23
+ }
24
+ manager.initSGC(DeviceTypes.SIMULATED) // Actual manager replacement; no Bluetooth device.
25
+ XCTAssertEqual(cleanupCalls, 1)
26
+ XCTAssertEqual(disconnectEffects, 0)
27
+ XCTAssertTrue(model.errors.isEmpty)
28
+ XCTAssertTrue(model.settled(producers: NimoResourceProducers())) // Fresh status after cleanup.
29
+ XCTAssertTrue(NimoResourceManagerState.allowsReplacement(fixtureEnabled: true, originalClosed: model.settled(producers: NimoResourceProducers())))
30
+ XCTAssertEqual(manager.sgc?.type, DeviceTypes.SIMULATED)
31
+ }
32
+ }
33
+
34
+ func testActualQueuedReplacementDoesNotJoinOriginalNimoProducerRoster() {
35
+ withRecordingDevice { manager, store in
36
+ let original = manager.sgc as! ReconnectRecordingDevice
37
+ original.type = DeviceTypes.NIMO
38
+ let uuid = "00000000-0000-4000-8000-000000000001"
39
+ let model = NimoResourceSession(captureNonce: uuid, pair: NimoResourcePair(name: "Nimo-Test", peripheralUuid: uuid))
40
+ XCTAssertTrue(model.admit(original, instanceId: uuid, name: "Nimo-Test"))
41
+ XCTAssertTrue(model.beginRelease(nonce: uuid, cancel: true, mic: false, canvas: false)); model.proveNoTransport()
42
+ let stopped = expectation(description: "Original disposal inside real queued manager handoff")
43
+ original.onDisconnect = {
44
+ XCTAssertFalse(model.shouldRunOrdinaryDisconnect(original, originalClosed: true))
45
+ stopped.fulfill()
46
+ }
47
+ // Same asynchronous connectByName path as G2; simulated replacement
48
+ // avoids any Bluetooth transport in this source regression.
49
+ store.set("bluetooth", "pending_wearable", DeviceTypes.SIMULATED)
50
+ manager.connectByName("Simulated")
51
+ XCTAssertEqual(NimoResourceFixture.shared.pendingManagerEntries, 1)
52
+ XCTAssertEqual(NimoResourceFixture.shared.pendingOriginalManagerEntries, 0)
53
+ wait(for: [stopped], timeout: 1)
54
+ var producers = NimoResourceProducers()
55
+ producers.postedCallbacks = NimoResourceFixture.shared.pendingOriginalManagerEntries
56
+ XCTAssertTrue(model.settled(producers: producers)) // Fresh status during replacement wait.
57
+ XCTAssertTrue(model.errors.isEmpty)
58
+ let completed = expectation(description: "Replacement queued work has actually settled")
59
+ Task { @MainActor in
60
+ let deadline = ProcessInfo.processInfo.systemUptime + 2
61
+ while ProcessInfo.processInfo.systemUptime < deadline {
62
+ if NimoResourceFixture.shared.pendingManagerEntries == 0,
63
+ manager.sgc?.type == DeviceTypes.SIMULATED {
64
+ completed.fulfill()
65
+ return
66
+ }
67
+ try? await Task.sleep(nanoseconds: 5_000_000)
68
+ }
69
+ // Leave the expectation unmet on timeout; elapsed delay alone
70
+ // cannot stand in for the queued manager's actual completion.
71
+ }
72
+ wait(for: [completed], timeout: 2.5)
73
+ XCTAssertEqual(NimoResourceFixture.shared.pendingManagerEntries, 0)
74
+ XCTAssertTrue(model.settled(producers: NimoResourceProducers()))
75
+ XCTAssertEqual(manager.sgc?.type, DeviceTypes.SIMULATED)
76
+ }
77
+ }
78
+
8
79
  func testDelayedReconnectReplayPreservesNimoDepthEndpoints() {
9
80
  for depth in [0, 10] {
10
81
  withRecordingDevice { manager, store in
@@ -280,6 +351,8 @@ final class DeviceManagerReconnectTests: XCTestCase {
280
351
 
281
352
  @MainActor
282
353
  private final class ReconnectRecordingDevice: SGCManager {
354
+ var onCleanup: (() -> Void)?
355
+ var onDisconnect: (() -> Void)?
283
356
  var type = "Reconnect test glasses"
284
357
  let hasMic = true
285
358
  let showConnectionConfirmation = false
@@ -333,7 +406,7 @@ private final class ReconnectRecordingDevice: SGCManager {
333
406
  func sendShutdown() {}
334
407
  func sendReboot() {}
335
408
  func sendRgbLedControl(requestId _: String, packageName _: String?, action _: String, color _: String?, onDurationMs _: Int, offDurationMs _: Int, count _: Int) {}
336
- func disconnect() {}
409
+ func disconnect() { onDisconnect?() }
337
410
  func forget() {}
338
411
  func findCompatibleDevices() {}
339
412
  func stopScan() {}
@@ -342,7 +415,7 @@ private final class ReconnectRecordingDevice: SGCManager {
342
415
  nil
343
416
  }
344
417
 
345
- func cleanup() {}
418
+ func cleanup() { onCleanup?() }
346
419
  func ping() {}
347
420
  func dbg1() {}
348
421
  func dbg2() {}
@@ -0,0 +1,191 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ /// Table tests for the iOS audio-setup rules (Android reports `not_applicable` while ready).
5
+ final class GlassesAudioSetupPolicyTests: XCTestCase {
6
+ private typealias Policy = GlassesAudioSetupPolicy
7
+ private let t0 = 1_000_000
8
+
9
+ private func inputs(
10
+ ready: Bool = true,
11
+ report: (a2dp: Bool, hfp: Bool)? = nil,
12
+ phone: Bool = false,
13
+ phase: GlassesAudioSetupPhase = .reconnect,
14
+ startedAt: Int? = nil
15
+ ) -> GlassesAudioSetupInputs {
16
+ GlassesAudioSetupInputs(
17
+ sessionReady: ready,
18
+ glassesReportsClassicLink: report != nil,
19
+ glassesA2dp: report?.a2dp ?? false,
20
+ glassesHfp: report?.hfp ?? false,
21
+ phoneAudioUp: phone,
22
+ phase: phase,
23
+ phaseStartedAtMs: startedAt ?? t0
24
+ )
25
+ }
26
+
27
+ private func state(_ inputs: GlassesAudioSetupInputs, at offsetMs: Int) -> GlassesAudioSetupState {
28
+ Policy.decide(inputs, nowMs: t0 + offsetMs).state
29
+ }
30
+
31
+ func testConstantsMatchTheContract() {
32
+ XCTAssertEqual(Policy.pairingAutoAudioWaitMs, 8000)
33
+ XCTAssertEqual(Policy.reconnectAudioGraceMs, 10000)
34
+ }
35
+
36
+ func testNoSessionIsIdle() {
37
+ XCTAssertEqual(
38
+ Policy.decide(inputs(ready: false, report: (true, true), phone: true), nowMs: t0),
39
+ GlassesAudioSetupDecision(state: .idle, nextDeadlineMs: nil)
40
+ )
41
+ }
42
+
43
+ func testPairingWithAutoAudioWaitsEightSecondsThenNeedsTheUser() {
44
+ let pairing = inputs(phase: .pairing(autoAudio: true))
45
+ XCTAssertEqual(
46
+ Policy.decide(pairing, nowMs: t0),
47
+ GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: t0 + 8000)
48
+ )
49
+ XCTAssertEqual(state(pairing, at: 7999), .connecting)
50
+ XCTAssertEqual(state(pairing, at: 8000), .needsUserConnectInSettings)
51
+ }
52
+
53
+ func testPairingWithoutAutoAudioNeedsTheUserAtOnce() {
54
+ XCTAssertEqual(
55
+ Policy.decide(inputs(phase: .pairing(autoAudio: false)), nowMs: t0),
56
+ GlassesAudioSetupDecision(state: .needsUserConnectInSettings, nextDeadlineMs: nil)
57
+ )
58
+ }
59
+
60
+ func testReconnectWaitsTenSecondsThenNeedsTheUser() {
61
+ let reconnect = inputs(phase: .reconnect)
62
+ XCTAssertEqual(
63
+ Policy.decide(reconnect, nowMs: t0 + 1000),
64
+ GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: t0 + 10000)
65
+ )
66
+ XCTAssertEqual(state(reconnect, at: 9999), .connecting)
67
+ XCTAssertEqual(state(reconnect, at: 10000), .needsUserConnectInSettings)
68
+ }
69
+
70
+ func testEitherAudioSourceIsEnoughInEveryPhase() {
71
+ for phase in [GlassesAudioSetupPhase.pairing(autoAudio: true), .pairing(autoAudio: false), .reconnect] {
72
+ for offset in [0, 30000] {
73
+ XCTAssertEqual(state(inputs(phone: true, phase: phase), at: offset), .connected, "phone \(phase)")
74
+ XCTAssertEqual(state(inputs(report: (true, false), phase: phase), at: offset), .connected, "a2dp \(phase)")
75
+ XCTAssertEqual(state(inputs(report: (false, true), phase: phase), at: offset), .connected, "hfp \(phase)")
76
+ }
77
+ }
78
+ XCTAssertEqual(Policy.decide(inputs(phone: true), nowMs: t0).nextDeadlineMs, nil)
79
+ }
80
+
81
+ func testAGlassesReportOfBothLinksDownNeverShortensTheWait() {
82
+ let down = inputs(report: (false, false), phase: .pairing(autoAudio: true))
83
+ XCTAssertEqual(state(down, at: 1), .connecting)
84
+ XCTAssertEqual(Policy.decide(down, nowMs: t0 + 1).nextDeadlineMs, t0 + 8000)
85
+ XCTAssertEqual(state(inputs(report: (false, false), phase: .reconnect), at: 9000), .connecting)
86
+ }
87
+
88
+ func testABothDownReportDoesNotVetoThePhone() {
89
+ XCTAssertEqual(state(inputs(report: (false, false), phone: true), at: 0), .connected)
90
+ }
91
+
92
+ func testTheGlassesReportArrivingBeforeThePhoneSignals() {
93
+ var tracker = GlassesAudioSetupTracker()
94
+ tracker.startPhase(.pairing(autoAudio: true), nowMs: t0)
95
+ tracker.classicLink(a2dp: true, hfp: true)
96
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 100).state, .connected)
97
+ // The phone's route catches up later: still connected, nothing to re-arm.
98
+ XCTAssertEqual(
99
+ tracker.evaluate(sessionReady: true, phoneAudioUp: true, nowMs: t0 + 900),
100
+ GlassesAudioSetupDecision(state: .connected, nextDeadlineMs: nil)
101
+ )
102
+ }
103
+
104
+ func testTheGlassesReportArrivingAfterThePhoneSignals() {
105
+ var tracker = GlassesAudioSetupTracker()
106
+ tracker.startPhase(.reconnect, nowMs: t0)
107
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: true, nowMs: t0 + 100).state, .connected)
108
+ // The glasses then report both down (for example A2DP closing while HFP reconnects).
109
+ // The phone still sees audio, so the state stays connected.
110
+ tracker.classicLink(a2dp: false, hfp: false)
111
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: true, nowMs: t0 + 200).state, .connected)
112
+ }
113
+
114
+ func testAReportAfterNeedsUserMovesToConnected() {
115
+ var tracker = GlassesAudioSetupTracker()
116
+ tracker.startPhase(.pairing(autoAudio: false), nowMs: t0)
117
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0).state, .needsUserConnectInSettings)
118
+ tracker.classicLink(a2dp: false, hfp: true)
119
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 60000).state, .connected)
120
+ }
121
+
122
+ func testLosingAudioAfterConnectedStartsTheReconnectWaitAgain() {
123
+ var tracker = GlassesAudioSetupTracker()
124
+ tracker.startPhase(.pairing(autoAudio: false), nowMs: t0)
125
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: true, nowMs: t0 + 500).state, .connected)
126
+
127
+ let lostAt = t0 + 60000
128
+ XCTAssertEqual(
129
+ tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: lostAt),
130
+ GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: lostAt + 10000)
131
+ )
132
+ XCTAssertEqual(tracker.phase, .reconnect)
133
+ XCTAssertEqual(tracker.phaseStartedAtMs, lostAt)
134
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: lostAt + 9999).state, .connecting)
135
+ XCTAssertEqual(
136
+ tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: lostAt + 10000).state,
137
+ .needsUserConnectInSettings
138
+ )
139
+ }
140
+
141
+ func testTheGlassesReportingAudioDownAfterConnectedStartsTheReconnectWait() {
142
+ var tracker = GlassesAudioSetupTracker()
143
+ tracker.startPhase(.reconnect, nowMs: t0)
144
+ tracker.classicLink(a2dp: true, hfp: true)
145
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0).state, .connected)
146
+ tracker.classicLink(a2dp: false, hfp: false)
147
+ XCTAssertEqual(
148
+ tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 30000),
149
+ GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: t0 + 40000)
150
+ )
151
+ }
152
+
153
+ func testASessionDropIsIdleAndForgetsTheGlassesReport() {
154
+ var tracker = GlassesAudioSetupTracker()
155
+ tracker.startPhase(.reconnect, nowMs: t0)
156
+ tracker.classicLink(a2dp: true, hfp: false)
157
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0).state, .connected)
158
+
159
+ tracker.endSession()
160
+ XCTAssertEqual(
161
+ tracker.evaluate(sessionReady: false, phoneAudioUp: false, nowMs: t0 + 1000),
162
+ GlassesAudioSetupDecision(state: .idle, nextDeadlineMs: nil)
163
+ )
164
+ XCTAssertFalse(tracker.glassesReportsClassicLink)
165
+
166
+ // The next session has not reported its link yet.
167
+ tracker.startPhase(.reconnect, nowMs: t0 + 2000)
168
+ XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 2000).state, .connecting)
169
+ }
170
+
171
+ func testMapEncodingMatchesTheContract() {
172
+ XCTAssertEqual(GlassesAudioSetupState.idle.toMap() as NSDictionary, ["state": "idle"])
173
+ XCTAssertEqual(GlassesAudioSetupState.notApplicable.toMap() as NSDictionary, ["state": "not_applicable"])
174
+ XCTAssertEqual(GlassesAudioSetupState.connecting.toMap() as NSDictionary, ["state": "connecting"])
175
+ XCTAssertEqual(GlassesAudioSetupState.connected.toMap() as NSDictionary, ["state": "connected"])
176
+ XCTAssertEqual(
177
+ GlassesAudioSetupState.needsUserConnectInSettings.toMap() as NSDictionary,
178
+ ["state": "needs_user", "action": "connect_in_settings"]
179
+ )
180
+ for state in [GlassesAudioSetupState.idle, .notApplicable, .connecting, .connected, .needsUserConnectInSettings] {
181
+ XCTAssertEqual(GlassesAudioSetupState(map: state.toMap()), state)
182
+ }
183
+ XCTAssertNil(GlassesAudioSetupState(map: ["state": "unknown"]))
184
+ XCTAssertNil(GlassesAudioSetupState(map: nil))
185
+ }
186
+
187
+ func testModelsWithoutADriverRuleAreNotApplicableWhileReady() {
188
+ XCTAssertEqual(GlassesAudioSetupState.modelDefault(ready: true), .notApplicable)
189
+ XCTAssertEqual(GlassesAudioSetupState.modelDefault(ready: false), .idle)
190
+ }
191
+ }