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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +99 -6
  2. package/android/build.gradle +15 -0
  3. package/android/lc3Lib/build.gradle +6 -1
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +1 -1
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +6 -2
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
  10. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +9 -1
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +231 -36
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +160 -20
  24. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +3 -1
  25. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
  26. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
  30. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +20 -7
  39. package/build/BluetoothSdk.types.d.ts +9 -1
  40. package/build/BluetoothSdk.types.d.ts.map +1 -1
  41. package/build/BluetoothSdk.types.js.map +1 -1
  42. package/build/_private/BluetoothSdkModule.d.ts +2 -1
  43. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  44. package/build/_private/BluetoothSdkModule.js +2 -1
  45. package/build/_private/BluetoothSdkModule.js.map +1 -1
  46. package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
  47. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  48. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  49. package/build/_private/nativeLogConsole.d.ts +19 -0
  50. package/build/_private/nativeLogConsole.d.ts.map +1 -1
  51. package/build/_private/nativeLogConsole.js +12 -0
  52. package/build/_private/nativeLogConsole.js.map +1 -1
  53. package/build/generated/changelogCatalog.d.ts +4 -1
  54. package/build/generated/changelogCatalog.d.ts.map +1 -1
  55. package/build/generated/changelogCatalog.js +5 -1
  56. package/build/generated/changelogCatalog.js.map +1 -1
  57. package/build/generated/releaseMetadata.js +6 -6
  58. package/build/generated/releaseMetadata.js.map +1 -1
  59. package/build/index.d.ts +1 -1
  60. package/build/index.d.ts.map +1 -1
  61. package/build/index.js +1 -0
  62. package/build/index.js.map +1 -1
  63. package/build/ota-transport/index.d.ts +4 -0
  64. package/build/ota-transport/index.d.ts.map +1 -1
  65. package/build/ota-transport/index.js +2 -0
  66. package/build/ota-transport/index.js.map +1 -1
  67. package/ios/BluetoothSdkModule.swift +16 -4
  68. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  69. package/ios/Source/DeviceManager.swift +10 -3
  70. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  71. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  72. package/ios/Source/MentraBluetoothSDK.swift +306 -54
  73. package/ios/Source/TouchGesture.swift +13 -0
  74. package/ios/Source/events/BluetoothEvents.swift +4 -0
  75. package/ios/Source/internal/BluetoothAvailability.swift +6 -0
  76. package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
  77. package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
  78. package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
  79. package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
  80. package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
  81. package/ios/Source/sgcs/MentraLive.swift +167 -64
  82. package/ios/Source/sgcs/NimoCanvasCodec.swift +4 -1
  83. package/ios/Source/sgcs/SGCManager.swift +1 -1
  84. package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
  85. package/ios/Source/utils/G1Text.swift +2 -24
  86. package/ios/Source/utils/G1TextSanitizer.swift +27 -0
  87. package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
  88. package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
  89. package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
  90. package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
  91. package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
  92. package/ios/Tests/G1TextSanitizerTests.swift +32 -0
  93. package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
  94. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  95. package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
  96. package/ios/Tests/NimoCanvasCodecTests.swift +17 -4
  97. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  98. package/ios/Tests/VersionInfoCommandTests.swift +142 -1
  99. package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
  100. package/package.json +2 -2
  101. package/src/BluetoothSdk.types.ts +16 -0
  102. package/src/_private/BluetoothSdkModule.ts +4 -1
  103. package/src/_private/MentraLocalNetworkModule.ts +28 -0
  104. package/src/_private/nativeLogConsole.ts +19 -0
  105. package/src/generated/changelogCatalog.ts +5 -1
  106. package/src/generated/releaseMetadata.ts +6 -6
  107. package/src/index.ts +2 -0
  108. package/src/ota-transport/index.ts +10 -1
