@mentra/bluetooth-sdk 3.4.0-dev.998 → 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
@@ -0,0 +1,112 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ import kotlinx.coroutines.CompletableDeferred
4
+ import kotlinx.coroutines.async
5
+ import kotlinx.coroutines.runBlocking
6
+ import org.junit.Assert.assertEquals
7
+ import org.junit.Assert.assertTrue
8
+ import org.junit.Assert.fail
9
+ import org.junit.Test
10
+
11
+ class BesCrashReportWaitersTest {
12
+ private val keyA = "ML395018B-dump-0000002a-1f2e3d4c"
13
+ private val keyB = "ML395018B-reset-9f3a0c1b2d4e5f60"
14
+
15
+ private fun ack(key: String, reportId: String?, ok: Boolean, error: String? = null): Map<String, Any> =
16
+ buildMap {
17
+ put("type", "bes_crash_reported_ack")
18
+ put("incidentKey", key)
19
+ reportId?.let { put("reportId", it) }
20
+ put("ok", ok)
21
+ error?.let { put("error", it) }
22
+ }
23
+
24
+ private suspend fun expectCode(code: String, block: suspend () -> Unit): BluetoothSdkException {
25
+ try {
26
+ block()
27
+ } catch (error: BluetoothSdkException) {
28
+ assertEquals(code, error.code)
29
+ return error
30
+ }
31
+ fail("expected $code")
32
+ throw AssertionError()
33
+ }
34
+
35
+ @Test fun `ack delivered during send resolves the call`() = runBlocking {
36
+ val waiters = BesCrashReportWaiters()
37
+ waiters.await(keyA, "rep_1", 1_000) { waiters.onAck(ack(keyA, "rep_1", ok = true)) }
38
+ }
39
+
40
+ @Test fun `concurrent incidents settle only their own call`() = runBlocking {
41
+ val waiters = BesCrashReportWaiters()
42
+ val sentA = CompletableDeferred<Unit>()
43
+ val sentB = CompletableDeferred<Unit>()
44
+ val a = async { waiters.await(keyA, "rep_a", 2_000) { sentA.complete(Unit) } }
45
+ val b = async { runCatching { waiters.await(keyB, "rep_b", 300) { sentB.complete(Unit) } } }
46
+ sentA.await()
47
+ sentB.await()
48
+ assertEquals(1, waiters.onAck(ack(keyA, "rep_a", ok = true)))
49
+ a.await()
50
+ val bResult = b.await()
51
+ assertEquals("request_timeout", (bResult.exceptionOrNull() as BluetoothSdkException).code)
52
+ }
53
+
54
+ @Test fun `ack for another reportId of the same incident is ignored`() = runBlocking {
55
+ val waiters = BesCrashReportWaiters()
56
+ expectCode("request_timeout") {
57
+ waiters.await(keyA, "rep_new", 200) {
58
+ assertEquals(0, waiters.onAck(ack(keyA, "rep_old", ok = true)))
59
+ }
60
+ }
61
+ Unit
62
+ }
63
+
64
+ @Test fun `ok false rejects with the glasses error`() = runBlocking {
65
+ val waiters = BesCrashReportWaiters()
66
+ val error = expectCode("bes_crash_report_rejected") {
67
+ waiters.await(keyA, "rep_1", 1_000) {
68
+ waiters.onAck(ack(keyA, "rep_1", ok = false, error = "unknown_incident"))
69
+ }
70
+ }
71
+ assertTrue(error.message!!.contains("unknown_incident"))
72
+ }
73
+
74
+ @Test fun `ok false without reportId rejects every call for that incident only`() = runBlocking {
75
+ val waiters = BesCrashReportWaiters()
76
+ val sent = CompletableDeferred<Unit>()
77
+ val other = async { runCatching { waiters.await(keyB, "rep_b", 300) { sent.complete(Unit) } } }
78
+ sent.await()
79
+ expectCode("bes_crash_report_rejected") {
80
+ waiters.await(keyA, "rep_1", 1_000) {
81
+ assertEquals(1, waiters.onAck(ack(keyA, null, ok = false, error = "unknown_incident")))
82
+ }
83
+ }
84
+ assertEquals("request_timeout", (other.await().exceptionOrNull() as BluetoothSdkException).code)
85
+ }
86
+
87
+ @Test fun `ok true without reportId does not resolve`() = runBlocking {
88
+ val waiters = BesCrashReportWaiters()
89
+ expectCode("request_timeout") {
90
+ waiters.await(keyA, "rep_1", 200) { assertEquals(0, waiters.onAck(ack(keyA, null, ok = true))) }
91
+ }
92
+ Unit
93
+ }
94
+
95
+ @Test fun `disconnect rejects pending calls`() = runBlocking {
96
+ val waiters = BesCrashReportWaiters()
97
+ expectCode("glasses_not_connected") {
98
+ waiters.await(keyA, "rep_1", 5_000) {
99
+ waiters.rejectAll(BluetoothSdkException("glasses_not_connected", "disconnected"))
100
+ }
101
+ }
102
+ Unit
103
+ }
104
+
105
+ @Test fun `send failure propagates and leaves no waiter behind`() = runBlocking {
106
+ val waiters = BesCrashReportWaiters()
107
+ expectCode("glasses_not_connected") {
108
+ waiters.await(keyA, "rep_1", 1_000) { throw BluetoothSdkException("glasses_not_connected", "no link") }
109
+ }
110
+ assertEquals(0, waiters.onAck(ack(keyA, "rep_1", ok = true)))
111
+ }
112
+ }
@@ -0,0 +1,141 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.os.Looper
4
+ import androidx.test.core.app.ApplicationProvider
5
+ import com.mentra.bluetoothsdk.Bridge
6
+ import com.mentra.bluetoothsdk.utils.ConnTypes
7
+ import java.time.Duration
8
+ import org.json.JSONObject
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertNotEquals
11
+ import org.junit.Assert.assertNotNull
12
+ import org.junit.Test
13
+ import org.junit.runner.RunWith
14
+ import org.robolectric.RobolectricTestRunner
15
+ import org.robolectric.Shadows.shadowOf
16
+ import org.robolectric.annotation.Config
17
+ import org.robolectric.annotation.LooperMode
18
+
19
+ @RunWith(RobolectricTestRunner::class)
20
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class], instrumentedPackages = ["com.mentra.lc3Lib"])
21
+ @LooperMode(LooperMode.Mode.PAUSED)
22
+ class MentraLiveGlassesReadyBurstTest {
23
+ @Test fun `buffered phone_ready copies are one exchange with one init`() = withLive { live, inits ->
24
+ // Two SOC-ready heartbeats while the glasses boot: one exchange, sent twice.
25
+ receive(live, socReady())
26
+ val readyId = pendingReadyId(live)
27
+ receive(live, socReady())
28
+ assertEquals(readyId, pendingReadyId(live))
29
+
30
+ // The glasses answer every buffered copy; only the first followed a reset.
31
+ repeat(7) { receive(live, glassesReady("booted", readyId)) }
32
+ assertEquals(1, inits())
33
+ }
34
+
35
+ @Test fun `answers to a superseded exchange are ignored until the pending one arrives`() = withLive { live, inits ->
36
+ receive(live, socReady())
37
+ val first = pendingReadyId(live)
38
+ receive(live, glassesReady("booted", first))
39
+ invoke(live, "sendPhoneReady", "readiness re-run")
40
+ val second = pendingReadyId(live)
41
+
42
+ // The same process already reset for the first exchange; the pending one is still to come.
43
+ receive(live, glassesReady("booted", first))
44
+ assertEquals(1, inits())
45
+ receive(live, glassesReady("booted", second))
46
+ assertEquals(2, inits())
47
+ }
48
+
49
+ @Test fun `an answer from another glasses process is handled with no exchange pending`() = withLive { live, inits ->
50
+ receive(live, socReady())
51
+ val readyId = pendingReadyId(live)
52
+ receive(live, glassesReady("booted", readyId))
53
+
54
+ // A restarted process reset its transport for this copy, so it is not a repeat.
55
+ receive(live, glassesReady("restarted", readyId))
56
+ assertEquals(2, inits())
57
+ }
58
+
59
+ @Test fun `a restarted process answering an older copy is handled and the pending exchange still counts`() = withLive { live, inits ->
60
+ receive(live, socReady())
61
+ val first = pendingReadyId(live)
62
+ receive(live, glassesReady("booted", first))
63
+ invoke(live, "sendPhoneReady", "glasses session changed")
64
+ val second = pendingReadyId(live)
65
+
66
+ // The restarted process reset for a buffered copy of the old exchange, then resets
67
+ // again for the pending one: both answers follow a reset.
68
+ receive(live, glassesReady("restarted", first))
69
+ assertEquals(2, inits())
70
+ receive(live, glassesReady("restarted", second))
71
+ assertEquals(3, inits())
72
+ receive(live, glassesReady("restarted", second))
73
+ assertEquals(3, inits())
74
+ }
75
+
76
+ @Test fun `the readiness exchange ends with the BLE session`() = withLive { live, _ ->
77
+ receive(live, socReady())
78
+ val first = pendingReadyId(live)
79
+ invoke(live, "updateConnectionState", ConnTypes.DISCONNECTED)
80
+
81
+ receive(live, socReady())
82
+ assertNotEquals(first, pendingReadyId(live))
83
+ }
84
+
85
+ @Test fun `glasses without readyId keep initializing on every answer`() = withLive { live, inits ->
86
+ receive(live, glassesReady("legacy", null))
87
+ receive(live, glassesReady("legacy", null))
88
+ assertEquals(2, inits())
89
+ }
90
+
91
+ /**
92
+ * Runs `body` on a fresh MentraLive with a live link, counting SOC inits (one version
93
+ * request each). glasses_ready is only accepted on a live link.
94
+ */
95
+ private fun withLive(body: (MentraLive, () -> Int) -> Unit) {
96
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
97
+ val live = MentraLive()
98
+ MentraLive::class.java.getDeclaredField("isConnected").apply { isAccessible = true }.set(live, true)
99
+ var inits = 0
100
+ val sink = Bridge.addEventSink { type, event ->
101
+ if (type == "log" && event["message"].toString().contains("Requesting version info from ASG client")) {
102
+ inits++
103
+ }
104
+ }
105
+ try {
106
+ body(live) { inits }
107
+ } finally {
108
+ Bridge.removeEventSink(sink)
109
+ live.destroy()
110
+ shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(2))
111
+ }
112
+ }
113
+
114
+ private fun socReady() = JSONObject().put("C", "sr_hrt").put("B", JSONObject().put("ready", 1))
115
+
116
+ private fun glassesReady(sid: String, readyId: String?) = JSONObject().apply {
117
+ put("type", "glasses_ready")
118
+ put("sid", sid)
119
+ if (readyId != null) put("readyId", readyId)
120
+ }
121
+
122
+ private fun pendingReadyId(live: MentraLive): String {
123
+ val readyId = MentraLive::class.java.getDeclaredField("pendingReadyId")
124
+ .apply { isAccessible = true }
125
+ .get(live) as String?
126
+ assertNotNull("SOC ready should start a readiness exchange", readyId)
127
+ return readyId!!
128
+ }
129
+
130
+ private fun receive(live: MentraLive, json: JSONObject) {
131
+ MentraLive::class.java.getDeclaredMethod("processJsonMessage", JSONObject::class.java)
132
+ .apply { isAccessible = true }
133
+ .invoke(live, json)
134
+ }
135
+
136
+ private fun invoke(live: MentraLive, name: String, argument: String) {
137
+ MentraLive::class.java.getDeclaredMethod(name, String::class.java)
138
+ .apply { isAccessible = true }
139
+ .invoke(live, argument)
140
+ }
141
+ }
@@ -8,9 +8,14 @@ import androidx.test.core.app.ApplicationProvider
8
8
  import com.mentra.bluetoothsdk.BluetoothSdkException
