-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathweb_config_api.cpp
More file actions
1159 lines (983 loc) · 50.3 KB
/
web_config_api.cpp
File metadata and controls
1159 lines (983 loc) · 50.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
#include "web_config.h"
#include "web_config_html.h"
#include "system_monitor.h"
#include "config_storage.h"
#include "network_manager.h"
#include "crash_logger.h"
#include "mqtt_manager.h"
#include "display_manager.h"
#include "ota_manager.h"
#include "device_health.h"
#include "ha_rest_client.h"
#include "ha_discovery.h"
#include "logging.h"
#include <Update.h>
// External global instances
extern CrashLogger crashLogger;
// System monitor is needed for watchdog resets during OTA
// API handler functions for the web configuration interface
// These functions process POST requests and handle configuration changes
void WebConfig::handleSaveConfig() {
LOG_INFO("[WebAPI] Configuration save request received");
bool needsRestart = false;
bool brightnessChanged = false;
bool imageSettingsChanged = false;
bool displayTypeChanged = false;
int newBrightness = -1;
// Parse form data and save configuration
for (int i = 0; i < server->args(); i++) {
String name = server->argName(i);
String value = server->arg(i);
// Device settings
if (name == "device_name") {
configStorage.setDeviceName(value);
}
// Network settings
else if (name == "wifi_ssid") {
if (configStorage.getWiFiSSID() != value) {
LOG_INFO_F("[WebAPI] WiFi SSID updated: %s (restart required)\n", value.c_str());
needsRestart = true;
}
configStorage.setWiFiSSID(value);
}
else if (name == "wifi_password") {
if (value.length() > 0) { // Skip empty values (placeholder pattern)
if (configStorage.getWiFiPassword() != value) {
LOG_INFO("[WebAPI] WiFi password updated (value hidden for security) - restart required");
needsRestart = true;
}
configStorage.setWiFiPassword(value);
}
}
// MQTT settings
else if (name == "mqtt_server") {
if (configStorage.getMQTTServer() != value) {
LOG_INFO_F("[WebAPI] MQTT server updated: %s (restart required)\n", value.c_str());
needsRestart = true;
}
configStorage.setMQTTServer(value);
}
else if (name == "mqtt_port") {
if (configStorage.getMQTTPort() != value.toInt()) {
LOG_INFO_F("[WebAPI] MQTT port updated: %d (restart required)\n", value.toInt());
needsRestart = true;
}
configStorage.setMQTTPort(value.toInt());
}
else if (name == "mqtt_user") {
LOG_DEBUG_F("[WebAPI] MQTT username updated: %s\n", value.c_str());
configStorage.setMQTTUser(value);
}
else if (name == "mqtt_password") {
if (value.length() > 0) { // Skip empty values (placeholder pattern)
LOG_DEBUG("[WebAPI] MQTT password updated (value hidden for security)");
configStorage.setMQTTPassword(value);
}
}
else if (name == "mqtt_client_id") configStorage.setMQTTClientID(value);
// Home Assistant Discovery settings
else if (name == "ha_device_name") configStorage.setHADeviceName(value);
else if (name == "ha_discovery_prefix") configStorage.setHADiscoveryPrefix(value);
else if (name == "ha_state_topic") configStorage.setHAStateTopic(value);
else if (name == "ha_sensor_update_interval") configStorage.setHASensorUpdateInterval(value.toInt());
// Image settings
else if (name == "image_url") {
if (configStorage.getImageURL() != value) {
LOG_INFO_F("[WebAPI] Image URL updated: %s\n", value.c_str());
imageSettingsChanged = true;
}
configStorage.setImageURL(value);
}
// Display settings
else if (name == "default_brightness") {
int brightness = value.toInt();
if (configStorage.getDefaultBrightness() != brightness) {
LOG_INFO_F("[WebAPI] Brightness updated: %d%% (applied immediately)\n", brightness);
brightnessChanged = true;
newBrightness = brightness;
}
configStorage.setDefaultBrightness(brightness);
}
else if (name == "default_scale_x") {
if (abs(configStorage.getDefaultScaleX() - value.toFloat()) > 0.01) imageSettingsChanged = true;
configStorage.setDefaultScaleX(value.toFloat());
}
else if (name == "default_scale_y") {
if (abs(configStorage.getDefaultScaleY() - value.toFloat()) > 0.01) imageSettingsChanged = true;
configStorage.setDefaultScaleY(value.toFloat());
}
else if (name == "default_offset_x") {
if (configStorage.getDefaultOffsetX() != value.toInt()) imageSettingsChanged = true;
configStorage.setDefaultOffsetX(value.toInt());
}
else if (name == "default_offset_y") {
if (configStorage.getDefaultOffsetY() != value.toInt()) imageSettingsChanged = true;
configStorage.setDefaultOffsetY(value.toInt());
}
else if (name == "default_rotation") {
if (abs(configStorage.getDefaultRotation() - value.toFloat()) > 0.01) imageSettingsChanged = true;
configStorage.setDefaultRotation(value.toFloat());
}
else if (name == "backlight_freq") configStorage.setBacklightFreq(value.toInt());
else if (name == "backlight_resolution") configStorage.setBacklightResolution(value.toInt());
else if (name == "color_temp") {
int temp = value.toInt();
configStorage.setColorTemp(temp);
LOG_INFO_F("[WebAPI] Color temperature set to %dK\n", temp);
imageSettingsChanged = true; // Trigger image refresh to apply new color temp
}
// Cycling settings
else if (name == "cycle_interval") {
unsigned long interval = value.toInt() * 1000UL;
configStorage.setCycleInterval(interval);
}
else if (name == "image_update_mode") {
int mode = value.toInt();
configStorage.setImageUpdateMode(mode);
LOG_INFO_F("[WebAPI] Image update mode changed to: %s\n", mode == 0 ? "Automatic Cycling" : "API-Triggered Refresh");
}
else if (name == "default_image_duration") {
unsigned long duration = value.toInt();
configStorage.setDefaultImageDuration(duration);
}
// Advanced settings
else if (name == "update_interval") {
unsigned long newInterval = value.toInt() * 60UL * 1000UL;
configStorage.setUpdateInterval(newInterval);
}
else if (name == "mqtt_reconnect_interval") configStorage.setMQTTReconnectInterval(value.toInt() * 1000);
else if (name == "watchdog_timeout") configStorage.setWatchdogTimeout(value.toInt() * 1000);
else if (name == "critical_heap_threshold") configStorage.setCriticalHeapThreshold(value.toInt());
else if (name == "critical_psram_threshold") configStorage.setCriticalPSRAMThreshold(value.toInt());
// Display hardware settings
else if (name == "display_type") {
int newDisplayType = value.toInt();
int currentDisplayType = configStorage.getDisplayType();
if (newDisplayType != currentDisplayType) {
LOG_INFO_F("[WebAPI] Display type changed: %d -> %d (restart required)\n", currentDisplayType, newDisplayType);
configStorage.setDisplayType(newDisplayType);
displayTypeChanged = true; // Flag for restart prompt
}
}
// Home Assistant REST Control settings
else if (name == "ha_base_url") configStorage.setHABaseUrl(value);
else if (name == "ha_access_token") {
// Only update token if not empty (allows saving other settings without re-entering token)
if (!value.isEmpty()) {
LOG_DEBUG("[WebAPI] HA Access Token updated (value hidden for security)");
configStorage.setHAAccessToken(value);
}
}
else if (name == "ha_light_sensor_entity") configStorage.setHALightSensorEntity(value);
else if (name == "light_sensor_min_lux") configStorage.setLightSensorMinLux(value.toFloat());
else if (name == "light_sensor_max_lux") configStorage.setLightSensorMaxLux(value.toFloat());
else if (name == "display_min_brightness") configStorage.setDisplayMinBrightness(value.toInt());
else if (name == "display_max_brightness") configStorage.setDisplayMaxBrightness(value.toInt());
else if (name == "ha_poll_interval") configStorage.setHAPollInterval(value.toInt());
else if (name == "light_sensor_mapping_mode") configStorage.setLightSensorMappingMode(value.toInt()); // Time settings
else if (name == "ntp_server") configStorage.setNTPServer(value);
else if (name == "timezone") configStorage.setTimezone(value);
}
// Handle checkbox parameters - HTML forms only send checked checkbox values
// If a checkbox parameter is not present, it means the checkbox was unchecked
// However, we need to distinguish between a full form submission and a partial update
// (e.g., when JavaScript sends only brightness_auto_mode without other checkboxes)
// Check which checkboxes are explicitly mentioned in the request (checked or with _present suffix)
bool hasCyclingEnabled = server->hasArg("cycling_enabled") || server->hasArg("cycling_enabled_present");
bool hasRandomOrder = server->hasArg("random_order") || server->hasArg("random_order_present");
bool hasBrightnessAutoMode = server->hasArg("brightness_auto_mode") || server->hasArg("brightness_auto_mode_present");
bool hasHADiscovery = server->hasArg("ha_discovery_enabled") || server->hasArg("ha_discovery_enabled_present");
bool hasNTPEnabled = server->hasArg("ntp_enabled") || server->hasArg("ntp_enabled_present");
bool hasUseHARestControl = server->hasArg("use_ha_rest_control") || server->hasArg("use_ha_rest_control_present");
// Process brightness mode changes first to handle mutual exclusion properly
if (hasBrightnessAutoMode) {
bool enableMQTTBrightness = server->hasArg("brightness_auto_mode");
configStorage.setBrightnessAutoMode(enableMQTTBrightness);
if (enableMQTTBrightness) {
LOG_INFO("[WebAPI] MQTT brightness control enabled - auto-disabling HA REST Control");
configStorage.setUseHARestControl(false);
}
}
// Logic: If enabling HA REST control, automatically disable MQTT auto mode to prevent conflicts
if (hasUseHARestControl) {
bool enableHARestControl = server->hasArg("use_ha_rest_control");
configStorage.setUseHARestControl(enableHARestControl);
if (enableHARestControl) {
LOG_INFO("[WebAPI] HA REST Control enabled - auto-disabling MQTT brightness control");
configStorage.setBrightnessAutoMode(false);
}
}
// Only update checkboxes that are explicitly present in this request
bool wasCycling = configStorage.getCyclingEnabled();
bool nowCycling = wasCycling; // Default to current value
bool modeChanged = false;
if (hasCyclingEnabled) {
nowCycling = server->hasArg("cycling_enabled");
modeChanged = (wasCycling != nowCycling);
if (modeChanged) {
LOG_INFO_F("[WebAPI] Cycling mode changed: %s -> %s\n",
wasCycling ? "enabled" : "disabled",
nowCycling ? "enabled" : "disabled");
}
configStorage.setCyclingEnabled(nowCycling);
}
if (hasRandomOrder) {
configStorage.setRandomOrder(server->hasArg("random_order"));
}
if (hasHADiscovery) {
configStorage.setHADiscoveryEnabled(server->hasArg("ha_discovery_enabled"));
}
if (hasNTPEnabled) {
configStorage.setNTPEnabled(server->hasArg("ntp_enabled"));
}
// Save configuration to persistent storage
configStorage.saveConfig();
// Re-sync time if NTP settings changed
if (server->hasArg("ntp_server") || server->hasArg("timezone") || server->hasArg("ntp_enabled")) {
extern WiFiManager wifiManager;
wifiManager.syncNTPTime();
}
// Reload configuration in the running system
reloadConfiguration();
// Apply immediate changes
if (brightnessChanged && newBrightness >= 0) {
displayManager.setBrightness(newBrightness);
}
if (imageSettingsChanged) {
applyImageSettings();
}
// Handle display type change - requires restart
if (displayTypeChanged) {
LOG_WARNING("[WebAPI] Display type changed - restart required for display hardware reinitialization");
needsRestart = true;
}
// Switch images immediately when mode changes
if (modeChanged) {
extern void advanceToNextImage();
extern volatile bool imageDownloadPending;
extern unsigned long lastUpdate;
extern unsigned long lastCycleTime;
extern bool cyclingEnabled;
// Update the global cycling state
cyclingEnabled = nowCycling;
if (nowCycling) {
// Switched to multi-image mode: reset to first image (index 0)
Serial.println("[Mode] Switched to CYCLING mode (multi-image)");
char modeMsg[64];
snprintf(modeMsg, sizeof(modeMsg), "Mode: CYCLING (%d images)", configStorage.getImageSourceCount());
displayManager.debugPrint(modeMsg, COLOR_CYAN);
configStorage.setCurrentImageIndex(0);
configStorage.saveConfig();
lastCycleTime = millis();
} else {
// Switched to single-image mode: load the single image URL
Serial.println("[Mode] Switched to SINGLE IMAGE mode");
displayManager.debugPrint("Mode: SINGLE IMAGE", COLOR_CYAN);
}
// Queue async image download
lastUpdate = 0;
imageDownloadPending = true;
}
// Consolidate restart requirement
if (displayTypeChanged) {
needsRestart = true;
}
// Prepare response message
String message = "Configuration saved successfully";
if (needsRestart) message += " (restart required for changes to take effect)";
if (brightnessChanged) message += " - brightness applied immediately";
if (imageSettingsChanged) message += " - image settings applied immediately";
LOG_INFO_F("[WebAPI] Configuration save completed: %s\n", message.c_str());
String response = "{\"status\":\"success\",\"message\":\"" + message + "\",\"needsRestart\":" + (needsRestart ? "true" : "false") + "}";
sendResponse(200, "application/json", response);
}
void WebConfig::handleRestart() {
LOG_WARNING("[WebAPI] Device restart requested via web interface");
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Device restarting now...\"}");
displayManager.debugPrint("Device restart requested...", COLOR_YELLOW);
delay(500);
crashLogger.saveBeforeReboot();
ESP.restart();
}
void WebConfig::handleAddImageSource() {
if (server->hasArg("url")) {
String url = server->arg("url");
if (url.length() > 0) {
LOG_INFO_F("[WebAPI] Adding image source: %s\n", url.c_str());
configStorage.addImageSource(url);
configStorage.saveConfig();
LOG_INFO_F("[WebAPI] Image source added successfully (total: %d)\n", configStorage.getImageSourceCount());
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Image source added successfully\"}");
} else {
LOG_WARNING("[WebAPI] Attempted to add empty image source URL");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid URL\"}");
}
} else {
LOG_WARNING("[WebAPI] Add image source called without URL parameter");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"URL parameter required\"}");
}
}
void WebConfig::handleRemoveImageSource() {
if (server->hasArg("index")) {
int index = server->arg("index").toInt();
LOG_INFO_F("[WebAPI] Remove image source request - index=%d\n", index);
if (configStorage.removeImageSource(index)) {
configStorage.saveConfig();
LOG_INFO_F("[WebAPI] Image source removed successfully (remaining: %d)\n", configStorage.getImageSourceCount());
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Image source removed successfully\"}");
} else {
LOG_WARNING_F("[WebAPI] Failed to remove image source at index %d (invalid or last source)\n", index);
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Failed to remove source: invalid index or last source\"}");
}
} else {
LOG_WARNING("[WebAPI] Remove image source called without index parameter");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index parameter required\"}");
}
}
void WebConfig::handleUpdateImageSource() {
if (server->hasArg("index") && server->hasArg("url")) {
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
String url = server->arg("url");
LOG_INFO_F("[WebAPI] Updating image source %d to: %s\n", index, url.c_str());
configStorage.setImageSource(index, url);
configStorage.saveConfig();
LOG_DEBUG_F("[WebAPI] Image source %d updated successfully\n", index);
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Image source updated successfully\"}");
} else {
LOG_WARNING("[WebAPI] Update image source called with missing parameters");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index and URL parameters required\"}");
}
}
void WebConfig::handleClearImageSources() {
configStorage.clearImageSources();
configStorage.addImageSource(configStorage.getImageURL());
configStorage.saveConfig();
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"All image sources cleared, reset to single default source\"}");
}
void WebConfig::handleBulkDeleteImageSources() {
if (!server->hasArg("indices")) {
LOG_WARNING("[WebAPI] Bulk delete called without indices parameter");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Indices parameter required\"}");
return;
}
String indicesJson = server->arg("indices");
LOG_INFO_F("[WebAPI] Bulk delete request - indices=%s\n", indicesJson.c_str());
// Parse JSON array manually (simple parsing for array of numbers)
indicesJson.trim();
if (!indicesJson.startsWith("[") || !indicesJson.endsWith("]")) {
LOG_WARNING("[WebAPI] Invalid JSON format for indices");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid indices format\"}");
return;
}
// Extract indices and sort in reverse order (delete from end to preserve indices)
int indices[MAX_IMAGE_SOURCES];
int count = 0;
indicesJson = indicesJson.substring(1, indicesJson.length() - 1); // Remove brackets
int startPos = 0;
while (startPos < indicesJson.length() && count < MAX_IMAGE_SOURCES) {
int commaPos = indicesJson.indexOf(',', startPos);
String numStr;
if (commaPos == -1) {
numStr = indicesJson.substring(startPos);
numStr.trim();
if (numStr.length() > 0) {
indices[count++] = numStr.toInt();
}
break;
} else {
numStr = indicesJson.substring(startPos, commaPos);
numStr.trim();
if (numStr.length() > 0) {
indices[count++] = numStr.toInt();
}
startPos = commaPos + 1;
}
}
if (count == 0) {
LOG_WARNING("[WebAPI] No valid indices parsed");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"No valid indices provided\"}");
return;
}
// Check if trying to delete all sources
if (count >= configStorage.getImageSourceCount()) {
LOG_WARNING("[WebAPI] Attempted to delete all sources");
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Cannot delete all sources. At least one must remain.\"}");
return;
}
// Sort indices in descending order to delete from end
for (int i = 0; i < count - 1; i++) {
for (int j = i + 1; j < count; j++) {
if (indices[i] < indices[j]) {
int temp = indices[i];
indices[i] = indices[j];
indices[j] = temp;
}
}
}
// Delete each source
int successCount = 0;
for (int i = 0; i < count; i++) {
if (configStorage.removeImageSource(indices[i])) {
successCount++;
LOG_DEBUG_F("[WebAPI] Deleted source at index %d\n", indices[i]);
} else {
LOG_WARNING_F("[WebAPI] Failed to delete source at index %d\n", indices[i]);
}
}
if (successCount > 0) {
configStorage.saveConfig();
String message = String("{\"status\":\"success\",\"message\":\"Successfully deleted ") +
String(successCount) + String(" of ") + String(count) + String(" source(s)\",\"deleted\":") +
String(successCount) + String(",\"remaining\":") +
String(configStorage.getImageSourceCount()) + String("}");
LOG_INFO_F("[WebAPI] Bulk delete completed - %d sources deleted, %d remaining\n",
successCount, configStorage.getImageSourceCount());
sendResponse(200, "application/json", message);
} else {
LOG_ERROR("[WebAPI] Bulk delete failed - no sources were deleted");
sendResponse(500, "application/json", "{\"status\":\"error\",\"message\":\"Failed to delete any sources\"}");
}
}
void WebConfig::handleNextImage() {
extern void advanceToNextImage();
extern void updateCyclingVariables();
extern volatile bool imageDownloadPending;
extern unsigned long lastUpdate;
extern unsigned long lastCycleTime;
LOG_INFO("[WebAPI] Next image requested via web interface");
updateCyclingVariables();
advanceToNextImage();
lastCycleTime = millis(); // Reset cycle timer for fresh interval
lastUpdate = 0; // Force immediate image download
imageDownloadPending = true;
LOG_DEBUG("[WebAPI] Image advance queued");
sendResponse(200, "application/json", "{\"status\":\"queued\",\"message\":\"Image download queued\"}");
}
void WebConfig::handleForceRefresh() {
extern volatile bool imageDownloadPending;
extern unsigned long lastUpdate;
LOG_INFO("[WebAPI] Force refresh requested via web interface - redownloading current image");
lastUpdate = 0; // Force immediate image download
imageDownloadPending = true;
LOG_DEBUG("[WebAPI] Image refresh queued");
sendResponse(200, "application/json", "{\"status\":\"queued\",\"message\":\"Image download queued\"}");
}
void WebConfig::handleUpdateImageTransform() {
if (server->hasArg("index") && server->hasArg("property") && server->hasArg("value")) {
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
String property = server->arg("property");
String value = server->arg("value");
// Pause cycling when user is actively editing transforms
extern bool cyclingPausedForEditing;
extern unsigned long lastEditActivity;
cyclingPausedForEditing = true;
lastEditActivity = millis();
LOG_DEBUG_F("[WebAPI] Transform update: image %d, %s = %s\n", index, property.c_str(), value.c_str());
bool success = true;
String message = "Transform updated successfully";
if (property == "scaleX") configStorage.setImageScaleX(index, value.toFloat());
else if (property == "scaleY") configStorage.setImageScaleY(index, value.toFloat());
else if (property == "offsetX") configStorage.setImageOffsetX(index, value.toInt());
else if (property == "offsetY") configStorage.setImageOffsetY(index, value.toInt());
else if (property == "rotation") configStorage.setImageRotation(index, value.toFloat());
else {
success = false;
message = "Invalid property name";
}
if (success) {
configStorage.saveConfig();
if (index == configStorage.getCurrentImageIndex()) {
extern float scaleX, scaleY;
extern int16_t offsetX, offsetY;
extern float rotationAngle;
extern void renderFullImage();
if (property == "scaleX") scaleX = configStorage.getImageScaleX(index);
else if (property == "scaleY") scaleY = configStorage.getImageScaleY(index);
else if (property == "offsetX") offsetX = configStorage.getImageOffsetX(index);
else if (property == "offsetY") offsetY = configStorage.getImageOffsetY(index);
else if (property == "rotation") rotationAngle = configStorage.getImageRotation(index);
renderFullImage();
}
}
String response = "{\"status\":\"" + String(success ? "success" : "error") + "\",\"message\":\"" + message + "\"}";
sendResponse(200, "application/json", response);
} else {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Missing parameters\"}");
}
}
void WebConfig::handleCopyDefaultsToImage() {
if (server->hasArg("index")) {
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
configStorage.copyDefaultsToImageTransform(index);
configStorage.saveConfig();
if (index == configStorage.getCurrentImageIndex()) {
extern float scaleX, scaleY;
extern int16_t offsetX, offsetY;
extern float rotationAngle;
extern void renderFullImage();
scaleX = configStorage.getImageScaleX(index);
scaleY = configStorage.getImageScaleY(index);
offsetX = configStorage.getImageOffsetX(index);
offsetY = configStorage.getImageOffsetY(index);
rotationAngle = configStorage.getImageRotation(index);
renderFullImage();
Serial.println("Applied global defaults to current image");
}
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Default settings copied to image\"}");
} else {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index parameter required\"}");
}
}
void WebConfig::handleApplyTransform() {
if (server->hasArg("index")) {
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
// Keep editing session active when applying transforms
extern bool cyclingPausedForEditing;
extern unsigned long lastEditActivity;
cyclingPausedForEditing = true;
lastEditActivity = millis();
int currentIndex = configStorage.getCurrentImageIndex();
if (index != currentIndex) {
configStorage.setCurrentImageIndex(index);
configStorage.saveConfig();
extern volatile bool imageDownloadPending;
imageDownloadPending = true;
} else {
extern float scaleX, scaleY;
extern int16_t offsetX, offsetY;
extern float rotationAngle;
extern void renderFullImage();
scaleX = configStorage.getImageScaleX(index);
scaleY = configStorage.getImageScaleY(index);
offsetX = configStorage.getImageOffsetX(index);
offsetY = configStorage.getImageOffsetY(index);
rotationAngle = configStorage.getImageRotation(index);
renderFullImage();
}
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Transform applied successfully\"}");
} else {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index parameter required\"}");
}
}
void WebConfig::handleToggleImageEnabled() {
if (!server->hasArg("index")) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index parameter required\"}");
return;
}
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
// Toggle the enabled state
bool currentState = configStorage.isImageEnabled(index);
bool newState = !currentState;
int currentImageIndex = configStorage.getCurrentImageIndex();
configStorage.setImageEnabled(index, newState);
configStorage.saveConfig();
LOG_INFO_F("[WebAPI] Image #%d %s\n", index + 1, newState ? "enabled" : "disabled");
LOG_INFO_F("[WebAPI] Current image index: %d, toggling index: %d\n", currentImageIndex, index);
// Handle automatic image switching
bool shouldSwitchImage = false;
if (!newState && index == currentImageIndex) {
// Disabling the currently displayed image - switch to next enabled image
LOG_INFO("[WebAPI] Currently displayed image disabled, switching to next image");
extern void advanceToNextImage();
advanceToNextImage();
shouldSwitchImage = true;
} else if (newState && index != currentImageIndex) {
// Enabling a different image - switch to it immediately
LOG_INFO_F("[WebAPI] Switching to newly enabled image #%d\n", index + 1);
LOG_INFO_F("[WebAPI] Setting current index from %d to %d\n", currentImageIndex, index);
configStorage.setCurrentImageIndex(index);
configStorage.saveConfig();
// Update the global currentImageIndex variable used by getCurrentImageURL()
extern int currentImageIndex;
currentImageIndex = index;
extern void updateCurrentImageTransformSettings();
updateCurrentImageTransformSettings();
shouldSwitchImage = true;
LOG_INFO("[WebAPI] Image switch flag set, will download new image");
}
// Trigger async image download if we switched
if (shouldSwitchImage) {
LOG_INFO("[WebAPI] Queuing image download for switched image");
extern volatile bool imageDownloadPending;
imageDownloadPending = true;
}
String response = "{\"status\":\"success\",\"enabled\":" + String(newState ? "true" : "false") +
",\"switched\":" + String(shouldSwitchImage ? "true" : "false") + "}";
sendResponse(200, "application/json", response);
}
void WebConfig::handleSelectImage() {
if (!server->hasArg("index")) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Index parameter required\"}");
return;
}
int index = server->arg("index").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
LOG_INFO_F("[WebAPI] Selecting image #%d for editing\n", index + 1);
// Pause automatic cycling when user selects an image for editing
extern bool cyclingPausedForEditing;
extern unsigned long lastEditActivity;
cyclingPausedForEditing = true;
lastEditActivity = millis();
LOG_INFO("[WebAPI] Cycling paused for editing (will resume after 30s of inactivity)");
// Update both the global and config storage index
configStorage.setCurrentImageIndex(index);
configStorage.saveConfig();
extern int currentImageIndex;
currentImageIndex = index;
// Update transform settings and switch to this image
extern void updateCurrentImageTransformSettings();
updateCurrentImageTransformSettings();
extern volatile bool imageDownloadPending;
imageDownloadPending = true;
sendResponse(200, "application/json", "{\"status\":\"success\",\"index\":" + String(index) + "}");
}
void WebConfig::handleClearEditingState() {
LOG_INFO("[WebAPI] Clearing editing state - resuming auto-cycling");
// Clear the editing pause flag
extern bool cyclingPausedForEditing;
cyclingPausedForEditing = false;
sendResponse(200, "application/json", "{\"status\":\"success\"}");
}
void WebConfig::handleUpdateImageDuration() {
if (!server->hasArg("index") || !server->hasArg("duration")) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Missing parameters\"}");
return;
}
int index = server->arg("index").toInt();
unsigned long duration = server->arg("duration").toInt();
if (index < 0 || index >= configStorage.getImageSourceCount()) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid index\"}");
return;
}
if (duration < 5 || duration > 3600) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Duration must be between 5 and 3600 seconds\"}");
return;
}
LOG_INFO_F("[WebAPI] Updating image #%d duration to %lu seconds\n", index + 1, duration);
configStorage.setImageDuration(index, duration);
configStorage.saveConfig();
sendResponse(200, "application/json", "{\"status\":\"success\"}");
}
void WebConfig::handleFactoryReset() {
LOG_WARNING("[WebAPI] Factory reset requested via web interface");
configStorage.resetToDefaults();
// Clear WiFi credentials and provisioning flag to trigger captive portal on next boot
configStorage.setWiFiSSID("");
configStorage.setWiFiPassword("");
configStorage.setWiFiProvisioned(false);
configStorage.saveConfig();
LOG_WARNING("[WebAPI] Factory reset completed - WiFi setup will run on next boot");
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Factory reset completed. WiFi setup will run on next boot. Device restarting...\"}");
displayManager.debugPrint("Factory reset in progress...", COLOR_YELLOW);
displayManager.debugPrint("WiFi setup portal will run on restart", COLOR_CYAN);
delay(500);
crashLogger.saveBeforeReboot();
ESP.restart();
}
void WebConfig::handleSetLogSeverity() {
if (!server->hasArg("severity")) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Missing severity parameter\"}");
return;
}
int severity = server->arg("severity").toInt();
// Validate severity range (0=DEBUG, 1=INFO, 2=WARNING, 3=ERROR, 4=CRITICAL)
if (severity < 0 || severity > 4) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Invalid severity level. Must be 0-4\"}");
return;
}
// Update configuration
configStorage.setMinLogSeverity(severity);
configStorage.saveConfig();
const char* severityNames[] = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"};
LOG_INFO_F("[WebAPI] Log severity filter changed to: %s (%d)\n", severityNames[severity], severity);
String json = "{";
json += "\"status\":\"success\",";
json += "\"message\":\"Log severity filter updated to " + String(severityNames[severity]) + "\",";
json += "\"severity\":" + String(severity);
json += "}";
sendResponse(200, "application/json", json);
}
void WebConfig::handleClearCrashLogs() {
// Clear crash logs from device memory
crashLogger.clearAll();
String json = "{";
json += "\"status\":\"success\",";
json += "\"message\":\"Crash logs cleared from RTC and NVS storage\"";
json += "}";
sendResponse(200, "application/json", json);
LOG_INFO("[WebConfig] Crash logs cleared by user request");
}
void WebConfig::applyImageSettings() {
extern float scaleX, scaleY;
extern int16_t offsetX, offsetY;
extern float rotationAngle;
extern void renderFullImage();
scaleX = configStorage.getDefaultScaleX();
scaleY = configStorage.getDefaultScaleY();
offsetX = configStorage.getDefaultOffsetX();
offsetY = configStorage.getDefaultOffsetY();
rotationAngle = configStorage.getDefaultRotation();
renderFullImage();
}
void WebConfig::reloadConfiguration() {
extern void updateCyclingVariables();
LOG_INFO("[WebAPI] Reloading configuration from web interface");
updateCyclingVariables();
extern unsigned long currentUpdateInterval;
extern unsigned long currentCycleInterval;
extern bool cyclingEnabled;
extern bool randomOrderEnabled;
extern int imageSourceCount;
currentUpdateInterval = configStorage.getUpdateInterval();
currentCycleInterval = configStorage.getCycleInterval();
cyclingEnabled = configStorage.getCyclingEnabled();
randomOrderEnabled = configStorage.getRandomOrder();
imageSourceCount = configStorage.getImageSourceCount();
}
void WebConfig::handleGetAllInfo() {
size_t heapBefore = ESP.getFreeHeap();
LOG_DEBUG_F("[WebAPI] /api/info request (heap before: %d bytes)\n", heapBefore);
// Comprehensive device information API endpoint
String json;
json.reserve(8000); // Pre-allocate ~8KB for large JSON response to prevent fragmentation
json = "{";
// Firmware information
json += "\"firmware\":{";
json += "\"sketch_size\":" + String(ESP.getSketchSize()) + ",";
json += "\"free_sketch_space\":" + String(ESP.getFreeSketchSpace()) + ",";
json += "\"sketch_md5\":\"" + String(ESP.getSketchMD5()) + "\"";
json += "},";
// System information
json += "\"system\":{";
json += "\"device_name\":\"" + escapeJson(configStorage.getDeviceName()) + "\",";
json += "\"uptime\":" + String(millis()) + ",";
json += "\"uptime_seconds\":" + String(millis() / 1000) + ",";
json += "\"free_heap\":" + String(systemMonitor.getCurrentFreeHeap()) + ",";
json += "\"total_heap\":" + String(ESP.getHeapSize()) + ",";
json += "\"min_free_heap\":" + String(systemMonitor.getMinFreeHeap()) + ",";
json += "\"free_psram\":" + String(systemMonitor.getCurrentFreePsram()) + ",";
json += "\"total_psram\":" + String(ESP.getPsramSize()) + ",";
json += "\"min_free_psram\":" + String(systemMonitor.getMinFreePsram()) + ",";
json += "\"flash_size\":" + String(ESP.getFlashChipSize()) + ",";
json += "\"flash_speed\":" + String(ESP.getFlashChipSpeed()) + ",";
json += "\"chip_model\":\"" + String(ESP.getChipModel()) + "\",";
json += "\"chip_revision\":" + String(ESP.getChipRevision()) + ",";
json += "\"chip_cores\":" + String(ESP.getChipCores()) + ",";
json += "\"cpu_freq\":" + String(ESP.getCpuFreqMHz()) + ",";
json += "\"sdk_version\":\"" + String(ESP.getSdkVersion()) + "\",";
json += "\"temperature_celsius\":" + String(temperatureRead(), 1) + ",";
json += "\"temperature_fahrenheit\":" + String(temperatureRead() * 9.0 / 5.0 + 32.0, 1) + ",";
json += "\"healthy\":" + String(systemMonitor.isSystemHealthy() ? "true" : "false");
json += "},";
// Network information
json += "\"network\":{";
json += "\"connected\":" + String(wifiManager.isConnected() ? "true" : "false") + ",";
if (wifiManager.isConnected()) {
json += "\"ssid\":\"" + escapeJson(String(WiFi.SSID())) + "\",";
json += "\"ip\":\"" + WiFi.localIP().toString() + "\",";
json += "\"gateway\":\"" + WiFi.gatewayIP().toString() + "\",";
json += "\"dns\":\"" + WiFi.dnsIP().toString() + "\",";
json += "\"mac\":\"" + WiFi.macAddress() + "\",";
json += "\"rssi\":" + String(WiFi.RSSI()) + ",";
json += "\"bssid\":\"" + WiFi.BSSIDstr() + "\",";
json += "\"hostname\":\"" + String(WiFi.getHostname()) + "\"";
} else {
json += "\"ssid\":null,";
json += "\"ip\":null,";
json += "\"gateway\":null,";
json += "\"dns\":null,";
json += "\"mac\":\"" + WiFi.macAddress() + "\",";
json += "\"rssi\":0,";
json += "\"bssid\":null,";
json += "\"hostname\":null";
}
json += "},";
// MQTT information
json += "\"mqtt\":{";
json += "\"connected\":" + String(mqttManager.isConnected() ? "true" : "false") + ",";
json += "\"server\":\"" + escapeJson(configStorage.getMQTTServer()) + "\",";
json += "\"port\":" + String(configStorage.getMQTTPort()) + ",";
json += "\"client_id\":\"" + escapeJson(configStorage.getMQTTClientID()) + "\",";
json += "\"username\":\"" + escapeJson(configStorage.getMQTTUser()) + "\"";
json += "},";
// Home Assistant Discovery information
json += "\"home_assistant\":{";
json += "\"discovery_enabled\":" + String(configStorage.getHADiscoveryEnabled() ? "true" : "false") + ",";
json += "\"device_name\":\"" + escapeJson(configStorage.getHADeviceName()) + "\",";
json += "\"discovery_prefix\":\"" + escapeJson(configStorage.getHADiscoveryPrefix()) + "\",";
json += "\"state_topic\":\"" + escapeJson(configStorage.getHAStateTopic()) + "\",";
json += "\"sensor_update_interval\":" + String(configStorage.getHASensorUpdateInterval());
json += "},";
// Display information
json += "\"display\":{";
json += "\"width\":" + String(displayManager.getWidth()) + ",";
json += "\"height\":" + String(displayManager.getHeight()) + ",";
json += "\"brightness\":" + String(displayManager.getBrightness()) + ",";
json += "\"brightness_auto_mode\":" + String(configStorage.getBrightnessAutoMode() ? "true" : "false") + ",";
json += "\"use_ha_rest_control\":" + String(configStorage.getUseHARestControl() ? "true" : "false") + ",";
json += "\"backlight_freq\":" + String(configStorage.getBacklightFreq()) + ",";
json += "\"backlight_resolution\":" + String(configStorage.getBacklightResolution());
json += "},";
// Image configuration
json += "\"image\":{";
json += "\"cycling_enabled\":" + String(configStorage.getCyclingEnabled() ? "true" : "false") + ",";
json += "\"update_interval\":" + String(configStorage.getUpdateInterval()) + ",";
json += "\"current_url\":\"" + escapeJson(configStorage.getCurrentImageURL()) + "\",";