forked from meshtastic/firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficManagementModule.cpp
More file actions
1299 lines (1135 loc) · 52.7 KB
/
Copy pathTrafficManagementModule.cpp
File metadata and controls
1299 lines (1135 loc) · 52.7 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
#include "TrafficManagementModule.h"
#if HAS_TRAFFIC_MANAGEMENT
#include "Channels.h"
#include "Default.h"
#include "MeshService.h"
#include "NodeDB.h"
#include "PositionPrecision.h"
#include "Router.h"
#include "TypeConversions.h"
#include "airtime.h"
#include "concurrency/LockGuard.h"
#include "configuration.h"
#include "memory/MemAudit.h"
#include "mesh-pb-constants.h"
#include "meshUtils.h"
#include <Arduino.h>
#include <algorithm>
#include <cstring>
#define TM_LOG_DEBUG(fmt, ...) LOG_DEBUG("[TM] " fmt, ##__VA_ARGS__)
#define TM_LOG_INFO(fmt, ...) LOG_INFO("[TM] " fmt, ##__VA_ARGS__)
#define TM_LOG_WARN(fmt, ...) LOG_WARN("[TM] " fmt, ##__VA_ARGS__)
// =============================================================================
// Anonymous Namespace - Internal Helpers
// =============================================================================
namespace
{
constexpr uint32_t kMaintenanceIntervalMs = 60 * 1000UL; // Cache cleanup interval
// NodeInfo direct response: enforced maximum hops by device role
// Both use maxHops logic (respond when hopsAway <= threshold)
// Config value is clamped to these role-based limits
// Note: nodeinfo_direct_response must also be enabled for this to take effect
constexpr uint32_t kRouterDefaultMaxHops = 3; // Routers: max 3 hops (can set lower via config)
constexpr uint32_t kClientDefaultMaxHops = 0; // Clients: direct only (cannot increase)
/**
* Convert seconds to milliseconds with overflow protection.
*/
uint32_t secsToMs(uint32_t secs)
{
uint64_t ms = static_cast<uint64_t>(secs) * 1000ULL;
if (ms > UINT32_MAX)
return UINT32_MAX;
return static_cast<uint32_t>(ms);
}
// Advertised role of the originating node (from NodeDB), or CLIENT (no exception) if unknown.
// Position filtering grants two role exceptions: trackers may refresh duplicates hourly, and
// lost-and-found is throttled only to the shortest dedup window. Both are still subject to
// the channel-precision ceiling in alterReceived().
meshtastic_Config_DeviceConfig_Role originRole(NodeNum from)
{
// Resolve via NodeDB: hot store (with user) → warm-tier cached role → CLIENT. The
// warm fallback keeps role exceptions firing for trackers/etc. aged out of the hot store.
return nodeDB ? nodeDB->getNodeRole(from) : meshtastic_Config_DeviceConfig_Role_CLIENT;
}
/**
* Clamp precision to a valid dedup range.
* Invalid values use the module default precision.
*/
uint8_t sanitizePositionPrecision(uint8_t precision)
{
if (precision > 0 && precision <= 32)
return precision;
const uint8_t defaultPrecision = static_cast<uint8_t>(default_traffic_mgmt_position_precision_bits);
if (defaultPrecision > 0 && defaultPrecision <= 32)
return defaultPrecision;
// Someone done messed up if we reach here
return 32;
}
/**
* Saturating increment for uint8_t counters.
* Prevents overflow by capping at UINT8_MAX (255).
*/
inline void saturatingIncrement(uint8_t &counter)
{
if (counter < UINT8_MAX)
counter++;
}
/**
* Return a short human-readable name for common port numbers.
* Falls back to "port:<N>" for unknown ports.
*/
const char *portName(int portnum)
{
switch (portnum) {
case meshtastic_PortNum_TEXT_MESSAGE_APP:
return "text";
case meshtastic_PortNum_POSITION_APP:
return "position";
case meshtastic_PortNum_NODEINFO_APP:
return "nodeinfo";
case meshtastic_PortNum_ROUTING_APP:
return "routing";
case meshtastic_PortNum_ADMIN_APP:
return "admin";
case meshtastic_PortNum_TELEMETRY_APP:
return "telemetry";
case meshtastic_PortNum_TRACEROUTE_APP:
return "traceroute";
case meshtastic_PortNum_NEIGHBORINFO_APP:
return "neighborinfo";
case meshtastic_PortNum_STORE_FORWARD_APP:
return "store-forward";
case meshtastic_PortNum_WAYPOINT_APP:
return "waypoint";
default:
return nullptr;
}
}
} // namespace
// =============================================================================
// Module Instance
// =============================================================================
TrafficManagementModule *trafficManagementModule;
// =============================================================================
// Constructor
// =============================================================================
TrafficManagementModule::TrafficManagementModule() : MeshModule("TrafficManagement"), concurrency::OSThread("TrafficManagement")
{
// Module configuration
isPromiscuous = true; // See all packets, not just those addressed to us
encryptedOk = true; // Can process encrypted packets
stats = meshtastic_TrafficManagementStats_init_zero;
const auto &cfg = moduleConfig.traffic_management;
TM_LOG_INFO("Config: nodeinfo_max_hops=%u rate_window=%us rate_max=%u unknown_thresh=%u pos_interval=%us",
cfg.nodeinfo_direct_response_max_hops, cfg.rate_limit_window_secs, cfg.rate_limit_max_packets,
cfg.unknown_packet_threshold, cfg.position_min_interval_secs);
// Allocate unified cache (10 bytes/entry for all platforms)
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
const uint16_t allocSize = cacheSize();
TM_LOG_INFO("Allocating unified cache: %u entries (%u bytes)", allocSize,
static_cast<unsigned>(allocSize * sizeof(UnifiedCacheEntry)));
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
// ESP32 with PSRAM: prefer PSRAM for large allocations
cache = static_cast<UnifiedCacheEntry *>(ps_calloc(allocSize, sizeof(UnifiedCacheEntry)));
if (cache) {
cacheFromPsram = true;
} else {
TM_LOG_WARN("PSRAM allocation failed, falling back to heap");
cache = new UnifiedCacheEntry[allocSize]();
}
#else
// All other platforms: heap allocation
cache = new UnifiedCacheEntry[allocSize]();
#endif
memaudit::set("tmm", cache ? allocSize * sizeof(UnifiedCacheEntry) : 0);
#endif // TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
TM_LOG_INFO("Allocating NodeInfo cache: %u entries, %u bytes (PSRAM flat array)",
static_cast<unsigned>(nodeInfoTargetEntries()),
static_cast<unsigned>(nodeInfoTargetEntries() * sizeof(NodeInfoPayloadEntry)));
nodeInfoPayload = static_cast<NodeInfoPayloadEntry *>(ps_calloc(nodeInfoTargetEntries(), sizeof(NodeInfoPayloadEntry)));
if (nodeInfoPayload) {
nodeInfoPayloadFromPsram = true;
TM_LOG_INFO("NodeInfo PSRAM cache ready");
} else {
TM_LOG_WARN("NodeInfo PSRAM payload allocation failed; direct responses will fall back to NodeDB");
}
memaudit::set("tmm_ni", nodeInfoPayload ? nodeInfoTargetEntries() * sizeof(NodeInfoPayloadEntry) : 0);
#else
TM_LOG_DEBUG("NodeInfo PSRAM cache not available on this target");
#endif
setIntervalFromNow(kMaintenanceIntervalMs);
}
// Cache may have been allocated via ps_calloc (PSRAM, C allocator) or new[] (heap).
// Must use the matching deallocator: free() for ps_calloc, delete[] for new[].
TrafficManagementModule::~TrafficManagementModule()
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (cache) {
// Cache may be from ps_calloc (PSRAM, C allocator) or new[] (heap).
// Use the matching deallocator for the allocation source.
if (cacheFromPsram)
free(cache);
else
delete[] cache;
cache = nullptr;
}
memaudit::set("tmm", 0);
#endif
if (nodeInfoPayload) {
if (nodeInfoPayloadFromPsram)
free(nodeInfoPayload);
else
delete[] nodeInfoPayload;
nodeInfoPayload = nullptr;
}
memaudit::set("tmm_ni", 0);
}
// =============================================================================
// Statistics
// =============================================================================
meshtastic_TrafficManagementStats TrafficManagementModule::getStats() const
{
concurrency::LockGuard guard(&cacheLock);
return stats;
}
void TrafficManagementModule::resetStats()
{
concurrency::LockGuard guard(&cacheLock);
stats = meshtastic_TrafficManagementStats_init_zero;
}
void TrafficManagementModule::recordRouterHopPreserved()
{
// router_preserve_hops: not suitable right now - removed from config until
// the right heuristic for when to preserve vs. exhaust is clearer.
(void)stats.router_hops_preserved;
}
void TrafficManagementModule::incrementStat(uint32_t *field)
{
concurrency::LockGuard guard(&cacheLock);
(*field)++;
}
// =============================================================================
// Flat Unified Cache Operations
// =============================================================================
/**
* Find an existing entry for the given node (linear scan).
*/
TrafficManagementModule::UnifiedCacheEntry *TrafficManagementModule::findEntry(NodeNum node)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE == 0
(void)node;
return nullptr;
#else
if (!cache || node == 0)
return nullptr;
for (uint16_t i = 0; i < cacheSize(); i++) {
if (cache[i].node == node)
return &cache[i];
}
return nullptr;
#endif
}
int TrafficManagementModule::peekCachedRole(NodeNum node)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE == 0
(void)node;
return -1;
#else
concurrency::LockGuard guard(&cacheLock);
const UnifiedCacheEntry *entry = findEntry(node);
return entry ? static_cast<int>(entry->getCachedRole()) : -1;
#endif
}
/**
* Find or create an entry for the given node.
*
* One linear pass tracks the match, the first empty slot, and the eviction
* victim. When the cache is full, the victim is the stalest entry (largest
* of its three relative timestamps is smallest), preferring entries without
* a next_hop hint - those hints are the long-tail routing state the cache
* exists to keep, and the maintenance sweep never ages them out.
*
* @param node NodeNum to find or create
* @param isNew Set to true if a new entry was created
* @return Pointer to entry, or nullptr if the cache is unavailable
*/
// Sender-role resolution for the position hot path. The tier-3 cache is authoritative
// here and is kept fresh by updateCachedRoleFromNodeInfo() - i.e. updated at the same
// time NodeDB learns a role, not re-derived on every packet. We only fall back to a
// NodeDB scan (tiers 1+2) the first time we start tracking a node, to seed the cache so
// a resident special-role node is correct from its very first position. Thereafter the
// read is O(1) and survives the node aging out of both NodeDB stores.
meshtastic_Config_DeviceConfig_Role TrafficManagementModule::resolveSenderRole(NodeNum from, UnifiedCacheEntry *entry, bool isNew)
{
if (!entry)
return originRole(from);
if (isNew) {
// First time tracking this node: seed tier 3 from NodeDB (hot → warm). Stores
// CLIENT (0) too, which simply reads back as "no exception".
const meshtastic_Config_DeviceConfig_Role role = originRole(from);
entry->setCachedRole(static_cast<uint8_t>(std::min(15, static_cast<int>(role))));
return role;
}
// Established entry: trust the cached role (refreshed on NodeInfo). No NodeDB scan.
return static_cast<meshtastic_Config_DeviceConfig_Role>(entry->getCachedRole());
}
// Refresh the tier-3 role cache from an observed NodeInfo - the same event that updates
// NodeDB's role - so role changes (including demotion back to CLIENT) are picked up
// without scanning NodeDB on the position hot path. Role is read straight from the
// packet's User payload (authoritative regardless of module ordering). Only updates nodes
// we already track (findEntry, no create) so NodeInfo from non-position nodes can't pollute
// the cache; the role rides along with the node's existing position/rate/unknown state.
void TrafficManagementModule::updateCachedRoleFromNodeInfo(const meshtastic_MeshPacket &mp)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (mp.decoded.payload.size == 0)
return;
meshtastic_User user = meshtastic_User_init_zero;
if (!pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, &meshtastic_User_msg, &user))
return;
concurrency::LockGuard guard(&cacheLock);
UnifiedCacheEntry *entry = findEntry(getFrom(&mp));
if (entry)
entry->setCachedRole(static_cast<uint8_t>(std::min(15, static_cast<int>(user.role))));
#else
(void)mp;
#endif
}
TrafficManagementModule::UnifiedCacheEntry *TrafficManagementModule::findOrCreateEntry(NodeNum node, bool *isNew)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE == 0
(void)node;
if (isNew)
*isNew = false;
return nullptr;
#else
if (isNew)
*isNew = false;
if (!cache || node == 0)
return nullptr;
UnifiedCacheEntry *empty = nullptr;
UnifiedCacheEntry *victim = nullptr;
bool leastPreferredVictim = true;
uint8_t victimRecency = UINT8_MAX;
for (uint16_t i = 0; i < cacheSize(); i++) {
UnifiedCacheEntry &e = cache[i];
if (e.node == node)
return &e;
if (e.node == 0) {
if (!empty)
empty = &e;
continue;
}
if (empty)
continue; // an empty slot beats any victim; stop scoring
// "Preferred" entries are evicted last: a confirmed next-hop hint (routing overflow
// store) or a cached special (non-CLIENT) role (tracker / lost-and-found / router).
// Both are the long-tail state this cache exists to retain.
const bool preferred = e.next_hop != 0 || e.getCachedRole() != meshtastic_Config_DeviceConfig_Role_CLIENT;
// Age in pos-ticks (8-bit modular, wraps correctly). Entries with no
// pos state (pos_time==0) score as maximally old (age=currentPosTick()).
const uint8_t nowPosTick = currentPosTick();
const uint8_t posAge = static_cast<uint8_t>(nowPosTick - e.pos_time);
// Blend in rate/unknown ages scaled to pos-tick units (coarser = conservative).
const uint8_t rateAgePosScale =
static_cast<uint8_t>(static_cast<uint8_t>((currentRateTick() - e.getRateTime()) & 0x0F) * 5 / 3);
const uint8_t unknownAgePosScale =
static_cast<uint8_t>(static_cast<uint8_t>((currentUnknownTick() - e.getUnknownTime()) & 0x0F) / 6);
uint8_t recencyAge = posAge;
if (e.getRateCount() != 0 && rateAgePosScale > recencyAge)
recencyAge = rateAgePosScale;
if (e.getUnknownCount() != 0 && unknownAgePosScale > recencyAge)
recencyAge = unknownAgePosScale;
const uint8_t recency = static_cast<uint8_t>(UINT8_MAX - recencyAge);
if (!victim || (preferred == leastPreferredVictim ? recency < victimRecency : !preferred)) {
victim = &e;
leastPreferredVictim = preferred;
victimRecency = recency;
}
}
UnifiedCacheEntry *slot = empty ? empty : victim;
if (!slot)
return nullptr;
if (!empty)
TM_LOG_DEBUG("Unified cache full, evicting node 0x%08x", slot->node);
memset(slot, 0, sizeof(UnifiedCacheEntry));
slot->node = node;
if (isNew)
*isNew = true;
return slot;
#endif
}
const TrafficManagementModule::NodeInfoPayloadEntry *TrafficManagementModule::findNodeInfoEntry(NodeNum node) const
{
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
if (!nodeInfoPayload || node == 0)
return nullptr;
for (uint16_t i = 0; i < nodeInfoTargetEntries(); i++) {
if (nodeInfoPayload[i].node == node)
return &nodeInfoPayload[i];
}
return nullptr;
#else
(void)node;
return nullptr;
#endif
}
/**
* Find or create a NodeInfo payload entry (linear scan of the flat PSRAM
* array). One pass tracks the match, the first empty slot, and the LRU
* victim by lastObservedMs (wrap-safe age). NodeInfo traffic is low-rate,
* so the O(n) scan is negligible.
*/
TrafficManagementModule::NodeInfoPayloadEntry *TrafficManagementModule::findOrCreateNodeInfoEntry(NodeNum node,
bool *usedEmptySlot)
{
if (usedEmptySlot)
*usedEmptySlot = false;
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
if (!nodeInfoPayload || node == 0)
return nullptr;
NodeInfoPayloadEntry *empty = nullptr;
NodeInfoPayloadEntry *lru = nullptr;
uint32_t lruAge = 0;
const uint32_t now = clockMs();
for (uint16_t i = 0; i < nodeInfoTargetEntries(); i++) {
NodeInfoPayloadEntry &e = nodeInfoPayload[i];
if (e.node == node)
return &e;
if (e.node == 0) {
if (!empty)
empty = &e;
continue;
}
if (empty)
continue; // an empty slot beats any victim; stop scoring
const uint32_t age = now - e.lastObservedMs; // unsigned subtraction is wrap-safe
if (!lru || age > lruAge) {
lru = &e;
lruAge = age;
}
}
NodeInfoPayloadEntry *slot = empty ? empty : lru;
if (!slot)
return nullptr;
memset(slot, 0, sizeof(NodeInfoPayloadEntry));
slot->node = node;
if (usedEmptySlot)
*usedEmptySlot = (slot == empty);
return slot;
#else
(void)node;
return nullptr;
#endif
}
uint16_t TrafficManagementModule::countNodeInfoEntriesLocked() const
{
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
if (!nodeInfoPayload)
return 0;
uint16_t count = 0;
for (uint16_t i = 0; i < nodeInfoTargetEntries(); i++) {
if (nodeInfoPayload[i].node != 0)
count++;
}
return count;
#else
return 0;
#endif
}
void TrafficManagementModule::cacheNodeInfoPacket(const meshtastic_MeshPacket &mp)
{
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
if (!nodeInfoPayload || mp.decoded.payload.size == 0)
return;
meshtastic_User user = meshtastic_User_init_zero;
if (!pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, &meshtastic_User_msg, &user))
return;
// Normalize user.id to the packet sender's node number.
snprintf(user.id, sizeof(user.id), "!%08x", getFrom(&mp));
bool usedEmptySlot = false;
uint16_t cachedCount = 0;
{
concurrency::LockGuard guard(&cacheLock);
NodeInfoPayloadEntry *entry = findOrCreateNodeInfoEntry(getFrom(&mp), &usedEmptySlot);
if (!entry)
return;
// Cache both payload and response metadata so direct replies can use
// richer context than "just the user protobuf" when PSRAM is present.
// This path is intentionally independent from NodeInfoModule/NodeDB.
entry->user = user;
entry->lastObservedMs = clockMs();
entry->lastObservedRxTime = mp.rx_time;
entry->sourceChannel = mp.channel;
entry->hasDecodedBitfield = mp.decoded.has_bitfield;
entry->decodedBitfield = mp.decoded.bitfield;
if (usedEmptySlot)
cachedCount = countNodeInfoEntriesLocked();
}
if (usedEmptySlot) {
TM_LOG_INFO("NodeInfo PSRAM cache entries: %u/%u", static_cast<unsigned>(cachedCount),
static_cast<unsigned>(nodeInfoTargetEntries()));
}
#else
(void)mp;
#endif
}
// =============================================================================
// Next-Hop Overflow Cache
// =============================================================================
//
// A routing hint store. The byte is the last byte of the NodeNum to use as next
// hop to reach `dest`. It is written ONLY from NextHopRouter's ACK-confirmed
// decision (a bidirectionally-verified relay) - never inferred one-way from
// relayed traffic. The TMM cache holds confirmed next-hops that have aged out of
// the hot NodeDB (NodeInfoLite), and NextHopRouter::getNextHop() consults it as a
// fallback after the hot store.
void TrafficManagementModule::setNextHop(NodeNum dest, uint8_t nextHopByte)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (!cache || dest == 0 || nextHopByte == 0)
return;
concurrency::LockGuard guard(&cacheLock);
bool isNew = false;
UnifiedCacheEntry *entry = findOrCreateEntry(dest, &isNew);
if (entry)
entry->next_hop = nextHopByte; // last-write-wins; only confirmed bytes reach here
#else
(void)dest;
(void)nextHopByte;
#endif
}
uint8_t TrafficManagementModule::getNextHopHint(NodeNum dest)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (!cache || dest == 0)
return 0;
concurrency::LockGuard guard(&cacheLock);
UnifiedCacheEntry *entry = findEntry(dest);
return entry ? entry->next_hop : 0;
#else
(void)dest;
return 0;
#endif
}
void TrafficManagementModule::clearNextHop(NodeNum dest)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (!cache || dest == 0)
return;
concurrency::LockGuard guard(&cacheLock);
UnifiedCacheEntry *entry = findEntry(dest);
if (entry)
entry->next_hop = 0; // keep the entry (other stats), just drop the routing hint
#else
(void)dest;
#endif
}
bool TrafficManagementModule::preloadNextHopsFromNodeDB()
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
if (!cache || !nodeDB)
return false; // prerequisites not ready yet - caller should retry on a later pass
uint16_t seeded = 0;
concurrency::LockGuard guard(&cacheLock);
const size_t count = nodeDB->getNumMeshNodes();
for (size_t i = 0; i < count; i++) {
const meshtastic_NodeInfoLite *node = nodeDB->getMeshNodeByIndex(i);
if (!node || node->num == 0 || node->next_hop == 0)
continue;
bool isNew = false;
UnifiedCacheEntry *entry = findOrCreateEntry(node->num, &isNew);
// Don't clobber a freshly-learned confirmed hop with a (possibly stale) persisted one.
if (entry && entry->next_hop == 0) {
entry->next_hop = node->next_hop;
seeded++;
}
}
TM_LOG_INFO("Preloaded %u next-hop hints from NodeDB", static_cast<unsigned>(seeded));
return true;
#else
return true; // nothing to preload on a cache-less build; don't keep retrying
#endif
}
// =============================================================================
// Epoch Management
// =============================================================================
void TrafficManagementModule::flushCache()
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
TM_LOG_DEBUG("Flushing cache");
memset(cache, 0, static_cast<size_t>(cacheSize()) * sizeof(UnifiedCacheEntry));
#endif
}
// =============================================================================
// Position Hash (Compact Mode)
// =============================================================================
/**
* Compute 8-bit position fingerprint from truncated lat/lon coordinates.
*
* Unlike a hash, this is deterministic: adjacent grid cells have sequential
* fingerprints, so nearby positions never collide. The fingerprint extracts
* the lower 4 significant bits from each truncated coordinate.
*
* Example with precision=16:
* lat_truncated = 0x12340000 (top 16 bits significant)
* Significant portion = 0x1234, lower 4 bits = 0x4
*
* fingerprint = (lat_low4 << 4) | lon_low4 = 8 bits total
*
* Collision: Two positions collide only if they differ by a multiple of 16
* grid cells in BOTH lat and lon dimensions simultaneously - very unlikely
* for typical position update patterns.
*
* @param lat_truncated Precision-truncated latitude
* @param lon_truncated Precision-truncated longitude
* @param precision Number of significant bits (1-32)
* @return 8-bit fingerprint (4 bits lat + 4 bits lon)
*/
uint8_t TrafficManagementModule::computePositionFingerprint(int32_t lat_truncated, int32_t lon_truncated, uint8_t precision)
{
precision = sanitizePositionPrecision(precision);
// Guard: if precision < 4, we have fewer bits to work with
// Take min(precision, 4) bits from each coordinate
uint8_t bitsToTake = (precision < 4) ? precision : 4;
// Shift to move significant bits to bottom, then mask lower bits
// For precision=16: shift by 16 to get the 16 significant bits at bottom
uint8_t shift = 32 - precision;
uint8_t latBits = (static_cast<uint32_t>(lat_truncated) >> shift) & ((1u << bitsToTake) - 1);
uint8_t lonBits = (static_cast<uint32_t>(lon_truncated) >> shift) & ((1u << bitsToTake) - 1);
const uint8_t fp = static_cast<uint8_t>((latBits << 4) | lonBits);
// 0 is the "no position seen" sentinel for pos_fingerprint, so a real position that happens to
// hash to 0 must not collide with it (otherwise its duplicates would never dedup). Remap 0 -> 0xFF,
// mirroring NodeDB::getLastByteOfNodeNum()'s 0 -> 0xFF idiom. Cost: the 0x00 bucket merges into
// 0xFF (one extra collision in 256 - negligible; the fingerprint already collides every 16 cells).
return fp ? fp : 0xFF;
}
// =============================================================================
// Packet Handling
// =============================================================================
// Processing order matters: this module runs BEFORE RoutingModule in the callModules() loop.
// - STOP prevents RoutingModule from calling sniffReceived() → perhapsRebroadcast(),
// so the packet is fully consumed (not forwarded).
// - ignoreRequest suppresses the default "no one responded" NAK for want_response packets.
// - exhaustRequested is set by alterReceived() and checked by perhapsRebroadcast() to
// force hop_limit=0 on the rebroadcast copy, allowing one final relay hop.
ProcessMessage TrafficManagementModule::handleReceived(const meshtastic_MeshPacket &mp)
{
if (!moduleConfig.has_traffic_management)
return ProcessMessage::CONTINUE;
ignoreRequest = false;
exhaustRequested = false; // Reset per-packet; may be set by alterReceived() below
exhaustRequestedFrom = 0;
exhaustRequestedId = 0;
incrementStat(&stats.packets_inspected);
const auto &cfg = moduleConfig.traffic_management;
const uint32_t nowMs = TrafficManagementModule::clockMs();
// -------------------------------------------------------------------------
// Undecoded Packet Handling
// -------------------------------------------------------------------------
// Packets we can't decode (wrong key, corruption, etc.) may indicate
// a misbehaving node. Track and optionally drop repeat offenders.
if (mp.which_payload_variant != meshtastic_MeshPacket_decoded_tag) {
if (cfg.unknown_packet_threshold > 0) {
if (shouldDropUnknown(&mp, nowMs)) {
logAction("drop", &mp, "unknown");
incrementStat(&stats.unknown_packet_drops);
ignoreRequest = true; // Suppress NAK for want_response packets
return ProcessMessage::STOP; // Consumed - will not be rebroadcast
}
}
return ProcessMessage::CONTINUE;
}
// Learn NodeInfo payloads into the dedicated PSRAM cache, and refresh the tier-3
// role cache for any node we already track (keeps the dedup role exception current).
if (mp.decoded.portnum == meshtastic_PortNum_NODEINFO_APP) {
cacheNodeInfoPacket(mp);
updateCachedRoleFromNodeInfo(mp);
}
// -------------------------------------------------------------------------
// NodeInfo Direct Response
// -------------------------------------------------------------------------
// When we see a unicast NodeInfo request for a node we know about,
// respond directly from cache instead of forwarding the request.
// STOP prevents the request from being rebroadcast toward the target node,
// and our cached response is sent back to the requestor with hop_limit=0.
if (cfg.nodeinfo_direct_response_max_hops > 0 && mp.decoded.portnum == meshtastic_PortNum_NODEINFO_APP &&
mp.decoded.want_response && !isBroadcast(mp.to) && !isToUs(&mp) && !isFromUs(&mp)) {
if (shouldRespondToNodeInfo(&mp, true)) {
meshtastic_User requester = meshtastic_User_init_zero;
if (pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, &meshtastic_User_msg, &requester)) {
nodeDB->updateUser(getFrom(&mp), requester, mp.channel);
}
logAction("respond", &mp, "nodeinfo-cache");
incrementStat(&stats.nodeinfo_cache_hits);
ignoreRequest = true; // We responded; suppress default NAK
return ProcessMessage::STOP; // Consumed - request will not be forwarded
}
}
// -------------------------------------------------------------------------
// Position Deduplication
// -------------------------------------------------------------------------
// Drop position broadcasts that haven't moved significantly since the
// last broadcast from this node. Uses truncated coordinates to ignore
// GPS jitter within the configured precision.
if (!isFromUs(&mp) && !isToUs(&mp)) {
if (channels.isWellKnownChannel(mp.channel) && mp.decoded.portnum == meshtastic_PortNum_POSITION_APP) {
meshtastic_Position pos = meshtastic_Position_init_zero;
if (pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, &meshtastic_Position_msg, &pos)) {
if (shouldDropPosition(&mp, &pos, nowMs)) {
logAction("drop", &mp, "position-dedup");
incrementStat(&stats.position_dedup_drops);
ignoreRequest = true; // Suppress NAK
return ProcessMessage::STOP; // Consumed - duplicate will not be rebroadcast
}
}
}
// ---------------------------------------------------------------------
// Rate Limiting
// ---------------------------------------------------------------------
// Throttle nodes sending too many packets within a time window.
// Excludes routing and admin packets which are essential for mesh operation.
if (cfg.rate_limit_window_secs > 0 && cfg.rate_limit_max_packets > 0) {
if (mp.decoded.portnum != meshtastic_PortNum_ROUTING_APP && mp.decoded.portnum != meshtastic_PortNum_ADMIN_APP) {
if (isRateLimited(mp.from, nowMs)) {
logAction("drop", &mp, "rate-limit");
incrementStat(&stats.rate_limit_drops);
ignoreRequest = true; // Suppress NAK
return ProcessMessage::STOP; // Consumed - throttled packet will not be rebroadcast
}
}
}
}
return ProcessMessage::CONTINUE;
}
void TrafficManagementModule::alterReceived(meshtastic_MeshPacket &mp)
{
if (!moduleConfig.has_traffic_management)
return;
if (mp.which_payload_variant != meshtastic_MeshPacket_decoded_tag)
return;
if (isFromUs(&mp))
return;
// exhaust_hop_telemetry / exhaust_hop_position / router_preserve_hops:
// not suitable right now - the right heuristics for when to exhaust or
// preserve hops need more field data before we expose them as config knobs.
// exhaustRequested stays false; perhapsRebroadcast() behaves normally.
const bool isPosition = mp.decoded.portnum == meshtastic_PortNum_POSITION_APP;
// -------------------------------------------------------------------------
// Relayed Position Precision Clamp
// -------------------------------------------------------------------------
// Clamp relayed position broadcasts to the channel's configured precision
// ceiling. Guards against forwarding more-precise coordinates than the
// channel is intended to carry (e.g. a LongFast channel set to 13-bit /
// ~1.5 km). chanPrec==0 means position sharing is disabled on the channel;
// skip - not our job to zero positions on relay.
// Ham mode (owner.is_licensed) is exempt. Lost-and-found is NOT exempt - its relayed
// positions get the same precision clamp as any node.
// Compile USERPREFS_TMM_APPLY_TO_PRIVATE_CHANNELS to extend to private channels.
if (!owner.is_licensed && isPosition && isBroadcast(mp.to)) {
#ifdef USERPREFS_TMM_APPLY_TO_PRIVATE_CHANNELS
const bool shouldClamp = true;
#else
const bool shouldClamp = channels.isWellKnownChannel(mp.channel);
#endif
if (shouldClamp) {
const uint32_t chanPrec = getPositionPrecisionForChannel(mp.channel);
if (chanPrec > 0) {
meshtastic_Position pos = meshtastic_Position_init_default;
if (pb_decode_from_bytes(mp.decoded.payload.bytes, mp.decoded.payload.size, &meshtastic_Position_msg, &pos)) {
const uint32_t packetPrec = pos.precision_bits > 0 ? pos.precision_bits : 32u;
if (packetPrec > chanPrec) {
applyPositionPrecision(pos, chanPrec);
mp.decoded.payload.size = pb_encode_to_bytes(mp.decoded.payload.bytes, sizeof(mp.decoded.payload.bytes),
&meshtastic_Position_msg, &pos);
logAction("clamp", &mp, "precision");
}
}
}
}
}
}
// =============================================================================
// Periodic Maintenance
// =============================================================================
int32_t TrafficManagementModule::runOnce()
{
if (!moduleConfig.has_traffic_management)
return INT32_MAX;
#if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
const uint32_t nowMs = TrafficManagementModule::clockMs();
// Warm-start the next-hop cache from persisted NodeInfoLite hints once nodeDB
// is populated. Done here (not in the constructor) so nodeDB has finished
// loading. Takes its own lock, so call before acquiring the sweep guard below.
// Only latch the one-shot guard once the preload actually ran; if nodeDB wasn't
// ready yet, retry on the next maintenance pass instead of skipping it forever.
if (!nextHopPreloaded && preloadNextHopsFromNodeDB())
nextHopPreloaded = true;
// Free-running tick counters (no epoch needed).
// TTL expressed in ticks:
// pos: 4× position_min_interval_secs (clamped to 255 ticks @ 6 min/tick)
// rate: 2× rate_limit_window_secs (clamped to 15 ticks @ 5 min/tick; only relevant when rate limits are configured)
// unknown: fixed 12 ticks @ 1 min/tick (only relevant when unknown_packet_threshold > 0)
const uint32_t positionIntervalMs = secsToMs(Default::getConfiguredOrDefault(
moduleConfig.traffic_management.position_min_interval_secs, default_traffic_mgmt_position_min_interval_secs));
const uint8_t posTtlTicks =
static_cast<uint8_t>(std::min(static_cast<uint32_t>(255), (positionIntervalMs * 4) / kPosTimeTickMs));
const uint32_t rateWindowMs = secsToMs(moduleConfig.traffic_management.rate_limit_window_secs);
const uint8_t rateTtlTicks = static_cast<uint8_t>(
std::min(static_cast<uint32_t>(15), (rateWindowMs > 0 ? rateWindowMs * 2 : 24 * kRateTimeTickMs) / kRateTimeTickMs));
// unknown: fixed 12-tick TTL (12 min - 4 ticks past the 5-min default window)
const uint8_t unknownTtlTicks = 12;
const uint8_t nowPosTick = currentPosTick();
const uint8_t nowRateTick = currentRateTick();
const uint8_t nowUnknownTick = currentUnknownTick();
// Sweep cache and clear expired entries
uint16_t activeEntries = 0;
uint16_t expiredEntries = 0;
const uint32_t sweepStartMs = TrafficManagementModule::clockMs();
const auto &cfg = moduleConfig.traffic_management;
concurrency::LockGuard guard(&cacheLock);
for (uint16_t i = 0; i < cacheSize(); i++) {
if (cache[i].node == 0)
continue;
bool anyValid = false;
// Check and clear expired position data (presence: pos_fingerprint != 0)
if (cache[i].pos_fingerprint != 0) {
if (static_cast<uint8_t>(nowPosTick - cache[i].pos_time) >= posTtlTicks) {
cache[i].pos_fingerprint = 0;
cache[i].pos_time = 0;
} else {
anyValid = true;
}
}
// Check and clear expired rate limit data (presence: getRateCount() != 0)
if (cache[i].getRateCount() != 0) {
if ((static_cast<uint8_t>(nowRateTick - cache[i].getRateTime()) & 0x0F) >= rateTtlTicks) {
cache[i].setRateCount(0);
cache[i].setRateTime(0);
} else {
anyValid = true;
}
}
// Check and clear expired unknown tracking data (presence: getUnknownCount() != 0)
if (cache[i].getUnknownCount() != 0) {
if ((static_cast<uint8_t>(nowUnknownTick - cache[i].getUnknownTime()) & 0x0F) >= unknownTtlTicks) {
cache[i].setUnknownCount(0);
cache[i].setUnknownTime(0);
} else {
anyValid = true;
}
}
// Two fields have no TTL of their own and pin the slot, so they outlive the
// dedup/rate/unknown state:
// - a confirmed next-hop hint (the routing overflow store), and
// - a cached special (non-CLIENT) role, so a tracker / lost-and-found / router
// keeps its dedup-window exception across quiet periods rather than reverting
// to CLIENT the moment its timed state expires.
if (cache[i].next_hop != 0 || cache[i].getCachedRole() != meshtastic_Config_DeviceConfig_Role_CLIENT)
anyValid = true;
// If all data expired, free the slot entirely
if (!anyValid) {
memset(&cache[i], 0, sizeof(UnifiedCacheEntry));
expiredEntries++;
} else {
activeEntries++;
}
}
TM_LOG_DEBUG("Maintenance: %u active, %u expired, %u/%u slots, %lums elapsed", activeEntries, expiredEntries,
static_cast<unsigned>(activeEntries), static_cast<unsigned>(cacheSize()),
static_cast<unsigned long>(TrafficManagementModule::clockMs() - sweepStartMs));
#if defined(ARCH_ESP32) && defined(BOARD_HAS_PSRAM)
if (nodeInfoPayload) {
TM_LOG_DEBUG("NodeInfo PSRAM cache: %u/%u", static_cast<unsigned>(countNodeInfoEntriesLocked()),
static_cast<unsigned>(nodeInfoTargetEntries()));
}
#endif
#endif // TRAFFIC_MANAGEMENT_CACHE_SIZE > 0
return kMaintenanceIntervalMs;
}
// =============================================================================
// Traffic Management Logic
// =============================================================================
bool TrafficManagementModule::shouldDropPosition(const meshtastic_MeshPacket *p, const meshtastic_Position *pos, uint32_t nowMs)
{
#if TRAFFIC_MANAGEMENT_CACHE_SIZE == 0
(void)p;
(void)pos;
(void)nowMs;
return false;
#else
if (!pos->has_latitude_i || !pos->has_longitude_i)
return false;
// Precision is driven by the channel's own position_precision ceiling - the same
// grid the channel uses for broadcast. Falls back to the firmware default (19-bit,
// ~90m cells) when the channel has no precision configured (chanPrec == 0).
const uint32_t chanPrec = getPositionPrecisionForChannel(p->channel);
uint8_t precision = sanitizePositionPrecision(
chanPrec > 0 ? static_cast<uint8_t>(chanPrec) : static_cast<uint8_t>(default_traffic_mgmt_position_precision_bits));
const int32_t lat_truncated = truncateCoordinate(pos->latitude_i, precision);
const int32_t lon_truncated = truncateCoordinate(pos->longitude_i, precision);
const uint8_t fingerprint = computePositionFingerprint(lat_truncated, lon_truncated, precision);
// Drop gate uses the RAW configured interval: 0 means "dedup disabled" (the
// contract documented below). The 12h default is only for resolution/TTL
// sizing (constructor / runOnce), not for deciding whether to drop - feeding
// the default here would silently turn the 0-disables-dedup contract off.
uint32_t minIntervalMs = secsToMs(moduleConfig.traffic_management.position_min_interval_secs);