9
9
  import com.mentra.bluetoothsdk.Bridge
10
10
  import com.mentra.bluetoothsdk.DeviceStore
11
+ import com.mentra.bluetoothsdk.utils.IncidentLogBleRelayNaming
12
+ import java.net.ServerSocket
13
+ import java.net.SocketException
11
14
  import java.nio.charset.StandardCharsets
12
15
  import java.time.Duration
13
16
  import java.util.UUID
17
+ import java.util.concurrent.LinkedBlockingQueue
18
+ import java.util.concurrent.TimeUnit
14
19
  import java.util.concurrent.atomic.AtomicLong
15
20
  import org.junit.Assert.*
16
21
  import org.junit.Test
@@ -20,12 +25,14 @@ import org.robolectric.Shadows.shadowOf
20
25
  import org.robolectric.annotation.Config
21
26
  import org.robolectric.annotation.LooperMode
22
27
  import org.robolectric.shadows.ShadowLog
28
+ import org.robolectric.shadows.ShadowSystemClock
23
29
 
24
30
  @RunWith(RobolectricTestRunner::class)
25
31
  @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class], instrumentedPackages = ["com.mentra.lc3Lib"])
26
32
  @LooperMode(LooperMode.Mode.PAUSED)
27
33
  class MentraLiveIncidentDispatchTest {
28
34
  private val incident = "rep_01M4HBVT88DFSN8TYNZ1WTV4PB"
35
+ private val collidingIncident = "rep_01M4HBVT88DZZZZZZZZZZZZZZZ"
29
36
  private val apiBase = "https://core.dev.us-west-2.mentraglass.com"
30
37
 
31
38
  @Test fun `missing native BLE link rejects even when cached status is connected`() = withLive { live ->
@@ -45,6 +52,14 @@ class MentraLiveIncidentDispatchTest {
45
52
  prefs.edit().remove("core_token").commit()
46
53
  }
47
54
 
55
+ @Test fun `deletes the Core token older builds left in plain storage`() {
56
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
57
+ val prefs = context.getSharedPreferences("augmentos_auth_prefs", android.content.Context.MODE_PRIVATE)
58
+ prefs.edit().putString("core_token", "stale-synthetic-token").commit()
59
+ withLive { }
60
+ assertFalse(prefs.contains("core_token"))
61
+ }
62
+
48
63
  @Test fun `current token is queued before upload and never logged`() = withLive { live ->
49
64
  ready(live)
50
65
  val token = "synthetic-${UUID.randomUUID()}"
@@ -87,6 +102,174 @@ class MentraLiveIncidentDispatchTest {
87
102
  } finally { Bridge.removeEventSink(sink) }
88
103
  }
89
104
 
105
+ @Test fun `colliding report waits for the owner's Cloud confirmation and never receives its evidence`() = withLive { live ->
106
+ ready(live)
107
+ DeviceStore.set("bluetooth", "core_token", "synthetic")
108
+ withCloud { cloud ->
109
+ val name = IncidentLogBleRelayNaming.bleFileBaseName(incident, 'B')
110
+ assertEquals(name, IncidentLogBleRelayNaming.bleFileBaseName(collidingIncident, 'B'))
111
+
112
+ live.sendIncidentId(incident, cloud.base)
113
+ expectCode("incident_relay_busy") { live.sendIncidentId(collidingIncident, cloud.base) }
114
+ assertFalse(wire(live).contains(collidingIncident))
115
+ assertEquals(incident, relayOwner(live, name))
116
+ assertEquals(incident, relayOwner(live, IncidentLogBleRelayNaming.bleFileBaseName(incident, 'L')))
117
+
118
+ receiveRelayFile(live, name, "owner-evidence")
119
+ assertEquals("/api/client/reports/$incident/artifacts owner-evidence", cloud.requests.poll(5, TimeUnit.SECONDS))
120
+ awaitMain { relayOwner(live, name) == null }
121
+ val confirmation = wire(live).substringAfterLast("transfer_complete")
122
+ assertTrue(confirmation.contains(name) && confirmation.contains("\"success\":true"))
123
+
124
+ // The owner's logcat name is still in flight, so the colliding report is still refused.
125
+ val logName = IncidentLogBleRelayNaming.bleFileBaseName(incident, 'L')
126
+ expectCode("incident_relay_busy") { live.sendIncidentId(collidingIncident, cloud.base) }
127
+ receiveRelayFile(live, logName, "owner-logcat")
128
+ assertEquals("/api/client/reports/$incident/artifacts owner-logcat", cloud.requests.poll(5, TimeUnit.SECONDS))
129
+ awaitMain { relayOwner(live, logName) == null }
130
+
131
+ live.sendIncidentId(collidingIncident, cloud.base)
132
+ receiveRelayFile(live, name, "second-evidence")
133
+ assertEquals(
134
+ "/api/client/reports/$collidingIncident/artifacts second-evidence",
135
+ cloud.requests.poll(5, TimeUnit.SECONDS),
136
+ )
137
+ }
138
+ }
139
+
140
+ @Test fun `stale callback of a finished owner cannot confirm the colliding report's file`() = withLive { live ->
141
+ ready(live)
142
+ DeviceStore.set("bluetooth", "core_token", "synthetic")
143
+ withCloud { cloud ->
144
+ val name = IncidentLogBleRelayNaming.bleFileBaseName(incident, 'B')
145
+ val logName = IncidentLogBleRelayNaming.bleFileBaseName(incident, 'L')
146
+ live.sendIncidentId(incident, cloud.base)
147
+ val staleRelay = (get(live, "bleIncidentLogRelays") as Map<*, *>)[name]!!
148
+ receiveRelayFile(live, name, "owner")
149
+ assertNotNull(cloud.requests.poll(5, TimeUnit.SECONDS))
150
+ awaitMain { relayOwner(live, name) == null }
151
+ receiveRelayFile(live, logName, "owner-logcat")
152
+ assertNotNull(cloud.requests.poll(5, TimeUnit.SECONDS))
153
+ awaitMain { relayOwner(live, logName) == null }
154
+
155
+ live.sendIncidentId(collidingIncident, cloud.base)
156
+ val confirmationsBefore = wire(live).split("transfer_complete").size
157
+
158
+ // A late callback of the first report's request arrives while the colliding report owns the name.
159
+ uploadWith(live, staleRelay, name, "late-owner-evidence")
160
+ assertNotNull(cloud.requests.poll(5, TimeUnit.SECONDS))
161
+ repeat(50) { shadowOf(Looper.getMainLooper()).idle(); Thread.sleep(10) }
162
+
163
+ assertEquals(confirmationsBefore, wire(live).split("transfer_complete").size)
164
+ assertEquals(collidingIncident, relayOwner(live, name))
165
+ }
166
+ }
167
+
168
+ @Test fun `failed Cloud POST keeps the owner until its ownership expires`() = withLive { live ->
169
+ ready(live)
170
+ DeviceStore.set("bluetooth", "core_token", "synthetic")
171
+ withCloud { cloud ->
172
+ cloud.status = 500
173
+ val name = IncidentLogBleRelayNaming.bleFileBaseName(incident, 'B')
174
+ live.sendIncidentId(incident, cloud.base)
175
+ receiveRelayFile(live, name, "owner-evidence")
176
+ assertNotNull(cloud.requests.poll(5, TimeUnit.SECONDS))
177
+ awaitMain { wire(live).contains("\"success\":false") }
178
+ assertEquals(incident, relayOwner(live, name))
179
+ expectCode("incident_relay_busy") { live.sendIncidentId(collidingIncident, cloud.base) }
180
+ live.sendIncidentId(incident, cloud.base)
181
+
182
+ ShadowSystemClock.advanceBy(Duration.ofMillis(MentraLive.INCIDENT_RELAY_OWNERSHIP_MS))
183
+ live.sendIncidentId(collidingIncident, cloud.base)
184
+ assertEquals(collidingIncident, relayOwner(live, name))
185
+ }
186
+ }
187
+
188
+ @Test fun `dispatch failure of a refused report cannot release the owner's names`() = withLive { live ->
189
+ ready(live)
190
+ DeviceStore.set("bluetooth", "core_token", "synthetic")
191
+ live.sendIncidentId(incident, apiBase)
192
+ set(live, "txCharacteristic", null)
193
+ expectCode("glasses_not_connected") { live.sendIncidentId(collidingIncident, apiBase) }
194
+ assertEquals(incident, relayOwner(live, IncidentLogBleRelayNaming.bleFileBaseName(incident, 'B')))
195
+ }
196
+
197
+ // A plain socket server: com.sun.net.httpserver is not on the Android unit-test classpath.
198
+ private class FakeCloud(val server: ServerSocket) {
199
+ @Volatile var status = 200
200
+ val requests = LinkedBlockingQueue<String>()
201
+ val base get() = "http://127.0.0.1:${server.localPort}"
202
+ }
203
+
204
+ private fun withCloud(body: (FakeCloud) -> Unit) {
205
+ val server = ServerSocket(0, 50, java.net.InetAddress.getByName("127.0.0.1"))
206
+ val cloud = FakeCloud(server)
207
+ val acceptor = Thread {
208
+ while (!server.isClosed) {
209
+ try {
210
+ server.accept().use { socket ->
211
+ val input = socket.getInputStream().buffered()
212
+ fun line(): String {
213
+ val sb = StringBuilder()
214
+ while (true) {
215
+ val c = input.read()
216
+ if (c < 0 || c == '\n'.code) break
217
+ if (c != '\r'.code) sb.append(c.toChar())
218
+ }
219
+ return sb.toString()
220
+ }
221
+ val path = line().split(" ").getOrElse(1) { "" }.substringBefore('?')
222
+ var length = 0
223
+ while (true) {
224
+ val header = line()
225
+ if (header.isEmpty()) break
226
+ if (header.startsWith("content-length:", ignoreCase = true)) {
227
+ length = header.substringAfter(':').trim().toInt()
228
+ }
229
+ }
230
+ val received = String(input.readNBytes(length), StandardCharsets.UTF_8)
231
+ cloud.requests.add("$path $received")
232
+ socket.getOutputStream().write(
233
+ "HTTP/1.1 ${cloud.status} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
234
+ .toByteArray(StandardCharsets.US_ASCII))
235
+ socket.getOutputStream().flush()
236
+ }
237
+ } catch (_: SocketException) {
238
+ // closed by the test
239
+ }
240
+ }
241
+ }.apply { isDaemon = true; start() }
242
+ try { body(cloud) } finally { server.close(); acceptor.join(2_000) }
243
+ }
244
+
245
+ private fun receiveRelayFile(live: MentraLive, name: String, payload: String) {
246
+ uploadWith(live, (get(live, "bleIncidentLogRelays") as Map<*, *>)[name]!!, name, payload)
247
+ }
248
+
249
+ private fun uploadWith(live: MentraLive, relay: Any, name: String, payload: String) {
250
+ MentraLive::class.java.declaredMethods.first { it.name == "uploadBleIncidentLogPayload" }
251
+ .apply { isAccessible = true }
252
+ .invoke(live, relay, name, payload.toByteArray(StandardCharsets.UTF_8))
253
+ }
254
+
255
+ private fun relayOwner(live: MentraLive, name: String): String? {
256
+ val relay = (get(live, "bleIncidentLogRelays") as Map<*, *>)[name] ?: return null
257
+ return relay.javaClass.getDeclaredField("incidentId").apply { isAccessible = true }.get(relay) as String
258
+ }
259
+
260
+ private fun awaitMain(condition: () -> Boolean) {
261
+ val deadline = System.currentTimeMillis() + 5_000
262
+ while (!condition() && System.currentTimeMillis() < deadline) {
263
+ shadowOf(Looper.getMainLooper()).idle()
264
+ Thread.sleep(10)
265
+ }
266
+ assertTrue(condition())
267
+ }
268
+
269
+ // sendJson wraps each message as {"C":"<escaped json>"}; unescape so assertions read the message.
270
+ private fun wire(live: MentraLive): String =
271
+ queuedWrites(live).joinToString("") { String(it, StandardCharsets.UTF_8) }.replace("\\\"", "\"")
272
+
90
273
  private fun ready(live: MentraLive) {
91
274
  val context = ApplicationProvider.getApplicationContext<android.content.Context>()
92
275
  val gatt = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("AA:BB:CC:DD:EE:FF")
@@ -0,0 +1,76 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.os.Looper
4
+ import androidx.test.core.app.ApplicationProvider
5
+ import com.mentra.bluetoothsdk.Bridge
6
+ import java.time.Duration
7
+ import org.json.JSONObject
8
+ import org.junit.Assert.assertEquals
9
+ import org.junit.Assert.assertTrue
10
+ import org.junit.Test
11
+ import org.junit.runner.RunWith
12
+ import org.robolectric.RobolectricTestRunner
13
+ import org.robolectric.Shadows.shadowOf
14
+ import org.robolectric.annotation.Config
15
+ import org.robolectric.annotation.LooperMode
16
+
17
+ /**
18
+ * The glasses answer every RGB LED command with `rgb_led_control_response` echoing the command's
19
+ * requestId. MentraLive must forward that reply so the pending SDK request settles instead of
20
+ * timing out.
21
+ */
22
+ @RunWith(RobolectricTestRunner::class)
23
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class], instrumentedPackages = ["com.mentra.lc3Lib"])
24
+ @LooperMode(LooperMode.Mode.PAUSED)
25
+ class MentraLiveRgbLedResponseTest {
26
+ @Test fun `success reply settles the request it echoes`() {
27
+ val replies = forwardedReplies(
28
+ JSONObject().put("type", "rgb_led_control_response").put("requestId", "led-1")
29
+ .put("state", "success").put("success", true),
30
+ )
31
+
32
+ assertEquals(1, replies.size)
33
+ assertEquals("led-1", replies[0]["requestId"])
34
+ assertEquals("success", replies[0]["state"])
35
+ }
36
+
37
+ @Test fun `error reply carries the glasses error code`() {
38
+ val replies = forwardedReplies(
39
+ JSONObject().put("type", "rgb_led_control_response").put("requestId", "led-2")
40
+ .put("state", "error").put("success", false)
41
+ .put("errorCode", "device_not_supported").put("error", "RGB LED not supported"),
42
+ )
43
+
44
+ assertEquals(1, replies.size)
45
+ assertEquals("error", replies[0]["state"])
46
+ assertEquals("device_not_supported", replies[0]["errorCode"])
47
+ }
48
+
49
+ @Test fun `reply without a requestId is not forwarded`() {
50
+ val replies = forwardedReplies(
51
+ JSONObject().put("type", "rgb_led_control_response").put("state", "success"),
52
+ )
53
+
54
+ assertTrue(replies.isEmpty())
55
+ }
56
+
57
+ private fun forwardedReplies(reply: JSONObject): List<Map<String, Any?>> {
58
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
59
+ val live = MentraLive()
60
+ val replies = mutableListOf<Map<String, Any?>>()
61
+ val sink = Bridge.addEventSink { type, body ->
62
+ if (type == "rgb_led_control_response") replies.add(body.toMap())
63
+ }
64
+ try {
65
+ MentraLive::class.java.getDeclaredMethod("processJsonMessage", JSONObject::class.java)
66
+ .apply { isAccessible = true }
67
+ .invoke(live, reply)
68
+ shadowOf(Looper.getMainLooper()).idle()
69
+ } finally {
70
+ Bridge.removeEventSink(sink)
71
+ live.destroy()
72
+ shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(2))
73
+ }
74
+ return replies
75
+ }
76
+ }
@@ -31,12 +31,11 @@ class NimoCanvasCoordinatorTest {
31
31
  val writes = mutableListOf<ByteArray>()
32
32
  val failures = mutableListOf<String>()
33
33
  val rejections = mutableListOf<Int>()
34
- var holdPreemptions = 0
35
34
  var rejectWrites = false
36
35
  val queue = NimoGattQueue<Any>(clock, { _, bytes -> writes += bytes; !rejectWrites }, { failures += it })
37
36
  val canvas = NimoCanvasCoordinator(clock, { 20 },
38
37
  { frames, started, completed -> queue.enqueue(connection, characteristic, frames, started, completed) },
39
- { queue.reset(); failures += it }, { rejections += it }, { holdPreemptions++ })
38
+ { queue.reset(); failures += it }, { rejections += it })
40
39
  init { queue.connected(connection) }
