@mentra/bluetooth-sdk 3.4.0-dev.998 → 3.4.0

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 (215) hide show
  1. package/MIGRATION.md +16 -7
  2. package/README.md +40 -13
  3. package/android/build.gradle +60 -51
  4. package/android/gradle.properties +3 -0
  5. package/android/settings.gradle +47 -3
  6. package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  8. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
  9. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
  10. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
  11. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +114 -122
  12. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -2
  13. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
  14. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
  15. package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
  16. package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
  17. package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
  18. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
  22. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
  23. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
  28. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
  29. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +274 -56
  30. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +5 -5
  31. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
  32. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  33. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  34. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
  35. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
  36. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  37. package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
  38. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  39. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  40. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  41. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  42. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  43. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  44. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  45. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  46. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  47. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  48. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  49. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  50. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  51. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  52. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  53. package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
  54. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
  55. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
  56. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
  57. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
  58. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
  59. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
  60. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
  61. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
  62. package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
  63. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
  64. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  65. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  66. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +3 -3
  67. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  68. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  69. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  70. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
  71. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
  72. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
  73. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  74. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
  75. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  76. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  77. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  78. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  79. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  80. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  81. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  82. package/build/BluetoothSdk.types.d.ts +103 -5
  83. package/build/BluetoothSdk.types.d.ts.map +1 -1
  84. package/build/BluetoothSdk.types.js.map +1 -1
  85. package/build/_private/BluetoothSdkModule.d.ts +42 -8
  86. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  87. package/build/_private/BluetoothSdkModule.js +1 -0
  88. package/build/_private/BluetoothSdkModule.js.map +1 -1
  89. package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
  90. package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
  91. package/build/_private/MentraLocalNetworkModule.js.map +1 -1
  92. package/build/generated/changelogCatalog.d.ts +2 -2
  93. package/build/generated/changelogCatalog.js +2 -2
  94. package/build/generated/changelogCatalog.js.map +1 -1
  95. package/build/generated/releaseMetadata.js +5 -5
  96. package/build/generated/releaseMetadata.js.map +1 -1
  97. package/build/index.d.ts +1 -1
  98. package/build/index.d.ts.map +1 -1
  99. package/build/index.js +7 -1
  100. package/build/index.js.map +1 -1
  101. package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
  102. package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
  103. package/build/ota-server/MentraOtaServerModule.js.map +1 -1
  104. package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
  105. package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
  106. package/build/ota-server/MentraOtaServerModule.web.js +0 -3
  107. package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
  108. package/build/ota-transport/index.d.ts +3 -3
  109. package/build/ota-transport/index.d.ts.map +1 -1
  110. package/build/ota-transport/index.js +4 -4
  111. package/build/ota-transport/index.js.map +1 -1
  112. package/build/react/useGlassesConnection.d.ts +1 -1
  113. package/build/react/useGlassesConnection.d.ts.map +1 -1
  114. package/build/react/useGlassesConnection.js +3 -3
  115. package/build/react/useGlassesConnection.js.map +1 -1
  116. package/build/react/useMentraBluetooth.d.ts +1 -1
  117. package/build/react/useMentraBluetooth.d.ts.map +1 -1
  118. package/build/react/useMentraBluetooth.js +1 -1
  119. package/build/react/useMentraBluetooth.js.map +1 -1
  120. package/ios/BluetoothSdkModule.swift +73 -22
  121. package/ios/LocalIPv4.swift +0 -61
  122. package/ios/MentraBluetoothSDK.podspec +7 -1
  123. package/ios/MentraOtaServerModule.swift +0 -16
  124. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  125. package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
  126. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  127. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  128. package/ios/Source/BluetoothSdkDefaults.swift +4 -4
  129. package/ios/Source/Bridge.swift +14 -0
  130. package/ios/Source/DeviceManager.swift +43 -22
  131. package/ios/Source/GeneratedChangelogCatalog.swift +2 -2
  132. package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
  133. package/ios/Source/MentraBluetoothSDK.swift +35 -16
  134. package/ios/Source/OtaManifest.swift +1 -17
  135. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  136. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  137. package/ios/Source/audio/SpeechActivity.swift +277 -0
  138. package/ios/Source/events/BluetoothEvents.swift +41 -0
  139. package/ios/Source/internal/BleTraceLogger.swift +14 -1
  140. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  141. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  142. package/ios/Source/sgcs/MentraLive.swift +195 -66
  143. package/ios/Source/sgcs/Nimo.swift +249 -276
  144. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  145. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  146. package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
  147. package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
  148. package/ios/Source/sgcs/SGCManager.swift +6 -0
  149. package/ios/Source/streaming/StreamModels.swift +15 -6
  150. package/ios/Source/stt/STTTools.swift +13 -31
  151. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  152. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  153. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  154. package/ios/Source/utils/BoundedWait.swift +44 -0
  155. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  156. package/ios/Source/utils/SttModelTraits.swift +62 -0
  157. package/ios/Tests/BesCrashReportTests.swift +142 -0
  158. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  159. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  160. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  161. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  162. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  163. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  164. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  165. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  166. package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
  167. package/ios/Tests/PcmStreamTests.swift +299 -0
  168. package/ios/Tests/SpeechActivityTests.swift +238 -0
  169. package/ios/Tests/StreamRequestTests.swift +18 -0
  170. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  171. package/package.json +2 -2
  172. package/plugin/build/withAndroid.js +9 -11
  173. package/plugin/build/withKotlinVersion.d.ts +2 -0
  174. package/plugin/build/withKotlinVersion.js +46 -0
  175. package/src/BluetoothSdk.types.ts +107 -5
  176. package/src/_private/BluetoothSdkModule.ts +45 -8
  177. package/src/_private/MentraLocalNetworkModule.ts +5 -1
  178. package/src/generated/changelogCatalog.ts +2 -2
  179. package/src/generated/releaseMetadata.ts +5 -5
  180. package/src/index.ts +13 -1
  181. package/src/ota-server/MentraOtaServerModule.ts +0 -2
  182. package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
  183. package/src/ota-transport/index.ts +4 -5
  184. package/src/react/useGlassesConnection.ts +4 -4
  185. package/src/react/useMentraBluetooth.ts +2 -2
  186. package/android/silero/LICENSE.md +0 -17
  187. package/android/silero/build.gradle +0 -50
  188. package/android/silero/proguard-rules.pro +0 -24
  189. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  190. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  191. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  192. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  193. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  194. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  195. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  196. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  197. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  198. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  199. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  200. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  201. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  202. package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
  203. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  204. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  205. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  206. package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
  207. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  208. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  209. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  210. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  211. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  212. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  213. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  214. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  215. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -30,7 +30,6 @@ 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
