@mentra/bluetooth-sdk 3.3.0 → 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 (168) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +80 -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 +85 -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 +154 -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 +1 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +27 -2
  15. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +925 -155
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +54 -59
  25. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +5 -32
  26. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +3 -10
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  32. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  33. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  34. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  39. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  40. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  44. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  46. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  49. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +5 -1
  52. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  54. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  59. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  60. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  61. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  62. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  63. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  64. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  65. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  66. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  67. package/build/BluetoothSdk.types.d.ts +201 -1
  68. package/build/BluetoothSdk.types.d.ts.map +1 -1
  69. package/build/BluetoothSdk.types.js.map +1 -1
  70. package/build/_private/BluetoothSdkModule.d.ts +43 -5
  71. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  72. package/build/_private/BluetoothSdkModule.js +2 -0
  73. package/build/_private/BluetoothSdkModule.js.map +1 -1
  74. package/build/generated/changelogCatalog.d.ts +3 -0
  75. package/build/generated/changelogCatalog.d.ts.map +1 -1
  76. package/build/generated/changelogCatalog.js +4 -0
  77. package/build/generated/changelogCatalog.js.map +1 -1
  78. package/build/generated/releaseMetadata.js +6 -6
  79. package/build/generated/releaseMetadata.js.map +1 -1
  80. package/build/index.d.ts +1 -1
  81. package/build/index.d.ts.map +1 -1
  82. package/build/index.js +9 -0
  83. package/build/index.js.map +1 -1
  84. package/ios/BluetoothSdkModule.swift +76 -12
  85. package/ios/MentraBluetoothSDK.podspec +4 -0
  86. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  87. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  88. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  89. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  90. package/ios/Source/Bridge.swift +11 -3
  91. package/ios/Source/DeviceManager.swift +131 -18
  92. package/ios/Source/DeviceStore.swift +27 -0
  93. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  94. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  95. package/ios/Source/MentraBluetoothSDK.swift +40 -5
  96. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  97. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  98. package/ios/Source/audio/SpeechActivity.swift +277 -0
  99. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  100. package/ios/Source/events/BluetoothEvents.swift +41 -0
  101. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  102. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  103. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +186 -0
  104. package/ios/Source/sgcs/MentraLive.swift +1270 -189
  105. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  106. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  107. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  108. package/ios/Source/sgcs/Nimo.swift +10 -3
  109. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +39 -9
  110. package/ios/Source/sgcs/SGCManager.swift +13 -0
  111. package/ios/Source/sgcs/Simulated.swift +2 -0
  112. package/ios/Source/status/DeviceStatus.swift +35 -0
  113. package/ios/Source/stt/STTTools.swift +13 -31
  114. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  115. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  116. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  117. package/ios/Source/types/DeviceModels.swift +8 -1
  118. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  119. package/ios/Source/utils/BoundedWait.swift +44 -0
  120. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  121. package/ios/Source/utils/SttModelTraits.swift +62 -0
  122. package/ios/Tests/BesCrashReportTests.swift +142 -0
  123. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  124. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  125. package/ios/Tests/DeviceManagerReconnectTests.swift +4 -2
  126. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +197 -0
  127. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  128. package/ios/Tests/MentraLiveAudioSetupTests.swift +209 -0
  129. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  130. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  131. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  132. package/ios/Tests/MentraLiveSessionReadinessTests.swift +368 -26
  133. package/ios/Tests/NimoCanvasTransportTests.swift +58 -0
  134. package/ios/Tests/PcmStreamTests.swift +299 -0
  135. package/ios/Tests/SpeechActivityTests.swift +238 -0
  136. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  137. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  138. package/package.json +3 -2
  139. package/plugin/build/withAndroid.js +9 -11
  140. package/plugin/build/withKotlinVersion.d.ts +2 -0
  141. package/plugin/build/withKotlinVersion.js +46 -0
  142. package/src/BluetoothSdk.types.ts +201 -1
  143. package/src/_private/BluetoothSdkModule.ts +47 -5
  144. package/src/generated/changelogCatalog.ts +4 -0
  145. package/src/generated/releaseMetadata.ts +6 -6
  146. package/src/index.ts +22 -0
  147. package/android/silero/LICENSE.md +0 -17
  148. package/android/silero/build.gradle +0 -50
  149. package/android/silero/proguard-rules.pro +0 -24
  150. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  151. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  152. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  153. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  154. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  155. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  156. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  157. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  158. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  159. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  160. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  161. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  162. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  163. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  164. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  165. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  166. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -288
  167. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  168. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -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,368 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.bluetooth.BluetoothDevice
