-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathAccessoryManager.swift
More file actions
1199 lines (1070 loc) · 50.4 KB
/
Copy pathAccessoryManager.swift
File metadata and controls
1199 lines (1070 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// AccessoryManager.swift
// Created by Jake Bordens on 7/10/25.
//
import Foundation
import SwiftUI
import SwiftData
import MeshtasticProtobufs
import CoreBluetooth
import OSLog
import CocoaMQTT
import Combine
enum AccessoryError: Error, LocalizedError {
case discoveryFailed(String)
case connectionFailed(String)
case versionMismatch(String)
case ioFailed(String)
case appError(String)
case timeout
case disconnected(String)
case tooManyRetries
case eventStreamCancelled
case coreBluetoothError(CBError)
case coreBluetoothATTError(CBATTError)
var errorDescription: String? {
switch self {
case .discoveryFailed(let message):
return "Discovery failed. \(message)"
case .connectionFailed(let message):
return "Connection failed. \(message)"
case .versionMismatch(let message):
return "Version mismatch: \(message)"
case .ioFailed(let message):
return "Communication failure: \(message)"
case .appError(let message):
return "Application error: \(message)"
case .timeout:
return "Connection Timeout"
case .disconnected(let message):
return "Disconnected: \(message)"
case .tooManyRetries:
return "Too Many Retries"
case .eventStreamCancelled:
return "Event stream cancelled"
case .coreBluetoothError(let cbError):
// Map specific CBError values to a more user-friendly message
switch cbError.code {
case .connectionTimeout: // 6
return "The Bluetooth connection to the radio unexpectedly disconnected, it will automatically reconnect to the preferred radio when it comes back in range or is powered back on.".localized
case .peripheralDisconnected: // 7
return "The Bluetooth connection to the radio was disconnected, it will automatically reconnect to the preferred radio when it is powered back on or finishes rebooting.".localized
case .peerRemovedPairingInformation: // 14
return "The radio has deleted its stored pairing information, but your device has not. To resolve this, you must forget the radio under Settings > Bluetooth to clear the old, now invalid, pairing information.".localized
default:
// Fallback for other CBError codes
return "A Bluetooth error occurred: \(cbError.localizedDescription)"
}
case .coreBluetoothATTError(let attError):
// Map specific CBATTError values to a more user-friendly message
switch attError.code {
case .insufficientAuthentication: // 5
return "Bluetooth \(attError.localizedDescription) Please try connecting again and check the BLE PIN carefully.".localized
case .insufficientEncryption: // 15
return "Bluetooth \(attError.localizedDescription) Please try connecting again and check the BLE PIN carefully.".localized
default:
// Fallback for other CBError codes
return "A Bluetooth Attribute Protocol error occurred: \(attError.localizedDescription)"
}
}
}
}
enum AccessoryManagerState: Equatable {
case uninitialized
case idle
case discovering
case connecting
case retrying(attempt: Int, maxAttempts: Int)
case retrievingDatabase(nodeCount: Int)
case communicating
case subscribed
var description: String {
switch self {
case .uninitialized:
return "Uninitialized"
case .idle:
return "Idle"
case .discovering:
return "Discovering"
case .connecting:
return "Connecting"
case .retrying(let attempt, let maxAttempts):
return "Retrying Connection (\(attempt) of \(maxAttempts))"
case .communicating:
return "Communicating"
case .subscribed:
return "Subscribed"
case .retrievingDatabase(let nodeCount):
return "Retreiving nodes \(nodeCount)"
}
}
}
@MainActor
class AccessoryManager: ObservableObject, MqttClientProxyManagerDelegate {
// Singleton Access. Conditionally compiled
#if targetEnvironment(macCatalyst)
static let shared = AccessoryManager(transports: [BLETransport(), TCPTransport(), SerialTransport()])
#else
static let shared = AccessoryManager(transports: [BLETransport(), TCPTransport()])
#endif
// Constants
let NONCE_ONLY_CONFIG = 69420
let NONCE_ONLY_DB = 69421
let minimumVersion = "2.5.18"
let securityVersion = "2.6.0"
// Global Objects
// Chicken/Egg problem. Set in the App object immediately after
// AppState and AccessoryManager are created
var appState: AppState!
lazy var context = PersistenceController.shared.context
let mqttManager = MqttClientProxyManager.shared
// MARK: - Database reset
/// Call after a full data clear (clear app data / device reset / node switch). Reopens the
/// SwiftData container fresh and repoints the MeshPackets actor and this manager's cached
/// `context` at it, so no long-lived context keeps stale objects that would trap
/// ("destroyed by ModelContext.reset") when a reconnect reuses freed SQLite rowids.
func repointToFreshContainer() {
PersistenceController.shared.recreateContainer()
MeshPackets.recreateShared()
context = PersistenceController.shared.context
}
/// `repointToFreshContainer()` plus a UI refresh: bumps `databaseResetID` so @Query-backed
/// views rebind to the recreated container. Use at clear sites with no follow-up reconnect;
/// the node-switch flow repoints first and refreshes the UI itself after its restore.
///
/// Pops every tab to its root and yields *before* recreating the container. Detail views such
/// as `ChannelMessageList` bind a `@Bindable ChannelEntity` directly; if one is still mounted
/// when the container is torn down, reading that now-invalid object traps with "This model
/// instance was destroyed by calling ModelContext.reset". Popping + yielding lets SwiftUI
/// unmount those views first. Mirrors the node-switch flow in `backupCurrentAndRestoreDatabase`
/// (Views/Connect/Connect.swift).
func resetDatabaseAfterClear() async {
// `appState` (and its `router`) are wired up at launch and are required for the safety
// guarantee here. Bail loudly rather than recreating the container without first popping the
// detail views: a half-done reset (container torn down, views still mounted) would
// reintroduce the exact ModelContext.reset crash this method exists to prevent. The data was
// already cleared by the preceding `clearDatabase`, so skipping the container swap is the
// safe degradation.
guard let appState else {
Logger.data.error("💾 [Database] resetDatabaseAfterClear skipped: appState is nil — cannot pop views before recreating the container")
return
}
let router = appState.router
router.popToRoot(tab: .messages)
router.popToRoot(tab: .nodes)
router.popToRoot(tab: .map)
router.popToRoot(tab: .settings)
await Task.yield()
repointToFreshContainer()
appState.databaseResetID = UUID()
}
// Published Stuff
@Published var mqttProxyConnected: Bool = false
@Published var devices: [Device] = []
@Published var state: AccessoryManagerState
@Published var mqttError: String = ""
@Published var activeDeviceNum: Int64?
@Published var allowDisconnect = false
@Published var lastConnectionError: Error?
@Published var isConnected: Bool = false
@Published var isConnecting: Bool = false
@Published var isInBackground: Bool = false
@Published var firmwareEdition: FirmwareEditions = .vanilla
/// MESHTASTIC_LOCKDOWN-hardened firmware state machine. See
/// Meshtastic/Helpers/LockdownCoordinator.swift and
/// specs/007-lockdown-mode/. Set by MeshtasticApp at startup.
var lockdownCoordinator: LockdownCoordinator?
/// Region → legal-preset lookup advertised by the connected radio during the
/// want_config handshake (FromRadio.region_presets, 2.8+). Empty when the
/// firmware predates the feature or hasn't sent it yet — callers must treat an
/// absent region (or an empty map) as "no constraint". Reset on disconnect.
@Published var loRaRegionPresets: [Config.LoRaConfig.RegionCode: RegionPresetInfo] = [:]
var activeConnection: (device: Device, connection: any Connection)?
/// Reference to the active discovery scan engine, if any
var discoveryScanEngine: DiscoveryScanEngine?
/// Shared discovery scan engine that persists across navigation
let discoveryEngine = DiscoveryScanEngine()
let transports: [any Transport]
// Config
public var wantRangeTestPackets = false
var wantStoreAndForwardPackets = false
var shouldAutomaticallyConnectToPreferredPeripheralAfterError = true
var userRequestedConnectionCancellation = false
/// True while a device switch (backup → clear → restore → connect) is in flight.
/// Suppresses the discovery restart in `closeConnection()` and auto-connect on
/// discovery events: the disconnect at the start of a switch must not let discovery
/// fire a concurrent connect whose node dump would interleave with the database
/// clear/restore (one source of nodes bleeding between radios). Set/cleared by
/// `switchToDevice` (Views/Connect/Connect.swift).
var isSwitchingDevices = false
// Conncetion process
var connectionSteps: SequentialSteps?
// Public due to file separation
var otaInProgress: Bool = false
var discoveryTask: Task<Void, Never>?
var connectionEventTask: Task <Void, Error>?
var locationTask: Task<Void, Error>?
var connectionStepper: SequentialSteps?
// Flash counters — NOT @Published to avoid triggering re-renders of all observing views.
// RXTXIndicatorWidget observes these via onChange polling.
var packetsSent: Int = 0
var packetsReceived: Int = 0
// Debug counter: MQTT client-proxy downlink packets dropped before forwarding
// to the device because they carried no payload (see MqttForwardFilter). NOT
// @Published — read only for debug logging, so it needn't drive view updates.
// Mutated on the main actor: CocoaMQTT delivers delegate callbacks on its
// default main delegateQueue, so onMqttMessageReceived runs on MainActor.
var mqttProxyDroppedNoPayload: Int = 0
// Continuations
var wantConfigContinuation: CheckedContinuation<Void, Error>?
var firstDatabaseNodeInfoContinuation: CheckedContinuation<Void, Error>?
var wantDatabaseGate: AsyncGate = AsyncGate()
// Misc
@Published var expectedNodeDBSize: Int?
var heartbeatTimer: ResettableTimer?
var heartbeatResponseTimer: ResettableTimer?
/// How long a TCP/serial connection may sit idle (no data or log packets) before we send a
/// keep-alive heartbeat. The timer is resettable, so an active link never sends one — heartbeats
/// only fire after this much silence. BLE does not use this at all (Core Bluetooth manages the
/// link); see `Transport.requiresPeriodicHeartbeat`.
static let heartbeatInterval: TimeInterval = 15.0
private var isClosingConnection = false
init(transports: [any Transport] = [BLETransport(), TCPTransport()]) {
self.transports = transports
self.state = .uninitialized
self.mqttManager.delegate = self
// Listen for system memory warnings to proactively save pending changes
if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil {
NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main) { [weak self] _ in
guard let self else { return }
try? self.context.save()
Logger.data.warning("⚠️ [AccessoryManager] Memory warning — saved context")
}
}
}
func transportForType(_ type: TransportType) -> Transport? {
return transports.first(where: {$0.type == type })
}
func connectToPreferredDevice(device: Device? = nil) {
if !self.isConnected && !self.isConnecting,
let preferredDevice = device ?? self.devices.first(where: { $0.id.uuidString == UserDefaults.preferredPeripheralId }) {
Task {
try await self.connect(to: preferredDevice)
}
}
}
func sendWantConfig() async throws {
if let inProgressWantConfigContinuation = wantConfigContinuation {
Logger.transport.info("[Accessory] Existing continuation for wantConfig(Config). Cancelling.")
wantConfigContinuation = nil
inProgressWantConfigContinuation.resume(throwing: CancellationError())
}
guard let connection = activeConnection?.connection else {
Logger.transport.error("Unable to send wantConfig (config): No device connected")
return
}
// Note: stale-node pruning used to run here, serializing a full fetch+delete+save on the
// ingestion actor ahead of the config handshake and node-DB dump (one cause of slow/hung
// connects). It now runs after the connection completes — see connect() Step 8 — where it
// also prunes against post-dump lastHeard values instead of pre-dump ones.
try await withTaskCancellationHandler {
var toRadio: ToRadio = ToRadio()
toRadio.wantConfigID = UInt32(NONCE_ONLY_CONFIG)
try await self.send(toRadio)
try await connection.startDrainPendingPackets()
try await withCheckedThrowingContinuation { cont in
self.wantConfigContinuation = cont
}
self.wantConfigContinuation = nil
Logger.transport.info("✅ [Accessory] NONCE_ONLY_CONFIG Done")
} onCancel: {
Task { @MainActor in
if let continuation = wantConfigContinuation {
wantConfigContinuation = nil
continuation.resume(throwing: CancellationError())
}
}
}
}
func sendWantDatabase() async throws {
if let firstDatabaseNodeInfoContinuation = firstDatabaseNodeInfoContinuation {
Logger.transport.info("[Accessory] Existing continuation for firstDatabaseNodeInfo. Cancelling.")
self.firstDatabaseNodeInfoContinuation = nil
firstDatabaseNodeInfoContinuation.resume(throwing: CancellationError())
}
guard let connection = activeConnection?.connection else {
Logger.transport.error("Unable to send wantConfig (Database): No device connected")
return
}
try await withTaskCancellationHandler {
var toRadio: ToRadio = ToRadio()
toRadio.wantConfigID = UInt32(NONCE_ONLY_DB)
try await self.send(toRadio)
try await connection.startDrainPendingPackets()
try await withCheckedThrowingContinuation { cont in
firstDatabaseNodeInfoContinuation = cont
}
firstDatabaseNodeInfoContinuation = nil
Logger.transport.info("✅ [Accessory] NONCE_ONLY_DB first NodeInfo received.")
} onCancel: {
Task { @MainActor in
if let continuation = firstDatabaseNodeInfoContinuation {
firstDatabaseNodeInfoContinuation = nil
continuation.resume(throwing: CancellationError())
}
}
}
}
func waitForWantDatabaseResponse() async throws {
try await wantDatabaseGate.wait()
}
// Fully tears down a connection and sets up the AccessoryManager for the next.
// If you are calling this in response to an error, then you should have
// exposed the error to the UI or handled the error prior to calling this.
func closeConnection() async throws {
guard !isClosingConnection else {
Logger.transport.debug("[AccessoryManager] closeConnection ignored while teardown is already in progress")
return
}
isClosingConnection = true
defer { isClosingConnection = false }
Logger.transport.debug("[AccessoryManager] received disconnect request")
if let activeConnection {
updateDevice(deviceId: activeConnection.device.id, key: \.connectionState, value: .disconnected)
self.activeConnection = nil
}
self.activeDeviceNum = nil
// Lockdown: clear per-connection state. If a Lock Now was in flight, the
// disconnect resolves the coordinator to `.lockNowAcknowledged`.
lockdownCoordinator?.onDisconnect()
connectionEventTask?.cancel()
connectionEventTask = nil
locationTask?.cancel()
locationTask = nil
await heartbeatTimer?.cancel(withReason: "Closing connection")
await heartbeatResponseTimer?.cancel(withReason: "Closing connection")
heartbeatTimer = nil
heartbeatResponseTimer = nil
// Clean up continuations — nil before resume to prevent double-resume races
if let continuation = wantConfigContinuation {
wantConfigContinuation = nil
continuation.resume(throwing: CancellationError())
}
if let continuation = firstDatabaseNodeInfoContinuation {
firstDatabaseNodeInfoContinuation = nil
continuation.resume(throwing: CancellationError())
}
await wantDatabaseGate.cancelAll()
await wantDatabaseGate.reset()
// Stop the MQTT proxy so it doesn't forward broker packets over BLE during reconnect,
// which would starve the wantConfig handshake. initializeMqtt() restarts it in Step 8.
// Disconnect unconditionally — mqttProxyConnected can be stale during a teardown race.
mqttManager.mqttClientProxy?.disconnect()
// Save any pending changes and let SwiftData manage object lifecycle on disconnect.
try? context.save()
Logger.data.info("💾 [AccessoryManager] Saved context on disconnect")
// Turn off the disconnect buttons
allowDisconnect = false
// Cancel any existing discovery task so startDiscovery() always creates a fresh one.
// Without this, if discovery was still running from before the connection attempt,
// startDiscovery() would silently no-op and the device would never reappear in the list.
discoveryTask?.cancel()
discoveryTask = nil
// During a device switch the teardown must NOT re-arm discovery: with autoconnect on,
// discovery can immediately re-connect (and start a node dump) while the switch is
// still clearing/restoring the database — interleaving one radio's dump with another
// radio's data. The switch flow restarts discovery itself if its connect fails.
if !isSwitchingDevices {
self.startDiscovery()
}
}
// Should only be called by UI-facing callers.
func disconnect() async throws {
guard !isClosingConnection else { return }
self.userRequestedConnectionCancellation = true
// Cancel ongoing connection task if it exists
await self.connectionStepper?.cancel()
// Flush any debounced position/telemetry saves before disconnecting
await MeshPackets.shared.flushDebouncedSaves()
// Close out the connection
if let activeConnection = activeConnection {
try await activeConnection.connection.disconnect(withError: nil, shouldReconnect: false)
}
}
// Update device attributes on MainActor for presentation in the UI
func updateDevice<T>(deviceId: UUID? = nil, key: WritableKeyPath<Device, T>, value: T) where T: Equatable {
guard let deviceId = deviceId ?? self.activeConnection?.device.id else {
Logger.transport.error("updateDevice<T> with nil deviceId")
return
}
// Update the active device if the UUID's match
if let activeConnection, activeConnection.device.id == deviceId {
var device = activeConnection.device
if device[keyPath: key] != value {
// Update the @Published stuff for the UI
self.objectWillChange.send()
device[keyPath: key] = value
self.activeConnection = (device: device, connection: activeConnection.connection)
}
// Make sure activeDeviceNum is up to date.
if key == \.num, self.activeDeviceNum != device.num {
self.activeDeviceNum = device.num
}
}
// Update the device in the devices array if it exists
if let index = devices.firstIndex(where: { $0.id == deviceId }) {
var device = devices[index]
device[keyPath: key] = value
if device[keyPath: key] != value {
// Update the @Published stuff for the UI
self.objectWillChange.send()
if let index = devices.firstIndex(where: { $0.id == deviceId }) {
devices[index] = device
}
}
} else {
// Durring active connections, this discover list will be empty, so this is expected.
// Logger.transport.error("Device with ID \(deviceId) not found in devices list.")
}
}
// Update state on MainActor for presentation in the UI
func updateState(_ newState: AccessoryManagerState) {
#if DEBUG
Logger.transport.info("🔗 Updating state from \(self.state.description, privacy: .public) to \(newState.description, privacy: .public)")
#endif
switch newState {
case .uninitialized, .idle, .discovering:
self.isConnected = false
self.isConnecting = false
self.firmwareEdition = .vanilla
self.loRaRegionPresets = [:]
case .connecting, .communicating, .retrying:
self.isConnected = false
self.isConnecting = true
case .subscribed, .retrievingDatabase:
self.isConnected = true
self.isConnecting = false
}
self.state = newState
}
func send(_ data: ToRadio, debugDescription: String? = nil) async throws {
packetsSent += 1
guard let active = activeConnection,
await active.connection.isConnected else {
throw AccessoryError.connectionFailed("Not connected to any device")
}
try await active.connection.send(applyingLicensedRemoteAdminPolicy(to: data, connectedDeviceNum: active.device.num))
if let debugDescription {
Logger.transport.info("📻 \(debugDescription, privacy: .public)")
}
}
/// Licensed-mode remote administration is authenticated by the firmware's verified packet
/// signature and must remain plaintext on air. Apply that invariant at the final send boundary
/// so both the shared Admin helper and older direct-send call sites receive the same treatment.
private func applyingLicensedRemoteAdminPolicy(to data: ToRadio, connectedDeviceNum: Int64?) -> ToRadio {
guard let connectedDeviceNum else { return data }
guard case let .packet(packet) = data.payloadVariant,
case let .decoded(decoded) = packet.payloadVariant,
decoded.portnum == .adminApp,
packet.to != Constants.maximumNodeNum,
packet.to != UInt32(truncatingIfNeeded: connectedDeviceNum)
else { return data }
let ownerNum = connectedDeviceNum
var descriptor = FetchDescriptor<UserEntity>(predicate: #Predicate { $0.num == ownerNum })
descriptor.fetchLimit = 1
guard let connectedOwner = try? context.fetch(descriptor).first,
connectedOwner.isLicensed
else { return data }
var plaintextPacket = packet
plaintextPacket.channel = 0
plaintextPacket.pkiEncrypted = false
plaintextPacket.publicKey = Data()
var result = data
result.packet = plaintextPacket
return result
}
func didReceive(_ event: ConnectionEvent) async {
let shouldIgnoreTransientEvent = isClosingConnection || userRequestedConnectionCancellation || activeConnection == nil
packetsReceived += 1
switch event {
case .data(let fromRadio):
guard !shouldIgnoreTransientEvent else {
Logger.transport.debug("[Accessory] Dropping data event during disconnect teardown")
return
}
// Logger.transport.info("✅ [Accessory] didReceive: \(fromRadio.payloadVariant.debugDescription)")
await self.processFromRadio(fromRadio)
Task {
await self.heartbeatResponseTimer?.cancel(withReason: "Data packet received")
await self.heartbeatTimer?.reset(delay: .seconds(Self.heartbeatInterval))
}
case .logMessage(let message):
guard !shouldIgnoreTransientEvent else {
Logger.transport.debug("[Accessory] Dropping log event during disconnect teardown")
return
}
self.didReceiveLog(message: message)
Task {
await self.heartbeatResponseTimer?.cancel(withReason: "Log message packet received")
await self.heartbeatTimer?.reset(delay: .seconds(Self.heartbeatInterval))
}
case .rssiUpdate(let rssi):
guard !shouldIgnoreTransientEvent else {
Logger.transport.debug("[Accessory] Dropping RSSI update during disconnect teardown")
return
}
guard let deviceId = self.activeConnection?.device.id else {
Logger.transport.error("Could not update RSSI, no active connection")
return
}
updateDevice(deviceId: deviceId, key: \.rssi, value: rssi)
case .error(let error), .errorWithoutReconnect(let error):
Task {
// Figure out if we'll reconnect
if case .errorWithoutReconnect = event {
shouldAutomaticallyConnectToPreferredPeripheralAfterError = false
} else {
shouldAutomaticallyConnectToPreferredPeripheralAfterError = true
}
Logger.transport.info("🚨 [Accessory] didReceive with failure: \(error.localizedDescription, privacy: .public) (willReconnect = \(self.shouldAutomaticallyConnectToPreferredPeripheralAfterError, privacy: .public))")
lastConnectionError = error
if let connectionStepper = self.connectionStepper {
// If we're in the midst of a connection process, tell the stepper that something happened
// This cancels retry connection attempts if we've been asked not to reconnect
await connectionStepper.cancelCurrentlyExecutingStep(withError: error, cancelFullProcess: !shouldAutomaticallyConnectToPreferredPeripheralAfterError)
} else {
// Normal processing. Expose the error and disconnect
try? await self.closeConnection()
// If we were actively reconnecting, then don't update the status because
// we're in the midst of a reconnection flow
if !(await self.connectionStepper?.isRunning ?? false) {
updateState(.discovering)
}
}
}
case .disconnected:
Task {
// This is user-initatied, so don't reconnect
shouldAutomaticallyConnectToPreferredPeripheralAfterError = false
try? await self.closeConnection()
updateState(.discovering)
}
Logger.transport.info("[Accessory] Connection reported user-initiated disconnect.")
}
}
func didReceiveLog(message: String) {
var log = message
/// Debug Log Level
if log.starts(with: "DEBUG |") {
do {
let logString = log
if let coordsMatch = try CommonRegex.COORDS_REGEX.firstMatch(in: logString) {
log = "\(log.replacingOccurrences(of: "DEBUG |", with: "").trimmingCharacters(in: .whitespaces))"
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.debug("🛰️ \(log.prefix(upTo: coordsMatch.range.lowerBound), privacy: .public) \(coordsMatch.0.replacingOccurrences(of: "[,]", with: "", options: .regularExpression), privacy: .private(mask: .none)) \(log.suffix(from: coordsMatch.range.upperBound), privacy: .public)")
} else {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.debug("🕵🏻♂️ \(log.replacingOccurrences(of: "DEBUG |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
}
} catch {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.debug("🕵🏻♂️ \(log.replacingOccurrences(of: "DEBUG |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
}
} else if log.starts(with: "INFO |") {
do {
let logString = log
if let coordsMatch = try CommonRegex.COORDS_REGEX.firstMatch(in: logString) {
log = "\(log.replacingOccurrences(of: "INFO |", with: "").trimmingCharacters(in: .whitespaces))"
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.info("🛰️ \(log.prefix(upTo: coordsMatch.range.lowerBound), privacy: .public) \(coordsMatch.0.replacingOccurrences(of: "[,]", with: "", options: .regularExpression), privacy: .private) \(log.suffix(from: coordsMatch.range.upperBound), privacy: .public)")
} else {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.info("📢 \(log.replacingOccurrences(of: "INFO |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
}
} catch {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.info("📢 \(log.replacingOccurrences(of: "INFO |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
}
} else if log.starts(with: "WARN |") {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.warning("⚠️ \(log.replacingOccurrences(of: "WARN |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
} else if log.starts(with: "ERROR |") {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.error("💥 \(log.replacingOccurrences(of: "ERROR |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
} else if log.starts(with: "CRIT |") {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.critical("🧨 \(log.replacingOccurrences(of: "CRIT |", with: "").trimmingCharacters(in: .whitespaces), privacy: .public)")
} else {
log = log.replacingOccurrences(of: "[,]", with: "", options: .regularExpression)
Logger.radio.debug("📟 \(log, privacy: .public)")
}
}
private func processFromRadio(_ decodedInfo: FromRadio) async {
// Logger.transport.info("📻 [processFromRadio] Processing: \(String(describing: decodedInfo.payloadVariant), privacy: .public)")
switch decodedInfo.payloadVariant {
case .mqttClientProxyMessage(let mqttClientProxyMessage):
handleMqttClientProxyMessage(mqttClientProxyMessage)
case .clientNotification(let clientNotification):
handleClientNotification(clientNotification)
case .myInfo(let myNodeInfo):
await handleMyInfo(myNodeInfo)
case .packet(let packet):
// All received packets get passed through updateAnyPacketFrom to update lastHeard, rxSnr, etc. (like firmware's NodeDB::updateFrom).
if let connectedNodeNum = self.activeDeviceNum {
await MeshPackets.shared.updateAnyPacketFrom(packet: packet, activeDeviceNum: connectedNodeNum)
} else {
Logger.mesh.error("🕸️ Unable to determine connectedNodeNum for updateAnyPacketFrom. Skipping.")
}
// Dispatch based on packet contents.
if case let .decoded(data) = packet.payloadVariant {
// Forward packets to discovery scan engine if active
if let engine = discoveryScanEngine, engine.isScanning {
engine.handleMeshPacket(packet, portNum: data.portnum)
}
switch data.portnum {
case .textMessageApp, .detectionSensorApp, .alertApp:
await handleTextMessageAppPacket(packet)
// Broadcast text message to TAK clients
if let text = String(bytes: data.payload, encoding: .utf8) {
Logger.tak.debug("Text message received, calling broadcast")
let server = TAKServerManager.shared
if server.ensureBridgeReadyForMeshToCot() {
await server.bridge?.broadcastMeshTextMessageToTAK(text: text, from: packet.from, channel: packet.channel, to: packet.to)
}
}
case .remoteHardwareApp:
Logger.mesh.info("[Remote Hardware] packet received from \(packet.from.toHex(), privacy: .public)")
case .positionApp:
await MeshPackets.shared.upsertPositionPacket(packet: packet)
WatchSessionManager.shared.sendNodesToWatch()
// Broadcast position to TAK clients
if let position = try? Position(serializedBytes: data.payload) {
Logger.tak.debug("Position received, calling broadcast")
let server = TAKServerManager.shared
if server.ensureBridgeReadyForMeshToCot() {
await server.bridge?.broadcastMeshPositionToTAK(position: position, from: packet.from)
}
}
case .waypointApp:
Logger.tak.info("WAYPOINT APP CASE REACHED")
await MeshPackets.shared.waypointPacket(packet: packet)
// Broadcast waypoint to TAK clients
if let waypoint = try? Waypoint(serializedBytes: data.payload) {
Logger.tak.info("WAYPOINT PARSED: \(waypoint.name)")
let server = TAKServerManager.shared
if server.ensureBridgeReadyForMeshToCot() {
await server.bridge?.broadcastMeshWaypointToTAK(waypoint: waypoint, from: packet.from)
} else {
Logger.tak.info("Waypoint broadcast skipped: server not ready or no clients")
}
}
case .nodeinfoApp:
guard let connectedNodeNum = self.activeDeviceNum else {
Logger.mesh.error("🕸️ Unable to determine connectedNodeNum for node info upsert.")
return
}
if packet.from != connectedNodeNum {
await MeshPackets.shared.upsertNodeInfoPacket(packet: packet)
} else {
Logger.mesh.error("🕸️ Received a node info packet from ourselves over the mesh. Dropping.")
}
case .routingApp:
guard let deviceNum = activeConnection?.device.num else {
Logger.mesh.error("🕸️ No active connection. Unable to determine connectedNodeNum for routingPacket.")
return
}
await MeshPackets.shared.routingPacket(packet: packet, connectedNodeNum: deviceNum)
case .adminApp:
await MeshPackets.shared.adminAppPacket(packet: packet)
case .replyApp:
Logger.mesh.info("[Reply] packet received from \(packet.from.toHex(), privacy: .public)")
guard let deviceNum = activeConnection?.device.num else {
Logger.mesh.error("🕸️ No active connection. Unable to determine connectedNodeNum for replyApp.")
return
}
await MeshPackets.shared.textMessageAppPacket(packet: packet, wantRangeTestPackets: wantRangeTestPackets, connectedNode: deviceNum, appState: appState)
case .ipTunnelApp:
Logger.mesh.info("[IP Tunnel] packet received from \(packet.from.toHex(), privacy: .public)")
case .serialApp:
Logger.mesh.info("[Serial] packet received from \(packet.from.toHex(), privacy: .public)")
case .storeForwardApp:
guard let deviceNum = activeConnection?.device.num else {
Logger.mesh.error("🕸️ No active connection. Unable to determine connectedNodeNum for storeAndForward.")
return
}
storeAndForwardPacket(packet: decodedInfo.packet, connectedNodeNum: deviceNum)
case .rangeTestApp:
guard let deviceNum = activeConnection?.device.num else {
Logger.mesh.error("🕸️ No active connection. Unable to determine connectedNodeNum for rangeTestApp.")
return
}
if wantRangeTestPackets {
await MeshPackets.shared.textMessageAppPacket(
packet: packet,
wantRangeTestPackets: true,
connectedNode: deviceNum,
appState: appState
)
} else {
Logger.mesh.info("[Range Test] packet received from \(packet.from.toHex(), privacy: .public)")
}
case .telemetryApp:
guard let deviceNum = activeConnection?.device.num else {
Logger.mesh.error("🕸️ No active connection. Unable to determine connectedNodeNum for telemetryApp.")
return
}
await MeshPackets.shared.telemetryPacket(packet: packet, connectedNode: deviceNum)
case .textMessageCompressedApp:
Logger.mesh.info("[Text Message Compressed] packet received from \(packet.from.toHex(), privacy: .public)")
case .zpsApp:
Logger.mesh.info("[Zero Positioning System] packet received from \(packet.from.toHex(), privacy: .public)")
case .privateApp:
Logger.mesh.info("[Private] packet received from \(packet.from.toHex(), privacy: .public)")
case .atakForwarder:
handleATAKForwarderPacket(packet)
case .simulatorApp:
Logger.mesh.info("[Simulator] packet received from \(packet.from.toHex(), privacy: .public)")
case .storeForwardPlusplusApp:
Logger.mesh.info("[SFPP] packet received from \(packet.from.toHex(), privacy: .public)")
case .audioApp:
Logger.mesh.info("[Audio] packet received from \(packet.from.toHex(), privacy: .public)")
case .nodeStatusApp:
await MeshPackets.shared.upsertNodeStatusPacket(packet: packet)
case .tracerouteApp:
handleTraceRouteApp(packet)
case .neighborinfoApp:
if let neighborInfo = try? NeighborInfo(serializedBytes: decodedInfo.packet.decoded.payload) {
if let engine = discoveryScanEngine, engine.isScanning {
engine.handleNeighborInfo(neighborInfo, packet: decodedInfo.packet)
} else {
Logger.mesh.info("[Neighbor Info] packet received from \(packet.from.toHex(), privacy: .public) — \(neighborInfo.neighbors.count, privacy: .public) neighbors")
}
}
case .paxcounterApp:
await MeshPackets.shared.paxCounterPacket(packet: decodedInfo.packet)
case .mapReportApp:
Logger.mesh.info("[Map Report] packet received from \(packet.from.toHex(), privacy: .public)")
case .meshBeaconApp:
if let beacon = try? MeshBeacon(serializedBytes: decodedInfo.packet.decoded.payload) {
if let engine = discoveryScanEngine, engine.isScanning {
engine.handleBeacon(beacon, packet: decodedInfo.packet)
} else {
// No active scan: passively capture the beacon as a session-less record so it
// shows in the Beacons list and feeds the next scan setup (FR-015). Two gates
// apply: "no active scan" here, plus the connected node's MeshBeaconConfig
// FLAG_LISTEN_ENABLED enforced inside ingestPassiveBeacon.
ingestPassiveBeacon(beacon, packet: decodedInfo.packet)
}
} else {
Logger.mesh.info("[Mesh Beacon] packet received from \(packet.from.toHex(), privacy: .public) — failed to decode payload")
}
case .UNRECOGNIZED:
Logger.mesh.info("[Unrecognized] packet received from \(packet.from.toHex(), privacy: .public)")
case .max:
Logger.services.info("MAX PORT NUM OF 511")
case .atakPlugin:
handleATAKPluginPacket(packet)
case .atakPluginV2:
handleATAKPluginV2Packet(packet)
case .powerstressApp:
Logger.mesh.info("[Power Stress] packet received from \(packet.from.toHex(), privacy: .public)")
case .reticulumTunnelApp:
Logger.mesh.info("[Reticulum Tunnel] packet received from \(packet.from.toHex(), privacy: .public)")
case .keyVerificationApp:
Logger.mesh.info("[Key Verification] packet received from \(packet.from.toHex(), privacy: .public)")
case .cayenneApp:
Logger.mesh.info("[Cayenne] packet received from \(packet.from.toHex(), privacy: .public)")
case .groupalarmApp:
Logger.mesh.info("[Group Alarm] packet received from \(packet.from.toHex(), privacy: .public)")
case .lorawanBridge:
Logger.mesh.info("[LoRaWAN Bridge] packet received from \(packet.from.toHex(), privacy: .public)")
case .remoteShellApp:
Logger.mesh.info("[Remote Shell] packet received from \(packet.from.toHex(), privacy: .public)")
case .unknownApp:
Logger.mesh.info("[Unknown] packet received from \(packet.from.toHex(), privacy: .public)")
}
}
// Flush via the debouncer rather than saving immediately. This runs for
// EVERY packet, so an immediate save here force-flushed the whole context
// on every packet — defeating the position/telemetry debounce and firing a
// main-context merge (and a full @Query re-sort) ~10×/sec under load. A
// debounced flush coalesces these to ≤1 save / 2s (5s hard ceiling) and also
// covers the updateAnyPacketFrom mutations for portnums with no dedicated handler.
await MeshPackets.shared.scheduleDebouncedSave()
case .nodeInfo(let nodeInfo):
await handleNodeInfo(nodeInfo)
case .channel(let channel):
await handleChannel(channel)
case .config(let config):
await handleConfig(config)
case .moduleConfig(let moduleConfig):
await handleModuleConfig(moduleConfig)
case .metadata(let metadata):
await handleDeviceMetadata(metadata)
case .regionPresets(let regionPresets):
handleRegionPresets(regionPresets)
case .deviceuiConfig:
#if DEBUG
Logger.admin.info("🕸️ MESH PACKET received for deviceUIConfig UNHANDLED \((try? decodedInfo.packet.jsonString()) ?? "JSON Decode Failure", privacy: .public)")
#endif
case .fileInfo:
#if DEBUG
Logger.admin.info("🕸️ MESH PACKET received for fileInfo UNHANDLED \((try? decodedInfo.packet.jsonString()) ?? "JSON Decode Failure", privacy: .public)")
#endif
case .queueStatus:
#if DEBUG
Logger.transport.info("🕸️ MESH PACKET received for queueStatus \((try? decodedInfo.packet.jsonString()) ?? "JSON Decode Failure", privacy: .public)")
#else
Logger.transport.info("🕸️ MESH PACKET received for heartbeat response")
#endif
case .logRecord(let record):
didReceiveLog(message: record.stringRepresentation)
case .configCompleteID(let configCompleteID):
// Not sure if we want to do anythign here directly? The continuation stuff lets you
// do the next step right in the connection flow.
// switch configCompleteID {
// case UInt32(NONCE_ONLY_CONFIG):
// break;
// case UInt32(NONCE_ONLY_DB):
// case UInt32(NONCE_ONLY_DB):
// break;
// break:
// Logger.mesh.error("✅ [Accessory] Unknown UNHANDLED confligCompleteID: \(configCompleteID)")
// }
Logger.transport.info("✅ [Accessory] Notifying completions that have completed for configCompleteID: \(configCompleteID)")
switch configCompleteID {
case UInt32(NONCE_ONLY_CONFIG):
if let continuation = wantConfigContinuation {
wantConfigContinuation = nil
continuation.resume()
}
case UInt32(NONCE_ONLY_DB):
// Open the gate for the wantDatabaseContinuation
Task { await wantDatabaseGate.open() }
// If we get the "done" for NONCE_ONLY_DB, but are still waiting for the first NodeInfo,
// Then the database is probably empty, and can continue
if let firstDatabaseNodeInfoContinuation {
self.firstDatabaseNodeInfoContinuation = nil
firstDatabaseNodeInfoContinuation.resume()
}
// Perform a single batch save after database retrieval completes
// This significantly improves performance on reconnect
Task {
// The dump was ingested with deferred saves on the MeshPackets actor
// (see handleNodeInfo); flush it so every node from the dump is persisted
// now rather than waiting on the debounce timer.
await MeshPackets.shared.flushDebouncedSaves()
do {
try context.save()
Logger.data.info("💾 [Database] Batch saved all node info after database retrieval")
// Push updated node data to the companion Watch app
WatchSessionManager.shared.sendNodesToWatch()
} catch {
let nsError = error as NSError
Logger.data.error("💥 [Database] Error saving batch node info: \(nsError, privacy: .public)")
}
}
default:
Logger.transport.error("[Accessory] Unknown nonce completed: \(configCompleteID)")
}
case .rebooted:
// If we had an existing connection, then we can probably get away with just a wantConfig?
if state == .subscribed {
Task { try? await sendWantConfig() }
}
case .lockdownStatus(let status):
// MESHTASTIC_LOCKDOWN-hardened firmware reports state after config_complete_id
// (and again in response to each LockdownAuth admin command). Route to the
// coordinator, which owns the per-connection state machine + passphrase cache.
lockdownCoordinator?.handle(status)
default:
Logger.transport.error("Unknown FromRadio variant: \(decodedInfo.payloadVariant.debugDescription)")
}
}
}
extension AccessoryManager {
var connectedVersion: String? {
return activeConnection?.device.firmwareVersion
}
var connectedDeviceRole: DeviceRoles? {
guard let connectedNodeNum = activeDeviceNum else { return nil }
guard let connectedNode = getNodeInfo(id: connectedNodeNum, context: context) else { return nil }
guard let connectedNodeUser = connectedNode.user else { return nil }