-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathotaUpdate.cpp
More file actions
737 lines (664 loc) · 27.3 KB
/
Copy pathotaUpdate.cpp
File metadata and controls
737 lines (664 loc) · 27.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
#include "otaUpdate.h"
#include <ArduinoJson.h>
#include <ArduinoOTA.h>
#include <ESPmDNS.h>
#include <SPIFFS.h> // filesystem usage in /api/status
#include <Update.h>
#include <WebServer.h>
#include <WiFi.h>
#include <soc/soc_caps.h> // SOC_TEMP_SENSOR_SUPPORTED
#include "ClockLogic.h" // tft, backlightLevel, SHOW_24HOUR, ...
#include "clockFaces.h" // FACE_COUNT, clockFaceName
#include "genericBaseProject.h" // BACKLIGHT_PIN, NTP sync counters
#include "holidayService.h" // holidayZonesLoaded - /api/status
#include "marketHolidays.h" // marketHolidaysFetchedInfo - /api/status
#include "uiPages.h" // TZ_PRESETS, applyZoneSelection, resetReasonText
#include "weatherService.h" // weatherAgeMinutes
#include "wifiWatch.h" // outage history - /api/status
// OTA_PASSWORD (optional) lives in the untracked secrets.h.
#if __has_include("secrets.h")
#include "secrets.h"
#endif
volatile bool otaInProgress = false;
static WebServer webServer(80);
static int otaLastPct = -1;
// Web-upload state, valid between UPLOAD_FILE_START and the completion handler
static bool webUploadAuthorized = false;
static size_t webUpdateExpectedSize = 0;
static bool webUpdateOk = false;
static String webUpdateError;
/*-------- Shared TFT progress screen ----------*/
static void drawOtaScreen(const String &line, uint16_t color)
{
tft.fillScreen(TFT_BLACK);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(color, TFT_BLACK);
tft.drawString(line, 160, 100);
}
static void drawOtaProgressFrame()
{
otaLastPct = -1;
tft.drawRect(58, 120, 204, 18, TFT_WHITE);
}
static void drawOtaProgressPct(int pct)
{
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
if (pct == otaLastPct) return;
otaLastPct = pct;
tft.fillRect(60, 122, pct * 2, 14, TFT_GREEN);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.drawString(String(pct) + " % ", 160, 146);
}
// Failure exit shared by both update paths: show the error, then hand the
// screen back to the clock with a full repaint.
static void otaFailScreen(const String &line)
{
otaInProgress = false;
drawOtaScreen(line, TFT_RED);
delay(2000);
switchToScreen(SCREEN_HOME);
}
/*-------- ArduinoOTA (espota / IDE network port) ----------*/
static void setupArduinoOTA()
{
// Configurable so two clocks on one network don't collide on
// "<hostname>.local" (web settings page; applied on boot).
ArduinoOTA.setHostname(projectConfig.hostname.c_str());
#ifdef OTA_PASSWORD
if (strlen(OTA_PASSWORD) > 0)
{
ArduinoOTA.setPassword(OTA_PASSWORD);
}
#endif
ArduinoOTA.onStart([]() {
otaInProgress = true;
drawOtaScreen(ArduinoOTA.getCommand() == U_FLASH
? "OTA update: receiving firmware..."
: "OTA update: receiving filesystem...",
TFT_CYAN);
drawOtaProgressFrame();
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
drawOtaProgressPct(total > 0 ? (int)((progress * 100ULL) / total) : 0);
});
ArduinoOTA.onEnd([]() {
drawOtaScreen("OTA update complete - rebooting...", TFT_GREEN);
});
ArduinoOTA.onError([](ota_error_t error) {
const char *msg = error == OTA_AUTH_ERROR ? "auth failed"
: error == OTA_BEGIN_ERROR ? "begin failed"
: error == OTA_CONNECT_ERROR ? "connect failed"
: error == OTA_RECEIVE_ERROR ? "receive failed"
: "end failed";
Log.println(String("OTA error: ") + msg);
otaFailScreen(String("OTA update failed (") + msg + ")");
});
ArduinoOTA.begin();
}
/*-------- Web updater (browser firmware upload) ----------*/
// Self-contained page: file picker, browser-side progress bar, result text.
// %BUILD% is replaced with the compile timestamp when served.
static const char UPDATE_PAGE[] PROGMEM = R"rawliteral(<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>World Clock firmware update</title>
<style>
body{font-family:system-ui,sans-serif;background:#111;color:#eee;display:flex;justify-content:center;padding:2rem}
.card{max-width:26rem;width:100%;background:#1c1c1c;border:1px solid #333;border-radius:10px;padding:1.5rem}
h1{font-size:1.2rem;margin:0 0 .3rem}
p{color:#aaa;font-size:.85rem;margin:.4rem 0}
code{color:#ccc}
input[type=file]{width:100%;margin:.8rem 0;color:#ccc}
button{width:100%;padding:.6rem;border:0;border-radius:6px;background:#0a84ff;color:#fff;font-size:1rem;cursor:pointer}
button:disabled{background:#444;cursor:default}
#bar{height:10px;background:#333;border-radius:5px;overflow:hidden;margin:1rem 0 .4rem;display:none}
#fill{height:100%;width:0;background:#30d158;transition:width .15s}
#msg{font-size:.9rem;min-height:1.2em}
.err{color:#ff6961}.ok{color:#30d158}
</style></head><body><div class="card">
<h1>ESP32 World Clock</h1>
<p>Running build: %BUILD% · <a href="/" style="color:#0a84ff">Settings</a></p>
<p>Select a firmware image (<code>firmware.bin</code> from PlatformIO's
<code>.pio/build/cyd/</code>, or Arduino IDE > Sketch > Export Compiled
Binary) and press Update. Keep the device powered until it reboots.</p>
<form id="f">
<input type="file" id="file" accept=".bin" required>
<button id="btn" type="submit">Update firmware</button>
</form>
<div id="bar"><div id="fill"></div></div>
<div id="msg"></div>
</div>
<script>
var f=document.getElementById('f'),file=document.getElementById('file'),
btn=document.getElementById('btn'),bar=document.getElementById('bar'),
fill=document.getElementById('fill'),msg=document.getElementById('msg');
f.addEventListener('submit',function(e){e.preventDefault();
var fw=file.files[0];if(!fw)return;
btn.disabled=true;bar.style.display='block';fill.style.width='0';
msg.textContent='Uploading...';msg.className='';
var x=new XMLHttpRequest();
x.open('POST','/update?size='+fw.size);
x.upload.onprogress=function(ev){if(ev.lengthComputable)
fill.style.width=Math.round(ev.loaded*100/ev.total)+'%';};
x.onload=function(){if(x.status==200){
msg.textContent='Success - the clock is rebooting; give it ~20 seconds.';
msg.className='ok';}else{
msg.textContent='Update failed: '+x.responseText;
msg.className='err';btn.disabled=false;}};
x.onerror=function(){msg.textContent='Connection lost.';btn.disabled=false;};
var d=new FormData();d.append('firmware',fw);x.send(d);});
</script></body></html>
)rawliteral";
// True if the request may proceed; otherwise a 401 challenge has been sent.
static bool webAuthenticate()
{
#ifdef OTA_PASSWORD
if (strlen(OTA_PASSWORD) > 0 && !webServer.authenticate("admin", OTA_PASSWORD))
{
webServer.requestAuthentication();
return false;
}
#endif
return true;
}
static void handleUpdatePage()
{
if (!webAuthenticate()) return;
String page = FPSTR(UPDATE_PAGE);
page.replace("%BUILD%", String(__DATE__) + " " + __TIME__);
webServer.send(200, "text/html", page);
}
// Streams the multipart upload into the OTA partition chunk by chunk. Runs on
// the main loop core (webServer.handleClient), so drawing on the TFT is safe;
// the clock is intentionally frozen behind the progress screen meanwhile.
static void handleUpdateUpload()
{
HTTPUpload &up = webServer.upload();
if (up.status == UPLOAD_FILE_START)
{
webUploadAuthorized = true;
#ifdef OTA_PASSWORD
if (strlen(OTA_PASSWORD) > 0)
{
webUploadAuthorized = webServer.authenticate("admin", OTA_PASSWORD);
}
#endif
if (!webUploadAuthorized) return;
otaInProgress = true;
webUpdateOk = false;
webUpdateError = "";
// The page passes the exact file size as ?size= so the on-screen
// percentage is accurate (multipart Content-Length would overshoot).
webUpdateExpectedSize = (size_t)webServer.arg("size").toInt();
Log.println("Web update started: " + up.filename);
drawOtaScreen("Web update: receiving firmware...", TFT_CYAN);
drawOtaProgressFrame();
if (!Update.begin(UPDATE_SIZE_UNKNOWN))
{
webUpdateError = Update.errorString();
}
}
else if (up.status == UPLOAD_FILE_WRITE)
{
if (!webUploadAuthorized || webUpdateError.length() > 0) return;
if (Update.write(up.buf, up.currentSize) != up.currentSize)
{
webUpdateError = Update.errorString();
}
else if (webUpdateExpectedSize > 0)
{
drawOtaProgressPct((int)((up.totalSize * 100ULL) / webUpdateExpectedSize));
}
}
else if (up.status == UPLOAD_FILE_END)
{
if (!webUploadAuthorized) return;
if (webUpdateError.length() == 0 && Update.end(true))
{
webUpdateOk = true;
Log.println("Web update received: " + String(up.totalSize) + " bytes");
}
else if (webUpdateError.length() == 0)
{
webUpdateError = Update.errorString();
}
}
else if (up.status == UPLOAD_FILE_ABORTED)
{
Update.abort();
webUpdateError = "upload aborted";
}
}
// Completion handler: runs after the upload callback has seen the whole body.
static void handleUpdateResult()
{
if (!webUploadAuthorized)
{
webServer.requestAuthentication();
return;
}
if (webUpdateOk)
{
webServer.sendHeader("Connection", "close");
webServer.send(200, "text/plain", "OK - rebooting");
drawOtaScreen("Web update complete - rebooting...", TFT_GREEN);
delay(750); // let the response reach the browser
ESP.restart();
}
else
{
String err = webUpdateError.length() > 0 ? webUpdateError : "update failed";
webServer.send(500, "text/plain", err);
Log.println("Web update failed: " + err);
otaFailScreen("Web update failed");
}
}
/*-------- Web settings page ----------*/
// Configure the clock from a browser: the same settings as the on-device
// touch UI (timezones, face, formats, brightness). Served at "/"; changes
// are applied on the main loop core (webServer.handleClient runs there), so
// it can safely reuse the touch UI's apply/persist functions.
static const char SETTINGS_PAGE_HEAD[] PROGMEM = R"rawliteral(<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>World Clock settings</title>
<style>
body{font-family:system-ui,sans-serif;background:#111;color:#eee;display:flex;justify-content:center;padding:2rem}
.card{max-width:26rem;width:100%;background:#1c1c1c;border:1px solid #333;border-radius:10px;padding:1.5rem}
h1{font-size:1.2rem;margin:0 0 .3rem}
p{color:#aaa;font-size:.85rem;margin:.4rem 0}
a{color:#0a84ff}
label{display:block;color:#ccc;font-size:.85rem;margin:.8rem 0 0}
select,input[type=range],input[type=text]{width:100%;margin:.3rem 0 0;padding:.4rem;background:#2a2a2a;color:#eee;border:1px solid #444;border-radius:6px;box-sizing:border-box}
.row{display:flex;gap:.6rem}.row label{flex:1;margin-top:.8rem}
button{width:100%;margin-top:1.2rem;padding:.6rem;border:0;border-radius:6px;background:#0a84ff;color:#fff;font-size:1rem;cursor:pointer}
</style></head><body><div class="card">
<h1>ESP32 World Clock</h1>
)rawliteral";
// One preset-city <select> for a quadrant slot, current selection marked.
static void appendZoneSelect(String &page, const char *label, int slot)
{
page += "<label>" + String(label) + "<select name=\"zone" + String(slot) + "\">";
bool matched = false;
for (int p = 0; p < TZ_PRESET_COUNT; p++)
{
bool sel = worldZones[slot].timezone == TZ_PRESETS[p].tz;
matched |= sel;
page += "<option value=\"" + String(p) + "\"" + (sel ? " selected" : "") + ">" +
TZ_PRESETS[p].name + " (" + TZ_PRESETS[p].tz + ")</option>";
}
if (!matched)
{
// Zone outside the preset list (e.g. hand-edited config): offer to
// keep it; value -1 is ignored by the POST handler.
page += "<option value=\"-1\" selected>keep " + worldZones[slot].name + "</option>";
}
page += "</select></label>";
}
// 0:00 .. 23:00 <option> rows for the night-window hour selects.
static void appendHourOptions(String &page, int selected)
{
for (int h = 0; h < 24; h++)
{
page += "<option value=\"" + String(h) + "\"" +
(h == selected ? " selected" : "") + ">" + String(h) + ":00</option>";
}
}
static void handleSettingsPage()
{
if (!webAuthenticate()) return;
String page;
page.reserve(12288);
page += FPSTR(SETTINGS_PAGE_HEAD);
page += "<p>Running build: " + String(__DATE__) + " " + __TIME__ +
" · <a href=\"/update\">Firmware update</a>"
" · <a href=\"/logs\">Logs</a>"
" · <a href=\"/api/status\">Status JSON</a></p>";
page += "<form method=\"POST\" action=\"/settings\">";
static const char *slotLabels[4] = {"Top-left clock (home)", "Top-right clock",
"Bottom-left clock", "Bottom-right clock"};
for (int i = 0; i < 4; i++)
{
appendZoneSelect(page, slotLabels[i], i);
}
page += "<label>Clock face<select name=\"face\">";
for (int f = 0; f < FACE_COUNT; f++)
{
page += "<option value=\"" + String(f) + "\"" +
(projectConfig.clockFace == f ? " selected" : "") + ">" +
clockFaceName(f) + "</option>";
}
page += "</select></label>";
page += "<label>Clock format<select name=\"clk\">";
page += String("<option value=\"24\"") + (SHOW_24HOUR ? " selected" : "") + ">24 hour</option>";
page += String("<option value=\"12\"") + (!SHOW_24HOUR ? " selected" : "") + ">12 hour (AM/PM)</option>";
page += "</select></label>";
page += "<label>Date format<select name=\"date\">";
page += String("<option value=\"dmy\"") + (NOT_US_DATE ? " selected" : "") + ">DD/MM/YY</option>";
page += String("<option value=\"mdy\"") + (!NOT_US_DATE ? " selected" : "") + ">MM/DD/YY</option>";
page += "</select></label>";
int pct = map(backlightLevel, 5, 255, 0, 100);
page += "<label>Brightness (<span id=\"bv\">" + String(pct) + "</span>%)"
"<input type=\"range\" name=\"bri\" min=\"5\" max=\"255\" value=\"" +
String(backlightLevel) + "\" oninput=\"document.getElementById('bv')"
".textContent=Math.round((this.value-5)*100/250)\"></label>";
// Night dimming: window (home-zone hours) + the dimmed level
page += "<div class=\"row\"><label>Night dim from<select name=\"nstart\">";
appendHourOptions(page, projectConfig.nightStartHour);
page += "</select></label><label>until<select name=\"nend\">";
appendHourOptions(page, projectConfig.nightEndHour);
page += "</select></label></div>";
int npct = map(constrain(projectConfig.nightBrightness, 1, 255), 1, 255, 0, 100);
page += "<label>Night brightness (<span id=\"nv\">" + String(npct) + "</span>%)"
"<input type=\"range\" name=\"nbri\" min=\"1\" max=\"255\" value=\"" +
String(constrain(projectConfig.nightBrightness, 1, 255)) +
"\" oninput=\"document.getElementById('nv')"
".textContent=Math.round((this.value-1)*100/254)\"></label>";
page += "<p>Night brightness is used when the room is dark (light sensor), "
"or inside the window above (home-zone time) when the sensor is "
"unavailable. Equal hours disable the schedule.</p>";
page += "<label>Hostname (mDNS \"<name>.local\", applied after reboot)"
"<input type=\"text\" name=\"host\" maxlength=\"32\" value=\"" +
projectConfig.hostname + "\"></label>";
page += "<button type=\"submit\">Save</button></form>"
"<p>Saving a brightness change pauses auto-brightness for 2 hours, "
"same as the on-device controls.</p>";
// Config backup/restore (/api/config). Restore expects a previously
// downloaded backup; the device saves it and reboots to apply.
page += "<p><a href=\"/api/config\" download=\"worldclock-config.json\">Backup config"
"</a> · restore: <input type=\"file\" id=\"cfg\" accept=\".json\" "
"style=\"width:auto;color:#ccc\"></p>"
"<script>document.getElementById('cfg').addEventListener('change',"
"async function(){if(!this.files[0])return;"
"var r=await fetch('/api/config',{method:'POST',body:await this.files[0].text()});"
"alert(await r.text());});</script>";
page += "</div></body></html>";
webServer.send(200, "text/html", page);
}
static void handleSettingsPost()
{
if (!webAuthenticate()) return;
// Timezone changes first - each one persists the config and re-fetches
// the zone definition (brief blocking network call per changed zone).
for (int i = 0; i < 4; i++)
{
String arg = webServer.arg("zone" + String(i));
if (arg.length() == 0) continue;
int idx = arg.toInt();
if (idx < 0 || idx >= TZ_PRESET_COUNT) continue; // -1 = keep current
if (worldZones[i].timezone == TZ_PRESETS[idx].tz &&
worldZones[i].name == TZ_PRESETS[idx].name) continue;
applyZoneSelection(i, TZ_PRESETS[idx]);
}
// Absent fields keep their current value, so a partial POST (scripted
// curl, say) can't silently flip unrelated settings.
bool wants24 = webServer.hasArg("clk") ? webServer.arg("clk") != "12" : SHOW_24HOUR;
bool wantsDmy = webServer.hasArg("date") ? webServer.arg("date") != "mdy" : NOT_US_DATE;
if (wants24 != SHOW_24HOUR || wantsDmy != NOT_US_DATE)
{
SHOW_24HOUR = wants24;
NOT_US_DATE = wantsDmy;
saveDisplayPrefs();
}
if (webServer.hasArg("face"))
{
int face = webServer.arg("face").toInt();
if (face >= 0 && face < FACE_COUNT && face != projectConfig.clockFace)
{
projectConfig.clockFace = face;
projectConfig.saveConfigFile();
}
}
int bri = webServer.arg("bri").toInt();
if (bri >= 5 && bri <= 255 && bri != backlightLevel)
{
backlightLevel = bri;
analogWrite(BACKLIGHT_PIN, backlightLevel);
manualBrightnessUntil = millis() + MANUAL_BRIGHTNESS_HOLD_MS;
projectConfig.brightness = backlightLevel;
projectConfig.saveConfigFile();
}
// Night dimming + hostname: gathered into a single config save
bool cfgDirty = false;
if (webServer.hasArg("nstart"))
{
int v = constrain(webServer.arg("nstart").toInt(), 0, 23);
if (v != projectConfig.nightStartHour)
{
projectConfig.nightStartHour = v;
cfgDirty = true;
}
}
if (webServer.hasArg("nend"))
{
int v = constrain(webServer.arg("nend").toInt(), 0, 23);
if (v != projectConfig.nightEndHour)
{
projectConfig.nightEndHour = v;
cfgDirty = true;
}
}
if (webServer.hasArg("nbri"))
{
int v = webServer.arg("nbri").toInt();
if (v >= 1 && v <= 255 && v != projectConfig.nightBrightness)
{
projectConfig.nightBrightness = v;
cfgDirty = true;
}
}
if (webServer.hasArg("host"))
{
String h = sanitizeHostname(webServer.arg("host"));
if (h != projectConfig.hostname)
{
projectConfig.hostname = h;
cfgDirty = true;
Log.println("Hostname changed to \"" + h + "\" - applies after the next reboot");
}
}
if (cfgDirty)
{
projectConfig.saveConfigFile();
}
// Repaint the home screen with the new settings, whatever page the
// on-device UI was showing.
switchToScreen(SCREEN_HOME);
Log.println("Settings applied from the web page");
webServer.sendHeader("Location", "/");
webServer.send(303, "text/plain", "Saved");
}
/*-------- Config backup / restore ----------*/
// GET /api/config downloads the settings JSON; POST the same JSON back to
// restore it (clone a second device, or recover after a partition-scheme
// change wipes SPIFFS). The device saves the imported config and reboots so
// zones, hostname and formats all apply through the normal boot path.
static void handleApiConfigGet()
{
if (!webAuthenticate()) return;
webServer.sendHeader("Content-Disposition",
"attachment; filename=\"worldclock-config.json\"");
webServer.send(200, "application/json", projectConfig.toJsonString());
}
static void handleApiConfigPost()
{
if (!webAuthenticate()) return;
String body = webServer.arg("plain");
if (body.length() == 0 || body.length() > 4096)
{
webServer.send(400, "text/plain",
"Expected the config JSON (a /api/config backup) as the request body");
return;
}
if (!projectConfig.applyFromJsonString(body))
{
webServer.send(400, "text/plain",
"Not a valid config JSON - no recognized settings found");
return;
}
projectConfig.saveConfigFile();
Log.println("Config imported via /api/config - rebooting to apply");
webServer.sendHeader("Connection", "close");
webServer.send(200, "text/plain", "OK - config saved, rebooting to apply it");
delay(750); // let the response reach the client
ESP.restart();
}
// Diagnostics as JSON - the System status page, but scriptable.
static void handleApiStatus()
{
if (!webAuthenticate()) return;
DynamicJsonDocument doc(3072);
doc["hostname"] = projectConfig.hostname;
doc["ip"] = WiFi.localIP().toString();
doc["ssid"] = WiFi.SSID();
doc["rssiDbm"] = WiFi.RSSI();
doc["mac"] = WiFi.macAddress();
doc["gateway"] = WiFi.gatewayIP().toString();
doc["dns"] = WiFi.dnsIP().toString();
doc["wifiChannel"] = WiFi.channel();
doc["wifiDrops"] = wifiDropCount();
doc["wifiOfflineSec"] = (long)(wifiOfflineDurationMs() / 1000UL);
doc["resetReason"] = resetReasonText();
doc["sdk"] = ESP.getSdkVersion();
doc["spiffsUsedBytes"] = SPIFFS.usedBytes();
doc["spiffsTotalBytes"] = SPIFFS.totalBytes();
doc["chip"] = String(ESP.getChipModel()) + " r" + String(ESP.getChipRevision());
doc["cpuMhz"] = ESP.getCpuFreqMHz();
#if SOC_TEMP_SENSOR_SUPPORTED
doc["cpuTempC"] = temperatureRead();
#endif
doc["flashSizeBytes"] = ESP.getFlashChipSize();
doc["sketchSizeBytes"] = ESP.getSketchSize();
doc["sketchSlotBytes"] = ESP.getSketchSize() + ESP.getFreeSketchSpace();
doc["uptimeSec"] = millis() / 1000UL;
doc["freeHeapBytes"] = ESP.getFreeHeap();
doc["minFreeHeapBytes"] = ESP.getMinFreeHeap();
doc["maxAllocHeapBytes"] = ESP.getMaxAllocHeap();
doc["ntpSyncs"] = syncCount;
doc["lastSyncAgoMin"] = (syncCount > 0)
? (long)((millis() - lastSyncTime) / 60000UL)
: -1;
doc["utc"] = UTC.dateTime("Y-m-d H:i:s");
doc["build"] = String(__DATE__) + " " + __TIME__;
doc["clockFace"] = clockFaceName(projectConfig.clockFace);
doc["brightness"] = backlightLevel;
doc["weatherAgeMin"] = weatherAgeMinutes();
long calAgeDays = -1;
doc["marketHolidaySource"] = marketHolidaysFetchedInfo(calAgeDays) ? "fetched" : "compiled";
if (calAgeDays >= 0)
{
doc["marketHolidayAgeDays"] = calAgeDays;
}
int holidayZonesEligible = 0;
doc["holidayZonesLoaded"] = holidayZonesLoaded(holidayZonesEligible);
doc["holidayZonesEligible"] = holidayZonesEligible;
bool ldrTrusted, ldrDark;
int ldrSmoothed;
if (getLdrState(ldrTrusted, ldrDark, ldrSmoothed))
{
doc["ldrTrusted"] = ldrTrusted;
if (ldrTrusted)
{
doc["ldrRoomDark"] = ldrDark;
}
}
unsigned long nowMs = millis();
doc["manualBrightnessHoldMin"] =
(manualBrightnessUntil > nowMs) ? (long)((manualBrightnessUntil - nowMs) / 60000UL) : 0;
JsonArray zones = doc.createNestedArray("zones");
for (int i = 0; i < 4; i++)
{
JsonObject z = zones.createNestedObject();
z["name"] = worldZones[i].name;
z["tz"] = worldZones[i].timezone;
if (worldZones[i].lastMarketStatus.length() > 0)
{
z["market"] = worldZones[i].lastMarketStatus;
}
}
String out;
serializeJson(doc, out);
webServer.send(200, "application/json", out);
}
/*-------- Log viewer ----------*/
// The tail of the in-RAM log ring (logBuffer.h) in the browser: /api/logs
// returns it as plain text, /logs is a small auto-refreshing viewer.
static const char LOGS_PAGE[] PROGMEM = R"rawliteral(<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>World Clock logs</title>
<style>
body{font-family:ui-monospace,Consolas,monospace;background:#111;color:#ddd;margin:0;padding:1rem}
h1{font-size:1rem;font-family:system-ui,sans-serif;margin:0 .0 .4rem}
a{color:#0a84ff;font-family:system-ui,sans-serif;font-size:.85rem;font-weight:normal}
label{font-family:system-ui,sans-serif;font-size:.8rem;color:#aaa}
pre{white-space:pre-wrap;word-break:break-all;font-size:.78rem;line-height:1.4;margin:.6rem 0 0}
</style></head><body>
<h1>ESP32 World Clock logs · <a href="/">settings</a></h1>
<label><input type="checkbox" id="auto" checked> auto-refresh (2s), timestamps are uptime</label>
<pre id="l">loading...</pre>
<script>
var l=document.getElementById('l'),auto=document.getElementById('auto');
async function load(){
try{
var r=await fetch('/api/logs');
var nearBottom=(window.innerHeight+window.scrollY)>=(document.body.scrollHeight-60);
l.textContent=await r.text();
if(nearBottom)window.scrollTo(0,document.body.scrollHeight);
}catch(e){}
}
load();
setInterval(function(){if(auto.checked)load();},2000);
</script></body></html>
)rawliteral";
static void handleLogsPage()
{
if (!webAuthenticate()) return;
webServer.send(200, "text/html", FPSTR(LOGS_PAGE));
}
static void handleApiLogs()
{
if (!webAuthenticate()) return;
webServer.send(200, "text/plain", logTail(6144));
}
static void setupWebUpdater()
{
webServer.on("/", HTTP_GET, handleSettingsPage);
webServer.on("/settings", HTTP_POST, handleSettingsPost);
webServer.on("/api/status", HTTP_GET, handleApiStatus);
webServer.on("/api/config", HTTP_GET, handleApiConfigGet);
webServer.on("/api/config", HTTP_POST, handleApiConfigPost);
webServer.on("/logs", HTTP_GET, handleLogsPage);
webServer.on("/api/logs", HTTP_GET, handleApiLogs);
webServer.on("/update", HTTP_GET, handleUpdatePage);
webServer.on("/update", HTTP_POST, handleUpdateResult, handleUpdateUpload);
webServer.onNotFound([]() {
webServer.sendHeader("Location", "/");
webServer.send(302, "text/plain", "");
});
webServer.begin();
// ArduinoOTA.begin() already registered the configured hostname on mDNS;
// advertise the web pages on it too.
MDNS.addService("http", "tcp", 80);
}
/*-------- Public entry points ----------*/
void setupOTA()
{
setupArduinoOTA();
setupWebUpdater();
Log.println("OTA updates enabled (hostname: " + projectConfig.hostname +
", espota port 3232)");
Log.println("Web settings + updater: http://" + WiFi.localIP().toString() +
"/ (or http://" + projectConfig.hostname + ".local/)");
}
void handleOTA()
{
ArduinoOTA.handle();
webServer.handleClient();
}