refactor: move render() to Activity super class, use freeRTOS notification (#774)

## Summary

Currently, each activity has to manage their own `displayTaskLoop` which
adds redundant boilerplate code. The loop is a wait loop which is also
not the best practice, as the `updateRequested` boolean is not protected
by a mutex.

In this PR:
- Move `displayTaskLoop` to the super `Activity` class
- Replace `updateRequested` with freeRTOS's [direct to task
notification](https://www.freertos.org/Documentation/02-Kernel/02-Kernel-features/03-Direct-to-task-notifications/01-Task-notifications)
- For `ActivityWithSubactivity`, whenever a sub-activity is present, the
parent's `render()` automatically goes inactive

With this change, activities now only need to expose `render()`
function, and anywhere in the code base can call `requestUpdate()` to
request a new rendering pass.

## Additional Context

In theory, this change may also make the battery life a bit better,
since one wait loop is removed. Although the equipment in my home lab
wasn't been able to verify it (the electric current is too noisy and
small). Would appreciate if anyone has any insights on this subject.

Update: I managed to hack [a small piece of
code](https://github.com/ngxson/crosspoint-reader/tree/xsn/measure_cpu_usage)
that allow tracking CPU idle time.

The CPU load does decrease a bit (1.47% down to 1.39%), which make
sense, because the display task is now sleeping most of the time unless
notified. This should translate to a slightly increase in battery life
in the long run.

```
PR:
[40012] [MEM] Free: 185856 bytes, Total: 231004 bytes, Min Free: 123316 bytes
[40012] [IDLE] Idle time: 98.61% (CPU load: 1.39%)
[50017] [MEM] Free: 185856 bytes, Total: 231004 bytes, Min Free: 123316 bytes
[50017] [IDLE] Idle time: 98.61% (CPU load: 1.39%)
[60022] [MEM] Free: 185856 bytes, Total: 231004 bytes, Min Free: 123316 bytes
[60022] [IDLE] Idle time: 98.61% (CPU load: 1.39%)

master:
[20012] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[20012] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
[30017] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[30017] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
[40022] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[40022] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
```

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **NO**


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Streamlined rendering architecture by consolidating update mechanisms
across all activities, improving efficiency and consistency.
* Modernized synchronization patterns for display updates to ensure
reliable, conflict-free rendering.

* **Bug Fixes**
* Enhanced rendering stability through improved locking mechanisms and
explicit update requests.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: znelson <znelson@users.noreply.github.com>
This commit is contained in:
Xuan-Son Nguyen
2026-02-16 11:11:15 +01:00
committed by GitHub
parent 0508bfc1f7
commit a616f42cb4
53 changed files with 458 additions and 1409 deletions

View File

@@ -16,15 +16,9 @@ constexpr uint8_t kUnassigned = 0xFF;
constexpr unsigned long kErrorDisplayMs = 1500;
} // namespace
void ButtonRemapActivity::taskTrampoline(void* param) {
auto* self = static_cast<ButtonRemapActivity*>(param);
self->displayTaskLoop();
}
void ButtonRemapActivity::onEnter() {
Activity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
// Start with all roles unassigned to avoid duplicate blocking.
currentStep = 0;
tempMapping[0] = kUnassigned;
@@ -33,25 +27,20 @@ void ButtonRemapActivity::onEnter() {
tempMapping[3] = kUnassigned;
errorMessage.clear();
errorUntil = 0;
updateRequired = true;
xTaskCreate(&ButtonRemapActivity::taskTrampoline, "ButtonRemapTask", 4096, this, 1, &displayTaskHandle);
requestUpdate();
}
void ButtonRemapActivity::onExit() {
Activity::onExit();
// Ensure display task is stopped outside of active rendering.
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void ButtonRemapActivity::onExit() { Activity::onExit(); }
void ButtonRemapActivity::loop() {
// Clear any temporary warning after its timeout.
if (errorUntil > 0 && millis() > errorUntil) {
errorMessage.clear();
errorUntil = 0;
requestUpdate();
return;
}
// Side buttons:
// - Up: reset mapping to defaults and exit.
// - Down: cancel without saving.
@@ -72,60 +61,39 @@ void ButtonRemapActivity::loop() {
return;
}
// Wait for the UI to refresh before accepting another assignment.
// This avoids rapid double-presses that can advance the step without a visible redraw.
if (updateRequired) {
return;
}
{
// Wait for the UI to refresh before accepting another assignment.
// This avoids rapid double-presses that can advance the step without a visible redraw.
requestUpdateAndWait();
// Wait for a front button press to assign to the current role.
const int pressedButton = mappedInput.getPressedFrontButton();
if (pressedButton < 0) {
return;
}
// Update temporary mapping and advance the remap step.
// Only accept the press if this hardware button isn't already assigned elsewhere.
if (!validateUnassigned(static_cast<uint8_t>(pressedButton))) {
updateRequired = true;
return;
}
tempMapping[currentStep] = static_cast<uint8_t>(pressedButton);
currentStep++;
if (currentStep >= kRoleCount) {
// All roles assigned; save to settings and exit.
applyTempMapping();
SETTINGS.saveToFile();
onBack();
return;
}
updateRequired = true;
}
[[noreturn]] void ButtonRemapActivity::displayTaskLoop() {
while (true) {
if (updateRequired) {
// Ensure render calls are serialized with UI thread changes.
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
updateRequired = false;
xSemaphoreGive(renderingMutex);
// Wait for a front button press to assign to the current role.
const int pressedButton = mappedInput.getPressedFrontButton();
if (pressedButton < 0) {
return;
}
// Clear any temporary warning after its timeout.
if (errorUntil > 0 && millis() > errorUntil) {
errorMessage.clear();
errorUntil = 0;
updateRequired = true;
// Update temporary mapping and advance the remap step.
// Only accept the press if this hardware button isn't already assigned elsewhere.
if (!validateUnassigned(static_cast<uint8_t>(pressedButton))) {
requestUpdate();
return;
}
tempMapping[currentStep] = static_cast<uint8_t>(pressedButton);
currentStep++;
if (currentStep >= kRoleCount) {
// All roles assigned; save to settings and exit.
applyTempMapping();
SETTINGS.saveToFile();
onBack();
return;
}
vTaskDelay(50 / portTICK_PERIOD_MS);
requestUpdate();
}
}
void ButtonRemapActivity::render() {
void ButtonRemapActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
#include <string>
@@ -17,12 +14,10 @@ class ButtonRemapActivity final : public Activity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
private:
// Rendering task state.
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
bool updateRequired = false;
// Callback used to exit the remap flow back to the settings list.
const std::function<void()> onBack;
@@ -34,11 +29,6 @@ class ButtonRemapActivity final : public Activity {
unsigned long errorUntil = 0;
std::string errorMessage;
// FreeRTOS task helpers.
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
// Commit temporary mapping to settings.
void applyTempMapping();
// Returns false if a hardware button is already assigned to a different role.

View File

@@ -15,37 +15,14 @@ constexpr int MENU_ITEMS = 3;
const char* menuNames[MENU_ITEMS] = {"OPDS Server URL", "Username", "Password"};
} // namespace
void CalibreSettingsActivity::taskTrampoline(void* param) {
auto* self = static_cast<CalibreSettingsActivity*>(param);
self->displayTaskLoop();
}
void CalibreSettingsActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
selectedIndex = 0;
updateRequired = true;
xTaskCreate(&CalibreSettingsActivity::taskTrampoline, "CalibreSettingsTask",
4096, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
requestUpdate();
}
void CalibreSettingsActivity::onExit() {
ActivityWithSubactivity::onExit();
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void CalibreSettingsActivity::onExit() { ActivityWithSubactivity::onExit(); }
void CalibreSettingsActivity::loop() {
if (subActivity) {
@@ -66,18 +43,16 @@ void CalibreSettingsActivity::loop() {
// Handle navigation
buttonNavigator.onNext([this] {
selectedIndex = (selectedIndex + 1) % MENU_ITEMS;
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPrevious([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
requestUpdate();
});
}
void CalibreSettingsActivity::handleSelection() {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (selectedIndex == 0) {
// OPDS Server URL
exitActivity();
@@ -90,11 +65,11 @@ void CalibreSettingsActivity::handleSelection() {
SETTINGS.opdsServerUrl[sizeof(SETTINGS.opdsServerUrl) - 1] = '\0';
SETTINGS.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
} else if (selectedIndex == 1) {
// Username
@@ -108,11 +83,11 @@ void CalibreSettingsActivity::handleSelection() {
SETTINGS.opdsUsername[sizeof(SETTINGS.opdsUsername) - 1] = '\0';
SETTINGS.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
} else if (selectedIndex == 2) {
// Password
@@ -126,30 +101,16 @@ void CalibreSettingsActivity::handleSelection() {
SETTINGS.opdsPassword[sizeof(SETTINGS.opdsPassword) - 1] = '\0';
SETTINGS.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
}
xSemaphoreGive(renderingMutex);
}
void CalibreSettingsActivity::displayTaskLoop() {
while (true) {
if (updateRequired && !subActivity) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void CalibreSettingsActivity::render() {
void CalibreSettingsActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
@@ -21,18 +18,12 @@ class CalibreSettingsActivity final : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
private:
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false;
int selectedIndex = 0;
const std::function<void()> onBack;
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
void handleSelection();
};

View File

@@ -8,52 +8,16 @@
#include "components/UITheme.h"
#include "fontIds.h"
void ClearCacheActivity::taskTrampoline(void* param) {
auto* self = static_cast<ClearCacheActivity*>(param);
self->displayTaskLoop();
}
void ClearCacheActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
state = WARNING;
updateRequired = true;
xTaskCreate(&ClearCacheActivity::taskTrampoline, "ClearCacheActivityTask",
4096, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
requestUpdate();
}
void ClearCacheActivity::onExit() {
ActivityWithSubactivity::onExit();
void ClearCacheActivity::onExit() { ActivityWithSubactivity::onExit(); }
// Wait until not rendering to delete task to avoid killing mid-instruction to EPD
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void ClearCacheActivity::displayTaskLoop() {
while (true) {
if (updateRequired) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void ClearCacheActivity::render() {
void ClearCacheActivity::render(Activity::RenderLock&&) {
const auto pageHeight = renderer.getScreenHeight();
renderer.clearScreen();
@@ -112,7 +76,7 @@ void ClearCacheActivity::clearCache() {
LOG_DBG("CLEAR_CACHE", "Failed to open cache directory");
if (root) root.close();
state = FAILED;
updateRequired = true;
requestUpdate();
return;
}
@@ -147,7 +111,7 @@ void ClearCacheActivity::clearCache() {
LOG_DBG("CLEAR_CACHE", "Cache cleared: %d removed, %d failed", clearedCount, failedCount);
state = SUCCESS;
updateRequired = true;
requestUpdate();
}
void ClearCacheActivity::loop() {
@@ -157,8 +121,7 @@ void ClearCacheActivity::loop() {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = CLEARING;
xSemaphoreGive(renderingMutex);
updateRequired = true;
vTaskDelay(10 / portTICK_PERIOD_MS);
requestUpdateAndWait();
clearCache();
}

View File

@@ -1,9 +1,5 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
#include "activities/ActivityWithSubactivity.h"
@@ -17,21 +13,16 @@ class ClearCacheActivity final : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
private:
enum State { WARNING, CLEARING, SUCCESS, FAILED };
State state = WARNING;
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
bool updateRequired = false;
const std::function<void()> goBack;
int clearedCount = 0;
int failedCount = 0;
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
void clearCache();
};

View File

@@ -10,11 +10,6 @@
#include "components/UITheme.h"
#include "fontIds.h"
void KOReaderAuthActivity::taskTrampoline(void* param) {
auto* self = static_cast<KOReaderAuthActivity*>(param);
self->displayTaskLoop();
}
void KOReaderAuthActivity::onWifiSelectionComplete(const bool success) {
exitActivity();
@@ -23,7 +18,7 @@ void KOReaderAuthActivity::onWifiSelectionComplete(const bool success) {
state = FAILED;
errorMessage = "WiFi connection failed";
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
return;
}
@@ -31,7 +26,7 @@ void KOReaderAuthActivity::onWifiSelectionComplete(const bool success) {
state = AUTHENTICATING;
statusMessage = "Authenticating...";
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
performAuthentication();
}
@@ -48,21 +43,12 @@ void KOReaderAuthActivity::performAuthentication() {
errorMessage = KOReaderSyncClient::errorString(result);
}
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
}
void KOReaderAuthActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
xTaskCreate(&KOReaderAuthActivity::taskTrampoline, "KOAuthTask",
4096, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
// Turn on WiFi
WiFi.mode(WIFI_STA);
@@ -70,7 +56,7 @@ void KOReaderAuthActivity::onEnter() {
if (WiFi.status() == WL_CONNECTED) {
state = AUTHENTICATING;
statusMessage = "Authenticating...";
updateRequired = true;
requestUpdate();
// Perform authentication in a separate task
xTaskCreate(
@@ -96,33 +82,9 @@ void KOReaderAuthActivity::onExit() {
delay(100);
WiFi.mode(WIFI_OFF);
delay(100);
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void KOReaderAuthActivity::displayTaskLoop() {
while (true) {
if (updateRequired && !subActivity) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void KOReaderAuthActivity::render() {
if (subActivity) {
return;
}
void KOReaderAuthActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
renderer.drawCenteredText(UI_12_FONT_ID, 15, "KOReader Auth", true, EpdFontFamily::BOLD);

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
@@ -20,15 +17,12 @@ class KOReaderAuthActivity final : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
bool preventAutoSleep() override { return state == CONNECTING || state == AUTHENTICATING; }
private:
enum State { WIFI_SELECTION, CONNECTING, AUTHENTICATING, SUCCESS, FAILED };
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
bool updateRequired = false;
State state = WIFI_SELECTION;
std::string statusMessage;
std::string errorMessage;
@@ -37,8 +31,4 @@ class KOReaderAuthActivity final : public ActivityWithSubactivity {
void onWifiSelectionComplete(bool success);
void performAuthentication();
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
};

View File

@@ -16,37 +16,14 @@ constexpr int MENU_ITEMS = 5;
const char* menuNames[MENU_ITEMS] = {"Username", "Password", "Sync Server URL", "Document Matching", "Authenticate"};
} // namespace
void KOReaderSettingsActivity::taskTrampoline(void* param) {
auto* self = static_cast<KOReaderSettingsActivity*>(param);
self->displayTaskLoop();
}
void KOReaderSettingsActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
selectedIndex = 0;
updateRequired = true;
xTaskCreate(&KOReaderSettingsActivity::taskTrampoline, "KOReaderSettingsTask",
4096, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
requestUpdate();
}
void KOReaderSettingsActivity::onExit() {
ActivityWithSubactivity::onExit();
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void KOReaderSettingsActivity::onExit() { ActivityWithSubactivity::onExit(); }
void KOReaderSettingsActivity::loop() {
if (subActivity) {
@@ -67,18 +44,16 @@ void KOReaderSettingsActivity::loop() {
// Handle navigation
buttonNavigator.onNext([this] {
selectedIndex = (selectedIndex + 1) % MENU_ITEMS;
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPrevious([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
requestUpdate();
});
}
void KOReaderSettingsActivity::handleSelection() {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (selectedIndex == 0) {
// Username
exitActivity();
@@ -90,11 +65,11 @@ void KOReaderSettingsActivity::handleSelection() {
KOREADER_STORE.setCredentials(username, KOREADER_STORE.getPassword());
KOREADER_STORE.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
} else if (selectedIndex == 1) {
// Password
@@ -107,11 +82,11 @@ void KOReaderSettingsActivity::handleSelection() {
KOREADER_STORE.setCredentials(KOREADER_STORE.getUsername(), password);
KOREADER_STORE.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
} else if (selectedIndex == 2) {
// Sync Server URL - prefill with https:// if empty to save typing
@@ -128,11 +103,11 @@ void KOReaderSettingsActivity::handleSelection() {
KOREADER_STORE.setServerUrl(urlToSave);
KOREADER_STORE.saveToFile();
exitActivity();
updateRequired = true;
requestUpdate();
},
[this]() {
exitActivity();
updateRequired = true;
requestUpdate();
}));
} else if (selectedIndex == 3) {
// Document Matching - toggle between Filename and Binary
@@ -141,7 +116,7 @@ void KOReaderSettingsActivity::handleSelection() {
(current == DocumentMatchMethod::FILENAME) ? DocumentMatchMethod::BINARY : DocumentMatchMethod::FILENAME;
KOREADER_STORE.setMatchMethod(newMethod);
KOREADER_STORE.saveToFile();
updateRequired = true;
requestUpdate();
} else if (selectedIndex == 4) {
// Authenticate
if (!KOREADER_STORE.hasCredentials()) {
@@ -152,26 +127,12 @@ void KOReaderSettingsActivity::handleSelection() {
exitActivity();
enterNewActivity(new KOReaderAuthActivity(renderer, mappedInput, [this] {
exitActivity();
updateRequired = true;
requestUpdate();
}));
}
xSemaphoreGive(renderingMutex);
}
void KOReaderSettingsActivity::displayTaskLoop() {
while (true) {
if (updateRequired && !subActivity) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void KOReaderSettingsActivity::render() {
void KOReaderSettingsActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
@@ -21,18 +18,13 @@ class KOReaderSettingsActivity final : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
private:
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false;
int selectedIndex = 0;
const std::function<void()> onBack;
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
void handleSelection();
};

View File

@@ -9,11 +9,6 @@
#include "fontIds.h"
#include "network/OtaUpdater.h"
void OtaUpdateActivity::taskTrampoline(void* param) {
auto* self = static_cast<OtaUpdateActivity*>(param);
self->displayTaskLoop();
}
void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
exitActivity();
@@ -28,15 +23,15 @@ void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = CHECKING_FOR_UPDATE;
xSemaphoreGive(renderingMutex);
updateRequired = true;
vTaskDelay(10 / portTICK_PERIOD_MS);
requestUpdateAndWait();
const auto res = updater.checkForUpdate();
if (res != OtaUpdater::OK) {
LOG_DBG("OTA", "Update check failed: %d", res);
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = FAILED;
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
return;
}
@@ -45,28 +40,19 @@ void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = NO_UPDATE;
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
return;
}
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = WAITING_CONFIRMATION;
xSemaphoreGive(renderingMutex);
updateRequired = true;
requestUpdate();
}
void OtaUpdateActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
xTaskCreate(&OtaUpdateActivity::taskTrampoline, "OtaUpdateActivityTask",
2048, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
// Turn on WiFi immediately
LOG_DBG("OTA", "Turning on WiFi...");
WiFi.mode(WIFI_STA);
@@ -85,30 +71,9 @@ void OtaUpdateActivity::onExit() {
delay(100); // Allow disconnect frame to be sent
WiFi.mode(WIFI_OFF);
delay(100); // Allow WiFi hardware to fully power down
// Wait until not rendering to delete task to avoid killing mid-instruction to EPD
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
}
void OtaUpdateActivity::displayTaskLoop() {
while (true) {
if (updateRequired || updater.getRender()) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void OtaUpdateActivity::render() {
void OtaUpdateActivity::render(Activity::RenderLock&&) {
if (subActivity) {
// Subactivity handles its own rendering
return;
@@ -182,6 +147,11 @@ void OtaUpdateActivity::render() {
}
void OtaUpdateActivity::loop() {
// TODO @ngxson : refactor this logic later
if (updater.getRender()) {
requestUpdate();
}
if (subActivity) {
subActivity->loop();
return;
@@ -190,26 +160,29 @@ void OtaUpdateActivity::loop() {
if (state == WAITING_CONFIRMATION) {
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
LOG_DBG("OTA", "New update available, starting download...");
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = UPDATE_IN_PROGRESS;
xSemaphoreGive(renderingMutex);
updateRequired = true;
vTaskDelay(10 / portTICK_PERIOD_MS);
{
RenderLock lock(*this);
state = UPDATE_IN_PROGRESS;
}
requestUpdate();
requestUpdateAndWait();
const auto res = updater.installUpdate();
if (res != OtaUpdater::OK) {
LOG_DBG("OTA", "Update failed: %d", res);
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = FAILED;
xSemaphoreGive(renderingMutex);
updateRequired = true;
{
RenderLock lock(*this);
state = FAILED;
}
requestUpdate();
return;
}
xSemaphoreTake(renderingMutex, portMAX_DELAY);
state = FINISHED;
xSemaphoreGive(renderingMutex);
updateRequired = true;
{
RenderLock lock(*this);
state = FINISHED;
}
requestUpdate();
}
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include "activities/ActivityWithSubactivity.h"
#include "network/OtaUpdater.h"
@@ -21,18 +18,12 @@ class OtaUpdateActivity : public ActivityWithSubactivity {
// Can't initialize this to 0 or the first render doesn't happen
static constexpr unsigned int UNINITIALIZED_PERCENTAGE = 111;
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
bool updateRequired = false;
const std::function<void()> goBack;
State state = WIFI_SELECTION;
unsigned int lastUpdaterPercentage = UNINITIALIZED_PERCENTAGE;
OtaUpdater updater;
void onWifiSelectionComplete(bool success);
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render();
public:
explicit OtaUpdateActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
@@ -41,5 +32,6 @@ class OtaUpdateActivity : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
void render(Activity::RenderLock&&) override;
bool preventAutoSleep() override { return state == CHECKING_FOR_UPDATE || state == UPDATE_IN_PROGRESS; }
};

View File

@@ -17,14 +17,8 @@
const char* SettingsActivity::categoryNames[categoryCount] = {"Display", "Reader", "Controls", "System"};
void SettingsActivity::taskTrampoline(void* param) {
auto* self = static_cast<SettingsActivity*>(param);
self->displayTaskLoop();
}
void SettingsActivity::onEnter() {
Activity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
// Build per-category vectors from the shared settings list
displaySettings.clear();
@@ -64,28 +58,12 @@ void SettingsActivity::onEnter() {
settingsCount = static_cast<int>(displaySettings.size());
// Trigger first update
updateRequired = true;
xTaskCreate(&SettingsActivity::taskTrampoline, "SettingsActivityTask",
4096, // Stack size
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
requestUpdate();
}
void SettingsActivity::onExit() {
ActivityWithSubactivity::onExit();
// Wait until not rendering to delete task to avoid killing mid-instruction to EPD
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
UITheme::getInstance().reload(); // Re-apply theme in case it was changed
}
@@ -101,10 +79,10 @@ void SettingsActivity::loop() {
if (selectedSettingIndex == 0) {
selectedCategoryIndex = (selectedCategoryIndex < categoryCount - 1) ? (selectedCategoryIndex + 1) : 0;
hasChangedCategory = true;
updateRequired = true;
requestUpdate();
} else {
toggleCurrentSetting();
updateRequired = true;
requestUpdate();
return;
}
}
@@ -118,24 +96,24 @@ void SettingsActivity::loop() {
// Handle navigation
buttonNavigator.onNextRelease([this] {
selectedSettingIndex = ButtonNavigator::nextIndex(selectedSettingIndex, settingsCount + 1);
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPreviousRelease([this] {
selectedSettingIndex = ButtonNavigator::previousIndex(selectedSettingIndex, settingsCount + 1);
updateRequired = true;
requestUpdate();
});
buttonNavigator.onNextContinuous([this, &hasChangedCategory] {
hasChangedCategory = true;
selectedCategoryIndex = ButtonNavigator::nextIndex(selectedCategoryIndex, categoryCount);
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPreviousContinuous([this, &hasChangedCategory] {
hasChangedCategory = true;
selectedCategoryIndex = ButtonNavigator::previousIndex(selectedCategoryIndex, categoryCount);
updateRequired = true;
requestUpdate();
});
if (hasChangedCategory) {
@@ -182,20 +160,18 @@ void SettingsActivity::toggleCurrentSetting() {
}
} else if (setting.type == SettingType::ACTION) {
auto enterSubActivity = [this](Activity* activity) {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
exitActivity();
enterNewActivity(activity);
xSemaphoreGive(renderingMutex);
};
auto onComplete = [this] {
exitActivity();
updateRequired = true;
requestUpdate();
};
auto onCompleteBool = [this](bool) {
exitActivity();
updateRequired = true;
requestUpdate();
};
switch (setting.action) {
@@ -228,19 +204,7 @@ void SettingsActivity::toggleCurrentSetting() {
SETTINGS.saveToFile();
}
void SettingsActivity::displayTaskLoop() {
while (true) {
if (updateRequired && !subActivity) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void SettingsActivity::render() const {
void SettingsActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();

View File

@@ -1,7 +1,4 @@
#pragma once
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
#include <string>
@@ -135,10 +132,8 @@ struct SettingInfo {
};
class SettingsActivity final : public ActivityWithSubactivity {
TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false;
int selectedCategoryIndex = 0; // Currently selected category
int selectedSettingIndex = 0;
int settingsCount = 0;
@@ -155,9 +150,6 @@ class SettingsActivity final : public ActivityWithSubactivity {
static constexpr int categoryCount = 4;
static const char* categoryNames[categoryCount];
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render() const;
void enterCategory(int categoryIndex);
void toggleCurrentSetting();
@@ -168,4 +160,5 @@ class SettingsActivity final : public ActivityWithSubactivity {
void onEnter() override;
void onExit() override;
void loop() override;
};
void render(Activity::RenderLock&&) override;
};