@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
@@ -25,6 +25,8 @@ internal class NimoGattQueue<C : Any>(
25
25
  private var descriptorCompletion: (() -> Unit)? = null
26
26
  private var cancelDeadline: (() -> Unit)? = null
27
27
 
28
+ fun pendingCount(): Int = queue.size + (if (current != null) 1 else 0) + (if (descriptor != null) 1 else 0)
29
+
28
30
  fun connected(connection: Any) { reset(); this.connection = connection }
29
31
 
30
32
  fun reset() {
@@ -120,6 +122,7 @@ internal class NimoCanvasCoordinator(
120
122
  private val reconnect: (String) -> Unit,
121
123
  private val rejected: (Int) -> Unit = {},
122
124
  private val holdPreempted: () -> Unit = {},
125
+ private val businessResponse: (Int, Int) -> Unit = { _, _ -> },
123
126
  ) {
124
127
  private class Flight(val action: NimoCanvasSession.Action.Send) {
125
128
  var finalStarted = false
@@ -134,6 +137,10 @@ internal class NimoCanvasCoordinator(
134
137
  private var cancelDeadline: (() -> Unit)? = null
135
138
  private var cancelRetry: (() -> Unit)? = null
136
139
 
140
+ fun pendingCount(): Int = if (flight != null) 1 else 0
141
+ fun active(): Boolean = session.active()
142
+ fun launchPending(): Boolean = flight?.action?.key == 1
143
+
137
144
  fun offer(bytes: ByteArray, scope: String, force: Boolean = false) {
138
145
  if (holding && scope != heldScope) {
139
146
  releaseHold(resume = false)
@@ -188,6 +195,7 @@ internal class NimoCanvasCoordinator(
188
195
  }
189
196
  cancelDeadline?.invoke(); cancelDeadline = null
190
197
  flight = null
198
+ businessResponse(key, payload[0].toInt() and 255)
191
199
  run(session.response(key, payload))
192
200
  notifyHoldReadyIfIdle()
193
201
  }
@@ -14,6 +14,10 @@ internal class NimoCanvasEncoder(
14
14
  private var generation = 0L
15
15
  private var pending: Request? = null
16
16
  private var closed = false
17
+ private var running = 0
18
+ private var deliveries = 0
19
+
20
+ @Synchronized fun pendingCount(): Int = (if (pending != null) 1 else 0) + running + deliveries
17
21
 
18
22
  @Synchronized
19
23
  fun submit(encode: () -> ByteArray, release: () -> Unit = {}, deliver: (ByteArray) -> Unit): Boolean {
@@ -44,15 +48,18 @@ internal class NimoCanvasEncoder(
44
48
  synchronized(this) {
45
49
  if (pending !== request) return
46
50
  pending = null // Running work releases its own source, never the invalidator.
51
+ running++
47
52
  }
48
53
  try {
49
54
  val bytes = request.encode()
55
+ synchronized(this) { deliveries++ }
50
56
  main.post(0) {
51
57
  synchronized(this) {
58
+ deliveries--
52
59
  if (!closed && generation == request.generation) request.deliver(bytes)
53
60
  }
54
61
  }
55
62
  } catch (error: Exception) { failed(error) }
56
- finally { request.release() }
63
+ finally { request.release(); synchronized(this) { running-- } }
57
64
  }
58
65
  }
@@ -60,6 +60,7 @@ internal class NimoCanvasSession {
60
60
  return if (!value && resume) pump() else emptyList()
61
61
  }
62
62
 
63
+ fun active(): Boolean = active
63
64
  fun currentScope(): String? = scope
64
65
 
65
66
  fun readiness(value: Boolean): List<Action> = updateReadiness(value, confirmed = false)
@@ -1,5 +1,8 @@
1
1
  package com.mentra.bluetoothsdk
2
2
 
3
+ import com.mentra.bluetoothsdk.sgcs.GlassesAudioSetupPolicy
4
+ import com.mentra.bluetoothsdk.sgcs.GlassesAudioSetupState
5
+
3
6
  data class WifiScanResult(
4
7
  val ssid: String,
5
8
  val requiresPassword: Boolean,
@@ -35,6 +38,8 @@ internal data class GlassesStatus(
35
38
  val voiceActivityDetectionEnabled: Boolean,
36
39
  val connectionState: GlassesConnectionState,
37
40
  val bluetoothClassicConnected: Boolean,
41
+ val bluetoothClassicProfilesConnected: Boolean,
42
+ val bluetoothAudioRouted: Boolean,
38
43
  val signalStrength: Int,
39
44
  val signalStrengthUpdatedAt: Long,
40
45
  val deviceModel: String,
@@ -77,6 +82,14 @@ internal data class GlassesStatus(
77
82
  val controllerBatteryLevel: Int,
78
83
  val controllerSignalStrength: Int,
79
84
  val ringSignalStrength: Int,
85
+ /** Mentra Live `MentraLivePairingState` map (`{state, windowId?, endsAtMs?}`); absent for other glasses. */
86
+ val pairingState: Map<String, Any>? = null,
87
+ /**
88
+ * `GlassesAudioSetupState` map, on every model. Derived from [fullyBooted] by
89
+ * [GlassesAudioSetupPolicy] rather than stored, so a snapshot that reports ready never
90
+ * carries a stale `idle`.
91
+ */
92
+ val audioSetup: Map<String, Any> = GlassesAudioSetupPolicy.state(fullyBooted).toMap(),
80
93
  ) {
81
94
  internal fun toMap(): Map<String, Any> {
82
95
  val values =
@@ -85,6 +98,8 @@ internal data class GlassesStatus(
85
98
  "micEnabled" to micEnabled,
86
99
  "voiceActivityDetectionEnabled" to voiceActivityDetectionEnabled,
87
100
  "bluetoothClassicConnected" to bluetoothClassicConnected,
101
+ "bluetoothClassicProfilesConnected" to bluetoothClassicProfilesConnected,
102
+ "bluetoothAudioRouted" to bluetoothAudioRouted,
88
103
  "signalStrength" to signalStrength,
89
104
  "signalStrengthUpdatedAt" to signalStrengthUpdatedAt,
90
105
  "deviceModel" to deviceModel,
@@ -123,6 +138,8 @@ internal data class GlassesStatus(
123
138
  "ringSignalStrength" to ringSignalStrength,
124
139
  )
125
140
  systemTimeMs?.let { values["systemTimeMs"] = it }
141
+ pairingState?.let { values["pairingState"] = it }
142
+ values["audioSetup"] = audioSetup
126
143
  return values
127
144
  }
128
145
 
@@ -137,6 +154,9 @@ internal data class GlassesStatus(
137
154
  ?: BluetoothSdkDefaults.VOICE_ACTIVITY_DETECTION_ENABLED,
138
155
  connectionState = GlassesConnectionState.fromValue(stringValue(values, "connectionState")),
139
156
  bluetoothClassicConnected = boolValue(values, "bluetoothClassicConnected") ?: false,
157
+ // Android has no separate profile/route signal; both mirror the Classic audio state.
158
+ bluetoothClassicProfilesConnected = boolValue(values, "bluetoothClassicConnected") ?: false,
159
+ bluetoothAudioRouted = boolValue(values, "bluetoothClassicConnected") ?: false,
140
160
  signalStrength = numberValue(values, "signalStrength") ?: -1,
141
161
  signalStrengthUpdatedAt = longValue(values, "signalStrengthUpdatedAt") ?: 0L,
142
162
  deviceModel = stringValue(values, "deviceModel") ?: "",
@@ -174,10 +194,25 @@ internal data class GlassesStatus(
174
194
  controllerBatteryLevel = numberValue(values, "controllerBatteryLevel") ?: -1,
175
195
  controllerSignalStrength = numberValue(values, "controllerSignalStrength") ?: -1,
176
196
  ringSignalStrength = numberValue(values, "ringSignalStrength") ?: -1,
197
+ pairingState = pairingStateValue(values),
177
198
  )
178
199
  }
179
200
  }
180
201
 
202
+ /** `audioSetup` from an event or update map, keeping only a known state and its action. */
203
+ internal fun audioSetupValue(values: Map<String, Any>): Map<String, Any>? =
204
+ GlassesAudioSetupState.fromMap(values["audioSetup"])?.toMap()
205
+
206
+ /** `pairingState` from a store or event map, keeping only string keys. */
207
+ internal fun pairingStateValue(values: Map<String, Any>): Map<String, Any>? {
208
+ val raw = values["pairingState"] as? Map<*, *> ?: return null
209
+ val state = raw["state"] as? String ?: return null
210
+ val result = mutableMapOf<String, Any>("state" to state)
211
+ (raw["windowId"] as? Number)?.let { result["windowId"] = it.toInt() }
212
+ (raw["endsAtMs"] as? Number)?.let { result["endsAtMs"] = it.toLong() }
213
+ return result
214
+ }
215
+
181
216
  data class VersionInfoResult(
182
217
  val androidVersion: String,
183
218
  val firmwareVersion: String,
@@ -406,6 +441,8 @@ internal data class GlassesStatusUpdate(
406
441
  val voiceActivityDetectionEnabled: Boolean? = null,
407
442
  val connectionState: GlassesConnectionState? = null,
408
443
  val bluetoothClassicConnected: Boolean? = null,
444
+ val bluetoothClassicProfilesConnected: Boolean? = null,
445
+ val bluetoothAudioRouted: Boolean? = null,
409
446
  val signalStrength: Int? = null,
410
447
  val signalStrengthUpdatedAt: Long? = null,
411
448
  val deviceModel: String? = null,
@@ -442,6 +479,9 @@ internal data class GlassesStatusUpdate(
442
479
  val controllerBatteryLevel: Int? = null,
443
480
  val controllerSignalStrength: Int? = null,
444
481
  val ringSignalStrength: Int? = null,
482
+ val pairingState: Map<String, Any>? = null,
483
+ /** Explicit `GlassesAudioSetupState` map. When absent, an update that sets [fullyBooted] carries the matching state. */
484
+ val audioSetup: Map<String, Any>? = null,
445
485
  ) {
446
486
  internal fun toMap(): Map<String, Any> =
447
487
  buildMap {
@@ -458,6 +498,8 @@ internal data class GlassesStatusUpdate(
458
498
  putIfNotNull("micEnabled", micEnabled)
459
499
  putIfNotNull("voiceActivityDetectionEnabled", voiceActivityDetectionEnabled)
460
500
  putIfNotNull("bluetoothClassicConnected", bluetoothClassicConnected)
501
+ putIfNotNull("bluetoothClassicProfilesConnected", bluetoothClassicProfilesConnected)
502
+ putIfNotNull("bluetoothAudioRouted", bluetoothAudioRouted)
461
503
  putIfNotNull("signalStrength", signalStrength)
462
504
  putIfNotNull("signalStrengthUpdatedAt", signalStrengthUpdatedAt)
463
505
  putIfNotNull("deviceModel", deviceModel)
@@ -498,6 +540,10 @@ internal data class GlassesStatusUpdate(
498
540
  putIfNotNull("controllerBatteryLevel", controllerBatteryLevel)
499
541
  putIfNotNull("controllerSignalStrength", controllerSignalStrength)
500
542
  putIfNotNull("ringSignalStrength", ringSignalStrength)
543
+ pairingState?.let { put("pairingState", it) }
544
+ (audioSetup ?: fullyBooted?.let { GlassesAudioSetupPolicy.state(it).toMap() })?.let {
545
+ put("audioSetup", it)
546
+ }
501
547
  }
502
548
 
503
549
  companion object {
@@ -509,6 +555,8 @@ internal data class GlassesStatusUpdate(
509
555
  voiceActivityDetectionEnabled = optionalBoolValue(values, "voiceActivityDetectionEnabled"),
510
556
  connectionState = GlassesConnectionState.optionalFromValue(optionalStringValue(values, "connectionState")),
511
557
  bluetoothClassicConnected = optionalBoolValue(values, "bluetoothClassicConnected"),
558
+ bluetoothClassicProfilesConnected = optionalBoolValue(values, "bluetoothClassicProfilesConnected"),
559
+ bluetoothAudioRouted = optionalBoolValue(values, "bluetoothAudioRouted"),
512
560
  signalStrength = optionalNumberValue(values, "signalStrength"),
513
561
  signalStrengthUpdatedAt = optionalLongValue(values, "signalStrengthUpdatedAt"),
514
562
  deviceModel = optionalStringValue(values, "deviceModel"),
@@ -559,6 +607,8 @@ internal data class GlassesStatusUpdate(
559
607
  controllerBatteryLevel = optionalNumberValue(values, "controllerBatteryLevel"),
560
608
  controllerSignalStrength = optionalNumberValue(values, "controllerSignalStrength"),
561
609
  ringSignalStrength = optionalNumberValue(values, "ringSignalStrength"),
610
+ pairingState = pairingStateValue(values),
611
+ audioSetup = audioSetupValue(values),
562
612
  )
563
613
  }
564
614
  }
@@ -0,0 +1,16 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.content.Context
4
+
5
+ /** Release builds register no receiver and expose no lifecycle control surface. */
6
+ @Suppress("UNUSED_PARAMETER")
7
+ internal object NimoResourceDiagnostics {
8
+ fun start(context: Context) {}
9
+ fun track(instance: Nimo) {}
10
+ fun dispatchCapturedEntry(entry: () -> Unit) = false
11
+ fun allowManagerConnect(wearable: String, name: String? = null) = true
12
+ fun preserveCapturedScan(wearable: String, name: String) = false
13
+ fun admit(instance: Nimo, name: String?, connect: Boolean) = true
14
+ fun allowPeer(instance: Nimo, address: String, bonded: Boolean) = true
15
+ fun beginTransport(instance: Nimo, address: String, bonded: Boolean) = true
16
+ }
@@ -0,0 +1,146 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import android.content.Context
4
+ import androidx.test.core.app.ApplicationProvider
5
+ import com.mentra.bluetoothsdk.sgcs.MentraLivePairingState
6
+ import com.mentra.bluetoothsdk.sgcs.MentraLivePairingStateMachine
7
+ import com.mentra.bluetoothsdk.sgcs.MentraLivePairingStateStore
8
+ import org.junit.After
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertFalse
11
+ import org.junit.Assert.assertTrue
12
+ import org.junit.Before
13
+ import org.junit.Test
14
+ import org.junit.runner.RunWith
15
+ import org.robolectric.RobolectricTestRunner
16
+ import org.robolectric.annotation.Config
17
+ import org.robolectric.annotation.LooperMode
18
+
19
+ @RunWith(RobolectricTestRunner::class)
20
+ @Config(sdk = [33])
21
+ @LooperMode(LooperMode.Mode.PAUSED)
22
+ class DeviceManagerOwnerLossTest {
23
+ private val device = "MENTRA_LIVE_BLE_ABCD"
24
+ private lateinit var savedBluetooth: Map<String, Any>
25
+ private lateinit var savedGlasses: Map<String, Any>
26
+
27
+ @Before fun setUp() {
28
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
29
+ savedBluetooth = DeviceStore.store.getCategory("bluetooth")
30
+ savedGlasses = DeviceStore.store.getCategory("glasses")
31
+ prefs().edit().clear().commit()
32
+ MentraLivePairingStateStore.resetForTest()
33
+ }
34
+
35
+ @After fun tearDown() {
36
+ MentraLivePairingStateStore.resetForTest()
37
+ prefs().edit().clear().commit()
38
+ restore("bluetooth", savedBluetooth)
39
+ restore("glasses", savedGlasses)
40
+ }
41
+
42
+ @Test fun `forgetting glasses clears the saved secure firmware flag`() {
43
+ val manager = DeviceManager(initializeHardware = false)
44
+ try {
45
+ DeviceStore.set("bluetooth", "mentra_live_secure_firmware", true)
46
+ manager.clearSecureFirmware()
47
+ assertFalse(DeviceStore.store.get("bluetooth", "mentra_live_secure_firmware") as Boolean)
48
+ } finally {
49
+ manager.cleanup()
50
+ }
51
+ }
52
+
53
+ @Test fun `bluetooth-on still reaches the manager while rejected so Pair Again stays possible`() {
54
+ val manager = DeviceManager(initializeHardware = false)
55
+ try {
56
+ DeviceStore.set("bluetooth", "default_wearable", "Mentra Live")
57
+ DeviceStore.set("bluetooth", "device_name", device)
58
+ rejectViaFlagOffNotice()
59
+ assertTrue(manager.shouldReconnectAfterBluetoothOn())
60
+ } finally {
61
+ manager.cleanup()
62
+ }
63
+ }
64
+
65
+ @Test fun `a pause and its window id survive a process restart`() {
66
+ MentraLivePairingStateStore.ensureRestored(device)
67
+ val now = System.currentTimeMillis()
68
+ MentraLivePairingStateStore.update("test") {
69
+ it.onEnteringPairingMode(120_000L, 99, true, false, device, now)
70
+ }
71
+ assertTrue(MentraLivePairingStateStore.isPaused)
72
+
73
+ MentraLivePairingStateStore.resetForTest()
74
+ assertEquals(MentraLivePairingState.Normal, MentraLivePairingStateStore.state)
75
+ MentraLivePairingStateStore.ensureRestored(device)
76
+
77
+ val state = MentraLivePairingStateStore.state as MentraLivePairingState.PairingMode
78
+ assertEquals(99, state.windowId)
79
+ assertEquals(now + 150_000L, state.endsAtMs)
80
+ @Suppress("UNCHECKED_CAST")
81
+ val published = DeviceStore.store.get("glasses", "pairingState") as Map<String, Any>
82
+ assertEquals("pairing_mode", published["state"])
83
+ assertEquals(99, published["windowId"])
84
+ }
85
+
86
+ @Test fun `a rejection survives a restart and is not touched by the replayed owner-lost setting`() {
87
+ MentraLivePairingStateStore.ensureRestored(device)
88
+ rejectViaFlagOffNotice()
89
+ // The old app replays mentra_live_owner_lost=false; that must not clear the native state.
90
+ DeviceStore.set("bluetooth", "mentra_live_owner_lost", false)
91
+ MentraLivePairingStateStore.resetForTest()
92
+ MentraLivePairingStateStore.ensureRestored(device)
93
+ assertTrue(MentraLivePairingStateStore.isRejected)
94
+ assertFalse(MentraLivePairingStateStore.allowsAutomaticReconnect)
95
+ }
96
+
97
+ @Test fun `forget clears pairing_rejected and the pre-v4 owner-lost setting`() {
98
+ val manager = DeviceManager(initializeHardware = false)
99
+ try {
100
+ MentraLivePairingStateStore.ensureRestored(device)
101
+ rejectViaFlagOffNotice()
102
+ DeviceStore.set("bluetooth", "mentra_live_owner_lost", true)
103
+ manager.clearPairingStateOnForget()
104
+ assertEquals(MentraLivePairingState.Normal, MentraLivePairingStateStore.state)
105
+ assertFalse(DeviceStore.store.get("bluetooth", "mentra_live_owner_lost") as Boolean)
106
+ MentraLivePairingStateStore.resetForTest()
107
+ MentraLivePairingStateStore.ensureRestored(device)
108
+ assertEquals(MentraLivePairingState.Normal, MentraLivePairingStateStore.state)
109
+ } finally {
110
+ manager.cleanup()
111
+ }
112
+ }
113
+
114
+ @Test fun `rollback tolerance - legacy keys migrate and unknown keys are ignored`() {
115
+ prefs()
116
+ .edit()
117
+ .putString(MentraLivePairingStateMachine.LEGACY_REJECTION_PHASE_KEY, "inside")
118
+ .putLong("pairing_yield_until_wall_ms", System.currentTimeMillis() + 60_000L)
119
+ .putString("pairing_v9_unknown", "x")
120
+ .commit()
121
+ MentraLivePairingStateStore.ensureRestored(device)
122
+ assertTrue(MentraLivePairingStateStore.isRejected)
123
+ // Legacy keys are removed after migration so an older build cannot re-apply them.
124
+ assertFalse(prefs().contains(MentraLivePairingStateMachine.LEGACY_REJECTION_PHASE_KEY))
125
+ assertFalse(prefs().contains("pairing_yield_until_wall_ms"))
126
+ assertTrue(prefs().contains("pairing_v9_unknown"))
127
+ }
128
+
129
+ private fun rejectViaFlagOffNotice() {
130
+ MentraLivePairingStateStore.update("test") {
131
+ it.onEnteringPairingMode(120_000L, null, false, false, device, System.currentTimeMillis())
132
+ }
133
+ assertTrue(MentraLivePairingStateStore.isRejected)
134
+ }
135
+
136
+ private fun prefs() =
137
+ ApplicationProvider.getApplicationContext<Context>()
138
+ .getSharedPreferences("mentra_live_owner", Context.MODE_PRIVATE)
139
+
140
+ private fun restore(category: String, saved: Map<String, Any>) {
141
+ (DeviceStore.store.getCategory(category).keys - saved.keys).forEach {
142
+ DeviceStore.store.remove(category, it)
143
+ }
144
+ saved.forEach { (key, value) -> DeviceStore.set(category, key, value) }
145
+ }
146
+ }
@@ -0,0 +1,51 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertNull
6
+ import org.junit.Test
7
+
8
+ class GlassesStatusAudioSetupTest {
9
+ private val notApplicable = mapOf("state" to "not_applicable")
10
+ private val idle = mapOf("state" to "idle")
11
+
12
+ @Test
13
+ fun `a ready snapshot carries not_applicable`() {
14
+ val status = GlassesStatus.fromMap(mapOf("fullyBooted" to true, "connected" to true))
15
+ assertEquals(notApplicable, status.audioSetup)
16
+ assertEquals(notApplicable, status.toMap()["audioSetup"])
17
+ }
18
+
19
+ @Test
20
+ fun `a snapshot without a ready session carries idle`() {
21
+ assertEquals(idle, GlassesStatus.fromMap(mapOf("fullyBooted" to false)).toMap()["audioSetup"])
22
+ // Connected but not yet ready (for example parked for the owner commit) is still idle.
23
+ assertEquals(
24
+ idle,
25
+ GlassesStatus.fromMap(mapOf("fullyBooted" to false, "connected" to true)).toMap()["audioSetup"],
26
+ )
27
+ assertEquals(idle, GlassesStatus.fromMap(emptyMap()).toMap()["audioSetup"])
28
+ }
29
+
30
+ @Test
31
+ fun `audioSetup follows readiness, never a stored copy`() {
32
+ // Even if something wrote a stale value, the snapshot reports the readiness rule.
33
+ val status = GlassesStatus.fromMap(mapOf("fullyBooted" to true, "audioSetup" to idle))
34
+ assertEquals(notApplicable, status.toMap()["audioSetup"])
35
+ }
36
+
37
+ @Test
38
+ fun `an update that marks the glasses ready carries not_applicable in the same update`() {
39
+ assertEquals(notApplicable, GlassesStatusUpdate(fullyBooted = true).toMap()["audioSetup"])
40
+ assertEquals(idle, GlassesStatusUpdate(fullyBooted = false).toMap()["audioSetup"])
41
+ assertFalse(GlassesStatusUpdate(batteryLevel = 50).toMap().containsKey("audioSetup"))
42
+ }
43
+
44
+ @Test
45
+ fun `update maps keep only a known audio setup state`() {
46
+ val needsUser = mapOf("state" to "needs_user", "action" to "connect_in_settings")
47
+ assertEquals(needsUser, GlassesStatusUpdate.fromMap(mapOf("audioSetup" to needsUser)).audioSetup)
48
+ assertNull(GlassesStatusUpdate.fromMap(mapOf("audioSetup" to mapOf("state" to "bogus"))).audioSetup)
49
+ assertNull(GlassesStatusUpdate.fromMap(mapOf("audioSetup" to "connected")).audioSetup)
50
+ }
51
+ }
@@ -10,5 +10,7 @@ class GlassesStatusClassicAudioTest {
10
10
  GlassesStatus.fromMap(mapOf("bluetoothClassicConnected" to true)).toMap()
11
11
 
12
12
  assertThat(serialized["bluetoothClassicConnected"]).isEqualTo(true)
13
+ assertThat(serialized["bluetoothClassicProfilesConnected"]).isEqualTo(true)
14
+ assertThat(serialized["bluetoothAudioRouted"]).isEqualTo(true)
13
15
  }
14
16
  }
@@ -0,0 +1,112 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import androidx.test.core.app.ApplicationProvider
4
+ import com.mentra.bluetoothsdk.sgcs.G1PairingTest
5
+ import com.mentra.bluetoothsdk.sgcs.MentraLive
6
+ import java.util.concurrent.ConcurrentLinkedQueue
7
+ import com.mentra.bluetoothsdk.utils.K900ProtocolUtils
8
+ import com.mentra.bluetoothsdk.utils.K900LengthCodec
9
+ import org.robolectric.annotation.Implementation
10
+ import org.robolectric.annotation.Implements
11
+ import org.robolectric.shadow.api.Shadow
12
+ import org.robolectric.util.ReflectionHelpers.ClassParameter
13
+ import java.util.concurrent.atomic.AtomicLong
14
+ import org.json.JSONObject
15
+ import org.junit.Assert.*
16
+ import org.junit.Test
17
+ import org.junit.runner.RunWith
18
+ import org.robolectric.RobolectricTestRunner
19
+ import org.robolectric.annotation.Config
20
+
21
+ @RunWith(RobolectricTestRunner::class)
22
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class, TouchGestureCommandTest.ShadowK900Encoder::class], instrumentedPackages = ["com.mentra.lc3Lib"])
23
+ class TouchGestureCommandTest {
24
+ @Implements(K900ProtocolUtils::class)
25
+ class ShadowK900Encoder {
26
+ companion object {
27
+ var beforeEncode: (() -> Unit)? = null
28
+ @JvmStatic
29
+ @Implementation
30
+ fun packDataToK900(data: ByteArray, cmdType: Byte, endian: K900LengthCodec.Endian): ByteArray? {
31
+ beforeEncode?.invoke()
32
+ return Shadow.directlyOn(K900ProtocolUtils::class.java, "packDataToK900",
33
+ ClassParameter.from(ByteArray::class.java, data),
34
+ ClassParameter.from(Byte::class.javaPrimitiveType!!, cmdType),
35
+ ClassParameter.from(K900LengthCodec.Endian::class.java, endian))
36
+ }
37
+ }
38
+ }
39
+
40
+ @Test
41
+ fun `disconnect during encoding cannot promote touch setting into next session`() {
42
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
43
+ val live = MentraLive()
44
+ val connection = MentraLive::class.java.getDeclaredField("isConnected").apply { isAccessible = true }
45
+ connection.setBoolean(live, true)
46
+ val queue = MentraLive::class.java.getDeclaredField("sendQueue").apply { isAccessible = true }
47
+ .get(live) as ConcurrentLinkedQueue<*>
48
+ val generation = MentraLive::class.java.getDeclaredField("bleSessionGeneration").apply { isAccessible = true }
49
+ .get(live) as AtomicLong
50
+ val admittedGeneration = generation.get()
51
+ val reset = MentraLive::class.java.getDeclaredMethod("resetPendingAckState").apply { isAccessible = true }
52
+ ShadowK900Encoder.beforeEncode = {
53
+ connection.setBoolean(live, false)
54
+ reset.invoke(live)
55
+ queue.clear()
56
+ connection.setBoolean(live, true)
57
+ }
58
+ try {
59
+ live.sendTouchGestureDefaultBehaviorEnabled("old-session", TouchGesture.DOUBLE_TAP, false)
60
+ val queued = queue.poll()!!
61
+ val queuedGeneration = queued.javaClass.getDeclaredField("sessionGeneration").apply { isAccessible = true }.getLong(queued)
62
+ assertEquals(admittedGeneration, queuedGeneration)
63
+ assertNotEquals(generation.get(), queuedGeneration)
64
+ } finally { ShadowK900Encoder.beforeEncode = null }
65
+ }
66
+
67
+ @Test
68
+ fun `each gesture serializes independently and acknowledgements retain typed event values`() {
69
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
70
+ val live = MentraLive()
71
+ val connection = MentraLive::class.java.getDeclaredField("isConnected").apply { isAccessible = true }
72
+ connection.setBoolean(live, true)
73
+ val queue = MentraLive::class.java.getDeclaredField("sendQueue").apply { isAccessible = true }
74
+ .get(live) as ConcurrentLinkedQueue<*>
75
+ val receive = MentraLive::class.java.getDeclaredMethod("processK900JsonMessage", JSONObject::class.java)
76
+ .apply { isAccessible = true }
77
+ val events = mutableListOf<Map<String, Any>>()
78
+ val sink = Bridge.addEventSink { name, values -> if (name == "settings_ack") events.add(values) }
79
+ try {
80
+ for (gesture in TouchGesture.entries) for (enabled in listOf(false, true)) {
81
+ live.sendTouchGestureDefaultBehaviorEnabled("request-${gesture.wireName}-$enabled", gesture, enabled)
82
+ val queued = queue.poll()!!
83
+ val bytes = queued.javaClass.getDeclaredField("data").apply { isAccessible = true }.get(queued) as ByteArray
84
+ assertEquals('#'.code.toByte(), bytes[0])
85
+ assertEquals('$'.code.toByte(), bytes.last())
86
+ val envelope = JSONObject(String(bytes, 5, bytes.size - 7, Charsets.UTF_8))
87
+ assertEquals("cs_tpdef", envelope.getString("C"))
88
+ val body = JSONObject(envelope.getString("B"))
89
+ assertEquals(gesture.wireName, body.getString("gesture"))
90
+ assertEquals(enabled, body.getBoolean("enabled"))
91
+ val ack = JSONObject().put("type", "settings_ack").put("setting", "touch_gesture_default")
92
+ .put("status", "applied").put("request_id", body.getString("request_id"))
93
+ .put("gesture", gesture.wireName).put("enabled", enabled)
94
+ receive.invoke(live, JSONObject().put("C", "sr_tpdef").put("B", if (enabled) ack.toString() else ack))
95
+ assertEquals(body.getString("request_id"), events.last()["requestId"])
96
+ assertEquals(enabled, events.last()["enabled"])
97
+ assertEquals(gesture.wireName, events.last()["gesture"])
98
+ }
99
+ assertEquals(16, events.size)
100
+ } finally { Bridge.removeEventSink(sink) }
101
+ }
102
+
103
+ @Test
104
+ fun `invalid gesture and disconnected radio reject before sending`() {
105
+ assertThrows(BluetoothSdkException::class.java) { TouchGesture.fromWireName("unknown") }
106
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
107
+ val live = MentraLive()
108
+ assertThrows(BluetoothSdkException::class.java) {
109
+ live.sendTouchGestureDefaultBehaviorEnabled("request", TouchGesture.DOUBLE_TAP, false)
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,19 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import com.mentra.bluetoothsdk.sgcs.MentraLive
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertTrue
6
+ import org.junit.Test
7
+
8
+ class WifiAdbPeerIntentTest {
9
+ private val mac = "AA:BB:CC:DD:EE:01"
10
+ @Test fun onlyFullCurrentSessionIdentityCanAdmitACommand() {
11
+ assertTrue(MentraLive.wifiAdbPeerMatches(mac.lowercase(), 7L to mac, 7L, true))
12
+ assertFalse(MentraLive.wifiAdbPeerMatches(mac, 7L to "AA:BB:CC:DD:EE:02", 7L, true))
13
+ assertFalse(MentraLive.wifiAdbPeerMatches(mac, 6L to mac, 7L, true))
14
+ assertFalse(MentraLive.wifiAdbPeerMatches(mac, null, 7L, true))
15
+ assertFalse(MentraLive.wifiAdbPeerMatches(mac, 7L to mac, 7L, false))
16
+ assertFalse(MentraLive.wifiAdbPeerMatches("EE:01", 7L to mac, 7L, true))
17
+ assertFalse(MentraLive.wifiAdbPeerMatches(" " + mac, 7L to mac, 7L, true))
18
+ }
19
+ }
@@ -0,0 +1,65 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import org.json.JSONObject
4
+ import org.junit.Assert.assertEquals
5
+ import org.junit.Assert.assertNull
6
+ import org.junit.Test
7
+
8
+ class GlassesAudioSetupPolicyTest {
9
+ @Test
10
+ fun `android needs no user step on any model - not_applicable when ready, idle otherwise`() {
11
+ assertEquals(GlassesAudioSetupState.NOT_APPLICABLE, GlassesAudioSetupPolicy.state(ready = true))
12
+ assertEquals(GlassesAudioSetupState.IDLE, GlassesAudioSetupPolicy.state(ready = false))
13
+ }
14
+
15
+ @Test
16
+ fun `states encode as the shared map shape`() {
17
+ assertEquals(mapOf("state" to "idle"), GlassesAudioSetupState.IDLE.toMap())
18
+ assertEquals(mapOf("state" to "not_applicable"), GlassesAudioSetupState.NOT_APPLICABLE.toMap())
19
+ assertEquals(mapOf("state" to "connecting"), GlassesAudioSetupState.CONNECTING.toMap())
20
+ assertEquals(mapOf("state" to "connected"), GlassesAudioSetupState.CONNECTED.toMap())
21
+ assertEquals(
22
+ mapOf("state" to "needs_user", "action" to "connect_in_settings"),
23
+ GlassesAudioSetupState.NEEDS_USER.toMap(),
24
+ )
25
+ }
26
+
27
+ @Test
28
+ fun `every state round-trips and unknown values are rejected`() {
29
+ for (state in GlassesAudioSetupState.values()) {
30
+ assertEquals(state, GlassesAudioSetupState.fromMap(state.toMap()))
31
+ }
32
+ assertNull(GlassesAudioSetupState.fromMap(mapOf("state" to "paired")))
33
+ assertNull(GlassesAudioSetupState.fromMap(mapOf("action" to "connect_in_settings")))
34
+ assertNull(GlassesAudioSetupState.fromMap("not_applicable"))
35
+ assertNull(GlassesAudioSetupState.fromMap(null))
36
+ }
37
+
38
+ @Test
39
+ fun `audio_setup_changed fires only when readiness changes the state`() {
40
+ assertEquals(GlassesAudioSetupState.NOT_APPLICABLE, GlassesAudioSetupPolicy.change(wasReady = false, ready = true))
41
+ assertEquals(GlassesAudioSetupState.IDLE, GlassesAudioSetupPolicy.change(wasReady = true, ready = false))
42
+ assertNull(GlassesAudioSetupPolicy.change(wasReady = true, ready = true))
43
+ assertNull(GlassesAudioSetupPolicy.change(wasReady = false, ready = false))
44
+ }
45
+
46
+ @Test
47
+ fun `classic_link reads both links and tolerates missing or odd fields`() {
48
+ assertEquals(
49
+ MentraLiveClassicLink(a2dp = true, hfp = false),
50
+ MentraLiveClassicLink.parse(JSONObject("""{"type":"classic_link","a2dp":true,"hfp":false}""")),
51
+ )
52
+ assertEquals(
53
+ MentraLiveClassicLink(a2dp = false, hfp = true),
54
+ MentraLiveClassicLink.parse(JSONObject("""{"type":"classic_link","a2dp":false,"hfp":true}""")),
55
+ )
56
+ assertEquals(
57
+ MentraLiveClassicLink(a2dp = false, hfp = false),
58
+ MentraLiveClassicLink.parse(JSONObject("""{"type":"classic_link"}""")),
59
+ )
60
+ assertEquals(
61
+ MentraLiveClassicLink(a2dp = false, hfp = false),
62
+ MentraLiveClassicLink.parse(JSONObject("""{"type":"classic_link","a2dp":"up","hfp":null}""")),
63
+ )
64
+ }
65
+ }