-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathRNode_Firmware.ino
More file actions
executable file
·3272 lines (2940 loc) · 108 KB
/
Copy pathRNode_Firmware.ino
File metadata and controls
executable file
·3272 lines (2940 loc) · 108 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
// Copyright (C) 2024, Mark Qvist
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// CBA Reticulum includes must come before local to avoid collision with local defines
#ifdef HAS_RNS
#include <Transport.h>
#include <Reticulum.h>
#include <Interface.h>
#include <Log.h>
#include <Bytes.h>
#include <queue>
#endif
#include <Arduino.h>
#include <SPI.h>
#include "Utilities.h"
// CBA Firewall Mode
// NOTE: FIREWALL_MODE is the compile flag for Firewall Mode.
// This is the only operating mode in this fork.
// temporarily as a compatibility shim during cleanup.
#ifdef FIREWALL_MODE
#include "FirewallMode.h"
#include "TcpInterface.h"
#include "FirewallConfig.h"
#include "Advertise.h"
#include "MdnsService.h"
#include "esp_bt.h"
#endif
// CBA FileSystem
#if defined(RNS_USE_FS)
#include "FileSystem.h"
#else
#include "NoopFileSystem.h"
#endif
// CBA SD
#if HAS_SDCARD
#include <SD.h>
SPIClass SDSPI(HSPI);
#endif
#if MCU_VARIANT == MCU_ESP32
#include <esp_task_wdt.h>
#include <esp_heap_caps.h>
#endif
// ── Forward declarations ──────────────────────────────────────────
// The Arduino preprocessor normally generates these from the .ino,
// but PlatformIO 6.1.18's preprocessor occasionally fails to emit
// prototypes for functions defined later in the file. Explicit
// declarations here ensure the sketch compiles regardless of
// toolchain version.
void serial_interrupt_init();
void serial_poll();
void buffer_serial();
bool medium_free();
void update_radio_lock();
void update_airtime();
void update_modem_status();
void validate_status();
void transmit(uint16_t size);
void flush_queue();
void pop_queue();
// WDT timeout
#define WDT_TIMEOUT 60 // seconds
FIFOBuffer serialFIFO;
uint8_t serialBuffer[CONFIG_UART_BUFFER_SIZE+1];
FIFOBuffer16 packet_starts;
uint16_t packet_starts_buf[CONFIG_QUEUE_MAX_LENGTH+1];
FIFOBuffer16 packet_lengths;
uint16_t packet_lengths_buf[CONFIG_QUEUE_MAX_LENGTH+1];
uint8_t packet_queue[CONFIG_QUEUE_SIZE];
volatile uint8_t queue_height = 0;
volatile uint16_t queued_bytes = 0;
volatile uint16_t queue_cursor = 0;
volatile uint16_t current_packet_start = 0;
volatile bool serial_buffering = false;
#if HAS_BLUETOOTH || HAS_BLE == true
bool bt_init_ran = false;
#endif
#if HAS_CONSOLE
#include "Console.h"
#endif
#if PLATFORM == PLATFORM_ESP32 || PLATFORM == PLATFORM_NRF52
#define MODEM_QUEUE_SIZE 8
typedef struct {
size_t len;
int rssi;
int snr_raw;
uint8_t data[];
} modem_packet_t;
static xQueueHandle modem_packet_queue = NULL;
static modem_packet_t* modem_packet_alloc(size_t len) {
size_t allocation_size = sizeof(modem_packet_t) + len;
#if MCU_VARIANT == MCU_ESP32
if (ESP.getPsramSize() > 0) {
modem_packet_t *packet = (modem_packet_t*)heap_caps_malloc(allocation_size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (packet) return packet;
}
return (modem_packet_t*)heap_caps_malloc(allocation_size, MALLOC_CAP_8BIT);
#else
return (modem_packet_t*)malloc(allocation_size);
#endif
}
static void modem_packet_free(modem_packet_t *packet) {
free(packet);
}
#endif
char sbuf[128];
#if MCU_VARIANT == MCU_ESP32 || MCU_VARIANT == MCU_NRF52
bool packet_ready = false;
#endif
#if MCU_VARIANT == MCU_ESP32 || MCU_VARIANT == MCU_NRF52
void update_csma_parameters();
#endif
#ifdef HAS_RNS
// CBA LoRa interface
class LoRaInterface : public RNS::InterfaceImpl {
public:
LoRaInterface() : RNS::InterfaceImpl("LoRaInterface") {
_IN = true;
_OUT = true;
_HW_MTU = 508;
}
LoRaInterface(const char *name) : RNS::InterfaceImpl(name) {
_IN = true;
_OUT = true;
_HW_MTU = 508;
}
virtual ~LoRaInterface() {
_name = "deleted";
}
protected:
virtual void handle_incoming(const RNS::Bytes& data) {
VERBOSEF("[LoRa] RX %u bytes", data.size());
TRACEF("LoRaInterface.handle_incoming: (%u bytes) data: %s", data.size(), data.toHex().c_str());
TRACE("LoRaInterface.handle_incoming: sending packet to rns...");
InterfaceImpl::handle_incoming(data);
}
virtual void send_outgoing(const RNS::Bytes& data) {
// CBA NOTE header will be addded later by transmit function
VERBOSEF("[LoRa] TX %u bytes", data.size());
TRACEF("LoRaInterface.send_outgoing: (%u bytes) data: %s", data.size(), data.toHex().c_str());
TRACE("LoRaInterface.send_outgoing: adding packet to outgoing queue...");
const size_t available_bytes = CONFIG_QUEUE_SIZE - queued_bytes;
if (fifo16_isfull(&packet_starts) || fifo16_isfull(&packet_lengths) ||
queue_height >= CONFIG_QUEUE_MAX_LENGTH || data.size() > available_bytes) {
WARNINGF("[LoRa] TX DROP %u bytes: queue packets=%u bytes=%u",
data.size(), queue_height, queued_bytes);
return;
}
for (size_t i = 0; i < data.size(); i++) {
queued_bytes++;
packet_queue[queue_cursor++] = data.data()[i];
if (queue_cursor == CONFIG_QUEUE_SIZE) queue_cursor = 0;
}
uint16_t packet_start = current_packet_start;
uint16_t packet_length = data.size();
if (packet_length >= MIN_L) {
queue_height++;
fifo16_push(&packet_starts, packet_start);
fifo16_push(&packet_lengths, packet_length);
current_packet_start = queue_cursor;
}
// Perform post-send housekeeping
InterfaceImpl::handle_outgoing(data);
}
};
// CBA logger callback
void on_log(const char* msg, RNS::LogLevel level) {
/*
Serial.print(RNS::getTimeString());
Serial.print(" [");
Serial.print(RNS::getLevelName(level));
Serial.print("] ");
Serial.println(msg);
Serial.flush();
*/
String line = RNS::getTimeString() + String(" [") + RNS::getLevelName(level) + "] " + msg + "\n";
Serial.print(line);
Serial.flush();
#ifdef HAS_SDCARD
File file = SD.open("/logfile.txt", FILE_APPEND);
if (file) {
file.write((uint8_t*)line.c_str(), line.length());
file.close();
}
#endif // HAS_SDCARD
}
// CBA receive packet callback
void on_receive_packet(const RNS::Bytes& raw, const RNS::Interface& interface) {
#ifdef HAS_SDCARD
TRACE("Logging receive packet to SD");
String line = RNS::getTimeString() + String(" recv: ") + String(raw.toHex().c_str()) + "\n";
File file = SD.open("/tracefile.txt", FILE_APPEND);
if (file) {
file.write((uint8_t*)line.c_str(), line.length());
file.close();
}
RNS::Packet packet({RNS::Type::NONE}, raw);
if (packet.unpack()) {
String line = RNS::getTimeString() + String(" recv: ") + String(packet.dumpString().c_str()) + "\n";
File file = SD.open("/tracedetails.txt", FILE_APPEND);
if (file) {
file.write((uint8_t*)line.c_str(), line.length());
file.close();
}
}
#endif // HAS_SDCARD
}
// CBA transmit packet callback
void on_transmit_packet(const RNS::Bytes& raw, const RNS::Interface& interface) {
#ifdef HAS_SDCARD
TRACE("Logging transmit packet to SD");
String line = RNS::getTimeString() + String(" send: ") + String(raw.toHex().c_str()) + "\n";
File file = SD.open("/tracefile.txt", FILE_APPEND);
if (file) {
file.write((uint8_t*)line.c_str(), line.length());
file.close();
}
RNS::Packet packet({RNS::Type::NONE}, raw);
if (packet.unpack()) {
String line = RNS::getTimeString() + String(" send: ") + String(packet.dumpString().c_str()) + "\n";
File file = SD.open("/tracedetails.txt", FILE_APPEND);
if (file) {
file.write((uint8_t*)line.c_str(), line.length());
file.close();
}
}
#endif // HAS_SDCARD
}
// CBA RNS
RNS::Reticulum reticulum(RNS::Type::NONE);
RNS::Interface lora_interface(RNS::Type::NONE);
RNS::FileSystem filesystem(RNS::Type::NONE);
#ifdef FIREWALL_MODE
// Firewall mode: TCP backbone interface + state
FirewallState firewall_state = {};
// Bridge to microReticulum Transport.cpp (avoids header coupling)
bool firewall_probe_enabled = false;
RNS::Interface tcp_rns_interfaces[FIREWALL_BACKBONE_SLOTS] = {
RNS::Interface(RNS::Type::NONE),
RNS::Interface(RNS::Type::NONE),
RNS::Interface(RNS::Type::NONE),
RNS::Interface(RNS::Type::NONE)
};
TcpInterface* tcp_interface_ptrs[FIREWALL_BACKBONE_SLOTS] = { nullptr, nullptr, nullptr, nullptr };
// Local TCP server
RNS::Interface local_tcp_rns_interface(RNS::Type::NONE);
TcpInterface* local_tcp_interface_ptr = nullptr;
// RTC memory flag — survives software reset but not power cycle
RTC_NOINIT_ATTR uint32_t boundary_config_request;
#define BOUNDARY_CONFIG_MAGIC 0xC0F19A7E
// RTC flag to skip config portal on next boot (set when user powers off from WCC)
RTC_NOINIT_ATTR uint32_t boundary_skip_config;
#define BOUNDARY_SKIP_MAGIC 0x5E1FC0F0
// Bootloop detection: count rapid reboots in RTC memory.
// After BOOTLOOP_THRESHOLD consecutive reboots within BOOTLOOP_WINDOW_MS,
// force entry into the config portal so the user can fix settings.
#define BOOTLOOP_THRESHOLD 5
#define BOOTLOOP_WINDOW_MS 120000 // 2 minutes
#define BOOTLOOP_MAGIC 0xB007100D
RTC_NOINIT_ATTR uint32_t bootloop_magic;
RTC_NOINIT_ATTR uint32_t bootloop_count;
RTC_NOINIT_ATTR uint32_t bootloop_first_boot_ms;
// Node public hash — cached in RTC so the config portal can display it without
// needing to start RNS. Populated after the transport destination is created
// on a normal boot; survives software reboots into the captive portal.
#define NODE_HASH_RTC_MAGIC 0x504B4841UL // "PKHA"
RTC_NOINIT_ATTR uint32_t rtc_node_hash_magic;
RTC_NOINIT_ATTR char rtc_node_hash_hex[33]; // 32 hex chars + NUL
RTC_NOINIT_ATTR char rtc_probe_hash_hex[21]; // 20 hex chars + NUL
RTC_NOINIT_ATTR BoundaryResetReport boundary_reset_report;
static uint16_t boundary_nominal_path_table_maxsize = 0;
static uint16_t boundary_nominal_path_table_maxpersist = 0;
bool boundary_reset_report_available() {
return boundary_reset_report.magic == BOUNDARY_RESET_REPORT_MAGIC
&& boundary_reset_report.version == BOUNDARY_RESET_REPORT_VERSION
&& boundary_reset_report.cause != BOUNDARY_RESET_CAUSE_NONE;
}
const char* boundary_reset_cause_label(uint8_t cause) {
switch (cause) {
case BOUNDARY_RESET_CAUSE_HEAP_WATCHDOG: return "Heap watchdog";
case BOUNDARY_RESET_CAUSE_WIFI_WATCHDOG: return "WiFi watchdog";
default: return "Unknown";
}
}
const char* boundary_heap_stage_label(uint8_t stage) {
switch (stage) {
case BOUNDARY_HEAP_STAGE_SHED: return "Queue shedding";
case BOUNDARY_HEAP_STAGE_TRIM: return "Path-table trim";
default: return "None";
}
}
const char* boundary_reset_reason_label(uint8_t reason) {
switch (reason) {
case 0: return "Pending";
case POWERON_RESET: return "Power-on";
case RTC_SW_SYS_RESET: return "Software reset";
case DEEPSLEEP_RESET: return "Deep sleep wake";
case TG0WDT_SYS_RESET: return "Timer group 0 watchdog";
case TG1WDT_SYS_RESET: return "Timer group 1 watchdog";
case RTCWDT_SYS_RESET: return "RTC watchdog";
case INTRUSION_RESET: return "Brownout/intrusion";
case TG0WDT_CPU_RESET: return "CPU watchdog (TG0)";
case TG1WDT_CPU_RESET: return "CPU watchdog (TG1)";
case RTC_SW_CPU_RESET: return "CPU software reset";
case RTCWDT_CPU_RESET: return "RTC CPU watchdog";
case RTCWDT_BROWN_OUT_RESET: return "Brownout";
case RTCWDT_RTC_RESET: return "RTC reset";
case SUPER_WDT_RESET: return "Super watchdog";
case GLITCH_RTC_RESET: return "Clock glitch";
case EFUSE_RESET: return "eFuse CRC";
case USB_UART_CHIP_RESET: return "USB UART reset";
case USB_JTAG_CHIP_RESET: return "USB JTAG reset";
case POWER_GLITCH_RESET: return "Power glitch";
default: return "Other";
}
}
static void boundary_clear_reset_report() {
memset(&boundary_reset_report, 0, sizeof(boundary_reset_report));
}
static void boundary_note_reset_report_boot_reason() {
uint8_t reset_reason = (uint8_t)rtc_get_reset_reason(0);
if (reset_reason == POWERON_RESET) {
boundary_clear_reset_report();
return;
}
if (boundary_reset_report_available() && boundary_reset_report.observed_reset_reason == 0) {
boundary_reset_report.observed_reset_reason = reset_reason;
Serial.printf("[Boundary] Last automatic reset: %s, observed=%s, heap=%lu, min=%lu, max_alloc=%lu\r\n",
boundary_reset_cause_label(boundary_reset_report.cause),
boundary_reset_reason_label(boundary_reset_report.observed_reset_reason),
boundary_reset_report.free_heap,
boundary_reset_report.min_free_heap,
boundary_reset_report.max_alloc_heap);
}
}
static void boundary_capture_reset_report(uint8_t cause, uint8_t heap_stage, uint32_t free_heap, int32_t wifi_status) {
boundary_reset_report.magic = BOUNDARY_RESET_REPORT_MAGIC;
boundary_reset_report.version = BOUNDARY_RESET_REPORT_VERSION;
boundary_reset_report.cause = cause;
boundary_reset_report.heap_stage = heap_stage;
boundary_reset_report.observed_reset_reason = 0;
boundary_reset_report.uptime_ms = millis();
boundary_reset_report.free_heap = free_heap;
boundary_reset_report.min_free_heap = ESP.getMinFreeHeap();
boundary_reset_report.max_alloc_heap = ESP.getMaxAllocHeap();
boundary_reset_report.wifi_status = wifi_status;
boundary_reset_report.path_table_maxsize = RNS::Transport::path_table_maxsize();
boundary_reset_report.path_table_maxpersist = RNS::Transport::probe_destination_enabled();
boundary_reset_report.bridged_lora_to_tcp = firewall_state.packets_bridged_lora_to_tcp;
boundary_reset_report.bridged_tcp_to_lora = firewall_state.packets_bridged_tcp_to_lora;
}
static void boundary_restore_path_caps_if_needed() {
if (boundary_nominal_path_table_maxsize == 0 || boundary_nominal_path_table_maxpersist == 0) {
return;
}
if (RNS::Transport::path_table_maxsize() != boundary_nominal_path_table_maxsize ||
RNS::Transport::probe_destination_enabled() != boundary_nominal_path_table_maxpersist) {
RNS::Transport::path_table_maxsize(boundary_nominal_path_table_maxsize);
RNS::Transport::path_table_maxpersist(boundary_nominal_path_table_maxpersist);
RNS::Transport::cull_path_table();
}
}
static void boundary_trim_path_caps_for_pressure() {
if (boundary_nominal_path_table_maxsize == 0 || boundary_nominal_path_table_maxpersist == 0) {
return;
}
uint16_t trimmed_maxsize = boundary_nominal_path_table_maxsize;
if (trimmed_maxsize > 8) {
trimmed_maxsize = trimmed_maxsize / 2;
if (trimmed_maxsize < 8) {
trimmed_maxsize = 8;
}
}
uint16_t trimmed_maxpersist = boundary_nominal_path_table_maxpersist;
if (trimmed_maxpersist > 4) {
trimmed_maxpersist = trimmed_maxpersist / 2;
if (trimmed_maxpersist < 4) {
trimmed_maxpersist = 4;
}
}
if (trimmed_maxpersist > trimmed_maxsize) {
trimmed_maxpersist = trimmed_maxsize;
}
if (trimmed_maxsize < RNS::Transport::path_table_maxsize() ||
trimmed_maxpersist < RNS::Transport::probe_destination_enabled()) {
RNS::Transport::path_table_maxsize(trimmed_maxsize);
RNS::Transport::path_table_maxpersist(trimmed_maxpersist);
RNS::Transport::cull_path_table();
}
}
static void boundary_apply_heap_relief(uint8_t heap_stage) {
if (heap_stage >= BOUNDARY_HEAP_STAGE_SHED) {
RNS::Transport::drop_announce_queues();
RNS::Transport::clear_caches_in_memory(); // clear packet hashlist, global blobs, rate table
}
if (heap_stage >= BOUNDARY_HEAP_STAGE_TRIM) {
boundary_trim_path_caps_for_pressure();
}
RNS::Transport::clean_caches();
RNS::Transport::cull_path_table();
}
#endif
#endif // HAS_RNS
void setup() {
// Initialise serial communication
memset(serialBuffer, 0, sizeof(serialBuffer));
fifo_init(&serialFIFO, serialBuffer, CONFIG_UART_BUFFER_SIZE);
Serial.begin(serial_baudrate);
// CBA Safely wait for serial initialization
while (!Serial) {
if (millis() > 2000) {
break;
}
delay(10);
}
// CBA Test
delay(2000);
#ifdef FIREWALL_MODE
boundary_note_reset_report_boot_reason();
#endif
// Configure WDT
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_init(WDT_TIMEOUT, true); // enable panic so ESP32 restarts
esp_task_wdt_add(NULL); // add current thread to WDT watch
#elif MCU_VARIANT == MCU_NRF52
NRF_WDT->CONFIG = 0x01; // Configure WDT to run when CPU is asleep
NRF_WDT->CRV = WDT_TIMEOUT * 32768 + 1; // set timeout
NRF_WDT->RREN = 0x01; // Enable the RR[0] reload register
NRF_WDT->TASKS_START = 1; // Start WDT
#endif
#if MCU_VARIANT == MCU_ESP32
boot_seq();
EEPROM.begin(EEPROM_SIZE);
Serial.setRxBufferSize(CONFIG_UART_BUFFER_SIZE);
#if BOARD_MODEL == BOARD_TDECK
pinMode(pin_poweron, OUTPUT);
digitalWrite(pin_poweron, HIGH);
pinMode(SD_CS, OUTPUT);
pinMode(DISPLAY_CS, OUTPUT);
digitalWrite(SD_CS, HIGH);
digitalWrite(DISPLAY_CS, HIGH);
pinMode(DISPLAY_BL_PIN, OUTPUT);
#endif
#endif
#if MCU_VARIANT == MCU_NRF52
#if BOARD_MODEL == BOARD_TECHO
delay(200);
pinMode(PIN_VEXT_EN, OUTPUT);
digitalWrite(PIN_VEXT_EN, HIGH);
pinMode(pin_btn_usr1, INPUT_PULLUP);
pinMode(pin_btn_touch, INPUT_PULLUP);
pinMode(PIN_LED_RED, OUTPUT);
pinMode(PIN_LED_GREEN, OUTPUT);
pinMode(PIN_LED_BLUE, OUTPUT);
delay(200);
#endif
if (!eeprom_begin()) { Serial.write("EEPROM initialisation failed.\r\n"); }
#endif
// Seed the PRNG for CSMA R-value selection
#if MCU_VARIANT == MCU_ESP32
// On ESP32, get the seed value from the
// hardware RNG
unsigned long seed_val = (unsigned long)esp_random();
#elif MCU_VARIANT == MCU_NRF52
// On nRF, get the seed value from the
// hardware RNG
unsigned long seed_val = get_rng_seed();
#else
// Otherwise, get a pseudo-random seed
// value from an unconnected analog pin
//
// CAUTION! If you are implementing the
// firmware on a platform that does not
// have a hardware RNG, you MUST take
// care to get a seed value with enough
// entropy at each device reset!
unsigned long seed_val = analogRead(0);
#endif
randomSeed(seed_val);
#if HAS_NP
led_init();
#endif
#if MCU_VARIANT == MCU_NRF52 && HAS_NP == true
boot_seq();
#endif
#if BOARD_MODEL != BOARD_RAK4631 && BOARD_MODEL != BOARD_HELTEC_T114 && BOARD_MODEL != BOARD_TECHO && BOARD_MODEL != BOARD_T3S3 && BOARD_MODEL != BOARD_TBEAM_S_V1 && BOARD_MODEL != BOARD_HELTEC32_V4 && BOARD_MODEL != BOARD_HELTEC32_V3
// Some boards need to wait until the hardware UART is set up before booting
// the full firmware. In the case of the RAK4631, Heltec T114, and Heltec V3,
// the line below will wait until a serial connection is actually established
// with a master. Thus, it is disabled on these platforms.
while (!Serial);
#endif
serial_interrupt_init();
// Configure input and output pins
#if HAS_INPUT
input_init();
#endif
#if HAS_NP == false
pinMode(pin_led_rx, OUTPUT);
pinMode(pin_led_tx, OUTPUT);
#ifdef FIREWALL_MODE
// Keep the LED off in Firewall Mode — the OLED is the status indicator.
digitalWrite(pin_led_rx, LOW);
digitalWrite(pin_led_tx, LOW);
#endif
#endif
#if HAS_TCXO == true
if (pin_tcxo_enable != -1) {
pinMode(pin_tcxo_enable, OUTPUT);
digitalWrite(pin_tcxo_enable, HIGH);
}
#endif
// Initialise buffers
memset(pbuf, 0, sizeof(pbuf));
memset(cmdbuf, 0, sizeof(cmdbuf));
memset(packet_queue, 0, sizeof(packet_queue));
memset(packet_starts_buf, 0, sizeof(packet_starts_buf));
fifo16_init(&packet_starts, packet_starts_buf, CONFIG_QUEUE_MAX_LENGTH);
memset(packet_lengths_buf, 0, sizeof(packet_starts_buf));
fifo16_init(&packet_lengths, packet_lengths_buf, CONFIG_QUEUE_MAX_LENGTH);
#if PLATFORM == PLATFORM_ESP32 || PLATFORM == PLATFORM_NRF52
modem_packet_queue = xQueueCreate(MODEM_QUEUE_SIZE, sizeof(modem_packet_t*));
#endif
// Set chip select, reset and interrupt
// pins for the LoRa module
#if MODEM == SX1276 || MODEM == SX1278
LoRa->setPins(pin_cs, pin_reset, pin_dio, pin_busy);
#elif MODEM == SX1262
LoRa->setPins(pin_cs, pin_reset, pin_dio, pin_busy, pin_rxen);
#elif MODEM == SX1280
LoRa->setPins(pin_cs, pin_reset, pin_dio, pin_busy, pin_rxen, pin_txen);
#endif
#if MCU_VARIANT == MCU_ESP32 || MCU_VARIANT == MCU_NRF52
init_channel_stats();
#if BOARD_MODEL == BOARD_T3S3
#if MODEM == SX1280
delay(300);
LoRa->reset();
delay(100);
#endif
#endif
#if BOARD_MODEL == BOARD_XIAO_S3
// Improve wakeup from sleep
delay(300);
LoRa->reset();
delay(100);
#endif
// Check installed transceiver chip and
// probe boot parameters.
if (LoRa->preInit()) {
modem_installed = true;
#if HAS_INPUT
// Skip quick-reset console activation
#else
uint32_t lfr = LoRa->getFrequency();
if (lfr == 0) {
// Normal boot
} else if (lfr == M_FRQ_R) {
// Quick reboot
#if HAS_CONSOLE
if (rtc_get_reset_reason(0) == POWERON_RESET) {
console_active = true;
}
#endif
} else {
// Unknown boot
}
LoRa->setFrequency(M_FRQ_S);
#endif
} else {
modem_installed = false;
}
#else
// Older variants only came with SX1276/78 chips,
// so assume that to be the case for now.
modem_installed = true;
#endif
#if HAS_DISPLAY
#if HAS_EEPROM
if (EEPROM.read(eeprom_addr(ADDR_CONF_DSET)) != CONF_OK_BYTE) {
#elif MCU_VARIANT == MCU_NRF52
if (eeprom_read(eeprom_addr(ADDR_CONF_DSET)) != CONF_OK_BYTE) {
#endif
eeprom_update(eeprom_addr(ADDR_CONF_DSET), CONF_OK_BYTE);
#if BOARD_MODEL == BOARD_TECHO
eeprom_update(eeprom_addr(ADDR_CONF_DINT), 0x03);
#else
eeprom_update(eeprom_addr(ADDR_CONF_DINT), 0xFF);
#endif
}
#if BOARD_MODEL == BOARD_TECHO
display_add_callback(work_while_waiting);
#endif
display_unblank();
disp_ready = display_init();
if (disp_ready) {
update_display();
} else {
headless_mode = true;
Serial.println("[Headless] No display detected — running in headless mode");
}
#endif
// LED solid on at boot for V3/V4 boards (with or without display).
// In FIREWALL_MODE the OLED is the status indicator — keep the LED off.
#if (BOARD_MODEL == BOARD_HELTEC32_V4 || BOARD_MODEL == BOARD_HELTEC32_V3) && !defined(FIREWALL_MODE)
headless_led_solid();
#endif
// ── Firewall Mode: check if config portal is needed ──
#ifdef FIREWALL_MODE
{
// Load LoRa config from EEPROM so the portal can show current values
eeprom_conf_load();
// Load boundary config so the portal can show current/default values
firewall_load_config();
// ── Bootloop detection ───────────────────────────────────────────────
// Track rapid reboots in RTC memory. If the device reboots more than
// BOOTLOOP_THRESHOLD times within BOOTLOOP_WINDOW_MS, force the config
// portal so the user can fix bad settings.
bool bootloop_detected = false;
{
uint32_t now = millis();
if (bootloop_magic != BOOTLOOP_MAGIC) {
// First boot or power cycle — initialize counter
bootloop_magic = BOOTLOOP_MAGIC;
bootloop_count = 1;
bootloop_first_boot_ms = now;
} else {
bootloop_count++;
// Check if we're within the time window
if (bootloop_count >= BOOTLOOP_THRESHOLD) {
Serial.printf("[Boundary] BOOTLOOP DETECTED: %lu reboots — forcing config portal\r\n", bootloop_count);
bootloop_detected = true;
// Reset counter so next reboot after config portal doesn't re-trigger
bootloop_count = 0;
bootloop_magic = 0;
}
}
}
// Enter config mode if: first boot with no config, OR button-triggered reboot,
// OR bootloop detected
bool app_marker_missing = !firewall_app_marker_valid();
bool need_config = boundary_needs_config();
bool config_requested = (boundary_config_request == BOUNDARY_CONFIG_MAGIC);
bool skip_config = (boundary_skip_config == BOUNDARY_SKIP_MAGIC);
boundary_config_request = 0; // Clear flag immediately
boundary_skip_config = 0; // Clear skip flag immediately
// Skip flag only suppresses a button-triggered re-entry, not a genuinely
// unconfigured device. If there's no config saved, always show the portal.
if (skip_config && config_requested) {
Serial.println("[Boundary] Skipping config portal — user requested normal boot");
config_requested = false;
}
if (need_config || config_requested || bootloop_detected) {
if (bootloop_detected) {
Serial.println("[Boundary] Entering config portal due to bootloop recovery");
} else if (config_requested) {
Serial.println("[Boundary] Config mode requested via button hold");
} else if (app_marker_missing) {
Serial.println("[Boundary] RTNode app marker missing — previous firmware was not RTNode or config is unclaimed");
Serial.println("[Boundary] Starting config portal to migrate settings into RTNode");
} else {
Serial.println("[Boundary] No configuration found — starting config portal");
}
config_portal_start();
// Block here: only run the config portal until user saves and device reboots
// Track button state for "off" action (1-3s press = sleep)
bool wcc_btn_down = false;
uint32_t wcc_btn_down_at = 0;
while (config_portal_is_active()) {
config_portal_loop();
// Headless LED: slow ramp breathe effect during WCC mode
headless_led_ramp();
// Button handling: allow 1-3s press to turn off (deep sleep)
// Next power-on boots to normal mode since boundary_config_request is cleared
#if HAS_INPUT
{
int btn = digitalRead(pin_btn_usr1);
if (btn == LOW && !wcc_btn_down) {
wcc_btn_down = true;
wcc_btn_down_at = millis();
} else if (btn == HIGH && wcc_btn_down) {
uint32_t held = millis() - wcc_btn_down_at;
wcc_btn_down = false;
if (held >= 700 && held <= 5000) {
Serial.println("[Boundary] Button press in WCC mode — powering off");
boundary_skip_config = BOUNDARY_SKIP_MAGIC; // Skip config on next boot
headless_led_off();
config_portal_stop();
#if HAS_SLEEP
sleep_now();
#endif
}
}
}
#endif
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
delay(1);
}
// If we exit (shouldn't normally), reboot anyway
ESP.restart();
}
}
#endif
#if MCU_VARIANT == MCU_ESP32 || MCU_VARIANT == MCU_NRF52
#if HAS_PMU == true
pmu_ready = init_pmu();
#endif
#if HAS_BLUETOOTH || HAS_BLE == true
#ifndef FIREWALL_MODE
bt_init();
bt_init_ran = true;
#else
// Firewall mode: release BT controller memory (~70KB)
btStop();
esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
#endif
#else
#ifdef FIREWALL_MODE
// Even when BLE/BT are compile-time disabled (e.g. V3 boundary),
// the ESP32 BT controller is still loaded. Release its ~70KB of RAM.
btStop();
esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
Serial.write("[Boundary] Released BT controller memory\r\n");
#endif
#endif
#ifdef FIREWALL_MODE
// Initialize bt_devname for WiFi hostname when BT is disabled
#if HAS_BLUETOOTH || HAS_BLE == true
if (!bt_init_ran)
#endif
{
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA);
sprintf(bt_devname, "RNode %02X%02X", mac[4], mac[5]);
}
#endif
if (console_active) {
#if HAS_CONSOLE
console_start();
#else
kiss_indicate_reset();
#endif
} else {
#if HAS_WIFI
wifi_mode = EEPROM.read(eeprom_addr(ADDR_CONF_WIFI));
if (wifi_mode == WR_WIFI_STA || wifi_mode == WR_WIFI_AP) { wifi_remote_init(); }
#endif
kiss_indicate_reset();
}
#endif
#if MCU_VARIANT == MCU_ESP32 || MCU_VARIANT == MCU_NRF52
#if MODEM == SX1280
avoid_interference = false;
#else
#if HAS_EEPROM
uint8_t ia_conf = EEPROM.read(eeprom_addr(ADDR_CONF_DIA));
if (ia_conf == 0x00) { avoid_interference = true; }
else { avoid_interference = false; }
#elif MCU_VARIANT == MCU_NRF52
uint8_t ia_conf = eeprom_read(eeprom_addr(ADDR_CONF_DIA));
if (ia_conf == 0x00) { avoid_interference = true; }
else { avoid_interference = false; }
#endif
#endif
#endif
// Feed WDT before validation + radio start, which may take time
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
// Validate board health, EEPROM and config
validate_status();
if (op_mode != MODE_TNC) LoRa->setFrequency(0);
// CBA SD
#ifdef HAS_SDCARD
pinMode(SDCARD_MISO, INPUT_PULLUP);
SDSPI.begin(SDCARD_SCLK, SDCARD_MISO, SDCARD_MOSI, SDCARD_CS);
if (!SD.begin(SDCARD_CS, SDSPI)) {
Serial.println("setupSDCard FAIL");
} else {
uint32_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.print("setupSDCard PASS . SIZE = ");
Serial.print(cardSize / 1024.0);
Serial.println(" GB");
SD.remove("/logfile");
SD.remove("/logfile.txt");
SD.remove("/tracefile");
SD.remove("/tracedetails");
SD.remove("/tracefile.txt");
SD.remove("/tracedetails.txt");
Serial.println("DIR: /");
File root = SD.open("/");
File file = root.openNextFile();
while(file){
Serial.print(" FILE: ");
Serial.println(file.name());
file = root.openNextFile();
}
}
delay(3000);
#endif
#ifdef HAS_RNS
try {
// Feed WDT before filesystem init (may format on first boot)
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
// CBA Init filesystem
#if defined(RNS_USE_FS)
filesystem = new FileSystem();
((FileSystem*)filesystem.get())->init();
#else
filesystem = new NoopFileSystem();
((FileSystem*)filesystem.get())->init();
#endif
// Feed WDT after filesystem init
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
HEAD("Registering filesystem...", RNS::LOG_TRACE);
RNS::Utilities::OS::register_filesystem(filesystem);
#ifndef NDEBUG
//filesystem.remove_directory("/cache");
//filesystem.remove_file("/destination_table");
//filesystem.reformat();
TRACE("Listing filesystem...");
#if defined(RNS_USE_FS)
//FileSystem::listDir("/");
#endif
TRACE("Finished listing");
//TRACE("Dumping filesystem...");
//FileSystem::dumpDir("/");
//TRACE("Finished dumping");
//reticulum.clear_caches();
// CBA DEBUG
/*
std::list<std::string> files = filesystem.list_directory("/cache");
for (auto& file : files) {
Serial.print(" FILE: ");
Serial.println(file.c_str());
//RNS::Bytes content = filesystem.read_file(file.c_str());
//DEBUG(std::string("FILE: ") + file);
//DEBUG(content.toString());
}
*/
TRACE("FILE: destination_table");
RNS::Bytes content;
if (filesystem.read_file("/destination_table", content) > 0) {
TRACE(content.toString() + "\r\n");
}
#endif // NDEBUG
// CBA Start RNS
if (hw_ready) {
// Feed WDT before RNS startup (identity generation + crypto can be slow)
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
RNS::setLogCallback(&on_log);
RNS::Transport::set_receive_packet_callback(on_receive_packet);
RNS::Transport::set_transmit_packet_callback(on_transmit_packet);
Serial.write("Starting RNS...\r\n");
RNS::loglevel(RNS::LOG_VERBOSE);
//RNS::loglevel(RNS::LOG_TRACE);
//RNS::loglevel(RNS::LOG_MEM);
HEAD("Registering LoRA Interface...", RNS::LOG_TRACE);
lora_interface = new LoRaInterface();
RNS::Transport::register_interface(lora_interface);
RNS::Transport::register_local_client_interface(lora_interface);
#ifdef FIREWALL_MODE
// ── Firewall Mode: Load config and optionally set up WiFi + TCP ──
HEAD("Firewall Mode: Initializing...", RNS::LOG_TRACE);