-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMeshmingle-Heltec_Lora_32_V3.ino
2832 lines (2565 loc) · 101 KB
/
Meshmingle-Heltec_Lora_32_V3.ino
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
//Test v1.00.030
//27-02-2025
//
//YOU MUST UPDATE ALL YOUR NODES FROM LAST VERSION OR YOU WONT SEE RELAYS ANYMORE!!!!!
//
//MAKE SURE ALL NODES USE THE SAME VERSION OR EXPECT STRANGE THINGS HAPPENING.
//EU868 Band P (869.4 MHz - 869.65 MHz): 10%, 500 mW ERP (10% 24hr 8640 seconds = 6 mins per hour TX Time.)
//After Accounting for Heartbeats: 20 sec after boot then every 15 mins thereafter.
//Per Hour: 136 Max Char messages within the 6-minute (360,000 ms) duty cycle
//Per Day: 3,296 Max Char messages within the 8,640,000 ms (10% duty cycle) allowance
////////////////////////////////////////////////////////////////////////
// M M EEEEE SSSSS H H M M I N N GGGGG L EEEEE //
// MM MM E S H H MM MM I NN N G L E //
// M MM M EEEE SSSSS HHHHH M MM M I N N N G GG L EEEE //
// M M E S H H M M I N NN G G L E //
// M M EEEEE SSSSS H H M M I N N GGG LLLLL EEEEE //
////////////////////////////////////////////////////////////////////////
//
// Uncomment the line below to enable Heltec V3.2 specific code.
//
#define HELTEC_V3_2
//
// If not defined, we assume Heltec V3.
#ifndef HELTEC_V3_2
#endif
//
#define RADIOLIB_SX1262
#define HELTEC_POWER_BUTTON // Use the power button feature of Heltec
#include <heltec_unofficial.h> // 0.9.2 Heltec library for OLED and LoRa
#include <painlessMesh.h> //1.5.4
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <DNSServer.h>
#include <Wire.h>
#include <esp_task_wdt.h> // Watchdog timer library
#include <vector> // For handling list of messages and our queue
#include <map> // For unified retransmission tracking
#include <RadioLib.h> //7.1.2
#include <set> // Used for node id count checking all 3 sources of nodes. i.e wifi, direct lora, indirect lora. now add to total node count.
// Meshmingle Parameters
#define MESH_SSID "meshmingle.co.uk"
#define MESH_PASSWORD "" //WARNING!! If you have set this and then unset it and reflash you must do FULL ERASE FIRST.
#define MESH_PORT 5555
// LoRa Parameters
#define PAUSE 5400000 //Required timeout Time for dutycycle (54 Min)
#define FREQUENCY 869.4000 //We are currently using an EU868 Lora Frequency that requires the full band 869.4000 - 869.6500 only single channel use supported for now.
#define BANDWIDTH 250.0
#define SPREADING_FACTOR 11
#define TRANSMIT_POWER 22 //This is max power for This Boards EU868 Config.
#define CODING_RATE 8
// Some Global Variables
bool enableRxBoost = true; //enable or disable RX Boost Mode
bool sendAggregatedHeartbeats = false; //0 hop nodelist sharing. Theres issues with this right now!!!!
bool bypassDutyCycle = false; // Enable or Disable DutyCycle (For Non EU Use ONLY!!!)
// ---------------------------------------------------------------------
// NEW: Define an enum to track the origin of each message
// ---------------------------------------------------------------------
enum OriginChannel {
ORIGIN_UNKNOWN,
ORIGIN_WIFI,
ORIGIN_LORA
};
// ===================
// TRANSMISSION TRACKING
// ===================
struct TransmissionStatus {
bool transmittedViaWiFi = false;
bool transmittedViaLoRa = false;
bool addedToMessages = false; // Flag to track if the message has been added to messages vector
bool relayedViaWiFi = false; // NEW: whether the message has been relayed via WiFi
bool relayedViaLoRa = false; // NEW: whether the message has been relayed via LoRa
bool queuedForLoRa = false; // NEW: whether the message is already queued for LoRa transmission
bool relayRetryAttempted = false; // NEW: whether a retry has already been attempted
bool pendingWiFiRelay = false; // NEW: flag to indicate WiFi relay pending after LoRa finishes
OriginChannel origin = ORIGIN_UNKNOWN; // NEW: track the origin (WiFi vs LoRa) of this message
uint64_t timestamp = millis(); // record when the entry was created/updated
};
// Map to track transmissions by message ID
std::map<String, TransmissionStatus> messageTransmissions;
// ---------------------------------------------------------------------
// NEW: Relay Log Definitions
// ---------------------------------------------------------------------
struct RelayLogEntry {
String relayID;
uint64_t timestamp;
};
// Global relay log: maps messageID to a vector of relay log entries.
std::map<String, std::vector<RelayLogEntry>> relayLog;
String rxdata;
// Global RX flag
volatile bool rxFlag = false;
long counter = 0;
uint64_t tx_time;
uint64_t last_tx = 0;
uint64_t minimum_pause = 0;
unsigned long lastTransmitTime = 0;
// Timeout for pending transmissions (e.g. 5 minutes)
const unsigned long pendingTxTimeout = 150000; // 150,000 ms = 2.5 minutes
// Retain transmission history for 24 hours
const unsigned long transmissionHistoryRetention = 86400000; // 86,400,000 ms = 24 hours
// Instead of a single message buffer, we now use a queue for outgoing LoRa messages.
std::vector<String> loraTransmissionQueue;
// Aggregated Heartbeat Interval: 31 minutes (31 * 60 * 1000 = 1,860,000 ms)
const unsigned long aggregatedHeartbeatInterval = 1860000;
unsigned long lastAggregatedHeartbeatTime = 0;
// Define a constant for the direct node timeout (16 minutes)
const uint64_t DIRECT_NODE_TIMEOUT = 16UL * 60UL * 1000UL; // 16 minutes in milliseconds
// Duty Cycle Definitions and Variables
#define DUTY_CYCLE_LIMIT_MS 360000 // 6 minutes in a 60-minute window
#define DUTY_CYCLE_WINDOW 3600000 // 60 minutes in milliseconds
uint64_t cumulativeTxTime = 0;
uint64_t dutyCycleStartTime = 0;
void resetDutyCycle() {
cumulativeTxTime = 0;
dutyCycleStartTime = millis();
Serial.println("[Duty Cycle] Reset duty cycle counter.");
}
void calculateDutyCyclePause(uint64_t tx_time) {
cumulativeTxTime += tx_time;
if (millis() - dutyCycleStartTime >= DUTY_CYCLE_WINDOW) {
resetDutyCycle();
}
if (cumulativeTxTime >= DUTY_CYCLE_LIMIT_MS) {
minimum_pause = DUTY_CYCLE_WINDOW - (millis() - dutyCycleStartTime);
if (minimum_pause < 0) minimum_pause = 0;
Serial.printf("[Duty Cycle] Duty cycle limit reached, waiting for %llu ms.\n", minimum_pause);
} else {
minimum_pause = 0;
Serial.printf("[Duty Cycle] Duty cycle time used: %llu ms.\n", cumulativeTxTime);
}
}
const int maxMessages = 50;
// Duty Cycle Variables
bool dutyCycleActive = false;
bool lastDutyCycleActive = false;
AsyncWebServer server(80);
DNSServer dnsServer;
painlessMesh mesh;
// --- Updated Message structure with a new recipient field ---
// NEW: Added relayIDs vector to hold all relay IDs for our own message.
struct Message {
String nodeId; // originator node ID
String sender;
String recipient; // target node (or "ALL" for public messages)
String content;
String source; // e.g., "[WiFi]" or "[LoRa]"
String messageID;
String relayID;
std::vector<String> relayIDs; // NEW: List of relay IDs for our own message
int rssi;
float snr;
uint64_t timeReceived;
};
std::vector<Message> messages;
int totalNodeCount = 0; // <-- now holds the WiFi (mesh) count only
uint32_t currentNodeId = 0;
unsigned long loRaTransmitDelay = 0;
unsigned long messageCounter = 0;
// Global jitter offset (derived from chip ID) used for all random delays
uint32_t global_jitter_offset = 0;
// New global: (we no longer solely rely on global lastRxRSSI for relayed messages)
// Returns a custom formatted node id, for example: "!Mxxxxxx"
String getCustomNodeId(uint32_t nodeId) {
String hexNodeId = String(nodeId, HEX);
while (hexNodeId.length() < 6) {
hexNodeId = "0" + hexNodeId;
}
if (hexNodeId.length() > 6) {
hexNodeId = hexNodeId.substring(hexNodeId.length() - 6);
}
return "!M" + hexNodeId;
}
String generateMessageID(const String& nodeId) {
messageCounter++;
return nodeId + ":" + String(messageCounter);
}
uint16_t crc16_ccitt(const uint8_t *buf, size_t len) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < len; i++) {
crc ^= (uint16_t)buf[i] << 8;
for (uint8_t j = 0; j < 8; j++) {
if (crc & 0x8000)
crc = (crc << 1) ^ 0x1021;
else
crc <<= 1;
}
}
return crc;
}
// --- Updated constructMessage() to include the recipient field ---
// The message format is now:
// messageID|originatorID|sender|recipient|content|relayID|CRC
String constructMessage(const String& messageID, const String& originatorID, const String& sender, const String& recipient, const String& content, const String& relayID) {
String messageWithoutCRC = messageID + "|" + originatorID + "|" + sender + "|" + recipient + "|" + content + "|" + relayID;
uint16_t crc = crc16_ccitt((const uint8_t *)messageWithoutCRC.c_str(), messageWithoutCRC.length());
char crcStr[5];
sprintf(crcStr, "%04X", crc);
String fullMessage = messageWithoutCRC + "|" + String(crcStr);
return fullMessage;
}
// --- METRICS HISTORY CHANGES ---
struct NodeMetricsSample {
uint64_t timestamp;
int rssi;
float snr;
};
struct LoRaNode {
String nodeId;
int lastRSSI;
float lastSNR;
uint64_t lastSeen;
std::vector<NodeMetricsSample> history;
String statusEmoji; // NEW: Holds the emoji for this node
};
// Global container for direct LoRa nodes
std::map<String, LoRaNode> loraNodes;
// --- NEW: Structure for Indirect Nodes ---
// (Modified to include a history vector.)
struct IndirectNode {
String originatorId; // The node that originally sent the message (which we never hear directly)
String relayId; // The node that relayed the message to us
int rssi; // RSSI as measured from the relay’s transmission
float snr; // SNR as measured from the relay’s transmission
uint64_t lastSeen; // Timestamp when we last received a relayed message from this originator via the relay
String statusEmoji; // NEW: Holds the emoji for this indirect node
std::vector<NodeMetricsSample> history; // NEW: History samples (up to 24 hours)
};
// Global container to hold indirect nodes keyed by a composite key (originatorID-relayID)
std::map<String, IndirectNode> indirectNodes;
unsigned long lastCleanupTime = 0;
const unsigned long cleanupInterval = 60000; // 1 minute
uint32_t getNodeId() {
return currentNodeId;
}
void cleanupLoRaNodes() {
uint64_t currentTime = millis();
const uint64_t timeout = 86400000; // 24 hours
for (auto it = loraNodes.begin(); it != loraNodes.end();) {
if (currentTime - it->second.lastSeen > timeout) {
Serial.printf("[LoRa Nodes] Removing inactive LoRa node: %s\n", it->first.c_str());
it = loraNodes.erase(it);
} else {
++it;
}
}
}
// --- NEW: Cleanup function for Indirect Nodes ---
void cleanupIndirectNodes() {
uint64_t currentTime = millis();
const uint64_t timeout = 86400000; // 24 hours
for (auto it = indirectNodes.begin(); it != indirectNodes.end();) {
if (currentTime - it->second.lastSeen > timeout) {
Serial.printf("[Indirect Nodes] Removing inactive indirect node: %s\n", it->first.c_str());
it = indirectNodes.erase(it);
} else {
++it;
}
}
}
void cleanupPendingTxQueue() {
unsigned long now = millis();
// Iterate over the queue in reverse order so we can remove items safely.
for (int i = loraTransmissionQueue.size() - 1; i >= 0; i--) {
String message = loraTransmissionQueue[i];
// Extract messageID from the message (assuming the format "messageID|...")
int separatorIndex = message.indexOf('|');
if (separatorIndex == -1) continue;
String messageID = message.substring(0, separatorIndex);
// Look up the transmission status for this message
auto it = messageTransmissions.find(messageID);
if (it != messageTransmissions.end()) {
// Remove from queue if the message is already relayed...
// OR if it has been pending longer than pendingTxTimeout.
if (it->second.relayedViaLoRa || (now - it->second.timestamp > pendingTxTimeout)) {
Serial.printf("[Cleanup] Removing pending message %s from queue (stale or already relayed).\n", messageID.c_str());
loraTransmissionQueue.erase(loraTransmissionQueue.begin() + i);
// Reset the queued flag so that future scheduling is possible.
it->second.queuedForLoRa = false;
}
} else {
// If we have no record for this message, remove it.
loraTransmissionQueue.erase(loraTransmissionQueue.begin() + i);
}
}
}
void cleanupTransmissionHistory() {
unsigned long now = millis();
for (auto it = messageTransmissions.begin(); it != messageTransmissions.end(); ) {
if (now - it->second.timestamp > transmissionHistoryRetention) {
Serial.printf("[Cleanup] Removing transmission history for message %s (older than 24 hrs).\n", it->first.c_str());
it = messageTransmissions.erase(it);
} else {
++it;
}
}
}
// --- Helper functions for dynamic slot calculation ---
// getTxDuration: returns the measured TX duration in ms; if not available, returns preset 3000 ms.
unsigned long getTxDuration(String message) {
// For now, we simply return 3000. (You can modify this function to compute based on message length.)
return 3000;
}
// getDynamicSlot: computes the slot duration as baseSlot plus an offset derived from RSSI.
// Here we map RSSI (from -120 to -50) to an offset from 0 to 500 ms.
unsigned long getDynamicSlot(unsigned long baseSlot, int rssi) {
if (baseSlot == 0) baseSlot = 3000; // default if not available
if (rssi < -180) rssi = -180;
if (rssi > -15) rssi = -15;
int rssiOffset = map(rssi, -180, -15, 0, 4000);
return baseSlot + rssiOffset;
}
// --- UPDATED addMessage() to accept the recipient and only add private messages if intended ---
// Also, for messages originating from our node, update the relay info and store each unique relayID.
void addMessage(const String& nodeId, const String& messageID, const String& sender,
const String& recipient, String content, const String& source,
const String& relayID, int rssi = 0, float snr = 0.0) {
const int maxMessageLength = 150;
if (content.length() > maxMessageLength) {
Serial.println("Message too long, truncating...");
content = content.substring(0, maxMessageLength);
}
auto& status = messageTransmissions[messageID];
// Early exit if message already processed.
if (status.addedToMessages) {
// Optionally update relayIDs if needed
if (source == "[LoRa]") {
// For our own message, if we get a new relayID different from our own, update relayIDs.
String myId = getCustomNodeId(getNodeId());
for (auto &msg : messages) {
if (msg.messageID == messageID) {
if (msg.nodeId == myId && relayID != myId) {
bool exists = false;
for (auto &id : msg.relayIDs) {
if (id == relayID) { exists = true; break; }
}
if (!exists) {
Serial.printf("Updating our message %s with relay info from %s\n", messageID.c_str(), relayID.c_str());
msg.relayIDs.push_back(relayID);
}
}
// Also, if a message received via WiFi now comes with LoRa details, update them.
if (source == "[LoRa]" && msg.source != "[LoRa]") {
Serial.printf("Updating message %s from WiFi to LoRa details\n", messageID.c_str());
msg.source = "[LoRa]";
msg.rssi = rssi;
msg.snr = snr;
msg.relayID = relayID;
}
break;
}
}
}
return;
}
// For private messages (recipient != "ALL") only add if this node is either the originator or the designated recipient.
String myId = getCustomNodeId(getNodeId());
if (recipient != "ALL" && myId != nodeId && myId != recipient) {
Serial.println("Private message not for me, skipping local addition.");
return;
}
String finalSource = "";
if (nodeId != myId) {
finalSource = source;
}
Message newMessage = {
nodeId,
sender,
recipient,
content,
finalSource,
messageID,
relayID,
std::vector<String>(), // Initialize relayIDs as empty
rssi,
snr,
millis()
};
// Insert the new message at the beginning of the list.
messages.insert(messages.begin(), newMessage);
status.addedToMessages = true;
// Trim the messages vector if it exceeds our maximum.
if (messages.size() > maxMessages) {
messages.pop_back();
}
Serial.printf("Message added: NodeID: %s, Sender: %s, Recipient: %s, Content: %s, Source: %s, ID: %s, RelayID: %s\n",
nodeId.c_str(), sender.c_str(), recipient.c_str(), content.c_str(),
finalSource.c_str(), messageID.c_str(), relayID.c_str());
}
// --- TX History Logging ---
// NEW: Structure and global vector to store TX history.
struct TxHistoryEntry {
uint64_t timestamp;
String type; // Emoji: "❤️" for heartbeat, "📡" for agg heartbeat, "⌨️" for our message, "🛰️" for relayed, "💬" for private message
uint64_t txTime; // in ms
bool success;
};
std::vector<TxHistoryEntry> txHistory;
// --- Helper: Determine TX type from message ---
String determineTxType(const String &message) {
if (message.startsWith("AGG_HEARTBEAT|")) {
return "📡";
} else if (message.startsWith("HEARTBEAT|")) {
return "❤️";
} else {
int pos1 = message.indexOf('|');
int pos2 = message.indexOf('|', pos1 + 1);
int pos3 = message.indexOf('|', pos2 + 1);
int pos4 = message.indexOf('|', pos3 + 1);
if (pos1 == -1 || pos2 == -1 || pos3 == -1 || pos4 == -1) {
return "❓";
}
String originatorID = message.substring(pos1 + 1, pos2);
String recipient = message.substring(pos3 + 1, pos4);
String myId = getCustomNodeId(getNodeId());
bool isPrivate = (recipient != "ALL");
if (isPrivate) {
if (originatorID == myId) {
return "⌨️💬";
} else {
return "🛰️💬";
}
} else {
if (originatorID == myId) {
return "⌨️";
} else {
return "🛰️";
}
}
}
}
// --- scheduleLoRaTransmission() updated to parse 6 fields ---
// Expected format: messageID|originatorID|sender|recipient|content|relayID|CRC
// Modified to take an additional parameter measuredRssi (default -100) so that for relayed messages we can use the measured RX RSSI.
void scheduleLoRaTransmission(String message, int measuredRssi = -100) {
int lastSeparator = message.lastIndexOf('|');
if (lastSeparator == -1) {
Serial.println("[LoRa Schedule] Invalid format (no CRC).");
return;
}
// Extract and validate the CRC.
String crcStr = message.substring(lastSeparator + 1);
String messageWithoutCRC = message.substring(0, lastSeparator);
uint16_t receivedCRC = (uint16_t)strtol(crcStr.c_str(), NULL, 16);
uint16_t computedCRC = crc16_ccitt((const uint8_t *)messageWithoutCRC.c_str(), messageWithoutCRC.length());
if (receivedCRC != computedCRC) {
Serial.printf("[LoRa Schedule] CRC mismatch. Received: %04X, Computed: %04X\n", receivedCRC, computedCRC);
return;
}
// Parse the message fields.
int firstSeparator = messageWithoutCRC.indexOf('|');
int secondSeparator = messageWithoutCRC.indexOf('|', firstSeparator + 1);
int thirdSeparator = messageWithoutCRC.indexOf('|', secondSeparator + 1);
int fourthSeparator = messageWithoutCRC.indexOf('|', thirdSeparator + 1);
int fifthSeparator = messageWithoutCRC.indexOf('|', fourthSeparator + 1);
if (firstSeparator == -1 || secondSeparator == -1 || thirdSeparator == -1 ||
fourthSeparator == -1 || fifthSeparator == -1) {
Serial.println("[LoRa Schedule] Invalid message format.");
return;
}
String messageID = messageWithoutCRC.substring(0, firstSeparator);
String originatorID = messageWithoutCRC.substring(firstSeparator + 1, secondSeparator);
String senderID = messageWithoutCRC.substring(secondSeparator + 1, thirdSeparator);
String recipientID = messageWithoutCRC.substring(thirdSeparator + 1, fourthSeparator);
String messageContent = messageWithoutCRC.substring(fourthSeparator + 1, fifthSeparator);
String relayID = messageWithoutCRC.substring(fifthSeparator + 1);
String myId = getCustomNodeId(getNodeId());
// If this is a private message that has reached its recipient, don't relay.
if (recipientID != "ALL" && myId == recipientID) {
Serial.println("[LoRa Schedule] Private message reached its recipient. Not scheduling retransmission.");
return;
}
auto &status = messageTransmissions[messageID];
if (status.queuedForLoRa) {
Serial.println("[LoRa Schedule] Message already queued for LoRa, skipping...");
return;
}
// Check if the message is originating from our own node.
bool isOwnMessage = (originatorID == myId);
if (!isOwnMessage) {
String newRelayID = myId;
String updatedMessage = constructMessage(messageID, originatorID, senderID, recipientID, messageContent, newRelayID);
loraTransmissionQueue.push_back(updatedMessage);
status.queuedForLoRa = true;
// Calculate dynamic slot:
unsigned long baseSlot = getTxDuration(message); // default returns 3000 ms
unsigned long dynamicSlot = getDynamicSlot(baseSlot, measuredRssi);
unsigned long totalWindow = 35000; // 35 seconds total window
int numSlots = totalWindow / dynamicSlot;
if(numSlots < 1) numSlots = 1;
int randomSlot = random(1, numSlots + 1);
loRaTransmitDelay = millis() + (randomSlot * dynamicSlot);
Serial.printf("[LoRa Schedule] Scheduled relay with dynamic slot: baseSlot=%lu, dynamicSlot=%lu, randomSlot=%d, delay=%lu ms: %s\n",
baseSlot, dynamicSlot, randomSlot, randomSlot * dynamicSlot, updatedMessage.c_str());
} else {
// For our own original message, keep the fixed 2-second delay.
loraTransmissionQueue.push_back(message);
status.queuedForLoRa = true;
loRaTransmitDelay = millis() + 2000;
Serial.printf("[LoRa Schedule] Scheduled original message with fixed 2-second delay: %s\n",
message.c_str());
}
}
void transmitViaWiFi(const String& message) {
// Early exit if already transmitted via WiFi.
int separatorIndex = message.indexOf('|');
if (separatorIndex == -1) {
Serial.println("[WiFi Tx] Invalid format.");
return;
}
String messageID = message.substring(0, separatorIndex);
auto& status = messageTransmissions[messageID];
if (status.transmittedViaWiFi) {
Serial.println("[WiFi Tx] Already sent via WiFi, skipping...");
return;
}
// Mark as transmitted via WiFi immediately.
status.transmittedViaWiFi = true;
mesh.sendBroadcast(message);
Serial.printf("[WiFi Tx] Sent: %s\n", message.c_str());
}
bool isDutyCycleAllowed() {
if (bypassDutyCycle) {
dutyCycleActive = false;
return true;
}
if (millis() > last_tx + minimum_pause) {
dutyCycleActive = false;
} else {
dutyCycleActive = true;
}
return !dutyCycleActive;
}
// ----------------------------------------------------------------------------
// CAROUSEL CHANGES: Global variables for the carousel
// ----------------------------------------------------------------------------
unsigned long lastCarouselChange = 0;
const unsigned long carouselInterval = 3000; // 3 seconds each screen
int carouselIndex = 0;
long lastTxTimeMillis = -1; // store last LoRa Tx time for the display
void drawMonospacedLine(int16_t x, int16_t y, const String &line, int charWidth = 7) {
for (uint16_t i = 0; i < line.length(); i++) {
display.drawString(x + i * charWidth, y, String(line[i]));
}
}
void showScrollingMonospacedAsciiArt() {
display.clear();
display.setFont(ArialMT_Plain_10);
String lines[5];
lines[0] = "M M EEEEE SSSSS H H M M I N N GGGGG L EEEEE ";
lines[1] = "MM MM E S H H MM MM I NN N G L E ";
lines[2] = "M MM M EEEE SSSSS HHHHH M MM M I N N N G GG L EEEE ";
lines[3] = "M M E S H H M M I N NN G G L E ";
lines[4] = "M M EEEEE SSSSS H H M M I N N GGG LLLLL EEEEE ";
const int screenWidth = 128;
const int screenHeight = 64;
const int lineHeight = 10;
const int totalBlockHeight = 5 * lineHeight;
int verticalOffset = (screenHeight - totalBlockHeight) / 2;
int charWidth = 7;
uint16_t maxChars = 0;
for (int i = 0; i < 5; i++) {
if (lines[i].length() > maxChars) {
maxChars = lines[i].length();
}
}
int totalBlockWidth = maxChars * charWidth;
if (totalBlockWidth <= screenWidth) {
int offsetX = (screenWidth - totalBlockWidth) / 2;
for (int i = 0; i < 5; i++) {
drawMonospacedLine(offsetX, verticalOffset + i * lineHeight, lines[i], charWidth);
}
display.display();
delay(3000);
return;
}
const int blankStart = 20;
const int blankEnd = 20;
for (int offset = -blankStart; offset <= (totalBlockWidth + screenWidth + blankEnd); offset += 2) {
display.clear();
for (int i = 0; i < 5; i++) {
drawMonospacedLine(-offset, verticalOffset + i * lineHeight, lines[i], charWidth);
}
display.display();
delay(30);
}
}
void drawMainScreen(long txTimeMillis = -1) {
if (txTimeMillis >= 0) {
lastTxTimeMillis = txTimeMillis;
}
display.clear();
display.setFont(ArialMT_Plain_10);
int16_t titleWidth = display.getStringWidth("Meshmingle 1.0");
display.drawString((128 - titleWidth) / 2, 0, "Meshmingle 1.0");
display.drawString(0, 13, "Node ID: " + getCustomNodeId(getNodeId()));
uint64_t currentTime = millis();
int activeDirectLoRaNodes = 0;
const uint64_t DIRECT_TIMEOUT = 900000; // 15 minutes
for (const auto& node : loraNodes) {
if (currentTime - node.second.lastSeen <= DIRECT_TIMEOUT) {
activeDirectLoRaNodes++;
}
}
int totalActiveLoRaNodes = activeDirectLoRaNodes;
int wifiCount = totalNodeCount;
String combinedNodes = "WiFi Nodes: " + String(wifiCount) + " LoRa: " + String(totalActiveLoRaNodes);
int16_t combinedWidth = display.getStringWidth(combinedNodes);
if (combinedWidth > 128) {
combinedNodes = "WiFi: " + String(wifiCount) + " LoRa: " + String(totalActiveLoRaNodes);
}
display.drawString(0, 27, combinedNodes);
if (dutyCycleActive) {
display.drawString(0, 40, "Duty Cycle Limit Reached!");
} else {
display.drawString(0, 40, "LoRa Tx Allowed");
}
if (lastTxTimeMillis >= 0) {
String txMessage = "TxOK (" + String(lastTxTimeMillis) + " ms)";
int16_t txMessageWidth = display.getStringWidth(txMessage);
display.drawString((128 - txMessageWidth) / 2, 54, txMessage);
}
display.display();
}
void displayCarousel() {
unsigned long currentMillis = millis();
if (currentMillis - lastCarouselChange >= carouselInterval) {
lastCarouselChange = currentMillis;
String myId = getCustomNodeId(getNodeId());
std::vector<Message> filteredMessages;
for (const auto& msg : messages) {
if (msg.recipient != "ALL" && (msg.recipient == myId || msg.nodeId == myId)) {
filteredMessages.push_back(msg);
}
}
if (filteredMessages.empty()) {
carouselIndex = 0;
} else {
carouselIndex++;
if (carouselIndex > (int)filteredMessages.size()) {
carouselIndex = 0;
}
}
display.clear();
display.setFont(ArialMT_Plain_10);
if (carouselIndex == 0) {
drawMainScreen(-1);
} else {
int msgIndex = carouselIndex - 1;
if (msgIndex < (int)filteredMessages.size()) {
String nodeLine = "Node: " + filteredMessages[msgIndex].nodeId;
display.drawString(0, 0, nodeLine);
String nameLine = "Name: " + filteredMessages[msgIndex].sender;
display.drawString(0, 13, nameLine);
display.drawString(0, 26, "[Private]");
display.drawString(0, 36, filteredMessages[msgIndex].content);
}
}
display.display();
}
}
long lastTxTimeMillisVar = -1;
void transmitWithDutyCycle(const String& message) {
if (!isDutyCycleAllowed()) {
Serial.printf("[LoRa Tx] Duty cycle active. Delaying transmission for %llu ms.\n", minimum_pause);
loRaTransmitDelay = millis() + minimum_pause;
return;
}
if (millis() < loRaTransmitDelay) {
Serial.println("[LoRa Tx] LoRa delay not expired, waiting...");
return;
}
int separatorIndex = message.indexOf('|');
if (separatorIndex == -1) {
Serial.println("[LoRa Tx] Invalid message format.");
return;
}
String messageID = message.substring(0, separatorIndex);
tx_time = millis();
Serial.printf("[LoRa Tx] Transmitting: %s\n", message.c_str());
heltec_led(50);
int transmitStatus = radio.transmit(message.c_str());
tx_time = millis() - tx_time;
heltec_led(0);
TxHistoryEntry txEntry;
txEntry.timestamp = millis();
txEntry.type = determineTxType(message);
txEntry.txTime = tx_time;
if (transmitStatus == RADIOLIB_ERR_NONE) {
Serial.printf("[LoRa Tx] Sent successfully (%i ms)\n", (int)tx_time);
messageTransmissions[messageID].transmittedViaLoRa = true;
messageTransmissions[messageID].relayedViaLoRa = true;
messageTransmissions[messageID].queuedForLoRa = false;
messageTransmissions[messageID].relayRetryAttempted = false;
calculateDutyCyclePause(tx_time);
last_tx = millis();
drawMainScreen(tx_time);
radio.startReceive();
// Channel Isolation:
// After LoRa Tx, if a WiFi relay was pending and the message did not originate via WiFi, perform it.
if (messageTransmissions[messageID].pendingWiFiRelay && messageTransmissions[messageID].origin != ORIGIN_WIFI) {
transmitViaWiFi(message);
messageTransmissions[messageID].pendingWiFiRelay = false;
}
if (!loraTransmissionQueue.empty()) {
loraTransmissionQueue.erase(loraTransmissionQueue.begin());
Serial.printf("[LoRa Tx] Removed top queued entry for message %s\n", messageID.c_str());
}
relayLog.erase(messageID);
txEntry.success = true;
} else {
Serial.printf("[LoRa Tx] Transmission failed with error code: %i\n", transmitStatus);
if (!messageTransmissions[messageID].relayRetryAttempted) {
messageTransmissions[messageID].relayRetryAttempted = true;
// Retry branch: if the message originated via our node, keep fixed 2-second delay; else, use dynamic slot delay.
if (messageTransmissions[messageID].origin == ORIGIN_WIFI) {
loRaTransmitDelay = millis() + 2000;
Serial.printf("[LoRa Tx] Scheduling a retry for own message %s with fixed 2-second delay\n", messageID.c_str());
} else {
unsigned long baseSlot = getTxDuration(message); // default 3000 ms if not available
unsigned long dynamicSlot = getDynamicSlot(baseSlot, -100); // For retry, if no new measurement, use default RSSI of -100
unsigned long totalWindow = 35000; // 35 seconds total window
int numSlots = totalWindow / dynamicSlot;
if(numSlots < 1) numSlots = 1;
int randomSlot = random(1, numSlots + 1);
loRaTransmitDelay = millis() + (randomSlot * dynamicSlot);
Serial.printf("[LoRa Tx] Scheduling a retry for message %s in %lu ms (dynamic slot, random slot %d)\n",
messageID.c_str(), loRaTransmitDelay - millis(), randomSlot);
}
} else {
messageTransmissions[messageID].queuedForLoRa = false;
if (!loraTransmissionQueue.empty()) {
loraTransmissionQueue.erase(loraTransmissionQueue.begin());
Serial.printf("[LoRa Tx] Removing top queued entry for message %s after retry failure\n", messageID.c_str());
}
}
txEntry.success = false;
}
txHistory.push_back(txEntry);
if(txHistory.size() > 100) {
txHistory.erase(txHistory.begin());
}
}
// ----------------------------
// NEW: Heartbeat scheduling with random jitter
// ----------------------------
const unsigned long firstHeartbeatDelayValue = 20000; // 20 seconds for first heartbeat
const unsigned long heartbeatIntervalValue = 900000; // 15 minutes for subsequent heartbeats
unsigned long nextHeartbeatTime = 0;
unsigned long nextAggregatedHeartbeatTime = 0;
void sendHeartbeat() {
String heartbeatWithoutCRC = "HEARTBEAT|" + getCustomNodeId(getNodeId());
uint16_t crc = crc16_ccitt((const uint8_t *)heartbeatWithoutCRC.c_str(), heartbeatWithoutCRC.length());
char crcStr[5];
sprintf(crcStr, "%04X", crc);
String heartbeatMessage = heartbeatWithoutCRC + "|" + String(crcStr);
if (!isDutyCycleAllowed()) {
Serial.println("[Heartbeat Tx] Duty cycle limit reached, skipping.");
return;
}
if (radio.available()) {
Serial.println("[Heartbeat Tx] Radio is busy receiving a packet. Delaying heartbeat by 500ms.");
return;
}
uint64_t txStart = millis();
Serial.printf("[Heartbeat Tx] Sending: %s\n", heartbeatMessage.c_str());
heltec_led(50);
int transmitStatus = radio.transmit(heartbeatMessage.c_str());
uint64_t txTime = millis() - txStart;
heltec_led(0);
{
TxHistoryEntry entry;
entry.timestamp = millis();
entry.type = "❤️";
entry.txTime = txTime;
entry.success = (transmitStatus == RADIOLIB_ERR_NONE);
txHistory.push_back(entry);
if (txHistory.size() > 100) txHistory.erase(txHistory.begin());
}
if (transmitStatus == RADIOLIB_ERR_NONE) {
Serial.printf("[Heartbeat Tx] Sent successfully (%llu ms)\n", txTime);
calculateDutyCyclePause(txTime);
last_tx = millis();
drawMainScreen(txTime);
radio.startReceive();
} else {
Serial.printf("[Heartbeat Tx] Failed with error code: %i\n", transmitStatus);
}
}
void sendAggregatedHeartbeat() {
if (!sendAggregatedHeartbeats) {
Serial.println("[Aggregated Heartbeat Tx] Aggregated heartbeats are disabled by global flag.");
return;
}
String aggMsgWithoutCRC = "AGG_HEARTBEAT|" + getCustomNodeId(getNodeId());
auto directNodes = mesh.getNodeList();
for (uint32_t node : directNodes) {
String nodeIdStr = getCustomNodeId(node);
if (nodeIdStr != getCustomNodeId(getNodeId())) {
aggMsgWithoutCRC += "|" + nodeIdStr;
}
}
uint16_t crc = crc16_ccitt((const uint8_t *)aggMsgWithoutCRC.c_str(), aggMsgWithoutCRC.length());
char crcStr[5];
sprintf(crcStr, "%04X", crc);
String aggMessage = aggMsgWithoutCRC + "|" + String(crcStr);
if (!isDutyCycleAllowed()) {
Serial.println("[Aggregated Heartbeat Tx] Duty cycle limit reached, skipping.");
return;
}
if (radio.available()) {
Serial.println("[Aggregated Heartbeat Tx] Radio busy, delaying aggregated heartbeat.");
return;
}
uint64_t txStart = millis();
Serial.printf("[Aggregated Heartbeat Tx] Sending: %s\n", aggMessage.c_str());
heltec_led(50);
int transmitStatus = radio.transmit(aggMessage.c_str());
uint64_t txTime = millis() - txStart;
heltec_led(0);
{
TxHistoryEntry entry;
entry.timestamp = millis();
entry.type = "📡";
entry.txTime = txTime;
entry.success = (transmitStatus == RADIOLIB_ERR_NONE);
txHistory.push_back(entry);
if (txHistory.size() > 100) txHistory.erase(txHistory.begin());
}
if (transmitStatus == RADIOLIB_ERR_NONE) {
Serial.printf("[Aggregated Heartbeat Tx] Sent successfully (%llu ms)\n", txTime);
calculateDutyCyclePause(txTime);
last_tx = millis();
drawMainScreen(txTime);
radio.startReceive();
} else {
Serial.printf("[Aggregated Heartbeat Tx] Failed with error code: %i\n", transmitStatus);
}
}
// --------------------------------------------------------------------------
// IMPORTANT: Callback for radio RX events. (Renamed to avoid conflict.)
// --------------------------------------------------------------------------
void onRadioRx() {
rxFlag = true;
}
void setup() {
Serial.begin(115200);
heltec_setup();
Serial.println("Initializing LoRa radio...");
heltec_led(0);
#ifdef HELTEC_V3_2
pinMode(Vext, OUTPUT);
digitalWrite(Vext, LOW);
delay(100);
#endif
display.init();
#ifdef HELTEC_V3_2
display.setContrast(255);
#endif
display.flipScreenVertically();
display.clear();
display.setFont(ArialMT_Plain_10);
drawMainScreen();
showScrollingMonospacedAsciiArt();
RADIOLIB_OR_HALT(radio.begin());
radio.setDio1Action(onRadioRx);
if(enableRxBoost) {
RADIOLIB_OR_HALT(radio.setRxBoostedGainMode(true));
} else {