forked from LextZip/Deskbuddy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdesk_buddy_github.cpp
More file actions
2928 lines (2483 loc) · 100 KB
/
desk_buddy_github.cpp
File metadata and controls
2928 lines (2483 loc) · 100 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
// Deskbuddy V.8
// Nav: Home / Weather / Notes / Status
// Full version
// - KP dots replaced with Low / Medium / High / Extreme text
// - KP level text uses same small font as wind direction and stays inside the box
// - Wind + direction added to Weather page
// - Wind direction uses Accent color
// - Weather sun event field automatically shows Sunrise or Sunset, whichever is next
// - Uptime added to Status page
#include <WiFi.h>
#include <WiFiManager.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <TFT_eSPI.h>
#include <time.h>
#include <ArduinoJson.h>
#include <WebServer.h>
#include <Preferences.h>
#include <SPI.h>
#include <XPT2046_Touchscreen.h>
#include <math.h>
// =========================================================
// WIFI
// =========================================================
#if __has_include("arduino_secrets.h")
#include "arduino_secrets.h"
#endif
#ifndef DESKBUDDY_WIFI_SSID
#define DESKBUDDY_WIFI_SSID "YOUR_WIFI_SSID"
#endif
#ifndef DESKBUDDY_WIFI_PASS
#define DESKBUDDY_WIFI_PASS "YOUR_WIFI_PASSWORD"
#endif
const char* WIFI_SSID = DESKBUDDY_WIFI_SSID;
const char* WIFI_PASS = DESKBUDDY_WIFI_PASS;
static bool hasStaticWifiCredentials() {
return String(WIFI_SSID) != "YOUR_WIFI_SSID" &&
String(WIFI_PASS) != "YOUR_WIFI_PASSWORD" &&
String(WIFI_SSID).length() > 0;
}
// =========================================================
// DISPLAY / TOUCH
// =========================================================
TFT_eSPI tft;
const int ROT = 2;
const bool INV = false;
#define TOUCH_CS 33
#define TOUCH_IRQ 36
static const int T_SCK = 25;
static const int T_MISO = 39;
static const int T_MOSI = 32;
SPIClass touchSPI(VSPI);
XPT2046_Touchscreen ts(TOUCH_CS);
static const int TOUCH_X_MIN = 562;
static const int TOUCH_X_MAX = 3604;
static const int TOUCH_Y_MIN = 544;
static const int TOUCH_Y_MAX = 3720;
static const bool TOUCH_SWAP_XY = false;
static const bool TOUCH_FLIP_X = false;
static const bool TOUCH_FLIP_Y = false;
// =========================================================
// WEB / STORAGE
// =========================================================
WebServer server(80);
Preferences prefs;
// =========================================================
// SPRITES
// =========================================================
TFT_eSprite sprClock = TFT_eSprite(&tft);
TFT_eSprite sprSmall = TFT_eSprite(&tft);
// =========================================================
// LOCATION
// =========================================================
float LAT = 52.5200f;
float LNG = 13.4050f;
String locationName = "Berlin";
// =========================================================
// THEME
// =========================================================
uint16_t COL_BG = 0x08A3;
uint16_t COL_PANEL = 0x1106;
uint16_t COL_PANEL_ALT = 0x18C7;
uint16_t COL_STROKE = 0x31EC;
uint16_t COL_TEXT = 0xEF7D;
uint16_t COL_DIM = 0x94B2;
uint16_t COL_ACCENT = 0x5EFA;
const uint16_t COL_GREEN = TFT_GREEN;
const uint16_t COL_YELLOW = 0xFFE0;
const uint16_t COL_RED = TFT_RED;
const uint16_t COL_BLUE = 0x041F;
String textColorKey = "standard";
String unitKey = "metric"; // metric = C/mm, imperial = F/in
String regionFormatKey = "europe"; // europe = 24h + dd.mm.yyyy, us = 12h + mm/dd/yyyy
// =========================================================
// LAYOUT
// =========================================================
const int SCREEN_W = 240;
const int SCREEN_H = 320;
const int TOPBAR_H = 34;
const int NAV_H = 44;
const int HOME_GRID_Y1 = 120;
const int HOME_GRID_Y2 = 198;
const int HOME_WIDGET_H = 70;
const int HOME_TIMER_X = 124;
const int HOME_TIMER_Y = HOME_GRID_Y1;
const int HOME_TIMER_W = 108;
const int HOME_TIMER_H = HOME_WIDGET_H;
const int TIMER_MENU_X = 20;
const int TIMER_MENU_Y = 68;
const int TIMER_MENU_W = 200;
const int TIMER_MENU_H = 194;
const int TIMER_DONE_X = 26;
const int TIMER_DONE_Y = 92;
const int TIMER_DONE_W = 188;
const int TIMER_DONE_H = 108;
const int PAGE_ROW1_Y = 42;
const int PAGE_ROW2_Y = 120;
const int PAGE_ROW3_Y = 198;
const int PAGE_WIDGET_H = HOME_WIDGET_H;
// =========================================================
// NOTES
// =========================================================
String notesText = "No notes yet.";
bool notesDirty = true;
String buddyNickname = "";
enum HomeWidgetType {
HOME_WIDGET_WEEK = 0,
HOME_WIDGET_TIMER,
HOME_WIDGET_RAIN,
HOME_WIDGET_OUTDOOR,
HOME_WIDGET_KP,
HOME_WIDGET_UV,
HOME_WIDGET_WIND,
HOME_WIDGET_SUN
};
const int HOME_SLOT_COUNT = 4;
HomeWidgetType homeWidgetSlots[HOME_SLOT_COUNT] = {
HOME_WIDGET_WEEK,
HOME_WIDGET_TIMER,
HOME_WIDGET_RAIN,
HOME_WIDGET_OUTDOOR
};
String cacheHomeSlots[HOME_SLOT_COUNT];
// =========================================================
// STATE
// =========================================================
enum Page {
PAGE_HOME = 0,
PAGE_WEATHER = 1,
PAGE_NOTES = 2,
PAGE_STATUS = 3,
PAGE_SETTINGS = 4
};
const int NAV_COUNT = 5;
Page currentPage = PAGE_HOME;
Page lastDrawnPage = (Page)-1;
unsigned long lastClockTick = 0;
unsigned long lastDataTick = 0;
const unsigned long CLOCK_TICK_MS = 1000;
const unsigned long DATA_TICK_MS = 30UL * 1000UL;
bool pageDirty = true;
bool dataDirty = true;
// cache
String cacheClock = "";
String cacheTemp = "";
String cacheRain = "";
String cacheWeek = "";
String cacheHomeEmpty1 = "";
String cacheHomeEmpty2 = "";
String cacheFocusTimer = "";
String cacheTimerMenu = "";
String cacheTimerDone = "";
String cacheTimerDoneCountdown = "";
String cacheTimerDoneFlash = "";
String lastWifiText = "";
String lastSignalText = "";
String lastIpText = "";
String lastUptimeText = "";
String lastTempText = "";
String lastRainText = "";
String lastUvText = "";
String lastUvLevelText = "";
String lastKpText = "";
String lastKpLevelText = "";
String lastWindText = "";
String lastWindDirText = "";
String lastNextSunLabel = "";
String lastNextSunTime = "";
String lastNotesText = "";
String lastNetworkToggleText = "";
String lastSettingsText = "";
String lastInsightText = "";
const char* homeWidgetKey(HomeWidgetType type) {
switch (type) {
case HOME_WIDGET_WEEK: return "week";
case HOME_WIDGET_TIMER: return "timer";
case HOME_WIDGET_RAIN: return "rain";
case HOME_WIDGET_OUTDOOR: return "outdoor";
case HOME_WIDGET_KP: return "kp";
case HOME_WIDGET_UV: return "uv";
case HOME_WIDGET_WIND: return "wind";
case HOME_WIDGET_SUN: return "sun";
default: return "week";
}
}
const char* homeWidgetLabel(HomeWidgetType type) {
switch (type) {
case HOME_WIDGET_WEEK: return "Week";
case HOME_WIDGET_TIMER: return "Timer";
case HOME_WIDGET_RAIN: return "Rain";
case HOME_WIDGET_OUTDOOR: return "Outdoor";
case HOME_WIDGET_KP: return "KP index";
case HOME_WIDGET_UV: return "UV index";
case HOME_WIDGET_WIND: return "Wind";
case HOME_WIDGET_SUN: return "Sun event";
default: return "Week";
}
}
HomeWidgetType homeWidgetFromKey(const String& key) {
if (key == "week") return HOME_WIDGET_WEEK;
if (key == "timer") return HOME_WIDGET_TIMER;
if (key == "rain") return HOME_WIDGET_RAIN;
if (key == "outdoor") return HOME_WIDGET_OUTDOOR;
if (key == "kp") return HOME_WIDGET_KP;
if (key == "uv") return HOME_WIDGET_UV;
if (key == "wind") return HOME_WIDGET_WIND;
if (key == "sun") return HOME_WIDGET_SUN;
return HOME_WIDGET_WEEK;
}
const char* homeSlotLabel(int slot) {
switch (slot) {
case 0: return "Top left";
case 1: return "Top right";
case 2: return "Bottom left";
case 3: return "Bottom right";
default: return "Slot";
}
}
void getHomeSlotRect(int slot, int& x, int& y, int& w, int& h) {
const int xs[HOME_SLOT_COUNT] = {8, 124, 8, 124};
const int ys[HOME_SLOT_COUNT] = {HOME_GRID_Y1, HOME_GRID_Y1, HOME_GRID_Y2, HOME_GRID_Y2};
x = xs[slot];
y = ys[slot];
w = 108;
h = HOME_WIDGET_H;
}
void appendHomeWidgetOptions(String& page, const String& selectedKey) {
const HomeWidgetType types[] = {
HOME_WIDGET_WEEK,
HOME_WIDGET_TIMER,
HOME_WIDGET_RAIN,
HOME_WIDGET_OUTDOOR,
HOME_WIDGET_KP,
HOME_WIDGET_UV,
HOME_WIDGET_WIND,
HOME_WIDGET_SUN
};
for (HomeWidgetType type : types) {
const char* key = homeWidgetKey(type);
page += "<option value='";
page += key;
page += "'";
if (selectedKey == key) page += " selected";
page += ">";
page += homeWidgetLabel(type);
page += "</option>";
}
}
void clearHomeSlotCaches() {
for (int i = 0; i < HOME_SLOT_COUNT; i++) {
cacheHomeSlots[i] = "";
}
}
// Focus timer
bool focusMenuOpen = false;
bool focusTimerRunning = false;
bool focusTimerFinished = false;
unsigned long focusEndMs = 0;
unsigned long focusDurationSec = 0;
unsigned long focusRemainingSec = 0;
bool timerDoneDialogOpen = false;
unsigned long timerDoneDialogStartedMs = 0;
const unsigned long TIMER_DONE_DIALOG_MS = 60UL * 1000UL;
bool flashModeEnabled = false;
int timerPresetMin[6] = {1, 5, 10, 15, 25, 30};
bool wifiEnabled = true;
bool wifiConnectInProgress = false;
unsigned long wifiConnectStartedMs = 0;
const unsigned long WIFI_CONNECT_TIMEOUT_MS = 15000UL;
bool wifiPortalRequested = false;
struct CityPreset {
const char* name;
float lat;
float lng;
};
const CityPreset CITY_PRESETS[] = {
{"Berlin", 52.5200f, 13.4050f},
{"Sao Paulo", -23.5505f, -46.6333f},
{"New York", 40.7128f, -74.0060f},
{"London", 51.5072f, -0.1276f},
{"Tokyo", 35.6762f, 139.6503f},
{"Lisbon", 38.7223f, -9.1393f}
};
const int CITY_PRESET_COUNT = sizeof(CITY_PRESETS) / sizeof(CITY_PRESETS[0]);
// Weather
static float tempC = NAN;
static float tempMinC = NAN;
static float tempMaxC = NAN;
static float precipMm = NAN;
static float windSpeedMs = NAN;
static float windDirectionDeg = NAN;
static float uvIndex = NAN;
static time_t lastWeatherFetch = 0;
static const uint32_t WEATHER_INTERVAL_SEC = 10 * 60;
// KP-index
static float kpIndex = NAN;
static time_t lastKpFetch = 0;
static const uint32_t KP_INTERVAL_SEC = 10 * 60;
// Sunrise / Sunset
static int sunriseMin = -1;
static int sunsetMin = -1;
static int lastSunYmd = -1;
static time_t lastSyncTime = 0;
// Public content
String contentMode = "quote"; // quote, tech, off
String insightTitle = "Deskbuddy";
String insightBody = "Tap Setup to choose quotes, tech headlines, city, Wi-Fi, and brightness.";
String insightSource = "Local";
static time_t lastInsightFetch = 0;
static const uint32_t INSIGHT_INTERVAL_SEC = 60 * 60;
// =========================================================
// SLEEP / BACKLIGHT
// =========================================================
const int BACKLIGHT_PIN = 21;
bool sleepDimmed = false;
bool sleepOff = false;
bool manualDimMode = false;
unsigned long lastInteractionMs = 0;
int sleepIntervalMin = 10;
int sleepOffDelaySec = 60;
int BL_FULL = 255;
const int BL_DIM = 18;
const int BL_OFF = 0;
const int FLASH_BL_LOW = 20;
const int FLASH_BL_HIGH = 255;
void wakeDisplay(bool clearManualMode = true);
int sanitizeTimerMinutes(int value);
// =========================================================
// HELPERS
// =========================================================
static int ymdFromLocal(time_t t) {
struct tm tmLocal;
localtime_r(&t, &tmLocal);
return (tmLocal.tm_year + 1900) * 10000 + (tmLocal.tm_mon + 1) * 100 + tmLocal.tm_mday;
}
static int minutesFromLocalEpoch(time_t t) {
struct tm tmLocal;
localtime_r(&t, &tmLocal);
return tmLocal.tm_hour * 60 + tmLocal.tm_min;
}
static int minutesNowLocal() {
time_t now = time(nullptr);
struct tm tmNow;
localtime_r(&now, &tmNow);
return tmNow.tm_hour * 60 + tmNow.tm_min;
}
static String wifiStatusText() {
if (!wifiEnabled) return "Disabled";
return WiFi.status() == WL_CONNECTED ? "Online" : "Offline";
}
static String signalText() {
if (!wifiEnabled || WiFi.status() != WL_CONNECTED) return "-- dBm";
return String(WiFi.RSSI()) + " dBm";
}
static String ipText() {
if (!wifiEnabled || WiFi.status() != WL_CONNECTED) return "-";
return WiFi.localIP().toString();
}
static bool useUsRegionFormat() {
return regionFormatKey == "us";
}
static String formatClockParts(const struct tm& tmValue, bool withSeconds) {
char buf[20];
const char* pattern = useUsRegionFormat()
? (withSeconds ? "%I:%M:%S %p" : "%I:%M %p")
: (withSeconds ? "%H:%M:%S" : "%H:%M");
strftime(buf, sizeof(buf), pattern, &tmValue);
return String(buf);
}
static String formatDateParts(const struct tm& tmValue) {
char buf[32];
strftime(buf, sizeof(buf), useUsRegionFormat() ? "%a %m/%d/%Y" : "%a %d.%m.%Y", &tmValue);
return String(buf);
}
static String formatMinuteOfDay(int minOfDay) {
if (minOfDay < 0) return "--:--";
if (useUsRegionFormat()) {
int hour24 = minOfDay / 60;
int minute = minOfDay % 60;
int hour12 = hour24 % 12;
if (hour12 == 0) hour12 = 12;
char buf[12];
snprintf(buf, sizeof(buf), "%d:%02d %s", hour12, minute, hour24 >= 12 ? "PM" : "AM");
return String(buf);
}
char buf[6];
snprintf(buf, sizeof(buf), "%02d:%02d", minOfDay / 60, minOfDay % 60);
return String(buf);
}
static String tempText() {
if (isnan(tempC)) return unitKey == "imperial" ? "--.-F" : "--.-C";
if (unitKey == "imperial") {
float f = tempC * 9.0f / 5.0f + 32.0f;
return String(f, 1) + "F";
}
return String(tempC, 1) + "C";
}
static String formatDisplayTemp(float value) {
if (isnan(value)) return "--";
if (unitKey == "imperial") {
float f = value * 9.0f / 5.0f + 32.0f;
return String((int)roundf(f)) + "F";
}
return String((int)roundf(value)) + "C";
}
static String tempRangeText() {
return "H:" + formatDisplayTemp(tempMaxC) + " L:" + formatDisplayTemp(tempMinC);
}
static String rainText() {
if (isnan(precipMm)) return unitKey == "imperial" ? "--.--in" : "--.-mm";
if (unitKey == "imperial") {
float inches = precipMm / 25.4f;
return String(inches, 2) + "in";
}
return String(precipMm, 1) + "mm";
}
static String windText() {
if (isnan(windSpeedMs)) return unitKey == "imperial" ? "--.-mph" : "--.-m/s";
if (unitKey == "imperial") {
float mph = windSpeedMs * 2.236936f;
return String(mph, 1) + "mph";
}
return String(windSpeedMs, 1) + "m/s";
}
static String windDirectionText() {
if (isnan(windDirectionDeg)) return "--";
const char* dirs[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"};
int idx = (int)roundf(windDirectionDeg / 45.0f) % 8;
return String(dirs[idx]) + " " + String((int)roundf(windDirectionDeg)) + "deg";
}
static String kpText() {
return isnan(kpIndex) ? "Kp --" : "Kp " + String(kpIndex, 1);
}
static String kpLevelText() {
if (isnan(kpIndex)) return "--";
if (kpIndex < 3.0f) return "Low";
if (kpIndex < 5.0f) return "Medium";
if (kpIndex < 7.0f) return "High";
return "Extreme";
}
static String uvText() {
return isnan(uvIndex) ? "UV --" : "UV " + String(uvIndex, 1);
}
static String uvLevelText() {
if (isnan(uvIndex)) return "--";
if (uvIndex < 3.0f) return "Low";
if (uvIndex < 6.0f) return "Moderate";
if (uvIndex < 8.0f) return "High";
if (uvIndex < 11.0f) return "Very High";
return "Extreme";
}
static uint16_t statusColor() {
if (textColorKey != "standard") return COL_TEXT;
if (!wifiEnabled) return COL_YELLOW;
return WiFi.status() == WL_CONNECTED ? COL_GREEN : COL_RED;
}
static String uptimeText() {
unsigned long seconds = millis() / 1000UL;
unsigned long days = seconds / 86400UL;
seconds %= 86400UL;
unsigned long hours = seconds / 3600UL;
seconds %= 3600UL;
unsigned long minutes = seconds / 60UL;
if (days > 0) return String(days) + "d " + String(hours) + "h";
if (hours > 0) return String(hours) + "h " + String(minutes) + "m";
return String(minutes) + "m";
}
static String nextSunLabel() {
int nowMin = minutesNowLocal();
if (sunriseMin < 0 || sunsetMin < 0) return "Sun";
if (nowMin < sunriseMin) return "Sunrise";
if (nowMin < sunsetMin) return "Sunset";
return "Sunrise";
}
static String nextSunTimeText() {
int nowMin = minutesNowLocal();
if (sunriseMin < 0 || sunsetMin < 0) return "--:--";
if (nowMin < sunriseMin) return formatMinuteOfDay(sunriseMin);
if (nowMin < sunsetMin) return formatMinuteOfDay(sunsetMin);
return formatMinuteOfDay(sunriseMin);
}
static String htmlEscape(const String& s) {
String out;
out.reserve(s.length());
for (size_t i = 0; i < s.length(); i++) {
char c = s[i];
if (c == '&') out += "&";
else if (c == '<') out += "<";
else if (c == '>') out += ">";
else if (c == '"') out += """;
else out += c;
}
return out;
}
static String cssColorFrom565(uint16_t color) {
uint8_t r = ((color >> 11) & 0x1F) * 255 / 31;
uint8_t g = ((color >> 5) & 0x3F) * 255 / 63;
uint8_t b = (color & 0x1F) * 255 / 31;
char buf[8];
snprintf(buf, sizeof(buf), "#%02X%02X%02X", r, g, b);
return String(buf);
}
static String accentPreviewCss(const String& key) {
if (key == "standard") return cssColorFrom565(0xEF7D);
if (key == "ice") return cssColorFrom565(0xEFFF);
if (key == "white") return cssColorFrom565(TFT_WHITE);
if (key == "cyan") return cssColorFrom565(0x5EFA);
if (key == "mint") return cssColorFrom565(0x07F0);
if (key == "green") return cssColorFrom565(TFT_GREEN);
if (key == "blue") return cssColorFrom565(0x3D9F);
if (key == "purple") return cssColorFrom565(0xA2F5);
if (key == "pink") return cssColorFrom565(0xF97F);
if (key == "orange") return cssColorFrom565(0xFD20);
if (key == "amber") return cssColorFrom565(0xFEA0);
if (key == "red") return cssColorFrom565(TFT_RED);
return cssColorFrom565(0xEF7D);
}
static String themePreviewCss(const String& key) {
if (key == "slate") return cssColorFrom565(0x08A3);
if (key == "deep") return cssColorFrom565(0x0000);
if (key == "nordic") return cssColorFrom565(0x0864);
if (key == "forest") return cssColorFrom565(0x0208);
if (key == "coffee") return cssColorFrom565(0x18A3);
if (key == "soft") return cssColorFrom565(0x10A2);
if (key == "midnight") return cssColorFrom565(0x0008);
if (key == "graphite") return cssColorFrom565(0x1082);
if (key == "garnet") return cssColorFrom565(0x1004);
if (key == "ochre") return cssColorFrom565(0x20E1);
return cssColorFrom565(0x08A3);
}
static String formatTimerClock(unsigned long totalSec) {
unsigned long minutes = totalSec / 60UL;
unsigned long seconds = totalSec % 60UL;
char buf[10];
snprintf(buf, sizeof(buf), "%02lu:%02lu", minutes, seconds);
return String(buf);
}
static String focusHintText() {
if (focusTimerFinished) return "Tap to reset";
if (focusTimerRunning) return String((focusDurationSec / 60UL)) + " min session";
return "Tap to start";
}
static String formatElapsedText(unsigned long totalSec) {
unsigned long minutes = totalSec / 60UL;
if (minutes == 0) return "< 1 minute elapsed";
if (minutes == 1) return "1 minute elapsed";
return String(minutes) + " minutes elapsed";
}
static String lastSyncText() {
if (lastSyncTime <= 0) return "Sync --:--";
struct tm tmSync;
localtime_r(&lastSyncTime, &tmSync);
return "Sync " + formatClockParts(tmSync, false);
}
static String weekNumberText() {
time_t now = time(nullptr);
struct tm tmNow;
localtime_r(&now, &tmNow);
char buf[4];
strftime(buf, sizeof(buf), "%V", &tmNow);
return String(buf);
}
static String timerDoneCountdownText() {
if (!timerDoneDialogOpen) return "";
unsigned long elapsedMs = millis() - timerDoneDialogStartedMs;
unsigned long remainingMs = (elapsedMs >= TIMER_DONE_DIALOG_MS) ? 0 : (TIMER_DONE_DIALOG_MS - elapsedMs);
unsigned long remainingSec = (remainingMs + 999UL) / 1000UL;
return String("Auto close in ") + String(remainingSec) + "s";
}
static String homeTitleText() {
return buddyNickname.length() > 0 ? buddyNickname : "Deskbuddy";
}
int sanitizeTimerMinutes(int value) {
return constrain(value, 1, 180);
}
void resetFocusTimer() {
focusTimerRunning = false;
focusTimerFinished = false;
focusMenuOpen = false;
timerDoneDialogOpen = false;
focusEndMs = 0;
focusDurationSec = 0;
focusRemainingSec = 0;
cacheFocusTimer = "";
clearHomeSlotCaches();
cacheTimerMenu = "";
cacheTimerDone = "";
cacheTimerDoneCountdown = "";
cacheTimerDoneFlash = "";
}
void startFocusTimer(unsigned long minutes) {
focusDurationSec = minutes * 60UL;
focusRemainingSec = focusDurationSec;
focusEndMs = millis() + (focusDurationSec * 1000UL);
focusTimerRunning = true;
focusTimerFinished = false;
focusMenuOpen = false;
timerDoneDialogOpen = false;
cacheFocusTimer = "";
clearHomeSlotCaches();
cacheTimerMenu = "";
cacheTimerDone = "";
cacheTimerDoneCountdown = "";
cacheTimerDoneFlash = "";
}
void dismissTimerDoneDialog() {
if (!timerDoneDialogOpen) return;
timerDoneDialogOpen = false;
timerDoneDialogStartedMs = 0;
cacheTimerDone = "";
cacheTimerDoneCountdown = "";
cacheTimerDoneFlash = "";
if (!sleepDimmed && !sleepOff) setBacklight(BL_FULL);
pageDirty = true;
}
void openTimerDoneDialog() {
timerDoneDialogOpen = true;
timerDoneDialogStartedMs = millis();
cacheTimerDone = "";
cacheTimerDoneCountdown = "";
wakeDisplay();
}
void updateFocusTimerState() {
if (!focusTimerRunning) return;
unsigned long now = millis();
if ((long)(focusEndMs - now) <= 0) {
focusRemainingSec = 0;
focusTimerRunning = false;
focusTimerFinished = true;
focusMenuOpen = false;
cacheFocusTimer = "";
clearHomeSlotCaches();
cacheTimerMenu = "";
openTimerDoneDialog();
return;
}
unsigned long remainingMs = focusEndMs - now;
unsigned long nextRemainingSec = (remainingMs + 999UL) / 1000UL;
if (nextRemainingSec != focusRemainingSec) {
focusRemainingSec = nextRemainingSec;
cacheFocusTimer = "";
clearHomeSlotCaches();
}
}
void updateTimerDoneDialogState() {
if (!timerDoneDialogOpen) return;
if (millis() - timerDoneDialogStartedMs >= TIMER_DONE_DIALOG_MS) {
dismissTimerDoneDialog();
}
}
void setBacklight(int value) {
value = constrain(value, 0, 255);
analogWrite(BACKLIGHT_PIN, value);
}
void wakeDisplay(bool clearManualMode) {
sleepDimmed = false;
sleepOff = false;
if (clearManualMode) manualDimMode = false;
lastInteractionMs = millis();
setBacklight(BL_FULL);
pageDirty = true;
}
void enterSleepDim() {
if (sleepDimmed || sleepOff || manualDimMode) return;
sleepDimmed = true;
setBacklight(BL_DIM);
}
void enterSleepOff() {
if (sleepOff) return;
sleepOff = true;
sleepDimmed = true;
setBacklight(BL_OFF);
pageDirty = true;
}
void toggleSleepMode() {
if (manualDimMode) {
wakeDisplay();
return;
}
manualDimMode = true;
sleepDimmed = true;
sleepOff = false;
setBacklight(BL_DIM);
pageDirty = true;
}
void handleAutoSleep() {
if (focusMenuOpen || timerDoneDialogOpen) return;
if (sleepIntervalMin <= 0) return;
unsigned long now = millis();
unsigned long dimAfterMs = (unsigned long)sleepIntervalMin * 60UL * 1000UL;
unsigned long offAfterMs = dimAfterMs + ((unsigned long)sleepOffDelaySec * 1000UL);
if (!sleepDimmed && !sleepOff && now - lastInteractionMs > dimAfterMs) {
enterSleepDim();
}
if (sleepDimmed && !sleepOff && now - lastInteractionMs > offAfterMs) {
enterSleepOff();
}
}
// =========================================================
// THEME / SETTINGS
// =========================================================
void applyThemeByKey(const String& accentKey, const String& bgKey) {
if (accentKey == "standard") COL_ACCENT = 0xEF7D;
else if (accentKey == "cyan") COL_ACCENT = 0x5EFA;
else if (accentKey == "ice") COL_ACCENT = 0xEFFF;
else if (accentKey == "white") COL_ACCENT = TFT_WHITE;
else if (accentKey == "mint") COL_ACCENT = 0x07F0;
else if (accentKey == "green") COL_ACCENT = TFT_GREEN;
else if (accentKey == "blue") COL_ACCENT = 0x3D9F;
else if (accentKey == "purple") COL_ACCENT = 0xA2F5;
else if (accentKey == "pink") COL_ACCENT = 0xF97F;
else if (accentKey == "orange") COL_ACCENT = 0xFD20;
else if (accentKey == "amber") COL_ACCENT = 0xFEA0;
else if (accentKey == "red") COL_ACCENT = TFT_RED;
else COL_ACCENT = 0x5EFA;
if (bgKey == "slate") {
COL_BG = 0x08A3; COL_PANEL = 0x1106; COL_PANEL_ALT = 0x18C7; COL_STROKE = 0x31EC;
} else if (bgKey == "deep") {
COL_BG = 0x0000; COL_PANEL = 0x0841; COL_PANEL_ALT = 0x1082; COL_STROKE = 0x2945;
} else if (bgKey == "nordic") {
COL_BG = 0x0864; COL_PANEL = 0x10C6; COL_PANEL_ALT = 0x1908; COL_STROKE = 0x3A2D;
} else if (bgKey == "forest") {
COL_BG = 0x0208; COL_PANEL = 0x0ACB; COL_PANEL_ALT = 0x134D; COL_STROKE = 0x2D72;
} else if (bgKey == "coffee") {
COL_BG = 0x18A3; COL_PANEL = 0x2945; COL_PANEL_ALT = 0x39C7; COL_STROKE = 0x5A89;
} else if (bgKey == "soft") {
COL_BG = 0x10A2; COL_PANEL = 0x1924; COL_PANEL_ALT = 0x2145; COL_STROKE = 0x3A49;
} else if (bgKey == "midnight") {
COL_BG = 0x0008; COL_PANEL = 0x0011; COL_PANEL_ALT = 0x0018; COL_STROKE = 0x3A7F;
} else if (bgKey == "graphite") {
COL_BG = 0x1082; COL_PANEL = 0x18C3; COL_PANEL_ALT = 0x2104; COL_STROKE = 0x4208;
} else if (bgKey == "garnet") {
COL_BG = 0x1004; COL_PANEL = 0x1886; COL_PANEL_ALT = 0x20E8; COL_STROKE = 0x41AC;
} else if (bgKey == "ochre") {
COL_BG = 0x20E1; COL_PANEL = 0x3184; COL_PANEL_ALT = 0x4226; COL_STROKE = 0x632B;
} else {
COL_BG = 0x08A3; COL_PANEL = 0x1106; COL_PANEL_ALT = 0x18C7; COL_STROKE = 0x31EC;
}
}
void applyTextColorByKey(const String& key) {
textColorKey = key;
if (key == "standard") {
COL_TEXT = 0xEF7D; COL_DIM = 0x94B2;
} else if (key == "white") {
COL_TEXT = TFT_WHITE; COL_DIM = 0xBDF7;
} else if (key == "ice") {
COL_TEXT = 0xEFFF; COL_DIM = 0x9D7F;
} else if (key == "mint") {
COL_TEXT = 0x07F0; COL_DIM = 0x05EC;
} else if (key == "orange") {
COL_TEXT = 0xFD20; COL_DIM = 0xBA26;
} else if (key == "amber") {
COL_TEXT = 0xFEA0; COL_DIM = 0xBCE0;
} else if (key == "green") {
COL_TEXT = TFT_GREEN; COL_DIM = 0x86E8;
} else if (key == "cyan") {
COL_TEXT = 0x5EFA; COL_DIM = 0x3D96;
} else if (key == "blue") {
COL_TEXT = 0x3D9F; COL_DIM = 0x22B1;
} else if (key == "purple") {
COL_TEXT = 0xA2F5; COL_DIM = 0x79ED;
} else if (key == "red") {
COL_TEXT = TFT_RED; COL_DIM = 0xB9E7;
} else if (key == "pink") {
COL_TEXT = 0xF97F; COL_DIM = 0xC2F1;
} else {
COL_TEXT = 0xEF7D;
COL_DIM = 0x94B2;
textColorKey = "standard";
}
}
void loadStoredSettings() {
prefs.begin("deskbuddy", false);
String accent = prefs.getString("accent", "cyan");
String bg = prefs.getString("bg", "slate");
String txt = prefs.getString("text", "standard");
notesText = prefs.getString("notes", "No notes yet.");
buddyNickname = prefs.getString("nickname", "");
locationName = prefs.getString("locname", "Berlin");
LAT = prefs.getFloat("lat", 52.5200f);
LNG = prefs.getFloat("lng", 13.4050f);
sleepIntervalMin = prefs.getInt("sleepMin", 10);
unitKey = prefs.getString("units", "metric");
regionFormatKey = prefs.getString("region", "europe");
flashModeEnabled = prefs.getBool("flashMode", false);
wifiEnabled = prefs.getBool("wifiEnabled", true);
BL_FULL = constrain(prefs.getInt("brightness", 255), 30, 255);
contentMode = prefs.getString("contentMode", "quote");
if (contentMode != "quote" && contentMode != "tech" && contentMode != "off") contentMode = "quote";
for (int i = 0; i < HOME_SLOT_COUNT; i++) {
String key = String("homeSlot") + String(i);
homeWidgetSlots[i] = homeWidgetFromKey(prefs.getString(key.c_str(), homeWidgetKey(homeWidgetSlots[i])));
}
for (int i = 0; i < 6; i++) {
String key = String("timer") + String(i);
timerPresetMin[i] = sanitizeTimerMinutes(prefs.getInt(key.c_str(), timerPresetMin[i]));
}
if (unitKey != "metric" && unitKey != "imperial") unitKey = "metric";
if (regionFormatKey != "europe" && regionFormatKey != "us") regionFormatKey = "europe";
buddyNickname.trim();
applyThemeByKey(accent, bg);
applyTextColorByKey(txt);
}
void resetDataCaches() {
tempC = NAN;
precipMm = NAN;
windSpeedMs = NAN;
windDirectionDeg = NAN;
kpIndex = NAN;
sunriseMin = -1;
sunsetMin = -1;
lastSunYmd = -1;
lastWeatherFetch = 0;
lastKpFetch = 0;
lastInsightFetch = 0;
dataDirty = true;
pageDirty = true;
}
// =========================================================
// TOUCH
// =========================================================
bool readTouchXY(int& sx, int& sy) {
if (!ts.touched()) return false;
TS_Point p = ts.getPoint();
if (p.z < 80 || p.z > 4000) return false;
int x = map(p.x, TOUCH_X_MIN, TOUCH_X_MAX, 0, SCREEN_W);
int y = map(p.y, TOUCH_Y_MIN, TOUCH_Y_MAX, 0, SCREEN_H);
x = constrain(x, 0, SCREEN_W - 1);
y = constrain(y, 0, SCREEN_H - 1);
if (TOUCH_SWAP_XY) { int tmp = x; x = y; y = tmp; }
if (TOUCH_FLIP_X) x = (SCREEN_W - 1) - x;
if (TOUCH_FLIP_Y) y = (SCREEN_H - 1) - y;
sx = x;
sy = y;
return true;
}
bool touchNewPress(int& tx, int& ty) {
static bool wasDown = false;
static unsigned long lastPressMs = 0;