@mentra/bluetooth-sdk 3.2.1 → 3.3.0-beta.1001

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 (108) hide show
  1. package/README.md +99 -6
  2. package/android/build.gradle +15 -0
  3. package/android/lc3Lib/build.gradle +6 -1
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +1 -1
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +6 -2
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +9 -1
  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 +231 -36
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +160 -20
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +3 -1
  25. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
  26. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
  30. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +20 -7
  39. package/build/BluetoothSdk.types.d.ts +9 -1
  40. package/build/BluetoothSdk.types.d.ts.map +1 -1
  41. package/build/BluetoothSdk.types.js.map +1 -1
  42. package/build/_private/BluetoothSdkModule.d.ts +2 -1
  43. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  44. package/build/_private/BluetoothSdkModule.js +2 -1
  45. package/build/_private/BluetoothSdkModule.js.map +1 -1
  46. package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
  47. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  48. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  49. package/build/_private/nativeLogConsole.d.ts +19 -0
  50. package/build/_private/nativeLogConsole.d.ts.map +1 -1
  51. package/build/_private/nativeLogConsole.js +12 -0
  52. package/build/_private/nativeLogConsole.js.map +1 -1
  53. package/build/generated/changelogCatalog.d.ts +4 -1
  54. package/build/generated/changelogCatalog.d.ts.map +1 -1
  55. package/build/generated/changelogCatalog.js +5 -1
  56. package/build/generated/changelogCatalog.js.map +1 -1
  57. package/build/generated/releaseMetadata.js +6 -6
  58. package/build/generated/releaseMetadata.js.map +1 -1
  59. package/build/index.d.ts +1 -1
  60. package/build/index.d.ts.map +1 -1
  61. package/build/index.js +1 -0
  62. package/build/index.js.map +1 -1
  63. package/build/ota-transport/index.d.ts +4 -0
  64. package/build/ota-transport/index.d.ts.map +1 -1
  65. package/build/ota-transport/index.js +2 -0
  66. package/build/ota-transport/index.js.map +1 -1
  67. package/ios/BluetoothSdkModule.swift +16 -4
  68. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  69. package/ios/Source/DeviceManager.swift +10 -3
  70. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  71. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  72. package/ios/Source/MentraBluetoothSDK.swift +306 -54
  73. package/ios/Source/TouchGesture.swift +13 -0
  74. package/ios/Source/events/BluetoothEvents.swift +4 -0
  75. package/ios/Source/internal/BluetoothAvailability.swift +6 -0
  76. package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
  77. package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
  78. package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
  79. package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
  80. package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
  81. package/ios/Source/sgcs/MentraLive.swift +167 -64
  82. package/ios/Source/sgcs/NimoCanvasCodec.swift +4 -1
  83. package/ios/Source/sgcs/SGCManager.swift +1 -1
  84. package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
  85. package/ios/Source/utils/G1Text.swift +2 -24
  86. package/ios/Source/utils/G1TextSanitizer.swift +27 -0
  87. package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
  88. package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
  89. package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
  90. package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
  91. package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
  92. package/ios/Tests/G1TextSanitizerTests.swift +32 -0
  93. package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
  94. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  95. package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
  96. package/ios/Tests/NimoCanvasCodecTests.swift +17 -4
  97. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  98. package/ios/Tests/VersionInfoCommandTests.swift +142 -1
  99. package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
  100. package/package.json +2 -2
  101. package/src/BluetoothSdk.types.ts +16 -0
  102. package/src/_private/BluetoothSdkModule.ts +4 -1
  103. package/src/_private/MentraLocalNetworkModule.ts +28 -0
  104. package/src/_private/nativeLogConsole.ts +19 -0
  105. package/src/generated/changelogCatalog.ts +5 -1
  106. package/src/generated/releaseMetadata.ts +6 -6
  107. package/src/index.ts +2 -0
  108. package/src/ota-transport/index.ts +10 -1
@@ -8,6 +8,7 @@ import android.content.Context
8
8
  import android.os.Bundle
9
9
  import android.os.Handler
10
10
  import android.os.Looper
11
+ import android.util.Log
11
12
  import com.mentra.bluetoothsdk.streaming.StreamSessionState
12
13
  import com.mentra.bluetoothsdk.utils.ControllerTypes
13
14
  import com.mentra.bluetoothsdk.utils.PhoneAudioMonitor
