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

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 (174) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +111 -11
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +89 -6
  9. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +35 -1
  10. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +159 -110
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +35 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +1002 -157
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  44. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  62. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  67. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  68. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  69. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  70. package/build/BluetoothSdk.types.d.ts +207 -2
  71. package/build/BluetoothSdk.types.d.ts.map +1 -1
  72. package/build/BluetoothSdk.types.js.map +1 -1
  73. package/build/_private/BluetoothSdkModule.d.ts +45 -6
  74. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  75. package/build/_private/BluetoothSdkModule.js +2 -0
  76. package/build/_private/BluetoothSdkModule.js.map +1 -1
  77. package/build/generated/changelogCatalog.d.ts +4 -1
  78. package/build/generated/changelogCatalog.d.ts.map +1 -1
  79. package/build/generated/changelogCatalog.js +5 -1
  80. package/build/generated/changelogCatalog.js.map +1 -1
  81. package/build/generated/releaseMetadata.js +6 -6
  82. package/build/generated/releaseMetadata.js.map +1 -1
  83. package/build/index.d.ts +1 -1
  84. package/build/index.d.ts.map +1 -1
  85. package/build/index.js +10 -0
  86. package/build/index.js.map +1 -1
  87. package/ios/BluetoothSdkModule.swift +84 -12
  88. package/ios/MentraBluetoothSDK.podspec +4 -0
  89. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  90. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  91. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  92. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  93. package/ios/Source/Bridge.swift +11 -3
  94. package/ios/Source/DeviceManager.swift +135 -18
  95. package/ios/Source/DeviceStore.swift +27 -0
  96. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  97. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  98. package/ios/Source/MentraBluetoothSDK.swift +51 -5
  99. package/ios/Source/TouchGesture.swift +13 -0
  100. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  101. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  102. package/ios/Source/audio/SpeechActivity.swift +277 -0
  103. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  104. package/ios/Source/events/BluetoothEvents.swift +45 -0
  105. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  106. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  107. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  108. package/ios/Source/sgcs/MentraLive.swift +1366 -212
  109. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  110. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  111. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  112. package/ios/Source/sgcs/Nimo.swift +10 -3
  113. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  114. package/ios/Source/sgcs/SGCManager.swift +13 -0
  115. package/ios/Source/sgcs/Simulated.swift +2 -0
  116. package/ios/Source/status/DeviceStatus.swift +35 -0
  117. package/ios/Source/stt/STTTools.swift +13 -31
  118. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  119. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  120. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  121. package/ios/Source/types/DeviceModels.swift +8 -1
  122. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  123. package/ios/Source/utils/BoundedWait.swift +44 -0
  124. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  125. package/ios/Source/utils/SttModelTraits.swift +62 -0
  126. package/ios/Tests/BesCrashReportTests.swift +142 -0
  127. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  128. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  129. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  130. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  131. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  132. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  133. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  134. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  135. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  136. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  137. package/ios/Tests/MentraLiveSessionReadinessTests.swift +497 -26
  138. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  139. package/ios/Tests/PcmStreamTests.swift +299 -0
  140. package/ios/Tests/SpeechActivityTests.swift +238 -0
  141. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  142. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  143. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  144. package/package.json +3 -2
  145. package/plugin/build/withAndroid.js +9 -11
  146. package/plugin/build/withKotlinVersion.d.ts +2 -0
  147. package/plugin/build/withKotlinVersion.js +46 -0
  148. package/src/BluetoothSdk.types.ts +216 -1
  149. package/src/_private/BluetoothSdkModule.ts +49 -5
  150. package/src/generated/changelogCatalog.ts +5 -1
  151. package/src/generated/releaseMetadata.ts +6 -6
  152. package/src/index.ts +24 -0
  153. package/android/silero/LICENSE.md +0 -17
  154. package/android/silero/build.gradle +0 -50
  155. package/android/silero/proguard-rules.pro +0 -24
  156. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  157. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  159. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  160. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  161. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  162. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  163. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  164. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  165. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  166. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  167. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  168. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  169. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  170. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  171. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  172. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  173. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  174. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -0,0 +1,231 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.bluetooth.BluetoothAdapter