41
40
  fun written(success: Boolean = true) {
42
41
  queue.written(connection, characteristic, success)
@@ -244,60 +243,6 @@ class NimoCanvasCoordinatorTest {
244
243
  assertTrue(f.failures.isEmpty())
245
244
  }
246
245
 
247
- @Test fun diagnosticHoldWaitsForCurrentBusinessAckAndThenResumesLatestScene() {
248
- val f = Fixture()
249
- val initial = byteArrayOf(0, 0, 1)
250
- val latest = byteArrayOf(2, 0, 1)
251
- f.launch(initial)
252
- var ready = 0
253
- f.canvas.hold { ready++ }
254
- f.canvas.offer(byteArrayOf(1, 0, 1), "one:1")
255
- f.canvas.offer(latest, "one:1")
256
-
257
- assertEquals(0, ready)
258
- f.finishUpdate(initial)
259
- assertEquals(1, ready)
260
- val beforeRelease = f.writes.size
261
-
262
- f.canvas.releaseHold()
263
-
264
- assertEquals(beforeRelease + 1, f.writes.size)
265
- assertArrayEquals(NimoCanvasCodec.frames(4, latest, 20).first(), f.writes.last())
266
- }
267
-
268
- @Test fun scopeTakeoverPreemptsHoldWithoutFlushingHeldScene() {
269
- val f = Fixture()
270
- val initial = byteArrayOf(0, 0, 1)
271
- val held = byteArrayOf(1, 0, 1)
272
- val takeover = byteArrayOf(2, 0, 1)
273
- f.launch(initial); f.finishUpdate(initial)
274
- var ready = 0
275
- f.canvas.hold { ready++ }
276
- f.canvas.offer(held, "one:1")
277
- val beforeTakeover = f.writes.size
278
-
279
- f.canvas.offer(takeover, "two:1")
280
-
281
- assertEquals(1, ready)
282
- assertEquals(1, f.holdPreemptions)
283
- assertEquals(beforeTakeover + 1, f.writes.size)
284
- assertArrayEquals(NimoCanvasCodec.frames(4, takeover, 20).first(), f.writes.last())
285
- }
286
-
287
- @Test fun firstScopePreemptsHoldAcquiredBeforeAnyCanvasScene() {
288
- val f = Fixture()
289
- var ready = 0
290
- f.canvas.readiness(true)
291
- f.canvas.hold { ready++ }
292
- assertEquals(1, ready)
293
-
294
- f.canvas.offer(byteArrayOf(0, 0, 1), "first:1")
295
-
296
- assertEquals(1, f.holdPreemptions)
297
- assertEquals(1, f.writes.size)
298
- assertArrayEquals(NimoCanvasCodec.frames(1, writeCapacity = 20).single(), f.writes.single())
299
- }
300
-
301
246
  @Test fun reentrantCompletionCannotReleaseNewConnectionWrite() {
302
247
  val f = Fixture(); val old = f.connection
303
248
  f.queue.enqueue(old, f.characteristic, listOf(byteArrayOf(1)), completed = {
@@ -314,26 +314,4 @@ class NimoCanvasSessionTest {
314
314
  assertThrows(IllegalArgumentException::class.java) { session.offer(ByteArray(12281), "one:1") }
315
315
  }
316
316
 
317
- @Test fun diagnosticHoldRetainsOnlyLatestSceneUntilReleased() {
318
- val session = NimoCanvasSession()
319
- launched(session); success(session, 4)
320
-
321
- assertTrue(session.hold(true).isEmpty())
322
- assertTrue(session.offer(frameB, "two:1").isEmpty())
323
- assertTrue(session.offer(frameC, "two:2", force = true).isEmpty())
324
-
325
- val update = send(session.hold(false))
326
- assertEquals(4, update.key)
327
- assertArrayEquals(frameC, update.frame)
328
- }
329
-
330
- @Test fun preemptedHoldDoesNotFlushStaleSceneBeforeExit() {
331
- val session = NimoCanvasSession()
332
- launched(session); success(session, 4)
333
- session.hold(true)
334
- session.offer(frameB, "two:1")
335
-
336
- assertTrue(session.hold(false, resume = false).isEmpty())
337
- assertEquals(3, send(session.exit()).key)
338
- }
339
317
  }
@@ -0,0 +1,23 @@
1
+ package com.mentra.bluetoothsdk.utils
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Assert.assertFalse
5
+ import org.junit.Assert.assertTrue
6
+ import org.junit.Test
7
+
8
+ class IncidentLogBleRelayNamingTest {
9
+ @Test fun `relay names built for a report are recognized`() {
10
+ val firmware = IncidentLogBleRelayNaming.bleFileBaseName("rep_01M4HBVT88DFSN8TYNZ1WTV4PB", 'B')
11
+ val logcat = IncidentLogBleRelayNaming.bleFileBaseName("rep_01M4HBVT88DFSN8TYNZ1WTV4PB", 'L')
12
+ assertEquals("Brep_01m4hbvt88d", firmware)
13
+ assertTrue(IncidentLogBleRelayNaming.isRelayFileName(firmware))
14
+ assertTrue(IncidentLogBleRelayNaming.isRelayFileName(logcat))
15
+ assertTrue(IncidentLogBleRelayNaming.isRelayFileName(IncidentLogBleRelayNaming.bleFileBaseName("short", 'B')))
16
+ }
17
+
18
+ @Test fun `photo and other transfers are not relays`() {
19
+ for (name in listOf("I000123456", "I000123456.jpg", "ble_1234567890", "Brep_01m4hbvt88d.json", "Xrep_01m4hbvt88d", "", null)) {
20
+ assertFalse(name.toString(), IncidentLogBleRelayNaming.isRelayFileName(name))
21
+ }
22
+ }
23
+ }