4
+ import org.junit.Assert.assertEquals
5
+ import org.junit.Assert.assertFalse
6
+ import org.junit.Assert.assertTrue
7
+ import org.junit.Test
8
+
9
+ class MentraLiveOwnerLossPolicyTest {
10
+ @Test
11
+ fun connectTimeRejectionIsAHintOnlyOutsideExplicitPairingOnSecureFirmware() {
12
+ assertTrue(gattRejection(5))
13
+ assertTrue(gattRejection(15))
14
+ assertFalse(gattRejection(5, manualPairing = true))
15
+ }
16
+
17
+ @Test
18
+ fun legacyFirmwareRejectionsAreNeverOwnerLoss() {
19
+ assertFalse(gattRejection(5, secureFirmware = false))
20
+ assertFalse(gattRejection(15, secureFirmware = false))
21
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, secureFirmware = false))
22
+ }
23
+
24
+ @Test
25
+ fun rfDropsAndRemoteTerminationAreNotOwnerLoss() {
26
+ for (status in listOf(8, 19, 22, 62, 133)) {
27
+ assertFalse("status $status", gattRejection(status))
28
+ }
29
+ }
30
+
31
+ @Test
32
+ fun bondDroppedRightAfterAutomaticReconnectIsARejection() {
33
+ assertTrue(bondRemoved(msSinceAutoReconnectLink = 600L))
34
+ }
35
+
36
+ @Test
37
+ fun bondRemovalOutsideAReconnectIsNotARejection() {
38
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = null))
39
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 60_000L))
40
+ }
41
+
42
+ @Test
43
+ fun appUnpairAndExplicitPairingNeverReportOwnerLoss() {
44
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, killed = true))
45
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, unpairInProgress = true))
46
+ assertFalse(bondRemoved(msSinceAutoReconnectLink = 600L, manualPairing = true))
47
+ }
48
+
49
+ @Test
50
+ fun aSingleRejectionDoesNotStandDown() {
51
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
52
+ assertFalse(streak.record(0L))
53
+ }
54
+
55
+ @Test
56
+ fun threeQuickRejectionsDoNotStandDownUntilTheStreakSpansAboutAMinute() {
57
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
58
+ assertFalse(streak.record(0L))
59
+ assertFalse(streak.record(3_000L))
60
+ // Third attempt, but a glasses reboot also rejects for a few seconds.
61
+ assertFalse(streak.record(8_000L))
62
+ assertFalse(streak.record(24_000L))
63
+ assertTrue(streak.record(MentraLiveOwnerLossPolicy.MIN_REJECTION_SPAN_MS))
64
+ }
65
+
66
+ @Test
67
+ fun aSuccessfulSessionEndsTheStreak() {
68
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
69
+ streak.record(0L)
70
+ streak.record(10_000L)
71
+ streak.reset()
72
+ assertFalse(streak.record(50_000L))
73
+ assertFalse(streak.record(60_000L))
74
+ }
75
+
76
+ @Test
77
+ fun rejectionsFarApartAreNotOneStreak() {
78
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
79
+ streak.record(0L)
80
+ streak.record(10_000L)
81
+ streak.record(20_000L)
82
+ // A long quiet gap means the earlier rejections were something else.
83
+ val later = 20_000L + MentraLiveOwnerLossPolicy.REJECTION_STREAK_GAP_MS + 1L
84
+ assertFalse(streak.record(later))
85
+ assertFalse(streak.record(later + 10_000L))
86
+ assertFalse(streak.record(later + 20_000L))
87
+ }
88
+
89
+ @Test
90
+ fun oneAttemptReportingTwiceCountsOnce() {
91
+ val streak = MentraLiveOwnerLossPolicy.OwnerRejectionStreak()
92
+ val span = MentraLiveOwnerLossPolicy.MIN_REJECTION_SPAN_MS
93
+ // Bond removed, then the GATT disconnect with status 5, for each of two attempts.
94
+ // Counted per signal this would be four rejections over a long enough span.
95
+ assertFalse(streak.record(0L))
96
+ assertFalse(streak.record(400L))
97
+ assertFalse(streak.record(span))
98
+ assertFalse(streak.record(span + 400L))
99
+ // A genuine third attempt completes the streak.
100
+ assertTrue(streak.record(span + 10_000L))
101
+ }
102
+
103
+ @Test
104
+ fun aFailedNewBondIsNotABondRemoval() {
105
+ assertFalse(
106
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnBondRemoved(
107
+ previousBondState = BluetoothDevice.BOND_BONDING,
108
+ bondState = BluetoothDevice.BOND_NONE,
109
+ killed = false,
110
+ unpairInProgress = false,
111
+ manualPairing = false,
112
+ msSinceAutoReconnectLink = 600L,
113
+ secureFirmware = true,
114
+ )
115
+ )
116
+ }
117
+
118
+ @Test
119
+ fun pauseIsTheWindowPlusTheCloseMarginWithNo300sClamp() {
120
+ assertEquals(150_000L, MentraLiveOwnerLossPolicy.yieldMs(120_000L))
121
+ // The glasses own the window: a longer one is paused for in full, not clamped to 300 s.
122
+ assertEquals(930_000L, MentraLiveOwnerLossPolicy.yieldMs(900_000L))
123
+ // A short window is not stretched to a floor either.
124
+ assertEquals(40_000L, MentraLiveOwnerLossPolicy.yieldMs(10_000L))
125
+ // A missing window falls back to the 120 s default.
126
+ assertEquals(150_000L, MentraLiveOwnerLossPolicy.yieldMs(0L))
127
+ }
128
+
129
+ @Test
130
+ fun aRestartedAppKeepsOnlyALiveDeadlineWithinThePersistedPause() {
131
+ val now = 1_000_000L
132
+ val pause = MentraLiveOwnerLossPolicy.yieldMs(120_000L)
133
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(0L, now, pause))
134
+ assertEquals(50_000L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + 50_000L, now, pause))
135
+ assertEquals(pause, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + pause, now, pause))
136
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now - 1L, now, pause))
137
+ // Further out than the pause that was recorded with it: a clock change, not a window.
138
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + pause + 1L, now, pause))
139
+ assertEquals(0L, MentraLiveOwnerLossPolicy.persistedYieldRemainingMs(now + 1_000L, now, 0L))
140
+ }
141
+
142
+ @Test
143
+ fun theWindowRefusalStatus0x14IsNeverARejection() {
144
+ assertFalse(gattRejection(0x14))
145
+ assertFalse(MentraLiveOwnerLossPolicy.isOwnerRejectionStatus(0x14))
146
+ }
147
+
148
+ @Test
149
+ fun pairSelectGoesOnlyWithAnExplicitAttemptToSecureGlasses() {
150
+ assertTrue(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = true, securePairingTarget = true))
151
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = false, securePairingTarget = true))
152
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = true, securePairingTarget = false))
153
+ assertFalse(MentraLiveOwnerLossPolicy.shouldSendPairSelect(explicitPairing = false, securePairingTarget = false))
154
+ }
155
+
156
+ @Test
157
+ fun parkedSecureReadinessAlwaysHasABondWaitDeadline() {
158
+ // Nothing (no awaiting_confirm any more) suspends the wait on an explicit secure pair.
159
+ assertTrue(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = true, securePairingTarget = true))
160
+ assertFalse(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = false, securePairingTarget = true))
161
+ assertFalse(MentraLiveOwnerLossPolicy.shouldRunSecureBondWait(explicitPairing = true, securePairingTarget = false))
162
+ assertEquals(40_000L, MentraLiveOwnerLossPolicy.SECURE_BOND_WAIT_MS)
163
+ }
164
+
165
+ @Test
166
+ fun explicitSecurePairDefersCtkdUntilPairingInfoArrives() {
167
+ assertTrue(
168
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
169
+ explicitPairing = true,
170
+ secureTarget = true,
171
+ bondState = BluetoothDevice.BOND_NONE,
172
+ pairingInfoSeen = false,
173
+ ),
174
+ )
175
+ assertFalse(
176
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
177
+ explicitPairing = true,
178
+ secureTarget = true,
179
+ bondState = BluetoothDevice.BOND_NONE,
180
+ pairingInfoSeen = true,
181
+ ),
182
+ )
183
+ assertFalse(
184
+ MentraLiveOwnerLossPolicy.shouldDeferCtkdBond(
185
+ explicitPairing = false,
186
+ secureTarget = true,
187
+ bondState = BluetoothDevice.BOND_NONE,
188
+ pairingInfoSeen = false,
189
+ ),
190
+ )
191
+ }
192
+
193
+ @Test
194
+ fun aClearedPairingFlagOnTheSavedGlassesIsNotHiddenFromThePauseWatchScan() {
195
+ assertFalse(
196
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
197
+ savedGlasses = true,
198
+ reconnectScan = false,
199
+ secureTrailer = true,
200
+ pairingDiscoverable = false,
201
+ )
202
+ )
203
+ assertTrue(
204
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
205
+ savedGlasses = false,
206
+ reconnectScan = false,
207
+ secureTrailer = true,
208
+ pairingDiscoverable = false,
209
+ )
210
+ )
211
+ assertFalse(
212
+ MentraLiveOwnerLossPolicy.shouldExposeAsNonPairable(
213
+ savedGlasses = false,
214
+ reconnectScan = false,
215
+ secureTrailer = true,
216
+ pairingDiscoverable = true,
217
+ )
218
+ )
219
+ }
220
+
221
+ @Test
222
+ fun automaticReconnectStandsDownWhileTheSavedGlassesAdvertisePairingMode() {
223
+ assertTrue(
224
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
225
+ pairingMode = true,
226
+ savedGlasses = true,
227
+ explicitPairing = false,
228
+ )
229
+ )
230
+ assertFalse(
231
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
232
+ pairingMode = true,
233
+ savedGlasses = true,
234
+ explicitPairing = true,
235
+ )
236
+ )
237
+ assertFalse(
238
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
239
+ pairingMode = false,
240
+ savedGlasses = true,
241
+ explicitPairing = false,
242
+ )
243
+ )
244
+ assertFalse(
245
+ MentraLiveOwnerLossPolicy.shouldStandDownInsteadOfReconnect(
246
+ pairingMode = true,
247
+ savedGlasses = false,
248
+ explicitPairing = false,
249
+ )
250
+ )
251
+ }
252
+
253
+ @Test
254
+ fun secureTargetIsNotReadyUntilBondedAndOwnerCommitted() {
255
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDING, committed = true))
256
+ assertTrue(defer(bond = BluetoothDevice.BOND_NONE, committed = true))
257
+ assertTrue(defer(bond = BluetoothDevice.BOND_NONE, committed = false))
258
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
259
+ assertFalse(defer(secure = false, bond = BluetoothDevice.BOND_NONE, committed = false))
260
+ }
261
+
262
+ @Test
263
+ fun staleBondWithoutOwnerCommitStillDefersAnExplicitSecurePair() {
264
+ // A leftover BOND_BONDED (or a Classic-only bond on the same public address) is not
265
+ // proof that the glasses committed this phone as owner.
266
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDED, committed = false))
267
+ }
268
+
269
+ @Test
270
+ fun bondedAndOwnerCommittedIsNotDeferred() {
271
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
272
+ }
273
+
274
+ @Test
275
+ fun lateOwnerCommitAfterBondAllowsReady() {
276
+ // glasses_ready and the bond arrive first: parked.
277
+ assertTrue(defer(bond = BluetoothDevice.BOND_BONDED, committed = false))
278
+ // The late pairing_info carries owner_committed: ready is allowed now.
279
+ assertTrue(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(true))
280
+ assertFalse(defer(bond = BluetoothDevice.BOND_BONDED, committed = true))
281
+ }
282
+
283
+ @Test
284
+ fun pairingInfoWithoutOwnerCommitDoesNotConfirmOwner() {
285
+ assertFalse(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(false))
286
+ assertTrue(MentraLiveOwnerLossPolicy.pairingInfoConfirmsOwner(true))
287
+ }
288
+
289
+ @Test
290
+ fun legacyTargetIsNeverGated() {
291
+ for (bond in listOf(BluetoothDevice.BOND_NONE, BluetoothDevice.BOND_BONDING, null)) {
292
+ for (committed in listOf(true, false)) {
293
+ assertFalse(defer(secure = false, bond = bond, committed = committed))
294
+ assertTrue(audioReady(secure = false, bond = bond, committed = committed))
295
+ }
296
+ }
297
+ }
298
+
299
+ @Test
300
+ fun classicAudioDoesNotCommitAnUnbondedSecurePair() {
301
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_BONDING, committed = false))
302
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_NONE, committed = false))
303
+ assertTrue(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = true))
304
+ }
305
+
306
+ @Test
307
+ fun classicAudioFirstWithoutOwnerCommitDoesNotMarkReadyDuringExplicitPairing() {
308
+ assertFalse(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = false))
309
+ // Once the commit arrives the same audio-first state may complete.
310
+ assertTrue(audioReady(bond = BluetoothDevice.BOND_BONDED, committed = true))
311
+ }
312
+
313
+ @Test
314
+ fun reconnectOutsideExplicitPairingIsNeverGated() {
315
+ for (bond in listOf(BluetoothDevice.BOND_NONE, BluetoothDevice.BOND_BONDING, null)) {
316
+ for (committed in listOf(true, false)) {
317
+ assertTrue(audioReady(explicit = false, bond = bond, committed = committed))
318
+ }
319
+ }
320
+ }
321
+
322
+ private fun defer(
323
+ secure: Boolean = true,
324
+ bond: Int?,
325
+ committed: Boolean,
326
+ ): Boolean = MentraLiveOwnerLossPolicy.shouldDeferReadyForBond(secure, bond, committed)
327
+
328
+ private fun audioReady(
329
+ explicit: Boolean = true,
330
+ secure: Boolean = true,
331
+ bond: Int?,
332
+ committed: Boolean,
333
+ ): Boolean =
334
+ MentraLiveOwnerLossPolicy.shouldMarkReadyFromAudio(
335
+ explicitPairing = explicit,
336
+ securePairingTarget = secure,
337
+ bondState = bond,
338
+ ownerCommitted = committed,
339
+ )
340
+
341
+ private fun gattRejection(
342
+ status: Int,
343
+ manualPairing: Boolean = false,
344
+ secureFirmware: Boolean = true,
345
+ ): Boolean =
346
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnGattError(
347
+ status,
348
+ manualPairing,
349
+ secureFirmware,
350
+ )
351
+
352
+ private fun bondRemoved(
353
+ msSinceAutoReconnectLink: Long?,
354
+ killed: Boolean = false,
355
+ unpairInProgress: Boolean = false,
356
+ manualPairing: Boolean = false,
357
+ secureFirmware: Boolean = true,
358
+ ): Boolean =
359
+ MentraLiveOwnerLossPolicy.isOwnerRejectionOnBondRemoved(
360
+ previousBondState = BluetoothDevice.BOND_BONDED,
361
+ bondState = BluetoothDevice.BOND_NONE,
362
+ killed = killed,
363
+ unpairInProgress = unpairInProgress,
364
+ manualPairing = manualPairing,
365
+ msSinceAutoReconnectLink = msSinceAutoReconnectLink,
366
+ secureFirmware = secureFirmware,
367
+ )
368
+ }
@@ -81,6 +81,26 @@ class MentraLivePairingAdvertisementParserTest {
81
81
  assertFalse(result?.pairingMode == true)
82
82
  }
83
83
 
84
+ @Test
85
+ fun readsTheOwnerChangedFlagAndWindowIdFromTheV4Trailer() {
86
+ val payload = securePayload(pairingFlag = 0)
87
+ payload[6] = 4
88
+ payload[7] = 0x05
89
+ payload[12] = 0xC8.toByte()
90
+ val result = MentraLivePairingAdvertisementParser.parse(payload)
91
+
92
+ assertTrue(result?.ownerChanged == true)
93
+ assertEquals(200, result?.pairingGeneration)
94
+ assertFalse(result?.pairingMode == true)
95
+ }
96
+
97
+ @Test
98
+ fun ownerChangedIsFalseWithoutTheFlag() {
99
+ val result = MentraLivePairingAdvertisementParser.parse(securePayload(pairingFlag = 1))
100
+
101
+ assertFalse(result?.ownerChanged == true)
102
+ }
103
+
84
104
  @Test
85
105
  fun rejectsLegacyPayloadThatMatchesOldVersionCapabilityHeuristic() {
86
106
  val legacyPayload = ByteArray(27)