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

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
@@ -134,9 +134,12 @@ private final class PendingVideoRecordingRequest {
134
134
  private final class PendingVersionInfoRequest {
135
135
  let pending: PendingResponse<VersionInfoResult>
136
136
  let accumulator: VersionInfoResponseAccumulator
137
+ let requestId: String
138
+ let startedAt = ProcessInfo.processInfo.systemUptime
137
139
 
138
140
  init(pending: PendingResponse<VersionInfoResult>, requestId: String) {
139
141
  self.pending = pending
142
+ self.requestId = requestId
140
143
  accumulator = VersionInfoResponseAccumulator(expectedRequestId: requestId)
141
144
  }
142
145
  }
@@ -163,13 +166,18 @@ private final class PendingStreamStart {
163
166
  @MainActor
164
167
  final class PendingResponse<T> {
165
168
  private let operation: String
169
+ /// The operation without per-request ids, so timeouts group in analytics.
170
+ private let telemetryOperation: String
171
+ private let onTimeout: ((String) -> Void)?
166
172
  private var continuation: CheckedContinuation<T, Error>?
167
173
  private var timeoutTask: Task<Void, Never>?
168
174
  private var result: Result<T, Error>?
169
175
  private var completed = false
170
176
 
171
- init(operation: String) {
177
+ init(operation: String, telemetryOperation: String? = nil, onTimeout: ((String) -> Void)? = nil) {
172
178
  self.operation = operation
179
+ self.telemetryOperation = telemetryOperation ?? operation
180
+ self.onTimeout = onTimeout
173
181
  }
174
182
 
175
183
  func resolve(_ value: T) {
@@ -207,10 +215,12 @@ final class PendingResponse<T> {
207
215
  } catch {
208
216
  return
209
217
  }
210
- self?.reject(
218
+ guard let self, !self.completed else { return }
219
+ self.onTimeout?(self.telemetryOperation)
220
+ self.reject(
211
221
  BluetoothSdkError(
212
222
  code: "request_timeout",
213
- message: "\(self?.operation ?? "Request") timed out waiting for glasses response."
223
+ message: "\(self.operation) timed out waiting for glasses response."
214
224
  )
215
225
  )
216
226
  }
@@ -254,6 +264,7 @@ public final class MentraBluetoothSDK {
254
264
  private static let otaBesVersionWaitMs = 5000
255
265
  private static let otaMtkVersionWaitMs = 2000
256
266
  private static let otaVersionPollMs = 100
267
+ private static let micStateKeys: Set<String> = ["currentMic", "should_send_transcript", "local_stt_fallback_active"]
257
268
 
258
269
  public weak var delegate: MentraBluetoothSDKDelegate?
259
270
 
@@ -272,6 +283,7 @@ public final class MentraBluetoothSDK {
272
283
  private var activeScanSessions: [UUID: ActiveScanSession] = [:]
273
284
  private let streamSession = StreamSessionState()
274
285
  private let analytics: BluetoothSdkAnalytics
286
+ private var updateCheck: BluetoothSdkUpdateCheck?
275
287
  private var pendingPhotoRequests: [String: PendingResponse<PhotoResponseEvent>] = [:]
276
288
  private var pendingCameraStatusRequests: [String: PendingResponse<CameraStatusEvent>] = [:]
277
289
  private var pendingVideoRecordingRequests: [String: PendingVideoRecordingRequest] = [:]
@@ -350,6 +362,31 @@ public final class MentraBluetoothSDK {
350
362
  }
351
363
  analytics.initializeGlassesStatus(glassesStatus)
352
364
  analytics.captureStarted()
365
+ let updateCheck = BluetoothSdkUpdateCheck(
366
+ surface: BluetoothSdkUpdateCheck.surface(forAnalyticsSurface: configuration.analytics.surface)
367
+ ) { [weak self] banner, result in
368
+ NSLog("%@", banner)
369
+ var values: [String: Any] = [
370
+ "message": banner,
371
+ "status": result.status,
372
+ "installedVersion": BluetoothSdkDefaults.sdkVersion ?? "unknown",
373
+ ]
374
+ if let latestVersion = result.latestVersion { values["latestVersion"] = latestVersion }
375
+ let notice = values
376
+ Task { @MainActor [weak self] in
377
+ guard let self else { return }
378
+ self.delegate?.mentraBluetoothSDK(self, didReceive: .raw(name: "sdk_update_notice", values: notice))
379
+ }
380
+ }
381
+ self.updateCheck = updateCheck
382
+ updateCheck.start()
383
+ }
384
+
385
+ /// Reports a glasses command that timed out, without its per-request id.
386
+ private var requestTimeoutReporter: (String) -> Void {
387
+ { [weak self] operation in
388
+ self?.analytics.recordUsage { $0.requestTimedOut(operation: operation) }
389
+ }
353
390
  }
354
391
 
355
392
  public var state: MentraBluetoothState {
@@ -545,6 +582,7 @@ public final class MentraBluetoothSDK {
545
582
  }
546
583
 
547
584
  public func cancelConnectionAttempt() {
585
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectCancel)
548
586
  clearBluetoothRestoreIntent()
549
587
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_name", "")
550
588
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_address", "")
@@ -558,6 +596,7 @@ public final class MentraBluetoothSDK {
558
596
  }
559
597
 
560
598
  public func disconnect() {
599
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectUser)
561
600
  clearBluetoothRestoreIntent()
562
601
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_name", "")
563
602
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_address", "")
@@ -566,6 +605,7 @@ public final class MentraBluetoothSDK {
566
605
  }
567
606
 
568
607
  public func forget() {
608
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectForget)
569
609
  clearBluetoothRestoreIntent()
570
610
  DeviceManager.shared.forget()
571
611
  }
@@ -664,6 +704,17 @@ public final class MentraBluetoothSDK {
664
704
  )
665
705
  }
666
706
 
707
+ /// Disable a stock action while retaining touch events. Reset by BES on BLE disconnect.
708
+ public func setTouchGestureDefaultBehaviorEnabled(_ gesture: TouchGesture, enabled: Bool) async throws -> SettingsAckEvent {
709
+ try await performSettingsCommand(
710
+ setting: "touch_gesture_default",
711
+ updateStore: { _ in },
712
+ send: { requestId in
713
+ try DeviceManager.shared.sendTouchGestureDefaultBehaviorEnabled(requestId: requestId, gesture: gesture, enabled: enabled)
714
+ }
715
+ )
716
+ }
717
+
667
718
  public func setGalleryModeEnabled(_ enabled: Bool) async throws -> SettingsAckEvent {
668
719
  try await performSettingsCommand(
669
720
  setting: "gallery_mode",
@@ -678,7 +729,7 @@ public final class MentraBluetoothSDK {
678
729
  send: (String) throws -> Void
679
730
  ) async throws -> SettingsAckEvent {
680
731
  let requestId = "settings-\(setting)-\(UUID().uuidString)"
681
- let pending = PendingResponse<SettingsAckEvent>(operation: "set \(setting)")
732
+ let pending = PendingResponse<SettingsAckEvent>(operation: "set \(setting)", onTimeout: requestTimeoutReporter)
682
733
  pendingSettingsRequests[requestId] = pending
683
734
  do {
684
735
  try send(requestId)
@@ -951,7 +1002,7 @@ public final class MentraBluetoothSDK {
951
1002
  // the scan screen auto-starts a scan on mount and can be pushed twice.
952
1003
  return try await existing.value
953
1004
  }
954
- let pending = PendingResponse<[WifiScanResult]>(operation: "WiFi scan request")
1005
+ let pending = PendingResponse<[WifiScanResult]>(operation: "WiFi scan request", onTimeout: requestTimeoutReporter)
955
1006
  let request = PendingWifiScan(pending: pending, scanId: "scan-\(UUID().uuidString)")
956
1007
  pendingWifiScan = request
957
1008
  // Claim the scan-results store for this scan before the command goes out,
@@ -991,11 +1042,15 @@ public final class MentraBluetoothSDK {
991
1042
  message: "A WiFi status command is already waiting for a glasses response."
992
1043
  )
993
1044
  }
994
- let pending = PendingResponse<WifiStatusEvent>(operation: "WiFi connect request")
1045
+ let pending = PendingResponse<WifiStatusEvent>(operation: "WiFi connect request", onTimeout: requestTimeoutReporter)
995
1046
  pendingWifiStatus = PendingWifiStatusRequest(ssid: ssid, pending: pending)
996
- DeviceManager.shared.sendWifiCredentials(ssid, password)
997
1047
  do {
998
- let event = try await pending.wait()
1048
+ let event = try await withUsageOutcome(record: { latencyMs, errorCode, _ in
1049
+ analytics.recordUsage { $0.wifiSetupSettled(latencyMs: latencyMs, errorCode: errorCode) }
1050
+ }) {
1051
+ DeviceManager.shared.sendWifiCredentials(ssid, password)
1052
+ return try await pending.wait()
1053
+ }
999
1054
  if pendingWifiStatus?.pending === pending {
1000
1055
  pendingWifiStatus = nil
1001
1056
  }
@@ -1018,7 +1073,7 @@ public final class MentraBluetoothSDK {
1018
1073
  message: "A WiFi status command is already waiting for a glasses response."
1019
1074
  )
1020
1075
  }
1021
- let pending = PendingResponse<WifiForgetResult>(operation: "WiFi forget request")
1076
+ let pending = PendingResponse<WifiForgetResult>(operation: "WiFi forget request", onTimeout: requestTimeoutReporter)
1022
1077
  let requestId = "forget-\(UUID().uuidString)"
1023
1078
  let request = PendingWifiForgetRequest(
1024
1079
  ssid: ssid,
@@ -1063,7 +1118,7 @@ public final class MentraBluetoothSDK {
1063
1118
  error: "saved_wifi_networks_unsupported"
1064
1119
  )
1065
1120
  }
1066
- let pending = PendingResponse<SavedWifiNetworksResult>(operation: "Saved WiFi networks request")
1121
+ let pending = PendingResponse<SavedWifiNetworksResult>(operation: "Saved WiFi networks request", onTimeout: requestTimeoutReporter)
1067
1122
  let request = PendingSavedWifiNetworks(
1068
1123
  requestId: requestId,
1069
1124
  sid: wifiSessionCapabilities.sessionId,
@@ -1100,12 +1155,18 @@ public final class MentraBluetoothSDK {
1100
1155
  _ = try? await previous.value
1101
1156
  }
1102
1157
  let pending = PendingResponse<HotspotStatusEvent>(
1103
- operation: "hotspot \(enabled ? "enable" : "disable") request"
1158
+ operation: "hotspot \(enabled ? "enable" : "disable") request",
1159
+ onTimeout: self.requestTimeoutReporter
1104
1160
  )
1105
1161
  self.pendingHotspotStatus = PendingHotspotStatusRequest(enabled: enabled, pending: pending)
1106
- DeviceManager.shared.setHotspotState(enabled)
1107
1162
  do {
1108
- let event = try await pending.wait()
1163
+ let event = try await self.withUsageOutcome(record: { latencyMs, errorCode, _ in
1164
+ guard enabled else { return }
1165
+ self.analytics.recordUsage { $0.hotspotStartSettled(latencyMs: latencyMs, errorCode: errorCode) }
1166
+ }) {
1167
+ DeviceManager.shared.setHotspotState(enabled)
1168
+ return try await pending.wait()
1169
+ }
1109
1170
  if self.pendingHotspotStatus?.pending === pending {
1110
1171
  self.pendingHotspotStatus = nil
1111
1172
  }
@@ -1138,13 +1199,30 @@ public final class MentraBluetoothSDK {
1138
1199
  Bridge.log(
1139
1200
  "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.requestPhoto requestId=\(routedRequest.requestId)"
1140
1201
  )
1141
- let pending = PendingResponse<PhotoResponseEvent>(operation: "photo request \(routedRequest.requestId)")
1202
+ let pending = PendingResponse<PhotoResponseEvent>(operation: "photo request \(routedRequest.requestId)", telemetryOperation: "photo request", onTimeout: requestTimeoutReporter)
1142
1203
  pendingPhotoRequests[routedRequest.requestId] = pending
1143
- DeviceManager.shared.requestPhoto(routedRequest)
1144
1204
  do {
1145
- let event = try await pending.wait(timeoutMs: routedRequest.presendThumbnail
1146
- ? MentraBluetoothSDK.photoThumbnailRequestTimeoutMs
1147
- : MentraBluetoothSDK.photoRequestTimeoutMs)
1205
+ let event = try await withUsageOutcome(record: { (latencyMs, errorCode, event: PhotoResponseEvent?) in
1206
+ var fileSizeBytes: Int64?
1207
+ if case let .success(_, _, _, _, _, size?, _) = event?.response { fileSizeBytes = Int64(size) }
1208
+ analytics.recordUsage {
1209
+ $0.photoSettled(
1210
+ size: routedRequest.size.rawValue,
1211
+ mode: routedRequest.mode.rawValue,
1212
+ compress: routedRequest.compress.rawValue,
1213
+ save: routedRequest.save,
1214
+ transferMethod: routedRequest.transferMethod,
1215
+ latencyMs: latencyMs,
1216
+ fileSizeBytes: fileSizeBytes,
1217
+ errorCode: errorCode
1218
+ )
1219
+ }
1220
+ }) {
1221
+ DeviceManager.shared.requestPhoto(routedRequest)
1222
+ return try await pending.wait(timeoutMs: routedRequest.presendThumbnail
1223
+ ? MentraBluetoothSDK.photoThumbnailRequestTimeoutMs
1224
+ : MentraBluetoothSDK.photoRequestTimeoutMs)
1225
+ }
1148
1226
  pendingPhotoRequests.removeValue(forKey: routedRequest.requestId)
1149
1227
  return event
1150
1228
  } catch {
@@ -1163,7 +1241,7 @@ public final class MentraBluetoothSDK {
1163
1241
  mfnr: Bool? = nil
1164
1242
  ) async throws -> CameraStatusEvent {
1165
1243
  let effectiveRequestId = nonBlankRequestId(requestId) ?? generatedCameraRequestId("warm")
1166
- let pending = PendingResponse<CameraStatusEvent>(operation: "camera warm up \(effectiveRequestId)")
1244
+ let pending = PendingResponse<CameraStatusEvent>(operation: "camera warm up \(effectiveRequestId)", telemetryOperation: "camera warm up", onTimeout: requestTimeoutReporter)
1167
1245
  pendingCameraStatusRequests[effectiveRequestId] = pending
1168
1246
  do {
1169
1247
  // Inside the catch so an unsupported-device throw also clears the pending entry.
@@ -1201,7 +1279,7 @@ public final class MentraBluetoothSDK {
1201
1279
  message: "A gallery status query is already waiting for a glasses response."
1202
1280
  )
1203
1281
  }
1204
- let pending = PendingResponse<GalleryStatusEvent>(operation: "gallery status query")
1282
+ let pending = PendingResponse<GalleryStatusEvent>(operation: "gallery status query", onTimeout: requestTimeoutReporter)
1205
1283
  pendingGalleryStatus = pending
1206
1284
  DeviceManager.shared.queryGalleryStatus()
1207
1285
  do {
@@ -1219,33 +1297,53 @@ public final class MentraBluetoothSDK {
1219
1297
  }
1220
1298
 
1221
1299
  public func startStream(_ request: StreamRequest) async throws -> StreamStatusEvent {
1222
- try requireGlassesConnected(operation: "start stream")
1223
- guard streamSession.supported else {
1224
- throw BluetoothSdkError(code: "stream_control_unsupported", message: "Update the glasses software before starting a stream.")
1225
- }
1226
1300
  var values = request.values
1227
1301
  let streamId = stringValue(values, "streamId").flatMap { $0.isEmpty ? nil : $0 } ?? "sdk-\(UUID().uuidString)"
1228
1302
  values["streamId"] = streamId
1229
- let pending = PendingResponse<StreamStatusEvent>(operation: "start stream \(streamId)")
1230
- // seq assignment through the BLE hand-off must stay await-free so this
1231
- // MainActor turn is one critical section: rejectPreemptedStreamStarts
1232
- // only works if seq order equals the order the commands reach the
1233
- // glasses' FIFO.
1234
- streamStartSeq += 1
1235
- pendingStreamStarts[streamId] = PendingStreamStart(seq: streamStartSeq, pending: pending)
1236
- DeviceManager.shared.startStream(values)
1237
- do {
1238
- let event = try await pending.wait(timeoutMs: 30000)
1239
- pendingStreamStarts.removeValue(forKey: streamId)
1240
- return event
1241
- } catch {
1242
- pendingStreamStarts.removeValue(forKey: streamId)
1243
- throw error
1303
+ let message = values
1304
+ return try await withUsageOutcome(record: { latencyMs, errorCode, _ in
1305
+ let glassesNetwork = glassesNetwork()
1306
+ analytics.recordUsage {
1307
+ $0.streamStartSettled(
1308
+ streamUrl: request.streamUrl,
1309
+ width: request.video?.width,
1310
+ height: request.video?.height,
1311
+ fps: request.video?.fps,
1312
+ bitrate: request.video?.bitrate,
1313
+ captureAudio: request.captureAudio,
1314
+ glassesNetwork: glassesNetwork,
1315
+ latencyMs: latencyMs,
1316
+ errorCode: errorCode
1317
+ )
1318
+ }
1319
+ }) {
1320
+ try requireGlassesConnected(operation: "start stream")
1321
+ guard streamSession.supported else {
1322
+ throw BluetoothSdkError(code: "stream_control_unsupported", message: "Update the glasses software before starting a stream.")
1323
+ }
1324
+ let pending = PendingResponse<StreamStatusEvent>(operation: "start stream \(streamId)", telemetryOperation: "start stream", onTimeout: requestTimeoutReporter)
1325
+ let requestedAt = BluetoothSdkAnalytics.epochMillis()
1326
+ analytics.recordUsage { $0.streamRequested(streamId: streamId, streamUrl: request.streamUrl, nowMs: requestedAt) }
1327
+ // seq assignment through the BLE hand-off must stay await-free so this
1328
+ // MainActor turn is one critical section: rejectPreemptedStreamStarts
1329
+ // only works if seq order equals the order the commands reach the
1330
+ // glasses' FIFO.
1331
+ streamStartSeq += 1
1332
+ pendingStreamStarts[streamId] = PendingStreamStart(seq: streamStartSeq, pending: pending)
1333
+ DeviceManager.shared.startStream(message)
1334
+ do {
1335
+ let event = try await pending.wait(timeoutMs: 30000)
1336
+ pendingStreamStarts.removeValue(forKey: streamId)
1337
+ return event
1338
+ } catch {
1339
+ pendingStreamStarts.removeValue(forKey: streamId)
1340
+ throw error
1341
+ }
1244
1342
  }
1245
1343
  }
1246
1344
 
1247
1345
  public func rgbLedControl(_ request: RgbLedRequest) async throws -> RgbLedControlResponseEvent {
1248
- let pending = PendingResponse<RgbLedControlResponseEvent>(operation: "RGB LED command \(request.requestId)")
1346
+ let pending = PendingResponse<RgbLedControlResponseEvent>(operation: "RGB LED command \(request.requestId)", telemetryOperation: "RGB LED command", onTimeout: requestTimeoutReporter)
1249
1347
  pendingRgbLedRequests[request.requestId] = pending
1250
1348
  DeviceManager.shared.rgbLedControl(
1251
1349
  requestId: request.requestId,
@@ -1267,13 +1365,14 @@ public final class MentraBluetoothSDK {
1267
1365
  }
1268
1366
 
1269
1367
  public func stopStream() async throws -> StreamStatusEvent {
1368
+ analytics.updateUsage { $0.streamStopRequested() }
1270
1369
  guard pendingStreamStop == nil else {
1271
1370
  throw BluetoothSdkError(
1272
1371
  code: "request_in_flight",
1273
1372
  message: "A stream stop command is already waiting for a glasses response."
1274
1373
  )
1275
1374
  }
1276
- let pending = PendingResponse<StreamStatusEvent>(operation: "stop stream")
1375
+ let pending = PendingResponse<StreamStatusEvent>(operation: "stop stream", onTimeout: requestTimeoutReporter)
1277
1376
  // The seq draw and the BLE hand-off stay in this single await-free
1278
1377
  // MainActor turn, sharing startStream's ordering critical section:
1279
1378
  // the stop takes its own slot in the send order, so its ack can
@@ -1302,7 +1401,9 @@ public final class MentraBluetoothSDK {
1302
1401
  }
1303
1402
  try requireGlassesConnected(operation: "start video recording")
1304
1403
  let pending = PendingResponse<VideoRecordingStatusEvent>(
1305
- operation: "start video recording \(request.requestId)"
1404
+ operation: "start video recording \(request.requestId)",
1405
+ telemetryOperation: "start video recording",
1406
+ onTimeout: requestTimeoutReporter
1306
1407
  )
1307
1408
  guard pendingVideoRecordingRequests[request.requestId] == nil else {
1308
1409
  throw BluetoothSdkError(
@@ -1314,6 +1415,16 @@ public final class MentraBluetoothSDK {
1314
1415
  expectedStatus: "recording_started",
1315
1416
  pending: pending
1316
1417
  )
1418
+ analytics.updateUsage {
1419
+ $0.videoRequested(
1420
+ requestId: request.requestId,
1421
+ width: request.width,
1422
+ height: request.height,
1423
+ fps: request.fps,
1424
+ save: request.save,
1425
+ maxDurationMinutes: request.maxRecordingTimeMinutes
1426
+ )
1427
+ }
1317
1428
  DeviceManager.shared.startVideoRecording(
1318
1429
  request.requestId,
1319
1430
  request.save,
@@ -1340,7 +1451,7 @@ public final class MentraBluetoothSDK {
1340
1451
  throw BluetoothSdkError(code: "missing_request_id", message: "requestId is required to stop video recording.")
1341
1452
  }
1342
1453
  try requireGlassesConnected(operation: "stop video recording")
1343
- let pending = PendingResponse<VideoRecordingStatusEvent>(operation: "stop video recording \(requestId)")
1454
+ let pending = PendingResponse<VideoRecordingStatusEvent>(operation: "stop video recording \(requestId)", telemetryOperation: "stop video recording", onTimeout: requestTimeoutReporter)
1344
1455
  guard pendingVideoRecordingRequests[requestId] == nil else {
1345
1456
  throw BluetoothSdkError(
1346
1457
  code: "request_in_flight",
@@ -1353,6 +1464,7 @@ public final class MentraBluetoothSDK {
1353
1464
  pending: pending,
1354
1465
  waitForUpload: waitForUpload
1355
1466
  )
1467
+ analytics.updateUsage { $0.videoStopRequested(requestId: requestId) }
1356
1468
  DeviceManager.shared.stopVideoRecording(requestId, webhookUrl, authToken)
1357
1469
  do {
1358
1470
  let timeoutMs = waitForUpload ? videoUploadStopTimeoutMs : 15000
@@ -1373,7 +1485,7 @@ public final class MentraBluetoothSDK {
1373
1485
  )
1374
1486
  }
1375
1487
  try requireGlassesConnected(operation: "query video recording status")
1376
- let pending = PendingResponse<VideoRecordingStatusEvent>(operation: "query video recording status \(requestId)")
1488
+ let pending = PendingResponse<VideoRecordingStatusEvent>(operation: "query video recording status \(requestId)", telemetryOperation: "query video recording status", onTimeout: requestTimeoutReporter)
1377
1489
  guard pendingVideoRecordingRequests[requestId] == nil else {
1378
1490
  throw BluetoothSdkError(
1379
1491
  code: "request_in_flight",
@@ -1396,27 +1508,35 @@ public final class MentraBluetoothSDK {
1396
1508
  }
1397
1509
 
1398
1510
  public func requestVersionInfo() async throws -> VersionInfoResult {
1399
- guard pendingVersionInfo == nil else {
1511
+ if let request = pendingVersionInfo {
1512
+ logVersionInfoRequest(request, stage: "refused", extra: ["code": "request_in_flight"])
1400
1513
  throw BluetoothSdkError(
1401
1514
  code: "request_in_flight",
1402
1515
  message: "A version info request is already waiting for a glasses response."
1403
1516
  )
1404
1517
  }
1405
1518
  let requestId = UUID().uuidString
1406
- let pending = PendingResponse<VersionInfoResult>(operation: "version info request")
1519
+ let pending = PendingResponse<VersionInfoResult>(operation: "version info request", onTimeout: requestTimeoutReporter)
1407
1520
  let request = PendingVersionInfoRequest(pending: pending, requestId: requestId)
1408
1521
  pendingVersionInfo = request
1522
+ logVersionInfoRequest(request, stage: "registered")
1409
1523
  DeviceManager.shared.requestVersionInfo(requestId: requestId)
1410
1524
  do {
1411
1525
  let status = try await pending.wait()
1412
1526
  if pendingVersionInfo === request {
1413
1527
  pendingVersionInfo = nil
1414
1528
  }
1529
+ logVersionInfoRequest(request, stage: "resolved")
1415
1530
  return status
1416
1531
  } catch {
1417
1532
  if pendingVersionInfo === request {
1418
1533
  pendingVersionInfo = nil
1419
1534
  }
1535
+ let sdkError = error as? BluetoothSdkError
1536
+ logVersionInfoRequest(request, stage: "rejected", extra: [
1537
+ "code": sdkError?.code ?? String((error as NSError).code),
1538
+ "message": String((sdkError?.message ?? error.localizedDescription).prefix(256)),
1539
+ ])
1420
1540
  throw error
1421
1541
  }
1422
1542
  }
@@ -1494,7 +1614,7 @@ public final class MentraBluetoothSDK {
1494
1614
  message: "An OTA status query is already waiting for a glasses response."
1495
1615
  )
1496
1616
  }
1497
- let pending = PendingResponse<OtaQueryResult>(operation: operation)
1617
+ let pending = PendingResponse<OtaQueryResult>(operation: operation, onTimeout: requestTimeoutReporter)
1498
1618
  pendingOtaQuery = pending
1499
1619
  sendRequest()
1500
1620
  do {
@@ -1525,7 +1645,7 @@ public final class MentraBluetoothSDK {
1525
1645
  message: "An OTA start command is already waiting for a glasses response."
1526
1646
  )
1527
1647
  }
1528
- let pending = PendingResponse<OtaStartAckEvent>(operation: "OTA start command")
1648
+ let pending = PendingResponse<OtaStartAckEvent>(operation: "OTA start command", onTimeout: requestTimeoutReporter)
1529
1649
  pendingOtaStart = pending
1530
1650
  DeviceManager.shared.sendOtaStart(otaVersionUrl: otaVersionUrl)
1531
1651
  do {
@@ -1656,8 +1776,8 @@ public final class MentraBluetoothSDK {
1656
1776
  DeviceManager.shared.sendReboot()
1657
1777
  }
1658
1778
 
1659
- func sendIncidentId(_ incidentId: String, apiBaseUrl: String? = nil) {
1660
- DeviceManager.shared.sendIncidentId(incidentId, apiBaseUrl: apiBaseUrl)
1779
+ func sendIncidentId(_ incidentId: String, apiBaseUrl: String? = nil) throws {
1780
+ try DeviceManager.shared.sendIncidentId(incidentId, apiBaseUrl: apiBaseUrl)
1661
1781
  }
1662
1782
 
1663
1783
  public func invalidate() {
@@ -1674,6 +1794,7 @@ public final class MentraBluetoothSDK {
1674
1794
  DeviceStore.shared.store.removeListener(storeListenerId)
1675
1795
  self.storeListenerId = nil
1676
1796
  }
1797
+ updateCheck?.stop()
1677
1798
  delegate = nil
1678
1799
  }
1679
1800
 
@@ -2267,17 +2388,90 @@ public final class MentraBluetoothSDK {
2267
2388
  )
2268
2389
  }
2269
2390
 
2391
+ private func recordStreamStatus(_ event: StreamStatusEvent) {
2392
+ guard analytics.isEnabled else { return }
2393
+ let attempt: Int?
2394
+ var statusErrorDetails: String?
2395
+ switch event.status {
2396
+ case let .reconnecting(_, reconnectAttempt, _, _, _, _), let .reconnected(_, reconnectAttempt, _, _):
2397
+ attempt = reconnectAttempt
2398
+ case let .error(_, errorDetails, _, _):
2399
+ attempt = nil
2400
+ statusErrorDetails = errorDetails
2401
+ default:
2402
+ attempt = nil
2403
+ }
2404
+ let errorDetails = event.errorDetails ?? statusErrorDetails
2405
+ let stats = event.stats
2406
+ let now = BluetoothSdkAnalytics.epochMillis()
2407
+ analytics.recordUsage {
2408
+ $0.streamStatus(
2409
+ streamId: event.streamId,
2410
+ state: event.state.rawValue,
2411
+ terminal: event.terminal,
2412
+ reconnectAttempt: attempt,
2413
+ bitrate: stats?.bitrate,
2414
+ fps: stats?.fps,
2415
+ droppedFrames: stats?.droppedFrames,
2416
+ temperatureC: stats?.temperatureC,
2417
+ errorDetails: errorDetails,
2418
+ nowMs: now
2419
+ )
2420
+ }
2421
+ }
2422
+
2423
+ private func glassesNetwork() -> String {
2424
+ let glasses = glassesStatus
2425
+ if case .enabled = glasses.hotspot { return "hotspot" }
2426
+ if case .connected = glasses.wifi { return "wifi" }
2427
+ return "none"
2428
+ }
2429
+
2430
+ /// Runs a glasses command and reports its latency and outcome to usage
2431
+ /// analytics. Cancellation is the caller giving up, not a command outcome, so
2432
+ /// it is not reported.
2433
+ private func withUsageOutcome<T>(
2434
+ record: (_ latencyMs: Int64, _ errorCode: String?, _ result: T?) -> Void,
2435
+ _ block: () async throws -> T
2436
+ ) async throws -> T {
2437
+ let startedAt = ProcessInfo.processInfo.systemUptime
2438
+ func elapsedMs() -> Int64 {
2439
+ Int64(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded(.down))
2440
+ }
2441
+ let result: T
2442
+ do {
2443
+ result = try await block()
2444
+ } catch {
2445
+ let sdkError = error as? BluetoothSdkError
2446
+ let cancelled = error is CancellationError || sdkError?.code == "request_cancelled"
2447
+ if analytics.isEnabled, !cancelled {
2448
+ record(elapsedMs(), sdkError?.code ?? String(describing: type(of: error)), nil)
2449
+ }
2450
+ throw error
2451
+ }
2452
+ if analytics.isEnabled { record(elapsedMs(), nil, result) }
2453
+ return result
2454
+ }
2455
+
2270
2456
  private func dispatchStoreUpdate(_ category: String, _ changes: [String: Any]) {
2271
2457
  switch ObservableStore.normalizeCategory(category) {
2272
2458
  case "glasses":
2273
2459
  if changes["connected"] as? Bool == false {
2274
2460
  resetWifiProtocolSession(sessionId: "", code: "wifi_session_disconnected")
2275
2461
  }
2276
- analytics.observeGlassesStatus(glassesStatus)
2462
+ // CBCentralManager state is read here on the main actor, not on the analytics queue.
2463
+ let phoneBluetoothOff = BluetoothAvailability.shared.isPoweredOff
2464
+ analytics.observeGlassesStatus(glassesStatus) { phoneBluetoothOff }
2277
2465
  let nextState = state
2278
2466
  delegate?.mentraBluetoothSDK(self, didUpdate: nextState)
2279
2467
  delegate?.mentraBluetoothSDK(self, didUpdateGlasses: nextState.glasses)
2280
2468
  case ObservableStore.bluetoothCategory:
2469
+ if analytics.isEnabled, changes.keys.contains(where: { Self.micStateKeys.contains($0) }) {
2470
+ let bluetooth = bluetoothStatus
2471
+ let transcribing = bluetooth.shouldSendTranscript || bluetooth.localSttFallbackActive
2472
+ let now = BluetoothSdkAnalytics.epochMillis()
2473
+ analytics.recordUsage { $0.observeMic(currentMic: bluetooth.currentMic, transcribing: transcribing, nowMs: now) }
2474
+ }
2281
2475
  let nextState = state
2282
2476
  delegate?.mentraBluetoothSDK(self, didUpdate: nextState)
2283
2477
  delegate?.mentraBluetoothSDK(self, didUpdateSdkState: nextState.sdk)
@@ -2379,17 +2573,48 @@ public final class MentraBluetoothSDK {
2379
2573
 
2380
2574
  private func handleVersionInfoForRequest(_ data: [String: Any]) {
2381
2575
  guard let request = pendingVersionInfo else { return }
2382
- switch request.accumulator.accept(data) {
2576
+ let outcome = request.accumulator.accept(data)
2577
+ var response: [String: Any] = [
2578
+ "responseRequestId": String((data[VersionInfoResponseAccumulator.responseRequestIdKey] as? String ?? "").prefix(128)),
2579
+ "responseChunk": String((data[VersionInfoResponseAccumulator.responseChunkKey] as? String ?? "").prefix(64)),
2580
+ ]
2581
+ for key in [VersionInfoResponseAccumulator.responseIndexKey,
2582
+ VersionInfoResponseAccumulator.responseCountKey,
2583
+ VersionInfoResponseAccumulator.responseFinalKey]
2584
+ {
2585
+ // Typed strings survive the logger's Bool/NSNumber sanitization and
2586
+ // preserve malformed metadata rather than making it look valid.
2587
+ if let value = data[key] as? NSNumber {
2588
+ response[key] = CFGetTypeID(value) == CFBooleanGetTypeID()
2589
+ ? "boolean:\(value.boolValue)" : "number:\(value.stringValue)"
2590
+ } else if let value = data[key] as? String {
2591
+ response[key] = "string:\(value.prefix(64))"
2592
+ } else if let value = data[key] {
2593
+ response[key] = "unsupported:\(type(of: value))"
2594
+ }
2595
+ }
2596
+ switch outcome {
2383
2597
  case .ignored:
2384
- break
2598
+ logVersionInfoRequest(request, stage: "response-ignored", extra: response)
2385
2599
  case .waiting:
2386
- break
2600
+ logVersionInfoRequest(request, stage: "response-waiting", extra: response)
2387
2601
  case let .complete(result):
2602
+ logVersionInfoRequest(request, stage: "response-complete", extra: response)
2388
2603
  pendingVersionInfo = nil
2389
2604
  request.pending.resolve(result)
2390
2605
  }
2391
2606
  }
2392
2607
 
2608
+ private func logVersionInfoRequest(_ request: PendingVersionInfoRequest, stage: String, extra: [String: Any] = [:]) {
2609
+ var payload: [String: Any] = [
2610
+ "requestId": request.requestId,
2611
+ "stage": stage,
2612
+ "elapsedMs": Int((ProcessInfo.processInfo.systemUptime - request.startedAt) * 1000),
2613
+ ]
2614
+ payload.merge(extra) { _, value in value }
2615
+ BleTraceLogger.logMap(direction: "phone_app", layer: "sdk_version_request", type: "version_info", payload: payload)
2616
+ }
2617
+
2393
2618
  private func dispatchBridgeEvent(_ eventName: String, _ data: [String: Any]) {
2394
2619
  switch eventName {
2395
2620
  case "log":
@@ -2487,6 +2712,11 @@ public final class MentraBluetoothSDK {
2487
2712
  case "photo_response":
2488
2713
  let event = PhotoResponseEvent(values: data)
2489
2714
  handlePhotoResponseForRequests(event)
2715
+ if case let .error(requestId, errorCode, _, _) = event.response,
2716
+ requestId == BluetoothSdkUsageTracker.localPhotoRequestId
2717
+ {
2718
+ analytics.recordUsage { $0.buttonPhotoFailed(errorCode: errorCode) }
2719
+ }
2490
2720
  delegate?.mentraBluetoothSDK(self, didReceive: .photoResponse(event))
2491
2721
  case "photo_status":
2492
2722
  delegate?.mentraBluetoothSDK(self, didReceive: .photoStatus(PhotoStatusEvent(values: data)))
@@ -2497,6 +2727,10 @@ public final class MentraBluetoothSDK {
2497
2727
  case "video_recording_status":
2498
2728
  let event = VideoRecordingStatusEvent(values: data)
2499
2729
  handleVideoRecordingStatusForRequests(event)
2730
+ let now = BluetoothSdkAnalytics.epochMillis()
2731
+ analytics.recordUsage {
2732
+ $0.videoStatus(requestId: event.requestId, status: event.status, success: event.success, nowMs: now)
2733
+ }
2500
2734
  delegate?.mentraBluetoothSDK(self, didReceive: .videoRecordingStatus(event))
2501
2735
  case "media_success", "media_error":
2502
2736
  let event = MediaUploadEvent(values: data)
@@ -2512,6 +2746,7 @@ public final class MentraBluetoothSDK {
2512
2746
  if data["revision"] != nil && !streamSession.accept(data) { return }
2513
2747
  let event = StreamStatusEvent(values: data)
2514
2748
  handleStreamStatusForRequests(event)
2749
+ recordStreamStatus(event)
2515
2750
  delegate?.mentraBluetoothSDK(self, didReceive: .streamStatus(event))
2516
2751
  case "keep_alive_ack":
2517
2752
  let event = KeepAliveAckEvent(values: data)
@@ -2532,6 +2767,23 @@ public final class MentraBluetoothSDK {
2532
2767
  BluetoothSdkError(code: errorCode, message: "Glasses rejected OTA start: \(errorCode)")
2533
2768
  )
2534
2769
  }
2770
+ if analytics.isEnabled {
2771
+ let glasses = glassesStatus
2772
+ let now = BluetoothSdkAnalytics.epochMillis()
2773
+ analytics.recordUsage {
2774
+ $0.otaStatus(
2775
+ sessionId: event.sessionId,
2776
+ status: event.status,
2777
+ stepType: event.stepType,
2778
+ totalSteps: event.totalSteps,
2779
+ errorMessage: event.errorMessage,
2780
+ fromBuildNumber: glasses.buildNumber,
2781
+ fromBesFirmwareVersion: glasses.besFirmwareVersion,
2782
+ fromMtkFirmwareVersion: glasses.mtkFirmwareVersion,
2783
+ nowMs: now
2784
+ )
2785
+ }
2786
+ }
2535
2787
  delegate?.mentraBluetoothSDK(self, didReceive: .otaStatus(event))
2536
2788
  case "settings_ack":
2537
2789
  let event = SettingsAckEvent(values: data)