Compare commits

...

3 Commits

Author SHA1 Message Date
Ken Van Hoeylandt
3354924359
LvglSync removed (#591)
Replaced all usages with lvgl-module functions.
2026-07-26 23:56:07 +02:00
Ken Van Hoeylandt
03a6285328
Add kernel memory functions & other memory-related changes (#590)
New Features

- Added policy-based memory allocation APIs with capability flags and optional alignment: `memory_alloc_with_policy`, `memory_realloc_with_policy`, `memory_calloc_with_policy`, and `memory_free`.
- Switched heap memory reporting to `memory_print_stats`.

Bug Fixes

- Improved allocation robustness with capability fallback behavior.
- Added overflow-safe handling for aligned zero-initialized allocations.
- Tightened const-correctness for generated device-tree device arrays.

Tests

- Added unit tests for default policy, alignment, zero-initialization, realloc preservation, freeing, and memory stats reporting.
2026-07-26 22:59:18 +02:00
Ken Van Hoeylandt
f21c0df6fe
Improvements & fixes (#589) 2026-07-26 21:26:52 +02:00
56 changed files with 771 additions and 433 deletions

View File

@ -350,7 +350,7 @@ def generate_devicetree_c(filename: str, items: list[object], bindings: list[Bin
for item in items: for item in items:
if type(item) is Device: if type(item) is Device:
write_device_structs(file, item, None, bindings, devices, verbose) write_device_structs(file, item, None, bindings, devices, verbose)
file.write("struct DtsDevice dts_devices[] = {\n") file.write("const struct DtsDevice dts_devices[] = {\n")
for item in items: for item in items:
if type(item) is Device: if type(item) is Device:
write_device_list_entry(file, item, bindings, verbose) write_device_list_entry(file, item, bindings, verbose)
@ -379,7 +379,7 @@ def generate_devicetree_c(filename: str, items: list[object], bindings: list[Bin
file.write(f"extern struct Module {symbol};\n") file.write(f"extern struct Module {symbol};\n")
file.write("\n") file.write("\n")
# Create array of symbol variables # Create array of symbol variables
file.write("struct Module* dts_modules[] = {\n") file.write("struct Module* const dts_modules[] = {\n")
for symbol in module_symbol_names: for symbol in module_symbol_names:
file.write(f"\t&{symbol},\n") file.write(f"\t&{symbol},\n")
file.write("\tNULL\n") file.write("\tNULL\n")
@ -397,10 +397,10 @@ def generate_devicetree_h(filename: str):
#endif #endif
// Array of device tree modules terminated with DTS_MODULE_TERMINATOR // Array of device tree modules terminated with DTS_MODULE_TERMINATOR
extern struct DtsDevice dts_devices[]; extern const struct DtsDevice dts_devices[];
// Array of module symbols terminated with NULL // Array of module symbols terminated with NULL
extern struct Module* dts_modules[]; extern struct Module* const dts_modules[];
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -50,7 +50,7 @@ static struct Device bool_test_device = {
.internal = NULL .internal = NULL
}; };
struct DtsDevice dts_devices[] = { const struct DtsDevice dts_devices[] = {
{ &root, "test,root", DTS_DEVICE_STATUS_OKAY }, { &root, "test,root", DTS_DEVICE_STATUS_OKAY },
{ &test_device, "test,generic-device", DTS_DEVICE_STATUS_OKAY }, { &test_device, "test,generic-device", DTS_DEVICE_STATUS_OKAY },
{ &bool_test_device, "test,bool-device", DTS_DEVICE_STATUS_OKAY }, { &bool_test_device, "test,bool-device", DTS_DEVICE_STATUS_OKAY },
@ -59,7 +59,7 @@ struct DtsDevice dts_devices[] = {
extern struct Module data_module; extern struct Module data_module;
struct Module* dts_modules[] = { struct Module* const dts_modules[] = {
&data_module, &data_module,
NULL NULL
}; };

View File

@ -7,10 +7,10 @@ extern "C" {
#endif #endif
// Array of device tree modules terminated with DTS_MODULE_TERMINATOR // Array of device tree modules terminated with DTS_MODULE_TERMINATOR
extern struct DtsDevice dts_devices[]; extern const struct DtsDevice dts_devices[];
// Array of module symbols terminated with NULL // Array of module symbols terminated with NULL
extern struct Module* dts_modules[]; extern struct Module* const dts_modules[];
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -4,6 +4,7 @@ idf_component_register(
"Libraries/TactilityKernel/include" "Libraries/TactilityKernel/include"
"Libraries/TactilityFreeRtos/include" "Libraries/TactilityFreeRtos/include"
"Libraries/lvgl/include" "Libraries/lvgl/include"
"Libraries/minmea/include"
"Modules/lvgl-module/include" "Modules/lvgl-module/include"
# DRIVER_INCLUDE_DIRS_PLACEHOLDER # DRIVER_INCLUDE_DIRS_PLACEHOLDER
REQUIRES esp_timer REQUIRES esp_timer
@ -13,7 +14,9 @@ idf_component_register(
add_prebuilt_library(TactilityC Libraries/TactilityC/binary/libTactilityC.a) add_prebuilt_library(TactilityC Libraries/TactilityC/binary/libTactilityC.a)
add_prebuilt_library(TactilityKernel Libraries/TactilityKernel/binary/libTactilityKernel.a) add_prebuilt_library(TactilityKernel Libraries/TactilityKernel/binary/libTactilityKernel.a)
add_prebuilt_library(lvgl Libraries/lvgl/binary/liblvgl.a) add_prebuilt_library(lvgl Libraries/lvgl/binary/liblvgl.a)
add_prebuilt_library(minmea Libraries/minmea/binary/libminmea.a)
target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityC) target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityC)
target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityKernel) target_link_libraries(${COMPONENT_LIB} INTERFACE TactilityKernel)
target_link_libraries(${COMPONENT_LIB} INTERFACE lvgl) target_link_libraries(${COMPONENT_LIB} INTERFACE lvgl)
target_link_libraries(${COMPONENT_LIB} INTERFACE minmea)

View File

@ -185,6 +185,13 @@ def main():
# elf_loader # elf_loader
{'src': 'Libraries/elf_loader/elf_loader.cmake', 'dst': 'Libraries/elf_loader/'}, {'src': 'Libraries/elf_loader/elf_loader.cmake', 'dst': 'Libraries/elf_loader/'},
{'src': 'Libraries/elf_loader/license.txt', 'dst': 'Libraries/elf_loader/'}, {'src': 'Libraries/elf_loader/license.txt', 'dst': 'Libraries/elf_loader/'},
# minmea
{'src': 'build/esp-idf/minmea/libminmea.a', 'dst': 'Libraries/minmea/binary/'},
{'src': 'Libraries/minmea/Include/**', 'dst': 'Libraries/minmea/include/'},
{'src': 'Libraries/minmea/CMakeLists.txt', 'dst': 'Libraries/minmea/'},
{'src': 'Libraries/minmea/README.md', 'dst': 'Libraries/minmea/'},
{'src': 'Libraries/minmea/LICENSE*.*', 'dst': 'Libraries/minmea/'},
{'src': 'Libraries/minmea/COPYING', 'dst': 'Libraries/minmea/'},
] ]
map_copy(mappings, target_path) map_copy(mappings, target_path)
@ -192,6 +199,7 @@ def main():
# Modules # Modules
add_module(target_path, "lvgl-module") add_module(target_path, "lvgl-module")
add_module(target_path, "crypt-module") add_module(target_path, "crypt-module")
add_module(target_path, "gps-module")
# Drivers - only ones actually built for this target (chip-restricted drivers like # Drivers - only ones actually built for this target (chip-restricted drivers like
# sc2356-module won't have a .a outside ESP32-P4) # sc2356-module won't have a .a outside ESP32-P4)

View File

@ -1,13 +1,12 @@
#include <tactility/module.h> #include <tactility/module.h>
#include <tactility/error.h> #include <tactility/error.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h> #include <lvgl/lvgl.h>
#include <Tactility/SystemEvents.h> #include <Tactility/SystemEvents.h>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/kernel/Kernel.h> #include <Tactility/kernel/Kernel.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/settings/TrackballSettings.h> #include <Tactility/settings/TrackballSettings.h>
#include <lilygo/drivers/trackball.h> #include <lilygo/drivers/trackball.h>

View File

@ -4,6 +4,9 @@
#include <stdint.h> #include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
// Official LVGL library header
#include <lvgl.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif

View File

@ -111,7 +111,7 @@ void lvgl_devices_detach() {
lv_disp_t* display = lv_disp_get_next(NULL); lv_disp_t* display = lv_disp_get_next(NULL);
while (display != NULL) { while (display != NULL) {
lv_display_delete(display); lvgl_display_remove(display);
display = lv_disp_get_next(NULL); display = lv_disp_get_next(NULL);
} }

View File

@ -43,7 +43,7 @@ private:
* @param dtsModules List of modules from devicetree, null-terminated, non-null parameter * @param dtsModules List of modules from devicetree, null-terminated, non-null parameter
* @param dtsDevices Array that is terminated with DTS_DEVICE_TERMINATOR * @param dtsDevices Array that is terminated with DTS_DEVICE_TERMINATOR
*/ */
void run(Module* dtsModules[], DtsDevice dtsDevices[]); void run(Module* const dtsModules[], const DtsDevice dtsDevices[]);
/** Provides access to the dispatcher that runs on the main task. /** Provides access to the dispatcher that runs on the main task.
* @warning This dispatcher is used for WiFi and might block for some time during WiFi connection. * @warning This dispatcher is used for WiFi and might block for some time during WiFi connection.

View File

@ -1,24 +0,0 @@
#pragma once
#include <Tactility/Lock.h>
#include <memory>
namespace tt::lvgl {
constexpr TickType_t defaultLockTime = 500 / portTICK_PERIOD_MS;
/**
* LVGL locking function
* @param[in] timeout as ticks
* @warning when passing zero, we wait forever, as this is the default behaviour for esp_lvgl_port, and we want it to remain consistent
* @deprecated Use lvgl_lock() or lvgl_try_lock() from lvgl-module instead.
*/
bool lock(TickType_t timeout = portMAX_DELAY) __attribute__((deprecated("Use lvgl_lock() from lvgl-module")));
/** @deprecated Use lvgl_unlock() from lvgl-module instead. */
void unlock() __attribute__((deprecated("Use lvgl_unlock() from lvgl-module")));
std::shared_ptr<Lock> getSyncLock() __attribute__((deprecated("Use lvgl locking functions from lvgl-module")));
} // namespace

View File

@ -3,7 +3,6 @@
#include <Tactility/MessageQueue.h> #include <Tactility/MessageQueue.h>
#include <Tactility/PubSub.h> #include <Tactility/PubSub.h>
#include <Tactility/RecursiveMutex.h> #include <Tactility/RecursiveMutex.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/service/Service.h> #include <Tactility/service/Service.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
@ -11,7 +10,6 @@
#include <tactility/concurrent/dispatcher.h> #include <tactility/concurrent/dispatcher.h>
#include <cstdio>
#include <lvgl.h> #include <lvgl.h>
namespace tt::service::gui { namespace tt::service::gui {

View File

@ -6,26 +6,33 @@
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/TactilityConfig.h> #include <Tactility/TactilityConfig.h>
#include <Tactility/bluetooth/Bluetooth.h>
#include <Tactility/LogMessages.h>
#include <Tactility/CpuAffinity.h> #include <Tactility/CpuAffinity.h>
#include <Tactility/MountPoints.h> #include <Tactility/MountPoints.h>
#include <Tactility/app/AppManifestParsing.h> #include <Tactility/app/AppManifestParsing.h>
#include <Tactility/app/AppRegistration.h> #include <Tactility/app/AppRegistration.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h> #include <Tactility/file/FileLock.h>
#include <Tactility/LogMessages.h>
#include <Tactility/hal/SdCard.h>
#include <Tactility/network/NtpPrivate.h> #include <Tactility/network/NtpPrivate.h>
#include <Tactility/Paths.h>
#include <Tactility/service/ServiceManifest.h> #include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h> #include <Tactility/service/ServiceRegistration.h>
#include <Tactility/service/audio/Audio.h> #include <Tactility/service/audio/Audio.h>
#include <Tactility/settings/TimePrivate.h> #include <Tactility/settings/TimePrivate.h>
#ifdef ESP_PLATFORM
#include <Tactility/InitEsp.h>
#endif
#include <gps/module.h> #include <gps/module.h>
#include <gps_generic/gps_generic_module.h> #include <gps_generic/gps_generic_module.h>
#include <crypt/module.h> #include <crypt/module.h>
#include <lvgl/module.h> #include <lvgl/module.h>
#include <lvgl/widgets/toolbar.h> #include <lvgl/widgets/toolbar.h>
#include <tactility/concurrent/thread.h> #include <tactility/concurrent/thread.h>
#include <tactility/drivers/audio_stream.h> #include <tactility/drivers/audio_stream.h>
#include <tactility/drivers/display.h> #include <tactility/drivers/display.h>
@ -36,15 +43,7 @@
#include <tactility/filesystem/file_system.h> #include <tactility/filesystem/file_system.h>
#include <tactility/kernel_init.h> #include <tactility/kernel_init.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/memory.h>
#ifdef ESP_PLATFORM
#include <Tactility/InitEsp.h>
#endif
#include "Tactility/Paths.h"
#include "Tactility/hal/SdCard.h"
#include <Tactility/bluetooth/Bluetooth.h>
namespace tt { namespace tt {
@ -371,6 +370,8 @@ static void onLvglStarted() {
#if TT_FEATURE_SCREENSHOT_ENABLED #if TT_FEATURE_SCREENSHOT_ENABLED
addService(service::screenshot::manifest); addService(service::screenshot::manifest);
#endif #endif
memory_print_stats();
} }
static void onLvglStopped() { static void onLvglStopped() {
@ -386,9 +387,11 @@ static void onLvglStopped() {
check(service::removeService(service::memorychecker::manifest.id)); check(service::removeService(service::memorychecker::manifest.id));
check(service::removeService(service::statusbar::manifest.id)); check(service::removeService(service::statusbar::manifest.id));
check(service::removeService(service::gui::manifest.id)); check(service::removeService(service::gui::manifest.id));
memory_print_stats();
} }
void run(Module* dtsModules[], DtsDevice dtsDevices[]) { void run(Module* const dtsModules[], const DtsDevice dtsDevices[]) {
LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID); LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID);
LOG_I(TAG, "Initializing kernel"); LOG_I(TAG, "Initializing kernel");

View File

@ -95,6 +95,7 @@ private:
// Note: the result code maps to values from cstdlib's errno.h // Note: the result code maps to values from cstdlib's errno.h
lastError = getErrorCodeString(-relocate_result); lastError = getErrorCodeString(-relocate_result);
LOG_E(TAG, "Application failed to load: %s", lastError.c_str()); LOG_E(TAG, "Application failed to load: %s", lastError.c_str());
esp_elf_deinit(&elf);
elfFileData = nullptr; elfFileData = nullptr;
return false; return false;
} }

View File

@ -1,18 +1,18 @@
#include "Tactility/lvgl/LvglSync.h"
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h> #include <Tactility/app/alertdialog/AlertDialog.h>
#include <tactility/check.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <lvgl/widgets/toolbar.h>
#include <lvgl.h>
#include <format>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <tactility/check.h>
#include <lvgl/lvgl.h>
#include <lvgl/widgets/toolbar.h>
#include <format>
namespace tt::app::appdetails { namespace tt::app::appdetails {
extern const AppManifest manifest; extern const AppManifest manifest;

View File

@ -1,20 +1,21 @@
#include <Tactility/Paths.h>
#include <Tactility/app/apphub/AppHub.h> #include <Tactility/app/apphub/AppHub.h>
#include <Tactility/app/apphub/AppHubEntry.h> #include <Tactility/app/apphub/AppHubEntry.h>
#include <Tactility/app/apphubdetails/AppHubDetailsApp.h> #include <Tactility/app/apphubdetails/AppHubDetailsApp.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <Tactility/lvgl/LvglSync.h>
#include <lvgl/widgets/spinner.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/network/Http.h> #include <Tactility/network/Http.h>
#include <Tactility/Paths.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h>
#include <lvgl/widgets/spinner.h>
#include <algorithm> #include <algorithm>
#include <format> #include <format>
#include <lvgl.h>
#include <tactility/log.h>
namespace tt::app::apphub { namespace tt::app::apphub {
@ -58,20 +59,16 @@ class AppHubApp final : public App {
void onRefreshSuccess() { void onRefreshSuccess() {
LOG_I(TAG, "Request success"); LOG_I(TAG, "Request success");
auto lockable = lvgl::getSyncLock(); lvgl_lock();
auto lock = lockable->asScopedLock();
lock.lock();
showApps(); showApps();
lvgl_unlock();
} }
void onRefreshError(const char* error) { void onRefreshError(const char* error) {
LOG_E(TAG, "Request failed: %s", error); LOG_E(TAG, "Request failed: %s", error);
auto lockable = lvgl::getSyncLock(); lvgl_lock();
auto lock = lockable->asScopedLock();
lock.lock();
showRefreshFailedError("Cannot reach server"); showRefreshFailedError("Cannot reach server");
lvgl_unlock();
} }
static void createAppWidget(const std::shared_ptr<AppManifest>& manifest, lv_obj_t* list) { static void createAppWidget(const std::shared_ptr<AppManifest>& manifest, lv_obj_t* list) {

View File

@ -1,17 +1,18 @@
#include <Tactility/Paths.h>
#include <Tactility/StringUtils.h>
#include <Tactility/app/AppRegistration.h>
#include <Tactility/app/alertdialog/AlertDialog.h> #include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/app/apphub/AppHub.h> #include <Tactility/app/apphub/AppHub.h>
#include <Tactility/app/apphub/AppHubEntry.h> #include <Tactility/app/apphub/AppHubEntry.h>
#include <Tactility/app/AppRegistration.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <Tactility/lvgl/LvglSync.h>
#include <lvgl/widgets/toolbar.h>
#include <Tactility/network/Http.h> #include <Tactility/network/Http.h>
#include <Tactility/Paths.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/StringUtils.h>
#include <lvgl.h> #include <lvgl/lvgl.h>
#include <lvgl/widgets/toolbar.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <format> #include <format>
namespace tt::app::apphubdetails { namespace tt::app::apphubdetails {
@ -87,15 +88,15 @@ class AppHubDetailsApp final : public App {
void uninstallApp() { void uninstallApp() {
LOG_I(TAG, "Uninstall"); LOG_I(TAG, "Uninstall");
lvgl::getSyncLock()->lock(); lvgl_lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
lvgl::getSyncLock()->unlock(); lvgl_unlock();
uninstall(entry.appId); uninstall(entry.appId);
lvgl::getSyncLock()->lock(); lvgl_lock();
updateViews(); updateViews();
lvgl::getSyncLock()->unlock(); lvgl_unlock();
} }
void doInstall() { void doInstall() {
@ -115,9 +116,9 @@ class AppHubDetailsApp final : public App {
LOG_I(TAG, "Deleted temporary file %s", temp_file_path.c_str()); LOG_I(TAG, "Deleted temporary file %s", temp_file_path.c_str());
} }
lvgl::getSyncLock()->lock(); lvgl_lock();
updateViews(); updateViews();
lvgl::getSyncLock()->unlock(); lvgl_unlock();
}, },
[temp_file_path](const char* errorMessage) { [temp_file_path](const char* errorMessage) {
LOG_E(TAG, "Download failed: %s", errorMessage); LOG_E(TAG, "Download failed: %s", errorMessage);
@ -133,9 +134,9 @@ class AppHubDetailsApp final : public App {
void installApp() { void installApp() {
LOG_I(TAG, "Install"); LOG_I(TAG, "Install");
lvgl::getSyncLock()->lock(); lvgl_lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
lvgl::getSyncLock()->unlock(); lvgl_unlock();
doInstall(); doInstall();
} }
@ -143,9 +144,9 @@ class AppHubDetailsApp final : public App {
void updateApp() { void updateApp() {
LOG_I(TAG, "Update"); LOG_I(TAG, "Update");
lvgl::getSyncLock()->lock(); lvgl_lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
lvgl::getSyncLock()->unlock(); lvgl_unlock();
LOG_I(TAG, "Removing previous version"); LOG_I(TAG, "Removing previous version");
uninstall(entry.appId); uninstall(entry.appId);

View File

@ -1,16 +1,12 @@
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <lvgl/icons/shared.h>
#include <Tactility/PubSub.h> #include <Tactility/PubSub.h>
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/audio/Audio.h> #include <Tactility/service/audio/Audio.h>
#include <lvgl/widgets/sliderbox.h>
#include <lvgl.h> #include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h> #include <lvgl/lvgl.h>
#include <lvgl/widgets/sliderbox.h>
namespace tt::app::audiosettings { namespace tt::app::audiosettings {
@ -161,10 +157,9 @@ public:
refresh(); refresh();
audioSubscription = service::audio::getPubsub()->subscribe([this](auto) { audioSubscription = service::audio::getPubsub()->subscribe([this](auto) {
if (lvgl::lock(lvgl::defaultLockTime)) { lvgl_lock();
refresh(); refresh();
lvgl::unlock(); lvgl_unlock();
}
}); });
} }

View File

@ -1,11 +1,11 @@
#include <lvgl/lvgl.h>
#include <Tactility/app/btmanage/BtManagePrivate.h> #include <Tactility/app/btmanage/BtManagePrivate.h>
#include <Tactility/app/btmanage/View.h> #include <Tactility/app/btmanage/View.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/lvgl/LvglSync.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
#include <tactility/log.h> #include <tactility/log.h>
@ -79,12 +79,9 @@ void BtManage::unlock() {
void BtManage::requestViewUpdate() { void BtManage::requestViewUpdate() {
lock(); lock();
if (isViewEnabled) { if (isViewEnabled) {
if (lvgl::lock(1000)) { lvgl_lock();
view.update(); view.update();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
} }
unlock(); unlock();
} }

View File

@ -1,23 +1,21 @@
#include <Tactility/app/btpeersettings/BtPeerSettings.h> #include <Tactility/app/btpeersettings/BtPeerSettings.h>
#include "tactility/device.h" #include <lvgl/lvgl.h>
#include <lvgl/widgets/toolbar.h>
#include <Tactility/LogMessages.h>
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h> #include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/bluetooth/Bluetooth.h> #include <Tactility/bluetooth/Bluetooth.h>
#include <Tactility/bluetooth/BluetoothPairedDevice.h> #include <Tactility/bluetooth/BluetoothPairedDevice.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <lvgl/widgets/toolbar.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/drivers/bluetooth.h> #include <tactility/drivers/bluetooth.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl.h>
namespace tt::app::btpeersettings { namespace tt::app::btpeersettings {
constexpr auto* TAG = "BtPeerSettings"; constexpr auto* TAG = "BtPeerSettings";
@ -84,12 +82,9 @@ class BtPeerSettings : public App {
void requestViewUpdate() const { void requestViewUpdate() const {
if (viewEnabled) { if (viewEnabled) {
if (lvgl::lock(1000)) { lvgl_lock();
updateViews(); updateViews();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
} }
} }

View File

@ -6,15 +6,16 @@
#include <Tactility/app/chat/ChatAppPrivate.h> #include <Tactility/app/chat/ChatAppPrivate.h>
#include <Tactility/app/chat/ChatProtocol.h> #include <Tactility/app/chat/ChatProtocol.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/lvgl/LvglSync.h>
#include <tactility/log.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h>
#include <algorithm> #include <algorithm>
#include <cctype> #include <cctype>
#include <cstdlib> #include <cstdlib>
#include <tactility/log.h>
#include <vector> #include <vector>
namespace tt::app::chat { namespace tt::app::chat {
@ -83,12 +84,9 @@ void ChatApp::onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* d
state.addMessage(msg); state.addMessage(msg);
{ lvgl_lock();
auto lockable = lvgl::getSyncLock(); view.displayMessage(msg);
auto lock = lockable->asScopedLock(); lvgl_unlock();
lock.lock();
view.displayMessage(msg);
}
} }
void ChatApp::sendMessage(const std::string& text) { void ChatApp::sendMessage(const std::string& text) {
@ -115,12 +113,9 @@ void ChatApp::sendMessage(const std::string& text) {
state.addMessage(msg); state.addMessage(msg);
{ lvgl_lock();
auto lockable = lvgl::getSyncLock(); view.displayMessage(msg);
auto lock = lockable->asScopedLock(); lvgl_unlock();
lock.lock();
view.displayMessage(msg);
}
} }
void ChatApp::applySettings(const std::string& nickname, const std::string& keyHex) { void ChatApp::applySettings(const std::string& nickname, const std::string& keyHex) {
@ -173,12 +168,9 @@ void ChatApp::switchChannel(const std::string& chatChannel) {
settings.chatChannel = trimmedChannel; settings.chatChannel = trimmedChannel;
saveSettings(settings); saveSettings(settings);
{ lvgl_lock();
auto lockable = lvgl::getSyncLock(); view.refreshMessageList();
auto lock = lockable->asScopedLock(); lvgl_unlock();
lock.lock();
view.refreshMessageList();
}
} }
extern const AppManifest manifest = { extern const AppManifest manifest = {

View File

@ -3,7 +3,6 @@
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/development/DevelopmentService.h> #include <Tactility/service/development/DevelopmentService.h>
@ -11,12 +10,12 @@
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h>
#include <cstring> #include <cstring>
#include <lvgl.h>
namespace tt::app::development { namespace tt::app::development {

View File

@ -1,6 +1,5 @@
#include <Tactility/app/files/SupportedFiles.h> #include <Tactility/app/files/SupportedFiles.h>
#include <Tactility/app/files/View.h> #include <Tactility/app/files/View.h>
#include <Tactility/Platform.h> #include <Tactility/Platform.h>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
@ -9,14 +8,15 @@
#include <Tactility/app/inputdialog/InputDialog.h> #include <Tactility/app/inputdialog/InputDialog.h>
#include <Tactility/app/notes/Notes.h> #include <Tactility/app/notes/Notes.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <tactility/check.h>
#include <tactility/check.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/usb_host_msc.h> #include <tactility/drivers/usb_host_msc.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <cctype> #include <cctype>
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
@ -450,9 +450,7 @@ void View::onEjectPressed() {
void View::update(size_t start_index) { void View::update(size_t start_index) {
const bool is_root = (state->getCurrentPath() == "/"); const bool is_root = (state->getCurrentPath() == "/");
auto sync_lockable = lvgl::getSyncLock(); if (!lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
auto scoped_lockable = sync_lockable->asScopedLock();
if (!scoped_lockable.lock(lvgl::defaultLockTime)) {
LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl"); LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl");
return; return;
} }
@ -516,6 +514,8 @@ void View::update(size_t start_index) {
} else { } else {
lv_obj_add_flag(lv_obj_get_parent(paste_button), LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(lv_obj_get_parent(paste_button), LV_OBJ_FLAG_HIDDEN);
} }
lvgl_unlock();
} }
void View::init(const AppContext& appContext, lv_obj_t* parent) { void View::init(const AppContext& appContext, lv_obj_t* parent) {
@ -551,18 +551,16 @@ void View::init(const AppContext& appContext, lv_obj_t* parent) {
} }
void View::onDirEntryListScrollBegin() { void View::onDirEntryListScrollBegin() {
auto sync_lockable = lvgl::getSyncLock(); if (lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN);
lvgl_unlock();
} }
} }
void View::onNavigate() { void View::onNavigate() {
auto sync_lockable = lvgl::getSyncLock(); if (lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN);
lvgl_unlock();
} }
} }

View File

@ -1,16 +1,16 @@
#include <Tactility/app/fileselection/View.h> #include <Tactility/app/fileselection/View.h>
#include <Tactility/Platform.h>
#include <Tactility/LogMessages.h>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/app/alertdialog/AlertDialog.h> #include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <Tactility/Platform.h>
#include <Tactility/lvgl/LvglSync.h>
#include <lvgl/widgets/toolbar.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <lvgl/widgets/toolbar.h>
#include <cstring> #include <cstring>
#include <unistd.h> #include <unistd.h>
@ -155,26 +155,27 @@ void View::onNavigateUpPressed() {
} }
void View::update() { void View::update() {
auto sync_lockable = lvgl::getSyncLock(); if (!lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_clean(dir_entry_list);
state->withEntries([this](const std::vector<dirent>& entries) {
for (auto entry : entries) {
LOG_D(TAG, "Entry: %s %d", entry.d_name, (int)entry.d_type);
createDirEntryWidget(dir_entry_list, entry);
}
});
if (state->getCurrentPath() == "/") {
lv_obj_add_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN);
}
} else {
LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl"); LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl");
return;
} }
lv_obj_clean(dir_entry_list);
state->withEntries([this](const std::vector<dirent>& entries) {
for (auto entry : entries) {
LOG_D(TAG, "Entry: %s %d", entry.d_name, (int)entry.d_type);
createDirEntryWidget(dir_entry_list, entry);
}
});
if (state->getCurrentPath() == "/") {
lv_obj_add_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN);
}
lvgl_unlock();
} }
void View::init(lv_obj_t* parent, Mode mode) { void View::init(lv_obj_t* parent, Mode mode) {

View File

@ -1,20 +1,20 @@
#include <Tactility/app/i2cscanner/I2cScannerPrivate.h>
#include <Tactility/app/i2cscanner/I2cHelpers.h> #include <Tactility/app/i2cscanner/I2cHelpers.h>
#include <Tactility/app/i2cscanner/I2cScannerPrivate.h>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/Preferences.h> #include <Tactility/Preferences.h>
#include <Tactility/RecursiveMutex.h> #include <Tactility/RecursiveMutex.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <tactility/drivers/i2c_controller.h> #include <tactility/drivers/i2c_controller.h>
#include <tactility/log.h>
#include <format> #include <format>
#include <lvgl/lvgl.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
#include <tactility/log.h>
namespace tt::app::i2cscanner { namespace tt::app::i2cscanner {
@ -367,12 +367,9 @@ void I2cScannerApp::updateViews() {
} }
void I2cScannerApp::updateViewsSafely() { void I2cScannerApp::updateViewsSafely() {
if (lvgl::lock(200 / portTICK_PERIOD_MS)) { lvgl_lock();
updateViews(); updateViews();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_W(TAG, "Mutex acquisition timeout (%s)", "updateViewsSafely");
}
} }
void I2cScannerApp::onScanTimerFinished() { void I2cScannerApp::onScanTimerFinished() {

View File

@ -1,10 +1,9 @@
#include "lvgl/lvgl.h"
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/fileselection/FileSelection.h> #include <Tactility/app/fileselection/FileSelection.h>
#include <Tactility/file/FileLock.h> #include <Tactility/file/FileLock.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/Assets.h>
#include <Tactility/file/File.h> #include <Tactility/file/File.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
@ -42,16 +41,16 @@ class NotesApp final : public App {
break; break;
case 1: // Save case 1: // Save
if (!filePath.empty()) { if (!filePath.empty()) {
lvgl::getSyncLock()->lock(); lvgl_lock();
saveBuffer = lv_textarea_get_text(uiNoteText); saveBuffer = lv_textarea_get_text(uiNoteText);
lvgl::getSyncLock()->unlock(); lvgl_unlock();
saveFile(filePath); saveFile(filePath);
} }
break; break;
case 2: // Save as... case 2: // Save as...
lvgl::getSyncLock()->lock(); lvgl_lock();
saveBuffer = lv_textarea_get_text(uiNoteText); saveBuffer = lv_textarea_get_text(uiNoteText);
lvgl::getSyncLock()->unlock(); lvgl_unlock();
saveFileLaunchId = fileselection::startForExistingOrNewFile(); saveFileLaunchId = fileselection::startForExistingOrNewFile();
LOG_I(TAG, "launched with id %u", saveFileLaunchId); LOG_I(TAG, "launched with id %u", saveFileLaunchId);
break; break;
@ -87,13 +86,12 @@ class NotesApp final : public App {
file::getLock(path)->withLock([this, path] { file::getLock(path)->withLock([this, path] {
auto data = file::readString(path); auto data = file::readString(path);
if (data != nullptr) { if (data != nullptr) {
auto lockable = lvgl::getSyncLock(); lvgl_lock();
auto lock = lockable->asScopedLock(); lv_textarea_set_text(uiNoteText, reinterpret_cast<const char*>(data.get()));
lock.lock(); lv_label_set_text(uiCurrentFileName, path.c_str());
lv_textarea_set_text(uiNoteText, reinterpret_cast<const char*>(data.get())); lvgl_unlock();
lv_label_set_text(uiCurrentFileName, path.c_str()); filePath = path;
filePath = path; LOG_I(TAG, "Loaded from %s", path.c_str());
LOG_I(TAG, "Loaded from %s", path.c_str());
} }
}); });
} }

View File

@ -1,16 +1,14 @@
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <lvgl/icons/shared.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/power_supply.h> #include <tactility/drivers/power_supply.h>
#include <lvgl.h> #include <lvgl/lvgl.h>
#include <lvgl/icons/shared.h>
#include <vector> #include <vector>
@ -136,7 +134,7 @@ class PowerApp : public App {
return; return;
} }
lvgl::lock(kernel::millisToTicks(1000)); lvgl_lock();
for (auto& entry : entries) { for (auto& entry : entries) {
if (entry.enableSwitch != nullptr) { if (entry.enableSwitch != nullptr) {
@ -155,7 +153,7 @@ class PowerApp : public App {
} }
} }
lvgl::unlock(); lvgl_unlock();
} }
public: public:

View File

@ -7,16 +7,16 @@
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/lvgl/Lvgl.h> #include <Tactility/lvgl/Lvgl.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/screenshot/Screenshot.h> #include <Tactility/service/screenshot/Screenshot.h>
#include <Tactility/Paths.h> #include <Tactility/Paths.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <lvgl/icons/shared.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <lvgl/icons/shared.h>
namespace tt::app::screenshot { namespace tt::app::screenshot {
constexpr auto* TAG = "Screenshot"; constexpr auto* TAG = "Screenshot";
@ -87,10 +87,9 @@ ScreenshotApp::~ScreenshotApp() {
} }
void ScreenshotApp::onTimerTick() { void ScreenshotApp::onTimerTick() {
auto lockable = lvgl::getSyncLock(); if (lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
auto lock = lockable->asScopedLock();
if (lock.lock(lvgl::defaultLockTime)) {
updateScreenshotMode(); updateScreenshotMode();
lvgl_unlock();
} }
} }

View File

@ -4,12 +4,10 @@
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/setup/Setup.h> #include <Tactility/app/setup/Setup.h>
#include <Tactility/Preferences.h> #include <Tactility/Preferences.h>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <Tactility/app/timezone/TimeZone.h> #include <Tactility/app/timezone/TimeZone.h>
#include <Tactility/app/wifimanage/WifiManage.h> #include <Tactility/app/wifimanage/WifiManage.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <lvgl.h> #include <lvgl.h>

View File

@ -1,14 +1,12 @@
#include <Tactility/TactilityConfig.h> #include <Tactility/TactilityConfig.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/Paths.h> #include <Tactility/Paths.h>
#include <algorithm> #include <algorithm>
#include <cstring> #include <cstring>
#include <format> #include <format>
#include <lvgl.h>
#include <utility> #include <utility>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
@ -247,20 +245,18 @@ class SystemInfoApp final : public App {
Timer memoryTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(10000), [] { Timer memoryTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(10000), [] {
auto app = optApp(); auto app = optApp();
if (app) { if (app) {
auto lockable = lvgl::getSyncLock(); lvgl_lock();
auto lock = lockable->asScopedLock();
lock.lock();
app->updateMemory(); app->updateMemory();
lvgl_unlock();
} }
}); });
Timer tasksTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(15000), [] { Timer tasksTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(15000), [] {
auto app = optApp(); auto app = optApp();
if (app) { if (app) {
auto lockable = lvgl::getSyncLock(); lvgl_lock();
auto lock = lockable->asScopedLock();
lock.lock();
app->updateTasks(); app->updateTasks();
lvgl_unlock();
} }
}); });

View File

@ -1,20 +1,16 @@
#include <lvgl/lvgl.h>
#include <Tactility/RecursiveMutex.h> #include <Tactility/RecursiveMutex.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/timezone/TimeZone.h> #include <Tactility/app/timezone/TimeZone.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/settings/SystemSettings.h> #include <Tactility/settings/SystemSettings.h>
#include <Tactility/settings/Time.h> #include <Tactility/settings/Time.h>
#include <lvgl.h>
#include <lvgl/icons/shared.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <lvgl/icons/shared.h>
namespace tt::app::timedatesettings { namespace tt::app::timedatesettings {
constexpr auto* TAG = "TimeDate"; constexpr auto* TAG = "TimeDate";

View File

@ -1,21 +1,20 @@
#include <lvgl/icons/shared.h>
#include <lvgl/fonts.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/timezone/TimeZone.h> #include <Tactility/app/timezone/TimeZone.h>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/MountPoints.h> #include <Tactility/MountPoints.h>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/settings/Time.h> #include <Tactility/settings/Time.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl.h> #include <lvgl/lvgl.h>
#include <lvgl/icons/shared.h>
#include <lvgl/fonts.h>
#include <memory> #include <memory>
namespace tt::app::timezone { namespace tt::app::timezone {
@ -166,16 +165,16 @@ class TimeZoneApp final : public App {
} }
void updateList() { void updateList() {
if (lvgl::lock(200 / portTICK_PERIOD_MS)) { if (lvgl_try_lock(200 / portTICK_PERIOD_MS)) {
std::string filter = string::lowercase(std::string(lv_textarea_get_text(filterTextareaWidget))); std::string filter = string::lowercase(std::string(lv_textarea_get_text(filterTextareaWidget)));
lvgl::unlock(); lvgl_unlock();
readTimeZones(filter); readTimeZones(filter);
} else { } else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "TimeZone LVGL"); LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "TimeZone LVGL");
return; return;
} }
if (lvgl::lock(200 / portTICK_PERIOD_MS)) { if (lvgl_try_lock(200 / portTICK_PERIOD_MS)) {
if (mutex.lock(100 / portTICK_PERIOD_MS)) { if (mutex.lock(100 / portTICK_PERIOD_MS)) {
lv_obj_clean(listWidget); lv_obj_clean(listWidget);
@ -188,7 +187,7 @@ class TimeZoneApp final : public App {
mutex.unlock(); mutex.unlock();
} }
lvgl::unlock(); lvgl_unlock();
} else { } else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "TimeZone LVGL"); LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "TimeZone LVGL");
} }

View File

@ -2,22 +2,17 @@
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/settings/WebServerSettings.h> #include <Tactility/settings/WebServerSettings.h>
#include <Tactility/service/wifi/Wifi.h>
#include <Tactility/service/wifi/WifiApSettings.h>
#include <Tactility/service/webserver/AssetVersion.h>
#include <Tactility/service/webserver/WebServerService.h>
#include <Tactility/Assets.h>
#include <Tactility/lvgl/Toolbar.h> #include <Tactility/lvgl/Toolbar.h>
#include <Tactility/lvgl/LvglSync.h> #include <Tactility/service/webserver/WebServerService.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h>
#include <lvgl/icons/shared.h> #include <lvgl/icons/shared.h>
#include <lvgl.h> #include <lvgl/lvgl.h>
#include <tactility/log.h>
#include <esp_netif.h> #include <esp_netif.h>
#include <esp_wifi.h> #include <esp_wifi.h>
#include <freertos/FreeRTOS.h>
#include <freertos/timers.h>
namespace tt::app::webserversettings { namespace tt::app::webserversettings {
@ -47,10 +42,9 @@ class WebServerSettingsApp final : public App {
app->wsSettings.wifiMode = static_cast<settings::webserver::WiFiMode>(index); app->wsSettings.wifiMode = static_cast<settings::webserver::WiFiMode>(index);
app->updated = true; app->updated = true;
app->wifiSettingsChanged = true; app->wifiSettingsChanged = true;
if (lvgl::lock(100)) { lvgl_lock();
app->updateUrlDisplay(); app->updateUrlDisplay();
lvgl::unlock(); lvgl_unlock();
}
}); });
} }
@ -60,10 +54,9 @@ class WebServerSettingsApp final : public App {
getMainDispatcher().dispatch([app, enabled] { getMainDispatcher().dispatch([app, enabled] {
app->wsSettings.webServerEnabled = enabled; app->wsSettings.webServerEnabled = enabled;
app->updated = true; app->updated = true;
if (lvgl::lock(100)) { lvgl_lock();
app->updateUrlDisplay(); app->updateUrlDisplay();
lvgl::unlock(); lvgl_unlock();
}
// Apply immediately instead of waiting for app exit // Apply immediately instead of waiting for app exit
const auto copy = app->wsSettings; const auto copy = app->wsSettings;

View File

@ -1,20 +1,17 @@
#include "Tactility/lvgl/LvglSync.h"
#include <Tactility/LogMessages.h>
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h> #include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <lvgl/widgets/toolbar.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <Tactility/service/wifi/WifiApSettings.h> #include <Tactility/service/wifi/WifiApSettings.h>
#include <lvgl/lvgl.h>
#include <lvgl/widgets/toolbar.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl.h>
namespace tt::app::wifiapsettings { namespace tt::app::wifiapsettings {
constexpr auto* TAG = "WifiApSettings"; constexpr auto* TAG = "WifiApSettings";
@ -88,12 +85,9 @@ class WifiApSettings : public App {
void requestViewUpdate() const { void requestViewUpdate() const {
if (viewEnabled) { if (viewEnabled) {
if (lvgl::lock(1000)) { lvgl_lock();
updateViews(); updateViews();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
} }
} }

View File

@ -1,12 +1,10 @@
#include <Tactility/app/wificonnect/WifiConnect.h> #include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/LogMessages.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h> #include <lvgl/lvgl.h>
namespace tt::app::wificonnect { namespace tt::app::wificonnect {
@ -68,12 +66,9 @@ void WifiConnect::unlock() {
void WifiConnect::requestViewUpdate() { void WifiConnect::requestViewUpdate() {
lock(); lock();
if (viewEnabled) { if (viewEnabled) {
if (lvgl::lock(1000)) { lvgl_lock();
view.update(); view.update();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
} }
unlock(); unlock();
} }

View File

@ -1,16 +1,16 @@
#include <Tactility/app/wifimanage/WifiManagePrivate.h>
#include <Tactility/app/wifimanage/View.h> #include <Tactility/app/wifimanage/View.h>
#include <Tactility/app/wifimanage/WifiManagePrivate.h>
#include <Tactility/LogMessages.h>
#include <Tactility/app/AppContext.h> #include <Tactility/app/AppContext.h>
#include <Tactility/app/wifiapsettings/WifiApSettings.h> #include <Tactility/app/wifiapsettings/WifiApSettings.h>
#include <Tactility/app/wificonnect/WifiConnect.h> #include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <lvgl/icons/shared.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/icons/shared.h>
#include <lvgl/lvgl.h>
namespace tt::app::wifimanage { namespace tt::app::wifimanage {
constexpr auto* TAG = "WifiManage"; constexpr auto* TAG = "WifiManage";
@ -65,12 +65,9 @@ void WifiManage::unlock() {
void WifiManage::requestViewUpdate() { void WifiManage::requestViewUpdate() {
lock(); lock();
if (isViewEnabled) { if (isViewEnabled) {
if (lvgl::lock(1000)) { lvgl_lock();
view.update(); view.update();
lvgl::unlock(); lvgl_unlock();
} else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
} }
unlock(); unlock();
} }

View File

@ -11,7 +11,8 @@
#include <Tactility/Assets.h> #include <Tactility/Assets.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/lvgl/Keyboard.h> #include <Tactility/lvgl/Keyboard.h>
#include <Tactility/lvgl/LvglSync.h>
#include <tactility/log.h>
#include <host/ble_gap.h> #include <host/ble_gap.h>
#include <host/ble_gatt.h> #include <host/ble_gatt.h>
@ -20,8 +21,8 @@
#include <esp_timer.h> #include <esp_timer.h>
#include <freertos/FreeRTOS.h> #include <freertos/FreeRTOS.h>
#include <freertos/queue.h> #include <freertos/queue.h>
#include <lvgl.h>
#include <tactility/log.h> #include <lvgl/lvgl.h>
#include <algorithm> #include <algorithm>
#include <array> #include <array>
@ -226,7 +227,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) {
if (hid_host_ctx && hid_host_ctx->mouseIndev == nullptr) { if (hid_host_ctx && hid_host_ctx->mouseIndev == nullptr) {
getMainDispatcher().dispatch([] { getMainDispatcher().dispatch([] {
if (!hid_host_ctx || hid_host_ctx->mouseIndev != nullptr) return; if (!hid_host_ctx || hid_host_ctx->mouseIndev != nullptr) return;
if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for mouse indev"); return; } if (!lvgl_try_lock(1000)) { LOG_W(TAG, "LVGL lock failed for mouse indev"); return; }
auto* ms = lv_indev_create(); auto* ms = lv_indev_create();
lv_indev_set_type(ms, LV_INDEV_TYPE_POINTER); lv_indev_set_type(ms, LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(ms, hidHostMouseReadCb); lv_indev_set_read_cb(ms, hidHostMouseReadCb);
@ -237,7 +238,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) {
lv_indev_set_cursor(ms, cur); lv_indev_set_cursor(ms, cur);
hid_host_ctx->mouseIndev = ms; hid_host_ctx->mouseIndev = ms;
hid_host_ctx->mouseCursor = cur; hid_host_ctx->mouseCursor = cur;
tt::lvgl::unlock(); lvgl_unlock();
LOG_I(TAG, "Mouse indev registered"); LOG_I(TAG, "Mouse indev registered");
}); });
} }
@ -468,13 +469,13 @@ static void hidHostSubscribeNext(HidHostCtx& ctx) {
} }
getMainDispatcher().dispatch([] { getMainDispatcher().dispatch([] {
if (!hid_host_ctx || hid_host_ctx->kbIndev != nullptr) return; if (!hid_host_ctx || hid_host_ctx->kbIndev != nullptr) return;
if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for kb indev"); return; } if (!lvgl_try_lock(1000)) { LOG_W(TAG, "LVGL lock failed for kb indev"); return; }
auto* kb = lv_indev_create(); auto* kb = lv_indev_create();
lv_indev_set_type(kb, LV_INDEV_TYPE_KEYPAD); lv_indev_set_type(kb, LV_INDEV_TYPE_KEYPAD);
lv_indev_set_read_cb(kb, hidHostKeyboardReadCb); lv_indev_set_read_cb(kb, hidHostKeyboardReadCb);
hid_host_ctx->kbIndev = kb; hid_host_ctx->kbIndev = kb;
tt::lvgl::hardware_keyboard_set_indev(kb); lvgl::hardware_keyboard_set_indev(kb);
tt::lvgl::unlock(); lvgl_unlock();
LOG_I(TAG, "Keyboard indev registered"); LOG_I(TAG, "Keyboard indev registered");
}); });
@ -694,18 +695,18 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
} }
getMainDispatcher().dispatch([saved_kb, saved_mouse, saved_cursor, saved_queue] { getMainDispatcher().dispatch([saved_kb, saved_mouse, saved_cursor, saved_queue] {
if (!tt::lvgl::lock(1000)) { if (!lvgl_try_lock(1000)) {
LOG_W(TAG, "Failed to acquire LVGL lock for indev cleanup"); LOG_W(TAG, "Failed to acquire LVGL lock for indev cleanup");
if (saved_queue) vQueueDelete(saved_queue); if (saved_queue) vQueueDelete(saved_queue);
return; return;
} }
if (saved_kb) { if (saved_kb) {
tt::lvgl::hardware_keyboard_set_indev(nullptr); lvgl::hardware_keyboard_set_indev(nullptr);
lv_indev_delete(saved_kb); lv_indev_delete(saved_kb);
} }
if (saved_mouse) lv_indev_delete(saved_mouse); if (saved_mouse) lv_indev_delete(saved_mouse);
if (saved_cursor) lv_obj_delete(saved_cursor); if (saved_cursor) lv_obj_delete(saved_cursor);
tt::lvgl::unlock(); lvgl_unlock();
if (saved_queue) vQueueDelete(saved_queue); if (saved_queue) vQueueDelete(saved_queue);
}); });
break; break;

View File

@ -1,35 +0,0 @@
#include "Tactility/lvgl/LvglSync.h"
#include <Tactility/Mutex.h>
#include <lvgl/lvgl.h>
namespace tt::lvgl {
bool lock(TickType_t timeout) {
return lvgl_try_lock(timeout);
}
void unlock() {
lvgl_unlock();
}
class LvglSync : public Lock {
public:
~LvglSync() override = default;
bool lock(TickType_t timeoutTicks) const override {
return lvgl_try_lock(timeoutTicks);
}
void unlock() const override {
lvgl_unlock();
}
};
static std::shared_ptr<Lock> lvglSync = std::make_shared<LvglSync>();
std::shared_ptr<Lock> getSyncLock() {
return lvglSync;
}
} // namespace

View File

@ -5,17 +5,16 @@
#include <Tactility/RecursiveMutex.h> #include <Tactility/RecursiveMutex.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Statusbar.h> #include <Tactility/lvgl/Statusbar.h>
#include <Tactility/lvgl/Style.h> #include <Tactility/lvgl/Style.h>
#include <Tactility/settings/Time.h> #include <Tactility/settings/Time.h>
#include <lvgl/fonts.h>
#include <lvgl/lvgl.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl.h> #include <lvgl/fonts.h>
#include <lvgl/lvgl.h>
#include <memory> #include <memory>
namespace tt::lvgl { namespace tt::lvgl {
@ -106,10 +105,10 @@ static lv_obj_class_t statusbar_class = {
static void statusbar_pubsub_event(Statusbar* statusbar) { static void statusbar_pubsub_event(Statusbar* statusbar) {
LOG_D(TAG, "Update event"); LOG_D(TAG, "Update event");
if (lock(defaultLockTime)) { if (lvgl_try_lock(500 / portTICK_PERIOD_MS)) {
update_main(statusbar); update_main(statusbar);
lv_obj_invalidate(&statusbar->obj); lv_obj_invalidate(&statusbar->obj);
unlock(); lvgl_unlock();
} else { } else {
LOG_W(TAG, "Mutex acquisition timeout (%s)", "Statusbar"); LOG_W(TAG, "Mutex acquisition timeout (%s)", "Statusbar");
} }

View File

@ -2,10 +2,8 @@
#ifdef ESP_PLATFORM #ifdef ESP_PLATFORM
#include <atomic>
#include <Tactility/Assets.h> #include <Tactility/Assets.h>
#include <Tactility/lvgl/Keyboard.h> #include <Tactility/lvgl/Keyboard.h>
#include <Tactility/lvgl/LvglSync.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/usb_host_hid.h> #include <tactility/drivers/usb_host_hid.h>
@ -16,7 +14,9 @@
#include <freertos/task.h> #include <freertos/task.h>
#include <freertos/semphr.h> #include <freertos/semphr.h>
#include <lvgl.h> #include <lvgl/lvgl.h>
#include <atomic>
namespace tt::lvgl { namespace tt::lvgl {
@ -148,33 +148,31 @@ static void usbHidInputTask(void* arg) {
auto* ctx = static_cast<UsbHidInputCtx*>(arg); auto* ctx = static_cast<UsbHidInputCtx*>(arg);
LOG_I(TAG, "started"); LOG_I(TAG, "started");
// TODO: Implement time-out
while (!lv_is_initialized()) { while (!lv_is_initialized()) {
vTaskDelay(pdMS_TO_TICKS(100)); vTaskDelay(pdMS_TO_TICKS(100));
} }
if (lock()) { lvgl_lock();
ctx->mouse_cursor = lv_image_create(lv_layer_sys());
lv_obj_remove_flag(ctx->mouse_cursor, LV_OBJ_FLAG_CLICKABLE);
lv_image_set_src(ctx->mouse_cursor, TT_ASSETS_UI_CURSOR);
lv_obj_add_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN);
ctx->mouse_indev = lv_indev_create(); ctx->mouse_cursor = lv_image_create(lv_layer_sys());
lv_indev_set_type(ctx->mouse_indev, LV_INDEV_TYPE_POINTER); lv_obj_remove_flag(ctx->mouse_cursor, LV_OBJ_FLAG_CLICKABLE);
lv_indev_set_read_cb(ctx->mouse_indev, mouse_read_cb); lv_image_set_src(ctx->mouse_cursor, TT_ASSETS_UI_CURSOR);
lv_indev_set_user_data(ctx->mouse_indev, ctx); lv_obj_add_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN);
lv_indev_set_cursor(ctx->mouse_indev, ctx->mouse_cursor);
ctx->kb_indev = lv_indev_create(); ctx->mouse_indev = lv_indev_create();
lv_indev_set_type(ctx->kb_indev, LV_INDEV_TYPE_KEYPAD); lv_indev_set_type(ctx->mouse_indev, LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(ctx->kb_indev, keyboard_read_cb); lv_indev_set_read_cb(ctx->mouse_indev, mouse_read_cb);
lv_indev_set_user_data(ctx->kb_indev, ctx); lv_indev_set_user_data(ctx->mouse_indev, ctx);
lv_indev_set_group(ctx->kb_indev, lv_group_get_default()); lv_indev_set_cursor(ctx->mouse_indev, ctx->mouse_cursor);
unlock(); ctx->kb_indev = lv_indev_create();
LOG_I(TAG, "LVGL input devices registered"); lv_indev_set_type(ctx->kb_indev, LV_INDEV_TYPE_KEYPAD);
} else { lv_indev_set_read_cb(ctx->kb_indev, keyboard_read_cb);
LOG_W(TAG, "could not acquire LVGL lock for indev registration"); lv_indev_set_user_data(ctx->kb_indev, ctx);
} lv_indev_set_group(ctx->kb_indev, lv_group_get_default());
lvgl_unlock();
// Drain the HID event queue and route events to the appropriate destinations // Drain the HID event queue and route events to the appropriate destinations
while (ctx->running) { while (ctx->running) {
@ -228,29 +226,29 @@ static void usbHidInputTask(void* arg) {
break; break;
} }
case USB_HID_EVENT_KEYBOARD_CONNECTED: case USB_HID_EVENT_KEYBOARD_CONNECTED:
if (ctx->kb_indev && lock(pdMS_TO_TICKS(200))) { if (ctx->kb_indev && lvgl_try_lock(pdMS_TO_TICKS(200))) {
hardware_keyboard_set_indev(ctx->kb_indev); hardware_keyboard_set_indev(ctx->kb_indev);
unlock(); lvgl_unlock();
} }
break; break;
case USB_HID_EVENT_KEYBOARD_DISCONNECTED: case USB_HID_EVENT_KEYBOARD_DISCONNECTED:
if (lock(pdMS_TO_TICKS(200))) { if (lvgl_try_lock(pdMS_TO_TICKS(200))) {
hardware_keyboard_set_indev(nullptr); hardware_keyboard_set_indev(nullptr);
unlock(); lvgl_unlock();
} }
break; break;
case USB_HID_EVENT_MOUSE_CONNECTED: case USB_HID_EVENT_MOUSE_CONNECTED:
ctx->mouse_connected = true; ctx->mouse_connected = true;
if (ctx->mouse_cursor && lock(pdMS_TO_TICKS(200))) { if (ctx->mouse_cursor && lvgl_try_lock(pdMS_TO_TICKS(200))) {
lv_obj_remove_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN);
unlock(); lvgl_unlock();
} }
break; break;
case USB_HID_EVENT_MOUSE_DISCONNECTED: case USB_HID_EVENT_MOUSE_DISCONNECTED:
ctx->mouse_connected = false; ctx->mouse_connected = false;
if (ctx->mouse_cursor && lock(pdMS_TO_TICKS(200))) { if (ctx->mouse_cursor && lvgl_try_lock(pdMS_TO_TICKS(200))) {
lv_obj_add_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(ctx->mouse_cursor, LV_OBJ_FLAG_HIDDEN);
unlock(); lvgl_unlock();
} }
break; break;
default: default:
@ -258,16 +256,15 @@ static void usbHidInputTask(void* arg) {
} }
} }
if (lock()) { lvgl_lock();
if (ctx->mouse_indev) { lv_indev_delete(ctx->mouse_indev); ctx->mouse_indev = nullptr; } if (ctx->mouse_indev) { lv_indev_delete(ctx->mouse_indev); ctx->mouse_indev = nullptr; }
if (ctx->mouse_cursor) { lv_obj_delete(ctx->mouse_cursor); ctx->mouse_cursor = nullptr; } if (ctx->mouse_cursor) { lv_obj_delete(ctx->mouse_cursor); ctx->mouse_cursor = nullptr; }
if (ctx->kb_indev) { if (ctx->kb_indev) {
hardware_keyboard_set_indev(nullptr); hardware_keyboard_set_indev(nullptr);
lv_indev_delete(ctx->kb_indev); lv_indev_delete(ctx->kb_indev);
ctx->kb_indev = nullptr; ctx->kb_indev = nullptr;
}
unlock();
} }
lvgl_unlock();
LOG_I(TAG, "stopped"); LOG_I(TAG, "stopped");
xSemaphoreGive(ctx->task_done); xSemaphoreGive(ctx->task_done);
@ -334,7 +331,7 @@ void stopUsbHidInput() {
vTaskDelete(ctx->task); vTaskDelete(ctx->task);
// Task was killed before it could clean up LVGL objects; do it here to // Task was killed before it could clean up LVGL objects; do it here to
// prevent mouse_read_cb / keyboard_read_cb from running with a freed ctx. // prevent mouse_read_cb / keyboard_read_cb from running with a freed ctx.
if (lock(pdMS_TO_TICKS(200))) { if (lvgl_try_lock(pdMS_TO_TICKS(200))) {
if (ctx->mouse_indev) { lv_indev_delete(ctx->mouse_indev); ctx->mouse_indev = nullptr; } if (ctx->mouse_indev) { lv_indev_delete(ctx->mouse_indev); ctx->mouse_indev = nullptr; }
if (ctx->mouse_cursor) { lv_obj_delete(ctx->mouse_cursor); ctx->mouse_cursor = nullptr; } if (ctx->mouse_cursor) { lv_obj_delete(ctx->mouse_cursor); ctx->mouse_cursor = nullptr; }
if (ctx->kb_indev) { if (ctx->kb_indev) {
@ -342,7 +339,7 @@ void stopUsbHidInput() {
lv_indev_delete(ctx->kb_indev); lv_indev_delete(ctx->kb_indev);
ctx->kb_indev = nullptr; ctx->kb_indev = nullptr;
} }
unlock(); lvgl_unlock();
} }
} }
ctx->task = nullptr; ctx->task = nullptr;

View File

@ -200,10 +200,10 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP
auto expected_chunk_size = std::min<size_t>(BUFFER_SIZE, length - bytes_received); auto expected_chunk_size = std::min<size_t>(BUFFER_SIZE, length - bytes_received);
size_t receive_chunk_size = httpd_req_recv(request, buffer, expected_chunk_size); size_t receive_chunk_size = httpd_req_recv(request, buffer, expected_chunk_size);
if (receive_chunk_size <= 0) { if (receive_chunk_size <= 0) {
LOG_E(TAG, "Receive failed"); LOG_E(TAG, "Receive failed, got 0 bytes but expected %zu more", length - bytes_received);
break; break;
} }
if (fwrite(buffer, 1, receive_chunk_size, file) != (size_t)receive_chunk_size) { if (fwrite(buffer, 1, receive_chunk_size, file) != receive_chunk_size) {
LOG_E(TAG, "Failed to write all bytes"); LOG_E(TAG, "Failed to write all bytes");
break; break;
} }

View File

@ -1,5 +1,6 @@
#include <Tactility/service/ServiceRegistration.h> #include <Tactility/service/ServiceRegistration.h>
#include <Tactility/Mutex.h>
#include <Tactility/service/ServiceContext.h> #include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServiceManifest.h> #include <Tactility/service/ServiceManifest.h>
@ -9,11 +10,35 @@
#include <cassert> #include <cassert>
#include <memory> #include <memory>
#include <unordered_map>
namespace tt::service { namespace tt::service {
constexpr auto* TAG = "ServiceRegistration"; constexpr auto* TAG = "ServiceRegistration";
namespace {
// Tracks the heap allocations addService() makes per registered id, so removeService()
// can free them once the kernel confirms the manifest is unregistered. The kernel only
// ever stores the raw pointer it's handed (see service_manager_add/_remove) - it never
// takes ownership - so the registering side (us) is responsible for the lifetime.
struct AllocatedManifest {
std::shared_ptr<const ServiceManifest>* persistentManifest;
::ServiceManifest* cManifest;
};
Mutex& allocatedManifestsMutex() {
static Mutex mutex;
return mutex;
}
std::unordered_map<std::string, AllocatedManifest>& allocatedManifests() {
static std::unordered_map<std::string, AllocatedManifest> map;
return map;
}
} // namespace
// Bridges the kernel's C ServiceManifest/Service callbacks to the C++ Service // Bridges the kernel's C ServiceManifest/Service callbacks to the C++ Service
// instances they wrap. Declared extern "C" to match the linkage of the C // instances they wrap. Declared extern "C" to match the linkage of the C
// function-pointer types they're assigned to (see e.g. gpio_controller.cpp). // function-pointer types they're assigned to (see e.g. gpio_controller.cpp).
@ -48,9 +73,8 @@ void addService(std::shared_ptr<const ServiceManifest> manifest, bool autoStart)
return; return;
} }
// Intentionally never freed: removeService() only unregisters the manifest // Freed by removeService() once the kernel confirms the manifest is unregistered.
// from the kernel, it doesn't own this allocation. Keeps id's backing // Keeps id's backing string alive for cManifest.id below in the meantime.
// string alive for cManifest.id below.
auto* persistentManifest = new std::shared_ptr(manifest); auto* persistentManifest = new std::shared_ptr(manifest);
auto* cManifest = new ::ServiceManifest { auto* cManifest = new ::ServiceManifest {
.id = (*persistentManifest)->id.c_str(), .id = (*persistentManifest)->id.c_str(),
@ -60,6 +84,12 @@ void addService(std::shared_ptr<const ServiceManifest> manifest, bool autoStart)
.on_stop = cppOnStopTrampoline, .on_stop = cppOnStopTrampoline,
}; };
{
auto lock = allocatedManifestsMutex().asScopedLock();
lock.lock();
allocatedManifests()[id] = AllocatedManifest { persistentManifest, cManifest };
}
error_t error = service_manager_add(cManifest, autoStart); error_t error = service_manager_add(cManifest, autoStart);
if (error != ERROR_NONE) { if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to add service %s: %s", id.c_str(), error_to_string(error)); LOG_E(TAG, "Failed to add service %s: %s", id.c_str(), error_to_string(error));
@ -85,6 +115,20 @@ bool removeService(const std::string& id) {
LOG_E(TAG, "Failed to remove service %s: %s", id.c_str(), error_to_string(error)); LOG_E(TAG, "Failed to remove service %s: %s", id.c_str(), error_to_string(error));
return false; return false;
} }
// The kernel has confirmed the manifest is unregistered, so id (which points into
// persistentManifest's string) is no longer needed by anything - safe to free now.
{
auto lock = allocatedManifestsMutex().asScopedLock();
lock.lock();
auto iterator = allocatedManifests().find(id);
if (iterator != allocatedManifests().end()) {
delete iterator->second.cManifest;
delete iterator->second.persistentManifest;
allocatedManifests().erase(iterator);
}
}
LOG_I(TAG, "Removed %s", id.c_str()); LOG_I(TAG, "Removed %s", id.c_str());
return true; return true;
} }

View File

@ -157,13 +157,20 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) {
// Create tmp directory // Create tmp directory
const std::string tmp_path = getTempPath(); const std::string tmp_path = getTempPath();
if (!file::findOrCreateDirectory(tmp_path, 0777)) { if (!file::findOrCreateDirectory(tmp_path, 0777)) {
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to save file"); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to create temp path");
return ESP_FAIL; return ESP_FAIL;
} }
auto file_path = std::format("{}/{}", tmp_path, filename_entry->second); std::string safe_name = file::getLastPathSegment(filename_entry->second);
if (safe_name.empty() || safe_name.find("..") != std::string::npos ||
safe_name.find('/') != std::string::npos || safe_name.find('\\') != std::string::npos) {
httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid filename");
return ESP_FAIL;
}
auto file_path = std::format("{}/{}", tmp_path, safe_name);
if (network::receiveFile(request, file_size, file_path) != file_size) { if (network::receiveFile(request, file_size, file_path) != file_size) {
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to save file"); file::deleteFile(file_path);
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive file");
return ESP_FAIL; return ESP_FAIL;
} }

View File

@ -1,19 +1,18 @@
#include <Tactility/service/gui/GuiService.h> #include <Tactility/service/gui/GuiService.h>
#include <cstring>
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/Tactility.h> #include <Tactility/Tactility.h>
#include <Tactility/app/AppInstance.h> #include <Tactility/app/AppInstance.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Statusbar.h> #include <Tactility/lvgl/Statusbar.h>
#include <Tactility/lvgl/UsbHidInput.h> #include <Tactility/lvgl/UsbHidInput.h>
#include <Tactility/service/ServiceRegistration.h> #include <Tactility/service/ServiceRegistration.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/lvgl.h> #include <lvgl/lvgl.h>
#include <cstring>
namespace tt::service::gui { namespace tt::service::gui {
extern const ServiceManifest manifest; extern const ServiceManifest manifest;
@ -200,6 +199,13 @@ void GuiService::redraw() {
// Create a default group which adds all objects automatically, // Create a default group which adds all objects automatically,
// and assign all indevs to it. // and assign all indevs to it.
// This enables navigation with limited input, such as encoder wheels. // This enables navigation with limited input, such as encoder wheels.
// The previous default group (if any) is no longer referenced by anything
// after lv_obj_clean() above, so it must be freed here or it leaks.
auto* previous_group = lv_group_get_default();
if (previous_group != nullptr) {
lv_group_delete(previous_group);
}
lv_group_t* group = lv_group_create(); lv_group_t* group = lv_group_create();
auto* indev = lv_indev_get_next(nullptr); auto* indev = lv_indev_get_next(nullptr);
while (indev) { while (indev) {
@ -279,6 +285,17 @@ void GuiService::onStop(ServiceContext& service) {
lv_group_delete(keyboardGroup); lv_group_delete(keyboardGroup);
keyboardGroup = nullptr; keyboardGroup = nullptr;
} }
auto* default_group = lv_group_get_default();
if (default_group != nullptr) {
lv_group_delete(default_group);
lv_group_set_default(nullptr);
}
auto* screen_root = lv_screen_active();
if (screen_root != nullptr) {
lv_obj_clean(screen_root);
}
lvgl_unlock(); lvgl_unlock();
delete thread; delete thread;

View File

@ -1,11 +1,12 @@
#include "Tactility/lvgl/Keyboard.h" #include <Tactility/lvgl/Keyboard.h>
#include "Tactility/lvgl/LvglSync.h" #include <Tactility/service/gui/GuiService.h>
#include "Tactility/service/gui/GuiService.h"
#include <tactility/check.h>
#include <Tactility/TactilityConfig.h> #include <Tactility/TactilityConfig.h>
#include <Tactility/service/espnow/EspNowService.h> #include <Tactility/service/espnow/EspNowService.h>
#include <tactility/check.h>
#include <lvgl/lvgl.h>
namespace tt::service::gui { namespace tt::service::gui {
static void show_keyboard(lv_event_t* event) { static void show_keyboard(lv_event_t* event) {
@ -53,7 +54,7 @@ void GuiService::keyboardAddTextArea(lv_obj_t* textarea) {
lock(); lock();
if (isStarted) { if (isStarted) {
check(lvgl::lock(0), "lvgl should already be locked before calling this method"); check(lvgl_try_lock(0), "lvgl should already be locked before calling this method");
if (softwareKeyboardIsEnabled()) { if (softwareKeyboardIsEnabled()) {
lv_obj_add_event_cb(textarea, show_keyboard, LV_EVENT_FOCUSED, nullptr); lv_obj_add_event_cb(textarea, show_keyboard, LV_EVENT_FOCUSED, nullptr);
@ -66,7 +67,7 @@ void GuiService::keyboardAddTextArea(lv_obj_t* textarea) {
lvgl::software_keyboard_activate(keyboardGroup); lvgl::software_keyboard_activate(keyboardGroup);
} }
lvgl::unlock(); lvgl_unlock();
} }
unlock(); unlock();

View File

@ -10,12 +10,8 @@
#include <vector> #include <vector>
#ifdef ESP_PLATFORM
#include <esp_heap_caps.h>
#include <utility>
#endif
#include <tactility/log.h> #include <tactility/log.h>
#include <tactility/memory.h>
namespace tt::service::loader { namespace tt::service::loader {
@ -72,6 +68,8 @@ void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launc
appStack.push_back(new_app); appStack.push_back(new_app);
transitionAppToState(new_app, app::State::Created); transitionAppToState(new_app, app::State::Created);
transitionAppToState(new_app, app::State::Showing); transitionAppToState(new_app, app::State::Showing);
memory_print_stats();
} }
void LoaderService::onStopTopAppMessage(const std::string& id) { void LoaderService::onStopTopAppMessage(const std::string& id) {
@ -125,10 +123,6 @@ void LoaderService::onStopTopAppMessage(const std::string& id) {
LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop->getApp().use_count() - 2)); LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop->getApp().use_count() - 2));
} }
#ifdef ESP_PLATFORM
LOG_I(TAG, "Free heap: %d", (int)heap_caps_get_free_size(MALLOC_CAP_INTERNAL));
#endif
std::shared_ptr<app::AppInstance> instance_to_resume; std::shared_ptr<app::AppInstance> instance_to_resume;
// If there's a previous app, resume it // If there's a previous app, resume it
if (!appStack.empty()) { if (!appStack.empty()) {
@ -167,6 +161,8 @@ void LoaderService::onStopTopAppMessage(const std::string& id) {
); );
} }
} }
memory_print_stats();
} }
int LoaderService::findAppInStack(const std::string& id) const { int LoaderService::findAppInStack(const std::string& id) const {

View File

@ -5,16 +5,17 @@
#include <Tactility/LogMessages.h> #include <Tactility/LogMessages.h>
#include <Tactility/CpuAffinity.h> #include <Tactility/CpuAffinity.h>
#include <Tactility/TactilityCore.h> #include <Tactility/TactilityCore.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h> #include <Tactility/service/loader/Loader.h>
#include <Tactility/service/screenshot/ScreenshotTask.h> #include <Tactility/service/screenshot/ScreenshotTask.h>
#include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <lv_screenshot.h> #include <lv_screenshot.h>
#include <format> #include <format>
#include <tactility/log.h>
namespace tt::service::screenshot { namespace tt::service::screenshot {
constexpr auto* TAG = "ScreenshotTask"; constexpr auto* TAG = "ScreenshotTask";
@ -50,13 +51,13 @@ void ScreenshotTask::setFinished() {
} }
static void makeScreenshot(const std::string& filename) { static void makeScreenshot(const std::string& filename) {
if (lvgl::lock(50 / portTICK_PERIOD_MS)) { if (lvgl_try_lock(50 / portTICK_PERIOD_MS)) {
if (lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, filename.c_str())) { if (lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, filename.c_str())) {
LOG_I(TAG, "Screenshot saved to %s", filename.c_str()); LOG_I(TAG, "Screenshot saved to %s", filename.c_str());
} else { } else {
LOG_E(TAG, "Screenshot not saved to %s", filename.c_str()); LOG_E(TAG, "Screenshot not saved to %s", filename.c_str());
} }
lvgl::unlock(); lvgl_unlock();
} else { } else {
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
} }

View File

@ -3,11 +3,11 @@
#include <Tactility/Mutex.h> #include <Tactility/Mutex.h>
#include <Tactility/Timer.h> #include <Tactility/Timer.h>
#include <Tactility/bluetooth/Bluetooth.h> #include <Tactility/bluetooth/Bluetooth.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/ServiceContext.h> #include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServicePaths.h> #include <Tactility/service/ServicePaths.h>
#include <Tactility/service/ServiceRegistration.h> #include <Tactility/service/ServiceRegistration.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <tactility/check.h> #include <tactility/check.h>
#include <tactility/device.h> #include <tactility/device.h>
#include <tactility/drivers/bluetooth.h> #include <tactility/drivers/bluetooth.h>
@ -18,7 +18,6 @@
#include <tactility/drivers/usb_host_midi.h> #include <tactility/drivers/usb_host_midi.h>
#include <tactility/drivers/usb_host_msc.h> #include <tactility/drivers/usb_host_msc.h>
#include <tactility/filesystem/file_system.h> #include <tactility/filesystem/file_system.h>
#include <tactility/log.h> #include <tactility/log.h>
#include <lvgl/icons/statusbar.h> #include <lvgl/icons/statusbar.h>

View File

@ -1,8 +1,6 @@
#ifdef ESP_PLATFORM #ifdef ESP_PLATFORM
#include <tactility/check.h>
#include <Tactility/service/webserver/WebServerService.h> #include <Tactility/service/webserver/WebServerService.h>
#include <Tactility/service/webserver/AssetVersion.h>
#include <Tactility/service/ServiceManifest.h> #include <Tactility/service/ServiceManifest.h>
#include <Tactility/settings/WebServerSettings.h> #include <Tactility/settings/WebServerSettings.h>
#include <Tactility/MountPoints.h> #include <Tactility/MountPoints.h>
@ -10,28 +8,29 @@
#include <Tactility/lvgl/Statusbar.h> #include <Tactility/lvgl/Statusbar.h>
#include <Tactility/Mutex.h> #include <Tactility/Mutex.h>
#include <tactility/check.h>
#include <Tactility/TactilityConfig.h> #include <Tactility/TactilityConfig.h>
#include <Tactility/app/AppRegistration.h> #include <Tactility/app/AppRegistration.h>
#include <Tactility/app/AppManifest.h> #include <Tactility/app/AppManifest.h>
#include <Tactility/app/App.h> #include <Tactility/app/App.h>
#include <Tactility/service/wifi/Wifi.h> #include <Tactility/service/wifi/Wifi.h>
#include <esp_wifi_default.h>
#include <Tactility/network/HttpdReq.h> #include <Tactility/network/HttpdReq.h>
#include <Tactility/network/Url.h> #include <Tactility/network/Url.h>
#include <Tactility/Paths.h> #include <Tactility/Paths.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Lvgl.h> #include <Tactility/lvgl/Lvgl.h>
#include <Tactility/StringUtils.h> #include <Tactility/StringUtils.h>
#include <ranges>
#include <tactility/filesystem/file_system.h> #include <tactility/filesystem/file_system.h>
#include <tactility/log.h>
#include <lvgl/lvgl.h>
#include <lvgl/icons/statusbar.h>
#if TT_FEATURE_SCREENSHOT_ENABLED #if TT_FEATURE_SCREENSHOT_ENABLED
#include <lv_screenshot.h> #include <lv_screenshot.h>
#endif #endif
#include <lvgl/icons/statusbar.h>
#include <atomic> #include <atomic>
#include <cctype> #include <cctype>
#include <cerrno> #include <cerrno>
@ -42,16 +41,16 @@
#include <esp_netif.h> #include <esp_netif.h>
#include <esp_system.h> #include <esp_system.h>
#include <esp_vfs_fat.h> #include <esp_vfs_fat.h>
#include <esp_wifi_default.h>
#include <esp_wifi.h> #include <esp_wifi.h>
#include <freertos/FreeRTOS.h> #include <freertos/FreeRTOS.h>
#include <freertos/task.h> #include <freertos/task.h>
#include <iomanip> #include <iomanip>
#include <lwip/ip4_addr.h> #include <lwip/ip4_addr.h>
#include <mbedtls/base64.h> #include <mbedtls/base64.h>
#include <ranges>
#include <sstream> #include <sstream>
#include <tactility/log.h>
namespace tt::service::webserver { namespace tt::service::webserver {
constexpr auto* TAG = "WebServerService"; constexpr auto* TAG = "WebServerService";
@ -1477,9 +1476,9 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
std::string lvgl_screenshot_path = lvgl::PATH_PREFIX + screenshot_path; std::string lvgl_screenshot_path = lvgl::PATH_PREFIX + screenshot_path;
// Capture screenshot using LVGL // Capture screenshot using LVGL
if (lvgl::lock(pdMS_TO_TICKS(100))) { if (lvgl_try_lock(pdMS_TO_TICKS(100))) {
bool success = lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, lvgl_screenshot_path.c_str()); bool success = lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, lvgl_screenshot_path.c_str());
lvgl::unlock(); lvgl_unlock();
if (!success) { if (!success) {
LOG_E(TAG, "lv_screenshot_create failed for path: %s", lvgl_screenshot_path.c_str()); LOG_E(TAG, "lv_screenshot_create failed for path: %s", lvgl_screenshot_path.c_str());

View File

@ -14,7 +14,7 @@ extern "C" {
* @param dts_devices The list of generated devices from the devicetree. The array must be terminated with DTS_DEVICE_TERMINATOR. Non-null parameter. * @param dts_devices The list of generated devices from the devicetree. The array must be terminated with DTS_DEVICE_TERMINATOR. Non-null parameter.
* @return ERROR_NONE on success, otherwise an error code * @return ERROR_NONE on success, otherwise an error code
*/ */
error_t kernel_init(struct Module* dts_modules[], struct DtsDevice dts_devices[]); error_t kernel_init(struct Module* const dts_modules[], const struct DtsDevice dts_devices[]);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -0,0 +1,115 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Capability flags that describe what a memory allocation needs or prefers. */
enum MemoryCapability {
/** Internal memory (non-external/non-PSRAM) memory. */
MEMORY_CAPABILITY_INTERNAL = 1u << 0,
/** External memory (e.g. PSRAM/SPIRAM). */
MEMORY_CAPABILITY_EXTERNAL = 1u << 1,
/** Usable for code execution. */
MEMORY_CAPABILITY_EXECUTABLE = 1u << 2,
/** Usable as a DMA source/destination. */
MEMORY_CAPABILITY_DMA = 1u << 3,
/** Usable for SIMD instructions. */
MEMORY_CAPABILITY_SIMD = 1u << 4,
};
/**
* @brief Describes the constraints an allocation must (or should) satisfy.
*
* `required` capabilities must all be satisfied or the allocation fails. `desired`
* capabilities are attempted alongside `required`, but implementations fall back to
* `required`-only if `required | desired` together can't be satisfied.
*/
struct MemoryPolicy {
/** A bitset of MemoryCapability flags that are required during allocation. */
uint16_t required;
/** A bitset of MemoryCapability flags that are preferable (but optional) during allocation. */
uint16_t desired;
/** Alignment (in bytes) of the returned pointer, or 0 for the platform default. Must be a power of 2. */
size_t alignment;
};
/** The default policy: no required/desired capabilities, no alignment requirement. */
extern const struct MemoryPolicy MEMORY_POLICY_DEFAULT;
/**
* @brief Logs current heap usage (internal and external, when applicable).
* No-op on platforms without heap capability tracking.
*/
void memory_print_stats();
/**
* @brief Allocates memory that satisfies the given policy.
* @param[in] size number of bytes to allocate
* @param[in] policy the allocation constraints
* @return the allocated memory, or NULL on failure
*/
void* memory_alloc_with_policy(size_t size, const struct MemoryPolicy* policy);
/**
* @brief Resizes a previous allocation, preserving its contents up to the smaller of the old and new size.
* @warning policy->alignment is not guaranteed to be preserved across a realloc - it is only
* honored on fresh allocations (memory_alloc_with_policy()/memory_calloc_with_policy()).
* @param[in] ptr memory previously returned by memory_alloc_with_policy(), memory_calloc_with_policy(),
* or memory_realloc_with_policy(), or NULL to allocate a new block
* @param[in] size new memory size in bytes
* @param[in] policy the policy for the new allocation
* @return the (possibly moved) allocated memory, or NULL on failure - in which case ptr is left untouched
*/
void* memory_realloc_with_policy(void* ptr, size_t size, const struct MemoryPolicy* policy);
/**
* @brief Allocates zero-initialized memory that satisfies the given policy.
* @param[in] count number of elements
* @param[in] size size of each element in bytes
* @param[in] policy the allocation constraints
* @return the allocated memory, or NULL on failure
*/
void* memory_calloc_with_policy(size_t count, size_t size, const struct MemoryPolicy* policy);
/**
* @brief Allocates memory using MEMORY_POLICY_DEFAULT.
* @param[in] size number of bytes to allocate
* @return the allocated memory, or NULL on failure
*/
inline void* memory_alloc(size_t size) {
return memory_alloc_with_policy(size, &MEMORY_POLICY_DEFAULT);
}
/**
* @brief Allocates zero-initialized memory using MEMORY_POLICY_DEFAULT.
* @param[in] count number of elements
* @param[in] size size of each element in bytes
* @return the allocated memory, or NULL on failure
*/
inline void* memory_calloc(size_t count, size_t size) {
return memory_calloc_with_policy(count, size, &MEMORY_POLICY_DEFAULT);
}
/**
* @brief Resizes a previous allocation using MEMORY_POLICY_DEFAULT. See memory_realloc_with_policy().
* @param[in] ptr memory previously returned by one of the memory_* allocation functions, or NULL
* @param[in] size new memory size in bytes
* @return the (possibly moved) allocated memory, or NULL on failure - in which case ptr is left untouched
*/
inline void* memory_realloc(void* ptr, size_t size) {
return memory_realloc_with_policy(ptr, size, &MEMORY_POLICY_DEFAULT);
}
/**
* @brief Frees memory previously returned by one of the memory_* allocation functions.
* @param[in] ptr the memory to free, or NULL (a no-op)
*/
void memory_free(void* ptr);
#ifdef __cplusplus
}
#endif

View File

@ -43,7 +43,7 @@ Module root_module = {
.internal = nullptr .internal = nullptr
}; };
error_t kernel_init(Module* dts_modules[], DtsDevice dts_devices[]) { error_t kernel_init(Module* const dts_modules[], const DtsDevice dts_devices[]) {
LOG_I(TAG, "init"); LOG_I(TAG, "init");
if (module_construct_add_start(&root_module) != ERROR_NONE) { if (module_construct_add_start(&root_module) != ERROR_NONE) {
@ -51,7 +51,7 @@ error_t kernel_init(Module* dts_modules[], DtsDevice dts_devices[]) {
return ERROR_RESOURCE; return ERROR_RESOURCE;
} }
Module** dts_module = dts_modules; Module* const* dts_module = dts_modules;
while (*dts_module != nullptr) { while (*dts_module != nullptr) {
if (module_construct_add_start(*dts_module) != ERROR_NONE) { if (module_construct_add_start(*dts_module) != ERROR_NONE) {
LOG_E(TAG, "dts module init failed: %s", (*dts_module)->name); LOG_E(TAG, "dts module init failed: %s", (*dts_module)->name);
@ -60,7 +60,7 @@ error_t kernel_init(Module* dts_modules[], DtsDevice dts_devices[]) {
dts_module++; dts_module++;
} }
DtsDevice* dts_device = dts_devices; const DtsDevice* dts_device = dts_devices;
while (dts_device->device != nullptr) { while (dts_device->device != nullptr) {
if (dts_device->status == DTS_DEVICE_STATUS_OKAY) { if (dts_device->status == DTS_DEVICE_STATUS_OKAY) {
if (device_construct_add_start(dts_device->device, dts_device->compatible) != ERROR_NONE) { if (device_construct_add_start(dts_device->device, dts_device->compatible) != ERROR_NONE) {

View File

@ -0,0 +1,29 @@
#include <tactility/log.h>
#include <tactility/memory.h>
#ifdef ESP_PLATFORM
#include <esp_heap_caps.h>
#endif
constexpr auto* TAG = "memory";
extern "C" {
const struct MemoryPolicy MEMORY_POLICY_DEFAULT = {
.required = 0,
.desired = 0,
.alignment = 0,
};
void memory_print_stats() {
#ifdef ESP_PLATFORM
size_t heap_free = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
size_t heap_total = heap_caps_get_total_size(MALLOC_CAP_INTERNAL);
LOG_I(TAG, "Heap: %zu / %zu available", heap_free, heap_total);
size_t ext_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
size_t ext_total = heap_caps_get_total_size(MALLOC_CAP_SPIRAM);
LOG_I(TAG, "External: %zu / %zu available", ext_free, ext_total);
#endif
}
}

View File

@ -0,0 +1,83 @@
// SPDX-License-Identifier: Apache-2.0
#ifdef ESP_PLATFORM
#include <tactility/memory.h>
#include <esp_heap_caps.h>
namespace {
uint32_t toHeapCaps(uint16_t capabilityFlags) {
uint32_t caps = 0;
if (capabilityFlags & MEMORY_CAPABILITY_INTERNAL) caps |= MALLOC_CAP_INTERNAL;
if (capabilityFlags & MEMORY_CAPABILITY_EXTERNAL) caps |= MALLOC_CAP_SPIRAM;
if (capabilityFlags & MEMORY_CAPABILITY_EXECUTABLE) caps |= MALLOC_CAP_EXEC;
if (capabilityFlags & MEMORY_CAPABILITY_DMA) caps |= MALLOC_CAP_DMA;
if (capabilityFlags & MEMORY_CAPABILITY_SIMD) caps |= MALLOC_CAP_SIMD;
return caps;
}
} // namespace
extern "C" {
void* memory_alloc_with_policy(size_t size, const struct MemoryPolicy* policy) {
uint32_t required_caps = toHeapCaps(policy->required);
uint32_t desired_caps = toHeapCaps(policy->desired);
void* ptr;
if (policy->alignment > 0) {
ptr = heap_caps_aligned_alloc(policy->alignment, size, required_caps | desired_caps);
if (ptr == nullptr && desired_caps != 0) {
// Desired caps couldn't be satisfied alongside the required ones - retry with
// required only, since desired is explicitly optional.
ptr = heap_caps_aligned_alloc(policy->alignment, size, required_caps);
}
} else {
ptr = heap_caps_malloc(size, required_caps | desired_caps);
if (ptr == nullptr && desired_caps != 0) {
ptr = heap_caps_malloc(size, required_caps);
}
}
return ptr;
}
void* memory_realloc_with_policy(void* ptr, size_t size, const struct MemoryPolicy* policy) {
uint32_t required_caps = toHeapCaps(policy->required);
uint32_t desired_caps = toHeapCaps(policy->desired);
// No aligned-realloc counterpart in the heap_caps API - policy->alignment is only honored
// on fresh allocations (memory_alloc_with_policy/memory_calloc_with_policy).
void* result = heap_caps_realloc(ptr, size, required_caps | desired_caps);
if (result == nullptr && desired_caps != 0) {
result = heap_caps_realloc(ptr, size, required_caps);
}
return result;
}
void* memory_calloc_with_policy(size_t count, size_t size, const struct MemoryPolicy* policy) {
uint32_t required_caps = toHeapCaps(policy->required);
uint32_t desired_caps = toHeapCaps(policy->desired);
void* ptr;
if (policy->alignment > 0) {
ptr = heap_caps_aligned_calloc(policy->alignment, count, size, required_caps | desired_caps);
if (ptr == nullptr && desired_caps != 0) {
ptr = heap_caps_aligned_calloc(policy->alignment, count, size, required_caps);
}
} else {
ptr = heap_caps_calloc(count, size, required_caps | desired_caps);
if (ptr == nullptr && desired_caps != 0) {
ptr = heap_caps_calloc(count, size, required_caps);
}
}
return ptr;
}
void memory_free(void* ptr) {
heap_caps_free(ptr);
}
} // extern "C"
#endif // ESP_PLATFORM

View File

@ -0,0 +1,68 @@
// SPDX-License-Identifier: Apache-2.0
#ifndef ESP_PLATFORM
#include <tactility/memory.h>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace {
// posix_memalign requires a power-of-2 alignment that's at least sizeof(void*).
size_t normalizeAlignment(uint8_t alignment) {
size_t result = alignment;
if (result < sizeof(void*)) {
result = sizeof(void*);
}
return result;
}
} // namespace
extern "C" {
// MEMORY_CAP_* flags are meaningless on the desktop simulator (no capability-restricted memory regions)
// policy->required/desired are intentionally ignored here.
void* memory_alloc_with_policy(size_t size, const struct MemoryPolicy* policy) {
if (policy->alignment > 0) {
void* ptr = nullptr;
if (posix_memalign(&ptr, normalizeAlignment(policy->alignment), size) != 0) {
return nullptr;
}
return ptr;
}
return malloc(size);
}
void* memory_realloc_with_policy(void* ptr, size_t size, const struct MemoryPolicy* policy) {
// Alignment can't be preserved across a POSIX realloc; only honored on fresh allocations
// (memory_alloc_with_policy/memory_calloc_with_policy).
return realloc(ptr, size);
}
void* memory_calloc_with_policy(size_t count, size_t size, const struct MemoryPolicy* policy) {
if (policy->alignment > 0) {
size_t total_size = count * size;
if (count != 0 && total_size / count != size) {
// count * size overflowed - reject rather than under-allocating.
return nullptr;
}
void* ptr = nullptr;
if (posix_memalign(&ptr, normalizeAlignment(policy->alignment), total_size) != 0) {
return nullptr;
}
memset(ptr, 0, total_size);
return ptr;
}
return calloc(count, size);
}
void memory_free(void* ptr) {
free(ptr);
}
} // extern "C"
#endif // !ESP_PLATFORM

View File

@ -37,6 +37,7 @@
#include <tactility/error.h> #include <tactility/error.h>
#include <tactility/filesystem/file_system.h> #include <tactility/filesystem/file_system.h>
#include <tactility/filesystem/file_mutex.h> #include <tactility/filesystem/file_mutex.h>
#include <tactility/memory.h>
#include <tactility/module.h> #include <tactility/module.h>
#include <tactility/wifi_auto_scan.h> #include <tactility/wifi_auto_scan.h>
#include <tactility/service/service_instance.h> #include <tactility/service/service_instance.h>
@ -175,6 +176,13 @@ const struct ModuleSymbol KERNEL_SYMBOLS[] = {
DEFINE_MODULE_SYMBOL(file_system_unmount), DEFINE_MODULE_SYMBOL(file_system_unmount),
DEFINE_MODULE_SYMBOL(file_system_is_mounted), DEFINE_MODULE_SYMBOL(file_system_is_mounted),
DEFINE_MODULE_SYMBOL(file_system_get_path), DEFINE_MODULE_SYMBOL(file_system_get_path),
// memory
DEFINE_MODULE_SYMBOL(MEMORY_POLICY_DEFAULT),
DEFINE_MODULE_SYMBOL(memory_print_stats),
DEFINE_MODULE_SYMBOL(memory_alloc_with_policy),
DEFINE_MODULE_SYMBOL(memory_realloc_with_policy),
DEFINE_MODULE_SYMBOL(memory_calloc_with_policy),
DEFINE_MODULE_SYMBOL(memory_free),
// drivers/gpio_controller // drivers/gpio_controller
DEFINE_MODULE_SYMBOL(gpio_descriptor_acquire), DEFINE_MODULE_SYMBOL(gpio_descriptor_acquire),
DEFINE_MODULE_SYMBOL(gpio_descriptor_release), DEFINE_MODULE_SYMBOL(gpio_descriptor_release),

View File

@ -0,0 +1,83 @@
#include "doctest.h"
#include <tactility/memory.h>
#include <cstdint>
#include <cstring>
TEST_CASE("MEMORY_POLICY_DEFAULT should have no requirements") {
CHECK_EQ(MEMORY_POLICY_DEFAULT.required, 0);
CHECK_EQ(MEMORY_POLICY_DEFAULT.desired, 0);
CHECK_EQ(MEMORY_POLICY_DEFAULT.alignment, 0);
}
TEST_CASE("memory_alloc should return usable memory") {
void* ptr = memory_alloc(64);
REQUIRE_NE(ptr, nullptr);
memset(ptr, 0xAB, 64);
CHECK_EQ(static_cast<uint8_t*>(ptr)[0], 0xAB);
CHECK_EQ(static_cast<uint8_t*>(ptr)[63], 0xAB);
memory_free(ptr);
}
TEST_CASE("memory_calloc should zero-initialize memory") {
auto* ptr = static_cast<uint8_t*>(memory_calloc(16, sizeof(uint8_t)));
REQUIRE_NE(ptr, nullptr);
for (size_t i = 0; i < 16; i++) {
CHECK_EQ(ptr[i], 0);
}
memory_free(ptr);
}
TEST_CASE("memory_realloc should preserve contents when growing") {
auto* ptr = static_cast<uint8_t*>(memory_alloc(8));
REQUIRE_NE(ptr, nullptr);
for (uint8_t i = 0; i < 8; i++) {
ptr[i] = i;
}
auto* grown = static_cast<uint8_t*>(memory_realloc(ptr, 32));
REQUIRE_NE(grown, nullptr);
for (uint8_t i = 0; i < 8; i++) {
CHECK_EQ(grown[i], i);
}
memory_free(grown);
}
TEST_CASE("memory_realloc with a NULL pointer should behave like an allocation") {
void* ptr = memory_realloc(nullptr, 32);
REQUIRE_NE(ptr, nullptr);
memset(ptr, 0, 32);
memory_free(ptr);
}
TEST_CASE("memory_free with a NULL pointer should be a no-op") {
memory_free(nullptr);
}
TEST_CASE("memory_alloc_with_policy should honor a power-of-2 alignment") {
MemoryPolicy policy = MEMORY_POLICY_DEFAULT;
policy.alignment = 64;
void* ptr = memory_alloc_with_policy(128, &policy);
REQUIRE_NE(ptr, nullptr);
CHECK_EQ(reinterpret_cast<uintptr_t>(ptr) % 64, 0);
memory_free(ptr);
}
TEST_CASE("memory_calloc_with_policy should honor alignment and zero-initialize") {
MemoryPolicy policy = MEMORY_POLICY_DEFAULT;
policy.alignment = 32;
auto* ptr = static_cast<uint8_t*>(memory_calloc_with_policy(8, sizeof(uint32_t), &policy));
REQUIRE_NE(ptr, nullptr);
CHECK_EQ(reinterpret_cast<uintptr_t>(ptr) % 32, 0);
for (size_t i = 0; i < 8 * sizeof(uint32_t); i++) {
CHECK_EQ(ptr[i], 0);
}
memory_free(ptr);
}
TEST_CASE("memory_print_stats should not crash") {
memory_print_stats();
}