@mentra/bluetooth-sdk 3.2.1-dev.314 → 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 (199) hide show
  1. package/README.md +103 -10
  2. package/android/build.gradle +15 -0
  3. package/android/lc3Lib/build.gradle +6 -1
  4. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +368 -0
  5. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +156 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +4 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +12 -2
  11. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +2 -1
  14. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +138 -26
  15. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +37 -13
  16. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
  17. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  18. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +235 -36
  19. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulator.kt +13 -2
  23. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/requests/DisplayRequests.kt +1 -1
  25. package/android/src/main/java/com/mentra/bluetoothsdk/services/Foreground.kt +33 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/services/G2ConnectionRecovery.kt +47 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1.kt +2 -2
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G2.kt +72 -21
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +261 -42
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraNex.kt +12 -8
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +314 -395
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +247 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +238 -0
  38. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +58 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +180 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +11 -0
  41. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddress.kt +17 -0
  42. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SerializedGattCallback.kt +5 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/utils/G2Text.kt +7 -0
  44. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +20 -0
  45. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
  46. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
  47. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
  48. package/android/src/test/java/com/mentra/bluetoothsdk/DashboardContentFormatterTest.kt +2 -2
  49. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceIdentityPairingTest.kt +59 -0
  50. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerSceneHandoffTest.kt +666 -0
  51. package/android/src/test/java/com/mentra/bluetoothsdk/G2TextTest.kt +13 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
  54. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulatorTest.kt +71 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/services/G2ConnectionRecoveryTest.kt +51 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1PairingTest.kt +105 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
  61. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2DisplayThreadTest.kt +120 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2PairingTargetTest.kt +90 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveFileTransferSessionTest.kt +55 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGattCallbackTest.kt +33 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingTargetTest.kt +65 -0
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraNexPairingTest.kt +151 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoBitmapAcceptanceTest.kt +105 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +233 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +348 -0
  74. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +339 -0
  75. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoMicReconnectTest.kt +93 -0
  76. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoProtocolTest.kt +11 -0
  77. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddressTest.kt +27 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +287 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +127 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +288 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +205 -0
  82. package/build/BluetoothSdk.types.d.ts +22 -1
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js +1 -0
  85. package/build/BluetoothSdk.types.js.map +1 -1
  86. package/build/_private/BluetoothSdkModule.d.ts +6 -1
  87. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  88. package/build/_private/BluetoothSdkModule.js +5 -1
  89. package/build/_private/BluetoothSdkModule.js.map +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
  91. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  92. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  93. package/build/_private/nativeLogConsole.d.ts +19 -0
  94. package/build/_private/nativeLogConsole.d.ts.map +1 -1
  95. package/build/_private/nativeLogConsole.js +12 -0
  96. package/build/_private/nativeLogConsole.js.map +1 -1
  97. package/build/generated/changelogCatalog.d.ts +5 -2
  98. package/build/generated/changelogCatalog.d.ts.map +1 -1
  99. package/build/generated/changelogCatalog.js +6 -2
  100. package/build/generated/changelogCatalog.js.map +1 -1
  101. package/build/generated/releaseMetadata.js +6 -6
  102. package/build/generated/releaseMetadata.js.map +1 -1
  103. package/build/index.d.ts +1 -1
  104. package/build/index.d.ts.map +1 -1
  105. package/build/index.js +2 -0
  106. package/build/index.js.map +1 -1
  107. package/build/ota-transport/index.d.ts +4 -0
  108. package/build/ota-transport/index.d.ts.map +1 -1
  109. package/build/ota-transport/index.js +2 -0
  110. package/build/ota-transport/index.js.map +1 -1
  111. package/ios/BluetoothSdkModule.swift +25 -4
  112. package/ios/MentraBluetoothSDK.podspec +3 -2
  113. package/ios/Source/BluetoothBackgroundMode.swift +32 -0
  114. package/ios/Source/BluetoothSdkDefaults.swift +7 -2
  115. package/ios/Source/Bridge.swift +15 -2
  116. package/ios/Source/DeviceManager.swift +106 -66
  117. package/ios/Source/DeviceStore.swift +26 -7
  118. package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
  119. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  120. package/ios/Source/MentraBluetoothSDK.swift +324 -54
  121. package/ios/Source/TouchGesture.swift +13 -0
  122. package/ios/Source/audio/GlassesMicWatchdog.swift +33 -0
  123. package/ios/Source/events/BluetoothEvents.swift +4 -0
  124. package/ios/Source/internal/BluetoothAvailability.swift +6 -0
  125. package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
  126. package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
  127. package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
  128. package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
  129. package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
  130. package/ios/Source/requests/DisplayRequests.swift +1 -1
  131. package/ios/Source/requests/VersionInfoResponseAccumulator.swift +11 -1
  132. package/ios/Source/sgcs/Ar99.swift +1 -2
  133. package/ios/Source/sgcs/G1.swift +68 -38
  134. package/ios/Source/sgcs/G1ConnectionTarget.swift +13 -0
  135. package/ios/Source/sgcs/G2.swift +261 -247
  136. package/ios/Source/sgcs/G2ConnectionSession.swift +101 -0
  137. package/ios/Source/sgcs/Mach1.swift +19 -7
  138. package/ios/Source/sgcs/MentraLive.swift +368 -220
  139. package/ios/Source/sgcs/MentraLiveFileTransferSession.swift +137 -0
  140. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +47 -0
  141. package/ios/Source/sgcs/MentraNex.swift +8 -31
  142. package/ios/Source/sgcs/NexConnectionTarget.swift +15 -0
  143. package/ios/Source/sgcs/Nimo.swift +280 -408
  144. package/ios/Source/sgcs/NimoCanvasCodec.swift +272 -0
  145. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +233 -0
  146. package/ios/Source/sgcs/NimoCanvasImage.swift +53 -0
  147. package/ios/Source/sgcs/NimoCanvasSession.swift +166 -0
  148. package/ios/Source/sgcs/NimoDiscovery.swift +49 -0
  149. package/ios/Source/sgcs/SGCManager.swift +25 -1
  150. package/ios/Source/sgcs/VuzixConnectionTarget.swift +15 -0
  151. package/ios/Source/status/DeviceStatus.swift +1 -0
  152. package/ios/Source/stt/SherpaOnnxTranscriber.swift +49 -189
  153. package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
  154. package/ios/Source/utils/DemandDrivenAudioWorker.swift +150 -0
  155. package/ios/Source/utils/G1Text.swift +2 -24
  156. package/ios/Source/utils/G1TextSanitizer.swift +27 -0
  157. package/ios/Source/utils/G2Text.swift +11 -0
  158. package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
  159. package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
  160. package/ios/Tests/BluetoothBackgroundModeTests.swift +32 -0
  161. package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
  162. package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
  163. package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
  164. package/ios/Tests/DashboardContentFormatterTests.swift +2 -2
  165. package/ios/Tests/DashboardRenderingTests.swift +31 -0
  166. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +157 -0
  167. package/ios/Tests/DeviceIdentityPairingTests.swift +49 -0
  168. package/ios/Tests/DeviceManagerReconnectTests.swift +362 -0
  169. package/ios/Tests/G1PairingTests.swift +162 -0
  170. package/ios/Tests/G1TextSanitizerTests.swift +32 -0
  171. package/ios/Tests/G2ConnectionSessionTests.swift +172 -0
  172. package/ios/Tests/G2TextTests.swift +10 -0
  173. package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
  174. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  175. package/ios/Tests/MentraLiveFileTransferSessionTests.swift +47 -0
  176. package/ios/Tests/MentraLiveReconnectPolicyTests.swift +58 -0
  177. package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
  178. package/ios/Tests/NimoCanvasCodecTests.swift +217 -0
  179. package/ios/Tests/NimoCanvasSessionTests.swift +181 -0
  180. package/ios/Tests/NimoCanvasTransportTests.swift +186 -0
  181. package/ios/Tests/NimoDeviceCommandsTests.swift +16 -0
  182. package/ios/Tests/NimoDiscoveryTests.swift +79 -0
  183. package/ios/Tests/SGCConnectionTargetTests.swift +48 -0
  184. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  185. package/ios/Tests/VersionInfoCommandTests.swift +194 -0
  186. package/ios/Tests/VersionInfoResponseAccumulatorTests.swift +65 -0
  187. package/ios/Tests/VideoRecordingCommandTests.swift +81 -0
  188. package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
  189. package/package.json +2 -2
  190. package/plugin/build/withIos.d.ts +2 -0
  191. package/plugin/build/withIos.js +12 -1
  192. package/src/BluetoothSdk.types.ts +30 -0
  193. package/src/_private/BluetoothSdkModule.ts +12 -1
  194. package/src/_private/MentraLocalNetworkModule.ts +28 -0
  195. package/src/_private/nativeLogConsole.ts +19 -0
  196. package/src/generated/changelogCatalog.ts +6 -2
  197. package/src/generated/releaseMetadata.ts +6 -6
  198. package/src/index.ts +3 -0
  199. 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] = [:]