33
  import java.util.concurrent.atomic.AtomicInteger
35
34
  import kotlinx.coroutines.Dispatchers
36
35
  import kotlinx.coroutines.runBlocking
@@ -45,6 +44,9 @@ internal object NimoBLE {
45
44
  val CHAR_TX: UUID = UUID.fromString("00002021-0000-1000-8000-00805F9B34FB")
46
45
  val CHAR_RX: UUID = UUID.fromString("00002022-0000-1000-8000-00805F9B34FB")
47
46
  val CHAR_MIC: UUID = UUID.fromString("00002025-0000-1000-8000-00805F9B34FB")
47
+ // Firmware update channel on the same service (see NimoOtaProtocol).
48
+ val CHAR_OTA_TX: UUID = UUID.fromString("00002001-0000-1000-8000-00805F9B34FB")
49
+ val CHAR_OTA_RX: UUID = UUID.fromString("00002002-0000-1000-8000-00805F9B34FB")
48
50
  val CLIENT_CHARACTERISTIC_CONFIG: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
49
51
 
50
52
  const val NAME_PREFIX = "nimo"
@@ -928,6 +930,16 @@ class Nimo : SGCManager() {
928
930
  private const val BATTERY_POLL_MS = 30_000L
929
931
  private const val SET_TIME_MAX_ATTEMPTS = 3
930
932
  private const val SET_TIME_RETRY_DELAY_MS = 500L
933
+ // Version replies normally arrive within a few hundred ms of the handshake.
934
+ private const val VERSION_WAIT_MS = 3_000L
935
+ // Let the wearer read the update notice before the display goes away.
936
+ private const val UPDATE_NOTICE_MS = 2_000L
937
+ private const val OTA_PREPARE_TIMEOUT_MS = 15_000L
938
+ // The glasses reboot after the update; force a reconnect if they never drop the link.
939
+ private const val POST_UPDATE_RECONNECT_MS = 120_000L
940
+ // Per app process, so a failing update cannot loop forever.
941
+ private const val MAX_UPDATE_ATTEMPTS = 3
942
+ private var updateAttempts = 0
931
943
  }
932
944
 
933
945
  init {
@@ -935,219 +947,14 @@ class Nimo : SGCManager() {
935
947
  hasMic = true
936
948
  }
937
949
 
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() {
950
+ private fun closeGatt() {
1139
951
  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}" }
952
+ try { original.disconnect() } catch (error: Exception) { Bridge.log("NIMO: disconnect failed: ${error.javaClass.simpleName}") }
953
+ try { original.close() } catch (error: Exception) { Bridge.log("NIMO: close failed: ${error.javaClass.simpleName}") }
1145
954
  }
1146
955
 
1147
956
  private val mainHandler = Handler(Looper.getMainLooper())
1148
957
  private val mainScheduler = handlerScheduler(mainHandler)
1149
- // Variant-specific: release has no receiver or framebuffer protocol implementation.
1150
- private var diagnostics: NimoDiagnostics? = null
1151
958
  private val canvasEncoderThread = HandlerThread("NimoCanvasEncoder").apply { start() }
1152
959
  private val canvasEncoder = NimoCanvasEncoder(mainScheduler,
1153
960
  handlerScheduler(Handler(canvasEncoderThread.looper)),
@@ -1155,17 +962,7 @@ class Nimo : SGCManager() {
1155
962
  { Bridge.log("NIMO: canvas validation/encoding failed; retaining last valid scene: ${it.message}") })
1156
963
  private val canvas = NimoCanvasCoordinator(mainScheduler,
1157
964
  { (negotiatedMtu - 3).coerceIn(20, 512) }, ::enqueueFrames, ::abortTransport,
1158
- { Bridge.log("NIMO: canvas rejected status=$it; not a render ACK") },
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
- })
965
+ { Bridge.log("NIMO: canvas rejected status=$it; not a render ACK") })
1169
966
 
1170
967
  private fun handlerScheduler(handler: Handler) = NimoScheduler { delay, task ->
1171
968
  val runnable = Runnable(task)
@@ -1181,6 +978,8 @@ class Nimo : SGCManager() {
1181
978
  private var txChar: BluetoothGattCharacteristic? = null
1182
979
  private var rxChar: BluetoothGattCharacteristic? = null
1183
980
  private var micChar: BluetoothGattCharacteristic? = null
981
+ private var otaTxChar: BluetoothGattCharacteristic? = null
982
+ private var otaRxChar: BluetoothGattCharacteristic? = null
1184
983
  private var isDisconnecting = false
1185
984
  private var negotiatedMtu = 23
1186
985
  // Device search
@@ -1231,7 +1030,11 @@ class Nimo : SGCManager() {
1231
1030
  // One queue owns characteristic writes and CCCD callbacks, including non-canvas commands.
1232
1031
  private val writes = NimoGattQueue<BluetoothGattCharacteristic>(mainScheduler,
1233
1032
  { characteristic, bytes ->
1234
- characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
1033
+ characteristic.writeType =
1034
+ if (characteristic === otaTxChar &&
1035
+ characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0)
1036
+ BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
1037
+ else BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
1235
1038
  characteristic.value = bytes
1236
1039
  gatt?.writeCharacteristic(characteristic) ?: false
1237
1040
  }, ::abortTransport, NimoBLE.INTER_FRAME_DELAY_MS)
@@ -1246,6 +1049,16 @@ class Nimo : SGCManager() {
1246
1049
  // Version info
1247
1050
  private var firmwareVersionPacked: String = ""
1248
1051
  private var firmwareVersionDetail: String = ""
1052
+ private var versionPackedReceived = false
1053
+ private var versionDetailReceived = false
1054
+
1055
+ // Firmware gate: the canvas only runs on the supported firmware; anything else is updated first.
1056
+ private enum class FirmwareState { UNKNOWN, CURRENT, UPDATING }
1057
+ private var firmwareState = FirmwareState.UNKNOWN
1058
+ private var firmwareUpdater: NimoFirmwareUpdater? = null
1059
+ private var cancelFirmwareTimer: (() -> Unit)? = null
1060
+ private var otaMtuPending: (() -> Unit)? = null
1061
+ private val updating get() = firmwareState == FirmwareState.UPDATING
1249
1062
 
1250
1063
  // Mic audio (vendor GlassesAudioClient structure)
1251
1064
  private val audioClient =
@@ -1258,8 +1071,6 @@ class Nimo : SGCManager() {
1258
1071
  // ---------- SGCManager: Connection Management ----------
1259
1072
 
1260
1073
  override fun findCompatibleDevices() {
1261
- if (NimoResourceDiagnostics.dispatchCapturedEntry { findCompatibleDevices() }) return
1262
- if (!NimoResourceDiagnostics.admit(this, null, false)) return
1263
1074
  Bridge.log("NIMO: findCompatibleDevices()")
1264
1075
  DEVICE_SEARCH_ID = "NOT_SET"
1265
1076
  DeviceStore.apply("glasses", "connectionState", ConnTypes.SCANNING)
@@ -1267,11 +1078,6 @@ class Nimo : SGCManager() {
1267
1078
  }
1268
1079
 
1269
1080
  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
1275
1081
  Bridge.log("NIMO: connectById($id)")
1276
1082
  DEVICE_SEARCH_ID = id
1277
1083
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
@@ -1331,17 +1137,18 @@ class Nimo : SGCManager() {
1331
1137
  reconnectionManager.stop()
1332
1138
  failAllPendingAcks()
1333
1139
 
1334
- closeResourceGatt()
1140
+ closeGatt()
1335
1141
  gatt = null
1336
1142
  txChar = null
1337
1143
  rxChar = null
1338
1144
  micChar = null
1145
+ otaTxChar = null
1146
+ otaRxChar = null
1339
1147
  resetSessionState()
1340
1148
 
1341
1149
  DeviceStore.apply("glasses", "connected", false)
1342
1150
  DeviceStore.apply("glasses", "fullyBooted", false)
1343
1151
  DeviceStore.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
1344
- NimoResourceDiagnostics.track(this)
1345
1152
  }
1346
1153
 
1347
1154
  /** Explicit Unpair only. Ordinary forget/cleanup must never reset the glasses. */
@@ -1357,7 +1164,6 @@ class Nimo : SGCManager() {
1357
1164
  reconnectionManager.stop()
1358
1165
  canvasEncoder.invalidate()
1359
1166
  canvas.disconnected()
1360
- resourceFactoryResetRequested = true
1361
1167
  Bridge.log("NIMO: sending factory reset for explicit Unpair")
1362
1168
  sendAwaitingAck(NimoProtocol.CMD_CONTROL_FACTORY, NimoProtocol.FACTORY_RECOVER, byteArrayOf()) {
1363
1169
  Bridge.log("NIMO: factory reset acknowledged=$it")
@@ -1367,7 +1173,6 @@ class Nimo : SGCManager() {
1367
1173
 
1368
1174
  internal fun removeBluetoothBond() {
1369
1175
  val address = gatt?.device?.address ?: lastDeviceAddress ?: return
1370
- resourceBondMutationRequested = true
1371
1176
  removeBluetoothBond(address)
1372
1177
  }
1373
1178
 
@@ -1390,8 +1195,6 @@ class Nimo : SGCManager() {
1390
1195
  }
1391
1196
  canvasEncoder.close()
1392
1197
  disconnect()
1393
- diagnostics?.close()
1394
- diagnostics = null
1395
1198
  audioClient.stop()
1396
1199
  }
1397
1200
 
@@ -1414,8 +1217,12 @@ class Nimo : SGCManager() {
1414
1217
  Bridge.log("NIMO: mic characteristic not available")
1415
1218
  return
1416
1219
  }
1220
+ if (enabled && updating) {
1221
+ Bridge.log("NIMO: mic stays off during the firmware update")
1222
+ return
1223
+ }
1417
1224
  DeviceStore.apply("glasses", "micEnabled", enabled)
1418
- if (enabled && !resourceReleasePending && !resourceReleased) {
1225
+ if (enabled) {
1419
1226
  audioClient.start()
1420
1227
  } else {
1421
1228
  audioClient.stop()
@@ -1546,8 +1353,7 @@ class Nimo : SGCManager() {
1546
1353
 
1547
1354
  private fun encodeCanvas(scope: String, force: Boolean = false, release: () -> Unit = {},
1548
1355
  encode: () -> ByteArray): Boolean =
1549
- if (resourceReleasePending || resourceReleased) { release(); false }
1550
- else canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1356
+ canvasEncoder.submit(encode, release) { bytes -> canvas.offer(bytes, scope, force) }
1551
1357
 
1552
1358
  private fun decodeCanvasSource(data: String): Bitmap {
1553
1359
  val bytes = NimoCanvasCodec.imageBytes(data)
@@ -1625,7 +1431,6 @@ class Nimo : SGCManager() {
1625
1431
  override fun exit() {
1626
1432
  canvasEncoder.invalidate()
1627
1433
  mainHandler.post {
1628
- diagnostics?.cancelHeldCapture("Explicit host exit preempted held capture", resumeCanvas = false)
1629
1434
  canvas.exit()
1630
1435
  }
1631
1436
  }
@@ -1845,22 +1650,14 @@ class Nimo : SGCManager() {
1845
1650
  * for Companion service 7033. The separate <name>_BLE ANCS peripheral is not the
1846
1651
  * canvas data channel. This matches the vendor transport=BREDR connection path.
1847
1652
  */
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
-
1854
1653
  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
1857
1654
  if (isDisconnecting || gatt != null) return
1858
1655
  // Classic discovery degrades/aborts connections — always cancel first.
1859
1656
  try {
1860
1657
  bluetoothAdapter?.cancelDiscovery()
1861
1658
  } catch (_: Exception) {}
1862
1659
 
1863
- val bondState = peer.bondState
1660
+ val bondState = try { device.bondState } catch (_: SecurityException) { android.bluetooth.BluetoothDevice.BOND_NONE }
1864
1661
  if (bondState != android.bluetooth.BluetoothDevice.BOND_BONDED) {
1865
1662
  // Bond over classic first, then open the Companion bearer on completion.
1866
1663
  startBond(device)
@@ -1875,9 +1672,7 @@ class Nimo : SGCManager() {
1875
1672
  * called both on the initial attempt and from the BOND_NONE handler.
1876
1673
  */
1877
1674
  private fun startBond(device: android.bluetooth.BluetoothDevice) {
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
1675
+ val bondState = try { device.bondState } catch (_: SecurityException) { android.bluetooth.BluetoothDevice.BOND_NONE }
1881
1676
  // A previous (apparently failed) attempt may have bonded in the background.
1882
1677
  if (bondState == android.bluetooth.BluetoothDevice.BOND_BONDED) {
1883
1678
  Bridge.log("NIMO: already bonded with ${device.address} — connecting")
@@ -1918,8 +1713,6 @@ class Nimo : SGCManager() {
1918
1713
 
1919
1714
  private fun connectBredrTransport(device: android.bluetooth.BluetoothDevice) {
1920
1715
  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
1923
1716
  // GATT over BR/EDR: the glasses pair with a legacy (non-SC) link key, so no LE
1924
1717
  // keys exist (le_linkkey_known:F) and the controller records the device as
1925
1718
  // BR_EDR-only — the 7033 UART service is served over the classic link. This is
@@ -1927,25 +1720,10 @@ class Nimo : SGCManager() {
1927
1720
  // why iOS needs Settings pairing (CoreBluetooth bridges GATT over BR/EDR only
1928
1721
  // for system-paired dual-mode accessories).
1929
1722
  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)
1944
1723
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTING)
1945
1724
  gatt = try {
1946
1725
  device.connectGatt(context, false, gattCallback, android.bluetooth.BluetoothDevice.TRANSPORT_BREDR)
1947
1726
  } catch (error: SecurityException) {
1948
- resourceTransportFailure = true
1949
1727
  Bridge.log("NIMO: connectGatt SecurityException: ${error.message}")
1950
1728
  null
1951
1729
  }
@@ -2078,10 +1856,6 @@ class Nimo : SGCManager() {
2078
1856
  override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
2079
1857
  mainHandler.post {
2080
1858
  if (g !== gatt) {
2081
- if (g === resourceClosingGatt && newState == BluetoothProfile.STATE_DISCONNECTED) {
2082
- resourceCloseObserved = true
2083
- resourceDisconnectCallbackStatus = status
2084
- }
2085
1859
  return@post
2086
1860
  }
2087
1861
  Bridge.log("NIMO: onConnectionStateChange status=$status newState=$newState")
@@ -2107,6 +1881,8 @@ class Nimo : SGCManager() {
2107
1881
  txChar = null
2108
1882
  rxChar = null
2109
1883
  micChar = null
1884
+ otaTxChar = null
1885
+ otaRxChar = null
2110
1886
  resetSessionState()
2111
1887
 
2112
1888
  DeviceStore.apply("glasses", "connected", false)
@@ -2122,8 +1898,9 @@ class Nimo : SGCManager() {
2122
1898
  override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {
2123
1899
  Bridge.log("NIMO: onMtuChanged mtu=$mtu status=$status")
2124
1900
  mainHandler.post {
2125
- if (g !== gatt || status != BluetoothGatt.GATT_SUCCESS) return@post
2126
- negotiatedMtu = mtu.coerceIn(23, 517)
1901
+ if (g !== gatt) return@post
1902
+ if (status == BluetoothGatt.GATT_SUCCESS) negotiatedMtu = mtu.coerceIn(23, 517)
1903
+ otaMtuPending?.let { otaMtuPending = null; it() }
2127
1904
  }
2128
1905
  }
2129
1906
 
@@ -2153,8 +1930,11 @@ class Nimo : SGCManager() {
2153
1930
  txChar = service.getCharacteristic(NimoBLE.CHAR_TX)
2154
1931
  rxChar = service.getCharacteristic(NimoBLE.CHAR_RX)
2155
1932
  micChar = service.getCharacteristic(NimoBLE.CHAR_MIC)
1933
+ otaTxChar = service.getCharacteristic(NimoBLE.CHAR_OTA_TX)
1934
+ otaRxChar = service.getCharacteristic(NimoBLE.CHAR_OTA_RX)
2156
1935
  Bridge.log(
2157
- "NIMO: chars tx=${txChar != null} rx=${rxChar != null} mic=${micChar != null}"
1936
+ "NIMO: chars tx=${txChar != null} rx=${rxChar != null} mic=${micChar != null} " +
1937
+ "ota=${otaTxChar != null && otaRxChar != null}"
2158
1938
  )
2159
1939
  if (txChar == null || rxChar == null) {
2160
1940
  Bridge.log("NIMO: required characteristics missing")
@@ -2182,11 +1962,9 @@ class Nimo : SGCManager() {
2182
1962
  handleRxPacket(data)
2183
1963
  }
2184
1964
  NimoBLE.CHAR_MIC -> {
2185
- if (resourceReleasePending && resourceMicStopStartedAt != null && data.contentEquals(byteArrayOf(0x52, 0, 0, 0))) {
2186
- recordResourceMicStopMarkerClock()
2187
- }
2188
- audioClient.enqueue(data)
1965
+ if (!updating) audioClient.enqueue(data)
2189
1966
  }
1967
+ NimoBLE.CHAR_OTA_RX -> firmwareUpdater?.receive(data)
2190
1968
  }
2191
1969
  }
2192
1970
  }
@@ -2234,16 +2012,12 @@ class Nimo : SGCManager() {
2234
2012
  // ---------- Write Queue ----------
2235
2013
 
2236
2014
  private fun enqueueWrite(char: BluetoothGattCharacteristic, bytes: ByteArray) {
2015
+ // The firmware update owns the link; ordinary commands wait for the next connection.
2016
+ if (updating) return
2237
2017
  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()
2241
2018
  mainHandler.post {
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
- })
2019
+ if (gatt !== expectedGatt) return@post
2020
+ writes.enqueue(expectedGatt, char, listOf(bytes))
2247
2021
  }
2248
2022
  }
2249
2023
 
@@ -2254,6 +2028,7 @@ class Nimo : SGCManager() {
2254
2028
 
2255
2029
  private fun enqueueFrames(frames: List<ByteArray>, finalStarted: () -> Unit,
2256
2030
  completed: () -> Unit): Boolean {
2031
+ if (updating) return false
2257
2032
  val tx = txChar ?: return false
2258
2033
  val connection = gatt ?: return false
2259
2034
  // Coordinator and GATT callbacks are Main-confined: enqueue the complete chain atomically.
@@ -2262,11 +2037,9 @@ class Nimo : SGCManager() {
2262
2037
 
2263
2038
  private fun abortTransport(reason: String) {
2264
2039
  Bridge.log("NIMO: resetting transport: $reason")
2265
- resourceTransportFailure = true
2266
- resourceClosedWithPending = true
2267
- closeResourceGatt()
2040
+ closeGatt()
2268
2041
  gatt = null
2269
- txChar = null; rxChar = null; micChar = null
2042
+ txChar = null; rxChar = null; micChar = null; otaTxChar = null; otaRxChar = null
2270
2043
  resetSessionState()
2271
2044
  DeviceStore.apply("glasses", "connected", false)
2272
2045
  DeviceStore.apply("glasses", "fullyBooted", false)
@@ -2321,7 +2094,7 @@ class Nimo : SGCManager() {
2321
2094
  // ---------- Handshake ----------
2322
2095
 
2323
2096
  private fun startHandshake() {
2324
- if (isDisconnecting || resourceReleasePending || resourceReleased) return
2097
+ if (isDisconnecting) return
2325
2098
  Bridge.log("NIMO: starting handshake (awaiting TWS service-connection state)")
2326
2099
  handshakeState = HandshakeState.AWAITING_TWS
2327
2100
  if (twsConnected) {
@@ -2356,7 +2129,6 @@ class Nimo : SGCManager() {
2356
2129
  private fun proceedToTimeSync() {
2357
2130
  if (handshakeState != HandshakeState.AWAITING_TWS) return
2358
2131
  cancelTwsTimeout()
2359
- resourceHandshakeTwsAt = resourceTwsAt; handshakeTwsElapsedMs = twsElapsedMs
2360
2132
  handshakeState = HandshakeState.AWAITING_TIME_ACK
2361
2133
  Bridge.log("NIMO: TWS OK — sending setTime (awaiting ACK)")
2362
2134
  setTimeAttempts = 0
@@ -2367,21 +2139,13 @@ class Nimo : SGCManager() {
2367
2139
  if (handshakeState != HandshakeState.AWAITING_TIME_ACK || gatt == null) return
2368
2140
  val expectedGatt = gatt
2369
2141
  setTimeAttempts++
2370
- resourceTimeCommandId = UUID.randomUUID().toString()
2371
- resourceTimeWriteStartedAt = null; timeWriteStartedElapsedMs = null
2372
2142
  sendAwaitingAck(
2373
2143
  NimoProtocol.CMD_SET_PARAMETER,
2374
2144
  NimoProtocol.SET_TIME,
2375
2145
  NimoFrameCodec.encodeDeviceTime()
2376
2146
  ) { ok ->
2377
2147
  if (gatt !== expectedGatt || handshakeState != HandshakeState.AWAITING_TIME_ACK) return@sendAwaitingAck
2378
- if (ok && resourceTimeWriteStartedAt == null) {
2379
- resourceTransportFailure = true
2380
- handshakeFailed()
2381
- return@sendAwaitingAck
2382
- }
2383
2148
  if (ok) {
2384
- recordResourceTimeAckClock()
2385
2149
  finishHandshake()
2386
2150
  } else if (setTimeAttempts < SET_TIME_MAX_ATTEMPTS &&
2387
2151
  handshakeState == HandshakeState.AWAITING_TIME_ACK &&
@@ -2426,22 +2190,147 @@ class Nimo : SGCManager() {
2426
2190
  DeviceStore.apply("glasses", "fullyBooted", true)
2427
2191
  DeviceStore.apply("glasses", "connectionState", ConnTypes.CONNECTED)
2428
2192
  startTimers()
2429
- if (diagnostics == null) {
2430
- diagnostics = NimoDiagnostics(
2431
- context,
2432
- mainHandler,
2433
- { frame, completed -> enqueueFrames(listOf(frame), {}, completed) },
2434
- { ready -> canvas.hold(ready) },
2435
- { resume -> canvas.releaseHold(resume) },
2436
- )
2193
+ // The canvas starts once the reported firmware is the supported one.
2194
+ cancelFirmwareTimer = mainScheduler.post(VERSION_WAIT_MS) {
2195
+ cancelFirmwareTimer = null
2196
+ checkFirmware(waited = true)
2437
2197
  }
2438
- diagnostics?.connected((negotiatedMtu - 3).coerceIn(20, 512))
2198
+ }
2199
+
2200
+ // ---------- Firmware check and update ----------
2201
+
2202
+ private fun canvasReadiness(ready: Boolean) {
2203
+ if (firmwareState == FirmwareState.CURRENT) canvas.readiness(ready)
2204
+ }
2205
+
2206
+ /**
2207
+ * Runs once per connection after the version replies (or [VERSION_WAIT_MS]). The supported
2208
+ * firmware starts the canvas; anything else gets the bundled image, after a plain-text notice
2209
+ * that the stock firmware can show.
2210
+ */
2211
+ private fun checkFirmware(waited: Boolean = false) {
2212
+ if (handshakeState != HandshakeState.READY || firmwareState != FirmwareState.UNKNOWN) return
2213
+ if (!waited && !(versionPackedReceived && versionDetailReceived)) return
2214
+ cancelFirmwareTimer?.invoke(); cancelFirmwareTimer = null
2215
+ if (!versionPackedReceived ||
2216
+ NimoFirmwareTarget.isCurrent(firmwareVersionPacked, firmwareVersionDetail)) {
2217
+ if (!versionPackedReceived) Bridge.log("NIMO: no firmware version reply; starting normally")
2218
+ startCanvas()
2219
+ return
2220
+ }
2221
+ Bridge.log("NIMO: firmware $firmwareVersionPacked '$firmwareVersionDetail' is not " +
2222
+ "${NimoFirmwareTarget.PACKED_VERSION}-${NimoFirmwareTarget.BUILD_TAG}")
2223
+ val firmware = if (updateAttempts < MAX_UPDATE_ATTEMPTS) loadFirmware() else null
2224
+ val connection = gatt
2225
+ if (firmware == null || connection == null || otaTxChar == null || otaRxChar == null) {
2226
+ Bridge.log("NIMO: firmware update unavailable (attempts=$updateAttempts); starting normally")
2227
+ startCanvas()
2228
+ return
2229
+ }
2230
+ updateAttempts++
2231
+ Bridge.log("NIMO: starting firmware update attempt $updateAttempts")
2232
+ showUpdateNotice(connection)
2233
+ audioClient.stop() // Its stop command must be queued before ordinary writes close.
2234
+ firmwareState = FirmwareState.UPDATING
2235
+ stopTimers()
2236
+ DeviceStore.apply("glasses", "micEnabled", false)
2237
+ // Prepare the channel after the notice frames drain and the wearer has had time to read it.
2238
+ cancelFirmwareTimer = mainScheduler.post(UPDATE_NOTICE_MS) {
2239
+ cancelFirmwareTimer = mainScheduler.post(OTA_PREPARE_TIMEOUT_MS) {
2240
+ cancelFirmwareTimer = null
2241
+ abortTransport("NIMO firmware update channel did not become ready")
2242
+ }
2243
+ prepareUpdateChannel(connection, firmware)
2244
+ }
2245
+ }
2246
+
2247
+ private fun startCanvas() {
2248
+ firmwareState = FirmwareState.CURRENT
2439
2249
  // Launch checks peer readiness in firmware; do not wait up to a minute for
2440
2250
  // the first unsolicited heartbeat just because peer status is still unknown.
2441
2251
  canvas.activate()
2442
2252
  canvas.readiness(twsConnected && peerCompanionReady != false)
2443
2253
  }
2444
2254
 
2255
+ /** The pre-canvas text page (ASR note app); it renders on the stock firmware too. */
2256
+ private fun showUpdateNotice(connection: BluetoothGatt) {
2257
+ val tx = txChar ?: return
2258
+ val enter = NimoFrameCodec.encodeFrame(
2259
+ NimoProtocol.CMD_CONTROL_INSTRUCTION,
2260
+ NimoProtocol.CTRL_ENTER_APP,
2261
+ byteArrayOf(NimoProtocol.APP_ID_ASR_NOTE.toByte(), NimoProtocol.APP_MODE_STANDALONE.toByte()))
2262
+ val text = NimoFrameCodec.updateContentFrames(
2263
+ appId = NimoProtocol.APP_ID_ASR_NOTE,
2264
+ layoutId = 0,
2265
+ resId = 0,
2266
+ resType = NimoProtocol.WIDGET_TEXT_NEW,
2267
+ content = NimoFirmwareTarget.UPDATING_TEXT.toByteArray(Charsets.UTF_8))
2268
+ writes.enqueue(connection, tx, listOf(enter) + text)
2269
+ }
2270
+
2271
+ private fun loadFirmware(): ByteArray? = try {
2272
+ val bytes = context.assets.open(NimoFirmwareTarget.ASSET_PATH).use { it.readBytes() }
2273
+ if (NimoFirmwareTarget.sha256(bytes) == NimoFirmwareTarget.SHA256) bytes
2274
+ else { Bridge.log("NIMO: bundled firmware hash mismatch"); null }
2275
+ } catch (error: Exception) {
2276
+ Bridge.log("NIMO: bundled firmware unavailable: ${error.message}")
2277
+ null
2278
+ }
2279
+
2280
+ /** Waits for queued writes to finish, raises the MTU and subscribes to the OTA replies. */
2281
+ private fun prepareUpdateChannel(connection: BluetoothGatt, firmware: ByteArray) {
2282
+ if (gatt !== connection || !updating) return
2283
+ if (writes.pendingCount() > 0) {
2284
+ mainScheduler.post(20) { prepareUpdateChannel(connection, firmware) }
2285
+ return
2286
+ }
2287
+ val subscribe = {
2288
+ val rx = otaRxChar
2289
+ if (gatt === connection && updating && rx != null) {
2290
+ enableNotifications(connection, rx) { startUpdater(connection, firmware) }
2291
+ }
2292
+ }
2293
+ if (negotiatedMtu - 3 > 20) { subscribe(); return }
2294
+ // The vendor warns against MTU requests during connect; now normal traffic is stopped.
2295
+ otaMtuPending = subscribe
2296
+ val started = try { connection.requestMtu(517) } catch (_: SecurityException) { false }
2297
+ if (!started) {
2298
+ otaMtuPending = null
2299
+ abortTransport("NIMO firmware update MTU request did not start")
2300
+ }
2301
+ }
2302
+
2303
+ private fun startUpdater(connection: BluetoothGatt, firmware: ByteArray) {
2304
+ if (gatt !== connection || !updating) return
2305
+ cancelFirmwareTimer?.invoke(); cancelFirmwareTimer = null
2306
+ val capacity = (negotiatedMtu - 3).coerceIn(20, 512)
2307
+ if (capacity <= 20) { abortTransport("NIMO firmware update needs a larger MTU"); return }
2308
+ Bridge.log("NIMO: firmware transfer starting (${firmware.size} bytes, write capacity $capacity)")
2309
+ val updater = NimoFirmwareUpdater(
2310
+ firmware, capacity, mainScheduler,
2311
+ write = { bytes, done ->
2312
+ val tx = otaTxChar
2313
+ if (gatt !== connection || tx == null ||
2314
+ !writes.enqueue(connection, tx, listOf(bytes), completed = { done(true) })) done(false)
2315
+ },
2316
+ progress = { Bridge.log("NIMO: firmware update $it%") },
2317
+ finished = finished@{ error ->
2318
+ if (gatt !== connection) return@finished
2319
+ firmwareUpdater = null
2320
+ if (error != null) {
2321
+ abortTransport("NIMO firmware update failed: $error")
2322
+ } else {
2323
+ Bridge.log("NIMO: firmware update sent; glasses are rebooting")
2324
+ cancelFirmwareTimer = mainScheduler.post(POST_UPDATE_RECONNECT_MS) {
2325
+ cancelFirmwareTimer = null
2326
+ if (gatt === connection) abortTransport("NIMO did not reboot after the firmware update")
2327
+ }
2328
+ }
2329
+ })
2330
+ firmwareUpdater = updater
2331
+ updater.start()
2332
+ }
2333
+
2445
2334
  private fun handshakeFailed() {
2446
2335
  handshakeState = HandshakeState.IDLE
2447
2336
  gatt?.disconnect()
@@ -2449,7 +2338,6 @@ class Nimo : SGCManager() {
2449
2338
  }
2450
2339
 
2451
2340
  private fun resetSessionState() {
2452
- diagnostics?.disconnected()
2453
2341
  handshakeState = HandshakeState.IDLE
2454
2342
  cancelTwsTimeout()
2455
2343
  cancelSetTimeRetry()
@@ -2457,6 +2345,12 @@ class Nimo : SGCManager() {
2457
2345
  peerCompanionReady = null
2458
2346
  canvasEncoder.invalidate()
2459
2347
  canvas.disconnected()
2348
+ cancelFirmwareTimer?.invoke(); cancelFirmwareTimer = null
2349
+ firmwareUpdater?.cancel(); firmwareUpdater = null
2350
+ otaMtuPending = null
2351
+ firmwareState = FirmwareState.UNKNOWN
2352
+ versionPackedReceived = false
2353
+ versionDetailReceived = false
2460
2354
  audioClient.stop()
2461
2355
  // Nimo's decoder/stream belongs to this GATT session. Consumer demand
2462
2356
  // remains in bluetooth.should_send_*; readiness must start a fresh stream
@@ -2474,7 +2368,6 @@ class Nimo : SGCManager() {
2474
2368
  if (fullyBooted) {
2475
2369
  return@start true
2476
2370
  }
2477
- if (!NimoResourceDiagnostics.admit(this, DEVICE_SEARCH_ID, true)) return@start true
2478
2371
  Bridge.log("NIMO: Attempting reconnection...")
2479
2372
  isDisconnecting = false
2480
2373
  // Each reconnection cycle is a fresh bond budget — the glasses drop their
@@ -2514,7 +2407,6 @@ class Nimo : SGCManager() {
2514
2407
 
2515
2408
  private fun handleRxPacket(packet: ByteArray) {
2516
2409
  // Diagnostic packets must retain their original wire CRC and framing.
2517
- if (diagnostics?.onPacket(packet) == true) return
2518
2410
  if (packet.size >= 10 && packet[8].toInt() == 7 && (packet[9].toInt() and 255) in listOf(1, 3, 4)) {
2519
2411
  val response = NimoCanvasCodec.response(packet) ?: return
2520
2412
  if (response.first == 1) Bridge.log("NIMO: canvas Launch response status=${response.second.firstOrNull()?.toInt()}")
@@ -2546,15 +2438,9 @@ class Nimo : SGCManager() {
2546
2438
  Bridge.log("NIMO: app state report appId=$appId phase=$phase")
2547
2439
  when (phase) {
2548
2440
  NimoProtocol.STATE_ENTER -> {
2549
- if (appId != NimoCanvasCodec.APP_ID) {
2550
- diagnostics?.cancelHeldCapture("Native app takeover preempted held capture", resumeCanvas = false)
2551
- }
2552
2441
  canvas.nativeApp(appId, true)
2553
2442
  }
2554
2443
  NimoProtocol.STATE_EXIT -> {
2555
- if (appId == NimoCanvasCodec.APP_ID) {
2556
- diagnostics?.cancelHeldCapture("Canvas exit preempted held capture", resumeCanvas = false)
2557
- }
2558
2444
  canvas.nativeApp(appId, false)
2559
2445
  }
2560
2446
  }
@@ -2586,7 +2472,7 @@ class Nimo : SGCManager() {
2586
2472
  onTwsState((v[8].toInt() and 0xFF) >= 1)
2587
2473
  // Both predicates were sampled by this device report. TWS-only
2588
2474
  // reports and cached state cannot release a status-7 wait.
2589
- if (handshakeState == HandshakeState.READY) {
2475
+ if (handshakeState == HandshakeState.READY && firmwareState == FirmwareState.CURRENT) {
2590
2476
  canvas.confirmedReadiness(twsConnected && peerCompanionReady != false)
2591
2477
  }
2592
2478
  }
@@ -2606,7 +2492,6 @@ class Nimo : SGCManager() {
2606
2492
  }
2607
2493
 
2608
2494
  private fun onTwsState(connected: Boolean) {
2609
- recordResourceTwsClock()
2610
2495
  twsConnected = connected
2611
2496
  if (connected && handshakeState == HandshakeState.AWAITING_TWS) {
2612
2497
  proceedToTimeSync()
@@ -2614,7 +2499,7 @@ class Nimo : SGCManager() {
2614
2499
  if (!connected && handshakeState == HandshakeState.READY) {
2615
2500
  Bridge.log("NIMO: TWS service dropped mid-session (arm removed/off?)")
2616
2501
  }
2617
- if (handshakeState == HandshakeState.READY) canvas.readiness(connected && peerCompanionReady != false)
2502
+ if (handshakeState == HandshakeState.READY) canvasReadiness(connected && peerCompanionReady != false)
2618
2503
  }
2619
2504
 
2620
2505
  private fun handleInputEvent(code: Int) {
@@ -2679,18 +2564,18 @@ class Nimo : SGCManager() {
2679
2564
  val micro = (v ushr 12) and 0x1FF
2680
2565
  val build = v and 0xFFF
2681
2566
  firmwareVersionPacked = "$major.$minor.$micro.$build"
2682
- resourceFirmwareVersion = firmwareVersionPacked; recordResourceFirmwareClock()
2567
+ versionPackedReceived = true
2683
2568
  emitVersionInfo()
2569
+ checkFirmware()
2684
2570
  }
2685
2571
  }
2686
2572
  NimoProtocol.GET_VERSION_DETAIL -> {
2687
2573
  var end = data.size
2688
2574
  while (end > 0 && data[end - 1].toInt() == 0) end--
2689
2575
  firmwareVersionDetail = String(data, 0, end, Charsets.UTF_8).trim()
2690
- if (firmwareVersionDetail.isNotEmpty() && firmwareVersionDetail.length <= 240) {
2691
- resourceFirmwareVersion = firmwareVersionDetail; recordResourceFirmwareClock()
2692
- }
2576
+ versionDetailReceived = true
2693
2577
  emitVersionInfo()
2578
+ checkFirmware()
2694
2579
  }
2695
2580
  NimoProtocol.GET_TWS_STATUS -> {
2696
2581
  if (data.isNotEmpty()) onTwsState((data[0].toInt() and 0xFF) >= 1)