@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.4.1-beta.1409
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.
- package/MIGRATION.md +16 -7
- package/README.md +41 -14
- package/android/build.gradle +60 -51
- package/android/gradle.properties +3 -0
- package/android/settings.gradle +47 -3
- package/android/src/main/assets/nimo/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +77 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +41 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +131 -122
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +3 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +31 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +57 -196
- package/android/src/main/java/com/mentra/bluetoothsdk/OtaManifest.kt +1 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +10 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/Ipv4Prefix.kt +51 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/NetworkFacts.kt +81 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkError.kt +108 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadiness.kt +103 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpec.kt +44 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkState.kt +117 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/ScopedSoftApNetwork.kt +598 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/hotspot/SoftApTrace.kt +143 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/otaserver/MentraOtaServerModule.kt +0 -7
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +15 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +308 -60
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicy.kt +14 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +210 -325
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdater.kt +213 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocol.kt +112 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/streaming/StreamModels.kt +17 -6
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/StreamRequestCaptureAudioTest.kt +23 -4
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/Ipv4PrefixTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/NetworkFactsTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedLocalNetworkPermissionTest.kt +35 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkErrorTest.kt +85 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkLifecycleTest.kt +164 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkReadinessTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/ScopedNetworkRequestSpecTest.kt +56 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/SoftApTraceTest.kt +97 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/hotspot/UnavailableRetryTest.kt +47 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTrackerTest.kt +26 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveOwnerLossPolicyTest.kt +9 -3
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareTargetTest.kt +15 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoFirmwareUpdaterTest.kt +76 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoOtaProtocolTest.kt +77 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +31 -1
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +103 -5
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +42 -8
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +1 -0
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/generated/changelogCatalog.d.ts +5 -2
- package/build/generated/changelogCatalog.d.ts.map +1 -1
- package/build/generated/changelogCatalog.js +6 -2
- package/build/generated/changelogCatalog.js.map +1 -1
- package/build/generated/releaseMetadata.js +6 -6
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +7 -1
- package/build/index.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.d.ts +0 -2
- package/build/ota-server/MentraOtaServerModule.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.js.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts +0 -1
- package/build/ota-server/MentraOtaServerModule.web.d.ts.map +1 -1
- package/build/ota-server/MentraOtaServerModule.web.js +0 -3
- package/build/ota-server/MentraOtaServerModule.web.js.map +1 -1
- package/build/ota-transport/index.d.ts +3 -3
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +4 -4
- package/build/ota-transport/index.js.map +1 -1
- package/build/react/useGlassesConnection.d.ts +1 -1
- package/build/react/useGlassesConnection.d.ts.map +1 -1
- package/build/react/useGlassesConnection.js +3 -3
- package/build/react/useGlassesConnection.js.map +1 -1
- package/build/react/useMentraBluetooth.d.ts +1 -1
- package/build/react/useMentraBluetooth.d.ts.map +1 -1
- package/build/react/useMentraBluetooth.js +1 -1
- package/build/react/useMentraBluetooth.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +73 -22
- package/ios/LocalIPv4.swift +0 -61
- package/ios/MentraBluetoothSDK.podspec +7 -1
- package/ios/MentraOtaServerModule.swift +0 -16
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/NimoFirmware/nimo-firmware-0.1.1.1-537cf1.bin +0 -0
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BesCrashReportWaiters.swift +64 -0
- package/ios/Source/BluetoothSdkDefaults.swift +4 -4
- package/ios/Source/Bridge.swift +14 -0
- package/ios/Source/DeviceManager.swift +52 -22
- package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +35 -16
- package/ios/Source/OtaManifest.swift +1 -17
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/events/BluetoothEvents.swift +41 -0
- package/ios/Source/internal/BleTraceLogger.swift +14 -1
- package/ios/Source/internal/BluetoothAvailability.swift +15 -5
- package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
- package/ios/Source/sgcs/MentraLive.swift +207 -66
- package/ios/Source/sgcs/Nimo.swift +249 -276
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
- package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
- package/ios/Source/sgcs/NimoFirmwareUpdater.swift +260 -0
- package/ios/Source/sgcs/NimoOtaProtocol.swift +159 -0
- package/ios/Source/sgcs/SGCManager.swift +6 -0
- package/ios/Source/streaming/StreamModels.swift +15 -6
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/BesCrashReportTests.swift +142 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
- package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
- package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
- package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
- package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
- package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
- package/ios/Tests/NimoOtaProtocolTests.swift +78 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/StreamRequestTests.swift +18 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +9 -11
- package/plugin/build/withKotlinVersion.d.ts +2 -0
- package/plugin/build/withKotlinVersion.js +46 -0
- package/src/BluetoothSdk.types.ts +107 -5
- package/src/_private/BluetoothSdkModule.ts +45 -8
- package/src/_private/MentraLocalNetworkModule.ts +5 -1
- package/src/generated/changelogCatalog.ts +6 -2
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +13 -1
- package/src/ota-server/MentraOtaServerModule.ts +0 -2
- package/src/ota-server/MentraOtaServerModule.web.ts +0 -4
- package/src/ota-transport/index.ts +4 -5
- package/src/react/useGlassesConnection.ts +4 -4
- package/src/react/useMentraBluetooth.ts +2 -2
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
- package/android/src/main/java/com/mentra/bluetoothsdk/ScopedNetworkReadiness.kt +0 -17
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
- package/android/src/test/java/com/mentra/bluetoothsdk/ScopedNetworkReadinessTest.kt +0 -39
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
- package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
- package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
- package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
- package/ios/Tests/NimoResourceSessionTests.swift +0 -476
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -19,6 +19,9 @@ enum NimoBLE {
|
|
|
19
19
|
static let CHAR_TX = CBUUID(string: "00002021-0000-1000-8000-00805F9B34FB")
|
|
20
20
|
static let CHAR_RX = CBUUID(string: "00002022-0000-1000-8000-00805F9B34FB")
|
|
21
21
|
static let CHAR_MIC = CBUUID(string: "00002025-0000-1000-8000-00805F9B34FB")
|
|
22
|
+
/// Firmware update channel on the same service (see NimoOtaProtocol).
|
|
23
|
+
static let CHAR_OTA_TX = CBUUID(string: "00002001-0000-1000-8000-00805F9B34FB")
|
|
24
|
+
static let CHAR_OTA_RX = CBUUID(string: "00002002-0000-1000-8000-00805F9B34FB")
|
|
22
25
|
|
|
23
26
|
static let CHUNK_SIZE = 501
|
|
24
27
|
static let INTER_FRAME_DELAY_MS = 5
|
|
@@ -536,7 +539,6 @@ private class NimoOpusDecoder {
|
|
|
536
539
|
|
|
537
540
|
actor NimoReconnectionManager {
|
|
538
541
|
private var task: Task<Void, Never>?
|
|
539
|
-
private(set) var liveTasks = 0
|
|
540
542
|
private let intervalSeconds: UInt64
|
|
541
543
|
|
|
542
544
|
init(intervalSeconds: UInt64 = 30) {
|
|
@@ -545,9 +547,7 @@ actor NimoReconnectionManager {
|
|
|
545
547
|
|
|
546
548
|
func start(_ onAttempt: @escaping () async -> Bool) {
|
|
547
549
|
stop()
|
|
548
|
-
liveTasks += 1
|
|
549
550
|
task = Task {
|
|
550
|
-
defer { liveTasks -= 1 }
|
|
551
551
|
var attempts = 0
|
|
552
552
|
while !Task.isCancelled {
|
|
553
553
|
try? await Task.sleep(nanoseconds: intervalSeconds * 1_000_000_000)
|
|
@@ -562,13 +562,6 @@ actor NimoReconnectionManager {
|
|
|
562
562
|
}
|
|
563
563
|
}
|
|
564
564
|
|
|
565
|
-
func stopAndWait() async {
|
|
566
|
-
let original = task
|
|
567
|
-
original?.cancel()
|
|
568
|
-
await original?.value
|
|
569
|
-
if liveTasks == 0 { task = nil }
|
|
570
|
-
}
|
|
571
|
-
|
|
572
565
|
func stop() {
|
|
573
566
|
task?.cancel()
|
|
574
567
|
task = nil
|
|
@@ -578,34 +571,6 @@ actor NimoReconnectionManager {
|
|
|
578
571
|
// MARK: - Nimo Class
|
|
579
572
|
|
|
580
573
|
class Nimo: NSObject, SGCManager {
|
|
581
|
-
let resourceInstanceId = UUID().uuidString.lowercased()
|
|
582
|
-
private(set) var resourceMicEnabled = false
|
|
583
|
-
private var resourceReleaseTask: Task<Void, Never>?
|
|
584
|
-
private var resourceNotificationElapsedMs: UInt64?
|
|
585
|
-
private var resourceTimeCommand: String?
|
|
586
|
-
private var resourceReconnectTasks = 0
|
|
587
|
-
nonisolated private let resourceCallbackCounter = NimoResourceCallbackCounter()
|
|
588
|
-
var resourceCanvasRequired: Bool { canvas.mayHaveEntered }
|
|
589
|
-
var resourceMicStopRequired: Bool { resourceMicEnabled || resourceSession?.connected == true }
|
|
590
|
-
#if SWIFT_PACKAGE
|
|
591
|
-
// Package-only, radio-free fixture for exercising actual private wiring.
|
|
592
|
-
private var packageTestResourceSession: NimoResourceSession?
|
|
593
|
-
#endif
|
|
594
|
-
private var resourceSession: NimoResourceSession? {
|
|
595
|
-
#if SWIFT_PACKAGE
|
|
596
|
-
if let packageTestResourceSession { return packageTestResourceSession }
|
|
597
|
-
#endif
|
|
598
|
-
return NimoResourceFixture.shared.captured(self)
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
nonisolated private func postCallback(_ action: @escaping @MainActor () -> Void) {
|
|
602
|
-
resourceCallbackCounter.add(1)
|
|
603
|
-
DispatchQueue.main.async { [self] in
|
|
604
|
-
action()
|
|
605
|
-
resourceCallbackCounter.add(-1)
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
|
|
609
574
|
var type: String = DeviceTypes.NIMO
|
|
610
575
|
let hasMic = true
|
|
611
576
|
let showBrightnessConfirmation = false
|
|
@@ -621,14 +586,27 @@ class Nimo: NSObject, SGCManager {
|
|
|
621
586
|
static let batteryPollSeconds: TimeInterval = 30
|
|
622
587
|
/// Fall back to the other ear if the preferred one goes quiet for this long.
|
|
623
588
|
static let micSideFallbackSeconds: TimeInterval = 2
|
|
589
|
+
/// Version replies normally arrive within a few hundred ms of the handshake.
|
|
590
|
+
static let versionWaitSeconds: TimeInterval = 3
|
|
591
|
+
/// Let the wearer read the update notice before the display goes away.
|
|
592
|
+
static let updateNoticeSeconds: TimeInterval = 2
|
|
593
|
+
static let otaPrepareTimeoutSeconds: TimeInterval = 15
|
|
594
|
+
/// The glasses reboot after the update; force a reconnect if they never drop the link.
|
|
595
|
+
static let postUpdateReconnectSeconds: TimeInterval = 120
|
|
596
|
+
/// Per app process, so a failing update cannot loop forever.
|
|
597
|
+
static let maxUpdateAttempts = 3
|
|
624
598
|
}
|
|
625
599
|
|
|
600
|
+
private static var updateAttempts = 0
|
|
601
|
+
|
|
626
602
|
// BLE
|
|
627
603
|
private var centralManager: CBCentralManager?
|
|
628
604
|
private var peripheral: CBPeripheral?
|
|
629
605
|
private var txChar: CBCharacteristic?
|
|
630
606
|
private var rxChar: CBCharacteristic?
|
|
631
607
|
private var micChar: CBCharacteristic?
|
|
608
|
+
private var otaTxChar: CBCharacteristic?
|
|
609
|
+
private var otaRxChar: CBCharacteristic?
|
|
632
610
|
private var isDisconnecting = false
|
|
633
611
|
private var scanRequested = false
|
|
634
612
|
private lazy var discovery = NimoDiscovery<CBPeripheral>(
|
|
@@ -718,11 +696,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
718
696
|
enqueue: { [weak self] frames, started, completed in
|
|
719
697
|
self?.enqueueFrames(frames, finalStarted: started, completed: completed) ?? false
|
|
720
698
|
}, reconnect: { [weak self] in self?.abortTransport($0) },
|
|
721
|
-
rejected: { Bridge.log("NIMO: canvas rejected status=\($0); not a render ACK") }
|
|
722
|
-
observedResult: { [weak self] key, status, received in
|
|
723
|
-
guard let self else { return }
|
|
724
|
-
if key == 3 { self.resourceSession?.exitAcknowledged(self, status: status, receivedElapsedMs: received) }
|
|
725
|
-
}, continuousNow: NimoResourceClock.now
|
|
699
|
+
rejected: { Bridge.log("NIMO: canvas rejected status=\($0); not a render ACK") }
|
|
726
700
|
)
|
|
727
701
|
private var batteryPollTimer: Timer?
|
|
728
702
|
|
|
@@ -733,6 +707,17 @@ class Nimo: NSObject, SGCManager {
|
|
|
733
707
|
// Version info
|
|
734
708
|
private var firmwareVersionPacked = ""
|
|
735
709
|
private var firmwareVersionDetail = ""
|
|
710
|
+
private var versionPackedReceived = false
|
|
711
|
+
private var versionDetailReceived = false
|
|
712
|
+
|
|
713
|
+
/// Firmware gate: the canvas only runs on the supported firmware; anything else is updated first.
|
|
714
|
+
private enum FirmwareState { case unknown, current, updating }
|
|
715
|
+
private var firmwareState = FirmwareState.unknown
|
|
716
|
+
private var firmwareUpdater: NimoFirmwareUpdater?
|
|
717
|
+
private var cancelFirmwareTimer: (() -> Void)?
|
|
718
|
+
private var otaNotifyPending: (() -> Void)?
|
|
719
|
+
private var pendingOtaWrite: (Data, (Bool) -> Void)?
|
|
720
|
+
private var updating: Bool { firmwareState == .updating }
|
|
736
721
|
|
|
737
722
|
// Mic audio
|
|
738
723
|
private var opusDecoder: NimoOpusDecoder?
|
|
@@ -742,7 +727,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
742
727
|
// MARK: - SGCManager: Connection Management
|
|
743
728
|
|
|
744
729
|
func findCompatibleDevices() {
|
|
745
|
-
guard NimoResourceFixture.shared.admit(self, name: nil) else { return }
|
|
746
730
|
Bridge.log("NIMO: findCompatibleDevices()")
|
|
747
731
|
DEVICE_SEARCH_ID = "NOT_SET"
|
|
748
732
|
isDisconnecting = false
|
|
@@ -752,7 +736,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
752
736
|
}
|
|
753
737
|
|
|
754
738
|
func connectById(_ id: String) {
|
|
755
|
-
guard NimoResourceFixture.shared.admit(self, name: id) else { return }
|
|
756
739
|
Bridge.log("NIMO: connectById(\(id))")
|
|
757
740
|
DEVICE_SEARCH_ID = id
|
|
758
741
|
scanRequested = true
|
|
@@ -769,10 +752,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
769
752
|
|
|
770
753
|
func disconnect() {
|
|
771
754
|
Bridge.log("NIMO: disconnect()")
|
|
772
|
-
if let resourceSession,
|
|
773
|
-
!resourceSession.shouldRunOrdinaryDisconnect(self, originalClosed: NimoResourceFixture.shared.hasVerifiedOriginalClosure(self)) {
|
|
774
|
-
return
|
|
775
|
-
}
|
|
776
755
|
isDisconnecting = true
|
|
777
756
|
cancelPairingTimeout()
|
|
778
757
|
cancelTwsTimeout()
|
|
@@ -788,6 +767,8 @@ class Nimo: NSObject, SGCManager {
|
|
|
788
767
|
txChar = nil
|
|
789
768
|
rxChar = nil
|
|
790
769
|
micChar = nil
|
|
770
|
+
otaTxChar = nil
|
|
771
|
+
otaRxChar = nil
|
|
791
772
|
resetSessionState()
|
|
792
773
|
|
|
793
774
|
DeviceStore.shared.apply("glasses", "connected", false)
|
|
@@ -797,7 +778,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
797
778
|
|
|
798
779
|
/// Explicit Unpair only; passive forget/cleanup must never reset the glasses.
|
|
799
780
|
func resetForUnpair(onResult: @escaping (Bool) -> Void) {
|
|
800
|
-
if let resourceSession { resourceSession.recordError("factory-reset-refused-during-capture"); onResult(false); return }
|
|
801
781
|
guard peripheral != nil, txChar != nil, handshakeState == .ready else {
|
|
802
782
|
Bridge.log("NIMO: unpair while offline; remote reset unavailable")
|
|
803
783
|
onResult(false)
|
|
@@ -818,7 +798,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
818
798
|
}
|
|
819
799
|
|
|
820
800
|
func forget() {
|
|
821
|
-
if let resourceSession { resourceSession.recordError("forget-refused-during-capture"); return }
|
|
822
801
|
Bridge.log("NIMO: forget()")
|
|
823
802
|
disconnect()
|
|
824
803
|
lastDeviceName = nil
|
|
@@ -851,13 +830,15 @@ class Nimo: NSObject, SGCManager {
|
|
|
851
830
|
// MARK: - SGCManager: Audio Control
|
|
852
831
|
|
|
853
832
|
func setMicEnabled(_ enabled: Bool) {
|
|
854
|
-
guard NimoResourceFixture.shared.allowsProducer(self) else { return }
|
|
855
833
|
Bridge.log("NIMO: setMicEnabled(\(enabled))")
|
|
856
834
|
guard let micChar else {
|
|
857
835
|
Bridge.log("NIMO: mic characteristic not available")
|
|
858
836
|
return
|
|
859
837
|
}
|
|
860
|
-
|
|
838
|
+
if enabled, updating {
|
|
839
|
+
Bridge.log("NIMO: mic stays off during the firmware update")
|
|
840
|
+
return
|
|
841
|
+
}
|
|
861
842
|
DeviceStore.shared.apply("glasses", "micEnabled", enabled)
|
|
862
843
|
if enabled {
|
|
863
844
|
if opusDecoder == nil {
|
|
@@ -964,7 +945,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
964
945
|
}
|
|
965
946
|
|
|
966
947
|
private func encodeCanvas(scope: String, force: Bool = false, encode: @escaping () throws -> Data) {
|
|
967
|
-
guard NimoResourceFixture.shared.allowsProducer(self) else { return }
|
|
968
948
|
canvasEncoder.submit(encode: encode) { [weak self] bytes in
|
|
969
949
|
self?.canvas.offer(bytes, scope: scope, force: force)
|
|
970
950
|
}
|
|
@@ -1163,7 +1143,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
1163
1143
|
|
|
1164
1144
|
@discardableResult
|
|
1165
1145
|
private func startScan() -> Bool {
|
|
1166
|
-
guard scanRequested, !isDisconnecting
|
|
1146
|
+
guard scanRequested, !isDisconnecting else { return false }
|
|
1167
1147
|
Bridge.log("NIMO: startScan()")
|
|
1168
1148
|
if centralManager == nil {
|
|
1169
1149
|
centralManager = CBCentralManager(
|
|
@@ -1195,7 +1175,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
1195
1175
|
guard DEVICE_SEARCH_ID != "NOT_SET", name == DEVICE_SEARCH_ID,
|
|
1196
1176
|
self.peripheral == nil else { return }
|
|
1197
1177
|
Bridge.log("NIMO: Connecting to \(name)")
|
|
1198
|
-
guard NimoResourceFixture.shared.beginTransport(self, peripheral: peripheral, uuid: peripheral.identifier.uuidString) else { return }
|
|
1199
1178
|
stopScan()
|
|
1200
1179
|
lastDeviceName = name
|
|
1201
1180
|
lastDeviceUUID = peripheral.identifier.uuidString
|
|
@@ -1215,7 +1194,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
1215
1194
|
else { return false }
|
|
1216
1195
|
|
|
1217
1196
|
Bridge.log("NIMO: connectByUUID - \(known.name ?? uuidString)")
|
|
1218
|
-
guard NimoResourceFixture.shared.beginTransport(self, peripheral: known, uuid: known.identifier.uuidString) else { return false }
|
|
1219
1197
|
peripheral = known
|
|
1220
1198
|
known.delegate = self
|
|
1221
1199
|
centralManager?.connect(known, options: nil)
|
|
@@ -1243,7 +1221,8 @@ class Nimo: NSObject, SGCManager {
|
|
|
1243
1221
|
// MARK: - Write Queue
|
|
1244
1222
|
|
|
1245
1223
|
private func enqueueWrite(_ characteristic: CBCharacteristic, _ bytes: Data) {
|
|
1246
|
-
|
|
1224
|
+
// The firmware update owns the link; ordinary commands wait for the next connection.
|
|
1225
|
+
guard !updating, let peripheral else { return }
|
|
1247
1226
|
writes.enqueue(peripheral, characteristic: characteristic, frames: [bytes])
|
|
1248
1227
|
}
|
|
1249
1228
|
|
|
@@ -1255,18 +1234,13 @@ class Nimo: NSObject, SGCManager {
|
|
|
1255
1234
|
private func enqueueFrames(_ frames: [Data], finalStarted: @escaping () -> Void,
|
|
1256
1235
|
completed: @escaping () -> Void) -> Bool
|
|
1257
1236
|
{
|
|
1258
|
-
guard let peripheral, let txChar else { return false }
|
|
1259
|
-
if let resourceSession, resourceSession.releaseNonce != nil, frames.first?.count ?? 0 > 9, frames.first?[9] != 3 { return false }
|
|
1237
|
+
guard !updating, let peripheral, let txChar else { return false }
|
|
1260
1238
|
return writes.enqueue(peripheral, characteristic: txChar, frames: frames,
|
|
1261
1239
|
finalStarted: finalStarted, completed: completed)
|
|
1262
1240
|
}
|
|
1263
1241
|
|
|
1264
1242
|
private func abortTransport(_ reason: String) {
|
|
1265
1243
|
Bridge.log("NIMO: retiring transport: \(reason)")
|
|
1266
|
-
if let resourceSession {
|
|
1267
|
-
resourceSession.recordError("transport-retired: \(reason)")
|
|
1268
|
-
if resourceSession.releaseNonce != nil { resourceSession.disconnectRequested(self) }
|
|
1269
|
-
}
|
|
1270
1244
|
resetSessionState()
|
|
1271
1245
|
if let peripheral { centralManager?.cancelPeripheralConnection(peripheral) }
|
|
1272
1246
|
}
|
|
@@ -1274,29 +1248,21 @@ class Nimo: NSObject, SGCManager {
|
|
|
1274
1248
|
// MARK: - Pending ACKs
|
|
1275
1249
|
|
|
1276
1250
|
private func sendAwaitingAck(
|
|
1277
|
-
cmd: Int, key: Int, payload: Data,
|
|
1251
|
+
cmd: Int, key: Int, payload: Data, onResult: @escaping (Bool) -> Void
|
|
1278
1252
|
) {
|
|
1279
|
-
guard NimoResourceFixture.shared.allowsProducer(self) else { onResult(false); return }
|
|
1280
1253
|
let ackKey = (cmd << 8) | key
|
|
1281
1254
|
// Only one in-flight ack per (cmd,key); fail any previous waiter.
|
|
1282
1255
|
if let previous = pendingAcks.removeValue(forKey: ackKey) {
|
|
1283
1256
|
previous.timeoutItem.cancel()
|
|
1284
1257
|
previous.onResult(false)
|
|
1285
1258
|
}
|
|
1286
|
-
let timeoutItem =
|
|
1259
|
+
let timeoutItem = DispatchWorkItem { [weak self] in
|
|
1260
|
+
guard let self else { return }
|
|
1261
|
+
self.pendingAcks.removeValue(forKey: ackKey)?.onResult(false)
|
|
1262
|
+
}
|
|
1287
1263
|
pendingAcks[ackKey] = PendingAck(onResult: onResult, timeoutItem: timeoutItem)
|
|
1288
1264
|
DispatchQueue.main.asyncAfter(deadline: .now() + Const.ackTimeoutSeconds, execute: timeoutItem)
|
|
1289
|
-
|
|
1290
|
-
writes.enqueue(peripheral, characteristic: txChar,
|
|
1291
|
-
frames: [NimoFrameCodec.encodeFrame(cmd: cmd, key: key, payload: payload, needsAck: true)],
|
|
1292
|
-
finalStarted: writeStarted, completed: writeCompleted)
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
private func pendingAckTimeoutAction(_ ackKey: Int) -> () -> Void {
|
|
1296
|
-
{ [weak self] in self?.pendingAcks.removeValue(forKey: ackKey)?.onResult(false) }
|
|
1297
|
-
}
|
|
1298
|
-
private func pendingAckTimeout(_ ackKey: Int) -> DispatchWorkItem {
|
|
1299
|
-
DispatchWorkItem(block: pendingAckTimeoutAction(ackKey))
|
|
1265
|
+
sendFrame(NimoFrameCodec.encodeFrame(cmd: cmd, key: key, payload: payload, needsAck: true))
|
|
1300
1266
|
}
|
|
1301
1267
|
|
|
1302
1268
|
private func resolvePendingAck(cmd: Int, key: Int, success: Bool) {
|
|
@@ -1354,34 +1320,23 @@ class Nimo: NSObject, SGCManager {
|
|
|
1354
1320
|
}
|
|
1355
1321
|
|
|
1356
1322
|
private func attemptSetTime() {
|
|
1357
|
-
guard
|
|
1323
|
+
guard handshakeState == .awaitingTimeAck, let expected = peripheral else { return }
|
|
1358
1324
|
setTimeAttempts += 1
|
|
1359
|
-
let command = resourceSession?.beginTimeCommand(self)
|
|
1360
|
-
resourceTimeCommand = command
|
|
1361
1325
|
sendAwaitingAck(cmd: NimoProtocol.CMD_SET_PARAMETER, key: NimoProtocol.SET_TIME,
|
|
1362
|
-
payload: NimoFrameCodec.encodeDeviceTime()
|
|
1363
|
-
writeStarted: { [weak self] in guard let self, let command else { return }; self.resourceSession?.timeWriteStarted(self, command: command) },
|
|
1364
|
-
writeCompleted: { [weak self] in guard let self, let command else { return }; self.resourceSession?.timeWriteCompleted(self, command: command)
|
|
1365
|
-
if self.resourceSession?.ready == true, self.handshakeState == .awaitingTimeAck { self.finishHandshake() }
|
|
1366
|
-
})
|
|
1326
|
+
payload: NimoFrameCodec.encodeDeviceTime())
|
|
1367
1327
|
{ [weak self] ok in
|
|
1368
|
-
self
|
|
1328
|
+
guard let self, self.peripheral === expected, self.handshakeState == .awaitingTimeAck else { return }
|
|
1329
|
+
if ok { self.finishHandshake() }
|
|
1330
|
+
else if self.setTimeAttempts < 3 {
|
|
1331
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
|
|
1332
|
+
guard let self, self.peripheral === expected else { return }
|
|
1333
|
+
self.attemptSetTime()
|
|
1334
|
+
}
|
|
1335
|
+
} else { self.handshakeFailed() }
|
|
1369
1336
|
}
|
|
1370
1337
|
}
|
|
1371
1338
|
|
|
1372
|
-
private func handleTimeSyncResult(_ ok: Bool, expected: CBPeripheral?) {
|
|
1373
|
-
guard peripheral === expected, handshakeState == .awaitingTimeAck else { return }
|
|
1374
|
-
if ok { if resourceSession == nil || resourceSession?.ready == true { finishHandshake() } }
|
|
1375
|
-
else if resourceSession == nil, setTimeAttempts < 3 {
|
|
1376
|
-
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
|
|
1377
|
-
guard let self, self.peripheral === expected else { return }
|
|
1378
|
-
self.attemptSetTime()
|
|
1379
|
-
}
|
|
1380
|
-
} else { handshakeFailed() }
|
|
1381
|
-
}
|
|
1382
|
-
|
|
1383
1339
|
private func finishHandshake() {
|
|
1384
|
-
guard NimoResourceFixture.shared.allowsProducer(self) else { return }
|
|
1385
1340
|
Bridge.log("NIMO: handshake complete — fully connected")
|
|
1386
1341
|
handshakeState = .ready
|
|
1387
1342
|
sendFrame(
|
|
@@ -1404,14 +1359,148 @@ class Nimo: NSObject, SGCManager {
|
|
|
1404
1359
|
DeviceStore.shared.apply("glasses", "fullyBooted", true)
|
|
1405
1360
|
DeviceStore.shared.apply("glasses", "connectionState", ConnTypes.CONNECTED)
|
|
1406
1361
|
startTimers()
|
|
1362
|
+
// The canvas starts once the reported firmware is the supported one.
|
|
1363
|
+
cancelFirmwareTimer = Self.scheduler(.main)(Const.versionWaitSeconds) { [weak self] in
|
|
1364
|
+
self?.cancelFirmwareTimer = nil
|
|
1365
|
+
self?.checkFirmware(waited: true)
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
// MARK: - Firmware check and update
|
|
1370
|
+
|
|
1371
|
+
/// Runs once per connection after the version replies (or `versionWaitSeconds`). The supported
|
|
1372
|
+
/// firmware starts the canvas; anything else gets the bundled image, after a plain-text notice
|
|
1373
|
+
/// that the stock firmware can show.
|
|
1374
|
+
private func checkFirmware(waited: Bool = false) {
|
|
1375
|
+
guard handshakeState == .ready, firmwareState == .unknown else { return }
|
|
1376
|
+
guard waited || (versionPackedReceived && versionDetailReceived) else { return }
|
|
1377
|
+
cancelFirmwareTimer?(); cancelFirmwareTimer = nil
|
|
1378
|
+
if !versionPackedReceived ||
|
|
1379
|
+
NimoFirmwareTarget.isCurrent(packedVersion: firmwareVersionPacked, detail: firmwareVersionDetail)
|
|
1380
|
+
{
|
|
1381
|
+
if !versionPackedReceived { Bridge.log("NIMO: no firmware version reply; starting normally") }
|
|
1382
|
+
startCanvas()
|
|
1383
|
+
return
|
|
1384
|
+
}
|
|
1385
|
+
Bridge.log("NIMO: firmware \(firmwareVersionPacked) '\(firmwareVersionDetail)' is not " +
|
|
1386
|
+
"\(NimoFirmwareTarget.packedVersion)-\(NimoFirmwareTarget.buildTag)")
|
|
1387
|
+
let firmware = Self.updateAttempts < Const.maxUpdateAttempts ? NimoFirmwareTarget.load() : nil
|
|
1388
|
+
guard let firmware, let peripheral, let txChar, otaTxChar != nil, otaRxChar != nil else {
|
|
1389
|
+
Bridge.log("NIMO: firmware update unavailable (attempts=\(Self.updateAttempts)); starting normally")
|
|
1390
|
+
startCanvas()
|
|
1391
|
+
return
|
|
1392
|
+
}
|
|
1393
|
+
Self.updateAttempts += 1
|
|
1394
|
+
Bridge.log("NIMO: starting firmware update attempt \(Self.updateAttempts)")
|
|
1395
|
+
showUpdateNotice(peripheral, txChar)
|
|
1396
|
+
if let micChar { writes.enqueue(peripheral, characteristic: micChar, frames: [Data([0x52, 0x00, 0x00, 0x00])]) }
|
|
1397
|
+
firmwareState = .updating
|
|
1398
|
+
stopTimers()
|
|
1399
|
+
opusDecoder = nil
|
|
1400
|
+
DeviceStore.shared.apply("glasses", "micEnabled", false)
|
|
1401
|
+
let schedule = Self.scheduler(.main)
|
|
1402
|
+
// Prepare the channel after the notice frames drain and the wearer has had time to read it.
|
|
1403
|
+
cancelFirmwareTimer = schedule(Const.updateNoticeSeconds) { [weak self] in
|
|
1404
|
+
guard let self else { return }
|
|
1405
|
+
self.cancelFirmwareTimer = schedule(Const.otaPrepareTimeoutSeconds) { [weak self] in
|
|
1406
|
+
self?.cancelFirmwareTimer = nil
|
|
1407
|
+
self?.abortTransport("NIMO firmware update channel did not become ready")
|
|
1408
|
+
}
|
|
1409
|
+
self.prepareUpdateChannel(peripheral, firmware)
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
private func startCanvas() {
|
|
1414
|
+
firmwareState = .current
|
|
1407
1415
|
// The Launch ACK validates peer readiness without waiting for the first
|
|
1408
1416
|
// unsolicited heartbeat (which can arrive a minute after connection).
|
|
1409
1417
|
canvas.activate()
|
|
1410
1418
|
canvas.readiness(twsConnected && peerCompanionReady != false)
|
|
1411
1419
|
}
|
|
1412
1420
|
|
|
1421
|
+
/// The pre-canvas text page (ASR note app); it renders on the stock firmware too.
|
|
1422
|
+
private func showUpdateNotice(_ peripheral: CBPeripheral, _ txChar: CBCharacteristic) {
|
|
1423
|
+
let enter = NimoFrameCodec.encodeFrame(
|
|
1424
|
+
cmd: NimoProtocol.CMD_CONTROL_INSTRUCTION,
|
|
1425
|
+
key: NimoProtocol.CTRL_ENTER_APP,
|
|
1426
|
+
payload: Data([UInt8(NimoProtocol.APP_ID_ASR_NOTE), UInt8(NimoProtocol.APP_MODE_STANDALONE)])
|
|
1427
|
+
)
|
|
1428
|
+
let text = NimoFrameCodec.updateContentFrames(
|
|
1429
|
+
appId: NimoProtocol.APP_ID_ASR_NOTE,
|
|
1430
|
+
layoutId: 0,
|
|
1431
|
+
resId: 0,
|
|
1432
|
+
resType: NimoProtocol.WIDGET_TEXT_NEW,
|
|
1433
|
+
content: Data(NimoFirmwareTarget.updatingText.utf8)
|
|
1434
|
+
)
|
|
1435
|
+
writes.enqueue(peripheral, characteristic: txChar, frames: [enter] + text)
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/// Waits for queued writes to finish, then subscribes to the OTA replies.
|
|
1439
|
+
private func prepareUpdateChannel(_ expected: CBPeripheral, _ firmware: Data) {
|
|
1440
|
+
guard peripheral === expected, updating, let rx = otaRxChar else { return }
|
|
1441
|
+
guard writes.queuedCount == 0, writes.activeCount == 0 else {
|
|
1442
|
+
_ = Self.scheduler(.main)(0.02) { [weak self] in self?.prepareUpdateChannel(expected, firmware) }
|
|
1443
|
+
return
|
|
1444
|
+
}
|
|
1445
|
+
if rx.isNotifying { startUpdater(expected, firmware); return }
|
|
1446
|
+
otaNotifyPending = { [weak self] in self?.startUpdater(expected, firmware) }
|
|
1447
|
+
expected.setNotifyValue(true, for: rx)
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
private func startUpdater(_ expected: CBPeripheral, _ firmware: Data) {
|
|
1451
|
+
guard peripheral === expected, updating else { return }
|
|
1452
|
+
cancelFirmwareTimer?(); cancelFirmwareTimer = nil
|
|
1453
|
+
let withResponse = otaTxChar?.properties.contains(.writeWithoutResponse) != true
|
|
1454
|
+
let capacity = min(512, expected.maximumWriteValueLength(for: withResponse ? .withResponse : .withoutResponse))
|
|
1455
|
+
guard capacity > 20 else { abortTransport("NIMO firmware update needs a larger MTU"); return }
|
|
1456
|
+
Bridge.log("NIMO: firmware transfer starting (\(firmware.count) bytes, write capacity \(capacity))")
|
|
1457
|
+
let updater = NimoFirmwareUpdater(
|
|
1458
|
+
firmware: firmware, writeCapacity: capacity, schedule: Self.scheduler(.main),
|
|
1459
|
+
write: { [weak self] bytes, done in
|
|
1460
|
+
guard let self, self.peripheral === expected, let tx = self.otaTxChar else { done(false); return }
|
|
1461
|
+
if withResponse {
|
|
1462
|
+
if !self.writes.enqueue(expected, characteristic: tx, frames: [bytes], completed: { done(true) }) { done(false) }
|
|
1463
|
+
} else {
|
|
1464
|
+
guard self.pendingOtaWrite == nil else { done(false); return }
|
|
1465
|
+
self.pendingOtaWrite = (bytes, done)
|
|
1466
|
+
self.drainOtaWrite()
|
|
1467
|
+
}
|
|
1468
|
+
},
|
|
1469
|
+
progress: { Bridge.log("NIMO: firmware update \($0)%") },
|
|
1470
|
+
finished: { [weak self] error in
|
|
1471
|
+
guard let self, self.peripheral === expected else { return }
|
|
1472
|
+
self.firmwareUpdater = nil
|
|
1473
|
+
if let error {
|
|
1474
|
+
self.abortTransport("NIMO firmware update failed: \(error)")
|
|
1475
|
+
return
|
|
1476
|
+
}
|
|
1477
|
+
Bridge.log("NIMO: firmware update sent; glasses are rebooting")
|
|
1478
|
+
self.cancelFirmwareTimer = Self.scheduler(.main)(Const.postUpdateReconnectSeconds) { [weak self] in
|
|
1479
|
+
guard let self else { return }
|
|
1480
|
+
self.cancelFirmwareTimer = nil
|
|
1481
|
+
if self.peripheral === expected { self.abortTransport("NIMO did not reboot after the firmware update") }
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
)
|
|
1485
|
+
firmwareUpdater = updater
|
|
1486
|
+
updater.start()
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/// Write-without-response with CoreBluetooth backpressure; one packet in hand at a time.
|
|
1490
|
+
private func drainOtaWrite() {
|
|
1491
|
+
guard updating, let pending = pendingOtaWrite, let peripheral, let tx = otaTxChar,
|
|
1492
|
+
peripheral.state == .connected, peripheral.canSendWriteWithoutResponse else { return }
|
|
1493
|
+
pendingOtaWrite = nil
|
|
1494
|
+
guard pending.0.count <= peripheral.maximumWriteValueLength(for: .withoutResponse) else {
|
|
1495
|
+
pending.1(false)
|
|
1496
|
+
return
|
|
1497
|
+
}
|
|
1498
|
+
peripheral.writeValue(pending.0, for: tx, type: .withoutResponse)
|
|
1499
|
+
// Complete on the next turn so a long chain never recurses on this stack.
|
|
1500
|
+
DispatchQueue.main.async { pending.1(true) }
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1413
1503
|
private func handshakeFailed() {
|
|
1414
|
-
if let resourceSession, !resourceSession.recordHandshakeFailure(self) { return }
|
|
1415
1504
|
handshakeState = .idle
|
|
1416
1505
|
if let peripheral {
|
|
1417
1506
|
centralManager?.cancelPeripheralConnection(peripheral)
|
|
@@ -1426,6 +1515,13 @@ class Nimo: NSObject, SGCManager {
|
|
|
1426
1515
|
peerCompanionReady = nil
|
|
1427
1516
|
canvasEncoder.invalidate()
|
|
1428
1517
|
canvas.disconnected()
|
|
1518
|
+
cancelFirmwareTimer?(); cancelFirmwareTimer = nil
|
|
1519
|
+
firmwareUpdater?.cancel(); firmwareUpdater = nil
|
|
1520
|
+
otaNotifyPending = nil
|
|
1521
|
+
pendingOtaWrite = nil
|
|
1522
|
+
firmwareState = .unknown
|
|
1523
|
+
versionPackedReceived = false
|
|
1524
|
+
versionDetailReceived = false
|
|
1429
1525
|
receiveAssembler.reset()
|
|
1430
1526
|
writes.reset()
|
|
1431
1527
|
failAllPendingAcks()
|
|
@@ -1433,10 +1529,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
1433
1529
|
}
|
|
1434
1530
|
|
|
1435
1531
|
private func startReconnectionTimer() {
|
|
1436
|
-
|
|
1437
|
-
resourceReconnectTasks += 1
|
|
1438
|
-
Task { [self] in
|
|
1439
|
-
defer { resourceReconnectTasks -= 1 }
|
|
1532
|
+
Task {
|
|
1440
1533
|
await reconnectionManager.start { [weak self] in
|
|
1441
1534
|
guard let self else { return false }
|
|
1442
1535
|
if await MainActor.run(body: {
|
|
@@ -1480,14 +1573,13 @@ class Nimo: NSObject, SGCManager {
|
|
|
1480
1573
|
private func handleRxPacket(_ packet: Data) {
|
|
1481
1574
|
if packet.count >= 10, packet[8] == 7, [1, 3, 4].contains(packet[9]) {
|
|
1482
1575
|
if let response = NimoCanvasCodec.response(packet) {
|
|
1483
|
-
|
|
1484
|
-
guard productAllowed || (resourceSession?.releaseNonce != nil && canvas.acceptsReleaseResponse(key: response.key, payload: response.payload)) else { return }
|
|
1576
|
+
guard (DeviceManager.shared.sgc as? Nimo) === self else { return }
|
|
1485
1577
|
if response.key == 1 { Bridge.log("NIMO: canvas Launch response status=\(response.payload.first.map(Int.init) ?? -1)") }
|
|
1486
|
-
canvas.response(key: response.key, payload: response.payload
|
|
1578
|
+
canvas.response(key: response.key, payload: response.payload)
|
|
1487
1579
|
}
|
|
1488
1580
|
return
|
|
1489
1581
|
}
|
|
1490
|
-
guard (DeviceManager.shared.sgc as? Nimo) === self
|
|
1582
|
+
guard (DeviceManager.shared.sgc as? Nimo) === self else { return }
|
|
1491
1583
|
receiveAssembler.cleanup()
|
|
1492
1584
|
for frame in receiveAssembler.ingest(packet) {
|
|
1493
1585
|
guard let decoded = NimoFrameCodec.decode(frame),
|
|
@@ -1548,7 +1640,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
1548
1640
|
if v.count >= 10 {
|
|
1549
1641
|
peerCompanionReady = v[9] != 0
|
|
1550
1642
|
onTwsState(Int(v[8]) >= 1)
|
|
1551
|
-
if handshakeState == .ready {
|
|
1643
|
+
if handshakeState == .ready, firmwareState == .current {
|
|
1552
1644
|
canvas.readiness(twsConnected && peerCompanionReady != false, confirmed: true)
|
|
1553
1645
|
}
|
|
1554
1646
|
}
|
|
@@ -1565,7 +1657,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
1565
1657
|
}
|
|
1566
1658
|
|
|
1567
1659
|
private func onTwsState(_ connected: Bool) {
|
|
1568
|
-
resourceSession?.observeTws(self, connected: connected, receivedElapsedMs: resourceNotificationElapsedMs)
|
|
1569
1660
|
twsConnected = connected
|
|
1570
1661
|
if connected, handshakeState == .awaitingTws {
|
|
1571
1662
|
proceedToTimeSync()
|
|
@@ -1573,7 +1664,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
1573
1664
|
if !connected, handshakeState == .ready {
|
|
1574
1665
|
Bridge.log("NIMO: TWS service dropped mid-session (arm removed/off?)")
|
|
1575
1666
|
}
|
|
1576
|
-
if handshakeState == .ready { canvas.readiness(connected && peerCompanionReady != false) }
|
|
1667
|
+
if handshakeState == .ready, firmwareState == .current { canvas.readiness(connected && peerCompanionReady != false) }
|
|
1577
1668
|
}
|
|
1578
1669
|
|
|
1579
1670
|
private func handleInputEvent(_ code: Int) {
|
|
@@ -1612,13 +1703,6 @@ class Nimo: NSObject, SGCManager {
|
|
|
1612
1703
|
if cmd == NimoProtocol.CMD_SET_PARAMETER, key == NimoProtocol.SET_SYSTEM_LANGUAGE {
|
|
1613
1704
|
Bridge.log("NIMO: English menu setting acknowledged=\(statusCode == 0) status=\(statusCode)")
|
|
1614
1705
|
}
|
|
1615
|
-
if cmd == NimoProtocol.CMD_SET_PARAMETER, key == NimoProtocol.SET_TIME, let resourceSession {
|
|
1616
|
-
guard let started = resourceSession.timeWriteStartedElapsedMs,
|
|
1617
|
-
let received = resourceNotificationElapsedMs, received >= started else { return }
|
|
1618
|
-
}
|
|
1619
|
-
if cmd == NimoProtocol.CMD_SET_PARAMETER, key == NimoProtocol.SET_TIME, let command = resourceTimeCommand {
|
|
1620
|
-
resourceSession?.timeAck(self, command: command, status: statusCode, receivedElapsedMs: resourceNotificationElapsedMs)
|
|
1621
|
-
}
|
|
1622
1706
|
resolvePendingAck(cmd: cmd, key: key, success: statusCode == 0)
|
|
1623
1707
|
|
|
1624
1708
|
guard cmd == NimoProtocol.CMD_GET_PARAMETER, statusCode == 0 else { return }
|
|
@@ -1641,7 +1725,9 @@ class Nimo: NSObject, SGCManager {
|
|
|
1641
1725
|
let micro = (v >> 12) & 0x1FF
|
|
1642
1726
|
let build = v & 0xFFF
|
|
1643
1727
|
firmwareVersionPacked = "\(major).\(minor).\(micro).\(build)"
|
|
1728
|
+
versionPackedReceived = true
|
|
1644
1729
|
emitVersionInfo()
|
|
1730
|
+
checkFirmware()
|
|
1645
1731
|
}
|
|
1646
1732
|
case NimoProtocol.GET_VERSION_DETAIL:
|
|
1647
1733
|
var end = bytes.count
|
|
@@ -1651,7 +1737,9 @@ class Nimo: NSObject, SGCManager {
|
|
|
1651
1737
|
firmwareVersionDetail =
|
|
1652
1738
|
String(bytes: bytes[0 ..< end], encoding: .utf8)?
|
|
1653
1739
|
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
|
1740
|
+
versionDetailReceived = true
|
|
1654
1741
|
emitVersionInfo()
|
|
1742
|
+
checkFirmware()
|
|
1655
1743
|
case NimoProtocol.GET_TWS_STATUS:
|
|
1656
1744
|
if !bytes.isEmpty {
|
|
1657
1745
|
onTwsState(Int(bytes[0]) >= 1)
|
|
@@ -1684,9 +1772,7 @@ class Nimo: NSObject, SGCManager {
|
|
|
1684
1772
|
// MARK: - Mic Audio
|
|
1685
1773
|
|
|
1686
1774
|
private func handleMicPacket(_ data: Data) {
|
|
1687
|
-
|
|
1688
|
-
guard (DeviceManager.shared.sgc as? Nimo) === self, NimoResourceFixture.shared.allowsProducer(self) else { return }
|
|
1689
|
-
if resourceSession?.releaseNonce != nil { return }
|
|
1775
|
+
guard (DeviceManager.shared.sgc as? Nimo) === self else { return }
|
|
1690
1776
|
guard let packet = NimoAudioParser.parse(data) else { return }
|
|
1691
1777
|
let now = Date()
|
|
1692
1778
|
switch packet.type {
|
|
@@ -1713,134 +1799,14 @@ class Nimo: NSObject, SGCManager {
|
|
|
1713
1799
|
}
|
|
1714
1800
|
}
|
|
1715
1801
|
}
|
|
1716
|
-
|
|
1717
|
-
func resourceProducers() async -> NimoResourceProducers {
|
|
1718
|
-
var result = NimoResourceProducers()
|
|
1719
|
-
result.writerActive = writes.activeCount; result.writerQueued = writes.queuedCount
|
|
1720
|
-
result.encoderWorker = canvasEncoder.workerCount; result.encoderDelivery = canvasEncoder.deliveryCount
|
|
1721
|
-
result.postedCallbacks = resourceCallbackCounter.value + NimoResourceFixture.shared.pendingOriginalManagerEntries
|
|
1722
|
-
result.canvasCommands = canvas.pendingCount; result.pendingAcks = pendingAcks.count
|
|
1723
|
-
// Opus decode, LC3 conversion and Bridge emission are synchronous on
|
|
1724
|
-
// Main on macOS; their entire extent is inside the posted CB callback.
|
|
1725
|
-
result.audioWorkers = 0
|
|
1726
|
-
result.scan = scanRequested ? 1 : 0
|
|
1727
|
-
result.timers = (batteryPollTimer == nil ? 0 : 1) + (twsTimeoutItem == nil ? 0 : 1) + (pairingTimeoutItem == nil ? 0 : 1)
|
|
1728
|
-
result.reconnectTask = await reconnectionManager.liveTasks + resourceReconnectTasks
|
|
1729
|
-
return result
|
|
1730
|
-
}
|
|
1731
|
-
|
|
1732
|
-
func releaseResource(_ original: NimoResourceSession) async {
|
|
1733
|
-
if let resourceReleaseTask { await resourceReleaseTask.value; return }
|
|
1734
|
-
guard original.isOwner(self) else { return }
|
|
1735
|
-
// Retire setup waiters synchronously. Their ACK/timeout can already be
|
|
1736
|
-
// queued when the capture fence is installed; shutdown is not a failed
|
|
1737
|
-
// handshake. The real transport writes and Canvas drain remain intact.
|
|
1738
|
-
handshakeState = .idle
|
|
1739
|
-
cancelTwsTimeout()
|
|
1740
|
-
resolvePendingAck(cmd: NimoProtocol.CMD_SET_PARAMETER, key: NimoProtocol.SET_TIME, success: false)
|
|
1741
|
-
// Original Canvas ACKs may arrive while reconnect tasks are settling.
|
|
1742
|
-
canvas.drainForRelease()
|
|
1743
|
-
let task = Task { @MainActor [self] in
|
|
1744
|
-
isDisconnecting = true
|
|
1745
|
-
stopScan(); stopTimers(); cancelPairingTimeout(); cancelTwsTimeout()
|
|
1746
|
-
canvasEncoder.invalidate()
|
|
1747
|
-
await reconnectionManager.stopAndWait()
|
|
1748
|
-
// Existing pending commands retain their real callbacks/deadlines.
|
|
1749
|
-
// Exit is queued through the same canvas/write state machine.
|
|
1750
|
-
if original.micStopRequired {
|
|
1751
|
-
if let peripheral, let micChar {
|
|
1752
|
-
writes.enqueue(peripheral, characteristic: micChar, frames: [Data([0x52, 0, 0, 0])],
|
|
1753
|
-
finalStarted: { [weak self] in guard let self else { return }; original.micStopStarted(self) },
|
|
1754
|
-
completed: { [weak self] in guard let self else { return }; original.micStopWritten(self) })
|
|
1755
|
-
} else { original.recordError("mic-stop-transport-unavailable") }
|
|
1756
|
-
}
|
|
1757
|
-
let deadline = NimoResourceClock.now() + 15_000
|
|
1758
|
-
while NimoResourceClock.now() < deadline {
|
|
1759
|
-
let producers = await resourceProducers()
|
|
1760
|
-
if original.commandsSettled, producers.writerActive == 0, producers.writerQueued == 0,
|
|
1761
|
-
producers.encoderWorker == 0, producers.encoderDelivery == 0, producers.pendingAcks == 0,
|
|
1762
|
-
producers.canvasCommands == 0, producers.reconnectTask == 0, producers.postedCallbacks == 0,
|
|
1763
|
-
producers.scan == 0, producers.timers == 0, producers.audioWorkers == 0 { break }
|
|
1764
|
-
try? await Task.sleep(nanoseconds: 10_000_000)
|
|
1765
|
-
}
|
|
1766
|
-
if !original.commandsSettled { original.recordError("release-command-evidence-incomplete") }
|
|
1767
|
-
if let peripheral {
|
|
1768
|
-
original.disconnectRequested(self)
|
|
1769
|
-
centralManager?.cancelPeripheralConnection(peripheral)
|
|
1770
|
-
// Retain this exact peripheral and delegate until original closure.
|
|
1771
|
-
while original.disconnectCallbackElapsedMs == nil, original.connectionFailedElapsedMs == nil, NimoResourceClock.now() < deadline + 5_000 {
|
|
1772
|
-
try? await Task.sleep(nanoseconds: 10_000_000)
|
|
1773
|
-
}
|
|
1774
|
-
if original.disconnectCallbackElapsedMs == nil, original.connectionFailedElapsedMs == nil { original.recordError("original-disconnect-callback-missing") }
|
|
1775
|
-
} else if original.connectionFailedElapsedMs == nil { original.proveNoTransport() }
|
|
1776
|
-
if original.disconnectCallbackElapsedMs != nil || original.connectionFailedElapsedMs != nil || original.noTransport {
|
|
1777
|
-
resetSessionState()
|
|
1778
|
-
peripheral = nil; txChar = nil; rxChar = nil; micChar = nil; opusDecoder = nil
|
|
1779
|
-
resourceMicEnabled = false
|
|
1780
|
-
NimoResourceManagerState.publish(owner: self, current: DeviceManager.shared.sgc as? Nimo) {
|
|
1781
|
-
DeviceStore.shared.apply("glasses", "micEnabled", false)
|
|
1782
|
-
DeviceStore.shared.apply("glasses", "connected", false)
|
|
1783
|
-
DeviceStore.shared.apply("glasses", "fullyBooted", false)
|
|
1784
|
-
}
|
|
1785
|
-
}
|
|
1786
|
-
}
|
|
1787
|
-
resourceReleaseTask = task
|
|
1788
|
-
await task.value
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
1802
|
}
|
|
1792
1803
|
|
|
1793
|
-
#if SWIFT_PACKAGE
|
|
1794
|
-
// SDK-package-only, radio-free regression fixture; no app or command API.
|
|
1795
|
-
struct NimoPackageHandshakeObservation {
|
|
1796
|
-
let errors: [String]
|
|
1797
|
-
let pendingAcks: Int
|
|
1798
|
-
let idle: Bool
|
|
1799
|
-
let ready: Bool
|
|
1800
|
-
let sameWriteEvidence: Bool
|
|
1801
|
-
let ackStillAbsent: Bool
|
|
1802
|
-
let noRadio: Bool
|
|
1803
|
-
let physicalClosure: Bool
|
|
1804
|
-
}
|
|
1805
|
-
extension Nimo {
|
|
1806
|
-
@MainActor
|
|
1807
|
-
func packageExercisePendingTimeAck(cancel: Bool, timeoutBeforeEntry: Bool, activeTimeout: Bool = false) async -> NimoPackageHandshakeObservation {
|
|
1808
|
-
let id = "00000000-0000-4000-8000-000000000001"
|
|
1809
|
-
var tick: UInt64 = 100
|
|
1810
|
-
let session = NimoResourceSession(captureNonce: id, pair: NimoResourcePair(name: "NIMO test", peripheralUuid: id), now: { tick += 1; return tick })
|
|
1811
|
-
let peer = NSObject()
|
|
1812
|
-
_ = session.admit(self, instanceId: resourceInstanceId, name: "NIMO test")
|
|
1813
|
-
_ = session.beginTransport(self, peripheral: peer, uuid: id)
|
|
1814
|
-
session.transportConnected(self, peer); session.observeTws(self, connected: true)
|
|
1815
|
-
let command = session.beginTimeCommand(self)!
|
|
1816
|
-
session.timeWriteStarted(self, command: command); session.timeWriteCompleted(self, command: command)
|
|
1817
|
-
let started = session.timeWriteStartedElapsedMs, completed = session.timeWriteCompletedElapsedMs
|
|
1818
|
-
packageTestResourceSession = session; resourceTimeCommand = command; handshakeState = .awaitingTimeAck
|
|
1819
|
-
let key = (NimoProtocol.CMD_SET_PARAMETER << 8) | NimoProtocol.SET_TIME
|
|
1820
|
-
let alreadyQueuedTimeout = pendingAckTimeoutAction(key)
|
|
1821
|
-
pendingAcks[key] = PendingAck(onResult: { [weak self] ok in self?.handleTimeSyncResult(ok, expected: nil) }, timeoutItem: DispatchWorkItem(block: alreadyQueuedTimeout))
|
|
1822
|
-
if activeTimeout { alreadyQueuedTimeout() }
|
|
1823
|
-
_ = session.beginRelease(nonce: id, cancel: cancel, mic: false, canvas: false)
|
|
1824
|
-
if timeoutBeforeEntry { alreadyQueuedTimeout() }
|
|
1825
|
-
await releaseResource(session)
|
|
1826
|
-
alreadyQueuedTimeout() // Closure already dequeued before cancellation.
|
|
1827
|
-
handleTimeSyncResult(true, expected: nil)
|
|
1828
|
-
session.timeAck(self, command: command, status: 0)
|
|
1829
|
-
return NimoPackageHandshakeObservation(errors: session.errors, pendingAcks: pendingAcks.count,
|
|
1830
|
-
idle: handshakeState == .idle, ready: session.ready,
|
|
1831
|
-
sameWriteEvidence: started == session.timeWriteStartedElapsedMs && completed == session.timeWriteCompletedElapsedMs,
|
|
1832
|
-
ackStillAbsent: session.timeAckElapsedMs == nil, noRadio: centralManager == nil && peripheral == nil && !scanRequested,
|
|
1833
|
-
physicalClosure: session.settled(producers: NimoResourceProducers()))
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
#endif
|
|
1837
|
-
|
|
1838
1804
|
// MARK: - CBCentralManagerDelegate
|
|
1839
1805
|
|
|
1840
1806
|
extension Nimo: CBCentralManagerDelegate {
|
|
1841
1807
|
nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
|
1842
1808
|
let state = central.state
|
|
1843
|
-
|
|
1809
|
+
DispatchQueue.main.async { [weak self] in
|
|
1844
1810
|
guard let self else { return }
|
|
1845
1811
|
Bridge.log("NIMO: Bluetooth state: \(state.rawValue)")
|
|
1846
1812
|
if state == .poweredOn {
|
|
@@ -1857,7 +1823,7 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1857
1823
|
) {
|
|
1858
1824
|
let advertisedName = advertisementData[CBAdvertisementDataLocalNameKey] as? String
|
|
1859
1825
|
let rssiValue = rssi.intValue
|
|
1860
|
-
|
|
1826
|
+
DispatchQueue.main.async { [weak self] in
|
|
1861
1827
|
self?.discovery.receive(peripheral, advertisedName: advertisedName, rssi: rssiValue)
|
|
1862
1828
|
}
|
|
1863
1829
|
}
|
|
@@ -1867,27 +1833,17 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1867
1833
|
_: CBCentralManager, connectionEventDidOccur event: CBConnectionEvent, for peripheral: CBPeripheral
|
|
1868
1834
|
) {
|
|
1869
1835
|
guard event == .peerConnected else { return }
|
|
1870
|
-
|
|
1836
|
+
DispatchQueue.main.async { [weak self] in
|
|
1871
1837
|
self?.discovery.receive(peripheral)
|
|
1872
1838
|
}
|
|
1873
1839
|
}
|
|
1874
1840
|
#endif
|
|
1875
1841
|
|
|
1876
1842
|
nonisolated func centralManager(_: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
|
1877
|
-
|
|
1843
|
+
DispatchQueue.main.async { [weak self] in
|
|
1878
1844
|
guard let self else { return }
|
|
1879
1845
|
Bridge.log("NIMO: Connected to \(peripheral.name ?? "unknown")")
|
|
1880
|
-
if let original = self.resourceSession, original.matches(self, peripheral), original.connectionFailedElapsedMs != nil {
|
|
1881
|
-
original.transportConnected(self, peripheral)
|
|
1882
|
-
self.centralManager?.cancelPeripheralConnection(peripheral)
|
|
1883
|
-
return
|
|
1884
|
-
}
|
|
1885
1846
|
guard self.peripheral === peripheral else { return }
|
|
1886
|
-
self.resourceSession?.transportConnected(self, peripheral)
|
|
1887
|
-
guard NimoResourceFixture.shared.allowsProducer(self) else {
|
|
1888
|
-
if self.resourceSession?.releaseNonce != nil { self.resourceSession?.disconnectRequested(self) }
|
|
1889
|
-
self.centralManager?.cancelPeripheralConnection(peripheral); return
|
|
1890
|
-
}
|
|
1891
1847
|
self.writes.connected(peripheral)
|
|
1892
1848
|
self.lastDeviceUUID = peripheral.identifier.uuidString
|
|
1893
1849
|
peripheral.discoverServices([NimoBLE.SERVICE_UUID])
|
|
@@ -1897,14 +1853,12 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1897
1853
|
nonisolated func centralManager(
|
|
1898
1854
|
_: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?
|
|
1899
1855
|
) {
|
|
1900
|
-
|
|
1901
|
-
self.postCallback { [weak self] in
|
|
1856
|
+
DispatchQueue.main.async { [weak self] in
|
|
1902
1857
|
guard let self else { return }
|
|
1903
1858
|
Bridge.log(
|
|
1904
1859
|
"NIMO: Failed to connect \(peripheral.name ?? "unknown"): \(error?.localizedDescription ?? "unknown")"
|
|
1905
1860
|
)
|
|
1906
1861
|
guard self.peripheral === peripheral else { return }
|
|
1907
|
-
self.resourceSession?.connectionFailed(self, peripheral, receivedElapsedMs: receivedElapsedMs)
|
|
1908
1862
|
self.writes.connectionClosed(peripheral)
|
|
1909
1863
|
self.peripheral = nil
|
|
1910
1864
|
self.startReconnectionTimer()
|
|
@@ -1914,13 +1868,9 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1914
1868
|
nonisolated func centralManager(
|
|
1915
1869
|
_: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?
|
|
1916
1870
|
) {
|
|
1917
|
-
|
|
1918
|
-
self.postCallback { [weak self] in
|
|
1871
|
+
DispatchQueue.main.async { [weak self] in
|
|
1919
1872
|
guard let self else { return }
|
|
1920
1873
|
Bridge.log("NIMO: Disconnected: \(error?.localizedDescription ?? "clean")")
|
|
1921
|
-
if let original = self.resourceSession, original.matches(self, peripheral) {
|
|
1922
|
-
original.disconnected(self, peripheral, error: error?.localizedDescription, receivedElapsedMs: receivedElapsedMs)
|
|
1923
|
-
}
|
|
1924
1874
|
self.writes.connectionClosed(peripheral)
|
|
1925
1875
|
if self.isDisconnecting || self.peripheral !== peripheral { return }
|
|
1926
1876
|
|
|
@@ -1928,9 +1878,11 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1928
1878
|
self.txChar = nil
|
|
1929
1879
|
self.rxChar = nil
|
|
1930
1880
|
self.micChar = nil
|
|
1881
|
+
self.otaTxChar = nil
|
|
1882
|
+
self.otaRxChar = nil
|
|
1931
1883
|
self.resetSessionState()
|
|
1932
1884
|
|
|
1933
|
-
|
|
1885
|
+
if (DeviceManager.shared.sgc as? Nimo) === self {
|
|
1934
1886
|
DeviceStore.shared.apply("glasses", "connected", false)
|
|
1935
1887
|
DeviceStore.shared.apply("glasses", "fullyBooted", false)
|
|
1936
1888
|
DeviceStore.shared.apply("glasses", "connectionState", ConnTypes.DISCONNECTED)
|
|
@@ -1944,8 +1896,8 @@ extension Nimo: CBCentralManagerDelegate {
|
|
|
1944
1896
|
|
|
1945
1897
|
extension Nimo: CBPeripheralDelegate {
|
|
1946
1898
|
nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
|
1947
|
-
|
|
1948
|
-
guard let self, self.peripheral === peripheral
|
|
1899
|
+
DispatchQueue.main.async { [weak self] in
|
|
1900
|
+
guard let self, self.peripheral === peripheral else { return }
|
|
1949
1901
|
guard error == nil, let service = peripheral.services?.first(where: { $0.uuid == NimoBLE.SERVICE_UUID }) else {
|
|
1950
1902
|
self.abortTransport("NIMO service discovery failed")
|
|
1951
1903
|
return
|
|
@@ -1961,9 +1913,9 @@ extension Nimo: CBPeripheralDelegate {
|
|
|
1961
1913
|
let characteristics = service.characteristics
|
|
1962
1914
|
else { return }
|
|
1963
1915
|
|
|
1964
|
-
|
|
1916
|
+
DispatchQueue.main.async { [weak self] in
|
|
1965
1917
|
guard let self else { return }
|
|
1966
|
-
guard self.peripheral === peripheral
|
|
1918
|
+
guard self.peripheral === peripheral else { return }
|
|
1967
1919
|
guard error == nil else { self.abortTransport("NIMO characteristic discovery failed"); return }
|
|
1968
1920
|
for char in characteristics {
|
|
1969
1921
|
switch char.uuid {
|
|
@@ -1975,6 +1927,11 @@ extension Nimo: CBPeripheralDelegate {
|
|
|
1975
1927
|
case NimoBLE.CHAR_MIC:
|
|
1976
1928
|
self.micChar = char
|
|
1977
1929
|
peripheral.setNotifyValue(true, for: char)
|
|
1930
|
+
case NimoBLE.CHAR_OTA_TX:
|
|
1931
|
+
self.otaTxChar = char
|
|
1932
|
+
case NimoBLE.CHAR_OTA_RX:
|
|
1933
|
+
// Subscribed only when an update starts.
|
|
1934
|
+
self.otaRxChar = char
|
|
1978
1935
|
default:
|
|
1979
1936
|
break
|
|
1980
1937
|
}
|
|
@@ -1993,9 +1950,19 @@ extension Nimo: CBPeripheralDelegate {
|
|
|
1993
1950
|
_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic,
|
|
1994
1951
|
error: Error?
|
|
1995
1952
|
) {
|
|
1996
|
-
|
|
1953
|
+
DispatchQueue.main.async { [weak self] in
|
|
1997
1954
|
guard let self else { return }
|
|
1998
|
-
guard self.peripheral === peripheral
|
|
1955
|
+
guard self.peripheral === peripheral else { return }
|
|
1956
|
+
if characteristic === self.otaRxChar {
|
|
1957
|
+
guard error == nil, characteristic.isNotifying else {
|
|
1958
|
+
self.abortTransport("NIMO firmware update notifications unavailable")
|
|
1959
|
+
return
|
|
1960
|
+
}
|
|
1961
|
+
let next = self.otaNotifyPending
|
|
1962
|
+
self.otaNotifyPending = nil
|
|
1963
|
+
next?()
|
|
1964
|
+
return
|
|
1965
|
+
}
|
|
1999
1966
|
if let error {
|
|
2000
1967
|
self.abortTransport("Notification subscription failed")
|
|
2001
1968
|
Bridge.log("NIMO: notify enable failed: \(error.localizedDescription)")
|
|
@@ -2014,18 +1981,17 @@ extension Nimo: CBPeripheralDelegate {
|
|
|
2014
1981
|
nonisolated func peripheral(
|
|
2015
1982
|
_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?
|
|
2016
1983
|
) {
|
|
2017
|
-
let receivedElapsedMs = NimoResourceClock.now()
|
|
2018
1984
|
guard let data = characteristic.value, error == nil else { return }
|
|
2019
1985
|
let uuid = characteristic.uuid
|
|
2020
|
-
|
|
1986
|
+
DispatchQueue.main.async { [weak self] in
|
|
2021
1987
|
guard let self else { return }
|
|
2022
1988
|
guard self.peripheral === peripheral else { return }
|
|
2023
|
-
self.resourceNotificationElapsedMs = receivedElapsedMs
|
|
2024
|
-
defer { self.resourceNotificationElapsedMs = nil }
|
|
2025
1989
|
if uuid == NimoBLE.CHAR_RX, characteristic === self.rxChar {
|
|
2026
1990
|
self.handleRxPacket(data)
|
|
2027
1991
|
} else if uuid == NimoBLE.CHAR_MIC, characteristic === self.micChar {
|
|
2028
|
-
self.handleMicPacket(data)
|
|
1992
|
+
if !self.updating { self.handleMicPacket(data) }
|
|
1993
|
+
} else if uuid == NimoBLE.CHAR_OTA_RX, characteristic === self.otaRxChar {
|
|
1994
|
+
self.firmwareUpdater?.receive(data)
|
|
2029
1995
|
}
|
|
2030
1996
|
}
|
|
2031
1997
|
}
|
|
@@ -2033,8 +1999,15 @@ extension Nimo: CBPeripheralDelegate {
|
|
|
2033
1999
|
nonisolated func peripheral(
|
|
2034
2000
|
_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?
|
|
2035
2001
|
) {
|
|
2036
|
-
|
|
2002
|
+
DispatchQueue.main.async { [weak self] in
|
|
2037
2003
|
self?.writes.written(peripheral, characteristic: characteristic, success: error == nil)
|
|
2038
2004
|
}
|
|
2039
2005
|
}
|
|
2006
|
+
|
|
2007
|
+
nonisolated func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
|
|
2008
|
+
DispatchQueue.main.async { [weak self] in
|
|
2009
|
+
guard let self, self.peripheral === peripheral else { return }
|
|
2010
|
+
self.drainOtaWrite()
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2040
2013
|
}
|