forked from crosspoint-reader/crosspoint-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
733 lines (650 loc) · 29.8 KB
/
Copy pathmain.cpp
File metadata and controls
733 lines (650 loc) · 29.8 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
#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 <HalFrontlight.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 <XteinkDetect.h>
#include <builtinFonts/all.h>
#if FREEINK_CAP_TOUCH
#include <esp_sntp.h>
#endif
#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;
static unsigned long lastX4ProPowerClickAt = 0;
namespace {
constexpr unsigned long X4PRO_POWER_DOUBLE_CLICK_MS = 500;
constexpr unsigned long X4PRO_POWER_CLICK_MAX_HOLD_MS = 300;
constexpr unsigned long X4PRO_RECOVERY_SETTLE_MS = 20;
constexpr unsigned long DEFAULT_RECOVERY_SETTLE_MS = 500;
} // namespace
// 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;
#if FREEINK_CAP_TOUCH
static bool finishWifiSessionWithoutRestart() {
if (!BoardConfig::hasTouch()) return false;
// A software reset does not cycle externally powered touch/frontlight rails.
// Shut down the network stack in place so those peripherals retain state.
if (esp_sntp_enabled()) {
esp_sntp_stop();
}
WiFi.mode(WIFI_OFF);
delay(100);
LOG_DBG("MAIN", "WiFi stopped without restart on touch device");
return true;
}
#endif
void silentRestart() {
if (deepSleepInProgress) return; // sleeping supersedes the heap-defrag reboot
#if FREEINK_CAP_TOUCH
if (finishWifiSessionWithoutRestart()) return;
#endif
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
#if FREEINK_CAP_TOUCH
if (finishWifiSessionWithoutRestart()) return;
#endif
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();
}
bool handleX4ProFrontlightDoubleClick() {
if (!BoardConfig::isX4Pro() || !gpio.wasReleased(HalGPIO::BTN_POWER)) {
return false;
}
const unsigned long now = millis();
if (gpio.getPowerButtonHeldTime() > X4PRO_POWER_CLICK_MAX_HOLD_MS) {
lastX4ProPowerClickAt = 0;
return false;
}
if (lastX4ProPowerClickAt == 0 || now - lastX4ProPowerClickAt > X4PRO_POWER_DOUBLE_CLICK_MS) {
lastX4ProPowerClickAt = now;
return false;
}
lastX4ProPowerClickAt = 0;
const bool lightOn = !Frontlight.isOn();
Frontlight.setOn(lightOn);
SETTINGS.frontlightOn = lightOn ? 1 : 0;
SETTINGS.saveToFile();
LOG_INF("LIGHT", "Frontlight toggled %s by power-button double-click", lightOn ? "on" : "off");
return true;
}
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) {
#if !FREEINK_MCU_C3
// C3 resolves its controller in HalGPIO::begin() before SPI claims the
// display pins. X4 Pro skips that C3-only path, so probe here before
// display.begin() selects and initializes its panel driver.
static bool controllerResolved = false;
if (!controllerResolved) {
controllerResolved = true;
if (freeink::applyXteinkDisplayController()) {
LOG_DBG("MAIN", "Panel controller: UltraChip UC81xx variant detected");
}
}
#endif
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();
const auto wakeupReason = gpio.getWakeupReason();
// Latch the recovery chord before SD and settings I/O. X4 Pro uses a plain
// digital button with 5 ms debounce; other Xteink inputs retain their legacy
// settling window. BTN_DOWN avoids the X4 Pro's GPIO0 boot-strap pin.
bool recoveryFirmwareMode = false;
if (wakeupReason == HalGPIO::WakeupReason::PowerButton) {
const unsigned long settleMs = BoardConfig::isX4Pro() ? X4PRO_RECOVERY_SETTLE_MS : DEFAULT_RECOVERY_SETTLE_MS;
const unsigned long settleStart = millis();
while (millis() - settleStart < settleMs) {
gpio.update();
delay(10);
}
const uint8_t recoveryButton = BoardConfig::isX4Pro() ? HalGPIO::BTN_DOWN : HalGPIO::BTN_UP;
if (gpio.isPressed(recoveryButton)) {
recoveryFirmwareMode = true;
LOG_INF("MAIN", "Recovery firmware mode (%s + POWER held at boot)", BoardConfig::isX4Pro() ? "DOWN" : "UP");
}
}
#if FREEINK_DEVICE_X4 || FREEINK_DEVICE_X3
LOG_INF("MAIN", "Hardware detect: %s", gpio.deviceIsX3() ? "X3" : "X4");
#else
LOG_INF("MAIN", "Device: %s", BoardConfig::ACTIVE.name);
#endif
// SD Card Initialization
// We need 6 open files concurrently when parsing a new chapter
if (!Storage.begin()) {
LOG_ERR("MAIN", "SD card initialization failed");
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);
// Brightness and warmth are always restored. A normal wake starts with the
// light off unless Restore Light on Wake is enabled; silent maintenance
// reboots preserve the live state so they do not unexpectedly go dark.
const bool restoreLightOn = SETTINGS.frontlightOn != 0 && (SETTINGS.frontlightRestoreOnWake != 0 || isSilentReboot);
Frontlight.begin(SETTINGS.frontlightBrightness, SETTINGS.frontlightWarmth, restoreLightOn);
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");
#if FREEINK_DEVICE_PAPERMONO
// There is no armable GPIO wake because the button is behind the PMIC.
// Sleeping here would strand the device in a USB-replug boot loop.
break;
#else
powerManager.startDeepSleep(gpio);
break;
#endif
case HalGPIO::WakeupReason::AfterFlash:
// After flashing, just proceed to boot
case HalGPIO::WakeupReason::Other:
default:
break;
}
// 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;
bool needsWakeRefresh = false;
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);
}
} else {
// The first Home/Reader paint is followed by an explicit clean refresh
// because the panel still physically shows the sleep image.
needsWakeRefresh = true;
}
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(HomeMenuItem::NONE, needsWakeRefresh);
} 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;
}
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();
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");
}
}
}
// 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;
}
// Consume the second X4 Pro power-button release so it does not also run a
// configured short-power action after toggling the frontlight.
if (handleX4ProFrontlightDoubleClick()) {
return;
}
#if FREEINK_CAP_TOUCH
// A single X4 Pro power click becomes Confirm only after the frontlight
// double-click window expires without a second click.
mappedInputManager.setPowerConfirmClickFrame(false);
if (SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::PWR_CONFIRM && BoardConfig::isX4Pro() &&
lastX4ProPowerClickAt != 0 && millis() - lastX4ProPowerClickAt > X4PRO_POWER_DOUBLE_CLICK_MS) {
lastX4ProPowerClickAt = 0;
mappedInputManager.setPowerConfirmClickFrame(true);
}
#endif
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;
}
#if FREEINK_DEVICE_PAPERMONO
// Paper Mono reports the PMIC power button as a one-tick click, so the held
// path above cannot fire. With the default Ignore action, retain the normal
// power-button meaning and shut down; explicit alternate bindings still win.
if ((SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::SLEEP ||
SETTINGS.shortPwrBtn == CrossPointSettings::SHORT_PWRBTN::IGNORE) &&
millis() >= allowSleepAt && mappedInputManager.wasReleased(MappedInputManager::Button::Power)) {
enterDeepSleep();
return;
}
#endif
// 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;
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 {
if (millis() - lastActivityTime >= HalPowerManager::IDLE_POWER_SAVING_MS) {
// If we've been inactive for a while, increase the delay to save power
powerManager.setPowerSaving(true); // Lower CPU frequency after extended inactivity
delay(50);
} else {
// Short delay to prevent tight loop while still being responsive
delay(10);
}
}
}