From 5f6780c8f4ca8925d3f91ac9136e44e085fdacbc Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Sun, 6 Dec 2026 21:55:31 +0100 Subject: [PATCH] Maps supports all platforms, updates for miniz-module and http-client esp_http_client is removed from future SDKs --- Apps/Calendar/main/CMakeLists.txt | 2 +- Apps/Calendar/main/Source/CalendarSync.cpp | 88 ++++++++++--------- Apps/Calendar/manifest.properties | 4 +- Apps/EpubReader/main/CMakeLists.txt | 5 +- Apps/EpubReader/manifest.properties | 4 +- Apps/Maps/main/CMakeLists.txt | 15 +++- Apps/Maps/main/Source/app/BrowsedCounter.cpp | 17 ++-- Apps/Maps/main/Source/app/BrowsedCounter.h | 9 +- Apps/Maps/main/Source/app/Downloader.cpp | 60 ++++++------- Apps/Maps/main/Source/app/Downloader.h | 23 ++--- Apps/Maps/main/Source/app/ElevationJob.cpp | 11 +-- Apps/Maps/main/Source/app/ElevationJob.h | 9 +- Apps/Maps/main/Source/app/EspCompat.h | 38 ++++++++ Apps/Maps/main/Source/app/GpxImport.cpp | 20 ++--- Apps/Maps/main/Source/app/GpxImport.h | 9 +- Apps/Maps/main/Source/app/IoTask.cpp | 11 ++- Apps/Maps/main/Source/app/IoTask.h | 15 ++-- Apps/Maps/main/Source/app/LabelFontMaker.cpp | 14 +-- Apps/Maps/main/Source/app/LabelFontMaker.h | 9 +- Apps/Maps/main/Source/app/LabelStore.h | 4 +- Apps/Maps/main/Source/app/LvglOutput.cpp | 23 +++-- Apps/Maps/main/Source/app/MapApp.cpp | 14 +-- Apps/Maps/main/Source/app/MapDebug.cpp | 16 ++-- Apps/Maps/main/Source/app/MapSearch.cpp | 13 +-- Apps/Maps/main/Source/app/MapView.cpp | 20 ++--- Apps/Maps/main/Source/app/Navigator.cpp | 21 ++--- Apps/Maps/main/Source/app/Navigator.h | 13 +-- .../main/Source/app/PlatformTactility.cpp | 28 +++--- Apps/Maps/main/Source/app/SearchIndexJob.cpp | 38 +++----- Apps/Maps/main/Source/app/SearchIndexJob.h | 11 +-- Apps/Maps/main/Source/app/SearchTask.cpp | 12 +-- Apps/Maps/main/Source/app/SearchTask.h | 15 ++-- Apps/Maps/main/Source/app/StallProbe.cpp | 29 ++++-- Apps/Maps/main/Source/app/StallProbe.h | 9 +- Apps/Maps/main/Source/app/Threads.h | 35 ++++++++ Apps/Maps/main/Source/app/TileWorker.cpp | 63 +++++-------- Apps/Maps/main/Source/app/TileWorker.h | 15 ++-- Apps/Maps/manifest.properties | 8 +- 38 files changed, 414 insertions(+), 336 deletions(-) create mode 100644 Apps/Maps/main/Source/app/EspCompat.h create mode 100644 Apps/Maps/main/Source/app/Threads.h diff --git a/Apps/Calendar/main/CMakeLists.txt b/Apps/Calendar/main/CMakeLists.txt index 7ffe3889..2a7937cf 100644 --- a/Apps/Calendar/main/CMakeLists.txt +++ b/Apps/Calendar/main/CMakeLists.txt @@ -5,6 +5,6 @@ set(L10N_DIR ../../../Libraries/AppLocalisation) tactility_component_register( SRCS ${SOURCE_FILES} ${L10N_DIR}/Source/AppLocalisation.c - REQUIRES http-module esp_http_client mbedtls localisation-module + REQUIRES http-module localisation-module INCLUDE_DIRS ${L10N_DIR}/Include $ENV{TACTILITY_SDK_PATH}/Modules/localisation-module/include ) diff --git a/Apps/Calendar/main/Source/CalendarSync.cpp b/Apps/Calendar/main/Source/CalendarSync.cpp index a2b60e96..f527d1ce 100644 --- a/Apps/Calendar/main/Source/CalendarSync.cpp +++ b/Apps/Calendar/main/Source/CalendarSync.cpp @@ -3,11 +3,8 @@ #include #include -#include +#include #include -#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE -#include -#endif #include #include @@ -60,16 +57,22 @@ bool isValidWindowTimestamp(const char* value) { return true; } -esp_err_t onHttpEvent(esp_http_client_event_t* event) { - auto* parser = static_cast(event->user_data); - if (event->event_id == HTTP_EVENT_ON_DATA && parser != nullptr && event->data_len > 0) { - // The bodies of redirects and authentication challenges are not part of the report. - if (esp_http_client_get_status_code(event->client) >= 300) return ESP_OK; - if (!parser->feed(static_cast(event->data), static_cast(event->data_len))) { - return ESP_FAIL; - } - } - return ESP_OK; +/** The value of a Basic Authorization header for the user and password, or an empty string when it doesn't fit */ +std::string makeBasicAuthorization(const char* username, const char* password) { + static constexpr char ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const std::string credentials = std::string(username) + ":" + password; + std::string result = "Basic "; + for (size_t i = 0; i < credentials.size(); i += 3) { + const size_t left = credentials.size() - i; + const uint32_t chunk = (static_cast(credentials[i]) << 16) | + ((left > 1 ? static_cast(credentials[i + 1]) : 0) << 8) | + (left > 2 ? static_cast(credentials[i + 2]) : 0); + result += ALPHABET[(chunk >> 18) & 63]; + result += ALPHABET[(chunk >> 12) & 63]; + result += left > 1 ? ALPHABET[(chunk >> 6) & 63] : '='; + result += left > 2 ? ALPHABET[chunk & 63] : '='; + } + return result; } bool makeFullCalendarReport(char* report, size_t size, char* error, size_t errorSize) { @@ -137,36 +140,38 @@ bool makeUpcomingReport(char* report, size_t size, bool performReport(const CalendarSyncSettings& settings, const char* report, CalendarResponseParser& parser, const char* invalidMessage, char* message, size_t messageSize) { - esp_http_client_config_t config {}; - config.url = settings.calendarUrl; - config.username = settings.username; - config.password = settings.password; - config.auth_type = HTTP_AUTH_TYPE_BASIC; - config.timeout_ms = HTTP_TIMEOUT_MS; - config.buffer_size = 2048; - config.event_handler = onHttpEvent; - config.user_data = &parser; -#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE - config.crt_bundle_attach = esp_crt_bundle_attach; -#else - copyText(message, messageSize, tr("This firmware has no HTTPS certificate bundle.")); - return false; -#endif - - esp_http_client_handle_t client = esp_http_client_init(&config); + HttpClient* client = http_client_alloc(); if (client == nullptr) { copyText(message, messageSize, tr("Could not create the HTTPS connection.")); return false; } - - esp_err_t result = esp_http_client_set_method(client, HTTP_METHOD_REPORT); - if (result == ESP_OK) result = esp_http_client_set_header(client, "Depth", "1"); - if (result == ESP_OK) result = esp_http_client_set_header(client, "Content-Type", "application/xml; charset=utf-8"); - if (result == ESP_OK) result = esp_http_client_set_header(client, "Accept", "application/xml"); - if (result == ESP_OK) result = esp_http_client_set_post_field(client, report, static_cast(strlen(report))); - if (result == ESP_OK) result = esp_http_client_perform(client); - const int statusCode = esp_http_client_get_status_code(client); - esp_http_client_cleanup(client); + http_client_set_timeout(client, HTTP_TIMEOUT_MS); + // A calendar server may redirect the collection URL, for example to its calendar path + http_client_set_max_redirects(client, 3); + http_client_set_header(client, "Depth", "1"); + http_client_set_header(client, "Content-Type", "application/xml; charset=utf-8"); + http_client_set_header(client, "Accept", "application/xml"); + if (settings.username[0] != '\0') { + // Sent right away, as the client doesn't answer a challenge. It isn't sent to another server after a redirect. + const std::string authorization = makeBasicAuthorization(settings.username, settings.password); + http_client_set_header(client, "Authorization", authorization.c_str()); + } + + bool received = http_client_send(client, "REPORT", settings.calendarUrl, report, strlen(report)) == ERROR_NONE; + const int statusCode = received ? http_client_get_status_code(client) : 0; + // The bodies of redirects and authentication challenges are not part of the report. + if (received && statusCode >= 200 && statusCode < 300) { + char buffer[2048]; + while (true) { + const int read = http_client_read(client, buffer, sizeof(buffer)); + if (read == 0) break; + if (read < 0 || !parser.feed(buffer, static_cast(read))) { + received = false; + break; + } + } + } + http_client_free(client); if (parser.error() == CalendarResponseParser::Error::OutOfMemory) { copyText(message, messageSize, tr("The calendar has too many events for the memory of this device.")); @@ -176,12 +181,11 @@ bool performReport(const CalendarSyncSettings& settings, const char* report, copyText(message, messageSize, tr("A calendar entry is too large to load.")); return false; } - // Checked before the result: the client reports an error for a challenge that it can't answer. if (statusCode == 401 || statusCode == 403) { copyText(message, messageSize, tr("CalDAV authentication failed or access was denied.")); return false; } - if (result != ESP_OK) { + if (!received) { copyText(message, messageSize, tr("Sync failed. Check Wi-Fi, URL and HTTPS certificate.")); return false; } diff --git a/Apps/Calendar/manifest.properties b/Apps/Calendar/manifest.properties index 7834202c..ba1a4e35 100644 --- a/Apps/Calendar/manifest.properties +++ b/Apps/Calendar/manifest.properties @@ -2,8 +2,8 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=esp32,esp32s3,esp32p4,esp32s31 id=tactility.calendar -version.name=0.7.2 -version.code=11 +version.name=0.7.3 +version.code=12 name=Calendar description.short=Read-only CalDAV calendar description.short.de-DE=CalDAV-Kalender (nur lesen) diff --git a/Apps/EpubReader/main/CMakeLists.txt b/Apps/EpubReader/main/CMakeLists.txt index bf2bf32e..a404306b 100644 --- a/Apps/EpubReader/main/CMakeLists.txt +++ b/Apps/EpubReader/main/CMakeLists.txt @@ -5,6 +5,9 @@ set(L10N_DIR ../../../Libraries/AppLocalisation) tactility_component_register( SRCS ${SOURCE_FILES} ${L10N_DIR}/Source/AppLocalisation.c - REQUIRES esp_rom localisation-module + REQUIRES miniz-module localisation-module INCLUDE_DIRS ${L10N_DIR}/Include $ENV{TACTILITY_SDK_PATH}/Modules/localisation-module/include ) +# miniz comes from miniz-module. Its header must come before the older one of esp_rom, which every ESP-IDF component gets, +# and the SDK doesn't add the include directory for apps. +target_include_directories(${COMPONENT_LIB} BEFORE PRIVATE $ENV{TACTILITY_SDK_PATH}/Modules/miniz-module/include) diff --git a/Apps/EpubReader/manifest.properties b/Apps/EpubReader/manifest.properties index 56c93dff..d898ed11 100644 --- a/Apps/EpubReader/manifest.properties +++ b/Apps/EpubReader/manifest.properties @@ -2,8 +2,8 @@ manifest.version=0.3 target.sdk=0.8.0-dev target.platforms=esp32s3,esp32p4,esp32s31 id=tactility.epubreader -version.name=0.28.1 -version.code=29 +version.name=0.28.2 +version.code=30 requires.ram=2M name=ePub Reader description.short=ePub and text file reader diff --git a/Apps/Maps/main/CMakeLists.txt b/Apps/Maps/main/CMakeLists.txt index ebfb0a66..e506570c 100644 --- a/Apps/Maps/main/CMakeLists.txt +++ b/Apps/Maps/main/CMakeLists.txt @@ -3,8 +3,21 @@ include("$ENV{TACTILITY_SDK_PATH}/TactilitySDK.cmake") file(GLOB_RECURSE SOURCE_FILES Source/*.c*) tactility_component_register( SRCS ${SOURCE_FILES} - REQUIRES graphics-module binfont-module location-module http-module esp_rom esp_driver_ppa + REQUIRES graphics-module binfont-module location-module http-module miniz-module esp_driver_ppa ) +# ESP-IDF sets COMPONENT_LIB; host (linux/macOS) builds name the library after the project. +if (NOT DEFINED COMPONENT_LIB) + set(COMPONENT_LIB ${PROJECT_NAME}) +endif () +# The host SDK target doesn't list these modules' include dirs (ESP-IDF resolves them through REQUIRES) +if (NOT ESP_PLATFORM) + target_include_directories(${COMPONENT_LIB} PRIVATE + $ENV{TACTILITY_SDK_PATH}/Modules/graphics-module/include + $ENV{TACTILITY_SDK_PATH}/Modules/location-module/include) +endif () +# miniz comes from miniz-module on every platform. On ESP32 its header must come before the older one of esp_rom, +# which every ESP-IDF component gets, and the SDK no longer adds the include directory for apps. +target_include_directories(${COMPONENT_LIB} BEFORE PRIVATE $ENV{TACTILITY_SDK_PATH}/Modules/miniz-module/include) target_compile_options(${COMPONENT_LIB} PRIVATE -O2 -Wno-format-truncation) # The search index must match the PC's byte for byte (M6): no fused multiply-add in its float maths (MSVC on the PC # does not fuse; GCC would, and one house at the 50 m limit then went to another street) diff --git a/Apps/Maps/main/Source/app/BrowsedCounter.cpp b/Apps/Maps/main/Source/app/BrowsedCounter.cpp index 250ba45f..d6518848 100644 --- a/Apps/Maps/main/Source/app/BrowsedCounter.cpp +++ b/Apps/Maps/main/Source/app/BrowsedCounter.cpp @@ -4,8 +4,8 @@ #include "../platform/Platform.h" #include "../tiles/TileStore.h" -#include -#include +#include "EspCompat.h" +#include "Threads.h" #include @@ -127,7 +127,7 @@ bool BrowsedCounter::count(const DownloadPlan& plan, int64_t& out) const { return true; } -void BrowsedCounter::taskMain(void* context) { +int32_t BrowsedCounter::taskMain(void* context) { auto* counter = static_cast(context); CountJob job { counter->rootPath, counter->counting, 0, false }; // A count that gave way to the map is tried again a little later @@ -140,14 +140,14 @@ void BrowsedCounter::taskMain(void* context) { counter->countingResult = job.count; counter->countingComplete = job.complete; counter->finished = true; - // Deleted by poll() or stop(): a task cannot free its own PSRAM stack - vTaskSuspend(nullptr); + // Joined by poll() or stop(): a thread cannot free its own PSRAM stack + return 0; } bool BrowsedCounter::poll(uint32_t nowMs) { bool changed = false; if (task != nullptr && finished) { - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; if (!countingComplete) { // Gave way to the map too often: try again after a pause @@ -163,8 +163,7 @@ bool BrowsedCounter::poll(uint32_t nowMs) { wanted.fits && wanted.tiles > 0) { counting = wanted; finished = false; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-count", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, - MALLOC_CAP_SPIRAM) != pdPASS) { + if ((task = startThread("maps-count", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { task = nullptr; // Not counted: the estimate simply shows no tiles on the card hasWanted = false; @@ -180,7 +179,7 @@ void BrowsedCounter::stop() { while (!finished) { vTaskDelay(pdMS_TO_TICKS(10)); } - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } diff --git a/Apps/Maps/main/Source/app/BrowsedCounter.h b/Apps/Maps/main/Source/app/BrowsedCounter.h index 8f4b57a8..5929ce16 100644 --- a/Apps/Maps/main/Source/app/BrowsedCounter.h +++ b/Apps/Maps/main/Source/app/BrowsedCounter.h @@ -5,8 +5,9 @@ #include "../tiles/DownloadPlan.h" -#include -#include +#include +#include +#include #include #include @@ -36,12 +37,12 @@ class BrowsedCounter { static constexpr uint32_t SETTLE_MS = 400; private: - static void taskMain(void* context); + static int32_t taskMain(void* context); static bool samePlan(const DownloadPlan& a, const DownloadPlan& b); IoTask* io = nullptr; char rootPath[160] = ""; - TaskHandle_t task = nullptr; + Thread* task = nullptr; std::atomic finished { false }; /** The plan wanted on screen, since when, and the one being counted. */ DownloadPlan wanted {}; diff --git a/Apps/Maps/main/Source/app/Downloader.cpp b/Apps/Maps/main/Source/app/Downloader.cpp index df1af813..a26ce9be 100644 --- a/Apps/Maps/main/Source/app/Downloader.cpp +++ b/Apps/Maps/main/Source/app/Downloader.cpp @@ -11,10 +11,12 @@ #include "../tiles/RegionCatalog.h" #include "../tiles/TileJson.h" -#include -#include +#include "EspCompat.h" +#include "Threads.h" +#include +#include +#include #include -#include #include #include @@ -72,11 +74,12 @@ constexpr size_t MAX_TRAILS_BYTES = 6 * 1024 * 1024; /** * Starts a network task with its stack in PSRAM, which keeps about 28 KB of internal RAM free for Wi-Fi, TLS and - * the display. These tasks never touch flash or the SD card themselves. The task ends by suspending itself after - * signalling its owner, who then deletes it with endNetworkTask(). + * the display. These tasks never touch flash or the SD card themselves. The task returns after signalling + * its owner, who then joins it with endNetworkTask(). */ -bool startNetworkTask(TaskFunction_t function, const char* name, uint32_t stack, void* context, TaskHandle_t* task) { - return xTaskCreatePinnedToCoreWithCaps(function, name, stack, context, TASK_PRIORITY, task, Downloader::NETWORK_CORE, MALLOC_CAP_SPIRAM) == pdPASS; +bool startNetworkTask(ThreadMain function, const char* name, uint32_t stack, void* context, Thread** thread) { + *thread = startThread(name, stack, function, context, TASK_PRIORITY, Downloader::NETWORK_CORE, true); + return *thread != nullptr; } /** @@ -161,17 +164,8 @@ class HttpBodyInput final : public ByteInput { bool overflow = false; }; -void endNetworkTask(TaskHandle_t task) { - // It signalled before suspending itself, wait until it got there - TaskStatus_t status {}; - for (int i = 0; i < 100; i++) { - vTaskGetInfo(task, &status, pdFALSE, eInvalid); - if (status.eCurrentState == eSuspended) { - break; - } - vTaskDelay(pdMS_TO_TICKS(5)); - } - vTaskDeleteWithCaps(task); +void endNetworkTask(Thread* thread) { + joinThread(thread); } constexpr int HTTP_TIMEOUT_MS = 15000; constexpr int SAVE_EVERY_TILES = 20; @@ -745,7 +739,7 @@ bool Downloader::loadOutlineTiles(const RegionMeta& region) { outlineNoMemory = fileSize(catalogPath, bytes); if (outlineNoMemory) { logError("Region catalog %s: no memory for its %u bytes (largest free block %u)", catalogPath, static_cast(bytes), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM))); + static_cast(memory_external_largest_block())); } else { logError("Region catalog %s not readable", catalogPath); } @@ -874,11 +868,11 @@ void Downloader::setStatus(State state, const char* message, bool paused) { } } -void Downloader::controlMain(void* context) { +int32_t Downloader::controlMain(void* context) { auto* downloader = static_cast(context); downloader->controlLoop(); xSemaphoreGive(downloader->stopped); - vTaskSuspend(nullptr); + return 0; } void Downloader::controlLoop() { @@ -977,9 +971,9 @@ bool Downloader::fetchTileJson(Connection& connection) { if (plain != nullptr) { http_client_set_timeout(plain, HTTP_TIMEOUT_MS); http_client_set_header(plain, "User-Agent", USER_AGENT); - const int64_t startUs = esp_timer_get_time(); + const int64_t startUs = get_micros_since_boot(); const error_t opened = http_client_open(plain, "http://tiles.openfreemap.org/planet"); - const int64_t headersUs = esp_timer_get_time(); + const int64_t headersUs = get_micros_since_boot(); logInfo("Timing http: start t=%u ms, headers +%u ms (DNS, TCP and the answer; %s, HTTP %d)", static_cast(startUs / 1000), msSince(startUs, headersUs), opened == ERROR_NONE ? "ok" : "failed", http_client_get_status_code(plain)); http_client_free(plain); @@ -994,10 +988,10 @@ bool Downloader::fetchTileJson(Connection& connection) { // The TileJSON is read as plain text http_client_set_header(client, "Accept-Encoding", "identity"); connection.body->clear(); - const int64_t startUs = esp_timer_get_time(); + const int64_t startUs = get_micros_since_boot(); int status = 0; const HttpResult result = perform(connection, "GET", TILEJSON_URL, status); - const int64_t doneUs = esp_timer_get_time(); + const int64_t doneUs = get_micros_since_boot(); http_client_set_header(client, "Accept-Encoding", "gzip"); ChunkedBody& text = *connection.body; bool ok = false; @@ -1221,11 +1215,11 @@ void Downloader::saveProgress() { writeMeta(copy); } -void Downloader::connectionMain(void* context) { +int32_t Downloader::connectionMain(void* context) { auto* connection = static_cast(context); connection->owner->connectionLoop(*connection); xSemaphoreGive(connection->owner->connectionsDone); - vTaskSuspend(nullptr); + return 0; } void Downloader::connectionLoop(Connection& connection) { @@ -1653,7 +1647,7 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b // The parser and the tiler first: the tiler grows to a few hundred KB (two of them at once while an array doubles), // the map's tile cache makes room when PSRAM has no such block (a browsed block failed on 23 Nov with 250 KB the // largest) - if (memoryRelief != nullptr && heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < TRAILS_PARSE_BLOCK) { + if (memoryRelief != nullptr && memory_external_largest_block() < TRAILS_PARSE_BLOCK) { memoryRelief(memoryReliefContext, TRAILS_PARSE_BLOCK); } void* tilerPlace = largeAlloc(sizeof(TrailTiler)); @@ -1726,7 +1720,7 @@ bool Downloader::runTrailsArea(const char* regionName, const BoundingBox& box, b sinceCheck += static_cast(got); if (sinceCheck >= TRAILS_MEMORY_CHECK_BYTES && memoryRelief != nullptr) { sinceCheck = 0; - if (heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < TRAILS_PARSE_HEADROOM) { + if (memory_external_largest_block() < TRAILS_PARSE_HEADROOM) { memoryRelief(memoryReliefContext, TRAILS_PARSE_HEADROOM); } } @@ -2291,11 +2285,11 @@ void Downloader::prepareBrowsing() { } } -void Downloader::browseMain(void* context) { +int32_t Downloader::browseMain(void* context) { auto* downloader = static_cast(context); downloader->browseLoop(); xSemaphoreGive(downloader->browseStopped); - vTaskSuspend(nullptr); + return 0; } bool Downloader::ensureBrowseRegion(const TileKey& tile) { @@ -2656,7 +2650,7 @@ void Downloader::runPendingTerrain() { if (!browsedWaiting && !(terrainSweep && updatesAllowed)) { return; } - if (heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) < TERRAIN_INTERNAL_BLOCK) { + if (memory_heap_largest_block() < TERRAIN_INTERNAL_BLOCK) { return; } // Heights of browsed areas: a few z12 tiles, fetched whenever they are wanted @@ -2828,7 +2822,7 @@ void Downloader::runPendingTrails() { if (!found && !sweepDue) { return; } - const bool roomy = heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) >= TERRAIN_INTERNAL_BLOCK; + const bool roomy = memory_heap_largest_block() >= TERRAIN_INTERNAL_BLOCK; if (found) { if (!roomy || !claimIdle()) { why(!roomy ? "internal RAM" : "a download or update runs"); diff --git a/Apps/Maps/main/Source/app/Downloader.h b/Apps/Maps/main/Source/app/Downloader.h index 73e42c47..f3faa38e 100644 --- a/Apps/Maps/main/Source/app/Downloader.h +++ b/Apps/Maps/main/Source/app/Downloader.h @@ -9,9 +9,10 @@ #include "../tiles/RegionMeta.h" #include "../tiles/TileStore.h" -#include -#include -#include +#include +#include +#include +#include #include #include @@ -188,8 +189,8 @@ class Downloader { } viewComplete = value; } - TaskHandle_t browseTaskHandle() const { return browseTask; } - TaskHandle_t controlTaskHandle() const { return controlTask; } + TaskHandle_t browseTaskHandle() const { return thread_get_task_handle(browseTask); } + TaskHandle_t controlTaskHandle() const { return thread_get_task_handle(controlTask); } /** Logs the phases of the first TileJSON request (developer option). */ void setTiming(bool value) { timing = value; } @@ -209,7 +210,7 @@ class Downloader { HttpClient* client; ChunkedBody* body; uint64_t received; - TaskHandle_t task; + Thread* task; char lastFolder[PATH_MAX_LENGTH]; /** When the request now running started, and how long its TCP and TLS connect took. */ uint32_t requestStartMs = 0; @@ -273,8 +274,8 @@ class Downloader { /** Frees connection's client. */ static void dropClient(Connection& connection); bool queue(Job next, const char* region); - static void controlMain(void* context); - static void connectionMain(void* context); + static int32_t controlMain(void* context); + static int32_t connectionMain(void* context); void controlLoop(); void runDownload(); void runDelete(); @@ -327,7 +328,7 @@ class Downloader { bool downloadTile(Connection& connection, const char* region, const TileKey& tile, int& status, bool waitForIdle = true); bool tileOnCard(const char* region, const TileKey& tile, bool& inThisRegion); bool ensureTileJson(Connection& connection); - static void browseMain(void* context); + static int32_t browseMain(void* context); void browseLoop(); bool fetchBrowseTile(const TileKey& tile); bool ensureBrowseRegion(const TileKey& tile); @@ -352,7 +353,7 @@ class Downloader { SemaphoreHandle_t mutex = nullptr; SemaphoreHandle_t wake = nullptr; SemaphoreHandle_t stopped = nullptr; - TaskHandle_t controlTask = nullptr; + Thread* controlTask = nullptr; /** The last loadOutlineTiles() failed for memory, not for a missing catalog (for the status text). */ bool outlineNoMemory = false; std::atomic stopRequested = false; @@ -423,7 +424,7 @@ class Downloader { SemaphoreHandle_t transferLock = nullptr; SemaphoreHandle_t browseWake = nullptr; SemaphoreHandle_t browseStopped = nullptr; - TaskHandle_t browseTask = nullptr; + Thread* browseTask = nullptr; static constexpr int BROWSE_QUEUE = 16; static constexpr int BROWSE_EMPTY = 64; TileKey browseQueue[BROWSE_QUEUE] {}; diff --git a/Apps/Maps/main/Source/app/ElevationJob.cpp b/Apps/Maps/main/Source/app/ElevationJob.cpp index f60f2e95..33905b54 100644 --- a/Apps/Maps/main/Source/app/ElevationJob.cpp +++ b/Apps/Maps/main/Source/app/ElevationJob.cpp @@ -5,7 +5,8 @@ #include "../platform/Platform.h" -#include +#include "EspCompat.h" +#include "Threads.h" namespace maps { @@ -28,7 +29,7 @@ void ElevationJob::waitStopped() { vTaskDelay(pdMS_TO_TICKS(10)); } if (task != nullptr && !running.load()) { - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } } @@ -76,18 +77,18 @@ void ElevationJob::start(TileWorker& tileWorker, const Route& route) { stopRequested = false; running = true; currentState = State::Busy; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-elev", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, MALLOC_CAP_SPIRAM) != pdPASS) { + if ((task = startThread("maps-elev", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { running = false; task = nullptr; currentState = State::Idle; } } -void ElevationJob::taskMain(void* context) { +int32_t ElevationJob::taskMain(void* context) { auto* job = static_cast(context); job->run(); job->running = false; - vTaskSuspend(nullptr); + return 0; } void ElevationJob::run() { diff --git a/Apps/Maps/main/Source/app/ElevationJob.h b/Apps/Maps/main/Source/app/ElevationJob.h index f91298b3..f3544dbe 100644 --- a/Apps/Maps/main/Source/app/ElevationJob.h +++ b/Apps/Maps/main/Source/app/ElevationJob.h @@ -4,8 +4,9 @@ #include "../render/ElevationProfile.h" #include "../route/RouteSearch.h" -#include -#include +#include +#include +#include #include @@ -37,12 +38,12 @@ class ElevationJob { void acknowledge(); private: - static void taskMain(void* context); + static int32_t taskMain(void* context); void run(); void waitStopped(); TileWorker* worker = nullptr; - TaskHandle_t task = nullptr; + Thread* task = nullptr; std::atomic currentState = State::Idle; std::atomic stopRequested = false; std::atomic running = false; diff --git a/Apps/Maps/main/Source/app/EspCompat.h b/Apps/Maps/main/Source/app/EspCompat.h new file mode 100644 index 00000000..2ec57ad1 --- /dev/null +++ b/Apps/Maps/main/Source/app/EspCompat.h @@ -0,0 +1,38 @@ +#pragma once + +// ESP-IDF APIs that the host (simulator/desktop) builds lack, mapped to the Tactility kernel or the C library. +// On ESP32 this only includes the ESP-IDF headers. + +#include +#include +#include +#include + +#ifdef ESP_PLATFORM + +#include +#include + +#else + +#include +#include +#include + +#ifndef tskNO_AFFINITY +#define tskNO_AFFINITY 0x7FFFFFFF +#endif + +static inline size_t heap_caps_get_allocated_size(void* pointer) { + return malloc_usable_size(pointer); +} + +static inline int xPortGetCoreID() { + return 0; +} + +static inline void esp_restart() { + std::exit(0); +} + +#endif diff --git a/Apps/Maps/main/Source/app/GpxImport.cpp b/Apps/Maps/main/Source/app/GpxImport.cpp index 0ff0b250..68436cc6 100644 --- a/Apps/Maps/main/Source/app/GpxImport.cpp +++ b/Apps/Maps/main/Source/app/GpxImport.cpp @@ -4,7 +4,8 @@ #include "../platform/Platform.h" #include "../render/PreparedTile.h" -#include +#include "EspCompat.h" +#include "Threads.h" #include #include @@ -81,17 +82,17 @@ bool GpxImport::start(IoTask& ioTask, const char* path) { snprintf(filePath, sizeof(filePath), "%s", path); message[0] = '\0'; currentState = State::Busy; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-gpx", TASK_STACK, this, TASK_PRIORITY, &task, 1, MALLOC_CAP_SPIRAM) != pdPASS) { + if ((task = startThread("maps-gpx", TASK_STACK, taskMain, this, TASK_PRIORITY, 1, true)) == nullptr) { currentState = State::Idle; return false; } return true; } -void GpxImport::taskMain(void* context) { +int32_t GpxImport::taskMain(void* context) { auto* import = static_cast(context); import->run(); - vTaskSuspend(nullptr); + return 0; } void GpxImport::run() { @@ -185,16 +186,7 @@ GpxLayer* GpxImport::takeLayer() { void GpxImport::acknowledge() { if (currentState == State::Done || currentState == State::Failed) { if (task != nullptr) { - // The state is set just before the task suspends itself - TaskStatus_t status {}; - for (int i = 0; i < 100; i++) { - vTaskGetInfo(task, &status, pdFALSE, eInvalid); - if (status.eCurrentState == eSuspended) { - break; - } - vTaskDelay(pdMS_TO_TICKS(5)); - } - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } if (layer != nullptr) { diff --git a/Apps/Maps/main/Source/app/GpxImport.h b/Apps/Maps/main/Source/app/GpxImport.h index d5193578..8c04725d 100644 --- a/Apps/Maps/main/Source/app/GpxImport.h +++ b/Apps/Maps/main/Source/app/GpxImport.h @@ -6,8 +6,9 @@ #include "../tiles/TilePaths.h" #include "../ui/GpxLayer.h" -#include -#include +#include +#include +#include #include @@ -38,12 +39,12 @@ class GpxImport { const char* path() const { return filePath; } private: - static void taskMain(void* context); + static int32_t taskMain(void* context); void run(); void finish(); IoTask* io = nullptr; - TaskHandle_t task = nullptr; + Thread* task = nullptr; std::atomic currentState = State::Idle; char filePath[PATH_MAX_LENGTH] = ""; char message[64] = ""; diff --git a/Apps/Maps/main/Source/app/IoTask.cpp b/Apps/Maps/main/Source/app/IoTask.cpp index 10204880..e68e9b0d 100644 --- a/Apps/Maps/main/Source/app/IoTask.cpp +++ b/Apps/Maps/main/Source/app/IoTask.cpp @@ -1,5 +1,7 @@ // SPDX-License-Identifier: GPL-3.0-or-later #include "IoTask.h" +#include "EspCompat.h" +#include "Threads.h" #include "../platform/Platform.h" @@ -31,8 +33,8 @@ bool IoTask::start() { } stopRequested = false; // Not pinned, so it never takes a core from one render lane only - if (xTaskCreatePinnedToCore(taskMain, "maps-io", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY) != pdPASS) { - task = nullptr; + task = startThread("maps-io", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, false); + if (task == nullptr) { return false; } runningTask = true; @@ -46,6 +48,7 @@ void IoTask::stop() { stopRequested = true; xSemaphoreGive(wake); xSemaphoreTake(stopped, portMAX_DELAY); + joinThread(task); task = nullptr; } runningTask = false; @@ -57,11 +60,11 @@ void IoTask::stop() { } } -void IoTask::taskMain(void* context) { +int32_t IoTask::taskMain(void* context) { auto* io = static_cast(context); io->loop(); xSemaphoreGive(io->stopped); - vTaskDelete(nullptr); + return 0; } bool IoTask::run(IoPriority priority, IoJob job, void* context) { diff --git a/Apps/Maps/main/Source/app/IoTask.h b/Apps/Maps/main/Source/app/IoTask.h index c5a48e46..ab6b838e 100644 --- a/Apps/Maps/main/Source/app/IoTask.h +++ b/Apps/Maps/main/Source/app/IoTask.h @@ -5,9 +5,10 @@ #include "../mvt/ByteInput.h" #include "../tiles/IoQueue.h" -#include -#include -#include +#include +#include +#include +#include #include #include @@ -66,8 +67,8 @@ class IoTask { /** Statistics for the log: jobs run, and the longest wait of a visible job. */ uint32_t longestVisibleWaitMs() const { return longestVisibleWait; } /** The fewest bytes of stack the task had left so far. */ - TaskHandle_t taskHandle() const { return task; } - uint32_t stackLeft() const { return task != nullptr ? static_cast(uxTaskGetStackHighWaterMark(task)) : 0; } + TaskHandle_t taskHandle() const { return thread_get_task_handle(task); } + uint32_t stackLeft() const { return task != nullptr ? thread_get_stack_space(task) : 0; } private: bool writeParts(const char* path, const char* temporaryPath, const uint8_t* const* parts, const size_t* sizes, int partCount, bool canYield); @@ -80,10 +81,10 @@ class IoTask { uint32_t prefetchGeneration; }; - static void taskMain(void* context); + static int32_t taskMain(void* context); void loop(); - TaskHandle_t task = nullptr; + Thread* task = nullptr; SemaphoreHandle_t mutex = nullptr; SemaphoreHandle_t wake = nullptr; SemaphoreHandle_t stopped = nullptr; diff --git a/Apps/Maps/main/Source/app/LabelFontMaker.cpp b/Apps/Maps/main/Source/app/LabelFontMaker.cpp index c8393f8e..b9ef43c3 100644 --- a/Apps/Maps/main/Source/app/LabelFontMaker.cpp +++ b/Apps/Maps/main/Source/app/LabelFontMaker.cpp @@ -5,7 +5,8 @@ #include "../platform/Platform.h" #include -#include +#include "EspCompat.h" +#include "Threads.h" #include #include @@ -94,8 +95,7 @@ bool LabelFontMaker::start(unsigned missingMask) { finished = false; stopRequested = false; written = 0; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-fonts", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, - MALLOC_CAP_SPIRAM) != pdPASS) { + if ((task = startThread("maps-fonts", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { task = nullptr; logError("Label font task not started, the map keeps the system fonts"); return false; @@ -103,12 +103,12 @@ bool LabelFontMaker::start(unsigned missingMask) { return true; } -void LabelFontMaker::taskMain(void* context) { +int32_t LabelFontMaker::taskMain(void* context) { auto* maker = static_cast(context); maker->run(); maker->finished = true; - // Deleted by stop(), a task cannot free its own PSRAM stack - vTaskSuspend(nullptr); + // Joined by stop(), a thread cannot free its own PSRAM stack + return 0; } void LabelFontMaker::run() { @@ -179,7 +179,7 @@ void LabelFontMaker::stop() { } vTaskDelay(pdMS_TO_TICKS(10)); } - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } diff --git a/Apps/Maps/main/Source/app/LabelFontMaker.h b/Apps/Maps/main/Source/app/LabelFontMaker.h index 762a117e..6a3d6d2d 100644 --- a/Apps/Maps/main/Source/app/LabelFontMaker.h +++ b/Apps/Maps/main/Source/app/LabelFontMaker.h @@ -3,8 +3,9 @@ #include "IoTask.h" -#include -#include +#include +#include +#include #include #include @@ -48,7 +49,7 @@ class LabelFontMaker { void stop(); private: - static void taskMain(void* context); + static int32_t taskMain(void* context); void run(); IoTask* io = nullptr; @@ -56,7 +57,7 @@ class LabelFontMaker { char ttfPath[260] = ""; float magnify = 1.0f; unsigned wanted = 0; - TaskHandle_t task = nullptr; + Thread* task = nullptr; std::atomic finished = false; std::atomic stopRequested = false; std::atomic written = 0; diff --git a/Apps/Maps/main/Source/app/LabelStore.h b/Apps/Maps/main/Source/app/LabelStore.h index dd24e557..96c703dd 100644 --- a/Apps/Maps/main/Source/app/LabelStore.h +++ b/Apps/Maps/main/Source/app/LabelStore.h @@ -4,8 +4,8 @@ #include "../render/PreparedLabels.h" #include "../tiles/TileMath.h" -#include -#include +#include +#include #include #include diff --git a/Apps/Maps/main/Source/app/LvglOutput.cpp b/Apps/Maps/main/Source/app/LvglOutput.cpp index 5bebf419..00e65d42 100644 --- a/Apps/Maps/main/Source/app/LvglOutput.cpp +++ b/Apps/Maps/main/Source/app/LvglOutput.cpp @@ -11,10 +11,12 @@ #include #include -#include -#include +#include +#include +#ifdef ESP_PLATFORM #include -#if defined(SOC_PPA_SUPPORTED) && SOC_PPA_SUPPORTED +#endif +#if defined(ESP_PLATFORM) && defined(SOC_PPA_SUPPORTED) && SOC_PPA_SUPPORTED #include #define MAPS_HAS_PPA 1 #else @@ -35,6 +37,12 @@ constexpr uint32_t TAKE_INTERVAL_MS = 500; /** The PPA writes whole cache lines of external memory (L1 and L2): its target buffers start and end on these. */ constexpr size_t PPA_ALIGNMENT = 128; +/** A block of external memory (PSRAM when there is some) that starts on a multiple of alignment. */ +void* externalAlloc(size_t size, size_t alignment) { + const MemoryPolicy policy = { .required = 0, .desired = MEMORY_CAPABILITY_EXTERNAL, .alignment = alignment }; + return memory_alloc_with_policy(size, &policy); +} + /** The image is the map: no scrolling, no focus, no gestures for the screen behind it. */ void configureMapImage(lv_obj_t* image) { lv_obj_set_clickable(image, true); @@ -81,8 +89,7 @@ bool LvglOutput::begin(Device* displayDevice, AppInstanceId app, int renderPerce const size_t bytes = static_cast(frameWidth) * frameHeight * sizeof(uint16_t); for (int i = 0; i < 2; i++) { // The PPA writes into these when it scales the map up: whole cache lines - buffers[i] = static_cast(scaled ? heap_caps_aligned_alloc(PPA_ALIGNMENT, (bytes + PPA_ALIGNMENT - 1) / PPA_ALIGNMENT * PPA_ALIGNMENT, - MALLOC_CAP_SPIRAM) + buffers[i] = static_cast(scaled ? externalAlloc((bytes + PPA_ALIGNMENT - 1) / PPA_ALIGNMENT * PPA_ALIGNMENT, PPA_ALIGNMENT) : largeAlloc(bytes)); if (buffers[i] == nullptr) { logError("No memory for the LVGL frames"); @@ -119,7 +126,7 @@ void LvglOutput::end() { const bool scaled = renderBuffer != nullptr; for (auto*& buffer : buffers) { if (scaled) { - heap_caps_free(buffer); + memory_free(buffer); } else { largeFree(buffer); } @@ -142,7 +149,7 @@ bool LvglOutput::startPpa(int renderPercent) { ppaScale = renderPercent <= 50 ? 2.0f : 21.0f / 16.0f; renderWidth = static_cast(frameWidth / ppaScale); renderHeight = static_cast(frameHeight / ppaScale); - renderBuffer = static_cast(heap_caps_malloc(static_cast(renderWidth) * renderHeight * sizeof(uint16_t), MALLOC_CAP_SPIRAM)); + renderBuffer = static_cast(externalAlloc(static_cast(renderWidth) * renderHeight * sizeof(uint16_t), 0)); ppa_client_config_t config {}; config.oper_type = PPA_OPERATION_SRM; config.max_pending_trans_num = 1; @@ -169,7 +176,7 @@ void LvglOutput::stopPpa() { ppaClient = nullptr; } #endif - heap_caps_free(renderBuffer); + memory_free(renderBuffer); renderBuffer = nullptr; renderWidth = frameWidth; renderHeight = frameHeight; diff --git a/Apps/Maps/main/Source/app/MapApp.cpp b/Apps/Maps/main/Source/app/MapApp.cpp index 1086eca7..46e53018 100644 --- a/Apps/Maps/main/Source/app/MapApp.cpp +++ b/Apps/Maps/main/Source/app/MapApp.cpp @@ -15,9 +15,9 @@ #include #include -#include -#include -#include +#include +#include +#include #include #include #include @@ -58,8 +58,8 @@ void logSession(const char* root, uint32_t startPsram, uint32_t startInternal) { char line[96]; snprintf(line, sizeof(line), "uptime %u s start %u/%u KB exit %u/%u KB (PSRAM/internal)\n", static_cast(nowMs() / 1000), static_cast(startPsram / 1024), static_cast(startInternal / 1024), - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), - static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL) / 1024)); + static_cast(memory_external_free() / 1024), + static_cast(memory_heap_free() / 1024)); if (FILE* file = fopen(path, "w")) { fputs(from, file); fputs(line, file); @@ -293,8 +293,8 @@ extern "C" int main(int argc, char* argv[]) { maps::logError("No display"); return 0; } - const auto startPsram = static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); - const auto startInternal = static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); + const auto startPsram = static_cast(memory_external_free()); + const auto startInternal = static_cast(memory_heap_free()); if (module_is_started(&lvgl_module)) { maps::runLvgl(display, root, dataPath, start); } else { diff --git a/Apps/Maps/main/Source/app/MapDebug.cpp b/Apps/Maps/main/Source/app/MapDebug.cpp index 20909f6a..34f3449b 100644 --- a/Apps/Maps/main/Source/app/MapDebug.cpp +++ b/Apps/Maps/main/Source/app/MapDebug.cpp @@ -7,10 +7,10 @@ #include "../platform/Platform.h" #include "../ui/Metrics.h" -#include -#include -#include -#include +#include +#include +#include +#include "EspCompat.h" #include #include @@ -203,10 +203,10 @@ void MapView::runDebugStep(const DebugScript::Step& step, uint32_t now) { logInfo("%s", line); // Into the script log too: the serial line is not always there (silent after a restart, 13 Nov) scriptLog("Memory %s: internal %u free (largest %u), PSRAM %u free (largest %u)", step.name, - static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM))); + static_cast(memory_heap_free()), + static_cast(memory_heap_largest_block()), + static_cast(memory_external_free()), + static_cast(memory_external_largest_block())); scriptLog("%s", line); break; } diff --git a/Apps/Maps/main/Source/app/MapSearch.cpp b/Apps/Maps/main/Source/app/MapSearch.cpp index cfa52a75..da728edd 100644 --- a/Apps/Maps/main/Source/app/MapSearch.cpp +++ b/Apps/Maps/main/Source/app/MapSearch.cpp @@ -6,8 +6,9 @@ #include "../platform/Platform.h" #include "../route/RouteSearch.h" -#include +#include "EspCompat.h" +#include #include #include #include @@ -246,7 +247,7 @@ bool MapView::loadSearchIndexes() { delete blocks; } // The name area and the key pages of the nearest index in PSRAM, when there is room (study: 0.76 MB for Bratislava) - if (searchFileCount > 0 && heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) > 1200 * 1024) { + if (searchFileCount > 0 && memory_external_largest_block() > 1200 * 1024) { const uint32_t started = nowMs(); bool loaded = false; auto load = [&]() { loaded = searchEngine->loadResident(0, true, true); }; @@ -685,8 +686,8 @@ void MapView::startSearchIndex(bool force, const char* only) { } if (searchIndexJob.start(io, rootPath, first, force, only)) { scriptLog("Search index build started%s (PSRAM %u KB free, largest block %u KB)", force ? " (force)" : "", - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + static_cast(memory_external_free() / 1024), + static_cast(memory_external_largest_block() / 1024)); } searchIndexDue = false; } @@ -734,8 +735,8 @@ void MapView::pollSearchIndex(uint32_t now) { downloading || navigating || worker.isPreparing()) { return; } - if (heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < SEARCH_INDEX_MIN_FREE || - heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < SEARCH_INDEX_MIN_BLOCK) { + if (memory_external_free() < SEARCH_INDEX_MIN_FREE || + memory_external_largest_block() < SEARCH_INDEX_MIN_BLOCK) { return; } startSearchIndex(false); diff --git a/Apps/Maps/main/Source/app/MapView.cpp b/Apps/Maps/main/Source/app/MapView.cpp index 87128ac4..6b64fffb 100644 --- a/Apps/Maps/main/Source/app/MapView.cpp +++ b/Apps/Maps/main/Source/app/MapView.cpp @@ -5,6 +5,7 @@ #include "../ui/Metrics.h" +#include #include #include "../platform/Platform.h" @@ -17,11 +18,10 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include "EspCompat.h" +#include #include #include @@ -121,7 +121,7 @@ bool MapView::begin(FrameOutput& frameOutput, Input& inputSource, const char* ro // The cache holds the tiles of the screen in map pixels const int mapWidth = static_cast(std::ceil(width / magnify)); const int mapHeight = static_cast(std::ceil(height / magnify)); - if (!worker.start(&store, &io, palette, tileCacheSlots(mapWidth, mapHeight, heap_caps_get_free_size(MALLOC_CAP_SPIRAM)), root)) { + if (!worker.start(&store, &io, palette, tileCacheSlots(mapWidth, mapHeight, memory_external_free()), root)) { return false; } startServices(root); @@ -244,7 +244,7 @@ void MapView::startLabels(const char* root) { labelsReady = labelStore.begin() && labels.begin(largeAlloc, largeFree); if (labelsReady) { worker.setLabelStore(&labelStore); - labels.setClock([] { return static_cast(esp_timer_get_time()); }); + labels.setClock([] { return static_cast(get_micros_since_boot()); }); applyLabelFonts(); applyLabelSettings(); } else { @@ -402,7 +402,7 @@ void MapView::squeezeMemory(size_t largest) { constexpr size_t BLOCK = 64 * 1024; int taken = 0; void* blocks[MAX_SQUEEZED * 2]; - while (taken < MAX_SQUEEZED * 2 && heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) >= largest) { + while (taken < MAX_SQUEEZED * 2 && memory_external_largest_block() >= largest) { void* block = largeAlloc(BLOCK); if (block == nullptr) { break; @@ -417,8 +417,8 @@ void MapView::squeezeMemory(size_t largest) { } } logInfo("debug: squeeze: %d blocks of 64 KB held, PSRAM %u KB free, largest block %u KB", squeezedCount, - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + static_cast(memory_external_free() / 1024), + static_cast(memory_external_largest_block() / 1024)); } void MapView::layoutControls() { diff --git a/Apps/Maps/main/Source/app/Navigator.cpp b/Apps/Maps/main/Source/app/Navigator.cpp index c667711d..7051ef05 100644 --- a/Apps/Maps/main/Source/app/Navigator.cpp +++ b/Apps/Maps/main/Source/app/Navigator.cpp @@ -8,9 +8,10 @@ #include "../route/RouteTrack.h" #include "../tiles/TileStore.h" -#include -#include +#include "EspCompat.h" +#include "Threads.h" +#include #include #include #include @@ -143,7 +144,7 @@ class Navigator::CardSource final : public GraphSource { readFailures++; logInfo("Route: no graph for %d/%d/%d (%s, yielded %d, %u bytes short, largest free block %u KB)", tile.z, tile.x, tile.y, job.found ? "file not read" : "no tile", job.yielded ? 1 : 0, static_cast(buffer.lastShortfall()), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + static_cast(memory_external_largest_block() / 1024)); return false; } // The buffer stays for the next tile: allocating it again for each tile left PSRAM in pieces @@ -154,7 +155,7 @@ class Navigator::CardSource final : public GraphSource { // The map draws tiles and places labels meanwhile: it keeps at least this much. Its largest need is one tile // cache slot (128 KB; conversions wait while a route is searched), so 160 KB in one piece: with 256 KB a PSRAM // in pieces ended Kosice - Bratislava early (T-Deck, 15 Nov 2026), though the budget had room - return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < 160 * 1024 || heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < 512 * 1024; + return memory_external_largest_block() < 160 * 1024 || memory_external_free() < 512 * 1024; } int readFailures = 0; /** Graphs made because the search asked for them. */ @@ -188,7 +189,7 @@ bool Navigator::start(IoTask& ioTask, TileStore& tileStore, TileWorker& tileWork logInfo("Route loaded: %s, %u points, %.0f m", routeProfileName(routes[current].profile), static_cast(routes[current].points.size()), routes[current].lengthM); } - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-route", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, MALLOC_CAP_SPIRAM) != pdPASS) { + if ((task = startThread("maps-route", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { task = nullptr; return false; } @@ -207,7 +208,7 @@ void Navigator::stop() { search.cancel(); xSemaphoreGive(wake); xSemaphoreTake(stopped, portMAX_DELAY); - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } for (SemaphoreHandle_t* handle : { &wake, &mutex, &stopped }) { @@ -366,8 +367,9 @@ void Navigator::clearRoute() { runOnCard(*io, remove); } -void Navigator::taskMain(void* context) { +int32_t Navigator::taskMain(void* context) { static_cast(context)->loop(); + return 0; } void Navigator::loop() { @@ -388,7 +390,6 @@ void Navigator::loop() { } } xSemaphoreGive(stopped); - vTaskSuspend(nullptr); } bool Navigator::takeMemory() { @@ -396,11 +397,11 @@ bool Navigator::takeMemory() { // The node table is one block of up to 1 MB: the tile cache makes room for it, then the search takes what is free // Down to 6 slots: enough for the tiles on screen while the user waits for the route worker->relieveMemory(1100 * 1024, SEARCH_BYTES + KEEP_FREE_BYTES, 6); - const size_t free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM); + const size_t free = memory_external_free(); const size_t budget = std::min(SEARCH_BYTES, free > KEEP_FREE_BYTES ? free - KEEP_FREE_BYTES : 0); if (budget < 512 * 1024 || !search.begin(budget, requestProfile)) { logError("Route: no memory for a search (%u KB free, largest block %u KB)", static_cast(free / 1024), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + static_cast(memory_external_largest_block() / 1024)); search.end(); worker->restoreMemory(); worker->setRouting(false); diff --git a/Apps/Maps/main/Source/app/Navigator.h b/Apps/Maps/main/Source/app/Navigator.h index 9e94481c..89bbd62e 100644 --- a/Apps/Maps/main/Source/app/Navigator.h +++ b/Apps/Maps/main/Source/app/Navigator.h @@ -6,9 +6,10 @@ #include "../route/RouteSearch.h" #include "../tiles/TilePaths.h" -#include -#include -#include +#include +#include +#include +#include #include #include @@ -70,12 +71,12 @@ class Navigator { void clearRoute(); /** For the stack measurements of the debug script. */ - TaskHandle_t taskHandle() const { return task; } + TaskHandle_t taskHandle() const { return thread_get_task_handle(task); } private: enum class Job : uint8_t { None, Route, Bench, Sides, Track, Quit }; - static void taskMain(void* context); + static int32_t taskMain(void* context); void loop(); void runRoute(); /** Makes the missing z14 graphs around both ends of a long route before the search starts. */ @@ -108,7 +109,7 @@ class Navigator { TileWorker* worker = nullptr; char routePath[PATH_MAX_LENGTH] = ""; char benchPath[PATH_MAX_LENGTH] = ""; - TaskHandle_t task = nullptr; + Thread* task = nullptr; SemaphoreHandle_t wake = nullptr; SemaphoreHandle_t mutex = nullptr; SemaphoreHandle_t stopped = nullptr; diff --git a/Apps/Maps/main/Source/app/PlatformTactility.cpp b/Apps/Maps/main/Source/app/PlatformTactility.cpp index fb24f2b5..f4c19a10 100644 --- a/Apps/Maps/main/Source/app/PlatformTactility.cpp +++ b/Apps/Maps/main/Source/app/PlatformTactility.cpp @@ -5,15 +5,15 @@ #include #include -#include -#include +#include "EspCompat.h" +#include #include #include #include #include #include -#include +#include #include #include @@ -64,11 +64,11 @@ void largeFree(void* pointer) { } uint64_t nowUs() { - return static_cast(esp_timer_get_time()); + return static_cast(get_micros_since_boot()); } uint32_t nowMs() { - return static_cast(esp_timer_get_time() / 1000); + return static_cast(get_micros_since_boot() / 1000); } namespace { @@ -118,7 +118,7 @@ void mirror(const char* level, const char* message) { return; } char line[200]; - const int length = snprintf(line, sizeof(line), "%u %s%s\n", static_cast(esp_timer_get_time() / 1000), level, message); + const int length = snprintf(line, sizeof(line), "%u %s%s\n", static_cast(get_micros_since_boot() / 1000), level, message); if (length <= 0) { return; } @@ -138,11 +138,11 @@ void setLogMirror(const char* word) { if (word != nullptr && word[0] != '\0' && mirrorLock.load(std::memory_order_acquire) == nullptr) { // Never freed: a few KB for the rest of the app session, only when a script asks for it. The lock is published // last: mirror() starts once it is there - mirrorBuffer = static_cast(heap_caps_malloc(MIRROR_BYTES, MALLOC_CAP_SPIRAM)); + mirrorBuffer = static_cast(largeAlloc(MIRROR_BYTES)); if (mirrorBuffer != nullptr) { SemaphoreHandle_t made = xSemaphoreCreateMutex(); if (made == nullptr) { - heap_caps_free(mirrorBuffer); + largeFree(mirrorBuffer); mirrorBuffer = nullptr; } mirrorLock.store(made, std::memory_order_release); @@ -215,14 +215,12 @@ void logError(const char* format, ...) { } void logMemory(const char* label) { - LOG_I(TAG, "Memory %s: internal %u free (largest %u), DMA %u free (largest %u), PSRAM %u free (largest %u), app large blocks %u in %u", + LOG_I(TAG, "Memory %s: internal %u free (largest %u), PSRAM %u free (largest %u), app large blocks %u in %u", label, - static_cast(heap_caps_get_free_size(MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_free_size(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL)), - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)), + static_cast(memory_heap_free()), + static_cast(memory_heap_largest_block()), + static_cast(memory_external_free()), + static_cast(memory_external_largest_block()), static_cast(largeBytes.load()), static_cast(largeBlocks.load())); } diff --git a/Apps/Maps/main/Source/app/SearchIndexJob.cpp b/Apps/Maps/main/Source/app/SearchIndexJob.cpp index 7e745590..300c30d4 100644 --- a/Apps/Maps/main/Source/app/SearchIndexJob.cpp +++ b/Apps/Maps/main/Source/app/SearchIndexJob.cpp @@ -9,7 +9,9 @@ #include "../tiles/RegionMeta.h" #include "../tiles/TileStore.h" -#include +#include "EspCompat.h" +#include "Threads.h" +#include #include #include @@ -450,18 +452,6 @@ bool keepGoingHook(const StreamProgress& progress, void* context) { return hook->job->keepGoing(static_cast(progress.done), static_cast(progress.total), progress.phase); } -/** The task suspends itself when its work is over: it must not run any more when it is deleted. */ -void waitUntilSuspended(TaskHandle_t task) { - TaskStatus_t status {}; - for (;;) { - vTaskGetInfo(task, &status, pdFALSE, eInvalid); - if (status.eCurrentState == eSuspended) { - return; - } - vTaskDelay(pdMS_TO_TICKS(5)); - } -} - } // namespace Translit translitForRegion(const char* region) { @@ -489,11 +479,10 @@ bool SearchIndexJob::start(IoTask& ioTask, const char* rootPath, const char* fir paused = false; progressDone = 0; progressTotal = 0; - lowestFree = static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + lowestFree = static_cast(memory_external_free()); buildLowestFree = lowestFree; currentState = State::Busy; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-sidx", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, MALLOC_CAP_SPIRAM) != - pdPASS) { + if ((task = startThread("maps-sidx", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { task = nullptr; currentState = State::Failed; return false; @@ -510,37 +499,34 @@ void SearchIndexJob::stop() { while (currentState.load() == State::Busy) { vTaskDelay(pdMS_TO_TICKS(20)); } - // The state is set just before the task suspends itself; delete it from here once it has - waitUntilSuspended(task); - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } void SearchIndexJob::acknowledge() { if (currentState.load() != State::Busy) { if (task != nullptr) { - waitUntilSuspended(task); - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } currentState = State::Idle; } } -void SearchIndexJob::taskMain(void* context) { +int32_t SearchIndexJob::taskMain(void* context) { auto* self = static_cast(context); self->run(); - vTaskSuspend(nullptr); + return 0; } bool SearchIndexJob::keepGoing(int32_t done, int32_t total, uint8_t phase) { progressDone = done; progressTotal = total; - const auto free = static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + const auto free = static_cast(memory_external_free()); lowestFree = std::min(lowestFree, free); buildLowestFree = std::min(buildLowestFree, free); if (phase < MEMORY_PHASES) { - const auto largest = static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); + const auto largest = static_cast(memory_external_largest_block()); phaseFree[phase] = std::min(phaseFree[phase], free); phaseLargest[phase] = std::min(phaseLargest[phase], largest); } @@ -759,7 +745,7 @@ bool SearchIndexJob::buildRegion(const char* region) { } MvtDecoder* owned = decoder; CardTileSource source(*io, regionPath, buffer, owned); - const uint32_t freeBefore = static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + const uint32_t freeBefore = static_cast(memory_external_free()); lowestFree = freeBefore; for (int i = 0; i < MEMORY_PHASES; i++) { phaseFree[i] = UINT32_MAX; diff --git a/Apps/Maps/main/Source/app/SearchIndexJob.h b/Apps/Maps/main/Source/app/SearchIndexJob.h index 363da763..9361bc39 100644 --- a/Apps/Maps/main/Source/app/SearchIndexJob.h +++ b/Apps/Maps/main/Source/app/SearchIndexJob.h @@ -6,8 +6,9 @@ #include "../search/TextFold.h" #include "../tiles/TilePaths.h" -#include -#include +#include +#include +#include #include #include @@ -64,15 +65,15 @@ class SearchIndexJob { void report(const char* format, ...); /** For the stack measurements of the debug script. */ - TaskHandle_t taskHandle() const { return task; } + TaskHandle_t taskHandle() const { return thread_get_task_handle(task); } private: - static void taskMain(void* context); + static int32_t taskMain(void* context); void run(); bool buildRegion(const char* region); IoTask* io = nullptr; - TaskHandle_t task = nullptr; + Thread* task = nullptr; std::atomic currentState = State::Idle; std::atomic paused = false; std::atomic stopping = false; diff --git a/Apps/Maps/main/Source/app/SearchTask.cpp b/Apps/Maps/main/Source/app/SearchTask.cpp index b97cabbc..7f7ca7d9 100644 --- a/Apps/Maps/main/Source/app/SearchTask.cpp +++ b/Apps/Maps/main/Source/app/SearchTask.cpp @@ -3,7 +3,8 @@ #include "../platform/Platform.h" -#include +#include "EspCompat.h" +#include "Threads.h" namespace maps { @@ -25,8 +26,7 @@ bool SearchTask::start() { return false; } quit = false; - if (xTaskCreatePinnedToCoreWithCaps(taskMain, "maps-search", TASK_STACK, this, TASK_PRIORITY, &task, tskNO_AFFINITY, MALLOC_CAP_SPIRAM) != - pdPASS) { + if ((task = startThread("maps-search", TASK_STACK, taskMain, this, TASK_PRIORITY, tskNO_AFFINITY, true)) == nullptr) { task = nullptr; stop(); logError("Search: no task"); @@ -40,7 +40,7 @@ void SearchTask::stop() { quit = true; xSemaphoreGive(wake); xSemaphoreTake(done, portMAX_DELAY); - vTaskDeleteWithCaps(task); + joinThread(task); task = nullptr; } if (wake != nullptr) { @@ -64,7 +64,7 @@ bool SearchTask::run(Job job, void* context) { return true; } -void SearchTask::taskMain(void* context) { +int32_t SearchTask::taskMain(void* context) { auto* self = static_cast(context); while (true) { xSemaphoreTake(self->wake, portMAX_DELAY); @@ -75,7 +75,7 @@ void SearchTask::taskMain(void* context) { xSemaphoreGive(self->done); } xSemaphoreGive(self->done); - vTaskSuspend(nullptr); + return 0; } } // namespace maps diff --git a/Apps/Maps/main/Source/app/SearchTask.h b/Apps/Maps/main/Source/app/SearchTask.h index c9ebd4d1..d76c9ceb 100644 --- a/Apps/Maps/main/Source/app/SearchTask.h +++ b/Apps/Maps/main/Source/app/SearchTask.h @@ -1,9 +1,10 @@ // SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include -#include -#include +#include +#include +#include +#include #include @@ -24,15 +25,15 @@ class SearchTask { /** Runs job(context) on the task and waits for it. False when the task could not start. */ bool run(Job job, void* context); /** The least stack the task has had left, in bytes (for the log). */ - uint32_t stackLeft() const { return task != nullptr ? static_cast(uxTaskGetStackHighWaterMark(task)) : 0; } + uint32_t stackLeft() const { return task != nullptr ? thread_get_stack_space(task) : 0; } /** For the stack measurements of the debug script. */ - TaskHandle_t taskHandle() const { return task; } + TaskHandle_t taskHandle() const { return thread_get_task_handle(task); } private: - static void taskMain(void* context); + static int32_t taskMain(void* context); - TaskHandle_t task = nullptr; + Thread* task = nullptr; SemaphoreHandle_t wake = nullptr; SemaphoreHandle_t done = nullptr; Job pending = nullptr; diff --git a/Apps/Maps/main/Source/app/StallProbe.cpp b/Apps/Maps/main/Source/app/StallProbe.cpp index bcf17e4b..a17131d5 100644 --- a/Apps/Maps/main/Source/app/StallProbe.cpp +++ b/Apps/Maps/main/Source/app/StallProbe.cpp @@ -2,8 +2,12 @@ #include "StallProbe.h" #include "../platform/Platform.h" +#include "EspCompat.h" +#include "Threads.h" -#include +#include + +#include namespace maps { @@ -18,7 +22,8 @@ constexpr uint32_t PROBE_STACK = 3072; bool StallProbe::startWatchdog() { stopRequested = false; watchdogOnly = true; - if (xTaskCreatePinnedToCore(probeMain, "maps-watchdog", PROBE_STACK, this, PROBE_PRIORITY, &tasks[0], tskNO_AFFINITY) != pdPASS) { + threads[0] = startThread("maps-watchdog", PROBE_STACK, probeMain, this, PROBE_PRIORITY, tskNO_AFFINITY, false); + if (threads[0] == nullptr) { return false; } running++; @@ -29,8 +34,8 @@ bool StallProbe::start() { stopRequested = false; watchdogOnly = false; for (int core = 0; core < 2; core++) { - if (xTaskCreatePinnedToCore(probeMain, core == 0 ? "maps-probe0" : "maps-probe1", PROBE_STACK, this, PROBE_PRIORITY, - &tasks[core], core) != pdPASS) { + threads[core] = startThread(core == 0 ? "maps-probe0" : "maps-probe1", PROBE_STACK, probeMain, this, PROBE_PRIORITY, core, false); + if (threads[core] == nullptr) { stop(); return false; } @@ -46,6 +51,12 @@ void StallProbe::stop() { while (running > 0) { vTaskDelay(pdMS_TO_TICKS(10)); } + for (Thread*& thread : threads) { + if (thread != nullptr) { + joinThread(thread); + thread = nullptr; + } + } } void StallProbe::watch(TaskHandle_t task, const char* name) { @@ -69,16 +80,16 @@ void StallProbe::logTaskStates(uint32_t stalledMs) { logInfo("%s", line); } -void StallProbe::probeMain(void* context) { +int32_t StallProbe::probeMain(void* context) { auto* probe = static_cast(context); const int core = xPortGetCoreID(); const int64_t tickUs = static_cast(portTICK_PERIOD_MS) * 1000; - int64_t last = esp_timer_get_time(); + int64_t last = get_micros_since_boot(); int64_t nextMemory = last; while (probe->watchdogOnly && !probe->stopRequested) { vTaskDelay(pdMS_TO_TICKS(250)); const uint32_t beat = probe->lastBeat; - const auto nowMs = static_cast(esp_timer_get_time() / 1000); + const auto nowMs = static_cast(get_micros_since_boot() / 1000); if (beat != 0 && nowMs - beat > WATCHDOG_MS && probe->reportedBeat != beat) { probe->reportedBeat = beat; probe->logTaskStates(nowMs - beat); @@ -87,7 +98,7 @@ void StallProbe::probeMain(void* context) { } while (!probe->watchdogOnly && !probe->stopRequested) { vTaskDelay(1); - const int64_t now = esp_timer_get_time(); + const int64_t now = get_micros_since_boot(); const int64_t lateUs = now - last - tickUs; if (lateUs > static_cast(GAP_MS) * 1000) { logInfo("Stall on core %d: %u ms, from t=%u ms", core, static_cast(lateUs / 1000), static_cast(last / 1000)); @@ -107,7 +118,7 @@ void StallProbe::probeMain(void* context) { } } probe->running--; - vTaskDelete(nullptr); + return 0; } } // namespace maps diff --git a/Apps/Maps/main/Source/app/StallProbe.h b/Apps/Maps/main/Source/app/StallProbe.h index 1e317c76..fac359e9 100644 --- a/Apps/Maps/main/Source/app/StallProbe.h +++ b/Apps/Maps/main/Source/app/StallProbe.h @@ -1,8 +1,9 @@ // SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include -#include +#include +#include +#include #include #include @@ -39,7 +40,7 @@ class StallProbe { void heartbeat(uint32_t nowMs) { lastBeat = nowMs; } private: - static void probeMain(void* context); + static int32_t probeMain(void* context); void logTaskStates(uint32_t stalledMs); struct Watched { @@ -53,7 +54,7 @@ class StallProbe { std::atomic currentPhase = "start"; bool watchdogOnly = false; - TaskHandle_t tasks[2] {}; + Thread* threads[2] {}; std::atomic stopRequested = false; std::atomic running = 0; }; diff --git a/Apps/Maps/main/Source/app/Threads.h b/Apps/Maps/main/Source/app/Threads.h new file mode 100644 index 00000000..7854d58b --- /dev/null +++ b/Apps/Maps/main/Source/app/Threads.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +namespace maps { + +using ThreadMain = int32_t (*)(void* context); + +/** + * Creates and starts a thread. A stack in external memory (PSRAM) keeps internal RAM free, but that thread must not + * touch flash or the SD card itself. The priority is the FreeRTOS one. Returns nullptr when it could not start. + */ +inline Thread* startThread(const char* name, size_t stackBytes, ThreadMain function, void* context, int priority, BaseType_t affinity, bool externalStack) { + Thread* thread = thread_alloc_full(name, stackBytes, function, context, affinity); + if (thread == nullptr) { + return nullptr; + } + // The simulator has fewer priority levels than an ESP32 (configMAX_PRIORITIES 10): a higher one asserts there + constexpr int maxPriority = static_cast(configMAX_PRIORITIES) - 1; + thread_set_priority(thread, static_cast(priority > maxPriority ? maxPriority : priority)); + thread_set_stack_external(thread, externalStack); + if (thread_start(thread) != ERROR_NONE) { + thread_free(thread); + return nullptr; + } + return thread; +} + +/** Waits until the thread's main function returned, then frees it. A thread cannot free its own external stack. */ +inline void joinThread(Thread* thread) { + thread_join(thread, portMAX_DELAY, 5); + thread_free(thread); +} + +} // namespace maps diff --git a/Apps/Maps/main/Source/app/TileWorker.cpp b/Apps/Maps/main/Source/app/TileWorker.cpp index 9061945b..d764ef2c 100644 --- a/Apps/Maps/main/Source/app/TileWorker.cpp +++ b/Apps/Maps/main/Source/app/TileWorker.cpp @@ -5,8 +5,9 @@ #include "../platform/Platform.h" #include "../render/TileCodec.h" -#include -#include +#include "EspCompat.h" +#include "Threads.h" +#include #include #include @@ -25,26 +26,6 @@ constexpr uint32_t TASK_STACK = 10240; constexpr size_t KEEP_FILE_BUFFER = 256 * 1024; constexpr UBaseType_t TASK_PRIORITY = 4; -/** Deletes a lane task that stopped, once it suspended itself (taskMain). */ -void deleteLaneTask(TaskHandle_t task) { - if (task == nullptr) { - return; - } - // Deleted only once it is suspended: before that it may still run on the other core, on the stack this frees. - // It gave the stopped signal and has only its suspend left, so this is short; a lane that takes long is logged. - TaskStatus_t status {}; - for (int i = 0;; i++) { - vTaskGetInfo(task, &status, pdFALSE, eInvalid); - if (status.eCurrentState == eSuspended) { - break; - } - if (i == 100) { - logError("Tile worker: a stopped lane hasn't suspended after 500 ms, waiting on"); - } - vTaskDelay(pdMS_TO_TICKS(5)); - } - vTaskDeleteWithCaps(task); -} constexpr uint32_t IDLE_WAIT_MS = 30; /** A conversion starts only with a PSRAM block this large free (the compressor needs 320 KB in one block), and this * much PSRAM free in all for the original, the features and the labels. */ @@ -67,8 +48,8 @@ constexpr int CONVERT_MAX_WAITS = 4; constexpr size_t PREPARE_NOW_MAX_BYTES = 96 * 1024; bool memoryForConversion() { - return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) >= CONVERT_SMALL_BLOCK && - heap_caps_get_free_size(MALLOC_CAP_SPIRAM) >= CONVERT_MIN_FREE; + return memory_external_largest_block() >= CONVERT_SMALL_BLOCK && + memory_external_free() >= CONVERT_MIN_FREE; } constexpr char CACHE_MAGIC[4] = { 'T', 'M', 'C', '2' }; constexpr size_t CACHE_HEADER_BYTES = 12; @@ -414,19 +395,19 @@ bool TileWorker::relieveMemory(size_t bytes, size_t totalBytes, int minSlots) { const int before = tileCache.slotCount(); // Never fewer than the tiles on screen (9 in a turned view), or they are drawn again and again const int keep = std::max(minSlots > 0 ? minSlots : MIN_CACHE_SLOTS, visibleWanted); - while ((heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < bytes || heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < totalBytes) && + while ((memory_external_largest_block() < bytes || memory_external_free() < totalBytes) && tileCache.slotCount() > keep && tileCache.freeSlot()) { } const int after = tileCache.slotCount(); unlock(); // Still short: the lanes free the buffers they keep between tiles (file, terrain, trails) at their next tile. Not // every time: they were made again at once, and the churn broke PSRAM into pieces - if (heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < bytes || heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < totalBytes) { + if (memory_external_largest_block() < bytes || memory_external_free() < totalBytes) { for (int i = 0; i < laneCount; i++) { lanes[i].releaseExtras = true; } } - const size_t largest = heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM); + const size_t largest = memory_external_largest_block(); logInfo("Memory for a %u KB block: %d of %d cache slots freed, largest block %u KB", static_cast(bytes / 1024), before - after, before, static_cast(largest / 1024)); return largest >= bytes; @@ -961,8 +942,8 @@ bool TileWorker::start(TileStore* tileStore, IoTask* ioTask, const Palette* tile char name[16]; snprintf(name, sizeof(name), "maps-render%d", i); // The stack in PSRAM: 10 KB twice was the largest share of the app's internal RAM - if (xTaskCreatePinnedToCoreWithCaps(taskMain, name, TASK_STACK, &lane, TASK_PRIORITY, &lane.task, i, MALLOC_CAP_SPIRAM) != pdPASS) { - lane.task = nullptr; + lane.task = startThread(name, TASK_STACK, taskMain, &lane, TASK_PRIORITY, i, true); + if (lane.task == nullptr) { logError("Tile worker: task %d not started", i); break; } @@ -978,7 +959,7 @@ void TileWorker::stop() { xSemaphoreTake(stopped, portMAX_DELAY); } for (int i = 0; i < laneCount; i++) { - deleteLaneTask(lanes[i].task); + joinThread(lanes[i].task); lanes[i].task = nullptr; } if (laneCount > 0) { @@ -1001,13 +982,13 @@ void TileWorker::stop() { } } -void TileWorker::taskMain(void* context) { +int32_t TileWorker::taskMain(void* context) { auto* lane = static_cast(context); TileWorker* worker = lane->worker; worker->loop(*lane); xSemaphoreGive(worker->stopped); - // A task with its stack in PSRAM cannot delete itself: stop() deletes it once it is suspended - vTaskSuspend(nullptr); + // A thread with its stack in PSRAM cannot free itself: stop() joins it + return 0; } void TileWorker::want(const TileKey* tiles, int count, int visibleCount) { @@ -1113,7 +1094,7 @@ bool TileWorker::noteConversionWait() { conversionsStopped = true; unlock(); logInfo("Preparing tiles stopped for memory: %d tiles left for the next start (largest free PSRAM block %u KB)", dropped, - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + static_cast(memory_external_largest_block() / 1024)); return true; } @@ -1295,13 +1276,13 @@ bool TileWorker::convertOne(Lane& lane) { return false; } const size_t wanted = CONVERT_MIN_FREE + CONVERT_DOWNLOAD_SPARE; - if (heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < wanted || heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < CONVERT_MIN_BLOCK) { + if (memory_external_free() < wanted || memory_external_largest_block() < CONVERT_MIN_BLOCK) { const TickType_t now = xTaskGetTickCount(); if (static_cast(now - conversionsWaitUntil.load()) < 0) { return false; } relieveMemory(CONVERT_MIN_BLOCK, wanted); - if (heap_caps_get_free_size(MALLOC_CAP_SPIRAM) < wanted || heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) < CONVERT_MIN_BLOCK) { + if (memory_external_free() < wanted || memory_external_largest_block() < CONVERT_MIN_BLOCK) { conversionsWaitUntil = now + pdMS_TO_TICKS(DOWNLOAD_BACKOFF_MS); return false; } @@ -1349,8 +1330,8 @@ bool TileWorker::convertOne(Lane& lane) { conversionsWaitUntil = now + pdMS_TO_TICKS(MEMORY_BACKOFF_MS); lane.triedTrim = false; logInfo("Preparing tiles waits for memory (largest free PSRAM block %u KB, %u KB free, %d queued)", - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024), - static_cast(heap_caps_get_free_size(MALLOC_CAP_SPIRAM) / 1024), queued); + static_cast(memory_external_largest_block() / 1024), + static_cast(memory_external_free() / 1024), queued); noteConversionWait(); return false; } @@ -1507,10 +1488,10 @@ bool TileWorker::convertOne(Lane& lane) { // Out of memory, not a bad tile: it stays queued and conversions pause, it does not count as a failure conversionsWaitUntil = xTaskGetTickCount() + pdMS_TO_TICKS(MEMORY_BACKOFF_MS); logInfo("[%d] Preparing %d/%d/%d waits for memory (%s, largest free PSRAM block %u KB)", lane.index, job.tile.z, job.tile.x, - job.tile.y, reason, static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024)); + job.tile.y, reason, static_cast(memory_external_largest_block() / 1024)); requeue = !noteConversionWait(); } else if (!ok && !requeue) { - const auto largest = static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); + const auto largest = static_cast(memory_external_largest_block()); lock(); // A tile that failed once, usually for want of memory, is tried once more at the end of the queue retry = std::find(retriedConversions, retriedConversions + retriedConversionCount, job.tile) == @@ -2066,7 +2047,7 @@ bool TileWorker::produce(Lane& lane, const TileKey& tile, uint16_t* pixels, bool // Not even that: tried again in a few seconds, not left drawn from a coarser zoom level logError("[%d] Tile %d/%d/%d: no %u KB block of PSRAM for its data (largest %u KB), tried again in %u s", lane.index, tile.z, tile.x, tile.y, static_cast(job.noMemoryBytes / 1024), - static_cast(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024), static_cast(MEMORY_RETRY_MS / 1000)); + static_cast(memory_external_largest_block() / 1024), static_cast(MEMORY_RETRY_MS / 1000)); lock(); if (missingRetryAt == 0) { missingRetryAt = xTaskGetTickCount() + pdMS_TO_TICKS(MEMORY_RETRY_MS); diff --git a/Apps/Maps/main/Source/app/TileWorker.h b/Apps/Maps/main/Source/app/TileWorker.h index 36e8de65..3f5ec223 100644 --- a/Apps/Maps/main/Source/app/TileWorker.h +++ b/Apps/Maps/main/Source/app/TileWorker.h @@ -15,9 +15,10 @@ #include "../render/TileRenderer.h" #include "../tiles/TileStore.h" -#include -#include -#include +#include +#include +#include +#include #include #include @@ -125,10 +126,10 @@ class TileWorker { * waiting, and of those the older tiles with labels inside that are split into their new files. */ void preparation(int& done, int& waiting, int& splitting); - TaskHandle_t laneTask(int lane) const { return lane < laneCount ? lanes[lane].task : nullptr; } + TaskHandle_t laneTask(int lane) const { return lane < laneCount ? thread_get_task_handle(lanes[lane].task) : nullptr; } /** The fewest bytes of stack a render lane had left so far. */ uint32_t stackLeft(int lane) const { - return lane < laneCount && lanes[lane].task != nullptr ? static_cast(uxTaskGetStackHighWaterMark(lanes[lane].task)) : 0; + return lane < laneCount && lanes[lane].task != nullptr ? thread_get_stack_space(lanes[lane].task) : 0; } /** Whether a tile is cached or known to have no data. Call between lock() and unlock(). */ bool isSettled(const TileKey& tile) const; @@ -204,7 +205,7 @@ class TileWorker { bool heldStale; bool heldSplit; uint32_t heldGeneration; - TaskHandle_t task; + Thread* task = nullptr; TileKey current; bool active; uint16_t* writeBuffer; @@ -303,7 +304,7 @@ class TileWorker { /** Runs loadJob on the I/O task; a job that did not start (a prefetch the view left behind) counts as giving way. */ void runLoad(IoPriority priority, LoadJob& job); - static void taskMain(void* context); + static int32_t taskMain(void* context); void loop(Lane& lane); /** Claims the next wanted tile that is on screen, or around the screen when visible is false. */ bool claimNext(Lane& lane, bool visible, TileKey& tile, uint16_t*& pixels); diff --git a/Apps/Maps/manifest.properties b/Apps/Maps/manifest.properties index 63129bcf..7ab6674b 100644 --- a/Apps/Maps/manifest.properties +++ b/Apps/Maps/manifest.properties @@ -1,14 +1,14 @@ manifest.version=0.3 target.sdk=0.8.0-dev -target.platforms=esp32s3,esp32p4,esp32s31 +target.platforms=all id=tactility.maps -version.name=0.11.1 -version.code=16 +version.name=0.11.2 +version.code=17 app.0.id=tactility.maps app.0.name=Maps app.0.binary=maps app.0.stack.depth=12288 name=Maps description.short=Offline vector maps -description=High-detail vector maps: get live maps via Wi-Fi, or download them to your SD card before your trip.\n\nFeatures terrain with hillshade and contour lines, an outdoor style for hiking, offline search, and navigation for walking, cycling, and driving with elevation profiles. Waypoints and GPX tracks can be shown or navigated to.\n\nWorks with keyboard, trackball, or touch only. Requires an ESP32-S3, ESP32-P4 or ESP32-S31 device with at least 8 MB PSRAM.\n\nTested on the LilyGO T-Deck and SeeedStudio Wio Tracker L2 Pro.\n\nMap data provided by OpenFreeMap & OpenStreetMap. +description=High-detail vector maps: get live maps via Wi-Fi, or download them to your SD card before your trip.\n\nFeatures terrain with hillshade and contour lines, an outdoor style for hiking, offline search, and navigation for walking, cycling, and driving with elevation profiles. Waypoints and GPX tracks can be shown or navigated to.\n\nWorks with keyboard, trackball, or touch only. Requires at least 8 MB of RAM.\n\nTested on the LilyGO T-Deck and SeeedStudio Wio Tracker L2 Pro.\n\nMap data provided by OpenFreeMap & OpenStreetMap. requires.ram=8M