-
-
Notifications
You must be signed in to change notification settings - Fork 270
Expand file tree
/
Copy pathMeshPackets.swift
More file actions
1565 lines (1466 loc) · 77.6 KB
/
Copy pathMeshPackets.swift
File metadata and controls
1565 lines (1466 loc) · 77.6 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
//
// MeshPackets.swift
// Meshtastic Apple
//
// Created by Garth Vander Houwen on 5/27/22.
//
import Foundation
@preconcurrency import SwiftData
import MeshtasticProtobufs
import SwiftUI
import RegexBuilder
import OSLog
#if canImport(ActivityKit)
import ActivityKit
#endif
// Simple extension to concisely pass values through a has_XXX boolean check
fileprivate extension Bool {
func then<T>(_ value: T) -> T? {
self ? value : nil
}
}
func generateMessageMarkdown(message: String) -> String {
guard !message.isEmoji() else { return message }
let types: NSTextCheckingResult.CheckingType = [.address, .link, .phoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else {
return message
}
let matches = detector.matches(in: message, options: [], range: NSRange(location: 0, length: message.utf16.count))
guard !matches.isEmpty else { return message }
// Find all existing markdown link ranges [text](url) so we can skip URLs inside them
let linkPattern = try? NSRegularExpression(pattern: "\\[[^\\]]+\\]\\([^)]+\\)")
let existingLinkRanges: [NSRange] = linkPattern?.matches(in: message, range: NSRange(location: 0, length: message.utf16.count)).map { $0.range } ?? []
var messageWithMarkdown = message
// Process matches in reverse order so earlier ranges stay valid
// after inserting markdown syntax at later positions.
for match in matches.reversed() {
guard let range = Range(match.range, in: messageWithMarkdown) else { continue }
let matchedText = String(messageWithMarkdown[range])
// Skip if this match overlaps with an existing markdown link
let matchNSRange = match.range
let isInsideExistingLink = existingLinkRanges.contains { linkRange in
NSIntersectionRange(linkRange, matchNSRange).length > 0
}
if isInsideExistingLink { continue }
let replacement: String
if match.resultType == .address {
let urlEncodedAddress = matchedText.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
replacement = "[\(matchedText)](http://maps.apple.com/?address=\(urlEncodedAddress))"
} else if match.resultType == .phoneNumber {
replacement = "[\(matchedText)](tel:\(matchedText))"
} else if match.resultType == .link {
let absoluteUrl = match.url?.absoluteString ?? ""
replacement = "[\(matchedText)](\(absoluteUrl))"
} else {
continue
}
messageWithMarkdown.replaceSubrange(range, with: replacement)
}
return messageWithMarkdown
}
@ModelActor
actor MeshPackets {
private struct TelemetryPruneKey: Hashable {
let nodeNum: Int64
let metricsType: Int32
}
/// Always the current shared container. Computed (not cached) so that after a data clear
/// recreates the container, the next `recreateShared()` rebuilds the actor on the new one
/// rather than a stale, torn-down container. Only read on the main actor (recreateShared and
/// the initial `_shared` are both reached from @MainActor code).
private static var _container: ModelContainer {
MainActor.assumeIsolated { PersistenceController.shared.container }
}
/// The current shared instance. Access via `MeshPackets.shared`.
/// Periodically recreated to release accumulated ModelContext memory.
nonisolated(unsafe) private static var _shared: MeshPackets = MeshPackets(modelContainer: _container)
private static let _lock = NSLock()
static var shared: MeshPackets {
_lock.lock()
defer { _lock.unlock() }
return _shared
}
/// Discards the current actor and creates a fresh one with a new ModelContext.
/// Call after DB retrieval completes or periodically to release accumulated memory.
static func recreateShared() {
_lock.lock()
let previous = _shared
_shared = MeshPackets(modelContainer: _container)
_lock.unlock()
// Invalidate the retired instance. In-flight tasks that captured `MeshPackets.shared`
// before the swap (a debounced save, a late packet for the previous radio) still hold
// the old actor, whose context is bound to the old container — which points at the SAME
// on-disk store as the new one. Letting those writes land after a device-switch
// clearDatabase resurrects the previous radio's rows (nodes bleeding across devices)
// and can trip reused-rowid "destroyed by ModelContext.reset" traps.
Task { await previous.invalidate() }
Logger.data.info("♻️ [MeshPackets] Recreated shared instance to release ModelContext memory")
}
// MARK: - Save Helpers
/// Set when this instance has been replaced by `recreateShared()`. A retired instance must
/// never persist again — see `recreateShared()`.
private var invalidated = false
func invalidate() {
invalidated = true
debounceSaveTask?.cancel()
debounceSaveTask = nil
}
/// Saves any pending changes in the model context. Call once at the end of each
/// top-level packet handler to batch all mutations from a single packet into one write.
func savePendingChanges(caller: String = #function) {
guard !invalidated else {
Logger.data.warning("💾 [\(caller, privacy: .public)] Dropped save on retired MeshPackets instance")
return
}
guard modelContext.hasChanges else { return }
do {
try modelContext.save()
Logger.data.debug("💾 [\(caller, privacy: .public)] Saved pending changes")
} catch {
Logger.data.error("💥 [\(caller, privacy: .public)] Error saving: \(error.localizedDescription, privacy: .public)")
}
}
// MARK: - Debounced Save for High-Frequency Packets
/// Timer task for debounced saves (position/telemetry).
private var debounceSaveTask: Task<Void, Never>?
/// Tracks when we last flushed debounced changes to enforce a maximum delay.
private var lastDebouncedSaveTime: ContinuousClock.Instant = .now
/// How long to wait after the last mutation before flushing.
private static let debounceInterval: Duration = .seconds(2)
/// Maximum wall-clock time between flushes, even if packets keep arriving.
private static let maxDebounceDelay: Duration = .seconds(5)
static let maxPositionHistoryPerNode = 5_000
static let maxTelemetryPerType = 5_000
static let maxTotalMessages = 50_000
private static let positionPruneInterval = 128
private static let telemetryPruneInterval = 128
private static let messagePruneInterval = 256
private var positionInsertsSincePrune: [Int64: Int] = [:]
private var telemetryInsertsSincePrune: [TelemetryPruneKey: Int] = [:]
private var messageInsertsSincePrune = 0
/// Schedules a debounced save. Each call resets the 2-second timer. If packets
/// keep arriving continuously, a save is forced every 5 seconds.
/// Use for high-frequency packet types (position, telemetry) instead of `savePendingChanges`.
func scheduleDebouncedSave() {
guard !invalidated else { return }
debounceSaveTask?.cancel()
let elapsed = ContinuousClock.now - lastDebouncedSaveTime
if elapsed >= Self.maxDebounceDelay {
savePendingChanges(caller: "debouncedFlush-maxDelay")
lastDebouncedSaveTime = .now
return
}
debounceSaveTask = Task {
try? await Task.sleep(for: Self.debounceInterval)
guard !Task.isCancelled else { return }
self.savePendingChanges(caller: "debouncedFlush")
self.lastDebouncedSaveTime = .now
}
}
/// Immediately flushes any debounced saves. Call on disconnect or when entering background.
func flushDebouncedSaves() {
debounceSaveTask?.cancel()
debounceSaveTask = nil
savePendingChanges(caller: "flushDebouncedSaves")
lastDebouncedSaveTime = .now
}
/// Last time the channel-unread badge count was recomputed (an O(unread) scan).
private var lastChannelUnreadRecompute: ContinuousClock.Instant?
/// Rate-limits the per-message channel-unread recompute to at most ~1/sec so a burst
/// of incoming channel messages doesn't turn the badge update into quadratic work.
func shouldRecomputeChannelUnread() -> Bool {
let now = ContinuousClock.now
if let last = lastChannelUnreadRecompute, now - last < .seconds(1) { return false }
lastChannelUnreadRecompute = now
return true
}
func shouldPrunePositionHistory(for nodeNum: Int64) -> Bool {
let nextCount = (positionInsertsSincePrune[nodeNum] ?? 0) + 1
if nextCount >= Self.positionPruneInterval {
positionInsertsSincePrune[nodeNum] = 0
return true
}
positionInsertsSincePrune[nodeNum] = nextCount
return false
}
func shouldPruneTelemetryHistory(nodeNum: Int64, metricsType: Int32) -> Bool {
let key = TelemetryPruneKey(nodeNum: nodeNum, metricsType: metricsType)
let nextCount = (telemetryInsertsSincePrune[key] ?? 0) + 1
if nextCount >= Self.telemetryPruneInterval {
telemetryInsertsSincePrune[key] = 0
return true
}
telemetryInsertsSincePrune[key] = nextCount
return false
}
func shouldPruneMessageHistory() -> Bool {
messageInsertsSincePrune += 1
if messageInsertsSincePrune >= Self.messagePruneInterval {
messageInsertsSincePrune = 0
return true
}
return false
}
func localConfig (config: Config, nodeNum: Int64, nodeLongName: String) {
switch config.payloadVariant {
case .bluetooth:
upsertBluetoothConfigPacket(config: config.bluetooth, nodeNum: nodeNum)
case .device:
upsertDeviceConfigPacket(config: config.device, nodeNum: nodeNum)
case .display:
upsertDisplayConfigPacket(config: config.display, nodeNum: nodeNum)
case .lora:
upsertLoRaConfigPacket(config: config.lora, nodeNum: nodeNum)
case .network:
upsertNetworkConfigPacket(config: config.network, nodeNum: nodeNum)
case .position:
upsertPositionConfigPacket(config: config.position, nodeNum: nodeNum)
case .power:
upsertPowerConfigPacket(config: config.power, nodeNum: nodeNum)
case .security:
upsertSecurityConfigPacket(config: config.security, nodeNum: nodeNum)
default:
#if DEBUG
Logger.services.error("⁉️ Unknown Config variant UNHANDLED \(config.payloadVariant.debugDescription, privacy: .public)")
#endif
}
}
func moduleConfig (config: ModuleConfig, nodeNum: Int64, nodeLongName: String) {
switch config.payloadVariant {
case .ambientLighting:
upsertAmbientLightingModuleConfigPacket(config: config.ambientLighting, nodeNum: nodeNum)
case .audio:
upsertAudioModuleConfigPacket(config: config.audio, nodeNum: nodeNum)
case .cannedMessage:
upsertCannedMessagesModuleConfigPacket(config: config.cannedMessage, nodeNum: nodeNum)
case .detectionSensor:
upsertDetectionSensorModuleConfigPacket(config: config.detectionSensor, nodeNum: nodeNum)
case .externalNotification:
upsertExternalNotificationModuleConfigPacket(config: config.externalNotification, nodeNum: nodeNum)
case .mqtt:
upsertMqttModuleConfigPacket(config: config.mqtt, nodeNum: nodeNum)
case .neighborInfo:
upsertNeighborInfoModuleConfigPacket(config: config.neighborInfo, nodeNum: nodeNum)
case .paxcounter:
upsertPaxCounterModuleConfigPacket(config: config.paxcounter, nodeNum: nodeNum)
case .rangeTest:
upsertRangeTestModuleConfigPacket(config: config.rangeTest, nodeNum: nodeNum)
case .serial:
upsertSerialModuleConfigPacket(config: config.serial, nodeNum: nodeNum)
case .telemetry:
upsertTelemetryModuleConfigPacket(config: config.telemetry, nodeNum: nodeNum)
case .storeForward:
upsertStoreForwardModuleConfigPacket(config: config.storeForward, nodeNum: nodeNum)
case .statusmessage:
upsertStatusMessageModuleConfigPacket(config: config.statusmessage, nodeNum: nodeNum)
case .tak:
upsertTAKModuleConfigPacket(config: config.tak, nodeNum: nodeNum)
case .trafficManagement:
upsertTrafficManagementModuleConfigPacket(config: config.trafficManagement, nodeNum: nodeNum)
default:
#if DEBUG
Logger.services.error("⁉️ Unknown Module Config variant UNHANDLED \(config.payloadVariant.debugDescription, privacy: .public)")
#endif
}
}
func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String) -> PersistentIdentifier? {
let logString = String.localizedStringWithFormat("MyInfo received: %@".localized, String(myInfo.myNodeNum))
Logger.admin.info("ℹ️ \(logString, privacy: .public)")
let myNodeNum = Int64(myInfo.myNodeNum)
let fetchDescriptor = FetchDescriptor<MyInfoEntity>(predicate: #Predicate { $0.myNodeNum == myNodeNum })
do {
let fetchedMyInfo = try modelContext.fetch(fetchDescriptor)
// Not Found Insert
if fetchedMyInfo.isEmpty {
let myInfoEntity = MyInfoEntity()
modelContext.insert(myInfoEntity)
myInfoEntity.peripheralId = peripheralId
myInfoEntity.myNodeNum = Int64(myInfo.myNodeNum)
myInfoEntity.rebootCount = Int32(myInfo.rebootCount)
myInfoEntity.deviceId = myInfo.deviceID
if !myInfo.pioEnv.isEmpty {
myInfoEntity.pioEnv = myInfo.pioEnv
}
Logger.data.info("💾 Saved a new myInfo for node: \(myInfo.myNodeNum.toHex(), privacy: .public)")
savePendingChanges()
return myInfoEntity.persistentModelID
} else {
fetchedMyInfo[0].peripheralId = peripheralId
fetchedMyInfo[0].myNodeNum = Int64(myInfo.myNodeNum)
fetchedMyInfo[0].rebootCount = Int32(myInfo.rebootCount)
if !myInfo.pioEnv.isEmpty {
fetchedMyInfo[0].pioEnv = myInfo.pioEnv
}
Logger.data.info("💾 Updated myInfo for node: \(myInfo.myNodeNum.toHex(), privacy: .public)")
savePendingChanges()
return fetchedMyInfo[0].persistentModelID
}
} catch {
Logger.data.error("💥 Fetch MyInfo Error")
}
return nil
}
func channelPacket (channel: Channel, fromNum: Int64) {
if channel.isInitialized && channel.hasSettings && channel.role != Channel.Role.disabled {
let logString = String.localizedStringWithFormat("Channel received: %d %@".localized, channel.index, String(fromNum))
Logger.admin.info("🎛️ \(logString, privacy: .public)")
let fetchDescriptor = FetchDescriptor<MyInfoEntity>(predicate: #Predicate { $0.myNodeNum == fromNum })
do {
let fetchedMyInfo = try modelContext.fetch(fetchDescriptor)
if fetchedMyInfo.count == 1 {
let existing = fetchedMyInfo[0].channels.first(where: { $0.index == Int32(channel.index) })
let newChannel: ChannelEntity
if let existing {
newChannel = existing
} else {
newChannel = ChannelEntity()
modelContext.insert(newChannel)
fetchedMyInfo[0].channels.append(newChannel)
}
newChannel.id = Int32(channel.index)
newChannel.index = Int32(channel.index)
newChannel.uplinkEnabled = channel.settings.uplinkEnabled
newChannel.downlinkEnabled = channel.settings.downlinkEnabled
newChannel.name = channel.settings.name
newChannel.role = Int32(channel.role.rawValue)
newChannel.psk = channel.settings.psk
if channel.settings.hasModuleSettings {
newChannel.positionPrecision = Int32(truncatingIfNeeded: channel.settings.moduleSettings.positionPrecision)
newChannel.mute = channel.settings.moduleSettings.isMuted
} else {
// When moduleSettings is absent, use proto3 defaults (0/false)
// rather than the entity default of 32, which would incorrectly
// enable full-precision position sharing.
newChannel.positionPrecision = 0
newChannel.mute = false
}
savePendingChanges()
Logger.data.info("💾 Updated MyInfo channel \(channel.index, privacy: .public) from Channel App Packet For: \(fetchedMyInfo[0].myNodeNum, privacy: .public)")
} else if channel.role.rawValue > 0 {
Logger.data.error("💥Trying to save a channel to a MyInfo that does not exist: \(fromNum.toHex(), privacy: .public)")
}
} catch {
let nsError = error as NSError
Logger.data.error("💥 Error Saving MyInfo Channel from ADMIN_APP \(nsError, privacy: .public)")
}
}
}
func deviceMetadataPacket (metadata: DeviceMetadata, fromNum: Int64, sessionPasskey: Data? = Data()) {
if metadata.isInitialized {
let logString = String.localizedStringWithFormat("Device Metadata received from: %@".localized, fromNum.toHex())
Logger.admin.info("🏷️ \(logString, privacy: .public)")
let fetchDescriptor = FetchDescriptor<NodeInfoEntity>(predicate: #Predicate { $0.num == fromNum })
do {
let fetchedNode = try modelContext.fetch(fetchDescriptor)
let newMetadata = DeviceMetadataEntity()
modelContext.insert(newMetadata)
newMetadata.time = Date()
newMetadata.deviceStateVersion = Int32(metadata.deviceStateVersion)
newMetadata.canShutdown = metadata.canShutdown
newMetadata.hasWifi = metadata.hasWifi_p
newMetadata.hasBluetooth = metadata.hasBluetooth_p
newMetadata.hasEthernet = metadata.hasEthernet_p
newMetadata.role = Int32(metadata.role.rawValue)
newMetadata.positionFlags = Int32(truncatingIfNeeded: metadata.positionFlags)
newMetadata.excludedModules = Int32(truncatingIfNeeded: metadata.excludedModules)
// Swift does strings weird, this does work to get the version without the github hash
let lastDotIndex = metadata.firmwareVersion.lastIndex(of: ".")
var version = metadata.firmwareVersion[...(lastDotIndex ?? String.Index(utf16Offset: 6, in: metadata.firmwareVersion))]
version = version.dropLast()
newMetadata.firmwareVersion = String(version)
if fetchedNode.count > 0 {
fetchedNode[0].metadata = newMetadata
if sessionPasskey?.count != 0 {
fetchedNode[0].sessionPasskey = sessionPasskey
fetchedNode[0].sessionExpiration = Date().addingTimeInterval(300)
}
} else {
if fromNum > 0 {
let newNode = findOrCreateNode(num: Int64(fromNum), context: modelContext)
newNode.metadata = newMetadata
}
}
savePendingChanges()
Logger.data.info("💾 Updated Device Metadata from Admin App Packet For: \(fromNum.toHex(), privacy: .public)")
} catch {
let nsError = error as NSError
Logger.data.error("Error Saving MyInfo Channel from ADMIN_APP \(nsError, privacy: .public)")
}
}
}
func nodeInfoPacket (nodeInfo: NodeInfo, channel: UInt32, deferSave: Bool = false) -> PersistentIdentifier? {
// This path handles the connected device's local node-DB dump during wantConfig
// (FromRadio.nodeInfo), not packets that crossed the mesh — log it as admin/setup.
// Over-the-air NodeInfo arrives via upsertNodeInfoPacket and stays on .mesh.
let logString = String.localizedStringWithFormat("📟 [NodeInfo] received for: %@".localized, String(nodeInfo.num))
Logger.admin.info("📟 \(logString, privacy: .public)")
guard nodeInfo.num > 0 else { return nil }
let nodeNum = Int64(nodeInfo.num)
let fetchDescriptor = FetchDescriptor<NodeInfoEntity>(predicate: #Predicate { $0.num == nodeNum })
do {
let fetchedNode = try modelContext.fetch(fetchDescriptor)
// Not Found Insert
if fetchedNode.isEmpty && nodeInfo.num > 0 {
let newNode = NodeInfoEntity()
modelContext.insert(newNode)
newNode.id = Int64(nodeInfo.num)
newNode.num = Int64(nodeInfo.num)
newNode.channel = Int32(nodeInfo.channel)
newNode.favorite = nodeInfo.isFavorite
newNode.ignored = nodeInfo.isIgnored
newNode.hopsAway = Int32(nodeInfo.hopsAway)
newNode.hasXeddsaSigned = nodeInfo.hasXeddsaSigned_p
if nodeInfo.hasDeviceMetrics {
let telemetry = TelemetryEntity()
modelContext.insert(telemetry)
telemetry.batteryLevel = Int32(truncatingIfNeeded: nodeInfo.deviceMetrics.batteryLevel)
telemetry.voltage = nodeInfo.deviceMetrics.voltage
telemetry.channelUtilization = nodeInfo.deviceMetrics.channelUtilization
telemetry.airUtilTx = nodeInfo.deviceMetrics.airUtilTx
telemetry.nodeTelemetry = newNode
}
if nodeInfo.lastHeard > 0 {
newNode.firstHeard = Date(timeIntervalSince1970: TimeInterval(Int64(nodeInfo.lastHeard)))
newNode.lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(nodeInfo.lastHeard)))
} else {
newNode.firstHeard = Date()
newNode.lastHeard = Date()
}
newNode.snr = nodeInfo.snr
if nodeInfo.hasUser {
let newUser = UserEntity()
modelContext.insert(newUser)
newUser.userId = nodeInfo.num.toHex()
newUser.num = Int64(nodeInfo.num)
newUser.longName = nodeInfo.user.longName
newUser.shortName = nodeInfo.user.shortName
newUser.hwModel = String(describing: nodeInfo.user.hwModel).uppercased()
newUser.hwModelId = Int32(nodeInfo.user.hwModel.rawValue)
let hwModelValue = Int64(newUser.hwModelId)
let hwDescriptor = FetchDescriptor<DeviceHardwareEntity>(
predicate: #Predicate { $0.hwModel == hwModelValue }
)
if let hardwareEntity = try? modelContext.fetch(hwDescriptor).first {
newUser.hwDisplayName = hardwareEntity.displayName
}
newUser.isLicensed = nodeInfo.user.isLicensed
newUser.role = Int32(nodeInfo.user.role.rawValue)
if !nodeInfo.user.publicKey.isEmpty {
newUser.pkiEncrypted = true
newUser.publicKey = nodeInfo.user.publicKey
}
/// For nodes that have the optional isUnmessagable boolean use that, otherwise excluded roles that are unmessagable by default
if nodeInfo.user.hasIsUnmessagable {
newUser.unmessagable = nodeInfo.user.isUnmessagable
} else {
let roles = [2, 4, 5, 6, 7, 10, 11]
let containsRole = roles.contains(Int(newUser.role))
if containsRole {
newUser.unmessagable = true
} else {
newUser.unmessagable = false
}}
newNode.user = newUser
} else if nodeInfo.num > Constants.minimumNodeNum {
do {
let newUser = try createUser(num: Int64(nodeInfo.num), context: modelContext)
newNode.user = newUser
} catch PersistenceError.invalidInput(let message) {
Logger.data.error("Error Creating a new UserEntity (Invalid Input) from node number: \(nodeInfo.num, privacy: .public) Error: \(message, privacy: .public)")
} catch {
Logger.data.error("Error Creating a new UserEntity from node number: \(nodeInfo.num, privacy: .public) Error: \(error.localizedDescription, privacy: .public)")
}
}
if nodeInfo.position.hasValidCoordinates {
let position = PositionEntity()
modelContext.insert(position)
position.latest = true
position.seqNo = Int32(nodeInfo.position.seqNumber)
position.latitudeI = nodeInfo.position.latitudeI
position.longitudeI = nodeInfo.position.longitudeI
position.altitude = nodeInfo.position.altitude
position.satsInView = Int32(nodeInfo.position.satsInView)
position.speed = Int32(nodeInfo.position.groundSpeed)
position.heading = Int32(nodeInfo.position.groundTrack)
position.time = Date(timeIntervalSince1970: TimeInterval(Int64(nodeInfo.position.time)))
position.nodePosition = newNode
newNode.latestPositionCache = position
}
// Look for a MyInfo
let myInfoNodeNum = Int64(nodeInfo.num)
let fetchMyInfoDescriptor = FetchDescriptor<MyInfoEntity>(predicate: #Predicate { $0.myNodeNum == myInfoNodeNum })
do {
let fetchedMyInfo = try modelContext.fetch(fetchMyInfoDescriptor)
if fetchedMyInfo.count > 0 {
newNode.myInfo = fetchedMyInfo[0]
}
if !deferSave {
savePendingChanges()
Logger.data.debug("💾 Saved a new Node Info For: \(String(nodeInfo.num), privacy: .public)")
} else {
// Deferred (node-DB dump): batch writes, but still persist at least
// every maxDebounceDelay so a long dump isn't one giant save.
scheduleDebouncedSave()
}
return newNode.persistentModelID
} catch {
Logger.data.error("Fetch MyInfo Error")
}
} else if nodeInfo.num > 0 {
fetchedNode[0].id = Int64(nodeInfo.num)
fetchedNode[0].num = Int64(nodeInfo.num)
if nodeInfo.lastHeard > 0 {
let candidate = Date(timeIntervalSince1970: TimeInterval(nodeInfo.lastHeard))
if fetchedNode[0].lastHeard == nil || candidate > fetchedNode[0].lastHeard! {
fetchedNode[0].lastHeard = candidate
}
}
fetchedNode[0].snr = nodeInfo.snr
fetchedNode[0].channel = Int32(nodeInfo.channel)
fetchedNode[0].favorite = nodeInfo.isFavorite
fetchedNode[0].ignored = nodeInfo.isIgnored
fetchedNode[0].hopsAway = Int32(nodeInfo.hopsAway)
// has_xeddsa_signed means the node has signed ≥1 verified broadcast and persists; latch it
// so a later NodeInfo that omits the bit doesn't downgrade a node we've seen sign.
fetchedNode[0].hasXeddsaSigned = fetchedNode[0].hasXeddsaSigned || nodeInfo.hasXeddsaSigned_p
if nodeInfo.hasUser {
if fetchedNode[0].user == nil {
let newUserEntity = UserEntity()
modelContext.insert(newUserEntity)
fetchedNode[0].user = newUserEntity
}
// Set the public key for a user if it is empty, don't update
if fetchedNode[0].user?.publicKey == nil && !nodeInfo.user.publicKey.isEmpty {
fetchedNode[0].user?.pkiEncrypted = true
fetchedNode[0].user?.publicKey = nodeInfo.user.publicKey
}
fetchedNode[0].user?.userId = nodeInfo.num.toHex()
fetchedNode[0].user?.num = Int64(nodeInfo.num)
fetchedNode[0].user?.numString = String(nodeInfo.num)
fetchedNode[0].user?.longName = nodeInfo.user.longName
fetchedNode[0].user?.shortName = nodeInfo.user.shortName
fetchedNode[0].user?.isLicensed = nodeInfo.user.isLicensed
fetchedNode[0].user?.role = Int32(nodeInfo.user.role.rawValue)
fetchedNode[0].user?.hwModel = String(describing: nodeInfo.user.hwModel).uppercased()
fetchedNode[0].user?.hwModelId = Int32(nodeInfo.user.hwModel.rawValue)
/// For nodes that have the optional isUnmessagable boolean use that, otherwise excluded roles that are unmessagable by default
if nodeInfo.user.hasIsUnmessagable {
fetchedNode[0].user?.unmessagable = nodeInfo.user.isUnmessagable
} else {
let roles = [-1, 2, 4, 5, 6, 7, 10, 11]
let containsRole = roles.contains(Int(fetchedNode[0].user?.role ?? -1))
if containsRole {
fetchedNode[0].user?.unmessagable = true
} else {
fetchedNode[0].user?.unmessagable = false
}
}
if let user = fetchedNode.first?.user {
let hwModelValue2 = Int64(user.hwModelId)
let hwDescriptor2 = FetchDescriptor<DeviceHardwareEntity>(
predicate: #Predicate { $0.hwModel == hwModelValue2 }
)
if let hardwareEntity = try? modelContext.fetch(hwDescriptor2).first {
user.hwDisplayName = hardwareEntity.displayName
}
}
} else {
if fetchedNode[0].user == nil && nodeInfo.num > Constants.minimumNodeNum {
do {
let newUser = try createUser(num: Int64(nodeInfo.num), context: modelContext)
fetchedNode[0].user = newUser
} catch PersistenceError.invalidInput(let message) {
Logger.data.error("Error Creating a new UserEntity on an existing node (Invalid Input) from node number: \(nodeInfo.num, privacy: .public) Error: \(message, privacy: .public)")
} catch {
Logger.data.error("Error Creating a new UserEntity on an existing node from node number: \(nodeInfo.num, privacy: .public) Error: \(error.localizedDescription, privacy: .public)")
}
}
}
if nodeInfo.hasDeviceMetrics {
let newTelemetry = TelemetryEntity()
modelContext.insert(newTelemetry)
newTelemetry.batteryLevel = Int32(truncatingIfNeeded: nodeInfo.deviceMetrics.batteryLevel)
newTelemetry.voltage = nodeInfo.deviceMetrics.voltage
newTelemetry.channelUtilization = nodeInfo.deviceMetrics.channelUtilization
newTelemetry.airUtilTx = nodeInfo.deviceMetrics.airUtilTx
newTelemetry.nodeTelemetry = fetchedNode[0]
}
if nodeInfo.hasPosition {
if nodeInfo.position.hasValidCoordinates {
let position = PositionEntity()
modelContext.insert(position)
position.latitudeI = nodeInfo.position.latitudeI
position.longitudeI = nodeInfo.position.longitudeI
position.altitude = nodeInfo.position.altitude
position.satsInView = Int32(nodeInfo.position.satsInView)
position.time = Date(timeIntervalSince1970: TimeInterval(Int64(nodeInfo.position.time)))
position.nodePosition = fetchedNode[0]
}
}
// Look for a MyInfo
let myInfoNodeNum2 = Int64(nodeInfo.num)
let fetchMyInfoDescriptor2 = FetchDescriptor<MyInfoEntity>(predicate: #Predicate { $0.myNodeNum == myInfoNodeNum2 })
do {
let fetchedMyInfo = try modelContext.fetch(fetchMyInfoDescriptor2)
if fetchedMyInfo.count > 0 {
fetchedNode[0].myInfo = fetchedMyInfo[0]
}
if !deferSave {
savePendingChanges()
Logger.data.debug("💾 [Node Info] saved for \(nodeInfo.num.toHex(), privacy: .public)")
} else {
scheduleDebouncedSave()
}
return fetchedNode[0].persistentModelID
} catch {
Logger.data.error("💥 Fetch MyInfo Error")
}
}
} catch {
Logger.data.error("💥 Fetch NodeInfoEntity Error")
}
return nil
}
func adminAppPacket (packet: MeshPacket) {
if let adminMessage = try? AdminMessage(serializedBytes: packet.decoded.payload) {
if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getCannedMessageModuleMessagesResponse(adminMessage.getCannedMessageModuleMessagesResponse) {
if let cmmc = try? CannedMessageModuleConfig(serializedBytes: packet.decoded.payload) {
let logString = String.localizedStringWithFormat("Canned Messages Messages Received For: %@".localized, packet.from.toHex())
Logger.admin.info("🥫 \(logString, privacy: .public)")
let packetFrom = Int64(packet.from)
let fetchDescriptor = FetchDescriptor<NodeInfoEntity>(predicate: #Predicate { $0.num == packetFrom })
do {
let fetchedNode = try modelContext.fetch(fetchDescriptor)
if fetchedNode.count == 1 {
let messages = String(cmmc.textFormatString())
.replacingOccurrences(of: "11: ", with: "")
.replacingOccurrences(of: "\"", with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n").first ?? ""
fetchedNode[0].cannedMessageConfig?.messages = messages
savePendingChanges()
Logger.data.info("💾 Updated Canned Messages Messages For: \(fetchedNode.first?.num.toHex() ?? "Unknown".localized, privacy: .public)")
}
} catch {
Logger.data.error("💥 Error Deserializing ADMIN_APP packet.")
}
}
} else if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getChannelResponse(adminMessage.getChannelResponse) {
channelPacket(channel: adminMessage.getChannelResponse, fromNum: Int64(packet.from))
} else if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getDeviceMetadataResponse(adminMessage.getDeviceMetadataResponse) {
deviceMetadataPacket(metadata: adminMessage.getDeviceMetadataResponse, fromNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getConfigResponse(adminMessage.getConfigResponse) {
let config = adminMessage.getConfigResponse
if config.payloadVariant == Config.OneOf_PayloadVariant.bluetooth(config.bluetooth) {
upsertBluetoothConfigPacket(config: config.bluetooth, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.device(config.device) {
upsertDeviceConfigPacket(config: config.device, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.display(config.display) {
self.upsertDisplayConfigPacket(config: config.display, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.lora(config.lora) {
self.upsertLoRaConfigPacket(config: config.lora, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.network(config.network) {
self.upsertNetworkConfigPacket(config: config.network, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.position(config.position) {
self.upsertPositionConfigPacket(config: config.position, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.power(config.power) {
self.upsertPowerConfigPacket(config: config.power, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
} else if config.payloadVariant == Config.OneOf_PayloadVariant.security(config.security) {
self.upsertSecurityConfigPacket(config: config.security, nodeNum: Int64(packet.from), sessionPasskey: adminMessage.sessionPasskey)
}
} else if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getModuleConfigResponse(adminMessage.getModuleConfigResponse) {
let moduleConfig = adminMessage.getModuleConfigResponse
if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.ambientLighting(moduleConfig.ambientLighting) {
self.upsertAmbientLightingModuleConfigPacket(config: moduleConfig.ambientLighting, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.audio(moduleConfig.audio) {
self.upsertAudioModuleConfigPacket(config: moduleConfig.audio, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.cannedMessage(moduleConfig.cannedMessage) {
self.upsertCannedMessagesModuleConfigPacket(config: moduleConfig.cannedMessage, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.detectionSensor(moduleConfig.detectionSensor) {
self.upsertDetectionSensorModuleConfigPacket(config: moduleConfig.detectionSensor, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.externalNotification(moduleConfig.externalNotification) {
self.upsertExternalNotificationModuleConfigPacket(config: moduleConfig.externalNotification, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.mqtt(moduleConfig.mqtt) {
self.upsertMqttModuleConfigPacket(config: moduleConfig.mqtt, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.rangeTest(moduleConfig.rangeTest) {
self.upsertRangeTestModuleConfigPacket(config: moduleConfig.rangeTest, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.serial(moduleConfig.serial) {
self.upsertSerialModuleConfigPacket(config: moduleConfig.serial, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.storeForward(moduleConfig.storeForward) {
self.upsertStoreForwardModuleConfigPacket(config: moduleConfig.storeForward, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.telemetry(moduleConfig.telemetry) {
self.upsertTelemetryModuleConfigPacket(config: moduleConfig.telemetry, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.tak(moduleConfig.tak) {
self.upsertTAKModuleConfigPacket(config: moduleConfig.tak, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.statusmessage(moduleConfig.statusmessage) {
self.upsertStatusMessageModuleConfigPacket(config: moduleConfig.statusmessage, nodeNum: Int64(packet.from))
} else if moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.trafficManagement(moduleConfig.trafficManagement) {
self.upsertTrafficManagementModuleConfigPacket(config: moduleConfig.trafficManagement, nodeNum: Int64(packet.from))
}
} else if adminMessage.payloadVariant == AdminMessage.OneOf_PayloadVariant.getRingtoneResponse(adminMessage.getRingtoneResponse) {
if let rt = try? RTTTLConfig(serializedBytes: packet.decoded.payload) {
self.upsertRtttlConfigPacket(ringtone: rt.ringtone, nodeNum: Int64(packet.from))
}
} else {
Logger.admin.error("🕸️ MESH PACKET received Admin App UNHANDLED \((try? packet.decoded.jsonString()) ?? "JSON Decode Failure", privacy: .public)")
}
// Save an ack for the admin message log for each admin message response received as we stopped sending acks if there is also a response to reduce airtime.
self.adminResponseAck(packet: packet)
}
}
private func adminResponseAck (packet: MeshPacket) {
let requestID = Int64(packet.decoded.requestID)
let fetchDescriptor = FetchDescriptor<MessageEntity>(predicate: #Predicate { $0.messageId == requestID })
do {
let fetchedMessage = try modelContext.fetch(fetchDescriptor)
if fetchedMessage.count > 0 {
fetchedMessage[0].ackTimestamp = Int32(Date().timeIntervalSince1970)
fetchedMessage[0].ackError = Int32(RoutingError.none.rawValue)
fetchedMessage[0].receivedACK = true
fetchedMessage[0].realACK = true
fetchedMessage[0].relayNode = Int64(packet.relayNode)
fetchedMessage[0].ackSNR = packet.rxSnr
savePendingChanges()
}
} catch {
Logger.data.error("Failed to fetch admin message by requestID: \(error.localizedDescription, privacy: .public)")
}
}
func paxCounterPacket (packet: MeshPacket) {
let paxDetail = (try? Paxcount(serializedBytes: packet.decoded.payload)).map { " — \($0.wifi) wifi \($0.ble) ble" } ?? ""
Logger.mesh.info("[PAX Counter] packet received from \(packet.from.toHex(), privacy: .public)\(paxDetail, privacy: .public)")
let packetFrom = Int64(packet.from)
var fetchDescriptor = FetchDescriptor<NodeInfoEntity>(predicate: #Predicate { $0.num == packetFrom })
fetchDescriptor.fetchLimit = 1
do {
let fetchedNode = try modelContext.fetch(fetchDescriptor)
if let paxMessage = try? Paxcount(serializedBytes: packet.decoded.payload) {
let newPax = PaxCounterEntity()
modelContext.insert(newPax)
newPax.ble = Int32(truncatingIfNeeded: paxMessage.ble)
newPax.wifi = Int32(truncatingIfNeeded: paxMessage.wifi)
newPax.uptime = Int32(truncatingIfNeeded: paxMessage.uptime)
newPax.time = Date()
if fetchedNode.count > 0 {
newPax.paxNode = fetchedNode[0]
scheduleDebouncedSave()
} else {
Logger.data.info("Node Info Not Found")
}
}
} catch {
}
}
func routingPacket (packet: MeshPacket, connectedNodeNum: Int64) {
if let routingMessage = try? Routing(serializedBytes: packet.decoded.payload) {
let routingError = RoutingError(rawValue: routingMessage.errorReason.rawValue)
let routingErrorString = routingError?.display ?? "Unknown".localized
let logString = String.localizedStringWithFormat("Routing received for RequestID: %@ Ack Status: %@".localized, String(packet.decoded.requestID), routingErrorString)
Logger.mesh.info("🕸️ \(logString, privacy: .public)")
let requestID = Int64(packet.decoded.requestID)
let fetchDescriptor = FetchDescriptor<MessageEntity>(predicate: #Predicate { $0.messageId == requestID })
do {
let fetchedMessage = try modelContext.fetch(fetchDescriptor)
if fetchedMessage.count > 0 {
if fetchedMessage[0].toUser != nil {
// Real ACK from DM Recipient
if packet.to != packet.from {
fetchedMessage[0].realACK = true
}
}
fetchedMessage[0].relayNode = Int64(packet.relayNode)
fetchedMessage[0].ackError = Int32(routingMessage.errorReason.rawValue)
if routingMessage.errorReason == Routing.Error.none {
fetchedMessage[0].receivedACK = true
fetchedMessage[0].relays += 1
}
fetchedMessage[0].ackSNR = packet.rxSnr
if packet.rxTime > 0 {
fetchedMessage[0].ackTimestamp = Int32(truncatingIfNeeded: packet.rxTime)
} else {
fetchedMessage[0].ackTimestamp = Int32(Date().timeIntervalSince1970)
}
} else {
return
}
scheduleDebouncedSave()
Logger.data.debug("💾 ACK buffered for Message: \(packet.decoded.requestID, privacy: .public)")
} catch {
let nsError = error as NSError
Logger.data.error("Error Saving ACK for message: \(packet.id, privacy: .public) Error: \(nsError, privacy: .public)")
}
}
}
/// Compact, human-readable summary of a Telemetry packet for the mesh log line, e.g.
/// " — device 87% 4.05V ch 12.3% air 3.1%" or " — env 23.5°C 45% 1013hPa". Reads the salient
/// metrics per variant (not raw JSON); returns "" for unhandled variants.
private func telemetryLogDetails(_ telemetry: Telemetry) -> String {
var parts: [String] = []
switch telemetry.variant {
case .deviceMetrics(let m)?:
parts.append("device")
if m.hasBatteryLevel { parts.append("\(m.batteryLevel)%") }
if m.hasVoltage { parts.append(String(format: "%.2fV", m.voltage)) }
if m.hasChannelUtilization { parts.append(String(format: "ch %.1f%%", m.channelUtilization)) }
if m.hasAirUtilTx { parts.append(String(format: "air %.1f%%", m.airUtilTx)) }
case .environmentMetrics(let m)?:
parts.append("env")
if m.hasTemperature { parts.append(String(format: "%.1f°C", m.temperature)) }
if m.hasRelativeHumidity { parts.append(String(format: "%.0f%%", m.relativeHumidity)) }
if m.hasBarometricPressure { parts.append(String(format: "%.0fhPa", m.barometricPressure)) }
case .powerMetrics(let m)?:
parts.append("power")
if m.hasCh1Voltage { parts.append(String(format: "ch1 %.2fV", m.ch1Voltage)) }
if m.hasCh2Voltage { parts.append(String(format: "ch2 %.2fV", m.ch2Voltage)) }
if m.hasCh3Voltage { parts.append(String(format: "ch3 %.2fV", m.ch3Voltage)) }
case .localStats(let m)?:
parts.append("stats")
parts.append("\(m.numOnlineNodes)/\(m.numTotalNodes) nodes")
default:
return ""
}
return " — " + parts.joined(separator: " ")
}
/// First non-zero proto epoch (seconds since 1970) from `candidates`, as a `Date`; falls back to
/// now when none are set. Remote nodes without an RTC/GPS report 0, which would otherwise store as
/// 1970 and be hidden by the node detail's "latest" sort and the 7-day chart window — so callers
/// pass the sensor's self-reported time first, then `packet.rxTime`, to anchor on the best clock
/// available.
private func resolveTimestamp(_ candidates: UInt32...) -> Date {
for seconds in candidates where seconds > 0 {
return Date(timeIntervalSince1970: TimeInterval(seconds))
}
return Date()
}
func telemetryPacket(packet: MeshPacket, connectedNode: Int64) {
if let telemetryMessage = try? Telemetry(serializedBytes: packet.decoded.payload) {
if telemetryMessage.variant != Telemetry.OneOf_Variant.deviceMetrics(telemetryMessage.deviceMetrics) && telemetryMessage.variant != Telemetry.OneOf_Variant.environmentMetrics(telemetryMessage.environmentMetrics) && telemetryMessage.variant != Telemetry.OneOf_Variant.localStats(telemetryMessage.localStats) && telemetryMessage.variant != Telemetry.OneOf_Variant.powerMetrics(telemetryMessage.powerMetrics) {
/// Other unhandled telemetry packets
return
}
// Mesh-category audit (spec 012): telemetry received over the air from a
// remote node is genuine mesh traffic and belongs in the Packet Stream,
// consistent with text/position/nodeinfo. The connected node's own
// localStats (from == connectedNode) is local, not OTA, so it stays on
// .data/.statistics below and out of the Mesh category.
if connectedNode != Int64(packet.from) {
Logger.mesh.info("📈 [Telemetry] packet received from \(packet.from.toHex(), privacy: .public)\(self.telemetryLogDetails(telemetryMessage), privacy: .public)")
}
let packetFrom = Int64(packet.from)
// packet.from == 0 is not a real node, so there is nothing to attribute telemetry to.
guard packetFrom > 0 else { return }
// Telemetry is genuine RF contact with packet.from. Like deviceMetadataPacket /
// textMessageAppPacket, ensure a NodeInfoEntity exists before storing so telemetry that
// arrives before the node's NodeInfo / nodeDB entry is not dropped as an orphan row
// (nodeTelemetry == nil) that the UI can never query. `num` is @Attribute(.unique), so this
// returns the existing node or a minimal stub that a later NodeInfo packet enriches.
let node = findOrCreateNode(num: packetFrom, context: modelContext)
let telemetry = TelemetryEntity()
modelContext.insert(telemetry)
/// Currently only Device Metrics and Environment Telemetry are supported in the app
if telemetryMessage.variant == Telemetry.OneOf_Variant.deviceMetrics(telemetryMessage.deviceMetrics) {
// Device Metrics
Logger.data.debug("📈 [Telemetry] Device Metrics Received for Node: \(packet.from.toHex(), privacy: .public)")
telemetry.airUtilTx = telemetryMessage.deviceMetrics.hasAirUtilTx.then(telemetryMessage.deviceMetrics.airUtilTx)
telemetry.channelUtilization = telemetryMessage.deviceMetrics.hasChannelUtilization.then(telemetryMessage.deviceMetrics.channelUtilization)
telemetry.batteryLevel = telemetryMessage.deviceMetrics.hasBatteryLevel.then(Int32(truncatingIfNeeded: telemetryMessage.deviceMetrics.batteryLevel))
telemetry.voltage = telemetryMessage.deviceMetrics.hasVoltage.then(telemetryMessage.deviceMetrics.voltage)
telemetry.uptimeSeconds = telemetryMessage.deviceMetrics.hasUptimeSeconds.then(Int32(truncatingIfNeeded: telemetryMessage.deviceMetrics.uptimeSeconds))
telemetry.metricsType = 0
Logger.statistics.debug("📈 [Mesh Statistics] Channel Utilization: \(telemetryMessage.deviceMetrics.channelUtilization, privacy: .public) Airtime: \(telemetryMessage.deviceMetrics.airUtilTx, privacy: .public) for Node: \(packet.from.toHex(), privacy: .public)")
} else if telemetryMessage.variant == Telemetry.OneOf_Variant.environmentMetrics(telemetryMessage.environmentMetrics) {
// Environment Metrics
Logger.data.debug("📈 [Telemetry] Environment Metrics Received for Node: \(packet.from.toHex(), privacy: .public)")
telemetry.barometricPressure = telemetryMessage.environmentMetrics.hasBarometricPressure.then(telemetryMessage.environmentMetrics.barometricPressure)
telemetry.iaq = telemetryMessage.environmentMetrics.hasIaq.then(Int32(truncatingIfNeeded: telemetryMessage.environmentMetrics.iaq))
telemetry.gasResistance = telemetryMessage.environmentMetrics.hasGasResistance.then(telemetryMessage.environmentMetrics.gasResistance)
telemetry.relativeHumidity = telemetryMessage.environmentMetrics.hasRelativeHumidity.then(telemetryMessage.environmentMetrics.relativeHumidity)
telemetry.temperature = telemetryMessage.environmentMetrics.hasTemperature.then(telemetryMessage.environmentMetrics.temperature)
telemetry.current = telemetryMessage.environmentMetrics.hasCurrent.then(telemetryMessage.environmentMetrics.current)
telemetry.voltage = telemetryMessage.environmentMetrics.hasVoltage.then(telemetryMessage.environmentMetrics.voltage)
telemetry.weight = telemetryMessage.environmentMetrics.hasWeight.then(telemetryMessage.environmentMetrics.weight)
telemetry.distance = telemetryMessage.environmentMetrics.hasDistance.then(telemetryMessage.environmentMetrics.distance)
telemetry.windSpeed = telemetryMessage.environmentMetrics.hasWindSpeed.then(telemetryMessage.environmentMetrics.windSpeed)
telemetry.windGust = telemetryMessage.environmentMetrics.hasWindGust.then(telemetryMessage.environmentMetrics.windGust)
telemetry.windLull = telemetryMessage.environmentMetrics.hasWindLull.then(telemetryMessage.environmentMetrics.windLull)
telemetry.windDirection = telemetryMessage.environmentMetrics.hasWindDirection.then(Int32(truncatingIfNeeded: telemetryMessage.environmentMetrics.windDirection))
telemetry.irLux = telemetryMessage.environmentMetrics.hasIrLux.then(telemetryMessage.environmentMetrics.irLux)
telemetry.lux = telemetryMessage.environmentMetrics.hasLux.then(telemetryMessage.environmentMetrics.lux)
telemetry.whiteLux = telemetryMessage.environmentMetrics.hasWhiteLux.then(telemetryMessage.environmentMetrics.whiteLux)
telemetry.uvLux = telemetryMessage.environmentMetrics.hasUvLux.then(telemetryMessage.environmentMetrics.uvLux)
telemetry.radiation = telemetryMessage.environmentMetrics.hasRadiation.then(telemetryMessage.environmentMetrics.radiation)
telemetry.rainfall1H = telemetryMessage.environmentMetrics.hasRainfall1H.then(telemetryMessage.environmentMetrics.rainfall1H)
telemetry.rainfall24H = telemetryMessage.environmentMetrics.hasRainfall24H.then(telemetryMessage.environmentMetrics.rainfall24H)
telemetry.soilTemperature = telemetryMessage.environmentMetrics.hasSoilTemperature.then(telemetryMessage.environmentMetrics.soilTemperature)
telemetry.soilMoisture = telemetryMessage.environmentMetrics.hasSoilMoisture.then(telemetryMessage.environmentMetrics.soilMoisture)
telemetry.metricsType = 1
} else if telemetryMessage.variant == Telemetry.OneOf_Variant.localStats(telemetryMessage.localStats) {
// Local Stats for Live activity
telemetry.uptimeSeconds = Int32(truncatingIfNeeded: telemetryMessage.localStats.uptimeSeconds)
telemetry.channelUtilization = telemetryMessage.localStats.channelUtilization
telemetry.airUtilTx = telemetryMessage.localStats.airUtilTx
telemetry.numPacketsTx = Int32(truncatingIfNeeded: telemetryMessage.localStats.numPacketsTx)
telemetry.numPacketsRx = Int32(truncatingIfNeeded: telemetryMessage.localStats.numPacketsRx)
telemetry.numPacketsRxBad = Int32(truncatingIfNeeded: telemetryMessage.localStats.numPacketsRxBad)
telemetry.numRxDupe = Int32(truncatingIfNeeded: telemetryMessage.localStats.numRxDupe)
telemetry.numTxRelay = Int32(truncatingIfNeeded: telemetryMessage.localStats.numTxRelay)
telemetry.numTxRelayCanceled = Int32(truncatingIfNeeded: telemetryMessage.localStats.numTxRelayCanceled)
telemetry.numOnlineNodes = Int32(truncatingIfNeeded: telemetryMessage.localStats.numOnlineNodes)
telemetry.numTotalNodes = Int32(truncatingIfNeeded: telemetryMessage.localStats.numTotalNodes)
// `noise_floor` is a plain proto3 scalar (not `optional`), so it has no
// presence tracking — firmware that doesn't report it is indistinguishable
// from a literal 0. Real LoRa noise floors are always strongly negative, so
// we treat 0 as "not available" (nil). If true nil-vs-0 is ever needed, make
// the field `optional` upstream and use `hasNoiseFloor`.
telemetry.noiseFloor = telemetryMessage.localStats.noiseFloor != 0 ? telemetryMessage.localStats.noiseFloor : nil
telemetry.metricsType = 4
Logger.statistics.debug("📈 [Mesh Statistics] Channel Utilization: \(telemetryMessage.localStats.channelUtilization, privacy: .public) Airtime: \(telemetryMessage.localStats.airUtilTx, privacy: .public) Packets Sent: \(telemetryMessage.localStats.numPacketsTx, privacy: .public) Packets Received: \(telemetryMessage.localStats.numPacketsRx, privacy: .public) Bad Packets Received: \(telemetryMessage.localStats.numPacketsRxBad, privacy: .public) Noise Floor: \(telemetryMessage.localStats.noiseFloor, privacy: .public) Nodes Online: \(telemetryMessage.localStats.numOnlineNodes, privacy: .public) of \(telemetryMessage.localStats.numTotalNodes, privacy: .public) nodes for Node: \(packet.from.toHex(), privacy: .public)")
} else if telemetryMessage.variant == Telemetry.OneOf_Variant.powerMetrics(telemetryMessage.powerMetrics) {