-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWifiManager.cpp
More file actions
1139 lines (1058 loc) · 54.3 KB
/
Copy pathWifiManager.cpp
File metadata and controls
1139 lines (1058 loc) · 54.3 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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 Dobrev IT Ltd
//
// This file is part of RetiMesh Node.
//
// RetiMesh Node 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.
//
// RetiMesh Node 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 RetiMesh Node. If not, see <https://www.gnu.org/licenses/>.
// ============================================================================
// WifiManager.cpp — see WifiManager.h for the service overview.
// ============================================================================
#include "WifiManager.h"
#include <sys/stat.h>
#include "QrCode.h"
#include "Pmu.h"
#include "Gps.h"
#include <LittleFS.h>
#include <ArduinoJson.h>
#include <esp_wifi.h>
#include <esp_heap_caps.h>
#include <ESPmDNS.h>
#include "LoRaRadio.h"
#include "Neighbors.h"
#include "RnsAnnounce.h"
#include "RnsTransport.h"
#include "Mdns.h"
#include "Diag.h"
#include "SdCard.h"
#include "AutoInterface.h"
#include "Power.h"
WifiManager wifiManager;
static const char PORTAL_URL[] = "http://10.42.0.1/";
static const char ADMIN_USER[] = "admin";
// ---------------------------------------------------------------------------
// Body accumulation for JSON POSTs. Chunks land in request->_tempObject,
// which the request destructor free()s. Returns the complete body on the
// final chunk, nullptr while more is coming (or after sending an error).
// ---------------------------------------------------------------------------
static const char* collectBody(AsyncWebServerRequest* request, const uint8_t* data,
size_t len, size_t index, size_t total) {
if (total == 0 || total > 2048) {
if (index == 0) request->send(413, "application/json", "{\"error\":\"too large\"}");
return nullptr;
}
if (index == 0) request->_tempObject = malloc(total + 1);
auto* body = static_cast<char*>(request->_tempObject);
if (body == nullptr) {
if (index + len >= total) request->send(500);
return nullptr;
}
memcpy(body + index, data, len);
if (index + len < total) return nullptr;
body[total] = '\0';
return body;
}
static void sendJson(AsyncWebServerRequest* r, int code, const JsonDocument& doc) {
String out;
serializeJson(doc, out);
r->send(code, "application/json", out);
}
static void sendError(AsyncWebServerRequest* r, int code, const char* msg) {
JsonDocument d;
d["error"] = msg;
sendJson(r, code, d);
}
// ---------------------------------------------------------------------------
void WifiManager::begin() {
startAccessPoint();
// Captive portal: answer every DNS query with our own address. The OS
// connectivity probes then hit port 80 and get redirected below, which
// pops the "sign in to network" sheet on Android/iOS/Windows.
_dns.setErrorReplyCode(DNSReplyCode::NoError);
_dns.setTTL(60);
_dns.start(53, "*", AP_IP);
setupRoutes();
_http.begin();
// http://retimesh.local/ (and http://<ssid>.local/) for clients whose
// captive-portal detection does not fire.
// Compare the stamp baked into this firmware against the one in the image it
// is serving. They are produced together by tools/asset_stamp.py, so a
// mismatch means only one half was flashed — the portal will be subtly wrong
// in ways nothing else reports.
{
File f = LittleFS.open("/assets.json", "r");
if (f) {
JsonDocument sd;
if (deserializeJson(sd, f) == DeserializationError::Ok) _assetStamp = sd["stamp"] | "";
f.close();
}
if (_assetStamp == ASSET_STAMP) {
log_i("web assets match this firmware (build %s)", ASSET_STAMP);
} else {
log_w("web assets were built from a different firmware: image has \"%s\", firmware "
"expects \"%s\". The portal may be missing controls this firmware supports, or "
"offer some it does not. Upload the filesystem to match — note that doing so "
"erases anything else on it, including the Reticulum store on boards with no "
"SD card.",
_assetStamp.isEmpty() ? "(none)" : _assetStamp.c_str(), ASSET_STAMP);
}
}
deriveHostname();
if (MDNS.begin(_hostname)) {
MDNS.addService("http", "tcp", HTTP_PORT);
MDNS.addService("rns", "tcp", RNS_TCP_PORT);
// So a browser or a script can tell the nodes apart without opening each
// one: the same identity the portal and the announce carry.
for (const char* svc : { "http", "rns" }) {
MDNS.addServiceTxt(svc, "tcp", "name", _ssid);
MDNS.addServiceTxt(svc, "tcp", "node", nodeIdentity.destHex());
MDNS.addServiceTxt(svc, "tcp", "fw", FW_VERSION);
MDNS.addServiceTxt(svc, "tcp", "board", BOARD_NAME);
}
log_i("mDNS: http://%s.local (rns on :%d) — browse _rns._tcp to find every node",
_hostname, RNS_TCP_PORT);
} else {
log_w("mDNS start failed");
}
log_i("SoftAP \"%s\" (%s) up at %s (http:%d, rns:%d)", _ssid, _securityName,
WiFi.softAPIP().toString().c_str(), HTTP_PORT, RNS_TCP_PORT);
}
void WifiManager::startAccessPoint() {
const WifiSettings& w = settings.wifi();
#ifdef AP_SSID
strlcpy(_ssid, AP_SSID, sizeof(_ssid));
#else
if (w.ssid[0] != '\0') {
strlcpy(_ssid, w.ssid, sizeof(_ssid));
} else {
// Factory base MAC from efuse: stable across boots and identical to
// the STA MAC (the SoftAP MAC is base+1, so it is deliberately not
// used).
uint64_t mac = ESP.getEfuseMac(); // little-endian: octet 0 in the LSB
snprintf(_ssid, sizeof(_ssid), "%s-%02X%02X%02X", AP_SSID_PREFIX,
(uint8_t)(mac >> 24), (uint8_t)(mac >> 32), (uint8_t)(mac >> 40));
}
#endif
// Every node used to answer to the same "retimesh.local", so the second one
// on a network either lost the race or was silently renamed by conflict
// resolution to something nobody could predict — which made more than one
// node on one LAN unusable. The access-point name is already unique per node
// and already what the display and the portal show, so the mDNS name is that
// name rather than a second derivation from the MAC that could drift from it.
//
// mDNS labels are letters, digits and hyphens, compared without regard to
// case, so an SSID someone has renamed to "Shed roof" still yields a legal
// "shed-roof.local".
// WPA needs 8..63 characters; anything else means an open network.
bool secured = w.security != ApSecurity::Open && strlen(w.password) >= 8;
const char* pass = secured ? w.password : nullptr;
WiFi.persistent(false);
WiFi.mode(stationConfigured() ? WIFI_AP_STA : WIFI_AP);
WiFi.softAPConfig(AP_IP, AP_IP, AP_NETMASK);
WiFi.softAP(_ssid, pass, w.channel, w.hidden ? 1 : 0, w.maxStations);
// Station mode: join the configured LAN too. The AP and the STA share
// one radio, so the AP follows the LAN's channel once connected.
if (stationConfigured()) {
WiFi.setAutoReconnect(true);
WiFi.begin(w.staSsid, w.staPassword[0] ? w.staPassword : nullptr);
log_i("station: joining \"%s\"", w.staSsid);
_staRetryAt = millis() + 30000;
}
_securityName = secured ? "wpa2" : "open";
// The Arduino wrapper only knows open/WPA2. WPA3 (SAE) is set through
// ESP-IDF: in IDF 4.4 the AP config accepts WPA2_WPA3_PSK / WPA3_PSK as
// auth modes (cipher forced to CCMP, PMF implied by SAE). Mixed mode
// lets WPA2-only clients still join.
if (secured && w.security != ApSecurity::WPA2 && !WPA3_SOFTAP_SUPPORTED) {
log_w("WPA3 needs an ESP-IDF 5 core; this build runs the AP as WPA2");
} else if (secured && w.security != ApSecurity::WPA2) {
wifi_config_t conf;
if (esp_wifi_get_config(WIFI_IF_AP, &conf) == ESP_OK) {
bool wpa3only = w.security == ApSecurity::WPA3;
conf.ap.authmode = wpa3only ? WIFI_AUTH_WPA3_PSK : WIFI_AUTH_WPA2_WPA3_PSK;
conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
if (err == ESP_OK) {
_securityName = wpa3only ? "wpa3" : "wpa2wpa3";
} else {
log_w("WPA3 mode rejected by the Wi-Fi driver (err 0x%x) — staying on WPA2", err);
}
}
}
}
void WifiManager::tick() {
// Station watchdog: log transitions, kick a reconnect if auto-reconnect
// gave up (e.g. the LAN was down at boot).
if (stationConfigured()) {
static bool wasConnected = false;
bool now = stationConnected();
if (now != wasConnected) {
wasConnected = now;
if (now) log_i("station: connected to \"%s\", IP %s, RSSI %d dBm", settings.wifi().staSsid, WiFi.localIP().toString().c_str(), WiFi.RSSI());
else log_w("station: disconnected from \"%s\"", settings.wifi().staSsid);
}
if (!now && (int32_t)(millis() - _staRetryAt) >= 0) {
_staRetryAt = millis() + 30000;
WiFi.reconnect();
}
}
if (_restartAt && (int32_t)(millis() - _restartAt) >= 0) {
log_w("restarting to apply settings");
delay(50);
ESP.restart();
}
}
// ---------------------------------------------------------------------------
// DNSServer is poll-driven; this task is pinned to CORE 0 by main.cpp so
// all captive-portal work stays off the radio core.
// ---------------------------------------------------------------------------
void WifiManager::dnsTask(void* self) {
auto* wm = static_cast<WifiManager*>(self);
for (;;) {
wm->_dns.processNextRequest();
vTaskDelay(pdMS_TO_TICKS(10));
}
}
// ---------------------------------------------------------------------------
// HTTP Basic Auth against the admin password. Sends the 401 challenge
// itself when it fails, so callers just `return`.
// ---------------------------------------------------------------------------
bool WifiManager::authed(AsyncWebServerRequest* request) {
if (request->authenticate(ADMIN_USER, settings.admin().password)) return true;
request->requestAuthentication();
return false;
}
// ---------------------------------------------------------------------------
void WifiManager::setupRoutes() {
// Handlers are matched in registration order: API and the protected
// page first, then the static handler for everything else in LittleFS.
_http.on("/api/status", HTTP_GET,
[this](AsyncWebServerRequest* r) { handleStatus(r); });
_http.on("/api/board", HTTP_GET,
[this](AsyncWebServerRequest* r) { handleBoardGet(r); });
// QR codes as SVG. "wifi" embeds the AP password, so it needs the admin
// credentials like every other place that reveals it; the portal URL and
// the node address are public.
_http.on("/api/qr", HTTP_GET, [this](AsyncWebServerRequest* r) {
Qr::Payload what;
if (!Qr::parsePayload(r->hasParam("what") ? r->getParam("what")->value().c_str() : "wifi", what)) {
sendError(r, 400, "what must be wifi, portal or address"); return;
}
if (what == Qr::Payload::Wifi && settings.wifi().security != ApSecurity::Open && !authed(r)) return;
handleQrFor(r, what);
});
_http.on("/api/board", HTTP_POST,
[](AsyncWebServerRequest* r) {
if (r->contentLength() == 0) sendError(r, 400, "empty");
}, nullptr,
[this](AsyncWebServerRequest* r, uint8_t* d, size_t l, size_t i, size_t t) {
if (const char* body = collectBody(r, d, l, i, t)) handleBoardPost(r, body, t);
});
// ---- admin -------------------------------------------------------------
_http.on("/settings.html", HTTP_GET, [this](AsyncWebServerRequest* r) {
if (!authed(r)) return; // browser prompts; fetches reuse the creds
r->send(LittleFS, "/settings.html", "text/html");
});
_http.on("/api/settings", HTTP_GET,
[this](AsyncWebServerRequest* r) { if (authed(r)) handleSettingsGet(r); });
struct Route { const char* path; void (WifiManager::*fn)(AsyncWebServerRequest*, const char*, size_t); };
static const Route posts[] = {
{ "/api/settings/radio", &WifiManager::handleRadioPost },
{ "/api/settings/wifi", &WifiManager::handleWifiPost },
{ "/api/settings/admin", &WifiManager::handleAdminPost },
{ "/api/settings/transport", &WifiManager::handleTransportPost },
{ "/api/settings/sd/format", &WifiManager::handleSdFormat },
{ "/api/settings/import", &WifiManager::handleImport },
};
for (const Route& rt : posts) {
auto fn = rt.fn;
_http.on(rt.path, HTTP_POST,
[this](AsyncWebServerRequest* r) {
if (r->contentLength() == 0 && authed(r)) sendError(r, 400, "empty");
}, nullptr,
[this, fn](AsyncWebServerRequest* r, uint8_t* d, size_t l, size_t i, size_t t) {
const char* body = collectBody(r, d, l, i, t);
if (body && authed(r)) (this->*fn)(r, body, t);
});
}
// Event log from the SD card (admin). ?prev=1 serves the rotated file.
_http.on("/api/sd/log", HTTP_GET, [this](AsyncWebServerRequest* r) {
if (!authed(r)) return;
if (!sdCard.mounted()) { sendError(r, 404, "no card mounted"); return; }
const char* path = r->hasParam("prev") ? SdCard::LOG_PREV_PATH : SdCard::LOG_PATH;
if (!SD.exists(path)) { sendError(r, 404, "no log yet"); return; }
AsyncWebServerResponse* res = r->beginResponse(SD, path, "text/plain");
res->addHeader("Content-Disposition", "attachment; filename=\"retimesh-events.log\"");
r->send(res);
});
_http.on("/api/settings/export", HTTP_GET,
[this](AsyncWebServerRequest* r) { if (authed(r)) handleExport(r); });
_http.on("/api/settings/reset", HTTP_POST,
[this](AsyncWebServerRequest* r) { if (authed(r)) handleReset(r); });
// OS connectivity probes — a redirect (any non-204/200 answer) is what
// makes the client OS open its captive-portal browser.
for (const char* probe : { "/generate_204", "/gen_204",
"/hotspot-detect.html", "/connecttest.txt",
"/ncsi.txt", "/canonical.html", "/success.txt" }) {
_http.on(probe, HTTP_GET,
[](AsyncWebServerRequest* r) { r->redirect(PORTAL_URL); });
}
// The single-page app lives in LittleFS (data/ -> `pio run -t uploadfs`).
// Explicit routes for the two hottest paths avoid the static handler's
// .gz / directory probes (each one logs a VFS error at debug level 3).
_http.on("/", HTTP_GET, [](AsyncWebServerRequest* r) { r->send(LittleFS, "/index.html", "text/html"); });
_http.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest* r) { r->send(204); });
_http.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
// Everything else (arbitrary hostnames typed by the user, probe paths
// not listed above) also lands on the portal.
_http.onNotFound([](AsyncWebServerRequest* r) { r->redirect(PORTAL_URL); });
}
// ---------------------------------------------------------------------------
// GET /api/status
// ---------------------------------------------------------------------------
void WifiManager::handleStatus(AsyncWebServerRequest* request) {
const RadioSettings& rs = settings.radio();
JsonDocument doc;
doc["firmware"] = FW_NAME;
doc["version"] = FW_VERSION;
doc["ssid"] = _ssid;
doc["hostname"] = _hostname; // reachable as <hostname>.local
doc["security"] = _securityName;
{
JsonObject st = doc["station"].to<JsonObject>();
st["configured"] = stationConfigured();
st["ssid"] = settings.wifi().staSsid;
st["connected"] = stationConnected();
st["ip"] = stationConnected() ? WiFi.localIP().toString() : "";
st["rssi"] = stationConnected() ? WiFi.RSSI() : 0;
}
doc["display"] = g_stats.displayPresent;
// Firmware and web assets are flashed separately and nothing forces them to
// be updated together, so a node can end up serving a portal built against a
// different API and look entirely healthy doing it. Both halves carry the
// same hash when they are built together; publishing both lets anyone see at
// a glance whether this node is one build or two.
{
JsonObject as = doc["assets"].to<JsonObject>();
as["firmware"] = ASSET_STAMP;
as["filesystem"] = _assetStamp;
as["match"] = (_assetStamp == ASSET_STAMP);
}
doc["identity"] = nodeIdentity.identityHex();
doc["destination"] = nodeIdentity.destHex(); // retimesh.node
doc["uptime_s"] = millis() / 1000;
{
Power::Battery b = Power::battery();
JsonObject pw = doc["power"].to<JsonObject>();
pw["profile"] = Power::profileName(Power::profile());
pw["cpu_mhz"] = getCpuFrequencyMhz();
pw["battery_present"] = b.present;
pw["battery_charging"] = b.charging;
pw["pmu"] = Pmu::model(); // "AXP192" / "AXP2101" / "none"
pw["board"] = BOARD_NAME;
pw["battery_v"] = b.volts;
pw["battery_pct"] = b.percent;
}
doc["heap_free"] = heap_caps_get_free_size(MALLOC_CAP_INTERNAL); // internal RAM
doc["heap_min_free"] = g_stats.heapMinFree;
doc["psram_free"] = ESP.getFreePsram();
// Everything a soak run needs to read off a node it cannot reach a console
// on: why it last restarted, how long that run lasted, and what it is
// running out of. See Diag.h.
{
JsonObject dg = doc["diag"].to<JsonObject>();
const Diag::Boot& b = Diag::boot();
JsonObject bo = dg["boot"].to<JsonObject>();
bo["count"] = b.count;
bo["reason"] = b.reason;
bo["reason_name"] = b.reasonName;
bo["clean"] = b.clean;
// Absent rather than zero when a power cut took the RTC domain with it:
// "unknown" and "it ran for no time at all" are not the same answer.
if (b.prevUptimeKnown) bo["prev_uptime_s"] = b.prevUptimeS;
Diag::Heap h = Diag::heap();
JsonObject hp = dg["heap"].to<JsonObject>();
hp["free"] = h.freeInternal;
hp["min_free"] = h.minFreeInternal;
hp["largest_block"] = h.largestBlock; // free minus this is the fragmentation
hp["psram_free"] = h.freePsram;
Diag::TaskStack st[16];
const size_t n = Diag::stacks(st, sizeof(st) / sizeof(st[0]));
JsonObject sk = dg["stacks"].to<JsonObject>();
for (size_t i = 0; i < n; i++)
if (st[i].present) sk[st[i].name] = st[i].headroom; // bytes never used
const char* lowestName = nullptr;
const uint32_t lowest = Diag::lowestHeadroom(&lowestName);
dg["stack_lowest"] = lowest;
dg["stack_lowest_task"] = lowestName ? lowestName : "none";
RnsTransport::Tables t = RnsTransport::tables();
JsonObject tb = dg["tables"].to<JsonObject>();
tb["paths"] = t.paths;
tb["links"] = t.links;
tb["links_active"] = t.activeLinks;
tb["links_pending"] = t.pendingLinks;
tb["destinations"] = t.destinations;
tb["announces"] = t.announces;
tb["announces_held"] = t.heldAnnounces;
tb["rates"] = t.rates;
}
JsonObject radio = doc["radio"].to<JsonObject>();
radio["online"] = g_stats.radioOnline;
radio["model"] = g_stats.radioModel;
radio["freq_mhz"] = rs.freqMhz;
radio["bw_khz"] = rs.bwKhz;
radio["sf"] = rs.sf;
radio["cr"] = rs.cr;
radio["tx_dbm"] = rs.txDbm;
radio["sync_word"] = rs.syncWord;
radio["preamble"] = rs.preamble;
radio["apply_error"]= g_stats.radioApplyError;
radio["rssi"] = g_stats.lastRssi;
radio["snr"] = g_stats.lastSnr;
radio["rx_packets"] = g_stats.loraRxPackets;
radio["tx_packets"] = g_stats.loraTxPackets;
// The total stays, so anything already reading it keeps working; the
// breakdown beside it is what says which of five different things happened.
radio["rx_dropped"] = g_stats.loraRxDropRing + g_stats.loraRxDropReasm +
g_stats.loraRxDropPartial;
radio["rx_dropped_ring"] = g_stats.loraRxDropRing;
radio["rx_dropped_reassembly"] = g_stats.loraRxDropReasm;
radio["rx_dropped_partial"] = g_stats.loraRxDropPartial;
radio["rx_crc_errors"] = g_stats.loraRxCrcErrors;
radio["rx_bad_length"] = g_stats.loraRxBadLength;
radio["rx_spurious_irq"] = g_stats.loraRxSpuriousIrq;
radio["beacon_interval"] = rs.beaconInterval;
radio["callsign"] = loraRadio.callsign();
radio["beacons_tx"] = g_stats.beaconsTx;
radio["beacons_rx"] = g_stats.beaconsRx;
radio["announce_interval"] = rs.announceInterval;
radio["announces_tx"] = g_stats.announcesTx;
radio["announces_rx"] = g_stats.announcesRx;
JsonObject peers = doc["peers"].to<JsonObject>();
peers["rns_tcp"] = g_stats.tcpClients; // Reticulum clients on :4242
peers["wifi_sta"] = WiFi.softAPgetStationNum();
peers["tcp_rx_packets"] = g_stats.tcpRxPackets;
#if HAS_SD
{
SdCard::Info si = sdCard.info();
JsonObject sd = doc["sd"].to<JsonObject>();
sd["state"] = SdCard::stateName(si.state);
sd["type"] = si.type == CARD_SDHC ? "SDHC" : si.type == CARD_SD ? "SD" : si.type == CARD_MMC ? "MMC" : "";
sd["card_bytes"] = si.cardBytes;
sd["volume_bytes"] = si.volumeBytes;
sd["used_bytes"] = si.usedBytes;
sd["last_format"] = si.lastFormat;
sd["reserved"] = sdCard.reserved(); // Reticulum store lives here
sd["storage_lost"] = sdCard.storageLost(); // ... and the card was pulled
}
#endif
{
// Channel use and the hourly transmit budget (see Airtime.h)
JsonObject at = doc["airtime"].to<JsonObject>();
at["short_pct"] = roundf(g_stats.airtimeShort * 10000.0f) / 100.0f;
at["long_pct"] = roundf(g_stats.airtimeLong * 10000.0f) / 100.0f;
const Airtime::Band* band = Airtime::bandFor(settings.radio().freqMhz, settings.radio().bwKhz);
// A node in the US band or at 2.4 GHz is not an exception to the European
// plan, it is under a different one — reporting it as "outside the EU
// 863-870 plan" described the only regime this field knows rather than the
// regime the node is in. The sub-band figures below stay EU-specific
// because only that plan has sub-bands to report.
const Airtime::RegionInfo* areg =
Airtime::regionFor(settings.radio().region, settings.radio().freqMhz);
at["band"] = band ? band->name
: (areg->regime == Airtime::Regime::EuSrd868
? "outside the EU 863-870 plan" : areg->name);
at["regime"] = Airtime::regimeName(areg->regime);
at["band_limit_pct"] = band ? band->basisPoints / 100.0f : 0.0f;
at["band_allocated"] = band ? band->allocated : false;
at["duty_limit_pct"] = g_stats.dutyLimitBp / 100.0f; // what is enforced
at["duty_manual_pct"] = settings.radio().dutyCyclePct; // 0 = follow the band
at["budget_used"] = roundf(g_stats.dutyBudget * 1000.0f) / 1000.0f;
at["locked"] = g_stats.dutyLocked;
at["retry_after_s"] = g_stats.dutyRetryS;
at["csma_slot_ms"] = g_stats.csmaSlotMs;
at["csma_band"] = g_stats.csmaBand;
}
#if HAS_GPS
{
Gps::Fix g = Gps::fix();
JsonObject gps = doc["gps"].to<JsonObject>();
gps["enabled"] = g.enabled;
gps["fix"] = g.valid;
gps["quality"] = g.quality;
gps["satellites"] = g.satellites;
gps["sentences"] = g.sentences;
gps["clock_set"] = g.clockSet;
gps["utc"] = g.utc;
// Everything above says whether the receiver is working. Where the node
// physically is says something else, and /api/status is public — on an
// open access point that is anyone within radio range. Coordinates are
// therefore withheld unless the operator has published them, or the
// caller holds the admin credentials.
const bool sharePosition = settings.radio().gpsSharePosition ||
request->authenticate(ADMIN_USER, settings.admin().password);
gps["position_public"] = settings.radio().gpsSharePosition;
// HDOP says how well the receiver is solving, not where it is, so it goes
// out with the rest of the health readings. It used to be published only
// alongside the coordinates, which left it missing on the default private
// configuration — and any consumer assuming a fix implies an HDOP broke
// there and nowhere else.
if (g.valid) gps["hdop"] = g.hdop;
if (g.valid && sharePosition) {
gps["latitude"] = g.latitude;
gps["longitude"] = g.longitude;
gps["altitude_m"] = g.altitude;
gps["speed_kmh"] = g.speedKmh;
}
}
#endif
{
JsonObject st = doc["storage"].to<JsonObject>();
st["backend"] = RnsTransport::storageBackend(); // "sd" | "littlefs"
st["path"] = RnsTransport::storagePath();
st["lost"] = sdCard.storageLost();
// The backend is chosen at boot. A card that turned up afterwards, or was
// inserted since, can only be used after a restart — say so rather than
// leaving the operator to wonder why the card is idle.
st["sd_available"] = sdCard.mounted() && !sdCard.reserved() && settings.transport().sdStore;
}
// Reticulum transport: interfaces with their modes, and the path table
JsonObject tr = doc["transport"].to<JsonObject>();
tr["enabled"] = settings.transport().enabled;
tr["online"] = g_stats.transportOnline;
tr["lora_mode"] = RnsTransport::modeName(settings.transport().loraMode);
tr["wifi_mode"] = RnsTransport::modeName(settings.transport().wifiMode);
JsonObject ai = tr["autointerface"].to<JsonObject>();
ai["enabled"] = settings.transport().autoEnabled;
ai["online"] = AutoInterface::enabled();
ai["address"] = AutoInterface::localAddress();
ai["peers"] = AutoInterface::peerCount();
ai["group_id"] = settings.transport().autoGroupId[0] ? settings.transport().autoGroupId : AUTOIF_GROUP_ID;
{
RnsTransport::IfaceInfo ifs[RNS_MAX_CLIENTS + 1];
size_t k = RnsTransport::interfaces(ifs, RNS_MAX_CLIENTS + 1);
JsonArray ia = tr["interfaces"].to<JsonArray>();
for (size_t i = 0; i < k; i++) {
JsonObject o = ia.add<JsonObject>();
o["name"] = ifs[i].name; o["mode"] = ifs[i].mode; o["rx_bytes"] = ifs[i].rxb; o["tx_bytes"] = ifs[i].txb;
}
RnsTransport::PathInfo ps[32];
size_t pk = RnsTransport::paths(ps, 32);
tr["path_count"] = RnsTransport::pathCount();
JsonArray pa = tr["paths"].to<JsonArray>();
for (size_t i = 0; i < pk; i++) {
JsonObject o = pa.add<JsonObject>();
o["hash"] = ps[i].hash; o["hops"] = ps[i].hops; o["via"] = ps[i].via; o["age_s"] = ps[i].ageS;
}
}
// Stations heard on the channel (beacons / RNode station IDs)
Neighbor snap[MAX_NEIGHBORS];
size_t n = neighbors.snapshot(snap, MAX_NEIGHBORS);
JsonArray nb = doc["neighbors"].to<JsonArray>();
uint32_t now = millis();
for (size_t i = 0; i < n; i++) {
JsonObject o = nb.add<JsonObject>();
o["name"] = snap[i].name;
o["version"] = snap[i].version;
o["kind"] = snap[i].kind == NeighborKind::Announce ? "announce"
: snap[i].kind == NeighborKind::Beacon ? "beacon" : "station-id";
o["hash"] = snap[i].hash;
o["aspect"] = snap[i].aspect;
o["hops"] = snap[i].hops;
o["via"] = snap[i].viaWifi ? "wifi" : "lora";
o["rssi"] = snap[i].rssi;
o["snr"] = snap[i].snr;
o["age_s"] = (now - snap[i].lastSeen) / 1000;
o["count"] = snap[i].count;
}
sendJson(request, 200, doc);
}
// ---------------------------------------------------------------------------
// Bulletin board — deliberately public and unencrypted; lives on this node
// only. Private traffic belongs on Reticulum, which this node cannot read.
// ---------------------------------------------------------------------------
// LittleFS.exists() and open() log a VFS error line for a file that is not
// there, and the board is empty until someone posts — so every status poll
// printed an error. stat() answers the same question silently.
void WifiManager::deriveHostname() {
Mdns::label(_ssid, _hostname, sizeof(_hostname), MDNS_HOSTNAME);
}
static bool littleFsHas(const char* path) {
struct stat st;
return stat((String("/littlefs") + path).c_str(), &st) == 0;
}
// GET /api/qr?what=wifi|portal|address -> image/svg+xml
void WifiManager::handleQrFor(AsyncWebServerRequest* request, Qr::Payload what) {
char text[192];
if (!Qr::payloadText(what, text, sizeof(text))) { sendError(request, 500, "payload too long"); return; }
QRCode qr;
uint8_t buffer[Qr::MAX_BUFFER];
if (!Qr::encode(text, qr, buffer)) { sendError(request, 500, "does not fit in a QR code"); return; }
AsyncWebServerResponse* res = request->beginResponse(200, "image/svg+xml", Qr::toSvg(qr));
res->addHeader("Cache-Control", "no-store");
request->send(res);
}
void WifiManager::handleBoardGet(AsyncWebServerRequest* request) {
String out = "[]";
if (littleFsHas(BOARD_FILE)) {
File f = LittleFS.open(BOARD_FILE, "r");
if (f) { out = f.readString(); f.close(); }
}
request->send(200, "application/json", out);
}
void WifiManager::handleBoardPost(AsyncWebServerRequest* request, const char* body, size_t len) {
JsonDocument in;
if (deserializeJson(in, body, len) != DeserializationError::Ok || !in["text"].is<const char*>()) {
sendError(request, 400, "bad json");
return;
}
String author = in["author"] | "anonymous";
String text = in["text"].as<String>();
author.trim(); text.trim();
if (text.isEmpty()) { sendError(request, 400, "empty"); return; }
if (author.isEmpty()) author = "anonymous";
if (author.length() > BOARD_MAX_AUTHOR) author = author.substring(0, BOARD_MAX_AUTHOR);
if (text.length() > BOARD_MAX_TEXT) text = text.substring(0, BOARD_MAX_TEXT);
// All HTTP handlers run on the single AsyncTCP task: no file locking needed.
JsonDocument boardDoc;
if (littleFsHas(BOARD_FILE)) {
File f = LittleFS.open(BOARD_FILE, "r");
if (f) { deserializeJson(boardDoc, f); f.close(); }
}
JsonArray posts = boardDoc.as<JsonArray>();
if (posts.isNull()) posts = boardDoc.to<JsonArray>();
uint32_t nextId = 1;
for (JsonObject p : posts) nextId = max(nextId, p["id"].as<uint32_t>() + 1);
JsonObject post = posts.add<JsonObject>();
post["id"] = nextId; // ordering only — the node has no RTC
post["author"] = author;
post["text"] = text;
while (posts.size() > BOARD_MAX_POSTS) posts.remove(0);
File f = LittleFS.open(BOARD_FILE, "w");
if (!f) { sendError(request, 500, "fs"); return; }
serializeJson(posts, f);
f.close();
request->send(200, "application/json", "{\"ok\":true}");
}
// ---------------------------------------------------------------------------
// Settings API (all authenticated)
// ---------------------------------------------------------------------------
void WifiManager::handleSettingsGet(AsyncWebServerRequest* request) {
const RadioSettings& rs = settings.radio();
const WifiSettings& ws = settings.wifi();
JsonDocument doc;
JsonObject radio = doc["radio"].to<JsonObject>();
radio["freq_mhz"] = rs.freqMhz;
radio["bw_khz"] = rs.bwKhz;
radio["sf"] = rs.sf;
radio["cr"] = rs.cr;
radio["tx_dbm"] = rs.txDbm;
radio["tx_dbm_max"]= loraRadio.online() ? loraRadio.maxTxDbm() : 22;
radio["region"] = rs.region;
// What this particular transceiver can be asked for. The settings page used
// to offer the sub-GHz bandwidth steps to every board, which on a 2.4 GHz
// radio is a list of values it cannot tune to.
{
const RadioCaps::Caps& c = loraRadio.caps();
JsonObject cp = radio["caps"].to<JsonObject>();
cp["model"] = c.name;
cp["freq_min_mhz"] = c.freqMinMhz;
cp["freq_max_mhz"] = c.freqMaxMhz;
cp["sf_min"] = c.sfMin;
cp["sf_max"] = c.sfMax;
cp["tx_min_dbm"] = c.txMinDbm;
cp["tx_max_dbm"] = c.txMaxDbm;
// An amplifier does not change what the chip may be driven at, but it does
// change what leaves the antenna, and the operator has to account for it.
cp["pa_fitted"] = LoRaRadio::hasPa();
JsonArray bws = cp["bandwidths_khz"].to<JsonArray>();
for (const float* b = c.bandwidthsKhz; *b != 0.0f; b++) bws.add(*b);
// Which rulebook the configured channel falls under, and what it caps
// What this node will actually enforce, which is decided by its region —
// reporting the frequency's regime here told an operator on "custom" that
// the EU plan applied while the radio had already stopped applying it.
const Airtime::Regime rg =
Airtime::regionFor(settings.radio().region, settings.radio().freqMhz)->regime;
cp["regime"] = Airtime::regimeName(rg);
cp["max_dwell_ms"] = Airtime::maxDwellMs(rg); // 0 = not a dwell regime
// Only the regions this radio can actually reach. Offering "Europe
// 863-870" on a 2.4 GHz node would be a choice that cannot be honoured,
// and the operator would find that out only when the frequency was
// rejected. Custom is always offered: it is the escape hatch.
JsonArray regs = cp["regions"].to<JsonArray>();
size_t n = 0;
const Airtime::RegionInfo* all = Airtime::regions(n);
for (size_t i = 0; i < n; i++) {
const Airtime::RegionInfo& ri = all[i];
const bool custom = (ri.id == Airtime::Region::Custom);
// Reachable when the region's band and the chip's tuning range overlap
const bool reachable = custom ||
(ri.highMhz >= c.freqMinMhz && ri.lowMhz <= c.freqMaxMhz);
if (!reachable) continue;
JsonObject o = regs.add<JsonObject>();
o["key"] = ri.key;
o["name"] = ri.name;
o["low_mhz"] = custom ? c.freqMinMhz : max(ri.lowMhz, c.freqMinMhz);
o["high_mhz"] = custom ? c.freqMaxMhz : min(ri.highMhz, c.freqMaxMhz);
o["regime"] = Airtime::regimeName(ri.regime);
o["dwell_ms"] = Airtime::maxDwellMs(ri.regime);
// Custom carries no channel of its own — it is offered on every radio,
// so a fixed sub-GHz suggestion would be untunable on a 2.4 GHz one.
// Fall back to the middle of what this chip can reach and its widest
// bandwidth, which is at least always a valid starting point.
float dfl = ri.defaultMhz, dbw = ri.defaultBwKhz;
if (dfl == 0.0f) dfl = (c.freqMinMhz + c.freqMaxMhz) / 2.0f;
if (dbw == 0.0f) {
dbw = c.bandwidthsKhz[0];
for (const float* b = c.bandwidthsKhz; *b != 0.0f; b++) dbw = *b;
}
o["default_mhz"] = dfl;
o["default_bw_khz"] = dbw;
o["default_sf"] = ri.defaultSf;
}
}
radio["sync_word"] = rs.syncWord;
radio["preamble"] = rs.preamble;
radio["beacon_interval"] = rs.beaconInterval;
radio["announce_interval"] = rs.announceInterval;
radio["callsign"] = rs.callsign; // "" = SSID
radio["duty_cycle_pct"] = rs.dutyCyclePct; // manual cap; 0 = follow the band
radio["gps_enabled"] = rs.gpsEnabled;
radio["gps_share_position"] = rs.gpsSharePosition;
radio["has_gps"] = HAS_GPS ? true : false;
radio["callsign_active"] = loraRadio.callsign();
radio["model"] = g_stats.radioModel;
radio["online"] = g_stats.radioOnline;
radio["apply_error"] = g_stats.radioApplyError;
JsonObject wifi = doc["wifi"].to<JsonObject>();
wifi["ssid"] = ws.ssid; // "" = automatic
wifi["ssid_active"]= _ssid;
wifi["security"] = Settings::securityName(ws.security);
wifi["security_active"] = _securityName;
wifi["wpa3_supported"] = (bool)WPA3_SOFTAP_SUPPORTED;
wifi["has_password"] = strlen(ws.password) >= 8;
wifi["channel"] = ws.channel;
wifi["max_stations"] = ws.maxStations;
wifi["hidden"] = ws.hidden;
wifi["sta_ssid"] = ws.staSsid;
wifi["sta_has_password"] = ws.staPassword[0] != '\0';
wifi["sta_connected"] = stationConnected();
JsonObject tr = doc["transport"].to<JsonObject>();
tr["enabled"] = settings.transport().enabled;
tr["lora_mode"] = settings.transport().loraMode;
tr["wifi_mode"] = settings.transport().wifiMode;
tr["announce_cap"] = settings.transport().announceCap;
tr["announce_rate_target"] = settings.transport().announceRateTarget;
tr["announce_rate_grace"] = settings.transport().announceRateGrace;
tr["announce_rate_penalty"] = settings.transport().announceRatePenalty;
tr["auto_enabled"] = settings.transport().autoEnabled;
tr["auto_group_id"] = settings.transport().autoGroupId;
tr["power_profile"] = Power::profileName((Power::Profile)settings.transport().powerProfile);
tr["sd_store"] = settings.transport().sdStore;
tr["online"] = g_stats.transportOnline;
doc["admin"]["user"] = ADMIN_USER;
doc["admin"]["default_password"] = strcmp(settings.admin().password, ADMIN_PASSWORD_DEFAULT) == 0;
sendJson(request, 200, doc);
}
void WifiManager::handleRadioPost(AsyncWebServerRequest* request, const char* body, size_t len) {
JsonDocument in;
if (deserializeJson(in, body, len) != DeserializationError::Ok) { sendError(request, 400, "bad json"); return; }
RadioSettings r = settings.radio();
if (in["freq_mhz"].is<float>()) r.freqMhz = in["freq_mhz"];
if (in["bw_khz"].is<float>()) r.bwKhz = in["bw_khz"];
if (in["sf"].is<int>()) r.sf = in["sf"];
if (in["cr"].is<int>()) r.cr = in["cr"];
if (in["tx_dbm"].is<int>()) r.txDbm = in["tx_dbm"];
if (in["sync_word"].is<int>()) r.syncWord = in["sync_word"];
if (in["preamble"].is<int>()) r.preamble = in["preamble"];
if (in["beacon_interval"].is<int>()) r.beaconInterval = in["beacon_interval"];
if (in["announce_interval"].is<int>()) r.announceInterval = in["announce_interval"];
if (in["duty_cycle_pct"].is<int>()) r.dutyCyclePct = in["duty_cycle_pct"];
if (in["gps_enabled"].is<bool>()) r.gpsEnabled = in["gps_enabled"];
if (in["gps_share_position"].is<bool>()) r.gpsSharePosition = in["gps_share_position"];
if (in["callsign"].is<const char*>()) {
String c = in["callsign"].as<String>(); c.trim();
for (size_t i = 0; i < c.length(); i++)
if (c[i] < 0x21 || c[i] > 0x7E) { sendError(request, 400, "callsign: printable ASCII without spaces only"); return; }
if (c.length() > 32) { sendError(request, 400, "callsign must be at most 32 characters"); return; }
strlcpy(r.callsign, c.c_str(), sizeof(r.callsign));
}
if (in["region"].is<const char*>()) {
strlcpy(r.region, in["region"].as<const char*>(), sizeof(r.region));
}
int8_t maxDbm = loraRadio.online() ? loraRadio.maxTxDbm() : 22;
// Bounds come from the transceiver that is actually fitted, not from a
// sub-GHz assumption: an SX1280 tunes 2400-2500 MHz and has four bandwidths,
// none of which appear in the SX127x list.
const RadioCaps::Caps& caps = loraRadio.caps();
char msg[160], bwlist[96];
// The region bounds the channel, and the chip bounds the region. Both have
// to hold, and the message says which one was missed rather than quoting a
// range the operator cannot use anyway.
const Airtime::RegionInfo* region = Airtime::regionByKey(r.region);
if (!region) { sendError(request, 400, "unknown region — pick one the node offers"); return; }
const float lowMhz = max(region->lowMhz, caps.freqMinMhz);
const float highMhz = min(region->highMhz, caps.freqMaxMhz);
if (lowMhz > highMhz) {
snprintf(msg, sizeof(msg), "the %s cannot tune %s — choose a region this radio reaches",
caps.name, region->name);
sendError(request, 400, msg); return;
}
if (r.freqMhz < lowMhz || r.freqMhz > highMhz) {
snprintf(msg, sizeof(msg), "frequency must be %g-%g MHz in %s on the %s",
(double)lowMhz, (double)highMhz, region->name, caps.name);
sendError(request, 400, msg); return;
}
if (!RadioCaps::bandwidthSupported(caps, r.bwKhz)) {
snprintf(msg, sizeof(msg), "the %s supports these bandwidths in kHz: %s",
caps.name, RadioCaps::bandwidthList(caps, bwlist, sizeof(bwlist)));
sendError(request, 400, msg); return;
}
if (r.sf < caps.sfMin || r.sf > caps.sfMax) {
snprintf(msg, sizeof(msg), "spreading factor must be %u-%u on the %s",
(unsigned)caps.sfMin, (unsigned)caps.sfMax, caps.name);
sendError(request, 400, msg); return;
}
if (r.cr < 5 || r.cr > 8) { sendError(request, 400, "coding rate must be 5-8 (4/5..4/8)"); return; }
if (r.txDbm < caps.txMinDbm || r.txDbm > maxDbm) {
snprintf(msg, sizeof(msg), "tx power must be %d to %d dBm on the %s",
(int)caps.txMinDbm, (int)maxDbm, caps.name);
sendError(request, 400, msg); return;
}
if (r.preamble < 6 || r.preamble > 1000) { sendError(request, 400, "preamble must be 6-1000 symbols"); return; }
if (r.beaconInterval != 0 && (r.beaconInterval < 10 || r.beaconInterval > 3600)) { sendError(request, 400, "beacon interval must be 0 (off) or 10-3600 s"); return; }
if (r.announceInterval != 0 && (r.announceInterval < 60 || r.announceInterval > 43200)) { sendError(request, 400, "announce interval must be 0 (off) or 60-43200 s"); return; }
if (r.dutyCyclePct > 100) { sendError(request, 400, "duty cycle must be 0 (off) or 1-100 %"); return; }
if (!settings.saveRadio(r)) { sendError(request, 500, "nvs"); return; }
if (loraRadio.online()) loraRadio.requestReconfigure(r);
#if HAS_GPS
Gps::setEnabled(r.gpsEnabled); // applies without a restart
#endif
JsonDocument out;
out["ok"] = true;
out["applied"] = loraRadio.online();
sendJson(request, 200, out);
}
void WifiManager::handleWifiPost(AsyncWebServerRequest* request, const char* body, size_t len) {
JsonDocument in;
if (deserializeJson(in, body, len) != DeserializationError::Ok) { sendError(request, 400, "bad json"); return; }
WifiSettings w = settings.wifi();
if (in["ssid"].is<const char*>()) {
String s = in["ssid"].as<String>(); s.trim();
if (s.length() > 32) { sendError(request, 400, "ssid must be at most 32 characters"); return; }
strlcpy(w.ssid, s.c_str(), sizeof(w.ssid));
}
if (in["security"].is<const char*>() && !Settings::securityFromName(in["security"], w.security)) {
sendError(request, 400, "security must be open|wpa2|wpa2wpa3|wpa3"); return;
}
if (in["password"].is<const char*>()) {
const char* p = in["password"];
if (p[0] != '\0') { // empty = keep the stored password
size_t pl = strlen(p);
if (pl < 8 || pl > 63) { sendError(request, 400, "password must be 8-63 characters"); return; }
strlcpy(w.password, p, sizeof(w.password));
}
}
if (in["channel"].is<int>()) w.channel = in["channel"];
if (in["max_stations"].is<int>()) w.maxStations = in["max_stations"];
if (in["hidden"].is<bool>()) w.hidden = in["hidden"];
if (in["sta_ssid"].is<const char*>()) {
String s = in["sta_ssid"].as<String>(); s.trim();
if (s.length() > 32) { sendError(request, 400, "station ssid must be at most 32 characters"); return; }
strlcpy(w.staSsid, s.c_str(), sizeof(w.staSsid));
if (s.isEmpty()) w.staPassword[0] = '\0';
}
if (in["sta_password"].is<const char*>()) {
const char* p = in["sta_password"];
if (p[0] != '\0') { // empty = keep
if (strlen(p) > 63) { sendError(request, 400, "station password too long"); return; }
strlcpy(w.staPassword, p, sizeof(w.staPassword));
}
}
if (w.security != ApSecurity::Open && strlen(w.password) < 8) { sendError(request, 400, "a password is required for a secured network"); return; }
if (w.channel < 1 || w.channel > 13) { sendError(request, 400, "channel must be 1-13"); return; }
if (w.maxStations < 1 || w.maxStations > 10) { sendError(request, 400, "max stations must be 1-10"); return; }
if (!settings.saveWifi(w)) { sendError(request, 500, "nvs"); return; }
JsonDocument out;
out["ok"] = true;
out["restart"] = true;
out["ssid"] = w.ssid[0] ? w.ssid : _ssid; // auto-derived name does not change
out["security"] = Settings::securityName(w.security);
sendJson(request, 200, out);
scheduleRestart(1500); // let the response leave first
}
void WifiManager::handleAdminPost(AsyncWebServerRequest* request, const char* body, size_t len) {
JsonDocument in;
if (deserializeJson(in, body, len) != DeserializationError::Ok || !in["password"].is<const char*>()) {
sendError(request, 400, "bad json"); return;
}
const char* p = in["password"];
size_t pl = strlen(p);
if (pl < 4 || pl > 32) { sendError(request, 400, "password must be 4-32 characters"); return; }
if (!settings.saveAdminPassword(p)) { sendError(request, 500, "nvs"); return; }
request->send(200, "application/json", "{\"ok\":true}");
}
void WifiManager::handleTransportPost(AsyncWebServerRequest* request, const char* body, size_t len) {
JsonDocument in;
if (deserializeJson(in, body, len) != DeserializationError::Ok) { sendError(request, 400, "bad json"); return; }
TransportSettings t = settings.transport();
if (in["enabled"].is<bool>()) t.enabled = in["enabled"];
if (in["lora_mode"].is<int>()) t.loraMode = in["lora_mode"];
if (in["wifi_mode"].is<int>()) t.wifiMode = in["wifi_mode"];
if (in["announce_cap"].is<int>()) t.announceCap = in["announce_cap"];
if (in["announce_rate_target"].is<int>()) t.announceRateTarget = in["announce_rate_target"];
if (in["announce_rate_grace"].is<int>()) t.announceRateGrace = in["announce_rate_grace"];
if (in["announce_rate_penalty"].is<int>()) t.announceRatePenalty = in["announce_rate_penalty"];
if (in["auto_enabled"].is<bool>()) t.autoEnabled = in["auto_enabled"];
if (in["sd_store"].is<bool>()) t.sdStore = in["sd_store"];
if (in["power_profile"].is<const char*>()) {
Power::Profile pp;
if (!Power::profileFromName(in["power_profile"], pp)) { sendError(request, 400, "power_profile must be performance|balanced|battery"); return; }
t.powerProfile = (uint8_t)pp;
}
if (in["auto_group_id"].is<const char*>()) {