@@ -923,7 +923,7 @@ extension MentraLive: CBCentralManagerDelegate {
923
923
  self.isConnecting = false
924
924
 
925
925
  self.connectedPeripheral = nil
926
- self.fullyBooted = false
926
+ self.clearPhysicalReadiness()
927
927
  self.connected = false
928
928
  self.glassesSessionId = nil // Fresh BLE session starts with no sid known
929
929
  self.streamControlVersion = 0
@@ -1345,11 +1345,12 @@ class MentraLive: NSObject, SGCManager {
1345
1345
  if state == ConnTypes.DISCONNECTED {
1346
1346
  resetPendingAckState(reason: "BLE session ended")
1347
1347
  resetWireNegotiationState()
1348
+ resetReadinessExchange()
1348
1349
  resetAncsRelayState()
1349
1350
  // Queued writes are session-bound: transmitting them into the NEXT session
1350
1351
  // (e.g. a stale handshake whose reply activates v2 before the new session
1351
1352
  // negotiated) is the bug class this clear removes.
1352
- Task { await commandQueue.removeAll() }
1353
+ commandQueue.removeAll()
1353
1354
  stopSignalStrengthPolling()
1354
1355
  DeviceStore.shared.apply("glasses", "signalStrength", -1)
1355
1356
  DeviceStore.shared.apply("glasses", "signalStrengthUpdatedAt", 0)
@@ -1603,6 +1604,13 @@ class MentraLive: NSObject, SGCManager {
1603
1604
  // the physical connection — so a first-seen sid after an upgrade OTA cannot be
1604
1605
  // mistaken for a fresh pairing just because a not-ready heartbeat slipped in first.
1605
1606
  private var readinessCompletedThisBleSession = false
1607
+ /// Readiness exchange the phone is waiting on. Every phone_ready carries it until the
1608
+ /// matching glasses_ready arrives, so retries and the copies the BES buffers while the
1609
+ /// glasses boot are one exchange: the glasses reset their transport once for it and answer
1610
+ /// later copies without resetting. Both exchange fields are scoped to the BLE session.
1611
+ private var pendingReadyId: String?
1612
+ /// `sid` of the glasses process whose glasses_ready this BLE session last handled.
1613
+ private var readyGlassesSessionId: String?
1606
1614
  private var globalMessageId = 0
1607
1615
  private var lastReceivedMessageId = 0
1608
1616
  private var bleWriteTraceSequence = 0
@@ -1617,6 +1625,16 @@ class MentraLive: NSObject, SGCManager {
1617
1625
  set { DeviceStore.shared.apply("glasses", "connected", newValue) }
1618
1626
  }
1619
1627
 
1628
+ private func clearPhysicalReadiness() {
1629
+ let readinessWasPending = connected && !fullyBooted
1630
+ fullyBooted = false
1631
+ if readinessWasPending {
1632
+ // Logical ASG readiness already emitted false without disconnecting.
1633
+ // The real disconnect must still perform the cleanup apply deduplicates.
1634
+ DeviceManager.shared.handleDeviceDisconnected()
1635
+ }
1636
+ }
1637
+
1620
1638
  // Queue Management
1621
1639
  private let commandQueue = CommandQueue()
1622
1640
  private let bluetoothQueue = DispatchQueue(label: "MentraLiveBluetooth", qos: .userInitiated)
@@ -1744,8 +1762,8 @@ class MentraLive: NSObject, SGCManager {
1744
1762
  // Publish disconnect immediately for Phone A UI. didDisconnectPeripheral may lag
1745
1763
  // or race with cancelPeripheralConnection; do not wait on it for stand-down.
1746
1764
  isConnecting = false
1765
+ clearPhysicalReadiness()
1747
1766
  connected = false
1748
- fullyBooted = false
1749
1767
  glassesSessionId = nil
1750
1768
  streamControlVersion = 0
1751
1769
  readinessCompletedThisBleSession = false
@@ -2123,8 +2141,7 @@ class MentraLive: NSObject, SGCManager {
2123
2141
  /// Wire-session generation at enqueue time; the drain loop drops entries from a
2124
2142
  /// previous session so a stale write (worst case: an old handshake whose reply
2125
2143
  /// would activate v2 pre-negotiation) can never cross a session boundary. This is
2126
- /// the deterministic guard - the async removeAll() on disconnect is best-effort
2127
- /// cleanup that may land after a reconnect has already resumed the drain loop.
2144
+ /// the deterministic guard if a consumer already dequeued a previous-session write.
2128
2145
  let generation: Int
2129
2146
  }
2130
2147
 
@@ -2166,7 +2183,7 @@ class MentraLive: NSObject, SGCManager {
2166
2183
  Bridge.log("LIVE: Cleared pending ACK mId \(pendingMessage.id) because \(reason)")
2167
2184
  }
2168
2185
 
2169
- actor CommandQueue {
2186
+ @MainActor final class CommandQueue {
2170
2187
  private var commands: [PendingMessage] = []
2171
2188
 
2172
2189
  func enqueue(_ command: PendingMessage) -> Int {
@@ -2184,6 +2201,17 @@ class MentraLive: NSObject, SGCManager {
2184
2201
  return commands.removeFirst()
2185
2202
  }
2186
2203
 
2204
+ /// Discards the run of writes from earlier wire-session generations at the head of
2205
+ /// the queue in one pass and dequeues the first current one. Stale writes are never
2206
+ /// sent, so they must not each cost a drain tick: a burst of epoch resets would
2207
+ /// otherwise park every current write behind seconds of dead entries.
2208
+ func dequeue(currentGeneration: Int) -> (command: PendingMessage?, staleIds: [String]) {
2209
+ let firstCurrent = commands.firstIndex { $0.generation == currentGeneration } ?? commands.endIndex
2210
+ let staleIds = commands[..<firstCurrent].map(\.id)
2211
+ commands.removeSubrange(..<firstCurrent)
2212
+ return (commands.isEmpty ? nil : commands.removeFirst(), staleIds)
2213
+ }
2214
+
2187
2215
  func removeAll() {
2188
2216
  commands.removeAll()
2189
2217
  }
@@ -2194,21 +2222,25 @@ class MentraLive: NSObject, SGCManager {
2194
2222
  guard let self else { return }
2195
2223
  while true {
2196
2224
  let pendingIsNil = await MainActor.run { self.pending == nil }
2197
- if pendingIsNil {
2198
- if let command = await self.commandQueue.dequeue() {
2199
- let currentGeneration = await MainActor.run { self.wireSessionGeneration }
2200
- if command.generation != currentGeneration {
2201
- Bridge.log("LIVE: Dropping stale queued write from a previous session epoch (id: \(command.id))")
2202
- } else {
2203
- await self.processSendQueue(command)
2204
- }
2205
- }
2225
+ if pendingIsNil, let command = await self.dequeueCurrentGenerationWrite() {
2226
+ await self.processSendQueue(command)
2206
2227
  }
2207
2228
  try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
2208
2229
  }
2209
2230
  }
2210
2231
  }
2211
2232
 
2233
+ private func dequeueCurrentGenerationWrite() -> PendingMessage? {
2234
+ let next = commandQueue.dequeue(currentGeneration: wireSessionGeneration)
2235
+ if !next.staleIds.isEmpty {
2236
+ Bridge.log(
2237
+ "LIVE: Dropping \(next.staleIds.count) stale queued write(s) from a previous session epoch " +
2238
+ "(ids: \(next.staleIds.joined(separator: ", ")))"
2239
+ )
2240
+ }
2241
+ return next.command
2242
+ }
2243
+
2212
2244
  private func processSendQueue(_ message: PendingMessage) async {
2213
2245
  guard let peripheral = connectedPeripheral,
2214
2246
  let txChar = txCharacteristic
@@ -2282,15 +2314,11 @@ class MentraLive: NSObject, SGCManager {
2282
2314
  )
2283
2315
 
2284
2316
  // Push to front of queue for immediate retry
2285
- Task {
2286
- let queueSize = await self.commandQueue.pushToFront(retryMessage)
2287
- await MainActor.run {
2288
- self.logBleWriteTrace("retry_queued", retryMessage.trace, extra: [
2289
- "retryDelayMs": 0,
2290
- "queueSizeAfterAdd": queueSize,
2291
- ])
2292
- }
2293
- }
2317
+ let queueSize = commandQueue.pushToFront(retryMessage)
2318
+ logBleWriteTrace("retry_queued", retryMessage.trace, extra: [
2319
+ "retryDelayMs": 0,
2320
+ "queueSizeAfterAdd": queueSize,
2321
+ ])
2294
2322
 
2295
2323
  Bridge.log(
2296
2324
  "🔄 Retrying message mId: \(pendingMessage.id) (attempt \(retryMessage.retries)/3)"
@@ -2528,8 +2556,8 @@ class MentraLive: NSObject, SGCManager {
2528
2556
  Bridge.log("LIVE: Maximum reconnection attempts reached (\(MAX_RECONNECT_ATTEMPTS))")
2529
2557
  reconnectAttempts = 0
2530
2558
  updateConnectionState(ConnTypes.DISCONNECTED)
2559
+ clearPhysicalReadiness()
2531
2560
  connected = false
2532
- fullyBooted = false
2533
2561
  glassesSessionId = nil
2534
2562
  streamControlVersion = 0
2535
2563
  readinessCompletedThisBleSession = false
@@ -2797,6 +2825,16 @@ class MentraLive: NSObject, SGCManager {
2797
2825
  Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
2798
2826
  return
2799
2827
  }
2828
+ let sid = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
2829
+ let readyId = (json["readyId"] as? String).flatMap { $0.isEmpty ? nil : $0 }
2830
+ if let readyId, isRepeatedGlassesReady(readyId: readyId, sid: sid) {
2831
+ Bridge.log("LIVE: Ignoring repeated glasses_ready for readiness exchange \(readyId) - the glasses did not reset for it")
2832
+ return
2833
+ }
2834
+ if readyId != nil, readyId == pendingReadyId {
2835
+ pendingReadyId = nil
2836
+ }
2837
+ readyGlassesSessionId = sid
2800
2838
  // glasses_ready is a REMOTE wire-session reset: the glasses ran
2801
2839
  // onTransportReset() before sending it, so their side is back on legacy
2802
2840
  // framing regardless of what this side negotiated earlier. Start a fresh
@@ -2812,7 +2850,7 @@ class MentraLive: NSObject, SGCManager {
2812
2850
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
2813
2851
  // already runs this full remote-reset flow, so recording (not re-triggering)
2814
2852
  // is correct here; version_info detection covers the restart case.
2815
- glassesSessionId = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
2853
+ glassesSessionId = sid
2816
2854
  streamControlVersion = json["streamControlVersion"] as? Int ?? 0
2817
2855
  Bridge.sendTypedMessage(
2818
2856
  "wifi_protocol_session_ready",
@@ -3143,6 +3181,11 @@ class MentraLive: NSObject, SGCManager {
3143
3181
  if type.hasPrefix("version_info") {
3144
3182
  Bridge.log("LIVE: Received \(type)")
3145
3183
 
3184
+ // A new process can report its build before glasses_ready resets the
3185
+ // wire epoch. Publish its pending readiness before those version fields
3186
+ // can complete OTA and trigger the next request.
3187
+ handleGlassesSessionId(json)
3188
+
3146
3189
  // Extract all fields from JSON (except "type")
3147
3190
  var fields: [String: Any] = [:]
3148
3191
  fields["version_info_type"] = type
@@ -3215,7 +3258,6 @@ class MentraLive: NSObject, SGCManager {
3215
3258
  // running them per chunk is safe.
3216
3259
  parsePeerWireCaps(json)
3217
3260
  maybeSendWireHandshake()
3218
- handleGlassesSessionId(json)
3219
3261
 
3220
3262
  Bridge.sendVersionInfo(fields, responseChunk: type)
3221
3263
  } else {
@@ -3332,6 +3374,11 @@ class MentraLive: NSObject, SGCManager {
3332
3374
  processAncsRelay(body)
3333
3375
  }
3334
3376
 
3377
+ case "sr_tpdef":
3378
+ if let body = k900ParseBody(json["B"]), body["setting"] as? String == "touch_gesture_default" {
3379
+ emitSettingsAck(body)
3380
+ }
3381
+
3335
3382
  case "sr_hrt":
3336
3383
  if let bodyObj = json["B"] as? [String: Any] {
3337
3384
  let readyResponse = bodyObj["ready"] as? Int ?? 0
@@ -3374,12 +3421,7 @@ class MentraLive: NSObject, SGCManager {
3374
3421
  // This prevents re-initialization on every heartbeat after initial connection
3375
3422
  // The ready flag is reset on disconnect/reconnect, so this won't prevent proper reconnection
3376
3423
  if !fullyBooted {
3377
- let readyMsg: [String: Any] = [
3378
- "type": "phone_ready",
3379
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
3380
- ]
3381
- // Send it through our data channel
3382
- sendJson(readyMsg, wakeUp: true)
3424
+ sendPhoneReady(reason: "SOC ready")
3383
3425
  }
3384
3426
  }
3385
3427
  }
@@ -3714,7 +3756,19 @@ class MentraLive: NSObject, SGCManager {
3714
3756
  sendJson(json, wakeUp: true)
3715
3757
  }
3716
3758
 
3717
- func sendIncidentId(_ incidentId: String, apiBaseUrl: String?) {
3759
+ var incidentLogTransportReady: Bool {
3760
+ connectedPeripheral?.state == .connected && txCharacteristic != nil
3761
+ }
3762
+
3763
+ func sendIncidentId(_ incidentId: String, apiBaseUrl: String?) throws {
3764
+ guard incidentLogTransportReady else {
3765
+ throw BluetoothSdkError(code: "glasses_not_connected", message: "Cannot request incident logs because the glasses BLE link is not ready.")
3766
+ }
3767
+ // Token sync may happen after glasses_ready; never rely on the last pairing's token.
3768
+ let coreToken = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
3769
+ guard !coreToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
3770
+ throw BluetoothSdkError(code: "core_token_unavailable", message: "Cannot request incident logs without the current Core access token.")
3771
+ }
3718
3772
  var base = (apiBaseUrl ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
3719
3773
  if base.isEmpty {
3720
3774
  base = "https://api.mentra.glass"
@@ -3731,10 +3785,20 @@ class MentraLive: NSObject, SGCManager {
3731
3785
  fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
3732
3786
  )
3733
3787
 
3734
- Bridge.log(
3735
- "LIVE: Sending incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))"
3736
- )
3737
- sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base], wakeUp: true)
3788
+ let auth: [String: Any] = [
3789
+ "type": "auth_token", "coreToken": coreToken,
3790
+ "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
3791
+ ]
3792
+ // MainActor queue insertion preserves auth-before-upload order, including all fragments.
3793
+ guard sendJson(auth, wakeUp: true, requireAck: true, bridgeLogging: true),
3794
+ sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
3795
+ wakeUp: true, requireAck: true, bridgeLogging: true)
3796
+ else {
3797
+ bleIncidentLogRelays.removeValue(forKey: bKey)
3798
+ bleIncidentLogRelays.removeValue(forKey: lKey)
3799
+ throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
3800
+ }
3801
+ Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
3738
3802
  }
3739
3803
 
3740
3804
  private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
@@ -3819,6 +3883,25 @@ class MentraLive: NSObject, SGCManager {
3819
3883
  sendJson(json, wakeUp: true)
3820
3884
  }
3821
3885
 
3886
+ func sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
3887
+ guard connectedPeripheral != nil, txCharacteristic != nil else {
3888
+ throw BluetoothSdkError(code: "not_connected", message: "Mentra Live glasses are not connected.")
3889
+ }
3890
+ try sendTouchGestureDefaultCommand(requestId: requestId, gesture: gesture, enabled: enabled)
3891
+ }
3892
+
3893
+ /// Kept separate from readiness admission so tests can replay the real K900 wire exchange.
3894
+ func sendTouchGestureDefaultCommand(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
3895
+ let body = try JSONSerialization.data(withJSONObject: [
3896
+ "request_id": requestId, "gesture": gesture.rawValue, "enabled": enabled,
3897
+ ])
3898
+ guard let bodyString = String(data: body, encoding: .utf8),
3899
+ sendRawK900Command(["C": "cs_tpdef", "V": 1, "B": bodyString])
3900
+ else {
3901
+ throw BluetoothSdkError(code: "command_send_failed", message: "Could not encode the touch gesture setting.")
3902
+ }
3903
+ }
3904
+
3822
3905
  func sendGalleryServerEnabled(requestId: String, enabled: Bool) {
3823
3906
  sendJson([
3824
3907
  "type": "set_gallery_server_enabled",
@@ -3889,6 +3972,20 @@ class MentraLive: NSObject, SGCManager {
3889
3972
 
3890
3973
  // MARK: - Message Handlers
3891
3974
 
3975
+ /// A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
3976
+ /// exchange the phone is waiting on, and any answer from a glasses process other than the
3977
+ /// one this link last handled (an asg restart resets for every exchange it first sees),
3978
+ /// followed a transport reset. Any other answer repeats an exchange that process already
3979
+ /// reset for, or one superseded by the pending exchange, whose answer is still to come.
3980
+ private func isRepeatedGlassesReady(readyId: String, sid: String?) -> Bool {
3981
+ readyId != pendingReadyId && sid == readyGlassesSessionId
3982
+ }
3983
+
3984
+ private func resetReadinessExchange() {
3985
+ pendingReadyId = nil
3986
+ readyGlassesSessionId = nil
3987
+ }
3988
+
3892
3989
  private func handleGlassesReady() {
3893
3990
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
3894
3991
 
@@ -4671,20 +4768,13 @@ class MentraLive: NSObject, SGCManager {
4671
4768
 
4672
4769
  func queueSend(_ data: Data, id: String, trace: BleWriteTrace?) {
4673
4770
  let significantQueueSize = SIGNIFICANT_BLE_TRACE_QUEUE_SIZE
4674
- // Capture the epoch at enqueue-request time: the Task body may run after a
4675
- // session reset, and a pre-reset payload stamped with the new generation would
4676
- // defeat the stale-write guard in the drain loop.
4771
+ // Insert synchronously on MainActor so fragments and dependent commands retain call order.
4677
4772
  let generation = wireSessionGeneration
4678
- Task {
4679
- let queueSize = await commandQueue.enqueue(PendingMessage(data: data, id: id, retries: 0, trace: trace, generation: generation))
4680
- guard trace != nil, queueSize >= significantQueueSize else {
4681
- return
4682
- }
4683
- await MainActor.run {
4684
- self.logBleChunkTrace("queued", trace, extra: [
4685
- "queueSizeAfterAdd": queueSize,
4686
- ])
4687
- }
4773
+ let queueSize = commandQueue.enqueue(PendingMessage(data: data, id: id, retries: 0, trace: trace, generation: generation))
4774
+ if trace != nil, queueSize >= significantQueueSize {
4775
+ logBleChunkTrace("queued", trace, extra: [
4776
+ "queueSizeAfterAdd": queueSize,
4777
+ ])
4688
4778
  }
4689
4779
  }
4690
4780
 
@@ -5201,7 +5291,10 @@ class MentraLive: NSObject, SGCManager {
5201
5291
  bridgeLogging: bridgeLogging
5202
5292
  )
5203
5293
  }
5204
- transportLog("LIVE: Sending data to glasses: \(jsonString)", bridgeLogging: bridgeLogging)
5294
+ // Credentials reach the wire unchanged; diagnostic logs omit their values.
5295
+ let loggedPayload = json["password"] == nil && json["coreToken"] == nil
5296
+ ? jsonString : "<\(commandInfo.commandType) with credentials omitted>"
5297
+ transportLog("LIVE: Sending data to glasses: \(loggedPayload)", bridgeLogging: bridgeLogging)
5205
5298
  let packedData =
5206
5299
  packJson(
5207
5300
  jsonString,
@@ -5724,7 +5817,7 @@ class MentraLive: NSObject, SGCManager {
5724
5817
  stopReadinessCheckLoop()
5725
5818
 
5726
5819
  readinessCheckCounter = 0
5727
- fullyBooted = false
5820
+ clearPhysicalReadiness()
5728
5821
  connected = false
5729
5822
  glassesSessionId = nil
5730
5823
  streamControlVersion = 0
@@ -5745,12 +5838,13 @@ class MentraLive: NSObject, SGCManager {
5745
5838
  )
5746
5839
  // requestReadyK900()
5747
5840
 
5748
- let readyMsg: [String: Any] = [
5749
- "type": "phone_ready",
5750
- "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
5751
- ]
5752
- // Send it through our data channel
5753
- sendJson(readyMsg, wakeUp: true)
5841
+ // The timer fires on bluetoothQueue; the pending readiness exchange is main-actor state.
5842
+ // A tick queued just before glasses_ready stopped the loop must not start a new exchange.
5843
+ let check = self.readinessCheckCounter
5844
+ DispatchQueue.main.async { [weak self] in
5845
+ guard let self, self.readinessCheckDispatchTimer != nil else { return }
5846
+ self.sendPhoneReady(reason: "readiness check #\(check)")
5847
+ }
5754
5848
  }
5755
5849
 
5756
5850
  readinessCheckDispatchTimer!.resume()
@@ -5996,7 +6090,8 @@ class MentraLive: NSObject, SGCManager {
5996
6090
  // Stop all timers
5997
6091
  stopAllTimers()
5998
6092
  resetWireNegotiationState()
5999
- Task { await commandQueue.removeAll() } // stale writes die with the session
6093
+ resetReadinessExchange()
6094
+ commandQueue.removeAll() // stale writes die with the session
6000
6095
  closeL2capFileChannel()
6001
6096
 
6002
6097
  // Disconnect BLE
@@ -6005,8 +6100,8 @@ class MentraLive: NSObject, SGCManager {
6005
6100
  centralManager?.cancelPeripheralConnection(peripheral)
6006
6101
  }
6007
6102
 
6103
+ clearPhysicalReadiness()
6008
6104
  DeviceStore.shared.apply("glasses", "connected", false)
6009
- DeviceStore.shared.apply("glasses", "fullyBooted", false)
6010
6105
  DeviceStore.shared.apply("glasses", "wifiConnected", false)
6011
6106
  DeviceStore.shared.apply("glasses", "wifiSsid", "")
6012
6107
  DeviceStore.shared.apply("glasses", "wifiLocalIp", "")
@@ -6125,10 +6220,15 @@ extension MentraLive {
6125
6220
 
6126
6221
  /// Sends phone_ready to (re)start the glasses-driven readiness flow.
6127
6222
  private func sendPhoneReady(reason: String) {
6128
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses (\(reason)) - waiting for glasses_ready response")
6223
+ let readyId = pendingReadyId ?? UUID().uuidString
6224
+ pendingReadyId = readyId
6225
+ Bridge.log(
6226
+ "LIVE: 📱 Sending phone_ready to glasses (\(reason), exchange \(readyId)) - waiting for glasses_ready response"
6227
+ )
6129
6228
  let readyMsg: [String: Any] = [
6130
6229
  "type": "phone_ready",
6131
6230
  "timestamp": Int64(Date().timeIntervalSince1970 * 1000),
6231
+ "readyId": readyId,
6132
6232
  ]
6133
6233
  sendJson(readyMsg, wakeUp: true)
6134
6234
  }
@@ -6143,8 +6243,8 @@ extension MentraLive {
6143
6243
  /// pre-sid build) or differing from the recorded one = restart; same sid = no action.
6144
6244
  /// A restart is a LOGICAL session reset: send phone_ready immediately (bypassing the
6145
6245
  /// sr_hrt heartbeat's stale-readiness suppression); the returning glasses_ready runs
6146
- /// the full existing remote-wire-reset flow. fullyBooted is deliberately untouched -
6147
- /// the physical link never dropped, so the connection UI must not flap.
6246
+ /// the full existing remote-wire-reset flow. Keep the physical connection intact,
6247
+ /// but mark readiness pending until that new wire epoch has been established.
6148
6248
  private func handleGlassesSessionId(_ json: [String: Any]) {
6149
6249
  guard let sid = json["sid"] as? String, !sid.isEmpty else { return }
6150
6250
  let previous = glassesSessionId
@@ -6159,6 +6259,9 @@ extension MentraLive {
6159
6259
  "LIVE: 🔁 Glasses session changed (\(previous ?? "<pre-sid build>") -> \(sid)) - " +
6160
6260
  "asg restarted under a live link, re-running readiness"
6161
6261
  )
6262
+ // Emit the existing connected-but-not-ready status without invoking the
6263
+ // physical-disconnect side effects of DeviceStore.apply(fullyBooted: false).
6264
+ DeviceStore.shared.set("glasses", "fullyBooted", false)
6162
6265
  sendPhoneReady(reason: "glasses session changed")
6163
6266
  Bridge.sendTypedMessage(
6164
6267
  "glasses_session_changed",
@@ -77,7 +77,10 @@ enum NimoCanvasCodec {
77
77
  {
78
78
  try region(x, y, w, h)
79
79
  try require((0 ... 3).contains(font) && (0 ... 20).contains(language) && (0 ... 255).contains(intensity))
80
- let utf8 = Data(text.utf8)
80
+ // Apply the shared Latin fallback and NIMO's dash fix before counting wire bytes.
81
+ let displayText = LatinTextSanitizer.sanitizeForDisplay(text, preserveOtherScripts: true)
82
+ .replacingOccurrences(of: "\u{2014}", with: "-")
83
+ let utf8 = Data(displayText.utf8)
81
84
  try require((1 ... 2048).contains(utf8.count) && !utf8.contains(0), "Label exceeds 2048 UTF-8 bytes or contains NUL")
82
85
  return Object(type: 3, payload: words(x, y, w, h, language) + bytes(font, intensity) + words(utf8.count) + utf8,
83
86
  textBytes: utf8.count)
@@ -217,7 +217,7 @@ protocol SGCManager {
217
217
 
218
218
  // MARK: - Incident Reporting
219
219
 
220
- func sendIncidentId(_ incidentId: String, apiBaseUrl: String?)
220
+ func sendIncidentId(_ incidentId: String, apiBaseUrl: String?) throws
221
221
 
222
222
  // MARK: - Gallery
223
223
 
@@ -10,9 +10,11 @@ import Foundation
10
10
 
11
11
  #if !os(macOS)
12
12
  import AVFoundation
13
+ import OSLog
13
14
  import UIKit
14
15
 
15
16
  class AudioSessionMonitor {
17
+ private static let readinessLog = Logger(subsystem: "com.mentra.bluetooth-sdk", category: "AudioReadiness")
16
18
  /// Singleton instance
17
19
  private static var instance: AudioSessionMonitor?
18
20
 
@@ -96,15 +98,31 @@ class AudioSessionMonitor {
96
98
  /// This avoids switching A2DP music playback to HFP microphone mode
97
99
  static func isDevicePaired(devicePattern: String) -> Bool {
98
100
  let session = AVAudioSession.sharedInstance()
101
+ let outputs = session.currentRoute.outputs
102
+ let route = BluetoothAudioRoute.observe(
103
+ outputs: outputs.map { (name: $0.portName, portType: $0.portType.rawValue) },
104
+ target: devicePattern, isIOSAppOnMac: ProcessInfo.processInfo.isiOSAppOnMac
105
+ )
106
+ let activeTarget = route.matchingOutputCount > 0
107
+ let availableInputs = session.availableInputs
108
+ let bluetoothInput = availableInputs?.first { input in
109
+ input.portType == .bluetoothHFP
110
+ && input.portName.localizedCaseInsensitiveContains(devicePattern)
111
+ }
112
+
113
+ // NSLog messages redact the native route checks in retained Mac logs.
114
+ // Keep categorical evidence at notice level without exposing names or
115
+ // selecting an input, activating the session, or changing audio routing.
116
+ readinessLog.notice("Pair audio: iosOnMac=\(ProcessInfo.processInfo.isiOSAppOnMac, privacy: .public) targetPresent=\(!devicePattern.isEmpty, privacy: .public) category=\(session.category.rawValue, privacy: .public) outputs=\(outputs.count, privacy: .public) bluetoothOutputs=\(route.bluetoothOutputCount, privacy: .public) targetNameOutputs=\(route.targetNameOutputCount, privacy: .public) inputs=\(availableInputs?.count ?? -1, privacy: .public) activeTarget=\(activeTarget, privacy: .public) hfpTarget=\(bluetoothInput != nil, privacy: .public)")
99
117
 
100
118
  // Check if already active (using A2DP for music or HFP for calls)
101
- if isAudioDeviceConnected(devicePattern: devicePattern) {
119
+ if activeTarget {
102
120
  Bridge.log("AudioMonitor: Device '\(devicePattern)' already active")
103
121
  return true
104
122
  }
105
123
 
106
124
  // Try to find in availableInputs (includes paired devices)
107
- guard let availableInputs = session.availableInputs else {
125
+ guard let availableInputs else {
108
126
  Bridge.log("AudioMonitor: ❌ availableInputs is nil")
109
127
  return false
110
128
  }
@@ -114,11 +132,6 @@ class AudioSessionMonitor {
114
132
  Bridge.log("AudioMonitor: - \(input.portName) (type: \(input.portType.rawValue))")
115
133
  }
116
134
 
117
- let bluetoothInput = availableInputs.first { input in
118
- input.portType == .bluetoothHFP
119
- && input.portName.localizedCaseInsensitiveContains(devicePattern)
120
- }
121
-
122
135
  if let btInput = bluetoothInput {
123
136
  Bridge.log(
124
137
  "AudioMonitor: ✅ Found paired device '\(btInput.portName)' (not activating to preserve A2DP)"
@@ -291,8 +304,31 @@ class AudioSessionMonitor {
291
304
  /// AVAudioSession preserves the route name on iOS-on-Mac but reports the
292
305
  /// CoreAudio transport "Bluetooth" instead of iPhone's profile-specific port.
293
306
  enum BluetoothAudioRoute {
307
+ struct Observation: Equatable {
308
+ let bluetoothOutputCount: Int
309
+ let targetNameOutputCount: Int
310
+ let matchingOutputCount: Int
311
+ }
312
+
313
+ static func observe(outputs: [(name: String, portType: String)], target: String, isIOSAppOnMac: Bool) -> Observation {
314
+ Observation(
315
+ bluetoothOutputCount: outputs.filter { isBluetoothTransport($0.portType, isIOSAppOnMac: isIOSAppOnMac) }.count,
316
+ targetNameOutputCount: outputs.filter { matchesName($0.name, target: target) }.count,
317
+ matchingOutputCount: outputs.filter {
318
+ matches(name: $0.name, portType: $0.portType, target: target, isIOSAppOnMac: isIOSAppOnMac)
319
+ }.count
320
+ )
321
+ }
322
+
294
323
  static func matches(name: String, portType: String, target: String, isIOSAppOnMac: Bool) -> Bool {
295
- guard !target.isEmpty, name.localizedCaseInsensitiveContains(target) else { return false }
324
+ matchesName(name, target: target) && isBluetoothTransport(portType, isIOSAppOnMac: isIOSAppOnMac)
325
+ }
326
+
327
+ private static func matchesName(_ name: String, target: String) -> Bool {
328
+ !target.isEmpty && name.localizedCaseInsensitiveContains(target)
329
+ }
330
+
331
+ private static func isBluetoothTransport(_ portType: String, isIOSAppOnMac: Bool) -> Bool {
296
332
  return portType == "BluetoothHFP" || portType == "BluetoothA2DPOutput"
297
333
  || (isIOSAppOnMac && portType == "Bluetooth")
298
334
  }
@@ -24,31 +24,9 @@ class G1Text {
24
24
 
25
25
  init() {}
26
26
 
27
- /// Converts text to the base Latin glyphs available in G1 firmware.
28
- /// Newer glasses bypass this G1-only transport and keep the original text.
27
+ /// Preserve supported G1 Latin glyphs before BLE encoding.
29
28
  static func sanitizeForDisplay(_ text: String) -> String {
30
- let expanded = text.reduce(into: "") { result, character in
31
- switch character {
32
- case "Đ", "Ð": result.append("D")
33
- case "đ", "ð": result.append("d")
34
- case "Ł": result.append("L")
35
- case "ł": result.append("l")
36
- case "Ø": result.append("O")
37
- case "ø": result.append("o")
38
- case "Æ": result.append("AE")
39
- case "æ": result.append("ae")
40
- case "Œ": result.append("OE")
41
- case "œ": result.append("oe")
42
- case "ẞ": result.append("SS")
43
- case "ß": result.append("ss")
44
- case "Þ": result.append("TH")
45
- case "þ": result.append("th")
46
- default: result.append(character)
47
- }
48
- }
49
-
50
- return expanded
51
- .folding(options: .diacriticInsensitive, locale: Locale(identifier: "en_US_POSIX"))
29
+ G1TextSanitizer.sanitizeForDisplay(text)
52
30
  }
53
31
 
54
32
  // MARK: - Text Wall Methods
@@ -0,0 +1,27 @@
1
+ import Foundation
2
+
3
+ /// Preserves the embedded G1 1.5.6 Latin glyphs; see notes/g1-character-support.md.
4
+ enum G1TextSanitizer {
5
+ private static let supportedLatin = Set("ÀÂÇÈÉÊËÎÏÔÙÛÜàçèéêëîïôùûüÿŸÄäÖößẞâÁáÍíÑñúÓóÚⁱIJijŠšŽžÃÅÆÌÐÒÕØÝÞãåæìðòõøýþĄąĆćČčĎďĘęĚěĞğŁłŃńŇňŘřŚśŞşŤťŮůŹźŻżĂăıȘșȚțǖǘǚǜǎǐǒǔŐőŰű".unicodeScalars)
6
+ private static let latinClusters = try! NSRegularExpression(pattern: #"\p{Latin}\p{M}*"#)
7
+
8
+ static func sanitizeForDisplay(_ text: String) -> String {
9
+ let output = NSMutableString(string: text)
10
+ let range = NSRange(text.startIndex ..< text.endIndex, in: text)
11
+ for match in latinClusters.matches(in: text, range: range).reversed() {
12
+ let cluster = output.substring(with: match.range)
13
+ let composed = cluster.precomposedStringWithCanonicalMapping
14
+ let scalars = composed.unicodeScalars
15
+ let replacement: String
16
+ if scalars.count == 1, let scalar = scalars.first,
17
+ (0x20 ... 0x7E).contains(scalar.value) || supportedLatin.contains(scalar)
18
+ {
19
+ replacement = composed
20
+ } else {
21
+ replacement = LatinTextSanitizer.sanitizeForDisplay(cluster, preserveOtherScripts: true)
22
+ }
23
+ output.replaceCharacters(in: match.range, with: replacement)
24
+ }
25
+ return output as String
26
+ }
27
+ }