-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimerFaces.cpp
More file actions
830 lines (737 loc) · 29 KB
/
Copy pathtimerFaces.cpp
File metadata and controls
830 lines (737 loc) · 29 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
#include "timerFaces.h"
#include <esp_timer.h> // 64-bit monotonic clock - immune to NTP steps
#include "brightness.h"
#include "ClockLogic.h" // tft, worldZones, readTouchPoint, formatHHMM
#include "clockFaces.h" // ClockFace enum, clockFaceName
#include "otaUpdate.h" // otaInProgress - defer the banner during updates
#include "projectConfig.h"
#include "timeFormat.h" // DAY_NAMES - shared weekday table
#include "timerLogic.h"
#include "uiPages.h" // uiScreen, switchToScreen, touchSuppressedUntilRelease
#include "uiScale.h" // scaleUiX/Y - shared 320x240 design scaling
// renderUiPage's "page needs a full repaint" flag (uiPages.cpp); the banner
// cleanup uses it to restore whatever settings/status page it painted over.
extern bool uiPageDrawn;
static timerlogic::Stopwatch stopwatch;
static timerlogic::Countdown countdown;
static bool timersInited = false;
// Monotonic milliseconds since boot, 64-bit (esp_timer_get_time is us). Never
// wraps and never jumps when NTP adjusts the wall clock.
static uint64_t monoMs()
{
return (uint64_t)(esp_timer_get_time() / 1000LL);
}
static bool largeTimerFace()
{
return screenWidth >= 440 && screenHeight >= 300;
}
/*-------- Buttons ----------*/
// Visible controls replace the home screen's invisible touch zones on the
// timer faces. Same rects are used for drawing and hit-testing, so drawn
// buttons and touch targets can never drift apart.
struct TimerBtn
{
int x, y, w, h; // design coordinates (320x240)
};
// Duration row (countdown only, while stopped)
static const TimerBtn BTN_ADJ[4] = {
{8, 114, 72, 30}, {86, 114, 72, 30}, {164, 114, 72, 30}, {242, 114, 70, 30}};
static const char *ADJ_LABELS[4] = {"-30 MIN", "-5 MIN", "+5 MIN", "+30 MIN"};
static const int64_t ADJ_DELTA_MS[4] = {-30LL * 60000LL, -5LL * 60000LL,
5LL * 60000LL, 30LL * 60000LL};
// Primary action (START/PAUSE/RESUME/RESTART) and the deliberately separated
// RESET, so an off-target tap on the primary button cannot wipe the timer.
static const TimerBtn BTN_PRIMARY = {24, 152, 148, 36};
static const TimerBtn BTN_RESET = {200, 152, 96, 36};
// Bottom row: previous face / settings / focus toggle / zoom / next face.
// The first three are the global actions the other faces put on invisible
// corner and center zones; HIDE SEC / SHOW SEC switches the big timer to a
// calm HH:MM that only changes once a minute (persisted:
// projectConfig.timerHideSeconds); ZOOM hides every control and shows just
// the timer as large as the panel fits.
static const TimerBtn BTN_PREV = {6, 198, 40, 38};
static const TimerBtn BTN_SET = {52, 198, 76, 38};
static const TimerBtn BTN_FOCUS = {134, 198, 76, 38};
static const TimerBtn BTN_ZOOM = {216, 198, 52, 38};
static const TimerBtn BTN_NEXT = {274, 198, 40, 38};
// Zoom mode: entered from [ZOOM], exited by a tap anywhere on the glass (the
// buttons are hidden, so the whole panel is the exit control). Session-only
// on purpose - a reboot always comes back with the buttons visible, and no
// flash write is spent on a mode that is one tap away.
static bool timerZoomMode = false;
static bool timerBtnHit(const TimerBtn &b, int tx, int ty)
{
int x = scaleUiX(b.x), y = scaleUiY(b.y), w = scaleUiX(b.w), h = scaleUiY(b.h);
return tx >= x && tx < x + w && ty >= y && ty < y + h;
}
static void drawTimerBtn(const TimerBtn &b, const char *label, uint16_t border,
uint16_t textColor)
{
int x = scaleUiX(b.x), y = scaleUiY(b.y), w = scaleUiX(b.w), h = scaleUiY(b.h);
tft.fillRect(x, y, w, h, clockBackgroundColor); // erase the previous label
tft.drawRoundRect(x, y, w, h, 6, border);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(textColor, clockBackgroundColor);
tft.drawString(label, x + w / 2, y + h / 2);
}
/*-------- Milestone reminder banner ----------*/
// Non-blocking: queued by timersService, painted (and later cleaned up via a
// full repaint) by timerOverlayService from the normal draw loop.
static char overlayText[48] = "";
static unsigned long overlayUntilMs = 0; // millis() deadline; 0 = idle
static unsigned long overlayLastDrawMs = 0;
static bool overlayShown = false; // drawn at least once - needs cleanup
/*-------- Final countdown alarm ----------*/
static bool alarmActive = false;
static bool alarmPhase = false; // false = red/white, true = white/red
static unsigned long alarmLastFlipMs = 0;
static bool alarmDrawn = false;
static void ensureTimersInited()
{
if (timersInited) return;
timersInited = true;
countdown.setDurationMs((int64_t)projectConfig.countdownDefaultMin * 60000LL);
}
static void queueMilestoneBanner(uint32_t minutes, const char *suffix)
{
char span[20];
if (minutes < 60) {
snprintf(span, sizeof(span), "%u MINUTE%s", (unsigned)minutes,
minutes == 1 ? "" : "S");
} else if (minutes % 60 == 0) {
snprintf(span, sizeof(span), "%u HOUR%s", (unsigned)(minutes / 60),
minutes == 60 ? "" : "S");
} else {
snprintf(span, sizeof(span), "%uH %02uM", (unsigned)(minutes / 60),
(unsigned)(minutes % 60));
}
snprintf(overlayText, sizeof(overlayText), "%s %s", span, suffix);
overlayUntilMs = millis() + 1600;
overlayLastDrawMs = 0;
Log.println("Timer reminder: " + String(overlayText));
}
/*-------- Engine service (runs every loop, any screen) ----------*/
void timersService()
{
// Session countdown duration starts from the saved default; on-device and
// web adjustments then stay session-only (never written to flash).
ensureTimersInited();
uint64_t now = monoMs();
int interval = projectConfig.timerReminderMin;
if (countdown.pollFinished(now)) {
Log.println("Countdown finished - raising the alarm until acknowledged");
alarmActive = true;
alarmPhase = false;
alarmDrawn = false;
// A finger already on the glass must not dismiss the alarm instantly.
touchSuppressedUntilRelease = true;
// The final alarm outranks any pending milestone banner.
overlayUntilMs = 0;
overlayShown = false;
}
uint32_t mark = stopwatch.pollMilestoneMinutes(now, interval);
if (mark > 0 && !alarmActive) {
queueMilestoneBanner(mark, "ELAPSED");
}
mark = countdown.pollMilestoneMinutes(now, interval);
if (mark > 0 && !alarmActive) {
queueMilestoneBanner(mark, "REMAINING");
}
}
void timersApplyConfigDefaults()
{
if (!timersInited) return; // first timersService() call picks it up
if (countdown.phase == timerlogic::TIMER_RUNNING ||
countdown.phase == timerlogic::TIMER_PAUSED) {
return; // never yank a live countdown; applies after its reset
}
countdown.setDurationMs((int64_t)projectConfig.countdownDefaultMin * 60000LL);
}
/*-------- Authenticated web controls ----------*/
bool countdownWebStart(uint32_t durationSec)
{
ensureTimersInited();
if (durationSec < 60 || durationSec > 359999) return false;
if (countdown.phase == timerlogic::TIMER_RUNNING ||
countdown.phase == timerlogic::TIMER_PAUSED) return false;
alarmActive = false;
countdown.setDurationMs((int64_t)durationSec * 1000LL);
bool started = countdown.start(monoMs());
if (started) {
char buf[16];
timerlogic::formatHMS(durationSec, buf, sizeof(buf));
Log.println("Countdown started from web (" + String(buf) + ")");
firstDraw = true;
}
return started;
}
bool countdownWebPause()
{
ensureTimersInited();
bool changed = countdown.pause(monoMs());
if (changed) Log.println("Countdown paused from web");
return changed;
}
bool countdownWebResume()
{
ensureTimersInited();
bool changed = countdown.resume(monoMs());
if (changed) Log.println("Countdown resumed from web");
return changed;
}
void countdownWebReset()
{
ensureTimersInited();
alarmActive = false;
overlayUntilMs = 0;
overlayShown = false;
countdown.reset();
firstDraw = true;
Log.println("Countdown reset from web");
}
/*-------- Final alarm (flash until acknowledged) ----------*/
static void drawAlarmFrame()
{
uint16_t bg = alarmPhase ? TFT_WHITE : TFT_RED;
uint16_t fg = alarmPhase ? TFT_RED : TFT_WHITE;
tft.fillScreen(bg);
tft.setTextDatum(MC_DATUM);
tft.setTextFont(4);
tft.setTextSize(2);
tft.setTextColor(fg, bg);
tft.drawString("TIME'S UP", screenWidth / 2, scaleUiY(66));
tft.setTextFont(7);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.drawString("00:00:00", screenWidth / 2, scaleUiY(102));
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.drawString("TAP TO DISMISS", screenWidth / 2, scaleUiY(190));
}
bool timerAlarmService()
{
if (!alarmActive) return false;
// Never fight an in-progress firmware update for the screen (or write to
// SPIFFS while OTA streams to flash). Keep alarmActive set - the alarm
// raises normally once the update finishes or fails; a completed update
// reboots and clears it anyway.
if (otaInProgress) return false;
TouchPoint t = readTouchPoint();
bool down = (t.zRaw > 800);
if (!down) {
touchSuppressedUntilRelease = false;
} else if (!touchSuppressedUntilRelease) {
// Any tap acknowledges the alarm; consume it so it cannot click
// through onto whatever page is drawn next.
alarmActive = false;
Log.println("Countdown alarm acknowledged");
bool dirty = false;
if (projectConfig.clockFace != FACE_COUNTDOWN) {
projectConfig.clockFace = FACE_COUNTDOWN;
dirty = true;
}
if (projectConfig.brightness != backlightLevel) {
// A brightness gesture may have been cut short by the alarm;
// fold its pending save in instead of dropping it.
projectConfig.brightness = backlightLevel;
dirty = true;
}
if (dirty) projectConfig.saveConfigFile();
brightnessBarVisible = false;
// Always land on the home screen showing the countdown face in its
// FINISHED state (documented behavior, predictable from any page).
switchToScreen(SCREEN_HOME);
return true;
}
unsigned long nowMs = millis();
if (!alarmDrawn || nowMs - alarmLastFlipMs >= 500) {
if (alarmDrawn) alarmPhase = !alarmPhase;
alarmLastFlipMs = nowMs;
alarmDrawn = true;
drawAlarmFrame();
}
return true;
}
/*-------- Milestone banner overlay ----------*/
void timerOverlayService()
{
if (overlayUntilMs == 0) return;
unsigned long nowMs = millis();
if ((long)(nowMs - overlayUntilMs) >= 0) {
// Expired: restore whatever screen the banner painted over.
overlayUntilMs = 0;
if (overlayShown) {
overlayShown = false;
if (uiScreen == SCREEN_HOME) {
invalidateHomeScreen(false);
} else {
uiPageDrawn = false;
}
}
return;
}
// Defer (don't drop) while another overlay/process owns the display; the
// touch calibration screen is never painted over at all.
if (uiScreen == SCREEN_TOUCH_CAL || otaInProgress || brightnessBarVisible) {
return;
}
// Repaint on a short cadence so the per-second face updates underneath
// can't chew a corner off the banner while it is up.
if (!overlayShown || nowMs - overlayLastDrawMs >= 250) {
overlayLastDrawMs = nowMs;
overlayShown = true;
int h = scaleUiY(24);
tft.fillRect(0, 0, screenWidth, h, TFT_ORANGE);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(MC_DATUM);
tft.setTextColor(TFT_BLACK, TFT_ORANGE);
tft.drawString(overlayText, screenWidth / 2, h / 2);
}
}
/*-------- Face rendering ----------*/
// Called every loop while the face is active (drawAlternateFace routes the
// timer faces around its once-per-minute gating). Only regions whose content
// actually changed are repainted, so the ~50Hz polls cost nothing between
// second ticks and the display never flickers.
static int cachedPhase = -1;
static char cachedBig[16] = "";
static uint16_t cachedBigColor = 0;
static uint8_t cachedBigFont = 0;
static int cachedHeaderMinute = -1;
static void resetRenderCache()
{
cachedPhase = -1;
cachedBig[0] = '\0';
cachedBigColor = 0;
cachedBigFont = 0;
cachedHeaderMinute = -1;
}
static uint16_t phaseColor(timerlogic::TimerPhase phase)
{
switch (phase) {
case timerlogic::TIMER_RUNNING: return TFT_GREEN;
case timerlogic::TIMER_PAUSED: return TFT_YELLOW;
case timerlogic::TIMER_FINISHED: return TFT_RED;
default: return TFT_LIGHTGREY;
}
}
// Header: home-zone clock (12/24h preference), weekday + date (date-format
// preference) and the face title. Repainted once per minute.
static void drawTimerHeader(bool full, const char *title)
{
time_t local = worldZones[0].tz.now();
if (!full && minute(local) == cachedHeaderMinute) return;
cachedHeaderMinute = minute(local);
tft.fillRect(0, 0, screenWidth, scaleUiY(28), clockBackgroundColor);
bool pm;
String hhmm = formatHHMM(local, pm);
if (!SHOW_24HOUR) hhmm += pm ? " PM" : " AM";
tft.setTextFont(4);
tft.setTextSize(1);
tft.setTextDatum(TL_DATUM);
tft.setTextColor(getDayNightColor(worldZones[0]), clockBackgroundColor);
tft.drawString(hhmm, scaleUiX(8), 2);
char dateBuf[8];
if (NOT_US_DATE) {
sprintf(dateBuf, "%02d/%02d", day(local), month(local));
} else {
sprintf(dateBuf, "%02d/%02d", month(local), day(local));
}
tft.setTextFont(2);
tft.setTextDatum(TR_DATUM);
tft.setTextColor(TFT_LIGHTGREY, clockBackgroundColor);
tft.drawString(String(DAY_NAMES[weekday(local)]) + " " + dateBuf,
screenWidth - scaleUiX(6), 6);
tft.setTextFont(1);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString(title, screenWidth / 2, scaleUiY(10));
}
static void drawStateLine(timerlogic::TimerPhase phase)
{
bool big = largeTimerFace();
tft.setTextFont(big ? 4 : 2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(phaseColor(phase), clockBackgroundColor);
tft.setTextPadding(scaleUiX(200));
tft.drawString(timerlogic::timerPhaseName(phase), screenWidth / 2, scaleUiY(34));
tft.setTextPadding(0);
}
// The big HH:MM:SS. Font 7 (7-segment, digits + colon only) at the largest
// size that fits; hour counts past 99 simply widen the string ("125:04:09" -
// never wrapped), falling back to Font 4 in the extreme case where even the
// 7-segment rendering no longer fits the panel.
static void drawBigTime(const char *text, uint16_t color)
{
int maxW = screenWidth - scaleUiX(8);
// Font 7 stays at size 1 on both panels: its 48px glyphs are the tallest
// that fit the band between the state line and the button rows (the band
// scales to 72px on the 4" panel; size 2 would be 96px and collide).
tft.setTextFont(7);
tft.setTextSize(1);
uint8_t fontKey = 7;
if (tft.textWidth(text) > maxW) {
tft.setTextFont(4);
tft.setTextSize(2);
fontKey = 4;
}
int y = scaleUiY(58);
if (fontKey != cachedBigFont) {
// Font or size changed: glyph heights differ, so clear the whole
// band once instead of relying on padding.
cachedBigFont = fontKey;
tft.fillRect(0, y, screenWidth, scaleUiY(112) - y, clockBackgroundColor);
}
tft.setTextDatum(TC_DATUM);
tft.setTextColor(color, clockBackgroundColor);
tft.setTextPadding(maxW);
tft.drawString(text, screenWidth / 2, y);
tft.setTextPadding(0);
}
// Time string + color for the big display, shared by the normal and zoom
// layouts. Focus mode (timerHideSeconds) drops both to HH:MM.
static uint16_t formatBigTimer(bool isCountdown, uint64_t now,
timerlogic::TimerPhase phase, char *buf,
size_t len)
{
bool hideSec = projectConfig.timerHideSeconds;
if (isCountdown) {
uint64_t rem = countdown.remainingMs(now);
if (hideSec) {
// Ceil to whole minutes: full duration at start, and never 00:00
// while any time is actually left.
timerlogic::formatHM(timerlogic::displayMinutesRemaining(rem), buf, len);
} else {
// Ceil to whole seconds: shows the full duration at start and
// reaches exactly 00:00:00 only when the countdown really is over.
timerlogic::formatHMS((rem + 999ULL) / 1000ULL, buf, len);
}
return (phase == timerlogic::TIMER_FINISHED) ? TFT_RED
: (phase == timerlogic::TIMER_RUNNING && rem < 60000ULL) ? TFT_ORANGE
: TFT_WHITE;
}
uint64_t elapsed = stopwatch.elapsedMs(now);
if (hideSec) {
timerlogic::formatHM(timerlogic::displayMinutesElapsed(elapsed), buf, len);
} else {
timerlogic::formatHMS(elapsed / 1000ULL, buf, len);
}
return TFT_WHITE;
}
// Zoom-mode counterpart of drawBigTime: with the whole panel free, try Font 7
// doubled (96px digits) first. "00:00:00" is 216px wide in Font 7, so the
// doubled rendering fits HH:MM:SS on the 480px-wide panel and the focus-mode
// HH:MM on every panel; HH:MM:SS on the 320px panel keeps the regular 48px
// digits, just decluttered and centered (combine ZOOM with HIDE SEC there for
// the doubled digits).
static void drawZoomTime(const char *text, uint16_t color)
{
int maxW = screenWidth - scaleUiX(8);
tft.setTextFont(7);
tft.setTextSize(2);
uint8_t fontKey = 72;
if (tft.textWidth(text) > maxW) {
tft.setTextSize(1);
fontKey = 71;
if (tft.textWidth(text) > maxW) {
tft.setTextFont(4);
tft.setTextSize(2);
fontKey = 42;
}
}
int y = (screenHeight - tft.fontHeight()) / 2;
if (fontKey != cachedBigFont) {
// Font or size changed: glyph heights differ, so clear the whole band
// between the state line and the exit hint instead of relying on
// padding.
cachedBigFont = fontKey;
tft.fillRect(0, scaleUiY(40), screenWidth, scaleUiY(196) - scaleUiY(40),
clockBackgroundColor);
}
tft.setTextDatum(TC_DATUM);
tft.setTextColor(color, clockBackgroundColor);
tft.setTextPadding(maxW);
tft.drawString(text, screenWidth / 2, y);
tft.setTextPadding(0);
}
// Zoom layout: face title and phase up top, the timer vertically centered and
// as big as it fits, an exit hint at the bottom - no buttons, no header.
static void renderZoomFace(bool full, bool isCountdown)
{
uint64_t now = monoMs();
timerlogic::TimerPhase phase = isCountdown ? countdown.phase : stopwatch.phase;
if (full) {
tft.fillScreen(clockBackgroundColor);
resetRenderCache();
tft.setTextFont(1);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString(isCountdown ? "COUNTDOWN" : "STOPWATCH",
screenWidth / 2, scaleUiY(8));
tft.drawString("TAP ANYWHERE TO EXIT", screenWidth / 2,
screenHeight - scaleUiY(16));
}
if (full || (int)phase != cachedPhase) {
cachedPhase = (int)phase;
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(phaseColor(phase), clockBackgroundColor);
tft.setTextPadding(scaleUiX(200));
tft.drawString(timerlogic::timerPhaseName(phase), screenWidth / 2,
scaleUiY(20));
tft.setTextPadding(0);
}
char buf[16];
uint16_t color = formatBigTimer(isCountdown, now, phase, buf, sizeof(buf));
if (full || color != cachedBigColor || strcmp(buf, cachedBig) != 0) {
strncpy(cachedBig, buf, sizeof(cachedBig) - 1);
cachedBig[sizeof(cachedBig) - 1] = '\0';
cachedBigColor = color;
drawZoomTime(buf, color);
}
}
static void drawPrimaryButton(timerlogic::TimerPhase phase)
{
const char *label;
uint16_t border;
switch (phase) {
case timerlogic::TIMER_RUNNING:
label = "PAUSE";
border = TFT_YELLOW;
break;
case timerlogic::TIMER_PAUSED:
label = "RESUME";
border = TFT_GREEN;
break;
case timerlogic::TIMER_FINISHED:
label = "RESTART";
border = TFT_GREEN;
break;
default:
label = "START";
border = TFT_GREEN;
break;
}
drawTimerBtn(BTN_PRIMARY, label, border, TFT_WHITE);
}
// Countdown duration row: +/- buttons while stopped, the configured total
// (read-only) while running or paused.
static void drawDurationRow(timerlogic::TimerPhase phase)
{
tft.fillRect(0, scaleUiY(112), screenWidth, scaleUiY(148) - scaleUiY(112), clockBackgroundColor);
if (phase == timerlogic::TIMER_RUNNING || phase == timerlogic::TIMER_PAUSED) {
char buf[16];
timerlogic::formatHMS(countdown.durationMs / 1000ULL, buf, sizeof(buf));
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString("TOTAL " + String(buf), screenWidth / 2, scaleUiY(122));
} else {
for (int i = 0; i < 4; i++) {
drawTimerBtn(BTN_ADJ[i], ADJ_LABELS[i], TFT_CYAN, TFT_WHITE);
}
}
}
// Shared frame for both faces; isCountdown selects the engine and the
// duration row.
static void renderTimerFace(bool full, bool isCountdown)
{
if (timerZoomMode) {
renderZoomFace(full, isCountdown);
return;
}
uint64_t now = monoMs();
timerlogic::TimerPhase phase = isCountdown ? countdown.phase : stopwatch.phase;
if (full) {
tft.fillScreen(clockBackgroundColor);
resetRenderCache();
tft.drawFastHLine(scaleUiX(10), scaleUiY(30), scaleUiX(300), TFT_DARKGREY);
drawTimerBtn(BTN_RESET, "RESET", TFT_RED, TFT_WHITE);
drawTimerBtn(BTN_PREV, "<", TFT_CYAN, TFT_WHITE);
drawTimerBtn(BTN_SET, "SETTINGS", TFT_CYAN, TFT_WHITE);
// Green border while focus mode is on, so the calmer display is
// recognizably a mode and not a stalled clock.
drawTimerBtn(BTN_FOCUS,
projectConfig.timerHideSeconds ? "SHOW SEC" : "HIDE SEC",
projectConfig.timerHideSeconds ? TFT_GREEN : TFT_CYAN,
TFT_WHITE);
drawTimerBtn(BTN_ZOOM, "ZOOM", TFT_CYAN, TFT_WHITE);
drawTimerBtn(BTN_NEXT, ">", TFT_CYAN, TFT_WHITE);
if (!isCountdown && timerlogic::reminderIntervalValid(projectConfig.timerReminderMin)) {
// The stopwatch has no duration row; use the slot for a reminder
// hint so the interval is discoverable on the device.
tft.setTextFont(1);
tft.setTextSize(1);
tft.setTextDatum(TC_DATUM);
tft.setTextColor(TFT_DARKGREY, clockBackgroundColor);
tft.drawString("REMINDER EVERY " + String(projectConfig.timerReminderMin) +
" MIN",
screenWidth / 2, scaleUiY(124));
}
}
drawTimerHeader(full, isCountdown ? "COUNTDOWN" : "STOPWATCH");
if (full || (int)phase != cachedPhase) {
cachedPhase = (int)phase;
drawStateLine(phase);
drawPrimaryButton(phase);
if (isCountdown) drawDurationRow(phase);
}
// Focus mode (timerHideSeconds): HH:MM only, so the big display changes
// just once a minute instead of ticking every second - nothing on the
// face keeps moving to pull the eye away from work.
char buf[16];
uint16_t color = formatBigTimer(isCountdown, now, phase, buf, sizeof(buf));
if (full || color != cachedBigColor || strcmp(buf, cachedBig) != 0) {
strncpy(cachedBig, buf, sizeof(cachedBig) - 1);
cachedBig[sizeof(cachedBig) - 1] = '\0';
cachedBigColor = color;
drawBigTime(buf, color);
}
}
void renderStopwatchFace(bool full)
{
renderTimerFace(full, false);
}
void renderCountdownFace(bool full)
{
renderTimerFace(full, true);
}
/*-------- Touch ----------*/
void timerFaceHandleTouch(int x, int y)
{
bool isCountdown = (projectConfig.clockFace == FACE_COUNTDOWN);
uint64_t now = monoMs();
char buf[16];
if (timerZoomMode) {
// Zoom mode hides every control (brightness zones included), so the
// whole glass is the exit button.
timerZoomMode = false;
Log.println("Timer face - zoom off, controls restored");
firstDraw = true;
touchSuppressedUntilRelease = true;
return;
}
if (timerBtnHit(BTN_SET, x, y)) {
Log.println("Timer face - opening settings page");
switchToScreen(SCREEN_SETTINGS); // suppresses touch until release
return;
}
// Face cycling from the [<] / [>] buttons - same shared behavior as the
// corner taps on the passive faces (persist + full repaint + suppress
// until release).
if (timerBtnHit(BTN_PREV, x, y)) {
cycleClockFace(FACE_COUNT - 1, "Timer face button");
return;
}
if (timerBtnHit(BTN_NEXT, x, y)) {
cycleClockFace(1, "Timer face button");
return;
}
if (timerBtnHit(BTN_FOCUS, x, y)) {
// Toggle the calm HH:MM display. Persisted (a deliberate, discrete
// tap - fine for flash), applied to both timer faces at once.
projectConfig.timerHideSeconds = !projectConfig.timerHideSeconds;
projectConfig.saveConfigFile();
Log.println(projectConfig.timerHideSeconds
? "Timer faces: seconds hidden (focus mode)"
: "Timer faces: seconds shown");
firstDraw = true; // repaint the face with the new display + button label
touchSuppressedUntilRelease = true;
return;
}
if (timerBtnHit(BTN_ZOOM, x, y)) {
timerZoomMode = true;
Log.println("Timer face - zoom on (tap anywhere to exit)");
firstDraw = true; // repaint as the buttonless zoom layout
touchSuppressedUntilRelease = true;
return;
}
if (timerBtnHit(BTN_PRIMARY, x, y)) {
touchSuppressedUntilRelease = true;
if (isCountdown) {
if (countdown.start(now)) {
timerlogic::formatHMS(countdown.durationMs / 1000ULL, buf, sizeof(buf));
Log.println("Countdown started (" + String(buf) + ")");
} else if (countdown.pause(now)) {
Log.println("Countdown paused");
} else if (countdown.resume(now)) {
Log.println("Countdown resumed");
}
} else {
if (stopwatch.start(now)) {
Log.println("Stopwatch started");
} else if (stopwatch.pause(now)) {
timerlogic::formatHMS(stopwatch.elapsedMs(now) / 1000ULL, buf, sizeof(buf));
Log.println("Stopwatch paused at " + String(buf));
} else if (stopwatch.resume(now)) {
Log.println("Stopwatch resumed");
}
}
return;
}
if (timerBtnHit(BTN_RESET, x, y)) {
touchSuppressedUntilRelease = true;
if (isCountdown) {
countdown.reset(); // back to READY at the configured duration
Log.println("Countdown reset");
} else {
stopwatch.reset();
Log.println("Stopwatch reset");
}
return;
}
if (isCountdown && countdown.phase != timerlogic::TIMER_RUNNING &&
countdown.phase != timerlogic::TIMER_PAUSED) {
for (int i = 0; i < 4; i++) {
if (timerBtnHit(BTN_ADJ[i], x, y)) {
// Session-only adjustment - deliberately NOT saved to flash;
// the persisted default changes only from the web settings.
countdown.adjustDurationMs(ADJ_DELTA_MS[i]);
touchSuppressedUntilRelease = true;
return;
}
}
}
// Match the other home faces: unused space in the left/right thirds dims
// or brightens the backlight. Visible timer buttons above take priority.
// A held finger repeats in small steps; handleTouch() owns overlay timeout
// and the single flash write after the gesture ends.
int leftThird = screenWidth / 3;
int rightThird = (screenWidth * 2) / 3;
if (x < leftThird || x > rightThird) {
brightnessGestureStep(x < leftThird ? -1 : +1);
}
}
/*-------- Status (/api/status) ----------*/
const char *stopwatchStateName()
{
return timerlogic::timerPhaseName(stopwatch.phase);
}
uint32_t stopwatchElapsedSec()
{
return (uint32_t)(stopwatch.elapsedMs(monoMs()) / 1000ULL);
}
const char *countdownStateName()
{
ensureTimersInited();
return timerlogic::timerPhaseName(countdown.phase);
}
uint32_t countdownConfiguredSec()
{
ensureTimersInited();
return (uint32_t)(countdown.durationMs / 1000ULL);
}
uint32_t countdownRemainingSec()
{
ensureTimersInited();
return (uint32_t)((countdown.remainingMs(monoMs()) + 999ULL) / 1000ULL);
}