-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathmain.cpp
More file actions
673 lines (600 loc) · 29 KB
/
Copy pathmain.cpp
File metadata and controls
673 lines (600 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
#include <Arduino.h>
#include <BoardConfig.h>
#include <Epub.h>
#include <FontCacheManager.h>
#include <FontDecompressor.h>
#include <GfxRenderer.h>
#include <HalClock.h>
#include <HalDisplay.h>
#include <HalGPIO.h>
#include <HalPowerManager.h>
#include <HalStorage.h>
#include <HalSystem.h>
#include <HalTiltSensor.h>
#include <I18n.h>
#include <Logging.h>
#include <SPI.h>
#include <WiFi.h>
#include <builtinFonts/all.h>
#include <cstring>
#include "CrossPointSettings.h"
#include "CrossPointState.h"
#include "KOReaderCredentialStore.h"
#include "MappedInputManager.h"
#include "OpdsServerStore.h"
#include "RecentBooksStore.h"
#include "SdCardFontSystem.h"
#include "activities/Activity.h"
#include "activities/ActivityManager.h"
#include "activities/settings/SdFirmwareUpdateActivity.h"
#include "components/UITheme.h"
#include "fontIds.h"
#include "images/LoadingIcon.h"
#include "util/ButtonNavigator.h"
#include "util/ScreenshotUtil.h"
GfxRenderer renderer(display);
MappedInputManager mappedInputManager(gpio, renderer);
ActivityManager activityManager(renderer, mappedInputManager);
FontDecompressor fontDecompressor;
SdCardFontSystem sdFontSystem;
FontCacheManager fontCacheManager(renderer.getFontMap(), renderer.getSdCardFonts());
static unsigned long allowSleepAt = 0;
// A wake hold must never become an in-app power-button action. Boot may continue
// while the button is held; swallow the one release that ends that wake gesture.
static bool wakePowerReleasePending = false;
// Fonts
EpdFont notoserif14RegularFont(¬oserif_14_regular);
EpdFont notoserif14BoldFont(¬oserif_14_bold);
EpdFont notoserif14ItalicFont(¬oserif_14_italic);
EpdFont notoserif14BoldItalicFont(¬oserif_14_bolditalic);
EpdFontFamily notoserif14FontFamily(¬oserif14RegularFont, ¬oserif14BoldFont, ¬oserif14ItalicFont,
¬oserif14BoldItalicFont);
#ifndef OMIT_FONTS
EpdFont notoserif12RegularFont(¬oserif_12_regular);
EpdFont notoserif12BoldFont(¬oserif_12_bold);
EpdFont notoserif12ItalicFont(¬oserif_12_italic);
EpdFont notoserif12BoldItalicFont(¬oserif_12_bolditalic);
EpdFontFamily notoserif12FontFamily(¬oserif12RegularFont, ¬oserif12BoldFont, ¬oserif12ItalicFont,
¬oserif12BoldItalicFont);
EpdFont notoserif16RegularFont(¬oserif_16_regular);
EpdFont notoserif16BoldFont(¬oserif_16_bold);
EpdFont notoserif16ItalicFont(¬oserif_16_italic);
EpdFont notoserif16BoldItalicFont(¬oserif_16_bolditalic);
EpdFontFamily notoserif16FontFamily(¬oserif16RegularFont, ¬oserif16BoldFont, ¬oserif16ItalicFont,
¬oserif16BoldItalicFont);
EpdFont notoserif18RegularFont(¬oserif_18_regular);
EpdFont notoserif18BoldFont(¬oserif_18_bold);
EpdFont notoserif18ItalicFont(¬oserif_18_italic);
EpdFont notoserif18BoldItalicFont(¬oserif_18_bolditalic);
EpdFontFamily notoserif18FontFamily(¬oserif18RegularFont, ¬oserif18BoldFont, ¬oserif18ItalicFont,
¬oserif18BoldItalicFont);
EpdFont notosans12RegularFont(¬osans_12_regular);
EpdFont notosans12BoldFont(¬osans_12_bold);
EpdFont notosans12ItalicFont(¬osans_12_italic);
EpdFont notosans12BoldItalicFont(¬osans_12_bolditalic);
EpdFontFamily notosans12FontFamily(¬osans12RegularFont, ¬osans12BoldFont, ¬osans12ItalicFont,
¬osans12BoldItalicFont);
EpdFont notosans14RegularFont(¬osans_14_regular);
EpdFont notosans14BoldFont(¬osans_14_bold);
EpdFont notosans14ItalicFont(¬osans_14_italic);
EpdFont notosans14BoldItalicFont(¬osans_14_bolditalic);
EpdFontFamily notosans14FontFamily(¬osans14RegularFont, ¬osans14BoldFont, ¬osans14ItalicFont,
¬osans14BoldItalicFont);
EpdFont notosans16RegularFont(¬osans_16_regular);
EpdFont notosans16BoldFont(¬osans_16_bold);
EpdFont notosans16ItalicFont(¬osans_16_italic);
EpdFont notosans16BoldItalicFont(¬osans_16_bolditalic);
EpdFontFamily notosans16FontFamily(¬osans16RegularFont, ¬osans16BoldFont, ¬osans16ItalicFont,
¬osans16BoldItalicFont);
EpdFont notosans18RegularFont(¬osans_18_regular);
EpdFont notosans18BoldFont(¬osans_18_bold);
EpdFont notosans18ItalicFont(¬osans_18_italic);
EpdFont notosans18BoldItalicFont(¬osans_18_bolditalic);
EpdFontFamily notosans18FontFamily(¬osans18RegularFont, ¬osans18BoldFont, ¬osans18ItalicFont,
¬osans18BoldItalicFont);
#endif // OMIT_FONTS
EpdFont smallFont(¬osans_8_regular);
EpdFontFamily smallFontFamily(&smallFont);
EpdFont ui10RegularFont(&ubuntu_10_regular);
EpdFont ui10BoldFont(&ubuntu_10_bold);
EpdFontFamily ui10FontFamily(&ui10RegularFont, &ui10BoldFont);
EpdFont ui12RegularFont(&ubuntu_12_regular);
EpdFont ui12BoldFont(&ubuntu_12_bold);
EpdFontFamily ui12FontFamily(&ui12RegularFont, &ui12BoldFont);
// measurement of power button press duration calibration value
unsigned long t1 = 0;
unsigned long t2 = 0;
// Definitions for SilentRestart.h. RTC_NOINIT survives ESP.restart() but not power loss.
RTC_NOINIT_ATTR uint32_t silentRebootMagic;
RTC_NOINIT_ATTR uint32_t silentRebootTarget;
constexpr uint32_t SILENT_REBOOT_MAGIC = 0xC1EAB007;
constexpr uint32_t SILENT_REBOOT_TARGET_HOME = 0;
constexpr uint32_t SILENT_REBOOT_TARGET_READER = 1;
// How the device is coming back to life, resolved once at boot. Both resume
// flows suppress the splash and leave the panel holding its pre-boot frame; a
// plain boot shows the splash. See setup() for the resolution.
enum class BootResume : uint8_t {
Splash, // cold boot, flash, panic, or plain reboot
Silent, // heap-defrag ESP.restart() (RTC flag; lost on power loss)
SplashlessWake, // wake from deep sleep with the splash suppressed by the SD flag
};
// Latched true once enterDeepSleep() commits to sleeping, before it tears down
// the current activity. WiFi activities call silentRestart() in onExit() to
// clear heap fragmentation on the way out, but deep sleep is a full chip reset
// on wake and already clears the heap, so rebooting here would just power the
// device back up against the user's sleep gesture. Never cleared:
// startDeepSleep() does not return, so a set latch only ends at the wakeup reset.
static bool deepSleepInProgress = false;
void silentRestart() {
if (deepSleepInProgress) return; // sleeping supersedes the heap-defrag reboot
silentRebootTarget = SILENT_REBOOT_TARGET_HOME;
silentRebootMagic = SILENT_REBOOT_MAGIC;
LOG_DBG("MAIN", "Silent restart (target=home)");
// E-ink retains the previous frame until Home's first paint lands (~2-3s).
// Without an overlay, users don't see the reboot and fire input through to
// Home. Select on the default selectorIndex=0 then opens the most-recent
// book, looking like a trampoline back to the reader they just exited.
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
delay(50);
ESP.restart();
}
void silentRestartToReader() {
if (deepSleepInProgress) return; // sleeping supersedes the heap-defrag reboot
silentRebootTarget = SILENT_REBOOT_TARGET_READER;
silentRebootMagic = SILENT_REBOOT_MAGIC;
LOG_DBG("MAIN", "Silent restart (target=reader)");
GUI.drawPopup(renderer, tr(STR_LOADING_POPUP));
delay(50);
ESP.restart();
}
constexpr char SLEEP_FRAME_FILE[] = "/.crosspoint/sleep_frame.bin";
static void saveSleepFrameBuffer() {
HalFile file;
if (!Storage.openFileForWrite("SLP", SLEEP_FRAME_FILE, file)) return;
file.write(renderer.getFrameBuffer(), renderer.getBufferSize());
file.close();
}
static bool loadSleepFrameBuffer() {
HalFile file;
if (!Storage.openFileForRead("SLP", SLEEP_FRAME_FILE, file)) return false;
const size_t bufferSize = display.getBufferSize();
const size_t bytesRead = file.read(display.getFrameBuffer(), bufferSize);
file.close();
if (bytesRead != bufferSize) {
Storage.remove(SLEEP_FRAME_FILE);
return false;
}
Storage.remove(SLEEP_FRAME_FILE);
return true;
}
// Enter deep sleep mode
void enterDeepSleep(bool fromTimeout = false) {
HalPowerManager::Lock powerLock; // Ensure we are at normal CPU frequency for sleep preparation
APP_STATE.lastSleepFromReader = activityManager.isReaderActivity();
const bool isQuickResumeSleep =
SETTINGS.sleepScreen == CrossPointSettings::SLEEP_SCREEN_MODE::QUICK_RESUME ||
(fromTimeout &&
SETTINGS.quickResumeSleepScreen == CrossPointSettings::QUICK_RESUME_SLEEP_SCREEN::QUICK_RESUME_AFTER_TIMEOUT);
// Every sleep mode leaves a complete retained frame on the e-ink panel. Keep
// it visible until the first useful reader or home paint replaces it.
APP_STATE.showBootScreen = false;
APP_STATE.saveToFile();
// Commit to sleeping before goToSleep() runs the outgoing activity's onExit():
// a WiFi activity would otherwise silentRestart() here and reboot instead.
deepSleepInProgress = true;
activityManager.goToSleep(fromTimeout);
if (isQuickResumeSleep) {
saveSleepFrameBuffer();
} else if (Storage.exists(SLEEP_FRAME_FILE)) {
// A stale Quick Resume frame must not replace the selected sleep screen during wake.
Storage.remove(SLEEP_FRAME_FILE);
}
// Tear down WiFi so the modem power domain isn't held alive across deep sleep.
// Wake from deep sleep is effectively a chip reset, so no state needs to survive.
if (WiFi.getMode() != WIFI_MODE_NULL) {
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
halTiltSensor.deepSleep();
display.deepSleep();
LOG_DBG("MAIN", "Entering deep sleep");
powerManager.startDeepSleep(gpio);
}
void setupDisplayAndFonts(bool seamless = false) {
display.begin(seamless);
renderer.begin();
activityManager.begin();
LOG_DBG("MAIN", "Display initialized");
// Initialize font decompressor for compressed reader fonts
if (!fontDecompressor.init()) {
LOG_ERR("MAIN", "Font decompressor init failed");
}
fontCacheManager.setFontDecompressor(&fontDecompressor);
renderer.setFontCacheManager(&fontCacheManager);
renderer.insertFont(NOTOSERIF_14_FONT_ID, notoserif14FontFamily);
#ifndef OMIT_FONTS
renderer.insertFont(NOTOSERIF_12_FONT_ID, notoserif12FontFamily);
renderer.insertFont(NOTOSERIF_16_FONT_ID, notoserif16FontFamily);
renderer.insertFont(NOTOSERIF_18_FONT_ID, notoserif18FontFamily);
renderer.insertFont(NOTOSANS_12_FONT_ID, notosans12FontFamily);
renderer.insertFont(NOTOSANS_14_FONT_ID, notosans14FontFamily);
renderer.insertFont(NOTOSANS_16_FONT_ID, notosans16FontFamily);
renderer.insertFont(NOTOSANS_18_FONT_ID, notosans18FontFamily);
#endif // OMIT_FONTS
renderer.insertFont(UI_10_FONT_ID, ui10FontFamily);
renderer.insertFont(UI_12_FONT_ID, ui12FontFamily);
renderer.insertFont(SMALL_FONT_ID, smallFontFamily);
// Discover and load SD card fonts
sdFontSystem.begin(renderer);
LOG_DBG("MAIN", "Fonts setup");
}
void setup() {
BoardConfig::holdPowerRails();
t1 = millis();
#ifdef ENABLE_SERIAL_LOG
// Earliest possible Serial setup. The 250 ms stall before begin() lets the
// USB Serial/JTAG peripheral finish power-on and lets the host complete USB
// enumeration before we touch the CDC state — otherwise cold boot races
// and the host has to be physically replugged for logs to flow. Warm reboot
// worked without the delay because USB was already enumerated.
delay(250);
Serial.begin(115200);
#if LOG_SERIAL_HAS_TX_TIMEOUT
logSerial.setTxTimeoutMs(1); // This is a load-bearing 1. Do not modify.
#endif
#endif
HalSystem::begin();
// checkPanic() clears the watchdog capture marker after a successful SD
// dump, so retain the boot classification for the later activity route.
const bool rebootedFromPanic = HalSystem::isRebootFromPanic();
// Read-and-clear so a panic later in setup() doesn't loop into silent reboot.
// Bound the target range too — RTC_NOINIT memory is uninitialized on cold boot.
const bool isSilentReboot = (silentRebootMagic == SILENT_REBOOT_MAGIC);
const uint32_t snapshotTarget =
(isSilentReboot && silentRebootTarget <= SILENT_REBOOT_TARGET_READER) ? silentRebootTarget : 0;
silentRebootMagic = 0;
silentRebootTarget = 0;
gpio.begin();
powerManager.begin();
halTiltSensor.begin();
halClock.begin();
// First of two USB samples (second below, before display bring-up): the SOF
// verdict needs two samples a frame apart, and it must be settled before the
// first refresh — the boot paint's light-sleep slices would otherwise kill a
// live CDC link whenever the charge-based check reads false (full battery,
// data-only cable). See HalGPIO::pollUsbState().
gpio.pollUsbState();
// Light-sleep through the render task's e-ink BUSY wait (0.3-2 s of pure pin
// polling) in short slices, waking exactly on the BUSY pin's completion level
// (falls back to plain polling when WiFi/USB blocks light sleep)
display.setBusyWaitSliceHook(
[](int8_t busyPin, uint8_t busyLevel) { return powerManager.onEinkBusyWaitSlice(busyPin, busyLevel); });
LOG_INF("MAIN", "Hardware detect: %s", gpio.deviceIsX3() ? "X3" : "X4");
// SD Card Initialization
// We need 6 open files concurrently when parsing a new chapter
if (!Storage.begin()) {
LOG_ERR("MAIN", "SD card initialization failed");
gpio.pollUsbState(); // settle the USB verdict before the error paint (see above)
setupDisplayAndFonts(isSilentReboot);
activityManager.goToFullScreenMessage("SD card error", EpdFontFamily::BOLD);
return;
}
HalSystem::checkPanic();
SETTINGS.loadFromFile();
APP_STATE.loadFromFile();
RECENT_BOOKS.loadFromFile();
I18N.setLanguage(static_cast<Language>(SETTINGS.language));
KOREADER_STORE.loadFromFile();
OPDS_STORE.loadFromFile();
UITheme::getInstance().reload();
ButtonNavigator::setMappedInputManager(mappedInputManager);
const auto wakeupReason = gpio.getWakeupReason();
switch (wakeupReason) {
case HalGPIO::WakeupReason::PowerButton:
LOG_DBG("MAIN", "Verifying power button press duration");
if (!gpio.verifyPowerButtonWakeup(SETTINGS.getPowerButtonDuration(),
SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP)) {
powerManager.startDeepSleep(gpio);
}
wakePowerReleasePending = true;
break;
case HalGPIO::WakeupReason::AfterUSBPower:
// If USB power caused a cold boot, go back to sleep
LOG_DBG("MAIN", "Wakeup reason: After USB Power");
powerManager.startDeepSleep(gpio);
break;
case HalGPIO::WakeupReason::AfterFlash:
// After flashing, just proceed to boot
case HalGPIO::WakeupReason::Other:
default:
break;
}
// Recovery firmware mode: hold left side button (BTN_UP) together with the power button at
// boot to skip directly to the SD-card firmware update screen. Useful on devices where USB
// flashing has been locked down (e.g. recent X3 firmware).
bool recoveryFirmwareMode = false;
if (wakeupReason == HalGPIO::WakeupReason::PowerButton) {
// Refresh the cached button state a few times — isPressed() needs ~half a second to settle
// after boot per the HalGPIO contract. Use a millis-based deadline so we always wait the full
// settle window even if the loop body takes longer than expected on slow boots.
const unsigned long settleStart = millis();
while (millis() - settleStart < 500) {
gpio.update();
delay(10);
}
if (gpio.isPressed(HalGPIO::BTN_UP)) {
recoveryFirmwareMode = true;
LOG_INF("MAIN", "Recovery firmware mode (UP + POWER held at boot)");
}
}
// First serial output only here to avoid timing inconsistencies for power button press duration verification
LOG_DBG("MAIN", "Starting CrossPoint version " CROSSPOINT_VERSION);
// Resolve the single boot-presentation decision. Skipping the splash also
// skips the panel-clearing pass and the X3 initial-full-sync arming (see
// HalDisplay::begin), so the first paint is FAST_REFRESH (~500ms) over the
// retained frame and input dispatches against a visible UI.
// Only a verified deep-sleep wake may use the one-shot persisted flag.
// Otherwise a stale flag could suppress the splash on a cold boot.
const bool isSleepWake = wakeupReason == HalGPIO::WakeupReason::PowerButton;
const BootResume resume = isSilentReboot ? BootResume::Silent
: isSleepWake && !APP_STATE.showBootScreen ? BootResume::SplashlessWake
: BootResume::Splash;
bool allowFastInitialReaderRefresh = false;
// Second USB sample (first one right after powerManager.begin()): settles the
// SOF host-link verdict before the first refresh can slice-sleep.
gpio.pollUsbState();
setupDisplayAndFonts(resume != BootResume::Splash);
switch (resume) {
case BootResume::Silent:
// Splash skipped: the routing block below picks the target activity; the
// panel keeps showing the pre-reboot popup until that first paint lands.
break;
case BootResume::SplashlessWake:
// One-shot flag: re-arm the splash for the next ordinary boot. Save
// before any painting so a hang in the blocking paint path can't strand
// us in a splashless-with-no-frame loop on the next boot.
APP_STATE.showBootScreen = true;
APP_STATE.saveToFile();
if (Storage.exists(SLEEP_FRAME_FILE) && loadSleepFrameBuffer()) {
const bool useDifferentialRefresh = gpio.deviceIsX3();
if (useDifferentialRefresh) {
// begin() clears the X3 controller RAM, so restore the saved frame as
// the baseline before replacing the moon with the loading icon.
renderer.cleanupGrayscaleWithFrameBuffer();
}
const auto pageHeight = renderer.getScreenHeight();
renderer.drawImage(LoadingIcon, 0, pageHeight - LOADINGICON_HEIGHT, LOADINGICON_WIDTH, LOADINGICON_HEIGHT);
if (useDifferentialRefresh) {
renderer.displayGrayscaleBase(HalDisplay::FAST_REFRESH);
allowFastInitialReaderRefresh = true;
} else {
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
}
break;
case BootResume::Splash:
activityManager.goToBoot();
break;
}
// Output polarity is resolved per render by ActivityManager (night mode
// inverts only the reading surfaces), so nothing to restore here.
if (recoveryFirmwareMode) {
// Skip normal home/reader routing: jump straight into the SD firmware picker.
activityManager.replaceActivity(
std::make_unique<SdFirmwareUpdateActivity>(renderer, mappedInputManager, /*recoveryMode=*/true));
} else if (rebootedFromPanic) {
// If we rebooted from a panic, go to crash report screen to show the panic info
activityManager.goToCrashReport();
} else if (resume == BootResume::Silent && snapshotTarget == SILENT_REBOOT_TARGET_READER &&
!APP_STATE.openEpubPath.empty()) {
activityManager.goToReader(APP_STATE.openEpubPath);
} else if (resume == BootResume::Silent) {
// target == home (or reader with no open book): land on home — don't fall
// through to the sleep-wake "resume reader" logic, which fires on stale
// openEpubPath + lastSleepFromReader from a prior session.
activityManager.goHome();
} else if (APP_STATE.openEpubPath.empty() || !APP_STATE.lastSleepFromReader ||
mappedInputManager.isPressed(MappedInputManager::Button::Back) || APP_STATE.readerActivityLoadCount > 0) {
// Boot to home screen if no book is open, last sleep was not from reader, back button is held, or reader activity
// crashed (indicated by readerActivityLoadCount > 0)
activityManager.goHome();
} else {
// Clear app state to avoid getting into a boot loop if the epub doesn't load
const auto path = APP_STATE.openEpubPath;
APP_STATE.openEpubPath = "";
APP_STATE.readerActivityLoadCount++;
APP_STATE.saveToFile();
activityManager.goToReader(path, allowFastInitialReaderRefresh);
}
if (resume == BootResume::Silent) {
// Block until the first paint physically completes. refreshDisplay()
// waits on the panel BUSY pin so when this returns the user can see the
// new activity. Without the wait, an edge captured by gpio.update()
// during boot dispatches against an invisible Home and the default
// selectorIndex=0 opens the most-recent book.
activityManager.requestUpdateAndWait();
// Absorb any button held at this point into currentState as a non-edge:
// two gpio.update() calls separated by > InputManager's 5ms debounce
// transition the held bit through lastDebounceTime into currentState
// without setting pressedEvents, so the first loop()'s own gpio.update()
// sees state == currentState and emits nothing.
gpio.update();
delay(10);
gpio.update();
}
allowSleepAt = millis() + 2000;
}
// delay() counts ticks, and the tick stops while onEinkBusyWaitSlice() light-sleeps
// the chip (millis() is RTC-corrected on wake; the tick is not). A delay(10) mid-refresh
// would stretch to ~210 ms and starve button sampling. millis() stays honest.
static void delayWallClock(const unsigned long ms) {
const unsigned long deadline = millis() + ms;
while (static_cast<long>(millis() - deadline) < 0) {
vTaskDelay(1);
}
}
void loop() {
static unsigned long maxLoopDuration = 0;
const unsigned long loopStartTime = millis();
static unsigned long lastMemPrint = 0;
gpio.setSharedConfirmPowerShortPressEmitsPower(SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP);
gpio.update();
halTiltSensor.update(SETTINGS.tiltPageTurn, SETTINGS.orientation, activityManager.isReaderActivity());
renderer.setFadingFix(SETTINGS.fadingFix);
if (Serial && millis() - lastMemPrint >= 10000) {
LOG_INF("MEM", "Free: %d bytes, Total: %d bytes, Min Free: %d bytes, MaxAlloc: %d bytes", ESP.getFreeHeap(),
ESP.getHeapSize(), ESP.getMinFreeHeap(), ESP.getMaxAllocHeap());
lastMemPrint = millis();
}
// Handle incoming serial commands,
// nb: we use logSerial from logging to avoid deprecation warnings
if (logSerial.available() > 0) {
String line = logSerial.readStringUntil('\n');
if (line.startsWith("CMD:")) {
String cmd = line.substring(4);
cmd.trim();
bool handled = true;
if (cmd == "SCREENSHOT") {
const uint32_t bufferSize = display.getBufferSize();
logSerial.printf("SCREENSHOT_START:%d\n", bufferSize);
uint8_t* buf = display.getFrameBuffer();
logSerial.write(buf, bufferSize);
logSerial.printf("SCREENSHOT_END\n");
} else {
handled = false;
}
// Raw print, not LOG_*: debugging_monitor.py keys on this ack to report
// command success, so it must survive LOG_LEVEL=0 builds. Commands
// compiled out of this build report unknown.
logSerial.printf(handled ? "CMDACK:%s\n" : "CMDERR:unknown:%s\n", cmd.c_str());
}
}
// Check for any user activity (button press or release) or active background work
static unsigned long lastActivityTime = millis();
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || gpio.wasTouchActivity() || halTiltSensor.hadActivity() ||
activityManager.preventAutoSleep()) {
lastActivityTime = millis(); // Reset inactivity timer
powerManager.setPowerSaving(false); // Restore normal CPU frequency on user activity
}
// Let wake continue as soon as its hold has been verified. The release can
// arrive after setup, so consume that one input frame rather than making it
// a page turn, refresh, or other short power-button action.
if (wakePowerReleasePending && !gpio.isPressed(HalGPIO::BTN_POWER)) {
wakePowerReleasePending = false;
return;
}
static bool screenshotButtonsReleased = true;
static bool screenshotComboActive = false;
if (gpio.isPressed(HalGPIO::BTN_POWER) && gpio.isPressed(HalGPIO::BTN_DOWN)) {
screenshotComboActive = true;
if (screenshotButtonsReleased) {
screenshotButtonsReleased = false;
{
RenderLock lock;
ScreenshotUtil::takeScreenshot(renderer);
}
}
return;
}
if (screenshotComboActive) {
if (gpio.isPressed(HalGPIO::BTN_POWER)) return;
if (gpio.wasReleased(HalGPIO::BTN_POWER)) {
screenshotButtonsReleased = true;
screenshotComboActive = false;
return;
}
screenshotButtonsReleased = true;
screenshotComboActive = false;
}
const unsigned long sleepTimeoutMs = SETTINGS.getSleepTimeoutMs();
if (sleepTimeoutMs > 0 && millis() - lastActivityTime >= sleepTimeoutMs) {
LOG_DBG("SLP", "Auto-sleep triggered after %lu ms of inactivity", sleepTimeoutMs);
enterDeepSleep(true);
// This should never be hit as `enterDeepSleep` calls esp_deep_sleep_start
return;
}
// A hold that woke the device must be released before it can count as a new
// in-app long press. Otherwise a user who keeps holding after wake would put
// the device straight back to sleep once allowSleepAt expires.
static bool powerReleasedSinceWake = false;
if (!gpio.isPressed(HalGPIO::BTN_POWER)) powerReleasedSinceWake = true;
if (powerReleasedSinceWake && millis() >= allowSleepAt && gpio.isPressed(HalGPIO::BTN_POWER) &&
gpio.getPowerButtonHeldTime() > SETTINGS.getPowerButtonDuration()) {
// If the screenshot combination is potentially being pressed, don't sleep
if (gpio.isPressed(HalGPIO::BTN_DOWN)) {
return;
}
enterDeepSleep();
// This should never be hit as `enterDeepSleep` calls esp_deep_sleep_start
return;
}
// Refresh screen when power button is short-pressed with FORCE_REFRESH setting.
if (SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::FORCE_REFRESH &&
mappedInputManager.wasReleased(MappedInputManager::Button::Power)) {
LOG_DBG("MAIN", "Manual screen refresh triggered");
if (!activityManager.handleForcedRefresh()) {
RenderLock lock;
renderer.displayBuffer(HalDisplay::HALF_REFRESH);
}
}
// Refresh the battery icon when USB is plugged or unplugged.
// Placed after sleep guards so we never queue a render that won't be processed.
if (gpio.wasUsbStateChanged()) {
activityManager.requestUpdate();
}
const unsigned long activityStartTime = millis();
activityManager.loop();
const unsigned long activityDuration = millis() - activityStartTime;
// Body complete: releases the slice hook's yield (see onEinkBusyWaitSlice).
powerManager.noteMainLoopIteration();
const unsigned long loopDuration = millis() - loopStartTime;
if (loopDuration > maxLoopDuration) {
maxLoopDuration = loopDuration;
if (maxLoopDuration > 50) {
LOG_DBG("LOOP", "New max loop duration: %lu ms (activity: %lu ms)", maxLoopDuration, activityDuration);
}
}
// Add delay at the end of the loop to prevent tight spinning
// When an activity requests skip loop delay (e.g., webserver running), use yield() for faster response
// Otherwise, use longer delay to save power
if (activityManager.skipLoopDelay()) {
powerManager.setPowerSaving(false); // Make sure we're at full performance when skipLoopDelay is requested
yield(); // Give FreeRTOS a chance to run tasks, but return immediately
} else {
const unsigned long idleMs = millis() - lastActivityTime;
if (idleMs >= HalPowerManager::IDLE_LIGHT_SLEEP_MS) {
// Idle: light-sleep between input polls instead of busy-delaying (same poll cadence).
// Race-to-sleep: run the brief wake windows at normal clock, not LOW_POWER_FREQ.
// The board's sleep-floor current is paid per-millisecond regardless of CPU
// speed, so finishing the per-wake work ~16x faster and returning to sleep
// costs less charge than stretching the window at 10 MHz (measured at 10 MHz:
// 8.8 mA for 4.5 ms per wake). The downclock below only serves the pre-sleep
// 100 Hz delay-poll phase. The lightSleep()-rejected fallback delay() then
// also runs at normal clock, but that only happens when USB (externally
// powered), WiFi, or a render Lock (full speed wanted anyway) is active.
powerManager.setPowerSaving(false);
if (gpio.isDebouncePending()) {
// A raw button-state change is mid-debounce: commitment needs a second
// matching sample, so poll again quickly instead of sleeping a slice —
// a tap shorter than the 50 ms cadence would otherwise land in a single
// sample and be dropped, and every press would commit a slice late.
delayWallClock(10);
} else if (!powerManager.lightSleep(gpio)) {
// Light sleep declined = a render Lock, USB, or WiFi is active — the
// chip is at full clock anyway, so poll at 100 Hz. A 50 ms cadence
// here dropped sub-slice power taps (a press needs two samples >=5 ms
// apart to commit), which made short-press sleep flaky during renders
// — exactly when a render Lock forces this fallback.
delayWallClock(10);
}
} else {
// Response window after recent input: keep 100 Hz polling for snappy interaction,
// but downclock once rapid-input bursts have settled — renders re-raise the clock
// via HalPowerManager::Lock, so full speed only serves loop bookkeeping here
if (idleMs >= HalPowerManager::IDLE_DOWNCLOCK_MS) {
powerManager.setPowerSaving(true);
}
delayWallClock(10);
}
}
}