-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuiPages.cpp
More file actions
996 lines (890 loc) · 31.6 KB
/
Copy pathuiPages.cpp
File metadata and controls
996 lines (890 loc) · 31.6 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
#include "uiPages.h"
#include <SPIFFS.h> // filesystem usage row on the status page
#include <WiFi.h>
#include <esp_system.h> // esp_reset_reason - reset reason row
#include <soc/soc_caps.h> // SOC_TEMP_SENSOR_SUPPORTED - CPU temp row
#include "clockFaces.h" // ClockFace enum, clockFaceName
#include "genericBaseProject.h" // BACKLIGHT_PIN, NTP sync state
#include "holidayService.h" // holidaysInvalidate, holidayZonesLoaded
#include "marketHolidays.h" // marketHolidaysFetchedInfo - status page
#include "projectConfig.h"
#include "weatherService.h" // weatherInvalidate
#include "wifiWatch.h" // outage history rows on the status page
UIScreen uiScreen = SCREEN_HOME;
bool uiPageDrawn = false; // false -> render the full page on the next loop
int zoneSlotBeingEdited = 0; // which quadrant the timezone list is editing
int tzListPage = 0; // current page of the timezone list
unsigned long lastStatusRefresh = 0;
// After a screen switch, ignore the touch panel until the finger is lifted so
// a single tap can't "click through" onto the newly drawn page.
bool touchSuppressedUntilRelease = false;
/*-------- Timezone presets ----------*/
// The posix column carries each zone's current POSIX TZ rules (matching the
// tz database's POSIX representation, including DST transitions). They are
// only used as a fallback when the timezone server is unreachable AND no
// cached definition exists, so the clock still shows correct local time on a
// first boot without the server. Update an entry if a region changes its
// DST law (rare).
//
// The country column feeds the public-holiday service (date.nager.at). It is
// "" for Dubai and Mumbai because that API has no AE / IN calendars - those
// zones simply show no holidays.
const TimezonePreset TZ_PRESETS[] = {
{"SANTA CLARA", "America/Los_Angeles", 37.35, -121.95, "PST8PDT,M3.2.0,M11.1.0", "US"},
{"DENVER", "America/Denver", 39.74, -104.99, "MST7MDT,M3.2.0,M11.1.0", "US"},
{"CHICAGO", "America/Chicago", 41.88, -87.63, "CST6CDT,M3.2.0,M11.1.0", "US"},
{"NEW YORK", "America/New_York", 40.71, -74.01, "EST5EDT,M3.2.0,M11.1.0", "US"},
{"SAO PAULO", "America/Sao_Paulo", -23.55, -46.63, "<-03>3", "BR"},
{"LONDON", "Europe/London", 51.51, -0.13, "GMT0BST,M3.5.0/1,M10.5.0", "GB"},
{"PARIS", "Europe/Paris", 48.86, 2.35, "CET-1CEST,M3.5.0,M10.5.0/3", "FR"},
{"BERLIN", "Europe/Berlin", 52.52, 13.41, "CET-1CEST,M3.5.0,M10.5.0/3", "DE"},
{"MOSCOW", "Europe/Moscow", 55.76, 37.62, "MSK-3", "RU"},
{"DUBAI", "Asia/Dubai", 25.20, 55.27, "<+04>-4", ""},
{"MUMBAI", "Asia/Kolkata", 19.08, 72.88, "IST-5:30", ""},
{"SINGAPORE", "Asia/Singapore", 1.35, 103.82, "<+08>-8", "SG"},
{"HONG KONG", "Asia/Hong_Kong", 22.32, 114.17, "HKT-8", "HK"},
{"BEIJING", "Asia/Shanghai", 39.90, 116.41, "CST-8", "CN"},
{"TOKYO", "Asia/Tokyo", 35.68, 139.69, "JST-9", "JP"},
{"SEOUL", "Asia/Seoul", 37.57, 126.98, "KST-9", "KR"},
{"SYDNEY", "Australia/Sydney", -33.87, 151.21, "AEST-10AEDT,M10.1.0,M4.1.0/3", "AU"},
{"AUCKLAND", "Pacific/Auckland", -36.85, 174.76, "NZST-12NZDT,M9.5.0,M4.1.0/3", "NZ"},
};
const int TZ_PRESET_COUNT = sizeof(TZ_PRESETS) / sizeof(TZ_PRESETS[0]);
const int TZ_PER_PAGE = 5;
const char *getPosixFallback(const String &tz)
{
for (int i = 0; i < TZ_PRESET_COUNT; i++)
{
if (tz == TZ_PRESETS[i].tz)
{
return TZ_PRESETS[i].posix;
}
}
return nullptr;
}
const char *getCountryForTimezone(const String &tz)
{
for (int i = 0; i < TZ_PRESET_COUNT; i++)
{
if (tz == TZ_PRESETS[i].tz)
{
return TZ_PRESETS[i].country;
}
}
return nullptr;
}
bool getCityCoords(const String &tz, float &lat, float &lon)
{
for (int i = 0; i < TZ_PRESET_COUNT; i++)
{
if (tz == TZ_PRESETS[i].tz)
{
lat = TZ_PRESETS[i].lat;
lon = TZ_PRESETS[i].lon;
return true;
}
}
return false;
}
MarketInfo getMarketInfoForTimezone(const String &tz)
{
if (tz == "America/New_York")
{
return {"NYSE", true, {
{9, 30, 16, 0, "REGULAR"},
{16, 0, 20, 0, "AFTER-HRS"},
{20, 0, 4, 0, "OVERNIGHT"},
{4, 0, 9, 30, "PRE-MARKET"}
}, 4};
}
if (tz == "Asia/Shanghai")
{
return {"SSE", true, {
{9, 0, 9, 30, "PRE-MARKET"},
{9, 30, 11, 30, "REGULAR"},
{13, 0, 15, 0, "REGULAR"},
{15, 0, 15, 30, "AFTER-HRS"}
}, 4};
}
if (tz == "Europe/London")
{
return {"LSE", true, {
{7, 15, 8, 0, "PRE-MARKET"},
{8, 0, 16, 30, "REGULAR"},
{16, 30, 17, 0, "CLOSING"},
{17, 0, 17, 30, "AFTER-HRS"}
}, 4};
}
if (tz == "Asia/Tokyo")
{
return {"TSE", true, {
{9, 0, 11, 30, "REGULAR"},
{12, 30, 15, 30, "REGULAR"}
}, 2};
}
if (tz == "Asia/Hong_Kong")
{
return {"HKEX", true, {
{9, 30, 12, 0, "REGULAR"},
{13, 0, 16, 0, "REGULAR"}
}, 2};
}
return {"", false, {}, 0};
}
void applyConfiguredZones()
{
for (int i = 0; i < 4; i++)
{
if (projectConfig.zoneTZ[i].length() == 0)
continue;
worldZones[i].name = projectConfig.zoneName[i];
worldZones[i].timezone = projectConfig.zoneTZ[i];
worldZones[i].market = getMarketInfoForTimezone(projectConfig.zoneTZ[i]);
}
}
/*-------- Buttons ----------*/
struct UIButton
{
int x, y, w, h;
};
bool buttonContains(const UIButton &b, int tx, int ty)
{
return tx >= b.x && tx < b.x + b.w && ty >= b.y && ty < b.y + b.h;
}
void drawButton(const UIButton &b, const String &label, uint16_t border, uint16_t textColor)
{
tft.drawRoundRect(b.x, b.y, b.w, b.h, 6, border);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(textColor, clockBackgroundColor);
tft.drawString(label, b.x + b.w / 2, b.y + b.h / 2);
}
// Settings page layout (6 rows, 34px pitch, below the 26px title)
const UIButton BTN_SET_TZ = {20, 30, 280, 28};
const UIButton BTN_SET_FACE = {20, 64, 280, 28};
const UIButton BTN_SET_CLK = {20, 98, 280, 28};
const UIButton BTN_SET_DATE = {20, 132, 280, 28};
const UIButton BTN_SET_DIM = {20, 166, 60, 28};
const UIButton BTN_SET_BRI = {240, 166, 60, 28};
const UIButton BTN_SET_STAT = {20, 200, 85, 28};
const UIButton BTN_SET_LOGS = {113, 200, 89, 28};
const UIButton BTN_SET_BACK = {210, 200, 90, 28};
// Zone-pick page layout (2x2 grid mirroring the clock quadrants)
const UIButton BTN_ZONE[4] = {
{10, 36, 145, 76},
{165, 36, 145, 76},
{10, 118, 145, 76},
{165, 118, 145, 76}
};
const UIButton BTN_ZONE_BACK = {90, 202, 140, 32};
const char *SLOT_LABELS[4] = {"TOP-LEFT", "TOP-RIGHT", "BOTTOM-LEFT", "BOTTOM-RIGHT"};
// Timezone list page layout
UIButton tzRowButton(int row)
{
UIButton b = {10, 34 + row * 32, 300, 28};
return b;
}
const UIButton BTN_TZ_PREV = {10, 202, 90, 32};
const UIButton BTN_TZ_BACK = {115, 202, 90, 32};
const UIButton BTN_TZ_NEXT = {220, 202, 90, 32};
/*-------- Touch input ----------*/
// Edge-triggered touch: fires once per physical tap (press after a release).
bool uiNewTouch(int &tx, int &ty)
{
static bool wasDown = false;
static unsigned long lastFire = 0;
TouchPoint t = touchscreen.getTouch();
bool down = (t.zRaw > 800);
bool fired = false;
if (!down)
{
touchSuppressedUntilRelease = false;
}
else if (!wasDown && !touchSuppressedUntilRelease && millis() - lastFire > 150)
{
tx = t.x;
ty = t.y;
fired = true;
lastFire = millis();
}
wasDown = down;
return fired;
}
/*-------- Screen switching ----------*/
void switchToScreen(UIScreen s)
{
uiScreen = s;
uiPageDrawn = false;
touchSuppressedUntilRelease = true; // don't click through onto the new page
if (s == SCREEN_HOME)
{
// Force a full clock redraw when returning home
tft.fillScreen(clockBackgroundColor);
firstDraw = true;
for (int i = 0; i < 4; i++)
{
worldZones[i].initialized = false;
}
}
}
/*-------- Settings actions ----------*/
void saveDisplayPrefs()
{
projectConfig.twentyFourHour = SHOW_24HOUR;
projectConfig.usDateFormat = !NOT_US_DATE;
projectConfig.saveConfigFile();
}
void drawSettingsBrightnessLabel()
{
tft.fillRect(85, 166, 150, 28, clockBackgroundColor);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
int pct = map(backlightLevel, 5, 255, 0, 100);
tft.drawString("Brightness " + String(pct) + "%", 160, 180);
}
void adjustBacklightFromUi(int delta)
{
backlightLevel += delta;
if (backlightLevel < 5) backlightLevel = 5;
if (backlightLevel > 255) backlightLevel = 255;
analogWrite(BACKLIGHT_PIN, backlightLevel);
// Hold this manual setting before auto-brightness resumes
manualBrightnessUntil = millis() + MANUAL_BRIGHTNESS_HOLD_MS;
// Persist so the level survives a reboot (taps are discrete, so this
// stays well within SPIFFS write-endurance territory)
projectConfig.brightness = backlightLevel;
projectConfig.saveConfigFile();
drawSettingsBrightnessLabel();
Log.println("Brightness set from settings page: " + String(backlightLevel));
}
// Apply a timezone preset to a quadrant, persist it, and re-fetch the zone
// definition from the ezTime server (brief blocking network call). Declared
// in uiPages.h - also used by the web settings page.
void applyZoneSelection(int slot, const TimezonePreset &preset)
{
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(TFT_CYAN, clockBackgroundColor);
tft.drawString("Loading " + String(preset.name) + "...", 160, 120);
worldZones[slot].name = preset.name;
worldZones[slot].timezone = preset.tz;
worldZones[slot].market = getMarketInfoForTimezone(preset.tz);
worldZones[slot].lastMarketStatus = "";
worldZones[slot].lastHour = -1;
worldZones[slot].lastMinute = -1;
worldZones[slot].lastDay = -1;
worldZones[slot].initialized = false;
if (!worldZones[slot].tz.setLocation(preset.tz))
{
// Timezone server unreachable - fall back to the preset's built-in
// POSIX rules so the quadrant still ticks with correct local time.
Log.println("Failed to fetch timezone " + String(preset.tz) +
" - using built-in POSIX rules");
worldZones[slot].tz.setPosix(preset.posix);
}
if (worldZones[slot].market.hasMarket)
{
worldZones[slot].lastMarketStatus = getMarketStatus(worldZones[slot]);
}
projectConfig.zoneName[slot] = preset.name;
projectConfig.zoneTZ[slot] = preset.tz;
projectConfig.saveConfigFile();
// Cached weather / holidays are for the old city - refetch as needed
weatherInvalidate();
holidaysInvalidate();
Log.println("Quadrant " + String(slot) + " set to " + String(preset.name) +
" (" + String(preset.tz) + ")");
}
/*-------- Page rendering ----------*/
void renderSettingsPage()
{
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(4);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
tft.drawString("SETTINGS", 160, 2);
drawButton(BTN_SET_TZ, "Change timezones >", TFT_CYAN, TFT_WHITE);
drawButton(BTN_SET_FACE,
"Clock face: " + String(clockFaceName(projectConfig.clockFace)),
TFT_CYAN, TFT_WHITE);
drawButton(BTN_SET_CLK,
SHOW_24HOUR ? "Clock format: 24 hour" : "Clock format: 12 hour (AM/PM)",
TFT_CYAN, TFT_WHITE);
drawButton(BTN_SET_DATE,
NOT_US_DATE ? "Date format: DD/MM/YY" : "Date format: MM/DD/YY",
TFT_CYAN, TFT_WHITE);
drawButton(BTN_SET_DIM, "-", TFT_CYAN, TFT_WHITE);
drawButton(BTN_SET_BRI, "+", TFT_CYAN, TFT_WHITE);
drawSettingsBrightnessLabel();
drawButton(BTN_SET_STAT, "Status", TFT_GREEN, TFT_WHITE);
drawButton(BTN_SET_LOGS, "Logs", TFT_GREEN, TFT_WHITE);
drawButton(BTN_SET_BACK, "Back", TFT_DARKGREY, TFT_WHITE);
}
void renderZonePickPage()
{
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
tft.drawString("TAP A CLOCK TO CHANGE ITS TIMEZONE", 160, 10);
for (int i = 0; i < 4; i++)
{
const UIButton &b = BTN_ZONE[i];
int cx = b.x + b.w / 2;
tft.drawRoundRect(b.x, b.y, b.w, b.h, 6, TFT_CYAN);
tft.setTextFont(1);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString(SLOT_LABELS[i], cx, b.y + 8);
tft.setTextFont(2);
tft.setTextColor(TFT_YELLOW, clockBackgroundColor);
tft.drawString(worldZones[i].name, cx, b.y + 26);
tft.setTextFont(1);
tft.setTextColor(TFT_LIGHTGREY, clockBackgroundColor);
tft.drawString(worldZones[i].timezone, cx, b.y + 54);
}
drawButton(BTN_ZONE_BACK, "Back", TFT_DARKGREY, TFT_WHITE);
}
void renderTzListPage()
{
int totalPages = (TZ_PRESET_COUNT + TZ_PER_PAGE - 1) / TZ_PER_PAGE;
if (tzListPage < 0) tzListPage = 0;
if (tzListPage >= totalPages) tzListPage = totalPages - 1;
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
tft.drawString(String(SLOT_LABELS[zoneSlotBeingEdited]) + " CLOCK", 160, 8);
tft.setTextFont(1);
tft.setTextDatum(TR_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString(String(tzListPage + 1) + "/" + String(totalPages), 314, 10);
for (int row = 0; row < TZ_PER_PAGE; row++)
{
int idx = tzListPage * TZ_PER_PAGE + row;
if (idx >= TZ_PRESET_COUNT)
break;
bool current = (worldZones[zoneSlotBeingEdited].timezone == TZ_PRESETS[idx].tz);
drawButton(tzRowButton(row),
String(TZ_PRESETS[idx].name) + " (" + TZ_PRESETS[idx].tz + ")",
current ? TFT_GREEN : TFT_DARKGREY,
current ? TFT_GREEN : TFT_WHITE);
}
drawButton(BTN_TZ_PREV, "< Prev", TFT_CYAN, TFT_WHITE);
drawButton(BTN_TZ_BACK, "Back", TFT_DARKGREY, TFT_WHITE);
drawButton(BTN_TZ_NEXT, "Next >", TFT_CYAN, TFT_WHITE);
}
/*-------- System status pages ----------*/
// Three pages, cycled by tapping the screen (the last tap returns to the
// settings page): 1) system, 2) network & storage, 3) clock data. The
// dynamic values refresh once a second while a page is showing.
const int STATUS_PAGE_COUNT = 3;
const int STATUS_MAX_ROWS = 11;
const int STATUS_VALUE_X = 96;
const int STATUS_ROW_Y0 = 34;
const int STATUS_ROW_STEP = 17;
int statusPageIndex = 0; // reset to 0 when entering from the settings page
static const char *STATUS_TITLES[STATUS_PAGE_COUNT] = {
"SYSTEM STATUS", "NETWORK & STORAGE", "CLOCK DATA"};
static const char *STATUS_LABELS_SYSTEM[] = {
"WiFi", "IP addr", "CPU", "CPU temp", "Flash", "Firmware",
"Build", "Heap", "Uptime", "NTP sync", "UTC time"};
static const char *STATUS_LABELS_NETWORK[] = {
"Hostname", "MAC", "Gateway", "DNS", "Channel", "Drops",
"Reset", "SPIFFS", "Max alloc", "SDK"};
static const char *STATUS_LABELS_DATA[] = {
"Home zone", "Face", "Format", "Weather", "Mkt hols", "Pub hols",
"Backlight", "Auto-dim", "Hold", "Night"};
static int statusRowCount(int page)
{
return page == 0 ? 11 : 10;
}
static const char *const *statusLabels(int page)
{
switch (page)
{
case 1: return STATUS_LABELS_NETWORK;
case 2: return STATUS_LABELS_DATA;
default: return STATUS_LABELS_SYSTEM;
}
}
const char *resetReasonText()
{
switch (esp_reset_reason())
{
case ESP_RST_POWERON: return "power-on";
case ESP_RST_EXT: return "external pin";
case ESP_RST_SW: return "software reset";
case ESP_RST_PANIC: return "crash (panic)";
case ESP_RST_INT_WDT: return "interrupt watchdog";
case ESP_RST_TASK_WDT: return "task watchdog";
case ESP_RST_WDT: return "watchdog";
case ESP_RST_DEEPSLEEP: return "deep-sleep wake";
case ESP_RST_BROWNOUT: return "brownout";
case ESP_RST_SDIO: return "SDIO reset";
default: return "unknown";
}
}
String formatUptime()
{
unsigned long s = millis() / 1000;
char buf[24];
sprintf(buf, "%lud %02lu:%02lu:%02lu",
s / 86400UL, (s / 3600UL) % 24UL, (s / 60UL) % 60UL, s % 60UL);
return String(buf);
}
// Compact duration for the outage-history row: "45m", "3h", "2d".
static String agoText(unsigned long ms)
{
unsigned long m = ms / 60000UL;
if (m < 60) return String(m) + "m";
if (m < 48 * 60) return String(m / 60) + "h";
return String(m / (24 * 60)) + "d";
}
// Page 1: the classic system diagnostics.
static void fillSystemValues(String *values, uint16_t *colors)
{
String ssid = WiFi.SSID();
if (ssid.length() > 14) ssid = ssid.substring(0, 14);
uint32_t sketch = ESP.getSketchSize();
uint32_t slot = sketch + ESP.getFreeSketchSpace();
bool wifiUp = (WiFi.status() == WL_CONNECTED);
int rssi = WiFi.RSSI();
values[0] = wifiUp ? ssid + " (" + String(rssi) + " dBm)" : "OFFLINE";
colors[0] = !wifiUp ? TFT_RED
: (rssi > -60) ? TFT_GREEN
: (rssi > -75) ? TFT_YELLOW
: TFT_RED;
values[1] = WiFi.localIP().toString();
values[2] = String(ESP.getChipModel()) + " r" + String(ESP.getChipRevision()) +
" @" + String(ESP.getCpuFreqMHz()) + "MHz";
#if SOC_TEMP_SENSOR_SUPPORTED
values[3] = String(temperatureRead(), 1) + " C";
#else
values[3] = "no sensor on this chip";
#endif
values[4] = String(ESP.getFlashChipSize() / (1024UL * 1024UL)) + " MB @ " +
String(ESP.getFlashChipSpeed() / 1000000UL) + " MHz";
values[5] = String(sketch / 1024) + " KB (" +
String(slot > 0 ? (sketch * 100UL) / slot : 0) + "% of slot)";
values[6] = String(__DATE__) + " " + __TIME__;
values[7] = String(ESP.getFreeHeap() / 1024) + " KB (min " +
String(ESP.getMinFreeHeap() / 1024) + ")";
values[8] = formatUptime();
values[9] = (syncCount > 0)
? String(syncCount) + " (" +
String((millis() - lastSyncTime) / 60000UL) + " min ago)"
: "none since boot";
values[10] = UTC.dateTime("H:i:s") + " UTC";
}
// Page 2: network details, outage history, reset reason and storage.
static void fillNetworkValues(String *values, uint16_t *colors)
{
String host = projectConfig.hostname + ".local";
if (host.length() > 28) host = host.substring(0, 28);
values[0] = host;
values[1] = WiFi.macAddress();
values[2] = WiFi.gatewayIP().toString();
values[3] = WiFi.dnsIP().toString();
values[4] = String(WiFi.channel());
int drops = wifiDropCount();
unsigned long offlineMs = wifiOfflineDurationMs();
if (offlineMs > 0)
{
values[5] = String(drops) + " (offline " + agoText(offlineMs) + ")";
colors[5] = TFT_RED;
}
else if (drops == 0)
{
values[5] = "none since boot";
}
else
{
values[5] = String(drops) + " (last " + agoText(wifiLastOutageDurationMs()) +
", " + agoText(wifiLastOutageEndedAgoMs()) + " ago)";
colors[5] = TFT_YELLOW;
}
esp_reset_reason_t rr = esp_reset_reason();
values[6] = resetReasonText();
if (rr == ESP_RST_PANIC || rr == ESP_RST_INT_WDT || rr == ESP_RST_TASK_WDT ||
rr == ESP_RST_WDT || rr == ESP_RST_BROWNOUT)
{
colors[6] = TFT_RED; // the previous run died abnormally
}
values[7] = String(SPIFFS.usedBytes() / 1024) + " / " +
String(SPIFFS.totalBytes() / 1024) + " KB";
values[8] = String(ESP.getMaxAllocHeap() / 1024) + " KB block";
values[9] = ESP.getSdkVersion();
}
// Page 3: what the clock is showing and how fresh its background data is.
static void fillDataValues(String *values, uint16_t *colors)
{
values[0] = worldZones[0].timezone;
values[1] = clockFaceName(projectConfig.clockFace);
values[2] = String(SHOW_24HOUR ? "24H" : "12H") + ", " +
(NOT_US_DATE ? "DD/MM/YY" : "MM/DD/YY");
long weatherAge = weatherAgeMinutes();
if (weatherAge < 0)
{
values[3] = "no data yet";
colors[3] = TFT_RED;
}
else
{
values[3] = "updated " + String(weatherAge) + " min ago";
if (weatherAge > 60) colors[3] = TFT_YELLOW; // fetches every 20 min
}
long calAgeDays = -1;
if (marketHolidaysFetchedInfo(calAgeDays))
{
values[4] = calAgeDays < 0 ? "fetched calendars"
: "fetched " + String(calAgeDays) + "d ago";
colors[4] = TFT_GREEN;
}
else
{
values[4] = "compiled-in tables";
colors[4] = TFT_YELLOW;
}
int eligible = 0;
int loaded = holidayZonesLoaded(eligible);
if (eligible == 0)
{
values[5] = "no eligible zones";
}
else
{
values[5] = String(loaded) + "/" + String(eligible) + " zones loaded";
colors[5] = (loaded == eligible) ? TFT_GREEN : TFT_YELLOW;
}
values[6] = String(backlightLevel) + " (" +
String(map(constrain(backlightLevel, 5, 255), 5, 255, 0, 100)) + "%)";
bool ldrTrusted, ldrDark;
int ldrSmoothed;
if (!getLdrState(ldrTrusted, ldrDark, ldrSmoothed))
{
values[7] = "schedule only (no LDR)";
}
else if (ldrTrusted)
{
values[7] = String("LDR: room ") + (ldrDark ? "dark" : "bright");
}
else
{
values[7] = "schedule (LDR unproven)";
}
unsigned long nowMs = millis();
values[8] = (manualBrightnessUntil > nowMs)
? "manual, " +
String((manualBrightnessUntil - nowMs + 59999UL) / 60000UL) +
" min left"
: "none";
int ns = projectConfig.nightStartHour;
int ne = projectConfig.nightEndHour;
int npct = map(constrain(projectConfig.nightBrightness, 1, 255), 1, 255, 0, 100);
values[9] = (ns == ne)
? "window off (" + String(npct) + "% dark)"
: String(ns) + ":00-" + String(ne) + ":00 -> " + String(npct) + "%";
}
void renderStatusValues()
{
String values[STATUS_MAX_ROWS];
uint16_t colors[STATUS_MAX_ROWS];
for (int i = 0; i < STATUS_MAX_ROWS; i++)
{
colors[i] = TFT_WHITE;
}
switch (statusPageIndex)
{
case 1: fillNetworkValues(values, colors); break;
case 2: fillDataValues(values, colors); break;
default: fillSystemValues(values, colors); break;
}
int rows = statusRowCount(statusPageIndex);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TL_DATUM);
for (int i = 0; i < rows; i++)
{
int y = STATUS_ROW_Y0 + i * STATUS_ROW_STEP;
tft.fillRect(STATUS_VALUE_X, y, 320 - STATUS_VALUE_X, STATUS_ROW_STEP, clockBackgroundColor);
tft.setTextColor(colors[i], clockBackgroundColor);
tft.drawString(values[i], STATUS_VALUE_X, y);
}
}
void renderStatusPage()
{
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(4);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
tft.drawString(STATUS_TITLES[statusPageIndex], 160, 2);
const char *const *labels = statusLabels(statusPageIndex);
int rows = statusRowCount(statusPageIndex);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_LIGHTGREY, clockBackgroundColor);
for (int i = 0; i < rows; i++)
{
tft.drawString(labels[i], 8, STATUS_ROW_Y0 + i * STATUS_ROW_STEP);
}
tft.setTextFont(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
String footer = (statusPageIndex + 1 < STATUS_PAGE_COUNT)
? "Page " + String(statusPageIndex + 1) + "/" +
String(STATUS_PAGE_COUNT) + " - tap for next"
: "Page " + String(STATUS_PAGE_COUNT) + "/" +
String(STATUS_PAGE_COUNT) + " - tap to go back";
tft.drawString(footer, 160, 228);
renderStatusValues();
}
/*-------- Logs page ----------*/
// The tail of the in-RAM log ring (see logBuffer.h), newest lines at the
// bottom, refreshed whenever a new line lands. Tap anywhere to go back.
const int LOGS_TOP = 18; // first log line y (below the title row)
const int LOGS_LINE_STEP = 10; // font 1 is 8px tall; +2 leading
const int LOGS_MAX_LINES = 21;
const int LOGS_MAX_CHARS = 52; // 320px / 6px per font-1 char, with margin
uint32_t lastShownLogVersion = 0;
static void renderLogsLines()
{
// Grab a bit more than one screenful and keep the last N lines.
String text = logTail(2600);
struct Seg
{
uint16_t start;
uint16_t len;
};
Seg segs[LOGS_MAX_LINES];
int count = 0, next = 0;
int lineStart = 0;
int tlen = (int)text.length();
for (int i = 0; i <= tlen; i++)
{
if (i == tlen || text[i] == '\n')
{
int len = i - lineStart;
if (len > 0)
{
if (len > LOGS_MAX_CHARS) len = LOGS_MAX_CHARS; // truncate, no wrap
segs[next] = {(uint16_t)lineStart, (uint16_t)len};
next = (next + 1) % LOGS_MAX_LINES;
if (count < LOGS_MAX_LINES) count++;
}
lineStart = i + 1;
}
}
tft.fillRect(0, LOGS_TOP, 320, 240 - LOGS_TOP, clockBackgroundColor);
tft.setTextFont(1);
tft.setTextSize(1);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_LIGHTGREY, clockBackgroundColor);
int first = (next + LOGS_MAX_LINES - count) % LOGS_MAX_LINES;
for (int k = 0; k < count; k++)
{
const Seg &g = segs[(first + k) % LOGS_MAX_LINES];
tft.drawString(text.substring(g.start, g.start + g.len),
4, LOGS_TOP + k * LOGS_LINE_STEP);
}
lastShownLogVersion = logVersion();
}
void renderLogsPage()
{
tft.fillScreen(clockBackgroundColor);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(TFT_WHITE, clockBackgroundColor);
tft.drawString("LOGS", 4, 0);
tft.setTextFont(1);
tft.setTextDatum(TR_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString("tap anywhere to go back", 316, 4);
renderLogsLines();
}
/*-------- Touch routing + page loop ----------*/
void handleUiTouch()
{
int tx = 0, ty = 0;
if (!uiNewTouch(tx, ty))
return;
switch (uiScreen)
{
case SCREEN_SETTINGS:
if (buttonContains(BTN_SET_TZ, tx, ty))
{
switchToScreen(SCREEN_ZONE_PICK);
}
else if (buttonContains(BTN_SET_FACE, tx, ty))
{
projectConfig.clockFace = (projectConfig.clockFace + 1) % FACE_COUNT;
projectConfig.saveConfigFile();
uiPageDrawn = false; // redraw with the new label
}
else if (buttonContains(BTN_SET_CLK, tx, ty))
{
SHOW_24HOUR = !SHOW_24HOUR;
saveDisplayPrefs();
uiPageDrawn = false; // redraw with the new label
}
else if (buttonContains(BTN_SET_DATE, tx, ty))
{
NOT_US_DATE = !NOT_US_DATE;
saveDisplayPrefs();
uiPageDrawn = false;
}
else if (buttonContains(BTN_SET_DIM, tx, ty))
{
adjustBacklightFromUi(-15);
}
else if (buttonContains(BTN_SET_BRI, tx, ty))
{
adjustBacklightFromUi(15);
}
else if (buttonContains(BTN_SET_STAT, tx, ty))
{
statusPageIndex = 0; // always enter on the first status page
switchToScreen(SCREEN_STATUS);
}
else if (buttonContains(BTN_SET_LOGS, tx, ty))
{
switchToScreen(SCREEN_LOGS);
}
else if (buttonContains(BTN_SET_BACK, tx, ty))
{
switchToScreen(SCREEN_HOME);
}
break;
case SCREEN_ZONE_PICK:
for (int i = 0; i < 4; i++)
{
if (buttonContains(BTN_ZONE[i], tx, ty))
{
zoneSlotBeingEdited = i;
// Open the list on the page containing the current selection
tzListPage = 0;
for (int p = 0; p < TZ_PRESET_COUNT; p++)
{
if (worldZones[i].timezone == TZ_PRESETS[p].tz)
{
tzListPage = p / TZ_PER_PAGE;
break;
}
}
switchToScreen(SCREEN_TZ_LIST);
return;
}
}
if (buttonContains(BTN_ZONE_BACK, tx, ty))
{
switchToScreen(SCREEN_SETTINGS);
}
break;
case SCREEN_TZ_LIST:
{
int totalPages = (TZ_PRESET_COUNT + TZ_PER_PAGE - 1) / TZ_PER_PAGE;
for (int row = 0; row < TZ_PER_PAGE; row++)
{
int idx = tzListPage * TZ_PER_PAGE + row;
if (idx >= TZ_PRESET_COUNT)
break;
if (buttonContains(tzRowButton(row), tx, ty))
{
applyZoneSelection(zoneSlotBeingEdited, TZ_PRESETS[idx]);
switchToScreen(SCREEN_ZONE_PICK);
return;
}
}
if (buttonContains(BTN_TZ_PREV, tx, ty))
{
tzListPage = (tzListPage + totalPages - 1) % totalPages;
uiPageDrawn = false;
}
else if (buttonContains(BTN_TZ_NEXT, tx, ty))
{
tzListPage = (tzListPage + 1) % totalPages;
uiPageDrawn = false;
}
else if (buttonContains(BTN_TZ_BACK, tx, ty))
{
switchToScreen(SCREEN_ZONE_PICK);
}
break;
}
case SCREEN_STATUS:
// Tap cycles through the status pages; the last one returns to settings
statusPageIndex++;
if (statusPageIndex >= STATUS_PAGE_COUNT)
{
statusPageIndex = 0;
switchToScreen(SCREEN_SETTINGS);
}
else
{
uiPageDrawn = false; // repaint with the next page's rows
touchSuppressedUntilRelease = true;
}
break;
case SCREEN_LOGS:
switchToScreen(SCREEN_SETTINGS);
break;
default:
break;
}
}
void renderUiPage()
{
if (!uiPageDrawn)
{
switch (uiScreen)
{
case SCREEN_SETTINGS:
renderSettingsPage();
break;
case SCREEN_ZONE_PICK:
renderZonePickPage();
break;
case SCREEN_TZ_LIST:
renderTzListPage();
break;
case SCREEN_STATUS:
renderStatusPage();
lastStatusRefresh = millis();
break;
case SCREEN_LOGS:
renderLogsPage();
lastStatusRefresh = millis();
break;
default:
break;
}
uiPageDrawn = true;
}
else if (uiScreen == SCREEN_STATUS && millis() - lastStatusRefresh > 1000)
{
// Live-refresh the dynamic values (uptime, heap, RSSI, clock) once a second
renderStatusValues();
lastStatusRefresh = millis();
}
else if (uiScreen == SCREEN_LOGS && millis() - lastStatusRefresh > 1000)
{
// Repaint the tail only when a new line has actually arrived
if (logVersion() != lastShownLogVersion)
{
renderLogsLines();
}
lastStatusRefresh = millis();
}
}