@mentra/bluetooth-sdk 3.4.0-dev.957 → 3.4.0-dev.965

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.
@@ -30,6 +30,8 @@ import java.nio.ByteOrder
30
30
  import java.util.Calendar
31
31
  import java.util.TimeZone
32
32
  import java.util.UUID
33
+ import org.json.JSONObject
34
+ import java.util.concurrent.atomic.AtomicInteger
33
35
  import kotlinx.coroutines.Dispatchers
34
36
  import kotlinx.coroutines.runBlocking
35
37
  import kotlinx.coroutines.withContext
@@ -641,6 +643,8 @@ private class NimoAudioClient(
641
643
  private var decoder: NimoOpusDecoder? = null
642
644
  @Volatile private var started = false
643
645
  private val pendingCount = java.util.concurrent.atomic.AtomicInteger(0)
646
+ private val retiringWorkers = AtomicInteger(0)
647
+ fun lifecyclePending(): Int = pendingCount.get() + retiringWorkers.get() + (if (started) 1 else 0)
644
648
  private var droppedCount = 0
645
649
  private var lastRightPacketMs = 0L
646
650
  private var preferRight = true
@@ -676,7 +680,7 @@ private class NimoAudioClient(
676
680
  sendCommand(byteArrayOf(0x52, 0x01, 0x00, 0x00))
677
681
  }
678
682
 
679
- fun stop() {
683
+ @Synchronized fun stop() {
680
684
  if (!started) return
681
685
  // Halt processing and drop in-flight frames BEFORE releasing the decoder —
682
686
  // the glasses keep sending a few frames after the stop command, and decoding
@@ -692,9 +696,9 @@ private class NimoAudioClient(
692
696
  thread = null
693
697
  decoder = null
694
698
  if (h != null) {
699
+ retiringWorkers.incrementAndGet()
695
700
  h.post {
696
- d?.release()
697
- t?.quitSafely()
701
+ try { d?.release(); t?.quitSafely() } finally { retiringWorkers.decrementAndGet() }
698
702
  }
699
703
  } else {
700
704
  d?.release()
@@ -717,7 +721,7 @@ private class NimoAudioClient(
717
721
  }
718
722
  pendingCount.incrementAndGet()
719
723
  h.post {
720
- pendingCount.decrementAndGet()
724
+ pendingCount.updateAndGet { if (it > 0) it - 1 else 0 }
721
725
  process(bytes)
722
726
  }
723
727
  }
@@ -768,8 +772,8 @@ private class NimoAudioClient(
768
772
  }
769
773
  return
770
774
  }
771
- // Any parsed opus packet counts as glasses-audio activity for the watchdog.
772
- onActivity()
775
+ // The owning session may stop while a decoder callback is already running.
776
+ synchronized(this) { if (!started) return; onActivity() }
773
777
 
774
778
  val now = System.currentTimeMillis()
775
779
  when (packet.type) {
@@ -807,7 +811,7 @@ private class NimoAudioClient(
807
811
  }
808
812
  statsFrames++
809
813
  statsPcmBytes += pcm16.size
810
- onPcm(pcm16)
814
+ synchronized(this) { if (!started) return; onPcm(pcm16) }
811
815
  }
812
816
  }
813
817
 
@@ -847,12 +851,15 @@ private class NimoReconnectionManager(
847
851
  private var runnable: Runnable? = null
848
852
  private var attempts = 0
849
853
 
854
+ fun pending(): Boolean = runnable != null
855
+
850
856
  fun start(onAttempt: () -> Boolean) {
851
857
  stop()
852
858
  attempts = 0
853
859
  val r =
854
860
  object : Runnable {
855
861
  override fun run() {
862
+ if (runnable !== this) return
856
863
  if (maxAttempts > 0 && attempts >= maxAttempts) {
857
864
  Bridge.log("NIMO: Max reconnection attempts ($maxAttempts) reached")
858
865
  stop()
@@ -865,7 +872,7 @@ private class NimoReconnectionManager(
865
872
  stop()
866
873
  return
867
874
  }
868
- handler.postDelayed(this, intervalMs)
875
+ if (runnable === this) handler.postDelayed(this, intervalMs)
869
876
  }
870
877
  }
871
878
  runnable = r
@@ -928,6 +935,156 @@ class Nimo : SGCManager() {
928
935
  hasMic = true
929
936
  }
930
937
 
938
+ internal val resourceInstanceId: String = UUID.randomUUID().toString()
939
+ private var resourceSessionGeneration = 0L
940
+ private var resourcePairAddress: String? = null
941
+ private var resourcePairName: String? = null
942
+ private var resourceTwsAt: Long? = null
943
+ private var resourceFirmwareAt: Long? = null
944
+ private var resourceFirmwareVersion: String? = null
945
+ private var resourceHandshakeTwsAt: Long? = null
946
+ private var resourceTimeAckAt: Long? = null
947
+ private var resourceTimeCommandId: String? = null
948
+ private var resourceTimeWriteStartedAt: Long? = null
949
+ @Volatile private var resourceReleasePending = false
950
+ @Volatile private var resourceReceiptPending = false
951
+ @Volatile private var resourceReleased = false
952
+ private val resourcePostedWrites = AtomicInteger(0)
953
+ private var resourceExitStatus: Int? = null
954
+ private var resourceExitAt: Long? = null
955
+ private var resourceMicStopWrittenAt: Long? = null
956
+ private var resourceMicStopStartedAt: Long? = null
957
+ private var resourceMicStopMarkerAt: Long? = null
958
+ private var resourceTransportFailure = false
959
+ private var resourceMicStopRequired = false
960
+ private var resourceExitRequired = false
961
+ private var resourceInitialLaunchPendingAtRelease = false
962
+ private var resourceBondMutationRequested = false
963
+ private var resourceFactoryResetRequested = false
964
+ private var resourceCloseCalled = false
965
+ private var resourceCloseObserved = false
966
+ private var resourceDisconnectCallbackStatus: Int? = null
967
+ private var resourceCloseError: String? = null
968
+ private var resourceClosedWithPending = false
969
+ private var resourceClosingGatt: BluetoothGatt? = null
970
+ private var resourceReleaseResult = "not-requested"
971
+
972
+ internal fun resourceCaptureEligible(): Boolean {
973
+ val snapshot = resourceSnapshot()
974
+ return resourceSessionGeneration == 0L && discoveryReceiver == null &&
975
+ !snapshot.getBoolean("managedSessionPresent") && !snapshot.getBoolean("initializationPending") &&
976
+ !snapshot.getBoolean("reconnectPending") && snapshot.getBoolean("localEffectsSettled") &&
977
+ !resourceReleasePending && !resourceReceiptPending
978
+ }
979
+
980
+ /** Passive local inspection only: no discovery, queries, radio or bond operations. */
981
+ internal fun resourceSnapshot(): JSONObject {
982
+ check(Looper.myLooper() == mainHandler.looper)
983
+ val pending = writes.pendingCount() + canvasEncoder.pendingCount() + audioClient.lifecyclePending() + resourcePostedWrites.get() + pendingAcks.size + canvas.pendingCount()
984
+ return JSONObject().put("observedAtEpochMs", System.currentTimeMillis()).put("sessionObservationCurrent", true).put("instanceId", resourceInstanceId).put("sessionGeneration", resourceSessionGeneration)
985
+ .put("pair", JSONObject().put("name", resourcePairName ?: lastDeviceName ?: JSONObject.NULL)
986
+ .put("bluetoothAddress", resourcePairAddress ?: lastDeviceAddress ?: JSONObject.NULL))
987
+ .put("handshake", handshakeState.name).put("managedSessionPresent", gatt != null)
988
+ .put("reconnectPending", reconnectionManager.pending()).put("initializationPending", handshakeState in listOf(HandshakeState.AWAITING_TWS, HandshakeState.AWAITING_TIME_ACK) || setTimeRetryRunnable != null || pairingTimeoutRunnable != null || bondReceiver != null)
989
+ .put("pending", JSONObject().put("gattWritesAndDescriptors", writes.pendingCount()).put("postedWrites", resourcePostedWrites.get())
990
+ .put("canvasCommands", canvas.pendingCount()).put("canvasEncodes", canvasEncoder.pendingCount())
991
+ .put("audioWorkersAndPackets", audioClient.lifecyclePending()).put("acks", pendingAcks.size))
992
+ .put("localEffectsSettled", pending == 0 && !resourceClosedWithPending)
993
+ .put("firmware", JSONObject().put("version", resourceFirmwareVersion ?: JSONObject.NULL).put("atEpochMs", resourceFirmwareAt ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
994
+ .put("tws", JSONObject().put("handshakeAtEpochMs", resourceHandshakeTwsAt ?: JSONObject.NULL).put("connected", twsConnected).put("atEpochMs", resourceTwsAt ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
995
+ .put("timeAck", JSONObject().put("statusCode", if (resourceTimeAckAt != null) 0 else JSONObject.NULL)
996
+ .put("writeStartedAtEpochMs", resourceTimeWriteStartedAt ?: JSONObject.NULL).put("atEpochMs", resourceTimeAckAt ?: JSONObject.NULL).put("commandId", resourceTimeCommandId ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
997
+ .put("release", JSONObject().put("result", resourceReleaseResult).put("pending", resourceReleasePending)
998
+ .put("micStopRequired", resourceMicStopRequired).put("displayExitRequired", resourceExitRequired).put("micStopStartedAtEpochMs", resourceMicStopStartedAt ?: JSONObject.NULL).put("micStopMarkerAtEpochMs", resourceMicStopMarkerAt ?: JSONObject.NULL).put("micStopWrittenAtEpochMs", resourceMicStopWrittenAt ?: JSONObject.NULL).put("micSilence", "unknown")
999
+ .put("displayExitStatus", resourceExitStatus ?: JSONObject.NULL).put("displayExitAtEpochMs", resourceExitAt ?: JSONObject.NULL)
1000
+ .put("displayVisibleState", "unknown").put("transportFailure", resourceTransportFailure).put("gattCloseCalled", resourceCloseCalled).put("gattDisconnectCallbackObserved", resourceCloseObserved).put("gattDisconnectCallbackStatus", resourceDisconnectCallbackStatus ?: JSONObject.NULL)
1001
+ .put("gattCloseError", resourceCloseError ?: JSONObject.NULL).put("classicAclState", "unknown").put("bondMutationRequested", resourceBondMutationRequested).put("factoryResetRequested", resourceFactoryResetRequested).put("bondState", "unknown"))
1002
+ }
1003
+
1004
+ /** Exact original instance only. Never delegates to the manager's current device. */
1005
+ internal fun releaseResource(expectedGeneration: Long, isCurrent: () -> Boolean, completed: (JSONObject) -> Unit) =
1006
+ releaseOriginalResource(expectedGeneration, false, isCurrent, completed)
1007
+
1008
+ /** Only the private admitted capture may cancel an original pre-GATT generation-zero attempt. */
1009
+ internal fun releaseCapturedResource(isCurrent: () -> Boolean, completed: (JSONObject) -> Unit) =
1010
+ releaseOriginalResource(resourceSessionGeneration, true, isCurrent, completed)
1011
+
1012
+ private fun releaseOriginalResource(expectedGeneration: Long, captured: Boolean, isCurrent: () -> Boolean, completed: (JSONObject) -> Unit) {
1013
+ check(Looper.myLooper() == mainHandler.looper)
1014
+ if (!isCurrent() || expectedGeneration != resourceSessionGeneration || (!captured && expectedGeneration < 1) || resourceReleasePending || resourceReceiptPending) {
1015
+ completed(JSONObject().put("error", "target-mismatch-or-release-pending")); return
1016
+ }
1017
+ if (resourceReleased) { completed(resourceSnapshot()); return }
1018
+ resourceReleasePending = true
1019
+ resourceReleaseResult = "draining"
1020
+ resourceExitStatus = null; resourceExitAt = null; resourceMicStopStartedAt = null; resourceMicStopMarkerAt = null; resourceMicStopWrittenAt = null
1021
+ resourceExitRequired = canvas.active() || canvas.pendingCount() > 0
1022
+ resourceInitialLaunchPendingAtRelease = !canvas.active() && canvas.launchPending()
1023
+ isDisconnecting = true
1024
+ handshakeState = HandshakeState.IDLE
1025
+ cancelPairingTimeout(); cancelTwsTimeout(); cancelSetTimeRetry(); stopTimers(); reconnectionManager.stop()
1026
+ unregisterBondReceiver()
1027
+ // Unregister our discovery listener without stopping the shared adapter scanner.
1028
+ discoveryReceiver?.let { try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {} }
1029
+ discoveryReceiver = null
1030
+ diagnostics?.disconnected()
1031
+ canvasEncoder.invalidate()
1032
+ failAllPendingAcks()
1033
+ audioClient.stop()
1034
+ val original = gatt
1035
+ val mic = micChar
1036
+ resourceMicStopRequired = original != null && mic != null
1037
+ if (original != null && mic != null) {
1038
+ writes.enqueue(original, mic, listOf(byteArrayOf(0x52, 0, 0, 0)), finalStarted = { resourceMicStopStartedAt = System.currentTimeMillis() }, completed = { resourceMicStopWrittenAt = System.currentTimeMillis() })
1039
+ }
1040
+ canvas.exit()
1041
+ val deadline = android.os.SystemClock.elapsedRealtime() + 15_000
1042
+ fun finish(result: String) {
1043
+ resourceReleaseResult = result
1044
+ if (result == "drain-timeout-native-effects-unknown") resourceClosedWithPending = true
1045
+ closeResourceGatt()
1046
+ gatt = null; txChar = null; rxChar = null; micChar = null
1047
+ resetSessionState()
1048
+ resourceReleasePending = false; resourceReleased = true
1049
+ resourceReceiptPending = true
1050
+ // Shared state belongs to this instance only while the manager still owns it.
1051
+ if (isCurrent()) {
1052
+ DeviceStore.apply("glasses", "connected", false)
1053
+ DeviceStore.apply("glasses", "fullyBooted", false)
1054
+ DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
1055
+ }
1056
+ NimoResourceDiagnostics.track(this)
1057
+ mainHandler.postDelayed({
1058
+ // Keep the original bearer/generation fenced through receipt delivery. The
1059
+ // short callback-observation window must not capture a later connection.
1060
+ val originalReceipt = resourceSnapshot()
1061
+ try { completed(originalReceipt) } finally { resourceReceiptPending = false }
1062
+ }, 100)
1063
+ }
1064
+ fun poll() {
1065
+ if (!isCurrent()) {
1066
+ resourceReleasePending = false; resourceReleaseResult = "target-replaced"
1067
+ NimoResourceDiagnostics.track(this); completed(resourceSnapshot()); return
1068
+ }
1069
+ val unsettled = writes.pendingCount() + canvasEncoder.pendingCount() + audioClient.lifecyclePending() + resourcePostedWrites.get() + canvas.pendingCount() +
1070
+ (if (resourceMicStopRequired && resourceMicStopMarkerAt == null) 1 else 0) +
1071
+ (if (resourceExitRequired && resourceExitStatus != 0) 1 else 0)
1072
+ if (unsettled == 0) { finish("local-drained-native-readback-required"); return }
1073
+ if (android.os.SystemClock.elapsedRealtime() >= deadline) { finish("drain-timeout-native-effects-unknown"); return }
1074
+ mainHandler.postDelayed({ poll() }, 25)
1075
+ }
1076
+ mainHandler.post { poll() }
1077
+ }
1078
+
1079
+ private fun closeResourceGatt() {
1080
+ val original = gatt ?: return
1081
+ resourceClosingGatt = original
1082
+ resourceClosedWithPending = resourceClosedWithPending || writes.pendingCount() > 0 || resourcePostedWrites.get() > 0 || canvas.pendingCount() > 0
1083
+ resourceCloseCalled = true
1084
+ try { original.disconnect() } catch (error: Exception) { resourceCloseError = "disconnect-${error.javaClass.simpleName}" }
1085
+ try { original.close() } catch (error: Exception) { resourceCloseError = "close-${error.javaClass.simpleName}" }
1086
+ }
1087
+
931
1088
  private val mainHandler = Handler(Looper.getMainLooper())
932
1089
  private val mainScheduler = handlerScheduler(mainHandler)
933
1090
  // Variant-specific: release has no receiver or framebuffer protocol implementation.
@@ -940,7 +1097,16 @@ class Nimo : SGCManager() {
940
1097
  private val canvas = NimoCanvasCoordinator(mainScheduler,
941
1098
  { (negotiatedMtu - 3).coerceIn(20, 512) }, ::enqueueFrames, ::abortTransport,
942
1099
  { Bridge.log("NIMO: canvas rejected status=$it; not a render ACK") },
943
- { diagnostics?.cancelHeldCapture("Canvas scope takeover preempted held capture", resumeCanvas = false) })
1100
+ { diagnostics?.cancelHeldCapture("Canvas scope takeover preempted held capture", resumeCanvas = false) },
1101
+ { key, status ->
1102
+ if (key == 3) { resourceExitStatus = status; resourceExitAt = System.currentTimeMillis() }
1103
+ if (resourceReleasePending && resourceInitialLaunchPendingAtRelease && key == 1) {
1104
+ // An explicit rejected initial Launch never acquired canvas ownership.
1105
+ // Status 2 is transport-ambiguous and must retain the unknown fence.
1106
+ if (status != 0 && status != 2) resourceExitRequired = false
1107
+ resourceInitialLaunchPendingAtRelease = false
1108
+ }
1109
+ })
944
1110
 
945
1111
  private fun handlerScheduler(handler: Handler) = NimoScheduler { delay, task ->
946
1112
  val runnable = Runnable(task)
@@ -1033,6 +1199,8 @@ class Nimo : SGCManager() {
1033
1199
  // ---------- SGCManager: Connection Management ----------
1034
1200
 
1035
1201
  override fun findCompatibleDevices() {
1202
+ if (NimoResourceDiagnostics.dispatchCapturedEntry { findCompatibleDevices() }) return
1203
+ if (!NimoResourceDiagnostics.admit(this, null, false)) return
1036
1204
  Bridge.log("NIMO: findCompatibleDevices()")
1037
1205
  DEVICE_SEARCH_ID = "NOT_SET"
1038
1206
  DeviceStore.apply("glasses", "connectionState", ConnTypes.SCANNING)
@@ -1040,6 +1208,11 @@ class Nimo : SGCManager() {
1040
1208
  }
1041
1209
 
1042
1210
  override fun connectById(id: String) {
1211
+ if (NimoResourceDiagnostics.dispatchCapturedEntry { connectById(id) }) return
1212
+ if (!NimoResourceDiagnostics.admit(this, id, true)) return
1213
+ if (resourceReleasePending || resourceReceiptPending) return
1214
+ resourceReleased = false
1215
+ resourceBondMutationRequested = false; resourceFactoryResetRequested = false
1043
1216
  Bridge.log("NIMO: connectById($id)")
1044
1217
  DEVICE_SEARCH_ID = id
1045
1218
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
@@ -1099,8 +1272,7 @@ class Nimo : SGCManager() {
1099
1272
  reconnectionManager.stop()
1100
1273
  failAllPendingAcks()
1101
1274
 
1102
- gatt?.disconnect()
1103
- gatt?.close()
1275
+ closeResourceGatt()
1104
1276
  gatt = null
1105
1277
  txChar = null
1106
1278
  rxChar = null
@@ -1110,6 +1282,7 @@ class Nimo : SGCManager() {
1110
1282
  DeviceStore.apply("glasses", "connected", false)
1111
1283
  DeviceStore.apply("glasses", "fullyBooted", false)
1112
1284
  DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
1285
+ NimoResourceDiagnostics.track(this)
1113
1286
  }
1114
1287
 
1115
1288
  /** Explicit Unpair only. Ordinary forget/cleanup must never reset the glasses. */
@@ -1125,6 +1298,7 @@ class Nimo : SGCManager() {
1125
1298
  reconnectionManager.stop()
1126
1299
  canvasEncoder.invalidate()
1127
1300
  canvas.disconnected()
1301
+ resourceFactoryResetRequested = true
1128
1302
  Bridge.log("NIMO: sending factory reset for explicit Unpair")
1129
1303
  sendAwaitingAck(NimoProtocol.CMD_CONTROL_FACTORY, NimoProtocol.FACTORY_RECOVER, byteArrayOf()) {
1130
1304
  Bridge.log("NIMO: factory reset acknowledged=$it")
@@ -1134,6 +1308,7 @@ class Nimo : SGCManager() {
1134
1308
 
1135
1309
  internal fun removeBluetoothBond() {
1136
1310
  val address = gatt?.device?.address ?: lastDeviceAddress ?: return
1311
+ resourceBondMutationRequested = true
1137
1312
  removeBluetoothBond(address)
1138
1313
  }
1139
1314
 
@@ -1181,7 +1356,7 @@ class Nimo : SGCManager() {
1181
1356
  return
1182
1357
  }
1183
1358
  DeviceStore.apply("glasses", "micEnabled", enabled)
1184
- if (enabled) {
1359
+ if (enabled && !resourceReleasePending && !resourceReleased) {
1185
1360
  audioClient.start()
1186
1361
  } else {
1187
1362
  audioClient.stop()
@@ -1312,7 +1487,8 @@ class Nimo : SGCManager() {
1312
1487
 
1313
1488
  private fun encodeCanvas(scope: String, force: Boolean = false, release: () -> Unit = {},
1314
1489
  encode: () -> ByteArray): Boolean =
1315
- canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1490
+ if (resourceReleasePending || resourceReleased) { release(); false }
1491
+ else canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1316
1492
 
1317
1493
  private fun decodeCanvasSource(data: String): Bitmap {
1318
1494
  val bytes = NimoCanvasCodec.imageBytes(data)
@@ -1610,19 +1786,22 @@ class Nimo : SGCManager() {
1610
1786
  * for Companion service 7033. The separate <name>_BLE ANCS peripheral is not the
1611
1787
  * canvas data channel. This matches the vendor transport=BREDR connection path.
1612
1788
  */
1789
+ private data class ResourcePeer(val address: String, val bondState: Int)
1790
+ private fun resourcePeer(device: android.bluetooth.BluetoothDevice): ResourcePeer = ResourcePeer(
1791
+ try { device.address } catch (_: SecurityException) { "" },
1792
+ try { device.bondState } catch (_: SecurityException) { android.bluetooth.BluetoothDevice.BOND_NONE },
1793
+ )
1794
+
1613
1795
  private fun connectCompanionGatt(device: android.bluetooth.BluetoothDevice) {
1796
+ val peer = resourcePeer(device)
1797
+ if (!NimoResourceDiagnostics.allowPeer(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1614
1798
  if (isDisconnecting || gatt != null) return
1615
1799
  // Classic discovery degrades/aborts connections — always cancel first.
1616
1800
  try {
1617
1801
  bluetoothAdapter?.cancelDiscovery()
1618
1802
  } catch (_: Exception) {}
1619
1803
 
1620
- val bondState =
1621
- try {
1622
- device.bondState
1623
- } catch (e: SecurityException) {
1624
- android.bluetooth.BluetoothDevice.BOND_NONE
1625
- }
1804
+ val bondState = peer.bondState
1626
1805
  if (bondState != android.bluetooth.BluetoothDevice.BOND_BONDED) {
1627
1806
  // Bond over classic first, then open the Companion bearer on completion.
1628
1807
  startBond(device)
@@ -1637,12 +1816,9 @@ class Nimo : SGCManager() {
1637
1816
  * called both on the initial attempt and from the BOND_NONE handler.
1638
1817
  */
1639
1818
  private fun startBond(device: android.bluetooth.BluetoothDevice) {
1640
- val bondState =
1641
- try {
1642
- device.bondState
1643
- } catch (e: SecurityException) {
1644
- android.bluetooth.BluetoothDevice.BOND_NONE
1645
- }
1819
+ val peer = resourcePeer(device)
1820
+ if (!NimoResourceDiagnostics.allowPeer(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1821
+ val bondState = peer.bondState
1646
1822
  // A previous (apparently failed) attempt may have bonded in the background.
1647
1823
  if (bondState == android.bluetooth.BluetoothDevice.BOND_BONDED) {
1648
1824
  Bridge.log("NIMO: already bonded with ${device.address} — connecting")
@@ -1683,6 +1859,8 @@ class Nimo : SGCManager() {
1683
1859
 
1684
1860
  private fun connectBredrTransport(device: android.bluetooth.BluetoothDevice) {
1685
1861
  if (isDisconnecting || gatt != null) return
1862
+ val peer = resourcePeer(device)
1863
+ if (!NimoResourceDiagnostics.beginTransport(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1686
1864
  // GATT over BR/EDR: the glasses pair with a legacy (non-SC) link key, so no LE
1687
1865
  // keys exist (le_linkkey_known:F) and the controller records the device as
1688
1866
  // BR_EDR-only — the 7033 UART service is served over the classic link. This is
@@ -1690,14 +1868,26 @@ class Nimo : SGCManager() {
1690
1868
  // why iOS needs Settings pairing (CoreBluetooth bridges GATT over BR/EDR only
1691
1869
  // for system-paired dual-mode accessories).
1692
1870
  Bridge.log("NIMO: connecting GATT over BR/EDR to ${device.address}")
1871
+ resourceSessionGeneration++
1872
+ resourceExitStatus = null; resourceExitAt = null; resourceMicStopWrittenAt = null
1873
+ resourceMicStopStartedAt = null; resourceMicStopMarkerAt = null; resourceTransportFailure = false; resourceClosingGatt = null
1874
+ resourceClosedWithPending = false; resourceReleaseResult = "not-requested"
1875
+ resourceMicStopRequired = false; resourceExitRequired = false; resourceInitialLaunchPendingAtRelease = false
1876
+ resourceReleased = false
1877
+ resourcePairAddress = peer.address
1878
+ resourcePairName = try { device.name ?: "" } catch (_: SecurityException) { "" }
1879
+ resourceFirmwareAt = null; resourceFirmwareVersion = null
1880
+ resourceTwsAt = null; resourceHandshakeTwsAt = null; resourceTimeAckAt = null; resourceTimeCommandId = null; resourceTimeWriteStartedAt = null
1881
+ resourceCloseCalled = false; resourceCloseObserved = false; resourceDisconnectCallbackStatus = null; resourceCloseError = null
1882
+ NimoResourceDiagnostics.track(this)
1693
1883
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
1694
- gatt =
1695
- device.connectGatt(
1696
- context,
1697
- false,
1698
- gattCallback,
1699
- android.bluetooth.BluetoothDevice.TRANSPORT_BREDR
1700
- )
1884
+ gatt = try {
1885
+ device.connectGatt(context, false, gattCallback, android.bluetooth.BluetoothDevice.TRANSPORT_BREDR)
1886
+ } catch (error: SecurityException) {
1887
+ resourceTransportFailure = true
1888
+ Bridge.log("NIMO: connectGatt SecurityException: ${error.message}")
1889
+ null
1890
+ }
1701
1891
  gatt?.let { writes.connected(it) }
1702
1892
  }
1703
1893
 
@@ -1826,9 +2016,16 @@ class Nimo : SGCManager() {
1826
2016
  object : BluetoothGattCallback() {
1827
2017
  override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
1828
2018
  mainHandler.post {
1829
- if (g !== gatt) return@post
2019
+ if (g !== gatt) {
2020
+ if (g === resourceClosingGatt && newState == BluetoothProfile.STATE_DISCONNECTED) {
2021
+ resourceCloseObserved = true
2022
+ resourceDisconnectCallbackStatus = status
2023
+ }
2024
+ return@post
2025
+ }
1830
2026
  Bridge.log("NIMO: onConnectionStateChange status=$status newState=$newState")
1831
2027
  if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
2028
+ if (isDisconnecting) return@post
1832
2029
  Bridge.log("NIMO: Connected to ${g.device?.name ?: "unknown"}")
1833
2030
  lastDeviceAddress = g.device?.address
1834
2031
  // Do NOT request a large MTU here: the vendor transport warns that
@@ -1877,6 +2074,7 @@ class Nimo : SGCManager() {
1877
2074
  }
1878
2075
  mainHandler.post {
1879
2076
  if (g !== gatt) return@post
2077
+ if (isDisconnecting) return@post
1880
2078
  val service = g.getService(NimoBLE.SERVICE_UUID)
1881
2079
  if (service == null) {
1882
2080
  // Dump everything so a UUID mismatch is diagnosable from logs.
@@ -1922,7 +2120,11 @@ class Nimo : SGCManager() {
1922
2120
  NimoBLE.CHAR_RX -> if (characteristic.service?.uuid == NimoBLE.SERVICE_UUID) {
1923
2121
  handleRxPacket(data)
1924
2122
  }
1925
- NimoBLE.CHAR_MIC -> audioClient.enqueue(data)
2123
+ NimoBLE.CHAR_MIC -> {
2124
+ if (resourceReleasePending && resourceMicStopStartedAt != null && data.contentEquals(byteArrayOf(0x52, 0, 0, 0)))
2125
+ resourceMicStopMarkerAt = System.currentTimeMillis()
2126
+ audioClient.enqueue(data)
2127
+ }
1926
2128
  }
1927
2129
  }
1928
2130
  }
@@ -1971,9 +2173,15 @@ class Nimo : SGCManager() {
1971
2173
 
1972
2174
  private fun enqueueWrite(char: BluetoothGattCharacteristic, bytes: ByteArray) {
1973
2175
  val expectedGatt = gatt ?: return
2176
+ val timeCommand = if (bytes.size >= 10 && (bytes[8].toInt() and 255) == NimoProtocol.CMD_SET_PARAMETER &&
2177
+ (bytes[9].toInt() and 255) == NimoProtocol.SET_TIME) resourceTimeCommandId else null
2178
+ resourcePostedWrites.incrementAndGet()
1974
2179
  mainHandler.post {
1975
- if (gatt !== expectedGatt) return@post
1976
- writes.enqueue(expectedGatt, char, listOf(bytes))
2180
+ resourcePostedWrites.decrementAndGet()
2181
+ if (gatt !== expectedGatt || resourceReleasePending || resourceReleased) return@post
2182
+ writes.enqueue(expectedGatt, char, listOf(bytes), finalStarted = {
2183
+ if (timeCommand != null && timeCommand == resourceTimeCommandId) resourceTimeWriteStartedAt = System.currentTimeMillis()
2184
+ })
1977
2185
  }
1978
2186
  }
1979
2187
 
@@ -1992,11 +2200,12 @@ class Nimo : SGCManager() {
1992
2200
 
1993
2201
  private fun abortTransport(reason: String) {
1994
2202
  Bridge.log("NIMO: resetting transport: $reason")
1995
- val old = gatt
2203
+ resourceTransportFailure = true
2204
+ resourceClosedWithPending = true
2205
+ closeResourceGatt()
1996
2206
  gatt = null
1997
2207
  txChar = null; rxChar = null; micChar = null
1998
2208
  resetSessionState()
1999
- try { old?.disconnect(); old?.close() } catch (_: Exception) {}
2000
2209
  DeviceStore.apply("glasses", "connected", false)
2001
2210
  DeviceStore.apply("glasses", "fullyBooted", false)
2002
2211
  DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
@@ -2050,6 +2259,7 @@ class Nimo : SGCManager() {
2050
2259
  // ---------- Handshake ----------
2051
2260
 
2052
2261
  private fun startHandshake() {
2262
+ if (isDisconnecting || resourceReleasePending || resourceReleased) return
2053
2263
  Bridge.log("NIMO: starting handshake (awaiting TWS service-connection state)")
2054
2264
  handshakeState = HandshakeState.AWAITING_TWS
2055
2265
  if (twsConnected) {
@@ -2075,10 +2285,16 @@ class Nimo : SGCManager() {
2075
2285
  }
2076
2286
 
2077
2287
  private var setTimeAttempts = 0
2288
+ private var setTimeRetryRunnable: Runnable? = null
2289
+ private fun cancelSetTimeRetry() {
2290
+ setTimeRetryRunnable?.let(mainHandler::removeCallbacks)
2291
+ setTimeRetryRunnable = null
2292
+ }
2078
2293
 
2079
2294
  private fun proceedToTimeSync() {
2080
2295
  if (handshakeState != HandshakeState.AWAITING_TWS) return
2081
2296
  cancelTwsTimeout()
2297
+ resourceHandshakeTwsAt = resourceTwsAt
2082
2298
  handshakeState = HandshakeState.AWAITING_TIME_ACK
2083
2299
  Bridge.log("NIMO: TWS OK — sending setTime (awaiting ACK)")
2084
2300
  setTimeAttempts = 0
@@ -2089,13 +2305,21 @@ class Nimo : SGCManager() {
2089
2305
  if (handshakeState != HandshakeState.AWAITING_TIME_ACK || gatt == null) return
2090
2306
  val expectedGatt = gatt
2091
2307
  setTimeAttempts++
2308
+ resourceTimeCommandId = UUID.randomUUID().toString()
2309
+ resourceTimeWriteStartedAt = null
2092
2310
  sendAwaitingAck(
2093
2311
  NimoProtocol.CMD_SET_PARAMETER,
2094
2312
  NimoProtocol.SET_TIME,
2095
2313
  NimoFrameCodec.encodeDeviceTime()
2096
2314
  ) { ok ->
2097
2315
  if (gatt !== expectedGatt || handshakeState != HandshakeState.AWAITING_TIME_ACK) return@sendAwaitingAck
2316
+ if (ok && resourceTimeWriteStartedAt == null) {
2317
+ resourceTransportFailure = true
2318
+ handshakeFailed()
2319
+ return@sendAwaitingAck
2320
+ }
2098
2321
  if (ok) {
2322
+ resourceTimeAckAt = System.currentTimeMillis()
2099
2323
  finishHandshake()
2100
2324
  } else if (setTimeAttempts < SET_TIME_MAX_ATTEMPTS &&
2101
2325
  handshakeState == HandshakeState.AWAITING_TIME_ACK &&
@@ -2104,7 +2328,12 @@ class Nimo : SGCManager() {
2104
2328
  // The firmware can answer "busy" right after the link comes up —
2105
2329
  // give it a moment and retry instead of dropping the connection.
2106
2330
  Bridge.log("NIMO: setTime attempt $setTimeAttempts failed — retrying")
2107
- mainHandler.postDelayed({ if (gatt === expectedGatt) attemptSetTime() }, SET_TIME_RETRY_DELAY_MS)
2331
+ val retry = Runnable {
2332
+ setTimeRetryRunnable = null
2333
+ if (gatt === expectedGatt) attemptSetTime()
2334
+ }
2335
+ setTimeRetryRunnable = retry
2336
+ mainHandler.postDelayed(retry, SET_TIME_RETRY_DELAY_MS)
2108
2337
  } else {
2109
2338
  Bridge.log("NIMO: setTime failed after $setTimeAttempts attempts — handshake failed")
2110
2339
  handshakeFailed()
@@ -2161,6 +2390,7 @@ class Nimo : SGCManager() {
2161
2390
  diagnostics?.disconnected()
2162
2391
  handshakeState = HandshakeState.IDLE
2163
2392
  cancelTwsTimeout()
2393
+ cancelSetTimeRetry()
2164
2394
  twsConnected = false
2165
2395
  peerCompanionReady = null
2166
2396
  canvasEncoder.invalidate()
@@ -2182,6 +2412,7 @@ class Nimo : SGCManager() {
2182
2412
  if (fullyBooted) {
2183
2413
  return@start true
2184
2414
  }
2415
+ if (!NimoResourceDiagnostics.admit(this, DEVICE_SEARCH_ID, true)) return@start true
2185
2416
  Bridge.log("NIMO: Attempting reconnection...")
2186
2417
  isDisconnecting = false
2187
2418
  // Each reconnection cycle is a fresh bond budget — the glasses drop their
@@ -2313,6 +2544,7 @@ class Nimo : SGCManager() {
2313
2544
  }
2314
2545
 
2315
2546
  private fun onTwsState(connected: Boolean) {
2547
+ resourceTwsAt = System.currentTimeMillis()
2316
2548
  twsConnected = connected
2317
2549
  if (connected && handshakeState == HandshakeState.AWAITING_TWS) {
2318
2550
  proceedToTimeSync()
@@ -2385,6 +2617,7 @@ class Nimo : SGCManager() {
2385
2617
  val micro = (v ushr 12) and 0x1FF
2386
2618
  val build = v and 0xFFF
2387
2619
  firmwareVersionPacked = "$major.$minor.$micro.$build"
2620
+ resourceFirmwareVersion = firmwareVersionPacked; resourceFirmwareAt = System.currentTimeMillis()
2388
2621
  emitVersionInfo()
2389
2622
  }
2390
2623
  }
@@ -2392,6 +2625,9 @@ class Nimo : SGCManager() {
2392
2625
  var end = data.size
2393
2626
  while (end > 0 && data[end - 1].toInt() == 0) end--
2394
2627
  firmwareVersionDetail = String(data, 0, end, Charsets.UTF_8).trim()
2628
+ if (firmwareVersionDetail.isNotEmpty() && firmwareVersionDetail.length <= 240) {
2629
+ resourceFirmwareVersion = firmwareVersionDetail; resourceFirmwareAt = System.currentTimeMillis()
2630
+ }
2395
2631
  emitVersionInfo()
2396
2632
  }
2397
2633
  NimoProtocol.GET_TWS_STATUS -> {
@@ -25,6 +25,8 @@ internal class NimoGattQueue<C : Any>(
25
25
  private var descriptorCompletion: (() -> Unit)? = null
26
26
  private var cancelDeadline: (() -> Unit)? = null
27
27
 
28
+ fun pendingCount(): Int = queue.size + (if (current != null) 1 else 0) + (if (descriptor != null) 1 else 0)
29
+
28
30
  fun connected(connection: Any) { reset(); this.connection = connection }
29
31
 
30
32
  fun reset() {
@@ -120,6 +122,7 @@ internal class NimoCanvasCoordinator(
120
122
  private val reconnect: (String) -> Unit,
121
123
  private val rejected: (Int) -> Unit = {},
122
124
  private val holdPreempted: () -> Unit = {},
125
+ private val businessResponse: (Int, Int) -> Unit = { _, _ -> },
123
126
  ) {
124
127
  private class Flight(val action: NimoCanvasSession.Action.Send) {
125
128
  var finalStarted = false
@@ -134,6 +137,10 @@ internal class NimoCanvasCoordinator(
134
137
  private var cancelDeadline: (() -> Unit)? = null
135
138
  private var cancelRetry: (() -> Unit)? = null
136
139
 
140
+ fun pendingCount(): Int = if (flight != null) 1 else 0
141
+ fun active(): Boolean = session.active()
142
+ fun launchPending(): Boolean = flight?.action?.key == 1
143
+
137
144
  fun offer(bytes: ByteArray, scope: String, force: Boolean = false) {
138
145
  if (holding && scope != heldScope) {
139
146
  releaseHold(resume = false)
@@ -188,6 +195,7 @@ internal class NimoCanvasCoordinator(
188
195
  }
189
196
  cancelDeadline?.invoke(); cancelDeadline = null
190
197
  flight = null
198
+ businessResponse(key, payload[0].toInt() and 255)
191
199
  run(session.response(key, payload))
192
200
  notifyHoldReadyIfIdle()
193
201
  }
@@ -14,6 +14,10 @@ internal class NimoCanvasEncoder(
14
14
  private var generation = 0L
15
15
  private var pending: Request? = null
16
16
  private var closed = false
17
+ private var running = 0
18
+ private var deliveries = 0
19
+
20
+ @Synchronized fun pendingCount(): Int = (if (pending != null) 1 else 0) + running + deliveries
17
21
 
18
22
  @Synchronized
19
23
  fun submit(encode: () -> ByteArray, release: () -> Unit = {}, deliver: (ByteArray) -> Unit): Boolean {
@@ -44,15 +48,18 @@ internal class NimoCanvasEncoder(
44
48
  synchronized(this) {
45
49
  if (pending !== request) return
46
50
  pending = null // Running work releases its own source, never the invalidator.
51
+ running++
47
52
  }
48
53
  try {
49
54
  val bytes = request.encode()
55
+ synchronized(this) { deliveries++ }
50
56
  main.post(0) {
51
57
  synchronized(this) {
58
+ deliveries--
52
59
  if (!closed && generation == request.generation) request.deliver(bytes)
53
60
  }
54
61
  }
55
62
  } catch (error: Exception) { failed(error) }
56
- finally { request.release() }
63
+ finally { request.release(); synchronized(this) { running-- } }
57
64
  }
58
65
  }