@mentra/bluetooth-sdk 3.3.0-dev.944 → 3.4.0-dev.1004

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 (100) hide show
  1. package/MIGRATION.md +61 -0
  2. package/README.md +78 -0
  3. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +274 -0
  4. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +13 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +8 -1
  6. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +79 -8
  7. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +21 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +1 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +22 -4
  11. package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
  12. package/android/src/main/java/com/mentra/bluetoothsdk/connection/ConnectionModels.kt +5 -0
  13. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicy.kt +64 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +832 -134
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +227 -0
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisement.kt +19 -0
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicy.kt +94 -0
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachine.kt +411 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateStore.kt +124 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +337 -39
  21. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +8 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +8 -1
  23. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +1 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/status/DeviceStatus.kt +50 -0
  25. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +16 -0
  26. package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerOwnerLossTest.kt +146 -0
  27. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusAudioSetupTest.kt +51 -0
  28. package/android/src/test/java/com/mentra/bluetoothsdk/GlassesStatusClassicAudioTest.kt +2 -0
  29. package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
  30. package/android/src/test/java/com/mentra/bluetoothsdk/WifiAdbPeerIntentTest.kt +19 -0
  31. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/GlassesAudioSetupPolicyTest.kt +65 -0
  32. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveAudioSetupReadinessTest.kt +231 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +368 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingAdvertisementParserTest.kt +20 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingReadinessPolicyTest.kt +136 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingStateMachineTest.kt +346 -0
  37. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +564 -1
  38. package/build/BluetoothSdk.types.d.ts +110 -2
  39. package/build/BluetoothSdk.types.d.ts.map +1 -1
  40. package/build/BluetoothSdk.types.js.map +1 -1
  41. package/build/_private/BluetoothSdkModule.d.ts +6 -2
  42. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  43. package/build/_private/BluetoothSdkModule.js +1 -0
  44. package/build/_private/BluetoothSdkModule.js.map +1 -1
  45. package/build/generated/changelogCatalog.d.ts +3 -0
  46. package/build/generated/changelogCatalog.d.ts.map +1 -1
  47. package/build/generated/changelogCatalog.js +4 -0
  48. package/build/generated/changelogCatalog.js.map +1 -1
  49. package/build/generated/releaseMetadata.js +6 -6
  50. package/build/generated/releaseMetadata.js.map +1 -1
  51. package/build/index.d.ts +1 -1
  52. package/build/index.d.ts.map +1 -1
  53. package/build/index.js +4 -0
  54. package/build/index.js.map +1 -1
  55. package/ios/BluetoothSdkModule.swift +24 -4
  56. package/ios/Source/BluetoothSdkDefaults.swift +1 -1
  57. package/ios/Source/Bridge.swift +11 -3
  58. package/ios/Source/DeviceManager.swift +103 -7
  59. package/ios/Source/DeviceStore.swift +27 -0
  60. package/ios/Source/GeneratedChangelogCatalog.swift +1 -0
  61. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  62. package/ios/Source/MentraBluetoothSDK.swift +41 -7
  63. package/ios/Source/TouchGesture.swift +13 -0
  64. package/ios/Source/errors/BluetoothSdkError.swift +5 -1
  65. package/ios/Source/events/BluetoothEvents.swift +4 -0
  66. package/ios/Source/internal/BleTraceLogger.swift +9 -6
  67. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +181 -0
  68. package/ios/Source/sgcs/MentraLive.swift +1196 -173
  69. package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +260 -1
  70. package/ios/Source/sgcs/MentraLivePairingStateMachine.swift +385 -0
  71. package/ios/Source/sgcs/MentraLivePairingStateStore.swift +121 -0
  72. package/ios/Source/sgcs/Nimo.swift +278 -38
  73. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +77 -18
  74. package/ios/Source/sgcs/NimoCanvasSession.swift +1 -0
  75. package/ios/Source/sgcs/NimoMacResourceTransport.swift +217 -0
  76. package/ios/Source/sgcs/NimoResourceFixture.swift +384 -0
  77. package/ios/Source/sgcs/NimoResourceSession.swift +406 -0
  78. package/ios/Source/sgcs/SGCManager.swift +7 -0
  79. package/ios/Source/sgcs/Simulated.swift +2 -0
  80. package/ios/Source/status/DeviceStatus.swift +35 -0
  81. package/ios/Source/types/DeviceModels.swift +8 -1
  82. package/ios/Source/utils/AudioSessionMonitor.swift +158 -5
  83. package/ios/Tests/BluetoothAudioRouteTests.swift +82 -0
  84. package/ios/Tests/DeviceManagerReconnectTests.swift +75 -2
  85. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +191 -0
  86. package/ios/Tests/MentraLiveAudioSetupTests.swift +215 -0
  87. package/ios/Tests/MentraLiveConnectionOptionsTests.swift +55 -0
  88. package/ios/Tests/MentraLivePairingAdvertisementTests.swift +327 -0
  89. package/ios/Tests/MentraLivePairingStateMachineTests.swift +402 -0
  90. package/ios/Tests/MentraLiveSessionReadinessTests.swift +328 -26
  91. package/ios/Tests/NimoCanvasTransportTests.swift +147 -0
  92. package/ios/Tests/NimoResourceSessionTests.swift +476 -0
  93. package/ios/Tests/TouchGestureCommandTests.swift +87 -0
  94. package/ios/Tests/WifiAdbDispatchTests.swift +118 -0
  95. package/package.json +3 -2
  96. package/src/BluetoothSdk.types.ts +115 -1
  97. package/src/_private/BluetoothSdkModule.ts +7 -1
  98. package/src/generated/changelogCatalog.ts +4 -0
  99. package/src/generated/releaseMetadata.ts +6 -6
  100. package/src/index.ts +12 -0
