@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.5.0-dev.1238

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 (140) hide show
  1. package/README.md +33 -11
  2. package/android/build.gradle +60 -51
  3. package/android/gradle.properties +3 -0
  4. package/android/settings.gradle +47 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +76 -3
  8. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +98 -120
  10. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  11. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  12. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +24 -9
  13. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +170 -23
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +13 -316
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  22. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  23. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  28. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  29. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  32. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  39. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  40. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  41. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  42. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  43. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  44. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  45. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  46. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  47. package/build/BluetoothSdk.types.d.ts +98 -1
  48. package/build/BluetoothSdk.types.d.ts.map +1 -1
  49. package/build/BluetoothSdk.types.js.map +1 -1
  50. package/build/_private/BluetoothSdkModule.d.ts +42 -7
  51. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  52. package/build/_private/BluetoothSdkModule.js +1 -0
  53. package/build/_private/BluetoothSdkModule.js.map +1 -1
  54. package/build/generated/changelogCatalog.d.ts +4 -1
  55. package/build/generated/changelogCatalog.d.ts.map +1 -1
  56. package/build/generated/changelogCatalog.js +5 -1
  57. package/build/generated/changelogCatalog.js.map +1 -1
  58. package/build/generated/releaseMetadata.js +6 -6
  59. package/build/generated/releaseMetadata.js.map +1 -1
  60. package/build/index.d.ts +1 -1
  61. package/build/index.d.ts.map +1 -1
  62. package/build/index.js +6 -0
  63. package/build/index.js.map +1 -1
  64. package/ios/BluetoothSdkModule.swift +66 -14
  65. package/ios/MentraBluetoothSDK.podspec +4 -0
  66. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  67. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  68. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  69. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  70. package/ios/Source/DeviceManager.swift +43 -22
  71. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  72. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  73. package/ios/Source/MentraBluetoothSDK.swift +27 -15
  74. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  75. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  76. package/ios/Source/audio/SpeechActivity.swift +277 -0
  77. package/ios/Source/events/BluetoothEvents.swift +41 -0
  78. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  79. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  80. package/ios/Source/sgcs/MentraLive.swift +173 -42
  81. package/ios/Source/sgcs/Nimo.swift +39 -272
  82. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  83. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  84. package/ios/Source/sgcs/SGCManager.swift +6 -0
  85. package/ios/Source/stt/STTTools.swift +13 -31
  86. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  87. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  88. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  89. package/ios/Source/utils/BoundedWait.swift +44 -0
  90. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  91. package/ios/Source/utils/SttModelTraits.swift +62 -0
  92. package/ios/Tests/BesCrashReportTests.swift +142 -0
  93. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  94. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  95. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  96. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  97. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  98. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  99. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  100. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  101. package/ios/Tests/PcmStreamTests.swift +299 -0
  102. package/ios/Tests/SpeechActivityTests.swift +238 -0
  103. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  104. package/package.json +2 -2
  105. package/plugin/build/withAndroid.js +9 -11
  106. package/plugin/build/withKotlinVersion.d.ts +2 -0
  107. package/plugin/build/withKotlinVersion.js +46 -0
  108. package/src/BluetoothSdk.types.ts +102 -1
  109. package/src/_private/BluetoothSdkModule.ts +45 -7
  110. package/src/generated/changelogCatalog.ts +5 -1
  111. package/src/generated/releaseMetadata.ts +6 -6
  112. package/src/index.ts +12 -0
  113. package/android/silero/LICENSE.md +0 -17
  114. package/android/silero/build.gradle +0 -50
  115. package/android/silero/proguard-rules.pro +0 -24
  116. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  117. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  118. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  119. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  120. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  121. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  122. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  123. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  124. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  125. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  126. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  127. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  128. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  129. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  130. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  131. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  132. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  133. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  134. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  135. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  136. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  137. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  138. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  139. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  140. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -1,851 +0,0 @@
