Repository navigation
Expand file tree
/
Copy pathweb_config_api.cpp
More file actions
1591 lines (1359 loc) · 71.2 KB
/
Copy pathweb_config_api.cpp
File metadata and controls
1591 lines (1359 loc) · 71.2 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 "image_presets.h"
#include "config_backup.h"
#include <Update.h>
#include <driver/jpeg_encode.h> // ESP32-P4 hardware JPEG encoder (screenshot endpoint)
// 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::handleAddPreset() {
if (!server->hasArg("id")) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"id parameter required\"}");
return;
}
if (server->arg("id") == "__moon__") {
int newIndex = configStorage.getImageSourceCount();
if (newIndex >= MAX_IMAGE_SOURCES) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Maximum image sources reached\"}");
return;
}
configStorage.addImageSource("moon://default");
// The moon renders at full panel size with the disk scaled inside it, so
// the per-source scale is the disk-fill fraction. Default to 0.8 (80% of
// the panel, leaving a small margin).
float fit = DEFAULT_MOON_DISK_SCALE;
if (fit < MIN_SCALE) fit = MIN_SCALE;
if (fit > MAX_SCALE) fit = MAX_SCALE;
configStorage.setImageScaleX(newIndex, fit);
configStorage.setImageScaleY(newIndex, fit);
configStorage.setImageOffsetX(newIndex, 0);
configStorage.setImageOffsetY(newIndex, 0);
configStorage.setImageRotation(newIndex, 0.0f);
configStorage.saveConfig();
LOG_INFO_F("[WebAPI] Added moon source at index %d (disk scale %.2f)\n", newIndex, fit);
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Moon source added\"}");
return;
}
const ImagePreset* p = findImagePreset(server->arg("id").c_str());
if (!p) {
sendResponse(404, "application/json", "{\"status\":\"error\",\"message\":\"Unknown preset id\"}");
return;
}
int newIndex = configStorage.getImageSourceCount(); // index the new source will occupy
if (newIndex >= MAX_IMAGE_SOURCES) {
sendResponse(400, "application/json", "{\"status\":\"error\",\"message\":\"Maximum image sources reached\"}");
return;
}
configStorage.addImageSource(String(p->url));
// Seed a "fit disc" transform for THIS source only.
// Display is square; pick the active panel size and fit the cropped disc to it.
int displaySize = displayManager.getWidth(); // 800 or 1448 (square panel)
float keptPx = (float)p->nominalPx * (float)p->cropPct / 100.0f;
float fit = (keptPx > 0.0f) ? ((float)displaySize / keptPx) : 1.0f;
if (fit < MIN_SCALE) fit = MIN_SCALE;
if (fit > MAX_SCALE) fit = MAX_SCALE;
configStorage.setImageScaleX(newIndex, fit);
configStorage.setImageScaleY(newIndex, fit);
configStorage.setImageOffsetX(newIndex, 0);
configStorage.setImageOffsetY(newIndex, 0);
configStorage.setImageRotation(newIndex, 0.0f);
configStorage.saveConfig();
LOG_INFO_F("[WebAPI] Added preset %s as source %d (fit scale %.2f)\n", p->id, newIndex, fit);
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Preset added\"}");
}
void WebConfig::handleSetMoon() {
if (server->hasArg("lat")) configStorage.setMoonLat(server->arg("lat").toFloat());
if (server->hasArg("lon")) configStorage.setMoonLon(server->arg("lon").toFloat());
if (server->hasArg("bg")) configStorage.setMoonBgStyle(server->arg("bg").toInt());
if (server->hasArg("flipu")) configStorage.setMoonFlipU((uint8_t)server->arg("flipu").toInt());
if (server->hasArg("flipv")) configStorage.setMoonFlipV((uint8_t)server->arg("flipv").toInt());
if (server->hasArg("roll")) configStorage.setMoonRollOffset(server->arg("roll").toFloat());
if (server->hasArg("yaw")) configStorage.setMoonYawOffset(server->arg("yaw").toFloat());
if (server->hasArg("pitch")) configStorage.setMoonPitchOffset(server->arg("pitch").toFloat());
if (server->hasArg("northup")) configStorage.setMoonNorthUp((uint8_t)server->arg("northup").toInt());
if (server->hasArg("light")) configStorage.setMoonDragLightMode((uint8_t)server->arg("light").toInt());
if (server->hasArg("spin")) configStorage.setMoonSpinMode((uint8_t)server->arg("spin").toInt());
if (server->hasArg("spinret")) configStorage.setMoonSpinReturnS((uint8_t)server->arg("spinret").toInt());
configStorage.saveConfig();
// Apply live: if the computed moon is the image currently on the display,
// re-render it so background / north-up / orientation changes show at once
// rather than waiting for the next refresh cycle. Goes through the normal
// moon pipeline, which re-centers the disk.
extern int currentImageIndex;
int cidx = currentImageIndex;
if (cidx >= 0 && cidx < configStorage.getImageSourceCount() &&
configStorage.getImageSource(cidx).startsWith("moon://")) {
extern volatile bool imageDownloadPending;
imageDownloadPending = true;
}
LOG_INFO_F("[WebAPI] Moon settings saved (lat %.4f lon %.4f bg %d)\n",
configStorage.getMoonLat(), configStorage.getMoonLon(), configStorage.getMoonBgStyle());
sendResponse(200, "application/json", "{\"status\":\"success\",\"message\":\"Moon settings saved\"}");
}
void WebConfig::handleGetMoon() {
char json[256];
snprintf(json, sizeof(json),
"{\"lat\":%.4f,\"lon\":%.4f,\"bg\":%d,"
"\"flipu\":%d,\"flipv\":%d,"
"\"roll\":%.2f,\"yaw\":%.2f,\"pitch\":%.2f,"
"\"northup\":%d,\"light\":%d,\"spin\":%d,\"spinret\":%d}",
configStorage.getMoonLat(), configStorage.getMoonLon(), configStorage.getMoonBgStyle(),
configStorage.getMoonFlipU(), configStorage.getMoonFlipV(),
configStorage.getMoonRollOffset(), configStorage.getMoonYawOffset(), configStorage.getMoonPitchOffset(),
configStorage.getMoonNorthUp(), configStorage.getMoonDragLightMode(),
configStorage.getMoonSpinMode(), configStorage.getMoonSpinReturnS());
sendResponse(200, "application/json", json);
}
// Consolidated state for the client-rendered /config/images app.
// Returns the shape defined in the shared contract: current index, tuning
// state, global defaults, moon config, available presets, and every source.
void WebConfig::handleGetImagesState() {
extern bool cyclingPausedForEditing;
extern int currentImageIndex; // live displayed index; tune does not persist to NVS
String json;
json.reserve(8000); // Pre-allocate to avoid heap fragmentation on large source lists
json = "{";
int currentIndex = currentImageIndex;
json += "\"currentIndex\":" + String(currentIndex) + ",";
// Tuning is active while cycling is paused for live on-device editing.
json += "\"tuning\":{";
json += "\"active\":" + String(cyclingPausedForEditing ? "true" : "false") + ",";
json += "\"index\":" + String(cyclingPausedForEditing ? currentIndex : -1);
json += "},";
json += "\"maxScale\":" + String((float)MAX_SCALE, 4) + ",";
json += "\"updateMode\":" + String(configStorage.getImageUpdateMode()) + ",";
json += "\"defaultDuration\":" + String(configStorage.getDefaultImageDuration()) + ",";
// getUpdateInterval() is in milliseconds; contract wants whole minutes.
json += "\"updateInterval\":" + String((unsigned long)(configStorage.getUpdateInterval() / 1000UL / 60UL)) + ",";
json += "\"randomOrder\":" + String(configStorage.getRandomOrder() ? "true" : "false") + ",";
json += "\"defaults\":{";
json += "\"scaleX\":" + String(configStorage.getDefaultScaleX(), 4) + ",";
json += "\"scaleY\":" + String(configStorage.getDefaultScaleY(), 4) + ",";
json += "\"offsetX\":" + String(configStorage.getDefaultOffsetX()) + ",";
json += "\"offsetY\":" + String(configStorage.getDefaultOffsetY()) + ",";
json += "\"rotation\":" + String((int)configStorage.getDefaultRotation());
json += "},";
json += "\"moon\":{";
json += "\"lat\":" + String(configStorage.getMoonLat(), 4) + ",";
json += "\"lon\":" + String(configStorage.getMoonLon(), 4) + ",";
json += "\"bg\":" + String(configStorage.getMoonBgStyle()) + ",";
json += "\"flipu\":" + String(configStorage.getMoonFlipU()) + ",";
json += "\"flipv\":" + String(configStorage.getMoonFlipV()) + ",";
json += "\"roll\":" + String(configStorage.getMoonRollOffset(), 2) + ",";
json += "\"yaw\":" + String(configStorage.getMoonYawOffset(), 2) + ",";
json += "\"pitch\":" + String(configStorage.getMoonPitchOffset(), 2) + ",";
json += "\"northup\":" + String(configStorage.getMoonNorthUp()) + ",";
json += "\"light\":" + String(configStorage.getMoonDragLightMode()) + ",";
json += "\"spin\":" + String(configStorage.getMoonSpinMode()) + ",";
json += "\"spinret\":" + String(configStorage.getMoonSpinReturnS());
json += "},";
// Static preset catalog (mirrors the shared contract list).
json += "\"presets\":[";
json += "{\"id\":\"sdo_aia_304\",\"label\":\"Sun SDO/AIA 304A\"},";
json += "{\"id\":\"sdo_aia_171\",\"label\":\"Sun SDO/AIA 171A\"},";
json += "{\"id\":\"sdo_aia_193\",\"label\":\"Sun SDO/AIA 193A\"},";
json += "{\"id\":\"sdo_hmi_igr\",\"label\":\"Sun SDO/HMI Continuum\"},";
json += "{\"id\":\"sdo_hmi_mag\",\"label\":\"Sun SDO/HMI Magnetogram\"},";
json += "{\"id\":\"soho_c2\",\"label\":\"Sun SOHO LASCO C2\"},";
json += "{\"id\":\"soho_c3\",\"label\":\"Sun SOHO LASCO C3\"},";
json += "{\"id\":\"goes19_full\",\"label\":\"Earth GOES-19 Full Disc\"},";
json += "{\"id\":\"__moon__\",\"label\":\"Moon (computed)\"}";
json += "],";
json += "\"sources\":[";
int count = configStorage.getImageSourceCount();
for (int i = 0; i < count; i++) {
if (i > 0) json += ",";
String url = configStorage.getImageSource(i);
bool isMoon = url.startsWith("moon://"); // moon:// sentinel = computed moon source
json += "{";
json += "\"index\":" + String(i) + ",";
json += "\"url\":\"" + escapeJson(url) + "\",";
json += "\"enabled\":" + String(configStorage.isImageEnabled(i) ? "true" : "false") + ",";
json += "\"duration\":" + String(configStorage.getImageDuration(i)) + ",";
json += "\"scaleX\":" + String(configStorage.getImageScaleX(i), 4) + ",";
json += "\"scaleY\":" + String(configStorage.getImageScaleY(i), 4) + ",";
json += "\"offsetX\":" + String(configStorage.getImageOffsetX(i)) + ",";
json += "\"offsetY\":" + String(configStorage.getImageOffsetY(i)) + ",";
json += "\"rotation\":" + String((int)configStorage.getImageRotation(i)) + ",";
json += "\"isMoon\":" + String(isMoon ? "true" : "false");
json += "}";
}
json += "]";
json += "}";
sendResponse(200, "application/json", json);
}
// Live-tune a source: switch the LCD to show it and pause cycling for editing.
// Unlike handleSelectImage, this does NOT persist a startup index to NVS; it
// only performs the live switch plus sets the editing-pause flag.
void WebConfig::handleTuneImage() {
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] Tuning image #%d (live preview on device)\n", index + 1);
// Pause cycling for editing (explicit-exit model; backstop only in .ino loop)
extern bool cyclingPausedForEditing;
extern unsigned long lastEditActivity;
cyclingPausedForEditing = true;
lastEditActivity = millis();
// Live-switch the displayed image (same mechanism as handleSelectImage),
// but without persisting a permanent startup index to NVS.
extern int currentImageIndex;
currentImageIndex = index;
extern void updateCurrentImageTransformSettings();
updateCurrentImageTransformSettings();
extern volatile bool imageDownloadPending;
imageDownloadPending = true;
sendResponse(200, "application/json", "{\"status\":\"success\"}");
}
// Exit tune mode: clear the editing-pause flag and resume cycling.
// Mirrors handleClearEditingState exactly.
void WebConfig::handleStopTune() {
LOG_INFO("[WebAPI] Stopping tune - resuming auto-cycling");
extern bool cyclingPausedForEditing;
cyclingPausedForEditing = false;
sendResponse(200, "application/json", "{\"status\":\"success\"}");
}
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");
// Editing a transform persists the value but does NOT by itself pause
// cycling. The live display changes only while the user is actively
// tuning this source on the device (see the guarded render below).
extern bool cyclingPausedForEditing;
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();
// Only disturb the live display when the user is actively tuning
// this exact source on the device. Editing numbers without tuning
// persists the value but leaves the displayed image untouched.
extern int currentImageIndex;
if (cyclingPausedForEditing && index == currentImageIndex) {
// Keep the tune session alive while the user is actively editing.
extern unsigned long lastEditActivity;
lastEditActivity = millis();
extern float scaleX, scaleY;
extern int16_t offsetX, offsetY;
extern float rotationAngle;
extern void renderFullImage();
extern void updateCurrentImageTransformSettings();
extern volatile bool imageDownloadPending;
// The computed moon is rendered at full panel size with its disk
// scale applied inside the renderer; the displayed bitmap is always
// drawn 1:1. So a scale/rotation change must trigger a disk
// re-render (the same pipeline the cycle uses, which re-centers via
// updateCurrentImageTransformSettings) rather than scaling the
// full-panel bitmap here, which pushes the draw origin negative and
// makes the moon grow from a corner instead of the center.
if (configStorage.getImageSource(index).startsWith("moon://")) {
if (property == "offsetX" || property == "offsetY") {
updateCurrentImageTransformSettings(); // moon-aware: scale=1, offsets from NVS
renderFullImage(); // pan the existing moon frame
} else {
imageDownloadPending = true; // re-render the disk at the new scale
}
} else {
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()) {
// For the computed moon, scale is a disk re-render (see
// handleUpdateImageTransform); re-run the moon pipeline so the copied
// scale is applied centered rather than as a full-panel bitmap scale.
if (configStorage.getImageSource(index).startsWith("moon://")) {
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();
}
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 if (configStorage.getImageSource(index).startsWith("moon://")) {
// Moon scale is a disk re-render, not a full-panel bitmap scale.
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");
}