@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
@@ -2,37 +2,16 @@ package com.mentra.bluetoothsdk.sgcs
2
2
 
3
3
  import java.text.Normalizer
4
4
 
5
- private val G1_COMBINING_MARKS = Regex("\\p{M}+")
5
+ // Embedded G1 1.5.6 Latin glyphs. See notes/g1-character-support.md.
6
+ private const val G1_LATIN_GLYPHS = "ÀÂÇÈÉÊËÎÏÔÙÛÜàçèéêëîïôùûüÿŸÄäÖößẞâÁáÍíÑñúÓóÚⁱIJijŠšŽžÃÅÆÌÐÒÕØÝÞãåæìðòõøýþĄąĆćČčĎďĘęĚěĞğŁłŃńŇňŘřŚśŞşŤťŮůŹźŻżĂăıȘșȚțǖǘǚǜǎǐǒǔŐőŰű"
7
+ private val G1_LATIN_CLUSTERS = Regex("\\p{IsLatin}\\p{M}*")
6
8
 
7
- /**
8
- * Converts text to the base Latin glyphs available in the Even Realities G1 firmware.
9
- *
10
- * G1 does not ship glyphs for combining diacritics. Normalize at the device boundary so
11
- * miniapps can retain the real text everywhere else and newer glasses receive it unchanged.
12
- */
13
- internal fun sanitizeG1DisplayText(text: String): String {
14
- val expanded = buildString(text.length) {
15
- text.forEach { character ->
16
- when (character) {
17
- 'Đ', 'Ð' -> append('D')
18
- 'đ', 'ð' -> append('d')
19
- 'Ł' -> append('L')
20
- 'ł' -> append('l')
21
- 'Ø' -> append('O')
22
- 'ø' -> append('o')
23
- 'Æ' -> append("AE")
24
- 'æ' -> append("ae")
25
- 'Œ' -> append("OE")
26
- 'œ' -> append("oe")
27
- 'ẞ' -> append("SS")
28
- 'ß' -> append("ss")
29
- 'Þ' -> append("TH")
30
- 'þ' -> append("th")
31
- else -> append(character)
32
- }
33
- }
34
- }
35
-
36
- return Normalizer.normalize(expanded, Normalizer.Form.NFD)
37
- .replace(G1_COMBINING_MARKS, "")
9
+ /** Preserves mapped Latin glyphs and falls back only for unmapped Latin clusters. */
10
+ internal fun sanitizeG1DisplayText(text: String): String = G1_LATIN_CLUSTERS.replace(text) { match ->
11
+ val composed = Normalizer.normalize(match.value, Normalizer.Form.NFC)
12
+ if (composed.length == 1 && (composed[0] in ' '..'~' || composed[0] in G1_LATIN_GLYPHS)) {
13
+ composed
14
+ } else {
15
+ sanitizeLatinDisplayText(match.value, preserveOtherScripts = true)
16
+ }
38
17
  }
@@ -0,0 +1,39 @@
1
+ package com.mentra.bluetoothsdk.sgcs
2
+
3
+ import java.text.Normalizer
4
+
5
+ private val LATIN_COMBINING_MARKS = Regex("\\p{M}+")
6
+ private val LATIN_LETTERS_WITH_MARKS = Regex("\\p{IsLatin}\\p{M}*")
7
+
8
+ /** Converts accented and extended Latin letters to base glyphs at the device boundary. */
9
+ internal fun sanitizeLatinDisplayText(text: String, preserveOtherScripts: Boolean = false): String {
10
+ val expanded = buildString(text.length) {
11
+ text.forEach { character ->
12
+ when (character) {
13
+ 'Đ', 'Ð' -> append('D')
14
+ 'đ', 'ð' -> append('d')
15
+ 'Ł' -> append('L')
16
+ 'ł' -> append('l')
17
+ 'Ø' -> append('O')
18
+ 'ø' -> append('o')
19
+ 'Æ' -> append("AE")
20
+ 'æ' -> append("ae")
21
+ 'Œ' -> append("OE")
22
+ 'œ' -> append("oe")
23
+ 'ẞ' -> append("SS")
24
+ 'ß' -> append("ss")
25
+ 'Þ' -> append("TH")
26
+ 'þ' -> append("th")
27
+ else -> append(character)
28
+ }
29
+ }
30
+ }
31
+
32
+ if (preserveOtherScripts) {
33
+ return LATIN_LETTERS_WITH_MARKS.replace(expanded) { match ->
34
+ Normalizer.normalize(match.value, Normalizer.Form.NFD).replace(LATIN_COMBINING_MARKS, "")
35
+ }
36
+ }
37
+ return Normalizer.normalize(expanded, Normalizer.Form.NFD)
38
+ .replace(LATIN_COMBINING_MARKS, "")
39
+ }
@@ -34,11 +34,13 @@ import android.os.SystemClock
34
34
  import com.mentra.bluetoothsdk.utils.NativeLog as Log
35
35
  import androidx.core.app.ActivityCompat
36
36
  import com.mentra.bluetoothsdk.BluetoothSdkDefaults
37
+ import com.mentra.bluetoothsdk.BluetoothSdkException
37
38
  import com.mentra.bluetoothsdk.Bridge
38
39
  import com.mentra.bluetoothsdk.DeviceManager
39
40
  import com.mentra.bluetoothsdk.PhotoRequest
40
41
  import com.mentra.bluetoothsdk.PhotoSize
41
42
  import com.mentra.bluetoothsdk.PhotoMode
43
+ import com.mentra.bluetoothsdk.TouchGesture
42
44
  import com.mentra.bluetoothsdk.DeviceStore
43
45
  import com.mentra.bluetoothsdk.ObservableStore
44
46
  import com.mentra.bluetoothsdk.incomingGlassesMessageAckId
@@ -564,6 +566,13 @@ class MentraLive : SGCManager() {
564
566
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
565
567
  // after an upgrade OTA is always detected as a restart.
566
568
  private var readinessCompletedThisBleSession = false
569
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
570
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
571
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
572
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
573
+ private var pendingReadyId: String? = null
574
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
575
+ private var readyGlassesSessionId: String? = null
567
576
  // Note: appVersion, buildNumber, deviceModel, androidVersion
568
577
  // are inherited from SGCManager parent class
569
578
 
@@ -645,6 +654,10 @@ class MentraLive : SGCManager() {
645
654
  private var a2dpProfile: BluetoothA2dp? = null
646
655
  private var isA2dpProxyRegistered = false
647
656
  private var a2dpConnectAttempts = 0
657
+ private val classicAudioServiceDiscovery =
658
+ ClassicAudioServiceDiscovery(handler, CONNECTION_TIMEOUT_MS.toLong()) {
659
+ Bridge.log("LIVE: Classic: $it")
660
+ }
648
661
 
649
662
  private data class OutgoingBleCommandTraceInfo(
650
663
  val commandType: String,
@@ -1188,6 +1201,7 @@ class MentraLive : SGCManager() {
1188
1201
  if (state == ConnTypes.DISCONNECTED) {
1189
1202
  resetWireNegotiationState()
1190
1203
  resetPendingAckState()
1204
+ resetReadinessExchange()
1191
1205
  // Queued writes are session-bound: transmitting them into the NEXT session
1192
1206
  // (e.g. a stale handshake whose reply activates v2 before the new session
1193
1207
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1243,6 +1257,7 @@ class MentraLive : SGCManager() {
1243
1257
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1244
1258
  resetWireNegotiationState()
1245
1259
  resetPendingAckState()
1260
+ resetReadinessExchange()
1246
1261
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1247
1262
  // next link must be allowed to send them again.
1248
1263
  lastSentMicTuningBody = null
@@ -1708,6 +1723,7 @@ class MentraLive : SGCManager() {
1708
1723
  readinessCompletedThisBleSession = false
1709
1724
  glassesReadyReceived = false
1710
1725
  ctkdInitiatedThisGattSession = false
1726
+ classicAudioServiceDiscovery.cancel()
1711
1727
  audioConnected = false
1712
1728
  notificationsEnabled = false
1713
1729
  currentMtu = 23
@@ -1983,6 +1999,7 @@ class MentraLive : SGCManager() {
1983
1999
  readinessCompletedThisBleSession = false
1984
2000
  glassesReadyReceived = false
1985
2001
  ctkdInitiatedThisGattSession = false
2002
+ classicAudioServiceDiscovery.cancel()
1986
2003
  audioConnected = false
1987
2004
  notificationsEnabled = false
1988
2005
  processSendQueueRunnable?.let { handler.removeCallbacks(it) }
@@ -2350,6 +2367,7 @@ class MentraLive : SGCManager() {
2350
2367
  registerBondingReceiver()
2351
2368
  bondingRetryCount = 0
2352
2369
  ctkdInitiatedThisGattSession = false
2370
+ classicAudioServiceDiscovery.cancel()
2353
2371
  Bridge.log(
2354
2372
  "LIVE: CTKD: BLE GATT up - deferring Classic/A2DP until notifications ready"
2355
2373
  )
@@ -2398,6 +2416,7 @@ class MentraLive : SGCManager() {
2398
2416
  // Reset audio pairing flags
2399
2417
  glassesReadyReceived = false
2400
2418
  ctkdInitiatedThisGattSession = false
2419
+ classicAudioServiceDiscovery.cancel()
2401
2420
  audioConnected = false
2402
2421
 
2403
2422
  notificationsEnabled = false
@@ -2460,6 +2479,7 @@ class MentraLive : SGCManager() {
2460
2479
  glassesReadyReceived = false
2461
2480
  audioConnected = false
2462
2481
  ctkdInitiatedThisGattSession = false
2482
+ classicAudioServiceDiscovery.cancel()
2463
2483
 
2464
2484
  notificationsEnabled = false
2465
2485
 
@@ -3371,10 +3391,12 @@ class MentraLive : SGCManager() {
3371
3391
  sendJson(json, wakeup, true)
3372
3392
  }
3373
3393
 
3374
- private fun sendJson(json: JSONObject?, wakeup: Boolean, bridgeLogging: Boolean): Boolean {
3394
+ private fun sendJson(
3395
+ json: JSONObject?, wakeup: Boolean, bridgeLogging: Boolean,
3396
+ sessionGeneration: Long = bleSessionGeneration.get(),
3397
+ ): Boolean {
3375
3398
  if (json != null) {
3376
3399
  try {
3377
- val sessionGeneration = bleSessionGeneration.get()
3378
3400
  if (buildNumberInt < 5) {
3379
3401
  val jsonStr = json.toString()
3380
3402
  // Bridge.log("LIVE: 📤 Sending JSON with esoteric message ID: " + jsonStr);
@@ -4599,6 +4621,19 @@ class MentraLive : SGCManager() {
4599
4621
  Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
4600
4622
  return
4601
4623
  }
4624
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
4625
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
4626
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
4627
+ Bridge.log(
4628
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
4629
+ "the glasses did not reset for it"
4630
+ )
4631
+ return
4632
+ }
4633
+ if (readyId != null && readyId == pendingReadyId) {
4634
+ pendingReadyId = null
4635
+ }
4636
+ readyGlassesSessionId = sid
4602
4637
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4603
4638
  pairingYieldAwaitingReclaim = false
4604
4639
  pairingYieldActive = false
@@ -4620,7 +4655,7 @@ class MentraLive : SGCManager() {
4620
4655
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4621
4656
  // already runs this full remote-reset flow, so recording (not re-triggering)
4622
4657
  // is correct here; version_info detection covers the restart case.
4623
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
4658
+ glassesSessionId = sid
4624
4659
  streamControlVersion = json.optInt("streamControlVersion", 0)
4625
4660
  Bridge.sendTypedMessage(
4626
4661
  "wifi_protocol_session_ready",
@@ -5458,6 +5493,14 @@ class MentraLive : SGCManager() {
5458
5493
  // Bridge.log("LIVE: Processing K900 command: " + command);
5459
5494
 
5460
5495
  when (command) {
5496
+ "sr_tpdef" -> {
5497
+ val body = when (val value = json.opt("B")) {
5498
+ is JSONObject -> value
5499
+ is String -> runCatching { JSONObject(value) }.getOrNull()
5500
+ else -> null
5501
+ }
5502
+ if (body != null && body.optString("setting") == "touch_gesture_default") emitSettingsAck(body)
5503
+ }
5461
5504
  "sr_hrt" -> {
5462
5505
  try {
5463
5506
  val bodyObj = json.optJSONObject("B")
@@ -6075,6 +6118,17 @@ class MentraLive : SGCManager() {
6075
6118
  }
6076
6119
 
6077
6120
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6121
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6122
+ throw BluetoothSdkException(
6123
+ "glasses_not_connected", "Cannot request incident logs because the glasses BLE link is not ready.",
6124
+ )
6125
+ }
6126
+ // The JS token sync may happen after glasses_ready. Use only its current native store value.
6127
+ val coreToken = DeviceStore.get("bluetooth", "core_token") as? String
6128
+ if (coreToken.isNullOrBlank()) {
6129
+ throw BluetoothSdkException("core_token_unavailable", "Cannot request incident logs without the current Core access token.")
6130
+ }
6131
+ val sessionGeneration = bleSessionGeneration.get()
6078
6132
  try {
6079
6133
  var base = if (apiBaseUrl != null) apiBaseUrl.trim() else ""
6080
6134
  if (base.isEmpty()) {
@@ -6087,13 +6141,25 @@ class MentraLive : SGCManager() {
6087
6141
  bleIncidentLogRelays[lKey] =
6088
6142
  BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6089
6143
 
6144
+ val auth = JSONObject()
6145
+ auth.put("type", "auth_token")
6146
+ auth.put("coreToken", coreToken)
6147
+ auth.put("timestamp", System.currentTimeMillis())
6090
6148
  val json = JSONObject()
6091
6149
  json.put("type", "upload_incident_logs")
6092
6150
  json.put("incidentId", incidentId)
6093
6151
  json.put("apiBaseUrl", base)
6094
- sendJson(json, true)
6152
+ // Wake ASG with its current token before the upload command enters the same FIFO.
6153
+ if (!sendJson(auth, true, true, sessionGeneration) ||
6154
+ sessionGeneration != bleSessionGeneration.get() ||
6155
+ !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6156
+ !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6157
+ bleIncidentLogRelays.remove(bKey)
6158
+ bleIncidentLogRelays.remove(lKey)
6159
+ throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6160
+ }
6095
6161
  Bridge.log(
6096
- "LIVE: Sent incidentId to glasses for log upload: " +
6162
+ "LIVE: Queued incidentId to glasses for log upload: " +
6097
6163
  incidentId +
6098
6164
  " (BLE relay keys " +
6099
6165
  bKey +
@@ -6102,7 +6168,7 @@ class MentraLive : SGCManager() {
6102
6168
  ")"
6103
6169
  )
6104
6170
  } catch (e: JSONException) {
6105
- Log.e(TAG, "Error creating upload_incident_logs command", e)
6171
+ throw BluetoothSdkException("incident_dispatch_failed", "Could not create the glasses incident-log request.", e)
6106
6172
  }
6107
6173
  }
6108
6174
 
@@ -6175,6 +6241,19 @@ class MentraLive : SGCManager() {
6175
6241
  }
6176
6242
  }
6177
6243
 
6244
+ fun sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Boolean) {
6245
+ val sessionGeneration = bleSessionGeneration.get()
6246
+ if (!isConnected) throw BluetoothSdkException("not_connected", "Mentra Live glasses are not connected.")
6247
+ val body = JSONObject().put("request_id", requestId).put("gesture", gesture.wireName).put("enabled", enabled)
6248
+ val command = JSONObject().put("C", "cs_tpdef").put("V", 1).put("B", body.toString())
6249
+ val packet = K900ProtocolUtils.packDataToK900(
6250
+ command.toString().toByteArray(StandardCharsets.UTF_8),
6251
+ K900ProtocolUtils.CMD_TYPE_STRING,
6252
+ k900LengthEndian(),
6253
+ ) ?: throw BluetoothSdkException("command_send_failed", "Could not encode the touch gesture setting.")
6254
+ queueData(packet, sessionGeneration = sessionGeneration)
6255
+ }
6256
+
6178
6257
  fun sendGalleryServerEnabled(requestId: String, enabled: Boolean) {
6179
6258
  val json = JSONObject()
6180
6259
  .put("type", "set_gallery_server_enabled")
@@ -7208,7 +7287,7 @@ class MentraLive : SGCManager() {
7208
7287
  BluetoothDevice.BOND_BONDED ->
7209
7288
  run {
7210
7289
  Bridge.log(
7211
- "LIVE: CTKD: ✅ Successfully bonded with device - BT Classic connection established"
7290
+ "LIVE: CTKD: Successfully bonded - checking Classic audio services"
7212
7291
  )
7213
7292
  markPairingTiming(
7214
7293
  "ctkd_bonded",
@@ -7227,7 +7306,7 @@ class MentraLive : SGCManager() {
7227
7306
  // path does this at GATT connect).
7228
7307
  // markAudioConnected / sendAudioConnected fire
7229
7308
  // when the A2DP path completes.
7230
- connectA2dpProfile(device)
7309
+ prepareClassicAudio(device)
7231
7310
 
7232
7311
  // Safety net: if glasses_ready somehow missed
7233
7312
  // setting fullyBooted, catch up here.
@@ -7264,6 +7343,7 @@ class MentraLive : SGCManager() {
7264
7343
  }
7265
7344
  }
7266
7345
  BluetoothDevice.BOND_NONE -> {
7346
+ classicAudioServiceDiscovery.cancel()
7267
7347
  Bridge.log(
7268
7348
  "LIVE: CTKD: ❌ Bonding failed or removed for device"
7269
7349
  )
@@ -7385,6 +7465,10 @@ class MentraLive : SGCManager() {
7385
7465
  classicAudioReceiver =
7386
7466
  object : BroadcastReceiver() {
7387
7467
  override fun onReceive(context: Context?, intent: Intent?) {
7468
+ if (intent?.action == BluetoothDevice.ACTION_UUID) {
7469
+ intent.bluetoothDeviceExtra()?.let { classicAudioServiceDiscovery.onUuids(it) }
7470
+ return
7471
+ }
7388
7472
  if (intent?.action != BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED &&
7389
7473
  intent?.action != BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) return
7390
7474
  val device = intent.bluetoothDeviceExtra() ?: return
@@ -7401,6 +7485,7 @@ class MentraLive : SGCManager() {
7401
7485
  try {
7402
7486
  val filter =
7403
7487
  IntentFilter().apply {
7488
+ addAction(BluetoothDevice.ACTION_UUID)
7404
7489
  addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED)
7405
7490
  addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)
7406
7491
  }
@@ -7525,10 +7610,10 @@ class MentraLive : SGCManager() {
7525
7610
  when (device.bondState) {
7526
7611
  BluetoothDevice.BOND_BONDED -> {
7527
7612
  Bridge.log(
7528
- "LIVE: CTKD: Device is already bonded - connecting A2DP audio profile"
7613
+ "LIVE: CTKD: Device is already bonded - checking Classic audio services"
7529
7614
  )
7530
7615
  markPairingTiming("ctkd_already_bonded")
7531
- connectA2dpProfile(device)
7616
+ prepareClassicAudio(device)
7532
7617
  }
7533
7618
  BluetoothDevice.BOND_BONDING -> {
7534
7619
  // Secure pairing firmware may request SMP as soon as GATT connects.
@@ -7587,6 +7672,19 @@ class MentraLive : SGCManager() {
7587
7672
  return classicAudioConnectionTracker.connected
7588
7673
  }
7589
7674
 
7675
+ private fun prepareClassicAudio(device: BluetoothDevice) {
7676
+ if (!canConnectClassicAudio(device)) return
7677
+ val gatt = bluetoothGatt
7678
+ classicAudioServiceDiscovery.connectWhenDiscovered(device) {
7679
+ if (bluetoothGatt === gatt && canConnectClassicAudio(device)) connectA2dpProfile(device)
7680
+ }
7681
+ }
7682
+
7683
+ private fun canConnectClassicAudio(device: BluetoothDevice): Boolean =
7684
+ !isKilled && !pairingYieldActive && isConnected && notificationsEnabled &&
7685
+ ctkdInitiatedThisGattSession && connectedDevice?.address == device.address &&
7686
+ device.bondState == BluetoothDevice.BOND_BONDED
7687
+
7590
7688
  /** A2DP profile service listener for connecting to already-bonded devices */
7591
7689
  private val a2dpServiceListener: BluetoothProfile.ServiceListener =
7592
7690
  object : BluetoothProfile.ServiceListener {
@@ -7635,7 +7733,9 @@ class MentraLive : SGCManager() {
7635
7733
  Bridge.log("LIVE: A2DP: Skipping connectA2dpWithProxy — SGC destroyed")
7636
7734
  return
7637
7735
  }
7638
- if (a2dpProfile == null || device == null) {
7736
+ if (device == null || !canConnectClassicAudio(device) ||
7737
+ !ClassicAudioServiceDiscovery.hasAudioSink(device)) return
7738
+ if (a2dpProfile == null) {
7639
7739
  Bridge.log("LIVE: A2DP: Cannot connect - proxy or device is null")
7640
7740
  return
7641
7741
  }
@@ -7685,14 +7785,11 @@ class MentraLive : SGCManager() {
7685
7785
  "LIVE: A2DP: Retry $a2dpConnectAttempts/$A2DP_CONNECT_MAX_ATTEMPTS in " +
7686
7786
  "${A2DP_CONNECT_RETRY_MS}ms ($reason)"
7687
7787
  )
7788
+ val gatt = bluetoothGatt
7688
7789
  handler.postDelayed(
7689
7790
  Runnable {
7690
- if (isKilled || pairingYieldActive || connectedDevice == null) {
7691
- return@Runnable
7692
- }
7693
- val target = connectedDevice ?: return@Runnable
7694
- if (a2dpProfile != null) {
7695
- connectA2dpWithProxy(target)
7791
+ if (bluetoothGatt === gatt && canConnectClassicAudio(device)) {
7792
+ connectA2dpWithProxy(device)
7696
7793
  }
7697
7794
  },
7698
7795
  A2DP_CONNECT_RETRY_MS
@@ -7912,6 +8009,7 @@ class MentraLive : SGCManager() {
7912
8009
 
7913
8010
  // Mark as killed to prevent reconnection attempts
7914
8011
  isKilled = true
8012
+ classicAudioServiceDiscovery.cancel()
7915
8013
  explicitConnectByName = false
7916
8014
  pairingYieldActive = false
7917
8015
  pairingYieldAwaitingReclaim = false
@@ -7933,7 +8031,11 @@ class MentraLive : SGCManager() {
7933
8031
 
7934
8032
  // Tear down Classic (A2DP/HFP) before GATT close. Closing only the proxy left the
7935
8033
  // phone's system Bluetooth UI showing Mentra Live still connected.
7936
- val classicDevice = connectedDevice
8034
+ // BLE loss clears connectedDevice while the OS audio profiles can remain connected.
8035
+ // Use this session's existing Classic target before resetting the tracker below.
8036
+ val classicDevice = connectedDevice ?: classicAudioConnectionTracker.targetForDisconnect()?.let {
8037
+ bluetoothAdapter?.getRemoteDevice(it)
8038
+ }
7937
8039
  disconnectClassicProfiles(classicDevice)
7938
8040
  closeA2dpProxy()
7939
8041
  classicAudioConnectionTracker.reset()
@@ -8010,6 +8112,7 @@ class MentraLive : SGCManager() {
8010
8112
  glassesReadyReceived = false
8011
8113
  audioConnected = false
8012
8114
  ctkdInitiatedThisGattSession = false
8115
+ classicAudioServiceDiscovery.cancel()
8013
8116
  DeviceStore.apply("glasses", "fullyBooted", false)
8014
8117
  updateConnectionState(ConnTypes.DISCONNECTED)
8015
8118
 
@@ -9029,13 +9132,34 @@ class MentraLive : SGCManager() {
9029
9132
  wireHandshakeSentGeneration = -1
9030
9133
  }
9031
9134
 
9135
+ /**
9136
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9137
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9138
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9139
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9140
+ * superseded by the pending exchange, whose answer is still to come.
9141
+ */
9142
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9143
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9144
+
9145
+ private fun resetReadinessExchange() {
9146
+ pendingReadyId = null
9147
+ readyGlassesSessionId = null
9148
+ }
9149
+
9032
9150
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9033
9151
  private fun sendPhoneReady(reason: String) {
9034
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9152
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9153
+ pendingReadyId = readyId
9154
+ Bridge.log(
9155
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
9156
+ "waiting for glasses_ready response"
9157
+ )
9035
9158
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9036
9159
  val readyMsg = JSONObject()
9037
9160
  readyMsg.put("type", "phone_ready")
9038
9161
  readyMsg.put("timestamp", System.currentTimeMillis())
9162
+ readyMsg.put("readyId", readyId)
9039
9163
  sendJson(readyMsg, true)
9040
9164
  }
9041
9165
 
@@ -9497,7 +9621,11 @@ class MentraLive : SGCManager() {
9497
9621
  }
9498
9622
  } else {
9499
9623
  // Normal single message transmission
9500
- transportLog("LIVE: Sending data to glasses: " + wireData, bridgeLogging)
9624
+ transportLog(
9625
+ "LIVE: Sending data to glasses: " +
9626
+ loggableOutgoingPayload(wireData, commandTraceInfo.commandType),
9627
+ bridgeLogging
9628
+ )
9501
9629
 
9502
9630
  // Pack the data using the centralized utility with the negotiated endianness
9503
9631
  val packedData =
@@ -9799,6 +9927,18 @@ class MentraLive : SGCManager() {
9799
9927
  }
9800
9928
  }
9801
9929
 
9930
+ /**
9931
+ * Credentials are sent unchanged but never logged; the BLE trace redacts their fields.
9932
+ */
9933
+ private fun loggableOutgoingPayload(payload: String, commandType: String): String =
9934
+ try {
9935
+ val json = JSONObject(payload)
9936
+ if (json.has("password") || json.has("coreToken")) "<$commandType with credentials omitted>"
9937
+ else payload
9938
+ } catch (_: JSONException) {
9939
+ payload
9940
+ }
9941
+
9802
9942
  private fun summarizeOutgoingMessage(payload: String?): String {
9803
9943
  if (payload == null || payload.isEmpty()) {
9804
9944
  return "type=unknown, requestId=none, appId=none, mode=none, transferMethod=none, bleImgId=none, exposureTimeNs=none, iso=none, mId=none"
@@ -103,7 +103,9 @@ internal object NimoCanvasCodec {
103
103
  require(text.length <= 2048 && '\u0000' !in text)
104
104
  val encoder = Charsets.UTF_8.newEncoder().onMalformedInput(CodingErrorAction.REPORT)
105
105
  .onUnmappableCharacter(CodingErrorAction.REPORT)
106
- val encoded = encoder.encode(CharBuffer.wrap(text))
106
+ // Apply the shared Latin fallback and NIMO's dash fix before counting wire bytes.
107
+ val displayText = sanitizeLatinDisplayText(text, preserveOtherScripts = true).replace('\u2014', '-')
108
+ val encoded = encoder.encode(CharBuffer.wrap(displayText))
107
109
  val utf8 = ByteArray(encoded.remaining()).also { encoded.get(it) }
108
110
  require(utf8.size in 1..2048) { "Label exceeds 2048 UTF-8 bytes" }
109
111
  return Object(3, words(x, y, width, height, language) + bytes(font, intensity) + words(utf8.size) + utf8,
@@ -12,7 +12,61 @@ class BluetoothSdkAnalyticsTrackerTest {
12
12
  model: String = "Mentra Live",
13
13
  serial: String = "",
14
14
  fullyBooted: Boolean = connected,
15
- ) = AnalyticsGlassesSnapshot(connected = connected, fullyBooted = fullyBooted, model = model, serialNumber = serial)
15
+ battery: Int = -1,
16
+ charging: Boolean = false,
17
+ ) = AnalyticsGlassesSnapshot(
18
+ connected = connected,
19
+ fullyBooted = fullyBooted,
20
+ model = model,
21
+ serialNumber = serial,
22
+ batteryLevel = battery,
23
+ charging = charging,
24
+ )
25
+
26
+ @Test
27
+ fun `a counted connection reports its length, reason and battery when it ends`() {
28
+ tracker.initialize(snapshot(connected = false), reportingDay = 100)
29
+ tracker.observe(snapshot(connected = true), reportingDay = 100, nowMs = 1_000)
30
+ tracker.observe(snapshot(connected = true, battery = 80), reportingDay = 100, nowMs = 2_000)
31
+ tracker.observe(snapshot(connected = true, battery = 71, charging = true), reportingDay = 100, nowMs = 3_000)
32
+
33
+ val ended =
34
+ tracker.observe(snapshot(connected = false), reportingDay = 100, nowMs = 61_000) {
35
+ BluetoothSdkAnalyticsTracker.DISCONNECT_USER
36
+ }
37
+ val disconnected = ended.single()
38
+ assertThat(disconnected.name).isEqualTo("bluetooth_sdk_glasses_disconnected")
39
+ assertThat(disconnected.properties)
40
+ .containsEntry("session_duration_ms", 60_000L)
41
+ .containsEntry("disconnect_reason", "user_disconnect")
42
+ .containsEntry("battery_level_at_connect", 80)
43
+ .containsEntry("battery_level_at_disconnect", 71)
44
+ .containsEntry("charging", true)
45
+ .containsEntry("glasses_model", "Mentra Live")
46
+
47
+ // Further disconnected updates do not report the connection again.
48
+ assertThat(tracker.observe(snapshot(connected = false), reportingDay = 100, nowMs = 62_000)).isEmpty()
49
+ }
50
+
51
+ @Test
52
+ fun `a connection already up when the SDK started is not reported as ending`() {
53
+ tracker.initialize(snapshot(connected = true, serial = "MLAB0001"), reportingDay = 100)
54
+ assertThat(tracker.observe(snapshot(connected = false), reportingDay = 100, nowMs = 5_000)).isEmpty()
55
+ }
56
+
57
+ @Test
58
+ fun `battery from a previous connection does not leak into the next one`() {
59
+ tracker.initialize(snapshot(connected = false), reportingDay = 100)
60
+ tracker.observe(snapshot(connected = true, battery = 90), reportingDay = 100, nowMs = 0)
61
+ tracker.observe(snapshot(connected = false), reportingDay = 100, nowMs = 1_000)
62
+ tracker.observe(snapshot(connected = true), reportingDay = 100, nowMs = 2_000)
63
+ val second = tracker.observe(snapshot(connected = false), reportingDay = 100, nowMs = 3_000).single()
64
+ assertThat(second.properties)
65
+ .doesNotContainKey("battery_level_at_connect")
66
+ .doesNotContainKey("battery_level_at_disconnect")
67
+ .doesNotContainKey("charging")
68
+ .containsEntry("disconnect_reason", "unknown")
69
+ }
16
70
 
17
71
  @Test
18
72
  fun `connect then serial emits connected and identified once, reconnects do not repeat identification within a connection`() {
@@ -55,8 +109,9 @@ class BluetoothSdkAnalyticsTrackerTest {
55
109
  tracker.initialize(snapshot(connected = false), reportingDay = 100)
56
110
  tracker.observe(snapshot(connected = true, model = ""), reportingDay = 100)
57
111
  val ended = tracker.observe(snapshot(connected = false, model = ""), reportingDay = 100)
58
- assertThat(ended.single().name).isEqualTo("bluetooth_sdk_glasses_connected")
59
- assertThat(ended.single().properties).containsEntry("glasses_model_unresolved", true).doesNotContainKey("glasses_model")
112
+ assertThat(ended.map { it.name })
113
+ .containsExactly("bluetooth_sdk_glasses_connected", "bluetooth_sdk_glasses_disconnected")
114
+ assertThat(ended.first().properties).containsEntry("glasses_model_unresolved", true).doesNotContainKey("glasses_model")
60
115
  }
61
116
 
62
117
  @Test