-
Notifications
You must be signed in to change notification settings - Fork 1
/
Meshify-Heltec_Lora_32_V3.ino
1699 lines (1480 loc) · 53 KB
/
Meshify-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.005
//20-12-2024
//MAKE SURE ALL NODES USE THE SAME VERSION OR EXPECT STRANGE THINGS HAPPENING.
//Improved Metrics Page to show best rssi snr.
//Fixed wifi only node messages showing numbers instead of converted node id.
//Moved navigation to top of node and hostory page.
////////////////////////////////////////////////
// M M EEEEE SSSSS H H I FFFF Y Y //
// MM MM E S H H I F Y Y //
// M MM M EEEE SSSSS HHHHH I FFFF Y //
// M M E S H H I F Y //
// M M EEEEE SSSSS H H I F Y //
////////////////////////////////////////////////
#define HELTEC_POWER_BUTTON // Use the power button feature of Heltec
#include <heltec_unofficial.h> // Heltec library for OLED and LoRa
#include <painlessMesh.h>
#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
#include <map> // For unified retransmission tracking
#include <RadioLib.h>
// Unified Retransmission Tracking Structure
struct TransmissionStatus {
bool transmittedViaWiFi = false;
bool transmittedViaLoRa = false;
bool addedToMessages = false; // Flag to track if the message has been added to messages vector
};
// Map to track retransmissions
std::map<String, TransmissionStatus> messageTransmissions;
// LoRa Parameters
#define PAUSE 5400000
#define FREQUENCY 869.4000
#define BANDWIDTH 250.0
#define SPREADING_FACTOR 11
#define TRANSMIT_POWER 22
#define CODING_RATE 8
String rxdata;
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;
String fullMessage;
// Function to handle LoRa received packets
void rx() {
rxFlag = true;
}
// Define the maximum allowed duty cycle (10%)
#define DUTY_CYCLE_LIMIT_MS 360000 // 6 minutes in a 60-minute window
#define DUTY_CYCLE_WINDOW 3600000 // 60 minutes in milliseconds
// Duty Cycle Variables
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);
}
}
// Meshify Parameters
#define MESH_SSID "Meshify 1.0"
#define MESH_PASSWORD ""
#define MESH_PORT 5555
const int maxMessages = 50;
// Duty Cycle Variables
bool bypassDutyCycle = false;
bool dutyCycleActive = false;
bool lastDutyCycleActive = false;
AsyncWebServer server(80);
DNSServer dnsServer;
painlessMesh mesh;
struct Message {
String nodeId;
String sender;
String content;
String source;
String messageID;
String relayID;
int rssi;
float snr;
uint64_t timeReceived;
};
std::vector<Message> messages;
int totalNodeCount = 0;
uint32_t currentNodeId = 0;
unsigned long loRaTransmitDelay = 0;
unsigned long messageCounter = 0;
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;
}
String constructMessage(const String& messageID, const String& originatorID, const String& sender, const String& content, const String& relayID) {
String messageWithoutCRC = messageID + "|" + originatorID + "|" + sender + "|" + 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 ***
// Store multiple samples for each node to track signal history (RSSI, SNR, timestamp).
struct NodeMetricsSample {
uint64_t timestamp;
int rssi;
float snr;
};
struct LoRaNode {
String nodeId;
int lastRSSI;
float lastSNR;
uint64_t lastSeen;
// Rolling history of signal metrics (RSSI, SNR, timestamp).
std::vector<NodeMetricsSample> history;
};
std::map<String, LoRaNode> loraNodes;
// *** END METRICS HISTORY CHANGES ***
unsigned long lastCleanupTime = 0;
const unsigned long cleanupInterval = 60000; // 1 minute
void cleanupLoRaNodes() {
uint64_t currentTime = millis();
const uint64_t timeout = 86400000; // 24 hours node is removed if not seen
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;
}
}
}
void addMessage(const String& nodeId, const String& messageID, const String& sender, 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];
if (status.addedToMessages) {
Serial.println("Message already exists, skipping...");
return;
}
String finalSource = "";
if (nodeId != getCustomNodeId(getNodeId())) {
finalSource = source;
}
Message newMessage = {
nodeId, sender, content, finalSource, messageID, relayID, rssi, snr, millis()
};
messages.insert(messages.begin(), newMessage);
status.addedToMessages = true;
if (messages.size() > maxMessages) {
messages.pop_back();
}
Serial.printf("Message added: NodeID: %s, Sender: %s, Content: %s, Source: %s, ID: %s, RelayID: %s\n",
nodeId.c_str(), sender.c_str(), content.c_str(), finalSource.c_str(), messageID.c_str(), relayID.c_str());
}
void scheduleLoRaTransmission(String message) {
int lastSeparator = message.lastIndexOf('|');
if (lastSeparator == -1) {
Serial.println("[LoRa Schedule] Invalid format (no CRC).");
return;
}
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;
}
int firstSeparator = messageWithoutCRC.indexOf('|');
int secondSeparator = messageWithoutCRC.indexOf('|', firstSeparator + 1);
int thirdSeparator = messageWithoutCRC.indexOf('|', secondSeparator + 1);
int fourthSeparator = messageWithoutCRC.indexOf('|', thirdSeparator + 1);
if (firstSeparator == -1 || secondSeparator == -1 || thirdSeparator == -1 || fourthSeparator == -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 messageContent = messageWithoutCRC.substring(thirdSeparator + 1, fourthSeparator);
String newRelayID = getCustomNodeId(getNodeId());
String updatedMessage = constructMessage(messageID, originatorID, senderID, messageContent, newRelayID);
fullMessage = updatedMessage;
loRaTransmitDelay = millis() + random(2201, 5000);
Serial.printf("[LoRa Schedule] Scheduled after %lu ms: %s\n", loRaTransmitDelay - millis(), updatedMessage.c_str());
}
void transmitViaWiFi(const String& message) {
Serial.printf("[WiFi Tx] Preparing to transmit: %s\n", message.c_str());
if (message.startsWith("HEARTBEAT|")) {
Serial.println("[WiFi Tx] Skipping heartbeat over WiFi.");
return;
}
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;
}
mesh.sendBroadcast(message);
status.transmittedViaWiFi = true;
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 I FFFF Y Y";
lines[1] = "MM MM E S H H I F Y Y ";
lines[2] = "M MM M EEEE SSSSS HHHHH I FFFF Y ";
lines[3] = "M M E S H H I F Y ";
lines[4] = "M M EEEEE SSSSS H H I F Y ";
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("Meshify 1.0");
display.drawString((128 - titleWidth) / 2, 0, "Meshify 1.0");
display.drawString(0, 13, "Node ID: " + getCustomNodeId(getNodeId()));
// Count active LoRa nodes
uint64_t currentTime = millis();
const uint64_t timeout = 900000; // 15 minutes
int activeLoRaNodes = 0;
for (const auto& node : loraNodes) {
if (currentTime - node.second.lastSeen <= timeout) {
activeLoRaNodes++;
}
}
String combinedNodes = "WiFi Nodes: " + String(getNodeCount()) + " LoRa: " + String(activeLoRaNodes);
int16_t combinedWidth = display.getStringWidth(combinedNodes);
if (combinedWidth > 128) {
combinedNodes = "WiFi: " + String(getNodeCount()) + " LoRa: " + String(activeLoRaNodes);
}
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;
carouselIndex++;
if (messages.empty()) {
carouselIndex = 0;
} else {
if (carouselIndex > (int)messages.size()) {
carouselIndex = 0;
}
}
}
display.clear();
display.setFont(ArialMT_Plain_10);
if (carouselIndex == 0) {
drawMainScreen(-1);
} else {
int msgIndex = carouselIndex - 1;
if (msgIndex < (int)messages.size()) {
String nodeLine = "Node: " + messages[msgIndex].nodeId;
display.drawString(0, 0, nodeLine);
String nameLine = "Name: " + messages[msgIndex].sender;
display.drawString(0, 13, nameLine);
display.drawStringMaxWidth(0, 26, 128, messages[msgIndex].content);
}
}
display.display();
}
long lastTxTimeMillisVar = -1;
void transmitWithDutyCycle(const String& message) {
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 format.");
return;
}
String messageID = message.substring(0, separatorIndex);
auto& status = messageTransmissions[messageID];
if (status.transmittedViaLoRa) {
Serial.println("[LoRa Tx] Already sent via LoRa, skipping...");
return;
}
if (isDutyCycleAllowed()) {
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);
if (transmitStatus == RADIOLIB_ERR_NONE) {
Serial.printf("[LoRa Tx] Sent OK (%i ms)\n", (int)tx_time);
status.transmittedViaLoRa = true;
calculateDutyCyclePause(tx_time);
last_tx = millis();
drawMainScreen(tx_time);
delay(200);
radio.startReceive();
if (!message.startsWith("HEARTBEAT|")) {
transmitViaWiFi(message);
}
} else {
Serial.printf("[LoRa Tx] Failed (%i)\n", transmitStatus);
}
} else {
Serial.printf("[LoRa Tx] Duty cycle limit reached, wait %i sec.\n",
(int)((minimum_pause - (millis() - last_tx)) / 1000) + 1);
}
}
unsigned long lastHeartbeatTime = 0;
const unsigned long firstHeartbeatDelay = 20000; // 20 seconds for first heartbeat
const unsigned long heartbeatInterval = 900000; // 15 minutes for subsequent heartbeats
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()) {
tx_time = millis();
Serial.printf("[Heartbeat Tx] Sending: %s\n", heartbeatMessage.c_str());
heltec_led(50);
int transmitStatus = radio.transmit(heartbeatMessage.c_str());
tx_time = millis() - tx_time;
heltec_led(0);
if (transmitStatus == RADIOLIB_ERR_NONE) {
Serial.printf("[Heartbeat Tx] OK (%i ms)\n", (int)tx_time);
calculateDutyCyclePause(tx_time);
last_tx = millis();
drawMainScreen(tx_time);
delay(200);
radio.startReceive();
} else {
Serial.printf("[Heartbeat Tx] Failed (%i)\n", transmitStatus);
}
} else {
Serial.println("[Heartbeat Tx] Duty cycle limit reached, skipping.");
}
}
void setup() {
Serial.begin(115200);
heltec_setup();
Serial.println("Initializing LoRa radio...");
heltec_led(0);
display.init();
display.flipScreenVertically();
display.clear();
display.setFont(ArialMT_Plain_10);
drawMainScreen();
showScrollingMonospacedAsciiArt();
RADIOLIB_OR_HALT(radio.begin());
radio.setDio1Action(rx);
RADIOLIB_OR_HALT(radio.setFrequency(FREQUENCY));
RADIOLIB_OR_HALT(radio.setBandwidth(BANDWIDTH));
RADIOLIB_OR_HALT(radio.setSpreadingFactor(SPREADING_FACTOR));
RADIOLIB_OR_HALT(radio.setCodingRate(CODING_RATE));
RADIOLIB_OR_HALT(radio.setOutputPower(TRANSMIT_POWER));
radio.startReceive(RADIOLIB_SX126X_RX_TIMEOUT_INF);
delay(2000);
WiFi.softAP(MESH_SSID, MESH_PASSWORD);
WiFi.setTxPower(WIFI_POWER_19_5dBm);
WiFi.setSleep(false);
initMesh();
setupServerRoutes();
server.begin();
dnsServer.start(53, "*", WiFi.softAPIP());
esp_task_wdt_init(30, true);
esp_task_wdt_add(NULL);
esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
randomSeed(analogRead(0));
}
void loop() {
esp_task_wdt_reset();
heltec_loop();
mesh.update();
// Send the first heartbeat after 20 seconds, then subsequent heartbeats every 15 minutes
if (millis() - lastHeartbeatTime >= firstHeartbeatDelay && lastHeartbeatTime == 0) {
sendHeartbeat();
lastHeartbeatTime = millis(); // After the first heartbeat, set the lastHeartbeatTime
} else if (millis() - lastHeartbeatTime >= heartbeatInterval && lastHeartbeatTime > 0) {
sendHeartbeat(); // Send subsequent heartbeats every 15 minutes
lastHeartbeatTime = millis(); // Update the last heartbeat time
}
if (rxFlag) {
rxFlag = false;
String message;
int state = radio.readData(message);
if (state == RADIOLIB_ERR_NONE) {
Serial.printf("[LoRa Rx] %s\n", message.c_str());
int lastSeparatorIndex = message.lastIndexOf('|');
if (lastSeparatorIndex == -1) {
Serial.println("[LoRa Rx] Invalid format (no CRC).");
} else {
String crcStr = message.substring(lastSeparatorIndex + 1);
String messageWithoutCRC = message.substring(0, lastSeparatorIndex);
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 Rx] CRC mismatch. Recv: %04X, Computed: %04X\n", receivedCRC, computedCRC);
} else {
Serial.println("[LoRa Rx] CRC valid.");
if (messageWithoutCRC.startsWith("HEARTBEAT|")) {
String senderNodeId = messageWithoutCRC.substring(strlen("HEARTBEAT|"));
Serial.printf("[LoRa Rx] Heartbeat from %s\n", senderNodeId.c_str());
int rssi = radio.getRSSI();
float snr = radio.getSNR();
uint64_t currentTime = millis();
if (senderNodeId != getCustomNodeId(getNodeId())) {
// *** METRICS HISTORY CHANGES ***
LoRaNode& node = loraNodes[senderNodeId];
node.nodeId = senderNodeId;
node.lastRSSI = rssi;
node.lastSNR = snr;
node.lastSeen = currentTime;
NodeMetricsSample sample = {currentTime, rssi, snr};
node.history.push_back(sample);
if (node.history.size() > 60) {
node.history.erase(node.history.begin());
}
// *** END METRICS HISTORY CHANGES ***
Serial.printf("[LoRa Nodes] Updated/Added node: %s (Heartbeat)\n", senderNodeId.c_str());
} else {
Serial.println("[LoRa Rx] Own heartbeat, ignore.");
}
} else {
int firstSeparator = messageWithoutCRC.indexOf('|');
int secondSeparator = messageWithoutCRC.indexOf('|', firstSeparator + 1);
int thirdSeparator = messageWithoutCRC.indexOf('|', secondSeparator + 1);
int fourthSeparator = messageWithoutCRC.indexOf('|', thirdSeparator + 1);
if (firstSeparator == -1 || secondSeparator == -1 || thirdSeparator == -1 || fourthSeparator == -1) {
Serial.println("[LoRa Rx] Invalid format.");
} else {
String messageID = messageWithoutCRC.substring(0, firstSeparator);
String originatorID = messageWithoutCRC.substring(firstSeparator + 1, secondSeparator);
String senderID = messageWithoutCRC.substring(secondSeparator + 1, thirdSeparator);
String messageContent = messageWithoutCRC.substring(thirdSeparator + 1, fourthSeparator);
String relayID = messageWithoutCRC.substring(fourthSeparator + 1);
int rssi = radio.getRSSI();
float snr = radio.getSNR();
if (originatorID == getCustomNodeId(getNodeId())) {
Serial.println("[LoRa Rx] Own message, ignore.");
} else {
auto& status = messageTransmissions[messageID];
if (status.transmittedViaWiFi && status.transmittedViaLoRa) {
Serial.println("[LoRa Rx] Already relayed both WiFi/LoRa, ignore...");
} else {
addMessage(originatorID, messageID, senderID, messageContent, "[LoRa]", relayID, rssi, snr);
if (!status.transmittedViaLoRa) {
scheduleLoRaTransmission(message);
}
uint64_t currentTime = millis();
// *** METRICS HISTORY CHANGES ***
// Update LoRaNode for 'relayID'
if (relayID != getCustomNodeId(getNodeId())) {
LoRaNode& relayNode = loraNodes[relayID];
relayNode.nodeId = relayID;
relayNode.lastRSSI = rssi;
relayNode.lastSNR = snr;
relayNode.lastSeen = currentTime;
NodeMetricsSample sample = {currentTime, rssi, snr};
relayNode.history.push_back(sample);
if (relayNode.history.size() > 60) {
relayNode.history.erase(relayNode.history.begin());
}
Serial.printf("[LoRa Nodes] Updated/Added node: %s\n", relayID.c_str());
} else {
Serial.println("[LoRa Nodes] RelayID is own node, not updating.");
}
// *** END METRICS HISTORY CHANGES ***
}
}
}
}
}
}
radio.startReceive();
} else {
Serial.printf("[LoRa Rx] Receive failed, code %d\n", state);
radio.startReceive();
}
}
if (!fullMessage.isEmpty() && millis() >= loRaTransmitDelay) {
transmitWithDutyCycle(fullMessage);
fullMessage = "";
}
updateMeshData();
displayCarousel();
dnsServer.processNextRequest();
if (millis() - lastCleanupTime >= cleanupInterval) {
cleanupLoRaNodes();
lastCleanupTime = millis();
}
if (millis() - lastHeartbeatTime >= heartbeatInterval) {
sendHeartbeat();
lastHeartbeatTime = millis();
}
}
void initMesh() {
mesh.setDebugMsgTypes(ERROR | STARTUP | CONNECTION);
mesh.init(MESH_SSID, MESH_PASSWORD, MESH_PORT);
mesh.onReceive(receivedCallback);
mesh.onChangedConnections([]() {
updateMeshData();
});
mesh.setContainsRoot(false);
}
void receivedCallback(uint32_t from, String& message) {
Serial.printf("[WiFi Rx] From %u: %s\n", from, message.c_str());
// Extract CRC from the message
int lastSeparatorIndex = message.lastIndexOf('|');
if (lastSeparatorIndex == -1) {
Serial.println("[WiFi Rx] Invalid format (no CRC).");
return;
}
String crcStr = message.substring(lastSeparatorIndex + 1);
String messageWithoutCRC = message.substring(0, lastSeparatorIndex);
// Compute and verify CRC
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("[WiFi Rx] CRC mismatch. Recv: %04X, Computed: %04X\n", receivedCRC, computedCRC);
return;
} else {
Serial.println("[WiFi Rx] CRC valid.");
}
// Parse message components
int firstSeparator = messageWithoutCRC.indexOf('|');
int secondSeparator = messageWithoutCRC.indexOf('|', firstSeparator + 1);
int thirdSeparator = messageWithoutCRC.indexOf('|', secondSeparator + 1);
int fourthSeparator = messageWithoutCRC.indexOf('|', thirdSeparator + 1);
if (firstSeparator == -1 || secondSeparator == -1 || thirdSeparator == -1 || fourthSeparator == -1) {
Serial.println("[WiFi Rx] Invalid format (missing separators).");
return;
}
String messageID = messageWithoutCRC.substring(0, firstSeparator);
String originatorID = messageWithoutCRC.substring(firstSeparator + 1, secondSeparator);
String senderID = messageWithoutCRC.substring(secondSeparator + 1, thirdSeparator);
String messageContent = messageWithoutCRC.substring(thirdSeparator + 1, fourthSeparator);
String relayID = messageWithoutCRC.substring(fourthSeparator + 1);
// **Convert originatorID to custom format if necessary**
if (!originatorID.startsWith("!M")) {
// Attempt to convert numeric ID to custom format
uint32_t numericId = originatorID.toInt();
originatorID = getCustomNodeId(numericId);
Serial.printf("[WiFi Rx] Converted originatorID to custom format: %s\n", originatorID.c_str());
}
// **Convert relayID to custom format if necessary**
if (!relayID.startsWith("!M")) {
// Attempt to convert numeric relayID to custom format
uint32_t numericRelayId = relayID.toInt();
relayID = getCustomNodeId(numericRelayId);
Serial.printf("[WiFi Rx] Converted relayID to custom format: %s\n", relayID.c_str());
}
// **Handle Heartbeat Messages**
if (messageWithoutCRC.startsWith("HEARTBEAT|")) {
Serial.println("[WiFi Rx] Skipping heartbeat relay over WiFi.");
return;
}
// **Ignore Own Messages**
if (originatorID == getCustomNodeId(getNodeId())) {
Serial.println("[WiFi Rx] Own message, just adding locally...");
addMessage(originatorID, messageID, senderID, messageContent, "[WiFi]", relayID);
return;
}
// **Check if Message Already Relayed**
auto& status = messageTransmissions[messageID];
if (status.transmittedViaWiFi && status.transmittedViaLoRa) {
Serial.println("[WiFi Rx] Already relayed both via WiFi and LoRa, ignoring...");
return;
}
// **Add Message to Local Storage**
Serial.printf("[WiFi Rx] Adding message: %s\n", message.c_str());
addMessage(originatorID, messageID, senderID, messageContent, "[WiFi]", relayID);
// **Schedule LoRa Transmission if Not Already Done**
if (!status.transmittedViaLoRa) {
scheduleLoRaTransmission(message);
}
// **Update LoRa Node Metrics Based on relayID**
uint64_t currentTime = millis();
if (relayID != getCustomNodeId(getNodeId())) {
// Update or add the relay node in the LoRa nodes map
LoRaNode& relayNode = loraNodes[relayID];
relayNode.nodeId = relayID;
relayNode.lastRSSI = radio.getRSSI();
relayNode.lastSNR = radio.getSNR();
relayNode.lastSeen = currentTime;
// Add a new metrics sample
NodeMetricsSample sample = {currentTime, radio.getRSSI(), radio.getSNR()};
relayNode.history.push_back(sample);
if (relayNode.history.size() > 60) {
relayNode.history.erase(relayNode.history.begin());
}
Serial.printf("[LoRa Nodes] Updated/Added node: %s\n", relayID.c_str());
} else {
Serial.println("[LoRa Nodes] RelayID is own node, not updating.");
}
}
const char mainPageHtml[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meshify Chat Room</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f7f6;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
height: 100vh;
overflow: hidden;
}
.warning {
color: red;
font-weight: normal;
font-size: 0.9em;
padding: 10px;
background-color: #fff3f3;
border: 1px solid red;
max-width: 100%;
text-align: center;
border-radius: 5px;
margin: 0;
}
h2 {
color: #333;
margin: 10px 0 5px;
font-size: 1.2em;
}
#chat-container {
background-color: #fff;
width: 100%;
max-width: 600px;
height: calc(100vh - 250px);
margin-top: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
overflow-y: auto;
padding: 10px;
border-radius: 10px;
box-sizing: border-box;
}
#messageForm {
width: 100%;
max-width: 600px;
display: flex;
position: fixed;
bottom: 0;
background-color: #fff;
padding: 10px;
box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
box-sizing: border-box;
}
#nameInput, #messageInput {
width: 40%;
padding: 10px;
margin-right: 5px;
border: 1px solid #ccc;
border-radius: 5px;
box-sizing: border-box;
}
#messageInput {
width: 60%;
}
#messageForm input[type=submit] {
background-color: #007bff;
color: white;
border: none;
padding: 10px;
cursor: pointer;
border-radius: 5px;
}
#messageList {
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
}
.message {
display: flex;
flex-direction: column;
margin: 5px 0;
padding: 8px;
border-radius: 5px;
width: 80%;
box-sizing: border-box;
border: 2px solid;
word-wrap: break-word;
}
.message.sent {
align-self: flex-end;
border-color: green;
background-color: #eaffea;
}
.message.received.wifi {
align-self: flex-start;
border-color: blue;
background-color: #e7f0ff;
}
.message.received.lora {
align-self: flex-start;
border-color: orange;
background-color: #fff4e0;
}
.message-nodeid {
font-size: 0.7em;
color: #666;
}
.message-relayid {
font-size: 0.7em;
color: #555;
margin-bottom: 2px;
display: block;
}
.message-rssi-snr {
font-size: 0.7em;
color: #666;
text-align: right;
margin-top: 2px;
}
.message-content {
font-size: 0.85em;
color: #333;
}
.message-time {
font-size: 0.7em;
color: #999;
text-align: right;
margin-top: 5px;
}
#deviceCount {
margin: 5px 0;
font-weight: normal;
font-size: 0.9em;
}
#deviceCount a {
color: #007bff;
text-decoration: none;
}
#deviceCount a:hover {