@mentra/bluetooth-sdk 3.4.0-dev.957 → 3.4.0-dev.965

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.
@@ -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)
@@ -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
+ }
@@ -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)
@@ -188,6 +199,472 @@ class NimoLifecycleTest {
188
199
  assertTrue(other.createBond())
189
200
  }
190
201
 
202
+ @Test fun resourceStatusIsPassiveAndReleaseRefusesCurrentG2Replacement() {
203
+ readyForReset()
204
+ setField("resourceSessionGeneration", 1L)
205
+ setField("resourcePairAddress", "00:11:22:33:44:55")
206
+ manager.sgc = nimo
207
+ NimoResourceDiagnostics.start(context)
208
+ NimoResourceDiagnostics.track(nimo)
209
+ val status = resourceCommand("status")
210
+ assertEquals(nimo.resourceInstanceId, status.getJSONObject("session").getString("instanceId"))
211
+ assertTrue(status.getJSONObject("session").getBoolean("managedSessionPresent"))
212
+ assertEquals(1, writes) // No diagnostic queries or scanner operations.
213
+ manager.sgc = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
214
+ val released = resourceCommand("release")
215
+ assertEquals("release-refused-replaced-or-unowned-target", released.getString("error"))
216
+ assertTrue(nimo.resourceSnapshot().getBoolean("managedSessionPresent"))
217
+ assertEquals(com.mentra.bluetoothsdk.utils.DeviceTypes.G2, manager.sgc?.type)
218
+ assertEquals(true, DeviceStore.get("glasses", "connected"))
219
+ }
220
+
221
+ @Test fun resourceReleaseWaitsForOriginalMicStopMarkerAndPreservesBond() {
222
+ readyForReset()
223
+ setField("resourceSessionGeneration", 1L)
224
+ setField("resourcePairAddress", "00:11:22:33:44:55")
225
+ val mic = BluetoothGattCharacteristic(NimoBLE.CHAR_MIC, 8, 16)
226
+ setField("micChar", mic)
227
+ var result: JSONObject? = null
228
+ nimo.releaseResource(1L, { true }) { result = it }
229
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)
230
+ assertNull("Write completion alone must not stand in for mic stop feedback", result)
231
+ val gatt = field("gatt") as android.bluetooth.BluetoothGatt
232
+ mic.value = byteArrayOf(0x52, 0, 0, 0)
233
+ @Suppress("DEPRECATION")
234
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onCharacteristicChanged(gatt, mic)
235
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
236
+ val release = requireNotNull(result).getJSONObject("release")
237
+ assertFalse(release.isNull("micStopWrittenAtEpochMs"))
238
+ assertFalse(release.isNull("micStopMarkerAtEpochMs"))
239
+ assertEquals("unknown", release.getString("micSilence"))
240
+ assertEquals("unknown", release.getString("classicAclState"))
241
+ assertTrue(release.getBoolean("gattCloseCalled"))
242
+ assertTrue(requireNotNull(result).getBoolean("localEffectsSettled"))
243
+ assertRememberedDevice()
244
+ }
245
+
246
+ @Test fun reconnectCannotReplaceOriginalGenerationDuringDelayedReleaseReceipt() {
247
+ readyForReset()
248
+ setField("resourceSessionGeneration", 1L)
249
+ val originalGatt = field("gatt") as android.bluetooth.BluetoothGatt
250
+ var result: JSONObject? = null
251
+ nimo.releaseResource(1L, { true }) {
252
+ result = it
253
+ // Even reentrant connection requests inside receipt delivery remain fenced.
254
+ nimo.connectById("replacement-at-completion")
255
+ assertEquals(ConnTypes.DISCONNECTED, DeviceStore.get("glasses", "connectionState"))
256
+ }
257
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
258
+ assertNull(result)
259
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").getBoolean("gattCloseCalled"))
260
+ nimo.connectById("replacement-during-observation-window")
261
+ assertEquals(ConnTypes.DISCONNECTED, DeviceStore.get("glasses", "connectionState"))
262
+ assertNull(field("gatt"))
263
+ // Late feedback from this exact closed bearer is still retained for its receipt.
264
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onConnectionStateChange(
265
+ originalGatt, android.bluetooth.BluetoothGatt.GATT_SUCCESS, android.bluetooth.BluetoothProfile.STATE_DISCONNECTED)
266
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(150, TimeUnit.MILLISECONDS)
267
+ val receipt = requireNotNull(result)
268
+ assertEquals(1L, receipt.getLong("sessionGeneration"))
269
+ assertFalse(receipt.getBoolean("managedSessionPresent"))
270
+ assertTrue(receipt.getJSONObject("release").getBoolean("gattDisconnectCallbackObserved"))
271
+ assertEquals(0, receipt.getJSONObject("release").getInt("gattDisconnectCallbackStatus"))
272
+ // The completed receipt is a detached value, not a live view of later session fields.
273
+ setField("resourceSessionGeneration", 2L)
274
+ assertEquals(1L, receipt.getLong("sessionGeneration"))
275
+ }
276
+
277
+ @Test fun resourceMissingMicFeedbackLeavesStickyUnknownAfterTimeout() {
278
+ readyForReset()
279
+ setField("resourceSessionGeneration", 1L)
280
+ setField("micChar", BluetoothGattCharacteristic(NimoBLE.CHAR_MIC, 8, 16))
281
+ var result: JSONObject? = null
282
+ nimo.releaseResource(1L, { true }) { result = it }
283
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(16, TimeUnit.SECONDS)
284
+ assertEquals("drain-timeout-native-effects-unknown", requireNotNull(result).getJSONObject("release").getString("result"))
285
+ assertFalse(nimo.resourceSnapshot().getBoolean("localEffectsSettled"))
286
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").isNull("micStopMarkerAtEpochMs"))
287
+ }
288
+
289
+ @Test fun readinessExportsOnlyFreshSameSessionStatusZeroAckAfterWriteStarted() {
290
+ readyForReset()
291
+ setField("resourceSessionGeneration", 3L)
292
+ val state = Nimo::class.java.getDeclaredField("handshakeState")
293
+ setField("handshakeState", state.type.enumConstants.single { it.toString() == "AWAITING_TWS" })
294
+ Nimo::class.java.getDeclaredMethod("onTwsState", Boolean::class.javaPrimitiveType).apply { isAccessible = true }.invoke(nimo, true)
295
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(10, TimeUnit.MILLISECONDS)
296
+ respond(NimoProtocol.CMD_SET_PARAMETER, NimoProtocol.SET_TIME, 1)
297
+ assertTrue(nimo.resourceSnapshot().getJSONObject("timeAck").isNull("atEpochMs"))
298
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(600, TimeUnit.MILLISECONDS)
299
+ respond(NimoProtocol.CMD_SET_PARAMETER, NimoProtocol.SET_TIME, 0)
300
+ val snapshot = nimo.resourceSnapshot()
301
+ assertEquals(3L, snapshot.getJSONObject("tws").getLong("sessionGeneration"))
302
+ assertFalse(snapshot.getJSONObject("tws").isNull("atEpochMs"))
303
+ assertEquals(0, snapshot.getJSONObject("timeAck").getInt("statusCode"))
304
+ assertFalse(snapshot.getJSONObject("timeAck").isNull("writeStartedAtEpochMs"))
305
+ assertEquals("READY", snapshot.getString("handshake"))
306
+ val causalTws = snapshot.getJSONObject("tws").getLong("handshakeAtEpochMs")
307
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(100, TimeUnit.MILLISECONDS)
308
+ Nimo::class.java.getDeclaredMethod("onTwsState", Boolean::class.javaPrimitiveType).apply { isAccessible = true }.invoke(nimo, true)
309
+ val heartbeat = nimo.resourceSnapshot()
310
+ assertEquals(causalTws, heartbeat.getJSONObject("tws").getLong("handshakeAtEpochMs"))
311
+ assertTrue(heartbeat.getJSONObject("tws").getLong("atEpochMs") > heartbeat.getJSONObject("timeAck").getLong("atEpochMs"))
312
+ assertEquals("READY", heartbeat.getString("handshake"))
313
+ }
314
+
315
+ @Test fun callbacksFromPriorGattCannotCreateCurrentReadiness() {
316
+ readyForReset()
317
+ val old = field("gatt") as android.bluetooth.BluetoothGatt
318
+ val other = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:66")
319
+ setField("gatt", ShadowBluetoothGatt.newInstance(other))
320
+ val rx = BluetoothGattCharacteristic(NimoBLE.CHAR_RX, 16, 16)
321
+ rx.value = byteArrayOf(0x52, 0, 0, 0)
322
+ @Suppress("DEPRECATION")
323
+ (field("gattCallback") as android.bluetooth.BluetoothGattCallback).onCharacteristicChanged(old, rx)
324
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
325
+ assertTrue(nimo.resourceSnapshot().getJSONObject("tws").isNull("atEpochMs"))
326
+ assertTrue(nimo.resourceSnapshot().getJSONObject("timeAck").isNull("atEpochMs"))
327
+ }
328
+
329
+ @Test fun firmwareFeedbackIsObservedWithinItsOwnSessionAndClearedOnReconnect() {
330
+ readyForReset()
331
+ setField("resourceSessionGeneration", 4L)
332
+ assertTrue(nimo.resourceSnapshot().getJSONObject("firmware").isNull("version"))
333
+ val response = Nimo::class.java.getDeclaredMethod("handleResponse", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, ByteArray::class.java).apply { isAccessible = true }
334
+ response.invoke(nimo, NimoProtocol.CMD_GET_PARAMETER, NimoProtocol.GET_VERSION, 1, byteArrayOf(1, 2, 3, 4))
335
+ assertTrue(nimo.resourceSnapshot().getJSONObject("firmware").isNull("atEpochMs"))
336
+ response.invoke(nimo, NimoProtocol.CMD_GET_PARAMETER, NimoProtocol.GET_VERSION_DETAIL, 0, "observed-test-version".toByteArray())
337
+ val observed = nimo.resourceSnapshot().getJSONObject("firmware")
338
+ assertEquals("observed-test-version", observed.getString("version"))
339
+ assertEquals(4L, observed.getLong("sessionGeneration"))
340
+ assertFalse(observed.isNull("atEpochMs"))
341
+ // New transport generation clears the evidence independently of the product's UI version cache.
342
+ setField("gatt", null); setField("isDisconnecting", false)
343
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
344
+ Nimo::class.java.getDeclaredMethod("connectBredrTransport", android.bluetooth.BluetoothDevice::class.java).apply { isAccessible = true }.invoke(nimo, device)
345
+ val fresh = nimo.resourceSnapshot().getJSONObject("firmware")
346
+ assertEquals(5L, fresh.getLong("sessionGeneration"))
347
+ assertTrue(fresh.isNull("version")); assertTrue(fresh.isNull("atEpochMs"))
348
+ }
349
+
350
+ @Test fun cancelledUnadmittedCaptureFencesLateConnectWithoutAdoptingManager() {
351
+ manager.sgc = null
352
+ NimoResourceDiagnostics.start(context)
353
+ val nonce = java.util.UUID.randomUUID().toString()
354
+ val armed = captureCommand("arm-capture", nonce, nonce)
355
+ assertTrue(armed.getJSONObject("session").getJSONObject("capture").isNull("instanceId"))
356
+ val cancelled = captureCommand("cancel-capture", nonce)
357
+ assertTrue(cancelled.getJSONObject("session").getJSONObject("capture").getBoolean("cancelled"))
358
+ manager.sgc = nimo
359
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
360
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
361
+ assertTrue(NimoResourceDiagnostics.allowManagerConnect("G2", "other"))
362
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
363
+ }
364
+
365
+ @Test fun capturePinsGenerationZeroBeforeEffectsAndRejectsWrongPeerAndReplacement() {
366
+ manager.sgc = null
367
+ NimoResourceDiagnostics.start(context)
368
+ val nonce = java.util.UUID.randomUUID().toString()
369
+ captureCommand("arm-capture", nonce, nonce)
370
+ manager.sgc = nimo
371
+ assertTrue(NimoResourceDiagnostics.admit(nimo, null, false))
372
+ val admission = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json").readText()
373
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission).getString("instanceId"))
374
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:56", true))
375
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:55", false)) // never create a new bond
376
+ assertTrue(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
377
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
378
+ assertTrue(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
379
+ assertFalse(NimoResourceDiagnostics.beginTransport(nimo, "00:11:22:33:44:55", true))
380
+ manager.sgc = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
381
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
382
+ assertEquals("capture-cancel-refused-replacement", captureCommand("cancel-capture", nonce).getString("error"))
383
+ assertEquals(admission, File(context.filesDir, "nimo-lifecycle/$nonce.admission.json").readText())
384
+ assertEquals(com.mentra.bluetoothsdk.utils.DeviceTypes.G2, manager.sgc?.type)
385
+ }
386
+
387
+ @Test fun captureAdmissionPersistenceFailurePreventsAnyConnectAndBecomesStickyFence() {
388
+ manager.sgc = null
389
+ NimoResourceDiagnostics.start(context)
390
+ val nonce = java.util.UUID.randomUUID().toString()
391
+ captureCommand("arm-capture", nonce, nonce)
392
+ manager.sgc = nimo
393
+ File(context.filesDir, "nimo-lifecycle/$nonce.admission.tmp").mkdir()
394
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
395
+ assertFalse(NimoResourceDiagnostics.allowManagerConnect("NIMO", "Nimo-test"))
396
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
397
+ }
398
+
399
+ @Test fun capturedGenerationZeroCancellationDrainsOriginalAndFencesQueuedAdmission() {
400
+ manager.sgc = null
401
+ NimoResourceDiagnostics.start(context)
402
+ val nonce = java.util.UUID.randomUUID().toString()
403
+ captureCommand("arm-capture", nonce, nonce)
404
+ manager.sgc = nimo
405
+ assertTrue(NimoResourceDiagnostics.admit(nimo, null, false))
406
+ val cancelNonce = java.util.UUID.randomUUID().toString()
407
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
408
+ .putExtra("nonce", cancelNonce).putExtra("mode", "cancel-capture").putExtra("expectedName", "Nimo-test")
409
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", nonce))
410
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
411
+ val result = JSONObject(File(context.filesDir, "nimo-lifecycle/$cancelNonce.json").readText())
412
+ val original = result.getJSONObject("session").getJSONObject("originalSession")
413
+ assertEquals(0L, original.getLong("sessionGeneration"))
414
+ assertFalse(original.getBoolean("managedSessionPresent"))
415
+ assertEquals("local-drained-native-readback-required", original.getJSONObject("release").getString("result"))
416
+ assertFalse(NimoResourceDiagnostics.admit(nimo, "Nimo-test", true))
417
+ assertFalse(NimoResourceDiagnostics.allowPeer(nimo, "00:11:22:33:44:55", true))
418
+ }
419
+
420
+ @Test fun offMainManagerConnectIsQueuedWholeAndCancellationFencesItBeforeEffects() {
421
+ manager.sgc = null
422
+ NimoResourceDiagnostics.start(context)
423
+ val nonce = java.util.UUID.randomUUID().toString()
424
+ captureCommand("arm-capture", nonce, nonce)
425
+ val thread = Thread { manager.connectDevice(com.mentra.bluetoothsdk.utils.DeviceTypes.NIMO, "Nimo-test") }
426
+ thread.start(); awaitMainDispatch(thread)
427
+ assertTrue(thread.isAlive)
428
+ assertNull(manager.sgc) // no off-main manager creation or cleanup
429
+ captureCommand("cancel-capture", nonce)
430
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
431
+ thread.join(1000); assertFalse(thread.isAlive)
432
+ assertNull(manager.sgc) // the already-queued real entry rechecks its immutable fence
433
+ }
434
+
435
+ @Test fun offMainOriginalNimoConnectAdmitsOnMainBeforeAnyPeerTransport() {
436
+ manager.sgc = null
437
+ NimoResourceDiagnostics.start(context)
438
+ val nonce = java.util.UUID.randomUUID().toString()
439
+ captureCommand("arm-capture", nonce, nonce)
440
+ manager.sgc = nimo
441
+ val thread = Thread { nimo.connectById("Nimo-test") }
442
+ thread.start(); awaitMainDispatch(thread)
443
+ val admission = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json")
444
+ assertFalse(admission.exists())
445
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
446
+ thread.join(1000); assertFalse(thread.isAlive)
447
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission.readText()).getString("instanceId"))
448
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
449
+ assertFalse(nimo.resourceSnapshot().getBoolean("managedSessionPresent"))
450
+ }
451
+
452
+ @Test fun sdkConnectQueuedBeforeCancelCannotMutateDefaultOrDisconnectReplacementG2() {
453
+ manager.sgc = null
454
+ NimoResourceDiagnostics.start(context)
455
+ val nonce = java.util.UUID.randomUUID().toString()
456
+ captureCommand("arm-capture", nonce, nonce)
457
+ // No SDK construction/hardware/analytics is needed: a fenced entry must return
458
+ // before accessing collaborators. If the early guard regresses this test fails.
459
+ val sdk = uninitializedSdk()
460
+ DeviceStore.apply("bluetooth", "default_wearable", "unchanged-default")
461
+ DeviceStore.apply("bluetooth", "pending_wearable", "unchanged-pending")
462
+ val thread = Thread { sdk.connect(com.mentra.bluetoothsdk.Device(com.mentra.bluetoothsdk.DeviceModel.NIMO, "Nimo-test")) }
463
+ thread.start(); awaitMainDispatch(thread)
464
+ captureCommand("cancel-capture", nonce)
465
+ val replacement = Simulated().apply { type = com.mentra.bluetoothsdk.utils.DeviceTypes.G2 }
466
+ manager.sgc = replacement
467
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
468
+ thread.join(1000); assertFalse(thread.isAlive)
469
+ assertSame(replacement, manager.sgc)
470
+ assertEquals("unchanged-default", DeviceStore.get("bluetooth", "default_wearable"))
471
+ assertEquals("unchanged-pending", DeviceStore.get("bluetooth", "pending_wearable"))
472
+ assertEquals(true, DeviceStore.get("glasses", "connected"))
473
+ }
474
+
475
+ @Test fun unarmedOrdinaryDebugEntryKeepsItsOriginalDirectExecution() {
476
+ val caller = AtomicReference<Thread?>()
477
+ val queued = AtomicReference<Boolean?>()
478
+ val thread = Thread {
479
+ queued.set(NimoResourceDiagnostics.dispatchCapturedEntry { fail("Unarmed debug must not queue") })
480
+ caller.set(Thread.currentThread())
481
+ }
482
+ thread.start(); thread.join(1000)
483
+ assertFalse(thread.isAlive)
484
+ assertSame(thread, caller.get())
485
+ assertEquals(false, queued.get())
486
+ }
487
+
488
+ @Test fun offMainSdkFailureIsDeliveredToCallerWithoutUncaughtMainException() {
489
+ manager.sgc = null
490
+ NimoResourceDiagnostics.start(context)
491
+ val nonce = java.util.UUID.randomUUID().toString()
492
+ captureCommand("arm-capture", nonce, nonce)
493
+ val sdk = uninitializedSdk()
494
+ DeviceStore.apply("bluetooth", "default_wearable", "")
495
+ val failure = AtomicReference<Throwable?>()
496
+ val thread = Thread { try { sdk.connectDefault() } catch (error: Throwable) { failure.set(error) } }
497
+ thread.start(); awaitMainDispatch(thread)
498
+ Shadows.shadowOf(Looper.getMainLooper()).idle() // FutureTask captures the error; main must not throw.
499
+ thread.join(1000); assertFalse(thread.isAlive)
500
+ assertTrue(failure.get() is com.mentra.bluetoothsdk.BluetoothSdkException)
501
+ assertEquals("default_device_missing", (failure.get() as com.mentra.bluetoothsdk.BluetoothSdkException).code)
502
+ }
503
+
504
+ @Test fun onlyDiagnosticVariantRequiresArmForNimoAndExistingManagerCannotBeAdopted() {
505
+ assertFalse(NimoResourceDiagnostics.allowUnarmedWearable("nimoDiagnostic", "NIMO"))
506
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("nimoDiagnostic", "G2"))
507
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("debug", "NIMO"))
508
+ assertTrue(NimoResourceDiagnostics.allowUnarmedWearable("release", "NIMO"))
509
+ manager.sgc = nimo
510
+ NimoResourceDiagnostics.start(context)
511
+ val nonce = java.util.UUID.randomUUID().toString()
512
+ assertEquals("capture-arm-refused-existing-owner", captureCommand("arm-capture", nonce, nonce).getString("error"))
513
+ assertEquals(0L, nimo.resourceSnapshot().getLong("sessionGeneration"))
514
+ }
515
+
516
+ @Test fun sdkScanThenConnectPreservesOriginalCapturedManagerAndCancelStillDrainsIt() {
517
+ // Retire the unrelated setup fixture. The real SDK scan must create and admit
518
+ // its own manager instance; no direct admit or fake manager transition is used.
519
+ nimo.cleanup()
520
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
521
+ encoderThread.join(1_000)
522
+ val threadsBeforeScan = Thread.getAllStackTraces().keys
523
+ manager.sgc = null
524
+ NimoResourceDiagnostics.start(context)
525
+ val nonce = java.util.UUID.randomUUID().toString()
526
+ captureCommand("arm-capture", nonce, nonce)
527
+ val sdk = uninitializedSdk()
528
+ for ((name, value) in mapOf("appContext" to context, "deviceManager" to manager,
529
+ "discoveredDeviceNames" to mutableSetOf<String>())) {
530
+ com.mentra.bluetoothsdk.MentraBluetoothSdk::class.java.getDeclaredField(name).apply { isAccessible = true }.set(sdk, value)
531
+ }
532
+ Shadows.shadowOf(BluetoothAdapter.getDefaultAdapter()).setState(BluetoothAdapter.STATE_ON)
533
+ sdk.startScan(com.mentra.bluetoothsdk.DeviceModel.NIMO)
534
+ nimo = manager.sgc as Nimo
535
+ encoderThread = Thread.getAllStackTraces().keys.single {
536
+ it.name == "NimoCanvasEncoder" && it !in threadsBeforeScan
537
+ }
538
+ val admissionFile = File(context.filesDir, "nimo-lifecycle/$nonce.admission.json")
539
+ val admission = admissionFile.readText()
540
+ assertEquals(nimo.resourceInstanceId, JSONObject(admission).getString("instanceId"))
541
+ assertSame(nimo, manager.sgc)
542
+ val target = com.mentra.bluetoothsdk.Device(com.mentra.bluetoothsdk.DeviceModel.NIMO, "Nimo-test", "00:11:22:33:44:55")
543
+ sdk.connect(target, com.mentra.bluetoothsdk.ConnectOptions(saveAsDefault = false))
544
+ assertSame("SDK cancelExisting and manager connect must retain the scan instance", nimo, manager.sgc)
545
+ assertTrue(encoderThread.isAlive)
546
+ assertEquals(admission, admissionFile.readText())
547
+ val connectedCapture = captureCommand("capture-status", nonce).getJSONObject("session").getJSONObject("capture")
548
+ assertTrue(connectedCapture.getBoolean("connectStarted"))
549
+ // A duplicate must be refused before either layer can discard the original.
550
+ sdk.connect(target, com.mentra.bluetoothsdk.ConnectOptions(saveAsDefault = false))
551
+ assertSame(nimo, manager.sgc)
552
+ val cancel = java.util.UUID.randomUUID().toString()
553
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
554
+ .putExtra("nonce", cancel).putExtra("mode", "cancel-capture").putExtra("expectedName", "Nimo-test")
555
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", nonce))
556
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
557
+ val result = JSONObject(File(context.filesDir, "nimo-lifecycle/$cancel.json").readText())
558
+ assertEquals(nimo.resourceInstanceId, result.getJSONObject("session").getJSONObject("originalSession").getString("instanceId"))
559
+ assertEquals("local-drained-native-readback-required", result.getJSONObject("session").getJSONObject("originalSession").getJSONObject("release").getString("result"))
560
+ }
561
+
562
+ @Test fun ordinaryConnectPermissionRevocationDoesNotEscapePeerGuardsOrGattOpen() {
563
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
564
+ Shadows.shadowOf(device).setShouldThrowSecurityExceptions(true)
565
+ Shadows.shadowOf(ApplicationProvider.getApplicationContext<android.app.Application>())
566
+ .denyPermissions(android.Manifest.permission.BLUETOOTH_CONNECT)
567
+ for (name in listOf("connectCompanionGatt", "startBond", "connectBredrTransport")) {
568
+ Nimo::class.java.getDeclaredMethod(name, android.bluetooth.BluetoothDevice::class.java)
569
+ .apply { isAccessible = true }.invoke(nimo, device)
570
+ assertNull(field("gatt"))
571
+ }
572
+ assertTrue(nimo.resourceSnapshot().getJSONObject("release").getBoolean("transportFailure"))
573
+ }
574
+
575
+ @Test fun rejectedInitialLaunchDuringReleaseDoesNotInventAnExitAckOrWaitForOne() {
576
+ for (status in listOf(7, 8)) {
577
+ readyForReset(); setField("resourceSessionGeneration", 1L); setField("resourceReleased", false)
578
+ val canvas = field("canvas") as NimoCanvasCoordinator
579
+ canvas.activate(); canvas.readiness(true)
580
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
581
+ assertTrue(canvas.launchPending())
582
+ var result: JSONObject? = null
583
+ nimo.releaseResource(1L, { true }) { result = it }
584
+ canvas.response(1, byteArrayOf(status.toByte()))
585
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(200, TimeUnit.MILLISECONDS)
586
+ val release = requireNotNull(result).getJSONObject("release")
587
+ assertEquals("local-drained-native-readback-required", release.getString("result"))
588
+ assertFalse(release.getBoolean("displayExitRequired"))
589
+ assertTrue(release.isNull("displayExitStatus"))
590
+ assertEquals("unknown", release.getString("displayVisibleState"))
591
+ }
592
+ }
593
+
594
+ @Test fun ambiguousLaunchRejectionRetainsExitUnknownAndTimesOut() {
595
+ readyForReset(); setField("resourceSessionGeneration", 1L)
596
+ val canvas = field("canvas") as NimoCanvasCoordinator
597
+ canvas.activate(); canvas.readiness(true)
598
+ Shadows.shadowOf(Looper.getMainLooper()).idle()
599
+ var result: JSONObject? = null
600
+ nimo.releaseResource(1L, { true }) { result = it }
601
+ canvas.response(1, byteArrayOf(2))
602
+ Shadows.shadowOf(Looper.getMainLooper()).idleFor(16, TimeUnit.SECONDS)
603
+ val release = requireNotNull(result).getJSONObject("release")
604
+ assertEquals("drain-timeout-native-effects-unknown", release.getString("result"))
605
+ assertTrue(release.getBoolean("displayExitRequired"))
606
+ assertTrue(release.isNull("displayExitStatus"))
607
+ }
608
+
609
+ @Test fun explicitNewConnectAttemptClearsEarlierMutationEvidenceBeforeItsOwnEffects() {
610
+ setField("resourceBondMutationRequested", true); setField("resourceFactoryResetRequested", true)
611
+ val prior = nimo.resourceSnapshot()
612
+ nimo.connectById("Nimo-test")
613
+ val current = nimo.resourceSnapshot().getJSONObject("release")
614
+ assertFalse(current.getBoolean("bondMutationRequested")); assertFalse(current.getBoolean("factoryResetRequested"))
615
+ assertTrue(prior.getJSONObject("release").getBoolean("bondMutationRequested"))
616
+ }
617
+
618
+ @Test fun transportGenerationResetsOldReleaseObligationsButRetainsCurrentAttemptMutationEvidence() {
619
+ setField("resourceSessionGeneration", 1L)
620
+ setField("resourceMicStopRequired", true); setField("resourceExitRequired", true)
621
+ setField("resourceBondMutationRequested", true); setField("resourceFactoryResetRequested", true)
622
+ setField("resourceReleased", true)
623
+ val original = nimo.resourceSnapshot()
624
+ val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
625
+ Nimo::class.java.getDeclaredMethod("connectBredrTransport", android.bluetooth.BluetoothDevice::class.java)
626
+ .apply { isAccessible = true }.invoke(nimo, device)
627
+ val current = nimo.resourceSnapshot().getJSONObject("release")
628
+ assertEquals("not-requested", current.getString("result"))
629
+ assertFalse(current.getBoolean("micStopRequired")); assertFalse(current.getBoolean("displayExitRequired"))
630
+ assertFalse(field("resourceReleased") as Boolean)
631
+ assertTrue(current.getBoolean("bondMutationRequested")); assertTrue(current.getBoolean("factoryResetRequested"))
632
+ assertTrue(original.getJSONObject("release").getBoolean("micStopRequired"))
633
+ }
634
+
635
+ private fun uninitializedSdk(): com.mentra.bluetoothsdk.MentraBluetoothSdk {
636
+ // JVM fixture only. Reflection avoids Android bootclasspath references to JDK internals.
637
+ val type = Class.forName("sun.misc.Unsafe")
638
+ val allocator = type.getDeclaredField("theUnsafe").apply { isAccessible = true }.get(null)
639
+ return type.getMethod("allocateInstance", Class::class.java)
640
+ .invoke(allocator, com.mentra.bluetoothsdk.MentraBluetoothSdk::class.java) as com.mentra.bluetoothsdk.MentraBluetoothSdk
641
+ }
642
+
643
+ private fun awaitMainDispatch(thread: Thread) {
644
+ val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)
645
+ while (thread.isAlive && thread.state != Thread.State.WAITING && System.nanoTime() < deadline) Thread.yield()
646
+ assertTrue("SDK caller must wait for its main-queue result", thread.isAlive)
647
+ assertEquals(Thread.State.WAITING, thread.state)
648
+ }
649
+
650
+ private fun captureCommand(mode: String, captureNonce: String, requestNonce: String = java.util.UUID.randomUUID().toString()): JSONObject {
651
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
652
+ .putExtra("nonce", requestNonce).putExtra("mode", mode).putExtra("expectedName", "Nimo-test")
653
+ .putExtra("expectedAddress", "00:11:22:33:44:55").putExtra("captureNonce", captureNonce))
654
+ return JSONObject(File(context.filesDir, "nimo-lifecycle/$requestNonce.json").readText())
655
+ }
656
+
657
+ private fun field(name: String): Any? = Nimo::class.java.getDeclaredField(name).apply { isAccessible = true }.get(nimo)
658
+
659
+ private fun resourceCommand(mode: String): JSONObject {
660
+ val nonce = java.util.UUID.randomUUID().toString()
661
+ NimoResourceDiagnostics.execute(android.content.Intent(NimoResourceDiagnostics.ACTION)
662
+ .putExtra("nonce", nonce).putExtra("mode", mode).putExtra("expectedAddress", "00:11:22:33:44:55")
663
+ .putExtra("instanceId", nimo.resourceInstanceId).putExtra("sessionGeneration", 1L))
664
+ val file = File(context.filesDir, "nimo-lifecycle/$nonce.json")
665
+ return JSONObject(file.readText())
666
+ }
667
+
191
668
  private fun readyForReset(): MutableList<ByteArray> {
192
669
  val frames = mutableListOf<ByteArray>()
193
670
  val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
@@ -218,7 +695,7 @@ class NimoLifecycleTest {
218
695
  return frames
219
696
  }
220
697
 
221
- private fun setField(name: String, value: Any) {
698
+ private fun setField(name: String, value: Any?) {
222
699
  Nimo::class.java.getDeclaredField(name).apply { isAccessible = true }.set(nimo, value)
223
700
  }
224
701
 
@@ -1,10 +1,10 @@
1
1
  export const BLUETOOTH_SDK_RELEASE_METADATA = Object.freeze({
2
2
  "schemaVersion": 1,
3
3
  "familyBaseVersion": "3.4.0",
4
- "releaseIdentity": "3.4.0-dev.957",
5
- "releaseSetId": "mentra-3.4.0-dev.957",
6
- "sourceCommit": "e3c9413a4ce6f14d8697074474bb717336dcee80",
7
- "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.957.json",
8
- "otaManifestSha256": "75b864b765ff692c46f53b024bfa4972e1d6ccf43af0d46550ab0cfc494a7ddf"
4
+ "releaseIdentity": "3.4.0-dev.965",
5
+ "releaseSetId": "mentra-3.4.0-dev.965",
6
+ "sourceCommit": "7909ffb46c61953874fffacdc737f8070be28f06",
7
+ "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.965.json",
8
+ "otaManifestSha256": "798e597eba66ca395abd7a77cffdb86e9f6ffa7702625361b52aba8ba434f594"
9
9
  });
10
10
  //# sourceMappingURL=releaseMetadata.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"releaseMetadata.js","sourceRoot":"","sources":["../../src/generated/releaseMetadata.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,8BAA8B,GAA0C,MAAM,CAAC,MAAM,CAAC;IACjG,eAAe,EAAE,CAAC;IAClB,mBAAmB,EAAE,OAAO;IAC5B,iBAAiB,EAAE,eAAe;IAClC,cAAc,EAAE,sBAAsB;IACtC,cAAc,EAAE,0CAA0C;IAC1D,gBAAgB,EAAE,iIAAiI;IACnJ,mBAAmB,EAAE,kEAAkE;CACxF,CAAC,CAAA","sourcesContent":["/** Generated by release CI. Do not edit in a release checkout. */\nexport interface BluetoothSdkReleaseMetadata {\n schemaVersion: 1\n familyBaseVersion: string | null\n releaseIdentity: string | null\n releaseSetId: string | null\n sourceCommit: string | null\n otaManifestUrl: string | null\n otaManifestSha256: string | null\n}\n\nexport const BLUETOOTH_SDK_RELEASE_METADATA: Readonly<BluetoothSdkReleaseMetadata> = Object.freeze({\n \"schemaVersion\": 1,\n \"familyBaseVersion\": \"3.4.0\",\n \"releaseIdentity\": \"3.4.0-dev.957\",\n \"releaseSetId\": \"mentra-3.4.0-dev.957\",\n \"sourceCommit\": \"e3c9413a4ce6f14d8697074474bb717336dcee80\",\n \"otaManifestUrl\": \"https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.957.json\",\n \"otaManifestSha256\": \"75b864b765ff692c46f53b024bfa4972e1d6ccf43af0d46550ab0cfc494a7ddf\"\n})\n"]}
1
+ {"version":3,"file":"releaseMetadata.js","sourceRoot":"","sources":["../../src/generated/releaseMetadata.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,8BAA8B,GAA0C,MAAM,CAAC,MAAM,CAAC;IACjG,eAAe,EAAE,CAAC;IAClB,mBAAmB,EAAE,OAAO;IAC5B,iBAAiB,EAAE,eAAe;IAClC,cAAc,EAAE,sBAAsB;IACtC,cAAc,EAAE,0CAA0C;IAC1D,gBAAgB,EAAE,iIAAiI;IACnJ,mBAAmB,EAAE,kEAAkE;CACxF,CAAC,CAAA","sourcesContent":["/** Generated by release CI. Do not edit in a release checkout. */\nexport interface BluetoothSdkReleaseMetadata {\n schemaVersion: 1\n familyBaseVersion: string | null\n releaseIdentity: string | null\n releaseSetId: string | null\n sourceCommit: string | null\n otaManifestUrl: string | null\n otaManifestSha256: string | null\n}\n\nexport const BLUETOOTH_SDK_RELEASE_METADATA: Readonly<BluetoothSdkReleaseMetadata> = Object.freeze({\n \"schemaVersion\": 1,\n \"familyBaseVersion\": \"3.4.0\",\n \"releaseIdentity\": \"3.4.0-dev.965\",\n \"releaseSetId\": \"mentra-3.4.0-dev.965\",\n \"sourceCommit\": \"7909ffb46c61953874fffacdc737f8070be28f06\",\n \"otaManifestUrl\": \"https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.965.json\",\n \"otaManifestSha256\": \"798e597eba66ca395abd7a77cffdb86e9f6ffa7702625361b52aba8ba434f594\"\n})\n"]}
@@ -16,7 +16,7 @@ enum BluetoothSdkDefaults {
16
16
  /// silently disable it on every pair the app touches.
17
17
  static let autoPowerOffEnabled = false
18
18
  private static let infoSdkVersionKey = "MentraBluetoothSdkVersion"
19
- private static let swiftPackageSdkVersion = "3.4.0-dev.957"
19
+ private static let swiftPackageSdkVersion = "3.4.0-dev.965"
20
20
  private static let swiftPackageSdkVersionPlaceholder = "__MENTRA" + "_BLUETOOTH_SDK_VERSION__"
21
21
 
22
22
  private static func normalizedSdkVersion(_ value: String?) -> String? {
@@ -3,9 +3,9 @@ import Foundation
3
3
  /// Generated by release CI. Do not edit in a release checkout.
4
4
  enum GeneratedReleaseMetadata {
5
5
  static let familyBaseVersion = "3.4.0"
6
- static let releaseIdentity = "3.4.0-dev.957"
7
- static let releaseSetId = "mentra-3.4.0-dev.957"
8
- static let sourceCommit = "e3c9413a4ce6f14d8697074474bb717336dcee80"
9
- static let otaManifestUrl = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.957.json"
10
- static let otaManifestSha256 = "75b864b765ff692c46f53b024bfa4972e1d6ccf43af0d46550ab0cfc494a7ddf"
6
+ static let releaseIdentity = "3.4.0-dev.965"
7
+ static let releaseSetId = "mentra-3.4.0-dev.965"
8
+ static let sourceCommit = "7909ffb46c61953874fffacdc737f8070be28f06"
9
+ static let otaManifestUrl = "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.965.json"
10
+ static let otaManifestSha256 = "798e597eba66ca395abd7a77cffdb86e9f6ffa7702625361b52aba8ba434f594"
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mentra/bluetooth-sdk",
3
- "version": "3.4.0-dev.957",
3
+ "version": "3.4.0-dev.965",
4
4
  "description": "SDK for communicating with smart glasses",
5
5
  "main": "build/index.js",
6
6
  "react-native": "src/index.ts",
@@ -114,7 +114,7 @@
114
114
  "registry": "https://registry.npmjs.org/"
115
115
  },
116
116
  "dependencies": {
117
- "@mentra/cloud-protocol": "3.4.0-dev.957"
117
+ "@mentra/cloud-protocol": "3.4.0-dev.965"
118
118
  },
119
119
  "devDependencies": {
120
120
  "@types/node": "^25.9.3",
@@ -12,9 +12,9 @@ export interface BluetoothSdkReleaseMetadata {
12
12
  export const BLUETOOTH_SDK_RELEASE_METADATA: Readonly<BluetoothSdkReleaseMetadata> = Object.freeze({
13
13
  "schemaVersion": 1,
14
14
  "familyBaseVersion": "3.4.0",
15
- "releaseIdentity": "3.4.0-dev.957",
16
- "releaseSetId": "mentra-3.4.0-dev.957",
17
- "sourceCommit": "e3c9413a4ce6f14d8697074474bb717336dcee80",
18
- "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.957.json",
19
- "otaManifestSha256": "75b864b765ff692c46f53b024bfa4972e1d6ccf43af0d46550ab0cfc494a7ddf"
15
+ "releaseIdentity": "3.4.0-dev.965",
16
+ "releaseSetId": "mentra-3.4.0-dev.965",
17
+ "sourceCommit": "7909ffb46c61953874fffacdc737f8070be28f06",
18
+ "otaManifestUrl": "https://artifactscdn.mentraglass.com/Mentra-Community/MentraOS/releases/mentra-builds-v3.4.0/mentra-live-ota-3.4.0-dev.965.json",
19
+ "otaManifestSha256": "798e597eba66ca395abd7a77cffdb86e9f6ffa7702625361b52aba8ba434f594"
20
20
  })