@@ -299,8 +311,22 @@ public final class MentraBluetoothSDK {
299
311
  private let wifiSessionCapabilities = WifiSessionCapabilities()
300
312
  private var configuredOtaVersionUrl: String?
301
313
 
314
+ /// Whether the app declares the `bluetooth-central` background mode. When false on iOS, the
315
+ /// glasses stay disconnected after a link drop until the user opens the app, so a software
316
+ /// update started on a locked phone stalls. Always true on macOS.
317
+ public static var supportsBackgroundReconnect: Bool {
318
+ BluetoothBackgroundMode.isDeclared(in: Bundle.main.infoDictionary)
319
+ }
320
+
321
+ private static var didWarnMissingBackgroundMode = false
322
+
302
323
  public init(configuration: MentraBluetoothSDKConfiguration = .default) {
303
324
  self.configuration = configuration
325
+ // Once per process: apps may create the SDK more than once.
326
+ if !Self.didWarnMissingBackgroundMode, !Self.supportsBackgroundReconnect {
327
+ Self.didWarnMissingBackgroundMode = true
328
+ Bridge.log(BluetoothBackgroundMode.missingWarning)
329
+ }
304
330
  analytics = BluetoothSdkAnalytics(configuration: configuration.analytics)
305
331
  bluetoothAvailabilityListenerId = BluetoothAvailability.shared.addStateListener { [weak self] state in
306
332
  Task { @MainActor [weak self] in
@@ -336,6 +362,31 @@ public final class MentraBluetoothSDK {
336
362
  }
337
363
  analytics.initializeGlassesStatus(glassesStatus)
338
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
+ }
339
390
  }
340
391
 
341
392
  public var state: MentraBluetoothState {
@@ -531,6 +582,7 @@ public final class MentraBluetoothSDK {
531
582
  }
532
583
 
533
584
  public func cancelConnectionAttempt() {
585
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectCancel)
534
586
  clearBluetoothRestoreIntent()
535
587
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_name", "")
536
588
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_address", "")
@@ -544,6 +596,7 @@ public final class MentraBluetoothSDK {
544
596
  }
545
597
 
546
598
  public func disconnect() {
599
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectUser)
547
600
  clearBluetoothRestoreIntent()
548
601
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_name", "")
549
602
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "pending_device_address", "")
@@ -552,6 +605,7 @@ public final class MentraBluetoothSDK {
552
605
  }
553
606
 
554
607
  public func forget() {
608
+ analytics.noteDisconnectRequested(BluetoothSdkAnalyticsTracker.disconnectForget)
555
609
  clearBluetoothRestoreIntent()
556
610
  DeviceManager.shared.forget()
557
611
  }
@@ -650,6 +704,17 @@ public final class MentraBluetoothSDK {
650
704
  )
651
705
  }
652
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
+
653
718
  public func setGalleryModeEnabled(_ enabled: Bool) async throws -> SettingsAckEvent {
654
719
  try await performSettingsCommand(
655
720
  setting: "gallery_mode",
@@ -664,7 +729,7 @@ public final class MentraBluetoothSDK {
664
729
  send: (String) throws -> Void
665
730
  ) async throws -> SettingsAckEvent {
666
731
  let requestId = "settings-\(setting)-\(UUID().uuidString)"
667
- let pending = PendingResponse<SettingsAckEvent>(operation: "set \(setting)")
732
+ let pending = PendingResponse<SettingsAckEvent>(operation: "set \(setting)", onTimeout: requestTimeoutReporter)
668
733
  pendingSettingsRequests[requestId] = pending
669
734
  do {
670
735
  try send(requestId)
@@ -688,6 +753,10 @@ public final class MentraBluetoothSDK {
688
753
  DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "loudness_gate_enabled", enabled)
689
754
  }
690
755
 
756
+ public func setAutoPowerOffEnabled(_ enabled: Bool) async throws {
757
+ DeviceStore.shared.apply(ObservableStore.bluetoothCategory, "auto_power_off_enabled", enabled)
758
+ }
759
+
691
760
  @available(*, deprecated, message: "Sticky action-button photo presets are deprecated. Prefer per-request requestPhoto(...) options (e.g. mode .text for text sensor size/crop, or explicit per-shot fields). This method still works but will be removed in a future release.")
692
761
  public func setPhotoCaptureDefaults(_ settings: PhotoCaptureDefaults) async throws -> SettingsAckEvent {
693
762
  try await performSettingsCommand(
@@ -933,7 +1002,7 @@ public final class MentraBluetoothSDK {
933
1002
  // the scan screen auto-starts a scan on mount and can be pushed twice.
934
1003
  return try await existing.value
935
1004
  }
936
- let pending = PendingResponse<[WifiScanResult]>(operation: "WiFi scan request")
1005
+ let pending = PendingResponse<[WifiScanResult]>(operation: "WiFi scan request", onTimeout: requestTimeoutReporter)
937
1006
  let request = PendingWifiScan(pending: pending, scanId: "scan-\(UUID().uuidString)")
938
1007
  pendingWifiScan = request
939
1008
  // Claim the scan-results store for this scan before the command goes out,
@@ -973,11 +1042,15 @@ public final class MentraBluetoothSDK {
973
1042
  message: "A WiFi status command is already waiting for a glasses response."
974
1043
  )
975
1044
  }
976
- let pending = PendingResponse<WifiStatusEvent>(operation: "WiFi connect request")
1045
+ let pending = PendingResponse<WifiStatusEvent>(operation: "WiFi connect request", onTimeout: requestTimeoutReporter)
977
1046
  pendingWifiStatus = PendingWifiStatusRequest(ssid: ssid, pending: pending)
978
- DeviceManager.shared.sendWifiCredentials(ssid, password)
979
1047
  do {
980
- 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
+ }
981
1054
  if pendingWifiStatus?.pending === pending {
982
1055
  pendingWifiStatus = nil
983
1056
  }
@@ -1000,7 +1073,7 @@ public final class MentraBluetoothSDK {
1000
1073
  message: "A WiFi status command is already waiting for a glasses response."
1001
1074
  )
1002
1075
  }
1003
- let pending = PendingResponse<WifiForgetResult>(operation: "WiFi forget request")
1076
+ let pending = PendingResponse<WifiForgetResult>(operation: "WiFi forget request", onTimeout: requestTimeoutReporter)
1004
1077
  let requestId = "forget-\(UUID().uuidString)"
1005
1078
  let request = PendingWifiForgetRequest(
1006
1079
  ssid: ssid,
@@ -1045,7 +1118,7 @@ public final class MentraBluetoothSDK {
1045
1118
  error: "saved_wifi_networks_unsupported"
1046
1119
  )
1047
1120
  }
1048
- let pending = PendingResponse<SavedWifiNetworksResult>(operation: "Saved WiFi networks request")
1121
+ let pending = PendingResponse<SavedWifiNetworksResult>(operation: "Saved WiFi networks request", onTimeout: requestTimeoutReporter)
1049
1122
  let request = PendingSavedWifiNetworks(
1050
1123
  requestId: requestId,
1051
1124
  sid: wifiSessionCapabilities.sessionId,
@@ -1082,12 +1155,18 @@ public final class MentraBluetoothSDK {
1082
1155
  _ = try? await previous.value
1083
1156
  }
1084
1157
  let pending = PendingResponse<HotspotStatusEvent>(
1085
- operation: "hotspot \(enabled ? "enable" : "disable") request"
1158
+ operation: "hotspot \(enabled ? "enable" : "disable") request",
1159
+ onTimeout: self.requestTimeoutReporter
1086
1160
  )
1087
1161
  self.pendingHotspotStatus = PendingHotspotStatusRequest(enabled: enabled, pending: pending)
1088
- DeviceManager.shared.setHotspotState(enabled)
1089
1162
  do {
1090
- 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
+ }
1091
1170
  if self.pendingHotspotStatus?.pending === pending {
1092
1171
  self.pendingHotspotStatus = nil
1093
1172
  }
@@ -1120,13 +1199,30 @@ public final class MentraBluetoothSDK {
1120
1199
  Bridge.log(
1121
1200
  "NATIVE: PHOTO PIPELINE [3b/6] MentraBluetoothSdk.requestPhoto requestId=\(routedRequest.requestId)"
1122
1201
  )
1123
- let pending = PendingResponse<PhotoResponseEvent>(operation: "photo request \(routedRequest.requestId)")
1202
+ let pending = PendingResponse<PhotoResponseEvent>(operation: "photo request \(routedRequest.requestId)", telemetryOperation: "photo request", onTimeout: requestTimeoutReporter)
1124
1203
  pendingPhotoRequests[routedRequest.requestId] = pending
1125
- DeviceManager.shared.requestPhoto(routedRequest)
1126
1204
  do {
1127
- let event = try await pending.wait(timeoutMs: routedRequest.presendThumbnail
1128
- ? MentraBluetoothSDK.photoThumbnailRequestTimeoutMs
1129
- : 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
+ }
1130
1226
  pendingPhotoRequests.removeValue(forKey: routedRequest.requestId)
1131
1227
  return event
1132
1228
  } catch {
@@ -1145,7 +1241,7 @@ public final class MentraBluetoothSDK {
1145
1241
  mfnr: Bool? = nil
1146
1242
  ) async throws -> CameraStatusEvent {
1147
1243
  let effectiveRequestId = nonBlankRequestId(requestId) ?? generatedCameraRequestId("warm")
1148
- 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)
1149
1245
  pendingCameraStatusRequests[effectiveRequestId] = pending
1150
1246
  do {
1151
1247
  // Inside the catch so an unsupported-device throw also clears the pending entry.
@@ -1183,7 +1279,7 @@ public final class MentraBluetoothSDK {
1183
1279
  message: "A gallery status query is already waiting for a glasses response."
1184
1280
  )
1185
1281
  }
1186
- let pending = PendingResponse<GalleryStatusEvent>(operation: "gallery status query")
1282
+ let pending = PendingResponse<GalleryStatusEvent>(operation: "gallery status query", onTimeout: requestTimeoutReporter)
1187
1283
  pendingGalleryStatus = pending
1188
1284
  DeviceManager.shared.queryGalleryStatus()
1189
1285
  do {
@@ -1201,33 +1297,53 @@ public final class MentraBluetoothSDK {
1201
1297
  }
1202
1298
 
1203
1299
  public func startStream(_ request: StreamRequest) async throws -> StreamStatusEvent {
1204
- try requireGlassesConnected(operation: "start stream")
1205
- guard streamSession.supported else {
1206
- throw BluetoothSdkError(code: "stream_control_unsupported", message: "Update the glasses software before starting a stream.")
1207
- }
1208
1300
  var values = request.values
1209
1301
  let streamId = stringValue(values, "streamId").flatMap { $0.isEmpty ? nil : $0 } ?? "sdk-\(UUID().uuidString)"
1210
1302
  values["streamId"] = streamId
1211
- let pending = PendingResponse<StreamStatusEvent>(operation: "start stream \(streamId)")
1212
- // seq assignment through the BLE hand-off must stay await-free so this
1213
- // MainActor turn is one critical section: rejectPreemptedStreamStarts
1214
- // only works if seq order equals the order the commands reach the
1215
- // glasses' FIFO.
1216
- streamStartSeq += 1
1217
- pendingStreamStarts[streamId] = PendingStreamStart(seq: streamStartSeq, pending: pending)
1218
- DeviceManager.shared.startStream(values)
1219
- do {
1220
- let event = try await pending.wait(timeoutMs: 30000)
1221
- pendingStreamStarts.removeValue(forKey: streamId)
1222
- return event
1223
- } catch {
1224
- pendingStreamStarts.removeValue(forKey: streamId)
1225
- 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
+ }
1226
1342
  }
1227
1343
  }
1228
1344
 
1229
1345
  public func rgbLedControl(_ request: RgbLedRequest) async throws -> RgbLedControlResponseEvent {
1230
- 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)
1231
1347
  pendingRgbLedRequests[request.requestId] = pending
1232
1348
  DeviceManager.shared.rgbLedControl(
1233
1349
  requestId: request.requestId,
@@ -1249,13 +1365,14 @@ public final class MentraBluetoothSDK {
1249
1365
  }
1250
1366
 
1251
1367
  public func stopStream() async throws -> StreamStatusEvent {
1368
+ analytics.updateUsage { $0.streamStopRequested() }
1252
1369
  guard pendingStreamStop == nil else {
1253
1370
  throw BluetoothSdkError(
1254
1371
  code: "request_in_flight",
1255
1372
  message: "A stream stop command is already waiting for a glasses response."
1256
1373
  )
1257
1374
  }
1258
- let pending = PendingResponse<StreamStatusEvent>(operation: "stop stream")
1375
+ let pending = PendingResponse<StreamStatusEvent>(operation: "stop stream", onTimeout: requestTimeoutReporter)
1259
1376
  // The seq draw and the BLE hand-off stay in this single await-free
1260
1377
  // MainActor turn, sharing startStream's ordering critical section:
1261
1378
  // the stop takes its own slot in the send order, so its ack can
@@ -1284,7 +1401,9 @@ public final class MentraBluetoothSDK {
1284
1401
  }
1285
1402
  try requireGlassesConnected(operation: "start video recording")
1286
1403
  let pending = PendingResponse<VideoRecordingStatusEvent>(
1287
- operation: "start video recording \(request.requestId)"
1404
+ operation: "start video recording \(request.requestId)",
1405
+ telemetryOperation: "start video recording",
1406
+ onTimeout: requestTimeoutReporter
1288
1407
  )
1289
1408
  guard pendingVideoRecordingRequests[request.requestId] == nil else {
1290
1409
  throw BluetoothSdkError(
@@ -1296,6 +1415,16 @@ public final class MentraBluetoothSDK {
1296
1415
  expectedStatus: "recording_started",
1297
1416
  pending: pending
1298
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
+ }
1299
1428
  DeviceManager.shared.startVideoRecording(
1300
1429
  request.requestId,
1301
1430
  request.save,
@@ -1322,7 +1451,7 @@ public final class MentraBluetoothSDK {
1322
1451
  throw BluetoothSdkError(code: "missing_request_id", message: "requestId is required to stop video recording.")
1323
1452
  }
1324
1453
  try requireGlassesConnected(operation: "stop video recording")
1325
- 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)
1326
1455
  guard pendingVideoRecordingRequests[requestId] == nil else {
1327
1456
  throw BluetoothSdkError(
1328
1457
  code: "request_in_flight",
@@ -1335,6 +1464,7 @@ public final class MentraBluetoothSDK {
1335
1464
  pending: pending,
1336
1465
  waitForUpload: waitForUpload
1337
1466
  )
1467
+ analytics.updateUsage { $0.videoStopRequested(requestId: requestId) }
1338
1468
  DeviceManager.shared.stopVideoRecording(requestId, webhookUrl, authToken)
1339
1469
  do {
1340
1470
  let timeoutMs = waitForUpload ? videoUploadStopTimeoutMs : 15000
@@ -1355,7 +1485,7 @@ public final class MentraBluetoothSDK {
1355
1485
  )
1356
1486
  }
1357
1487
  try requireGlassesConnected(operation: "query video recording status")
1358
- 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)
1359
1489
  guard pendingVideoRecordingRequests[requestId] == nil else {
1360
1490
  throw BluetoothSdkError(
1361
1491
  code: "request_in_flight",
@@ -1378,27 +1508,35 @@ public final class MentraBluetoothSDK {
1378
1508
  }
1379
1509
 
1380
1510
  public func requestVersionInfo() async throws -> VersionInfoResult {
1381
- guard pendingVersionInfo == nil else {
1511
+ if let request = pendingVersionInfo {
1512
+ logVersionInfoRequest(request, stage: "refused", extra: ["code": "request_in_flight"])
1382
1513
  throw BluetoothSdkError(
1383
1514
  code: "request_in_flight",
1384
1515
  message: "A version info request is already waiting for a glasses response."
1385
1516
  )
1386
1517
  }
1387
1518
  let requestId = UUID().uuidString
1388
- let pending = PendingResponse<VersionInfoResult>(operation: "version info request")
1519
+ let pending = PendingResponse<VersionInfoResult>(operation: "version info request", onTimeout: requestTimeoutReporter)
1389
1520
  let request = PendingVersionInfoRequest(pending: pending, requestId: requestId)
1390
1521
  pendingVersionInfo = request
1522
+ logVersionInfoRequest(request, stage: "registered")
1391
1523
  DeviceManager.shared.requestVersionInfo(requestId: requestId)
1392
1524
  do {
1393
1525
  let status = try await pending.wait()
1394
1526
  if pendingVersionInfo === request {
1395
1527
  pendingVersionInfo = nil
1396
1528
  }
1529
+ logVersionInfoRequest(request, stage: "resolved")
1397
1530
  return status
1398
1531
  } catch {
1399
1532
  if pendingVersionInfo === request {
1400
1533
  pendingVersionInfo = nil
1401
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
+ ])
1402
1540
  throw error
1403
1541
  }
1404
1542
  }
@@ -1476,7 +1614,7 @@ public final class MentraBluetoothSDK {
1476
1614
  message: "An OTA status query is already waiting for a glasses response."
1477
1615
  )
1478
1616
  }
1479
- let pending = PendingResponse<OtaQueryResult>(operation: operation)
1617
+ let pending = PendingResponse<OtaQueryResult>(operation: operation, onTimeout: requestTimeoutReporter)
1480
1618
  pendingOtaQuery = pending
1481
1619
  sendRequest()
1482
1620
  do {
@@ -1507,7 +1645,7 @@ public final class MentraBluetoothSDK {
1507
1645
  message: "An OTA start command is already waiting for a glasses response."
1508
1646
  )
1509
1647
  }
1510
- let pending = PendingResponse<OtaStartAckEvent>(operation: "OTA start command")
1648
+ let pending = PendingResponse<OtaStartAckEvent>(operation: "OTA start command", onTimeout: requestTimeoutReporter)
1511
1649
  pendingOtaStart = pending
1512
1650
  DeviceManager.shared.sendOtaStart(otaVersionUrl: otaVersionUrl)
1513
1651
  do {
@@ -1638,8 +1776,8 @@ public final class MentraBluetoothSDK {
1638
1776
  DeviceManager.shared.sendReboot()
1639
1777
  }
1640
1778
 
1641
- func sendIncidentId(_ incidentId: String, apiBaseUrl: String? = nil) {
1642
- DeviceManager.shared.sendIncidentId(incidentId, apiBaseUrl: apiBaseUrl)
1779
+ func sendIncidentId(_ incidentId: String, apiBaseUrl: String? = nil) throws {
1780
+ try DeviceManager.shared.sendIncidentId(incidentId, apiBaseUrl: apiBaseUrl)
1643
1781
  }
1644
1782
 
1645
1783
  public func invalidate() {
@@ -1656,6 +1794,7 @@ public final class MentraBluetoothSDK {
1656
1794
  DeviceStore.shared.store.removeListener(storeListenerId)
1657
1795
  self.storeListenerId = nil
1658
1796
  }
1797
+ updateCheck?.stop()
1659
1798
  delegate = nil
1660
1799
  }
1661
1800
 
@@ -2249,17 +2388,90 @@ public final class MentraBluetoothSDK {
2249
2388
  )
2250
2389
  }
2251
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
+
2252
2456
  private func dispatchStoreUpdate(_ category: String, _ changes: [String: Any]) {
2253
2457
  switch ObservableStore.normalizeCategory(category) {
2254
2458
  case "glasses":
2255
2459
  if changes["connected"] as? Bool == false {
2256
2460
  resetWifiProtocolSession(sessionId: "", code: "wifi_session_disconnected")
2257
2461
  }
2258
- 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 }
2259
2465
  let nextState = state
2260
2466
  delegate?.mentraBluetoothSDK(self, didUpdate: nextState)
2261
2467
  delegate?.mentraBluetoothSDK(self, didUpdateGlasses: nextState.glasses)
2262
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
+ }
2263
2475
  let nextState = state
2264
2476
  delegate?.mentraBluetoothSDK(self, didUpdate: nextState)
2265
2477
  delegate?.mentraBluetoothSDK(self, didUpdateSdkState: nextState.sdk)
@@ -2361,17 +2573,48 @@ public final class MentraBluetoothSDK {
2361
2573
 
2362
2574
  private func handleVersionInfoForRequest(_ data: [String: Any]) {
2363
2575
  guard let request = pendingVersionInfo else { return }
2364
- 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 {
2365
2597
  case .ignored:
2366
- break
2598
+ logVersionInfoRequest(request, stage: "response-ignored", extra: response)
2367
2599
  case .waiting:
2368
- break
2600
+ logVersionInfoRequest(request, stage: "response-waiting", extra: response)
2369
2601
  case let .complete(result):
2602
+ logVersionInfoRequest(request, stage: "response-complete", extra: response)
2370
2603
  pendingVersionInfo = nil
2371
2604
  request.pending.resolve(result)
2372
2605
  }
2373
2606
  }
2374
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
+
2375
2618
  private func dispatchBridgeEvent(_ eventName: String, _ data: [String: Any]) {
2376
2619
  switch eventName {
2377
2620
  case "log":
@@ -2469,6 +2712,11 @@ public final class MentraBluetoothSDK {
2469
2712
  case "photo_response":
2470
2713
  let event = PhotoResponseEvent(values: data)
2471
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
+ }
2472
2720
  delegate?.mentraBluetoothSDK(self, didReceive: .photoResponse(event))
2473
2721
  case "photo_status":
2474
2722
  delegate?.mentraBluetoothSDK(self, didReceive: .photoStatus(PhotoStatusEvent(values: data)))
@@ -2479,6 +2727,10 @@ public final class MentraBluetoothSDK {
2479
2727
  case "video_recording_status":
2480
2728
  let event = VideoRecordingStatusEvent(values: data)
2481
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
+ }
2482
2734
  delegate?.mentraBluetoothSDK(self, didReceive: .videoRecordingStatus(event))
2483
2735
  case "media_success", "media_error":
2484
2736
  let event = MediaUploadEvent(values: data)
@@ -2494,6 +2746,7 @@ public final class MentraBluetoothSDK {
2494
2746
  if data["revision"] != nil && !streamSession.accept(data) { return }
2495
2747
  let event = StreamStatusEvent(values: data)
2496
2748
  handleStreamStatusForRequests(event)
2749
+ recordStreamStatus(event)
2497
2750
  delegate?.mentraBluetoothSDK(self, didReceive: .streamStatus(event))
2498
2751
  case "keep_alive_ack":
2499
2752
  let event = KeepAliveAckEvent(values: data)
@@ -2514,6 +2767,23 @@ public final class MentraBluetoothSDK {
2514
2767
  BluetoothSdkError(code: errorCode, message: "Glasses rejected OTA start: \(errorCode)")
2515
2768
  )
2516
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
+ }
2517
2787
  delegate?.mentraBluetoothSDK(self, didReceive: .otaStatus(event))
2518
2788
  case "settings_ack":
2519
2789
  let event = SettingsAckEvent(values: data)