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

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,231 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.bluetooth.BluetoothAdapter
4
+ import android.bluetooth.BluetoothDevice
5
+ import android.bluetooth.BluetoothGattCallback
6
+ import android.bluetooth.BluetoothGattCharacteristic
7
+ import android.os.Looper
8
+ import androidx.test.core.app.ApplicationProvider
9
+ import com.mentra.bluetoothsdk.Bridge
10
+ import com.mentra.bluetoothsdk.DeviceManager
11
+ import com.mentra.bluetoothsdk.DeviceStore
12
+ import com.mentra.bluetoothsdk.GlassesStatus
13
+ import java.time.Duration
14
+ import java.util.UUID
15
+ import java.util.concurrent.CopyOnWriteArrayList
16
+ import org.json.JSONObject
17
+ import org.junit.Assert.assertEquals
18
+ import org.junit.Assert.assertFalse
19
+ import org.junit.Assert.assertNotNull
20
+ import org.junit.Assert.assertNull
21
+ import org.junit.Assert.assertTrue
22
+ import org.junit.Test
23
+ import org.junit.runner.RunWith
24
+ import org.robolectric.RobolectricTestRunner
25
+ import org.robolectric.Shadows.shadowOf
26
+ import org.robolectric.annotation.Config
27
+ import org.robolectric.annotation.LooperMode
28
+
29
+ /**
30
+ * Drives [MentraLive]'s real BLE message handling and the shared status layer: audioSetup in
31
+ * the ready snapshot, the unknown-capability readiness wait, the selected-row secure rule, the
32
+ * secure firmware refresh, and the `classic_link` message.
33
+ */
34
+ @RunWith(RobolectricTestRunner::class)
35
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class], instrumentedPackages = ["com.mentra.lc3Lib"])
36
+ @LooperMode(LooperMode.Mode.PAUSED)
37
+ class MentraLiveAudioSetupReadinessTest {
38
+ private val targetName = "MENTRA_LIVE_BLE_AUDIOSETUP"
39
+ private val targetAddress = "AA:BB:CC:DD:EE:42"
40
+
41
+ @Test fun `readiness and audioSetup arrive in one snapshot and audio_setup_changed fires once`() =
42
+ withLive(selectedCapability = false) { live, events ->
43
+ val snapshots = CopyOnWriteArrayList<Map<String, Any>>()
44
+ val listener =
45
+ DeviceStore.store.addListener { category, _ ->
46
+ if (category == "glasses") snapshots.add(glassesSnapshot())
47
+ }
48
+ try {
49
+ message(live, """{"type":"glasses_ready"}""")
50
+ } finally {
51
+ DeviceStore.store.removeListener(listener)
52
+ }
53
+ assertTrue(ready())
54
+ val readySnapshots = snapshots.filter { it["connection"].let { c -> (c as Map<*, *>)["fullyBooted"] == true } }
55
+ assertTrue(readySnapshots.isNotEmpty())
56
+ // Never "ready" with a stale idle.
57
+ readySnapshots.forEach { assertEquals(mapOf("state" to "not_applicable"), it["audioSetup"]) }
58
+ assertEquals(listOf(mapOf("state" to "not_applicable")), audioSetupEvents(events))
59
+
60
+ // A repeated ready report is not a change.
61
+ message(live, """{"type":"glasses_ready"}""")
62
+ assertEquals(1, audioSetupEvents(events).size)
63
+
64
+ DeviceStore.apply("glasses", "fullyBooted", false)
65
+ assertEquals(mapOf("state" to "idle"), glassesSnapshot()["audioSetup"])
66
+ assertEquals(
67
+ listOf(mapOf("state" to "not_applicable"), mapOf("state" to "idle")),
68
+ audioSetupEvents(events),
69
+ )
70
+ }
71
+
72
+ @Test fun `unknown capability without pairing_info is reported ready after 5 s as legacy`() =
73
+ withLive(selectedCapability = "") { live, _ ->
74
+ message(live, """{"type":"glasses_ready"}""")
75
+ assertFalse(ready())
76
+ assertEquals(mapOf("state" to "idle"), glassesSnapshot()["audioSetup"])
77
+ idle(MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS - 100)
78
+ assertFalse(ready())
79
+ idle(200)
80
+ assertTrue(ready())
81
+ assertEquals(mapOf("state" to "not_applicable"), glassesSnapshot()["audioSetup"])
82
+ assertNull(get(live, "secureBondWaitRunnable"))
83
+ }
84
+
85
+ @Test fun `unknown capability with a secure pairing_info follows the owner commit rule`() =
86
+ withLive(selectedCapability = "") { live, _ ->
87
+ message(live, """{"type":"glasses_ready"}""")
88
+ message(live, pairingInfo(secure = true, ownerCommitted = false))
89
+ assertFalse(ready())
90
+ // The secure rule runs its own deadline instead of the 5 s legacy fallback.
91
+ assertNotNull(get(live, "secureBondWaitRunnable"))
92
+ idle(MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS + 1_000)
93
+ assertFalse(ready())
94
+
95
+ shadowOf(device()).setBondState(BluetoothDevice.BOND_BONDED)
96
+ message(live, pairingInfo(secure = true, ownerCommitted = true))
97
+ assertTrue(ready())
98
+ assertNull(get(live, "secureBondWaitRunnable"))
99
+ }
100
+
101
+ @Test fun `unknown capability with a legacy pairing_info is ready at once`() =
102
+ withLive(selectedCapability = "") { live, _ ->
103
+ message(live, """{"type":"glasses_ready"}""")
104
+ assertFalse(ready())
105
+ message(live, pairingInfo(secure = false, ownerCommitted = false))
106
+ assertTrue(ready())
107
+ }
108
+
109
+ @Test fun `a legacy row is not secure even if its address advertised the trailer before`() =
110
+ withLive(selectedCapability = false) { live, _ ->
111
+ trailerMemory().noteSecureTrailer(targetAddress)
112
+ try {
113
+ message(live, """{"type":"glasses_ready"}""")
114
+ assertTrue(ready())
115
+ assertNull(get(live, "secureBondWaitRunnable"))
116
+ } finally {
117
+ trailerMemory().onScanStart()
118
+ }
119
+ }
120
+
121
+ @Test fun `a ready session without pairing_info clears the secure firmware memory after 15 s`() =
122
+ withLive(selectedCapability = false) { live, _ ->
123
+ DeviceStore.set("bluetooth", "mentra_live_secure_firmware", true)
124
+ message(live, """{"type":"glasses_ready"}""")
125
+ idle(MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS - 100)
126
+ assertEquals(true, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
127
+ idle(200)
128
+ assertEquals(false, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
129
+ }
130
+
131
+ @Test fun `a secure pairing_info keeps the secure firmware memory`() =
132
+ withLive(selectedCapability = true) { live, _ ->
133
+ DeviceStore.set("bluetooth", "mentra_live_secure_firmware", false)
134
+ message(live, pairingInfo(secure = true, ownerCommitted = false))
135
+ message(live, """{"type":"glasses_ready"}""")
136
+ idle(MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS + 1_000)
137
+ assertEquals(true, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
138
+ }
139
+
140
+ @Test fun `classic_link is accepted and logged`() =
141
+ withLive(selectedCapability = false) { live, events ->
142
+ message(live, """{"type":"classic_link","a2dp":true,"hfp":false}""")
143
+ message(live, """{"type":"classic_link"}""")
144
+ val logs = events.filter { it.first == "log" }.map { it.second["message"].toString() }
145
+ assertTrue(logs.any { it.contains("LIVE: classic_link a2dp=true hfp=false") })
146
+ assertTrue(logs.any { it.contains("LIVE: classic_link a2dp=false hfp=false") })
147
+ assertFalse(ready())
148
+ }
149
+
150
+ private fun withLive(
151
+ selectedCapability: Any,
152
+ body: (MentraLive, MutableList<Pair<String, Map<String, Any>>>) -> Unit,
153
+ ) {
154
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
155
+ val saved = listOf("bluetooth", "glasses").associateWith { DeviceStore.store.getCategory(it) }
156
+ val singleton = DeviceManager::class.java.getDeclaredField("_instance").apply { isAccessible = true }
157
+ val previous = singleton.get(null)
158
+ val manager = DeviceManager(initializeHardware = false)
159
+ singleton.set(null, manager)
160
+ MentraLivePairingStateStore.resetForTest()
161
+ DeviceStore.set("glasses", "fullyBooted", false)
162
+ DeviceStore.set("bluetooth", "pending_device_name", targetName)
163
+ DeviceStore.set("bluetooth", "pending_device_address", targetAddress)
164
+ DeviceStore.set("bluetooth", "pending_device_secure_pairing_capable", selectedCapability)
165
+ val events = CopyOnWriteArrayList<Pair<String, Map<String, Any>>>()
166
+ val sink = Bridge.addEventSink { type, body -> events.add(type to HashMap(body)) }
167
+ val live = MentraLive()
168
+ try {
169
+ link(live)
170
+ body(live, events)
171
+ } finally {
172
+ Bridge.removeEventSink(sink)
173
+ live.destroy()
174
+ shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(2))
175
+ manager.cleanup()
176
+ singleton.set(null, previous)
177
+ MentraLivePairingStateStore.resetForTest()
178
+ saved.forEach { (category, values) ->
179
+ (DeviceStore.store.getCategory(category).keys - values.keys).forEach {
180
+ DeviceStore.store.remove(category, it)
181
+ }
182
+ values.forEach { (key, value) -> DeviceStore.set(category, key, value) }
183
+ }
184
+ }
185
+ }
186
+
187
+ private fun device(): BluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(targetAddress)
188
+
189
+ /** A live GATT link to the pairing target; CTKD is marked started so no Classic work runs. */
190
+ private fun link(live: MentraLive) {
191
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
192
+ val gatt = device().connectGatt(context, false, object : BluetoothGattCallback() {})
193
+ set(live, "isConnected", true)
194
+ set(live, "bluetoothGatt", gatt)
195
+ set(live, "connectedDevice", device())
196
+ set(live, "txCharacteristic", BluetoothGattCharacteristic(UUID.randomUUID(), 0, 0))
197
+ set(live, "ctkdInitiatedThisGattSession", true)
198
+ }
199
+
200
+ private fun message(live: MentraLive, json: String) {
201
+ MentraLive::class.java.getDeclaredMethod("processJsonMessage", JSONObject::class.java)
202
+ .apply { isAccessible = true }
203
+ .invoke(live, JSONObject(json))
204
+ }
205
+
206
+ private fun pairingInfo(secure: Boolean, ownerCommitted: Boolean): String =
207
+ """{"type":"pairing_info","secure_pairing_capable":$secure,"owner_committed":$ownerCommitted}"""
208
+
209
+ private fun ready(): Boolean = DeviceStore.get("glasses", "fullyBooted") == true
210
+
211
+ /** What `glasses_status` sends to JavaScript for the current store. */
212
+ private fun glassesSnapshot(): Map<String, Any> =
213
+ GlassesStatus.fromMap(DeviceStore.store.getCategory("glasses")).toMap()
214
+
215
+ private fun audioSetupEvents(events: List<Pair<String, Map<String, Any>>>): List<Any?> =
216
+ events.filter { it.first == "audio_setup_changed" }.map { it.second["state"] }
217
+
218
+ private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
219
+
220
+ private fun trailerMemory(): MentraLiveSecureTrailerScanMemory =
221
+ MentraLive::class.java.getDeclaredField("secureTrailerScanMemory")
222
+ .apply { isAccessible = true }
223
+ .get(null) as MentraLiveSecureTrailerScanMemory
224
+
225
+ private fun get(live: MentraLive, name: String): Any? =
226
+ MentraLive::class.java.getDeclaredField(name).apply { isAccessible = true }.get(live)
227
+
228
+ private fun set(live: MentraLive, name: String, value: Any?) {
229
+ MentraLive::class.java.getDeclaredField(name).apply { isAccessible = true }.set(live, value)
230
+ }
231
+ }
@@ -0,0 +1,368 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.bluetooth.BluetoothDevice
4
+ import org.junit.Assert.assertEquals
5
+ import org.junit.Assert.assertFalse
6
+ import org.junit.Assert.assertTrue
7
+ import org.junit.Test
8
+
9
+ class MentraLiveOwnerLossPolicyTest {
10
+ @Test
11
+ fun connectTimeRejectionIsAHintOnlyOutsideExplicitPairingOnSecureFirmware() {
12
+ assertTrue(gattRejection(5))
13
+ assertTrue(gattRejection(15))
14
+ assertFalse(gattRejection(5, manualPairing = true))
15
+ }
16
+
17
+ @Test
18
+ fun legacyFirmwareRejectionsAreNeverOwnerLoss() {
19
+ assertFalse(gattRejection(5, secureFirmware = false))
20
+ assertFalse(gattRejection(15, secureFirmware = false))
21
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, secureFirmware = false))
22
+ }
23
+
24
+ @Test
25
+ fun rfDropsAndRemoteTerminationAreNotOwnerLoss() {
26
+ for (status in listOf(8, 19, 22, 62, 133)) {
27
+ assertFalse("status $status", gattRejection(status))
28
+ }
29
+ }
30
+
31
+ @Test
32
+ fun bondDroppedRightAfterAutomaticReconnectIsARejection() {
33
+ assertTrue(bondRemoved(msSinceAutoReconnectLink = 600L))
34
+ }
35
+
36
+ @Test
37
+ fun bondRemovalOutsideAReconnectIsNotARejection() {
38
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = null))
39
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 60_000L))
40
+ }
41
+
42
+ @Test
43
+ fun appUnpairAndExplicitPairingNeverReportOwnerLoss() {
44
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, killed = true))
45
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, unpairInProgress = true))
46
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, manualPairing = true))
47
+ }
48
+
49
+ @Test
50
+ fun aSingleRejectionDoesNotStandDown() {
51
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
52
+ assertFalse(streak.record(0L))
53
+ }
54
+
55
+ @Test
56
+ fun threeQuickRejectionsDoNotStandDownUntilTheStreakSpansAboutAMinute() {
57
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
58
+ assertFalse(streak.record(0L))
59
+ assertFalse(streak.record(3_000L))
60
+ // Third attempt, but a glasses reboot also rejects for a few seconds.
61
+ assertFalse(streak.record(8_000L))
62
+ assertFalse(streak.record(24_000L))
63
+ assertTrue(streak.record(MentraLiveOwnerLossPolicy.MIN_REJECTION_SPAN_MS))
64
+ }
65
+
66
+ @Test
67
+ fun aSuccessfulSessionEndsTheStreak() {
68
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
69
+ streak.record(0L)
70
+ streak.record(10_000L)
71
+ streak.reset()
72
+ assertFalse(streak.record(50_000L))
73
+ assertFalse(streak.record(60_000L))
74
+ }
75
+
76
+ @Test
77
+ fun rejectionsFarApartAreNotOneStreak() {
78
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
79
+ streak.record(0L)
80
+ streak.record(10_000L)
81
+ streak.record(20_000L)
82
+ // A long quiet gap means the earlier rejections were something else.
83
+ val later = 20_000L + MentraLiveOwnerLossPolicy.REJECTION_STREAK_GAP_MS + 1L
84
+ assertFalse(streak.record(later))
85
+ assertFalse(streak.record(later + 10_000L))
86
+ assertFalse(streak.record(later + 20_000L))
87
+ }
88
+
89
+ @Test
90
+ fun oneAttemptReportingTwiceCountsOnce() {
91
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
92
+ val span = MentraLiveOwnerLossPolicy.MIN_REJECTION_SPAN_MS
93
+ // Bond removed, then the GATT disconnect with status 5, for each of two attempts.
94
+ // Counted per signal this would be four rejections over a long enough span.
95
+ assertFalse(streak.record(0L))
96
+ assertFalse(streak.record(400L))
97
+ assertFalse(streak.record(span))
98
+ assertFalse(streak.record(span + 400L))
99
+ // A genuine third attempt completes the streak.
100
+ assertTrue(streak.record(span + 10_000L))
101
+ }
102
+
103
+ @Test
104
+ fun aFailedNewBondIsNotABondRemoval() {
105
+ assertFalse(
106
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnBondRemoved(
107
+ previousBondState = BluetoothDevice.BOND_BONDING,
108
+ bondState = BluetoothDevice.BOND_NONE,
109
+ killed = false,
110
+ unpairInProgress = false,
111
+ manualPairing = false,
112
+ msSinceAutoReconnectLink = 600L,
113
+ secureFirmware = true,
114
+ )
115
+ )
116
+ }
117
+
118
+ @Test
119
+ fun pauseIsTheWindowPlusTheCloseMarginWithNo300sClamp() {
120
+ assertEquals(150_000L, MentraLiveOwnerLossPolicy.yieldMs(120_000L))
121
+ // The glasses own the window: a longer one is paused for in full, not clamped to 300 s.
122
+ assertEquals(930_000L, MentraLiveOwnerLossPolicy.yieldMs(900_000L))
123
+ // A short window is not stretched to a floor either.
124
+ assertEquals(40_000L, MentraLiveOwnerLossPolicy.yieldMs(10_000L))
125
+ // A missing window falls back to the 120 s default.
126
+ assertEquals(150_000L, MentraLiveOwnerLossPolicy.yieldMs(0L))
127
+ }
128
+
129
+ @Test
130
+ fun aRestartedAppKeepsOnlyALiveDeadlineWithinThePersistedPause() {
131
+ val now = 1_000_000L
132
+ val pause = MentraLiveOwnerLossPolicy.yieldMs(120_000L)
133
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(0L, now, pause))
134
+ assertEquals(50_000L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + 50_000L, now, pause))
135
+ assertEquals(pause, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + pause, now, pause))
136
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now - 1L, now, pause))
137
+ // Further out than the pause that was recorded with it: a clock change, not a window.
138
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + pause + 1L, now, pause))
139
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + 1_000L, now, 0L))
140
+ }
141
+
142
+ @Test
143
+ fun theWindowRefusalStatus0x14IsNeverARejection() {
144
+ assertFalse(gattRejection(0x14))
145
+ assertFalse(MentraLiveOwnerLossPolicy.isOwnerRejectionStatus(0x14))
146
+ }
147
+
148
+ @Test
149
+ fun pairSelectGoesOnlyWithAnExplicitAttemptToSecureGlasses() {
150
+ assertTrue(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = true, securePairingTarget = true))
151
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = false, securePairingTarget = true))
152
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = true, securePairingTarget = false))
153
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = false, securePairingTarget = false))
154
+ }
155
+
156
+ @Test
157
+ fun parkedSecureReadinessAlwaysHasABondWaitDeadline() {
158
+ // Nothing (no awaiting_confirm any more) suspends the wait on an explicit secure pair.
159
+ assertTrue(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = true, securePairingTarget = true))
160
+ assertFalse(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = false, securePairingTarget = true))
161
+ assertFalse(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = true, securePairingTarget = false))
162
+ assertEquals(40_000L, MentraLiveOwnerLossPolicy.SECURE_BOND_WAIT_MS)
163
+ }
164
+
165
+ @Test
166
+ fun explicitSecurePairDefersCtkdUntilPairingInfoArrives() {
167
+ assertTrue(
168
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
169
+ explicitPairing = true,
170
+ secureTarget = true,
171
+ bondState = BluetoothDevice.BOND_NONE,
172
+ pairingInfoSeen = false,
173
+ ),
174
+ )
175
+ assertFalse(
176
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
177
+ explicitPairing = true,
178
+ secureTarget = true,
179
+ bondState = BluetoothDevice.BOND_NONE,
180
+ pairingInfoSeen = true,
181
+ ),
182
+ )
183
+ assertFalse(
184
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
185
+ explicitPairing = false,
186
+ secureTarget = true,
187
+ bondState = BluetoothDevice.BOND_NONE,
188
+ pairingInfoSeen = false,
189
+ ),
190
+ )
191
+ }
192
+
193
+ @Test
194
+ fun aClearedPairingFlagOnTheSavedGlassesIsNotHiddenFromThePauseWatchScan() {
195
+ assertFalse(
196
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
197
+ savedGlasses = true,
198
+ reconnectScan = false,
199
+ secureTrailer = true,
200
+ pairingDiscoverable = false,
201
+ )
202
+ )
203
+ assertTrue(
204
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
205
+ savedGlasses = false,
206
+ reconnectScan = false,
207
+ secureTrailer = true,
208
+ pairingDiscoverable = false,
209
+ )
210
+ )
211
+ assertFalse(
212
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
213
+ savedGlasses = false,
214
+ reconnectScan = false,
215
+ secureTrailer = true,
216
+ pairingDiscoverable = true,
217
+ )
218
+ )
219
+ }
220
+
221
+ @Test
222
+ fun automaticReconnectStandsDownWhileTheSavedGlassesAdvertisePairingMode() {
223
+ assertTrue(
224
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
225
+ pairingMode = true,
226
+ savedGlasses = true,
227
+ explicitPairing = false,
228
+ )
229
+ )
230
+ assertFalse(
231
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
232
+ pairingMode = true,
233
+ savedGlasses = true,
234
+ explicitPairing = true,
235
+ )
236
+ )
237
+ assertFalse(
238
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
239
+ pairingMode = false,
240
+ savedGlasses = true,
241
+ explicitPairing = false,
242
+ )
243
+ )
244
+ assertFalse(
245
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
246
+ pairingMode = true,
247
+ savedGlasses = false,
248
+ explicitPairing = false,
249
+ )
250
+ )
251
+ }
252
+
253
+ @Test
254
+ fun secureTargetIsNotReadyUntilBondedAndOwnerCommitted() {
255
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDING, committed = true))
256
+ assertTrue(defer(bond = BluetoothDevice.BOND_NONE, committed = true))
257
+ assertTrue(defer(bond = BluetoothDevice.BOND_NONE, committed = false))
258
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
259
+ assertFalse(defer(secure = false, bond = BluetoothDevice.BOND_NONE, committed = false))
260
+ }
261
+
262
+ @Test
263
+ fun staleBondWithoutOwnerCommitStillDefersAnExplicitSecurePair() {
264
+ // A leftover BOND_BONDED (or a Classic-only bond on the same public address) is not
265
+ // proof that the glasses committed this phone as owner.
266
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDED, committed = false))
267
+ }
268
+
269
+ @Test
270
+ fun bondedAndOwnerCommittedIsNotDeferred() {
271
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
272
+ }
273
+
274
+ @Test
275
+ fun lateOwnerCommitAfterBondAllowsReady() {
276
+ // glasses_ready and the bond arrive first: parked.
277
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDED, committed = false))
278
+ // The late pairing_info carries owner_committed: ready is allowed now.
279
+ assertTrue(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(true))
280
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
281
+ }
282
+
283
+ @Test
284
+ fun pairingInfoWithoutOwnerCommitDoesNotConfirmOwner() {
285
+ assertFalse(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(false))
286
+ assertTrue(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(true))
287
+ }
288
+
289
+ @Test
290
+ fun legacyTargetIsNeverGated() {
291
+ for (bond in listOf(BluetoothDevice.BOND_NONE, BluetoothDevice.BOND_BONDING, null)) {
292
+ for (committed in listOf(true, false)) {
293
+ assertFalse(defer(secure = false, bond = bond, committed = committed))
294
+ assertTrue(audioReady(secure = false, bond = bond, committed = committed))
295
+ }
296
+ }
297
+ }
298
+
299
+ @Test
300
+ fun classicAudioDoesNotCommitAnUnbondedSecurePair() {
301
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_BONDING, committed = false))
302
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_NONE, committed = false))
303
+ assertTrue(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = true))
304
+ }
305
+
306
+ @Test
307
+ fun classicAudioFirstWithoutOwnerCommitDoesNotMarkReadyDuringExplicitPairing() {
308
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = false))
309
+ // Once the commit arrives the same audio-first state may complete.
310
+ assertTrue(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = true))
311
+ }
312
+
313
+ @Test
314
+ fun reconnectOutsideExplicitPairingIsNeverGated() {
315
+ for (bond in listOf(BluetoothDevice.BOND_NONE, BluetoothDevice.BOND_BONDING, null)) {
316
+ for (committed in listOf(true, false)) {
317
+ assertTrue(audioReady(explicit = false, bond = bond, committed = committed))
318
+ }
319
+ }
320
+ }
321
+
322
+ private fun defer(
323
+ secure: Boolean = true,
324
+ bond: Int?,
325
+ committed: Boolean,
326
+ ): Boolean = MentraLiveOwnerLossPolicy.shouldDeferReadyForBond(secure, bond, committed)
327
+
328
+ private fun audioReady(
329
+ explicit: Boolean = true,
330
+ secure: Boolean = true,
331
+ bond: Int?,
332
+ committed: Boolean,
333
+ ): Boolean =
334
+ MentraLiveOwnerLossPolicy.shouldMarkReadyFromAudio(
335
+ explicitPairing = explicit,
336
+ securePairingTarget = secure,
337
+ bondState = bond,
338
+ ownerCommitted = committed,
339
+ )
340
+
341
+ private fun gattRejection(
342
+ status: Int,
343
+ manualPairing: Boolean = false,
344
+ secureFirmware: Boolean = true,
345
+ ): Boolean =
346
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnGattError(
347
+ status,
348
+ manualPairing,
349
+ secureFirmware,
350
+ )
351
+
352
+ private fun bondRemoved(
353
+ msSinceAutoReconnectLink: Long?,
354
+ killed: Boolean = false,
355
+ unpairInProgress: Boolean = false,
356
+ manualPairing: Boolean = false,
357
+ secureFirmware: Boolean = true,
358
+ ): Boolean =
359
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnBondRemoved(
360
+ previousBondState = BluetoothDevice.BOND_BONDED,
361
+ bondState = BluetoothDevice.BOND_NONE,
362
+ killed = killed,
363
+ unpairInProgress = unpairInProgress,
364
+ manualPairing = manualPairing,
365
+ msSinceAutoReconnectLink = msSinceAutoReconnectLink,
366
+ secureFirmware = secureFirmware,
367
+ )
368
+ }
@@ -81,6 +81,26 @@ class MentraLivePairingAdvertisementParserTest {
81
81
  assertFalse(result?.pairingMode == true)
82
82
  }
83
83
 
84
+ @Test
85
+ fun readsTheOwnerChangedFlagAndWindowIdFromTheV4Trailer() {
86
+ val payload = securePayload(pairingFlag = 0)
87
+ payload[6] = 4
88
+ payload[7] = 0x05
89
+ payload[12] = 0xC8.toByte()
90
+ val result = MentraLivePairingAdvertisementParser.parse(payload)
91
+
92
+ assertTrue(result?.ownerChanged == true)
93
+ assertEquals(200, result?.pairingGeneration)
94
+ assertFalse(result?.pairingMode == true)
95
+ }
96
+
97
+ @Test
98
+ fun ownerChangedIsFalseWithoutTheFlag() {
99
+ val result = MentraLivePairingAdvertisementParser.parse(securePayload(pairingFlag = 1))
100
+
101
+ assertFalse(result?.ownerChanged == true)
102
+ }
103
+
84
104
  @Test
85
105
  fun rejectsLegacyPayloadThatMatchesOldVersionCapabilityHeuristic() {
86
106
  val legacyPayload = ByteArray(27)