@mentra/bluetooth-sdk 3.2.1-dev.314 → 3.3.0-beta.1000
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -10
- package/android/build.gradle +15 -0
- package/android/lc3Lib/build.gradle +6 -1
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +368 -0
- package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +156 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalytics.kt +63 -14
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTracker.kt +55 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +4 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkInstallId.kt +23 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +12 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheck.kt +184 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTracker.kt +388 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +2 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +138 -26
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceStore.kt +37 -13
- 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 +235 -36
- package/android/src/main/java/com/mentra/bluetoothsdk/MentraLocalNetworkModule.kt +24 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/NetworkDiagnostics.kt +25 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/TouchGesture.kt +19 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulator.kt +13 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/debug/BleTraceLogger.kt +3 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/requests/DisplayRequests.kt +1 -1
- package/android/src/main/java/com/mentra/bluetoothsdk/services/Foreground.kt +33 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/services/G2ConnectionRecovery.kt +47 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioConnectionTracker.kt +4 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscovery.kt +70 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1.kt +2 -2
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizer.kt +11 -32
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/G2.kt +72 -21
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/LatinTextSanitizer.kt +39 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +261 -42
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraNex.kt +12 -8
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +314 -395
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodec.kt +247 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +238 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasEncoder.kt +58 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +180 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +11 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddress.kt +17 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SerializedGattCallback.kt +5 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/G2Text.kt +7 -0
- package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +20 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkAnalyticsTrackerTest.kt +58 -3
- package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUpdateCheckTest.kt +124 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/BluetoothSdkUsageTrackerTest.kt +263 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/DashboardContentFormatterTest.kt +2 -2
- package/android/src/test/java/com/mentra/bluetoothsdk/DeviceIdentityPairingTest.kt +59 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/DeviceManagerSceneHandoffTest.kt +666 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/G2TextTest.kt +13 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/NetworkDiagnosticsTest.kt +55 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/ScanCompletionTest.kt +5 -1
- package/android/src/test/java/com/mentra/bluetoothsdk/TouchGestureCommandTest.kt +112 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/VersionInfoResponseAccumulatorTest.kt +71 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/debug/BleTraceLoggerTest.kt +69 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/services/G2ConnectionRecoveryTest.kt +51 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/ClassicAudioServiceDiscoveryTest.kt +124 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1PairingTest.kt +105 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G1TextSanitizerTest.kt +29 -4
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2DisplayThreadTest.kt +120 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/G2PairingTargetTest.kt +90 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveClassicDisconnectTest.kt +133 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveFileTransferSessionTest.kt +55 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGattCallbackTest.kt +33 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +137 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +126 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLivePairingTargetTest.kt +65 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveWifiCredentialLogTest.kt +55 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraNexPairingTest.kt +151 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoBitmapAcceptanceTest.kt +105 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCodecTest.kt +233 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +348 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +339 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoMicReconnectTest.kt +93 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoProtocolTest.kt +11 -0
- package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/SelectedDeviceAddressTest.kt +27 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +287 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +127 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +288 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoReadinessDriverTest.kt +205 -0
- package/build/BluetoothSdk.types.d.ts +22 -1
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js +1 -0
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +6 -1
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js +5 -1
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/_private/MentraLocalNetworkModule.d.ts +23 -0
- package/build/_private/MentraLocalNetworkModule.d.ts.map +1 -1
- package/build/_private/MentraLocalNetworkModule.js.map +1 -1
- package/build/_private/nativeLogConsole.d.ts +19 -0
- package/build/_private/nativeLogConsole.d.ts.map +1 -1
- package/build/_private/nativeLogConsole.js +12 -0
- package/build/_private/nativeLogConsole.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 +2 -0
- package/build/index.js.map +1 -1
- package/build/ota-transport/index.d.ts +4 -0
- package/build/ota-transport/index.d.ts.map +1 -1
- package/build/ota-transport/index.js +2 -0
- package/build/ota-transport/index.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +25 -4
- package/ios/MentraBluetoothSDK.podspec +3 -2
- package/ios/Source/BluetoothBackgroundMode.swift +32 -0
- package/ios/Source/BluetoothSdkDefaults.swift +7 -2
- package/ios/Source/Bridge.swift +15 -2
- package/ios/Source/DeviceManager.swift +106 -66
- package/ios/Source/DeviceStore.swift +26 -7
- package/ios/Source/GeneratedChangelogCatalog.swift +3 -2
- package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
- package/ios/Source/MentraBluetoothSDK.swift +324 -54
- package/ios/Source/TouchGesture.swift +13 -0
- package/ios/Source/audio/GlassesMicWatchdog.swift +33 -0
- package/ios/Source/events/BluetoothEvents.swift +4 -0
- package/ios/Source/internal/BluetoothAvailability.swift +6 -0
- package/ios/Source/internal/BluetoothSdkAnalytics.swift +87 -13
- package/ios/Source/internal/BluetoothSdkAnalyticsTracker.swift +54 -1
- package/ios/Source/internal/BluetoothSdkInstallId.swift +21 -0
- package/ios/Source/internal/BluetoothSdkUpdateCheck.swift +223 -0
- package/ios/Source/internal/BluetoothSdkUsageTracker.swift +428 -0
- package/ios/Source/requests/DisplayRequests.swift +1 -1
- package/ios/Source/requests/VersionInfoResponseAccumulator.swift +11 -1
- package/ios/Source/sgcs/Ar99.swift +1 -2
- package/ios/Source/sgcs/G1.swift +68 -38
- package/ios/Source/sgcs/G1ConnectionTarget.swift +13 -0
- package/ios/Source/sgcs/G2.swift +261 -247
- package/ios/Source/sgcs/G2ConnectionSession.swift +101 -0
- package/ios/Source/sgcs/Mach1.swift +19 -7
- package/ios/Source/sgcs/MentraLive.swift +368 -220
- package/ios/Source/sgcs/MentraLiveFileTransferSession.swift +137 -0
- package/ios/Source/sgcs/MentraLivePairingAdvertisement.swift +47 -0
- package/ios/Source/sgcs/MentraNex.swift +8 -31
- package/ios/Source/sgcs/NexConnectionTarget.swift +15 -0
- package/ios/Source/sgcs/Nimo.swift +280 -408
- package/ios/Source/sgcs/NimoCanvasCodec.swift +272 -0
- package/ios/Source/sgcs/NimoCanvasCoordinator.swift +233 -0
- package/ios/Source/sgcs/NimoCanvasImage.swift +53 -0
- package/ios/Source/sgcs/NimoCanvasSession.swift +166 -0
- package/ios/Source/sgcs/NimoDiscovery.swift +49 -0
- package/ios/Source/sgcs/SGCManager.swift +25 -1
- package/ios/Source/sgcs/VuzixConnectionTarget.swift +15 -0
- package/ios/Source/status/DeviceStatus.swift +1 -0
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +49 -189
- package/ios/Source/utils/AudioSessionMonitor.swift +44 -8
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +150 -0
- package/ios/Source/utils/G1Text.swift +2 -24
- package/ios/Source/utils/G1TextSanitizer.swift +27 -0
- package/ios/Source/utils/G2Text.swift +11 -0
- package/ios/Source/utils/LatinTextSanitizer.swift +48 -0
- package/ios/Tests/BluetoothAudioRouteTests.swift +26 -0
- package/ios/Tests/BluetoothBackgroundModeTests.swift +32 -0
- package/ios/Tests/BluetoothSdkAnalyticsTrackerTests.swift +54 -3
- package/ios/Tests/BluetoothSdkUpdateCheckTests.swift +153 -0
- package/ios/Tests/BluetoothSdkUsageTrackerTests.swift +296 -0
- package/ios/Tests/DashboardContentFormatterTests.swift +2 -2
- package/ios/Tests/DashboardRenderingTests.swift +31 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +157 -0
- package/ios/Tests/DeviceIdentityPairingTests.swift +49 -0
- package/ios/Tests/DeviceManagerReconnectTests.swift +362 -0
- package/ios/Tests/G1PairingTests.swift +162 -0
- package/ios/Tests/G1TextSanitizerTests.swift +32 -0
- package/ios/Tests/G2ConnectionSessionTests.swift +172 -0
- package/ios/Tests/G2TextTests.swift +10 -0
- package/ios/Tests/IncidentLogDispatchTests.swift +111 -0
- package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
- package/ios/Tests/MentraLiveFileTransferSessionTests.swift +47 -0
- package/ios/Tests/MentraLiveReconnectPolicyTests.swift +58 -0
- package/ios/Tests/MentraLiveSessionReadinessTests.swift +292 -0
- package/ios/Tests/NimoCanvasCodecTests.swift +217 -0
- package/ios/Tests/NimoCanvasSessionTests.swift +181 -0
- package/ios/Tests/NimoCanvasTransportTests.swift +186 -0
- package/ios/Tests/NimoDeviceCommandsTests.swift +16 -0
- package/ios/Tests/NimoDiscoveryTests.swift +79 -0
- package/ios/Tests/SGCConnectionTargetTests.swift +48 -0
- package/ios/Tests/TouchGestureCommandTests.swift +87 -0
- package/ios/Tests/VersionInfoCommandTests.swift +194 -0
- package/ios/Tests/VersionInfoResponseAccumulatorTests.swift +65 -0
- package/ios/Tests/VideoRecordingCommandTests.swift +81 -0
- package/ios/Tests/WifiCredentialLoggingTests.swift +42 -0
- package/package.json +2 -2
- package/plugin/build/withIos.d.ts +2 -0
- package/plugin/build/withIos.js +12 -1
- package/src/BluetoothSdk.types.ts +30 -0
- package/src/_private/BluetoothSdkModule.ts +12 -1
- package/src/_private/MentraLocalNetworkModule.ts +28 -0
- package/src/_private/nativeLogConsole.ts +19 -0
- package/src/generated/changelogCatalog.ts +6 -2
- package/src/generated/releaseMetadata.ts +6 -6
- package/src/index.ts +3 -0
- package/src/ota-transport/index.ts +10 -1
|
@@ -677,145 +677,13 @@ enum K900ProtocolUtils {
|
|
|
677
677
|
}
|
|
678
678
|
}
|
|
679
679
|
|
|
680
|
-
private struct FileTransferSession {
|
|
681
|
-
let fileName: String
|
|
682
|
-
let fileSize: Int // NOTE: May be "fake" (inflated) due to BES firmware workaround
|
|
683
|
-
var actualPackSize: Int = 0 // Actual pack size from first received packet
|
|
684
|
-
var totalPackets: Int
|
|
685
|
-
var expectedNextPacket: Int = 0
|
|
686
|
-
var receivedPackets: [Int: Data] = [:]
|
|
687
|
-
let startTime: Date
|
|
688
|
-
var isComplete: Bool = false
|
|
689
|
-
var isAnnounced: Bool = false
|
|
690
|
-
|
|
691
|
-
/// BES2700 firmware hardcodes FILE_PACK_SIZE=400 when calculating totalPack.
|
|
692
|
-
/// Android glasses "lie" about fileSize to make BES expect correct packet count.
|
|
693
|
-
private static let BES_HARDCODED_PACK_SIZE = 400
|
|
694
|
-
|
|
695
|
-
init(fileName: String, fileSize: Int, announcedPackets: Int? = nil) {
|
|
696
|
-
self.fileName = fileName
|
|
697
|
-
self.fileSize = fileSize
|
|
698
|
-
let computedPackets =
|
|
699
|
-
(fileSize + K900ProtocolUtils.FILE_PACK_SIZE - 1) / K900ProtocolUtils.FILE_PACK_SIZE
|
|
700
|
-
if let announced = announcedPackets, announced > 0 {
|
|
701
|
-
totalPackets = announced
|
|
702
|
-
isAnnounced = true
|
|
703
|
-
} else {
|
|
704
|
-
totalPackets = computedPackets
|
|
705
|
-
isAnnounced = false
|
|
706
|
-
}
|
|
707
|
-
startTime = Date()
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
mutating func updateAnnouncedPackets(_ announced: Int) {
|
|
711
|
-
guard announced > 0 else { return }
|
|
712
|
-
totalPackets = announced
|
|
713
|
-
isAnnounced = true
|
|
714
|
-
if expectedNextPacket >= totalPackets {
|
|
715
|
-
expectedNextPacket = min(expectedNextPacket, max(totalPackets - 1, 0))
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
/// Recalculate total packets based on actual pack size from received packet.
|
|
720
|
-
/// Detects BES lie: if fileSize is multiple of 400 but actual pack size differs.
|
|
721
|
-
mutating func recalculateTotalPackets(actualPackSize: Int) {
|
|
722
|
-
guard actualPackSize > 0, actualPackSize <= K900ProtocolUtils.FILE_PACK_SIZE else { return }
|
|
723
|
-
|
|
724
|
-
self.actualPackSize = actualPackSize
|
|
725
|
-
|
|
726
|
-
// Detect BES lie: if fileSize is exact multiple of 400, glasses used the lie strategy
|
|
727
|
-
let isBesLie =
|
|
728
|
-
(fileSize % Self.BES_HARDCODED_PACK_SIZE == 0)
|
|
729
|
-
&& (actualPackSize != Self.BES_HARDCODED_PACK_SIZE)
|
|
730
|
-
|
|
731
|
-
let newTotalPackets: Int
|
|
732
|
-
if isBesLie {
|
|
733
|
-
// BES lie detected: totalPackets = fileSize / 400
|
|
734
|
-
newTotalPackets = fileSize / Self.BES_HARDCODED_PACK_SIZE
|
|
735
|
-
Bridge.log(
|
|
736
|
-
"📦 BES Lie detected! fakeFileSize=\(fileSize), totalPackets=\(newTotalPackets), actualPackSize=\(actualPackSize)"
|
|
737
|
-
)
|
|
738
|
-
} else {
|
|
739
|
-
// Normal case: calculate based on actual pack size
|
|
740
|
-
newTotalPackets = (fileSize + actualPackSize - 1) / actualPackSize
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
if newTotalPackets != totalPackets {
|
|
744
|
-
Bridge.log(
|
|
745
|
-
"📦 Recalculating totalPackets: \(totalPackets) -> \(newTotalPackets) (packSize=\(actualPackSize), fileSize=\(fileSize))"
|
|
746
|
-
)
|
|
747
|
-
totalPackets = newTotalPackets
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
mutating func addPacket(_ index: Int, data: Data) -> Bool {
|
|
752
|
-
guard index >= 0 else { return false }
|
|
753
|
-
|
|
754
|
-
// On first packet, recalculate total packets only when we do not already
|
|
755
|
-
// have an authoritative pack size from protocol metadata.
|
|
756
|
-
if receivedPackets.isEmpty && actualPackSize == 0 && !data.isEmpty {
|
|
757
|
-
recalculateTotalPackets(actualPackSize: data.count)
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
if index >= totalPackets {
|
|
761
|
-
totalPackets = index + 1
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
guard receivedPackets[index] == nil else {
|
|
765
|
-
return false
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
receivedPackets[index] = data
|
|
769
|
-
|
|
770
|
-
while receivedPackets[expectedNextPacket] != nil, expectedNextPacket < totalPackets {
|
|
771
|
-
expectedNextPacket += 1
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
isComplete = (receivedPackets.count == totalPackets)
|
|
775
|
-
return true
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
func isFinalPacket(_ index: Int) -> Bool {
|
|
779
|
-
index == totalPackets - 1
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
func missingPacketIndices() -> [Int] {
|
|
783
|
-
guard totalPackets > receivedPackets.count else { return [] }
|
|
784
|
-
return (0 ..< totalPackets).compactMap { receivedPackets[$0] == nil ? $0 : nil }
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
/// Assemble file from received packets.
|
|
788
|
-
/// NOTE: Calculates actual file size from received data, NOT from header fileSize,
|
|
789
|
-
/// because fileSize may be "fake" (inflated) due to BES firmware workaround.
|
|
790
|
-
func assembleFile() -> Data? {
|
|
791
|
-
guard isComplete else { return nil }
|
|
792
|
-
|
|
793
|
-
// Calculate actual file size by summing all received packet sizes
|
|
794
|
-
let actualFileSize = receivedPackets.values.reduce(0) { $0 + $1.count }
|
|
795
|
-
|
|
796
|
-
Bridge.log(
|
|
797
|
-
"📦 Assembling file: headerFileSize=\(fileSize), actualFileSize=\(actualFileSize), totalPackets=\(totalPackets)"
|
|
798
|
-
)
|
|
799
|
-
|
|
800
|
-
var fileData = Data(capacity: actualFileSize)
|
|
801
|
-
|
|
802
|
-
for i in 0 ..< totalPackets {
|
|
803
|
-
if let packet = receivedPackets[i] {
|
|
804
|
-
fileData.append(packet)
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
return fileData
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
|
|
812
680
|
private struct BlePhotoTransfer {
|
|
813
681
|
var isThumbnail = false
|
|
814
682
|
let bleImgId: String
|
|
815
683
|
let requestId: String
|
|
816
684
|
let webhookUrl: String
|
|
817
685
|
var authToken: String?
|
|
818
|
-
var session:
|
|
686
|
+
var session: MentraLiveFileTransferSession?
|
|
819
687
|
let phoneStartTime: Date
|
|
820
688
|
var bleTransferStartTime: Date?
|
|
821
689
|
var glassesCompressionDurationMs: Int64 = 0
|
|
@@ -838,7 +706,7 @@ private final class BleIncidentLogRelayEntry {
|
|
|
838
706
|
let incidentId: String
|
|
839
707
|
let apiBaseUrl: String
|
|
840
708
|
let kind: BleIncidentLogRelayKind
|
|
841
|
-
var session:
|
|
709
|
+
var session: MentraLiveFileTransferSession?
|
|
842
710
|
|
|
843
711
|
init(
|
|
844
712
|
fileBaseKey: String, incidentId: String, apiBaseUrl: String, kind: BleIncidentLogRelayKind
|
|
@@ -994,6 +862,7 @@ extension MentraLive: CBCentralManagerDelegate {
|
|
|
994
862
|
Bridge.log("Connected to GATT server, discovering services...")
|
|
995
863
|
|
|
996
864
|
self.stopConnectionTimeout()
|
|
865
|
+
self.clearPendingReconnectTracking()
|
|
997
866
|
self.isConnecting = false
|
|
998
867
|
self.connectingPeripheral = nil
|
|
999
868
|
self.connectedPeripheral = peripheral
|
|
@@ -1048,12 +917,13 @@ extension MentraLive: CBCentralManagerDelegate {
|
|
|
1048
917
|
return
|
|
1049
918
|
}
|
|
1050
919
|
self.connectingPeripheral = nil
|
|
920
|
+
self.clearPendingReconnectTracking()
|
|
1051
921
|
Bridge.log("LIVE: Disconnected from GATT server")
|
|
1052
922
|
|
|
1053
923
|
self.isConnecting = false
|
|
1054
924
|
|
|
1055
925
|
self.connectedPeripheral = nil
|
|
1056
|
-
self.
|
|
926
|
+
self.clearPhysicalReadiness()
|
|
1057
927
|
self.connected = false
|
|
1058
928
|
self.glassesSessionId = nil // Fresh BLE session starts with no sid known
|
|
1059
929
|
self.streamControlVersion = 0
|
|
@@ -1077,8 +947,9 @@ extension MentraLive: CBCentralManagerDelegate {
|
|
|
1077
947
|
return
|
|
1078
948
|
}
|
|
1079
949
|
|
|
1080
|
-
//
|
|
1081
|
-
|
|
950
|
+
// Prefer a pending direct reconnect: it is the only path iOS completes while the
|
|
951
|
+
// app is suspended. Fall back to the scan backoff when it does not apply.
|
|
952
|
+
if !self.isKilled, !self.reconnectDirectly(to: peripheral) {
|
|
1082
953
|
self.handleReconnection()
|
|
1083
954
|
}
|
|
1084
955
|
}
|
|
@@ -1098,6 +969,7 @@ extension MentraLive: CBCentralManagerDelegate {
|
|
|
1098
969
|
Bridge.log("LIVE: Failed to connect to peripheral: \(errorDescription)")
|
|
1099
970
|
|
|
1100
971
|
self.stopConnectionTimeout()
|
|
972
|
+
self.clearPendingReconnectTracking()
|
|
1101
973
|
self.isConnecting = false
|
|
1102
974
|
self.closeL2capFileChannel()
|
|
1103
975
|
self.connectedPeripheral = nil
|
|
@@ -1414,6 +1286,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1414
1286
|
private let BLOCK_AUDIO_DUPLEX = false
|
|
1415
1287
|
private static let voiceActivityDetectionSwitchType = 8
|
|
1416
1288
|
private static let loudnessGateSwitchType = 10
|
|
1289
|
+
private static let autoPowerOffSwitchType = 11
|
|
1417
1290
|
private func pairingAdvertisement(
|
|
1418
1291
|
_ advertisementData: [String: Any]
|
|
1419
1292
|
) -> MentraLivePairingAdvertisement? {
|
|
@@ -1472,11 +1345,12 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1472
1345
|
if state == ConnTypes.DISCONNECTED {
|
|
1473
1346
|
resetPendingAckState(reason: "BLE session ended")
|
|
1474
1347
|
resetWireNegotiationState()
|
|
1348
|
+
resetReadinessExchange()
|
|
1475
1349
|
resetAncsRelayState()
|
|
1476
1350
|
// Queued writes are session-bound: transmitting them into the NEXT session
|
|
1477
1351
|
// (e.g. a stale handshake whose reply activates v2 before the new session
|
|
1478
1352
|
// negotiated) is the bug class this clear removes.
|
|
1479
|
-
|
|
1353
|
+
commandQueue.removeAll()
|
|
1480
1354
|
stopSignalStrengthPolling()
|
|
1481
1355
|
DeviceStore.shared.apply("glasses", "signalStrength", -1)
|
|
1482
1356
|
DeviceStore.shared.apply("glasses", "signalStrengthUpdatedAt", 0)
|
|
@@ -1601,7 +1475,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1601
1475
|
// NEW: File transfer properties
|
|
1602
1476
|
private var fileReadCharacteristic: CBCharacteristic?
|
|
1603
1477
|
private var fileWriteCharacteristic: CBCharacteristic?
|
|
1604
|
-
private var activeFileTransfers = [String:
|
|
1478
|
+
private var activeFileTransfers = [String: MentraLiveFileTransferSession]()
|
|
1605
1479
|
private var blePhotoTransfers = [String: BlePhotoTransfer]()
|
|
1606
1480
|
private var bleIncidentLogRelays = [String: BleIncidentLogRelayEntry]()
|
|
1607
1481
|
private var l2capFileChannel: MentraLiveL2capChannel?
|
|
@@ -1730,6 +1604,13 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1730
1604
|
// the physical connection — so a first-seen sid after an upgrade OTA cannot be
|
|
1731
1605
|
// mistaken for a fresh pairing just because a not-ready heartbeat slipped in first.
|
|
1732
1606
|
private var readinessCompletedThisBleSession = false
|
|
1607
|
+
/// Readiness exchange the phone is waiting on. Every phone_ready carries it until the
|
|
1608
|
+
/// matching glasses_ready arrives, so retries and the copies the BES buffers while the
|
|
1609
|
+
/// glasses boot are one exchange: the glasses reset their transport once for it and answer
|
|
1610
|
+
/// later copies without resetting. Both exchange fields are scoped to the BLE session.
|
|
1611
|
+
private var pendingReadyId: String?
|
|
1612
|
+
/// `sid` of the glasses process whose glasses_ready this BLE session last handled.
|
|
1613
|
+
private var readyGlassesSessionId: String?
|
|
1733
1614
|
private var globalMessageId = 0
|
|
1734
1615
|
private var lastReceivedMessageId = 0
|
|
1735
1616
|
private var bleWriteTraceSequence = 0
|
|
@@ -1744,6 +1625,16 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1744
1625
|
set { DeviceStore.shared.apply("glasses", "connected", newValue) }
|
|
1745
1626
|
}
|
|
1746
1627
|
|
|
1628
|
+
private func clearPhysicalReadiness() {
|
|
1629
|
+
let readinessWasPending = connected && !fullyBooted
|
|
1630
|
+
fullyBooted = false
|
|
1631
|
+
if readinessWasPending {
|
|
1632
|
+
// Logical ASG readiness already emitted false without disconnecting.
|
|
1633
|
+
// The real disconnect must still perform the cleanup apply deduplicates.
|
|
1634
|
+
DeviceManager.shared.handleDeviceDisconnected()
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1747
1638
|
// Queue Management
|
|
1748
1639
|
private let commandQueue = CommandQueue()
|
|
1749
1640
|
private let bluetoothQueue = DispatchQueue(label: "MentraLiveBluetooth", qos: .userInitiated)
|
|
@@ -1777,6 +1668,10 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1777
1668
|
private static let glassesMediaVolumeTimeoutSec: TimeInterval = 2.0
|
|
1778
1669
|
|
|
1779
1670
|
private var connectionTimeoutTimer: Timer?
|
|
1671
|
+
/// Peripheral of an armed pending reconnect (see `reconnectDirectly`).
|
|
1672
|
+
private var pendingReconnectPeripheral: CBPeripheral?
|
|
1673
|
+
private var pendingReconnect = MentraLivePendingReconnect()
|
|
1674
|
+
private var pendingReconnectSettleWorkItem: DispatchWorkItem?
|
|
1780
1675
|
private var reconnectionWorkItem: DispatchWorkItem?
|
|
1781
1676
|
private var requiresAncs = true
|
|
1782
1677
|
|
|
@@ -1844,6 +1739,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1844
1739
|
|
|
1845
1740
|
// clear the saved device name:
|
|
1846
1741
|
UserDefaults.standard.set("", forKey: PREFS_DEVICE_NAME)
|
|
1742
|
+
cancelPendingReconnect(reason: "discovery")
|
|
1847
1743
|
|
|
1848
1744
|
manualDiscoveryActive = true
|
|
1849
1745
|
startScan()
|
|
@@ -1856,6 +1752,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1856
1752
|
}
|
|
1857
1753
|
|
|
1858
1754
|
private func enterPairingYield(windowMs: Int) {
|
|
1755
|
+
cancelPendingReconnect(reason: "pairing_yield")
|
|
1859
1756
|
pairingYieldActive = true
|
|
1860
1757
|
pairingYieldAwaitingReclaim = false
|
|
1861
1758
|
pairingYieldEndWorkItem?.cancel()
|
|
@@ -1865,8 +1762,8 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1865
1762
|
// Publish disconnect immediately for Phone A UI. didDisconnectPeripheral may lag
|
|
1866
1763
|
// or race with cancelPeripheralConnection; do not wait on it for stand-down.
|
|
1867
1764
|
isConnecting = false
|
|
1765
|
+
clearPhysicalReadiness()
|
|
1868
1766
|
connected = false
|
|
1869
|
-
fullyBooted = false
|
|
1870
1767
|
glassesSessionId = nil
|
|
1871
1768
|
streamControlVersion = 0
|
|
1872
1769
|
readinessCompletedThisBleSession = false
|
|
@@ -1936,6 +1833,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
1936
1833
|
return
|
|
1937
1834
|
}
|
|
1938
1835
|
Bridge.log("connectById: \(deviceName)")
|
|
1836
|
+
cancelPendingReconnect(reason: "connect_by_id")
|
|
1939
1837
|
// Save the device name for future reconnection
|
|
1940
1838
|
UserDefaults.standard.set(deviceName, forKey: PREFS_DEVICE_NAME)
|
|
1941
1839
|
|
|
@@ -2243,8 +2141,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2243
2141
|
/// Wire-session generation at enqueue time; the drain loop drops entries from a
|
|
2244
2142
|
/// previous session so a stale write (worst case: an old handshake whose reply
|
|
2245
2143
|
/// would activate v2 pre-negotiation) can never cross a session boundary. This is
|
|
2246
|
-
/// the deterministic guard
|
|
2247
|
-
/// cleanup that may land after a reconnect has already resumed the drain loop.
|
|
2144
|
+
/// the deterministic guard if a consumer already dequeued a previous-session write.
|
|
2248
2145
|
let generation: Int
|
|
2249
2146
|
}
|
|
2250
2147
|
|
|
@@ -2286,7 +2183,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2286
2183
|
Bridge.log("LIVE: Cleared pending ACK mId \(pendingMessage.id) because \(reason)")
|
|
2287
2184
|
}
|
|
2288
2185
|
|
|
2289
|
-
|
|
2186
|
+
@MainActor final class CommandQueue {
|
|
2290
2187
|
private var commands: [PendingMessage] = []
|
|
2291
2188
|
|
|
2292
2189
|
func enqueue(_ command: PendingMessage) -> Int {
|
|
@@ -2304,6 +2201,17 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2304
2201
|
return commands.removeFirst()
|
|
2305
2202
|
}
|
|
2306
2203
|
|
|
2204
|
+
/// Discards the run of writes from earlier wire-session generations at the head of
|
|
2205
|
+
/// the queue in one pass and dequeues the first current one. Stale writes are never
|
|
2206
|
+
/// sent, so they must not each cost a drain tick: a burst of epoch resets would
|
|
2207
|
+
/// otherwise park every current write behind seconds of dead entries.
|
|
2208
|
+
func dequeue(currentGeneration: Int) -> (command: PendingMessage?, staleIds: [String]) {
|
|
2209
|
+
let firstCurrent = commands.firstIndex { $0.generation == currentGeneration } ?? commands.endIndex
|
|
2210
|
+
let staleIds = commands[..<firstCurrent].map(\.id)
|
|
2211
|
+
commands.removeSubrange(..<firstCurrent)
|
|
2212
|
+
return (commands.isEmpty ? nil : commands.removeFirst(), staleIds)
|
|
2213
|
+
}
|
|
2214
|
+
|
|
2307
2215
|
func removeAll() {
|
|
2308
2216
|
commands.removeAll()
|
|
2309
2217
|
}
|
|
@@ -2314,21 +2222,25 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2314
2222
|
guard let self else { return }
|
|
2315
2223
|
while true {
|
|
2316
2224
|
let pendingIsNil = await MainActor.run { self.pending == nil }
|
|
2317
|
-
if pendingIsNil {
|
|
2318
|
-
|
|
2319
|
-
let currentGeneration = await MainActor.run { self.wireSessionGeneration }
|
|
2320
|
-
if command.generation != currentGeneration {
|
|
2321
|
-
Bridge.log("LIVE: Dropping stale queued write from a previous session epoch (id: \(command.id))")
|
|
2322
|
-
} else {
|
|
2323
|
-
await self.processSendQueue(command)
|
|
2324
|
-
}
|
|
2325
|
-
}
|
|
2225
|
+
if pendingIsNil, let command = await self.dequeueCurrentGenerationWrite() {
|
|
2226
|
+
await self.processSendQueue(command)
|
|
2326
2227
|
}
|
|
2327
2228
|
try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
|
|
2328
2229
|
}
|
|
2329
2230
|
}
|
|
2330
2231
|
}
|
|
2331
2232
|
|
|
2233
|
+
private func dequeueCurrentGenerationWrite() -> PendingMessage? {
|
|
2234
|
+
let next = commandQueue.dequeue(currentGeneration: wireSessionGeneration)
|
|
2235
|
+
if !next.staleIds.isEmpty {
|
|
2236
|
+
Bridge.log(
|
|
2237
|
+
"LIVE: Dropping \(next.staleIds.count) stale queued write(s) from a previous session epoch " +
|
|
2238
|
+
"(ids: \(next.staleIds.joined(separator: ", ")))"
|
|
2239
|
+
)
|
|
2240
|
+
}
|
|
2241
|
+
return next.command
|
|
2242
|
+
}
|
|
2243
|
+
|
|
2332
2244
|
private func processSendQueue(_ message: PendingMessage) async {
|
|
2333
2245
|
guard let peripheral = connectedPeripheral,
|
|
2334
2246
|
let txChar = txCharacteristic
|
|
@@ -2402,15 +2314,11 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2402
2314
|
)
|
|
2403
2315
|
|
|
2404
2316
|
// Push to front of queue for immediate retry
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
"queueSizeAfterAdd": queueSize,
|
|
2411
|
-
])
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2317
|
+
let queueSize = commandQueue.pushToFront(retryMessage)
|
|
2318
|
+
logBleWriteTrace("retry_queued", retryMessage.trace, extra: [
|
|
2319
|
+
"retryDelayMs": 0,
|
|
2320
|
+
"queueSizeAfterAdd": queueSize,
|
|
2321
|
+
])
|
|
2414
2322
|
|
|
2415
2323
|
Bridge.log(
|
|
2416
2324
|
"🔄 Retrying message mId: \(pendingMessage.id) (attempt \(retryMessage.retries)/3)"
|
|
@@ -2488,15 +2396,59 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2488
2396
|
}
|
|
2489
2397
|
Bridge.log("LIVE: Connecting to device: \(peripheral.identifier.uuidString)")
|
|
2490
2398
|
|
|
2399
|
+
// A timed attempt supersedes any pending reconnect: withdraw one aimed at other
|
|
2400
|
+
// glasses, and drop tracking for this one so its settle timer cannot touch this attempt.
|
|
2401
|
+
if let pending = pendingReconnectPeripheral, pending !== peripheral {
|
|
2402
|
+
cancelPendingReconnect(reason: "superseded")
|
|
2403
|
+
} else {
|
|
2404
|
+
clearPendingReconnectTracking()
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2491
2407
|
isConnecting = true
|
|
2492
2408
|
updateConnectionState(ConnTypes.CONNECTING)
|
|
2493
2409
|
connectingPeripheral = peripheral
|
|
2494
2410
|
connectedPeripheral = peripheral
|
|
2495
|
-
peripheral.delegate = self
|
|
2496
2411
|
|
|
2497
2412
|
// Set connection timeout
|
|
2498
2413
|
startConnectionTimeout()
|
|
2499
2414
|
|
|
2415
|
+
issueConnect(peripheral)
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
/// Re-arms a pending connection to the glasses that just dropped. Unlike `connectToDevice`,
|
|
2419
|
+
/// it sets no timeout: CoreBluetooth keeps the request open until the glasses advertise
|
|
2420
|
+
/// again (for example after a BES firmware reset), completes it in the background and wakes
|
|
2421
|
+
/// the app. Discovery, connect-by-id, pairing yield and `destroy()` cancel it through
|
|
2422
|
+
/// `cancelPendingReconnect`. Returns false when the policy does not apply, so the caller can
|
|
2423
|
+
/// fall back to scanning.
|
|
2424
|
+
private func reconnectDirectly(to peripheral: CBPeripheral) -> Bool {
|
|
2425
|
+
guard let centralManager,
|
|
2426
|
+
MentraLiveConnectionAttemptPolicy.shouldReconnectDirectly(
|
|
2427
|
+
isKilled: isKilled,
|
|
2428
|
+
pairingYieldActive: pairingYieldActive,
|
|
2429
|
+
bluetoothPoweredOn: centralManager.state == .poweredOn,
|
|
2430
|
+
peripheralName: peripheral.name,
|
|
2431
|
+
savedDeviceName: UserDefaults.standard.string(forKey: PREFS_DEVICE_NAME)
|
|
2432
|
+
)
|
|
2433
|
+
else {
|
|
2434
|
+
return false
|
|
2435
|
+
}
|
|
2436
|
+
Bridge.log(
|
|
2437
|
+
"LIVE: Pending direct reconnect to \(peripheral.identifier.uuidString) (no timeout, completes in background)"
|
|
2438
|
+
)
|
|
2439
|
+
isConnecting = true
|
|
2440
|
+
updateConnectionState(ConnTypes.CONNECTING)
|
|
2441
|
+
connectingPeripheral = peripheral
|
|
2442
|
+
connectedPeripheral = peripheral
|
|
2443
|
+
pendingReconnectPeripheral = peripheral
|
|
2444
|
+
issueConnect(peripheral)
|
|
2445
|
+
schedulePendingReconnectSettle(attempt: pendingReconnect.arm())
|
|
2446
|
+
return true
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
/// The single CoreBluetooth connect call, shared by user-initiated and pending reconnects.
|
|
2450
|
+
private func issueConnect(_ peripheral: CBPeripheral) {
|
|
2451
|
+
peripheral.delegate = self
|
|
2500
2452
|
#if os(macOS)
|
|
2501
2453
|
centralManager?.connect(peripheral, options: nil)
|
|
2502
2454
|
#else
|
|
@@ -2511,6 +2463,58 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2511
2463
|
#endif
|
|
2512
2464
|
}
|
|
2513
2465
|
|
|
2466
|
+
/// A pending connect never times out, so the glasses may simply never return (battery
|
|
2467
|
+
/// dead, left behind). After the old scan backoff's span, report DISCONNECTED like that
|
|
2468
|
+
/// backoff did, but keep the request armed: iOS still completes it whenever the glasses
|
|
2469
|
+
/// advertise, and `didConnect` accepts it through `connectingPeripheral`.
|
|
2470
|
+
private func schedulePendingReconnectSettle(attempt: Int) {
|
|
2471
|
+
pendingReconnectSettleWorkItem?.cancel()
|
|
2472
|
+
let work = DispatchWorkItem { [weak self] in
|
|
2473
|
+
// Only the attempt that armed this timer may settle state; a failure, fallback
|
|
2474
|
+
// connect or re-arm clears or replaces it.
|
|
2475
|
+
guard let self, self.pendingReconnect.owns(attempt),
|
|
2476
|
+
self.connectionState != ConnTypes.CONNECTED
|
|
2477
|
+
else { return }
|
|
2478
|
+
Bridge.log("LIVE: Glasses still unreachable; reporting disconnected, pending reconnect stays armed")
|
|
2479
|
+
self.pendingReconnectSettleWorkItem = nil
|
|
2480
|
+
self.isConnecting = false
|
|
2481
|
+
self.connectedPeripheral = nil
|
|
2482
|
+
self.updateConnectionState(ConnTypes.DISCONNECTED)
|
|
2483
|
+
}
|
|
2484
|
+
pendingReconnectSettleWorkItem = work
|
|
2485
|
+
DispatchQueue.main.asyncAfter(
|
|
2486
|
+
deadline: .now() + .milliseconds(MentraLiveConnectionAttemptPolicy.pendingReconnectSettleMs),
|
|
2487
|
+
execute: work
|
|
2488
|
+
)
|
|
2489
|
+
}
|
|
2490
|
+
|
|
2491
|
+
/// Stops tracking a pending reconnect after it connected; no CoreBluetooth call needed.
|
|
2492
|
+
private func clearPendingReconnectTracking() {
|
|
2493
|
+
pendingReconnectSettleWorkItem?.cancel()
|
|
2494
|
+
pendingReconnectSettleWorkItem = nil
|
|
2495
|
+
pendingReconnect.clear()
|
|
2496
|
+
pendingReconnectPeripheral = nil
|
|
2497
|
+
}
|
|
2498
|
+
|
|
2499
|
+
/// Withdraws a pending reconnect before the user retargets (discovery, connect-by-id,
|
|
2500
|
+
/// pairing yield) or tears down, so iOS cannot later complete it to the previous glasses.
|
|
2501
|
+
private func cancelPendingReconnect(reason: String) {
|
|
2502
|
+
guard let peripheral = pendingReconnectPeripheral else {
|
|
2503
|
+
clearPendingReconnectTracking()
|
|
2504
|
+
return
|
|
2505
|
+
}
|
|
2506
|
+
clearPendingReconnectTracking()
|
|
2507
|
+
Bridge.log("LIVE: Cancelling pending reconnect to \(peripheral.identifier.uuidString) (\(reason))")
|
|
2508
|
+
if connectingPeripheral === peripheral {
|
|
2509
|
+
connectingPeripheral = nil
|
|
2510
|
+
}
|
|
2511
|
+
if connectedPeripheral === peripheral, connectionState != ConnTypes.CONNECTED {
|
|
2512
|
+
connectedPeripheral = nil
|
|
2513
|
+
}
|
|
2514
|
+
isConnecting = false
|
|
2515
|
+
centralManager?.cancelPeripheralConnection(peripheral)
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2514
2518
|
/// Opt the firmware into ANCS only after iOS has authorized this accessory.
|
|
2515
2519
|
/// Old firmware safely ignores the command, while new firmware stays inert
|
|
2516
2520
|
/// for old mobile clients that never send it.
|
|
@@ -2552,8 +2556,8 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2552
2556
|
Bridge.log("LIVE: Maximum reconnection attempts reached (\(MAX_RECONNECT_ATTEMPTS))")
|
|
2553
2557
|
reconnectAttempts = 0
|
|
2554
2558
|
updateConnectionState(ConnTypes.DISCONNECTED)
|
|
2559
|
+
clearPhysicalReadiness()
|
|
2555
2560
|
connected = false
|
|
2556
|
-
fullyBooted = false
|
|
2557
2561
|
glassesSessionId = nil
|
|
2558
2562
|
streamControlVersion = 0
|
|
2559
2563
|
readinessCompletedThisBleSession = false
|
|
@@ -2638,7 +2642,8 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2638
2642
|
// The reader thread keeps draining the stream (and returning CoC credits)
|
|
2639
2643
|
// while the existing transfer state remains serialized on the main actor.
|
|
2640
2644
|
DispatchQueue.main.async {
|
|
2641
|
-
self
|
|
2645
|
+
guard let self, self.l2capFileChannelId == channelId else { return }
|
|
2646
|
+
self.processReceivedData(frame)
|
|
2642
2647
|
}
|
|
2643
2648
|
},
|
|
2644
2649
|
onClose: { [weak self] in
|
|
@@ -2665,7 +2670,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2665
2670
|
|
|
2666
2671
|
// MARK: - Data Processing
|
|
2667
2672
|
|
|
2668
|
-
|
|
2673
|
+
/// Internal so native integration tests can replay the actual BLE receive path.
|
|
2669
2674
|
func processReceivedData(_ data: Data) {
|
|
2670
2675
|
guard data.count > 0 else { return }
|
|
2671
2676
|
|
|
@@ -2820,6 +2825,16 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2820
2825
|
Bridge.log("LIVE: Ignoring stale glasses_ready during pairing yield")
|
|
2821
2826
|
return
|
|
2822
2827
|
}
|
|
2828
|
+
let sid = (json["sid"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
2829
|
+
let readyId = (json["readyId"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
2830
|
+
if let readyId, isRepeatedGlassesReady(readyId: readyId, sid: sid) {
|
|
2831
|
+
Bridge.log("LIVE: Ignoring repeated glasses_ready for readiness exchange \(readyId) - the glasses did not reset for it")
|
|
2832
|
+
return
|
|
2833
|
+
}
|
|
2834
|
+
if readyId != nil, readyId == pendingReadyId {
|
|
2835
|
+
pendingReadyId = nil
|
|
2836
|
+
}
|
|
2837
|
+
readyGlassesSessionId = sid
|
|
2823
2838
|
// glasses_ready is a REMOTE wire-session reset: the glasses ran
|
|
2824
2839
|
// onTransportReset() before sending it, so their side is back on legacy
|
|
2825
2840
|
// framing regardless of what this side negotiated earlier. Start a fresh
|
|
@@ -2835,7 +2850,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
2835
2850
|
// Record the session id BEFORE marking ready: an unsolicited glasses_ready
|
|
2836
2851
|
// already runs this full remote-reset flow, so recording (not re-triggering)
|
|
2837
2852
|
// is correct here; version_info detection covers the restart case.
|
|
2838
|
-
glassesSessionId =
|
|
2853
|
+
glassesSessionId = sid
|
|
2839
2854
|
streamControlVersion = json["streamControlVersion"] as? Int ?? 0
|
|
2840
2855
|
Bridge.sendTypedMessage(
|
|
2841
2856
|
"wifi_protocol_session_ready",
|
|
@@ -3015,7 +3030,9 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3015
3030
|
|
|
3016
3031
|
case "stream_controller_probe":
|
|
3017
3032
|
if let response = StreamControllerProbe.response(json) {
|
|
3018
|
-
|
|
3033
|
+
// BES buffers non-waking commands when MTK enters standby, even while
|
|
3034
|
+
// its streaming CPU lease is held. The current probe needs a live reply.
|
|
3035
|
+
sendJson(response, wakeUp: true)
|
|
3019
3036
|
}
|
|
3020
3037
|
|
|
3021
3038
|
case "pong":
|
|
@@ -3164,6 +3181,11 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3164
3181
|
if type.hasPrefix("version_info") {
|
|
3165
3182
|
Bridge.log("LIVE: Received \(type)")
|
|
3166
3183
|
|
|
3184
|
+
// A new process can report its build before glasses_ready resets the
|
|
3185
|
+
// wire epoch. Publish its pending readiness before those version fields
|
|
3186
|
+
// can complete OTA and trigger the next request.
|
|
3187
|
+
handleGlassesSessionId(json)
|
|
3188
|
+
|
|
3167
3189
|
// Extract all fields from JSON (except "type")
|
|
3168
3190
|
var fields: [String: Any] = [:]
|
|
3169
3191
|
fields["version_info_type"] = type
|
|
@@ -3236,7 +3258,6 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3236
3258
|
// running them per chunk is safe.
|
|
3237
3259
|
parsePeerWireCaps(json)
|
|
3238
3260
|
maybeSendWireHandshake()
|
|
3239
|
-
handleGlassesSessionId(json)
|
|
3240
3261
|
|
|
3241
3262
|
Bridge.sendVersionInfo(fields, responseChunk: type)
|
|
3242
3263
|
} else {
|
|
@@ -3353,6 +3374,11 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3353
3374
|
processAncsRelay(body)
|
|
3354
3375
|
}
|
|
3355
3376
|
|
|
3377
|
+
case "sr_tpdef":
|
|
3378
|
+
if let body = k900ParseBody(json["B"]), body["setting"] as? String == "touch_gesture_default" {
|
|
3379
|
+
emitSettingsAck(body)
|
|
3380
|
+
}
|
|
3381
|
+
|
|
3356
3382
|
case "sr_hrt":
|
|
3357
3383
|
if let bodyObj = json["B"] as? [String: Any] {
|
|
3358
3384
|
let readyResponse = bodyObj["ready"] as? Int ?? 0
|
|
@@ -3395,12 +3421,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3395
3421
|
// This prevents re-initialization on every heartbeat after initial connection
|
|
3396
3422
|
// The ready flag is reset on disconnect/reconnect, so this won't prevent proper reconnection
|
|
3397
3423
|
if !fullyBooted {
|
|
3398
|
-
|
|
3399
|
-
"type": "phone_ready",
|
|
3400
|
-
"timestamp": Int64(Date().timeIntervalSince1970 * 1000),
|
|
3401
|
-
]
|
|
3402
|
-
// Send it through our data channel
|
|
3403
|
-
sendJson(readyMsg, wakeUp: true)
|
|
3424
|
+
sendPhoneReady(reason: "SOC ready")
|
|
3404
3425
|
}
|
|
3405
3426
|
}
|
|
3406
3427
|
}
|
|
@@ -3440,10 +3461,13 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3440
3461
|
if let body = k900ParseBody(json["B"]) {
|
|
3441
3462
|
let switchType = k900JsonInt(body, "type") ?? -1
|
|
3442
3463
|
let switchValue = k900JsonInt(body, "switch") ?? -1
|
|
3464
|
+
// K900 replies carry result in "S"; 0 is RC_SUCCESS.
|
|
3465
|
+
let resultCode = k900JsonInt(json, "S") ?? -1
|
|
3443
3466
|
handleSwitchStatus(
|
|
3444
3467
|
switchType: switchType,
|
|
3445
3468
|
value: switchValue,
|
|
3446
|
-
timestamp: Int64(Date().timeIntervalSince1970 * 1000)
|
|
3469
|
+
timestamp: Int64(Date().timeIntervalSince1970 * 1000),
|
|
3470
|
+
resultCode: resultCode
|
|
3447
3471
|
)
|
|
3448
3472
|
}
|
|
3449
3473
|
|
|
@@ -3459,7 +3483,14 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3459
3483
|
|
|
3460
3484
|
case "sr_wrst":
|
|
3461
3485
|
if let body = k900ParseBody(json["B"]) {
|
|
3462
|
-
Bridge.sendWearState(
|
|
3486
|
+
Bridge.sendWearState(
|
|
3487
|
+
worn: (k900JsonInt(body, "on") ?? 0) != 0,
|
|
3488
|
+
elapsedMs: k900JsonInt(body, "elapsed_ms"),
|
|
3489
|
+
timeoutMs: k900JsonInt(body, "timeout_ms"),
|
|
3490
|
+
enabled: body["enabled"] == nil ? nil : (k900JsonInt(body, "enabled") ?? 0) != 0,
|
|
3491
|
+
armed: body["armed"] == nil ? nil : (k900JsonInt(body, "armed") ?? 0) != 0,
|
|
3492
|
+
inhibited: body["inhibited"] == nil ? nil : (k900JsonInt(body, "inhibited") ?? 0) != 0
|
|
3493
|
+
)
|
|
3463
3494
|
}
|
|
3464
3495
|
|
|
3465
3496
|
case "sr_micrms":
|
|
@@ -3725,7 +3756,19 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3725
3756
|
sendJson(json, wakeUp: true)
|
|
3726
3757
|
}
|
|
3727
3758
|
|
|
3728
|
-
|
|
3759
|
+
var incidentLogTransportReady: Bool {
|
|
3760
|
+
connectedPeripheral?.state == .connected && txCharacteristic != nil
|
|
3761
|
+
}
|
|
3762
|
+
|
|
3763
|
+
func sendIncidentId(_ incidentId: String, apiBaseUrl: String?) throws {
|
|
3764
|
+
guard incidentLogTransportReady else {
|
|
3765
|
+
throw BluetoothSdkError(code: "glasses_not_connected", message: "Cannot request incident logs because the glasses BLE link is not ready.")
|
|
3766
|
+
}
|
|
3767
|
+
// Token sync may happen after glasses_ready; never rely on the last pairing's token.
|
|
3768
|
+
let coreToken = DeviceStore.shared.get("bluetooth", "core_token") as? String ?? ""
|
|
3769
|
+
guard !coreToken.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
|
3770
|
+
throw BluetoothSdkError(code: "core_token_unavailable", message: "Cannot request incident logs without the current Core access token.")
|
|
3771
|
+
}
|
|
3729
3772
|
var base = (apiBaseUrl ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
|
3730
3773
|
if base.isEmpty {
|
|
3731
3774
|
base = "https://api.mentra.glass"
|
|
@@ -3742,10 +3785,20 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3742
3785
|
fileBaseKey: lKey, incidentId: incidentId, apiBaseUrl: base, kind: .logcat
|
|
3743
3786
|
)
|
|
3744
3787
|
|
|
3745
|
-
|
|
3746
|
-
"
|
|
3747
|
-
|
|
3748
|
-
|
|
3788
|
+
let auth: [String: Any] = [
|
|
3789
|
+
"type": "auth_token", "coreToken": coreToken,
|
|
3790
|
+
"timestamp": Int64(Date().timeIntervalSince1970 * 1000),
|
|
3791
|
+
]
|
|
3792
|
+
// MainActor queue insertion preserves auth-before-upload order, including all fragments.
|
|
3793
|
+
guard sendJson(auth, wakeUp: true, requireAck: true, bridgeLogging: true),
|
|
3794
|
+
sendJson(["type": "upload_incident_logs", "incidentId": incidentId, "apiBaseUrl": base],
|
|
3795
|
+
wakeUp: true, requireAck: true, bridgeLogging: true)
|
|
3796
|
+
else {
|
|
3797
|
+
bleIncidentLogRelays.removeValue(forKey: bKey)
|
|
3798
|
+
bleIncidentLogRelays.removeValue(forKey: lKey)
|
|
3799
|
+
throw BluetoothSdkError(code: "incident_dispatch_failed", message: "Could not queue the glasses incident-log request.")
|
|
3800
|
+
}
|
|
3801
|
+
Bridge.log("LIVE: Queued incidentId to glasses for log upload: \(incidentId) (BLE relay \(bKey), \(lKey))")
|
|
3749
3802
|
}
|
|
3750
3803
|
|
|
3751
3804
|
private static func incidentBleFileBase(incidentId: String, prefix: Character) -> String {
|
|
@@ -3830,6 +3883,25 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3830
3883
|
sendJson(json, wakeUp: true)
|
|
3831
3884
|
}
|
|
3832
3885
|
|
|
3886
|
+
func sendTouchGestureDefaultBehaviorEnabled(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
|
|
3887
|
+
guard connectedPeripheral != nil, txCharacteristic != nil else {
|
|
3888
|
+
throw BluetoothSdkError(code: "not_connected", message: "Mentra Live glasses are not connected.")
|
|
3889
|
+
}
|
|
3890
|
+
try sendTouchGestureDefaultCommand(requestId: requestId, gesture: gesture, enabled: enabled)
|
|
3891
|
+
}
|
|
3892
|
+
|
|
3893
|
+
/// Kept separate from readiness admission so tests can replay the real K900 wire exchange.
|
|
3894
|
+
func sendTouchGestureDefaultCommand(requestId: String, gesture: TouchGesture, enabled: Bool) throws {
|
|
3895
|
+
let body = try JSONSerialization.data(withJSONObject: [
|
|
3896
|
+
"request_id": requestId, "gesture": gesture.rawValue, "enabled": enabled,
|
|
3897
|
+
])
|
|
3898
|
+
guard let bodyString = String(data: body, encoding: .utf8),
|
|
3899
|
+
sendRawK900Command(["C": "cs_tpdef", "V": 1, "B": bodyString])
|
|
3900
|
+
else {
|
|
3901
|
+
throw BluetoothSdkError(code: "command_send_failed", message: "Could not encode the touch gesture setting.")
|
|
3902
|
+
}
|
|
3903
|
+
}
|
|
3904
|
+
|
|
3833
3905
|
func sendGalleryServerEnabled(requestId: String, enabled: Bool) {
|
|
3834
3906
|
sendJson([
|
|
3835
3907
|
"type": "set_gallery_server_enabled",
|
|
@@ -3900,6 +3972,20 @@ class MentraLive: NSObject, SGCManager {
|
|
|
3900
3972
|
|
|
3901
3973
|
// MARK: - Message Handlers
|
|
3902
3974
|
|
|
3975
|
+
/// A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
|
|
3976
|
+
/// exchange the phone is waiting on, and any answer from a glasses process other than the
|
|
3977
|
+
/// one this link last handled (an asg restart resets for every exchange it first sees),
|
|
3978
|
+
/// followed a transport reset. Any other answer repeats an exchange that process already
|
|
3979
|
+
/// reset for, or one superseded by the pending exchange, whose answer is still to come.
|
|
3980
|
+
private func isRepeatedGlassesReady(readyId: String, sid: String?) -> Bool {
|
|
3981
|
+
readyId != pendingReadyId && sid == readyGlassesSessionId
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
private func resetReadinessExchange() {
|
|
3985
|
+
pendingReadyId = nil
|
|
3986
|
+
readyGlassesSessionId = nil
|
|
3987
|
+
}
|
|
3988
|
+
|
|
3903
3989
|
private func handleGlassesReady() {
|
|
3904
3990
|
Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
|
|
3905
3991
|
|
|
@@ -4148,7 +4234,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4148
4234
|
activeFileTransfers.removeValue(forKey: fileName)
|
|
4149
4235
|
}
|
|
4150
4236
|
|
|
4151
|
-
var session =
|
|
4237
|
+
var session = MentraLiveFileTransferSession(
|
|
4152
4238
|
fileName: fileName, fileSize: fileSize, announcedPackets: totalPackets
|
|
4153
4239
|
)
|
|
4154
4240
|
session.isAnnounced = true
|
|
@@ -4158,7 +4244,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4158
4244
|
if var bleTransfer = blePhotoTransfers[bleImgId] {
|
|
4159
4245
|
var bleSession =
|
|
4160
4246
|
bleTransfer.session
|
|
4161
|
-
??
|
|
4247
|
+
?? MentraLiveFileTransferSession(
|
|
4162
4248
|
fileName: fileName, fileSize: fileSize, announcedPackets: totalPackets
|
|
4163
4249
|
)
|
|
4164
4250
|
bleSession.updateAnnouncedPackets(totalPackets)
|
|
@@ -4251,8 +4337,8 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4251
4337
|
|
|
4252
4338
|
if incidentRelay.session == nil {
|
|
4253
4339
|
activeFileTransfers.removeValue(forKey: packetInfo.fileName)
|
|
4254
|
-
var session =
|
|
4255
|
-
fileName: packetInfo.fileName, fileSize: Int(packetInfo.fileSize)
|
|
4340
|
+
var session = MentraLiveFileTransferSession(
|
|
4341
|
+
fileName: packetInfo.fileName, fileSize: Int(packetInfo.fileSize), flags: packetInfo.flags
|
|
4256
4342
|
)
|
|
4257
4343
|
session.recalculateTotalPackets(actualPackSize: Int(packetInfo.packSize))
|
|
4258
4344
|
incidentRelay.session = session
|
|
@@ -4303,10 +4389,11 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4303
4389
|
|
|
4304
4390
|
// Get or create session for this transfer
|
|
4305
4391
|
if photoTransfer.session == nil {
|
|
4306
|
-
var session =
|
|
4392
|
+
var session = MentraLiveFileTransferSession(
|
|
4307
4393
|
fileName: packetInfo.fileName,
|
|
4308
|
-
fileSize: Int(packetInfo.fileSize)
|
|
4394
|
+
fileSize: Int(packetInfo.fileSize), flags: packetInfo.flags
|
|
4309
4395
|
)
|
|
4396
|
+
session.recalculateTotalPackets(actualPackSize: Int(packetInfo.packSize))
|
|
4310
4397
|
photoTransfer.session = session
|
|
4311
4398
|
blePhotoTransfers[bleImgId] = photoTransfer
|
|
4312
4399
|
Bridge.log(
|
|
@@ -4379,9 +4466,10 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4379
4466
|
var session = activeFileTransfers[packetInfo.fileName]
|
|
4380
4467
|
if session == nil {
|
|
4381
4468
|
// New file transfer
|
|
4382
|
-
session =
|
|
4383
|
-
fileName: packetInfo.fileName, fileSize: Int(packetInfo.fileSize)
|
|
4469
|
+
session = MentraLiveFileTransferSession(
|
|
4470
|
+
fileName: packetInfo.fileName, fileSize: Int(packetInfo.fileSize), flags: packetInfo.flags
|
|
4384
4471
|
)
|
|
4472
|
+
session?.recalculateTotalPackets(actualPackSize: Int(packetInfo.packSize))
|
|
4385
4473
|
activeFileTransfers[packetInfo.fileName] = session
|
|
4386
4474
|
|
|
4387
4475
|
Bridge.log(
|
|
@@ -4680,20 +4768,13 @@ class MentraLive: NSObject, SGCManager {
|
|
|
4680
4768
|
|
|
4681
4769
|
func queueSend(_ data: Data, id: String, trace: BleWriteTrace?) {
|
|
4682
4770
|
let significantQueueSize = SIGNIFICANT_BLE_TRACE_QUEUE_SIZE
|
|
4683
|
-
//
|
|
4684
|
-
// session reset, and a pre-reset payload stamped with the new generation would
|
|
4685
|
-
// defeat the stale-write guard in the drain loop.
|
|
4771
|
+
// Insert synchronously on MainActor so fragments and dependent commands retain call order.
|
|
4686
4772
|
let generation = wireSessionGeneration
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
await MainActor.run {
|
|
4693
|
-
self.logBleChunkTrace("queued", trace, extra: [
|
|
4694
|
-
"queueSizeAfterAdd": queueSize,
|
|
4695
|
-
])
|
|
4696
|
-
}
|
|
4773
|
+
let queueSize = commandQueue.enqueue(PendingMessage(data: data, id: id, retries: 0, trace: trace, generation: generation))
|
|
4774
|
+
if trace != nil, queueSize >= significantQueueSize {
|
|
4775
|
+
logBleChunkTrace("queued", trace, extra: [
|
|
4776
|
+
"queueSizeAfterAdd": queueSize,
|
|
4777
|
+
])
|
|
4697
4778
|
}
|
|
4698
4779
|
}
|
|
4699
4780
|
|
|
@@ -5210,7 +5291,10 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5210
5291
|
bridgeLogging: bridgeLogging
|
|
5211
5292
|
)
|
|
5212
5293
|
}
|
|
5213
|
-
|
|
5294
|
+
// Credentials reach the wire unchanged; diagnostic logs omit their values.
|
|
5295
|
+
let loggedPayload = json["password"] == nil && json["coreToken"] == nil
|
|
5296
|
+
? jsonString : "<\(commandInfo.commandType) with credentials omitted>"
|
|
5297
|
+
transportLog("LIVE: Sending data to glasses: \(loggedPayload)", bridgeLogging: bridgeLogging)
|
|
5214
5298
|
let packedData =
|
|
5215
5299
|
packJson(
|
|
5216
5300
|
jsonString,
|
|
@@ -5273,7 +5357,8 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5273
5357
|
if let requestId {
|
|
5274
5358
|
json["request_id"] = requestId
|
|
5275
5359
|
}
|
|
5276
|
-
|
|
5360
|
+
// Wake ASG so the version request and its response can finish after idle.
|
|
5361
|
+
sendJson(json, wakeUp: true)
|
|
5277
5362
|
}
|
|
5278
5363
|
|
|
5279
5364
|
private func sendCoreTokenToAsgClient() {
|
|
@@ -5523,8 +5608,17 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5523
5608
|
Bridge.sendSpeakingStatus(speaking)
|
|
5524
5609
|
}
|
|
5525
5610
|
|
|
5526
|
-
private func handleSwitchStatus(
|
|
5611
|
+
private func handleSwitchStatus(
|
|
5612
|
+
switchType: Int, value: Int, timestamp: Int64, resultCode: Int = -1
|
|
5613
|
+
) {
|
|
5527
5614
|
Bridge.sendSwitchStatus(switchType: switchType, value: value, timestamp: timestamp)
|
|
5615
|
+
if switchType == Self.autoPowerOffSwitchType {
|
|
5616
|
+
let ok = resultCode == 0
|
|
5617
|
+
Bridge.log(
|
|
5618
|
+
"LIVE: 🔋 auto power-off sr_swit reply type=\(switchType) switch=\(value)"
|
|
5619
|
+
+ " result=\(resultCode) ok=\(ok)"
|
|
5620
|
+
)
|
|
5621
|
+
}
|
|
5528
5622
|
if switchType == Self.voiceActivityDetectionSwitchType, value == 0 || value == 1 {
|
|
5529
5623
|
handleVoiceActivityDetectionStatus(enabled: value == 1)
|
|
5530
5624
|
}
|
|
@@ -5723,7 +5817,7 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5723
5817
|
stopReadinessCheckLoop()
|
|
5724
5818
|
|
|
5725
5819
|
readinessCheckCounter = 0
|
|
5726
|
-
|
|
5820
|
+
clearPhysicalReadiness()
|
|
5727
5821
|
connected = false
|
|
5728
5822
|
glassesSessionId = nil
|
|
5729
5823
|
streamControlVersion = 0
|
|
@@ -5744,12 +5838,13 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5744
5838
|
)
|
|
5745
5839
|
// requestReadyK900()
|
|
5746
5840
|
|
|
5747
|
-
|
|
5748
|
-
|
|
5749
|
-
|
|
5750
|
-
]
|
|
5751
|
-
|
|
5752
|
-
|
|
5841
|
+
// The timer fires on bluetoothQueue; the pending readiness exchange is main-actor state.
|
|
5842
|
+
// A tick queued just before glasses_ready stopped the loop must not start a new exchange.
|
|
5843
|
+
let check = self.readinessCheckCounter
|
|
5844
|
+
DispatchQueue.main.async { [weak self] in
|
|
5845
|
+
guard let self, self.readinessCheckDispatchTimer != nil else { return }
|
|
5846
|
+
self.sendPhoneReady(reason: "readiness check #\(check)")
|
|
5847
|
+
}
|
|
5753
5848
|
}
|
|
5754
5849
|
|
|
5755
5850
|
readinessCheckDispatchTimer!.resume()
|
|
@@ -5995,16 +6090,18 @@ class MentraLive: NSObject, SGCManager {
|
|
|
5995
6090
|
// Stop all timers
|
|
5996
6091
|
stopAllTimers()
|
|
5997
6092
|
resetWireNegotiationState()
|
|
5998
|
-
|
|
6093
|
+
resetReadinessExchange()
|
|
6094
|
+
commandQueue.removeAll() // stale writes die with the session
|
|
5999
6095
|
closeL2capFileChannel()
|
|
6000
6096
|
|
|
6001
6097
|
// Disconnect BLE
|
|
6098
|
+
cancelPendingReconnect(reason: "destroy")
|
|
6002
6099
|
if let peripheral = connectedPeripheral {
|
|
6003
6100
|
centralManager?.cancelPeripheralConnection(peripheral)
|
|
6004
6101
|
}
|
|
6005
6102
|
|
|
6103
|
+
clearPhysicalReadiness()
|
|
6006
6104
|
DeviceStore.shared.apply("glasses", "connected", false)
|
|
6007
|
-
DeviceStore.shared.apply("glasses", "fullyBooted", false)
|
|
6008
6105
|
DeviceStore.shared.apply("glasses", "wifiConnected", false)
|
|
6009
6106
|
DeviceStore.shared.apply("glasses", "wifiSsid", "")
|
|
6010
6107
|
DeviceStore.shared.apply("glasses", "wifiLocalIp", "")
|
|
@@ -6123,10 +6220,15 @@ extension MentraLive {
|
|
|
6123
6220
|
|
|
6124
6221
|
/// Sends phone_ready to (re)start the glasses-driven readiness flow.
|
|
6125
6222
|
private func sendPhoneReady(reason: String) {
|
|
6126
|
-
|
|
6223
|
+
let readyId = pendingReadyId ?? UUID().uuidString
|
|
6224
|
+
pendingReadyId = readyId
|
|
6225
|
+
Bridge.log(
|
|
6226
|
+
"LIVE: 📱 Sending phone_ready to glasses (\(reason), exchange \(readyId)) - waiting for glasses_ready response"
|
|
6227
|
+
)
|
|
6127
6228
|
let readyMsg: [String: Any] = [
|
|
6128
6229
|
"type": "phone_ready",
|
|
6129
6230
|
"timestamp": Int64(Date().timeIntervalSince1970 * 1000),
|
|
6231
|
+
"readyId": readyId,
|
|
6130
6232
|
]
|
|
6131
6233
|
sendJson(readyMsg, wakeUp: true)
|
|
6132
6234
|
}
|
|
@@ -6141,8 +6243,8 @@ extension MentraLive {
|
|
|
6141
6243
|
/// pre-sid build) or differing from the recorded one = restart; same sid = no action.
|
|
6142
6244
|
/// A restart is a LOGICAL session reset: send phone_ready immediately (bypassing the
|
|
6143
6245
|
/// sr_hrt heartbeat's stale-readiness suppression); the returning glasses_ready runs
|
|
6144
|
-
/// the full existing remote-wire-reset flow.
|
|
6145
|
-
///
|
|
6246
|
+
/// the full existing remote-wire-reset flow. Keep the physical connection intact,
|
|
6247
|
+
/// but mark readiness pending until that new wire epoch has been established.
|
|
6146
6248
|
private func handleGlassesSessionId(_ json: [String: Any]) {
|
|
6147
6249
|
guard let sid = json["sid"] as? String, !sid.isEmpty else { return }
|
|
6148
6250
|
let previous = glassesSessionId
|
|
@@ -6157,6 +6259,9 @@ extension MentraLive {
|
|
|
6157
6259
|
"LIVE: 🔁 Glasses session changed (\(previous ?? "<pre-sid build>") -> \(sid)) - " +
|
|
6158
6260
|
"asg restarted under a live link, re-running readiness"
|
|
6159
6261
|
)
|
|
6262
|
+
// Emit the existing connected-but-not-ready status without invoking the
|
|
6263
|
+
// physical-disconnect side effects of DeviceStore.apply(fullyBooted: false).
|
|
6264
|
+
DeviceStore.shared.set("glasses", "fullyBooted", false)
|
|
6160
6265
|
sendPhoneReady(reason: "glasses session changed")
|
|
6161
6266
|
Bridge.sendTypedMessage(
|
|
6162
6267
|
"glasses_session_changed",
|
|
@@ -6874,6 +6979,9 @@ extension MentraLive {
|
|
|
6874
6979
|
// Send glasses-side loudness / Barrier gate setting.
|
|
6875
6980
|
sendLoudnessGateSetting()
|
|
6876
6981
|
|
|
6982
|
+
// Send glasses-side auto power-off setting.
|
|
6983
|
+
sendAutoPowerOffSetting()
|
|
6984
|
+
|
|
6877
6985
|
// Send mic tuning. With nothing authorized this sends a reset, which is
|
|
6878
6986
|
// what returns a freshly connected pair of glasses to stock behaviour.
|
|
6879
6987
|
sendMicTuningSetting()
|
|
@@ -7100,6 +7208,46 @@ extension MentraLive {
|
|
|
7100
7208
|
}
|
|
7101
7209
|
}
|
|
7102
7210
|
|
|
7211
|
+
func sendAutoPowerOffSetting() {
|
|
7212
|
+
let enabled = DeviceStore.shared.get("bluetooth", "auto_power_off_enabled") as? Bool
|
|
7213
|
+
?? BluetoothSdkDefaults.autoPowerOffEnabled
|
|
7214
|
+
Bridge.log(
|
|
7215
|
+
"LIVE: 🔋 Sending auto power-off setting to glasses: enabled=\(enabled)"
|
|
7216
|
+
+ " (cs_swit type=\(Self.autoPowerOffSwitchType))"
|
|
7217
|
+
)
|
|
7218
|
+
|
|
7219
|
+
guard connectedPeripheral != nil, txCharacteristic != nil else {
|
|
7220
|
+
Bridge.log("LIVE: Cannot send auto power-off setting - BLE write path not ready")
|
|
7221
|
+
return
|
|
7222
|
+
}
|
|
7223
|
+
|
|
7224
|
+
do {
|
|
7225
|
+
let bodyData = try JSONSerialization.data(withJSONObject: [
|
|
7226
|
+
"type": Self.autoPowerOffSwitchType,
|
|
7227
|
+
"switch": enabled ? 1 : 0,
|
|
7228
|
+
])
|
|
7229
|
+
guard let bodyString = String(data: bodyData, encoding: .utf8) else {
|
|
7230
|
+
Bridge.log("LIVE: Failed to encode auto power-off payload")
|
|
7231
|
+
return
|
|
7232
|
+
}
|
|
7233
|
+
let command: [String: Any] = [
|
|
7234
|
+
"C": "cs_swit",
|
|
7235
|
+
"V": 1,
|
|
7236
|
+
"B": bodyString,
|
|
7237
|
+
]
|
|
7238
|
+
if !sendRawK900Command(command, wakeUp: true) {
|
|
7239
|
+
Bridge.log("LIVE: Failed to send auto power-off setting command")
|
|
7240
|
+
} else {
|
|
7241
|
+
Bridge.log(
|
|
7242
|
+
"LIVE: 🔋 Queued auto power-off cs_swit type=\(Self.autoPowerOffSwitchType)"
|
|
7243
|
+
+ " switch=\(enabled ? 1 : 0)"
|
|
7244
|
+
)
|
|
7245
|
+
}
|
|
7246
|
+
} catch {
|
|
7247
|
+
Bridge.log("LIVE: Error encoding auto power-off payload: \(error)")
|
|
7248
|
+
}
|
|
7249
|
+
}
|
|
7250
|
+
|
|
7103
7251
|
func sendButtonVideoRecordingSettings() {
|
|
7104
7252
|
let settings =
|
|
7105
7253
|
DeviceStore.shared.get("bluetooth", "button_video_settings") as? [String: Any] ?? [
|
|
@@ -7418,7 +7566,7 @@ extension MentraLive {
|
|
|
7418
7566
|
if fps > 0 { settings["fps"] = fps }
|
|
7419
7567
|
json["settings"] = settings
|
|
7420
7568
|
}
|
|
7421
|
-
sendJson(json)
|
|
7569
|
+
sendJson(json, wakeUp: true)
|
|
7422
7570
|
}
|
|
7423
7571
|
|
|
7424
7572
|
func stopVideoRecording(requestId: String) {
|
|
@@ -7433,7 +7581,7 @@ extension MentraLive {
|
|
|
7433
7581
|
sendJson([
|
|
7434
7582
|
"type": "get_video_recording_status",
|
|
7435
7583
|
"requestId": requestId,
|
|
7436
|
-
])
|
|
7584
|
+
], wakeUp: true)
|
|
7437
7585
|
}
|
|
7438
7586
|
|
|
7439
7587
|
func stopVideoRecording(requestId: String, webhookUrl: String?, authToken: String?) {
|
|
@@ -7458,7 +7606,7 @@ extension MentraLive {
|
|
|
7458
7606
|
if let authToken, !authToken.isEmpty {
|
|
7459
7607
|
json["authToken"] = authToken
|
|
7460
7608
|
}
|
|
7461
|
-
sendJson(json)
|
|
7609
|
+
sendJson(json, wakeUp: true)
|
|
7462
7610
|
}
|
|
7463
7611
|
}
|
|
7464
7612
|
|