@mentra/bluetooth-sdk 3.4.0-beta.1346 → 3.4.0-beta.1347

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.
@@ -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
@@ -583,14 +586,27 @@ class Nimo: NSObject, SGCManager {
583
586
  static let batteryPollSeconds: TimeInterval = 30
584
587
  /// Fall back to the other ear if the preferred one goes quiet for this long.
585
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
586
598
  }
587
599
 
600
+ private static var updateAttempts = 0
601
+
588
602
  // BLE
589
603
  private var centralManager: CBCentralManager?
590
604
  private var peripheral: CBPeripheral?
591
605
  private var txChar: CBCharacteristic?
592
606
  private var rxChar: CBCharacteristic?
593
607
  private var micChar: CBCharacteristic?
608
+ private var otaTxChar: CBCharacteristic?
609
+ private var otaRxChar: CBCharacteristic?
594
610
  private var isDisconnecting = false
595
611
  private var scanRequested = false
596
612
  private lazy var discovery = NimoDiscovery<CBPeripheral>(
@@ -691,6 +707,17 @@ class Nimo: NSObject, SGCManager {
691
707
  // Version info
692
708
  private var firmwareVersionPacked = ""
693
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 }
694
721
 
695
722
  // Mic audio
696
723
  private var opusDecoder: NimoOpusDecoder?
@@ -740,6 +767,8 @@ class Nimo: NSObject, SGCManager {
740
767
  txChar = nil
741
768
  rxChar = nil
742
769
  micChar = nil
770
+ otaTxChar = nil
771
+ otaRxChar = nil
743
772
  resetSessionState()
744
773
 
745
774
  DeviceStore.shared.apply("glasses", "connected", false)
@@ -806,6 +835,10 @@ class Nimo: NSObject, SGCManager {
806
835
  Bridge.log("NIMO: mic characteristic not available")
807
836
  return
808
837
  }
838
+ if enabled, updating {
839
+ Bridge.log("NIMO: mic stays off during the firmware update")
840
+ return
841
+ }
809
842
  DeviceStore.shared.apply("glasses", "micEnabled", enabled)
810
843
  if enabled {
811
844
  if opusDecoder == nil {
@@ -1188,7 +1221,8 @@ class Nimo: NSObject, SGCManager {
1188
1221
  // MARK: - Write Queue
1189
1222
 
1190
1223
  private func enqueueWrite(_ characteristic: CBCharacteristic, _ bytes: Data) {
1191
- guard let peripheral else { return }
1224
+ // The firmware update owns the link; ordinary commands wait for the next connection.
1225
+ guard !updating, let peripheral else { return }
1192
1226
  writes.enqueue(peripheral, characteristic: characteristic, frames: [bytes])
1193
1227
  }
1194
1228
 
@@ -1200,7 +1234,7 @@ class Nimo: NSObject, SGCManager {
1200
1234
  private func enqueueFrames(_ frames: [Data], finalStarted: @escaping () -> Void,
1201
1235
  completed: @escaping () -> Void) -> Bool
1202
1236
  {
1203
- guard let peripheral, let txChar else { return false }
1237
+ guard !updating, let peripheral, let txChar else { return false }
1204
1238
  return writes.enqueue(peripheral, characteristic: txChar, frames: frames,
1205
1239
  finalStarted: finalStarted, completed: completed)
1206
1240
  }
@@ -1325,12 +1359,147 @@ class Nimo: NSObject, SGCManager {
1325
1359
  DeviceStore.shared.apply("glasses", "fullyBooted", true)
1326
1360
  DeviceStore.shared.apply("glasses", "connectionState", ConnTypes.CONNECTED)
1327
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
1328
1415
  // The Launch ACK validates peer readiness without waiting for the first
1329
1416
  // unsolicited heartbeat (which can arrive a minute after connection).
1330
1417
  canvas.activate()
1331
1418
  canvas.readiness(twsConnected && peerCompanionReady != false)
1332
1419
  }
1333
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
+
1334
1503
  private func handshakeFailed() {
1335
1504
  handshakeState = .idle
1336
1505
  if let peripheral {
@@ -1346,6 +1515,13 @@ class Nimo: NSObject, SGCManager {
1346
1515
  peerCompanionReady = nil
1347
1516
  canvasEncoder.invalidate()
1348
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
1349
1525
  receiveAssembler.reset()
1350
1526
  writes.reset()
1351
1527
  failAllPendingAcks()
@@ -1464,7 +1640,7 @@ class Nimo: NSObject, SGCManager {
1464
1640
  if v.count >= 10 {
1465
1641
  peerCompanionReady = v[9] != 0
1466
1642
  onTwsState(Int(v[8]) >= 1)
1467
- if handshakeState == .ready {
1643
+ if handshakeState == .ready, firmwareState == .current {
1468
1644
  canvas.readiness(twsConnected && peerCompanionReady != false, confirmed: true)
1469
1645
  }
1470
1646
  }
@@ -1488,7 +1664,7 @@ class Nimo: NSObject, SGCManager {
1488
1664
  if !connected, handshakeState == .ready {
1489
1665
  Bridge.log("NIMO: TWS service dropped mid-session (arm removed/off?)")
1490
1666
  }
1491
- if handshakeState == .ready { canvas.readiness(connected && peerCompanionReady != false) }
1667
+ if handshakeState == .ready, firmwareState == .current { canvas.readiness(connected && peerCompanionReady != false) }
1492
1668
  }
1493
1669
 
1494
1670
  private func handleInputEvent(_ code: Int) {
@@ -1549,7 +1725,9 @@ class Nimo: NSObject, SGCManager {
1549
1725
  let micro = (v >> 12) & 0x1FF
1550
1726
  let build = v & 0xFFF
1551
1727
  firmwareVersionPacked = "\(major).\(minor).\(micro).\(build)"
1728
+ versionPackedReceived = true
1552
1729
  emitVersionInfo()
1730
+ checkFirmware()
1553
1731
  }
1554
1732
  case NimoProtocol.GET_VERSION_DETAIL:
1555
1733
  var end = bytes.count
@@ -1559,7 +1737,9 @@ class Nimo: NSObject, SGCManager {
1559
1737
  firmwareVersionDetail =
1560
1738
  String(bytes: bytes[0 ..< end], encoding: .utf8)?
1561
1739
  .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
1740
+ versionDetailReceived = true
1562
1741
  emitVersionInfo()
1742
+ checkFirmware()
1563
1743
  case NimoProtocol.GET_TWS_STATUS:
1564
1744
  if !bytes.isEmpty {
1565
1745
  onTwsState(Int(bytes[0]) >= 1)
@@ -1698,6 +1878,8 @@ extension Nimo: CBCentralManagerDelegate {
1698
1878
  self.txChar = nil
1699
1879
  self.rxChar = nil
1700
1880
  self.micChar = nil
1881
+ self.otaTxChar = nil
1882
+ self.otaRxChar = nil
1701
1883
  self.resetSessionState()
1702
1884
 
1703
1885
  if (DeviceManager.shared.sgc as? Nimo) === self {
@@ -1745,6 +1927,11 @@ extension Nimo: CBPeripheralDelegate {
1745
1927
  case NimoBLE.CHAR_MIC:
1746
1928
  self.micChar = char
1747
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
1748
1935
  default:
1749
1936
  break
1750
1937
  }
@@ -1766,6 +1953,16 @@ extension Nimo: CBPeripheralDelegate {
1766
1953
  DispatchQueue.main.async { [weak self] in
1767
1954
  guard let self else { return }
1768
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
+ }
1769
1966
  if let error {
1770
1967
  self.abortTransport("Notification subscription failed")
1771
1968
  Bridge.log("NIMO: notify enable failed: \(error.localizedDescription)")
@@ -1792,7 +1989,9 @@ extension Nimo: CBPeripheralDelegate {
1792
1989
  if uuid == NimoBLE.CHAR_RX, characteristic === self.rxChar {
1793
1990
  self.handleRxPacket(data)
1794
1991
  } else if uuid == NimoBLE.CHAR_MIC, characteristic === self.micChar {
1795
- 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)
1796
1995
  }
1797
1996
  }
1798
1997
  }
@@ -1804,4 +2003,11 @@ extension Nimo: CBPeripheralDelegate {
1804
2003
  self?.writes.written(peripheral, characteristic: characteristic, success: error == nil)
1805
2004
  }
1806
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
+ }
1807
2013
  }
@@ -0,0 +1,260 @@
1
+ import CryptoKit
2
+ import Foundation
3
+
4
+ /// The one NIMO firmware the app supports: the vendor's 537cf1 dynamic-v1 build.
5
+ enum NimoFirmwareTarget {
6
+ static let packedVersion = "0.1.1.1"
7
+ static let buildTag = "537cf1"
8
+ static let sha256 = "5e23c574e3dfd8c27172f4f9a33475e6efd0d33e7230bfcce8f4fe8ca59fe433"
9
+ static let resourceBundle = "MentraNimoFirmware"
10
+ static let resourceName = "nimo-firmware-0.1.1.1-537cf1"
11
+ static let updatingText = "Updating your NIMO glasses.\n\nKeep the Mentra app open."
12
+
13
+ /// A missing detail string (older firmware) is judged on the packed version alone.
14
+ static func isCurrent(packedVersion: String, detail: String) -> Bool {
15
+ packedVersion == self.packedVersion && (detail.isEmpty || detail.contains("-\(buildTag)-"))
16
+ }
17
+
18
+ static func hash(_ data: Data) -> String {
19
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
20
+ }
21
+
22
+ /// The bundled image, only if it is exactly the expected file.
23
+ static func load() -> Data? {
24
+ let candidates = [Bundle(for: Nimo.self), Bundle.main]
25
+ for bundle in candidates {
26
+ let resources = bundle.url(forResource: resourceBundle, withExtension: "bundle").flatMap(Bundle.init(url:)) ?? bundle
27
+ guard let url = resources.url(forResource: resourceName, withExtension: "bin"),
28
+ let data = try? Data(contentsOf: url) else { continue }
29
+ if hash(data) == sha256 { return data }
30
+ Bridge.log("NIMO: bundled firmware hash mismatch")
31
+ return nil
32
+ }
33
+ Bridge.log("NIMO: bundled firmware unavailable")
34
+ return nil
35
+ }
36
+ }
37
+
38
+ /// Single-attempt NIMO OTA over the 2001/2002 channel. Main-thread confined; `schedule` posts there.
39
+ /// `finished` gets nil once the reboot command was sent, otherwise the failure reason.
40
+ /// No failure path sends reset; the next connection decides again from the reported version.
41
+ final class NimoFirmwareUpdater {
42
+ private struct Failure: Error, LocalizedError {
43
+ let message: String
44
+ var errorDescription: String? { message }
45
+ }
46
+
47
+ private final class Pending {
48
+ let command: UInt8
49
+ let sequence: UInt8
50
+ let callback: (Result<Data, Error>) -> Void
51
+ init(_ command: UInt8, _ sequence: UInt8, _ callback: @escaping (Result<Data, Error>) -> Void) {
52
+ self.command = command; self.sequence = sequence; self.callback = callback
53
+ }
54
+ }
55
+
56
+ private let firmware: Data
57
+ private let capacity: Int
58
+ private let schedule: NimoScheduler
59
+ private let write: (Data, @escaping (Bool) -> Void) -> Void
60
+ private let progress: (Int) -> Void
61
+ private let finished: (String?) -> Void
62
+ private let decoder = NimoOtaProtocol.Decoder()
63
+ private var sequence: UInt8 = 0
64
+ private var pending: Pending?
65
+ private var cancelTimer: (() -> Void)?
66
+ private var cancelDelay: (() -> Void)?
67
+ private var done = false
68
+ private var crc = false
69
+ private var covered: [Bool]
70
+ private var coveredCount = 0
71
+ private var lastPercent = -1
72
+ private var stalls = 0
73
+ private var transferStarted = Date()
74
+ private var syncPending = 0
75
+ private var syncFailures = 0
76
+
77
+ init(firmware: Data, writeCapacity: Int, schedule: @escaping NimoScheduler,
78
+ write: @escaping (Data, @escaping (Bool) -> Void) -> Void,
79
+ progress: @escaping (Int) -> Void, finished: @escaping (String?) -> Void)
80
+ {
81
+ self.firmware = Data(firmware)
82
+ capacity = min(512, writeCapacity)
83
+ self.schedule = schedule
84
+ self.write = write
85
+ self.progress = progress
86
+ self.finished = finished
87
+ covered = Array(repeating: false, count: firmware.count)
88
+ }
89
+
90
+ func start() {
91
+ exchange(NimoOtaProtocol.info, Data(repeating: 0xFF, count: 4)) { [self] info in
92
+ try checkDeviceInfo(info)
93
+ exchange(NimoOtaProtocol.fileOffsetCommand) { [self] body in
94
+ let header = try NimoOtaProtocol.firmwareSlice(firmware, NimoOtaProtocol.fileOffset(body))
95
+ exchange(NimoOtaProtocol.canUpdate, header) { [self] result in
96
+ // 0 = can update, 3 = same image already staged; anything else is a refusal.
97
+ guard result == Data([0]) || result == Data([3]) else {
98
+ throw Failure(message: "Glasses refused the firmware (battery or prerequisites)")
99
+ }
100
+ exchange(NimoOtaProtocol.enter) { [self] entryBody in
101
+ let entry = try NimoOtaProtocol.enterResult(entryBody)
102
+ crc = entry.crc
103
+ transferStarted = Date()
104
+ try sendBlock(entry.slice)
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ func receive(_ data: Data) {
112
+ guard !done else { return }
113
+ do {
114
+ for reply in try decoder.feed(data) {
115
+ guard let expected = pending, expected.command == reply.command, expected.sequence == reply.sequence else { continue }
116
+ pending = nil
117
+ cancelTimer?(); cancelTimer = nil
118
+ if reply.status == 0 { expected.callback(.success(reply.body)) } else {
119
+ expected.callback(.failure(Failure(message: "OTA command \(reply.command) returned status \(reply.status)")))
120
+ }
121
+ }
122
+ } catch { fail(error) }
123
+ }
124
+
125
+ /// The connection went away; stop without reporting.
126
+ func cancel() {
127
+ done = true
128
+ clearTimers()
129
+ }
130
+
131
+ private func checkDeviceInfo(_ body: Data) throws {
132
+ let fields = try NimoOtaProtocol.deviceInfo(body)
133
+ guard fields[3] == Data([1]), fields[5] == Data([1]), fields[2]?.count == 2 else {
134
+ throw Failure(message: "Both arms must be connected and ready to update")
135
+ }
136
+ }
137
+
138
+ private func sendBlock(_ slice: NimoOtaProtocol.Slice) throws {
139
+ guard Date().timeIntervalSince(transferStarted) <= 20 * 60 else { throw Failure(message: "Transfer exceeded 20 minutes") }
140
+ let parts = try NimoOtaProtocol.blockParts(firmware, slice: slice, crc: crc, writeCapacity: capacity)
141
+ sendPart(parts, 0) { [self] body in
142
+ let next = try NimoOtaProtocol.blockResult(body)
143
+ var added = 0
144
+ for index in Int(slice.offset) ..< Int(slice.offset) + slice.length where !covered[index] {
145
+ covered[index] = true
146
+ added += 1
147
+ }
148
+ coveredCount += added
149
+ stalls = added == 0 ? stalls + 1 : 0
150
+ guard stalls < 5 else { throw Failure(message: "Five repeated blocks without progress") }
151
+ let percent = coveredCount * 100 / firmware.count
152
+ if percent != lastPercent { lastPercent = percent; progress(percent) }
153
+ if next.slice.offset == 0, next.slice.length == 0 {
154
+ exchange(NimoOtaProtocol.validate, timeout: 30) { [self] validation in
155
+ guard validation == Data([0]) else { throw Failure(message: "Glasses rejected the transferred image") }
156
+ pollSync()
157
+ }
158
+ } else {
159
+ _ = try NimoOtaProtocol.firmwareSlice(firmware, next.slice)
160
+ delay(TimeInterval(next.delayMs) / 1000) { [self] in try sendBlock(next.slice) }
161
+ }
162
+ }
163
+ }
164
+
165
+ private func sendPart(_ parts: [Data], _ index: Int, completion: @escaping (Data) throws -> Void) {
166
+ if index == parts.count - 1 { exchange(NimoOtaProtocol.block, parts[index], timeout: 30, completion); return }
167
+ do {
168
+ let packet = try nextPacket(NimoOtaProtocol.block, parts[index])
169
+ write(packet) { [weak self] ok in
170
+ guard let self, !self.done else { return }
171
+ if !ok { self.fail(Failure(message: "OTA write failed")); return }
172
+ self.delay(0.005) { [self] in self.sendPart(parts, index + 1, completion: completion) }
173
+ }
174
+ } catch { fail(error) }
175
+ }
176
+
177
+ /// Wait for the right arm to copy the image to the left arm, then reboot both.
178
+ private func pollSync() {
179
+ exchangeResult(NimoOtaProtocol.sync, timeout: 8) { [self] result in
180
+ let body = try? result.get()
181
+ if body == Data([0]) {
182
+ do {
183
+ let packet = try nextPacket(NimoOtaProtocol.reset, Data([0]))
184
+ write(packet) { _ in }
185
+ done = true
186
+ clearTimers()
187
+ finished(nil)
188
+ } catch { fail(error) }
189
+ return
190
+ }
191
+ if body == Data([1]) { syncPending += 1 } else { syncFailures += 1 }
192
+ if syncPending >= 180 || syncFailures >= 8 {
193
+ fail(Failure(message: "Arms did not finish synchronizing; no reboot sent"))
194
+ } else {
195
+ delay(1) { [self] in pollSync() }
196
+ }
197
+ }
198
+ }
199
+
200
+ private func exchange(_ command: UInt8, _ params: Data = Data(), timeout: TimeInterval = 15,
201
+ _ completion: @escaping (Data) throws -> Void)
202
+ {
203
+ exchangeResult(command, params, timeout: timeout) { [weak self] result in
204
+ do { try completion(result.get()) } catch { self?.fail(error) }
205
+ }
206
+ }
207
+
208
+ private func exchangeResult(_ command: UInt8, _ params: Data = Data(), timeout: TimeInterval,
209
+ _ completion: @escaping (Result<Data, Error>) -> Void)
210
+ {
211
+ guard !done else { return }
212
+ do {
213
+ let packet = try nextPacket(command, params)
214
+ let entry = Pending(command, sequence, completion)
215
+ pending = entry
216
+ cancelTimer = schedule(timeout) { [weak self] in
217
+ guard let self, self.pending === entry, !self.done else { return }
218
+ self.pending = nil; self.cancelTimer = nil
219
+ completion(.failure(Failure(message: "OTA command \(command) timed out")))
220
+ }
221
+ write(packet) { [weak self] ok in
222
+ guard let self, !ok, self.pending === entry, !self.done else { return }
223
+ self.pending = nil
224
+ self.cancelTimer?(); self.cancelTimer = nil
225
+ completion(.failure(Failure(message: "OTA write failed")))
226
+ }
227
+ } catch { completion(.failure(error)) }
228
+ }
229
+
230
+ private func nextPacket(_ command: UInt8, _ params: Data = Data()) throws -> Data {
231
+ sequence &+= 1
232
+ let packet = try NimoOtaProtocol.request(command, sequence: sequence, params: params)
233
+ guard packet.count <= capacity else { throw Failure(message: "OTA request exceeds the negotiated write capacity") }
234
+ return packet
235
+ }
236
+
237
+ private func delay(_ seconds: TimeInterval, _ callback: @escaping () throws -> Void) {
238
+ cancelDelay?()
239
+ cancelDelay = schedule(seconds) { [weak self] in
240
+ guard let self else { return }
241
+ self.cancelDelay = nil
242
+ guard !self.done else { return }
243
+ do { try callback() } catch { self.fail(error) }
244
+ }
245
+ }
246
+
247
+ private func clearTimers() {
248
+ cancelTimer?(); cancelTimer = nil
249
+ cancelDelay?(); cancelDelay = nil
250
+ pending = nil
251
+ decoder.reset()
252
+ }
253
+
254
+ private func fail(_ error: Error) {
255
+ guard !done else { return }
256
+ done = true
257
+ clearTimers()
258
+ finished(error.localizedDescription)
259
+ }
260
+ }