@@ -34,6 +35,21 @@ class MentraBluetoothSdk private constructor(
34
35
  private val listeners =
35
36
  Collections.synchronizedSet(mutableSetOf<MentraBluetoothSdkListener>())
36
37
  private val analytics = BluetoothSdkAnalytics(appContext, config.analytics)
38
+ private val updateCheck =
39
+ BluetoothSdkUpdateCheck(appContext, config.analytics.surface) { banner, result ->
40
+ Log.w(UPDATE_LOG_TAG, banner)
41
+ dispatchToListeners {
42
+ it.onRawEvent(
43
+ "sdk_update_notice",
44
+ buildMap {
45
+ put("message", banner)
46
+ put("status", result.status)
47
+ put("installedVersion", BuildConfig.SDK_VERSION)
48
+ result.latestVersion?.let { latest -> put("latestVersion", latest) }
49
+ },
50
+ )
51
+ }
52
+ }
37
53
  private val discoveredDeviceNames = mutableSetOf<String>()
38
54
  private val bridgeEventSinkId: String
39
55
  private val storeListenerId: String
@@ -99,6 +115,7 @@ class MentraBluetoothSdk private constructor(
99
115
  analytics.initializeGlassesStatus(getRawGlassesStatus())
100
116
  storeListenerId = DeviceStore.store.addListener { category, changes -> dispatchStoreUpdate(category, changes) }
101
117
  analytics.captureStarted()
118
+ updateCheck.start()
102
119
  }
103
120
 
104
121
  companion object {
@@ -106,6 +123,8 @@ class MentraBluetoothSdk private constructor(
106
123
  private val SCAN_STATE_KEYS = setOf("searching", "searchingController", "searchResults")
107
124
  private const val DEFAULT_SCAN_TIMEOUT_MS = 15_000L
108
125
  private const val DEFAULT_REQUEST_TIMEOUT_MS = 15_000L
126
+ private const val UPDATE_LOG_TAG = "MentraBluetoothSDK"
127
+ private val MIC_STATE_KEYS = setOf("currentMic", "should_send_transcript", "local_stt_fallback_active")
109
128
  // Mirrors AsgConstants: one active + one coalesced pending FOV update, plus BLE margin.
110
129
  // Keep in sync with ios/Source/MentraBluetoothSDK.swift and the ASG readiness budget.
111
130
  private const val CAMERA_FOV_READY_TIMEOUT_MS = 20_000L
@@ -240,8 +259,10 @@ class MentraBluetoothSdk private constructor(
240
259
  // (expo.modules.AsyncFunctionQueue), so a blocked await here froze all
241
260
  // miniapp event delivery (Crust.mentraJsDispatchToJs) until the glasses
242
261
  // responded. resolve()/reject() stay callable from any thread.
243
- private class PendingResponse<T>(
262
+ private inner class PendingResponse<T>(
244
263
  private val operation: String,
264
+ // The operation without per-request ids, so timeouts group in analytics.
265
+ private val telemetryOperation: String = operation,
245
266
  ) {
246
267
  private val deferred = CompletableDeferred<T>()
247
268
 
@@ -258,10 +279,13 @@ class MentraBluetoothSdk private constructor(
258
279
  // can only mean the deadline elapsed. A rejected deferred rethrows
259
280
  // its error from await() and propagates out unchanged.
260
281
  return withTimeoutOrNull(timeoutMs) { deferred.await() }
261
- ?: throw BluetoothSdkException(
262
- "request_timeout",
263
- "$operation timed out waiting for glasses response.",
264
- )
282
+ ?: run {
283
+ analytics.recordUsage { requestTimedOut(telemetryOperation) }
284
+ throw BluetoothSdkException(
285
+ "request_timeout",
286
+ "$operation timed out waiting for glasses response.",
287
+ )
288
+ }
265
289
  }
266
290
 
267
291
  }
@@ -503,6 +527,7 @@ class MentraBluetoothSdk private constructor(
503
527
  }
504
528
 
505
529
  fun cancelConnectionAttempt() {
530
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.DISCONNECT_CANCEL)
506
531
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_name", "")
507
532
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_address", "")
508
533
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_secure_pairing_capable", "")
@@ -514,6 +539,7 @@ class MentraBluetoothSdk private constructor(
514
539
  }
515
540
 
516
541
  fun disconnect() {
542
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.DISCONNECT_USER)
517
543
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_name", "")
518
544
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_address", "")
519
545
  DeviceStore.apply(ObservableStore.BLUETOOTH_CATEGORY, "pending_device_secure_pairing_capable", "")
@@ -521,6 +547,7 @@ class MentraBluetoothSdk private constructor(
521
547
  }
522
548
 
523
549
  fun forget() {
550
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.DISCONNECT_FORGET)
524
551
  deviceManager.forget()
525
552
  }
526
553
 
@@ -613,6 +640,14 @@ class MentraBluetoothSdk private constructor(
613
640
  send = { requestId -> deviceManager.sendGalleryServerEnabled(requestId, enabled) },
614
641
  )
615
642
 
643
+ /** Disable a stock action while retaining touch events. Reset by BES on BLE disconnect. */
644
+ suspend fun setTouchGestureDefaultBehaviorEnabled(gesture: TouchGesture, enabled: Boolean): SettingsAckEvent =
645
+ performSettingsCommand(
646
+ setting = "touch_gesture_default",
647
+ updateStore = {},
648
+ send = { requestId -> deviceManager.sendTouchGestureDefaultBehaviorEnabled(requestId, gesture, enabled) },
649
+ )
650
+
616
651
  suspend fun setGalleryModeEnabled(enabled: Boolean): SettingsAckEvent =
617
652
  performSettingsCommand(
618
653
  setting = "gallery_mode",
@@ -947,8 +982,12 @@ class MentraBluetoothSdk private constructor(
947
982
  pendingWifiStatus = PendingWifiStatusRequest(ssid, pending)
948
983
  }
949
984
  try {
950
- deviceManager.sendWifiCredentials(ssid, password)
951
- return pending.await()
985
+ return withUsageOutcome(
986
+ { latencyMs, errorCode, _ -> analytics.recordUsage { wifiSetupSettled(latencyMs, errorCode) } },
987
+ ) {
988
+ deviceManager.sendWifiCredentials(ssid, password)
989
+ pending.await()
990
+ }
952
991
  } finally {
953
992
  synchronized(oneShotLock) {
954
993
  if (pendingWifiStatus?.pending === pending) {
@@ -1062,8 +1101,14 @@ class MentraBluetoothSdk private constructor(
1062
1101
  pendingHotspotStatus = PendingHotspotStatusRequest(enabled, pending)
1063
1102
  }
1064
1103
  try {
1065
- deviceManager.setHotspotState(enabled)
1066
- pending.await()
1104
+ withUsageOutcome(
1105
+ { latencyMs, errorCode, _ ->
1106
+ if (enabled) analytics.recordUsage { hotspotStartSettled(latencyMs, errorCode) }
1107
+ },
1108
+ ) {
1109
+ deviceManager.setHotspotState(enabled)
1110
+ pending.await()
1111
+ }
1067
1112
  } finally {
1068
1113
  synchronized(oneShotLock) {
1069
1114
  if (pendingHotspotStatus?.pending === pending) {
@@ -1090,13 +1135,31 @@ class MentraBluetoothSdk private constructor(
1090
1135
  Bridge.log(
1091
1136
  "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.requestPhoto requestId=${routedRequest.requestId}"
1092
1137
  )
1093
- val pending = PendingResponse<PhotoResponseEvent>("photo request ${routedRequest.requestId}")
1138
+ val pending = PendingResponse<PhotoResponseEvent>("photo request ${routedRequest.requestId}", "photo request")
1094
1139
  pendingPhotoRequests[routedRequest.requestId] = pending
1095
1140
  try {
1096
- deviceManager.requestPhoto(routedRequest)
1097
- return pending.await(
1098
- if (routedRequest.presendThumbnail) PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS else PHOTO_REQUEST_TIMEOUT_MS,
1099
- )
1141
+ return withUsageOutcome(
1142
+ { latencyMs, errorCode, event ->
1143
+ val fileSizeBytes = (event?.response as? PhotoResponse.Success)?.fileSizeBytes
1144
+ analytics.recordUsage {
1145
+ photoSettled(
1146
+ size = routedRequest.size.value,
1147
+ mode = routedRequest.mode.value,
1148
+ compress = routedRequest.compress.value,
1149
+ save = routedRequest.save,
1150
+ transferMethod = routedRequest.transferMethod,
1151
+ latencyMs = latencyMs,
1152
+ fileSizeBytes = fileSizeBytes,
1153
+ errorCode = errorCode,
1154
+ )
1155
+ }
1156
+ },
1157
+ ) {
1158
+ deviceManager.requestPhoto(routedRequest)
1159
+ pending.await(
1160
+ if (routedRequest.presendThumbnail) PHOTO_THUMBNAIL_REQUEST_TIMEOUT_MS else PHOTO_REQUEST_TIMEOUT_MS,
1161
+ )
1162
+ }
1100
1163
  } finally {
1101
1164
  pendingPhotoRequests.remove(routedRequest.requestId, pending)
1102
1165
  }
@@ -1112,7 +1175,7 @@ class MentraBluetoothSdk private constructor(
1112
1175
  mfnr: Boolean? = null,
1113
1176
  ): CameraStatusEvent {
1114
1177
  val effectiveRequestId = nonBlankRequestId(requestId) ?: generatedCameraRequestId("warm")
1115
- val pending = PendingResponse<CameraStatusEvent>("camera warm up $effectiveRequestId")
1178
+ val pending = PendingResponse<CameraStatusEvent>("camera warm up $effectiveRequestId", "camera warm up")
1116
1179
  // Guard against a concurrent warm-up reusing the same requestId: a blind put would overwrite
1117
1180
  // (and strand) the first caller's continuation until it times out. Reject the duplicate.
1118
1181
  if (pendingCameraStatusRequests.putIfAbsent(effectiveRequestId, pending) != null) {
@@ -1159,35 +1222,55 @@ class MentraBluetoothSdk private constructor(
1159
1222
  }
1160
1223
 
1161
1224
  suspend fun startStream(request: StreamRequest): StreamStatusEvent {
1162
- requireGlassesConnected("start stream")
1163
- if (!streamSession.supported) {
1164
- throw BluetoothSdkException("stream_control_unsupported", "Update the glasses software before starting a stream.")
1165
- }
1166
1225
  val message = request.toMap().toMutableMap()
1167
1226
  val streamId = (message["streamId"] as? String)?.takeIf { it.isNotBlank() }
1168
1227
  ?: "sdk-${UUID.randomUUID()}"
1169
1228
  message["streamId"] = streamId
1170
- val pending = PendingResponse<StreamStatusEvent>("start stream $streamId")
1171
- var start: PendingStreamStart? = null
1172
- try {
1173
- // seq assignment and the BLE hand-off must be one critical section:
1174
- // rejectPreemptedStreamStarts only works if seq order equals the
1175
- // order the commands reach the glasses' FIFO.
1176
- synchronized(streamStartOrderLock) {
1177
- val registered = PendingStreamStart(streamStartSeq.incrementAndGet(), pending)
1178
- pendingStreamStarts[streamId] = registered
1179
- start = registered
1180
- deviceManager.startStream(message)
1229
+ return withUsageOutcome(
1230
+ { latencyMs, errorCode, _ ->
1231
+ val glassesNetwork = glassesNetwork()
1232
+ analytics.recordUsage {
1233
+ streamStartSettled(
1234
+ streamUrl = request.streamUrl,
1235
+ width = request.video?.width,
1236
+ height = request.video?.height,
1237
+ fps = request.video?.fps,
1238
+ bitrate = request.video?.bitrate,
1239
+ captureAudio = request.captureAudio,
1240
+ glassesNetwork = glassesNetwork,
1241
+ latencyMs = latencyMs,
1242
+ errorCode = errorCode,
1243
+ )
1244
+ }
1245
+ },
1246
+ ) {
1247
+ requireGlassesConnected("start stream")
1248
+ if (!streamSession.supported) {
1249
+ throw BluetoothSdkException("stream_control_unsupported", "Update the glasses software before starting a stream.")
1250
+ }
1251
+ val pending = PendingResponse<StreamStatusEvent>("start stream $streamId", "start stream")
1252
+ val requestedAt = System.currentTimeMillis()
1253
+ analytics.recordUsage { streamRequested(streamId, request.streamUrl, requestedAt) }
1254
+ var start: PendingStreamStart? = null
1255
+ try {
1256
+ // seq assignment and the BLE hand-off must be one critical section:
1257
+ // rejectPreemptedStreamStarts only works if seq order equals the
1258
+ // order the commands reach the glasses' FIFO.
1259
+ synchronized(streamStartOrderLock) {
1260
+ val registered = PendingStreamStart(streamStartSeq.incrementAndGet(), pending)
1261
+ pendingStreamStarts[streamId] = registered
1262
+ start = registered
1263
+ deviceManager.startStream(message)
1264
+ }
1265
+ pending.await(STREAM_START_TIMEOUT_MS)
1266
+ } finally {
1267
+ start?.let { pendingStreamStarts.remove(streamId, it) }
1181
1268
  }
1182
- val event = pending.await(STREAM_START_TIMEOUT_MS)
1183
- return event
1184
- } finally {
1185
- start?.let { pendingStreamStarts.remove(streamId, it) }
1186
1269
  }
1187
1270
  }
1188
1271
 
1189
1272
  suspend fun rgbLedControl(request: RgbLedRequest): RgbLedControlResponseEvent {
1190
- val pending = PendingResponse<RgbLedControlResponseEvent>("RGB LED command ${request.requestId}")
1273
+ val pending = PendingResponse<RgbLedControlResponseEvent>("RGB LED command ${request.requestId}", "RGB LED command")
1191
1274
  pendingRgbLedRequests[request.requestId] = pending
1192
1275
  try {
1193
1276
  deviceManager.rgbLedControl(
@@ -1206,6 +1289,7 @@ class MentraBluetoothSdk private constructor(
1206
1289
  }
1207
1290
 
1208
1291
  suspend fun stopStream(): StreamStatusEvent {
1292
+ analytics.updateUsage { streamStopRequested() }
1209
1293
  val pending = PendingResponse<StreamStatusEvent>("stop stream")
1210
1294
  val targetStreamId = streamSession.currentStreamId
1211
1295
  try {
@@ -1247,6 +1331,16 @@ class MentraBluetoothSdk private constructor(
1247
1331
  "A video recording command is already waiting for requestId ${request.requestId}.",
1248
1332
  )
1249
1333
  }
1334
+ analytics.updateUsage {
1335
+ videoRequested(
1336
+ request.requestId,
1337
+ request.width,
1338
+ request.height,
1339
+ request.fps,
1340
+ request.save,
1341
+ request.maxRecordingTimeMinutes,
1342
+ )
1343
+ }
1250
1344
  try {
1251
1345
  deviceManager.startVideoRecording(
1252
1346
  request.requestId,
@@ -1285,6 +1379,7 @@ class MentraBluetoothSdk private constructor(
1285
1379
  "A video recording command is already waiting for requestId $requestId.",
1286
1380
  )
1287
1381
  }
1382
+ analytics.updateUsage { videoStopRequested(requestId) }
1288
1383
  try {
1289
1384
  deviceManager.stopVideoRecording(requestId, webhookUrl, authToken)
1290
1385
  val timeoutMs =
@@ -1591,6 +1686,7 @@ class MentraBluetoothSdk private constructor(
1591
1686
  Bridge.removeEventSink(bridgeEventSinkId)
1592
1687
  DeviceStore.store.removeListener(storeListenerId)
1593
1688
  analytics.shutdown()
1689
+ updateCheck.stop()
1594
1690
  listeners.clear()
1595
1691
  }
1596
1692
 
@@ -1600,7 +1696,7 @@ class MentraBluetoothSdk private constructor(
1600
1696
  if (changes["connected"] == false) {
1601
1697
  resetWifiProtocolSession("", "wifi_session_disconnected")
1602
1698
  }
1603
- analytics.observeGlassesStatus(getRawGlassesStatus())
1699
+ analytics.observeGlassesStatus(getRawGlassesStatus(), ::isPhoneBluetoothOff)
1604
1700
  val state = getState()
1605
1701
  dispatchToListeners {
1606
1702
  it.onStateChanged(state)
@@ -1608,6 +1704,12 @@ class MentraBluetoothSdk private constructor(
1608
1704
  }
1609
1705
  }
1610
1706
  ObservableStore.BLUETOOTH_CATEGORY -> {
1707
+ if (analytics.isEnabled && changes.keys.any { it in MIC_STATE_KEYS }) {
1708
+ val bluetooth = getRawBluetoothStatus()
1709
+ val transcribing = bluetooth.shouldSendTranscript || bluetooth.localSttFallbackActive
1710
+ val now = System.currentTimeMillis()
1711
+ analytics.recordUsage { observeMic(bluetooth.currentMic, transcribing, now) }
1712
+ }
1611
1713
  val state = getState()
1612
1714
  val scanChanged = changes.keys.any { it in SCAN_STATE_KEYS }
1613
1715
  dispatchToListeners {
@@ -1874,6 +1976,10 @@ class MentraBluetoothSdk private constructor(
1874
1976
  "photo_response" -> {
1875
1977
  val event = PhotoResponseEvent(data)
1876
1978
  handlePhotoResponseForRequests(event)
1979
+ val response = event.response
1980
+ if (response is PhotoResponse.Error && event.requestId == BluetoothSdkUsageTracker.LOCAL_PHOTO_REQUEST_ID) {
1981
+ analytics.recordUsage { buttonPhotoFailed(response.errorCode) }
1982
+ }
1877
1983
  dispatchToListeners { it.onPhotoResponse(event) }
1878
1984
  }
1879
1985
  "photo_status" -> dispatchToListeners { it.onPhotoStatus(PhotoStatusEvent(data)) }
@@ -1885,6 +1991,8 @@ class MentraBluetoothSdk private constructor(
1885
1991
  "video_recording_status" -> {
1886
1992
  val event = VideoRecordingStatusEvent(data)
1887
1993
  handleVideoRecordingStatusForRequests(event)
1994
+ val now = System.currentTimeMillis()
1995
+ analytics.recordUsage { videoStatus(event.requestId, event.status, event.success, now) }
1888
1996
  dispatchToListeners { it.onVideoRecordingStatus(event) }
1889
1997
  }
1890
1998
  "media_success", "media_error" -> {
@@ -1904,6 +2012,7 @@ class MentraBluetoothSdk private constructor(
1904
2012
  if (data.containsKey("revision") && !streamSession.accept(data)) return
1905
2013
  val event = StreamStatusEvent(data)
1906
2014
  handleStreamStatusForRequests(event)
2015
+ recordStreamStatus(event)
1907
2016
  dispatchToListeners { it.onStreamStatus(event) }
1908
2017
  }
1909
2018
  "keep_alive_ack" -> {
@@ -1928,6 +2037,23 @@ class MentraBluetoothSdk private constructor(
1928
2037
  )
1929
2038
  }
1930
2039
  }
2040
+ if (analytics.isEnabled) {
2041
+ val glasses = getRawGlassesStatus()
2042
+ val now = System.currentTimeMillis()
2043
+ analytics.recordUsage {
2044
+ otaStatus(
2045
+ sessionId = event.sessionId,
2046
+ status = event.status,
2047
+ stepType = event.stepType,
2048
+ totalSteps = event.totalSteps,
2049
+ errorMessage = event.errorMessage,
2050
+ fromBuildNumber = glasses.buildNumber,
2051
+ fromBesFirmwareVersion = glasses.besFirmwareVersion,
2052
+ fromMtkFirmwareVersion = glasses.mtkFirmwareVersion,
2053
+ nowMs = now,
2054
+ )
2055
+ }
2056
+ }
1931
2057
  dispatchToListeners { it.onOtaStatus(event) }
1932
2058
  }
1933
2059
  "mic_health" -> {
@@ -1983,6 +2109,75 @@ class MentraBluetoothSdk private constructor(
1983
2109
  }
1984
2110
  }
1985
2111
 
2112
+ private fun recordStreamStatus(event: StreamStatusEvent) {
2113
+ if (!analytics.isEnabled) return
2114
+ val status = event.status
2115
+ val attempt =
2116
+ when (status) {
2117
+ is StreamStatus.Reconnecting -> status.attempt
2118
+ is StreamStatus.Reconnected -> status.attempt
2119
+ else -> null
2120
+ }
2121
+ val errorDetails = event.errorDetails ?: (status as? StreamStatus.Error)?.errorDetails
2122
+ val now = System.currentTimeMillis()
2123
+ analytics.recordUsage {
2124
+ streamStatus(
2125
+ streamId = event.streamId,
2126
+ state = event.state.value,
2127
+ terminal = event.terminal,
2128
+ reconnectAttempt = attempt,
2129
+ bitrate = event.stats?.bitrate,
2130
+ fps = event.stats?.fps,
2131
+ droppedFrames = event.stats?.droppedFrames,
2132
+ temperatureC = event.stats?.temperatureC,
2133
+ errorDetails = errorDetails,
2134
+ nowMs = now,
2135
+ )
2136
+ }
2137
+ }
2138
+
2139
+ private fun glassesNetwork(): String {
2140
+ val glasses = getRawGlassesStatus()
2141
+ return when {
2142
+ glasses.hotspot is HotspotStatus.Enabled -> "hotspot"
2143
+ glasses.wifi is WifiStatus.Connected -> "wifi"
2144
+ else -> "none"
2145
+ }
2146
+ }
2147
+
2148
+ private fun isPhoneBluetoothOff(): Boolean =
2149
+ try {
2150
+ (appContext.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter?.isEnabled == false
2151
+ } catch (_: Exception) {
2152
+ false
2153
+ }
2154
+
2155
+ /**
2156
+ * Runs a glasses command and reports its latency and outcome to usage
2157
+ * analytics. Cancellation is the caller giving up, not a command outcome, so
2158
+ * it is not reported.
2159
+ */
2160
+ private inline fun <T> withUsageOutcome(
2161
+ record: (latencyMs: Long, errorCode: String?, result: T?) -> Unit,
2162
+ block: () -> T,
2163
+ ): T {
2164
+ val startedAt = System.currentTimeMillis()
2165
+ val result =
2166
+ try {
2167
+ block()
2168
+ } catch (error: CancellationException) {
2169
+ throw error
2170
+ } catch (error: Exception) {
2171
+ if (analytics.isEnabled) {
2172
+ val errorCode = (error as? BluetoothSdkException)?.code ?: error.javaClass.simpleName
2173
+ record(System.currentTimeMillis() - startedAt, errorCode, null)
2174
+ }
2175
+ throw error
2176
+ }
2177
+ if (analytics.isEnabled) record(System.currentTimeMillis() - startedAt, null, result)
2178
+ return result
2179
+ }
2180
+
1986
2181
  private fun dispatchToListeners(callback: (MentraBluetoothSdkListener) -> Unit) {
1987
2182
  val snapshot = synchronized(listeners) { listeners.toList() }
1988
2183
  val deliver = {
@@ -41,6 +41,30 @@ class MentraLocalNetworkModule : Module() {
41
41
  Name("MentraLocalNetwork")
42
42
  Events("downloadProgress", "networkLost")
43
43
 
44
+ Function("getNetworkDiagnostics") {
45
+ val manager = connectivityManager()
46
+ // Sample time marks the beginning of these sequential local OS reads.
47
+ val sampledAtMs = System.currentTimeMillis()
48
+ networkDiagnostics(
49
+ sampledAtMs,
50
+ manager.boundNetworkForProcess,
51
+ manager.activeNetwork,
52
+ synchronized(lock) { localNetwork },
53
+ ) { network ->
54
+ manager.getNetworkCapabilities(network)?.let { capabilities ->
55
+ mapOf(
56
+ "wifi" to capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI),
57
+ "cellular" to capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR),
58
+ "ethernet" to capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET),
59
+ "vpn" to capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN),
60
+ "internet" to capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET),
61
+ "validated" to capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED),
62
+ "captivePortal" to capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL),
63
+ )
64
+ }
65
+ }
66
+ }
67
+
44
68
  AsyncFunction("connect") { ssid: String, password: String, promise: Promise ->
45
69
  connect(ssid, password, promise)
46
70
  }
@@ -0,0 +1,25 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ /** Only routing relationships and capabilities cross the bridge, never network identities. */
4
+ internal fun <N> networkDiagnostics(
5
+ sampledAtMs: Long,
6
+ processBound: N?,
7
+ activeNetwork: N?,
8
+ glassesLocal: N?,
9
+ capabilities: (N) -> Map<String, Boolean>?,
10
+ ): Map<String, Any?> {
11
+ fun observation(network: N?): Map<String, Any?> = mapOf(
12
+ "present" to (network != null),
13
+ "capabilities" to network?.let(capabilities),
14
+ )
15
+ fun same(first: N?, second: N?): Boolean = first != null && first == second
16
+ return mapOf(
17
+ "sampledAtMs" to sampledAtMs,
18
+ "processBound" to observation(processBound),
19
+ "activeNetwork" to observation(activeNetwork),
20
+ "glassesLocal" to observation(glassesLocal),
21
+ "processBoundMatchesActive" to same(processBound, activeNetwork),
22
+ "processBoundMatchesGlassesLocal" to same(processBound, glassesLocal),
23
+ "activeNetworkMatchesGlassesLocal" to same(activeNetwork, glassesLocal),
24
+ )
25
+ }
@@ -0,0 +1,19 @@
1
+ package com.mentra.bluetoothsdk
2
+
3
+ /** Mentra Live touchpad gestures, using the public touch_event names. */
4
+ enum class TouchGesture(val wireName: String) {
5
+ SINGLE_TAP("single_tap"),
6
+ DOUBLE_TAP("double_tap"),
7
+ TRIPLE_TAP("triple_tap"),
8
+ LONG_PRESS("long_press"),
9
+ FORWARD_SWIPE("forward_swipe"),
10
+ BACKWARD_SWIPE("backward_swipe"),
11
+ UP_SWIPE("up_swipe"),
12
+ DOWN_SWIPE("down_swipe");
13
+
14
+ companion object {
15
+ fun fromWireName(value: String): TouchGesture =
16
+ entries.firstOrNull { it.wireName == value }
17
+ ?: throw BluetoothSdkException("invalid_touch_gesture", "Unknown touch gesture: $value")
18
+ }
19
+ }
@@ -108,6 +108,9 @@ object BleTraceLogger {
108
108
  }
109
109
 
110
110
  private fun sanitizeValue(key: String?, value: Any?): Any? {
111
+ // Scan security metadata is a boolean, not a credential. Keep the exact
112
+ // typed field while still redacting string/unknown values under this key.
113
+ if (key == "requiresPassword" && value is Boolean) return value
111
114
  if (key != null && sensitiveKeyParts.any { key.contains(it, ignoreCase = true) }) {
112
115
  return "<redacted>"
113
116
  }
@@ -29,6 +29,10 @@ internal class ClassicAudioConnectionTracker(
29
29
  val connected: Boolean
30
30
  get() = connectedProfiles.isNotEmpty()
31
31
 
32
+ /** BLE may already be gone when the user explicitly disconnects Classic audio. */
33
+ @Synchronized
34
+ fun targetForDisconnect(): String? = targetAddress
35
+
32
36
  @Synchronized
33
37
  fun setTarget(address: String) {
34
38
  val normalizedAddress = address.normalizedBluetoothAddress()
@@ -0,0 +1,70 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import android.bluetooth.BluetoothDevice
4
+ import android.os.Handler
5
+ import android.os.ParcelUuid
6
+
7
+ /** One bounded SDP discovery; a BLE bond alone does not populate Android's Classic UUID cache. */
8
+ internal class ClassicAudioServiceDiscovery(
9
+ private val handler: Handler,
10
+ private val timeoutMs: Long,
11
+ private val log: (String) -> Unit,
12
+ ) {
13
+ private class Pending(val device: BluetoothDevice, val ready: () -> Unit) {
14
+ lateinit var timeout: Runnable
15
+ }
16
+ private var pending: Pending? = null
17
+
18
+ fun connectWhenDiscovered(device: BluetoothDevice, ready: () -> Unit) {
19
+ if (hasAudioSink(device)) {
20
+ cancel()
21
+ ready()
22
+ return
23
+ }
24
+ if (pending?.device?.address == device.address) return
25
+ cancel()
26
+ val request = Pending(device, ready)
27
+ request.timeout = Runnable {
28
+ if (pending === request) {
29
+ cancel()
30
+ log("SDP timed out for ${device.address}; Classic audio remains disconnected")
31
+ }
32
+ }
33
+ pending = request
34
+ handler.postDelayed(request.timeout, timeoutMs)
35
+ try {
36
+ log("Refreshing Classic service UUIDs for ${device.address}")
37
+ if (!device.fetchUuidsWithSdp()) {
38
+ cancel()
39
+ log("SDP request rejected for ${device.address}; Classic audio remains disconnected")
40
+ }
41
+ } catch (error: Exception) {
42
+ cancel()
43
+ log("SDP request failed for ${device.address}: ${error.message}")
44
+ }
45
+ }
46
+
47
+ /** ACTION_UUID is a completion hint. Read the current OS cache, not a stale intent payload. */
48
+ fun onUuids(device: BluetoothDevice) {
49
+ val request = pending ?: return
50
+ if (device.address != request.device.address) return
51
+ if (hasAudioSink(request.device)) {
52
+ cancel()
53
+ log("Discovered A2DP Sink UUID for ${device.address}")
54
+ request.ready()
55
+ } else {
56
+ // Bonding can announce cached UUIDs before SDP finishes. Keep the original deadline.
57
+ log("UUID event without A2DP Sink for ${device.address}; waiting for SDP within the existing deadline")
58
+ }
59
+ }
60
+
61
+ fun cancel() {
62
+ pending?.let { handler.removeCallbacks(it.timeout) }
63
+ pending = null
64
+ }
65
+
66
+ companion object {
67
+ private val AUDIO_SINK = ParcelUuid.fromString("0000110b-0000-1000-8000-00805f9b34fb")
68
+ fun hasAudioSink(device: BluetoothDevice): Boolean = device.uuids?.contains(AUDIO_SINK) == true
69
+ }
70
+ }