-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebManager.cpp
More file actions
8045 lines (7310 loc) · 314 KB
/
WebManager.cpp
File metadata and controls
8045 lines (7310 loc) · 314 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
#include "WebManager.h"
#include "DebugLog.h"
#include "LiveEventServer.h"
#include "JsonHelpers.h"
#include "ReleaseUpdateManager.h"
#include "lvgl_v8_port.h"
#include "ui/UiManager.h"
#include "NotificationTask.h"
#include <WiFi.h>
#include <LittleFS.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <esp_heap_caps.h>
#include <esp_sntp.h>
#include <esp_sleep.h>
#include <driver/rtc_io.h>
#include <esp_random.h>
#include <mbedtls/sha256.h>
#include <ctime>
#include <sys/time.h>
#include <math.h>
#include <cstring>
#include <ctype.h>
#include "AudioEngine.h"
#include "AppConfig.h"
#include "AppRuntimeStats.h"
#include "TrustedCerts.h"
#define Serial0 DebugSerial0
extern AudioEngine g_audio;
static uint32_t g_bootMs = 0;
static float g_webDbInstant = 0.0f;
static float g_webLeq = 0.0f;
static float g_webPeak = 0.0f;
static constexpr char SP7_SESSION_COOKIE_NAME[] = "sp7_session";
static constexpr HTTPMethod kSyncHttpGet = static_cast<HTTPMethod>(::HTTP_GET);
static constexpr HTTPMethod kSyncHttpPost = static_cast<HTTPMethod>(::HTTP_POST);
static constexpr uint32_t kNotificationHttpConnectTimeoutMs = 5000UL;
static constexpr uint32_t kNotificationHttpTimeoutMs = 8000UL;
static uint32_t tardisColorHex(uint8_t r, uint8_t g, uint8_t b) {
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | (uint32_t)b;
}
static float clamp01f(float value) {
if (value < 0.0f) return 0.0f;
if (value > 1.0f) return 1.0f;
return value;
}
static float smoothStep01(float t) {
t = clamp01f(t);
return t * t * (3.0f - 2.0f * t);
}
static float mixf(float a, float b, float amount) {
amount = clamp01f(amount);
return a + ((b - a) * amount);
}
/**
* Génère une courbe de pulse TARDIS avec montée, plateau haut et descente.
*
* Le cycle complet est divisé en 4 phases :
* 1. Montée (rise) : 0 → 1 avec interpolation cosinus ou mécanique
* 2. Plateau haut (highHold) : maintien à 1.0
* 3. Descente (fall) : 1 → 0 avec interpolation cosinus ou mécanique
* 4. Plateau bas (implicit) : maintien à 0.0 jusqu'à la fin du cycle
*
* Interpolation :
* - Cosinus : utilise 0.5 - 0.5*cos(t*π) pour une courbe sinusoïdale douce (S-curve)
* - Mécanique : mix(linear, smoothStep, 0.42) pour simuler l'inertie d'un système physique
*
* @param phase Valeur [0..∞) normalisée en interne à [0..1) (phase = phase - floor(phase))
* @param riseSpan Durée de montée en fraction de cycle [0..1]
* @param highHoldSpan Durée du plateau haut en fraction de cycle [0..1]
* @param fallSpan Durée de descente en fraction de cycle [0..1]
* @param mechanicalRamp Si true, utilise interpolation mécanique ; si false, cosinus
* @return Intensité [0..1] à la phase donnée, ou 0.0 si configuration invalide
*
* @note La somme (riseSpan + highHoldSpan + fallSpan) doit être < 1.0 pour laisser un plateau bas
* @note Utilisé pour l'effet lumineux RGB TARDIS (intérieur/extérieur)
*/
static float tardisPulseWithPlateaus01(float phase,
float riseSpan,
float highHoldSpan,
float fallSpan,
bool mechanicalRamp) {
phase = phase - floorf(phase);
if (phase < 0.0f) phase += 1.0f;
riseSpan = clamp01f(riseSpan);
highHoldSpan = clamp01f(highHoldSpan);
fallSpan = clamp01f(fallSpan);
const float total = riseSpan + highHoldSpan + fallSpan;
if (total >= 1.0f || riseSpan <= 0.0f || fallSpan <= 0.0f) {
return 0.0f;
}
if (phase < riseSpan) {
const float t = phase / riseSpan;
if (mechanicalRamp) {
return mixf(t, smoothStep01(t), 0.42f);
}
return 0.5f - 0.5f * cosf(t * PI);
}
if (phase < (riseSpan + highHoldSpan)) {
return 1.0f;
}
const float fallStart = riseSpan + highHoldSpan;
if (phase < (fallStart + fallSpan)) {
const float t = (phase - fallStart) / fallSpan;
if (mechanicalRamp) {
return 1.0f - mixf(t, smoothStep01(t), 0.42f);
}
return 0.5f + 0.5f * cosf(t * PI);
}
return 0.0f;
}
struct NotificationVisualStyle {
const char* emoji;
const char* title;
const char* slackColor;
const char* slackIconEmoji;
};
static NotificationVisualStyle notificationVisualStyle(uint8_t alertState, bool isTest) {
if (isTest) return {"🧪", "Test de notification", "#1E88E5", ":test_tube:"};
if (alertState == 2) return {"🚨", "Alerte critique", "#E53935", ":rotating_light:"};
if (alertState == 1) return {"⚠️", "Alerte warning", "#FB8C00", ":warning:"};
return {"✅", "Retour a la normale", "#43A047", ":white_check_mark:"};
}
static String formatAlertDuration(uint32_t durationMs) {
uint32_t totalSeconds = durationMs / 1000UL;
const uint32_t hours = totalSeconds / 3600UL;
totalSeconds %= 3600UL;
const uint32_t minutes = totalSeconds / 60UL;
const uint32_t seconds = totalSeconds % 60UL;
String out;
out.reserve(32); // Pré-allocation pour éviter réallocations ("XX h XX min XX s")
if (hours > 0) {
out += String(hours);
out += " h ";
}
if (minutes > 0 || hours > 0) {
out += String(minutes);
out += " min ";
}
out += String(seconds);
out += " s";
return out;
}
static void appendBoolField(String& json, const char* key, bool value, bool trailingComma = true) {
json += "\"";
json += key;
json += "\":";
json += value ? "true" : "false";
if (trailingComma) json += ",";
}
static void appendWifiJson(String& json, bool wifiConnected, const String& ip, int rssi, const String& ssid) {
appendBoolField(json, "wifi", wifiConnected);
sp7json::appendEscapedField(json, "ip", ip.c_str());
sp7json::appendEscapedField(json, "ssid", ssid.c_str());
json += "\"rssi\":"; json += String(rssi); json += ",";
}
static uint64_t currentUnixTimeMs(bool* hasTimeOut = nullptr) {
struct timeval tv;
const bool hasTime = gettimeofday(&tv, nullptr) == 0 && tv.tv_sec > 946684800;
if (hasTimeOut) *hasTimeOut = hasTime;
if (!hasTime) return 0;
return ((uint64_t)tv.tv_sec * 1000ULL) + (uint64_t)(tv.tv_usec / 1000);
}
static void appendTimeJson(String& json, bool hasTime, const char* timeText) {
const uint64_t timeUnixMs = hasTime ? currentUnixTimeMs(nullptr) : 0;
appendBoolField(json, "time_ok", hasTime);
sp7json::appendEscapedField(json, "time", hasTime ? timeText : "");
json += "\"timeUnixMs\":";
if (timeUnixMs > 0) {
char buf[24];
snprintf(buf, sizeof(buf), "%llu", (unsigned long long)timeUnixMs);
json += buf;
} else {
json += "0";
}
json += ",";
}
static void appendDeviceJson(String& json,
const float mcuTempC,
const bool mcuTempOk,
const OtaManager* ota,
MqttManager* mqtt) {
json += "\"version\":\""; json += String(SOUNDPANEL7_VERSION); json += "\",";
json += "\"buildDate\":\""; json += String(SOUNDPANEL7_BUILD_DATE); json += "\",";
json += "\"buildEnv\":\""; json += String(SOUNDPANEL7_BUILD_ENV); json += "\",";
appendBoolField(json, "mcuTempOk", mcuTempOk);
json += "\"mcuTempC\":"; json += (mcuTempOk ? String(mcuTempC, 1) : String("0")); json += ",";
appendBoolField(json, "otaEnabled", ota && ota->enabled());
appendBoolField(json, "otaStarted", ota && ota->started());
appendBoolField(json, "mqttEnabled", mqtt && mqtt->enabled());
appendBoolField(json, "mqttConnected", mqtt && mqtt->connected());
sp7json::appendEscapedField(json, "mqttLastError", (mqtt && mqtt->lastError()) ? mqtt->lastError() : "");
}
static void appendReleaseUpdateJson(String& json, const ReleaseUpdateManager* releaseUpdate) {
appendBoolField(json, "releaseUpdateChecked", releaseUpdate && releaseUpdate->hasChecked());
appendBoolField(json, "releaseUpdateOk", releaseUpdate && releaseUpdate->lastCheckOk());
appendBoolField(json, "releaseUpdateAvailable", releaseUpdate && releaseUpdate->updateAvailable());
json += "\"releaseUpdateCheckedAt\":";
json += String(releaseUpdate ? releaseUpdate->lastCheckUnix() : 0U);
json += ",";
json += "\"releaseHttpCode\":";
json += String(releaseUpdate ? releaseUpdate->lastHttpCode() : 0);
json += ",";
sp7json::appendEscapedField(json, "releaseManifestUrl",
(releaseUpdate && releaseUpdate->manifestUrl()) ? releaseUpdate->manifestUrl() : "");
sp7json::appendEscapedField(json, "releaseCurrentVersion",
(releaseUpdate && releaseUpdate->currentVersion()) ? releaseUpdate->currentVersion() : "");
sp7json::appendEscapedField(json, "releaseLatestVersion",
(releaseUpdate && releaseUpdate->latestVersion()[0]) ? releaseUpdate->latestVersion() : "");
sp7json::appendEscapedField(json, "releasePublishedAt",
(releaseUpdate && releaseUpdate->publishedAt()[0]) ? releaseUpdate->publishedAt() : "");
sp7json::appendEscapedField(json, "releaseReleaseUrl",
(releaseUpdate && releaseUpdate->releaseUrl()[0]) ? releaseUpdate->releaseUrl() : "");
sp7json::appendEscapedField(json, "releaseOtaUrl",
(releaseUpdate && releaseUpdate->otaUrl()[0]) ? releaseUpdate->otaUrl() : "");
sp7json::appendEscapedField(json, "releaseOtaSha256",
(releaseUpdate && releaseUpdate->otaSha256()[0]) ? releaseUpdate->otaSha256() : "");
appendBoolField(json, "releaseInstallInProgress", releaseUpdate && releaseUpdate->installInProgress());
appendBoolField(json, "releaseInstallFinished", releaseUpdate && releaseUpdate->installFinished());
appendBoolField(json, "releaseInstallSucceeded", releaseUpdate && releaseUpdate->installSucceeded());
json += "\"releaseInstallStartedAt\":";
json += String(releaseUpdate ? releaseUpdate->installStartedUnix() : 0U);
json += ",";
json += "\"releaseInstallFinishedAt\":";
json += String(releaseUpdate ? releaseUpdate->installFinishedUnix() : 0U);
json += ",";
json += "\"releaseInstallTotalBytes\":";
json += String(releaseUpdate ? releaseUpdate->installTotalBytes() : 0U);
json += ",";
json += "\"releaseInstallWrittenBytes\":";
json += String(releaseUpdate ? releaseUpdate->installWrittenBytes() : 0U);
json += ",";
json += "\"releaseInstallProgressPct\":";
json += String(releaseUpdate ? releaseUpdate->installProgressPct() : 0U);
json += ",";
sp7json::appendEscapedField(json, "releaseInstallStatus",
(releaseUpdate && releaseUpdate->installStatus()[0]) ? releaseUpdate->installStatus() : "");
sp7json::appendEscapedField(json, "releaseInstallError",
(releaseUpdate && releaseUpdate->installError()[0]) ? releaseUpdate->installError() : "");
sp7json::appendEscapedField(json, "releaseLastError",
(releaseUpdate && releaseUpdate->lastError()[0]) ? releaseUpdate->lastError() : "");
}
static void appendUiStateJson(String& json, const SettingsV1* s, const SharedHistory* history, bool includeCalibrationPointCount) {
json += "\"backlight\":"; json += String(s ? s->backlight : 0); json += ",";
json += "\"greenMax\":"; json += String(s ? s->th.greenMax : DEFAULT_GREEN_MAX); json += ",";
json += "\"orangeMax\":"; json += String(s ? s->th.orangeMax : DEFAULT_ORANGE_MAX); json += ",";
json += "\"historyMinutes\":"; json += String(s ? s->historyMinutes : DEFAULT_HISTORY_MINUTES); json += ",";
appendBoolField(json, "liveEnabled", s && s->liveEnabled);
appendBoolField(json, "touchEnabled", s && s->touchEnabled);
appendBoolField(json, "hasScreen", SOUNDPANEL7_HAS_SCREEN);
json += "\"dashboardPage\":"; json += String(s ? s->dashboardPage : DEFAULT_DASHBOARD_PAGE); json += ",";
json += "\"dashboardFullscreenMask\":"; json += String(s ? s->dashboardFullscreenMask : DEFAULT_DASHBOARD_FULLSCREEN_MASK); json += ",";
json += "\"audioSource\":"; json += String(s ? s->audioSource : 1); json += ",";
appendBoolField(json, "audioSourceSupportsCalibration", AudioEngine::sourceSupportsCalibration(s ? s->audioSource : 1));
appendBoolField(json, "audioSourceUsesAnalog", AudioEngine::sourceUsesAnalog(s ? s->audioSource : 1));
appendBoolField(json, "supportsDashboardDisplay", SOUNDPANEL7_HAS_SCREEN);
appendBoolField(json, "supportsDashboardPin", SOUNDPANEL7_HAS_SCREEN);
appendBoolField(json, "supportsTardisControl", SOUNDPANEL7_TARDIS_SUPPORTED);
appendBoolField(json, "supportsTardisInteriorRgb", SOUNDPANEL7_TARDIS_INTERIOR_RGB_SUPPORTED);
appendBoolField(json, "tardisModeEnabled", s && s->tardisModeEnabled);
appendBoolField(json, "tardisInteriorLedEnabled", s && s->tardisInteriorLedEnabled);
appendBoolField(json, "tardisExteriorLedEnabled", s && s->tardisExteriorLedEnabled);
json += "\"tardisInteriorLedPin\":"; json += String((int)SOUNDPANEL7_TARDIS_INTERIOR_LED_PIN); json += ",";
json += "\"tardisExteriorLedPin\":"; json += String((int)SOUNDPANEL7_TARDIS_EXTERIOR_LED_PIN); json += ",";
json += "\"tardisInteriorRgbPin\":"; json += String((int)SOUNDPANEL7_TARDIS_INTERIOR_RGB_PIN); json += ",";
json += "\"tardisInteriorRgbMode\":"; json += String(s ? s->tardisInteriorRgbMode : TARDIS_INTERIOR_RGB_MODE_ALERT); json += ",";
json += "\"tardisInteriorRgbColor\":"; json += String(s ? s->tardisInteriorRgbColor : TARDIS_INTERIOR_RGB_DEFAULT_COLOR); json += ",";
json += "\"audioResponseMode\":"; json += String(s ? s->audioResponseMode : 0); json += ",";
json += "\"historyCapacity\":"; json += String(SharedHistory::POINT_COUNT); json += ",";
json += "\"historySamplePeriodMs\":"; json += String(history ? history->samplePeriodMs() : 3000); json += ",";
json += "\"warningHoldSec\":"; json += String(s ? (s->orangeAlertHoldMs / MS_PER_SECOND) : (DEFAULT_WARNING_HOLD_MS / MS_PER_SECOND)); json += ",";
json += "\"criticalHoldSec\":"; json += String(s ? (s->redAlertHoldMs / MS_PER_SECOND) : (DEFAULT_CRITICAL_HOLD_MS / MS_PER_SECOND)); json += ",";
if (includeCalibrationPointCount) {
json += "\"calibrationPointCount\":"; json += String(s ? s->calibrationPointCount : 3); json += ",";
}
json += "\"calibrationCaptureSec\":"; json += String(s ? (s->calibrationCaptureMs / MS_PER_SECOND) : (DEFAULT_CALIBRATION_CAPTURE_MS / MS_PER_SECOND)); json += ",";
}
static bool tardisPinConflictsWithAudioPin(uint8_t pin, const SettingsV1* s) {
if (pin == SOUNDPANEL7_DEFAULT_ANALOG_PIN
|| pin == SOUNDPANEL7_DEFAULT_PDM_CLK_PIN
|| pin == SOUNDPANEL7_DEFAULT_PDM_DATA_PIN
|| pin == SOUNDPANEL7_DEFAULT_INMP441_BCLK_PIN
|| pin == SOUNDPANEL7_DEFAULT_INMP441_WS_PIN
|| pin == SOUNDPANEL7_DEFAULT_INMP441_DATA_PIN) {
return true;
}
if (!s) return false;
return pin == s->analogPin
|| pin == s->pdmClkPin
|| pin == s->pdmDataPin
|| pin == s->inmp441BclkPin
|| pin == s->inmp441WsPin
|| pin == s->inmp441DataPin;
}
static void appendPinStateJson(String& json, bool configured) {
json += "\"pinConfigured\":";
json += configured ? "true" : "false";
json += ",";
}
static void appendAudioMetricsJson(String& json, const AudioMetrics& am) {
json += "\"db\":"; json += String(g_webDbInstant, 1); json += ",";
json += "\"leq\":"; json += String(g_webLeq, 1); json += ",";
json += "\"peak\":"; json += String(g_webPeak, 1); json += ",";
json += "\"rawRms\":"; json += String(am.rawRms, 2); json += ",";
json += "\"rawPseudoDb\":"; json += String(am.rawPseudoDb, 1); json += ",";
json += "\"rawAdcMean\":"; json += String(am.rawAdcMean); json += ",";
json += "\"rawAdcLast\":"; json += String(am.rawAdcLast); json += ",";
appendBoolField(json, "analogOk", am.analogOk);
}
static void appendRuntimeStatsJson(String& json, const RuntimeStats& stats) {
json += "\"cpuIdlePct\":"; json += String(stats.cpuIdlePct); json += ",";
json += "\"cpuLoadPct\":"; json += String(stats.cpuLoadPct); json += ",";
json += "\"lvglIdlePct\":"; json += String(stats.lvglIdlePct); json += ",";
json += "\"lvglLoadPct\":"; json += String(stats.lvglLoadPct); json += ",";
json += "\"lvglUiWorkUs\":"; json += String(stats.uiWorkLastUs); json += ",";
json += "\"lvglUiWorkMaxUs\":"; json += String(stats.uiWorkMaxUs); json += ",";
json += "\"lvglHandlerUs\":"; json += String(stats.lvHandlerLastUs); json += ",";
json += "\"lvglHandlerMaxUs\":"; json += String(stats.lvHandlerMaxUs); json += ",";
json += "\"lvglObjCount\":"; json += String(stats.lvObjCount); json += ",";
json += "\"heapInternalFree\":"; json += String(stats.heapInternalFree); json += ",";
json += "\"heapInternalTotal\":"; json += String(stats.heapInternalTotal); json += ",";
json += "\"heapInternalMin\":"; json += String(stats.heapInternalMin); json += ",";
json += "\"heapPsramFree\":"; json += String(stats.heapPsramFree); json += ",";
json += "\"heapPsramTotal\":"; json += String(stats.heapPsramTotal); json += ",";
json += "\"heapPsramMin\":"; json += String(stats.heapPsramMin); json += ",";
sp7json::appendEscapedField(json, "activePage", stats.activePage);
}
static uint32_t currentUnixTimestamp() {
time_t now = time(nullptr);
return now > 946684800 ? (uint32_t)now : 0U;
}
static String trimmedHttpResponse(String value) {
value.trim();
if (value.length() > 96) {
value.remove(96);
value += "...";
}
return value;
}
void WebManager::addCommonSecurityHeaders(bool noStore) {
_srv.sendHeader("X-Frame-Options", "DENY");
_srv.sendHeader("X-Content-Type-Options", "nosniff");
_srv.sendHeader("Referrer-Policy", "same-origin");
if (noStore) {
_srv.sendHeader("Cache-Control", "no-store, max-age=0");
_srv.sendHeader("Pragma", "no-cache");
}
}
bool WebManager::secureEquals(const char* a, const char* b) {
if (!a || !b) return false;
const size_t lenA = strlen(a);
const size_t lenB = strlen(b);
const size_t maxLen = lenA > lenB ? lenA : lenB;
uint8_t diff = (uint8_t)(lenA ^ lenB);
for (size_t i = 0; i < maxLen; i++) {
const uint8_t ca = i < lenA ? (uint8_t)a[i] : 0;
const uint8_t cb = i < lenB ? (uint8_t)b[i] : 0;
diff |= (uint8_t)(ca ^ cb);
}
return diff == 0;
}
bool WebManager::normalizeUsername(String& username) {
username.trim();
username.toLowerCase();
if (username.length() < 3 || username.length() > WEB_USERNAME_MAX_LENGTH) return false;
for (size_t i = 0; i < username.length(); i++) {
const char c = username[i];
const bool allowed = (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9')
|| c == '.'
|| c == '_'
|| c == '-';
if (!allowed) return false;
}
return true;
}
bool WebManager::homeAssistantTokenIsValid(const String& token) {
// SECURITY: Enforce minimum 32-char length for adequate entropy (HIGH-05)
// 32 chars = minimum 128-bit entropy (assuming base64-like encoding)
// Generated tokens use 64 hex chars = 256-bit entropy
const size_t len = token.length();
if (len < 32 || len > HOME_ASSISTANT_TOKEN_MAX_LENGTH) return false;
for (size_t i = 0; i < len; i++) {
const char c = token[i];
const bool allowed = (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '-'
|| c == '_';
if (!allowed) return false;
}
return true;
}
bool WebManager::passwordIsStrongEnough(const String& password, String* reason) {
const size_t len = password.length();
if (len < WEB_PASSWORD_MIN_LENGTH || len > WEB_PASSWORD_MAX_LENGTH) {
if (reason) *reason = "password must be 10 to 64 chars";
return false;
}
bool hasLower = false;
bool hasUpper = false;
bool hasDigit = false;
bool hasSymbol = false;
for (size_t i = 0; i < len; i++) {
const char c = password[i];
if (c >= 'a' && c <= 'z') hasLower = true;
else if (c >= 'A' && c <= 'Z') hasUpper = true;
else if (c >= '0' && c <= '9') hasDigit = true;
else hasSymbol = true;
}
const uint8_t classCount = (hasLower ? 1 : 0) + (hasUpper ? 1 : 0) + (hasDigit ? 1 : 0) + (hasSymbol ? 1 : 0);
if (classCount < 3) {
if (reason) *reason = "password needs 3 character classes";
return false;
}
return true;
}
String WebManager::randomHex(size_t hexChars) {
// SECURITY: Session token entropy sources (HIGH-03)
// - esp_random(): ESP32 hardware RNG (cryptographically secure, automatically seeded by RF noise + boot ROM)
// - millis(): Monotonic timestamp provides additional timing entropy
// - Static counter: Ensures uniqueness even if called at same millisecond
// Result: 192-bit tokens (48 hex chars) with multiple entropy sources
static const char kHexChars[] = "0123456789abcdef";
static uint32_t tokenCounter = 0;
String out;
out.reserve(hexChars);
// Mix in timestamp and counter for first 8 chars (32 bits)
const uint32_t mixedEntropy = esp_random() ^ millis() ^ (++tokenCounter);
for (int shift = 28; shift >= 0 && out.length() < hexChars; shift -= 4) {
out += kHexChars[(mixedEntropy >> shift) & 0x0F];
}
// Fill remaining chars with pure hardware RNG
while (out.length() < hexChars) {
const uint32_t value = esp_random();
for (int shift = 28; shift >= 0 && out.length() < hexChars; shift -= 4) {
out += kHexChars[(value >> shift) & 0x0F];
}
}
return out;
}
String WebManager::hashPassword(const char* username, const char* password, const char* saltHex) {
uint8_t digest[32] = {0};
mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx);
auto runRound = [&](bool firstRound) {
mbedtls_sha256_starts(&ctx, 0);
if (!firstRound) {
mbedtls_sha256_update(&ctx, digest, sizeof(digest));
}
if (saltHex) mbedtls_sha256_update(&ctx, (const uint8_t*)saltHex, strlen(saltHex));
if (username) mbedtls_sha256_update(&ctx, (const uint8_t*)username, strlen(username));
if (password) mbedtls_sha256_update(&ctx, (const uint8_t*)password, strlen(password));
mbedtls_sha256_finish(&ctx, digest);
};
runRound(true);
for (uint16_t i = 1; i < WEB_PASSWORD_HASH_ROUNDS; i++) runRound(false);
mbedtls_sha256_free(&ctx);
static const char kHexChars[] = "0123456789abcdef";
char out[(32 * 2) + 1];
for (size_t i = 0; i < sizeof(digest); i++) {
out[i * 2] = kHexChars[(digest[i] >> 4) & 0x0F];
out[(i * 2) + 1] = kHexChars[digest[i] & 0x0F];
}
out[sizeof(out) - 1] = '\0';
return String(out);
}
bool WebManager::webUsersConfigured() const {
return _store && _store->webUserCount() > 0;
}
void WebManager::cleanupExpiredSessions() {
const uint32_t now = millis();
for (WebSession& session : _sessions) {
if (!session.active) continue;
if ((uint32_t)(now - session.lastSeenMs) > WEB_SESSION_IDLE_TIMEOUT_MS) {
session = WebSession{};
}
}
}
const WebManager::WebSession* WebManager::findSessionByToken(const char* token, bool touch) {
if (!token || !token[0]) return nullptr;
cleanupExpiredSessions();
const uint32_t now = millis();
for (WebSession& session : _sessions) {
if (!session.active) continue;
if (!secureEquals(session.sessionToken, token)) continue;
if (touch) session.lastSeenMs = now;
return &session;
}
return nullptr;
}
const WebManager::WebSession* WebManager::findSessionByLiveToken(const char* token, bool touch) {
if (!token || !token[0]) return nullptr;
cleanupExpiredSessions();
const uint32_t now = millis();
for (WebSession& session : _sessions) {
if (!session.active) continue;
if (!secureEquals(session.liveToken, token)) continue;
if (touch) session.lastSeenMs = now;
return &session;
}
return nullptr;
}
const WebManager::WebSession* WebManager::currentSession(bool touch) {
return findSessionByToken(extractCookieValue(SP7_SESSION_COOKIE_NAME).c_str(), touch);
}
WebManager::WebSession* WebManager::newSessionSlot() {
cleanupExpiredSessions();
for (WebSession& session : _sessions) {
if (!session.active) return &session;
}
WebSession* oldest = &_sessions[0];
for (WebSession& session : _sessions) {
if (session.lastSeenMs < oldest->lastSeenMs) oldest = &session;
}
return oldest;
}
void WebManager::invalidateSessionToken(const char* token) {
if (!token || !token[0]) return;
for (WebSession& session : _sessions) {
if (session.active && secureEquals(session.sessionToken, token)) {
session = WebSession{};
if (_live) _live->close();
return;
}
}
}
void WebManager::invalidateSessionsForUser(const char* username) {
if (!username || !username[0]) return;
bool changed = false;
for (WebSession& session : _sessions) {
if (session.active && secureEquals(session.username, username)) {
session = WebSession{};
changed = true;
}
}
if (changed && _live) _live->close();
}
void WebManager::clearAllSessions() {
for (WebSession& session : _sessions) session = WebSession{};
if (_live) _live->close();
}
bool WebManager::issueSessionForUser(const char* username, String& liveTokenOut) {
if (!username || !username[0]) return false;
WebSession* session = newSessionSlot();
if (!session) return false;
*session = WebSession{};
session->active = true;
const String sessionToken = randomHex(sizeof(session->sessionToken) - 1);
const String liveToken = randomHex(sizeof(session->liveToken) - 1);
if (!sp7json::safeCopy(session->sessionToken, sizeof(session->sessionToken), sessionToken)) return false;
if (!sp7json::safeCopy(session->liveToken, sizeof(session->liveToken), liveToken)) return false;
if (!sp7json::safeCopy(session->username, sizeof(session->username), String(username))) return false;
session->lastSeenMs = millis();
liveTokenOut = liveToken;
// SECURITY: HTTP-only deployment threat model (MED-03)
// Cookie flags: HttpOnly (prevents XSS), SameSite=Strict (prevents CSRF)
// Secure flag NOT set: Device operates HTTP-only on local network (no TLS)
// Threat model assumptions:
// - Deployed on physically secured, trusted local network (home/office LAN)
// - Network isolation via VLAN or firewall from untrusted devices
// - No exposure to public internet or untrusted users
// Risk: HTTP traffic can be intercepted on local network by attacker with network access
// Mitigation: Physical security, network isolation, strong passwords, session timeout
// Future: Consider HTTPS with self-signed certificates for defense-in-depth
_srv.sendHeader("Set-Cookie", String(SP7_SESSION_COOKIE_NAME) + "=" + sessionToken + "; Path=/; HttpOnly; SameSite=Strict");
return true;
}
String WebManager::extractCookieValue(const char* cookieName) const {
if (!cookieName || !_srv.hasHeader("Cookie")) return "";
const String cookieHeader = _srv.header("Cookie");
const String prefix = String(cookieName) + "=";
int start = 0;
while (start < (int)cookieHeader.length()) {
while (start < (int)cookieHeader.length() && (cookieHeader[start] == ' ' || cookieHeader[start] == ';')) start++;
const int end = cookieHeader.indexOf(';', start);
const String part = cookieHeader.substring(start, end >= 0 ? end : cookieHeader.length());
if (part.startsWith(prefix)) return part.substring(prefix.length());
if (end < 0) break;
start = end + 1;
}
return "";
}
String WebManager::extractAuthorizationBearer() const {
if (!_srv.hasHeader("Authorization")) return "";
String header = _srv.header("Authorization");
header.trim();
if (header.length() < 7) return "";
if (!header.substring(0, 7).equalsIgnoreCase("Bearer ")) return "";
String token = header.substring(7);
token.trim();
return token;
}
bool WebManager::requireWebAuth() {
if (currentSession()) return true;
addCommonSecurityHeaders();
_srv.sendHeader("Set-Cookie", String(SP7_SESSION_COOKIE_NAME) + "=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict");
replyErrorJson(401, "auth required");
return false;
}
bool WebManager::homeAssistantTokenConfigured() const {
return _s && _s->homeAssistantToken[0] != '\0';
}
bool WebManager::requireHomeAssistantToken() {
if (!_s) {
replyErrorJson(500, "settings missing");
return false;
}
if (!homeAssistantTokenConfigured()) {
replyErrorJson(403, "home assistant token not configured");
return false;
}
const String token = extractAuthorizationBearer();
if (homeAssistantTokenIsValid(token) && secureEquals(_s->homeAssistantToken, token.c_str())) {
return true;
}
addCommonSecurityHeaders();
replyErrorJson(401, "invalid home assistant token");
return false;
}
bool WebManager::begin(SettingsStore* store,
SettingsV1* settings,
NetManager* net,
esp_panel::board::Board* board,
SharedHistory* history,
OtaManager* ota,
ReleaseUpdateManager* releaseUpdate,
MqttManager* mqtt,
UiManager* ui) {
_store = store;
_s = settings;
_net = net;
_board = board;
_history = history;
_ota = ota;
_releaseUpdate = releaseUpdate;
_mqtt = mqtt;
_ui = ui;
if (!_live) _live = new LiveEventServer(81, "/api/events");
if (_net) {
_net->setConfigPortalStateCallback([this](bool active) {
if (active) {
stopHttpServer();
} else {
syncHttpAvailability();
}
});
}
if (!g_bootMs) g_bootMs = millis();
if (_started) return true;
const char* headers[] = {"Cookie", "Authorization"};
_srv.collectHeaders(headers, 2);
routes();
setupLiveStream();
// SECURITY: Create mutex to protect bootstrap endpoint from race conditions (CRIT-02)
if (!_bootstrapMutex) {
_bootstrapMutex = xSemaphoreCreateMutex();
}
// SECURITY: Create mutex to protect settings modifications (MED-02)
if (!_settingsMutex) {
_settingsMutex = xSemaphoreCreateMutex();
}
// Start async notification task on Core 0
if (!NotificationTask::begin()) {
Serial0.println("[WEB] WARNING: Notification task failed to start");
}
_started = true;
applyTardisNow();
Serial0.println("[WEB] LIVE SSE on 81");
syncHttpAvailability();
return true;
}
static bool dueOnFixedPeriod(uint32_t& anchorMs, uint32_t periodMs, uint32_t nowMs, bool force = false) {
if (force) {
anchorMs = nowMs;
return true;
}
if (anchorMs == 0) {
anchorMs = nowMs;
return true;
}
if ((uint32_t)(nowMs - anchorMs) < periodMs) return false;
do {
anchorMs += periodMs;
} while ((uint32_t)(nowMs - anchorMs) >= periodMs);
return true;
}
void WebManager::updateMetrics(float dbInstant, float leq, float peak) {
g_webDbInstant = dbInstant;
g_webLeq = leq;
g_webPeak = peak;
pushLiveMetrics();
updateAlertState(dbInstant, leq, peak);
}
void WebManager::routes() {
_srv.on("/", kSyncHttpGet, [this]() { handleRoot(); });
_srv.on("/api/auth/status", kSyncHttpGet, [this]() { handleAuthStatus(); });
_srv.on("/api/auth/login", kSyncHttpPost, [this]() { handleAuthLogin(); });
_srv.on("/api/auth/logout", kSyncHttpPost, [this]() { handleAuthLogout(); });
_srv.on("/api/auth/bootstrap", kSyncHttpPost, [this]() { handleAuthBootstrap(); });
_srv.on("/api/users", kSyncHttpGet, [this]() { handleUsersGet(); });
_srv.on("/api/users/create", kSyncHttpPost, [this]() { handleUsersCreate(); });
_srv.on("/api/users/password", kSyncHttpPost, [this]() { handleUsersPassword(); });
_srv.on("/api/users/delete", kSyncHttpPost, [this]() { handleUsersDelete(); });
_srv.on("/api/ha/status", kSyncHttpGet, [this]() { handleHomeAssistantStatus(); });
_srv.on("/api/homeassistant", kSyncHttpGet, [this]() { handleHomeAssistantGet(); });
_srv.on("/api/homeassistant", kSyncHttpPost, [this]() { handleHomeAssistantSave(); });
_srv.on("/api/homeassistant/reveal", kSyncHttpGet, [this]() { handleHomeAssistantReveal(); });
_srv.on("/api/status", kSyncHttpGet, [this]() { handleStatus(); });
_srv.on("/api/system", kSyncHttpGet, [this]() { handleSystemSummary(); });
_srv.on("/api/pin", kSyncHttpPost, [this]() { handlePinSave(); });
_srv.on("/api/ui", kSyncHttpPost, [this]() { handleUiSave(); });
_srv.on("/api/live", kSyncHttpGet, [this]() { handleLiveGet(); });
_srv.on("/api/live", kSyncHttpPost, [this]() { handleLiveSave(); });
_srv.on("/api/wifi", kSyncHttpGet, [this]() { handleWifiGet(); });
_srv.on("/api/wifi", kSyncHttpPost, [this]() { handleWifiSave(); });
_srv.on("/api/time", kSyncHttpGet, [this]() { handleTimeGet(); });
_srv.on("/api/time", kSyncHttpPost, [this]() { handleTimeSave(); });
_srv.on("/api/config/export", kSyncHttpGet, [this]() { handleConfigExport(); });
_srv.on("/api/config/export_full", kSyncHttpPost, [this]() { handleConfigExportFull(); });
_srv.on("/api/config/import", kSyncHttpPost, [this]() { handleConfigImport(); });
_srv.on("/api/config/backup", kSyncHttpPost, [this]() { handleConfigBackup(); });
_srv.on("/api/config/restore", kSyncHttpPost, [this]() { handleConfigRestore(); });
_srv.on("/api/config/reset_partial", kSyncHttpPost, [this]() { handleConfigResetPartial(); });
_srv.on("/api/ota", kSyncHttpGet, [this]() { handleOtaGet(); });
_srv.on("/api/ota", kSyncHttpPost, [this]() { handleOtaSave(); });
_srv.on("/api/release", kSyncHttpGet, [this]() { handleReleaseGet(); });
_srv.on("/api/release/check", kSyncHttpPost, [this]() { handleReleaseCheck(); });
_srv.on("/api/release/install", kSyncHttpPost, [this]() { handleReleaseInstall(); });
_srv.on("/api/mqtt", kSyncHttpGet, [this]() { handleMqttGet(); });
_srv.on("/api/mqtt", kSyncHttpPost, [this]() { handleMqttSave(); });
_srv.on("/api/notifications", kSyncHttpGet, [this]() { handleNotificationsGet(); });
_srv.on("/api/notifications", kSyncHttpPost, [this]() { handleNotificationsSave(); });
_srv.on("/api/notifications/test", kSyncHttpPost, [this]() { handleNotificationsTest(); });
_srv.on("/api/slack/reveal", kSyncHttpGet, [this]() { handleSlackReveal(); });
_srv.on("/api/debug/logs", kSyncHttpGet, [this]() { handleDebugLogsGet(); });
_srv.on("/api/debug/logs/clear", kSyncHttpPost, [this]() { handleDebugLogsClear(); });
_srv.on("/api/calibrate", kSyncHttpPost, [this]() { handleCalPoint(); });
_srv.on("/api/calibrate/clear", kSyncHttpPost, [this]() { handleCalClear(); });
_srv.on("/api/calibrate/mode", kSyncHttpPost, [this]() { handleCalMode(); });
_srv.on("/api/reboot", kSyncHttpPost, [this]() { handleReboot(); });
_srv.on("/api/shutdown", kSyncHttpPost, [this]() { handleShutdown(); });
_srv.on("/api/factory_reset", kSyncHttpPost, [this]() { handleFactoryReset(); });
_srv.onNotFound([this]() { replyText(404, "404\n"); });
}
void WebManager::loop() {
if (!_started) return;
updateTardisAnimationNow();
const bool localOtaInProgress = _ota && _ota->inProgress();
const bool releaseInstallInProgress = _releaseUpdate && _releaseUpdate->installInProgress();
if (localOtaInProgress) {
stopHttpServer();
if (_live && _live->clientCount() > 0) {
_live->close();
}
return;
}
if (releaseInstallInProgress && _live && _live->clientCount() > 0) {
_live->close();
}
processPendingNotification();
syncHttpAvailability();
if (!_httpListening) return;
_srv.handleClient();
}
const char* WebManager::alertStateName(uint8_t alertState) {
switch (alertState) {
case 1: return "warning";
case 2: return "critical";
default: return "recovery";
}
}
void WebManager::updateAlertState(float dbInstant, float leq, float peak) {
if (!_s) return;
const uint32_t now = millis();
const bool orangeZone = dbInstant > _s->th.greenMax;
const bool redZone = dbInstant > _s->th.orangeMax;
if (redZone) {
if (_redZoneSinceMs == 0) _redZoneSinceMs = now;
}
if (orangeZone) {
if (_orangeZoneSinceMs == 0) _orangeZoneSinceMs = now;
} else {
_redZoneSinceMs = 0;
_orangeZoneSinceMs = 0;
}
const bool orangeAlert = _orangeZoneSinceMs != 0 && (now - _orangeZoneSinceMs) >= _s->orangeAlertHoldMs;
const bool redAlert = _redZoneSinceMs != 0 && (now - _redZoneSinceMs) >= _s->redAlertHoldMs;
const uint8_t nextAlertState = redAlert ? 2 : (orangeAlert ? 1 : 0);
const uint8_t previousAlertState = _alertState;
_alertState = nextAlertState;
if (SOUNDPANEL7_TARDIS_SUPPORTED && SOUNDPANEL7_TARDIS_INTERIOR_RGB_SUPPORTED
&& _s->tardisModeEnabled && _s->tardisInteriorLedEnabled) {
applyTardisInteriorRgbColor(tardisInteriorRgbColorForCurrentState());
}
if (nextAlertState == previousAlertState) return;
if (nextAlertState > previousAlertState) {
if (previousAlertState == 0 && _activeAlertStartedMs == 0) _activeAlertStartedMs = now;
if (nextAlertState == 2) {
enqueueNotification(2, false, dbInstant, leq, peak);
} else if (_s->notifyOnWarning == ALERT_NOTIFY_LEVEL_WARNING) {
enqueueNotification(1, false, dbInstant, leq, peak);
}
return;
}
if (nextAlertState == 0 && previousAlertState > 0 && _s->notifyOnRecovery && _lastNotifiedAlertState > 0) {
const uint32_t durationMs = _activeAlertStartedMs != 0 ? (now - _activeAlertStartedMs) : 0;
enqueueNotification(0, false, dbInstant, leq, peak, durationMs);
}
if (nextAlertState == 0) _activeAlertStartedMs = 0;
}
void WebManager::enqueueNotification(uint8_t alertState, bool isTest, float dbInstant, float leq, float peak, uint32_t durationMs) {
_notificationPending = true;
_notificationPendingTest = isTest;
_pendingNotificationState = alertState;
_pendingNotificationDb = dbInstant;
_pendingNotificationLeq = leq;
_pendingNotificationPeak = peak;
_pendingNotificationDurationMs = durationMs;
}
void WebManager::processPendingNotification() {
if (!_notificationPending) return;
if (!_s) return;
const bool isTest = _notificationPendingTest;
const uint8_t alertState = _pendingNotificationState;
const float dbInstant = _pendingNotificationDb;
const float leq = _pendingNotificationLeq;
const float peak = _pendingNotificationPeak;
const uint32_t durationMs = _pendingNotificationDurationMs;
_notificationPending = false;
_notificationPendingTest = false;
_pendingNotificationDurationMs = 0;
// Build notification request with copied data (thread-safe)
NotificationRequest req = {};
req.alertState = alertState;
req.isTest = isTest;
req.dbInstant = dbInstant;
req.leq = leq;
req.peak = peak;
req.durationMs = durationMs;
req.updateAlertTracking = !isTest;
// Copy settings (thread-safe, no pointer sharing)
req.slackEnabled = _s->slackEnabled != 0;
strncpy(req.slackWebhookUrl, _s->slackWebhookUrl, sizeof(req.slackWebhookUrl) - 1);
strncpy(req.slackChannel, _s->slackChannel, sizeof(req.slackChannel) - 1);
req.telegramEnabled = _s->telegramEnabled != 0;
strncpy(req.telegramBotToken, _s->telegramBotToken, sizeof(req.telegramBotToken) - 1);
strncpy(req.telegramChatId, _s->telegramChatId, sizeof(req.telegramChatId) - 1);
req.whatsappEnabled = _s->whatsappEnabled != 0;
strncpy(req.whatsappAccessToken, _s->whatsappAccessToken, sizeof(req.whatsappAccessToken) - 1);
strncpy(req.whatsappPhoneNumberId, _s->whatsappPhoneNumberId, sizeof(req.whatsappPhoneNumberId) - 1);
strncpy(req.whatsappRecipient, _s->whatsappRecipient, sizeof(req.whatsappRecipient) - 1);
strncpy(req.whatsappApiVersion, _s->whatsappApiVersion, sizeof(req.whatsappApiVersion) - 1);
strncpy(req.hostname, _s->hostname, sizeof(req.hostname) - 1);
req.greenMax = _s->th.greenMax;
req.orangeMax = _s->th.orangeMax;
// Send to async task (non-blocking)
NotificationTask::queueNotification(req);
// Update tracking immediately (don't wait for async result)
if (req.updateAlertTracking) {
_lastNotifiedAlertState = alertState;
}
}
void WebManager::startHttpServer() {
if (_httpListening) return;
_srv.begin();
_httpListening = true;
Serial0.println("[WEB] LISTEN on 80");
if (WiFi.isConnected()) {
Serial0.printf("[WEB] URL: http://%s/\n", WiFi.localIP().toString().c_str());
} else {
Serial0.println("[WEB] WiFi not connected yet (URL available after connect)");
}
}
void WebManager::stopHttpServer() {
if (!_httpListening) return;
Serial0.println("[WEB] stopping main HTTP server");
_srv.stop();
_httpListening = false;