@@ -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,215 @@ 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
+ private var resourceCaptureNonce: String? = null
973
+ private var resourceArmedElapsedMs: Long? = null
974
+ private var resourceAdmittedElapsedMs: Long? = null
975
+ private var resourceSessionStartedElapsedMs: Long? = null
976
+ private var resourceReleaseNonce: String? = null
977
+ private var resourceReleaseStartedElapsedMs: Long? = null
978
+ private var firmwareElapsedMs: Long? = null
979
+ private var twsElapsedMs: Long? = null
980
+ private var handshakeTwsElapsedMs: Long? = null
981
+ private var timeWriteStartedElapsedMs: Long? = null
982
+ private var timeAckElapsedMs: Long? = null
983
+ private var micStopStartedElapsedMs: Long? = null
984
+ private var micStopMarkerElapsedMs: Long? = null
985
+ private var micStopWrittenElapsedMs: Long? = null
986
+ private var displayExitElapsedMs: Long? = null
987
+
988
+ // Keep paired clock sampling in this class even when the triggering callback
989
+ // is an escaping Kotlin lambda. This preserves event timing and permits APK
990
+ // bytecode inspection without treating an unrelated elapsed clock call as proof.
991
+ private fun recordResourceFirmwareClock() { resourceFirmwareAt = System.currentTimeMillis(); firmwareElapsedMs = android.os.SystemClock.elapsedRealtime() }
992
+ private fun recordResourceTwsClock() { resourceTwsAt = System.currentTimeMillis(); twsElapsedMs = android.os.SystemClock.elapsedRealtime() }
993
+ private fun recordResourceTimeWriteClock() { resourceTimeWriteStartedAt = System.currentTimeMillis(); timeWriteStartedElapsedMs = android.os.SystemClock.elapsedRealtime() }
994
+ private fun recordResourceTimeAckClock() { resourceTimeAckAt = System.currentTimeMillis(); timeAckElapsedMs = android.os.SystemClock.elapsedRealtime() }
995
+ private fun recordResourceMicStopStartedClock() { resourceMicStopStartedAt = System.currentTimeMillis(); micStopStartedElapsedMs = android.os.SystemClock.elapsedRealtime() }
996
+ private fun recordResourceMicStopMarkerClock() { resourceMicStopMarkerAt = System.currentTimeMillis(); micStopMarkerElapsedMs = android.os.SystemClock.elapsedRealtime() }
997
+ private fun recordResourceMicStopWrittenClock() { resourceMicStopWrittenAt = System.currentTimeMillis(); micStopWrittenElapsedMs = android.os.SystemClock.elapsedRealtime() }
998
+ private fun recordResourceExitClock() { resourceExitAt = System.currentTimeMillis(); displayExitElapsedMs = android.os.SystemClock.elapsedRealtime() }
999
+
1000
+ internal fun resourceCaptureAdmission(nonce: String, armed: Long, admitted: Long) {
1001
+ check(Looper.myLooper() == mainHandler.looper)
1002
+ check(resourceCaptureNonce == null && admitted >= armed)
1003
+ resourceCaptureNonce = nonce; resourceArmedElapsedMs = armed; resourceAdmittedElapsedMs = admitted
1004
+ }
1005
+
1006
+ internal fun resourceCaptureEligible(): Boolean {
1007
+ val snapshot = resourceSnapshot()
1008
+ return resourceSessionGeneration == 0L && discoveryReceiver == null &&
1009
+ !snapshot.getBoolean("managedSessionPresent") && !snapshot.getBoolean("initializationPending") &&
1010
+ !snapshot.getBoolean("reconnectPending") && snapshot.getBoolean("localEffectsSettled") &&
1011
+ !resourceReleasePending && !resourceReceiptPending
1012
+ }
1013
+
1014
+ /** Passive local inspection only: no discovery, queries, radio or bond operations. */
1015
+ internal fun resourceSnapshot(): JSONObject {
1016
+ check(Looper.myLooper() == mainHandler.looper)
1017
+ val pending = writes.pendingCount() + canvasEncoder.pendingCount() + audioClient.lifecyclePending() + resourcePostedWrites.get() + pendingAcks.size + canvas.pendingCount()
1018
+ return JSONObject().put("observedAtEpochMs", System.currentTimeMillis()).put("sessionObservationCurrent", true).put("instanceId", resourceInstanceId).put("sessionGeneration", resourceSessionGeneration)
1019
+ .put("clock", JSONObject().put("kind", "android-elapsed-realtime-v1").put("observedElapsedMs", android.os.SystemClock.elapsedRealtime())
1020
+ .put("captureNonce", resourceCaptureNonce ?: JSONObject.NULL).put("armedElapsedMs", resourceArmedElapsedMs ?: JSONObject.NULL)
1021
+ .put("admittedElapsedMs", resourceAdmittedElapsedMs ?: JSONObject.NULL).put("sessionStartedElapsedMs", resourceSessionStartedElapsedMs ?: JSONObject.NULL)
1022
+ .put("releaseNonce", resourceReleaseNonce ?: JSONObject.NULL).put("releaseStartedElapsedMs", resourceReleaseStartedElapsedMs ?: JSONObject.NULL)
1023
+ .put("firmwareElapsedMs", firmwareElapsedMs ?: JSONObject.NULL)
1024
+ .put("twsElapsedMs", twsElapsedMs ?: JSONObject.NULL)
1025
+ .put("handshakeTwsElapsedMs", handshakeTwsElapsedMs ?: JSONObject.NULL)
1026
+ .put("timeWriteStartedElapsedMs", timeWriteStartedElapsedMs ?: JSONObject.NULL)
1027
+ .put("timeAckElapsedMs", timeAckElapsedMs ?: JSONObject.NULL)
1028
+ .put("micStopStartedElapsedMs", micStopStartedElapsedMs ?: JSONObject.NULL)
1029
+ .put("micStopMarkerElapsedMs", micStopMarkerElapsedMs ?: JSONObject.NULL)
1030
+ .put("micStopWrittenElapsedMs", micStopWrittenElapsedMs ?: JSONObject.NULL)
1031
+ .put("displayExitElapsedMs", displayExitElapsedMs ?: JSONObject.NULL)
1032
+ )
1033
+ .put("pair", JSONObject().put("name", resourcePairName ?: lastDeviceName ?: JSONObject.NULL)
1034
+ .put("bluetoothAddress", resourcePairAddress ?: lastDeviceAddress ?: JSONObject.NULL))
1035
+ .put("handshake", handshakeState.name).put("managedSessionPresent", gatt != null)
1036
+ .put("reconnectPending", reconnectionManager.pending()).put("initializationPending", handshakeState in listOf(HandshakeState.AWAITING_TWS, HandshakeState.AWAITING_TIME_ACK) || setTimeRetryRunnable != null || pairingTimeoutRunnable != null || bondReceiver != null)
1037
+ .put("pending", JSONObject().put("gattWritesAndDescriptors", writes.pendingCount()).put("postedWrites", resourcePostedWrites.get())
1038
+ .put("canvasCommands", canvas.pendingCount()).put("canvasEncodes", canvasEncoder.pendingCount())
1039
+ .put("audioWorkersAndPackets", audioClient.lifecyclePending()).put("acks", pendingAcks.size))
1040
+ .put("localEffectsSettled", pending == 0 && !resourceClosedWithPending)
1041
+ .put("firmware", JSONObject().put("version", resourceFirmwareVersion ?: JSONObject.NULL).put("atEpochMs", resourceFirmwareAt ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
1042
+ .put("tws", JSONObject().put("handshakeAtEpochMs", resourceHandshakeTwsAt ?: JSONObject.NULL).put("connected", twsConnected).put("atEpochMs", resourceTwsAt ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
1043
+ .put("timeAck", JSONObject().put("statusCode", if (resourceTimeAckAt != null) 0 else JSONObject.NULL)
1044
+ .put("writeStartedAtEpochMs", resourceTimeWriteStartedAt ?: JSONObject.NULL).put("atEpochMs", resourceTimeAckAt ?: JSONObject.NULL).put("commandId", resourceTimeCommandId ?: JSONObject.NULL).put("sessionGeneration", resourceSessionGeneration))
1045
+ .put("release", JSONObject().put("result", resourceReleaseResult).put("pending", resourceReleasePending)
1046
+ .put("micStopRequired", resourceMicStopRequired).put("displayExitRequired", resourceExitRequired).put("micStopStartedAtEpochMs", resourceMicStopStartedAt ?: JSONObject.NULL).put("micStopMarkerAtEpochMs", resourceMicStopMarkerAt ?: JSONObject.NULL).put("micStopWrittenAtEpochMs", resourceMicStopWrittenAt ?: JSONObject.NULL).put("micSilence", "unknown")
1047
+ .put("displayExitStatus", resourceExitStatus ?: JSONObject.NULL).put("displayExitAtEpochMs", resourceExitAt ?: JSONObject.NULL)
1048
+ .put("displayVisibleState", "unknown").put("transportFailure", resourceTransportFailure).put("gattCloseCalled", resourceCloseCalled).put("gattDisconnectCallbackObserved", resourceCloseObserved).put("gattDisconnectCallbackStatus", resourceDisconnectCallbackStatus ?: JSONObject.NULL)
1049
+ .put("gattCloseError", resourceCloseError ?: JSONObject.NULL).put("classicAclState", "unknown").put("bondMutationRequested", resourceBondMutationRequested).put("factoryResetRequested", resourceFactoryResetRequested).put("bondState", "unknown"))
1050
+ }
1051
+
1052
+ /** Exact original instance only. Never delegates to the manager's current device. */
1053
+ internal fun releaseResource(expectedGeneration: Long, isCurrent: () -> Boolean, completed: (JSONObject) -> Unit) =
1054
+ releaseOriginalResource(expectedGeneration, false, isCurrent, completed, null, null)
1055
+
1056
+ internal fun releaseResource(expectedGeneration: Long, isCurrent: () -> Boolean, completed: (JSONObject) -> Unit, requestNonce: String, requestReceivedElapsedMs: Long) =
1057
+ releaseOriginalResource(expectedGeneration, false, isCurrent, completed, requestNonce, requestReceivedElapsedMs)
1058
+
1059
+ /** Only the private admitted capture may cancel an original pre-GATT generation-zero attempt. */
1060
+ internal fun releaseCapturedResource(isCurrent: () -> Boolean, completed: (JSONObject) -> Unit) =
1061
+ releaseOriginalResource(resourceSessionGeneration, true, isCurrent, completed, null, null)
1062
+
1063
+ internal fun releaseCapturedResource(isCurrent: () -> Boolean, completed: (JSONObject) -> Unit, requestNonce: String, requestReceivedElapsedMs: Long) =
1064
+ releaseOriginalResource(resourceSessionGeneration, true, isCurrent, completed, requestNonce, requestReceivedElapsedMs)
1065
+
1066
+ private fun releaseOriginalResource(expectedGeneration: Long, captured: Boolean, isCurrent: () -> Boolean, completed: (JSONObject) -> Unit, requestNonce: String?, requestReceivedElapsedMs: Long?) {
1067
+ check(Looper.myLooper() == mainHandler.looper)
1068
+ if (!isCurrent() || expectedGeneration != resourceSessionGeneration || (!captured && expectedGeneration < 1) || resourceReleasePending || resourceReceiptPending) {
1069
+ completed(JSONObject().put("error", "target-mismatch-or-release-pending")); return
1070
+ }
1071
+ if (resourceReleased) { completed(resourceSnapshot()); return }
1072
+ if (requestReceivedElapsedMs != null && android.os.SystemClock.elapsedRealtime() < requestReceivedElapsedMs) {
1073
+ completed(JSONObject().put("error", "invalid-request-clock")); return
1074
+ }
1075
+ resourceReleaseNonce = requestNonce
1076
+ resourceReleaseStartedElapsedMs = android.os.SystemClock.elapsedRealtime()
1077
+ resourceReleasePending = true
1078
+ resourceReleaseResult = "draining"
1079
+ resourceExitStatus = null; resourceExitAt = null; displayExitElapsedMs = null; resourceMicStopStartedAt = null; micStopStartedElapsedMs = null; resourceMicStopMarkerAt = null; micStopMarkerElapsedMs = null; resourceMicStopWrittenAt = null; micStopWrittenElapsedMs = null
1080
+ resourceExitRequired = canvas.active() || canvas.pendingCount() > 0
1081
+ resourceInitialLaunchPendingAtRelease = !canvas.active() && canvas.launchPending()
1082
+ isDisconnecting = true
1083
+ handshakeState = HandshakeState.IDLE
1084
+ cancelPairingTimeout(); cancelTwsTimeout(); cancelSetTimeRetry(); stopTimers(); reconnectionManager.stop()
1085
+ unregisterBondReceiver()
1086
+ // Unregister our discovery listener without stopping the shared adapter scanner.
1087
+ discoveryReceiver?.let { try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {} }
1088
+ discoveryReceiver = null
1089
+ diagnostics?.disconnected()
1090
+ canvasEncoder.invalidate()
1091
+ failAllPendingAcks()
1092
+ audioClient.stop()
1093
+ val original = gatt
1094
+ val mic = micChar
1095
+ resourceMicStopRequired = original != null && mic != null
1096
+ if (original != null && mic != null) {
1097
+ writes.enqueue(original, mic, listOf(byteArrayOf(0x52, 0, 0, 0)), finalStarted = { recordResourceMicStopStartedClock() }, completed = { recordResourceMicStopWrittenClock() })
1098
+ }
1099
+ canvas.exit()
1100
+ val deadline = android.os.SystemClock.elapsedRealtime() + 15_000
1101
+ fun finish(result: String) {
1102
+ resourceReleaseResult = result
1103
+ if (result == "drain-timeout-native-effects-unknown") resourceClosedWithPending = true
1104
+ closeResourceGatt()
1105
+ gatt = null; txChar = null; rxChar = null; micChar = null
1106
+ resetSessionState()
1107
+ resourceReleasePending = false; resourceReleased = true
1108
+ resourceReceiptPending = true
1109
+ // Shared state belongs to this instance only while the manager still owns it.
1110
+ if (isCurrent()) {
1111
+ DeviceStore.apply("glasses", "connected", false)
1112
+ DeviceStore.apply("glasses", "fullyBooted", false)
1113
+ DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
1114
+ }
1115
+ NimoResourceDiagnostics.track(this)
1116
+ mainHandler.postDelayed({
1117
+ // Keep the original bearer/generation fenced through receipt delivery. The
1118
+ // short callback-observation window must not capture a later connection.
1119
+ val originalReceipt = resourceSnapshot()
1120
+ try { completed(originalReceipt) } finally { resourceReceiptPending = false }
1121
+ }, 100)
1122
+ }
1123
+ fun poll() {
1124
+ if (!isCurrent()) {
1125
+ resourceReleasePending = false; resourceReleaseResult = "target-replaced"
1126
+ NimoResourceDiagnostics.track(this); completed(resourceSnapshot()); return
1127
+ }
1128
+ val unsettled = writes.pendingCount() + canvasEncoder.pendingCount() + audioClient.lifecyclePending() + resourcePostedWrites.get() + canvas.pendingCount() +
1129
+ (if (resourceMicStopRequired && resourceMicStopMarkerAt == null) 1 else 0) +
1130
+ (if (resourceExitRequired && resourceExitStatus != 0) 1 else 0)
1131
+ if (unsettled == 0) { finish("local-drained-native-readback-required"); return }
1132
+ if (android.os.SystemClock.elapsedRealtime() >= deadline) { finish("drain-timeout-native-effects-unknown"); return }
1133
+ mainHandler.postDelayed({ poll() }, 25)
1134
+ }
1135
+ mainHandler.post { poll() }
1136
+ }
1137
+
1138
+ private fun closeResourceGatt() {
1139
+ val original = gatt ?: return
1140
+ resourceClosingGatt = original
1141
+ resourceClosedWithPending = resourceClosedWithPending || writes.pendingCount() > 0 || resourcePostedWrites.get() > 0 || canvas.pendingCount() > 0
1142
+ resourceCloseCalled = true
1143
+ try { original.disconnect() } catch (error: Exception) { resourceCloseError = "disconnect-${error.javaClass.simpleName}" }
1144
+ try { original.close() } catch (error: Exception) { resourceCloseError = "close-${error.javaClass.simpleName}" }
1145
+ }
1146
+
931
1147
  private val mainHandler = Handler(Looper.getMainLooper())
932
1148
  private val mainScheduler = handlerScheduler(mainHandler)
933
1149
  // Variant-specific: release has no receiver or framebuffer protocol implementation.
@@ -940,7 +1156,16 @@ class Nimo : SGCManager() {
940
1156
  private val canvas = NimoCanvasCoordinator(mainScheduler,
941
1157
  { (negotiatedMtu - 3).coerceIn(20, 512) }, ::enqueueFrames, ::abortTransport,
942
1158
  { Bridge.log("NIMO: canvas rejected status=$it; not a render ACK") },
943
- { diagnostics?.cancelHeldCapture("Canvas scope takeover preempted held capture", resumeCanvas = false) })
1159
+ { diagnostics?.cancelHeldCapture("Canvas scope takeover preempted held capture", resumeCanvas = false) },
1160
+ { key, status ->
1161
+ if (key == 3) { resourceExitStatus = status; recordResourceExitClock() }
1162
+ if (resourceReleasePending && resourceInitialLaunchPendingAtRelease && key == 1) {
1163
+ // An explicit rejected initial Launch never acquired canvas ownership.
1164
+ // Status 2 is transport-ambiguous and must retain the unknown fence.
1165
+ if (status != 0 && status != 2) resourceExitRequired = false
1166
+ resourceInitialLaunchPendingAtRelease = false
1167
+ }
1168
+ })
944
1169
 
945
1170
  private fun handlerScheduler(handler: Handler) = NimoScheduler { delay, task ->
946
1171
  val runnable = Runnable(task)
@@ -1033,6 +1258,8 @@ class Nimo : SGCManager() {
1033
1258
  // ---------- SGCManager: Connection Management ----------
1034
1259
 
1035
1260
  override fun findCompatibleDevices() {
1261
+ if (NimoResourceDiagnostics.dispatchCapturedEntry { findCompatibleDevices() }) return
1262
+ if (!NimoResourceDiagnostics.admit(this, null, false)) return
1036
1263
  Bridge.log("NIMO: findCompatibleDevices()")
1037
1264
  DEVICE_SEARCH_ID = "NOT_SET"
1038
1265
  DeviceStore.apply("glasses", "connectionState", ConnTypes.SCANNING)
@@ -1040,6 +1267,11 @@ class Nimo : SGCManager() {
1040
1267
  }
1041
1268
 
1042
1269
  override fun connectById(id: String) {
1270
+ if (NimoResourceDiagnostics.dispatchCapturedEntry { connectById(id) }) return
1271
+ if (!NimoResourceDiagnostics.admit(this, id, true)) return
1272
+ if (resourceReleasePending || resourceReceiptPending) return
1273
+ resourceReleased = false
1274
+ resourceBondMutationRequested = false; resourceFactoryResetRequested = false
1043
1275
  Bridge.log("NIMO: connectById($id)")
1044
1276
  DEVICE_SEARCH_ID = id
1045
1277
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
@@ -1099,8 +1331,7 @@ class Nimo : SGCManager() {
1099
1331
  reconnectionManager.stop()
1100
1332
  failAllPendingAcks()
1101
1333
 
1102
- gatt?.disconnect()
1103
- gatt?.close()
1334
+ closeResourceGatt()
1104
1335
  gatt = null
1105
1336
  txChar = null
1106
1337
  rxChar = null
@@ -1110,6 +1341,7 @@ class Nimo : SGCManager() {
1110
1341
  DeviceStore.apply("glasses", "connected", false)
1111
1342
  DeviceStore.apply("glasses", "fullyBooted", false)
1112
1343
  DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
1344
+ NimoResourceDiagnostics.track(this)
1113
1345
  }
1114
1346
 
1115
1347
  /** Explicit Unpair only. Ordinary forget/cleanup must never reset the glasses. */
@@ -1125,6 +1357,7 @@ class Nimo : SGCManager() {
1125
1357
  reconnectionManager.stop()
1126
1358
  canvasEncoder.invalidate()
1127
1359
  canvas.disconnected()
1360
+ resourceFactoryResetRequested = true
1128
1361
  Bridge.log("NIMO: sending factory reset for explicit Unpair")
1129
1362
  sendAwaitingAck(NimoProtocol.CMD_CONTROL_FACTORY, NimoProtocol.FACTORY_RECOVER, byteArrayOf()) {
1130
1363
  Bridge.log("NIMO: factory reset acknowledged=$it")
@@ -1134,6 +1367,7 @@ class Nimo : SGCManager() {
1134
1367
 
1135
1368
  internal fun removeBluetoothBond() {
1136
1369
  val address = gatt?.device?.address ?: lastDeviceAddress ?: return
1370
+ resourceBondMutationRequested = true
1137
1371
  removeBluetoothBond(address)
1138
1372
  }
1139
1373
 
@@ -1181,7 +1415,7 @@ class Nimo : SGCManager() {
1181
1415
  return
1182
1416
  }
1183
1417
  DeviceStore.apply("glasses", "micEnabled", enabled)
1184
- if (enabled) {
1418
+ if (enabled && !resourceReleasePending && !resourceReleased) {
1185
1419
  audioClient.start()
1186
1420
  } else {
1187
1421
  audioClient.stop()
@@ -1312,7 +1546,8 @@ class Nimo : SGCManager() {
1312
1546
 
1313
1547
  private fun encodeCanvas(scope: String, force: Boolean = false, release: () -> Unit = {},
1314
1548
  encode: () -> ByteArray): Boolean =
1315
- canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1549
+ if (resourceReleasePending || resourceReleased) { release(); false }
1550
+ else canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1316
1551
 
1317
1552
  private fun decodeCanvasSource(data: String): Bitmap {
1318
1553
  val bytes = NimoCanvasCodec.imageBytes(data)
@@ -1610,19 +1845,22 @@ class Nimo : SGCManager() {
1610
1845
  * for Companion service 7033. The separate <name>_BLE ANCS peripheral is not the
1611
1846
  * canvas data channel. This matches the vendor transport=BREDR connection path.
1612
1847
  */
1848
+ private data class ResourcePeer(val address: String, val bondState: Int)
1849
+ private fun resourcePeer(device: android.bluetooth.BluetoothDevice): ResourcePeer = ResourcePeer(
1850
+ try { device.address } catch (_: SecurityException) { "" },
1851
+ try { device.bondState } catch (_: SecurityException) { android.bluetooth.BluetoothDevice.BOND_NONE },
1852
+ )
1853
+
1613
1854
  private fun connectCompanionGatt(device: android.bluetooth.BluetoothDevice) {
1855
+ val peer = resourcePeer(device)
1856
+ if (!NimoResourceDiagnostics.allowPeer(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1614
1857
  if (isDisconnecting || gatt != null) return
1615
1858
  // Classic discovery degrades/aborts connections — always cancel first.
1616
1859
  try {
1617
1860
  bluetoothAdapter?.cancelDiscovery()
1618
1861
  } catch (_: Exception) {}
1619
1862
 
1620
- val bondState =
1621
- try {
1622
- device.bondState
1623
- } catch (e: SecurityException) {
1624
- android.bluetooth.BluetoothDevice.BOND_NONE
1625
- }
1863
+ val bondState = peer.bondState
1626
1864
  if (bondState != android.bluetooth.BluetoothDevice.BOND_BONDED) {
1627
1865
  // Bond over classic first, then open the Companion bearer on completion.
1628
1866
  startBond(device)
@@ -1637,12 +1875,9 @@ class Nimo : SGCManager() {
1637
1875
  * called both on the initial attempt and from the BOND_NONE handler.
1638
1876
  */
1639
1877
  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
- }
1878
+ val peer = resourcePeer(device)
1879
+ if (!NimoResourceDiagnostics.allowPeer(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1880
+ val bondState = peer.bondState
1646
1881
  // A previous (apparently failed) attempt may have bonded in the background.
1647
1882
  if (bondState == android.bluetooth.BluetoothDevice.BOND_BONDED) {
1648
1883
  Bridge.log("NIMO: already bonded with ${device.address} — connecting")
@@ -1683,6 +1918,8 @@ class Nimo : SGCManager() {
1683
1918
 
1684
1919
  private fun connectBredrTransport(device: android.bluetooth.BluetoothDevice) {
1685
1920
  if (isDisconnecting || gatt != null) return
1921
+ val peer = resourcePeer(device)
1922
+ if (!NimoResourceDiagnostics.beginTransport(this, peer.address, peer.bondState == android.bluetooth.BluetoothDevice.BOND_BONDED)) return
1686
1923
  // GATT over BR/EDR: the glasses pair with a legacy (non-SC) link key, so no LE
1687
1924
  // keys exist (le_linkkey_known:F) and the controller records the device as
1688
1925
  // BR_EDR-only — the 7033 UART service is served over the classic link. This is
@@ -1690,14 +1927,28 @@ class Nimo : SGCManager() {
1690
1927
  // why iOS needs Settings pairing (CoreBluetooth bridges GATT over BR/EDR only
1691
1928
  // for system-paired dual-mode accessories).
1692
1929
  Bridge.log("NIMO: connecting GATT over BR/EDR to ${device.address}")
1930
+ resourceSessionGeneration++
1931
+ resourceSessionStartedElapsedMs = android.os.SystemClock.elapsedRealtime()
1932
+ resourceReleaseNonce = null; resourceReleaseStartedElapsedMs = null
1933
+ resourceExitStatus = null; resourceExitAt = null; displayExitElapsedMs = null; resourceMicStopWrittenAt = null; micStopWrittenElapsedMs = null
1934
+ resourceMicStopStartedAt = null; micStopStartedElapsedMs = null; resourceMicStopMarkerAt = null; micStopMarkerElapsedMs = null; resourceTransportFailure = false; resourceClosingGatt = null
1935
+ resourceClosedWithPending = false; resourceReleaseResult = "not-requested"
1936
+ resourceMicStopRequired = false; resourceExitRequired = false; resourceInitialLaunchPendingAtRelease = false
1937
+ resourceReleased = false
1938
+ resourcePairAddress = peer.address
1939
+ resourcePairName = try { device.name ?: "" } catch (_: SecurityException) { "" }
1940
+ resourceFirmwareAt = null; firmwareElapsedMs = null; resourceFirmwareVersion = null
1941
+ resourceTwsAt = null; twsElapsedMs = null; resourceHandshakeTwsAt = null; handshakeTwsElapsedMs = null; resourceTimeAckAt = null; timeAckElapsedMs = null; resourceTimeCommandId = null; resourceTimeWriteStartedAt = null; timeWriteStartedElapsedMs = null
1942
+ resourceCloseCalled = false; resourceCloseObserved = false; resourceDisconnectCallbackStatus = null; resourceCloseError = null
1943
+ NimoResourceDiagnostics.track(this)
1693
1944
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
1694
- gatt =
1695
- device.connectGatt(
1696
- context,
1697
- false,
1698
- gattCallback,
1699
- android.bluetooth.BluetoothDevice.TRANSPORT_BREDR
1700
- )
1945
+ gatt = try {
1946
+ device.connectGatt(context, false, gattCallback, android.bluetooth.BluetoothDevice.TRANSPORT_BREDR)
1947
+ } catch (error: SecurityException) {
1948
+ resourceTransportFailure = true
1949
+ Bridge.log("NIMO: connectGatt SecurityException: ${error.message}")
1950
+ null
1951
+ }
1701
1952
  gatt?.let { writes.connected(it) }
1702
1953
  }
1703
1954
 
@@ -1826,9 +2077,16 @@ class Nimo : SGCManager() {
1826
2077
  object : BluetoothGattCallback() {
1827
2078
  override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
1828
2079
  mainHandler.post {
1829
- if (g !== gatt) return@post
2080
+ if (g !== gatt) {
2081
+ if (g === resourceClosingGatt && newState == BluetoothProfile.STATE_DISCONNECTED) {
2082
+ resourceCloseObserved = true
2083
+ resourceDisconnectCallbackStatus = status
2084
+ }
2085
+ return@post
2086
+ }
1830
2087
  Bridge.log("NIMO: onConnectionStateChange status=$status newState=$newState")
1831
2088
  if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
2089
+ if (isDisconnecting) return@post
1832
2090
  Bridge.log("NIMO: Connected to ${g.device?.name ?: "unknown"}")
1833
2091
  lastDeviceAddress = g.device?.address
1834
2092
  // Do NOT request a large MTU here: the vendor transport warns that
@@ -1877,6 +2135,7 @@ class Nimo : SGCManager() {
1877
2135
  }
1878
2136
  mainHandler.post {
1879
2137
  if (g !== gatt) return@post
2138
+ if (isDisconnecting) return@post
1880
2139
  val service = g.getService(NimoBLE.SERVICE_UUID)
1881
2140
  if (service == null) {
1882
2141
  // Dump everything so a UUID mismatch is diagnosable from logs.
@@ -1922,7 +2181,12 @@ class Nimo : SGCManager() {
1922
2181
  NimoBLE.CHAR_RX -> if (characteristic.service?.uuid == NimoBLE.SERVICE_UUID) {
1923
2182
  handleRxPacket(data)
1924
2183
  }
1925
- NimoBLE.CHAR_MIC -> audioClient.enqueue(data)
2184
+ NimoBLE.CHAR_MIC -> {
2185
+ if (resourceReleasePending && resourceMicStopStartedAt != null && data.contentEquals(byteArrayOf(0x52, 0, 0, 0))) {
2186
+ recordResourceMicStopMarkerClock()
2187
+ }
2188
+ audioClient.enqueue(data)
2189
+ }
1926
2190
  }
1927
2191
  }
1928
2192
  }
@@ -1971,9 +2235,15 @@ class Nimo : SGCManager() {
1971
2235
 
1972
2236
  private fun enqueueWrite(char: BluetoothGattCharacteristic, bytes: ByteArray) {
1973
2237
  val expectedGatt = gatt ?: return
2238
+ val timeCommand = if (bytes.size >= 10 && (bytes[8].toInt() and 255) == NimoProtocol.CMD_SET_PARAMETER &&
2239
+ (bytes[9].toInt() and 255) == NimoProtocol.SET_TIME) resourceTimeCommandId else null
2240
+ resourcePostedWrites.incrementAndGet()
1974
2241
  mainHandler.post {
1975
- if (gatt !== expectedGatt) return@post
1976
- writes.enqueue(expectedGatt, char, listOf(bytes))
2242
+ resourcePostedWrites.decrementAndGet()
2243
+ if (gatt !== expectedGatt || resourceReleasePending || resourceReleased) return@post
2244
+ writes.enqueue(expectedGatt, char, listOf(bytes), finalStarted = {
2245
+ if (timeCommand != null && timeCommand == resourceTimeCommandId) { recordResourceTimeWriteClock() }
2246
+ })
1977
2247
  }
1978
2248
  }
1979
2249
 
@@ -1992,11 +2262,12 @@ class Nimo : SGCManager() {
1992
2262
 
1993
2263
  private fun abortTransport(reason: String) {
1994
2264
  Bridge.log("NIMO: resetting transport: $reason")
1995
- val old = gatt
2265
+ resourceTransportFailure = true
2266
+ resourceClosedWithPending = true
2267
+ closeResourceGatt()
1996
2268
  gatt = null
1997
2269
  txChar = null; rxChar = null; micChar = null
1998
2270
  resetSessionState()
1999
- try { old?.disconnect(); old?.close() } catch (_: Exception) {}
2000
2271
  DeviceStore.apply("glasses", "connected", false)
2001
2272
  DeviceStore.apply("glasses", "fullyBooted", false)
2002
2273
  DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
@@ -2050,6 +2321,7 @@ class Nimo : SGCManager() {
2050
2321
  // ---------- Handshake ----------
2051
2322
 
2052
2323
  private fun startHandshake() {
2324
+ if (isDisconnecting || resourceReleasePending || resourceReleased) return
2053
2325
  Bridge.log("NIMO: starting handshake (awaiting TWS service-connection state)")
2054
2326
  handshakeState = HandshakeState.AWAITING_TWS
2055
2327
  if (twsConnected) {
@@ -2075,10 +2347,16 @@ class Nimo : SGCManager() {
2075
2347
  }
2076
2348
 
2077
2349
  private var setTimeAttempts = 0
2350
+ private var setTimeRetryRunnable: Runnable? = null
2351
+ private fun cancelSetTimeRetry() {
2352
+ setTimeRetryRunnable?.let(mainHandler::removeCallbacks)
2353
+ setTimeRetryRunnable = null
2354
+ }
2078
2355
 
2079
2356
  private fun proceedToTimeSync() {
2080
2357
  if (handshakeState != HandshakeState.AWAITING_TWS) return
2081
2358
  cancelTwsTimeout()
2359
+ resourceHandshakeTwsAt = resourceTwsAt; handshakeTwsElapsedMs = twsElapsedMs
2082
2360
  handshakeState = HandshakeState.AWAITING_TIME_ACK
2083
2361
  Bridge.log("NIMO: TWS OK — sending setTime (awaiting ACK)")
2084
2362
  setTimeAttempts = 0
@@ -2089,13 +2367,21 @@ class Nimo : SGCManager() {
2089
2367
  if (handshakeState != HandshakeState.AWAITING_TIME_ACK || gatt == null) return
2090
2368
  val expectedGatt = gatt
2091
2369
  setTimeAttempts++
2370
+ resourceTimeCommandId = UUID.randomUUID().toString()
2371
+ resourceTimeWriteStartedAt = null; timeWriteStartedElapsedMs = null
2092
2372
  sendAwaitingAck(
2093
2373
  NimoProtocol.CMD_SET_PARAMETER,
2094
2374
  NimoProtocol.SET_TIME,
2095
2375
  NimoFrameCodec.encodeDeviceTime()
2096
2376
  ) { ok ->
2097
2377
  if (gatt !== expectedGatt || handshakeState != HandshakeState.AWAITING_TIME_ACK) return@sendAwaitingAck
2378
+ if (ok && resourceTimeWriteStartedAt == null) {
2379
+ resourceTransportFailure = true
2380
+ handshakeFailed()
2381
+ return@sendAwaitingAck
2382
+ }
2098
2383
  if (ok) {
2384
+ recordResourceTimeAckClock()
2099
2385
  finishHandshake()
2100
2386
  } else if (setTimeAttempts < SET_TIME_MAX_ATTEMPTS &&
2101
2387
  handshakeState == HandshakeState.AWAITING_TIME_ACK &&
@@ -2104,7 +2390,12 @@ class Nimo : SGCManager() {
2104
2390
  // The firmware can answer "busy" right after the link comes up —
2105
2391
  // give it a moment and retry instead of dropping the connection.
2106
2392
  Bridge.log("NIMO: setTime attempt $setTimeAttempts failed — retrying")
2107
- mainHandler.postDelayed({ if (gatt === expectedGatt) attemptSetTime() }, SET_TIME_RETRY_DELAY_MS)
2393
+ val retry = Runnable {
2394
+ setTimeRetryRunnable = null
2395
+ if (gatt === expectedGatt) attemptSetTime()
2396
+ }
2397
+ setTimeRetryRunnable = retry
2398
+ mainHandler.postDelayed(retry, SET_TIME_RETRY_DELAY_MS)
2108
2399
  } else {
2109
2400
  Bridge.log("NIMO: setTime failed after $setTimeAttempts attempts — handshake failed")
2110
2401
  handshakeFailed()
@@ -2161,6 +2452,7 @@ class Nimo : SGCManager() {
2161
2452
  diagnostics?.disconnected()
2162
2453
  handshakeState = HandshakeState.IDLE
2163
2454
  cancelTwsTimeout()
2455
+ cancelSetTimeRetry()
2164
2456
  twsConnected = false
2165
2457
  peerCompanionReady = null
2166
2458
  canvasEncoder.invalidate()
@@ -2182,6 +2474,7 @@ class Nimo : SGCManager() {
2182
2474
  if (fullyBooted) {
2183
2475
  return@start true
2184
2476
  }
2477
+ if (!NimoResourceDiagnostics.admit(this, DEVICE_SEARCH_ID, true)) return@start true
2185
2478
  Bridge.log("NIMO: Attempting reconnection...")
2186
2479
  isDisconnecting = false
2187
2480
  // Each reconnection cycle is a fresh bond budget — the glasses drop their
@@ -2313,6 +2606,7 @@ class Nimo : SGCManager() {
2313
2606
  }
2314
2607
 
2315
2608
  private fun onTwsState(connected: Boolean) {
2609
+ recordResourceTwsClock()
2316
2610
  twsConnected = connected
2317
2611
  if (connected && handshakeState == HandshakeState.AWAITING_TWS) {
2318
2612
  proceedToTimeSync()
@@ -2385,6 +2679,7 @@ class Nimo : SGCManager() {
2385
2679
  val micro = (v ushr 12) and 0x1FF
2386
2680
  val build = v and 0xFFF
2387
2681
  firmwareVersionPacked = "$major.$minor.$micro.$build"
2682
+ resourceFirmwareVersion = firmwareVersionPacked; recordResourceFirmwareClock()
2388
2683
  emitVersionInfo()
2389
2684
  }
2390
2685
  }
@@ -2392,6 +2687,9 @@ class Nimo : SGCManager() {
2392
2687
  var end = data.size
2393
2688
  while (end > 0 && data[end - 1].toInt() == 0) end--
2394
2689
  firmwareVersionDetail = String(data, 0, end, Charsets.UTF_8).trim()
2690
+ if (firmwareVersionDetail.isNotEmpty() && firmwareVersionDetail.length <= 240) {
2691
+ resourceFirmwareVersion = firmwareVersionDetail; recordResourceFirmwareClock()
2692
+ }
2395
2693
  emitVersionInfo()
2396
2694
  }
2397
2695
  NimoProtocol.GET_TWS_STATUS -> {