@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
@@ -271,6 +271,10 @@ class BluetoothSdkModule : Module() {
271
271
  sendEvent("ota_status", event.values)
272
272
  }
273
273
 
274
+ override fun onBesCrashDetected(event: BesCrashDetectedEvent) {
275
+ sendEvent("bes_crash_detected", event.toEventMap())
276
+ }
277
+
274
278
  override fun onSettingsAck(event: SettingsAckEvent) {
275
279
  sendEvent("settings_ack", event.values)
276
280
  }
@@ -310,7 +314,9 @@ class BluetoothSdkModule : Module() {
310
314
  }
311
315
 
312
316
  override fun onError(error: BluetoothError) {
313
- sendEvent("pair_failure", mapOf("error" to error.message))
317
+ val body = mutableMapOf<String, Any>("error" to error.message)
318
+ error.failureCode?.let { body["code"] = it }
319
+ sendEvent("pair_failure", body)
314
320
  }
315
321
 
316
322
  override fun onRawEvent(eventName: String, values: Map<String, Any>) {
@@ -349,6 +355,8 @@ class BluetoothSdkModule : Module() {
349
355
  "speaking_status",
350
356
  "battery_status",
351
357
  "local_transcription",
358
+ "wake_word",
359
+ "speech_activity",
352
360
  "wifi_status_change",
353
361
  "wifi_scan_result",
354
362
  "wifi_forget_result",
@@ -379,6 +387,9 @@ class BluetoothSdkModule : Module() {
379
387
  "pair_failure",
380
388
  "pairing_info",
381
389
  "entering_pairing_mode",
390
+ "pairing_mode_ended",
391
+ "pairing_state_changed",
392
+ "audio_setup_changed",
382
393
  "owner_replaced",
383
394
  "audio_pairing_needed",
384
395
  "audio_connected",
@@ -401,6 +412,7 @@ class BluetoothSdkModule : Module() {
401
412
  "ota_start_ack",
402
413
  "ota_status",
403
414
  "ar99_ota_status",
415
+ "bes_crash_detected",
404
416
  // Nex / BLE debug (NexEventUtils —Bridge.sendTypedMessage)
405
417
  "send_command_to_ble",
406
418
  "receive_command_from_ble",
@@ -562,6 +574,12 @@ class BluetoothSdkModule : Module() {
562
574
  sdk?.startScan(DeviceModel.fromDeviceType(model))
563
575
  }
564
576
 
577
+ SdkAsyncFunction("getBondedGlasses") { ->
578
+ com.mentra.bluetoothsdk.sgcs.MentraLive.soleBondedMentraLive(Bridge.getContext())?.let {
579
+ mapOf("name" to (it.name ?: ""), "address" to it.address)
580
+ }
581
+ }
582
+
565
583
  SdkAsyncFunction("getScanDiagnostic") { model: String ->
566
584
  sdk?.connectedDeviceScanDiagnostic(DeviceModel.fromDeviceType(model))?.let {
567
585
  mapOf("code" to it.code, "message" to it.message)
@@ -621,6 +639,10 @@ class BluetoothSdkModule : Module() {
621
639
  requireSdk().sendIncidentId(incidentId, apiBaseUrl)
622
640
  }
623
641
 
642
+ SdkCoroutineFunction("sendBesCrashReported") { incidentKey: String, reportId: String ->
643
+ requireSdk().sendBesCrashReported(incidentKey, reportId)
644
+ }
645
+
624
646
  // MARK: - Native Notification Centre
625
647
 
626
648
  // Public controls use the SDK facade; phone payload delivery uses DeviceManager.
@@ -652,8 +674,9 @@ class BluetoothSdkModule : Module() {
652
674
  requireSdk().setHotspotState(enabled).values
653
675
  }
654
676
 
655
- SdkAsyncFunction("setWifiAdbState") { enabled: Boolean ->
656
- sdk?.setWifiAdbState(enabled)
677
+ SdkAsyncFunction("setWifiAdbState") { enabled: Boolean, expectedBluetoothMac: String? ->
678
+ val current = sdk ?: throw BluetoothSdkException("glasses_not_connected", "Bluetooth SDK is unavailable.")
679
+ current.setWifiAdbState(enabled, expectedBluetoothMac)
657
680
  }
658
681
 
659
682
  SdkAsyncFunction("setSystemTime") { timestampMs: Double ->
@@ -879,13 +902,42 @@ class BluetoothSdkModule : Module() {
879
902
  sdk?.setMicSourcePin(source)
880
903
  }
881
904
 
882
- // Runs on Dispatchers.IO, not the shared Expo AsyncFunctionQueue: restart()
883
- // does a synchronous JNI model reload that would otherwise block every other
884
- // native call in the app until it completes.
905
+ // MARK: - On-device voice
906
+ //
907
+ // Everything that can wait on a model load or a worker runs on Dispatchers.IO,
908
+ // never on the shared Expo AsyncFunctionQueue, which every other native call
909
+ // (and every miniapp) waits behind.
910
+
911
+ AsyncFunction("setWakeWordDetection") Coroutine { enabled: Boolean, modelDir: String? ->
912
+ withContext(Dispatchers.IO) {
913
+ com.mentra.bluetoothsdk.stt.WakeWordDetector.configure(enabled, modelDir)
914
+ }
915
+ }
916
+
917
+ // Lock-free: never waits on a model load.
918
+ AsyncFunction("isSttModelLoaded") { path: String ->
919
+ deviceManager?.isSttModelLoaded(path) ?: false
920
+ }
921
+
922
+ // Resolves with the final text, "" when nothing was pending, or null when no
923
+ // streaming model is active, the model can't finalize early, or after 3 s.
924
+ AsyncFunction("finishTranscription") Coroutine { ->
925
+ withContext(Dispatchers.IO) { deviceManager?.finishTranscription() }
926
+ }
927
+
885
928
  AsyncFunction("restartTranscriber") Coroutine { ->
886
929
  withContext(Dispatchers.IO) { deviceManager?.restartTranscriber() }
887
930
  }
888
931
 
932
+ AsyncFunction("setSpeechActivityDetection") Coroutine { enabled: Boolean, options: Map<String, Any?>? ->
933
+ val minSilenceMs =
934
+ (options?.get("minSilenceMs") as? Number)?.toInt()
935
+ ?: com.mentra.bluetoothsdk.stt.SpeechActivityEngine.DEFAULT_MIN_SILENCE_MS
936
+ withContext(Dispatchers.IO) {
937
+ com.mentra.bluetoothsdk.stt.SpeechActivityDetector.configure(enabled, minSilenceMs)
938
+ }
939
+ }
940
+
889
941
  // MARK: - Audio Playback Monitoring
890
942
 
891
943
  SdkAsyncFunction("setOwnAppAudioPlaying") { playing: Boolean ->
@@ -927,6 +979,33 @@ class BluetoothSdkModule : Module() {
927
979
  PcmStreamManager.abort(streamId)
928
980
  }
929
981
 
982
+ // Native HTTP GET of raw s16le mono PCM, played as it arrives. Blocks a
983
+ // Dispatchers.IO thread (never the shared queue) until the body has played.
984
+ AsyncFunction("pcmStreamPlayUrl") Coroutine {
985
+ streamId: String,
986
+ url: String,
987
+ sampleRate: Int,
988
+ volume: Double,
989
+ jitterMs: Int?,
990
+ ->
991
+ withContext(Dispatchers.IO) {
992
+ try {
993
+ mapOf(
994
+ "durationMs" to
995
+ PcmStreamManager.playUrl(
996
+ streamId,
997
+ url,
998
+ sampleRate,
999
+ volume.toFloat(),
1000
+ jitterMs,
1001
+ )
1002
+ )
1003
+ } catch (error: com.mentra.bluetoothsdk.utils.audio.PcmUrlPlaybackException) {
1004
+ throw CodedException(error.code, error.message ?: error.code, error)
1005
+ }
1006
+ }
1007
+ }
1008
+
930
1009
  // *Blocking on Dispatchers.IO, not the shared AsyncFunctionQueue: these wait on
931
1010
  // a CountDownLatch (up to 5s) for a BLE round-trip, which would otherwise stall
932
1011
  // every other native call queued behind them.
@@ -125,9 +125,10 @@ public class Bridge private constructor() {
125
125
 
126
126
  /** Send pair failure event */
127
127
  @JvmStatic
128
- fun sendPairFailureEvent(error: String) {
128
+ fun sendPairFailureEvent(error: String, code: String? = null) {
129
129
  val data = HashMap<String, Any>()
130
130
  data["error"] = error
131
+ if (code != null) data["code"] = code
131
132
  sendTypedMessage("pair_failure", data as Map<String, Any>)
132
133
  }
133
134
 
@@ -138,6 +139,9 @@ public class Bridge private constructor() {
138
139
  classicBondReady: Boolean = false,
139
140
  securePairingCapable: Boolean = true,
140
141
  protocolVersion: Int = 1,
142
+ ownershipTransfer: Boolean = false,
143
+ ownerCommitted: Boolean = false,
144
+ autoAudio: Boolean = false,
141
145
  ) {
142
146
  val data = HashMap<String, Any>()
143
147
  data["had_previous_bond"] = hadPreviousBond
@@ -145,6 +149,9 @@ public class Bridge private constructor() {
145
149
  data["classic_bond_ready"] = classicBondReady
146
150
  data["secure_pairing_capable"] = securePairingCapable
147
151
  data["protocol_version"] = protocolVersion
152
+ data["ownership_transfer"] = ownershipTransfer
153
+ data["owner_committed"] = ownerCommitted
154
+ data["auto_audio"] = autoAudio
148
155
  sendTypedMessage("pairing_info", data as Map<String, Any>)
149
156
  }
150
157
 
@@ -248,6 +255,33 @@ public class Bridge private constructor() {
248
255
  sendTypedMessage("speaking_status", body as Map<String, Any>)
249
256
  }
250
257
 
258
+ /**
259
+ * Send a phone-side speech activity transition from the on-device Silero detector.
260
+ * [silentForMs] is 0 while speaking; on a silence transition, how long it has been quiet.
261
+ */
262
+ @JvmStatic
263
+ fun sendSpeechActivity(speaking: Boolean, silentForMs: Long) {
264
+ val body = HashMap<String, Any>()
265
+ body["speaking"] = speaking
266
+ body["silentForMs"] = silentForMs
267
+ body["timestamp"] = System.currentTimeMillis()
268
+ sendTypedMessage("speech_activity", body as Map<String, Any>)
269
+ }
270
+
271
+ /**
272
+ * Send on-device keyword spotter state or a detection. [kind] is "loading", "ready",
273
+ * "detected" or "error"; it describes only the wake-word model.
274
+ */
275
+ @JvmStatic
276
+ fun sendWakeWord(kind: String, phrase: String, message: String? = null) {
277
+ val body = HashMap<String, Any>()
278
+ body["kind"] = kind
279
+ body["phrase"] = phrase
280
+ body["timestamp"] = System.currentTimeMillis()
281
+ if (message != null) body["message"] = message
282
+ sendTypedMessage("wake_word", body as Map<String, Any>)
283
+ }
284
+
251
285
  /** Send battery status */
252
286
  @JvmStatic
253
287
  fun sendBatteryStatus(level: Int, charging: Boolean) {
@@ -23,6 +23,7 @@ import com.mentra.bluetoothsdk.sgcs.SceneElement
23
23
  import com.mentra.bluetoothsdk.sgcs.SceneFrame
24
24
  import com.mentra.bluetoothsdk.sgcs.Mach1
25
25
  import com.mentra.bluetoothsdk.sgcs.MentraLive
26
+ import com.mentra.bluetoothsdk.sgcs.MentraLivePairingStateStore
26
27
  import com.mentra.bluetoothsdk.sgcs.MentraNex
27
28
  import com.mentra.bluetoothsdk.sgcs.Nimo
28
29
  import com.mentra.bluetoothsdk.sgcs.SGCManager
@@ -34,7 +35,11 @@ import com.mentra.bluetoothsdk.utils.MicSourcePin
34
35
  import com.mentra.bluetoothsdk.utils.MicTypes
35
36
  import com.mentra.bluetoothsdk.utils.PhoneAudioMonitor
36
37
  import com.mentra.lc3Lib.Lc3Cpp
38
+ import com.mentra.bluetoothsdk.stt.OnDeviceRecognizerHost
39
+ import com.mentra.bluetoothsdk.stt.STTTools
37
40
  import com.mentra.bluetoothsdk.stt.SherpaOnnxTranscriber
41
+ import com.mentra.bluetoothsdk.stt.SpeechActivityDetector
42
+ import com.mentra.bluetoothsdk.stt.WakeWordDetector
38
43
  import kotlin.coroutines.resume
39
44
  import kotlinx.coroutines.suspendCancellableCoroutine
40
45
  import kotlinx.coroutines.CoroutineScope
@@ -44,6 +49,7 @@ import kotlinx.coroutines.launch
44
49
  import java.text.SimpleDateFormat
45
50
  import java.util.*
46
51
  import java.util.concurrent.CountDownLatch
52
+ import java.util.concurrent.ExecutionException
47
53
  import java.util.concurrent.ExecutorService
48
54
  import java.util.concurrent.Executors
49
55
  import java.util.concurrent.TimeUnit
@@ -163,13 +169,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
163
169
  get() = DeviceStore.store.get("bluetooth", "power_saving_mode") as? Boolean ?: false
164
170
  set(value) = DeviceStore.apply("bluetooth", "power_saving_mode", value)
165
171
 
166
- // Phone-side VAD gating switch. Default is OFF (VAD runs) so the
167
- // coordinator can drive per-utterance offline/online STT switching from
168
- // `vad_status` events. Set to `true` only as an emergency kill-switch.
169
- private var bypassVad: Boolean
170
- get() = DeviceStore.store.get("bluetooth", "bypass_vad") as? Boolean ?: false
171
- set(value) = DeviceStore.apply("bluetooth", "bypass_vad", value)
172
-
173
172
  private var localSttFallbackActive: Boolean
174
173
  get() = DeviceStore.store.get("bluetooth", "local_stt_fallback_active") as? Boolean ?: false
175
174
  set(value) = DeviceStore.apply("bluetooth", "local_stt_fallback_active", value)
@@ -282,13 +281,23 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
282
281
  private var micReinitRunnable: Runnable? = null
283
282
  private var systemMicAvailabilityRecheckRunnable: Runnable? = null
284
283
 
285
- // VAD
286
- private val vadBuffer = mutableListOf<ByteArray>()
287
- private var isSpeaking = false
288
- private var vadPolicy: com.mentra.bluetoothsdk.stt.VadGateSpeechPolicy? = null
289
-
290
- // STT
291
- private var transcriber: SherpaOnnxTranscriber? = null
284
+ // STT: one recognizer, loaded only while on-device transcription is in demand. Models
285
+ // load on sttLoader (never on the audio thread or under a DeviceManager lock) and are
286
+ // swapped in afterwards; see OnDeviceRecognizerHost.
287
+ private val sttLoader: ExecutorService =
288
+ Executors.newSingleThreadExecutor { runnable ->
289
+ Thread(runnable, "SttModelLoader").apply { isDaemon = true }
290
+ }
291
+ private val transcription =
292
+ OnDeviceRecognizerHost(
293
+ selection = ::selectedSttModel,
294
+ loadModel = ::loadTranscriber,
295
+ pathMatches = { transcriber, path -> transcriber.isModelLoaded(path) },
296
+ // Returns at once; the model is released on its worker after queued audio.
297
+ release = { transcriber -> transcriber.shutdown() },
298
+ loader = sttLoader,
299
+ log = { message -> Bridge.log(message) },
300
+ )
292
301
 
293
302
  // View states
294
303
  private val viewStates = mutableListOf<ViewState>()
@@ -305,7 +314,9 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
305
314
  }
306
315
  }
307
316
  initializeViewStates()
308
- if (initializeHardware) initializeHardwareServices()
317
+ if (initializeHardware) {
318
+ initializeHardwareServices()
319
+ }
309
320
  }
310
321
 
311
322
  // Keep host routing usable without starting audio codecs, receivers or services.
@@ -331,30 +342,6 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
331
342
  lc3DecoderPtr = 0
332
343
  }
333
344
 
334
- // Initialize phone-side Silero VAD. Used by handlePcm to gate audio
335
- // fan-out and to drive per-utterance offline/online STT switching
336
- // (see LocalSttFallbackCoordinator on the JS side). If a previous
337
- // policy somehow exists (re-init on hot reload), stop it first to
338
- // release the ONNX session.
339
- try {
340
- vadPolicy?.stop()
341
- val ctx = Bridge.getContext()
342
- val policy = com.mentra.bluetoothsdk.stt.VadGateSpeechPolicy(ctx)
343
- policy.init(blockSizeSamples = 512)
344
- policy.onSpeechStateChanged = { speaking ->
345
- isSpeaking = speaking
346
- Bridge.sendVoiceActivityDetectionStatus(speaking)
347
- }
348
- vadPolicy = policy
349
- Bridge.log("VadGateSpeechPolicy initialized")
350
- } catch (e: Exception) {
351
- Bridge.log("Failed to initialize VadGateSpeechPolicy: ${e.message}")
352
- vadPolicy = null
353
- } catch (e: LinkageError) {
354
- Bridge.log("Failed to initialize VadGateSpeechPolicy: ${e.message}")
355
- vadPolicy = null
356
- }
357
-
358
345
  // Mic reinit check every 10 seconds
359
346
  val micReinitR =
360
347
  object : Runnable {
@@ -567,8 +554,10 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
567
554
 
568
555
  BluetoothAdapter.STATE_ON -> {
569
556
  Bridge.log("MAN: Bluetooth turned ON")
570
- // Auto-reconnect to last known device if we have one
571
- if (defaultWearable.isNotEmpty() && deviceName.isNotEmpty()) {
557
+ // Auto-reconnect to last known device if we have one.
558
+ // After owner loss, connectById watches for the next pairing
559
+ // mode instead of opening GATT.
560
+ if (shouldReconnectAfterBluetoothOn()) {
572
561
  Bridge.log(
573
562
  "MAN: Bluetooth restored, attempting reconnect to: $deviceName"
574
563
  )
@@ -959,22 +948,15 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
959
948
  // #endregion
960
949
 
961
950
  fun handlePcm(pcmData: ByteArray) {
962
- // Audio always flows. The previous phone-side Silero VAD gate was a
963
- // bandwidth-saver that ate transcripts when the mic delivered frames
964
- // not aligned to 512 samples (the case for Android AudioRecord on the
965
- // phone internal mic) and was never wired up correctly anyway —
966
- // `bypass_vad_for_debugging` was dead, cloud-side `bypass_vad` was
967
- // the only knob, and the policy double-VAD'd what the cloud already
968
- // VADs server-side. VadGateSpeechPolicy is kept around because
969
- // hardware-side VAD events from the glasses route through the same
970
- // class to fire `vad_status` (a separate signal the cloud SDK
971
- // surfaces as `session.audio.isSpeaking`).
951
+ // Audio always flows; nothing here gates it. The on-device consumers below only
952
+ // copy and queue on this (glasses or phone mic) audio thread: model loading and
953
+ // inference run on their own workers. The glasses' hardware voice detection
954
+ // (Mentra Live sr_vad -> speaking_status) is separate and unaffected.
955
+ WakeWordDetector.accept(pcmData)
956
+ SpeechActivityDetector.accept(pcmData)
972
957
  handleSendingPcm(pcmData)
973
- if (shouldSendTranscript || localSttFallbackActive) {
974
- if (ensureTranscriberInitialized()) {
975
- transcriber?.acceptAudio(pcmData)
976
- }
977
- }
958
+ // Non-null only while on-device transcription is in demand.
959
+ transcription.current?.acceptAudio(pcmData)
978
960
  }
979
961
 
980
962
  // turns a single mic on and turns off all other mics:
@@ -1446,55 +1428,67 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1446
1428
  }
1447
1429
  }
1448
1430
 
1431
+ /**
1432
+ * Finish the active recognizer's current utterance. Returns the final text once its
1433
+ * `local_transcription` event has been sent, `""` when nothing was pending, or null when
1434
+ * no streaming model is active, the loaded model can't finalize early, or the 3 s wait
1435
+ * expires. Never throws. Call from a background thread: the final event is delivered on
1436
+ * the main thread before this returns.
1437
+ */
1438
+ fun finishTranscription(): String? =
1439
+ try {
1440
+ transcription.current?.finishUtterance()
1441
+ } catch (e: Exception) {
1442
+ Bridge.log("STT: finishTranscription failed: ${e.message}")
1443
+ null
1444
+ }
1445
+
1446
+ /** Whether the active recognizer has [path] loaded. Lock-free; never waits on a load. */
1447
+ fun isSttModelLoaded(path: String): Boolean = transcription.isLoaded(path)
1448
+
1449
+ /**
1450
+ * Load the selected speech model if on-device transcription is in demand, and wait until
1451
+ * it is loaded. Returns at once when there is no demand or the model is already loaded;
1452
+ * throws when loading fails. Call from a background thread.
1453
+ */
1449
1454
  fun restartTranscriber() {
1450
1455
  Bridge.log("MAN: Restarting transcriber via command")
1451
- if (ensureTranscriberInitialized()) {
1452
- transcriber?.restart()
1456
+ try {
1457
+ transcription.restart().get()
1458
+ } catch (e: ExecutionException) {
1459
+ throw e.cause ?: e
1453
1460
  }
1454
1461
  }
1455
1462
 
1456
- private fun ensureTranscriberInitialized(): Boolean {
1457
- if (transcriber != null) return true
1458
-
1459
- return try {
1460
- val context = Bridge.getContext()
1461
- val nextTranscriber = SherpaOnnxTranscriber(context)
1462
- nextTranscriber.setTranscriptListener(
1463
- object : SherpaOnnxTranscriber.TranscriptListener {
1464
- override fun onPartialResult(text: String, language: String) {
1465
- Bridge.log("STT: Partial result: $text")
1466
- // The Sherpa model emits all-caps text; lowercase English
1467
- // output to match the rest of the pipeline (parity with iOS).
1468
- val formatted = if (language == "en-US") text.lowercase() else text
1469
- Bridge.sendLocalTranscription(formatted, false, language)
1470
- }
1463
+ private fun selectedSttModel(): OnDeviceRecognizerHost.Selection? {
1464
+ val context =
1465
+ try {
1466
+ Bridge.getContext()
1467
+ } catch (_: IllegalStateException) {
1468
+ return null
1469
+ }
1470
+ val path = STTTools.getSttModelPath(context).takeIf { it.isNotBlank() } ?: return null
1471
+ return OnDeviceRecognizerHost.Selection(path, STTTools.getSttModelLanguage(context))
1472
+ }
1473
+
1474
+ /** Runs on [sttLoader]. Throws when the model can't be loaded. */
1475
+ private fun loadTranscriber(selection: OnDeviceRecognizerHost.Selection): SherpaOnnxTranscriber {
1476
+ val next = SherpaOnnxTranscriber(Bridge.getContext(), selection.path, selection.language)
1477
+ next.setTranscriptListener(
1478
+ object : SherpaOnnxTranscriber.TranscriptListener {
1479
+ override fun onPartialResult(text: String, language: String) {
1480
+ Bridge.log("STT: Partial result: $text")
1481
+ Bridge.sendLocalTranscription(text, false, language)
1482
+ }
1471
1483
 
1472
- override fun onFinalResult(text: String, language: String) {
1473
- Bridge.log("STT: Final result: $text")
1474
- // The Sherpa model emits all-caps text; lowercase English
1475
- // output to match the rest of the pipeline (parity with iOS).
1476
- val formatted = if (language == "en-US") text.lowercase() else text
1477
- Bridge.sendLocalTranscription(formatted, true, language)
1478
- }
1484
+ override fun onFinalResult(text: String, language: String) {
1485
+ Bridge.log("STT: Final result: $text")
1486
+ Bridge.sendLocalTranscription(text, true, language)
1479
1487
  }
1480
- )
1481
- nextTranscriber.initialize()
1482
- if (!nextTranscriber.isInitialized()) {
1483
- Bridge.log("SherpaOnnxTranscriber initialize() returned without becoming ready")
1484
- return false
1485
1488
  }
1486
- transcriber = nextTranscriber
1487
- Bridge.log("SherpaOnnxTranscriber fully initialized")
1488
- true
1489
- } catch (e: Exception) {
1490
- Bridge.log("Failed to initialize SherpaOnnxTranscriber: ${e.message}")
1491
- transcriber = null
1492
- false
1493
- } catch (e: LinkageError) {
1494
- Bridge.log("Failed to initialize SherpaOnnxTranscriber: ${e.message}")
1495
- transcriber = null
1496
- false
1497
- }
1489
+ )
1490
+ next.load()
1491
+ return next
1498
1492
  }
1499
1493
 
1500
1494
  // MARK: - connection state management
@@ -1504,6 +1498,8 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1504
1498
  Bridge.log("MAN: SGC is null, returning")
1505
1499
  return
1506
1500
  }
1501
+ // Before clearPendingConnection(): the pending target is what marks an explicit pair.
1502
+ notePairingSessionReady()
1507
1503
 
1508
1504
  // A new identity must never inherit the previous glasses' address when
1509
1505
  // pairing supplied only a name. Same-device reconnects retain their cache.
@@ -1996,6 +1992,13 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
1996
1992
  driver.sendIncidentId(incidentId, apiBaseUrl)
1997
1993
  }
1998
1994
 
1995
+ fun sendBesCrashReported(incidentKey: String, reportId: String) {
1996
+ val driver = sgc ?: throw BluetoothSdkException(
1997
+ "glasses_not_connected", "Cannot report the BES crash because glasses are not connected.",
1998
+ )
1999
+ driver.sendBesCrashReported(incidentKey, reportId)
2000
+ }
2001
+
1999
2002
  /** Push a notification into the glasses' own notification centre; rejects unsupported or disconnected devices. */
2000
2003
  fun sendPhoneNotification(notification: Map<String, Any>) {
2001
2004
  // Package only - never the notification text.
@@ -2017,7 +2020,13 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2017
2020
  sgc?.sendHotspotState(enabled)
2018
2021
  }
2019
2022
 
2020
- fun setWifiAdbState(enabled: Boolean) {
2023
+ fun setWifiAdbState(enabled: Boolean, expectedBluetoothMac: String? = null) {
2024
+ if (expectedBluetoothMac != null) {
2025
+ val current = sgc as? MentraLive ?: throw BluetoothSdkException(
2026
+ "glasses_not_connected", "Mentra Live glasses are not connected.")
2027
+ current.sendWifiAdbStateToPeer(enabled, expectedBluetoothMac)
2028
+ return
2029
+ }
2021
2030
  Bridge.log("MAN: Setting glasses Wi-Fi ADB state: $enabled")
2022
2031
  sgc?.sendWifiAdbState(enabled)
2023
2032
  }
@@ -2288,14 +2297,9 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2288
2297
  val willSendPcm = shouldSendPcm || shouldSendLc3
2289
2298
  val willSendTranscript = shouldSendTranscript || localSttFallbackActive
2290
2299
  val nextEnabled = willSendPcm || willSendTranscript
2291
- // Tell VAD when the mic is shutting down so it doesn't get stuck in
2292
- // a stale "speaking" state and keep emitting vad_status=true after
2293
- // audio stops flowing.
2294
- if (micEnabled && !nextEnabled) {
2295
- vadPolicy?.microphoneStateChanged(false)
2296
- }
2300
+ // Load the recognizer while on-device transcription is in demand; release it when not.
2301
+ transcription.setDemand(willSendTranscript)
2297
2302
  micEnabled = nextEnabled
2298
- vadBuffer.clear()
2299
2303
  updateMicState()
2300
2304
  }
2301
2305
 
@@ -2339,6 +2343,37 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2339
2343
  sgc?.sendRgbLedControl(requestId, packageName, action, color, onDurationMs, offDurationMs, count)
2340
2344
  }
2341
2345
 
2346
+ internal fun shouldReconnectAfterBluetoothOn(): Boolean =
2347
+ defaultWearable.isNotEmpty() && deviceName.isNotEmpty()
2348
+
2349
+ /**
2350
+ * A ready Mentra Live session. Only an explicit pair (a pending target) clears
2351
+ * `pairing_rejected`; an automatic session only ends a pause and resets the streak.
2352
+ */
2353
+ internal fun notePairingSessionReady() {
2354
+ if (sgc !is MentraLive) return
2355
+ val explicitAttempt = pendingDeviceName.isNotEmpty() || pendingDeviceAddress.isNotEmpty()
2356
+ MentraLivePairingStateStore.update("device_ready") { it.onSessionReady(explicitAttempt) }
2357
+ }
2358
+
2359
+ /** Forget ends the pairing record. Also drops the pre-v4 owner-lost setting. */
2360
+ internal fun clearPairingStateOnForget() {
2361
+ MentraLivePairingStateStore.update("forget") { it.onForget() }
2362
+ if (DeviceStore.store.get("bluetooth", "mentra_live_owner_lost") as? Boolean != true) return
2363
+ DeviceStore.apply("bluetooth", "mentra_live_owner_lost", false)
2364
+ Bridge.saveSetting("mentra_live_owner_lost", false)
2365
+ }
2366
+
2367
+ /**
2368
+ * The saved glasses' firmware is no longer known once they are forgotten. The next glasses
2369
+ * report it again with their first `pairing_info`.
2370
+ */
2371
+ internal fun clearSecureFirmware() {
2372
+ if (DeviceStore.store.get("bluetooth", "mentra_live_secure_firmware") as? Boolean != true) return
2373
+ DeviceStore.apply("bluetooth", "mentra_live_secure_firmware", false)
2374
+ Bridge.saveSetting("mentra_live_secure_firmware", false)
2375
+ }
2376
+
2342
2377
  fun connectDefault() {
2343
2378
  if (defaultWearable.isEmpty()) {
2344
2379
  Bridge.log("MAN: No default wearable, returning")
@@ -2363,8 +2398,14 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2363
2398
  }
2364
2399
  initSGC(defaultWearable)
2365
2400
  val live = sgc as? MentraLive
2366
- if (live?.isPairingYieldActive() == true) {
2367
- Bridge.log("MAN: connectDefault skipped — Mentra Live pairing yield active")
2401
+ if (live != null && MentraLivePairingStateStore.isRejected) {
2402
+ Bridge.log("MAN: connectDefault skipped — Mentra Live pairing_rejected (Pair Again or forget)")
2403
+ return
2404
+ }
2405
+ if (live != null && MentraLivePairingStateStore.isPaused) {
2406
+ // connectById only records the target and watches for the window to end.
2407
+ Bridge.log("MAN: connectDefault deferred — Mentra Live pairing_mode")
2408
+ live.connectById(reconnectTarget)
2368
2409
  return
2369
2410
  }
2370
2411
  searching = true
@@ -2550,6 +2591,8 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2550
2591
  connectionRecovery.clear()
2551
2592
  }
2552
2593
  Bridge.log("MAN: Forgetting smart glasses")
2594
+ clearPairingStateOnForget()
2595
+ clearSecureFirmware()
2553
2596
 
2554
2597
  val live = sgc as? MentraLive
2555
2598
  if (live != null) {
@@ -2673,9 +2716,10 @@ class DeviceManager internal constructor(initializeHardware: Boolean) {
2673
2716
  systemMicAvailabilityRecheckRunnable?.let { mainHandler.removeCallbacks(it) }
2674
2717
  systemMicAvailabilityRecheckRunnable = null
2675
2718
 
2676
- // Clean up transcriber resources
2677
- transcriber?.shutdown()
2678
- transcriber = null
2719
+ // Release on-device voice models (each on its own worker).
2720
+ transcription.setDemand(false)
2721
+ WakeWordDetector.shutdown()
2722
+ SpeechActivityDetector.shutdown()
2679
2723
 
2680
2724
  // Clean up LC3 encoder/decoder (synchronized to prevent use-after-free
2681
2725
  // if the recording thread is mid-encode/decode)