@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
@@ -59,6 +59,17 @@ class NimoLifecycleTest {
59
59
  private var listener: String? = null
60
60
 
61
61
  @Before fun setup() {
62
+ // Each Robolectric case has a new app/files directory; simulate its fresh process
63
+ // rather than retaining the preceding test's registered receiver and output root.
64
+ val collaborator = NimoResourceDiagnostics::class.java
65
+ collaborator.getDeclaredField("capture").apply { isAccessible = true }.set(NimoResourceDiagnostics, null)
66
+ collaborator.getDeclaredField("registered").apply { isAccessible = true }.setBoolean(NimoResourceDiagnostics, false)
67
+ collaborator.getDeclaredField("application").apply { isAccessible = true }.set(NimoResourceDiagnostics, null)
68
+ for (name in listOf("sessions", "requests")) {
69
+ val value = collaborator.getDeclaredField(name).apply { isAccessible = true }.get(NimoResourceDiagnostics)
70
+ if (value is MutableMap<*, *>) value.clear()
71
+ if (value is MutableSet<*>) value.clear()
72
+ }
62
73
  context = TrackingContext(ApplicationProvider.getApplicationContext())
63
74
  Bridge.initialize(context)
64
75
  manager = DeviceManager(initializeHardware = false)
@@ -109,6 +120,63 @@ class NimoLifecycleTest {
109
120
  .set(null, previousManager)
110
121
  }
111
122
 
123
+ @Test fun monotonicSnapshotRetainsOriginalAdmissionWhenWallMarkersJumpBothDirections() {
124
+ val armed = android.os.SystemClock.elapsedRealtime()
125
+ val nonce = java.util.UUID.randomUUID().toString()
126
+ org.robolectric.shadows.ShadowSystemClock.advanceBy(25, TimeUnit.MILLISECONDS)
127
+ val admitted = android.os.SystemClock.elapsedRealtime()
128
+ nimo.resourceCaptureAdmission(nonce, armed, admitted)
129
+ setField("resourceSessionStartedElapsedMs", admitted)
130
+ setField("resourceSessionGeneration", 1L)
131
+ setField("twsElapsedMs", admitted)
132
+ setField("handshakeTwsElapsedMs", admitted)
133
+ setField("timeWriteStartedElapsedMs", admitted)
134
+ org.robolectric.shadows.ShadowSystemClock.advanceBy(10, TimeUnit.MILLISECONDS)
135
+ val ack = android.os.SystemClock.elapsedRealtime()
136
+ setField("timeAckElapsedMs", ack)
137
+ // Model independent phone epoch jumps: neither direction can rewrite causal time.
138
+ for (epoch in listOf(1L, 4_000_000_000_000L)) {
139
+ setField("resourceTwsAt", epoch)
140
+ setField("resourceHandshakeTwsAt", epoch)
141
+ setField("resourceTimeWriteStartedAt", epoch)
142
+ setField("resourceTimeAckAt", epoch)
143
+ val clock = nimo.resourceSnapshot().getJSONObject("clock")
144
+ assertEquals("android-elapsed-realtime-v1", clock.getString("kind"))
145
+ assertEquals(nonce, clock.getString("captureNonce"))
146
+ assertEquals(armed, clock.getLong("armedElapsedMs"))
147
+ assertEquals(admitted, clock.getLong("admittedElapsedMs"))
148
+ assertEquals(ack, clock.getLong("timeAckElapsedMs"))
149
+ assertTrue(clock.getLong("observedElapsedMs") >= ack)
150
+ }
151
+ }
152
+
153
+ @Test fun originalReleaseClockAndNonceSurviveLaterStatusAndRepeatedRelease() {
154
+ manager.sgc = nimo
155
+ NimoResourceDiagnostics.start(context)
156
+ setField("resourceSessionGeneration", 1L)
157
+ setField("resourcePairAddress", "00:11:22:33:44:55")
158
+ val nonce = java.util.UUID.randomUUID().toString()
159
+ val received = android.os.SystemClock.elapsedRealtime()
160
+ var first: JSONObject? = null
161
+ nimo.releaseResource(1L, { true }, { first = it }, nonce, received)
162
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(300, TimeUnit.MILLISECONDS)
163
+ val original = requireNotNull(first).getJSONObject("clock")
164
+ assertEquals(nonce, original.getString("releaseNonce"))
165
+ assertTrue(original.getLong("releaseStartedElapsedMs") >= received)
166
+ org.robolectric.shadows.ShadowSystemClock.advanceBy(10, TimeUnit.SECONDS)
167
+ val status = resourceCommand("status")
168
+ assertEquals("nimo-monotonic-receipt-v1", status.getString("clockProtocol"))
169
+ val statusClock = status.getJSONObject("clock")
170
+ assertTrue(statusClock.getLong("observedElapsedMs") >= statusClock.getLong("requestReceivedElapsedMs"))
171
+ var repeated: JSONObject? = null
172
+ nimo.releaseResource(1L, { true }, { repeated = it }, java.util.UUID.randomUUID().toString(), android.os.SystemClock.elapsedRealtime())
173
+ for (snapshot in listOf(status.getJSONObject("session"), requireNotNull(repeated))) {
174
+ val clock = snapshot.getJSONObject("clock")
175
+ assertEquals(nonce, clock.getString("releaseNonce"))
176
+ assertEquals(original.getLong("releaseStartedElapsedMs"), clock.getLong("releaseStartedElapsedMs"))
177
+ }
178
+ }
179
+
112
180
  @Test fun offMainDisconnectCompletesOnMainAndInterruptsActiveCapture() {
113
181
  runOffMain { nimo.disconnect() }
114
182
  assertDisconnectedOnMain()
@@ -188,6 +256,501 @@ class NimoLifecycleTest {
188
256
  assertTrue(other.createBond())
189
257
  }
190
258
 
259
+ @Test fun resourceStatusIsPassiveAndReleaseRefusesCurrentG2Replacement() {
260
+ readyForReset()
261
+ setField("resourceSessionGeneration", 1L)
262
+ setField("resourcePairAddress", "00:11:22:33:44:55")
263
+ manager.sgc = nimo
264
+ NimoResourceDiagnostics.start(context)
265
+ NimoResourceDiagnostics.track(nimo)
266
+ val status = resourceCommand("status")
267
+ assertEquals(nimo.resourceInstanceId, status.getJSONObject("session").getString("instanceId"))
268
+ assertTrue(status.getJSONObject("session").getBoolean("managedSessionPresent"))
269
+ assertEquals(1, writes) // No diagnostic queries or scanner operations.
270
+ manager.sgc = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
271
+ val released = resourceCommand("release")
272
+ assertEquals("release-refused-replaced-or-unowned-target", released.getString("error"))
273
+ assertTrue(nimo.resourceSnapshot().getBoolean("managedSessionPresent"))
274
+ assertEquals(com.mentra.bluetoothsdk.utils.DeviceTypes.G2, manager.sgc?.type)
275
+ assertEquals(true, DeviceStore.get("glasses", "connected"))
276
+ }
277
+
278
+ @Test fun resourceReleaseWaitsForOriginalMicStopMarkerAndPreservesBond() {
279
+ readyForReset()
280
+ setField("resourceSessionGeneration", 1L)
281
+ setField("resourcePairAddress", "00:11:22:33:44:55")
282
+ val mic = BluetoothGattCharacteristic(NimoBLE.CHAR_MIC, 8, 16)
283
+ setField("micChar", mic)
284
+ var result: JSONObject? = null
285
+ nimo.releaseResource(1L, { true }) { result = it }
286
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)
287
+ assertNull("Write completion alone must not stand in for mic stop feedback", result)
288
+ val gatt = field("gatt") as android.bluetooth.BluetoothGatt
289
+ mic.value = byteArrayOf(0x52, 0, 0, 0)
290
+ @Suppress("DEPRECATION")
291
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onCharacteristicChanged(gatt, mic)
292
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
293
+ val release = requireNotNull(result).getJSONObject("release")
294
+ assertFalse(release.isNull("micStopWrittenAtEpochMs"))
295
+ assertFalse(release.isNull("micStopMarkerAtEpochMs"))
296
+ assertEquals("unknown", release.getString("micSilence"))
297
+ assertEquals("unknown", release.getString("classicAclState"))
298
+ assertTrue(release.getBoolean("gattCloseCalled"))
299
+ assertTrue(requireNotNull(result).getBoolean("localEffectsSettled"))
300
+ assertRememberedDevice()
301
+ }
302
+
303
+ @Test fun reconnectCannotReplaceOriginalGenerationDuringDelayedReleaseReceipt() {
304
+ readyForReset()
305
+ setField("resourceSessionGeneration", 1L)
306
+ val originalGatt = field("gatt") as android.bluetooth.BluetoothGatt
307
+ var result: JSONObject? = null
308
+ nimo.releaseResource(1L, { true }) {
309
+ result = it
310
+ // Even reentrant connection requests inside receipt delivery remain fenced.
311
+ nimo.connectById("replacement-at-completion")
312
+ assertEquals(ConnTypes.DISCONNECTED, DeviceStore.get("glasses", "connectionState"))
313
+ }
314
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
315
+ assertNull(result)
316
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").getBoolean("gattCloseCalled"))
317
+ nimo.connectById("replacement-during-observation-window")
318
+ assertEquals(ConnTypes.DISCONNECTED, DeviceStore.get("glasses", "connectionState"))
319
+ assertNull(field("gatt"))
320
+ // Late feedback from this exact closed bearer is still retained for its receipt.
321
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onConnectionStateChange(
322
+ originalGatt, android.bluetooth.BluetoothGatt.GATT_SUCCESS, android.bluetooth.BluetoothProfile.STATE_DISCONNECTED)
323
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(150, TimeUnit.MILLISECONDS)
324
+ val receipt = requireNotNull(result)
325
+ assertEquals(1L, receipt.getLong("sessionGeneration"))
326
+ assertFalse(receipt.getBoolean("managedSessionPresent"))
327
+ assertTrue(receipt.getJSONObject("release").getBoolean("gattDisconnectCallbackObserved"))
328
+ assertEquals(0, receipt.getJSONObject("release").getInt("gattDisconnectCallbackStatus"))
329
+ // The completed receipt is a detached value, not a live view of later session fields.
330
+ setField("resourceSessionGeneration", 2L)
331
+ assertEquals(1L, receipt.getLong("sessionGeneration"))
332
+ }
333
+
334
+ @Test fun resourceMissingMicFeedbackLeavesStickyUnknownAfterTimeout() {
335
+ readyForReset()
336
+ setField("resourceSessionGeneration", 1L)
337
+ setField("micChar", BluetoothGattCharacteristic(NimoBLE.CHAR_MIC, 8, 16))
338
+ var result: JSONObject? = null
339
+ nimo.releaseResource(1L, { true }) { result = it }
340
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(16, TimeUnit.SECONDS)
341
+ assertEquals("drain-timeout-native-effects-unknown", requireNotNull(result).getJSONObject("release").getString("result"))
342
+ assertFalse(nimo.resourceSnapshot().getBoolean("localEffectsSettled"))
343
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").isNull("micStopMarkerAtEpochMs"))
344
+ }
345
+
346
+ @Test fun readinessExportsOnlyFreshSameSessionStatusZeroAckAfterWriteStarted() {
347
+ readyForReset()
348
+ setField("resourceSessionGeneration", 3L)
349
+ val state = Nimo::class.java.getDeclaredField("handshakeState")
350
+ setField("handshakeState", state.type.enumConstants.single { it.toString() == "AWAITING_TWS" })
351
+ Nimo::class.java.getDeclaredMethod("onTwsState", Boolean::class.javaPrimitiveType).apply { isAccessible = true }.invoke(nimo, true)
352
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(10, TimeUnit.MILLISECONDS)
353
+ respond(NimoProtocol.CMD_SET_PARAMETER, NimoProtocol.SET_TIME, 1)
354
+ assertTrue(nimo.resourceSnapshot().getJSONObject("timeAck").isNull("atEpochMs"))
355
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(600, TimeUnit.MILLISECONDS)
356
+ respond(NimoProtocol.CMD_SET_PARAMETER, NimoProtocol.SET_TIME, 0)
357
+ val snapshot = nimo.resourceSnapshot()
358
+ assertEquals(3L, snapshot.getJSONObject("tws").getLong("sessionGeneration"))
359
+ assertFalse(snapshot.getJSONObject("tws").isNull("atEpochMs"))
360
+ assertEquals(0, snapshot.getJSONObject("timeAck").getInt("statusCode"))
361
+ assertFalse(snapshot.getJSONObject("timeAck").isNull("writeStartedAtEpochMs"))
362
+ assertEquals("READY", snapshot.getString("handshake"))
363
+ val causalTws = snapshot.getJSONObject("clock").getLong("handshakeTwsElapsedMs")
364
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(100, TimeUnit.MILLISECONDS)
365
+ Nimo::class.java.getDeclaredMethod("onTwsState", Boolean::class.javaPrimitiveType).apply { isAccessible = true }.invoke(nimo, true)
366
+ val heartbeat = nimo.resourceSnapshot()
367
+ // Raw phone epochs are diagnostics; event order belongs to phone elapsed time.
368
+ assertFalse(heartbeat.getJSONObject("tws").isNull("atEpochMs"))
369
+ assertFalse(heartbeat.getJSONObject("timeAck").isNull("atEpochMs"))
370
+ val clock = heartbeat.getJSONObject("clock")
371
+ assertEquals(causalTws, clock.getLong("handshakeTwsElapsedMs"))
372
+ assertTrue(clock.getLong("twsElapsedMs") > clock.getLong("timeAckElapsedMs"))
373
+ assertEquals("READY", heartbeat.getString("handshake"))
374
+ }
375
+
376
+ @Test fun callbacksFromPriorGattCannotCreateCurrentReadiness() {
377
+ readyForReset()
378
+ val old = field("gatt") as android.bluetooth.BluetoothGatt
379
+ val other = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:66")
380
+ setField("gatt", ShadowBluetoothGatt.newInstance(other))
381
+ val rx = BluetoothGattCharacteristic(NimoBLE.CHAR_RX, 16, 16)
382
+ rx.value = byteArrayOf(0x52, 0, 0, 0)
383
+ @Suppress("DEPRECATION")
384
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onCharacteristicChanged(old, rx)
385
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
386
+ assertTrue(nimo.resourceSnapshot().getJSONObject("tws").isNull("atEpochMs"))
387
+ assertTrue(nimo.resourceSnapshot().getJSONObject("timeAck").isNull("atEpochMs"))
388
+ }
389
+
390
+ @Test fun firmwareFeedbackIsObservedWithinItsOwnSessionAndClearedOnReconnect() {
391
+ readyForReset()
392
+ setField("resourceSessionGeneration", 4L)
393
+ assertTrue(nimo.resourceSnapshot().getJSONObject("firmware").isNull("version"))
394
+ val response = Nimo::class.java.getDeclaredMethod("handleResponse", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, ByteArray::class.java).apply { isAccessible = true }
395
+ response.invoke(nimo, NimoProtocol.CMD_GET_PARAMETER, NimoProtocol.GET_VERSION, 1, byteArrayOf(1, 2, 3, 4))
396
+ assertTrue(nimo.resourceSnapshot().getJSONObject("firmware").isNull("atEpochMs"))
397
+ response.invoke(nimo, NimoProtocol.CMD_GET_PARAMETER, NimoProtocol.GET_VERSION_DETAIL, 0, "observed-test-version".toByteArray())
398
+ val observed = nimo.resourceSnapshot().getJSONObject("firmware")
399
+ assertEquals("observed-test-version", observed.getString("version"))
400
+ assertEquals(4L, observed.getLong("sessionGeneration"))
401
+ assertFalse(observed.isNull("atEpochMs"))
402
+ // New transport generation clears the evidence independently of the product's UI version cache.
403
+ setField("gatt", null); setField("isDisconnecting", false)
404
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
405
+ Nimo::class.java.getDeclaredMethod("connectBredrTransport", android.bluetooth.BluetoothDevice::class.java).apply { isAccessible = true }.invoke(nimo, device)
406
+ val fresh = nimo.resourceSnapshot().getJSONObject("firmware")
407
+ assertEquals(5L, fresh.getLong("sessionGeneration"))
408
+ assertTrue(fresh.isNull("version")); assertTrue(fresh.isNull("atEpochMs"))
409
+ }
410
+
411
+ @Test fun cancelledUnadmittedCaptureFencesLateConnectWithoutAdoptingManager() {
412
+ manager.sgc = null
413
+ NimoResourceDiagnostics.start(context)
414
+ val nonce = java.util.UUID.randomUUID().toString()
415
+ val armed = captureCommand("arm-capture", nonce, nonce)
416
+ assertTrue(armed.getJSONObject("session").getJSONObject("capture").isNull("instanceId"))
417
+ val cancelled = captureCommand("cancel-capture", nonce)
418
+ assertTrue(cancelled.getJSONObject("session").getJSONObject("capture").getBoolean("cancelled"))
419
+ manager.sgc = nimo
420
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
421
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
422
+ assertTrue(NimoResourceDiagnostics.allowManagerConnect("G2", "other"))
423
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
424
+ }
425
+
426
+ @Test fun capturePinsGenerationZeroBeforeEffectsAndRejectsWrongPeerAndReplacement() {
427
+ manager.sgc = null
428
+ NimoResourceDiagnostics.start(context)
429
+ val nonce = java.util.UUID.randomUUID().toString()
430
+ captureCommand("arm-capture", nonce, nonce)
431
+ manager.sgc = nimo
432
+ assertTrue(NimoResourceDiagnostics.admit(nimo, null, false))
433
+ val admission = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json").readText()
434
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission).getString("instanceId"))
435
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:56", true))
436
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:55", false)) // never create a new bond
437
+ assertTrue(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
438
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
439
+ assertTrue(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
440
+ assertFalse(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
441
+ manager.sgc = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
442
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
443
+ assertEquals("capture-cancel-refused-replacement", captureCommand("cancel-capture", nonce).getString("error"))
444
+ assertEquals(admission, File(context.filesDir, "nimo-lifecycle/$nonce.admission.json").readText())
445
+ assertEquals(com.mentra.bluetoothsdk.utils.DeviceTypes.G2, manager.sgc?.type)
446
+ }
447
+
448
+ @Test fun captureAdmissionPersistenceFailurePreventsAnyConnectAndBecomesStickyFence() {
449
+ manager.sgc = null
450
+ NimoResourceDiagnostics.start(context)
451
+ val nonce = java.util.UUID.randomUUID().toString()
452
+ captureCommand("arm-capture", nonce, nonce)
453
+ manager.sgc = nimo
454
+ File(context.filesDir, "nimo-lifecycle/$nonce.admission.tmp").mkdir()
455
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
456
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
457
+ assertFalse(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
458
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
459
+ assertFalse(File(context.filesDir, "nimo-lifecycle/$nonce.admission.json").exists())
460
+ val clock = nimo.resourceSnapshot().getJSONObject("clock")
461
+ assertTrue(clock.isNull("captureNonce")); assertTrue(clock.isNull("admittedElapsedMs"))
462
+ val capture = captureCommand("capture-status", nonce).getJSONObject("session").getJSONObject("capture")
463
+ assertTrue(capture.getBoolean("cancelled"))
464
+ assertTrue(capture.getJSONObject("clock").isNull("admittedElapsedMs"))
465
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
466
+ }
467
+
468
+ @Test fun preexistingAdmissionIsNeverOverwrittenOrStampedOntoLiveInstance() {
469
+ manager.sgc = null
470
+ NimoResourceDiagnostics.start(context)
471
+ val nonce = java.util.UUID.randomUUID().toString()
472
+ captureCommand("arm-capture", nonce, nonce)
473
+ manager.sgc = nimo
474
+ val original = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json")
475
+ original.writeText("preexisting-immutable-evidence")
476
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
477
+ assertEquals("preexisting-immutable-evidence", original.readText())
478
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
479
+ assertFalse(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
480
+ val clock = nimo.resourceSnapshot().getJSONObject("clock")
481
+ assertTrue(clock.isNull("captureNonce")); assertTrue(clock.isNull("admittedElapsedMs"))
482
+ assertTrue(captureCommand("capture-status", nonce).getJSONObject("session").getJSONObject("capture").getJSONObject("clock").isNull("admittedElapsedMs"))
483
+ }
484
+
485
+ @Test fun capturedGenerationZeroCancellationDrainsOriginalAndFencesQueuedAdmission() {
486
+ manager.sgc = null
487
+ NimoResourceDiagnostics.start(context)
488
+ val nonce = java.util.UUID.randomUUID().toString()
489
+ captureCommand("arm-capture", nonce, nonce)
490
+ manager.sgc = nimo
491
+ assertTrue(NimoResourceDiagnostics.admit(nimo, null, false))
492
+ val cancelNonce = java.util.UUID.randomUUID().toString()
493
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
494
+ .putExtra("nonce", cancelNonce).putExtra("mode", "cancel-capture").putExtra("expectedName", "Nimo-test")
495
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", nonce))
496
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
497
+ val result = JSONObject(File(context.filesDir, "nimo-lifecycle/$cancelNonce.json").readText())
498
+ val original = result.getJSONObject("session").getJSONObject("originalSession")
499
+ assertEquals(0L, original.getLong("sessionGeneration"))
500
+ assertFalse(original.getBoolean("managedSessionPresent"))
501
+ assertEquals("local-drained-native-readback-required", original.getJSONObject("release").getString("result"))
502
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
503
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:55", true))
504
+ }
505
+
506
+ @Test fun offMainManagerConnectIsQueuedWholeAndCancellationFencesItBeforeEffects() {
507
+ manager.sgc = null
508
+ NimoResourceDiagnostics.start(context)
509
+ val nonce = java.util.UUID.randomUUID().toString()
510
+ captureCommand("arm-capture", nonce, nonce)
511
+ val thread = Thread { manager.connectDevice(com.mentra.bluetoothsdk.utils.DeviceTypes.NIMO, "Nimo-test") }
512
+ thread.start(); awaitMainDispatch(thread)
513
+ assertTrue(thread.isAlive)
514
+ assertNull(manager.sgc) // no off-main manager creation or cleanup
515
+ captureCommand("cancel-capture", nonce)
516
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
517
+ thread.join(1000); assertFalse(thread.isAlive)
518
+ assertNull(manager.sgc) // the already-queued real entry rechecks its immutable fence
519
+ }
520
+
521
+ @Test fun offMainOriginalNimoConnectAdmitsOnMainBeforeAnyPeerTransport() {
522
+ manager.sgc = null
523
+ NimoResourceDiagnostics.start(context)
524
+ val nonce = java.util.UUID.randomUUID().toString()
525
+ captureCommand("arm-capture", nonce, nonce)
526
+ manager.sgc = nimo
527
+ val thread = Thread { nimo.connectById("Nimo-test") }
528
+ thread.start(); awaitMainDispatch(thread)
529
+ val admission = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json")
530
+ assertFalse(admission.exists())
531
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
532
+ thread.join(1000); assertFalse(thread.isAlive)
533
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission.readText()).getString("instanceId"))
534
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
535
+ assertFalse(nimo.resourceSnapshot().getBoolean("managedSessionPresent"))
536
+ }
537
+
538
+ @Test fun sdkConnectQueuedBeforeCancelCannotMutateDefaultOrDisconnectReplacementG2() {
539
+ manager.sgc = null
540
+ NimoResourceDiagnostics.start(context)
541
+ val nonce = java.util.UUID.randomUUID().toString()
542
+ captureCommand("arm-capture", nonce, nonce)
543
+ // No SDK construction/hardware/analytics is needed: a fenced entry must return
544
+ // before accessing collaborators. If the early guard regresses this test fails.
545
+ val sdk = uninitializedSdk()
546
+ DeviceStore.apply("bluetooth", "default_wearable", "unchanged-default")
547
+ DeviceStore.apply("bluetooth", "pending_wearable", "unchanged-pending")
548
+ val thread = Thread { sdk.connect(com.mentra.bluetoothsdk.Device(com.mentra.bluetoothsdk.DeviceModel.NIMO, "Nimo-test")) }
549
+ thread.start(); awaitMainDispatch(thread)
550
+ captureCommand("cancel-capture", nonce)
551
+ val replacement = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
552
+ manager.sgc = replacement
553
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
554
+ thread.join(1000); assertFalse(thread.isAlive)
555
+ assertSame(replacement, manager.sgc)
556
+ assertEquals("unchanged-default", DeviceStore.get("bluetooth", "default_wearable"))
557
+ assertEquals("unchanged-pending", DeviceStore.get("bluetooth", "pending_wearable"))
558
+ assertEquals(true, DeviceStore.get("glasses", "connected"))
559
+ }
560
+
561
+ @Test fun unarmedOrdinaryDebugEntryKeepsItsOriginalDirectExecution() {
562
+ val caller = AtomicReference<Thread?>()
563
+ val queued = AtomicReference<Boolean?>()
564
+ val thread = Thread {
565
+ queued.set(NimoResourceDiagnostics.dispatchCapturedEntry { fail("Unarmed debug must not queue") })
566
+ caller.set(Thread.currentThread())
567
+ }
568
+ thread.start(); thread.join(1000)
569
+ assertFalse(thread.isAlive)
570
+ assertSame(thread, caller.get())
571
+ assertEquals(false, queued.get())
572
+ }
573
+
574
+ @Test fun offMainSdkFailureIsDeliveredToCallerWithoutUncaughtMainException() {
575
+ manager.sgc = null
576
+ NimoResourceDiagnostics.start(context)
577
+ val nonce = java.util.UUID.randomUUID().toString()
578
+ captureCommand("arm-capture", nonce, nonce)
579
+ val sdk = uninitializedSdk()
580
+ DeviceStore.apply("bluetooth", "default_wearable", "")
581
+ val failure = AtomicReference<Throwable?>()
582
+ val thread = Thread { try { sdk.connectDefault() } catch (error: Throwable) { failure.set(error) } }
583
+ thread.start(); awaitMainDispatch(thread)
584
+ Shadows.shadowOf(Looper.getMainLooper()).idle() // FutureTask captures the error; main must not throw.
585
+ thread.join(1000); assertFalse(thread.isAlive)
586
+ assertTrue(failure.get() is com.mentra.bluetoothsdk.BluetoothSdkException)
587
+ assertEquals("default_device_missing", (failure.get() as com.mentra.bluetoothsdk.BluetoothSdkException).code)
588
+ }
589
+
590
+ @Test fun onlyDiagnosticVariantRequiresArmForNimoAndExistingManagerCannotBeAdopted() {
591
+ assertFalse(NimoResourceDiagnostics.allowUnarmedWearable("nimoDiagnostic", "NIMO"))
592
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("nimoDiagnostic", "G2"))
593
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("debug", "NIMO"))
594
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("release", "NIMO"))
595
+ manager.sgc = nimo
596
+ NimoResourceDiagnostics.start(context)
597
+ val nonce = java.util.UUID.randomUUID().toString()
598
+ assertEquals("capture-arm-refused-existing-owner", captureCommand("arm-capture", nonce, nonce).getString("error"))
599
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
600
+ }
601
+
602
+ @Test fun sdkScanThenConnectPreservesOriginalCapturedManagerAndCancelStillDrainsIt() {
603
+ // Retire the unrelated setup fixture. The real SDK scan must create and admit
604
+ // its own manager instance; no direct admit or fake manager transition is used.
605
+ nimo.cleanup()
606
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
607
+ encoderThread.join(1_000)
608
+ val threadsBeforeScan = Thread.getAllStackTraces().keys
609
+ manager.sgc = null
610
+ NimoResourceDiagnostics.start(context)
611
+ val nonce = java.util.UUID.randomUUID().toString()
612
+ captureCommand("arm-capture", nonce, nonce)
613
+ val sdk = uninitializedSdk()
614
+ for ((name, value) in mapOf("appContext" to context, "deviceManager" to manager,
615
+ "discoveredDeviceNames" to mutableSetOf<String>())) {
616
+ com.mentra.bluetoothsdk.MentraBluetoothSdk::class.java.getDeclaredField(name).apply { isAccessible = true }.set(sdk, value)
617
+ }
618
+ Shadows.shadowOf(BluetoothAdapter.getDefaultAdapter()).setState(BluetoothAdapter.STATE_ON)
619
+ sdk.startScan(com.mentra.bluetoothsdk.DeviceModel.NIMO)
620
+ nimo = manager.sgc as Nimo
621
+ encoderThread = Thread.getAllStackTraces().keys.single {
622
+ it.name == "NimoCanvasEncoder" && it !in threadsBeforeScan
623
+ }
624
+ val admissionFile = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json")
625
+ val admission = admissionFile.readText()
626
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission).getString("instanceId"))
627
+ assertSame(nimo, manager.sgc)
628
+ val target = com.mentra.bluetoothsdk.Device(com.mentra.bluetoothsdk.DeviceModel.NIMO, "Nimo-test", "00:11:22:33:44:55")
629
+ sdk.connect(target, com.mentra.bluetoothsdk.ConnectOptions(saveAsDefault = false))
630
+ assertSame("SDK cancelExisting and manager connect must retain the scan instance", nimo, manager.sgc)
631
+ assertTrue(encoderThread.isAlive)
632
+ assertEquals(admission, admissionFile.readText())
633
+ val connectedCapture = captureCommand("capture-status", nonce).getJSONObject("session").getJSONObject("capture")
634
+ assertTrue(connectedCapture.getBoolean("connectStarted"))
635
+ // A duplicate must be refused before either layer can discard the original.
636
+ sdk.connect(target, com.mentra.bluetoothsdk.ConnectOptions(saveAsDefault = false))
637
+ assertSame(nimo, manager.sgc)
638
+ val cancel = java.util.UUID.randomUUID().toString()
639
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
640
+ .putExtra("nonce", cancel).putExtra("mode", "cancel-capture").putExtra("expectedName", "Nimo-test")
641
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", nonce))
642
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
643
+ val result = JSONObject(File(context.filesDir, "nimo-lifecycle/$cancel.json").readText())
644
+ assertEquals(nimo.resourceInstanceId, result.getJSONObject("session").getJSONObject("originalSession").getString("instanceId"))
645
+ assertEquals("local-drained-native-readback-required", result.getJSONObject("session").getJSONObject("originalSession").getJSONObject("release").getString("result"))
646
+ }
647
+
648
+ @Test fun ordinaryConnectPermissionRevocationDoesNotEscapePeerGuardsOrGattOpen() {
649
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
650
+ Shadows.shadowOf(device).setShouldThrowSecurityExceptions(true)
651
+ Shadows.shadowOf(ApplicationProvider.getApplicationContext<android.app.Application>())
652
+ .denyPermissions(android.Manifest.permission.BLUETOOTH_CONNECT)
653
+ for (name in listOf("connectCompanionGatt", "startBond", "connectBredrTransport")) {
654
+ Nimo::class.java.getDeclaredMethod(name, android.bluetooth.BluetoothDevice::class.java)
655
+ .apply { isAccessible = true }.invoke(nimo, device)
656
+ assertNull(field("gatt"))
657
+ }
658
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").getBoolean("transportFailure"))
659
+ }
660
+
661
+ @Test fun rejectedInitialLaunchDuringReleaseDoesNotInventAnExitAckOrWaitForOne() {
662
+ for (status in listOf(7, 8)) {
663
+ readyForReset(); setField("resourceSessionGeneration", 1L); setField("resourceReleased", false)
664
+ val canvas = field("canvas") as NimoCanvasCoordinator
665
+ canvas.activate(); canvas.readiness(true)
666
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
667
+ assertTrue(canvas.launchPending())
668
+ var result: JSONObject? = null
669
+ nimo.releaseResource(1L, { true }) { result = it }
670
+ canvas.response(1, byteArrayOf(status.toByte()))
671
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
672
+ val release = requireNotNull(result).getJSONObject("release")
673
+ assertEquals("local-drained-native-readback-required", release.getString("result"))
674
+ assertFalse(release.getBoolean("displayExitRequired"))
675
+ assertTrue(release.isNull("displayExitStatus"))
676
+ assertEquals("unknown", release.getString("displayVisibleState"))
677
+ }
678
+ }
679
+
680
+ @Test fun ambiguousLaunchRejectionRetainsExitUnknownAndTimesOut() {
681
+ readyForReset(); setField("resourceSessionGeneration", 1L)
682
+ val canvas = field("canvas") as NimoCanvasCoordinator
683
+ canvas.activate(); canvas.readiness(true)
684
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
685
+ var result: JSONObject? = null
686
+ nimo.releaseResource(1L, { true }) { result = it }
687
+ canvas.response(1, byteArrayOf(2))
688
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(16, TimeUnit.SECONDS)
689
+ val release = requireNotNull(result).getJSONObject("release")
690
+ assertEquals("drain-timeout-native-effects-unknown", release.getString("result"))
691
+ assertTrue(release.getBoolean("displayExitRequired"))
692
+ assertTrue(release.isNull("displayExitStatus"))
693
+ }
694
+
695
+ @Test fun explicitNewConnectAttemptClearsEarlierMutationEvidenceBeforeItsOwnEffects() {
696
+ setField("resourceBondMutationRequested", true); setField("resourceFactoryResetRequested", true)
697
+ val prior = nimo.resourceSnapshot()
698
+ nimo.connectById("Nimo-test")
699
+ val current = nimo.resourceSnapshot().getJSONObject("release")
700
+ assertFalse(current.getBoolean("bondMutationRequested")); assertFalse(current.getBoolean("factoryResetRequested"))
701
+ assertTrue(prior.getJSONObject("release").getBoolean("bondMutationRequested"))
702
+ }
703
+
704
+ @Test fun transportGenerationResetsOldReleaseObligationsButRetainsCurrentAttemptMutationEvidence() {
705
+ setField("resourceSessionGeneration", 1L)
706
+ setField("resourceMicStopRequired", true); setField("resourceExitRequired", true)
707
+ setField("resourceBondMutationRequested", true); setField("resourceFactoryResetRequested", true)
708
+ setField("resourceReleased", true)
709
+ val original = nimo.resourceSnapshot()
710
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
711
+ Nimo::class.java.getDeclaredMethod("connectBredrTransport", android.bluetooth.BluetoothDevice::class.java)
712
+ .apply { isAccessible = true }.invoke(nimo, device)
713
+ val current = nimo.resourceSnapshot().getJSONObject("release")
714
+ assertEquals("not-requested", current.getString("result"))
715
+ assertFalse(current.getBoolean("micStopRequired")); assertFalse(current.getBoolean("displayExitRequired"))
716
+ assertFalse(field("resourceReleased") as Boolean)
717
+ assertTrue(current.getBoolean("bondMutationRequested")); assertTrue(current.getBoolean("factoryResetRequested"))
718
+ assertTrue(original.getJSONObject("release").getBoolean("micStopRequired"))
719
+ }
720
+
721
+ private fun uninitializedSdk(): com.mentra.bluetoothsdk.MentraBluetoothSdk {
722
+ // JVM fixture only. Reflection avoids Android bootclasspath references to JDK internals.
723
+ val type = Class.forName("sun.misc.Unsafe")
724
+ val allocator = type.getDeclaredField("theUnsafe").apply { isAccessible = true }.get(null)
725
+ return type.getMethod("allocateInstance", Class::class.java)
726
+ .invoke(allocator, com.mentra.bluetoothsdk.MentraBluetoothSdk::class.java) as com.mentra.bluetoothsdk.MentraBluetoothSdk
727
+ }
728
+
729
+ private fun awaitMainDispatch(thread: Thread) {
730
+ val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)
731
+ while (thread.isAlive && thread.state != Thread.State.WAITING && System.nanoTime() < deadline) Thread.yield()
732
+ assertTrue("SDK caller must wait for its main-queue result", thread.isAlive)
733
+ assertEquals(Thread.State.WAITING, thread.state)
734
+ }
735
+
736
+ private fun captureCommand(mode: String, captureNonce: String, requestNonce: String = java.util.UUID.randomUUID().toString()): JSONObject {
737
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
738
+ .putExtra("nonce", requestNonce).putExtra("mode", mode).putExtra("expectedName", "Nimo-test")
739
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", captureNonce))
740
+ return JSONObject(File(context.filesDir, "nimo-lifecycle/$requestNonce.json").readText())
741
+ }
742
+
743
+ private fun field(name: String): Any? = Nimo::class.java.getDeclaredField(name).apply { isAccessible = true }.get(nimo)
744
+
745
+ private fun resourceCommand(mode: String): JSONObject {
746
+ val nonce = java.util.UUID.randomUUID().toString()
747
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
748
+ .putExtra("nonce", nonce).putExtra("mode", mode).putExtra("expectedAddress", "00:11:22:33:44:55")
749
+ .putExtra("instanceId", nimo.resourceInstanceId).putExtra("sessionGeneration", 1L))
750
+ val file = File(context.filesDir, "nimo-lifecycle/$nonce.json")
751
+ return JSONObject(file.readText())
752
+ }
753
+
191
754
  private fun readyForReset(): MutableList<ByteArray> {
192
755
  val frames = mutableListOf<ByteArray>()
193
756
  val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
@@ -218,7 +781,7 @@ class NimoLifecycleTest {
218
781
  return frames
219
782
  }
220
783
 
221
- private fun setField(name: String, value: Any) {
784
+ private fun setField(name: String, value: Any?) {
222
785
  Nimo::class.java.getDeclaredField(name).apply { isAccessible = true }.set(nimo, value)
223
786
  }
224
787