forked from ratspeak/rsCardputer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1841 lines (1670 loc) · 69.8 KB
/
Copy pathmain.cpp
File metadata and controls
1841 lines (1670 loc) · 69.8 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
// =============================================================================
// csCardputer Standalone — Main Entry Point
// C1-C7: Radio, Keyboard, Display, Reticulum, Nodes, WiFi, LXMF
// =============================================================================
#include <Arduino.h>
#include <M5Unified.h>
#include <M5Cardputer.h>
#include <utility/PI4IOE5V6408_Class.hpp>
#include <SPI.h>
#include "config/BoardConfig.h"
#include "config/Config.h"
#include "radio/SX1262.h"
#include "input/Keyboard.h"
#include "input/HotkeyManager.h"
#include "ui/UIManager.h"
#include "ui/screens/BootScreen.h"
#include "ui/screens/HomeScreen.h"
#include "storage/FlashStore.h"
#include "storage/SDStore.h"
#include "storage/MessageStore.h"
#include "reticulum/ReticulumManager.h"
#include "reticulum/AnnounceManager.h"
#include "reticulum/LXMFManager.h"
#include "transport/WiFiInterface.h"
#include "transport/TCPClientInterface.h"
#include "transport/AutoInterfaceWrapper.h"
#include "config/UserConfig.h"
#include <esp_netif.h>
#include "ui/screens/NodesScreen.h"
#include "ui/screens/MessagesScreen.h"
#include "ui/screens/MessageView.h"
#include "ui/screens/SettingsScreen.h"
#include "ui/screens/NameInputScreen.h"
#include "ui/screens/DataCleanScreen.h"
#include "ui/screens/HelpOverlay.h"
#include "ui/screens/StampConfirmOverlay.h"
#include "ui/screens/RadioSetupScreen.h"
#include "ui/screens/RadioDiagnosticsScreen.h"
#include "ui/screens/PasswordScreen.h"
#include "reticulum/IdentityCrypto.h"
#include "security/Duress.h"
#include "storage/FactoryWipe.h"
#include "power/PowerManager.h"
#include "audio/AudioNotify.h"
#include "transport/BLEStub.h"
#include "hal/GPSManager.h"
#include <Preferences.h>
#include <atomic>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <list>
#include <string>
#include <esp_system.h>
#include <freertos/task.h>
SET_LOOP_TASK_STACK_SIZE(16384); // 16KB — needed for Ed25519 crypto in RNS boot
// --- Hardware ---
// Cardputer ADV display uses Arduino HSPI/SPI3 via M5GFX. Keep the external
// LoRa/SD bus on FSPI/SPI2 so display refreshes cannot reconfigure radio SPI.
SPIClass loraSPI(FSPI);
SX1262 radio(&loraSPI,
LORA_CS, LORA_SCK, LORA_MOSI, LORA_MISO,
LORA_RST, LORA_IRQ, LORA_BUSY, LORA_RXEN,
LORA_HAS_TCXO, LORA_DIO2_AS_RF_SWITCH);
// --- Subsystems ---
Keyboard keyboard;
HotkeyManager hotkeys;
UIManager ui;
FlashStore flash;
SDStore sdStore;
MessageStore messageStore;
ReticulumManager rns;
AnnounceManager* announceManager = nullptr;
RNS::HAnnounceHandler announceHandler;
LXMFManager lxmf;
WiFiInterface* wifiImpl = nullptr;
RNS::Interface wifiIface({RNS::Type::NONE});
std::vector<TCPClientInterface*> tcpClients;
std::list<RNS::Interface> tcpIfaces; // Must persist — Transport stores references (list: no realloc)
AutoInterfaceWrapper autoIface;
bool autoIfaceDeferredStart = false;
unsigned long autoIfaceDeferredAt = 0;
unsigned long tcpReloadAnnounceAt = 0; // deferred re-announce after TCP clients come up
unsigned long lastAutoIfaceLinkCheck = 0;
UserConfig userConfig;
PowerManager power;
AudioNotify audio;
BLEStub ble;
#if HAS_GPS
GPSManager gps;
#endif
// --- Screens ---
BootScreen bootScreen;
HomeScreen homeScreen;
NodesScreen nodesScreen;
MessagesScreen messagesScreen;
MessageView messageView;
NameInputScreen nameInputScreen;
DataCleanScreen dataCleanScreen;
SettingsScreen settingsScreen;
RadioSetupScreen radioSetupScreen;
RadioDiagnosticsScreen radioDiagnosticsScreen;
HelpOverlay helpOverlay;
StampConfirmOverlay stampConfirmOverlay;
PasswordScreen passwordScreen;
MigrationWarningScreen migrationScreen;
// Tab-screen mapping
Screen* tabScreens[4] = {nullptr, nullptr, nullptr, nullptr};
// --- State ---
bool radioOnline = false;
bool bootComplete = false;
volatile bool pendingMessageSound = false; // Deferred audio from packet callback
bool bootLoopRecovery = false;
bool wifiSTAStarted = false;
bool wifiSTAConnected = false;
// STA reconnects are scheduled from WiFi events and fired from loop().
std::atomic<bool> wifiNeedsReconnect{false};
std::atomic<unsigned long> wifiReconnectAt{0};
std::atomic<uint8_t> wifiReconnectAttempt{0};
constexpr unsigned long WIFI_BACKOFF_MS[4] = {5000, 15000, 60000, 300000};
constexpr unsigned long WIFI_NETIF_SETTLE_MS = 1500;
// --- Timing state (millis-based throttling) ---
unsigned long lastRNS = 0;
unsigned long lastRender = 0;
unsigned long lastAutoAnnounce = 0;
unsigned long lastHeartbeat = 0;
unsigned long lastStatusUpdate = 0;
unsigned long loopCycleStart = 0;
unsigned long maxLoopTime = 0;
// --- Intervals ---
constexpr unsigned long RNS_INTERVAL_MS = 10; // 100 Hz (matches Ratdeck)
constexpr unsigned long RENDER_INTERVAL_MS = 50; // 20 FPS
constexpr unsigned long STATUS_UPDATE_MS = 1000; // 1 Hz status bar
constexpr unsigned long ANNOUNCE_INTERVAL_MS = 120000; // 2 minutes
constexpr unsigned long HEARTBEAT_INTERVAL_MS = 5000;
constexpr unsigned long TCP_GLOBAL_BUDGET_MS = 12; // Max cumulative TCP time per loop
// Power-aware RNS interval
unsigned long rnsInterval = RNS_INTERVAL_MS;
static void scheduleWiFiReconnect() {
uint8_t attempt = wifiReconnectAttempt.load();
uint8_t idx = attempt < 4 ? attempt : 3;
unsigned long backoff = WIFI_BACKOFF_MS[idx];
if (backoff < WIFI_NETIF_SETTLE_MS) backoff = WIFI_NETIF_SETTLE_MS;
wifiReconnectAt.store(millis() + backoff);
wifiNeedsReconnect.store(true);
if (attempt < 4) wifiReconnectAttempt.store(attempt + 1);
}
static void onWiFiEvent(WiFiEvent_t event) {
switch (event) {
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
if (wifiNeedsReconnect.load()) break;
scheduleWiFiReconnect();
WiFi.disconnect(false, true);
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
wifiNeedsReconnect.store(false);
wifiReconnectAttempt.store(0);
break;
default:
break;
}
}
static void beginSTAConnection() {
auto& s = userConfig.settings();
if (s.wifiSTASSID.isEmpty()) return;
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(false);
if (s.autoIfaceEnabled) WiFi.enableIpV6();
WiFi.begin(s.wifiSTASSID.c_str(), s.wifiSTAPassword.c_str());
wifiSTAStarted = true;
Serial.printf("[WIFI] STA begin (SSID: %s)\n", s.wifiSTASSID.c_str());
}
// Time comes from GPS — see GPSManager for how the active POSIX TZ string
// is derived (TimeZoneDB match, longitude/season fallback, or a manual
// override from Settings). Falls back to UTC before the first fix.
static const char* currentPosixTZ() {
#if HAS_GPS
return gps.posixTZ();
#else
return "UTC0";
#endif
}
// =============================================================================
// TCP client management — stop old clients, create new from config
// =============================================================================
static void reloadTCPClients() {
// Stop all clients first (marks them offline, waits for any in-flight
// connect task to finish so the shared_ptr destructor below is safe)
for (auto* tcp : tcpClients) {
if (tcp) tcp->stop();
}
for (auto& iface : tcpIfaces) {
RNS::Transport::deregister_interface(iface);
}
tcpClients.clear();
// shared_ptr inside each RNS::Interface drops to 0 here → ~TCPClientInterface
tcpIfaces.clear();
// Create new clients from current config
if (WiFi.status() == WL_CONNECTED) {
for (auto& ep : userConfig.settings().tcpConnections) {
if (ep.autoConnect && !ep.host.isEmpty()) {
char name[32];
snprintf(name, sizeof(name), "TCP.%s", ep.host.c_str());
auto* tcp = new TCPClientInterface(ep.host.c_str(), ep.port, name);
tcpIfaces.emplace_back(tcp);
// MODE_FULL = standard client mode for connecting to a hub
// (MODE_GATEWAY is for the server-side interface facing clients)
tcpIfaces.back().mode(RNS::Type::Interface::MODE_FULL);
RNS::Transport::register_interface(tcpIfaces.back());
tcp->start();
tcpClients.push_back(tcp);
Serial.printf("[TCP] Created client: %s:%d\n", ep.host.c_str(), ep.port);
}
}
}
if (tcpClients.empty()) {
Serial.println("[TCP] No active TCP connections");
} else {
// Schedule a re-announce ~4 s from now so the hub learns our address
// on the freshly-established TCP connection. 4 s is enough time for
// the async connect task to complete before the announce goes out.
tcpReloadAnnounceAt = millis() + 4000;
}
}
// =============================================================================
// Hotkey callbacks
// =============================================================================
void onHotkeyHelp() {
Serial.println("[HOTKEY] Help overlay");
helpOverlay.toggle();
ui.setOverlay(helpOverlay.isVisible() ? &helpOverlay : nullptr);
}
void onHotkeyMessages() {
Serial.println("[HOTKEY] Jump to Messages");
ui.tabBar().setActiveTab(TabBar::TAB_MSGS);
ui.setScreen(&messagesScreen);
}
void onHotkeyNewMsg() {
Serial.println("[HOTKEY] New message");
ui.tabBar().setActiveTab(TabBar::TAB_MSGS);
ui.setScreen(&messagesScreen);
}
void onHotkeySettings() {
Serial.println("[HOTKEY] Jump to Settings");
ui.tabBar().setActiveTab(TabBar::TAB_SETUP);
ui.setScreen(&settingsScreen);
}
static void announceWithName(bool silent = false);
void onHotkeyAnnounce() {
Serial.println("[HOTKEY] Force announce");
announceWithName();
}
void onHotkeyDiag() {
Serial.println("=== DIAGNOSTIC DUMP ===");
Serial.printf("Identity: %s\n", rns.identityHash().c_str());
Serial.printf("Node: %s (endpoint, no forwarding)\n", rns.isTransportActive() ? "ONLINE" : "OFFLINE");
Serial.printf("Paths: %d Links: %d\n", (int)rns.pathCount(), (int)rns.linkCount());
Serial.printf("Radio: %s\n", radioOnline ? "ONLINE" : "OFFLINE");
if (radioOnline) {
Serial.printf("Freq: %lu Hz SF: %d BW: %lu CR: 4/%d TXP: %d dBm\n",
(unsigned long)radio.getFrequency(),
radio.getSpreadingFactor(),
(unsigned long)radio.getSignalBandwidth(),
radio.getCodingRate4(),
radio.getTxPower());
Serial.printf("Regulator: %s\n", LORA_USE_DCDC_REGULATOR ? "DC-DC" : "LDO");
Serial.printf("Preamble: %ld symbols\n", radio.getPreambleLength());
Serial.printf("IQ invert: %s\n", radio.getInvertIQ() ? "ON" : "off");
Serial.printf("SyncWord regs: 0x%02X%02X\n",
radio.readRegister(REG_SYNC_WORD_MSB_6X),
radio.readRegister(REG_SYNC_WORD_LSB_6X));
uint16_t devErr = radio.getDeviceErrors();
uint8_t status = radio.getStatus();
Serial.printf("DevErrors: 0x%04X Status: 0x%02X (mode=%d cmd=%d)\n",
devErr, status, (status >> 4) & 0x07, (status >> 1) & 0x07);
if (devErr & 0x40) Serial.println(" *** PLL LOCK FAILED ***");
Serial.printf("Current RSSI: %d dBm\n", radio.currentRssi());
Serial.println("--- SX1262 Register Dump ---");
Serial.printf(" 0x0740 (SyncWordMSB): 0x%02X\n", radio.readRegister(0x0740));
Serial.printf(" 0x0741 (SyncWordLSB): 0x%02X\n", radio.readRegister(0x0741));
Serial.printf(" 0x0889 (IQ polarity): 0x%02X\n", radio.readRegister(0x0889));
Serial.printf(" 0x0736 (IQ config): 0x%02X\n", radio.readRegister(0x0736));
Serial.printf(" 0x08AC (LNA): 0x%02X\n", radio.readRegister(0x08AC));
Serial.printf(" 0x08E7 (OCP): 0x%02X\n", radio.readRegister(0x08E7));
Serial.printf(" 0x08D8 (TX clamp): 0x%02X\n", radio.readRegister(REG_TX_CLAMP_CONFIG_6X));
uint8_t packetType = radio.getPacketType();
const char* packetTypeName =
(packetType == 0x00) ? "GFSK" :
(packetType == 0x01) ? "LoRa" :
(packetType == 0x02) ? "LR-FHSS" : "unknown";
Serial.printf(" packet_type: 0x%02X (%s)%s\n",
packetType, packetTypeName,
packetType == 0x01 ? "" : " *** NOT LoRa ***");
Serial.println("----------------------------");
}
Serial.printf("Free heap: %lu bytes\n", (unsigned long)ESP.getFreeHeap());
Serial.printf("Flash: used/total (see heartbeat for heap)\n");
Serial.printf("WriteQ pending: %d\n", messageStore.writeQueue().drainCount());
Serial.printf("Uptime: %lu s\n", millis() / 1000);
Serial.println("=======================");
}
// Ctrl+R: Continuous RSSI sampling for 5 seconds
volatile bool rssiMonitorActive = false;
void onHotkeyRssiMonitor() {
if (!radioOnline) {
Serial.println("[RSSI] Radio offline");
return;
}
Serial.println("[RSSI] Sampling RSSI for 5 seconds — transmit from another device now...");
rssiMonitorActive = true;
int minRssi = 0, maxRssi = -200;
unsigned long start = millis();
int samples = 0;
while (millis() - start < 5000) {
int rssi = radio.currentRssi();
if (rssi < minRssi) minRssi = rssi;
if (rssi > maxRssi) maxRssi = rssi;
samples++;
Serial.printf("[RSSI] %d dBm\n", rssi);
delay(100);
}
rssiMonitorActive = false;
Serial.printf("[RSSI] Done: %d samples, min=%d max=%d dBm\n", samples, minRssi, maxRssi);
Serial.printf("[RSSI] If max stayed near %d dBm, RX front-end may not be receiving RF\n", minRssi);
}
void onHotkeyRadioTest() {
Serial.println("[TEST] Sending raw radio test packet...");
uint8_t header = 0xA0;
const char* testPayload = "RSCARDPUTER_TEST_1234567890";
size_t totalLen = 1 + strlen(testPayload);
radio.beginPacket();
radio.write(header);
radio.write((const uint8_t*)testPayload, strlen(testPayload));
bool ok = radio.endPacket();
Serial.printf("[TEST] TX %s (%d bytes)\n", ok ? "OK" : "FAILED", (int)totalLen);
uint8_t verify[32] = {0};
radio.readBuffer(verify, totalLen);
Serial.printf("[TEST] FIFO verify: ");
for (size_t i = 0; i < totalLen; i++) Serial.printf("%02X ", verify[i]);
Serial.println();
radio.receive();
}
// =============================================================================
// Announce with display name
// =============================================================================
// LXMF announce app_data:
// [display_name(bin), stamp_cost(nil|uint), supported_functionality(array)]
// Always emit fixarray(3) so Python LXMF doesn't default auto_compress=True for
// our destinations. stamp_cost=nil means no inbound stamp is required. Empty
// supported_functionality list = we do NOT support SF_COMPRESSION (bz2).
static RNS::Bytes encodeAnnounceName(const String& name) {
size_t nameLen = name.length();
if (nameLen > 31) nameLen = 31;
uint8_t buf[5 + 31];
size_t i = 0;
buf[i++] = 0x93; // fixarray(3)
buf[i++] = 0xC4; // bin 8
buf[i++] = (uint8_t)nameLen;
if (nameLen) { memcpy(buf + i, name.c_str(), nameLen); i += nameLen; }
buf[i++] = 0xC0; // stamp_cost = nil (no stamp required)
buf[i++] = 0x90; // empty fixarray (no SF_* supported)
return RNS::Bytes(buf, i);
}
static void announceWithName(bool silent) {
RNS::Bytes appData = encodeAnnounceName(userConfig.settings().displayName);
Serial.printf("[ANNOUNCE-TX] name=\"%s\" appData=%d bytes silent=%s\n",
userConfig.settings().displayName.c_str(), (int)appData.size(),
silent ? "yes" : "no");
rns.announce(appData);
}
static bool enableCapLoRaRfSwitch() {
if (!m5::In_I2C.isEnabled()) {
if (!m5::In_I2C.begin(I2C_NUM_0, KB_SDA, KB_SCL)) {
Serial.println("[RADIO] Cap LoRa-1262 IOE init failed: I2C unavailable");
return false;
}
}
m5::PI4IOE5V6408_Class ioe(LORA_CAP_IOE_ADDR, 400000, &m5::In_I2C);
if (!ioe.begin()) {
Serial.println("[RADIO] Cap LoRa-1262 IOE not detected; RF switch enable skipped");
return false;
}
ioe.setDirection(LORA_CAP_RF_SW_PIN, true);
ioe.setHighImpedance(LORA_CAP_RF_SW_PIN, false);
ioe.digitalWrite(LORA_CAP_RF_SW_PIN, true);
delay(5);
Serial.println("[RADIO] Cap LoRa-1262 RF antenna switch enabled (IOE P0=HIGH)");
return true;
}
static void cycleDiagnosticTxPower() {
static constexpr int8_t kPowers[] = {-9, -3, 0, 2, 6, 10, 14, 17, LORA_MAX_TX_POWER};
int current = radio.getTxPower();
size_t next = 0;
for (size_t i = 0; i < sizeof(kPowers) / sizeof(kPowers[0]); i++) {
if (current == kPowers[i]) {
next = (i + 1) % (sizeof(kPowers) / sizeof(kPowers[0]));
break;
}
}
radio.setTxPower(kPowers[next]);
radio.receive();
Serial.printf("[SERIAL] transient TX power set to %d dBm\n", (int)kPowers[next]);
}
static void setDiagnosticMinTxPower() {
radio.setTxPower(-9);
radio.receive();
Serial.println("[SERIAL] transient TX power set to -9 dBm");
}
static bool setDiagnosticTxPower(int powerDbm) {
if (powerDbm < -9 || powerDbm > LORA_MAX_TX_POWER) {
Serial.printf("[SERIAL] TX power out of range: %d dBm (allowed -9..%d)\n",
powerDbm, (int)LORA_MAX_TX_POWER);
return false;
}
radio.setTxPower((int8_t)powerDbm);
radio.receive();
Serial.printf("[SERIAL] transient TX power set to %d dBm\n", powerDbm);
return true;
}
static void toggleDiagnosticInvertIQ() {
radio.setInvertIQ(!radio.getInvertIQ());
radio.receive();
Serial.printf("[SERIAL] IQ inversion %s\n", radio.getInvertIQ() ? "ON" : "off");
}
static bool setDiagnosticFrequency(uint32_t frequencyHz) {
if (frequencyHz < 150000000UL || frequencyHz > 960000000UL) {
Serial.printf("[SERIAL] frequency out of range: %lu Hz (allowed 150000000..960000000)\n",
(unsigned long)frequencyHz);
return false;
}
radio.setFrequency(frequencyHz);
radio.receive();
Serial.printf("[SERIAL] transient frequency set to %lu Hz\n", (unsigned long)frequencyHz);
return true;
}
static void nudgeDiagnosticFrequency(int32_t deltaHz) {
uint32_t next = radio.getFrequency() + deltaHz;
radio.setFrequency(next);
radio.receive();
Serial.printf("[SERIAL] transient frequency set to %lu Hz\n", (unsigned long)next);
}
static const char* skipSerialSeparators(const char* p) {
while (p && (*p == ' ' || *p == '\t' || *p == ':' || *p == '=' || *p == ',')) {
++p;
}
return p;
}
static bool hasSerialArgument(const char* p) {
p = skipSerialSeparators(p);
return p && *p != '\0';
}
static bool parseSerialLong(const char* p, long& value, const char** rest = nullptr) {
p = skipSerialSeparators(p);
if (!p || *p == '\0') return false;
char* end = nullptr;
value = std::strtol(p, &end, 10);
if (end == p) return false;
if (rest) *rest = end;
return true;
}
static bool parseSerialDestinationHash(const char* p, RNS::Bytes& hash) {
p = skipSerialSeparators(p);
if (!p || *p == '\0') return false;
char hex[33] = {0};
size_t len = 0;
while (*p && len < 32) {
unsigned char ch = (unsigned char)*p;
if (std::isxdigit(ch)) {
hex[len++] = (char)*p;
} else if (*p != ' ' && *p != '\t' && *p != ':' && *p != '=' && *p != ',' && *p != '-') {
return false;
}
++p;
}
if (len != 32) return false;
hash.assignHex(hex);
return hash.size() == 16;
}
static bool selectDiagnosticPeer(const char* explicitArg, RNS::Bytes& destHash, std::string& label) {
if (hasSerialArgument(explicitArg)) {
if (!parseSerialDestinationHash(explicitArg, destHash)) {
Serial.println("[SERIAL] invalid LXMF destination hash; expected 32 hex characters");
return false;
}
label = destHash.toHex();
return true;
}
if (!announceManager) {
Serial.println("[SERIAL] LXMF test failed: announce manager is not ready");
return false;
}
const std::string localHex = rns.destination().hash().toHex();
for (const auto& node : announceManager->nodes()) {
if (node.hash.size() != 16) continue;
const std::string nodeHex = node.hash.toHex();
if (nodeHex == localHex) continue;
destHash = node.hash;
label = node.name.empty() ? nodeHex : (node.name + " " + nodeHex);
return true;
}
Serial.println("[SERIAL] LXMF test failed: no peer known; send/receive announces first or pass a hash");
return false;
}
static std::string makeDiagnosticLxmfPayload(size_t length) {
static constexpr char kPrefix[] = "RSCARDPUTER-LXMF-TEST:";
static constexpr char kPattern[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
std::string out;
out.reserve(length);
for (size_t i = 0; kPrefix[i] && out.size() < length; ++i) {
out.push_back(kPrefix[i]);
}
for (size_t i = 0; out.size() < length; ++i) {
out.push_back(kPattern[i % (sizeof(kPattern) - 1)]);
}
return out;
}
static bool sendDiagnosticLxmf(size_t length, const char* explicitDest) {
static constexpr size_t kMaxDiagnosticLxmfChars = 512;
if (length == 0 || length > kMaxDiagnosticLxmfChars) {
Serial.printf("[SERIAL] LXMF test length out of range: %u (allowed 1..%u)\n",
(unsigned)length, (unsigned)kMaxDiagnosticLxmfChars);
return false;
}
RNS::Bytes destHash;
std::string peerLabel;
if (!selectDiagnosticPeer(explicitDest, destHash, peerLabel)) return false;
std::string payload = makeDiagnosticLxmfPayload(length);
bool ok = lxmf.sendMessage(destHash, payload);
Serial.printf("[SERIAL] LXMF test %s: len=%u dest=%s queue=%d\n",
ok ? "queued" : "rejected",
(unsigned)payload.size(),
peerLabel.c_str(),
lxmf.queuedCount());
return ok;
}
static void handleSerialLineCommand(const char* line) {
if (!line || !*line) return;
switch (line[0]) {
case 'F': {
long value = 0;
if (!parseSerialLong(line + 1, value) || value < 0) {
Serial.println("[SERIAL] usage: F<frequency_hz>, for example F915000000");
return;
}
setDiagnosticFrequency((uint32_t)value);
break;
}
case 'P': {
long value = 0;
if (!parseSerialLong(line + 1, value)) {
Serial.println("[SERIAL] usage: P<tx_power_dbm>, for example P1 or P5");
return;
}
setDiagnosticTxPower((int)value);
break;
}
case 'L': {
long length = 0;
const char* rest = nullptr;
if (!parseSerialLong(line + 1, length, &rest) || length <= 0) {
Serial.println("[SERIAL] usage: L<payload_chars> [dest_hash], for example L120");
return;
}
sendDiagnosticLxmf((size_t)length, rest);
break;
}
default:
Serial.printf("[SERIAL] unknown line command '%c'\n", line[0]);
break;
}
}
static void printSerialHelp() {
Serial.println("[SERIAL] commands: ? help | a announce | t raw-test | d diag | r rssi | p tx-power-cycle | m min-power | q iq | +/- freq | f rf-switch");
Serial.println("[SERIAL] line commands: F<hz> exact-frequency | P<dBm> exact-tx-power | L<len> [dest_hash] LXMF test");
}
static void handleSerialCommands() {
static char line[96];
static size_t lineLen = 0;
static bool lineActive = false;
while (Serial.available() > 0) {
char c = (char)Serial.read();
if (lineActive) {
if (c == '\r' || c == '\n') {
line[lineLen] = '\0';
handleSerialLineCommand(line);
lineLen = 0;
lineActive = false;
continue;
}
if (lineLen + 1 >= sizeof(line)) {
Serial.println("[SERIAL] line command too long; discarded");
lineLen = 0;
lineActive = false;
continue;
}
line[lineLen++] = c;
continue;
}
if (c == '\r' || c == '\n' || c == ' ' || c == '\t') continue;
if (c == 'F' || c == 'P' || c == 'L') {
lineActive = true;
lineLen = 0;
line[lineLen++] = c;
continue;
}
switch (c) {
case '?':
printSerialHelp();
break;
case 'a':
case 'A':
announceWithName(false);
break;
case 't':
case 'T':
onHotkeyRadioTest();
break;
case 'd':
case 'D':
onHotkeyDiag();
break;
case 'r':
case 'R':
onHotkeyRssiMonitor();
break;
case 'p':
cycleDiagnosticTxPower();
break;
case 'm':
case 'M':
setDiagnosticMinTxPower();
break;
case 'q':
case 'Q':
toggleDiagnosticInvertIQ();
break;
case '+':
case '=':
nudgeDiagnosticFrequency(1000);
break;
case '-':
case '_':
nudgeDiagnosticFrequency(-1000);
break;
case 'f':
enableCapLoRaRfSwitch();
break;
default:
Serial.printf("[SERIAL] unknown command '%c'\n", c);
printSerialHelp();
break;
}
}
}
// =============================================================================
// Boot-time blocking helpers (password / migration prompts)
// =============================================================================
//
// These run BEFORE the main loop() exists, so they can't rely on it for
// rendering or input. They poll the keyboard directly and call ui.render()
// every frame. They are intentionally synchronous — the device is not
// transmitting yet, the radio is in receive mode but Reticulum hasn't
// started, so blocking here is safe.
static void runBlockingInputLoop(std::function<bool()> doneCheck) {
keyboard.setMode(InputMode::TextInput);
while (!doneCheck()) {
M5.update();
keyboard.update();
if (keyboard.hasEvent()) {
const KeyEvent& evt = keyboard.getEvent();
ui.handleKey(evt);
}
ui.markAllDirty();
ui.render();
ui.flush();
delay(20);
}
keyboard.setMode(InputMode::Navigation);
}
// Read the largest identity blob available from any tier. Used to fetch
// the encrypted envelope for password-attempt unwrapping. Returns true if
// any tier yielded usable bytes.
static bool readAnyIdentityBlob(RNS::Bytes& out) {
uint8_t buf[512];
size_t len = 0;
out = RNS::Bytes();
// Flash
if (flash.exists(PATH_IDENTITY)) {
if (flash.readFile(PATH_IDENTITY, buf, sizeof(buf), len) && len > 0) {
if (IdentityCrypto::isEncrypted(buf, len)) {
out = RNS::Bytes(buf, len);
return true;
}
}
}
// NVS
{
Preferences prefs;
if (prefs.begin("ratcom_id", true)) {
size_t nvsLen = prefs.getBytesLength("encid");
if (nvsLen > 0 && nvsLen <= sizeof(buf)) {
prefs.getBytes("encid", buf, nvsLen);
prefs.end();
if (IdentityCrypto::isEncrypted(buf, nvsLen)) {
out = RNS::Bytes(buf, nvsLen);
return true;
}
} else {
prefs.end();
}
}
}
// SD
if (sdStore.isReady() && sdStore.exists(SD_PATH_IDENTITY)) {
len = 0;
if (sdStore.readFile(SD_PATH_IDENTITY, buf, sizeof(buf), len) && len > 0) {
if (IdentityCrypto::isEncrypted(buf, len)) {
out = RNS::Bytes(buf, len);
return true;
}
}
}
return false;
}
// Outcome of the password gate. Carries the verified password (and, for
// the ENCRYPTED path, the decrypted identity private key) to the caller.
struct PasswordGateResult {
bool ok = false;
String password;
RNS::Bytes unlockedKey; // empty for SETUP path; populated for UNLOCK
bool legacyDetected = false;
};
// Drive the password screens until we either obtain a verified password or
// hit the hard lockout (in which case we halt). On lockout we do NOT
// proceed to boot — the user must power cycle.
static PasswordGateResult runPasswordGate(ReticulumManager::IdentityState state) {
PasswordGateResult res;
if (state == ReticulumManager::IdentityState::ENCRYPTED) {
RNS::Bytes blob;
if (!readAnyIdentityBlob(blob)) {
Serial.println("[BOOT] State=ENCRYPTED but no readable blob — bailing");
return res;
}
passwordScreen.setMode(PasswordScreen::Mode::UNLOCK);
ui.setScreen(&passwordScreen);
constexpr int MAX_ATTEMPTS = 10;
int attempts = 0;
bool done = false;
String submitted;
passwordScreen.setSubmitCallback([&](const String& pw) {
submitted = pw;
done = true;
});
for (;;) {
done = false;
submitted = "";
runBlockingInputLoop([&]() { return done; });
RNS::Bytes plain;
if (IdentityCrypto::unwrap(submitted, blob, plain)) {
res.ok = true;
res.password = submitted;
res.unlockedKey = plain;
IdentityCrypto::secureZero((void*)submitted.c_str(), submitted.length());
return res;
}
// Duress check — a separate password that wipes the device
// instead of unlocking it. Checked only after the real password
// fails, so a correct real password always wins on the (should
// never happen) chance the two were ever made to collide. On
// match this never returns: wipe, then reboot straight into the
// normal fresh-device setup flow with no special-case screen —
// to anyone watching, the device just reset itself.
if (Duress::isConfigured() && Duress::check(submitted)) {
IdentityCrypto::secureZero((void*)submitted.c_str(), submitted.length());
Serial.println("[BOOT] Duress password entered — wiping all data");
FactoryWipe::wipeAll(&flash, &sdStore);
delay(300);
ESP.restart();
}
attempts++;
int remaining = MAX_ATTEMPTS - attempts;
if (remaining <= 0) {
passwordScreen.setLockedOut();
ui.markAllDirty();
ui.render();
ui.flush();
Serial.println("[BOOT] Hard lockout — halting boot");
// Halt — no further attempts until power cycle.
for (;;) {
M5.update();
keyboard.update();
(void)keyboard.hasEvent();
ui.render();
ui.flush();
delay(200);
}
}
passwordScreen.setUnlockFailed(remaining);
Serial.printf("[BOOT] Unlock failed, %d remaining\n", remaining);
// Small delay to slow automated guessing within a single boot.
delay(800);
}
}
// SETUP path: first-boot or legacy plaintext identity. Show setup.
passwordScreen.setMode(PasswordScreen::Mode::SETUP);
ui.setScreen(&passwordScreen);
bool done = false;
String submitted;
passwordScreen.setSubmitCallback([&](const String& pw) {
submitted = pw;
done = true;
});
runBlockingInputLoop([&]() { return done; });
res.ok = true;
res.password = submitted;
res.legacyDetected = (state == ReticulumManager::IdentityState::LEGACY_PLAINTEXT);
IdentityCrypto::secureZero((void*)submitted.c_str(), submitted.length());
return res;
}
// Drive the migration warning screen and execute the chosen action.
// Caller has already set the password on rns. Identity is loaded
// (legacy plaintext form) and MessageStore is initialized.
static void runLegacyIdentityMigration() {
ui.setScreen(&migrationScreen);
bool done = false;
MigrationWarningScreen::Choice choice = MigrationWarningScreen::Choice::IDENTITY_ONLY;
migrationScreen.setChoiceCallback([&](MigrationWarningScreen::Choice c) {
choice = c;
done = true;
});
runBlockingInputLoop([&]() { return done; });
migrationScreen.setProgress("Encrypting identity...");
ui.markAllDirty(); ui.render(); ui.flush();
if (!rns.migrateLegacyIdentity()) {
migrationScreen.setProgress("Identity migration FAILED");
ui.markAllDirty(); ui.render(); ui.flush();
delay(2500);
return;
}
if (choice == MigrationWarningScreen::Choice::ALL_MESSAGES) {
char buf[48];
int converted = messageStore.migratePlaintextMessages(
[&](int cur, int total, const char* peer) {
snprintf(buf, sizeof(buf), "Encrypting messages %d/%d", cur, total);
migrationScreen.setProgress(buf);
// Re-render every few files so progress is visible
if ((cur & 0x07) == 0 || cur == total) {
ui.markAllDirty(); ui.render(); ui.flush();
}
});
snprintf(buf, sizeof(buf), "Encrypted %d messages", converted);
migrationScreen.setProgress(buf);
} else {
migrationScreen.setProgress("Identity encrypted");
}
ui.markAllDirty(); ui.render(); ui.flush();
delay(1200);
}
// =============================================================================
// Setup
// =============================================================================
void setup() {
// Initialize M5Cardputer (includes M5Unified + keyboard)
auto cfg = M5.config();
cfg.serial_baudrate = SERIAL_BAUD;
M5Cardputer.begin(cfg, true);
Serial.println();
Serial.println("=================================");
Serial.printf(" csCardputer Standalone v%s\n", RSCARDPUTER_VERSION_STRING);
Serial.println(" M5Stack Cardputer Adv");
Serial.println("=================================");
esp_reset_reason_t reason = esp_reset_reason();
const char* reasonStr = "UNKNOWN";
switch (reason) {
case ESP_RST_POWERON: reasonStr = "POWER_ON"; break;
case ESP_RST_SW: reasonStr = "SOFTWARE"; break;
case ESP_RST_PANIC: reasonStr = "PANIC (crash!)"; break;
case ESP_RST_INT_WDT: reasonStr = "INT_WDT (interrupt watchdog!)"; break;
case ESP_RST_TASK_WDT: reasonStr = "TASK_WDT (task watchdog!)"; break;
case ESP_RST_WDT: reasonStr = "WDT (other watchdog!)"; break;
case ESP_RST_BROWNOUT: reasonStr = "BROWNOUT (low voltage!)"; break;
case ESP_RST_DEEPSLEEP: reasonStr = "DEEP_SLEEP"; break;
default: break;
}
Serial.printf("[BOOT] Reset reason: %s (%d)\n", reasonStr, (int)reason);
Serial.printf("[BOOT] Free heap: %lu, min ever: %lu\n",
(unsigned long)ESP.getFreeHeap(), (unsigned long)ESP.getMinFreeHeap());
// Mount flash early (before UI) purely so a saved theme.json can be
// applied before the very first frame is drawn. FlashStore::begin() is
// idempotent — the existing mount call later in setup() just confirms
// the same state and still drives its own boot-screen progress step.
// This does not move or affect the identity-at-rest gate ordering.
flash.begin();
Theme::load(&flash, nullptr);
// Initialize UI + boot screen
ui.begin();
ui.setBootMode(true);
ui.setScreen(&bootScreen);
bootScreen.setProgress(0.1f, "Display ready");
ui.render();
// Play the boot mark's intro animation (wipe-in, decrypt-scramble
// title, then the bar/status fade-in) out to completion before doing
// any real init work. Without this, BootScreen only gets repainted
// once per init step below — far too few frames for the animation to
// read as motion. This is a fixed, one-time ~1s cosmetic cost paid