1
- package com.mentra.bluetoothsdk.sgcs
2
-
3
- import android.bluetooth.BluetoothAdapter
4
- import android.bluetooth.BluetoothGattCharacteristic
5
- import org.robolectric.shadows.ShadowBluetoothGatt
6
- import android.content.BroadcastReceiver
7
- import android.content.Context
8
- import android.content.ContextWrapper
9
- import android.content.SharedPreferences
10
- import android.os.Handler
11
- import android.os.Looper
12
- import androidx.test.core.app.ApplicationProvider
13
- import com.mentra.bluetoothsdk.Bridge
14
- import com.mentra.bluetoothsdk.DeviceManager
15
- import com.mentra.bluetoothsdk.DeviceStore
16
- import com.mentra.bluetoothsdk.utils.ConnTypes
17
- import java.io.File
18
- import java.util.concurrent.TimeUnit
19
- import java.util.concurrent.atomic.AtomicReference
20
- import org.json.JSONObject
21
- import org.junit.After
22
- import org.junit.Assert.*
23
- import org.junit.Before
24
- import org.junit.Test
25
- import org.junit.runner.RunWith
26
- import org.robolectric.RobolectricTestRunner
27
- import org.robolectric.Shadows
28
- import org.robolectric.annotation.Config
29
- import org.robolectric.annotation.LooperMode
30
-
31
- @RunWith(RobolectricTestRunner::class)
32
- @Config(sdk = [33])
33
- @LooperMode(LooperMode.Mode.PAUSED)
34
- class NimoLifecycleTest {
35
- private class TrackingContext(base: Context) : ContextWrapper(base) {
36
- val unregisterLoopers = mutableListOf<Looper?>()
37
- val preferenceLoopers = mutableListOf<Looper?>()
38
- override fun getApplicationContext(): Context = this
39
- override fun getSharedPreferences(name: String, mode: Int): SharedPreferences {
40
- if (name == "NimoPrefs") preferenceLoopers.add(Looper.myLooper())
41
- return super.getSharedPreferences(name, mode)
42
- }
43
- override fun unregisterReceiver(receiver: BroadcastReceiver) {
44
- unregisterLoopers.add(Looper.myLooper())
45
- super.unregisterReceiver(receiver)
46
- }
47
- }
48
-
49
- private lateinit var context: TrackingContext
50
- private lateinit var nimo: Nimo
51
- private lateinit var encoderThread: Thread
52
- private lateinit var manager: DeviceManager
53
- private var previousManager: DeviceManager? = null
54
- private lateinit var diagnostics: NimoDiagnostics
55
- private lateinit var captureDirectory: File
56
- private lateinit var writeCompleted: () -> Unit
57
- private var writes = 0
58
- private val storeLoopers = mutableListOf<Looper?>()
59
- private var listener: String? = null
60
-
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
- }
73
- context = TrackingContext(ApplicationProvider.getApplicationContext())
74
- Bridge.initialize(context)
75
- manager = DeviceManager(initializeHardware = false)
76
- DeviceManager::class.java.getDeclaredField("_instance").apply { isAccessible = true }.let {
77
- previousManager = it.get(null) as DeviceManager?
78
- it.set(null, manager)
79
- }
80
- val threadsBefore = Thread.getAllStackTraces().keys
81
- nimo = Nimo()
82
- encoderThread = Thread.getAllStackTraces().keys.single {
83
- it.name == "NimoCanvasEncoder" && it !in threadsBefore
84
- }
85
- context.getSharedPreferences("NimoPrefs", Context.MODE_PRIVATE).edit()
86
- .putString("nimo_lastDeviceAddress", "00:11:22:33:44:55")
87
- .putString("nimo_lastDeviceName", "Nimo-test")
88
- .commit()
89
- DeviceStore.set("glasses", "connected", true)
90
- DeviceStore.set("glasses", "fullyBooted", true)
91
- DeviceStore.set("glasses", "connectionState", ConnTypes.CONNECTED)
92
- listener = DeviceStore.store.addListener { category, _ ->
93
- if (category == "glasses") storeLoopers.add(Looper.myLooper())
94
- }
95
- diagnostics = NimoDiagnostics(context, Handler(Looper.getMainLooper()), send = { _, completed ->
96
- writes += 1
97
- writeCompleted = completed
98
- true
99
- })
100
- diagnostics.connected(512)
101
- // Install the real debug collaborator without requiring a Bluetooth radio handshake.
102
- Nimo::class.java.getDeclaredField("diagnostics").apply { isAccessible = true }
103
- .set(nimo, diagnostics)
104
- val root = File(context.filesDir, "nimo-framebuffer")
105
- val previous = root.listFiles()?.map { it.name }?.toSet() ?: emptySet()
106
- // Receiver permission enforcement is a device test; this starts its real capture path.
107
- NimoDiagnostics::class.java.getDeclaredMethod("start", String::class.java)
108
- .apply { isAccessible = true }.invoke(diagnostics, "capture")
109
- captureDirectory = root.listFiles()!!.single { it.name !in previous }
110
- assertEquals(1, writes)
111
- }
112
-
113
- @After fun dispose() {
114
- nimo.cleanup()
115
- Shadows.shadowOf(Looper.getMainLooper()).idle()
116
- encoderThread.join(1_000)
117
- listener?.let { DeviceStore.store.removeListener(it) }
118
- manager.cleanup()
119
- DeviceManager::class.java.getDeclaredField("_instance").apply { isAccessible = true }
120
- .set(null, previousManager)
121
- }
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
-
180
- @Test fun offMainDisconnectCompletesOnMainAndInterruptsActiveCapture() {
181
- runOffMain { nimo.disconnect() }
182
- assertDisconnectedOnMain()
183
- assertRememberedDevice()
184
- }
185
-
186
- @Test fun offMainForgetClearsRememberedDeviceAfterMainThreadTeardown() {
187
- runOffMain { nimo.forget() }
188
- assertDisconnectedOnMain()
189
- val prefs = context.getSharedPreferences("NimoPrefs", Context.MODE_PRIVATE)
190
- assertFalse(prefs.contains("nimo_lastDeviceAddress"))
191
- assertFalse(prefs.contains("nimo_lastDeviceName"))
192
- assertTrue(context.preferenceLoopers.all { it === Looper.getMainLooper() })
193
- }
194
-
195
- @Test fun offMainCleanupClosesDiagnosticsAfterMainThreadTeardown() {
196
- runOffMain { nimo.cleanup() }
197
- assertDisconnectedOnMain()
198
- assertRememberedDevice()
199
- encoderThread.join(1_000)
200
- assertFalse("Cleanup left its encoder thread alive", encoderThread.isAlive)
201
- // A closed diagnostic cannot register another receiver or start a new capture.
202
- diagnostics.connected(512)
203
- NimoDiagnostics::class.java.getDeclaredMethod("start", String::class.java)
204
- .apply { isAccessible = true }.invoke(diagnostics, "capture")
205
- assertEquals(1, writes)
206
- }
207
-
208
- @Test fun resetForUnpairOfflineDoesNotSendFactoryCommand() {
209
- val results = mutableListOf<Boolean>()
210
- nimo.resetForUnpair { results.add(it) }
211
- assertEquals(listOf(false), results)
212
- }
213
-
214
- @Test fun explicitResetWaitsForMatchingAckAndCompletesOnlyOnce() {
215
- val frames = readyForReset()
216
- val results = mutableListOf<Boolean>()
217
- nimo.resetForUnpair { results.add(it) }
218
- Shadows.shadowOf(Looper.getMainLooper()).idle()
219
- assertTrue(results.isEmpty())
220
- assertArrayEquals(byteArrayOf(8, 3, 0, 0), frames.single().drop(8).toByteArray())
221
- assertEquals(2, frames.single()[1].toInt())
222
- respond(3, 1, 0)
223
- assertTrue(results.isEmpty())
224
- respond(8, 3, 0)
225
- respond(8, 3, 0)
226
- assertEquals(listOf(true), results)
227
- Shadows.shadowOf(Looper.getMainLooper()).idleFor(6, TimeUnit.SECONDS)
228
- assertEquals(listOf(true), results)
229
- }
230
-
231
- @Test fun resetTimeoutCompletesRatherThanLeavingUnpairWaitingForever() {
232
- readyForReset()
233
- val results = mutableListOf<Boolean>()
234
- nimo.resetForUnpair { results.add(it) }
235
- Shadows.shadowOf(Looper.getMainLooper()).idleFor(6, TimeUnit.SECONDS)
236
- assertEquals(listOf(false), results)
237
- respond(8, 3, 0)
238
- assertEquals(listOf(false), results)
239
- }
240
-
241
- @Test fun passiveForgetNeverSendsFactoryReset() {
242
- val frames = readyForReset()
243
- nimo.forget()
244
- assertTrue(frames.isEmpty())
245
- }
246
-
247
- @Test fun unbondTargetsOnlyTheSelectedNimo() {
248
- val adapter = BluetoothAdapter.getDefaultAdapter()
249
- val selected = adapter.getRemoteDevice("00:11:22:33:44:55")
250
- val other = adapter.getRemoteDevice("00:11:22:33:44:66")
251
- Shadows.shadowOf(selected).setCreatedBond(true)
252
- Shadows.shadowOf(other).setCreatedBond(true)
253
- Nimo.removeBluetoothBond(selected.address)
254
- // Robolectric tracks removeBond through this flag, independently of bondState.
255
- assertFalse(selected.createBond())
256
- assertTrue(other.createBond())
257
- }
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
-
754
- private fun readyForReset(): MutableList<ByteArray> {
755
- val frames = mutableListOf<ByteArray>()
756
- val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
757
- val gatt = ShadowBluetoothGatt.newInstance(device)
758
- setField("gatt", gatt)
759
- setField("txChar", BluetoothGattCharacteristic(NimoBLE.CHAR_TX, 8, 16))
760
- val state = Nimo::class.java.getDeclaredField("handshakeState")
761
- setField("handshakeState", state.type.enumConstants.single { it.toString() == "READY" })
762
- lateinit var queue: NimoGattQueue<BluetoothGattCharacteristic>
763
- queue = NimoGattQueue(
764
- NimoScheduler { delay, task ->
765
- val handler = Handler(Looper.getMainLooper())
766
- val pending = Runnable { task() }
767
- handler.postDelayed(pending, delay)
768
- val cancel: () -> Unit = { handler.removeCallbacks(pending) }
769
- cancel
770
- },
771
- { characteristic, bytes ->
772
- frames.add(bytes.copyOf())
773
- Handler(Looper.getMainLooper()).post { queue.written(gatt, characteristic, true) }
774
- true
775
- },
776
- { fail(it) },
777
- NimoBLE.INTER_FRAME_DELAY_MS,
778
- )
779
- queue.connected(gatt)
780
- setField("writes", queue)
781
- return frames
782
- }
783
-
784
- private fun setField(name: String, value: Any?) {
785
- Nimo::class.java.getDeclaredField(name).apply { isAccessible = true }.set(nimo, value)
786
- }
787
-
788
- private fun respond(cmd: Int, key: Int, status: Int) {
789
- Nimo::class.java.getDeclaredMethod("handleResponse", Int::class.javaPrimitiveType,
790
- Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, ByteArray::class.java)
791
- .apply { isAccessible = true }.invoke(nimo, cmd, key, status, byteArrayOf())
792
- }
793
-
794
- private fun runOffMain(operation: () -> Unit) {
795
- val failure = AtomicReference<Throwable?>()
796
- val caller = Thread({
797
- try {
798
- operation()
799
- // The manager may replace this instance immediately after return. An asynchronous
800
- // post is insufficient: the old connection must already be completely torn down.
801
- assertEquals(false, DeviceStore.get("glasses", "connected"))
802
- assertEquals(false, DeviceStore.get("glasses", "fullyBooted"))
803
- assertTrue(File(captureDirectory, "session.json").exists())
804
- } catch (error: Throwable) { failure.set(error) }
805
- }, "Expo-AsyncFunctionQueue-test")
806
- caller.start()
807
- // The Main looper is paused, so no teardown may have run on the Expo worker.
808
- assertEquals(true, DeviceStore.get("glasses", "connected"))
809
- assertEquals(true, DeviceStore.get("glasses", "fullyBooted"))
810
- assertRememberedDevice()
811
- assertTrue(context.unregisterLoopers.isEmpty())
812
- assertTrue(storeLoopers.isEmpty())
813
- assertTrue("Encoder stopped before Main processed teardown", encoderThread.isAlive)
814
- assertFalse(File(captureDirectory, "session.json").exists())
815
- val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
816
- while (caller.isAlive && System.nanoTime() < deadline) {
817
- Shadows.shadowOf(Looper.getMainLooper()).idle()
818
- caller.join(10)
819
- }
820
- if (caller.isAlive) {
821
- caller.interrupt()
822
- caller.join(1_000)
823
- fail("Lifecycle did not return after Main processed teardown")
824
- }
825
- failure.get()?.let { throw AssertionError("Off-main lifecycle entrypoint failed", it) }
826
- }
827
-
828
- private fun assertDisconnectedOnMain() {
829
- assertEquals(false, DeviceStore.get("glasses", "connected"))
830
- assertEquals(false, DeviceStore.get("glasses", "fullyBooted"))
831
- assertEquals(ConnTypes.DISCONNECTED, DeviceStore.get("glasses", "connectionState"))
832
- assertEquals(listOf(Looper.getMainLooper()), context.unregisterLoopers)
833
- assertTrue(storeLoopers.isNotEmpty())
834
- assertTrue(storeLoopers.all { it === Looper.getMainLooper() })
835
- val receiptFile = File(captureDirectory, "session.json")
836
- val beforeLateCallback = receiptFile.readText()
837
- val receipt = JSONObject(beforeLateCallback)
838
- assertFalse(receipt.getBoolean("ok"))
839
- assertTrue(receipt.getString("error").contains("disconnected"))
840
- writeCompleted()
841
- Shadows.shadowOf(Looper.getMainLooper()).idle()
842
- assertEquals(beforeLateCallback, receiptFile.readText())
843
- assertEquals(1, writes)
844
- }
845
-
846
- private fun assertRememberedDevice() {
847
- val prefs = context.getSharedPreferences("NimoPrefs", Context.MODE_PRIVATE)
848
- assertEquals("00:11:22:33:44:55", prefs.getString("nimo_lastDeviceAddress", null))
849
- assertEquals("Nimo-test", prefs.getString("nimo_lastDeviceName", null))
850
- }
851
- }