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

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.

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%)
```

---

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
-->

* **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 cottongin
parent 12cc7de49e
commit ed8a0feac1
53 changed files with 511 additions and 1462 deletions

View File

@@ -19,15 +19,9 @@ namespace {
constexpr int PAGE_ITEMS = 23;
} // namespace
void OpdsBookBrowserActivity::taskTrampoline(void* param) {
auto* self = static_cast<OpdsBookBrowserActivity*>(param);
self->displayTaskLoop();
}
void OpdsBookBrowserActivity::onEnter() {
ActivityWithSubactivity::onEnter();
renderingMutex = xSemaphoreCreateMutex();
state = BrowserState::CHECK_WIFI;
entries.clear();
navigationHistory.clear();
@@ -35,14 +29,7 @@ void OpdsBookBrowserActivity::onEnter() {
selectorIndex = 0;
errorMessage.clear();
statusMessage = "Checking WiFi...";
updateRequired = true;
xTaskCreate(&OpdsBookBrowserActivity::taskTrampoline, "OpdsBookBrowserTask",
4096, // Stack size (larger for HTTP operations)
this, // Parameters
1, // Priority
&displayTaskHandle // Task handle
);
requestUpdate();
// Check WiFi and connect if needed, then fetch feed
checkAndConnectWifi();
@@ -54,13 +41,6 @@ void OpdsBookBrowserActivity::onExit() {
// Turn off WiFi when exiting
WiFi.mode(WIFI_OFF);
xSemaphoreTake(renderingMutex, portMAX_DELAY);
if (displayTaskHandle) {
vTaskDelete(displayTaskHandle);
displayTaskHandle = nullptr;
}
vSemaphoreDelete(renderingMutex);
renderingMutex = nullptr;
entries.clear();
navigationHistory.clear();
}
@@ -81,7 +61,7 @@ void OpdsBookBrowserActivity::loop() {
LOG_DBG("OPDS", "Retry: WiFi connected, retrying fetch");
state = BrowserState::LOADING;
statusMessage = "Loading...";
updateRequired = true;
requestUpdate();
fetchFeed(currentPath);
} else {
// WiFi not connected - launch WiFi selection
@@ -134,40 +114,28 @@ void OpdsBookBrowserActivity::loop() {
if (!entries.empty()) {
buttonNavigator.onNextRelease([this] {
selectorIndex = ButtonNavigator::nextIndex(selectorIndex, entries.size());
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPreviousRelease([this] {
selectorIndex = ButtonNavigator::previousIndex(selectorIndex, entries.size());
updateRequired = true;
requestUpdate();
});
buttonNavigator.onNextContinuous([this] {
selectorIndex = ButtonNavigator::nextPageIndex(selectorIndex, entries.size(), PAGE_ITEMS);
updateRequired = true;
requestUpdate();
});
buttonNavigator.onPreviousContinuous([this] {
selectorIndex = ButtonNavigator::previousPageIndex(selectorIndex, entries.size(), PAGE_ITEMS);
updateRequired = true;
requestUpdate();
});
}
}
}
void OpdsBookBrowserActivity::displayTaskLoop() {
while (true) {
if (updateRequired) {
updateRequired = false;
xSemaphoreTake(renderingMutex, portMAX_DELAY);
render();
xSemaphoreGive(renderingMutex);
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
void OpdsBookBrowserActivity::render() const {
void OpdsBookBrowserActivity::render(Activity::RenderLock&&) {
renderer.clearScreen();
const auto pageWidth = renderer.getScreenWidth();
@@ -260,7 +228,7 @@ void OpdsBookBrowserActivity::fetchFeed(const std::string& path) {
if (strlen(serverUrl) == 0) {
state = BrowserState::ERROR;
errorMessage = "No server URL configured";
updateRequired = true;
requestUpdate();
return;
}
@@ -274,7 +242,7 @@ void OpdsBookBrowserActivity::fetchFeed(const std::string& path) {
if (!HttpDownloader::fetchUrl(url, stream)) {
state = BrowserState::ERROR;
errorMessage = "Failed to fetch feed";
updateRequired = true;
requestUpdate();
return;
}
}
@@ -282,7 +250,7 @@ void OpdsBookBrowserActivity::fetchFeed(const std::string& path) {
if (!parser) {
state = BrowserState::ERROR;
errorMessage = "Failed to parse feed";
updateRequired = true;
requestUpdate();
return;
}
@@ -293,12 +261,12 @@ void OpdsBookBrowserActivity::fetchFeed(const std::string& path) {
if (entries.empty()) {
state = BrowserState::ERROR;
errorMessage = "No entries found";
updateRequired = true;
requestUpdate();
return;
}
state = BrowserState::BROWSING;
updateRequired = true;
requestUpdate();
}
void OpdsBookBrowserActivity::navigateToEntry(const OpdsEntry& entry) {
@@ -310,7 +278,7 @@ void OpdsBookBrowserActivity::navigateToEntry(const OpdsEntry& entry) {
statusMessage = "Loading...";
entries.clear();
selectorIndex = 0;
updateRequired = true;
requestUpdate();
fetchFeed(currentPath);
}
@@ -328,7 +296,7 @@ void OpdsBookBrowserActivity::navigateBack() {
statusMessage = "Loading...";
entries.clear();
selectorIndex = 0;
updateRequired = true;
requestUpdate();
fetchFeed(currentPath);
}
@@ -339,7 +307,7 @@ void OpdsBookBrowserActivity::downloadBook(const OpdsEntry& book) {
statusMessage = book.title;
downloadProgress = 0;
downloadTotal = 0;
updateRequired = true;
requestUpdate();
// Build full download URL
std::string downloadUrl = UrlUtils::buildUrl(SETTINGS.opdsServerUrl, book.href);
@@ -357,7 +325,7 @@ void OpdsBookBrowserActivity::downloadBook(const OpdsEntry& book) {
HttpDownloader::downloadToFile(downloadUrl, filename, [this](const size_t downloaded, const size_t total) {
downloadProgress = downloaded;
downloadTotal = total;
updateRequired = true;
requestUpdate();
});
if (result == HttpDownloader::OK) {
@@ -369,11 +337,11 @@ void OpdsBookBrowserActivity::downloadBook(const OpdsEntry& book) {
LOG_DBG("OPDS", "Cleared cache for: %s", filename.c_str());
state = BrowserState::BROWSING;
updateRequired = true;
requestUpdate();
} else {
state = BrowserState::ERROR;
errorMessage = "Download failed";
updateRequired = true;
requestUpdate();
}
}
@@ -382,7 +350,7 @@ void OpdsBookBrowserActivity::checkAndConnectWifi() {
if (WiFi.status() == WL_CONNECTED && WiFi.localIP() != IPAddress(0, 0, 0, 0)) {
state = BrowserState::LOADING;
statusMessage = "Loading...";
updateRequired = true;
requestUpdate();
fetchFeed(currentPath);
return;
}
@@ -393,7 +361,7 @@ void OpdsBookBrowserActivity::checkAndConnectWifi() {
void OpdsBookBrowserActivity::launchWifiSelection() {
state = BrowserState::WIFI_SELECTION;
updateRequired = true;
requestUpdate();
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
[this](const bool connected) { onWifiSelectionComplete(connected); }));
@@ -406,7 +374,7 @@ void OpdsBookBrowserActivity::onWifiSelectionComplete(const bool connected) {
LOG_DBG("OPDS", "WiFi connected via selection, fetching feed");
state = BrowserState::LOADING;
statusMessage = "Loading...";
updateRequired = true;
requestUpdate();
fetchFeed(currentPath);
} else {
LOG_DBG("OPDS", "WiFi selection cancelled/failed");
@@ -416,6 +384,6 @@ void OpdsBookBrowserActivity::onWifiSelectionComplete(const bool connected) {
WiFi.mode(WIFI_OFF);
state = BrowserState::ERROR;
errorMessage = "WiFi connection failed";
updateRequired = true;
requestUpdate();
}
}

View File

@@ -1,8 +1,5 @@
#pragma once
#include <OpdsParser.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#include <functional>
#include <string>
@@ -34,13 +31,10 @@ class OpdsBookBrowserActivity 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;
BrowserState state = BrowserState::LOADING;
std::vector<OpdsEntry> entries;
std::vector<std::string> navigationHistory; // Stack of previous feed paths for back navigation
@@ -53,10 +47,6 @@ class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
const std::function<void()> onGoHome;
static void taskTrampoline(void* param);
[[noreturn]] void displayTaskLoop();
void render() const;
void checkAndConnectWifi();
void launchWifiSelection();
void onWifiSelectionComplete(bool connected);