4
+ import android.bluetooth.BluetoothDevice
5
+ import android.bluetooth.BluetoothGattCallback
6
+ import android.bluetooth.BluetoothGattCharacteristic
7
+ import android.os.Looper
8
+ import androidx.test.core.app.ApplicationProvider
9
+ import com.mentra.bluetoothsdk.Bridge
10
+ import com.mentra.bluetoothsdk.DeviceManager
11
+ import com.mentra.bluetoothsdk.DeviceStore
12
+ import com.mentra.bluetoothsdk.GlassesStatus
13
+ import java.time.Duration
14
+ import java.util.UUID
15
+ import java.util.concurrent.CopyOnWriteArrayList
16
+ import org.json.JSONObject
17
+ import org.junit.Assert.assertEquals
18
+ import org.junit.Assert.assertFalse
19
+ import org.junit.Assert.assertNotNull
20
+ import org.junit.Assert.assertNull
21
+ import org.junit.Assert.assertTrue
22
+ import org.junit.Test
23
+ import org.junit.runner.RunWith
24
+ import org.robolectric.RobolectricTestRunner
25
+ import org.robolectric.Shadows.shadowOf
26
+ import org.robolectric.annotation.Config
27
+ import org.robolectric.annotation.LooperMode
28
+
29
+ /**
30
+ * Drives [MentraLive]'s real BLE message handling and the shared status layer: audioSetup in
31
+ * the ready snapshot, the unknown-capability readiness wait, the selected-row secure rule, the
32
+ * secure firmware refresh, and the `classic_link` message.
33
+ */
34
+ @RunWith(RobolectricTestRunner::class)
35
+ @Config(sdk = [33], shadows = [G1PairingTest.ShadowLc3Cpp::class], instrumentedPackages = ["com.mentra.lc3Lib"])
36
+ @LooperMode(LooperMode.Mode.PAUSED)
37
+ class MentraLiveAudioSetupReadinessTest {
38
+ private val targetName = "MENTRA_LIVE_BLE_AUDIOSETUP"
39
+ private val targetAddress = "AA:BB:CC:DD:EE:42"
40
+
41
+ @Test fun `readiness and audioSetup arrive in one snapshot and audio_setup_changed fires once`() =
42
+ withLive(selectedCapability = false) { live, events ->
43
+ val snapshots = CopyOnWriteArrayList<Map<String, Any>>()
44
+ val listener =
45
+ DeviceStore.store.addListener { category, _ ->
46
+ if (category == "glasses") snapshots.add(glassesSnapshot())
47
+ }
48
+ try {
49
+ message(live, """{"type":"glasses_ready"}""")
50
+ } finally {
51
+ DeviceStore.store.removeListener(listener)
52
+ }
53
+ assertTrue(ready())
54
+ val readySnapshots = snapshots.filter { it["connection"].let { c -> (c as Map<*, *>)["fullyBooted"] == true } }
55
+ assertTrue(readySnapshots.isNotEmpty())
56
+ // Never "ready" with a stale idle.
57
+ readySnapshots.forEach { assertEquals(mapOf("state" to "not_applicable"), it["audioSetup"]) }
58
+ assertEquals(listOf(mapOf("state" to "not_applicable")), audioSetupEvents(events))
59
+
60
+ // A repeated ready report is not a change.
61
+ message(live, """{"type":"glasses_ready"}""")
62
+ assertEquals(1, audioSetupEvents(events).size)
63
+
64
+ DeviceStore.apply("glasses", "fullyBooted", false)
65
+ assertEquals(mapOf("state" to "idle"), glassesSnapshot()["audioSetup"])
66
+ assertEquals(
67
+ listOf(mapOf("state" to "not_applicable"), mapOf("state" to "idle")),
68
+ audioSetupEvents(events),
69
+ )
70
+ }
71
+
72
+ @Test fun `unknown capability without pairing_info is reported ready after 5 s as legacy`() =
73
+ withLive(selectedCapability = "") { live, _ ->
74
+ message(live, """{"type":"glasses_ready"}""")
75
+ assertFalse(ready())
76
+ assertEquals(mapOf("state" to "idle"), glassesSnapshot()["audioSetup"])
77
+ idle(MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS - 100)
78
+ assertFalse(ready())
79
+ idle(200)
80
+ assertTrue(ready())
81
+ assertEquals(mapOf("state" to "not_applicable"), glassesSnapshot()["audioSetup"])
82
+ assertNull(get(live, "secureBondWaitRunnable"))
83
+ }
84
+
85
+ @Test fun `unknown capability with a secure pairing_info follows the owner commit rule`() =
86
+ withLive(selectedCapability = "") { live, _ ->
87
+ message(live, """{"type":"glasses_ready"}""")
88
+ message(live, pairingInfo(secure = true, ownerCommitted = false))
89
+ assertFalse(ready())
90
+ // The secure rule runs its own deadline instead of the 5 s legacy fallback.
91
+ assertNotNull(get(live, "secureBondWaitRunnable"))
92
+ idle(MentraLivePairingReadinessPolicy.UNKNOWN_CAPABILITY_PAIRING_INFO_WAIT_MS + 1_000)
93
+ assertFalse(ready())
94
+
95
+ shadowOf(device()).setBondState(BluetoothDevice.BOND_BONDED)
96
+ message(live, pairingInfo(secure = true, ownerCommitted = true))
97
+ assertTrue(ready())
98
+ assertNull(get(live, "secureBondWaitRunnable"))
99
+ }
100
+
101
+ @Test fun `unknown capability with a legacy pairing_info is ready at once`() =
102
+ withLive(selectedCapability = "") { live, _ ->
103
+ message(live, """{"type":"glasses_ready"}""")
104
+ assertFalse(ready())
105
+ message(live, pairingInfo(secure = false, ownerCommitted = false))
106
+ assertTrue(ready())
107
+ }
108
+
109
+ @Test fun `a legacy row is not secure even if its address advertised the trailer before`() =
110
+ withLive(selectedCapability = false) { live, _ ->
111
+ trailerMemory().noteSecureTrailer(targetAddress)
112
+ try {
113
+ message(live, """{"type":"glasses_ready"}""")
114
+ assertTrue(ready())
115
+ assertNull(get(live, "secureBondWaitRunnable"))
116
+ } finally {
117
+ trailerMemory().onScanStart()
118
+ }
119
+ }
120
+
121
+ @Test fun `a ready session without pairing_info clears the secure firmware memory after 15 s`() =
122
+ withLive(selectedCapability = false) { live, _ ->
123
+ DeviceStore.set("bluetooth", "mentra_live_secure_firmware", true)
124
+ message(live, """{"type":"glasses_ready"}""")
125
+ idle(MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS - 100)
126
+ assertEquals(true, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
127
+ idle(200)
128
+ assertEquals(false, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
129
+ }
130
+
131
+ @Test fun `a secure pairing_info keeps the secure firmware memory`() =
132
+ withLive(selectedCapability = true) { live, _ ->
133
+ DeviceStore.set("bluetooth", "mentra_live_secure_firmware", false)
134
+ message(live, pairingInfo(secure = true, ownerCommitted = false))
135
+ message(live, """{"type":"glasses_ready"}""")
136
+ idle(MentraLivePairingReadinessPolicy.SECURE_FIRMWARE_REFRESH_MS + 1_000)
137
+ assertEquals(true, DeviceStore.get("bluetooth", "mentra_live_secure_firmware"))
138
+ }
139
+
140
+ @Test fun `classic_link is accepted and logged`() =
141
+ withLive(selectedCapability = false) { live, events ->
142
+ message(live, """{"type":"classic_link","a2dp":true,"hfp":false}""")
143
+ message(live, """{"type":"classic_link"}""")
144
+ val logs = events.filter { it.first == "log" }.map { it.second["message"].toString() }
145
+ assertTrue(logs.any { it.contains("LIVE: classic_link a2dp=true hfp=false") })
146
+ assertTrue(logs.any { it.contains("LIVE: classic_link a2dp=false hfp=false") })
147
+ assertFalse(ready())
148
+ }
149
+
150
+ private fun withLive(
151
+ selectedCapability: Any,
152
+ body: (MentraLive, MutableList<Pair<String, Map<String, Any>>>) -> Unit,
153
+ ) {
154
+ Bridge.initialize(ApplicationProvider.getApplicationContext())
155
+ val saved = listOf("bluetooth", "glasses").associateWith { DeviceStore.store.getCategory(it) }
156
+ val singleton = DeviceManager::class.java.getDeclaredField("_instance").apply { isAccessible = true }
157
+ val previous = singleton.get(null)
158
+ val manager = DeviceManager(initializeHardware = false)
159
+ singleton.set(null, manager)
160
+ MentraLivePairingStateStore.resetForTest()
161
+ DeviceStore.set("glasses", "fullyBooted", false)
162
+ DeviceStore.set("bluetooth", "pending_device_name", targetName)
163
+ DeviceStore.set("bluetooth", "pending_device_address", targetAddress)
164
+ DeviceStore.set("bluetooth", "pending_device_secure_pairing_capable", selectedCapability)
165
+ val events = CopyOnWriteArrayList<Pair<String, Map<String, Any>>>()
166
+ val sink = Bridge.addEventSink { type, body -> events.add(type to HashMap(body)) }
167
+ val live = MentraLive()
168
+ try {
169
+ link(live)
170
+ body(live, events)
171
+ } finally {
172
+ Bridge.removeEventSink(sink)
173
+ live.destroy()
174
+ shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(2))
175
+ manager.cleanup()
176
+ singleton.set(null, previous)
177
+ MentraLivePairingStateStore.resetForTest()
178
+ saved.forEach { (category, values) ->
179
+ (DeviceStore.store.getCategory(category).keys - values.keys).forEach {
180
+ DeviceStore.store.remove(category, it)
181
+ }
182
+ values.forEach { (key, value) -> DeviceStore.set(category, key, value) }
183
+ }
184
+ }
185
+ }
186
+
187
+ private fun device(): BluetoothDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(targetAddress)
188
+
189
+ /** A live GATT link to the pairing target; CTKD is marked started so no Classic work runs. */
190
+ private fun link(live: MentraLive) {
191
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
192
+ val gatt = device().connectGatt(context, false, object : BluetoothGattCallback() {})
193
+ set(live, "isConnected", true)
194
+ set(live, "bluetoothGatt", gatt)
195
+ set(live, "connectedDevice", device())
196
+ set(live, "txCharacteristic", BluetoothGattCharacteristic(UUID.randomUUID(), 0, 0))
197
+ set(live, "ctkdInitiatedThisGattSession", true)
198
+ }
199
+
200
+ private fun message(live: MentraLive, json: String) {
201
+ MentraLive::class.java.getDeclaredMethod("processJsonMessage", JSONObject::class.java)
202
+ .apply { isAccessible = true }
203
+ .invoke(live, JSONObject(json))
204
+ }
205
+
206
+ private fun pairingInfo(secure: Boolean, ownerCommitted: Boolean): String =
207
+ """{"type":"pairing_info","secure_pairing_capable":$secure,"owner_committed":$ownerCommitted}"""
208
+
209
+ private fun ready(): Boolean = DeviceStore.get("glasses", "fullyBooted") == true
210
+
211
+ /** What `glasses_status` sends to JavaScript for the current store. */
212
+ private fun glassesSnapshot(): Map<String, Any> =
213
+ GlassesStatus.fromMap(DeviceStore.store.getCategory("glasses")).toMap()
214
+
215
+ private fun audioSetupEvents(events: List<Pair<String, Map<String, Any>>>): List<Any?> =
216
+ events.filter { it.first == "audio_setup_changed" }.map { it.second["state"] }
217
+
218
+ private fun idle(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
219
+
220
+ private fun trailerMemory(): MentraLiveSecureTrailerScanMemory =
221
+ MentraLive::class.java.getDeclaredField("secureTrailerScanMemory")
222
+ .apply { isAccessible = true }
223
+ .get(null) as MentraLiveSecureTrailerScanMemory
224
+
225
+ private fun get(live: MentraLive, name: String): Any? =
226
+ MentraLive::class.java.getDeclaredField(name).apply { isAccessible = true }.get(live)
227
+
228
+ private fun set(live: MentraLive, name: String, value: Any?) {
229
+ MentraLive::class.java.getDeclaredField(name).apply { isAccessible = true }.set(live, value)
230
+ }
231
+ }
@@ -0,0 +1,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")