Remove old HAL components and refactored GPS-related code (#583)

- Added generic GPS/GNSS support with device detection, configuration, and persistent settings.
- Improved device and module lifecycle management.
- Added flexible filesystem locking support for displays and storage.
- Improved display-idle and keyboard backlight handling.
- Updated architecture, driver, module, testing, and licensing documentation.
- Removed old HAL device and related code.
This commit is contained in:
Ken Van Hoeylandt
2026-07-25 17:20:17 +02:00
committed by GitHub
parent 29e80cfd65
commit 2a2558b29a
173 changed files with 3855 additions and 5445 deletions
-1
View File
@@ -1,7 +1,6 @@
#include "Tactility/MountPoints.h"
#include "Tactility/TactilityConfig.h"
#include <tactility/hal/Device.h>
#include <Tactility/file/File.h>
-4
View File
@@ -24,10 +24,6 @@ static std::list<SubscriptionData> subscriptions;
static const char* getEventName(SystemEvent event) {
switch (event) {
using enum SystemEvent;
case BootInitHalBegin:
return TT_STRINGIFY(BootInitHalBegin);
case BootInitHalEnd:
return TT_STRINGIFY(BootInitHalEnd);
case BootSplash:
return TT_STRINGIFY(BootSplash);
case NetworkConnected:
+24 -33
View File
@@ -14,14 +14,15 @@
#include <Tactility/app/AppRegistration.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <Tactility/hal/HalPrivate.h>
#include <Tactility/lvgl/LvglPrivate.h>
#include <Tactility/network/NtpPrivate.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/service/audio/Audio.h>
#include <Tactility/settings/TimePrivate.h>
#include <gps/gps_module.h>
#include <gps_generic/gps_generic_module.h>
#include <tactility/concurrent/thread.h>
#include <tactility/crypt_module.h>
#include <tactility/drivers/audio_stream.h>
@@ -31,7 +32,6 @@
#include <tactility/drivers/rtc.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/filesystem/file_system.h>
#include <tactility/hal_device_module.h>
#include <tactility/kernel_init.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
@@ -41,7 +41,8 @@
#endif
#include "Tactility/Paths.h"
#include "Tactility/SystemEvents.h"
#include "Tactility/hal/SdCard.h"
#include <Tactility/bluetooth/Bluetooth.h>
@@ -49,9 +50,10 @@ namespace tt {
constexpr auto* TAG = "Tactility";
static const Configuration* config_instance = nullptr;
static DispatcherHandle_t mainDispatcherHandle = dispatcher_alloc();
void initFileMutexForLvgl();
namespace {
void mainDispatcherTrampoline(void* context) {
@@ -75,7 +77,6 @@ bool MainDispatcher::dispatch(Function function, TickType_t timeout) const {
namespace service {
// Primary
namespace audio { extern const ServiceManifest manifest; }
namespace gps { extern const ServiceManifest manifest; }
namespace wifi { extern const ServiceManifest manifest; }
#ifdef ESP_PLATFORM
namespace development { extern const ServiceManifest manifest; }
@@ -183,8 +184,6 @@ static void registerInternalApps() {
}
if (device_exists_of_type(&DISPLAY_TYPE)) {
addAppManifest(app::kerneldisplay::manifest);
} else if (hal::hasDevice(hal::Device::Type::Display)) {
addAppManifest(app::display::manifest);
}
addAppManifest(app::files::manifest);
addAppManifest(app::fileselection::manifest);
@@ -322,7 +321,6 @@ static void registerAndStartPrimaryServices() {
if (device_exists_of_type(&AUDIO_STREAM_TYPE)) {
addService(service::audio::manifest);
}
addService(service::gps::manifest);
addService(service::wifi::manifest);
#ifdef ESP_PLATFORM
addService(service::development::manifest);
@@ -340,7 +338,8 @@ void createTempDirectory() {
auto data_path = getUserDataPath();
auto temp_path = std::format("{}/tmp", data_path);
if (!file::isDirectory(temp_path)) {
auto lock = file::getLock(data_path)->asScopedLock();
auto lockable = file::getLock(data_path);
auto lock = lockable->asScopedLock();
if (lock.lock(1000 / portTICK_PERIOD_MS)) {
if (!file::findOrCreateParentDirectory(temp_path, 0777)) {
LOG_E(TAG, "Failed to create %s", data_path.c_str());
@@ -366,40 +365,39 @@ void registerApps() {
registerInstalledAppsFromFileSystems();
}
void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices[]) {
void run(Module* dtsModules[], DtsDevice dtsDevices[]) {
LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID);
assert(config.hardware);
LOG_I(TAG, "Initializing kernel");
if (kernel_init(dtsModules, dtsDevices) != ERROR_NONE) {
LOG_E(TAG, "Failed to initialize kernel");
return;
}
// hal-device-module
check(module_construct_add_start(&hal_device_module) == ERROR_NONE);
// crypt-module
check(module_construct_add_start(&crypt_module) == ERROR_NONE);
// Assign early so starting services can use it
config_instance = &config;
check(module_ensure_started(&crypt_module) == ERROR_NONE);
check(module_ensure_started(&gps_module) == ERROR_NONE);
check(module_ensure_started(&gps_generic_module) == ERROR_NONE);
#ifdef ESP_PLATFORM
initEsp();
#endif
file::setFindLockFunction(file::findLock);
settings::initTimeZone();
hal::init(*config.hardware);
// Attempt to start all disabled SD cards (some require delayed init)
hal::sdcard::startAll();
network::ntp::init();
bluetooth::systemStart();
registerAndStartPrimaryServices();
// Must start right before LVGL
initFileMutexForLvgl();
lvgl_module_configure((LvglModuleConfig) {
.on_start = lvgl::attachDevices,
.on_stop = lvgl::detachDevices,
.on_start = nullptr,
.on_stop = nullptr,
.task_priority = THREAD_PRIORITY_HIGHER,
/** Minimum seems to be about 3500. In some scenarios, the WiFi app crashes at 8192,
* so we now have 9120 to run in a stable manner. We should figure out a way to avoid this.
@@ -409,9 +407,7 @@ void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices
.task_affinity = getCpuAffinityConfiguration().graphics
#endif
});
check(module_construct(&lvgl_module) == ERROR_NONE);
check(module_add(&lvgl_module) == ERROR_NONE);
lvgl::start();
check(module_ensure_started(&lvgl_module) == ERROR_NONE);
registerAndStartSecondaryServices();
@@ -428,11 +424,6 @@ void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices
}
}
/** return the configuration or nullptr if it's not initialized */
const Configuration* getConfiguration() {
return config_instance;
}
MainDispatcher getMainDispatcher() {
return MainDispatcher(mainDispatcherHandle);
}
+4 -3
View File
@@ -4,7 +4,6 @@
#include <Tactility/app/AppRegistration.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <tactility/hal/Device.h>
#include <Tactility/Paths.h>
#include <cerrno>
@@ -118,8 +117,10 @@ bool install(const std::string& path) {
return false;
}
auto target_path_lock = file::getLock(app_parent_path)->asScopedLock();
auto source_path_lock = file::getLock(path)->asScopedLock();
auto target_path_lockable = file::getLock(app_parent_path);
auto source_path_lockable = file::getLock(path);
auto target_path_lock = target_path_lockable->asScopedLock();
auto source_path_lock = source_path_lockable->asScopedLock();
target_path_lock.lock();
source_path_lock.lock();
LOG_I(TAG, "Extracting app from %s to %s", path.c_str(), app_target_path.c_str());
+27 -31
View File
@@ -1,17 +1,19 @@
#include <Tactility/StringUtils.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/hal/gps/GpsDevice.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/gps/GpsService.h>
#include "tactility/drivers/uart_controller.h"
#include <cstring>
#include <lvgl.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <gps/gps.h>
#include <gps/gps_settings.h>
#include <cstring>
#include <lvgl.h>
namespace tt::app::addgps {
constexpr auto* TAG = "AddGps";
@@ -29,6 +31,14 @@ class AddGpsApp final : public App {
std::array<uint32_t, 6> baudRates = { 9600, 19200, 28800, 38400, 57600, 115200 };
const char* baudRatesDropdownValues = "9600\n19200\n28800\n38400\n57600\n115200";
static std::vector<std::string> getModelNames() {
std::vector<std::string> result;
for (int model = GpsModel::GPS_MODEL_UNKNOWN; model <= GpsModel::GPS_MODEL_UC6580; model++) {
result.emplace_back(gps_model_to_string(static_cast<GpsModel>(model)));
}
return result;
}
static void onAddGpsCallback(lv_event_t* event) {
auto* app = (AddGpsApp*)lv_event_get_user_data(event);
app->onAddGps();
@@ -37,38 +47,24 @@ class AddGpsApp final : public App {
void onAddGps() {
auto selected_baud_index = lv_dropdown_get_selected(baudDropdown);
auto new_configuration = hal::gps::GpsConfiguration {
.uartName = { 0x00 },
.baudRate = baudRates[selected_baud_index],
GpsConfiguration new_configuration = {
.uart_name = { 0x00 },
.baud_rate = baudRates[selected_baud_index],
// Warning: This assumes that the enum is a regularly indexed one that starts at 0
.model = (hal::gps::GpsModel)lv_dropdown_get_selected(modelDropdown)
.model = (GpsModel)lv_dropdown_get_selected(modelDropdown)
};
lv_dropdown_get_selected_str(uartDropdown, new_configuration.uartName, sizeof(new_configuration.uartName));
if (new_configuration.uartName[0] == 0x00) {
lv_dropdown_get_selected_str(uartDropdown, new_configuration.uart_name, sizeof(new_configuration.uart_name));
if (new_configuration.uart_name[0] == 0x00) {
alertdialog::start("Error", "You must select a bus/uart.");
return;
}
LOG_I(TAG, "Saving: uart=%s, model=%d, baud=%u", new_configuration.uartName, (int)new_configuration.model, (unsigned)new_configuration.baudRate);
auto service = service::gps::findGpsService();
std::vector<tt::hal::gps::GpsConfiguration> configurations;
if (service != nullptr) {
service->getGpsConfigurations(configurations);
for (auto& stored_configuration: configurations) {
if (strcmp(stored_configuration.uartName, new_configuration.uartName) == 0) {
auto message = std::string("Bus \"{}\" is already in use in another configuration", (const char*)new_configuration.uartName);
app::alertdialog::start("Error", message.c_str());
return;
}
}
if (!service->addGpsConfiguration(new_configuration)) {
app::alertdialog::start("Error", "Failed to add configuration");
} else {
stop();
}
LOG_I(TAG, "Saving: uart=%s, model=%d, baud=%u", new_configuration.uart_name, (int)new_configuration.model, (unsigned)new_configuration.baud_rate);
if (gps_settings_add_configuration(&new_configuration) != ERROR_NONE) {
alertdialog::start("Error", "Failed to add configuration");
} else {
stop();
}
}
@@ -137,7 +133,7 @@ public:
modelDropdown = lv_dropdown_create(model_wrapper);
auto model_names = hal::gps::getModels();
auto model_names = getModelNames();
auto model_options = string::join(model_names, "\n");
lv_dropdown_set_options(modelDropdown, model_options.c_str());
lv_obj_align(modelDropdown, LV_ALIGN_TOP_RIGHT, 0, 0);
+4 -2
View File
@@ -58,7 +58,8 @@ class AppHubApp final : public App {
void onRefreshSuccess() {
LOG_I(TAG, "Request success");
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
showApps();
@@ -66,7 +67,8 @@ class AppHubApp final : public App {
void onRefreshError(const char* error) {
LOG_E(TAG, "Request failed: %s", error);
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
showRefreshFailedError("Cannot reach server");
+2 -1
View File
@@ -21,7 +21,8 @@ static bool parseEntry(const cJSON* object, AppHubEntry& entry) {
}
bool parseJson(const std::string& filePath, std::vector<AppHubEntry>& entries) {
auto lock = file::getLock(filePath)->asScopedLock();
auto lockable = file::getLock(filePath);
auto lock = lockable->asScopedLock();
lock.lock();
auto data = file::readString(filePath);
+3 -32
View File
@@ -9,7 +9,6 @@
#include <Tactility/app/AppContext.h>
#include <Tactility/app/AppPaths.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/usb/Usb.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/service/loader/Loader.h>
@@ -36,10 +35,6 @@ constexpr auto* TAG = "Boot";
extern const AppManifest manifest;
static std::shared_ptr<hal::display::DisplayDevice> getHalDisplay() {
return hal::findFirstDevice<hal::display::DisplayDevice>(hal::Device::Type::Display);
}
class BootApp : public App {
// Snapshot of hal::usb::isUsbBootMode(), taken before the boot thread starts and
@@ -58,31 +53,7 @@ class BootApp : public App {
getCpuAffinityConfiguration().system
);
static void setupHalDisplay() {
const auto hal_display = getHalDisplay();
if (hal_display == nullptr) {
return;
}
settings::display::DisplaySettings settings;
if (settings::display::load(settings)) {
if (hal_display->getGammaCurveCount() > 0) {
hal_display->setGammaCurve(settings.gammaCurve);
LOG_I(TAG, "Gamma curve %d", settings.gammaCurve);
}
} else {
settings = settings::display::getDefault();
}
if (hal_display->supportsBacklightDuty()) {
LOG_I(TAG, "Backlight %d", settings.backlightDuty);
hal_display->setBacklightDuty(settings.backlightDuty);
} else {
LOG_I(TAG, "No backlight");
}
}
static void setupKernelDisplay() {
static void setupDisplay() {
auto* display = device_find_first_by_type(&DISPLAY_TYPE);
// Boards not yet migrated to the kernel display driver register a placeholder device (so
// the devicetree node resolves) with a NULL api - nothing for this function to act on.
@@ -161,8 +132,8 @@ class BootApp : public App {
// TODO: Support for multiple displays
LOG_I(TAG, "Setup display");
setupHalDisplay();
setupKernelDisplay();
setupDisplay();
LOG_I(TAG, "Prepare file systems");
prepareFileSystems();
#ifdef CONFIG_TT_USER_DATA_LOCATION_SD
+6 -3
View File
@@ -84,7 +84,8 @@ void ChatApp::onReceive(const esp_now_recv_info_t* receiveInfo, const uint8_t* d
state.addMessage(msg);
{
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
view.displayMessage(msg);
}
@@ -115,7 +116,8 @@ void ChatApp::sendMessage(const std::string& text) {
state.addMessage(msg);
{
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
view.displayMessage(msg);
}
@@ -172,7 +174,8 @@ void ChatApp::switchChannel(const std::string& chatChannel) {
saveSettings(settings);
{
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
view.refreshMessageList();
}
@@ -3,12 +3,12 @@
#include <Tactility/app/crashdiagnostics/QrHelpers.h>
#include <Tactility/app/crashdiagnostics/QrUrl.h>
#include <Tactility/app/launcher/Launcher.h>
#include <tactility/hal/Device.h>
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/service/loader/Loader.h>
#include <lvgl.h>
#include <qrcode.h>
#include <tactility/drivers/pointer.h>
#include <tactility/log.h>
namespace tt::app::crashdiagnostics {
@@ -36,7 +36,7 @@ public:
lv_obj_align(top_label, LV_ALIGN_TOP_MID, 0, 2);
auto* bottom_label = lv_label_create(parent);
if (hal::hasDevice(hal::Device::Type::Touch)) {
if (device_has_active_by_type(&POINTER_TYPE)) {
lv_label_set_text(bottom_label, "Tap screen to continue");
} else {
lv_label_set_text(bottom_label, "Reboot device to continue");
@@ -1,9 +1,8 @@
#ifdef ESP_PLATFORM
#include <Tactility/Timer.h>
#include <Tactility/Tactility.h>
#include <Tactility/Timer.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/lvgl/Lvgl.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
@@ -14,6 +13,7 @@
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <tactility/lvgl_module.h>
#include <cstring>
#include <lvgl.h>
@@ -31,9 +31,10 @@ class DevelopmentApp final : public App {
std::shared_ptr<service::development::DevelopmentService> service;
Timer timer = Timer(Timer::Type::Periodic, pdMS_TO_TICKS(1000), [this] {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
// TODO: There's a crash when this is called when the app is being destroyed
if (lock.lock(lvgl::defaultLockTime) && lvgl::isStarted()) {
if (lock.lock(lvgl::defaultLockTime) && module_is_started(&lvgl_module)) {
updateViewState();
}
});
@@ -157,7 +158,8 @@ public:
}
void onHide(AppContext& appContext) override {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
// Ensure that the update isn't already happening
lock.lock();
timer.stop();
-310
View File
@@ -1,310 +0,0 @@
#include <Tactility/Tactility.h>
#include <tactility/lvgl_icon_shared.h>
#ifdef ESP_PLATFORM
#include <Tactility/service/displayidle/DisplayIdleService.h>
#endif
#include <Tactility/app/App.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/settings/DisplaySettings.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
namespace tt::app::display {
constexpr auto* TAG = "Display";
static std::shared_ptr<hal::display::DisplayDevice> getHalDisplay() {
return hal::findFirstDevice<hal::display::DisplayDevice>(hal::Device::Type::Display);
}
class HalDisplayApp final : public App {
settings::display::DisplaySettings displaySettings;
bool displaySettingsUpdated = false;
lv_obj_t* timeoutSwitch = nullptr;
lv_obj_t* timeoutDropdown = nullptr;
lv_obj_t* screensaverDropdown = nullptr;
static void onBacklightSliderEvent(lv_event_t* event) {
auto* slider = static_cast<lv_obj_t*>(lv_event_get_target(event));
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
auto hal_display = getHalDisplay();
assert(hal_display != nullptr);
if (hal_display->supportsBacklightDuty()) {
int32_t slider_value = lv_slider_get_value(slider);
app->displaySettings.backlightDuty = static_cast<uint8_t>(slider_value);
app->displaySettingsUpdated = true;
hal_display->setBacklightDuty(app->displaySettings.backlightDuty);
}
}
static void onGammaSliderEvent(lv_event_t* event) {
auto* slider = static_cast<lv_obj_t*>(lv_event_get_target(event));
auto hal_display = hal::findFirstDevice<hal::display::DisplayDevice>(hal::Device::Type::Display);
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
assert(hal_display != nullptr);
if (hal_display->getGammaCurveCount() > 0) {
int32_t slider_value = lv_slider_get_value(slider);
app->displaySettings.gammaCurve = static_cast<uint8_t>(slider_value);
app->displaySettingsUpdated = true;
hal_display->setGammaCurve(app->displaySettings.gammaCurve);
}
}
static void onOrientationSet(lv_event_t* event) {
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
uint32_t selected_index = lv_dropdown_get_selected(dropdown);
LOG_I(TAG, "Selected %u", (unsigned)selected_index);
auto selected_orientation = static_cast<settings::display::Orientation>(selected_index);
if (selected_orientation != app->displaySettings.orientation) {
app->displaySettings.orientation = selected_orientation;
app->displaySettingsUpdated = true;
lv_display_set_rotation(lv_display_get_default(), settings::display::toLvglDisplayRotation(selected_orientation));
}
}
static void onTimeoutSwitch(lv_event_t* event) {
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
auto* sw = static_cast<lv_obj_t*>(lv_event_get_target(event));
bool enabled = lv_obj_has_state(sw, LV_STATE_CHECKED);
app->displaySettings.backlightTimeoutEnabled = enabled;
app->displaySettingsUpdated = true;
if (app->timeoutDropdown) {
if (enabled) {
lv_obj_clear_state(app->timeoutDropdown, LV_STATE_DISABLED);
if (app->screensaverDropdown) {
lv_obj_clear_state(app->screensaverDropdown, LV_STATE_DISABLED);
}
} else {
lv_obj_add_state(app->timeoutDropdown, LV_STATE_DISABLED);
if (app->screensaverDropdown) {
lv_obj_add_state(app->screensaverDropdown, LV_STATE_DISABLED);
}
}
}
}
static void onTimeoutChanged(lv_event_t* event) {
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
uint32_t idx = lv_dropdown_get_selected(dropdown);
// Map dropdown index to ms: 0=15s,1=30s,2=1m,3=2m,4=5m,5=Never
static const uint32_t values_ms[] = {15000, 30000, 60000, 120000, 300000, 0};
if (idx < (sizeof(values_ms)/sizeof(values_ms[0]))) {
app->displaySettings.backlightTimeoutMs = values_ms[idx];
app->displaySettingsUpdated = true;
}
}
static void onScreensaverChanged(lv_event_t* event) {
auto* app = static_cast<HalDisplayApp*>(lv_event_get_user_data(event));
auto* dropdown = static_cast<lv_obj_t*>(lv_event_get_target(event));
uint32_t idx = lv_dropdown_get_selected(dropdown);
// Validate index bounds before casting to enum
if (idx >= static_cast<uint32_t>(settings::display::ScreensaverType::Count)) {
return;
}
auto selected_type = static_cast<settings::display::ScreensaverType>(idx);
if (selected_type != app->displaySettings.screensaverType) {
app->displaySettings.screensaverType = selected_type;
app->displaySettingsUpdated = true;
}
}
public:
void onShow(AppContext& app, lv_obj_t* parent) override {
displaySettings = settings::display::loadOrGetDefault();
auto ui_density = lvgl_get_ui_density();
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT);
auto hal_display = getHalDisplay();
assert(hal_display != nullptr);
lvgl::toolbar_create(parent, app);
auto* main_wrapper = lv_obj_create(parent);
lv_obj_set_flex_flow(main_wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_width(main_wrapper, LV_PCT(100));
lv_obj_set_flex_grow(main_wrapper, 1);
// Backlight slider
if (hal_display->supportsBacklightDuty()) {
auto* brightness_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(brightness_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_hor(brightness_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(brightness_wrapper, 0, LV_STATE_DEFAULT);
if (ui_density != LVGL_UI_DENSITY_COMPACT) {
lv_obj_set_style_pad_ver(brightness_wrapper, 4, LV_STATE_DEFAULT);
}
auto* brightness_label = lv_label_create(brightness_wrapper);
lv_label_set_text(brightness_label, "Brightness");
lv_obj_align(brightness_label, LV_ALIGN_LEFT_MID, 0, 0);
auto* brightness_slider = lv_slider_create(brightness_wrapper);
lv_obj_set_width(brightness_slider, LV_PCT(50));
lv_obj_align(brightness_slider, LV_ALIGN_RIGHT_MID, 0, 0);
lv_slider_set_range(brightness_slider, 0, 255);
lv_obj_add_event_cb(brightness_slider, onBacklightSliderEvent, LV_EVENT_VALUE_CHANGED, this);
lv_slider_set_value(brightness_slider, displaySettings.backlightDuty, LV_ANIM_OFF);
}
// Gamma slider
if (hal_display->getGammaCurveCount() > 0) {
auto* gamma_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(gamma_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_hor(gamma_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(gamma_wrapper, 0, LV_STATE_DEFAULT);
if (ui_density != LVGL_UI_DENSITY_COMPACT) {
lv_obj_set_style_pad_ver(gamma_wrapper, 4, LV_STATE_DEFAULT);
}
auto* gamma_label = lv_label_create(gamma_wrapper);
lv_label_set_text(gamma_label, "Gamma");
lv_obj_align(gamma_label, LV_ALIGN_LEFT_MID, 0, 0);
lv_obj_set_y(gamma_label, 0);
auto* gamma_slider = lv_slider_create(gamma_wrapper);
lv_obj_set_width(gamma_slider, LV_PCT(50));
lv_obj_align(gamma_slider, LV_ALIGN_RIGHT_MID, 0, 0);
lv_slider_set_range(gamma_slider, 0, hal_display->getGammaCurveCount());
lv_obj_add_event_cb(gamma_slider, onGammaSliderEvent, LV_EVENT_VALUE_CHANGED, this);
uint8_t curve_index = displaySettings.gammaCurve;
lv_slider_set_value(gamma_slider, curve_index, LV_ANIM_OFF);
}
// Orientation
auto* orientation_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(orientation_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(orientation_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(orientation_wrapper, 0, LV_STATE_DEFAULT);
auto* orientation_label = lv_label_create(orientation_wrapper);
lv_label_set_text(orientation_label, "Orientation");
lv_obj_align(orientation_label, LV_ALIGN_LEFT_MID, 0, 0);
auto* orientation_dropdown = lv_dropdown_create(orientation_wrapper);
// Note: order correlates with settings::display::Orientation item order
lv_dropdown_set_options(orientation_dropdown, "Landscape\nPortrait Right\nLandscape Flipped\nPortrait Left");
lv_obj_align(orientation_dropdown, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_add_event_cb(orientation_dropdown, onOrientationSet, LV_EVENT_VALUE_CHANGED, this);
// Set the dropdown to match current orientation enum
lv_dropdown_set_selected(orientation_dropdown, static_cast<uint16_t>(displaySettings.orientation));
// Screen timeout
if (hal_display->supportsBacklightDuty()) {
auto* timeout_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(timeout_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(timeout_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(timeout_wrapper, 0, LV_STATE_DEFAULT);
auto* timeout_label = lv_label_create(timeout_wrapper);
lv_label_set_text(timeout_label, "Auto screen off");
lv_obj_align(timeout_label, LV_ALIGN_LEFT_MID, 0, 0);
timeoutSwitch = lv_switch_create(timeout_wrapper);
if (displaySettings.backlightTimeoutEnabled) {
lv_obj_add_state(timeoutSwitch, LV_STATE_CHECKED);
}
lv_obj_align(timeoutSwitch, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_add_event_cb(timeoutSwitch, onTimeoutSwitch, LV_EVENT_VALUE_CHANGED, this);
auto* timeout_select_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(timeout_select_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(timeout_select_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(timeout_select_wrapper, 0, LV_STATE_DEFAULT);
auto* timeout_value_label = lv_label_create(timeout_select_wrapper);
lv_label_set_text(timeout_value_label, "Timeout");
lv_obj_align(timeout_value_label, LV_ALIGN_LEFT_MID, 0, 0);
timeoutDropdown = lv_dropdown_create(timeout_select_wrapper);
lv_dropdown_set_options(timeoutDropdown, "15 seconds\n30 seconds\n1 minute\n2 minutes\n5 minutes\nNever");
lv_obj_align(timeoutDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_add_event_cb(timeoutDropdown, onTimeoutChanged, LV_EVENT_VALUE_CHANGED, this);
// Initialize dropdown selection from settings
uint32_t ms = displaySettings.backlightTimeoutMs;
uint32_t idx = 2; // default 1 minute
if (ms == 15000) idx = 0;
else if (ms == 30000)
idx = 1;
else if (ms == 60000)
idx = 2;
else if (ms == 120000)
idx = 3;
else if (ms == 300000)
idx = 4;
else if (ms == 0)
idx = 5;
lv_dropdown_set_selected(timeoutDropdown, idx);
if (!displaySettings.backlightTimeoutEnabled) {
lv_obj_add_state(timeoutDropdown, LV_STATE_DISABLED);
}
// Screensaver type
auto* screensaver_wrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(screensaver_wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_pad_all(screensaver_wrapper, 0, LV_STATE_DEFAULT);
lv_obj_set_style_border_width(screensaver_wrapper, 0, LV_STATE_DEFAULT);
auto* screensaver_label = lv_label_create(screensaver_wrapper);
lv_label_set_text(screensaver_label, "Screensaver");
lv_obj_align(screensaver_label, LV_ALIGN_LEFT_MID, 0, 0);
screensaverDropdown = lv_dropdown_create(screensaver_wrapper);
// Note: order correlates with settings::display::ScreensaverType enum order
lv_dropdown_set_options(screensaverDropdown, "None\nBouncing Balls\nMystify\nMatrix Rain\nStackChan");
lv_obj_align(screensaverDropdown, LV_ALIGN_RIGHT_MID, 0, 0);
lv_obj_add_event_cb(screensaverDropdown, onScreensaverChanged, LV_EVENT_VALUE_CHANGED, this);
lv_dropdown_set_selected(screensaverDropdown, static_cast<uint16_t>(displaySettings.screensaverType));
if (!displaySettings.backlightTimeoutEnabled) {
lv_obj_add_state(screensaverDropdown, LV_STATE_DISABLED);
}
}
}
void onHide(AppContext& app) override {
if (displaySettingsUpdated) {
// Dispatch it, so file IO doesn't block the UI
const settings::display::DisplaySettings settings_to_save = displaySettings;
getMainDispatcher().dispatch([settings_to_save] {
settings::display::save(settings_to_save);
#ifdef ESP_PLATFORM
// Notify DisplayIdle service to reload settings
auto displayIdle = service::displayidle::findService();
if (displayIdle) {
displayIdle->reloadSettings();
}
#endif
});
}
}
};
extern const AppManifest manifest = {
.appId = "Display",
.appName = "Display",
.appIcon = LVGL_ICON_SHARED_DISPLAY_SETTINGS,
.appCategory = Category::Settings,
.createApp = create<HalDisplayApp>
};
} // namespace
+6 -3
View File
@@ -450,7 +450,8 @@ void View::onEjectPressed() {
void View::update(size_t start_index) {
const bool is_root = (state->getCurrentPath() == "/");
auto scoped_lockable = lvgl::getSyncLock()->asScopedLock();
auto sync_lockable = lvgl::getSyncLock();
auto scoped_lockable = sync_lockable->asScopedLock();
if (!scoped_lockable.lock(lvgl::defaultLockTime)) {
LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl");
return;
@@ -550,14 +551,16 @@ void View::init(const AppContext& appContext, lv_obj_t* parent) {
}
void View::onDirEntryListScrollBegin() {
auto scoped_lockable = lvgl::getSyncLock()->asScopedLock();
auto sync_lockable = lvgl::getSyncLock();
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN);
}
}
void View::onNavigate() {
auto scoped_lockable = lvgl::getSyncLock()->asScopedLock();
auto sync_lockable = lvgl::getSyncLock();
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_add_flag(action_list, LV_OBJ_FLAG_HIDDEN);
}
+2 -1
View File
@@ -155,7 +155,8 @@ void View::onNavigateUpPressed() {
}
void View::update() {
auto scoped_lockable = lvgl::getSyncLock()->asScopedLock();
auto sync_lockable = lvgl::getSyncLock();
auto scoped_lockable = sync_lockable->asScopedLock();
if (scoped_lockable.lock(lvgl::defaultLockTime)) {
lv_obj_clean(dir_entry_list);
+223 -376
View File
@@ -1,20 +1,28 @@
#include "tactility/lvgl_module.h"
#include <Tactility/Tactility.h>
#include <Tactility/Timer.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/service/gps/GpsState.h>
#include <Tactility/service/loader/Loader.h>
#include <tactility/log.h>
#include <tactility/device.h>
#include <tactility/lvgl_icon_shared.h>
#include <atomic>
#include <cstring>
#include <format>
#include <lvgl.h>
#include <string>
#include <vector>
#include <gps/gps.h>
#include <gps/gps_settings.h>
namespace tt::app::addgps {
extern AppManifest manifest;
@@ -26,40 +34,21 @@ extern const AppManifest manifest;
class GpsSettingsApp final : public App {
static constexpr auto* TAG = "GpsSettings";
struct DeviceRow {
Device* device;
lv_obj_t* button;
lv_obj_t* buttonLabel;
bool hasConfiguration = false;
size_t configurationIndex = 0;
};
std::unique_ptr<Timer> timer;
std::shared_ptr<GpsSettingsApp*> appReference = std::make_shared<GpsSettingsApp*>(this);
lv_obj_t* statusWrapper = nullptr;
lv_obj_t* statusLabelWidget = nullptr;
lv_obj_t* statusLatitudeValue = nullptr;
lv_obj_t* statusLongitudeValue = nullptr;
lv_obj_t* statusAltitudeValue = nullptr;
lv_obj_t* statusSpeedValue = nullptr;
lv_obj_t* statusHeadingValue = nullptr;
lv_obj_t* statusSatellitesValue = nullptr;
lv_obj_t* switchWidget = nullptr;
lv_obj_t* spinnerWidget = nullptr;
lv_obj_t* infoContainerWidget = nullptr;
lv_obj_t* gpsConfigWrapper = nullptr;
lv_obj_t* addGpsWrapper = nullptr;
bool hasSetInfo = false;
PubSub<service::gps::State>::SubscriptionHandle serviceStateSubscription = nullptr;
std::shared_ptr<service::gps::GpsService> service;
void onServiceStateChanged() {
auto lock = lvgl::getSyncLock()->asScopedLock();
if (lock.lock(100 / portTICK_PERIOD_MS)) {
if (!updateTimerState()) {
updateViews();
}
}
}
static void onGpsToggledCallback(lv_event_t* event) {
auto* app = (GpsSettingsApp*)lv_event_get_user_data(event);
app->onGpsToggled(event);
}
lv_obj_t* deviceListWrapper = nullptr;
std::vector<DeviceRow> deviceRows;
std::atomic<bool> isShown = false;
bool hasPendingDelete = false;
Device* pendingDeleteDevice = nullptr;
size_t pendingDeleteIndex = 0;
static void onAddGpsCallback(lv_event_t* event) {
auto* app = (GpsSettingsApp*)lv_event_get_user_data(event);
@@ -70,385 +59,243 @@ class GpsSettingsApp final : public App {
app::start(addgps::manifest.appId);
}
void startReceivingUpdates() {
timer->start();
updateViews();
}
void stopReceivingUpdates() {
timer->stop();
updateViews();
}
void createInfoView(hal::gps::GpsModel model) {
auto* label = lv_label_create(infoContainerWidget);
if (model == hal::gps::GpsModel::Unknown) {
lv_label_set_text(label, "Model: auto-detect");
} else {
lv_label_set_text_fmt(label, "Model: %s", toString(model));
}
}
static void onDeleteConfiguration(lv_event_t* event) {
auto* app = (GpsSettingsApp*)lv_event_get_user_data(event);
static void onDeviceButtonCallback(lv_event_t* event) {
auto* button = lv_event_get_target_obj(event);
auto index_as_voidptr = lv_obj_get_user_data(button); // config index
int index;
// TODO: Find a better way to cast void* to int, or find a different way to pass the index
memcpy(&index, &index_as_voidptr, sizeof(int));
auto* device = static_cast<Device*>(lv_obj_get_user_data(button));
std::vector<tt::hal::gps::GpsConfiguration> configurations;
auto gps_service = service::gps::findGpsService();
if (gps_service && gps_service->getGpsConfigurations(configurations)) {
LOG_I(TAG, "Found service and configs %d %d", index, (int)configurations.size());
if (index < configurations.size()) {
if (gps_service->removeGpsConfiguration(configurations[index])) {
app->updateViews();
} else {
alertdialog::start("Error", "Failed to remove configuration");
}
}
}
}
void createGpsView(const hal::gps::GpsConfiguration& configuration, int index) {
auto* wrapper = lv_obj_create(gpsConfigWrapper);
lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_ROW);
lv_obj_set_style_margin_hor(wrapper, 0, 0);
lv_obj_set_style_margin_bottom(wrapper, 8, 0);
// Left wrapper
auto* left_wrapper = lv_obj_create(wrapper);
lv_obj_set_style_border_width(left_wrapper, 0, 0);
lv_obj_set_style_pad_all(left_wrapper, 0, 0);
lv_obj_set_size(left_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_grow(left_wrapper, 1);
lv_obj_set_flex_flow(left_wrapper, LV_FLEX_FLOW_COLUMN);
auto* uart_label = lv_label_create(left_wrapper);
lv_label_set_text_fmt(uart_label, "UART: %s", configuration.uartName);
auto* baud_label = lv_label_create(left_wrapper);
lv_label_set_text_fmt(baud_label, "Baud: %lu", configuration.baudRate);
auto* model_label = lv_label_create(left_wrapper);
if (configuration.model == hal::gps::GpsModel::Unknown) {
lv_label_set_text(model_label, "Model: auto-detect");
} else {
lv_label_set_text_fmt(model_label, "Model: %s", toString(configuration.model));
}
// Right wrapper
auto* right_wrapper = lv_obj_create(wrapper);
lv_obj_set_style_border_width(right_wrapper, 0, 0);
lv_obj_set_style_pad_all(right_wrapper, 0, 0);
lv_obj_set_size(right_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(right_wrapper, LV_FLEX_FLOW_COLUMN);
auto* delete_button = lv_button_create(right_wrapper);
lv_obj_add_event_cb(delete_button, onDeleteConfiguration, LV_EVENT_SHORT_CLICKED, this);
lv_obj_set_user_data(delete_button, reinterpret_cast<void*>(index));
auto* delete_label = lv_label_create(delete_button);
lv_label_set_text_fmt(delete_label, LV_SYMBOL_TRASH);
}
void updateViews() {
auto lock = lvgl::getSyncLock()->asScopedLock();
if (lock.lock(100 / portTICK_PERIOD_MS)) {
auto state = service->getState();
// Update toolbar
switch (state) {
case service::gps::State::OnPending:
LOG_D(TAG, "OnPending");
lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_state(switchWidget, LV_STATE_CHECKED);
lv_obj_add_state(switchWidget, LV_STATE_DISABLED);
lv_obj_remove_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::On:
LOG_D(TAG, "On");
lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_state(switchWidget, LV_STATE_CHECKED);
lv_obj_remove_state(switchWidget, LV_STATE_DISABLED);
lv_obj_remove_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::OffPending:
LOG_D(TAG, "OffPending");
lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_state(switchWidget, LV_STATE_CHECKED);
lv_obj_add_state(switchWidget, LV_STATE_DISABLED);
lv_obj_add_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::Off:
LOG_D(TAG, "Off");
lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_state(switchWidget, LV_STATE_CHECKED);
lv_obj_remove_state(switchWidget, LV_STATE_DISABLED);
lv_obj_add_flag(statusWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN);
lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
}
// Update status label and device info
if (state == service::gps::State::On) {
if (!hasSetInfo) {
auto devices = hal::findDevices<hal::gps::GpsDevice>(hal::Device::Type::Gps);
for (auto& device : devices) {
createInfoView(device->getModel());
hasSetInfo = true;
}
}
minmea_sentence_rmc rmc;
char buffer[64];
if (service->getCoordinates(rmc)) {
lv_label_set_text(statusLabelWidget, "Lock acquired");
lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0x00ff00), 0);
minmea_float latitude = { rmc.latitude.value, rmc.latitude.scale };
minmea_float longitude = { rmc.longitude.value, rmc.longitude.scale };
double latCoord = minmea_tocoord(&latitude);
double lonCoord = minmea_tocoord(&longitude);
if (isnan(latCoord) || isnan(lonCoord)) {
lv_label_set_text(statusLatitudeValue, "--");
lv_label_set_text(statusLongitudeValue, "--");
} else {
const char* latDir = (latCoord >= 0) ? "N" : "S";
const char* lonDir = (lonCoord >= 0) ? "E" : "W";
snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(latCoord), latDir);
lv_label_set_text(statusLatitudeValue, buffer);
snprintf(buffer, sizeof(buffer), "%.6f %s", std::abs(lonCoord), lonDir);
lv_label_set_text(statusLongitudeValue, buffer);
}
float speedKnots = minmea_tofloat(&rmc.speed);
if (!isnan(speedKnots)) {
float speedKmh = speedKnots * 1.852f;
snprintf(buffer, sizeof(buffer), "%.1f km/h", speedKmh);
lv_label_set_text(statusSpeedValue, buffer);
} else {
lv_label_set_text(statusSpeedValue, "--");
}
float heading = minmea_tofloat(&rmc.course);
if (!isnan(heading)) {
// Normalize heading to [0, 360) range
heading = fmodf(heading, 360.0f);
if (heading < 0) heading += 360.0f;
const char* dirs[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"};
// Calculate cardinal direction index (0-7)
int idx = (int)((heading + 22.5f) / 45.0f) % 8;
snprintf(buffer, sizeof(buffer), "%.0f° %s", heading, dirs[idx]);
lv_label_set_text(statusHeadingValue, buffer);
} else {
lv_label_set_text(statusHeadingValue, "--");
}
} else {
lv_label_set_text(statusLabelWidget, "Acquiring lock...");
lv_obj_set_style_text_color(statusLabelWidget, lv_color_hex(0xffaa00), 0);
lv_label_set_text(statusLatitudeValue, "--");
lv_label_set_text(statusLongitudeValue, "--");
lv_label_set_text(statusSpeedValue, "--");
lv_label_set_text(statusHeadingValue, "--");
}
minmea_sentence_gga gga;
if (service->getGga(gga)) {
float altitude = minmea_tofloat(&gga.altitude);
if (!isnan(altitude)) {
snprintf(buffer, sizeof(buffer), "%.1f m", altitude);
lv_label_set_text(statusAltitudeValue, buffer);
} else {
lv_label_set_text(statusAltitudeValue, "--");
}
snprintf(buffer, sizeof(buffer), "%d", gga.satellites_tracked);
lv_label_set_text(statusSatellitesValue, buffer);
} else {
lv_label_set_text(statusAltitudeValue, "--");
lv_label_set_text(statusSatellitesValue, "--");
}
lv_obj_remove_flag(statusLabelWidget, LV_OBJ_FLAG_HIDDEN);
bool running = device_is_ready(device);
// device_start()/device_stop() are potentially blocking calls, so use a dispatcher to not block the UI
getMainDispatcher().dispatch([device, running] {
if (running) {
device_stop(device);
} else {
if (hasSetInfo) {
lv_obj_clean(infoContainerWidget);
hasSetInfo = false;
}
lv_obj_add_flag(statusLabelWidget, LV_OBJ_FLAG_HIDDEN);
device_start(device);
}
if (!lv_obj_has_flag(gpsConfigWrapper, LV_OBJ_FLAG_HIDDEN)) {
lv_obj_clean(gpsConfigWrapper);
std::vector<tt::hal::gps::GpsConfiguration> configurations;
auto gps_service = tt::service::gps::findGpsService();
if (gps_service && gps_service->getGpsConfigurations(configurations)) {
int index = 0;
for (auto& configuration : configurations) {
createGpsView(configuration, index++);
}
}
} else {
lv_obj_clean(gpsConfigWrapper);
}
}
});
}
/** @return true if the views were updated */
bool updateTimerState() {
bool is_on = service->getState() == service::gps::State::On;
if (is_on && !timer->isRunning()) {
startReceivingUpdates();
return true;
} else if (!is_on && timer->isRunning()) {
stopReceivingUpdates();
return true;
} else {
// Finds the persisted configuration backing `device` (matched by its parent UART's name)
// and returns its index into gps_settings_for_each_configuration()'s ordering - the handle
// gps_settings_remove_configuration_at() needs to delete exactly this entry, even if another
// entry happens to have identical field values.
// Devicetree-declared GPS_TYPE devices have no such configuration and never match.
static bool findConfigurationIndexForDevice(Device* device, size_t& outIndex) {
auto* parent = device_get_parent(device);
if (parent == nullptr) {
return false;
}
struct Context {
const char* uartName;
size_t* outIndex;
bool found;
} context = { parent->name, &outIndex, false };
gps_settings_for_each_configuration(&context, [](const GpsConfiguration* configuration, size_t index, void* untyped_context) {
auto* ctx = static_cast<Context*>(untyped_context);
if (!ctx->found && strcmp(configuration->uart_name, ctx->uartName) == 0) {
*ctx->outIndex = index;
ctx->found = true;
}
});
return context.found;
}
void onGpsToggled(lv_event_t* event) {
bool wants_on = lv_obj_has_state(switchWidget, LV_STATE_CHECKED);
auto state = service->getState();
bool is_on = (state == service::gps::State::On) || (state == service::gps::State::OnPending);
static void onDeleteButtonCallback(lv_event_t* event) {
auto* app = static_cast<GpsSettingsApp*>(lv_event_get_user_data(event));
auto* button = lv_event_get_target_obj(event);
auto* device = static_cast<Device*>(lv_obj_get_user_data(button));
app->onDeleteDevice(device);
}
if (wants_on != is_on) {
// start/stop are potentially blocking calls, so we use a dispatcher to not block the UI
if (wants_on) {
getMainDispatcher().dispatch([this] {
service->startReceiving();
});
} else {
getMainDispatcher().dispatch([this] {
service->stopReceiving();
});
void onDeleteDevice(Device* device) {
for (auto& row : deviceRows) {
if (row.device == device && row.hasConfiguration) {
pendingDeleteDevice = device;
pendingDeleteIndex = row.configurationIndex;
hasPendingDelete = true;
alertdialog::start("Confirmation", std::string("Do you want to delete ") + device->name + "?", std::vector<std::string> { "Yes", "No" });
return;
}
}
}
lv_obj_t* createInfoRow(lv_obj_t* parent, const char* labelText, lv_color_t color) {
lv_obj_t* row = lv_obj_create(parent);
lv_obj_set_size(row, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(row, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(row, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START);
void createDeviceRow(Device* device) {
auto* wrapper = lv_obj_create(deviceListWrapper);
lv_obj_set_size(wrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(wrapper, LV_FLEX_FLOW_ROW);
lv_obj_set_flex_align(wrapper, LV_FLEX_ALIGN_SPACE_BETWEEN, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_border_width(wrapper, 0, 0);
lv_obj_set_style_pad_all(wrapper, 0, 0);
lv_obj_set_style_pad_all(row, 0, 0);
lv_obj_set_style_pad_right(row, 10, 0);
lv_obj_set_style_border_width(row, 0, 0);
lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0);
auto* name_label = lv_label_create(wrapper);
char model_name[64];
if (gps_get_model_name(device, model_name, sizeof(model_name)) == ERROR_NONE) {
lv_label_set_text(name_label, model_name);
} else {
lv_label_set_text(name_label, device->name);
}
lv_obj_t* label = lv_label_create(row);
lv_label_set_text(label, labelText);
lv_obj_set_style_text_color(label, lv_palette_lighten(LV_PALETTE_GREY, 5), 0);
auto* actions_wrapper = lv_obj_create(wrapper);
lv_obj_set_size(actions_wrapper, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(actions_wrapper, LV_FLEX_FLOW_ROW);
lv_obj_set_style_border_width(actions_wrapper, 0, 0);
lv_obj_set_style_pad_all(actions_wrapper, 0, 0);
lv_obj_set_style_pad_column(actions_wrapper, 4, 0);
lv_obj_t* value = lv_label_create(row);
lv_label_set_text(value, "--");
lv_obj_set_style_text_color(value, color, 0);
auto* button = lv_button_create(actions_wrapper);
lv_obj_add_event_cb(button, onDeviceButtonCallback, LV_EVENT_SHORT_CLICKED, this);
lv_obj_set_user_data(button, device);
auto* button_label = lv_label_create(button);
lv_label_set_text(button_label, "Start");
return value;
DeviceRow row { .device = device, .button = button, .buttonLabel = button_label };
// Only devices backed by a persisted configuration (not devicetree-declared ones) can be deleted.
size_t configurationIndex;
if ((device->flags & DEVICE_FLAG_DYNAMIC) && findConfigurationIndexForDevice(device, configurationIndex)) {
auto* delete_button = lv_button_create(actions_wrapper);
lv_obj_add_event_cb(delete_button, onDeleteButtonCallback, LV_EVENT_SHORT_CLICKED, this);
lv_obj_set_user_data(delete_button, device);
auto* delete_label = lv_label_create(delete_button);
lv_label_set_text(delete_label, LVGL_ICON_SHARED_DELETE);
row.hasConfiguration = true;
row.configurationIndex = configurationIndex;
}
deviceRows.push_back(row);
}
// Rebuilds the device list. Only needs to run when the set of devices could've changed
// (on show, and after returning from AddGpsApp) - button state itself is refreshed by the timer.
void rebuildDeviceList() {
lv_obj_clean(deviceListWrapper);
deviceRows.clear();
device_for_each_of_type(&GPS_TYPE, this, [](Device* device, void* context) {
static_cast<GpsSettingsApp*>(context)->createDeviceRow(device);
return true;
});
}
void updateDeviceStates() {
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
if (lock.lock(100 / portTICK_PERIOD_MS)) {
for (auto& row : deviceRows) {
const char* text = "Start";
bool enabled = true;
if (device_is_ready(row.device)) {
switch (gps_get_state(row.device)) {
case GPS_STATE_PENDING_ON:
text = "Starting...";
enabled = false;
break;
case GPS_STATE_PENDING_OFF:
text = "Stopping...";
enabled = false;
break;
default:
text = "Stop";
enabled = true;
break;
}
}
lv_label_set_text(row.buttonLabel, text);
if (enabled) {
lv_obj_remove_state(row.button, LV_STATE_DISABLED);
} else {
lv_obj_add_state(row.button, LV_STATE_DISABLED);
}
}
}
}
public:
GpsSettingsApp() {
// Runs while the screen is shown - there's no push notification for GPS device state
// changes, so this is the only way this screen finds out about them.
timer = std::make_unique<Timer>(Timer::Type::Periodic, kernel::secondsToTicks(1), [this] {
updateViews();
updateDeviceStates();
});
service = service::gps::findGpsService();
}
void onShow(AppContext& app, lv_obj_t* parent) override {
lv_obj_set_flex_flow(parent, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_pad_row(parent, 0, LV_STATE_DEFAULT);
uint8_t margin = (lvgl_get_ui_density() == LVGL_UI_DENSITY_COMPACT) ? 2 : 8;
auto* toolbar = lvgl::toolbar_create(parent, app);
lvgl::toolbar_add_text_button_action(toolbar, LV_SYMBOL_PLUS, onAddGpsCallback, this);
lv_obj_set_style_margin_bottom(toolbar, margin, LV_STATE_DEFAULT);
spinnerWidget = lvgl::toolbar_add_spinner_action(toolbar);
lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN);
deviceListWrapper = lv_obj_create(parent);
lv_obj_set_size(deviceListWrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(deviceListWrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_grow(deviceListWrapper, 1);
lv_obj_set_style_border_width(deviceListWrapper, 0, 0);
lv_obj_set_style_pad_hor(deviceListWrapper, margin, 0);
lv_obj_set_style_pad_top(deviceListWrapper, 0, 0);
lv_obj_set_style_pad_bottom(deviceListWrapper, margin, 0);
lv_obj_set_style_pad_row(deviceListWrapper, margin, 0);
switchWidget = lvgl::toolbar_add_switch_action(toolbar);
lv_obj_add_event_cb(switchWidget, onGpsToggledCallback, LV_EVENT_VALUE_CHANGED, this);
rebuildDeviceList();
auto* main_wrapper = lv_obj_create(parent);
lv_obj_set_flex_flow(main_wrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_width(main_wrapper, LV_PCT(100));
lv_obj_set_flex_grow(main_wrapper, 1);
lv_obj_set_style_border_width(main_wrapper, 0, 0);
lv_obj_set_style_pad_all(main_wrapper, 0, 0);
timer->start();
updateDeviceStates();
statusWrapper = lv_obj_create(main_wrapper);
lv_obj_set_width(statusWrapper, LV_PCT(100));
lv_obj_set_height(statusWrapper, LV_SIZE_CONTENT);
lv_obj_set_flex_flow(statusWrapper, LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(statusWrapper, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
lv_obj_set_style_pad_all(statusWrapper, 0, 0);
lv_obj_set_style_pad_row(statusWrapper, 8, 0);
lv_obj_set_style_border_width(statusWrapper, 0, 0);
statusLabelWidget = lv_label_create(statusWrapper);
infoContainerWidget = lv_obj_create(statusWrapper);
lv_obj_set_size(infoContainerWidget, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_flex_flow(infoContainerWidget, LV_FLEX_FLOW_COLUMN);
lv_obj_set_style_border_width(infoContainerWidget, 0, 0);
lv_obj_set_style_pad_row(infoContainerWidget, 5, 0);
lv_obj_set_style_pad_hor(infoContainerWidget, 10, 0);
hasSetInfo = false;
statusLatitudeValue = createInfoRow(infoContainerWidget, "Latitude", lv_color_hex(0x00ff00));
statusLongitudeValue = createInfoRow(infoContainerWidget, "Longitude", lv_color_hex(0x00ff00));
statusAltitudeValue = createInfoRow(infoContainerWidget, "Altitude", lv_color_hex(0x00ffff));
statusSpeedValue = createInfoRow(infoContainerWidget, "Speed", lv_color_hex(0xffff00));
statusHeadingValue = createInfoRow(infoContainerWidget, "Heading", lv_color_hex(0xff88ff));
statusSatellitesValue = createInfoRow(infoContainerWidget, "Satellites", lv_color_hex(0xffffff));
serviceStateSubscription = service->getStatePubsub()->subscribe([this](auto) {
onServiceStateChanged();
});
gpsConfigWrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(gpsConfigWrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_border_width(gpsConfigWrapper, 0, 0);
lv_obj_set_style_margin_all(gpsConfigWrapper, 0, 0);
lv_obj_set_style_pad_bottom(gpsConfigWrapper, 0, 0);
addGpsWrapper = lv_obj_create(main_wrapper);
lv_obj_set_size(addGpsWrapper, LV_PCT(100), LV_SIZE_CONTENT);
lv_obj_set_style_border_width(addGpsWrapper, 0, 0);
lv_obj_set_style_pad_all(addGpsWrapper, 0, 0);
lv_obj_set_style_margin_top(addGpsWrapper, 0, 0);
lv_obj_set_style_margin_bottom(addGpsWrapper, 8, 0);
auto* add_gps_button = lv_button_create(addGpsWrapper);
auto* add_gps_label = lv_label_create(add_gps_button);
lv_label_set_text(add_gps_label, "Add GPS");
lv_obj_add_event_cb(add_gps_button, onAddGpsCallback, LV_EVENT_SHORT_CLICKED, this);
lv_obj_align(add_gps_button, LV_ALIGN_TOP_MID, 0, 0);
updateTimerState();
updateViews();
// Only after deviceListWrapper is fully built: onResult() (Loader thread) checks
// this before touching it, since it can run before or after this onShow() call.
isShown = true;
}
void onHide(AppContext& app) override {
service->getStatePubsub()->unsubscribe(serviceStateSubscription);
serviceStateSubscription = nullptr;
isShown = false;
timer->stop();
}
void onResult(AppContext&, LaunchId, Result result, std::unique_ptr<Bundle> bundle) override {
if (!hasPendingDelete) {
return;
}
hasPendingDelete = false;
if (result != Result::Ok || bundle == nullptr || alertdialog::getResultIndex(*bundle) != 0) { // 0 = Yes
return;
}
// This runs on the Loader thread, concurrently with the periodic timer callback
// (updateDeviceStates(), timer daemon thread) and possibly with onShow() (GUI
// thread). Take the same lock updateDeviceStates() uses and hold it across the
// free below, so the timer can never observe pendingDeleteDevice as a dangling
// pointer in deviceRows.
lvgl_lock();
// Drop the stale row unconditionally (cheap vector op, no LVGL calls) - this is
// what keeps the timer safe regardless of whether onShow() has run yet this cycle.
std::erase_if(deviceRows, [this](const DeviceRow& row) {
return row.device == pendingDeleteDevice;
});
lvgl_unlock();
// gps_settings_remove_configuration_at() frees the underlying Device synchronously -
// do this only after the dangling pointer is already out of deviceRows.
gps_settings_remove_configuration_at(pendingDeleteIndex);
pendingDeleteDevice = nullptr;
// Only safe to touch deviceListWrapper if onShow() already built it for this show
// cycle - it may not have run yet, in which case it'll rebuild fresh (post-deletion,
// deviceRows already correct) when it does.
lvgl_lock();
if (isShown) {
rebuildDeviceList();
}
lvgl_unlock();
}
};
+2 -1
View File
@@ -87,7 +87,8 @@ class NotesApp final : public App {
file::getLock(path)->withLock([this, path] {
auto data = file::readString(path);
if (data != nullptr) {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
lv_textarea_set_text(uiNoteText, reinterpret_cast<const char*>(data.get()));
lv_label_set_text(uiCurrentFileName, path.c_str());
@@ -4,13 +4,11 @@
#include <Tactility/app/AppContext.h>
#include <Tactility/app/AppRegistration.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/service/loader/Loader.h>
#include <lvgl.h>
#include <tactility/device.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/hal/Device.h>
#include <tactility/lvgl_fonts.h>
#include <tactility/lvgl_icon_shared.h>
@@ -87,7 +87,8 @@ ScreenshotApp::~ScreenshotApp() {
}
void ScreenshotApp::onTimerTick() {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
if (lock.lock(lvgl::defaultLockTime)) {
updateScreenshotMode();
}
@@ -247,7 +247,8 @@ class SystemInfoApp final : public App {
Timer memoryTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(10000), [] {
auto app = optApp();
if (app) {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
app->updateMemory();
}
@@ -256,7 +257,8 @@ class SystemInfoApp final : public App {
Timer tasksTimer = Timer(Timer::Type::Periodic, kernel::millisToTicks(15000), [] {
auto app = optApp();
if (app) {
auto lock = lvgl::getSyncLock()->asScopedLock();
auto lockable = lvgl::getSyncLock();
auto lock = lockable->asScopedLock();
lock.lock();
app->updateTasks();
}
@@ -1,4 +1,4 @@
#include "tactility/lvgl_module.h"
#include <tactility/lvgl_module.h>
#include <Tactility/RecursiveMutex.h>
+34 -29
View File
@@ -4,7 +4,9 @@
#include <fstream>
#include <unistd.h>
#include <tactility/filesystem/file_mutex.h>
#include <tactility/log.h>
#include <Tactility/Mutex.h>
#include <Tactility/StringUtils.h>
namespace tt::hal::sdcard {
@@ -15,30 +17,25 @@ namespace tt::file {
constexpr auto* TAG = "file";
class NoLock final : public Lock {
bool lock(TickType_t timeout) const override { return true; }
void unlock() const override { /* NO-OP */ }
class FileMutexLock final : public Lock {
FileMutex mutex;
public:
explicit FileMutexLock(const std::string& path) {
file_mutex_get(&mutex, path.c_str());
}
bool lock(TickType_t timeout) const override {
return file_mutex_try_lock(&mutex, timeout);
}
void unlock() const override {
file_mutex_unlock(&mutex);
}
};
static std::shared_ptr<Lock> noLock = std::make_shared<NoLock>();
static std::function<std::shared_ptr<Lock>(const std::string&)> findLockFunction = nullptr;
std::shared_ptr<Lock> getLock(const std::string& path) {
if (findLockFunction == nullptr) {
LOG_W(TAG, "File lock function not set!");
return noLock;
}
auto lock = findLockFunction(path);
if (lock == nullptr) {
return noLock;
}
return lock;
}
void setFindLockFunction(const FindLockFunction& function) {
findLockFunction = function;
return std::make_shared<FileMutexLock>(path);
}
std::string getChildPath(const std::string& basePath, const std::string& childPath) {
@@ -68,7 +65,8 @@ bool listDirectory(
const std::string& path,
std::function<void(const dirent&)> onEntry
) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
LOG_I(TAG, "listDir start %s", path.c_str());
@@ -95,7 +93,8 @@ int scandir(
ScandirFilter filterMethod,
ScandirSort sortMethod
) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
LOG_I(TAG, "scandir start");
@@ -221,7 +220,8 @@ bool writeString(const std::string& filepath, const std::string& content) {
}
static bool findOrCreateDirectoryInternal(std::string path, mode_t mode) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
struct stat dir_stat;
@@ -336,32 +336,37 @@ bool deleteRecursively(const std::string& path) {
}
bool deleteFile(const std::string& path) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
return remove(path.c_str()) == 0;
}
bool deleteDirectory(const std::string& path) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
return rmdir(path.c_str()) == 0;
}
bool isFile(const std::string& path) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
return access(path.c_str(), F_OK) == 0;
}
bool isDirectory(const std::string& path) {
auto lock = getLock(path)->asScopedLock();
auto lockable = getLock(path);
auto lock = lockable->asScopedLock();
lock.lock();
struct stat stat_result;
return stat(path.c_str(), &stat_result) == 0 && S_ISDIR(stat_result.st_mode);
}
bool readLines(const std::string& filePath, bool stripNewLine, std::function<void(const char* line)> callback) {
auto lock = getLock(filePath)->asScopedLock();
auto lockable = getLock(filePath);
auto lock = lockable->asScopedLock();
lock.lock();
auto* file = fopen(filePath.c_str(), "r");
-11
View File
@@ -1,11 +0,0 @@
#include "Tactility/file/FileLock.h"
#include <Tactility/hal/SdCard.h>
namespace tt::file {
std::shared_ptr<Lock> findLock(const std::string& path) {
return hal::sdcard::findSdCardLock(path);
}
}
+80
View File
@@ -0,0 +1,80 @@
#include <tactility/device.h>
#include <tactility/drivers/display.h>
#include <tactility/drivers/spi_controller.h>
#include <tactility/filesystem/file_mutex.h>
#include <tactility/filesystem/file_system.h>
#include <tactility/lvgl_module.h>
constexpr auto* TAG = "file_mutex_lvgl";
struct Device;
namespace tt {
static const FileMutex lvgl_mutex = {
.lock = lvgl_lock,
.try_lock = lvgl_try_lock,
.unlock = lvgl_unlock,
};
/**
* Finds file systems with a device (e.g. sd card) that is owned by a SPI controller.
* If the SPI controller has a display on the bus, we create an LVGL lock for the file system path.
*/
void initFileMutexForLvgl() {
file_system_for_each(nullptr, [](FileSystem* fs, void* context) {
char mount_path[64];
if (file_system_get_path(fs, mount_path, sizeof(mount_path)) != ERROR_NONE) {
return true;
}
LOG_D(TAG, "Mount path %s", mount_path);
// We only care about file system with a Device (owner)
auto* owner = file_system_get_owner(fs);
if (owner == nullptr) {
LOG_D(TAG, "Owner: none");
return true;
}
LOG_D(TAG, "Owner: %s", owner->name);
// Ignore devices without a parent (root)
auto* parent = device_get_parent(owner);
if (parent == nullptr) {
LOG_D(TAG, "Owner: no parent");
return true;
}
LOG_D(TAG, "Owner: parent %s", parent->name);
// If the FileSystem is on a SPI bus and there's more than 1 device, we assume the other one is the display.
auto* type = device_get_type(parent);
if (type != &SPI_CONTROLLER_TYPE || device_get_child_count(parent) <= 1) {
LOG_D(TAG, "Owner parent not SPI controller or not enough children");
return true;
}
struct Context {
const char* mountPath;
};
Context ctx = { .mountPath = mount_path };
device_for_each_child(parent, &ctx, [](Device* child, void* context) -> bool {
Context* ctx = static_cast<Context*>(context);
if (device_get_type(child) == &DISPLAY_TYPE) {
LOG_I(TAG, "Adding file mutex for %s as it shares a bus with a display", ctx->mountPath);
file_mutex_register(
&lvgl_mutex,
ctx->mountPath
);
return false;
} else {
LOG_D(TAG, "child of parent, %s: not DISPLAY_TYPE", child->name);
}
return true;
});
return true;
});
}
}
-83
View File
@@ -1,83 +0,0 @@
#include <Tactility/SystemEvents.h>
#include <Tactility/Tactility.h>
#include <Tactility/hal/Configuration.h>
#include <Tactility/hal/SdCard.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/touch/TouchDevice.h>
#include <tactility/check.h>
#include <tactility/hal/Device.h>
#include <tactility/log.h>
namespace tt::hal {
constexpr auto* TAG = "Hal";
void registerDevices(const Configuration& configuration) {
LOG_I(TAG, "Registering devices");
auto devices = configuration.createDevices();
for (auto& device : devices) {
registerDevice(device);
// Register attached devices
if (device->getType() == Device::Type::Display) {
const auto display = std::static_pointer_cast<display::DisplayDevice>(device);
assert(display != nullptr);
const std::shared_ptr<Device> touch = display->getTouchDevice();
if (touch != nullptr) {
registerDevice(touch);
}
}
}
}
static void startDisplays() {
LOG_I(TAG, "Starting displays & touch");
auto displays = hal::findDevices<display::DisplayDevice>(Device::Type::Display);
for (auto& display : displays) {
LOG_I(TAG, "%s starting", display->getName().c_str());
if (!display->start()) {
LOG_E(TAG, "%s start failed", display->getName().c_str());
} else {
LOG_I(TAG, "%s started", display->getName().c_str());
if (display->supportsBacklightDuty()) {
LOG_I(TAG, "Setting backlight");
display->setBacklightDuty(0);
}
auto touch = display->getTouchDevice();
if (touch != nullptr) {
LOG_I(TAG, "%s starting", touch->getName().c_str());
if (!touch->start()) {
LOG_E(TAG, "%s start failed", touch->getName().c_str());
} else {
LOG_I(TAG, "%s started", touch->getName().c_str());
}
}
}
}
}
void init(const Configuration& configuration) {
kernel::publishSystemEvent(kernel::SystemEvent::BootInitHalBegin);
if (configuration.initBoot != nullptr) {
check(configuration.initBoot(), "Init boot failed");
}
registerDevices(configuration);
sdcard::mountAll(); // Warning: This needs to happen BEFORE displays are initialized on the SPI bus
startDisplays(); // Warning: SPI displays need to start after SPI SD cards are mounted
kernel::publishSystemEvent(kernel::SystemEvent::BootInitHalEnd);
}
const Configuration* getConfiguration() {
return tt::getConfiguration()->hardware;
}
} // namespace
@@ -1,59 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <Tactility/hal/display/KernelDisplayDriver.h>
#include <tactility/drivers/display.h>
#include <algorithm>
#include <cassert>
#include <utility>
namespace tt::hal::display {
static ColorFormat toColorFormat(DisplayColorFormat format) {
switch (format) {
case DISPLAY_COLOR_FORMAT_MONOCHROME:
return ColorFormat::Monochrome;
case DISPLAY_COLOR_FORMAT_BGR565:
return ColorFormat::BGR565;
case DISPLAY_COLOR_FORMAT_BGR565_SWAPPED:
return ColorFormat::BGR565Swapped;
case DISPLAY_COLOR_FORMAT_RGB565:
return ColorFormat::RGB565;
case DISPLAY_COLOR_FORMAT_RGB565_SWAPPED:
return ColorFormat::RGB565Swapped;
case DISPLAY_COLOR_FORMAT_RGB888:
return ColorFormat::RGB888;
default:
std::unreachable();
}
}
KernelDisplayDriver::KernelDisplayDriver(::Device* device) : device(device) {
assert(device_get_type(device) == &DISPLAY_TYPE);
}
ColorFormat KernelDisplayDriver::getColorFormat() const {
return toColorFormat(display_get_color_format(device));
}
uint16_t KernelDisplayDriver::getPixelWidth() const {
return display_get_resolution_x(device);
}
uint16_t KernelDisplayDriver::getPixelHeight() const {
return display_get_resolution_y(device);
}
bool KernelDisplayDriver::drawBitmap(int xStart, int yStart, int xEnd, int yEnd, const void* pixelData) {
return display_draw_bitmap(device, xStart, yStart, xEnd, yEnd, pixelData) == ERROR_NONE;
}
uint8_t KernelDisplayDriver::getFrameBuffers(void* outBuffers[2]) const {
uint8_t count = std::min<uint8_t>(display_get_frame_buffer_count(device), 2);
for (uint8_t i = 0; i < count; i++) {
display_get_frame_buffer(device, i, &outBuffers[i]);
}
return count;
}
}
-87
View File
@@ -1,87 +0,0 @@
#include <Tactility/hal/gpio/Gpio.h>
#ifdef ESP_PLATFORM
#include <driver/gpio.h>
#endif
namespace tt::hal::gpio {
#ifdef ESP_PLATFORM
constexpr gpio_num_t toEspPin(Pin pin) { return static_cast<gpio_num_t>(pin); }
constexpr gpio_mode_t toEspGpioMode(Mode mode) {
switch (mode) {
case Mode::Input:
return GPIO_MODE_INPUT;
case Mode::Output:
return GPIO_MODE_OUTPUT;
case Mode::OutputOpenDrain:
return GPIO_MODE_OUTPUT_OD;
case Mode::InputOutput:
return GPIO_MODE_INPUT_OUTPUT;
case Mode::InputOutputOpenDrain:
return GPIO_MODE_INPUT_OUTPUT_OD;
case Mode::Disable:
default:
return GPIO_MODE_DISABLE;
}
}
#endif
bool getLevel(Pin pin) {
#ifdef ESP_PLATFORM
return gpio_get_level(toEspPin(pin)) == 1;
#else
return false;
#endif
}
bool setLevel(Pin pin, bool level) {
#ifdef ESP_PLATFORM
return gpio_set_level(toEspPin(pin), level) == ESP_OK;
#else
return true;
#endif
}
int getPinCount() {
#ifdef ESP_PLATFORM
return GPIO_NUM_MAX;
#else
return 16;
#endif
}
bool configureWithPinBitmask(uint64_t pinBitMask, Mode mode, bool pullUp, bool pullDown) {
#ifdef ESP_PLATFORM
gpio_config_t sd_gpio_config = {
.pin_bit_mask = pinBitMask,
.mode = toEspGpioMode(mode),
.pull_up_en = pullUp ? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE,
.pull_down_en = pullDown ? GPIO_PULLDOWN_ENABLE : GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
return gpio_config(&sd_gpio_config) == ESP_OK;
#else
return true;
#endif
}
bool configure(Pin pin, Mode mode, bool pullUp, bool pullDown) {
#ifdef ESP_PLATFORM
return configureWithPinBitmask(BIT64(toEspPin(pin)), mode, pullUp, pullDown);
#else
return true;
#endif
}
bool setMode(Pin pin, Mode mode) {
#ifdef ESP_PLATFORM
return gpio_set_direction(toEspPin(pin), toEspGpioMode(mode)) == ESP_OK;
#endif
return true;
}
}
@@ -1,51 +0,0 @@
#include "Tactility/hal/gps/GpsConfiguration.h"
#include "Tactility/service/gps/GpsService.h"
#include "Tactility/file/ObjectFile.h"
#include <Tactility/TactilityCore.h>
namespace tt::hal::gps {
const char* toString(GpsModel model) {
using enum GpsModel;
switch (model) {
case AG3335:
return TT_STRINGIFY(AG3335);
case AG3352:
return TT_STRINGIFY(AG3352);
case ATGM336H:
return TT_STRINGIFY(ATGM336H);
case LS20031:
return TT_STRINGIFY(LS20031);
case MTK:
return TT_STRINGIFY(MTK);
case MTK_L76B:
return TT_STRINGIFY(MTK_L76B);
case MTK_PA1616S:
return TT_STRINGIFY(MTK_PA1616S);
case UBLOX6:
return TT_STRINGIFY(UBLOX6);
case UBLOX7:
return TT_STRINGIFY(UBLOX7);
case UBLOX8:
return TT_STRINGIFY(UBLOX8);
case UBLOX9:
return TT_STRINGIFY(UBLOX9);
case UBLOX10:
return TT_STRINGIFY(UBLOX10);
case UC6580:
return TT_STRINGIFY(UC6580);
default:
return TT_STRINGIFY(Unknown);
}
}
std::vector<std::string> getModels() {
std::vector<std::string> result;
for (GpsModel model = GpsModel::Unknown; model <= GpsModel::UC6580; ++(int&)model) {
result.push_back(toString(model));
}
return result;
}
}
-199
View File
@@ -1,199 +0,0 @@
#include <Tactility/hal/gps/GpsDevice.h>
#include <Tactility/hal/gps/GpsInit.h>
#include <Tactility/hal/gps/Probe.h>
#include <tactility/log.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <minmea.h>
namespace tt::hal::gps {
constexpr uint32_t GPS_UART_BUFFER_SIZE = 256;
constexpr auto* TAG = "GpsDevice";
int32_t GpsDevice::threadMain() {
uint8_t buffer[GPS_UART_BUFFER_SIZE];
auto* uart = device_find_by_name(configuration.uartName);
if (uart == nullptr) {
LOG_E(TAG, "Failed to find UART %s", configuration.uartName);
return -1;
}
struct UartConfig uartConfig = {
.baud_rate = configuration.baudRate,
.data_bits = UART_CONTROLLER_DATA_8_BITS,
.parity = UART_CONTROLLER_PARITY_DISABLE,
.stop_bits = UART_CONTROLLER_STOP_BITS_1
};
error_t error = uart_controller_set_config(uart, &uartConfig);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to configure UART %s: %s", configuration.uartName, error_to_string(error));
return -1;
}
error = uart_controller_open(uart);
if (error != ERROR_NONE) {
LOG_E(TAG, "Failed to open UART %s: %s", configuration.uartName, error_to_string(error));
return -1;
}
GpsModel model = configuration.model;
if (model == GpsModel::Unknown) {
model = probe(uart);
if (model == GpsModel::Unknown) {
LOG_E(TAG, "Probe failed");
setState(State::Error);
return -1;
}
}
mutex.lock();
this->model = model;
mutex.unlock();
if (!init(uart, model)) {
LOG_E(TAG, "Init failed");
setState(State::Error);
return -1;
}
setState(State::On);
// Reference: https://gpsd.gitlab.io/gpsd/NMEA.html
while (!isThreadInterrupted()) {
size_t bytes_read = 0;
uart_controller_read_until(uart, buffer, GPS_UART_BUFFER_SIZE, '\n', true, &bytes_read, 100 / portTICK_PERIOD_MS);
// Thread might've been interrupted in the meanwhile
if (isThreadInterrupted()) {
break;
}
if (bytes_read > 0U) {
LOG_I(TAG, "[%d] %s", (int)bytes_read, reinterpret_cast<const char*>(buffer));
switch (minmea_sentence_id((char*)buffer, false)) {
case MINMEA_SENTENCE_RMC:
minmea_sentence_rmc rmc_frame;
if (minmea_parse_rmc(&rmc_frame, (char*)buffer)) {
mutex.lock();
for (auto& subscription : rmcSubscriptions) {
(*subscription.onData)(getId(), rmc_frame);
}
mutex.unlock();
LOG_D(TAG, "RMC %f lat, %f lon, %f m/s", minmea_tocoord(&rmc_frame.latitude), minmea_tocoord(&rmc_frame.longitude), minmea_tofloat(&rmc_frame.speed));
} else {
LOG_E(TAG, "RMC parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
case MINMEA_SENTENCE_GGA:
minmea_sentence_gga gga_frame;
if (minmea_parse_gga(&gga_frame, (char*)buffer)) {
mutex.lock();
for (auto& subscription : ggaSubscriptions) {
(*subscription.onData)(getId(), gga_frame);
}
mutex.unlock();
LOG_D(TAG, "GGA %f lat, %f lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude));
} else {
LOG_E(TAG, "GGA parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
default:
break;
}
}
}
if (uart_controller_close(uart) != ERROR_NONE) {
LOG_W(TAG, "Failed to stop UART %s", configuration.uartName);
}
return 0;
}
bool GpsDevice::start() {
auto lock = mutex.asScopedLock();
lock.lock();
if (thread != nullptr && thread->getState() != Thread::State::Stopped) {
LOG_W(TAG, "Already started");
return true;
}
threadInterrupted = false;
LOG_I(TAG, "Starting thread");
setState(State::PendingOn);
thread = std::make_unique<Thread>(
"gps",
4096,
[this]() {
return this->threadMain();
}
);
thread->setPriority(tt::Thread::Priority::High);
thread->start();
LOG_I(TAG, "Starting finished");
return true;
}
bool GpsDevice::stop() {
auto lock = mutex.asScopedLock();
lock.lock();
setState(State::PendingOff);
if (thread != nullptr) {
threadInterrupted = true;
// Detach thread, it will auto-delete when leaving the current scope
auto old_thread = std::move(thread);
if (old_thread->getState() != Thread::State::Stopped) {
// Unlock so thread can lock
lock.unlock();
// Wait for thread to finish
old_thread->join();
// Re-lock to continue logic below
lock.lock();
}
}
setState(State::Off);
return true;
}
bool GpsDevice::isThreadInterrupted() const {
auto lock = mutex.asScopedLock();
lock.lock();
return threadInterrupted;
}
GpsModel GpsDevice::getModel() const {
auto lock = mutex.asScopedLock();
lock.lock();
return model; // Make copy because of thread safety
}
GpsDevice::State GpsDevice::getState() const {
auto lock = mutex.asScopedLock();
lock.lock();
return state; // Make copy because of thread safety
}
void GpsDevice::setState(State newState) {
auto lock = mutex.asScopedLock();
lock.lock();
state = newState;
}
} // namespace tt::hal::gps
-298
View File
@@ -1,298 +0,0 @@
#include <Tactility/hal/gps/Cas.h>
#include <Tactility/hal/gps/GpsDevice.h>
#include <Tactility/hal/gps/Ublox.h>
#include <Tactility/kernel/Kernel.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <cstring>
namespace tt::hal::gps {
constexpr auto* TAG = "Gps";
bool initMtk(::Device* uart);
bool initMtkL76b(::Device* uart);
bool initMtkPa1616s(::Device* uart);
bool initAtgm336h(::Device* uart);
bool initUc6580(::Device* uart);
bool initAg33xx(::Device* uart);
// region CAS
// Calculate the checksum for a CAS packet
static void CASChecksum(uint8_t *message, size_t length)
{
uint32_t cksum = ((uint32_t)message[5] << 24); // Message ID
cksum += ((uint32_t)message[4]) << 16; // Class
cksum += message[2]; // Payload Len
// Iterate over the payload as a series of uint32_t's and
// accumulate the cksum
for (size_t i = 0; i < (length - 10) / 4; i++) {
uint32_t pl = 0;
memcpy(&pl, (message + 6) + (i * sizeof(uint32_t)), sizeof(uint32_t)); // avoid pointer dereference
cksum += pl;
}
// Place the checksum values in the message
message[length - 4] = (cksum & 0xFF);
message[length - 3] = (cksum & (0xFF << 8)) >> 8;
message[length - 2] = (cksum & (0xFF << 16)) >> 16;
message[length - 1] = (cksum & (0xFF << 24)) >> 24;
}
// Function to create a CAS packet for editing in memory
static uint8_t makeCASPacket(uint8_t* buffer, uint8_t class_id, uint8_t msg_id, uint8_t payload_size, const uint8_t *msg)
{
// General CAS structure
// | H1 | H2 | payload_len | cls | msg | Payload ... | Checksum |
// Size: | 1 | 1 | 2 | 1 | 1 | payload_len | 4 |
// Pos: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 ... | 6 + payload_len ... |
// |------|------|-------------|------|------|------|--------------|---------------------------|
// | 0xBA | 0xCE | 0xXX | 0xXX | 0xXX | 0xXX | 0xXX | 0xXX ... | 0xXX | 0xXX | 0xXX | 0xXX |
// Construct the CAS packet
buffer[0] = 0xBA; // header 1 (0xBA)
buffer[1] = 0xCE; // header 2 (0xCE)
buffer[2] = payload_size; // length 1
buffer[3] = 0; // length 2
buffer[4] = class_id; // class
buffer[5] = msg_id; // id
buffer[6 + payload_size] = 0x00; // Checksum
buffer[7 + payload_size] = 0x00;
buffer[8 + payload_size] = 0x00;
buffer[9 + payload_size] = 0x00;
for (int i = 0; i < payload_size; i++) {
buffer[6 + i] = msg[i];
}
CASChecksum(buffer, (payload_size + 10));
return (payload_size + 10);
}
GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis)
{
uint32_t startTime = kernel::getMillis();
uint8_t buffer[CAS_ACK_NACK_MSG_SIZE] = {0};
uint8_t bufferPos = 0;
TickType_t waitTicks = pdMS_TO_TICKS(waitMillis);
// CAS-ACK-(N)ACK structure
// | H1 | H2 | Payload Len | cls | msg | Payload | Checksum (4) |
// | | | | | | Cls | Msg | Reserved | |
// |------|------|-------------|------|------|------|------|-------------|---------------------------|
// ACK-NACK| 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x00 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
// ACK-ACK | 0xBA | 0xCE | 0x04 | 0x00 | 0x05 | 0x01 | 0xXX | 0xXX | 0x00 | 0x00 | 0xXX | 0xXX | 0xXX | 0xXX |
while (kernel::getTicks() - startTime < waitTicks) {
size_t available = 0;
uart_controller_get_available(uart, &available);
if (available > 0) {
uart_controller_read_byte(uart, &buffer[bufferPos++], 1);
// keep looking at the first two bytes of buffer until
// we have found the CAS frame header (0xBA, 0xCE), if not
// keep reading bytes until we find a frame header or we run
// out of time.
if ((bufferPos == 2) && !(buffer[0] == 0xBA && buffer[1] == 0xCE)) {
buffer[0] = buffer[1];
buffer[1] = 0;
bufferPos = 1;
}
}
// we have read all the bytes required for the Ack/Nack (14-bytes)
// and we must have found a frame to get this far
if (bufferPos == sizeof(buffer) - 1) {
uint8_t msg_cls = buffer[4]; // message class should be 0x05
uint8_t msg_msg_id = buffer[5]; // message id should be 0x00 or 0x01
uint8_t payload_cls = buffer[6]; // payload class id
uint8_t payload_msg = buffer[7]; // payload message id
// Check for an ACK-ACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_I(TAG, "Got ACK for class %02X message %02X in %zu ms", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok;
}
// Check for an ACK-NACK for the specified class and message id
if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) {
#ifdef GPS_DEBUG
LOG_W(TAG, "Got NACK for class %02X message %02X in %zu ms", class_id, msg_id, millis() - startTime);
#endif
return GpsResponse::NotAck;
}
// This isn't the frame we are looking for, clear the buffer
// and try again until we run out of time.
memset(buffer, 0x0, sizeof(buffer));
bufferPos = 0;
}
}
return GpsResponse::None;
}
// endregion
bool init(::Device* uart, GpsModel type) {
switch (type) {
case GpsModel::Unknown:
check(false);
case GpsModel::AG3335:
case GpsModel::AG3352:
return initAg33xx(uart);
case GpsModel::ATGM336H:
return initAtgm336h(uart);
case GpsModel::LS20031:
return true;
case GpsModel::MTK:
return initMtk(uart);
case GpsModel::MTK_L76B:
return initMtkL76b(uart);
case GpsModel::MTK_PA1616S:
return initMtkPa1616s(uart);
case GpsModel::UBLOX6:
case GpsModel::UBLOX7:
case GpsModel::UBLOX8:
case GpsModel::UBLOX9:
case GpsModel::UBLOX10:
return ublox::init(uart, type);
case GpsModel::UC6580:
return initUc6580(uart);
}
LOG_I(TAG, "Init not implemented %d", static_cast<int>(type));
return false;
}
bool initAg33xx(::Device* uart) {
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR066,1,0,1,0,0,1*3B\r\n", 25, 250); // Enable GPS+GALILEO+NAVIC
// Configure NMEA (sentences will output once per fix)
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,0,1*3F\r\n", 17, 250); // GGA ON
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,1,0*3F\r\n", 17, 250); // GLL OFF
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,2,0*3C\r\n", 17, 250); // GSA OFF
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,3,0*3D\r\n", 17, 250); // GSV OFF
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,4,1*3B\r\n", 17, 250); // RMC ON
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,5,0*3B\r\n", 17, 250); // VTG OFF
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,6,0*38\r\n", 17, 250); // ZDA ON
kernel::delayMillis(250);
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR513*3D\r\n", 13, 250); // save configuration
return true;
}
bool initUc6580(::Device* uart) {
// The Unicore UC6580 can use a lot of sat systems, enable it to
// use GPS L1 & L5 + BDS B1I & B2a + GLONASS L1 + GALILEO E1 & E5a + SBAS + QZSS
// This will reset the receiver, so wait a bit afterwards
// The paranoid will wait for the OK*04 confirmation response after each command.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGSYS,h35155\r\n", 16, 250);
kernel::delayMillis(750);
// Must be done after the CFGSYS command
// Turn off GSV messages, we don't really care about which and where the sats are, maybe someday.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,3,0\r\n", 15, 250);
kernel::delayMillis(250);
// Turn off GSA messages, TinyGPS++ doesn't use this message.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,0,2,0\r\n", 15, 250);
kernel::delayMillis(250);
// Turn off NOTICE __TXT messages, these may provide Unicore some info but we don't care.
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,0,0\r\n", 15, 250);
kernel::delayMillis(250);
uart_controller_write_bytes(uart, (const uint8_t*)"$CFGMSG,6,1,0\r\n", 15, 250);
kernel::delayMillis(250);
return true;
}
bool initAtgm336h(::Device* uart) {
uint8_t buffer[256];
// Set the intial configuration of the device - these _should_ work for most AT6558 devices
int msglen = makeCASPacket(buffer, 0x06, 0x07, sizeof(_message_CAS_CFG_NAVX_CONF), _message_CAS_CFG_NAVX_CONF);
uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not set Config");
}
// Set the update frequence to 1Hz
msglen = makeCASPacket(buffer, 0x06, 0x04, sizeof(_message_CAS_CFG_RATE_1HZ), _message_CAS_CFG_RATE_1HZ);
uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not set Update Frequency");
}
// Set the NEMA output messages
// Ask for only RMC and GGA
uint8_t fields[] = {CAS_NEMA_RMC, CAS_NEMA_GGA};
for (unsigned int i = 0; i < sizeof(fields); i++) {
// Construct a CAS-CFG-MSG packet
uint8_t cas_cfg_msg_packet[] = {0x4e, fields[i], 0x01, 0x00};
msglen = makeCASPacket(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet);
uart_controller_write_bytes(uart, buffer, msglen, 250);
if (getACKCas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) {
LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %u", fields[i]);
}
}
return true;
}
bool initMtkPa1616s(::Device* uart) {
// PA1616S is used in some GPS breakout boards from Adafruit
// PA1616S does not have GLONASS capability. PA1616D does, but is not implemented here.
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,0,0,0,0*2A\r\n", 23, 250);
// Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000);
// Only ask for RMC and GGA (GNRMC and GNGGA)
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250);
kernel::delayMillis(250);
// Enable SBAS / WAAS
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250);
kernel::delayMillis(250);
return true;
}
bool initMtkL76b(::Device* uart) {
// Waveshare Pico-GPS hat uses the L76B with 9600 baud
// Initialize the L76B Chip, use GPS + GLONASS
// See note in L76_Series_GNSS_Protocol_Specification, chapter 3.29
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK353,1,1,0,0,0*2B\r\n", 23, 250);
// Above command will reset the GPS and takes longer before it will accept new commands
kernel::delayMillis(1000);
// only ask for RMC and GGA (GNRMC and GNGGA)
// See note in L76_Series_GNSS_Protocol_Specification, chapter 2.1
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28\r\n", 51, 250);
kernel::delayMillis(250);
// Enable SBAS
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK301,2*2E\r\n", 15, 250);
kernel::delayMillis(250);
// Enable PPS for 2D/3D fix only
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK285,3,100*3F\r\n", 19, 250);
kernel::delayMillis(250);
// Switch to Fitness Mode, for running and walking purpose with low speed (<5 m/s)
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK886,1*29\r\n", 15, 250);
kernel::delayMillis(250);
return true;
}
bool initMtk(::Device* uart) {
// Initialize the L76K Chip, use GPS + GLONASS + BEIDOU
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS04,7*1E\r\n", 14, 250);
kernel::delayMillis(250);
// only ask for RMC and GGA
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS03,1,0,0,0,1,0,0,0,0,0,,,0,0*02\r\n", 38, 250);
kernel::delayMillis(250);
// Switch to Vehicle Mode, since SoftRF enables Aviation < 2g
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS11,3*1E\r\n", 14, 250);
kernel::delayMillis(250);
return true;
}
} // namespace tt::hal::gps
-146
View File
@@ -1,146 +0,0 @@
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/gps/Ublox.h"
#include <Tactility/kernel/Kernel.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <cstring>
constexpr auto* TAG = "Gps";
#define GPS_UART_BUFFER_SIZE 256
using namespace tt;
using namespace tt::hal;
namespace tt::hal::gps {
/**
* From: https://github.com/meshtastic/firmware/blob/3b0232de1b6282eacfbff6e50b68fca7e67b8511/src/meshUtils.cpp#L40
*/
char* strnstr(const char* s, const char* find, size_t slen) {
char c;
if ((c = *find++) != '\0') {
char sc;
size_t len;
len = strlen(find);
do {
do {
if (slen-- < 1 || (sc = *s++) == '\0')
return (nullptr);
} while (sc != c);
if (len > slen)
return (nullptr);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char*)s);
}
/**
* From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp
*/
GpsResponse getAck(::Device* uart, const char* message, uint32_t waitMillis) {
uint8_t buffer[768] = {0};
uint8_t b;
int bytesRead = 0;
uint32_t startTimeout = kernel::getMillis() + waitMillis;
#ifdef GPS_DEBUG
std::string debugmsg = "";
#endif
while (kernel::getMillis() < startTimeout) {
size_t available = 0;
uart_controller_get_available(uart, &available);
if (available > 0) {
uart_controller_read_byte(uart, &b, 1);
#ifdef GPS_DEBUG
debugmsg += vformat("%c", (b >= 32 && b <= 126) ? b : '.');
#endif
buffer[bytesRead] = b;
bytesRead++;
if ((bytesRead == 767) || (b == '\r')) {
if (strnstr((char*)buffer, message, bytesRead) != nullptr) {
#ifdef GPS_DEBUG
LOG_D(TAG, "Found: %s", message); // Log the found message
#endif
return GpsResponse::Ok;
} else {
bytesRead = 0;
#ifdef GPS_DEBUG
LOG_D(TAG, "%s", debugmsg.c_str());
#endif
}
}
}
}
return GpsResponse::None;
}
/**
* From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp
*/
#define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \
do { \
LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \
uart_controller_flush_input(UART); \
uart_controller_write_bytes(UART, (const uint8_t*)(TOWRITE "\r\n"), strlen(TOWRITE "\r\n"), TIMEOUT); \
if (getAck(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \
LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \
return DRIVER; \
} \
} while (0)
/**
* From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp
*/
GpsModel probe(::Device* uart) {
// Close all NMEA sentences, valid for L76K, ATGM336H (and likely other AT6558 devices)
uart_controller_write_bytes(uart, (const uint8_t*)"$PCAS03,0,0,0,0,0,0,0,0,0,0,,,0,0*02\r\n", 40, 500);
kernel::delayMillis(20);
// Close NMEA sequences on Ublox
uart_controller_write_bytes(uart, (const uint8_t*)"$PUBX,40,GLL,0,0,0,0,0,0*5C\r\n", 29, 500);
uart_controller_write_bytes(uart, (const uint8_t*)"$PUBX,40,GSV,0,0,0,0,0,0*59\r\n", 29, 500);
uart_controller_write_bytes(uart, (const uint8_t*)"$PUBX,40,VTG,0,0,0,0,0,0*5E\r\n", 29, 500);
kernel::delayMillis(20);
// Unicore UFirebirdII Series: UC6580, UM620, UM621, UM670A, UM680A, or UM681A
PROBE_SIMPLE(uart, "UC6580", "$PDTINFO", "UC6580", GpsModel::UC6580, 500);
PROBE_SIMPLE(uart, "UM600", "$PDTINFO", "UM600", GpsModel::UC6580, 500);
PROBE_SIMPLE(uart, "ATGM336H", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM336H", GpsModel::ATGM336H, 500);
/* ATGM332D series (-11(GPS), -21(BDS), -31(GPS+BDS), -51(GPS+GLONASS), -71-0(GPS+BDS+GLONASS))
based on AT6558 */
PROBE_SIMPLE(uart, "ATGM332D", "$PCAS06,1*1A", "$GPTXT,01,01,02,HW=ATGM332D", GpsModel::ATGM336H, 500);
/* Airoha (Mediatek) AG3335A/M/S, A3352Q, Quectel L89 2.0, SimCom SIM65M */
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,2,0*3C\r\n", 17, 500); // GSA OFF to reduce volume
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR062,3,0*3D\r\n", 17, 500); // GSV OFF to reduce volume
uart_controller_write_bytes(uart, (const uint8_t*)"$PAIR513*3D\r\n", 13, 500); // save configuration
PROBE_SIMPLE(uart, "AG3335", "$PAIR021*39", "$PAIR021,AG3335", GpsModel::AG3335, 500);
PROBE_SIMPLE(uart, "AG3352", "$PAIR021*39", "$PAIR021,AG3352", GpsModel::AG3352, 500);
PROBE_SIMPLE(uart, "LC86", "$PQTMVERNO*58", "$PQTMVERNO,LC86", GpsModel::AG3352, 500);
PROBE_SIMPLE(uart, "L76K", "$PCAS06,0*1B", "$GPTXT,01,01,02,SW=", GpsModel::MTK, 500);
// Close all NMEA sentences, valid for L76B MTK platform (Waveshare Pico GPS)
uart_controller_write_bytes(uart, (const uint8_t*)"$PMTK514,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*2E\r\n", 51, 500);
kernel::delayMillis(20);
PROBE_SIMPLE(uart, "L76B", "$PMTK605*31", "Quectel-L76B", GpsModel::MTK_L76B, 500);
PROBE_SIMPLE(uart, "PA1616S", "$PMTK605*31", "1616S", GpsModel::MTK_PA1616S, 500);
auto ublox_result = ublox::probe(uart);
if (ublox_result != GpsModel::Unknown) {
return ublox_result;
} else {
LOG_W(TAG, "No GNSS Module");
return GpsModel::Unknown;
}
}
} // namespace tt::hal::gps
-115
View File
@@ -1,115 +0,0 @@
#include <Tactility/hal/gps/Satellites.h>
#include <Tactility/kernel/Kernel.h>
#include <tactility/log.h>
namespace tt::hal::gps {
constexpr auto* TAG = "Satellites";
constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
return (TickType_t)(now - timeInThePast) >= expireTimeInTicks;
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecord(int number) {
auto result = records | std::views::filter([number](auto& record) {
return record.inUse && record.data.nr == number;
});
if (!result.empty()) {
return &result.front();
} else {
return nullptr;
}
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findUnusedRecord() {
auto lock = mutex.asScopedLock();
lock.lock();
auto result = records | std::views::filter([](auto& record) {
return !record.inUse;
});
if (!result.empty()) {
auto* record = &result.front();
record->inUse = true;
LOG_D(TAG, "Found unused record");
return record;
} else {
return nullptr;
}
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() {
auto lock = mutex.asScopedLock();
lock.lock();
int candidate_index = -1;
auto candidate_age = kernel::MAX_TICKS;
TickType_t expire_duration = kernel::secondsToTicks(recycleTimeSeconds);
TickType_t now = kernel::getTicks();
for (int i = 0; i < records.size(); ++i) {
// First try to find a record that is "old enough"
if (hasTimeElapsed(now, records[i].lastUpdated, expire_duration)) {
LOG_D(TAG, "! [%d] %u < %u", i, records[i].lastUpdated, expire_duration);
candidate_index = i;
break;
}
// Otherwise keep finding the oldest record
if (records[i].inUse && records[i].lastUpdated < candidate_age) {
candidate_index = i;
candidate_age = records[i].lastUpdated;
LOG_D(TAG, "? [%d] %u < %u", i, records[i].lastUpdated, candidate_age);
}
}
assert(candidate_index != -1);
LOG_D(TAG, "Recycled record %d", candidate_index);
return &records[candidate_index];
}
SatelliteStorage::SatelliteRecord* SatelliteStorage::findWithFallback(int number) {
auto lock = mutex.asScopedLock();
lock.lock();
if (auto* found_record = findRecord(number)) {
return found_record;
} else if (auto* unused_record = findUnusedRecord()) {
return unused_record;
} else {
return findRecordToRecycle();
}
}
void SatelliteStorage::notify(const minmea_sat_info& data) {
auto lock = mutex.asScopedLock();
lock.lock();
auto* record = findWithFallback(data.nr);
if (record != nullptr) {
record->inUse = true;
record->lastUpdated = kernel::getTicks();
record->data = data;
LOG_D(TAG, "Updated satellite %d: elevation %d, azimuth %d, snr %d", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr);
}
}
void SatelliteStorage::getRecords(const std::function<void(const minmea_sat_info&)>& onRecord) const {
auto lock = mutex.asScopedLock();
lock.lock();
TickType_t expire_duration = kernel::secondsToTicks(recentTimeSeconds);
TickType_t now = kernel::getTicks();
for (auto& record: records) {
if (record.inUse && !hasTimeElapsed(now, record.lastUpdated, expire_duration)) {
onRecord(record.data);
}
}
}
} // namespace tt::hal::gps
-492
View File
@@ -1,492 +0,0 @@
#include <Tactility/hal/gps/Ublox.h>
#include <Tactility/hal/gps/UbloxMessages.h>
#include <Tactility/kernel/Kernel.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <cstring>
namespace tt::hal::gps::ublox {
constexpr auto* TAG = "Ublox";
bool initUblox6(::Device* uart);
bool initUblox789(::Device* uart, GpsModel model);
bool initUblox10(::Device* uart);
#define SEND_UBX_PACKET(UART, BUFFER, TYPE, ID, DATA, ERRMSG, TIMEOUT_MILLIS) \
do { \
auto msglen = makePacket(TYPE, ID, DATA, sizeof(DATA), BUFFER); \
uart_controller_write_bytes(UART, BUFFER, msglen, TIMEOUT_MILLIS / portTICK_PERIOD_MS); \
if (getAck(UART, TYPE, ID, TIMEOUT_MILLIS) != GpsResponse::Ok) { \
LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \
} \
} while (0)
void checksum(uint8_t* message, size_t length) {
uint8_t CK_A = 0, CK_B = 0;
// Calculate the checksum, starting from the CLASS field (which is message[2])
for (size_t i = 2; i < length - 2; i++) {
CK_A = (CK_A + message[i]) & 0xFF;
CK_B = (CK_B + CK_A) & 0xFF;
}
// Place the calculated checksum values in the message
message[length - 2] = CK_A;
message[length - 1] = CK_B;
}
uint8_t makePacket(uint8_t classId, uint8_t messageId, const uint8_t* payload, uint8_t payloadSize, uint8_t* bufferOut) {
// Construct the UBX packet
bufferOut[0] = 0xB5U; // header
bufferOut[1] = 0x62U; // header
bufferOut[2] = classId; // class
bufferOut[3] = messageId; // id
bufferOut[4] = payloadSize; // length
bufferOut[5] = 0x00U;
bufferOut[6 + payloadSize] = 0x00U; // CK_A
bufferOut[7 + payloadSize] = 0x00U; // CK_B
for (int i = 0; i < payloadSize; i++) {
bufferOut[6 + i] = payload[i];
}
checksum(bufferOut, (payloadSize + 8U));
return (payloadSize + 8U);
}
GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t waitMillis) {
uint8_t b;
uint8_t ack = 0;
const uint8_t ackP[2] = {class_id, msg_id};
uint8_t buf[10] = {0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t startTime = kernel::getTicks();
TickType_t waitTicks = pdMS_TO_TICKS(waitMillis);
const char frame_errors[] = "More than 100 frame errors";
int sCounter = 0;
#ifdef GPS_DEBUG
std::string debugmsg = "";
#endif
for (int j = 2; j < 6; j++) {
buf[8] += buf[j];
buf[9] += buf[8];
}
for (int j = 0; j < 2; j++) {
buf[6 + j] = ackP[j];
buf[8] += buf[6 + j];
buf[9] += buf[8];
}
while (kernel::getTicks() - startTime < waitTicks) {
if (ack > 9) {
#ifdef GPS_DEBUG
LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok; // ACK received
}
size_t available = 0;
uart_controller_get_available(uart, &available);
if (available > 0) {
uart_controller_read_byte(uart, &b, 1);
if (b == frame_errors[sCounter]) {
sCounter++;
if (sCounter == 26) {
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
return GpsResponse::FrameErrors;
}
} else {
sCounter = 0;
}
#ifdef GPS_DEBUG
debugmsg += std::format("%02X", b);
#endif
if (b == buf[ack]) {
ack++;
} else {
if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id);
return GpsResponse::NotAck; // NAK received
}
ack = 0; // Reset the acknowledgement counter
}
}
}
#ifdef GPS_DEBUG
LOG_I(TAG, "%s", debugmsg.c_str());
LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id);
#endif
return GpsResponse::None; // No response received within timeout
}
static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t requestedClass, uint8_t requestedId, uint32_t timeoutMillis) {
uint16_t ubxFrameCounter = 0;
TickType_t startTime = kernel::getTicks();
TickType_t timeoutTicks = pdMS_TO_TICKS(timeoutMillis);
uint16_t needRead = 0;
while ((kernel::getTicks() - startTime) < timeoutTicks) {
size_t available = 0;
uart_controller_get_available(uart, &available);
while (available > 0) {
uint8_t c;
uart_controller_read_byte(uart, &c, 1);
available--;
switch (ubxFrameCounter) {
case 0:
if (c == 0xB5) {
ubxFrameCounter++;
}
break;
case 1:
if (c == 0x62) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 2:
if (c == requestedClass) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 3:
if (c == requestedId) {
ubxFrameCounter++;
} else {
ubxFrameCounter = 0;
}
break;
case 4:
needRead = c;
ubxFrameCounter++;
break;
case 5: {
// Payload length msb
needRead |= (c << 8);
ubxFrameCounter++;
// Check for buffer overflow
if (needRead >= size) {
ubxFrameCounter = 0;
break;
}
auto read_bytes = 0U;
uart_controller_read_bytes(uart, buffer, needRead, 250 / portTICK_PERIOD_MS);
if (read_bytes != needRead) {
ubxFrameCounter = 0;
} else {
// return payload length
#ifdef GPS_DEBUG
LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", requestedClass, requestedId, kernel::getMillis() - startTime);
#endif
return needRead;
}
break;
}
default:
break;
}
}
}
return 0;
}
static struct uBloxGnssModelInfo {
char swVersion[30];
char hwVersion[10];
uint8_t extensionNo;
char extension[10][30];
uint8_t protocol_version;
} ublox_info;
GpsModel probe(::Device* uart) {
LOG_I(TAG, "Probing for U-blox");
uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00};
checksum(cfg_rate, sizeof(cfg_rate));
uart_controller_flush_input(uart);
uart_controller_write_bytes(uart, cfg_rate, sizeof(cfg_rate), 500 / portTICK_PERIOD_MS);
// Check that the returned response class and message ID are correct
GpsResponse response = getAck(uart, 0x06, 0x08, 750);
if (response == GpsResponse::None) {
LOG_W(TAG, "No GNSS Module");
return GpsModel::Unknown;
} else if (response == GpsResponse::FrameErrors) {
LOG_W(TAG, "UBlox Frame Errors");
}
uint8_t buffer[256];
memset(buffer, 0, sizeof(buffer));
uint8_t _message_MONVER[8] = {
0xB5, 0x62, // Sync message for UBX protocol
0x0A, 0x04, // Message class and ID (UBX-MON-VER)
0x00, 0x00, // Length of payload (we're asking for an answer, so no payload)
0x00, 0x00 // Checksum
};
// Get Ublox gnss module hardware and software info
checksum(_message_MONVER, sizeof(_message_MONVER));
uart_controller_flush_input(uart);
uart_controller_write_bytes(uart, _message_MONVER, sizeof(_message_MONVER), 500);
uint16_t ack_response_len = getAck(uart, buffer, sizeof(buffer), 0x0A, 0x04, 1200);
if (ack_response_len) {
uint16_t position = 0;
for (char& i: ublox_info.swVersion) {
i = buffer[position];
position++;
}
for (char& i: ublox_info.hwVersion) {
i = buffer[position];
position++;
}
while (ack_response_len >= position + 30) {
for (int i = 0; i < 30; i++) {
ublox_info.extension[ublox_info.extensionNo][i] = buffer[position];
position++;
}
ublox_info.extensionNo++;
if (ublox_info.extensionNo > 9)
break;
}
LOG_I(TAG, "Module Info:");
LOG_I(TAG, "Soft version: %s", ublox_info.swVersion);
LOG_I(TAG, "Hard version: %s", ublox_info.hwVersion);
LOG_I(TAG, "Extensions: %u", ublox_info.extensionNo);
for (int i = 0; i < ublox_info.extensionNo; i++) {
LOG_I(TAG, " %s", ublox_info.extension[i]);
}
memset(buffer, 0, sizeof(buffer));
// tips: extensionNo field is 0 on some 6M GNSS modules
for (int i = 0; i < ublox_info.extensionNo; ++i) {
if (!strncmp(ublox_info.extension[i], "MOD=", 4)) {
strncpy((char*)buffer, &(ublox_info.extension[i][4]), sizeof(buffer));
} else if (!strncmp(ublox_info.extension[i], "PROTVER", 7)) {
char* ptr = nullptr;
memset(buffer, 0, sizeof(buffer));
strncpy((char*)buffer, &(ublox_info.extension[i][8]), sizeof(buffer));
LOG_I(TAG, "Protocol Version: %s", (char*)buffer);
if (strlen((char*)buffer)) {
ublox_info.protocol_version = strtoul((char*)buffer, &ptr, 10);
LOG_I(TAG, "ProtVer=%u", ublox_info.protocol_version);
} else {
ublox_info.protocol_version = 0;
}
}
}
#define DETECTED_MESSAGE "%s detected, using %s Module"
if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6");
return GpsModel::UBLOX6;
} else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7");
return GpsModel::UBLOX7;
} else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8");
return GpsModel::UBLOX8;
} else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9");
return GpsModel::UBLOX9;
} else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) {
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10");
return GpsModel::UBLOX10;
}
}
return GpsModel::Unknown;
}
bool init(::Device* uart, GpsModel model) {
LOG_I(TAG, "U-blox init");
switch (model) {
case GpsModel::UBLOX6:
return initUblox6(uart);
case GpsModel::UBLOX7:
case GpsModel::UBLOX8:
case GpsModel::UBLOX9:
return initUblox789(uart, model);
case GpsModel::UBLOX10:
return initUblox10(uart);
default:
LOG_E(TAG, "Unknown or unsupported U-blox model");
return false;
}
}
bool initUblox10(::Device* uart) {
uint8_t buffer[256];
kernel::delayMillis(1000);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_RAM, "disable NMEA messages in M10 RAM", 300);
kernel::delayMillis(750);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_NMEA_BBR, "disable NMEA messages in M10 BBR", 300);
kernel::delayMillis(750);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_RAM, "disable Info messages for M10 GPS RAM", 300);
kernel::delayMillis(750);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_TXT_INFO_BBR, "disable Info messages for M10 GPS BBR", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_RAM, "enable powersave for M10 GPS RAM", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_PM_BBR, "enable powersave for M10 GPS BBR", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_RAM, "enable jam detection M10 GPS RAM", 300);
kernel::delayMillis(750);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ITFM_BBR, "enable jam detection M10 GPS BBR", 300);
kernel::delayMillis(750);
// Here is where the init commands should go to do further M10 initialization.
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_RAM, "disable SBAS M10 GPS RAM", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_DISABLE_SBAS_BBR, "disable SBAS M10 GPS BBR", 300);
kernel::delayMillis(750); // will cause a receiver restart so wait a bit
// Done with initialization
// Enable wanted NMEA messages in BBR layer so they will survive a periodic sleep
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_BBR, "enable messages for M10 GPS BBR", 300);
kernel::delayMillis(750);
// Enable wanted NMEA messages in RAM layer
SEND_UBX_PACKET(uart, buffer, 0x06, 0x8A, _message_VALSET_ENABLE_NMEA_RAM, "enable messages for M10 GPS RAM", 500);
kernel::delayMillis(750);
// As the M10 has no flash, the best we can do to preserve the config is to set it in RAM and BBR.
// BBR will survive a restart, and power off for a while, but modules with small backup
// batteries or super caps will not retain the config for a long power off time.
auto packet_size = makePacket(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
bool initUblox789(::Device* uart, GpsModel model) {
uint8_t buffer[256];
if (model == GpsModel::UBLOX7) {
LOG_D(TAG, "Set GPS+SBAS");
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer);
uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS);
} else { // 8,9
auto msglen = makePacket(0x06, 0x3e, _message_GNSS_8, sizeof(_message_GNSS_8), buffer);
uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS);
}
if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) {
// It's not critical if the module doesn't acknowledge this configuration.
LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?");
} else {
if (model == GpsModel::UBLOX7) {
LOG_I(TAG, "GPS+SBAS configured");
} else { // 8,9
LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured");
}
// Documentation say, we need wait at least 0.5s after reconfiguration of GNSS module, before sending next
// commands for the M8 it tends to be more. 1 sec should be enough
kernel::delayMillis(1000);
}
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500);
if (model == GpsModel::UBLOX8) { // 8
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_8, "enable interference resistance", 500);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5_8, "configure NAVX5_8 settings", 500);
} else { // 6,7,9
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_6_7, "enable interference resistance", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5, "configure NAVX5 settings", 500);
}
// Turn off unwanted NMEA messages, set update rate
SEND_UBX_PACKET(uart, buffer, 0x06, 0x08, _message_1HZ, "set GPS update rate", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GLL, "disable NMEA GLL", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSA, "enable NMEA GSA", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSV, "disable NMEA GSV", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_VTG, "disable NMEA VTG", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_RMC, "enable NMEA RMC", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GGA, "enable NMEA GGA", 500);
if (ublox_info.protocol_version >= 18) {
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x86, _message_PMS, "enable powersave for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
// For M8 we want to enable NMEA version 4.10 so we can see the additional satellites.
if (model == GpsModel::UBLOX8) {
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x17, _message_NMEA, "enable NMEA 4.10", 500);
}
} else {
SEND_UBX_PACKET(uart, buffer, 0x06, 0x11, _message_CFG_RXM_PSM, "enable powersave mode for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
}
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
bool initUblox6(::Device* uart) {
uint8_t buffer[256];
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x02, _message_DISABLE_TXT_INFO, "disable text info messages", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x39, _message_JAM_6_7, "enable interference resistance", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x23, _message_NAVX5, "configure NAVX5 settings", 500);
// Turn off unwanted NMEA messages, set update rate
SEND_UBX_PACKET(uart, buffer, 0x06, 0x08, _message_1HZ, "set GPS update rate", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GLL, "disable NMEA GLL", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSA, "enable NMEA GSA", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GSV, "disable NMEA GSV", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_VTG, "disable NMEA VTG", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_RMC, "enable NMEA RMC", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_GGA, "enable NMEA GGA", 500);
uart_controller_flush_input(uart);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x11, _message_CFG_RXM_ECO, "enable powersave ECO mode for Neo-6", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x3B, _message_CFG_PM2, "enable powersave details for GPS", 500);
SEND_UBX_PACKET(uart, buffer, 0x06, 0x01, _message_AID, "disable UBX-AID", 500);
auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer);
uart_controller_write_bytes(uart, buffer, packet_size, 2000);
if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) {
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOG_I(TAG, "GNSS module config saved!");
}
return true;
}
} // namespace tt::hal::gps::ublox
-81
View File
@@ -1,81 +0,0 @@
#include "Tactility/hal/i2c/I2cDevice.h"
#include <cstdint>
namespace tt::hal::i2c {
bool I2cDevice::read(uint8_t* data, size_t dataSize, TickType_t timeout) {
return i2c_controller_read(controller, address, data, dataSize, timeout) == ERROR_NONE;
}
bool I2cDevice::write(const uint8_t* data, uint16_t dataSize, TickType_t timeout) {
return i2c_controller_write(controller, address, data, dataSize, timeout) == ERROR_NONE;
}
bool I2cDevice::writeRead(const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout) {
return i2c_controller_write_read(controller, address, writeData, writeDataSize, readData, readDataSize, timeout) == ERROR_NONE;
}
bool I2cDevice::writeRegister(uint8_t reg, const uint8_t* data, uint16_t dataSize, TickType_t timeout) {
return i2c_controller_write_register(controller, address, reg, data, dataSize, timeout) == ERROR_NONE;
}
bool I2cDevice::readRegister12(uint8_t reg, float& out) const {
std::uint8_t data[2] = {0};
if (i2c_controller_read_register(controller, address, reg, data, 2, DEFAULT_TIMEOUT) == ERROR_NONE) {
out = (data[0] & 0x0F) << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister14(uint8_t reg, float& out) const {
std::uint8_t data[2] = {0};
if (i2c_controller_read_register(controller, address, reg, data, 2, DEFAULT_TIMEOUT) == ERROR_NONE) {
out = (data[0] & 0x3F) << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister16(uint8_t reg, uint16_t& out) const {
std::uint8_t data[2] = {0};
if (i2c_controller_read_register(controller, address, reg, data, 2, DEFAULT_TIMEOUT) == ERROR_NONE) {
out = data[0] << 8 | data[1];
return true;
} else {
return false;
}
}
bool I2cDevice::readRegister8(uint8_t reg, uint8_t& result) const {
return i2c_controller_write_read(controller, address, &reg, 1, &result, 1, DEFAULT_TIMEOUT) == ERROR_NONE;
}
bool I2cDevice::writeRegister8(uint8_t reg, uint8_t value) const {
return i2c_controller_write_register(controller, address, reg, &value, 1, DEFAULT_TIMEOUT) == ERROR_NONE;
}
bool I2cDevice::bitOn(uint8_t reg, uint8_t bitmask) const {
uint8_t state;
if (readRegister8(reg, state)) {
state |= bitmask;
return writeRegister8(reg, state);
} else {
return false;
}
}
bool I2cDevice::bitOff(uint8_t reg, uint8_t bitmask) const {
uint8_t state;
if (readRegister8(reg, state)) {
state &= ~bitmask;
return writeRegister8(reg, state);
} else {
return false;
}
}
} // namespace tt::hal::i2c
-172
View File
@@ -1,172 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <Tactility/hal/power/PowerDevice.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/power_supply.h>
#include <format>
namespace tt::hal::power {
#define GET_POWER_DEVICE(device) (static_cast<PowerDevice*>(device_get_driver_data(device)))
static PowerDevice::MetricType toMetricType(PowerSupplyProperty property) {
switch (property) {
case POWER_SUPPLY_PROP_IS_CHARGING:
return PowerDevice::MetricType::IsCharging;
case POWER_SUPPLY_PROP_CURRENT:
return PowerDevice::MetricType::Current;
case POWER_SUPPLY_PROP_VOLTAGE:
return PowerDevice::MetricType::BatteryVoltage;
case POWER_SUPPLY_PROP_CAPACITY:
default:
return PowerDevice::MetricType::ChargeLevel;
}
}
static int toIntValue(PowerDevice::MetricType type, const PowerDevice::MetricData& data) {
switch (type) {
case PowerDevice::MetricType::IsCharging:
return data.valueAsBool ? 1 : 0;
case PowerDevice::MetricType::Current:
return data.valueAsInt32;
case PowerDevice::MetricType::BatteryVoltage:
return static_cast<int>(data.valueAsUint32);
case PowerDevice::MetricType::ChargeLevel:
default:
return data.valueAsUint8;
}
}
static bool apiSupportsProperty(::Device* device, PowerSupplyProperty property) {
return GET_POWER_DEVICE(device)->supportsMetric(toMetricType(property));
}
static error_t apiGetProperty(::Device* device, PowerSupplyProperty property, PowerSupplyPropertyValue* outValue) {
auto* power_device = GET_POWER_DEVICE(device);
auto metric_type = toMetricType(property);
if (!power_device->supportsMetric(metric_type)) {
return ERROR_NOT_SUPPORTED;
}
PowerDevice::MetricData data;
if (!power_device->getMetric(metric_type, data)) {
return ERROR_NOT_FOUND;
}
outValue->int_value = toIntValue(metric_type, data);
return ERROR_NONE;
}
static bool apiSupportsChargeControl(::Device* device) {
return GET_POWER_DEVICE(device)->supportsChargeControl();
}
static bool apiIsAllowedToCharge(::Device* device) {
return GET_POWER_DEVICE(device)->isAllowedToCharge();
}
static error_t apiSetAllowedToCharge(::Device* device, bool allowed) {
auto* power_device = GET_POWER_DEVICE(device);
if (!power_device->supportsChargeControl()) {
return ERROR_NOT_SUPPORTED;
}
power_device->setAllowedToCharge(allowed);
return ERROR_NONE;
}
static bool apiSupportsQuickCharge(::Device* device) {
return GET_POWER_DEVICE(device)->supportsQuickCharge();
}
static bool apiIsQuickChargeEnabled(::Device* device) {
return GET_POWER_DEVICE(device)->isQuickChargeEnabled();
}
static error_t apiSetQuickChargeEnabled(::Device* device, bool enabled) {
auto* power_device = GET_POWER_DEVICE(device);
if (!power_device->supportsQuickCharge()) {
return ERROR_NOT_SUPPORTED;
}
power_device->setQuickChargeEnabled(enabled);
return ERROR_NONE;
}
static bool apiSupportsPowerOff(::Device* device) {
return GET_POWER_DEVICE(device)->supportsPowerOff();
}
static error_t apiPowerOff(::Device* device) {
auto* power_device = GET_POWER_DEVICE(device);
if (!power_device->supportsPowerOff()) {
return ERROR_NOT_SUPPORTED;
}
power_device->powerOff();
return ERROR_NONE;
}
static error_t startDevice(::Device*) { return ERROR_NONE; }
static error_t stopDevice(::Device*) { return ERROR_NONE; }
static PowerSupplyApi powerSupplyApi {
.supports_property = apiSupportsProperty,
.get_property = apiGetProperty,
.supports_charge_control = apiSupportsChargeControl,
.is_allowed_to_charge = apiIsAllowedToCharge,
.set_allowed_to_charge = apiSetAllowedToCharge,
.supports_quick_charge = apiSupportsQuickCharge,
.is_quick_charge_enabled = apiIsQuickChargeEnabled,
.set_quick_charge_enabled = apiSetQuickChargeEnabled,
.supports_power_off = apiSupportsPowerOff,
.power_off = apiPowerOff,
};
static const char* powerSupplyCompatible[] = { "hal-power-device", nullptr };
static Driver powerSupplyDriver {
.name = "hal-power-device",
.compatible = powerSupplyCompatible,
.start_device = startDevice,
.stop_device = stopDevice,
.api = &powerSupplyApi,
.device_type = &POWER_SUPPLY_TYPE,
.owner = nullptr,
.internal = nullptr,
};
/** Registers the "hal-power-device" driver with the kernel on first use. */
static Driver& getPowerSupplyDriver() {
static const bool registered = [] {
check(driver_construct_add(&powerSupplyDriver) == ERROR_NONE);
return true;
}();
(void)registered;
return powerSupplyDriver;
}
void PowerDevice::createPowerSupplyDevice() {
kernelDeviceName = std::format("power-supply-{}", getId());
kernelDevice.name = kernelDeviceName.c_str();
check(device_construct(&kernelDevice) == ERROR_NONE);
check(device_add(&kernelDevice) == ERROR_NONE);
device_set_driver(&kernelDevice, &getPowerSupplyDriver());
check(device_start(&kernelDevice) == ERROR_NONE);
device_set_driver_data(&kernelDevice, this);
}
void PowerDevice::destroyPowerSupplyDevice() {
device_set_driver_data(&kernelDevice, nullptr);
check(device_stop(&kernelDevice) == ERROR_NONE);
check(device_remove(&kernelDevice) == ERROR_NONE);
check(device_destruct(&kernelDevice) == ERROR_NONE);
}
PowerDevice::PowerDevice() {
createPowerSupplyDevice();
}
PowerDevice::~PowerDevice() {
destroyPowerSupplyDevice();
}
}
+1 -35
View File
@@ -1,43 +1,9 @@
#include <Tactility/lvgl/LvglSync.h>
#include <tactility/device.h>
#include <tactility/drivers/sdcard.h>
#include <tactility/filesystem/file_system.h>
#include <string>
#include <memory>
namespace tt::hal::sdcard {
std::shared_ptr<Lock> findSdCardLock(const std::string& path) {
struct Ctx {
const std::string& path;
std::shared_ptr<Lock> result;
};
Ctx ctx = { path, nullptr };
file_system_for_each(&ctx, [](FileSystem* fs, void* context) {
auto* c = static_cast<Ctx*>(context);
char mount_path[64];
if (file_system_get_path(fs, mount_path, sizeof(mount_path)) != ERROR_NONE) return true;
if (!c->path.starts_with(mount_path)) return true;
auto* owner = file_system_get_owner(fs);
if (owner != nullptr) {
// Check for I2C controller: if it has more than 2 children, assume it's the display
// TODO: Improve this
auto* parent = device_get_parent(owner);
if (parent != nullptr && device_get_child_count(parent) >= 2) {
c->result = lvgl::getSyncLock();
}
}
return false;
});
return ctx.result;
}
void mountAll() {
void startAll() {
device_for_each_of_type(&SDCARD_TYPE, nullptr, [](::Device* device, void*) -> bool {
if (!device_is_ready(device)) {
if (device_start(device) != ERROR_NONE) {
@@ -1,24 +0,0 @@
// SPDX-License-Identifier: Apache-2.0
#include <Tactility/hal/touch/KernelTouchDriver.h>
#include <tactility/drivers/pointer.h>
#include <cassert>
namespace tt::hal::touch {
// Bus reads are expected to complete quickly; bound the wait so a stalled controller can't block the LVGL indev poll.
static constexpr TickType_t READ_TIMEOUT = pdMS_TO_TICKS(10);
KernelTouchDriver::KernelTouchDriver(::Device* device) : device(device) {
assert(device_get_type(device) == &POINTER_TYPE);
}
bool KernelTouchDriver::getTouchedPoints(uint16_t* x, uint16_t* y, uint16_t* strength, uint8_t* pointCount, uint8_t maxPointCount) {
if (pointer_read_data(device, READ_TIMEOUT) != ERROR_NONE) {
return false;
}
return pointer_get_touched_points(device, x, y, strength, pointCount, maxPointCount);
}
}
-205
View File
@@ -1,205 +0,0 @@
#include <Tactility/hal/Configuration.h>
#include <Tactility/hal/encoder/EncoderDevice.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/keyboard/KeyboardDevice.h>
#include <Tactility/hal/touch/TouchDevice.h>
#include <Tactility/lvgl/Keyboard.h>
#include <Tactility/lvgl/Lvgl.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/settings/DisplaySettings.h>
#include <Tactility/settings/TouchCalibrationSettings.h>
#include <tactility/device.h>
#include <tactility/drivers/backlight.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
#include <tactility/lvgl_pointer.h>
#include <tactility/module.h>
#include <lvgl.h>
namespace tt::lvgl {
constexpr auto* TAG = "LVGL";
bool isStarted() {
return module_is_started(&lvgl_module);
}
void attachDevices() {
LOG_I(TAG, "Adding devices");
auto lock = getSyncLock()->asScopedLock();
lock.lock();
// Start displays (their related touch devices start automatically within)
LOG_I(TAG, "Start displays");
auto hal_displays= hal::findDevices<hal::display::DisplayDevice>(hal::Device::Type::Display);
for (const auto& display: hal_displays) {
if (display->supportsLvgl()) {
if (display->startLvgl()) {
LOG_I(TAG, "Started %s", display->getName().c_str());
} else {
LOG_E(TAG, "Start failed for %s", display->getName().c_str());
}
}
}
auto* primary_lvgl_display = lv_disp_get_default();
if (primary_lvgl_display != nullptr) {
LOG_I(TAG, "Set default display rotation");
auto settings = settings::display::loadOrGetDefault();
lv_display_rotation_t rotation = settings::display::toLvglDisplayRotation(settings.orientation);
if (rotation != lv_display_get_rotation(primary_lvgl_display)) {
lv_display_set_rotation(primary_lvgl_display, rotation);
}
}
// Start touch
if (primary_lvgl_display != nullptr) {
LOG_I(TAG, "Start touch devices");
auto touch_devices = hal::findDevices<hal::touch::TouchDevice>(hal::Device::Type::Touch);
for (const auto& touch_device: touch_devices) {
// Start any touch devices that haven't been started yet
if (touch_device->supportsLvgl() && touch_device->getLvglIndev() == nullptr) {
if (touch_device->startLvgl(primary_lvgl_display)) {
LOG_I(TAG, "Started %s", touch_device->getName().c_str());
} else {
LOG_E(TAG, "Start failed for %s", touch_device->getName().c_str());
}
}
}
// Apply touch calibration (kernel POINTER_TYPE model only - see tactility/lvgl_pointer.h)
LOG_I(TAG, "Apply touch calibration");
auto touch_calibration_settings = settings::touch::loadOrGetDefault();
if (touch_calibration_settings.enabled && settings::touch::isValid(touch_calibration_settings)) {
auto* pointer_indev = lvgl_pointer_get_default();
if (pointer_indev != nullptr) {
struct LvglPointerCalibration calibration = {
.x_min = touch_calibration_settings.xMin,
.x_max = touch_calibration_settings.xMax,
.y_min = touch_calibration_settings.yMin,
.y_max = touch_calibration_settings.yMax,
};
if (lvgl_pointer_set_calibration(pointer_indev, &calibration) != ERROR_NONE) {
LOG_E(TAG, "Failed to apply saved touch calibration");
}
}
}
// Start keyboards
LOG_I(TAG, "Start keyboards");
auto keyboards = hal::findDevices<hal::keyboard::KeyboardDevice>(hal::Device::Type::Keyboard);
for (const auto& keyboard: keyboards) {
if (keyboard->isAttached()) {
if (keyboard->startLvgl(primary_lvgl_display)) {
lv_indev_t* keyboard_indev = keyboard->getLvglIndev();
hardware_keyboard_set_indev(keyboard_indev);
LOG_I(TAG, "Started %s", keyboard->getName().c_str());
} else {
LOG_E(TAG, "Start failed for %s", keyboard->getName().c_str());
}
}
}
// Start encoders
LOG_I(TAG, "Start encoders");
auto encoders = hal::findDevices<hal::encoder::EncoderDevice>(hal::Device::Type::Encoder);
for (const auto& encoder: encoders) {
if (encoder->startLvgl(primary_lvgl_display)) {
LOG_I(TAG, "Started %s", encoder->getName().c_str());
} else {
LOG_E(TAG, "Start failed for %s", encoder->getName().c_str());
}
}
}
// Restart services
// We search for the manifest first, because during the initial start() during boot
// the service won't be registered yet.
if (service::findManifestById("Gui") != nullptr) {
if (service::getState("Gui") == SERVICE_STATE_STOPPED) {
service::startService("Gui");
} else {
LOG_E(TAG, "Gui service is not in Stopped state");
}
}
// We search for the manifest first, because during the initial start() during boot
// the service won't be registered yet.
if (service::findManifestById("Statusbar") != nullptr) {
if (service::getState("Statusbar") == SERVICE_STATE_STOPPED) {
service::startService("Statusbar");
} else {
LOG_E(TAG, "Statusbar service is not in Stopped state");
}
}
}
void detachDevices() {
LOG_I(TAG, "Removing devices");
auto lock = getSyncLock()->asScopedLock();
lock.lock();
// Stop services that highly depend on LVGL
service::stopService("Statusbar");
service::stopService("Gui");
// Stop keyboards
LOG_I(TAG, "Stopping keyboards");
auto keyboards = hal::findDevices<hal::keyboard::KeyboardDevice>(hal::Device::Type::Keyboard);
for (auto keyboard: keyboards) {
if (keyboard->getLvglIndev() != nullptr) {
keyboard->stopLvgl();
}
}
// Stop touch
LOG_I(TAG, "Stopping touch");
// The display generally stops their own touch devices, but we'll clean up anything that didn't
auto touch_devices = hal::findDevices<hal::touch::TouchDevice>(hal::Device::Type::Touch);
for (auto touch_device: touch_devices) {
if (touch_device->getLvglIndev() != nullptr) {
touch_device->stopLvgl();
}
}
// Stop encoders
LOG_I(TAG, "Stopping encoders");
// The display generally stops their own touch devices, but we'll clean up anything that didn't
auto encoder_devices = hal::findDevices<hal::encoder::EncoderDevice>(hal::Device::Type::Encoder);
for (auto encoder_device: encoder_devices) {
if (encoder_device->getLvglIndev() != nullptr) {
encoder_device->stopLvgl();
}
}
// Stop displays (and their touch devices)
LOG_I(TAG, "Stopping displays");
auto displays = hal::findDevices<hal::display::DisplayDevice>(hal::Device::Type::Display);
for (auto display: displays) {
if (display->supportsLvgl() && display->getLvglDisplay() != nullptr && !display->stopLvgl()) {
LOG_E(TAG, "Failed to detach display from LVGL");
}
}
}
void start() {
check(module_start(&lvgl_module) == ERROR_NONE);
}
void stop() {
check(module_stop(&lvgl_module) == ERROR_NONE);
}
} // namespace
+3 -1
View File
@@ -3,6 +3,8 @@
#include <Tactility/Tactility.h>
#include <Tactility/lvgl/Toolbar.h>
#include "tactility/drivers/pointer.h"
#include <Tactility/lvgl/Spinner.h>
#include <Tactility/service/loader/Loader.h>
@@ -154,7 +156,7 @@ lv_obj_t* toolbar_create(lv_obj_t* parent, const std::string& title) {
// If we don't have a touch device, we assume there's some other kind of input like a keyboard, an encoder or button control
// In that scenario we want to automatically have the close button selected so the user doesn't have to press the widget selection
// an extra time for every screen.
if (!hal::hasDevice(hal::Device::Type::Touch)) {
if (!device_has_active_by_type(&POINTER_TYPE)) {
lv_group_focus_obj(toolbar->close_button);
}
+2 -1
View File
@@ -70,7 +70,8 @@ void download(
auto bytes_left = client->getContentLength();
auto lock = file::getLock(downloadFilePath)->asScopedLock();
auto lockable = file::getLock(downloadFilePath);
auto lock = lockable->asScopedLock();
lock.lock();
LOG_I(TAG, "opening %s", downloadFilePath.c_str());
auto* file = fopen(downloadFilePath.c_str(), "wb");
+2 -1
View File
@@ -186,7 +186,8 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP
char buffer[BUFFER_SIZE];
size_t bytes_received = 0;
auto lock = file::getLock(filePath)->asScopedLock();
auto lockable = file::getLock(filePath);
auto lock = lockable->asScopedLock();
lock.lock();
auto* file = fopen(filePath.c_str(), "wb");
@@ -2,32 +2,28 @@
#include <Tactility/service/displayidle/DisplayIdleService.h>
#include "Screensaver.h"
#include "BouncingBallsScreensaver.h"
#include "MatrixRainScreensaver.h"
#include "MystifyScreensaver.h"
#include "Screensaver.h"
#include "StackChanScreensaver.h"
#include <tactility/log.h>
#include <Tactility/CoreDefines.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h>
#include <cstdlib>
#include <ctime>
#include <tactility/log.h>
#include <tactility/drivers/display.h>
#include <tactility/drivers/backlight.h>
#include <tactility/lvgl_module.h>
namespace tt::service::displayidle {
constexpr auto* TAG = "DisplayIdle";
constexpr uint32_t kWakeActivityThresholdMs = 100;
static std::shared_ptr<hal::display::DisplayDevice> getDisplay() {
return hal::findFirstDevice<hal::display::DisplayDevice>(hal::Device::Type::Display);
}
void DisplayIdleService::stopScreensaverCb(lv_event_t* e) {
auto* self = static_cast<DisplayIdleService*>(lv_event_get_user_data(e));
lv_event_stop_bubbling(e);
@@ -35,8 +31,34 @@ void DisplayIdleService::stopScreensaverCb(lv_event_t* e) {
lv_display_trigger_activity(nullptr);
}
static void setBacklightBrightness(uint8_t brightness) {
::Device* display;
if (device_get_first_active_by_type(&DISPLAY_TYPE, &display) == ERROR_NONE) {
::Device* backlight;
if (display_get_backlight(display, &backlight) == ERROR_NONE) {
device_get(backlight);
backlight_set_brightness(backlight, brightness);
device_put(backlight);
}
device_put(display);
}
}
static bool hasDisplayWithBacklight() {
::Device* display;
bool result = false;
if (device_get_first_active_by_type(&DISPLAY_TYPE, &display) == ERROR_NONE) {
::Device* backlight;
if (display_get_backlight(display, &backlight) == ERROR_NONE) {
result = true;
}
device_put(display);
}
return result;
}
void DisplayIdleService::stopScreensaver() {
if (!lvgl::lock(100)) {
if (!lvgl_try_lock(100)) {
// Lock failed - keep flag set to retry on next tick
return;
}
@@ -52,7 +74,7 @@ void DisplayIdleService::stopScreensaver() {
lv_obj_delete(screensaverOverlay);
screensaverOverlay = nullptr;
}
lvgl::unlock();
lvgl_unlock();
stopScreensaverRequested.store(false, std::memory_order_relaxed);
// Reset auto-off state
@@ -60,10 +82,10 @@ void DisplayIdleService::stopScreensaver() {
backlightOff = false;
// Restore backlight if display was dimmed
auto display = getDisplay();
if (display && wasDimmed) {
display->setBacklightDuty(restoreDuty);
if (wasDimmed) {
setBacklightBrightness(restoreDuty);
}
displayDimmed = wasDimmed ? false : displayDimmed;
}
@@ -124,11 +146,11 @@ void DisplayIdleService::updateScreensaver() {
}
void DisplayIdleService::tick() {
if (!lvgl::lock(100)) {
if (!lvgl_try_lock(100)) {
return;
}
if (lv_display_get_default() == nullptr) {
lvgl::unlock();
lvgl_unlock();
return;
}
@@ -152,10 +174,7 @@ void DisplayIdleService::tick() {
screensaver->stop();
screensaver.reset();
}
auto display = getDisplay();
if (display) {
display->setBacklightDuty(0);
}
setBacklightBrightness(0);
backlightOff = true;
} else {
updateScreensaver();
@@ -163,7 +182,7 @@ void DisplayIdleService::tick() {
}
}
lvgl::unlock();
lvgl_unlock();
// Check stop request early for faster response
if (stopScreensaverRequested.load(std::memory_order_acquire)) {
@@ -171,23 +190,22 @@ void DisplayIdleService::tick() {
return;
}
auto display = getDisplay();
if (display != nullptr && display->supportsBacklightDuty()) {
if (hasDisplayWithBacklight()) {
if (!cachedDisplaySettings.backlightTimeoutEnabled || cachedDisplaySettings.backlightTimeoutMs == 0) {
if (displayDimmed) {
display->setBacklightDuty(cachedDisplaySettings.backlightDuty);
setBacklightBrightness(cachedDisplaySettings.backlightDuty);
displayDimmed = false;
}
} else {
if (!displayDimmed && inactive_ms >= cachedDisplaySettings.backlightTimeoutMs) {
if (!lvgl::lock(100)) {
if (!lvgl_try_lock(100)) {
return; // Retry on next tick
}
activateScreensaver();
lvgl::unlock();
lvgl_unlock();
// Turn off backlight for "None" screensaver (just black screen)
if (cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::None) {
display->setBacklightDuty(0);
setBacklightBrightness(0);
}
displayDimmed = true;
} else if (displayDimmed && (inactive_ms < kWakeActivityThresholdMs)) {
@@ -231,7 +249,7 @@ void DisplayIdleService::onStop(ServiceContext& service) {
}
void DisplayIdleService::startScreensaver() {
if (!lvgl::lock(100)) {
if (!lvgl_try_lock(100)) {
return;
}
@@ -240,12 +258,11 @@ void DisplayIdleService::startScreensaver() {
cachedDisplaySettings = settings::display::loadOrGetDefault();
activateScreensaver();
lvgl::unlock();
lvgl_unlock();
// Turn off backlight for "None" screensaver
auto display = getDisplay();
if (display && cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::None) {
display->setBacklightDuty(0);
if (hasDisplayWithBacklight() && cachedDisplaySettings.screensaverType == settings::display::ScreensaverType::None) {
setBacklightBrightness(0);
}
displayDimmed = true;
}
@@ -1,119 +0,0 @@
#include <Tactility/file/ObjectFile.h>
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/service/ServicePaths.h>
#include <cstring>
#include <unistd.h>
#include <tactility/log.h>
using tt::hal::gps::GpsDevice;
namespace tt::service::gps {
constexpr auto* TAG = "GpsService";
bool GpsService::getConfigurationFilePath(std::string& output) const {
if (paths == nullptr) {
LOG_E(TAG, "Can't add configuration: service not started");
return false;
}
if (!file::findOrCreateDirectory(paths->getUserDataDirectory(), 0777)) {
LOG_E(TAG, "Failed to find or create path %s", paths->getUserDataDirectory().c_str());
return false;
}
output = paths->getUserDataPath("config.bin");
return true;
}
bool GpsService::getGpsConfigurations(std::vector<hal::gps::GpsConfiguration>& configurations) const {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
// If file does not exist, return empty list
if (access(path.c_str(), F_OK) != 0) {
LOG_W(TAG, "No configurations (file not found: %s)", path.c_str());
return true;
}
LOG_I(TAG, "Reading configuration file %s", path.c_str());
auto reader = file::ObjectFileReader(path, sizeof(hal::gps::GpsConfiguration));
if (!reader.open()) {
LOG_E(TAG, "Failed to open configuration file");
return false;
}
hal::gps::GpsConfiguration configuration;
while (reader.hasNext()) {
if (!reader.readNext(&configuration)) {
LOG_E(TAG, "Failed to read configuration");
reader.close();
return false;
} else {
configurations.push_back(configuration);
}
}
return true;
}
bool GpsService::addGpsConfiguration(hal::gps::GpsConfiguration configuration) {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
auto appender = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, true);
if (!appender.open()) {
LOG_E(TAG, "Failed to open/create configuration file");
return false;
}
if (!appender.write(&configuration)) {
LOG_E(TAG, "Failed to add configuration");
appender.close();
return false;
}
appender.close();
return true;
}
bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration) {
std::string path;
if (!getConfigurationFilePath(path)) {
return false;
}
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
LOG_E(TAG, "Failed to get gps configurations");
return false;
}
auto count = std::erase_if(configurations, [&configuration](auto& item) {
return strcmp(item.uartName, configuration.uartName) == 0 &&
item.baudRate == configuration.baudRate &&
item.model == configuration.model;
});
auto writer = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, false);
if (!writer.open()) {
LOG_E(TAG, "Failed to open configuration file");
return false;
}
for (auto& configuration : configurations) {
writer.write(&configuration);
}
writer.close();
return count > 0;
}
} // namespace tt::service::gps
-259
View File
@@ -1,259 +0,0 @@
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/file/File.h>
#include <Tactility/service/ServicePaths.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h>
#include <tactility/log.h>
using tt::hal::gps::GpsDevice;
namespace tt::service::gps {
constexpr auto* TAG = "GpsService";
extern const ServiceManifest manifest;
constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
return (now - timeInThePast) >= expireTimeInTicks;
}
GpsService::GpsDeviceRecord* GpsService::findGpsRecord(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
auto result = std::views::filter(deviceRecords, [&device](auto& record) {
return record.device.get() == device.get();
});
if (!result.empty()) {
return &result.front();
} else {
return nullptr;
}
}
void GpsService::addGpsDevice(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
GpsDeviceRecord record = {.device = device};
if (getState() == State::On) { // Ignore during OnPending due to risk of data corruption
startGpsDevice(record);
}
deviceRecords.push_back(record);
}
void GpsService::removeGpsDevice(const std::shared_ptr<GpsDevice>& device) {
auto lock = mutex.asScopedLock();
lock.lock();
GpsDeviceRecord* record = findGpsRecord(device);
if (getState() == State::On) { // Ignore during OnPending due to risk of data corruption
stopGpsDevice(*record);
}
std::erase_if(deviceRecords, [&device](auto& reference) {
return reference.device.get() == device.get();
});
}
bool GpsService::onStart(ServiceContext& serviceContext) {
auto lock = mutex.asScopedLock();
lock.lock();
paths = serviceContext.getPaths();
return true;
}
void GpsService::onStop(ServiceContext& serviceContext) {
if (getState() == State::On) {
stopReceiving();
}
}
bool GpsService::startGpsDevice(GpsDeviceRecord& record) {
LOG_I(TAG, "[device %u] starting", (unsigned)record.device->getId());
auto lock = mutex.asScopedLock();
lock.lock();
auto device = record.device;
if (!device->start()) {
LOG_E(TAG, "[device %u] starting failed", (unsigned)record.device->getId());
return false;
}
record.satelliteSubscriptionId = device->subscribeGga([this](hal::Device::Id deviceId, auto& record) {
mutex.lock();
if (record.fix_quality > 0) {
ggaRecord = record;
ggaTime = kernel::getTicks();
}
onGgaSentence(deviceId, record);
mutex.unlock();
});
record.rmcSubscriptionId = device->subscribeRmc([this](hal::Device::Id deviceId, auto& record) {
mutex.lock();
if (record.longitude.value != 0 && record.longitude.scale != 0) {
rmcRecord = record;
rmcTime = kernel::getTicks();
}
onRmcSentence(deviceId, record);
mutex.unlock();
});
return true;
}
bool GpsService::stopGpsDevice(GpsDeviceRecord& record) {
LOG_I(TAG, "[device %u] stopping", (unsigned)record.device->getId());
auto device = record.device;
device->unsubscribeGga(record.satelliteSubscriptionId);
device->unsubscribeRmc(record.rmcSubscriptionId);
record.satelliteSubscriptionId = -1;
record.rmcSubscriptionId = -1;
if (!device->stop()) {
LOG_E(TAG, "[device %u] stopping failed", (unsigned)record.device->getId());
return false;
}
return true;
}
bool GpsService::startReceiving() {
LOG_I(TAG, "Start receiving");
if (getState() != State::Off) {
LOG_E(TAG, "Already receiving");
return false;
}
setState(State::OnPending);
auto lock = mutex.asScopedLock();
lock.lock();
deviceRecords.clear();
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
LOG_E(TAG, "Failed to get GPS configurations");
setState(State::Off);
return false;
}
if (configurations.empty()) {
LOG_E(TAG, "No GPS configurations");
setState(State::Off);
return false;
}
for (const auto& configuration: configurations) {
auto device = std::make_shared<GpsDevice>(configuration);
addGpsDevice(device);
}
// Reset times before starting devices to avoid race with incoming data
rmcTime = 0;
ggaTime = 0;
bool started_one_or_more = false;
for (auto& record: deviceRecords) {
started_one_or_more |= startGpsDevice(record);
}
if (started_one_or_more) {
setState(State::On);
return true;
} else {
setState(State::Off);
return false;
}
}
void GpsService::stopReceiving() {
LOG_I(TAG, "Stop receiving");
setState(State::OffPending);
auto lock = mutex.asScopedLock();
lock.lock();
for (auto& record: deviceRecords) {
stopGpsDevice(record);
}
rmcTime = 0;
ggaTime = 0;
setState(State::Off);
}
void GpsService::onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga) {
LOG_D(TAG, "[device %u] LAT %f LON %f, satellites: %d", (unsigned)deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked);
}
void GpsService::onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc) {
LOG_D(TAG, "[device %u] LAT %f LON %f, speed: %f", (unsigned)deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed));
}
State GpsService::getState() const {
auto lock = stateMutex.asScopedLock();
lock.lock();
return state;
}
void GpsService::setState(State newState) {
auto lock = stateMutex.asScopedLock();
lock.lock();
state = newState;
lock.unlock();
statePubSub->publish(state);
}
bool GpsService::hasCoordinates() const {
auto lock = mutex.asScopedLock();
lock.lock();
return getState() == State::On && rmcTime != 0 && !hasTimeElapsed(kernel::getTicks(), rmcTime, kernel::secondsToTicks(10));
}
bool GpsService::getCoordinates(minmea_sentence_rmc& rmc) const {
if (hasCoordinates()) {
rmc = rmcRecord;
return true;
} else {
return false;
}
}
bool GpsService::getGga(minmea_sentence_gga& gga) const {
auto lock = mutex.asScopedLock();
lock.lock();
if (getState() == State::On && ggaTime != 0 && !hasTimeElapsed(kernel::getTicks(), ggaTime, kernel::secondsToTicks(10))) {
gga = ggaRecord;
return true;
}
return false;
}
std::shared_ptr<GpsService> findGpsService() {
auto service = findServiceById(manifest.id);
assert(service != nullptr);
return std::static_pointer_cast<GpsService>(service);
}
extern const ServiceManifest manifest = {
.id = "Gps",
.createService = create<GpsService>
};
} // namespace tt::service::gps
@@ -1,16 +1,18 @@
#ifdef ESP_PLATFORM
#include <Tactility/CoreDefines.h>
#include <Tactility/hal/keyboard/KeyboardDevice.h>
#include <Tactility/lvgl/LvglSync.h>
#include <display/lv_display.h>
#include <Tactility/Timer.h>
#include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/settings/KeyboardSettings.h>
#include <Tactility/Timer.h>
#include <tactility/device.h>
#include <tactility/drivers/backlight.h>
#include <tactility/drivers/keyboard.h>
#include <tactility/lvgl_module.h>
namespace tt::service::keyboardidle {
@@ -20,18 +22,29 @@ class KeyboardIdleService final : public Service {
bool keyboardDimmed = false;
settings::keyboard::KeyboardSettings cachedKeyboardSettings;
static std::shared_ptr<hal::keyboard::KeyboardDevice> getKeyboard() {
return hal::findFirstDevice<hal::keyboard::KeyboardDevice>(hal::Device::Type::Keyboard);
}
// TODO: This only works for the fist active keyboard. Update it so it works for all keyboards with a backlight.
static Device* getKeyboardBacklight() {
return device_find_by_name("keyboard_backlight");
::Device* keyboard;
if (device_get_first_active_by_type(&KEYBOARD_TYPE, &keyboard) == ERROR_NONE) {
::Device* backlight = nullptr;
keyboard_get_backlight(keyboard, &backlight); // disregard result
device_put(keyboard);
return backlight; // WARNING: did not increase refcount
}
// TODO: Remove after all drivers are migrated
::Device* backlight;
if (device_get_by_name("keyboard_backlight", &backlight) != ERROR_NONE) {
return nullptr;
}
return backlight;
}
void setKeyboardBacklightBrightness(uint8_t brightness) {
Device* backlight = getKeyboardBacklight();
if (backlight != nullptr) {
backlight_set_brightness(backlight, brightness);
device_put(backlight);
}
}
@@ -41,14 +54,16 @@ class KeyboardIdleService final : public Service {
// Query LVGL inactivity once for both checks
uint32_t inactive_ms = 0;
if (lvgl::lock(100)) {
if (lvgl_try_lock(100)) {
inactive_ms = lv_display_get_inactive_time(nullptr);
lvgl::unlock();
lvgl_unlock();
} else {
// Assume it's not used
inactive_ms = 100;
}
// Handle keyboard backlight
auto keyboard = getKeyboard();
if (keyboard != nullptr && keyboard->isAttached()) {
if (device_has_active_by_type(&KEYBOARD_TYPE)) {
// If timeout disabled, ensure backlight restored if we had dimmed it
if (!cachedKeyboardSettings.backlightTimeoutEnabled || cachedKeyboardSettings.backlightTimeoutMs == 0) {
if (keyboardDimmed) {
@@ -89,8 +104,7 @@ public:
timer = nullptr;
}
// Ensure keyboard restored on stop
auto keyboard = getKeyboard();
if (keyboard && keyboardDimmed) {
if (device_has_active_by_type(&KEYBOARD_TYPE) && keyboardDimmed) {
setKeyboardBacklightBrightness(cachedKeyboardSettings.backlightEnabled ? cachedKeyboardSettings.backlightBrightness : 0);
keyboardDimmed = false;
}
@@ -2,30 +2,32 @@
#include <Tactility/Mutex.h>
#include <Tactility/Timer.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/filesystem/file_system.h>
#include <Tactility/lvgl/Lvgl.h>
#include <Tactility/bluetooth/Bluetooth.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServicePaths.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/bluetooth/Bluetooth.h>
#include <tactility/drivers/bluetooth.h>
#include <tactility/drivers/bluetooth_serial.h>
#include <tactility/drivers/bluetooth_midi.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/check.h>
#include <tactility/device.h>
#include <tactility/drivers/bluetooth.h>
#include <tactility/drivers/bluetooth_midi.h>
#include <tactility/drivers/bluetooth_serial.h>
#include <tactility/drivers/power_supply.h>
#include <tactility/drivers/usb_host_hid.h>
#include <tactility/drivers/usb_host_midi.h>
#include <tactility/drivers/usb_host_msc.h>
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/check.h>
#include <tactility/filesystem/file_system.h>
#include <tactility/log.h>
#include <tactility/module.h>
#include <tactility/lvgl_module.h>
#include <tactility/lvgl_icon_statusbar.h>
#include <cstring>
#include <tactility/log.h>
#include <gps/gps.h>
namespace tt::service::statusbar {
@@ -152,8 +154,7 @@ class StatusbarService final : public Service {
}
void updateGpsIcon() {
auto gps_state = gps::findGpsService()->getState();
bool show_icon = (gps_state == gps::State::OnPending) || (gps_state == gps::State::On);
bool show_icon = device_has_active_by_type(&GPS_TYPE);
if (gps_last_state != show_icon) {
if (show_icon) {
lvgl::statusbar_icon_set_image(gps_icon_id, LVGL_ICON_STATUSBAR_LOCATION_ON);
@@ -267,15 +268,15 @@ class StatusbarService final : public Service {
}
void update() {
if (lvgl::isStarted()) {
if (lvgl::lock(100)) {
if (module_is_started(&lvgl_module)) {
if (lvgl_try_lock(100)) {
updateGpsIcon();
updateBluetoothIcon();
updateWifiIcon();
updateSdCardIcon();
updatePowerStatusIcon();
updateUsbIcon();
lvgl::unlock();
lvgl_unlock();
}
}
}
@@ -11,7 +11,6 @@
#include <Tactility/Mutex.h>
#include <Tactility/TactilityConfig.h>
#include <tactility/hal/Device.h>
#include <Tactility/app/AppRegistration.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/App.h>
@@ -3,8 +3,6 @@
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Paths.h>
#include <tactility/hal/Device.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <map>
#include <string>