-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathRNode_Firmware.ino
More file actions
executable file
·2865 lines (2567 loc) · 90.6 KB
/
RNode_Firmware.ino
File metadata and controls
executable file
·2865 lines (2567 loc) · 90.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 Boundary Mode
// NOTE: Boundary Mode is the legacy name. This firmware branch intends to
// converge on a single Transport Mode, with the BOUNDARY_MODE symbol kept
// temporarily as a compatibility shim during cleanup.
#ifdef BOUNDARY_MODE
#include "BoundaryMode.h"
#include "TcpInterface.h"
#include "BoundaryConfig.h"
#include "Advertise.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>
#endif
// 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;
#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) {
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
TRACEF("LoRaInterface.send_outgoing: (%u bytes) data: %s", data.size(), data.toHex().c_str());
TRACE("LoRaInterface.send_outgoing: adding packet to outgoing queue...");
for (size_t i = 0; i < data.size(); i++) {
if (queue_height < CONFIG_QUEUE_MAX_LENGTH && queued_bytes < CONFIG_QUEUE_SIZE) {
queued_bytes++;
packet_queue[queue_cursor++] = data.data()[i];
if (queue_cursor == CONFIG_QUEUE_SIZE) queue_cursor = 0;
}
}
if (!fifo16_isfull(&packet_starts) && queued_bytes < CONFIG_QUEUE_SIZE) {
uint16_t s = current_packet_start;
int16_t e = queue_cursor-1; if (e == -1) e = CONFIG_QUEUE_SIZE-1;
uint16_t l;
if (s != e) {
l = (s < e) ? e - s + 1 : CONFIG_QUEUE_SIZE - s + e + 1;
} else {
l = 1;
}
if (l >= MIN_L) {
queue_height++;
fifo16_push(&packet_starts, s);
fifo16_push(&packet_lengths, l);
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 BOUNDARY_MODE
// Boundary mode: TCP backbone interface + state
BoundaryState boundary_state = {};
RNS::Interface tcp_rns_interface(RNS::Type::NONE);
TcpInterface* tcp_interface_ptr = nullptr;
// Local TCP server (MODE_ACCESS_POINT, doesn't forward announces)
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
#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);
// 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);
#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)
#if BOARD_MODEL == BOARD_HELTEC32_V4 || BOARD_MODEL == BOARD_HELTEC32_V3
headless_led_solid();
#endif
// ── Boundary Mode: check if config portal is needed ──
#ifdef BOUNDARY_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
boundary_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 = !boundary_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 BOUNDARY_MODE
bt_init();
bt_init_ran = true;
#else
// Boundary mode: release BT controller memory (~70KB)
btStop();
esp_bt_controller_mem_release(ESP_BT_MODE_BTDM);
#endif
#else
#ifdef BOUNDARY_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 BOUNDARY_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();
lora_interface.mode(RNS::Type::Interface::MODE_ACCESS_POINT);
RNS::Transport::register_interface(lora_interface);
#ifdef BOUNDARY_MODE
// ── Boundary Mode: Load config and optionally set up WiFi + TCP ──
HEAD("Boundary Mode: Initializing...", RNS::LOG_TRACE);
// ESP32 has only ~324KB heap. Each path entry with random_blobs costs
// ~200-500 bytes. Keep tables small to avoid heap exhaustion.
// cull_path_table() evicts backbone paths first, preserving local ones.
RNS::Transport::path_table_maxsize(24);
RNS::Transport::path_table_maxpersist(12);
boundary_load_config();
// Set up IFAC on the LoRa interface if configured
if (boundary_state.ifac_enabled &&
(boundary_state.ifac_netname[0] != '\0' || boundary_state.ifac_passphrase[0] != '\0')) {
HEAD("Setting up IFAC on LoRa interface...", RNS::LOG_TRACE);
lora_interface.setup_ifac(boundary_state.ifac_netname, boundary_state.ifac_passphrase);
{
char _ifac_msg[96];
snprintf(_ifac_msg, sizeof(_ifac_msg), "IFAC configured: netname=%s, passphrase=%s",
boundary_state.ifac_netname[0] ? boundary_state.ifac_netname : "(none)",
boundary_state.ifac_passphrase[0] ? "***" : "(none)");
HEAD(_ifac_msg, RNS::LOG_TRACE);
}
}
// Start WiFi if enabled
if (boundary_state.wifi_enabled) {
if (!wifi_initialized) {
if (wifi_mode != WR_WIFI_STA && wifi_mode != WR_WIFI_AP) {
wifi_mode = WR_WIFI_STA;
EEPROM.write(eeprom_addr(ADDR_CONF_WIFI), wifi_mode);
EEPROM.commit();
}
wifi_remote_init();
}
} else {
HEAD("Boundary Mode: WiFi DISABLED (LoRa-only repeater)", RNS::LOG_TRACE);
}
// Register TCP backbone interface if enabled (mode 1 = client)
if (boundary_state.wifi_enabled && boundary_state.tcp_mode == 1) {
tcp_interface_ptr = new TcpInterface(
TCP_IF_MODE_CLIENT,
boundary_state.tcp_port,
boundary_state.backbone_host,
boundary_state.backbone_port
);
tcp_rns_interface = tcp_interface_ptr;
tcp_rns_interface.mode(RNS::Type::Interface::MODE_BOUNDARY);
tcp_rns_interface.is_backbone(true);
RNS::Transport::register_interface(tcp_rns_interface);
{
char _bm_msg[128];
snprintf(_bm_msg, sizeof(_bm_msg), "TCP backbone: client -> %s:%d",
boundary_state.backbone_host, boundary_state.backbone_port);
HEAD(_bm_msg, RNS::LOG_TRACE);
}
} else if (boundary_state.tcp_mode == 0) {
HEAD("Boundary Mode: TCP backbone DISABLED", RNS::LOG_TRACE);
}
// Register local TCP server if enabled
// MODE_GATEWAY allows announce rebroadcasts so local TCP clients
// can discover each other and receive backbone announces.
// (MODE_ACCESS_POINT blocks all announce broadcasts in outbound(),
// which prevented local clients from finding paths to each other.)
if (boundary_state.wifi_enabled && boundary_state.ap_tcp_enabled) {
local_tcp_interface_ptr = new TcpInterface(
TCP_IF_MODE_SERVER,
boundary_state.ap_tcp_port,
"", // no target host for server mode
0,
"LocalTcpInterface"
);
// rnsd can be quiet for long stretches — use 10 min timeout
// to prevent unnecessary reconnection cycles that leak lwIP memory
local_tcp_interface_ptr->setReadTimeout(600000);
local_tcp_rns_interface = local_tcp_interface_ptr;
local_tcp_rns_interface.mode(RNS::Type::Interface::MODE_GATEWAY);
RNS::Transport::register_interface(local_tcp_rns_interface);
// Register as local client interface so Transport forwards
// announces, link packets, and proofs to TCP clients
RNS::Transport::register_local_client_interface(local_tcp_rns_interface);
{
char _bm_msg[128];
snprintf(_bm_msg, sizeof(_bm_msg), "Local TCP server: port %d (GATEWAY mode)",
boundary_state.ap_tcp_port);
HEAD(_bm_msg, RNS::LOG_TRACE);
}
}
#endif
// Feed WDT before Reticulum instance creation (loads caches, generates keys)
#if MCU_VARIANT == MCU_ESP32
esp_task_wdt_reset();
#endif
HEAD("Creating Reticulum instance...", RNS::LOG_TRACE);
reticulum = RNS::Reticulum();
#ifdef BOUNDARY_MODE
// In boundary mode, transport is ALWAYS enabled
reticulum.transport_enabled(true);
#else
reticulum.transport_enabled(op_mode == MODE_TNC);
#endif
reticulum.probe_destination_enabled(true);
reticulum.start();
#ifdef BOUNDARY_MODE
// Start TCP interfaces after Reticulum is running
if (boundary_state.wifi_enabled && (wifi_is_connected() || wifi_mode == WR_WIFI_AP)) {
if (tcp_interface_ptr) {
tcp_interface_ptr->start();
HEAD("Boundary Mode: TCP backbone started", RNS::LOG_TRACE);
}
if (local_tcp_interface_ptr) {
local_tcp_interface_ptr->start();
HEAD("Boundary Mode: Local TCP server started", RNS::LOG_TRACE);
}
} else if (boundary_state.wifi_enabled) {
HEAD("Boundary Mode: Waiting for WiFi before starting TCP interfaces", RNS::LOG_WARNING);
}
#endif
// CBA load/create local destination for admin node
/*
RNS::Identity identity = {RNS::Type::NONE};
std::string local_identity_path = RNS::Reticulum::_storagepath + "/local_identity";
if (RNS::Utilities::OS::file_exists(local_identity_path.c_str())) {
identity = RNS::Identity::from_file(local_identity_path.c_str());
}
if (!identity) {
RNS::verbose("No valid local identity in storage, creating...");
identity = RNS::Identity();
identity.to_file(local_identity_path.c_str());
}
else {
RNS::verbose("Loaded local identity from storage");
}
RNS::Destination destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "rnstransport", "local");
*/
RNS::Destination destination(RNS::Transport::identity(), RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "rnstransport", "local");
// Cache this node's destination hash in RTC memory so the captive-portal
// config page can show it without needing RNS to be running.
{
std::string h = destination.hash().toHex();
size_t len = h.length();
if (len > 32) len = 32;
memcpy(rtc_node_hash_hex, h.c_str(), len);
rtc_node_hash_hex[len] = '\0';
rtc_node_hash_magic = NODE_HASH_RTC_MAGIC;
}
#ifdef BOUNDARY_MODE
// Initialise the Reticulum interface-discovery announcer. Per the
// Reticulum manual (https://reticulum.network/manual/interfaces.html)
// this announces this node and its parameters on the network so that
// maps such as rmap.world can automatically place a pin for it. The
// announcer is a no-op until the user has enabled "Advertise Device"
// in the captive-portal configuration.
advertise_init();
#endif
HEAD("RNS is READY!", RNS::LOG_TRACE);
#ifdef BOUNDARY_MODE
HEAD("*** BOUNDARY MODE ACTIVE ***", RNS::LOG_TRACE);
HEAD("RNS transport mode is ENABLED (boundary)", RNS::LOG_TRACE);
HEAD("LoRa Interface: MODE_ACCESS_POINT", RNS::LOG_TRACE);
{
char _bm_info[128];
if (boundary_state.tcp_mode == 1) {
snprintf(_bm_info, sizeof(_bm_info), "TCP Backbone: client -> %s:%d",
boundary_state.backbone_host, boundary_state.backbone_port);
HEAD(_bm_info, RNS::LOG_TRACE);
} else {
HEAD("TCP Backbone: DISABLED", RNS::LOG_TRACE);
}
if (boundary_state.ap_tcp_enabled) {
snprintf(_bm_info, sizeof(_bm_info), "Local TCP Server: port %d (MODE_ACCESS_POINT)",
boundary_state.ap_tcp_port);
HEAD(_bm_info, RNS::LOG_TRACE);
}
if (!boundary_state.wifi_enabled) {
HEAD("WiFi: DISABLED (LoRa-only repeater)", RNS::LOG_TRACE);
}
}
#endif
if (op_mode == MODE_TNC) {
HEAD("RNS transport mode is ENABLED", RNS::LOG_TRACE);
TRACEF("Frequency: %d Hz", lora_freq);
TRACEF("Bandwidth: %d Hz", lora_bw);
TRACEF("TX Power: %d dBm", lora_txp);
TRACEF("Spreading Factor: %d", lora_sf);
TRACEF("Coding Rate: %d", lora_cr);
}
else {
HEAD("RNS transport mode is DISABLED", RNS::LOG_INFO);
HEAD("Configure TNC mode with radio configuration to enable RNS transport", RNS::LOG_INFO);
}
//RNS::loglevel(RNS::LOG_NONE);
}
else {
HEAD("RNS is inoperable because hardware is not ready!", RNS::LOG_ERROR);
HEAD("Check firmware signature and eeprom provisioning", RNS::LOG_ERROR);
// CBA Clear cached files just in case cached files are responsible for failure