Replaced Logger usage with LOG_x (#548)

This commit is contained in:
Ken Van Hoeylandt
2026-07-04 23:49:19 +02:00
committed by GitHub
parent ecad2248d9
commit 9d5993930d
162 changed files with 1776 additions and 1842 deletions
+8 -8
View File
@@ -1,16 +1,16 @@
#ifdef ESP_PLATFORM
#include <Tactility/PartitionsEsp.h>
#include <Tactility/Logger.h>
#include <esp_vfs_fat.h>
#include <nvs_flash.h>
#include <tactility/error.h>
#include <tactility/filesystem/file_system.h>
#include <tactility/log.h>
namespace tt {
static const auto LOGGER = Logger("Partitions");
constexpr auto* TAG = "Partitions";
// region file_system stub
@@ -47,7 +47,7 @@ FileSystemApi partition_fs_api = {
// endregion file_system stub
static esp_err_t initNvsFlashSafely() {
LOGGER.info("Init NVS");
LOG_I(TAG, "Init NVS");
esp_err_t result = nvs_flash_init();
if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
@@ -77,7 +77,7 @@ size_t getSectorSize() {
}
bool initPartitionsEsp() {
LOGGER.info("Init partitions");
LOG_I(TAG, "Init partitions");
ESP_ERROR_CHECK(initNvsFlashSafely());
const esp_vfs_fat_mount_config_t mount_config = {
@@ -90,21 +90,21 @@ bool initPartitionsEsp() {
auto system_result = esp_vfs_fat_spiflash_mount_ro("/system", "system", &mount_config);
if (system_result != ESP_OK) {
LOGGER.error("Failed to mount /system ({})", esp_err_to_name(system_result));
LOG_E(TAG, "Failed to mount /system (%s)", esp_err_to_name(system_result));
return false;
}
LOGGER.info("Mounted /system");
LOG_I(TAG, "Mounted /system");
static auto system_fs_data = PartitionFsData("/system");
file_system_add(&partition_fs_api, &system_fs_data);
#ifdef CONFIG_TT_USER_DATA_LOCATION_INTERNAL
auto data_result = esp_vfs_fat_spiflash_mount_rw_wl("/data", "data", &mount_config, &data_wl_handle);
if (data_result != ESP_OK) {
LOGGER.error("Failed to mount /data ({})", esp_err_to_name(data_result));
LOG_E(TAG, "Failed to mount /data (%s)", esp_err_to_name(data_result));
return false;
}
LOGGER.info("Mounted /data");
LOG_I(TAG, "Mounted /data");
static auto data_fs_data = PartitionFsData("/data");
file_system_add(&partition_fs_api, &data_fs_data);
#endif
+18 -18
View File
@@ -1,19 +1,19 @@
#ifdef ESP_PLATFORM
#include <Tactility/Logger.h>
#include <Tactility/Preferences.h>
#include <Tactility/TactilityCore.h>
#include <nvs_flash.h>
#include <tactility/log.h>
namespace tt {
static const auto LOGGER = Logger("Preferences");
constexpr auto* TAG = "Preferences";
bool Preferences::optBool(const std::string& key, bool& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
uint8_t out_number;
@@ -29,7 +29,7 @@ bool Preferences::optBool(const std::string& key, bool& out) const {
bool Preferences::optInt32(const std::string& key, int32_t& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
bool success = nvs_get_i32(handle, key.c_str(), &out) == ESP_OK;
@@ -41,7 +41,7 @@ bool Preferences::optInt32(const std::string& key, int32_t& out) const {
bool Preferences::optInt64(const std::string& key, int64_t& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
bool success = nvs_get_i64(handle, key.c_str(), &out) == ESP_OK;
@@ -53,7 +53,7 @@ bool Preferences::optInt64(const std::string& key, int64_t& out) const {
bool Preferences::optString(const std::string& key, std::string& out) const {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
return false;
} else {
size_t out_size = 256;
@@ -90,13 +90,13 @@ void Preferences::putBool(const std::string& key, bool value) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_u8(handle, key.c_str(), value) != ESP_OK) {
LOGGER.error("Failed to set {}:{}", namespace_, key);
LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str());
} else if (nvs_commit(handle) != ESP_OK) {
LOGGER.error("Failed to commit {}:{}", namespace_, key);
LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
@@ -104,13 +104,13 @@ void Preferences::putInt32(const std::string& key, int32_t value) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_i32(handle, key.c_str(), value) != ESP_OK) {
LOGGER.error("Failed to set {}:{}", namespace_, key);
LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str());
} else if (nvs_commit(handle) != ESP_OK) {
LOGGER.error("Failed to commit {}:{}", namespace_, key);
LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
@@ -118,13 +118,13 @@ void Preferences::putInt64(const std::string& key, int64_t value) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_i64(handle, key.c_str(), value) != ESP_OK) {
LOGGER.error("Failed to set {}:{}", namespace_, key);
LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str());
} else if (nvs_commit(handle) != ESP_OK) {
LOGGER.error("Failed to commit {}:{}", namespace_, key);
LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
@@ -132,13 +132,13 @@ void Preferences::putString(const std::string& key, const std::string& text) {
nvs_handle_t handle;
if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) {
if (nvs_set_str(handle, key.c_str(), text.c_str()) != ESP_OK) {
LOGGER.error("Failed to set {}:{}", namespace_, key.c_str());
LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str());
} else if (nvs_commit(handle) != ESP_OK) {
LOGGER.error("Failed to commit {}:{}", namespace_, key);
LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str());
}
nvs_close(handle);
} else {
LOGGER.error("Failed to open namespace {}", namespace_);
LOG_E(TAG, "Failed to open namespace %s", namespace_);
}
}
+22 -22
View File
@@ -7,10 +7,9 @@
#include <Tactility/Tactility.h>
#include <Tactility/TactilityConfig.h>
#include <Tactility/LogMessages.h>
#include <Tactility/CpuAffinity.h>
#include <Tactility/DispatcherThread.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/MountPoints.h>
#include <Tactility/app/AppManifestParsing.h>
#include <Tactility/app/AppRegistration.h>
@@ -29,6 +28,7 @@
#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>
#ifdef ESP_PLATFORM
@@ -42,7 +42,7 @@
namespace tt {
static auto LOGGER = Logger("Tactility");
constexpr auto* TAG = "Tactility";
static const Configuration* config_instance = nullptr;
static Dispatcher mainDispatcher;
@@ -139,7 +139,7 @@ namespace app {
// List of all apps excluding Boot app (as Boot app calls this function indirectly)
static void registerInternalApps() {
LOGGER.info("Registering internal apps");
LOG_I(TAG, "Registering internal apps");
addAppManifest(app::alertdialog::manifest);
addAppManifest(app::appdetails::manifest);
@@ -210,16 +210,16 @@ static void registerInternalApps() {
}
static void registerInstalledApp(std::string path) {
LOGGER.info("Registering app at {}", path);
LOG_I(TAG, "Registering app at %s", path.c_str());
std::string manifest_path = path + "/manifest.properties";
if (!file::isFile(manifest_path)) {
LOGGER.error("Manifest not found at {}", manifest_path);
LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str());
return;
}
app::AppManifest manifest;
if (!app::parseManifest(manifest_path, manifest)) {
LOGGER.error("Failed to parse manifest at {}", manifest_path);
LOG_E(TAG, "Failed to parse manifest at %s", manifest_path.c_str());
return;
}
@@ -230,7 +230,7 @@ static void registerInstalledApp(std::string path) {
}
static void registerInstalledApps(const std::string& path) {
LOGGER.info("Registering apps from {}", path);
LOG_I(TAG, "Registering apps from %s", path.c_str());
file::listDirectory(path, [&path](const auto& entry) {
auto absolute_path = std::format("{}/{}", path, entry.d_name);
@@ -247,7 +247,7 @@ static void registerInstalledAppsFromFileSystems() {
if (file_system_get_path(fs, path, sizeof(path)) != ERROR_NONE) return true;
const auto app_path = std::format("{}/tactility/app", path);
if (!app_path.starts_with(file::MOUNT_POINT_SYSTEM) && file::isDirectory(app_path)) {
LOGGER.info("Registering apps from {}", app_path);
LOG_I(TAG, "Registering apps from %s", app_path.c_str());
registerInstalledApps(app_path);
}
return true;
@@ -255,7 +255,7 @@ static void registerInstalledAppsFromFileSystems() {
}
static void registerAndStartSecondaryServices() {
LOGGER.info("Registering and starting secondary system services");
LOG_I(TAG, "Registering and starting secondary system services");
addService(service::loader::manifest);
addService(service::gui::manifest);
addService(service::statusbar::manifest);
@@ -272,7 +272,7 @@ static void registerAndStartSecondaryServices() {
}
static void registerAndStartPrimaryServices() {
LOGGER.info("Registering and starting primary system services");
LOG_I(TAG, "Registering and starting primary system services");
addService(service::gps::manifest);
addService(service::wifi::manifest);
#ifdef ESP_PLATFORM
@@ -294,17 +294,17 @@ void createTempDirectory() {
auto lock = file::getLock(data_path)->asScopedLock();
if (lock.lock(1000 / portTICK_PERIOD_MS)) {
if (!file::findOrCreateParentDirectory(temp_path, 0777)) {
LOGGER.error("Failed to create {}", data_path);
LOG_E(TAG, "Failed to create %s", data_path.c_str());
} else if (mkdir(temp_path.c_str(), 0777) == 0) {
LOGGER.info("Created {}", temp_path);
LOG_I(TAG, "Created %s", temp_path.c_str());
} else {
LOGGER.error("Failed to create {}", temp_path);
LOG_E(TAG, "Failed to create %s", temp_path.c_str());
}
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, data_path);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, data_path.c_str());
}
} else {
LOGGER.info("Found existing {}", temp_path);
LOG_I(TAG, "Found existing %s", temp_path.c_str());
}
}
@@ -318,13 +318,13 @@ void registerApps() {
}
void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices[]) {
LOGGER.info("Tactility v{} on {} ({})", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID);
LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID);
assert(config.hardware);
LOGGER.info("Initializing kernel");
LOG_I(TAG, "Initializing kernel");
if (kernel_init(dtsModules, dtsDevices) != ERROR_NONE) {
LOGGER.error("Failed to initialize kernel");
LOG_E(TAG, "Failed to initialize kernel");
return;
}
@@ -363,14 +363,14 @@ void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices
registerAndStartSecondaryServices();
LOGGER.info("Core systems ready");
LOG_I(TAG, "Core systems ready");
LOGGER.info("Starting boot app");
LOG_I(TAG, "Starting boot app");
// The boot app takes care of registering system apps, user services and user apps
addAppManifest(app::boot::manifest);
app::start(app::boot::manifest.appId);
LOGGER.info("Main dispatcher ready");
LOG_I(TAG, "Main dispatcher ready");
while (true) {
mainDispatcher.consume();
}
+26 -26
View File
@@ -5,7 +5,6 @@
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <tactility/hal/Device.h>
#include <Tactility/Logger.h>
#include <Tactility/Paths.h>
#include <cerrno>
@@ -16,21 +15,22 @@
#include <unistd.h>
#include <minitar.h>
#include <tactility/log.h>
namespace tt::app {
static const auto LOGGER = Logger("App");
constexpr auto* TAG = "App";
static bool untarFile(minitar* mp, const minitar_entry* entry, const std::string& destinationPath) {
const auto absolute_path = destinationPath + "/" + entry->metadata.path;
if (!file::findOrCreateDirectory(destinationPath, 0777)) {
LOGGER.error("Can't find or create directory {}", destinationPath.c_str());
LOG_E(TAG, "Can't find or create directory %s", destinationPath.c_str());
return false;
}
// minitar_read_contents(&mp, &entry, file_buffer, entry.metadata.size);
if (!minitar_read_contents_to_file(mp, entry, absolute_path.c_str())) {
LOGGER.error("Failed to write data to {}", absolute_path.c_str());
LOG_E(TAG, "Failed to write data to %s", absolute_path.c_str());
return false;
}
@@ -59,32 +59,32 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath
do {
if (minitar_read_entry(&mp, &entry) == 0) {
LOGGER.info("Extracting {}", entry.metadata.path);
LOG_I(TAG, "Extracting %s", entry.metadata.path);
if (entry.metadata.type == MTAR_DIRECTORY) {
if (!strcmp(entry.metadata.name, ".") || !strcmp(entry.metadata.name, "..") || !strcmp(entry.metadata.name, "/")) continue;
if (!untarDirectory(&entry, destinationPath)) {
LOGGER.error("Failed to create directory {}/{}: {}", destinationPath, entry.metadata.name, strerror(errno));
LOG_E(TAG, "Failed to create directory %s/%s: %s", destinationPath.c_str(), entry.metadata.name, strerror(errno));
success = false;
break;
}
} else if (entry.metadata.type == MTAR_REGULAR) {
if (!untarFile(&mp, &entry, destinationPath)) {
LOGGER.error("Failed to extract file {}: {}", entry.metadata.path, strerror(errno));
LOG_E(TAG, "Failed to extract file %s: %s", entry.metadata.path, strerror(errno));
success = false;
break;
}
} else if (entry.metadata.type == MTAR_SYMLINK) {
LOGGER.error("SYMLINK not supported");
LOG_E(TAG, "SYMLINK not supported");
} else if (entry.metadata.type == MTAR_HARDLINK) {
LOGGER.error("HARDLINK not supported");
LOG_E(TAG, "HARDLINK not supported");
} else if (entry.metadata.type == MTAR_FIFO) {
LOGGER.error("FIFO not supported");
LOG_E(TAG, "FIFO not supported");
} else if (entry.metadata.type == MTAR_BLKDEV) {
LOGGER.error("BLKDEV not supported");
LOG_E(TAG, "BLKDEV not supported");
} else if (entry.metadata.type == MTAR_CHRDEV) {
LOGGER.error("CHRDEV not supported");
LOG_E(TAG, "CHRDEV not supported");
} else {
LOGGER.error("Unknown entry type: {}", static_cast<int>(entry.metadata.type));
LOG_E(TAG, "Unknown entry type: %d", static_cast<int>(entry.metadata.type));
success = false;
break;
}
@@ -96,7 +96,7 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath
void cleanupInstallDirectory(const std::string& path) {
if (!file::deleteRecursively(path)) {
LOGGER.warn("Failed to delete existing installation at {}", path);
LOG_W(TAG, "Failed to delete existing installation at %s", path.c_str());
}
}
@@ -105,16 +105,16 @@ bool install(const std::string& path) {
// the lock with the display. We don't want to lock the display for very long.
auto app_parent_path = getAppInstallPath();
LOGGER.info("Installing app {} to {}", path, app_parent_path);
LOG_I(TAG, "Installing app %s to %s", path.c_str(), app_parent_path.c_str());
auto filename = file::getLastPathSegment(path);
const std::string app_target_path = std::format("{}/{}", app_parent_path, filename);
if (file::isDirectory(app_target_path) && !file::deleteRecursively(app_target_path)) {
LOGGER.warn("Failed to delete {}", app_target_path);
LOG_W(TAG, "Failed to delete %s", app_target_path.c_str());
}
if (!file::findOrCreateDirectory(app_target_path, 0777)) {
LOGGER.info("Failed to create directory {}", app_target_path);
LOG_I(TAG, "Failed to create directory %s", app_target_path.c_str());
return false;
}
@@ -122,9 +122,9 @@ bool install(const std::string& path) {
auto source_path_lock = file::getLock(path)->asScopedLock();
target_path_lock.lock();
source_path_lock.lock();
LOGGER.info("Extracting app from {} to {}", path, app_target_path);
LOG_I(TAG, "Extracting app from %s to %s", path.c_str(), app_target_path.c_str());
if (!untar(path, app_target_path)) {
LOGGER.error("Failed to extract");
LOG_E(TAG, "Failed to extract");
return false;
}
source_path_lock.unlock();
@@ -132,14 +132,14 @@ bool install(const std::string& path) {
auto manifest_path = app_target_path + "/manifest.properties";
if (!file::isFile(manifest_path)) {
LOGGER.error("Manifest not found at {}", manifest_path);
LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str());
cleanupInstallDirectory(app_target_path);
return false;
}
AppManifest manifest;
if (!parseManifest(manifest_path, manifest)) {
LOGGER.warn("Invalid manifest");
LOG_W(TAG, "Invalid manifest");
cleanupInstallDirectory(app_target_path);
return false;
}
@@ -152,7 +152,7 @@ bool install(const std::string& path) {
const std::string renamed_target_path = std::format("{}/{}", app_parent_path, manifest.appId);
if (file::isDirectory(renamed_target_path)) {
if (!file::deleteRecursively(renamed_target_path)) {
LOGGER.warn("Failed to delete existing installation at {}", renamed_target_path);
LOG_W(TAG, "Failed to delete existing installation at %s", renamed_target_path.c_str());
cleanupInstallDirectory(app_target_path);
return false;
}
@@ -163,7 +163,7 @@ bool install(const std::string& path) {
target_path_lock.unlock();
if (!rename_success) {
LOGGER.error(R"(Failed to rename "{}" to "{}")", app_target_path, manifest.appId);
LOG_E(TAG, R"(Failed to rename "%s" to "%s")", app_target_path.c_str(), manifest.appId.c_str());
cleanupInstallDirectory(app_target_path);
return false;
}
@@ -176,7 +176,7 @@ bool install(const std::string& path) {
}
bool uninstall(const std::string& appId) {
LOGGER.info("Uninstalling app {}", appId);
LOG_I(TAG, "Uninstalling app %s", appId.c_str());
// If the app was running, then stop it
if (isRunning(appId)) {
@@ -185,7 +185,7 @@ bool uninstall(const std::string& appId) {
auto app_path = getAppInstallPath(appId);
if (!file::isDirectory(app_path)) {
LOGGER.error("App {} not found at {}", appId, app_path);
LOG_E(TAG, "App %s not found at %s", appId.c_str(), app_path.c_str());
return false;
}
@@ -194,7 +194,7 @@ bool uninstall(const std::string& appId) {
}
if (!removeAppManifest(appId)) {
LOGGER.warn("Failed to remove app {} from registry", appId);
LOG_W(TAG, "Failed to remove app %s from registry", appId.c_str());
}
return true;
+5 -5
View File
@@ -1,16 +1,16 @@
#include <Tactility/app/AppManifestParsing.h>
#include <Tactility/app/AppManifestParsingInternal.h>
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <algorithm>
#include <tactility/log.h>
namespace tt::app {
static const auto LOGGER = Logger("AppManifest");
constexpr auto* TAG = "AppManifest";
constexpr bool validateString(const std::string& value, const std::function<bool(char)>& isValidChar) {
return std::ranges::all_of(value, isValidChar);
@@ -19,7 +19,7 @@ constexpr bool validateString(const std::string& value, const std::function<bool
bool getValueFromManifest(const std::map<std::string, std::string>& map, const std::string& key, std::string& output) {
const auto iterator = map.find(key);
if (iterator == map.end()) {
LOGGER.error("Failed to find {} in manifest", key);
LOG_E(TAG, "Failed to find %s in manifest", key.c_str());
return false;
}
output = iterator->second;
@@ -70,13 +70,13 @@ static bool detectIsV1Format(const std::string& filePath) {
}
bool parseManifest(const std::string& filePath, AppManifest& manifest) {
LOGGER.info("Parsing manifest {}", filePath);
LOG_I(TAG, "Parsing manifest %s", filePath.c_str());
bool is_v1_format = detectIsV1Format(filePath);
std::map<std::string, std::string> properties;
if (!file::loadPropertiesFile(filePath, properties)) {
LOGGER.error("Failed to load manifest at {}", filePath);
LOG_E(TAG, "Failed to load manifest at %s", filePath.c_str());
return false;
}
@@ -1,11 +1,11 @@
#include <Tactility/app/AppManifestParsing.h>
#include <Tactility/app/AppManifestParsingInternal.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::app {
static const auto LOGGER = Logger("AppManifestV1");
constexpr auto* TAG = "AppManifestV1";
bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest& manifest) {
// [manifest]
@@ -16,7 +16,7 @@ bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidManifestVersion(manifest_version)) {
LOGGER.error("Invalid version");
LOG_E(TAG, "Invalid version");
return false;
}
@@ -27,7 +27,7 @@ bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidId(manifest.appId)) {
LOGGER.error("Invalid app id");
LOG_E(TAG, "Invalid app id");
return false;
}
@@ -36,7 +36,7 @@ bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidName(manifest.appName)) {
LOGGER.error("Invalid app name");
LOG_E(TAG, "Invalid app name");
return false;
}
@@ -45,7 +45,7 @@ bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidAppVersionName(manifest.appVersionName)) {
LOGGER.error("Invalid app version name");
LOG_E(TAG, "Invalid app version name");
return false;
}
@@ -55,7 +55,7 @@ bool parseManifestV1(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidAppVersionCode(version_code_string)) {
LOGGER.error("Invalid app version code");
LOG_E(TAG, "Invalid app version code");
return false;
}
@@ -1,11 +1,11 @@
#include <Tactility/app/AppManifestParsing.h>
#include <Tactility/app/AppManifestParsingInternal.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::app {
static const auto LOGGER = Logger("AppManifestV2");
constexpr auto* TAG = "AppManifestV2";
bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest& manifest) {
// manifest
@@ -16,7 +16,7 @@ bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidManifestVersion(manifest_version)) {
LOGGER.error("Invalid version");
LOG_E(TAG, "Invalid version");
return false;
}
@@ -27,7 +27,7 @@ bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidId(manifest.appId)) {
LOGGER.error("Invalid app id");
LOG_E(TAG, "Invalid app id");
return false;
}
@@ -36,7 +36,7 @@ bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidName(manifest.appName)) {
LOGGER.error("Invalid app name");
LOG_E(TAG, "Invalid app name");
return false;
}
@@ -45,7 +45,7 @@ bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidAppVersionName(manifest.appVersionName)) {
LOGGER.error("Invalid app version name");
LOG_E(TAG, "Invalid app version name");
return false;
}
@@ -55,7 +55,7 @@ bool parseManifestV2(const std::map<std::string, std::string>& map, AppManifest&
}
if (!isValidAppVersionCode(version_code_string)) {
LOGGER.error("Invalid app version code");
LOG_E(TAG, "Invalid app version code");
return false;
}
+5 -5
View File
@@ -1,15 +1,15 @@
#include <Tactility/app/AppRegistration.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <unordered_map>
#include <Tactility/file/File.h>
#include <tactility/log.h>
namespace tt::app {
static const auto LOGGER = Logger("AppRegistration");
constexpr auto* TAG = "AppRegistration";
typedef std::unordered_map<std::string, std::shared_ptr<AppManifest>> AppManifestMap;
@@ -17,12 +17,12 @@ static AppManifestMap app_manifest_map;
static Mutex hash_mutex;
void addAppManifest(const AppManifest& manifest) {
LOGGER.info("Registering manifest {}", manifest.appId);
LOG_I(TAG, "Registering manifest %s", manifest.appId.c_str());
hash_mutex.lock();
if (app_manifest_map.contains(manifest.appId)) {
LOGGER.warn("Overwriting existing manifest for {}", manifest.appId);
LOG_W(TAG, "Overwriting existing manifest for %s", manifest.appId.c_str());
}
app_manifest_map[manifest.appId] = std::make_shared<AppManifest>(manifest);
@@ -31,7 +31,7 @@ void addAppManifest(const AppManifest& manifest) {
}
bool removeAppManifest(const std::string& id) {
LOGGER.info("Removing manifest for {}", id);
LOG_I(TAG, "Removing manifest for %s", id.c_str());
auto lock = hash_mutex.asScopedLock();
lock.lock();
+9 -9
View File
@@ -4,17 +4,17 @@
#include <Tactility/app/ElfApp.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <Tactility/Logger.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/StringUtils.h>
#include <esp_elf.h>
#include <string>
#include <tactility/log.h>
#include <utility>
namespace tt::app {
static auto LOGGER = Logger("ElfApp");
constexpr auto* TAG = "ElfApp";
static std::string getErrorCodeString(int error_code) {
switch (error_code) {
@@ -71,7 +71,7 @@ private:
bool startElf() {
const std::string elf_path = std::format("{}/elf/{}.elf", appPath, CONFIG_IDF_TARGET);
LOGGER.info("Starting ELF {}", elf_path);
LOG_I(TAG, "Starting ELF %s", elf_path.c_str());
assert(elfFileData == nullptr);
size_t size = 0;
@@ -85,7 +85,7 @@ private:
if (esp_elf_init(&elf) != ESP_OK) {
lastError = "Failed to initialize";
LOGGER.error("{}", lastError);
LOG_E(TAG, "%s", lastError.c_str());
elfFileData = nullptr;
return false;
}
@@ -94,7 +94,7 @@ private:
if (relocate_result != 0) {
// Note: the result code maps to values from cstdlib's errno.h
lastError = getErrorCodeString(-relocate_result);
LOGGER.error("Application failed to load: {}", lastError);
LOG_E(TAG, "Application failed to load: %s", lastError.c_str());
elfFileData = nullptr;
return false;
}
@@ -104,7 +104,7 @@ private:
if (esp_elf_request(&elf, 0, argc, argv) != ESP_OK) {
lastError = "Executable returned error code";
LOGGER.error("{}", lastError);
LOG_E(TAG, "%s", lastError.c_str());
esp_elf_deinit(&elf);
elfFileData = nullptr;
return false;
@@ -115,7 +115,7 @@ private:
}
void stopElf() {
LOGGER.info("Cleaning up ELF");
LOG_I(TAG, "Cleaning up ELF");
if (shouldCleanupElf) {
esp_elf_deinit(&elf);
@@ -163,7 +163,7 @@ public:
}
void onDestroy(AppContext& appContext) override {
LOGGER.info("Cleaning up app");
LOG_I(TAG, "Cleaning up app");
if (manifest != nullptr) {
if (manifest->onDestroy != nullptr) {
manifest->onDestroy(&appContext, data);
@@ -222,7 +222,7 @@ void setElfAppParameters(
}
std::shared_ptr<App> createElfApp(const std::shared_ptr<AppManifest>& manifest) {
LOGGER.info("createElfApp");
LOG_I(TAG, "createElfApp");
assert(manifest != nullptr);
assert(manifest->appLocation.isExternal());
return std::make_shared<ElfApp>(manifest->appLocation.getPath());
+3 -3
View File
@@ -1,4 +1,3 @@
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
@@ -10,11 +9,12 @@
#include "tactility/drivers/uart_controller.h"
#include <cstring>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::addgps {
static const auto LOGGER = Logger("AddGps");
constexpr auto* TAG = "AddGps";
class AddGpsApp final : public App {
@@ -50,7 +50,7 @@ class AddGpsApp final : public App {
return;
}
LOGGER.info("Saving: uart={}, model={}, baud={}", new_configuration.uartName, (uint32_t)new_configuration.model, new_configuration.baudRate);
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;
@@ -3,10 +3,10 @@
#include "Tactility/lvgl/Toolbar.h"
#include "Tactility/service/loader/Loader.h"
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <lvgl.h>
#include <tactility/log.h>
namespace tt::app::alertdialog {
@@ -18,7 +18,7 @@ namespace tt::app::alertdialog {
#define PARAMETER_ITEM_CONCATENATION_TOKEN ";;"
#define DEFAULT_TITLE ""
static const auto LOGGER = Logger("AlertDialog");
constexpr auto* TAG = "AlertDialog";
extern const AppManifest manifest;
@@ -74,7 +74,7 @@ class AlertDialogApp : public App {
void onButtonClicked(lv_event_t* e) {
auto index = reinterpret_cast<std::size_t>(lv_event_get_user_data(e));
LOGGER.info("Selected item at index {}", index);
LOG_I(TAG, "Selected item at index %d", (int)index);
auto bundle = std::make_unique<Bundle>();
bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, (int32_t)index);
+5 -5
View File
@@ -5,20 +5,20 @@
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Spinner.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Logger.h>
#include <Tactility/network/Http.h>
#include <Tactility/Paths.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <algorithm>
#include <format>
namespace tt::app::apphub {
static const auto LOGGER = Logger("AppHub");
constexpr auto* TAG = "AppHub";
extern const AppManifest manifest;
@@ -57,7 +57,7 @@ class AppHubApp final : public App {
}
void onRefreshSuccess() {
LOGGER.info("Request success");
LOG_I(TAG, "Request success");
auto lock = lvgl::getSyncLock()->asScopedLock();
lock.lock();
@@ -65,7 +65,7 @@ class AppHubApp final : public App {
}
void onRefreshError(const char* error) {
LOGGER.error("Request failed: {}", error);
LOG_E(TAG, "Request failed: %s", error);
auto lock = lvgl::getSyncLock()->asScopedLock();
lock.lock();
@@ -108,7 +108,7 @@ class AppHubApp final : public App {
lv_obj_set_size(list, LV_PCT(100), LV_SIZE_CONTENT);
for (int i = 0; i < entries.size(); i++) {
auto& entry = entries[i];
LOGGER.info("Adding {}", entry.appName.c_str());
LOG_I(TAG, "Adding %s", entry.appName.c_str());
const char* icon = findAppManifestById(entry.appId) != nullptr ? LV_SYMBOL_OK : nullptr;
auto* entry_button = lv_list_add_button(list, icon, entry.appName.c_str());
auto int_as_voidptr = reinterpret_cast<void*>(i);
+7 -6
View File
@@ -1,11 +1,12 @@
#include <Tactility/app/apphub/AppHubEntry.h>
#include <Tactility/file/File.h>
#include <Tactility/json/Reader.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::app::apphub {
static const auto LOGGER = Logger("AppHubJson");
constexpr auto* TAG = "AppHubJson";
static bool parseEntry(const cJSON* object, AppHubEntry& entry) {
const json::Reader reader(object);
@@ -25,21 +26,21 @@ bool parseJson(const std::string& filePath, std::vector<AppHubEntry>& entries) {
auto data = file::readString(filePath);
if (data == nullptr) {
LOGGER.error("Failed to read {}", filePath);
LOG_E(TAG, "Failed to read %s", filePath.c_str());
return false;
}
auto data_ptr = reinterpret_cast<const char*>(data.get());
auto* json = cJSON_Parse(data_ptr);
if (json == nullptr) {
LOGGER.error("Failed to parse {}", filePath);
LOG_E(TAG, "Failed to parse %s", filePath.c_str());
return false;
}
const cJSON* apps_json = cJSON_GetObjectItemCaseSensitive(json, "apps");
if (!cJSON_IsArray(apps_json)) {
cJSON_Delete(json);
LOGGER.error("apps is not an array");
LOG_E(TAG, "apps is not an array");
return false;
}
@@ -49,7 +50,7 @@ bool parseJson(const std::string& filePath, std::vector<AppHubEntry>& entries) {
auto& entry = entries.at(i);
auto* entry_json = cJSON_GetArrayItem(apps_json, i);
if (!parseEntry(entry_json, entry)) {
LOGGER.error("Failed to read entry");
LOG_E(TAG, "Failed to read entry");
cJSON_Delete(json);
return false;
}
@@ -5,18 +5,18 @@
#include <Tactility/file/File.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Logger.h>
#include <Tactility/network/Http.h>
#include <Tactility/Paths.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/StringUtils.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <format>
namespace tt::app::apphubdetails {
static const auto LOGGER = Logger("AppHubDetails");
constexpr auto* TAG = "AppHubDetails";
extern const AppManifest manifest;
@@ -85,7 +85,7 @@ class AppHubDetailsApp final : public App {
}
void uninstallApp() {
LOGGER.info("Uninstall");
LOG_I(TAG, "Uninstall");
lvgl::getSyncLock()->lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
@@ -110,9 +110,9 @@ class AppHubDetailsApp final : public App {
install(temp_file_path);
if (!file::deleteFile(temp_file_path)) {
LOGGER.warn("Failed to remove {}", temp_file_path);
LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str());
} else {
LOGGER.info("Deleted temporary file {}", temp_file_path);
LOG_I(TAG, "Deleted temporary file %s", temp_file_path.c_str());
}
lvgl::getSyncLock()->lock();
@@ -120,18 +120,18 @@ class AppHubDetailsApp final : public App {
lvgl::getSyncLock()->unlock();
},
[temp_file_path](const char* errorMessage) {
LOGGER.error("Download failed: {}", errorMessage);
LOG_E(TAG, "Download failed: %s", errorMessage);
alertdialog::start("Error", "Failed to install app");
if (file::isFile(temp_file_path) && !file::deleteFile(temp_file_path.c_str())) {
LOGGER.warn("Failed to remove {}", temp_file_path);
LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str());
}
}
);
}
void installApp() {
LOGGER.info("Install");
LOG_I(TAG, "Install");
lvgl::getSyncLock()->lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
@@ -141,15 +141,15 @@ class AppHubDetailsApp final : public App {
}
void updateApp() {
LOGGER.info("Update");
LOG_I(TAG, "Update");
lvgl::getSyncLock()->lock();
lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN);
lvgl::getSyncLock()->unlock();
LOGGER.info("Removing previous version");
LOG_I(TAG, "Removing previous version");
uninstall(entry.appId);
LOGGER.info("Installing new version");
LOG_I(TAG, "Installing new version");
doInstall();
}
@@ -175,13 +175,13 @@ public:
void onCreate(AppContext& appContext) override {
auto parameters = appContext.getParameters();
if (parameters == nullptr) {
LOGGER.error("No parameters");
LOG_E(TAG, "No parameters");
stop();
return;
}
if (!fromBundle(*parameters.get(), entry)) {
LOGGER.error("Invalid parameters");
LOG_E(TAG, "Invalid parameters");
stop();
}
}
@@ -1,6 +1,5 @@
#ifdef ESP_PLATFORM
#include <Tactility/Logger.h>
#include <Tactility/Tactility.h>
#include <Tactility/app/App.h>
#include <Tactility/lvgl/Toolbar.h>
@@ -8,10 +7,11 @@
#include <Tactility/settings/WebServerSettings.h>
#include <lvgl.h>
#include <tactility/log.h>
namespace tt::app::apwebserver {
static const auto LOGGER = tt::Logger("ApWebServerApp");
constexpr auto* TAG = "ApWebServerApp";
class ApWebServerApp final : public App {
lv_obj_t* labelSsidValue = nullptr;
@@ -91,7 +91,7 @@ public:
// Apply settings and start services
getMainDispatcher().dispatch([apSettings] {
if (!settings::webserver::save(apSettings)) {
LOGGER.error("Failed to save AP settings");
LOG_E(TAG, "Failed to save AP settings");
return;
}
service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged);
@@ -106,13 +106,13 @@ public:
getMainDispatcher().dispatch([copy, webServerChanged] {
if (!settings::webserver::save(copy)) {
LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot");
LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot");
}
service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged);
if (webServerChanged) {
LOGGER.info("WebServer {}", copy.webServerEnabled ? "enabling..." : "disabling...");
LOG_I(TAG, "WebServer %s", copy.webServerEnabled ? "enabling..." : "disabling...");
service::webserver::setWebServerEnabled(copy.webServerEnabled);
}
});
+16 -16
View File
@@ -9,7 +9,6 @@
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/usb/Usb.h>
#include <Tactility/kernel/SystemEvents.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/Paths.h>
#include <Tactility/service/loader/Loader.h>
@@ -17,6 +16,7 @@
#include <Tactility/settings/DisplaySettings.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <atomic>
@@ -31,7 +31,7 @@
namespace tt::app::boot {
static const auto LOGGER = Logger("Boot");
constexpr auto* TAG = "Boot";
extern const AppManifest manifest;
@@ -67,17 +67,17 @@ class BootApp : public App {
if (settings::display::load(settings)) {
if (hal_display->getGammaCurveCount() > 0) {
hal_display->setGammaCurve(settings.gammaCurve);
LOGGER.info("Gamma curve {}", settings.gammaCurve);
LOG_I(TAG, "Gamma curve %d", settings.gammaCurve);
}
} else {
settings = settings::display::getDefault();
}
if (hal_display->supportsBacklightDuty()) {
LOGGER.info("Backlight {}", settings.backlightDuty);
LOG_I(TAG, "Backlight %d", settings.backlightDuty);
hal_display->setBacklightDuty(settings.backlightDuty);
} else {
LOGGER.info("No backlight");
LOG_I(TAG, "No backlight");
}
}
@@ -86,17 +86,17 @@ class BootApp : public App {
return false;
}
LOGGER.info("Rebooting into mass storage device mode");
LOG_I(TAG, "Rebooting into mass storage device mode");
auto mode = hal::usb::getUsbBootMode(); // Get mode before reset
hal::usb::resetUsbBootMode();
if (mode == hal::usb::BootMode::Flash) {
if (!hal::usb::startMassStorageWithFlash(true)) {
LOGGER.error("Unable to start flash mass storage");
LOG_E(TAG, "Unable to start flash mass storage");
return false;
}
} else if (mode == hal::usb::BootMode::Sdmmc) {
if (!hal::usb::startMassStorageWithSdmmc(true)) {
LOGGER.error("Unable to start SD mass storage");
LOG_E(TAG, "Unable to start SD mass storage");
return false;
}
}
@@ -114,7 +114,7 @@ class BootApp : public App {
}
static int32_t bootThreadCallback() {
LOGGER.info("Starting boot thread");
LOG_I(TAG, "Starting boot thread");
const auto start_time = kernel::getTicks();
// Give the UI some time to redraw
@@ -124,20 +124,20 @@ class BootApp : public App {
kernel::delayMillis(10);
// TODO: Support for multiple displays
LOGGER.info("Setup display");
LOG_I(TAG, "Setup display");
setupDisplay(); // Set backlight
prepareFileSystems();
#ifdef CONFIG_TT_USER_DATA_LOCATION_SD
std::string sd_path;
if (!findFirstMountedSdCardPath(sd_path)) {
LOGGER.error("SD card not found");
LOG_E(TAG, "SD card not found");
sdCardMissing = true;
}
#endif
if (!setupUsbBootMode()) {
LOGGER.info("initFromBootApp");
LOG_I(TAG, "initFromBootApp");
registerApps();
waitForMinimalSplashDuration(start_time);
// When SD card is missing, wait for dialog result
@@ -147,7 +147,7 @@ class BootApp : public App {
// This event will likely block as other systems are initialized
// e.g. Wi-Fi reads AP configs from SD card
LOGGER.info("Publish event");
LOG_I(TAG, "Publish event");
kernel::publishSystemEvent(kernel::SystemEvent::BootSplash);
return 0;
@@ -162,13 +162,13 @@ class BootApp : public App {
// When boot properties didn't specify an override, return default
if (boot_properties.launcherAppId.empty()) {
LOGGER.error("Failed to load launcher configuration, or launcher not configured");
LOG_E(TAG, "Failed to load launcher configuration, or launcher not configured");
return CONFIG_TT_LAUNCHER_APP_ID;
}
// If the app in the boot.properties does not exist, return default
if (findAppManifestById(boot_properties.launcherAppId) == nullptr) {
LOGGER.error("Launcher app {} not found", boot_properties.launcherAppId);
LOG_E(TAG, "Launcher app %s not found", boot_properties.launcherAppId.c_str());
return CONFIG_TT_LAUNCHER_APP_ID;
}
@@ -239,7 +239,7 @@ public:
logo = isUsbBootSplash ? "logo_usb.png" : "logo.png";
}
const auto logo_path = lvgl::PATH_PREFIX + paths->getAssetsPath(logo);
LOGGER.info("{}", logo_path);
LOG_I(TAG, "%s", logo_path.c_str());
lv_image_set_src(image, logo_path.c_str());
#ifdef ESP_PLATFORM
+9 -9
View File
@@ -1,18 +1,18 @@
#include <Tactility/app/btmanage/BtManagePrivate.h>
#include <Tactility/app/btmanage/View.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Tactility.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/Tactility.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::btmanage {
static const auto LOGGER = Logger("BtManage");
constexpr auto* TAG = "BtManage";
extern const AppManifest manifest;
@@ -83,7 +83,7 @@ void BtManage::requestViewUpdate() {
view.update();
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
unlock();
@@ -91,7 +91,7 @@ void BtManage::requestViewUpdate() {
void BtManage::onBtEvent(const struct BtEvent& event) {
auto radio_state = bluetooth::getRadioState();
LOGGER.info("Update with state {}", bluetooth::radioStateToString(radio_state));
LOG_I(TAG, "Update with state %s", bluetooth::radioStateToString(radio_state));
getState().setRadioState(radio_state);
switch (event.type) {
case BT_EVENT_SCAN_STARTED:
@@ -162,10 +162,10 @@ void BtManage::onShow(AppContext& app, lv_obj_t* parent) {
auto radio_state = bluetooth::getRadioState();
bool can_scan = radio_state == bluetooth::RadioState::On;
LOGGER.info("Radio: {}, Scanning: {}, Can scan: {}",
LOG_I(TAG, "Radio: %s, Scanning: %d, Can scan: %d",
bluetooth::radioStateToString(radio_state),
dev ? bluetooth_is_scanning(dev) : false,
can_scan);
(int)(dev ? bluetooth_is_scanning(dev) : false),
(int)can_scan);
if (can_scan && dev && !bluetooth_is_scanning(dev)) {
bluetooth_scan_start(dev);
}
-1
View File
@@ -6,7 +6,6 @@
#include <Tactility/app/btmanage/View.h>
#include <Tactility/app/btmanage/BtManagePrivate.h>
#include <Tactility/app/btpeersettings/BtPeerSettings.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/bluetooth/Bluetooth.h>
@@ -3,7 +3,6 @@
#include "tactility/device.h"
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/app/App.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h>
@@ -15,12 +14,13 @@
#include <Tactility/lvgl/Toolbar.h>
#include <tactility/check.h>
#include <tactility/drivers/bluetooth.h>
#include <tactility/log.h>
#include <lvgl.h>
namespace tt::app::btpeersettings {
static const auto LOGGER = Logger("BtPeerSettings");
constexpr auto* TAG = "BtPeerSettings";
extern const AppManifest manifest;
@@ -77,7 +77,7 @@ class BtPeerSettings : public App {
if (bluetooth::settings::load(self->addrHex, device)) {
device.autoConnect = is_on;
if (!bluetooth::settings::save(device)) {
LOGGER.error("Failed to save auto-connect setting");
LOG_E(TAG, "Failed to save auto-connect setting");
}
}
}
@@ -88,7 +88,7 @@ class BtPeerSettings : public App {
updateViews();
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
}
+6 -6
View File
@@ -8,18 +8,18 @@
#include <Tactility/app/chat/ChatProtocol.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/LvglSync.h>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <vector>
namespace tt::app::chat {
static const auto LOGGER = Logger("ChatApp");
constexpr auto* TAG = "ChatApp";
static constexpr uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
void ChatApp::enableEspNow() {
@@ -98,12 +98,12 @@ void ChatApp::sendMessage(const std::string& text) {
std::vector<uint8_t> wireMsg;
if (!serializeTextMessage(settings.senderId, BROADCAST_ID, nickname, channel, text, wireMsg)) {
LOGGER.error("Failed to serialize message");
LOG_E(TAG, "Failed to serialize message");
return;
}
if (!service::espnow::send(BROADCAST_ADDRESS, wireMsg.data(), wireMsg.size())) {
LOGGER.error("Failed to send message");
LOG_E(TAG, "Failed to send message");
return;
}
@@ -144,7 +144,7 @@ void ChatApp::applySettings(const std::string& nickname, const std::string& keyH
}
settings.hasEncryptionKey = true;
} else {
LOGGER.warn("Invalid hex characters in encryption key");
LOG_W(TAG, "Invalid hex characters in encryption key");
}
} else if (keyHex.empty()) {
if (settings.hasEncryptionKey) {
@@ -153,7 +153,7 @@ void ChatApp::applySettings(const std::string& nickname, const std::string& keyH
needRestart = true;
}
} else {
LOGGER.warn("Key must be exactly {} hex characters, got {}", ESP_NOW_KEY_LEN * 2, keyHex.size());
LOG_W(TAG, "Key must be exactly %d hex characters, got %d", (int)(ESP_NOW_KEY_LEN * 2), (int)keyHex.size());
}
state.setLocalNickname(settings.nickname);
+7 -7
View File
@@ -10,7 +10,6 @@
#include <Tactility/crypt/Crypt.h>
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Logger.h>
#include <Tactility/Paths.h>
#include <esp_random.h>
@@ -20,11 +19,12 @@
#include <iomanip>
#include <map>
#include <sstream>
#include <tactility/log.h>
#include <unistd.h>
namespace tt::app::chat {
static const auto LOGGER = Logger("ChatSettings");
constexpr auto* TAG = "ChatSettings";
static std::string getSettingsFilePath() {
return getUserDataPath() + "/settings/chat.properties";
@@ -52,7 +52,7 @@ static std::string toHexString(const uint8_t* data, size_t length) {
static bool readHex(const std::string& input, uint8_t* buffer, size_t length) {
if (input.size() != length * 2) {
LOGGER.error("readHex() length mismatch");
LOG_E(TAG, "readHex() length mismatch");
return false;
}
@@ -63,7 +63,7 @@ static bool readHex(const std::string& input, uint8_t* buffer, size_t length) {
char* endptr;
unsigned long val = strtoul(hex, &endptr, 16);
if (endptr != hex + 2) {
LOGGER.error("readHex() invalid hex character");
LOG_E(TAG, "readHex() invalid hex character");
return false;
}
buffer[i] = static_cast<uint8_t>(val);
@@ -77,7 +77,7 @@ static bool encryptKey(const uint8_t key[ESP_NOW_KEY_LEN], std::string& hexOutpu
uint8_t encrypted[ESP_NOW_KEY_LEN];
if (crypt::encrypt(iv, key, encrypted, ESP_NOW_KEY_LEN) != 0) {
LOGGER.error("Failed to encrypt key");
LOG_E(TAG, "Failed to encrypt key");
return false;
}
@@ -99,7 +99,7 @@ static bool decryptKey(const std::string& hexInput, uint8_t key[ESP_NOW_KEY_LEN]
crypt::getIv(IV_SEED, std::strlen(IV_SEED), iv);
if (crypt::decrypt(iv, encrypted, key, ESP_NOW_KEY_LEN) != 0) {
LOGGER.error("Failed to decrypt key");
LOG_E(TAG, "Failed to decrypt key");
return false;
}
return true;
@@ -188,7 +188,7 @@ bool saveSettings(const ChatSettingsData& settings) {
auto settings_path = getSettingsFilePath();
if (!file::findOrCreateParentDirectory(settings_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", settings_path);
LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str());
return false;
}
return file::savePropertiesFile(settings_path, map);
@@ -4,16 +4,16 @@
#include <Tactility/app/crashdiagnostics/QrUrl.h>
#include <Tactility/app/launcher/Launcher.h>
#include <tactility/hal/Device.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/service/loader/Loader.h>
#include <lvgl.h>
#include <qrcode.h>
#include <tactility/log.h>
namespace tt::app::crashdiagnostics {
static const auto LOGGER = Logger("CrashDiagnostics");
constexpr auto* TAG = "CrashDiagnostics";
extern const AppManifest manifest;
@@ -44,38 +44,38 @@ public:
lv_obj_align(bottom_label, LV_ALIGN_BOTTOM_MID, 0, -2);
std::string url = getUrlFromCrashData();
LOGGER.info("{}", url);
LOG_I(TAG, "%s", url.c_str());
size_t url_length = url.length();
int qr_version;
if (!getQrVersionForBinaryDataLength(url_length, qr_version)) {
LOGGER.error("QR is too large");
LOG_E(TAG, "QR is too large");
stop(manifest.appId);
return;
}
LOGGER.info("QR version {} (length: {})", qr_version, url_length);
LOG_I(TAG, "QR version %d (length: %d)", qr_version, (int)url_length);
auto qrcodeData = std::make_shared<uint8_t[]>(qrcode_getBufferSize(qr_version));
if (qrcodeData == nullptr) {
LOGGER.error("Failed to allocate QR buffer");
LOG_E(TAG, "Failed to allocate QR buffer");
stop(manifest.appId);
return;
}
QRCode qrcode;
LOGGER.info("QR init text");
LOG_I(TAG, "QR init text");
if (qrcode_initText(&qrcode, qrcodeData.get(), qr_version, ECC_LOW, url.c_str()) != 0) {
LOGGER.error("QR init text failed");
LOG_E(TAG, "QR init text failed");
stop(manifest.appId);
return;
}
LOGGER.info("QR size: {}", qrcode.size);
LOG_I(TAG, "QR size: %d", qrcode.size);
// Calculate QR dot size
int32_t top_label_height = lv_obj_get_height(top_label) + 2;
int32_t bottom_label_height = lv_obj_get_height(bottom_label) + 2;
LOGGER.info("Create canvas");
LOG_I(TAG, "Create canvas");
int32_t available_height = parent_height - top_label_height - bottom_label_height;
int32_t available_width = lv_display_get_horizontal_resolution(display);
int32_t smallest_size = std::min(available_height, available_width);
@@ -85,7 +85,7 @@ public:
} else if (qrcode.size <= smallest_size) {
pixel_size = 1;
} else {
LOGGER.error("QR code won't fit screen");
LOG_E(TAG, "QR code won't fit screen");
stop(manifest.appId);
return;
}
@@ -97,10 +97,10 @@ public:
lv_obj_set_content_height(canvas, qrcode.size * pixel_size);
lv_obj_set_content_width(canvas, qrcode.size * pixel_size);
LOGGER.info("Create draw buffer");
LOG_I(TAG, "Create draw buffer");
auto* draw_buf = lv_draw_buf_create(pixel_size * qrcode.size, pixel_size * qrcode.size, LV_COLOR_FORMAT_RGB565, LV_STRIDE_AUTO);
if (draw_buf == nullptr) {
LOGGER.error("Failed to allocate draw buffer");
LOG_E(TAG, "Failed to allocate draw buffer");
stop(manifest.appId);
return;
}
@@ -7,12 +7,12 @@
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Logger.h>
#include <Tactility/service/development/DevelopmentService.h>
#include <Tactility/service/development/DevelopmentSettings.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <cstring>
@@ -20,7 +20,7 @@
namespace tt::app::development {
static const auto LOGGER = Logger("Development");
constexpr auto* TAG = "Development";
extern const AppManifest manifest;
class DevelopmentApp final : public App {
@@ -87,7 +87,7 @@ public:
void onCreate(AppContext& appContext) override {
service = service::development::findService();
if (service == nullptr) {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
stop(manifest.appId);
}
}
+3 -3
View File
@@ -6,7 +6,6 @@
#include <Tactility/service/displayidle/DisplayIdleService.h>
#endif
#include <Tactility/Logger.h>
#include <Tactility/app/App.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/touch/TouchDevice.h>
@@ -14,11 +13,12 @@
#include <Tactility/settings/DisplaySettings.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
namespace tt::app::display {
static const auto LOGGER = Logger("Display");
constexpr auto* TAG = "Display";
static std::shared_ptr<hal::display::DisplayDevice> getHalDisplay() {
return hal::findFirstDevice<hal::display::DisplayDevice>(hal::Device::Type::Display);
@@ -74,7 +74,7 @@ class DisplayApp final : public App {
auto* app = static_cast<DisplayApp*>(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);
LOGGER.info("Selected {}", selected_index);
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;
+11 -11
View File
@@ -1,11 +1,11 @@
#include <Tactility/app/files/State.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/MountPoints.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <Tactility/kernel/Platform.h>
#include <tactility/log.h>
#include <cstring>
#include <dirent.h>
@@ -14,7 +14,7 @@
namespace tt::app::files {
static const auto LOGGER = Logger("Files");
constexpr auto* TAG = "Files";
State::State() {
if (kernel::getPlatform() == kernel::PlatformSimulator) {
@@ -22,7 +22,7 @@ State::State() {
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
setEntriesForPath(cwd);
} else {
LOGGER.error("Failed to get current work directory files");
LOG_E(TAG, "Failed to get current work directory files");
setEntriesForPath("/");
}
} else {
@@ -37,11 +37,11 @@ std::string State::getSelectedChildPath() const {
bool State::setEntriesForPath(const std::string& path) {
auto lock = mutex.asScopedLock();
if (!lock.lock(100)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath");
LOG_E(TAG, "Mutex acquisition timeout (%s)", "setEntriesForPath");
return false;
}
LOGGER.info("Changing path: {} -> {}", current_path, path);
LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str());
/**
* On PC, the root entry point ("/") is a folder.
@@ -49,7 +49,7 @@ bool State::setEntriesForPath(const std::string& path) {
*/
bool get_mount_points = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/");
if (get_mount_points) {
LOGGER.info("Setting custom root");
LOG_I(TAG, "Setting custom root");
dir_entries = file::getFileSystemDirents();
current_path = path;
selected_child_entry = "";
@@ -59,13 +59,13 @@ bool State::setEntriesForPath(const std::string& path) {
dir_entries.clear();
int count = file::scandir(path, dir_entries, &file::direntFilterDotEntries, file::direntSortAlphaAndType);
if (count >= 0) {
LOGGER.info("{} has {} entries", path, count);
LOG_I(TAG, "%s has %d entries", path.c_str(), count);
current_path = path;
selected_child_entry = "";
action = ActionNone;
return true;
} else {
LOGGER.error("Failed to fetch entries for {}", path);
LOG_E(TAG, "Failed to fetch entries for %s", path.c_str());
return false;
}
}
@@ -73,7 +73,7 @@ bool State::setEntriesForPath(const std::string& path) {
bool State::setEntriesForChildPath(const std::string& childPath) {
auto path = file::getChildPath(current_path, childPath);
LOGGER.info("Navigating from {} to {}", current_path, path);
LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str());
return setEntriesForPath(path);
}
+37 -37
View File
@@ -2,7 +2,6 @@
#include <Tactility/app/files/View.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <Tactility/Tactility.h>
#include <Tactility/app/ElfApp.h>
@@ -18,6 +17,7 @@
#include <tactility/device.h>
#include <tactility/drivers/usb_host_msc.h>
#include <tactility/log.h>
#include <cctype>
#include <cstdio>
@@ -30,7 +30,7 @@
namespace tt::app::files {
static const auto LOGGER = Logger("Files");
constexpr auto* TAG = "Files";
// region Callbacks
@@ -202,11 +202,11 @@ void View::viewFile(const std::string& path, const std::string& filename) {
if (kernel::getPlatform() == kernel::PlatformSimulator) {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == nullptr) {
LOGGER.error("Failed to get current working directory");
LOG_E(TAG, "Failed to get current working directory");
return;
}
if (!file_path.starts_with(cwd)) {
LOGGER.error("Can only work with files in working directory {}", cwd);
LOG_E(TAG, "Can only work with files in working directory %s", cwd);
return;
}
processed_filepath = file_path.substr(strlen(cwd));
@@ -214,7 +214,7 @@ void View::viewFile(const std::string& path, const std::string& filename) {
processed_filepath = file_path;
}
LOGGER.info("Clicked {}", file_path);
LOG_I(TAG, "Clicked %s", file_path.c_str());
if (isSupportedAppFile(filename)) {
#ifdef ESP_PLATFORM
@@ -234,7 +234,7 @@ void View::viewFile(const std::string& path, const std::string& filename) {
notes::start(processed_filepath.substr(1));
}
} else {
LOGGER.warn("Opening files of this type is not supported");
LOG_W(TAG, "Opening files of this type is not supported");
}
onNavigate();
@@ -260,7 +260,7 @@ void View::onDirEntryPressed(uint32_t index) {
return;
}
LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type);
LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type);
state->setSelectedChildEntry(dir_entry.d_name);
using namespace tt::file;
@@ -273,7 +273,7 @@ void View::onDirEntryPressed(uint32_t index) {
break;
case TT_DT_LNK:
LOGGER.warn("opening links is not supported");
LOG_W(TAG, "opening links is not supported");
break;
default:
@@ -289,7 +289,7 @@ void View::onDirEntryLongPressed(int32_t index) {
return;
}
LOGGER.info("Long-pressed {} {}", dir_entry.d_name, dir_entry.d_type);
LOG_I(TAG, "Long-pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type);
state->setSelectedChildEntry(dir_entry.d_name);
if (state->getCurrentPath() == "/") {
@@ -310,7 +310,7 @@ void View::onDirEntryLongPressed(int32_t index) {
break;
case TT_DT_LNK:
LOGGER.warn("Opening links is not supported");
LOG_W(TAG, "Opening links is not supported");
break;
default:
@@ -369,7 +369,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) {
void View::onNavigateUpPressed() {
if (state->getCurrentPath() != "/") {
LOGGER.info("Navigating upwards");
LOG_I(TAG, "Navigating upwards");
std::string new_absolute_path;
if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) {
state->setEntriesForPath(new_absolute_path);
@@ -381,14 +381,14 @@ void View::onNavigateUpPressed() {
void View::onRenamePressed() {
std::string entry_name = state->getSelectedChildEntry();
LOGGER.info("Pending rename {}", entry_name);
LOG_I(TAG, "Pending rename %s", entry_name.c_str());
state->setPendingAction(State::ActionRename);
inputdialog::start("Rename", "", entry_name);
}
void View::onDeletePressed() {
std::string file_path = state->getSelectedChildPath();
LOGGER.info("Pending delete {}", file_path);
LOG_I(TAG, "Pending delete %s", file_path.c_str());
state->setPendingAction(State::ActionDelete);
std::string message = "Do you want to delete this?\n" + file_path;
const std::vector<std::string> choices = {"Yes", "No"};
@@ -396,13 +396,13 @@ void View::onDeletePressed() {
}
void View::onNewFilePressed() {
LOGGER.info("Creating new file");
LOG_I(TAG, "Creating new file");
state->setPendingAction(State::ActionCreateFile);
inputdialog::start("New File", "Enter filename:", "");
}
void View::onNewFolderPressed() {
LOGGER.info("Creating new folder");
LOG_I(TAG, "Creating new folder");
state->setPendingAction(State::ActionCreateFolder);
inputdialog::start("New Folder", "Enter folder name:", "");
}
@@ -436,11 +436,11 @@ void View::showActionsForMountPoint() {
void View::onEjectPressed() {
std::string mount_path = state->getSelectedChildPath();
LOGGER.info("Ejecting {}", mount_path);
LOG_I(TAG, "Ejecting %s", mount_path.c_str());
struct Device* msc_dev = device_find_first_active_by_type(&USB_HOST_MSC_TYPE);
if (!msc_dev || !usb_msc_eject(msc_dev, mount_path.c_str())) {
LOGGER.warn("usb_msc_eject: {} not found", mount_path);
LOG_W(TAG, "usb_msc_eject: %s not found", mount_path.c_str());
alertdialog::start("Eject failed", "Could not eject \"" + file::getLastPathSegment(mount_path) + "\".");
}
@@ -454,7 +454,7 @@ void View::update(size_t start_index) {
auto scoped_lockable = lvgl::getSyncLock()->asScopedLock();
if (!scoped_lockable.lock(lvgl::defaultLockTime)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl");
LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl");
return;
}
@@ -580,20 +580,20 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
}
std::string filepath = state->getSelectedChildPath();
LOGGER.info("Result for {}", filepath);
LOG_I(TAG, "Result for %s", filepath.c_str());
switch (state->getPendingAction()) {
case State::ActionDelete: {
if (alertdialog::getResultIndex(*bundle) == 0) {
if (file::isDirectory(filepath)) {
if (!file::deleteRecursively(filepath)) {
LOGGER.warn("Failed to delete {}", filepath);
LOG_W(TAG, "Failed to delete %s", filepath.c_str());
}
} else if (file::isFile(filepath)) {
auto lock = file::getLock(filepath);
lock->lock();
if (remove(filepath.c_str()) != 0) {
LOGGER.warn("Failed to delete {}", filepath);
LOG_W(TAG, "Failed to delete %s", filepath.c_str());
}
lock->unlock();
}
@@ -611,16 +611,16 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
std::string rename_to = file::getChildPath(state->getCurrentPath(), new_name);
struct stat st;
if (stat(rename_to.c_str(), &st) == 0) {
LOGGER.warn("Rename: destination already exists: \"{}\"", rename_to);
LOG_W(TAG, "Rename: destination already exists: \"%s\"", rename_to.c_str());
lock->unlock();
state->setPendingAction(State::ActionNone);
alertdialog::start("Rename failed", "\"" + new_name + "\" already exists.");
break;
}
if (rename(filepath.c_str(), rename_to.c_str()) == 0) {
LOGGER.info("Renamed \"{}\" to \"{}\"", filepath, rename_to);
LOG_I(TAG, "Renamed \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str());
} else {
LOGGER.error("Failed to rename \"{}\" to \"{}\"", filepath, rename_to);
LOG_E(TAG, "Failed to rename \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str());
}
lock->unlock();
@@ -639,7 +639,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
struct stat st;
if (stat(new_file_path.c_str(), &st) == 0) {
LOGGER.warn("File already exists: \"{}\"", new_file_path);
LOG_W(TAG, "File already exists: \"%s\"", new_file_path.c_str());
lock->unlock();
break;
}
@@ -647,9 +647,9 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
FILE* new_file = fopen(new_file_path.c_str(), "w");
if (new_file) {
fclose(new_file);
LOGGER.info("Created file \"{}\"", new_file_path);
LOG_I(TAG, "Created file \"%s\"", new_file_path.c_str());
} else {
LOGGER.error("Failed to create file \"{}\"", new_file_path);
LOG_E(TAG, "Failed to create file \"%s\"", new_file_path.c_str());
}
lock->unlock();
@@ -668,15 +668,15 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
struct stat st;
if (stat(new_folder_path.c_str(), &st) == 0) {
LOGGER.warn("Folder already exists: \"{}\"", new_folder_path);
LOG_W(TAG, "Folder already exists: \"%s\"", new_folder_path.c_str());
lock->unlock();
break;
}
if (mkdir(new_folder_path.c_str(), 0755) == 0) {
LOGGER.info("Created folder \"{}\"", new_folder_path);
LOG_I(TAG, "Created folder \"%s\"", new_folder_path.c_str());
} else {
LOGGER.error("Failed to create folder \"{}\"", new_folder_path);
LOG_E(TAG, "Failed to create folder \"%s\"", new_folder_path.c_str());
}
lock->unlock();
@@ -698,7 +698,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
if (file::deleteRecursively(dst)) {
doPaste(clipboard->first, clipboard->second, dst);
} else {
LOGGER.error("Overwrite: failed to remove existing destination: \"{}\"", dst);
LOG_E(TAG, "Overwrite: failed to remove existing destination: \"%s\"", dst.c_str());
state->setPendingAction(State::ActionNone);
alertdialog::start(
"Overwrite failed",
@@ -717,7 +717,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr<Bundle> bu
void View::onCopyPressed() {
std::string path = state->getSelectedChildPath();
state->setClipboard(path, false);
LOGGER.info("Copied to clipboard: {}", path);
LOG_I(TAG, "Copied to clipboard: %s", path.c_str());
onNavigate();
update();
}
@@ -725,7 +725,7 @@ void View::onCopyPressed() {
void View::onCutPressed() {
std::string path = state->getSelectedChildPath();
state->setClipboard(path, true);
LOGGER.info("Cut to clipboard: {}", path);
LOG_I(TAG, "Cut to clipboard: %s", path.c_str());
onNavigate();
update();
}
@@ -744,7 +744,7 @@ void View::onPastePressed() {
// between this check and the write inside doPaste. Acceptable on a
// single-user embedded device; locking dst instead would be more correct.
if (src == dst) {
LOGGER.info("Paste: source and destination are the same path, skipping");
LOG_I(TAG, "Paste: source and destination are the same path, skipping");
return;
}
auto lock = file::getLock(src);
@@ -783,7 +783,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst)
success = true;
} else {
src_delete_failed = true;
LOGGER.error("Cut: copied \"{}\" to \"{}\" but failed to remove source — manual cleanup required", src, dst);
LOG_E(TAG, "Cut: copied \"%s\" to \"%s\" but failed to remove source — manual cleanup required", src.c_str(), dst.c_str());
}
}
}
@@ -793,7 +793,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst)
const std::string filename = file::getLastPathSegment(src);
if (success) {
LOGGER.info("{} \"{}\" to \"{}\"", is_cut ? "Moved" : "Copied", src, dst);
LOG_I(TAG, "%s \"%s\" to \"%s\"", is_cut ? "Moved" : "Copied", src.c_str(), dst.c_str());
if (is_cut) {
state->clearClipboard();
}
@@ -801,7 +801,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst)
state->setPendingAction(State::ActionNone); // prevent re-trigger on dialog dismiss
alertdialog::start("Move incomplete", "\"" + filename + "\" was copied but the original could not be removed.\nPlease delete it manually.");
} else {
LOGGER.error("Failed to {} \"{}\" to \"{}\"", is_cut ? "move" : "copy", src, dst);
LOG_E(TAG, "Failed to %s \"%s\" to \"%s\"", is_cut ? "move" : "copy", src.c_str(), dst.c_str());
state->setPendingAction(State::ActionNone); // prevent re-trigger on dialog dismiss
alertdialog::start(
std::string("Failed to ") + (is_cut ? "move" : "copy"),
+9 -9
View File
@@ -1,19 +1,19 @@
#include "Tactility/app/fileselection/State.h"
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/MountPoints.h>
#include <Tactility/kernel/Platform.h>
#include <Tactility/LogMessages.h>
#include <cstring>
#include <dirent.h>
#include <tactility/log.h>
#include <unistd.h>
#include <vector>
namespace tt::app::fileselection {
static const auto LOGGER = Logger("FileSelection");
constexpr auto* TAG = "FileSelection";
State::State() {
if (kernel::getPlatform() == kernel::PlatformSimulator) {
@@ -21,7 +21,7 @@ State::State() {
if (getcwd(cwd, sizeof(cwd)) != nullptr) {
setEntriesForPath(cwd);
} else {
LOGGER.error("Failed to get current work directory files");
LOG_E(TAG, "Failed to get current work directory files");
setEntriesForPath("/");
}
} else {
@@ -34,11 +34,11 @@ std::string State::getSelectedChildPath() const {
}
bool State::setEntriesForPath(const std::string& path) {
LOGGER.info("Changing path: {} -> {}", current_path, path);
LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str());
auto lock = mutex.asScopedLock();
if (!lock.lock(100)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath");
LOG_E(TAG, "Mutex acquisition timeout (%s)", "setEntriesForPath");
return false;
}
@@ -48,7 +48,7 @@ bool State::setEntriesForPath(const std::string& path) {
*/
bool show_custom_root = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/");
if (show_custom_root) {
LOGGER.info("Setting custom root");
LOG_I(TAG, "Setting custom root");
dir_entries = file::getFileSystemDirents();
current_path = path;
selected_child_entry = "";
@@ -57,12 +57,12 @@ bool State::setEntriesForPath(const std::string& path) {
dir_entries.clear();
int count = file::scandir(path, dir_entries, &file::direntFilterDotEntries, file::direntSortAlphaAndType);
if (count >= 0) {
LOGGER.info("{} has {} entries", path, count);
LOG_I(TAG, "%s has %d entries", path.c_str(), count);
current_path = path;
selected_child_entry = "";
return true;
} else {
LOGGER.error("Failed to fetch entries for {}", path);
LOG_E(TAG, "Failed to fetch entries for %s", path.c_str());
return false;
}
}
@@ -70,7 +70,7 @@ bool State::setEntriesForPath(const std::string& path) {
bool State::setEntriesForChildPath(const std::string& childPath) {
auto path = file::getChildPath(current_path, childPath);
LOGGER.info("Navigating from {} to {}", current_path, path);
LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str());
return setEntriesForPath(path);
}
+12 -12
View File
@@ -1,15 +1,15 @@
#include <Tactility/app/fileselection/View.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <Tactility/Tactility.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <tactility/check.h>
#include <Tactility/file/File.h>
#include <Tactility/kernel/Platform.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <tactility/check.h>
#include <tactility/log.h>
#include <cstring>
#include <unistd.h>
@@ -20,7 +20,7 @@
namespace tt::app::fileselection {
const static Logger LOGGER = Logger("FileSelection");
constexpr auto* TAG = "FileSelection";
// region Callbacks
@@ -47,11 +47,11 @@ void View::onTapFile(const std::string& path, const std::string& filename) {
if (kernel::getPlatform() == kernel::PlatformSimulator) {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == nullptr) {
LOGGER.error("Failed to get current working directory");
LOG_E(TAG, "Failed to get current working directory");
return;
}
if (!file_path.starts_with(cwd)) {
LOGGER.error("Can only work with files in working directory {}", cwd);
LOG_E(TAG, "Can only work with files in working directory %s", cwd);
return;
}
processed_filepath = file_path.substr(strlen(cwd));
@@ -59,7 +59,7 @@ void View::onTapFile(const std::string& path, const std::string& filename) {
processed_filepath = file_path;
}
LOGGER.info("Clicked {}", processed_filepath);
LOG_I(TAG, "Clicked %s", processed_filepath.c_str());
lv_textarea_set_text(path_textarea, processed_filepath.c_str());
}
@@ -67,7 +67,7 @@ void View::onTapFile(const std::string& path, const std::string& filename) {
void View::onDirEntryPressed(uint32_t index) {
dirent dir_entry;
if (state->getDirent(index, dir_entry)) {
LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type);
LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type);
state->setSelectedChildEntry(dir_entry.d_name);
using namespace tt::file;
switch (dir_entry.d_type) {
@@ -78,7 +78,7 @@ void View::onDirEntryPressed(uint32_t index) {
update();
break;
case TT_DT_LNK:
LOGGER.warn("Opening links is not supported");
LOG_W(TAG, "Opening links is not supported");
break;
case TT_DT_REG:
onTapFile(state->getCurrentPath(), dir_entry.d_name);
@@ -96,7 +96,7 @@ void View::onSelectButtonPressed(lv_event_t* event) {
auto* view = static_cast<View*>(lv_event_get_user_data(event));
const char* path = lv_textarea_get_text(view->path_textarea);
if (path == nullptr || strlen(path) == 0) {
LOGGER.warn("Select pressed, but not path found in textarea");
LOG_W(TAG, "Select pressed, but not path found in textarea");
return;
}
@@ -140,7 +140,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) {
void View::onNavigateUpPressed() {
if (state->getCurrentPath() != "/") {
LOGGER.info("Navigating upwards");
LOG_I(TAG, "Navigating upwards");
std::string new_absolute_path;
if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) {
state->setEntriesForPath(new_absolute_path);
@@ -161,7 +161,7 @@ void View::update() {
state->withEntries([this](const std::vector<dirent>& entries) {
for (auto entry : entries) {
LOGGER.debug("Entry: {} {}", entry.d_name, entry.d_type);
LOG_D(TAG, "Entry: %s %d", entry.d_name, (int)entry.d_type);
createDirEntryWidget(dir_entry_list, entry);
}
});
@@ -172,7 +172,7 @@ void View::update() {
lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN);
}
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl");
LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl");
}
}
@@ -5,11 +5,11 @@
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Logger.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/lvgl_icon_shared.h>
#include <cstring>
@@ -26,7 +26,7 @@ extern const AppManifest manifest;
class GpsSettingsApp final : public App {
const Logger logger = Logger("GpsSettings");
static constexpr auto* TAG = "GpsSettings";
std::unique_ptr<Timer> timer;
std::shared_ptr<GpsSettingsApp*> appReference = std::make_shared<GpsSettingsApp*>(this);
@@ -101,7 +101,7 @@ class GpsSettingsApp final : public App {
std::vector<tt::hal::gps::GpsConfiguration> configurations;
auto gps_service = service::gps::findGpsService();
if (gps_service && gps_service->getGpsConfigurations(configurations)) {
Logger("GpsSettings").info("Found service and configs {} {}", index, configurations.size());
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();
@@ -163,7 +163,7 @@ class GpsSettingsApp final : public App {
// Update toolbar
switch (state) {
case service::gps::State::OnPending:
logger.debug("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);
@@ -172,7 +172,7 @@ class GpsSettingsApp final : public App {
lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::On:
logger.debug("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);
@@ -181,7 +181,7 @@ class GpsSettingsApp final : public App {
lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::OffPending:
logger.debug("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);
@@ -190,7 +190,7 @@ class GpsSettingsApp final : public App {
lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN);
break;
case service::gps::State::Off:
logger.debug("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);
+22 -22
View File
@@ -1,19 +1,19 @@
#include <Tactility/app/i2cscanner/I2cScannerPrivate.h>
#include <Tactility/app/i2cscanner/I2cHelpers.h>
#include <Tactility/app/AppContext.h>
#include <tactility/drivers/i2c_controller.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/Preferences.h>
#include <Tactility/RecursiveMutex.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/Timer.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h>
#include <tactility/drivers/i2c_controller.h>
#include <format>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::i2cscanner {
@@ -22,7 +22,7 @@ extern const AppManifest manifest;
class I2cScannerApp final : public App {
const Logger logger = Logger("I2cScanner");
static constexpr auto* TAG = "I2cScanner";
static constexpr auto* START_SCAN_TEXT = "Scan";
static constexpr auto* STOP_SCAN_TEXT = "Stop scan";
@@ -190,7 +190,7 @@ bool I2cScannerApp::getPort(struct Device** outPort) {
mutex.unlock();
return true;
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "getPort");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "getPort");
return false;
}
}
@@ -201,7 +201,7 @@ bool I2cScannerApp::addAddressToList(uint8_t address) {
mutex.unlock();
return true;
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "addAddressToList");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "addAddressToList");
return false;
}
}
@@ -217,24 +217,24 @@ bool I2cScannerApp::shouldStopScanTimer() {
}
void I2cScannerApp::onScanTimer() {
logger.info("Scan thread started");
LOG_I(TAG, "Scan thread started");
Device* safe_port;
if (!getPort(&safe_port)) {
logger.error("Failed to get I2C port");
LOG_E(TAG, "Failed to get I2C port");
onScanTimerFinished();
return;
}
if (!device_is_ready(safe_port)) {
logger.error("I2C port not started");
LOG_E(TAG, "I2C port not started");
onScanTimerFinished();
return;
}
for (uint8_t address = 1; address < 128; ++address) {
if (i2c_controller_has_device_at_address(safe_port, address, 10 / portTICK_PERIOD_MS) == ERROR_NONE) {
logger.info("Found device at address 0x{:02X}", address);
LOG_I(TAG, "Found device at address 0x%02X", address);
if (!shouldStopScanTimer()) {
addAddressToList(address);
} else {
@@ -247,11 +247,11 @@ void I2cScannerApp::onScanTimer() {
}
}
logger.info("Scan thread finalizing");
LOG_I(TAG, "Scan thread finalizing");
onScanTimerFinished();
logger.info("Scan timer done");
LOG_I(TAG, "Scan timer done");
}
bool I2cScannerApp::hasScanThread() {
@@ -262,7 +262,7 @@ bool I2cScannerApp::hasScanThread() {
return has_thread;
} else {
// Unsafe way
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "hasScanTimer");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "hasScanTimer");
return scanTimer != nullptr;
}
}
@@ -285,7 +285,7 @@ void I2cScannerApp::startScanning() {
scanTimer->start();
mutex.unlock();
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "startScanning");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "startScanning");
}
}
void I2cScannerApp::stopScanning() {
@@ -294,7 +294,7 @@ void I2cScannerApp::stopScanning() {
scanState = ScanStateStopped;
mutex.unlock();
} else {
logger.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
}
}
@@ -317,7 +317,7 @@ void I2cScannerApp::selectBus(int32_t selected) {
mutex.unlock();
}
logger.info("Selected {}", selected);
LOG_I(TAG, "Selected %d", (int)selected);
setLastBusIndex(selected);
startScanning();
@@ -362,7 +362,7 @@ void I2cScannerApp::updateViews() {
mutex.unlock();
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViews");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "updateViews");
}
}
@@ -371,7 +371,7 @@ void I2cScannerApp::updateViewsSafely() {
updateViews();
lvgl::unlock();
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViewsSafely");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "updateViewsSafely");
}
}
@@ -384,7 +384,7 @@ void I2cScannerApp::onScanTimerFinished() {
updateViewsSafely();
} else {
logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "onScanTimerFinished");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "onScanTimerFinished");
}
}
@@ -2,8 +2,8 @@
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/Logger.h>
#include <Tactility/StringUtils.h>
#include <tactility/log.h>
#include <lvgl.h>
@@ -11,7 +11,7 @@ namespace tt::app::imageviewer {
extern const AppManifest manifest;
static const auto LOGGER = Logger("ImageViewer");
constexpr auto* TAG = "ImageViewer";
constexpr auto* IMAGE_VIEWER_FILE_ARGUMENT = "file";
class ImageViewerApp final : public App {
@@ -49,7 +49,7 @@ class ImageViewerApp final : public App {
std::string file_argument;
if (bundle->optString(IMAGE_VIEWER_FILE_ARGUMENT, file_argument)) {
std::string prefixed_path = lvgl::PATH_PREFIX + file_argument;
LOGGER.info("Opening {}", prefixed_path);
LOG_I(TAG, "Opening %s", prefixed_path.c_str());
lv_img_set_src(image, prefixed_path.c_str());
auto path = string::getLastPathSegment(file_argument);
lv_label_set_text(file_label, path.c_str());
@@ -3,6 +3,7 @@
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/TactilityCore.h>
#include <tactility/log.h>
#include <lvgl.h>
@@ -15,7 +16,7 @@ constexpr auto* RESULT_BUNDLE_KEY_RESULT = "result";
constexpr auto* DEFAULT_TITLE = "Input";
static const auto LOGGER = Logger("InputDialog");
constexpr auto* TAG = "InputDialog";
extern const AppManifest manifest;
class InputDialogApp;
@@ -62,7 +63,7 @@ class InputDialogApp final : public App {
void onButtonClicked(lv_event_t* e) {
auto user_data = lv_event_get_user_data(e);
int index = (user_data != 0) ? 0 : 1;
LOGGER.info("Selected item at index {}", index);
LOG_I(TAG, "Selected item at index %d", index);
if (index == 0) {
auto bundle = std::make_unique<Bundle>();
const char* text = lv_textarea_get_text((lv_obj_t*)user_data);
+4 -3
View File
@@ -11,13 +11,14 @@
#include <cstring>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_fonts.h>
#include <tactility/lvgl_icon_launcher.h>
#include <tactility/lvgl_module.h>
namespace tt::app::launcher {
static const auto LOGGER = Logger("Launcher");
constexpr auto* TAG = "Launcher";
static uint32_t getButtonPadding(UiDensity density, uint32_t buttonSize) {
if (density == LVGL_UI_DENSITY_COMPACT) {
@@ -143,7 +144,7 @@ public:
strcmp(CONFIG_TT_AUTO_START_APP_ID, "") != 0 &&
findAppManifestById(CONFIG_TT_AUTO_START_APP_ID) != nullptr
) {
LOGGER.info("Starting {}", CONFIG_TT_AUTO_START_APP_ID);
LOG_I(TAG, "Starting %s", CONFIG_TT_AUTO_START_APP_ID);
start(CONFIG_TT_AUTO_START_APP_ID);
} else if (
// Auto-start due to user configuration
@@ -151,7 +152,7 @@ public:
!boot_properties.autoStartAppId.empty() &&
findAppManifestById(boot_properties.autoStartAppId) != nullptr
) {
LOGGER.info("Starting {}", boot_properties.autoStartAppId);
LOG_I(TAG, "Starting %s", boot_properties.autoStartAppId.c_str());
start(boot_properties.autoStartAppId);
} else {
// No auto-start, consider running system setup
+8 -7
View File
@@ -8,11 +8,12 @@
#include <Tactility/file/File.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::notes {
static const auto LOGGER = Logger("Notes");
constexpr auto* TAG = "Notes";
constexpr auto* NOTES_FILE_ARGUMENT = "file";
class NotesApp final : public App {
@@ -52,11 +53,11 @@ class NotesApp final : public App {
saveBuffer = lv_textarea_get_text(uiNoteText);
lvgl::getSyncLock()->unlock();
saveFileLaunchId = fileselection::startForExistingOrNewFile();
LOGGER.info("launched with id {}", saveFileLaunchId);
LOG_I(TAG, "launched with id %u", saveFileLaunchId);
break;
case 3: // Load
loadFileLaunchId = fileselection::startForExistingFile();
LOGGER.info("launched with id {}", loadFileLaunchId);
LOG_I(TAG, "launched with id %u", loadFileLaunchId);
break;
}
} else {
@@ -64,7 +65,7 @@ class NotesApp final : public App {
if (obj == cont) return;
if (lv_obj_get_child(cont, 1)) {
saveFileLaunchId = fileselection::startForExistingOrNewFile();
LOGGER.info("launched with id {}", saveFileLaunchId);
LOG_I(TAG, "launched with id %u", saveFileLaunchId);
} else { //Reset
resetFileContent();
}
@@ -91,7 +92,7 @@ class NotesApp final : public App {
lv_textarea_set_text(uiNoteText, reinterpret_cast<const char*>(data.get()));
lv_label_set_text(uiCurrentFileName, path.c_str());
filePath = path;
LOGGER.info("Loaded from {}", path);
LOG_I(TAG, "Loaded from %s", path.c_str());
}
});
}
@@ -101,7 +102,7 @@ class NotesApp final : public App {
bool result = false;
file::getLock(path)->withLock([&result, this, path] {
if (file::writeString(path, saveBuffer.c_str())) {
LOGGER.info("Saved to {}", path);
LOG_I(TAG, "Saved to %s", path.c_str());
filePath = path;
result = true;
}
@@ -193,7 +194,7 @@ class NotesApp final : public App {
}
void onResult(AppContext& appContext, LaunchId launchId, Result result, std::unique_ptr<Bundle> resultData) override {
LOGGER.info("Result for launch id {}", launchId);
LOG_I(TAG, "Result for launch id %u", launchId);
if (launchId == loadFileLaunchId) {
loadFileLaunchId = 0;
if (result == Result::Ok && resultData != nullptr) {
@@ -6,7 +6,6 @@
#include <Tactility/app/App.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/kernel/Platform.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Lvgl.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Toolbar.h>
@@ -15,11 +14,12 @@
#include <Tactility/Paths.h>
#include <Tactility/Timer.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::screenshot {
static const auto LOGGER = Logger("Screenshot");
constexpr auto* TAG = "Screenshot";
extern const AppManifest manifest;
@@ -100,27 +100,27 @@ void ScreenshotApp::onModeSet() {
void ScreenshotApp::onStartPressed() {
auto service = service::screenshot::optScreenshotService();
if (service == nullptr) {
LOGGER.error("Service not found/running");
LOG_E(TAG, "Service not found/running");
return;
}
if (service->isTaskStarted()) {
LOGGER.info("Stop screenshot");
LOG_I(TAG, "Stop screenshot");
service->stop();
} else {
uint32_t selected = lv_dropdown_get_selected(modeDropdown);
const char* path = lv_textarea_get_text(pathTextArea);
if (selected == 0) {
LOGGER.info("Start timed screenshots");
LOG_I(TAG, "Start timed screenshots");
const char* delay_text = lv_textarea_get_text(delayTextArea);
int delay = atoi(delay_text);
if (delay > 0) {
service->startTimed(path, delay, 1);
} else {
LOGGER.warn("Ignored screenshot start because delay was 0");
LOG_W(TAG, "Ignored screenshot start because delay was 0");
}
} else {
LOGGER.info("Start app screenshots");
LOG_I(TAG, "Start app screenshots");
service->startApps(path);
}
}
@@ -131,7 +131,7 @@ void ScreenshotApp::onStartPressed() {
void ScreenshotApp::updateScreenshotMode() {
auto service = service::screenshot::optScreenshotService();
if (service == nullptr) {
LOGGER.error("Service not found/running");
LOG_E(TAG, "Service not found/running");
return;
}
@@ -154,7 +154,7 @@ void ScreenshotApp::updateScreenshotMode() {
void ScreenshotApp::createModeSettingWidgets(lv_obj_t* parent) {
auto service = service::screenshot::optScreenshotService();
if (service == nullptr) {
LOGGER.error("Service not found/running");
LOG_E(TAG, "Service not found/running");
return;
}
@@ -1,9 +1,9 @@
#include <Tactility/app/selectiondialog/SelectionDialog.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/StringUtils.h>
#include <tactility/log.h>
#include <lvgl.h>
@@ -16,7 +16,7 @@ constexpr auto* RESULT_BUNDLE_KEY_INDEX = "index";
constexpr auto* PARAMETER_ITEM_CONCATENATION_TOKEN = ";;";
constexpr auto* DEFAULT_TITLE = "Select...";
static const auto LOGGER = Logger("SelectionDialog");
constexpr auto* TAG = "SelectionDialog";
extern const AppManifest manifest;
@@ -53,7 +53,7 @@ class SelectionDialogApp final : public App {
void onListItemSelected(lv_event_t* e) {
auto index = reinterpret_cast<std::size_t>(lv_event_get_user_data(e));
LOGGER.info("Selected item at index {}", index);
LOG_I(TAG, "Selected item at index %d", (int)index);
auto bundle = std::make_unique<Bundle>();
bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, (int32_t)index);
setResult(Result::Ok, std::move(bundle));
@@ -85,7 +85,7 @@ public:
if (parameters->optString(PARAMETER_BUNDLE_KEY_ITEMS, items_concatenated)) {
std::vector<std::string> items = string::split(items_concatenated, PARAMETER_ITEM_CONCATENATION_TOKEN);
if (items.empty() || items.front().empty()) {
LOGGER.error("No items provided");
LOG_E(TAG, "No items provided");
setResult(Result::Error);
stop(manifest.appId);
} else if (items.size() == 1) {
@@ -93,7 +93,7 @@ public:
result_bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, 0);
setResult(Result::Ok, std::move(result_bundle));
stop(manifest.appId);
LOGGER.warn("Auto-selecting single item");
LOG_W(TAG, "Auto-selecting single item");
} else {
size_t index = 0;
for (const auto& item: items) {
@@ -101,7 +101,7 @@ public:
}
}
} else {
LOGGER.error("No items provided");
LOG_E(TAG, "No items provided");
setResult(Result::Error);
stop(manifest.appId);
}
@@ -1,7 +1,6 @@
#include "tactility/lvgl_module.h"
#include <Tactility/Logger.h>
#include <Tactility/RecursiveMutex.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/timezone/TimeZone.h>
@@ -13,11 +12,12 @@
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::timedatesettings {
static const auto LOGGER = Logger("TimeDate");
constexpr auto* TAG = "TimeDate";
extern const AppManifest manifest;
@@ -149,7 +149,7 @@ public:
if (result == Result::Ok && bundle != nullptr) {
const auto name = timezone::getResultName(*bundle);
const auto code = timezone::getResultCode(*bundle);
LOGGER.info("Result name={} code={}", name, code);
LOG_I(TAG, "Result name=%s code=%s", name.c_str(), code.c_str());
// onShow() may not have (re)created the widgets yet: onResult() runs synchronously
// on the loader thread and can race ahead of the async gui-task redraw.
+8 -8
View File
@@ -6,7 +6,6 @@
#include <Tactility/app/timezone/TimeZone.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/MountPoints.h>
#include <Tactility/StringUtils.h>
#include <Tactility/Timer.h>
@@ -14,13 +13,14 @@
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/settings/Time.h>
#include <tactility/log.h>
#include <lvgl.h>
#include <memory>
namespace tt::app::timezone {
static const auto LOGGER = Logger("TimeZone");
constexpr auto* TAG = "TimeZone";
constexpr auto* RESULT_BUNDLE_CODE_INDEX = "code";
constexpr auto* RESULT_BUNDLE_NAME_INDEX = "name";
@@ -103,7 +103,7 @@ class TimeZoneApp final : public App {
}
void onListItemSelected(std::size_t index) {
LOGGER.info("Selected item at index {}", index);
LOG_I(TAG, "Selected item at index %d", (int)index);
auto& entry = entries[index];
@@ -128,7 +128,7 @@ class TimeZoneApp final : public App {
auto path = std::string(file::MOUNT_POINT_SYSTEM) + "/timezones.csv";
auto* file = fopen(path.c_str(), "rb");
if (file == nullptr) {
LOGGER.error("Failed to open {}", path);
LOG_E(TAG, "Failed to open %s", path.c_str());
return;
}
char line[96];
@@ -149,7 +149,7 @@ class TimeZoneApp final : public App {
}
}
} else {
LOGGER.error("Parse error at line {}", count);
LOG_E(TAG, "Parse error at line %llu", count);
}
}
@@ -159,10 +159,10 @@ class TimeZoneApp final : public App {
entries = std::move(new_entries);
mutex.unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
}
LOGGER.info("Processed {} entries", count);
LOG_I(TAG, "Processed %llu entries", count);
}
void updateList() {
@@ -171,7 +171,7 @@ class TimeZoneApp final : public App {
readTimeZones(filter);
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
return;
}
@@ -2,15 +2,16 @@
#include <Tactility/app/touchcalibration/TouchCalibration.h>
#include <Tactility/Logger.h>
#include <Tactility/settings/TouchCalibrationSettings.h>
#include <tactility/log.h>
#include <algorithm>
#include <lvgl.h>
namespace tt::app::touchcalibration {
static const auto LOGGER = Logger("TouchCalibration");
constexpr auto* TAG = "TouchCalibration";
extern const AppManifest manifest;
@@ -102,7 +103,7 @@ class TouchCalibrationApp final : public App {
return;
}
LOGGER.info("Saved calibration x=[{}, {}] y=[{}, {}]", xMin, xMax, yMin, yMax);
LOG_I(TAG, "Saved calibration x=[%d, %d] y=[%d, %d]", xMin, xMax, yMin, yMax);
lv_label_set_text(titleLabel, "Calibration Complete");
lv_label_set_text(hintLabel, "Touch anywhere to continue.");
lv_obj_add_flag(target, LV_OBJ_FLAG_HIDDEN);
@@ -9,9 +9,9 @@
#include <Tactility/Assets.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/Logger.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
#include <esp_netif.h>
@@ -21,7 +21,7 @@
namespace tt::app::webserversettings {
static const auto LOGGER = tt::Logger("WebServerSettingsApp");
constexpr auto* TAG = "WebServerSettingsApp";
class WebServerSettingsApp final : public App {
@@ -68,10 +68,10 @@ class WebServerSettingsApp final : public App {
// Apply immediately instead of waiting for app exit
const auto copy = app->wsSettings;
if (!settings::webserver::save(copy)) {
LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot");
LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot");
}
service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged);
LOGGER.info("WebServer {}", enabled ? "enabling..." : "disabling...");
LOG_I(TAG, "WebServer %s", enabled ? "enabling..." : "disabling...");
service::webserver::setWebServerEnabled(enabled);
});
}
@@ -360,7 +360,7 @@ public:
getMainDispatcher().dispatch([copy, wifiChanged]{
// Save to flash (fast, low memory pressure)
if (!settings::webserver::save(copy)) {
LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot");
LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot");
}
// Publish event immediately after save so WebServer cache refreshes BEFORE requests arrive
@@ -368,7 +368,7 @@ public:
// Only reconnect WiFi if WiFi settings actually changed
if (wifiChanged) {
LOGGER.info("WiFi mode changed to {}", copy.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station");
LOG_I(TAG, "WiFi mode changed to %s", copy.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station");
}
});
}
@@ -1,22 +1,23 @@
#include "Tactility/lvgl/LvglSync.h"
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/app/App.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/alertdialog/AlertDialog.h>
#include <tactility/check.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/wifi/Wifi.h>
#include <Tactility/service/wifi/WifiApSettings.h>
#include <tactility/check.h>
#include <tactility/log.h>
#include <lvgl.h>
namespace tt::app::wifiapsettings {
static const auto LOGGER = Logger("WifiApSettings");
constexpr auto* TAG = "WifiApSettings";
extern const AppManifest manifest;
@@ -52,10 +53,10 @@ class WifiApSettings : public App {
if (service::wifi::settings::load(self->ssid.c_str(), settings)) {
settings.autoConnect = is_on;
if (!service::wifi::settings::save(settings)) {
LOGGER.error("Failed to save settings");
LOG_E(TAG, "Failed to save settings");
}
} else {
LOGGER.error("Failed to load settings");
LOG_E(TAG, "Failed to load settings");
}
}
@@ -91,7 +92,7 @@ class WifiApSettings : public App {
updateViews();
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
}
@@ -194,7 +195,7 @@ public:
lv_obj_remove_state(auto_connect_switch, LV_STATE_CHECKED);
}
} else {
LOGGER.warn("No settings found");
LOG_W(TAG, "No settings found");
lv_obj_add_flag(forget_button, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag(auto_connect_wrapper, LV_OBJ_FLAG_HIDDEN);
}
@@ -225,11 +226,11 @@ public:
std::string ssid = parameters->getString("ssid");
if (!service::wifi::settings::remove(ssid.c_str())) {
LOGGER.error("Failed to remove SSID");
LOG_E(TAG, "Failed to remove SSID");
return;
}
LOGGER.info("Removed SSID");
LOG_I(TAG, "Removed SSID");
if (
service::wifi::getRadioState() == service::wifi::RadioState::ConnectionActive &&
service::wifi::getConnectionTarget() == ssid
+5 -4
View File
@@ -2,18 +2,19 @@
#include <Tactility/app/wificonnect/View.h>
#include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/lvgl/Spinner.h>
#include <Tactility/service/wifi/WifiApSettings.h>
#include <Tactility/service/wifi/WifiGlobals.h>
#include <tactility/log.h>
#include <lvgl.h>
#include <cstring>
namespace tt::app::wificonnect {
static const auto LOGGER = Logger("WifiConnect");
constexpr auto* TAG = "WifiConnect";
void View::resetErrors() {
lv_obj_add_flag(password_error, LV_OBJ_FLAG_HIDDEN);
@@ -31,7 +32,7 @@ static void onConnect(lv_event_t* event) {
const char* ssid = lv_textarea_get_text(view.ssid_textarea);
size_t ssid_len = strlen(ssid);
if (ssid_len > TT_WIFI_SSID_LIMIT) {
LOGGER.error("SSID too long");
LOG_E(TAG, "SSID too long");
lv_label_set_text(view.ssid_error, "SSID too long");
lv_obj_remove_flag(view.ssid_error, LV_OBJ_FLAG_HIDDEN);
return;
@@ -40,7 +41,7 @@ static void onConnect(lv_event_t* event) {
const char* password = lv_textarea_get_text(view.password_textarea);
size_t password_len = strlen(password);
if (password_len > TT_WIFI_CREDENTIALS_PASSWORD_LIMIT) {
LOGGER.error("Password too long");
LOG_E(TAG, "Password too long");
lv_label_set_text(view.password_error, "Password too long");
lv_obj_remove_flag(view.password_error, LV_OBJ_FLAG_HIDDEN);
return;
@@ -1,15 +1,16 @@
#include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h>
namespace tt::app::wificonnect {
static const auto LOGGER = Logger("WifiConnect");
constexpr auto* TAG = "WifiConnect";
constexpr auto* WIFI_CONNECT_PARAM_SSID = "ssid"; // String
constexpr auto* WIFI_CONNECT_PARAM_PASSWORD = "password"; // String
@@ -74,7 +75,7 @@ void WifiConnect::requestViewUpdate() {
view.update();
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
unlock();
+11 -11
View File
@@ -2,21 +2,21 @@
#include <string>
#include <set>
#include <tactility/lvgl_module.h>
#include <Tactility/network/HttpdReq.h>
#include <Tactility/app/wifimanage/View.h>
#include <Tactility/app/wifimanage/WifiManagePrivate.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Style.h>
#include <Tactility/lvgl/Toolbar.h>
#include <Tactility/service/wifi/Wifi.h>
#include <Tactility/service/wifi/WifiSettings.h>
#include <Tactility/Tactility.h>
#include <tactility/log.h>
#include <tactility/lvgl_module.h>
namespace tt::app::wifimanage {
static const auto LOGGER = Logger("WifiManageView");
constexpr auto* TAG = "WifiManageView";
std::shared_ptr<WifiManage> optWifiManage();
@@ -68,16 +68,16 @@ static void onConnectToHiddenClicked(lv_event_t* event) {
// region Secondary updates
void View::connect(lv_event_t* event) {
LOGGER.debug("connect()");
LOG_D(TAG, "connect()");
auto* widget = lv_event_get_current_target_obj(event);
auto index = reinterpret_cast<size_t>(lv_obj_get_user_data(widget));
auto* self = static_cast<View*>(lv_event_get_user_data(event));
auto ap_records = self->state->getApRecords();
if (index < ap_records.size()) {
LOGGER.info("Clicked {}/{}", index, ap_records.size() - 1);
LOG_I(TAG, "Clicked %zu/%zu", index, ap_records.size() - 1);
auto& ssid = ap_records[index].ssid;
LOGGER.info("Clicked AP: {}", ssid);
LOG_I(TAG, "Clicked AP: %s", ssid.c_str());
std::string connection_target = service::wifi::getConnectionTarget();
if (connection_target == ssid) {
self->bindings->onDisconnect();
@@ -85,12 +85,12 @@ void View::connect(lv_event_t* event) {
self->bindings->onConnectSsid(ssid);
}
} else {
LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1);
LOG_W(TAG, "Clicked AP: record %zu/%zu does not exist", index, ap_records.size() - 1);
}
}
void View::showDetails(lv_event_t* event) {
LOGGER.debug("showDetails()");
LOG_D(TAG, "showDetails()");
auto* widget = lv_event_get_current_target_obj(event);
auto index = reinterpret_cast<size_t>(lv_obj_get_user_data(widget));
auto* self = static_cast<View*>(lv_event_get_user_data(event));
@@ -98,10 +98,10 @@ void View::showDetails(lv_event_t* event) {
if (index < ap_records.size()) {
auto& ssid = ap_records[index].ssid;
LOGGER.info("Clicked AP: {}", ssid);
LOG_I(TAG, "Clicked AP: %s", ssid.c_str());
self->bindings->onShowApSettings(ssid);
} else {
LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1);
LOG_W(TAG, "Clicked AP: record %zu/%zu does not exist", index, ap_records.size() - 1);
}
}
+11 -11
View File
@@ -1,29 +1,29 @@
#include <Tactility/app/wifimanage/WifiManagePrivate.h>
#include <Tactility/app/wifimanage/View.h>
#include <Tactility/LogMessages.h>
#include <Tactility/app/AppContext.h>
#include <Tactility/app/wifiapsettings/WifiApSettings.h>
#include <Tactility/app/wificonnect/WifiConnect.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h>
#include <tactility/log.h>
#include <tactility/lvgl_icon_shared.h>
namespace tt::app::wifimanage {
static const auto LOGGER = Logger("WifiManage");
constexpr auto* TAG = "WifiManage";
extern const AppManifest manifest;
static void onConnect(const std::string& ssid) {
service::wifi::settings::WifiApSettings settings;
if (service::wifi::settings::load(ssid, settings)) {
LOGGER.info("Connecting with known credentials");
LOG_I(TAG, "Connecting with known credentials");
service::wifi::connect(settings, false);
} else {
LOGGER.info("Starting connection dialog");
LOG_I(TAG, "Starting connection dialog");
wificonnect::start(ssid);
}
}
@@ -69,7 +69,7 @@ void WifiManage::requestViewUpdate() {
view.update();
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
unlock();
@@ -77,7 +77,7 @@ void WifiManage::requestViewUpdate() {
void WifiManage::onWifiEvent(service::wifi::WifiEvent event) {
auto radio_state = service::wifi::getRadioState();
LOGGER.info("Update with state {}", service::wifi::radioStateToString(radio_state));
LOG_I(TAG, "Update with state %s", service::wifi::radioStateToString(radio_state));
getState().setRadioState(radio_state);
switch (event) {
using enum service::wifi::WifiEvent;
@@ -123,11 +123,11 @@ void WifiManage::onShow(AppContext& app, lv_obj_t* parent) {
radio_state == service::wifi::RadioState::ConnectionPending ||
radio_state == service::wifi::RadioState::ConnectionActive;
std::string connection_target = service::wifi::getConnectionTarget();
LOGGER.info("Radio: {}, Scanning: {}, Connected to: {}, Can scan: {}",
service::wifi::radioStateToString(radio_state),
service::wifi::isScanning(),
LOG_I(TAG, "Radio: %s, Scanning: %d, Connected to: %s, Can scan: %d",
service::wifi::radioStateToString(radio_state),
(int)service::wifi::isScanning(),
connection_target.empty() ? "(none)" : connection_target.c_str(),
can_scan);
(int)can_scan);
if (can_scan && !service::wifi::isScanning()) {
service::wifi::scan();
}
+20 -20
View File
@@ -9,7 +9,6 @@
#include <Tactility/bluetooth/BluetoothSettings.h>
#include <Tactility/bluetooth/BluetoothPrivate.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <Tactility/Tactility.h>
#include <tactility/check.h>
@@ -18,6 +17,7 @@
#include <tactility/drivers/bluetooth_hid_device.h>
#include <tactility/drivers/bluetooth_midi.h>
#include <tactility/drivers/bluetooth_serial.h>
#include <tactility/log.h>
#include <array>
#include <cstring>
@@ -25,7 +25,7 @@
namespace tt::bluetooth {
static const auto LOGGER = Logger("Bluetooth");
constexpr auto* TAG = "Bluetooth";
// ---- Scan result cache (C++ PeerRecord list, updated from BT_EVENT_PEER_FOUND) ----
@@ -123,24 +123,24 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) {
if (p.profileId == BT_PROFILE_HID_DEVICE) has_hid_device_auto = true;
}
if (has_hid_host_auto) {
LOGGER.info("HID host auto-connect peer found — starting scan");
LOG_I(TAG, "HID host auto-connect peer found — starting scan");
if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) {
bluetooth_scan_start(dev);
}
} else if (has_hid_device_auto) {
LOGGER.info("HID device auto-start (bonded peer found)");
LOG_I(TAG, "HID device auto-start (bonded peer found)");
if (Device* dev = bluetooth_hid_device_get_device()) {
bluetooth_hid_device_start(dev, BT_HID_DEVICE_MODE_KEYBOARD);
}
} else {
if (settings::shouldSppAutoStart()) {
LOGGER.info("Auto-starting SPP server");
LOG_I(TAG, "Auto-starting SPP server");
if (Device* dev = bluetooth_serial_get_device()) {
bluetooth_serial_start(dev);
}
}
if (settings::shouldMidiAutoStart()) {
LOGGER.info("Auto-starting MIDI server");
LOG_I(TAG, "Auto-starting MIDI server");
if (Device* dev = bluetooth_midi_get_device()) {
bluetooth_midi_start(dev);
}
@@ -186,7 +186,7 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) {
dev.autoConnect = true;
dev.profileId = profile_copy;
if (settings::save(dev)) {
LOGGER.info("Saved paired peer {} (profile={})", hex, profile_copy);
LOG_I(TAG, "Saved paired peer %s (profile=%d)", hex.c_str(), profile_copy);
}
}
});
@@ -251,7 +251,7 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) {
void systemStart() {
Device* dev = findFirstRegisteredDevice();
if (dev == nullptr) {
LOGGER.warn("systemStart: no BLE device found");
LOG_W(TAG, "systemStart: no BLE device found");
return;
}
@@ -268,29 +268,29 @@ bool isRadioOnOrPending(Device* dev) {
}
bool start(Device* dev) {
LOGGER.info("Auto-enabling BLE on boot");
LOG_I(TAG, "Auto-enabling BLE on boot");
if (!device_is_ready(dev)) {
LOGGER.info("Starting BLE device");
LOG_I(TAG, "Starting BLE device");
if (device_start(dev) != ERROR_NONE) {
LOGGER.error("Failed to start BLE device");
LOG_E(TAG, "Failed to start BLE device");
return false;
}
}
// TODO: Fix bug where repeatedly calling start would add this callback multiple times
if (bluetooth_add_event_callback(dev, nullptr, bt_event_bridge) != ERROR_NONE) {
LOGGER.error("Failed to set BLE callback");
LOG_E(TAG, "Failed to set BLE callback");
}
LOGGER.info("Enabling BT radio");
LOG_I(TAG, "Enabling BT radio");
if (bluetooth_set_radio_enabled(dev, true) != ERROR_NONE) {
LOGGER.error("Failed to enable BLE radio");
LOG_E(TAG, "Failed to enable BLE radio");
// Add bridge again
bluetooth_remove_event_callback(dev, bt_event_bridge);
return false;
}
LOGGER.info("BT enabled");
LOG_I(TAG, "BT enabled");
return true;
}
@@ -305,18 +305,18 @@ bool stop(Device* dev) {
}
if (bluetooth_remove_event_callback(dev, bt_event_bridge) != ERROR_NONE) {
LOGGER.error("Failed to remove BLE callback");
LOG_E(TAG, "Failed to remove BLE callback");
}
if (bluetooth_set_radio_enabled(dev, false) != ERROR_NONE) {
LOGGER.error("Failed to disable BT radio");
LOG_E(TAG, "Failed to disable BT radio");
// Re-register bridge
bluetooth_add_event_callback(dev, nullptr, bt_event_bridge);
return false;
}
if (device_stop(dev) != ERROR_NONE) {
LOGGER.error("Failed to stop BT device");
LOG_E(TAG, "Failed to stop BT device");
return false;
}
@@ -413,7 +413,7 @@ void unpair(const std::array<uint8_t, 6>& addr) {
}
void connect(const std::array<uint8_t, 6>& addr, int profileId) {
LOGGER.info("connect(profile={})", profileId);
LOG_I(TAG, "connect(profile=%d)", profileId);
if (profileId == BT_PROFILE_HID_HOST) {
hidHostConnect(addr);
} else if (profileId == BT_PROFILE_HID_DEVICE) {
@@ -434,7 +434,7 @@ void connect(const std::array<uint8_t, 6>& addr, int profileId) {
}
void disconnect(const std::array<uint8_t, 6>& addr, int profileId) {
LOGGER.info("disconnect(profile={})", profileId);
LOG_I(TAG, "disconnect(profile=%d)", profileId);
if (profileId == BT_PROFILE_HID_HOST) {
hidHostDisconnect();
} else if (profileId == BT_PROFILE_HID_DEVICE) {
+44 -47
View File
@@ -9,7 +9,6 @@
#include <Tactility/bluetooth/BluetoothPrivate.h>
#include <Tactility/Assets.h>
#include <Tactility/Logger.h>
#include <Tactility/Tactility.h>
#include <Tactility/lvgl/Keyboard.h>
#include <Tactility/lvgl/LvglSync.h>
@@ -22,6 +21,7 @@
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <lvgl.h>
#include <tactility/log.h>
#include <algorithm>
#include <array>
@@ -30,12 +30,9 @@
#include <memory>
#include <vector>
#define TAG "BtHidHost"
#include <esp_log.h>
namespace tt::bluetooth {
static const auto LOGGER = Logger("BtHidHost");
constexpr auto* TAG = "BtHidHost";
// ---- Report type ----
@@ -229,7 +226,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) {
if (hid_host_ctx && hid_host_ctx->mouseIndev == nullptr) {
getMainDispatcher().dispatch([] {
if (!hid_host_ctx || hid_host_ctx->mouseIndev != nullptr) return;
if (!tt::lvgl::lock(1000)) { LOGGER.warn("LVGL lock failed for mouse indev"); return; }
if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for mouse indev"); return; }
auto* ms = lv_indev_create();
lv_indev_set_type(ms, LV_INDEV_TYPE_POINTER);
lv_indev_set_read_cb(ms, hidHostMouseReadCb);
@@ -241,7 +238,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) {
hid_host_ctx->mouseIndev = ms;
hid_host_ctx->mouseCursor = cur;
tt::lvgl::unlock();
LOGGER.info("Mouse indev registered");
LOG_I(TAG, "Mouse indev registered");
});
}
}
@@ -251,11 +248,11 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) {
static void hidEncRetryTimerCb(void* /*arg*/) {
if (hid_host_ctx) {
if (!hid_host_ctx->typeResolutionDone) {
LOGGER.warn("Post-encryption delay — type resolution timed out, proceeding");
LOG_W(TAG, "Post-encryption delay — type resolution timed out, proceeding");
hid_host_ctx->typeResolutionDone = true;
hid_host_ctx->subscribeIdx = 0;
} else {
LOGGER.info("Post-encryption delay complete — starting CCCD subscriptions");
LOG_I(TAG, "Post-encryption delay complete — starting CCCD subscriptions");
}
hidHostSubscribeNext(*hid_host_ctx);
}
@@ -336,7 +333,7 @@ static void applyReportMapTypes(HidHostCtx& ctx) {
if (zeroRptIdx < collOrder.size()) rpt.type = collOrder[zeroRptIdx];
zeroRptIdx++;
}
LOGGER.info("Report val_handle={} reportId={} type={}", rpt.valHandle, rpt.reportId, (int)rpt.type);
LOG_I(TAG, "Report val_handle=%d reportId=%d type=%d", rpt.valHandle, rpt.reportId, (int)rpt.type);
}
ctx.rptMap.clear();
}
@@ -365,7 +362,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) {
uint8_t rpt_ref[2] = {};
os_mbuf_copydata(attr->om, 0, 2, rpt_ref);
ctx.inputRpts[ctx.rptRefReadIdx].reportId = rpt_ref[0];
LOGGER.info("Report[{}] val_handle={} reportId={}", ctx.rptRefReadIdx,
LOG_I(TAG, "Report[%d] val_handle=%d reportId=%d", ctx.rptRefReadIdx,
ctx.inputRpts[ctx.rptRefReadIdx].valHandle, rpt_ref[0]);
}
}
@@ -374,7 +371,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) {
return 0;
}, nullptr);
if (rc != 0) {
LOGGER.warn("rptRef read[{}] failed rc={} — skipping", ctx.rptRefReadIdx, rc);
LOG_W(TAG, "rptRef read[%d] failed rc=%d — skipping", ctx.rptRefReadIdx, rc);
ctx.rptRefReadIdx++;
hidHostStartRptRefRead(ctx);
}
@@ -384,7 +381,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) {
static void hidHostReadReportMap(HidHostCtx& ctx) {
if (ctx.rptMapHandle == 0) {
LOGGER.info("No Report Map char — skipping type resolution");
LOG_I(TAG, "No Report Map char — skipping type resolution");
ctx.typeResolutionDone = true;
ctx.subscribeIdx = 0;
hidHostSubscribeNext(ctx);
@@ -404,10 +401,10 @@ static void hidHostReadReportMap(HidHostCtx& ctx) {
return 0;
}
if (!ctx.rptMap.empty()) {
LOGGER.info("Report map read ({} bytes)", ctx.rptMap.size());
LOG_I(TAG, "Report map read (%d bytes)", (int)ctx.rptMap.size());
applyReportMapTypes(ctx);
} else {
LOGGER.warn("Report map read failed — types remain Unknown");
LOG_W(TAG, "Report map read failed — types remain Unknown");
}
ctx.typeResolutionDone = true;
ctx.subscribeIdx = 0;
@@ -415,7 +412,7 @@ static void hidHostReadReportMap(HidHostCtx& ctx) {
return 0;
}, nullptr);
if (rc != 0) {
LOGGER.warn("Report map read_long failed rc={} — skipping", rc);
LOG_W(TAG, "Report map read_long failed rc=%d — skipping", rc);
ctx.typeResolutionDone = true;
ctx.subscribeIdx = 0;
hidHostSubscribeNext(ctx);
@@ -434,22 +431,22 @@ static int hidHostCccdWriteCb(uint16_t conn_handle, const struct ble_gatt_error*
if ((error->status == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN) ||
error->status == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC))
&& !ctx.securityInitiated) {
LOGGER.info("CCCD auth required — initiating security");
LOG_I(TAG, "CCCD auth required — initiating security");
ctx.securityInitiated = true;
ble_gap_security_initiate(conn_handle);
return 0;
}
if (error->status == BLE_HS_ETIMEOUT) {
LOGGER.warn("CCCD write timed out for report[{}] — skipping", ctx.subscribeIdx);
LOG_W(TAG, "CCCD write timed out for report[%d] — skipping", ctx.subscribeIdx);
ctx.subscribeIdx++;
hidHostSubscribeNext(ctx);
return 0;
}
if (error->status == BLE_HS_ENOTCONN) {
LOGGER.warn("CCCD write failed — not connected");
LOG_W(TAG, "CCCD write failed — not connected");
return 0;
}
LOGGER.warn("CCCD write failed status={}", error->status);
LOG_W(TAG, "CCCD write failed status=%d", error->status);
}
ctx.subscribeIdx++;
hidHostSubscribeNext(ctx);
@@ -459,11 +456,11 @@ static int hidHostCccdWriteCb(uint16_t conn_handle, const struct ble_gatt_error*
static void hidHostSubscribeNext(HidHostCtx& ctx) {
if (ctx.subscribeIdx >= (int)ctx.inputRpts.size()) {
if (ctx.readyBlockFired) {
LOGGER.info("Subscribe ready block already ran — ignoring duplicate");
LOG_I(TAG, "Subscribe ready block already ran — ignoring duplicate");
return;
}
ctx.readyBlockFired = true;
LOGGER.info("All {} reports subscribed — ready", ctx.inputRpts.size());
LOG_I(TAG, "All %d reports subscribed — ready", (int)ctx.inputRpts.size());
if (hid_enc_retry_timer) esp_timer_stop(hid_enc_retry_timer);
if (!hid_host_key_queue) {
@@ -471,14 +468,14 @@ static void hidHostSubscribeNext(HidHostCtx& ctx) {
}
getMainDispatcher().dispatch([] {
if (!hid_host_ctx || hid_host_ctx->kbIndev != nullptr) return;
if (!tt::lvgl::lock(1000)) { LOGGER.warn("LVGL lock failed for kb indev"); return; }
if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for kb indev"); return; }
auto* kb = lv_indev_create();
lv_indev_set_type(kb, LV_INDEV_TYPE_KEYPAD);
lv_indev_set_read_cb(kb, hidHostKeyboardReadCb);
hid_host_ctx->kbIndev = kb;
tt::lvgl::hardware_keyboard_set_indev(kb);
tt::lvgl::unlock();
LOGGER.info("Keyboard indev registered");
LOG_I(TAG, "Keyboard indev registered");
});
auto peer_addr = ctx.peerAddr;
@@ -523,7 +520,7 @@ static void hidHostSubscribeNext(HidHostCtx& ctx) {
&notify_val, sizeof(notify_val),
hidHostCccdWriteCb, nullptr);
if (rc != 0) {
LOGGER.warn("gattc_write_flat CCCD failed rc={}", rc);
LOG_W(TAG, "gattc_write_flat CCCD failed rc=%d", rc);
ctx.subscribeIdx++;
hidHostSubscribeNext(ctx);
}
@@ -554,7 +551,7 @@ static int hidHostDscDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e
int rc = ble_gattc_disc_all_dscs(ctx.connHandle, next_rpt.valHandle, end,
hidHostDscDiscCb, nullptr);
if (rc != 0) {
LOGGER.warn("disc_all_dscs[{}] failed rc={}", next_idx, rc);
LOG_W(TAG, "disc_all_dscs[%d] failed rc=%d", next_idx, rc);
ctx.rptRefReadIdx = 0;
hidHostStartRptRefRead(ctx);
}
@@ -588,14 +585,14 @@ static int hidHostChrDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e
HidHostInputRpt rpt = {};
rpt.valHandle = chr->val_handle;
ctx.inputRpts.push_back(rpt);
LOGGER.info("Input Report chr val_handle={}", chr->val_handle);
LOG_I(TAG, "Input Report chr val_handle=%d", chr->val_handle);
} else if (uuid16 == 0x2A4B) {
ctx.rptMapHandle = chr->val_handle;
}
} else if (error->status == BLE_HS_EDONE) {
std::sort(ctx.allChrDefHandles.begin(), ctx.allChrDefHandles.end());
if (ctx.inputRpts.empty()) {
LOGGER.warn("No Input Report chars — disconnecting");
LOG_W(TAG, "No Input Report chars — disconnecting");
ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM);
return 0;
}
@@ -605,7 +602,7 @@ static int hidHostChrDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e
int rc = ble_gattc_disc_all_dscs(ctx.connHandle, first.valHandle, end,
hidHostDscDiscCb, nullptr);
if (rc != 0) {
LOGGER.warn("disc_all_dscs[0] failed rc={}", rc);
LOG_W(TAG, "disc_all_dscs[0] failed rc=%d", rc);
ctx.rptRefReadIdx = 0;
hidHostStartRptRefRead(ctx);
}
@@ -625,18 +622,18 @@ static int hidHostSvcDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e
if (ble_uuid_u16(&svc->uuid.u) == 0x1812) {
ctx.hidSvcStart = svc->start_handle;
ctx.hidSvcEnd = svc->end_handle;
LOGGER.info("HID service start={} end={}", ctx.hidSvcStart, ctx.hidSvcEnd);
LOG_I(TAG, "HID service start=%d end=%d", ctx.hidSvcStart, ctx.hidSvcEnd);
}
} else if (error->status == BLE_HS_EDONE) {
if (ctx.hidSvcStart == 0) {
LOGGER.warn("No HID service found — disconnecting");
LOG_W(TAG, "No HID service found — disconnecting");
ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM);
return 0;
}
int rc = ble_gattc_disc_all_chrs(ctx.connHandle, ctx.hidSvcStart, ctx.hidSvcEnd,
hidHostChrDiscCb, nullptr);
if (rc != 0) {
LOGGER.warn("disc_all_chrs failed rc={}", rc);
LOG_W(TAG, "disc_all_chrs failed rc=%d", rc);
ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM);
}
}
@@ -653,14 +650,14 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
case BLE_GAP_EVENT_CONNECT:
if (event->connect.status == 0) {
ctx.connHandle = event->connect.conn_handle;
LOGGER.info("Connected (handle={})", ctx.connHandle);
LOG_I(TAG, "Connected (handle=%d)", ctx.connHandle);
int rc = ble_gattc_disc_all_svcs(ctx.connHandle, hidHostSvcDiscCb, nullptr);
if (rc != 0) {
LOGGER.warn("disc_all_svcs failed rc={}", rc);
LOG_W(TAG, "disc_all_svcs failed rc=%d", rc);
ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM);
}
} else {
LOGGER.warn("Connect failed status={}", event->connect.status);
LOG_W(TAG, "Connect failed status=%d", event->connect.status);
hid_host_ctx.reset();
if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) {
bluetooth_set_hid_host_active(dev, false);
@@ -674,7 +671,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
break;
case BLE_GAP_EVENT_DISCONNECT: {
LOGGER.info("Disconnected reason={}", event->disconnect.reason);
LOG_I(TAG, "Disconnected reason=%d", event->disconnect.reason);
lv_indev_t* saved_kb = hid_host_ctx ? hid_host_ctx->kbIndev : nullptr;
lv_indev_t* saved_mouse = hid_host_ctx ? hid_host_ctx->mouseIndev : nullptr;
lv_obj_t* saved_cursor = hid_host_ctx ? hid_host_ctx->mouseCursor : nullptr;
@@ -698,7 +695,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
getMainDispatcher().dispatch([saved_kb, saved_mouse, saved_cursor, saved_queue] {
if (!tt::lvgl::lock(1000)) {
LOGGER.warn("Failed to acquire LVGL lock for indev cleanup");
LOG_W(TAG, "Failed to acquire LVGL lock for indev cleanup");
if (saved_queue) vQueueDelete(saved_queue);
return;
}
@@ -717,7 +714,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
case BLE_GAP_EVENT_ENC_CHANGE:
if (event->enc_change.conn_handle == ctx.connHandle) {
if (event->enc_change.status == 0) {
LOGGER.info("Encryption established — retrying CCCD in 500ms");
LOG_I(TAG, "Encryption established — retrying CCCD in 500ms");
ctx.subscribeIdx = 0;
if (hid_enc_retry_timer) {
esp_timer_stop(hid_enc_retry_timer);
@@ -726,7 +723,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
hidHostSubscribeNext(ctx);
}
} else {
LOGGER.warn("Encryption failed status={}", event->enc_change.status);
LOG_W(TAG, "Encryption failed status=%d", event->enc_change.status);
}
}
break;
@@ -743,7 +740,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
case HidReportType::Keyboard: hidHostHandleKeyboardReport(buf, len); break;
case HidReportType::Mouse: hidHostHandleMouseReport(buf, len); break;
case HidReportType::Consumer:
LOGGER.info("Consumer report len={}", len);
LOG_I(TAG, "Consumer report len=%d", len);
break;
case HidReportType::Unknown:
if (len >= 6) hidHostHandleKeyboardReport(buf, len);
@@ -766,11 +763,11 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) {
void hidHostConnect(const std::array<uint8_t, 6>& addr) {
if (getRadioState() != RadioState::On) {
LOGGER.warn("hidHostConnect: radio not on");
LOG_W(TAG, "hidHostConnect: radio not on");
return;
}
if (hid_host_ctx) {
LOGGER.warn("hidHostConnect: already connecting/connected");
LOG_W(TAG, "hidHostConnect: already connecting/connected");
return;
}
@@ -789,7 +786,7 @@ void hidHostConnect(const std::array<uint8_t, 6>& addr) {
args.dispatch_method = ESP_TIMER_TASK;
args.name = "hid_enc_retry";
if (esp_timer_create(&args, &hid_enc_retry_timer) != ESP_OK) {
LOGGER.error("Failed to create hid_enc_retry timer");
LOG_E(TAG, "Failed to create hid_enc_retry timer");
hid_enc_retry_timer = nullptr;
}
}
@@ -813,7 +810,7 @@ void hidHostConnect(const std::array<uint8_t, 6>& addr) {
int rc = ble_gap_connect(own_addr_type, &ble_addr, 5000, nullptr, hidHostGapCb, nullptr);
if (rc != 0) {
LOGGER.warn("ble_gap_connect failed rc={}", rc);
LOG_W(TAG, "ble_gap_connect failed rc=%d", rc);
hid_host_ctx.reset();
if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) {
bluetooth_set_hid_host_active(dev, false);
@@ -825,7 +822,7 @@ void hidHostConnect(const std::array<uint8_t, 6>& addr) {
bluetooth_fire_event(dev, e);
}
} else {
LOGGER.info("Connecting...");
LOG_I(TAG, "Connecting...");
}
}
@@ -858,7 +855,7 @@ void autoConnectHidHost() {
if (settings::load(settings::addrToHex(r.addr), stored) &&
stored.autoConnect &&
stored.profileId == BT_PROFILE_HID_HOST) {
LOGGER.info("Auto-connecting HID host to {}", settings::addrToHex(r.addr));
LOG_I(TAG, "Auto-connecting HID host to %s", settings::addrToHex(r.addr).c_str());
hidHostConnect(r.addr);
return;
}
@@ -871,7 +868,7 @@ void autoConnectHidHost() {
if (peer.autoConnect && peer.profileId == BT_PROFILE_HID_HOST) {
if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) {
if (!bluetooth_is_scanning(dev)) {
LOGGER.info("Auto-connect HID host: device not in scan, retrying scan");
LOG_I(TAG, "Auto-connect HID host: device not in scan, retrying scan");
bluetooth_scan_start(dev);
}
}
@@ -2,7 +2,7 @@
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
#include <dirent.h>
#include <format>
@@ -13,7 +13,7 @@
namespace tt::bluetooth::settings {
static const auto LOGGER = Logger("BluetoothPairedDevice");
constexpr auto* TAG = "BluetoothPairedDevice";
// Use the same directory as the old service for backward compatibility.
constexpr auto* DATA_DIR = "/data/service/bluetooth";
@@ -34,7 +34,7 @@ std::string addrToHex(const std::array<uint8_t, 6>& addr) {
static bool hexToAddr(const std::string& hex, std::array<uint8_t, 6>& addr) {
if (hex.size() != 12) {
LOGGER.error("hexToAddr() length mismatch: expected 12, got {}", hex.size());
LOG_E(TAG, "hexToAddr() length mismatch: expected 12, got %d", (int)hex.size());
return false;
}
char buf[3] = { 0 };
@@ -44,7 +44,7 @@ static bool hexToAddr(const std::string& hex, std::array<uint8_t, 6>& addr) {
char* endptr = nullptr;
addr[i] = static_cast<uint8_t>(strtoul(buf, &endptr, 16));
if (endptr != buf + 2) {
LOGGER.error("hexToAddr() invalid hex at byte {}: '{}{}'", i, buf[0], buf[1]);
LOG_E(TAG, "hexToAddr() invalid hex at byte %d: '%c%c'", i, buf[0], buf[1]);
return false;
}
}
@@ -88,7 +88,7 @@ bool save(const PairedDevice& device) {
map[KEY_PROFILE_ID] = std::to_string(device.profileId);
auto file_path = getFilePath(addr_hex);
if (!file::findOrCreateParentDirectory(file_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", file_path);
LOG_E(TAG, "Failed to create parent dir for %s", file_path.c_str());
return false;
}
return file::savePropertiesFile(file_path, map);
@@ -2,13 +2,13 @@
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <Tactility/Paths.h>
#include <tactility/log.h>
namespace tt::bluetooth::settings {
static const auto LOGGER = Logger("BluetoothSettings");
constexpr auto* TAG = "BluetoothSettings";
static std::string getSettingsPath() {
return getUserDataPath() + "/settings/bluetooth.settings";
@@ -60,7 +60,7 @@ static bool save(const BluetoothSettings& s) {
map[KEY_MIDI_AUTO_START] = s.midiAutoStart ? "true" : "false";
auto settings_path = getSettingsPath();
if (!file::findOrCreateParentDirectory(settings_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", settings_path);
LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str());
return false;
}
return file::savePropertiesFile(settings_path, map);
@@ -84,7 +84,7 @@ void setEnableOnBoot(bool enable) {
cached.enableOnBoot = enable;
cached_valid = true;
settings_mutex.unlock();
if (!save(cached)) LOGGER.error("Failed to save");
if (!save(cached)) LOG_E(TAG, "Failed to save");
}
bool shouldEnableOnBoot() {
@@ -96,7 +96,7 @@ void setSppAutoStart(bool enable) {
cached.sppAutoStart = enable;
cached_valid = true;
settings_mutex.unlock();
if (!save(cached)) LOGGER.error("Failed to save (setSppAutoStart)");
if (!save(cached)) LOG_E(TAG, "Failed to save (setSppAutoStart)");
}
bool shouldSppAutoStart() {
@@ -108,7 +108,7 @@ void setMidiAutoStart(bool enable) {
cached.midiAutoStart = enable;
cached_valid = true;
settings_mutex.unlock();
if (!save(cached)) LOGGER.error("Failed to save (setMidiAutoStart)");
if (!save(cached)) LOG_E(TAG, "Failed to save (setMidiAutoStart)");
}
bool shouldMidiAutoStart() {
+11 -11
View File
@@ -2,43 +2,43 @@
#include <Tactility/file/ObjectFilePrivate.h>
#include <cstring>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::file {
static const auto LOGGER = Logger("ObjectFileReader");
constexpr auto* TAG = "ObjectFileReader";
bool ObjectFileReader::open() {
auto opening_file = std::unique_ptr<FILE, FileCloser>(fopen(filePath.c_str(), "r"));
if (opening_file == nullptr) {
LOGGER.error("Failed to open file {}", filePath.c_str());
LOG_E(TAG, "Failed to open file %s", filePath.c_str());
return false;
}
FileHeader file_header;
if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) {
LOGGER.error("Failed to read file header from {}", filePath);
LOG_E(TAG, "Failed to read file header from %s", filePath.c_str());
return false;
}
if (file_header.identifier != OBJECT_FILE_IDENTIFIER) {
LOGGER.error("Invalid file type for {}", filePath);
LOG_E(TAG, "Invalid file type for %s", filePath.c_str());
return false;
}
if (file_header.version != OBJECT_FILE_VERSION) {
LOGGER.error("Unknown version for {}: {}", filePath, file_header.identifier);
LOG_E(TAG, "Unknown version for %s: %u", filePath.c_str(), (unsigned)file_header.identifier);
return false;
}
ContentHeader content_header;
if (fread(&content_header, sizeof(ContentHeader), 1, opening_file.get()) != 1) {
LOGGER.error("Failed to read content header from {}", filePath);
LOG_E(TAG, "Failed to read content header from %s", filePath.c_str());
return false;
}
if (recordSize != content_header.recordSize) {
LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize);
LOG_E(TAG, "Record size mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordSize, (unsigned)content_header.recordSize);
return false;
}
@@ -47,8 +47,8 @@ bool ObjectFileReader::open() {
file = std::move(opening_file);
LOGGER.debug("File version: {}", file_header.version);
LOGGER.debug("Content: version = {}, size = {} bytes, count = {}", content_header.recordVersion, content_header.recordSize, content_header.recordCount);
LOG_D(TAG, "File version: %u", (unsigned)file_header.version);
LOG_D(TAG, "Content: version = %u, size = %u bytes, count = %u", (unsigned)content_header.recordVersion, (unsigned)content_header.recordSize, (unsigned)content_header.recordCount);
return true;
}
@@ -63,7 +63,7 @@ void ObjectFileReader::close() {
bool ObjectFileReader::readNext(void* output) {
if (file == nullptr) {
LOGGER.error("File not open");
LOG_E(TAG, "File not open");
return false;
}
+16 -16
View File
@@ -1,24 +1,24 @@
#include <Tactility/file/ObjectFile.h>
#include <Tactility/file/ObjectFilePrivate.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
#include <cstring>
#include <unistd.h>
namespace tt::file {
static const auto LOGGER = Logger("ObjectFileWriter");
constexpr auto* TAG = "ObjectFileWriter";
bool ObjectFileWriter::open() {
bool edit_existing = append && access(filePath.c_str(), F_OK) == 0;
if (append && !edit_existing) {
LOGGER.warn("access() to {} failed: {}", filePath, strerror(errno));
LOG_W(TAG, "access() to %s failed: %s", filePath.c_str(), strerror(errno));
}
// Edit existing or create a new file
auto opening_file = std::unique_ptr<FILE, FileCloser>(std::fopen(filePath.c_str(), edit_existing ? "rb+" : "wb"));
if (opening_file == nullptr) {
LOGGER.error("Failed to open file {}", filePath);
LOG_E(TAG, "Failed to open file %s", filePath.c_str());
return false;
}
@@ -29,17 +29,17 @@ bool ObjectFileWriter::open() {
FileHeader file_header;
if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) {
LOGGER.error("Failed to read file header from {}", filePath);
LOG_E(TAG, "Failed to read file header from %s", filePath.c_str());
return false;
}
if (file_header.identifier != OBJECT_FILE_IDENTIFIER) {
LOGGER.error("Invalid file type for {}", filePath);
LOG_E(TAG, "Invalid file type for %s", filePath.c_str());
return false;
}
if (file_header.version != OBJECT_FILE_VERSION) {
LOGGER.error("Unknown version for {}: {}", filePath, file_header.version);
LOG_E(TAG, "Unknown version for %s: %u", filePath.c_str(), (unsigned)file_header.version);
return false;
}
@@ -47,17 +47,17 @@ bool ObjectFileWriter::open() {
ContentHeader content_header;
if (fread(&content_header, sizeof(ContentHeader), 1, opening_file.get()) != 1) {
LOGGER.error("Failed to read content header from {}", filePath);
LOG_E(TAG, "Failed to read content header from %s", filePath.c_str());
return false;
}
if (recordSize != content_header.recordSize) {
LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize);
LOG_E(TAG, "Record size mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordSize, (unsigned)content_header.recordSize);
return false;
}
if (recordVersion != content_header.recordVersion) {
LOGGER.error("Version mismatch for {}: expected {}, got {}", filePath, recordVersion, content_header.recordVersion);
LOG_E(TAG, "Version mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordVersion, (unsigned)content_header.recordVersion);
return false;
}
@@ -66,7 +66,7 @@ bool ObjectFileWriter::open() {
} else {
FileHeader file_header;
if (fwrite(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) {
LOGGER.error("Failed to write file header for {}", filePath);
LOG_E(TAG, "Failed to write file header for %s", filePath.c_str());
return false;
}
@@ -81,12 +81,12 @@ bool ObjectFileWriter::open() {
void ObjectFileWriter::close() {
if (file == nullptr) {
LOGGER.error("File not opened: {}", filePath);
LOG_E(TAG, "File not opened: %s", filePath.c_str());
return;
}
if (fseek(file.get(), sizeof(FileHeader), SEEK_SET) != 0) {
LOGGER.error("File seek failed: {}", filePath);
LOG_E(TAG, "File seek failed: %s", filePath.c_str());
return;
}
@@ -97,7 +97,7 @@ void ObjectFileWriter::close() {
};
if (fwrite(&content_header, sizeof(ContentHeader), 1, file.get()) != 1) {
LOGGER.error("Failed to write content header to {}", filePath);
LOG_E(TAG, "Failed to write content header to %s", filePath.c_str());
}
file = nullptr;
@@ -105,12 +105,12 @@ void ObjectFileWriter::close() {
bool ObjectFileWriter::write(void* data) {
if (file == nullptr) {
LOGGER.error("File not opened: {}", filePath);
LOG_E(TAG, "File not opened: %s", filePath.c_str());
return false;
}
if (fwrite(data, recordSize, 1, file.get()) != 1) {
LOGGER.error("Failed to write record to {}", filePath);
LOG_E(TAG, "Failed to write record to %s", filePath.c_str());
return false;
}
+6 -6
View File
@@ -3,11 +3,11 @@
#include <Tactility/StringUtils.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::file {
static const auto LOGGER = Logger("PropertiesFile");
constexpr auto* TAG = "PropertiesFile";
bool getKeyValuePair(const std::string& input, std::string& key, std::string& value) {
auto index = input.find('=');
@@ -22,7 +22,7 @@ bool getKeyValuePair(const std::string& input, std::string& key, std::string& va
bool loadPropertiesFile(const std::string& filePath, std::function<void(const std::string& key, const std::string& value)> callback) {
// Reading properties is a common operation; make this debug-level to avoid
// flooding the serial console under frequent polling.
LOGGER.debug("Reading properties file {}", filePath);
LOG_D(TAG, "Reading properties file %s", filePath.c_str());
uint16_t line_count = 0;
std::string key_prefix = "";
// Malformed lines are skipped, valid lines are loaded and callback is called
@@ -40,7 +40,7 @@ bool loadPropertiesFile(const std::string& filePath, std::function<void(const st
std::string trimmed_value = string::trim(value, " \t");
callback(trimmed_key, trimmed_value);
} else {
LOGGER.error("Failed to parse line {} of {} (skipped)", line_count, filePath);
LOG_E(TAG, "Failed to parse line %d of %s (skipped)", line_count, filePath.c_str());
// Continue loading other lines
}
}
@@ -57,11 +57,11 @@ bool loadPropertiesFile(const std::string& filePath, std::map<std::string, std::
bool savePropertiesFile(const std::string& filePath, const std::map<std::string, std::string>& properties) {
bool result = false;
getLock(filePath)->withLock([&result, filePath, &properties] {
LOGGER.info("Saving properties file {}", filePath);
LOG_I(TAG, "Saving properties file %s", filePath.c_str());
FILE* file = fopen(filePath.c_str(), "w");
if (file == nullptr) {
LOGGER.error("Failed to open {}", filePath);
LOG_E(TAG, "Failed to open %s", filePath.c_str());
return;
}
+14 -14
View File
@@ -1,20 +1,20 @@
#include <Tactility/Logger.h>
#include <Tactility/Tactility.h>
#include <tactility/check.h>
#include <Tactility/hal/Configuration.h>
#include <tactility/hal/Device.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/SdCard.h>
#include <Tactility/hal/touch/TouchDevice.h>
#include <Tactility/kernel/SystemEvents.h>
#include <tactility/check.h>
#include <tactility/hal/Device.h>
#include <tactility/log.h>
namespace tt::hal {
static const auto LOGGER = Logger("Hal");
constexpr auto* TAG = "Hal";
void registerDevices(const Configuration& configuration) {
LOGGER.info("Registering devices");
LOG_I(TAG, "Registering devices");
auto devices = configuration.createDevices();
for (auto& device : devices) {
@@ -33,27 +33,27 @@ void registerDevices(const Configuration& configuration) {
}
static void startDisplays() {
LOGGER.info("Starting displays & touch");
LOG_I(TAG, "Starting displays & touch");
auto displays = hal::findDevices<display::DisplayDevice>(Device::Type::Display);
for (auto& display : displays) {
LOGGER.info("{} starting", display->getName());
LOG_I(TAG, "%s starting", display->getName().c_str());
if (!display->start()) {
LOGGER.error("{} start failed", display->getName());
LOG_E(TAG, "%s start failed", display->getName().c_str());
} else {
LOGGER.info("{} started", display->getName());
LOG_I(TAG, "%s started", display->getName().c_str());
if (display->supportsBacklightDuty()) {
LOGGER.info("Setting backlight");
LOG_I(TAG, "Setting backlight");
display->setBacklightDuty(0);
}
auto touch = display->getTouchDevice();
if (touch != nullptr) {
LOGGER.info("{} starting", touch->getName());
LOG_I(TAG, "%s starting", touch->getName().c_str());
if (!touch->start()) {
LOGGER.error("{} start failed", touch->getName());
LOG_E(TAG, "%s start failed", touch->getName().c_str());
} else {
LOGGER.info("{} started", touch->getName());
LOG_I(TAG, "%s started", touch->getName().c_str());
}
}
}
+16 -21
View File
@@ -1,26 +1,25 @@
#include <Tactility/hal/gps/GpsDevice.h>
#include <Tactility/hal/gps/GpsInit.h>
#include <Tactility/hal/gps/Probe.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <cstring>
#include <minmea.h>
namespace tt::hal::gps {
constexpr uint32_t GPS_UART_BUFFER_SIZE = 256;
static const auto LOGGER = Logger("GpsDevice");
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) {
LOGGER.error("Failed to find UART {}", configuration.uartName);
LOG_E(TAG, "Failed to find UART %s", configuration.uartName);
return -1;
}
@@ -33,13 +32,13 @@ int32_t GpsDevice::threadMain() {
error_t error = uart_controller_set_config(uart, &uartConfig);
if (error != ERROR_NONE) {
LOGGER.error("Failed to configure UART {}: {}", configuration.uartName, error_to_string(error));
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) {
LOGGER.error("Failed to open UART {}: {}", configuration.uartName, error_to_string(error));
LOG_E(TAG, "Failed to open UART %s: %s", configuration.uartName, error_to_string(error));
return -1;
}
@@ -47,7 +46,7 @@ int32_t GpsDevice::threadMain() {
if (model == GpsModel::Unknown) {
model = probe(uart);
if (model == GpsModel::Unknown) {
LOGGER.error("Probe failed");
LOG_E(TAG, "Probe failed");
setState(State::Error);
return -1;
}
@@ -57,7 +56,7 @@ int32_t GpsDevice::threadMain() {
mutex.unlock();
if (!init(uart, model)) {
LOGGER.error("Init failed");
LOG_E(TAG, "Init failed");
setState(State::Error);
return -1;
}
@@ -76,7 +75,7 @@ int32_t GpsDevice::threadMain() {
if (bytes_read > 0U) {
LOGGER.info("[{}] {}", bytes_read, reinterpret_cast<const char*>(buffer));
LOG_I(TAG, "[%d] %s", (int)bytes_read, reinterpret_cast<const char*>(buffer));
switch (minmea_sentence_id((char*)buffer, false)) {
case MINMEA_SENTENCE_RMC:
@@ -87,11 +86,9 @@ int32_t GpsDevice::threadMain() {
(*subscription.onData)(getId(), rmc_frame);
}
mutex.unlock();
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("RMC {} lat, {} lon, {} m/s", minmea_tocoord(&rmc_frame.latitude), minmea_tocoord(&rmc_frame.longitude), minmea_tofloat(&rmc_frame.speed));
}
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 {
LOGGER.error("RMC parse error: {}", reinterpret_cast<const char*>(buffer));
LOG_E(TAG, "RMC parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
case MINMEA_SENTENCE_GGA:
@@ -102,11 +99,9 @@ int32_t GpsDevice::threadMain() {
(*subscription.onData)(getId(), gga_frame);
}
mutex.unlock();
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("GGA {} lat, {} lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude));
}
LOG_D(TAG, "GGA %f lat, %f lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude));
} else {
LOGGER.error("GGA parse error: {}", reinterpret_cast<const char*>(buffer));
LOG_E(TAG, "GGA parse error: %s", reinterpret_cast<const char*>(buffer));
}
break;
default:
@@ -116,7 +111,7 @@ int32_t GpsDevice::threadMain() {
}
if (uart_controller_close(uart) != ERROR_NONE) {
LOGGER.warn("Failed to stop UART {}", configuration.uartName);
LOG_W(TAG, "Failed to stop UART %s", configuration.uartName);
}
return 0;
@@ -127,13 +122,13 @@ bool GpsDevice::start() {
lock.lock();
if (thread != nullptr && thread->getState() != Thread::State::Stopped) {
LOGGER.warn("Already started");
LOG_W(TAG, "Already started");
return true;
}
threadInterrupted = false;
LOGGER.info("Starting thread");
LOG_I(TAG, "Starting thread");
setState(State::PendingOn);
thread = std::make_unique<Thread>(
@@ -146,7 +141,7 @@ bool GpsDevice::start() {
thread->setPriority(tt::Thread::Priority::High);
thread->start();
LOGGER.info("Starting finished");
LOG_I(TAG, "Starting finished");
return true;
}
+9 -9
View File
@@ -1,18 +1,18 @@
#include <Tactility/Logger.h>
#include <tactility/check.h>
#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 {
static const auto LOGGER = Logger("Gps");
constexpr auto* TAG = "Gps";
bool initMtk(::Device* uart);
bool initMtkL76b(::Device* uart);
@@ -118,7 +118,7 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t
// 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
LOGGER.info("Got ACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, kernel::getMillis() - startTime);
LOG_I(TAG, "Got ACK for class %02X message %02X in %zu ms", class_id, msg_id, kernel::getMillis() - startTime);
#endif
return GpsResponse::Ok;
}
@@ -126,7 +126,7 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t
// 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
LOGGER.warn("Got NACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, millis() - startTime);
LOG_W(TAG, "Got NACK for class %02X message %02X in %zu ms", class_id, msg_id, millis() - startTime);
#endif
return GpsResponse::NotAck;
}
@@ -169,7 +169,7 @@ bool init(::Device* uart, GpsModel type) {
return initUc6580(uart);
}
LOGGER.info("Init not implemented {}", static_cast<int>(type));
LOG_I(TAG, "Init not implemented %d", static_cast<int>(type));
return false;
}
@@ -219,14 +219,14 @@ bool initAtgm336h(::Device* uart) {
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) {
LOGGER.warn("ATGM336H: Could not set Config");
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) {
LOGGER.warn("ATGM336H: Could not set Update Frequency");
LOG_W(TAG, "ATGM336H: Could not set Update Frequency");
}
// Set the NEMA output messages
@@ -238,7 +238,7 @@ bool initAtgm336h(::Device* uart) {
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) {
LOGGER.warn("ATGM336H: Could not enable NMEA MSG: {}", fields[i]);
LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %u", fields[i]);
}
}
return true;
+7 -7
View File
@@ -1,14 +1,14 @@
#include "Tactility/hal/gps/GpsDevice.h"
#include "Tactility/hal/gps/Ublox.h"
#include <Tactility/Logger.h>
#include <Tactility/kernel/Kernel.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <cstring>
static const auto LOGGER = tt::Logger("Gps");
constexpr auto* TAG = "Gps";
#define GPS_UART_BUFFER_SIZE 256
@@ -65,13 +65,13 @@ GpsResponse getAck(::Device* uart, const char* message, uint32_t waitMillis) {
if ((bytesRead == 767) || (b == '\r')) {
if (strnstr((char*)buffer, message, bytesRead) != nullptr) {
#ifdef GPS_DEBUG
LOGGER.debug("Found: {}", message); // Log the found message
LOG_D(TAG, "Found: %s", message); // Log the found message
#endif
return GpsResponse::Ok;
} else {
bytesRead = 0;
#ifdef GPS_DEBUG
LOGGER.debug("{}", debugmsg);
LOG_D(TAG, "%s", debugmsg.c_str());
#endif
}
}
@@ -85,11 +85,11 @@ GpsResponse getAck(::Device* uart, const char* message, uint32_t waitMillis) {
*/
#define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \
do { \
LOGGER.info("Probing for {} ({})", CHIP, TOWRITE); \
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) { \
LOGGER.info("Probe detected {} {}", CHIP, #DRIVER); \
LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \
return DRIVER; \
} \
} while (0)
@@ -138,7 +138,7 @@ GpsModel probe(::Device* uart) {
if (ublox_result != GpsModel::Unknown) {
return ublox_result;
} else {
LOGGER.warn("No GNSS Module");
LOG_W(TAG, "No GNSS Module");
return GpsModel::Unknown;
}
}
+8 -17
View File
@@ -1,10 +1,11 @@
#include <Tactility/hal/gps/Satellites.h>
#include <Tactility/kernel/Kernel.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::hal::gps {
static const auto LOGGER = Logger("Satellites");
constexpr auto* TAG = "Satellites";
constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
return (TickType_t)(now - timeInThePast) >= expireTimeInTicks;
@@ -33,9 +34,7 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findUnusedRecord() {
if (!result.empty()) {
auto* record = &result.front();
record->inUse = true;
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("Found unused record");
}
LOG_D(TAG, "Found unused record");
return record;
} else {
return nullptr;
@@ -53,9 +52,7 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() {
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)) {
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("! [{}] {} < {}", i, records[i].lastUpdated, expire_duration);
}
LOG_D(TAG, "! [%d] %u < %u", i, records[i].lastUpdated, expire_duration);
candidate_index = i;
break;
}
@@ -64,17 +61,13 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() {
if (records[i].inUse && records[i].lastUpdated < candidate_age) {
candidate_index = i;
candidate_age = records[i].lastUpdated;
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("? [{}] {} < {}", i, records[i].lastUpdated, candidate_age);
}
LOG_D(TAG, "? [%d] %u < %u", i, records[i].lastUpdated, candidate_age);
}
}
assert(candidate_index != -1);
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("Recycled record {}", candidate_index);
}
LOG_D(TAG, "Recycled record %d", candidate_index);
return &records[candidate_index];
}
@@ -101,9 +94,7 @@ void SatelliteStorage::notify(const minmea_sat_info& data) {
record->inUse = true;
record->lastUpdated = kernel::getTicks();
record->data = data;
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("Updated satellite {}: elevation {}, azimuth {}, snr {}", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr);
}
LOG_D(TAG, "Updated satellite %d: elevation %d, azimuth %d, snr %d", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr);
}
}
+38 -38
View File
@@ -1,16 +1,16 @@
#include <Tactility/hal/gps/Ublox.h>
#include <Tactility/hal/gps/UbloxMessages.h>
#include <Tactility/kernel/Kernel.h>
#include <Tactility/Logger.h>
#include <tactility/device.h>
#include <tactility/drivers/uart_controller.h>
#include <tactility/log.h>
#include <cstring>
namespace tt::hal::gps::ublox {
static const auto LOGGER = Logger("Ublox");
constexpr auto* TAG = "Ublox";
bool initUblox6(::Device* uart);
bool initUblox789(::Device* uart, GpsModel model);
@@ -21,7 +21,7 @@ bool initUblox10(::Device* uart);
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) { \
LOGGER.info("Sending packet failed: {}", #ERRMSG); \
LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \
} \
} while (0)
@@ -85,7 +85,7 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
while (kernel::getTicks() - startTime < waitTicks) {
if (ack > 9) {
#ifdef GPS_DEBUG
LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", class_id, msg_id, kernel::getMillis() - startTime);
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
}
@@ -98,7 +98,7 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
if (sCounter == 26) {
#ifdef GPS_DEBUG
LOGGER.info("%s", debugmsg.c_str());
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
return GpsResponse::FrameErrors;
}
@@ -113,9 +113,9 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
} else {
if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message
#ifdef GPS_DEBUG
LOGGER.info("%s", debugmsg.c_str());
LOG_I(TAG, "%s", debugmsg.c_str());
#endif
LOGGER.warn("Got NAK for class {:02X} message {:02X}", class_id, msg_id);
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
@@ -123,8 +123,8 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa
}
}
#ifdef GPS_DEBUG
LOGGER.info("%s", debugmsg.c_str());
LOGGER.warn("No response for class %02X message %02X", class_id, msg_id);
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
}
@@ -190,7 +190,7 @@ static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t reques
} else {
// return payload length
#ifdef GPS_DEBUG
LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", requestedClass, requestedId, kernel::getMillis() - startTime);
LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", requestedClass, requestedId, kernel::getMillis() - startTime);
#endif
return needRead;
}
@@ -214,8 +214,7 @@ static struct uBloxGnssModelInfo {
} ublox_info;
GpsModel probe(::Device* uart) {
LOGGER.info("Probing for U-blox");
constexpr auto DETECTED_MESSAGE = "{} detected, using {} Module";
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));
@@ -224,10 +223,10 @@ GpsModel probe(::Device* uart) {
// Check that the returned response class and message ID are correct
GpsResponse response = getAck(uart, 0x06, 0x08, 750);
if (response == GpsResponse::None) {
LOGGER.warn("No GNSS Module");
LOG_W(TAG, "No GNSS Module");
return GpsModel::Unknown;
} else if (response == GpsResponse::FrameErrors) {
LOGGER.warn("UBlox Frame Errors");
LOG_W(TAG, "UBlox Frame Errors");
}
uint8_t buffer[256];
@@ -265,12 +264,12 @@ GpsModel probe(::Device* uart) {
break;
}
LOGGER.info("Module Info:");
LOGGER.info("Soft version: {}", ublox_info.swVersion);
LOGGER.info("Hard version: {}", ublox_info.hwVersion);
LOGGER.info("Extensions: {}", ublox_info.extensionNo);
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++) {
LOGGER.info(" %s", ublox_info.extension[i]);
LOG_I(TAG, " %s", ublox_info.extension[i]);
}
memset(buffer, 0, sizeof(buffer));
@@ -283,29 +282,30 @@ GpsModel probe(::Device* uart) {
char* ptr = nullptr;
memset(buffer, 0, sizeof(buffer));
strncpy((char*)buffer, &(ublox_info.extension[i][8]), sizeof(buffer));
LOGGER.info("Protocol Version: {}", (char*)buffer);
LOG_I(TAG, "Protocol Version: %s", (char*)buffer);
if (strlen((char*)buffer)) {
ublox_info.protocol_version = strtoul((char*)buffer, &ptr, 10);
LOGGER.info("ProtVer={}", ublox_info.protocol_version);
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) {
LOGGER.info(DETECTED_MESSAGE, "U-blox 6", "6");
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6");
return GpsModel::UBLOX6;
} else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) {
LOGGER.info(DETECTED_MESSAGE, "U-blox 7", "7");
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7");
return GpsModel::UBLOX7;
} else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) {
LOGGER.info(DETECTED_MESSAGE, "U-blox 8", "8");
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8");
return GpsModel::UBLOX8;
} else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) {
LOGGER.info(DETECTED_MESSAGE, "U-blox 9", "9");
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9");
return GpsModel::UBLOX9;
} else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) {
LOGGER.info(DETECTED_MESSAGE, "U-blox 10", "10");
LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10");
return GpsModel::UBLOX10;
}
}
@@ -314,7 +314,7 @@ GpsModel probe(::Device* uart) {
}
bool init(::Device* uart, GpsModel model) {
LOGGER.info("U-blox init");
LOG_I(TAG, "U-blox init");
switch (model) {
case GpsModel::UBLOX6:
return initUblox6(uart);
@@ -325,7 +325,7 @@ bool init(::Device* uart, GpsModel model) {
case GpsModel::UBLOX10:
return initUblox10(uart);
default:
LOGGER.error("Unknown or unsupported U-blox model");
LOG_E(TAG, "Unknown or unsupported U-blox model");
return false;
}
}
@@ -374,9 +374,9 @@ bool initUblox10(::Device* uart) {
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) {
LOGGER.warn("Unable to save GNSS module config");
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOGGER.info("GNSS module configuration saved!");
LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
@@ -384,7 +384,7 @@ bool initUblox10(::Device* uart) {
bool initUblox789(::Device* uart, GpsModel model) {
uint8_t buffer[256];
if (model == GpsModel::UBLOX7) {
LOGGER.debug("Set GPS+SBAS");
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
@@ -394,12 +394,12 @@ bool initUblox789(::Device* uart, GpsModel model) {
if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) {
// It's not critical if the module doesn't acknowledge this configuration.
LOGGER.debug("reconfigure GNSS - defaults maintained. Is this module GPS-only?");
LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?");
} else {
if (model == GpsModel::UBLOX7) {
LOGGER.info("GPS+SBAS configured");
LOG_I(TAG, "GPS+SBAS configured");
} else { // 8,9
LOGGER.info("GPS+SBAS+GLONASS+Galileo configured");
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
@@ -448,9 +448,9 @@ bool initUblox789(::Device* uart, GpsModel model) {
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) {
LOGGER.warn("Unable to save GNSS module config");
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOGGER.info("GNSS module configuration saved!");
LOG_I(TAG, "GNSS module configuration saved!");
}
return true;
}
@@ -482,9 +482,9 @@ bool initUblox6(::Device* uart) {
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) {
LOGGER.warn("Unable to save GNSS module config");
LOG_W(TAG, "Unable to save GNSS module config");
} else {
LOGGER.info("GNSS module config saved!");
LOG_I(TAG, "GNSS module config saved!");
}
return true;
}
+7 -7
View File
@@ -5,14 +5,14 @@
#include <Tactility/hal/usb/Usb.h>
#include <Tactility/hal/usb/UsbTusb.h>
#include <Tactility/Logger.h>
#include <tactility/device.h>
#include <tactility/driver.h>
#include <tactility/drivers/esp32_sdcard.h>
#include <tactility/log.h>
namespace tt::hal::usb {
static const auto LOGGER = Logger("USB");
constexpr auto* TAG = "USB";
constexpr auto BOOT_FLAG_SDMMC = 42; // Existing
constexpr auto BOOT_FLAG_FLASH = 43; // For flash mode
@@ -38,7 +38,7 @@ sdmmc_card_t* getCard() {
});
if (card == nullptr) {
LOGGER.warn("Couldn't find a mounted SD card");
LOG_W(TAG, "Couldn't find a mounted SD card");
}
return card;
@@ -54,7 +54,7 @@ bool isSupported() {
bool startMassStorageWithSdmmc(bool fromBootMode) {
if (!canStartNewMode()) {
LOGGER.error("Can't start");
LOG_E(TAG, "Can't start");
return false;
}
@@ -62,7 +62,7 @@ bool startMassStorageWithSdmmc(bool fromBootMode) {
currentMode = Mode::MassStorageSdmmc;
return true;
} else {
LOGGER.error("Failed to init mass storage");
LOG_E(TAG, "Failed to init mass storage");
return false;
}
}
@@ -95,7 +95,7 @@ void rebootIntoMassStorageSdmmc() {
// NEW: Flash mass storage functions
bool startMassStorageWithFlash(bool fromBootMode) {
if (!canStartNewMode()) {
LOGGER.error("Can't start flash mass storage");
LOG_E(TAG, "Can't start flash mass storage");
return false;
}
@@ -103,7 +103,7 @@ bool startMassStorageWithFlash(bool fromBootMode) {
currentMode = Mode::MassStorageFlash;
return true;
} else {
LOGGER.error("Failed to init flash mass storage");
LOG_E(TAG, "Failed to init flash mass storage");
return false;
}
}
+14 -13
View File
@@ -7,7 +7,6 @@
#if CONFIG_TINYUSB_MSC_ENABLED == 1
#include <Tactility/Logger.h>
#include <esp_system.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
@@ -15,6 +14,8 @@
#include <tusb_msc_storage.h>
#include <wear_levelling.h>
#include <tactility/log.h>
#if CONFIG_IDF_TARGET_ESP32P4
#include "hal/usb_wrap_ll.h"
#endif
@@ -23,7 +24,7 @@
#define TUSB_DESC_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MSC_DESC_LEN)
#define SECTOR_SIZE 512
static const auto LOGGER = tt::Logger("USB");
constexpr auto* TAG = "USB";
namespace tt::hal::usb {
extern sdmmc_card_t* getCard();
@@ -105,18 +106,18 @@ static uint8_t const msc_hs_configuration_desc[] = {
static void storage_mount_changed_cb(tinyusb_msc_event_t* event) {
if (event->mount_changed_data.is_mounted) {
LOGGER.info("MSC Mounted");
LOG_I(TAG, "MSC Mounted");
// Storage is only (re)mounted into our own filesystem after the host sends a SCSI
// START STOP UNIT eject (see tud_msc_start_stop_cb() in tusb_msc_storage.c). Windows
// is known not to send this reliably, so this is a best-effort path for hosts that do
// (e.g. Linux/macOS) - the "Return to OS" button on the boot screen is the primary one.
// If we got here while booted into MSC mode, it's safe to reboot back into normal OS now.
if (startedFromBootMode) {
LOGGER.info("MSC ejected by host, rebooting into normal OS");
LOG_I(TAG, "MSC ejected by host, rebooting into normal OS");
esp_restart();
}
} else {
LOGGER.info("MSC Unmounted");
LOG_I(TAG, "MSC Unmounted");
}
}
@@ -149,7 +150,7 @@ static bool ensureDriverInstalled() {
};
if (tinyusb_driver_install(&tusb_cfg) != ESP_OK) {
LOGGER.error("Failed to install TinyUSB driver");
LOG_E(TAG, "Failed to install TinyUSB driver");
#if CONFIG_IDF_TARGET_ESP32P4
// Roll back routing when TinyUSB did not start.
usb_wrap_ll_phy_select(&USB_WRAP, 1);
@@ -171,7 +172,7 @@ bool tusbStartMassStorageWithSdmmc(bool fromBootMode) {
auto* card = tt::hal::usb::getCard();
if (card == nullptr) {
LOGGER.error("SD card not mounted");
LOG_E(TAG, "SD card not mounted");
return false;
}
@@ -190,16 +191,16 @@ bool tusbStartMassStorageWithSdmmc(bool fromBootMode) {
auto result = tinyusb_msc_storage_init_sdmmc(&config_sdmmc);
if (result != ESP_OK) {
LOGGER.error("TinyUSB SDMMC init failed: {}", esp_err_to_name(result));
LOG_E(TAG, "TinyUSB SDMMC init failed: %s", esp_err_to_name(result));
} else {
LOGGER.info("TinyUSB SDMMC init success");
LOG_I(TAG, "TinyUSB SDMMC init success");
}
return result == ESP_OK;
}
bool tusbStartMassStorageWithFlash(bool fromBootMode) {
LOGGER.info("Starting flash MSC");
LOG_I(TAG, "Starting flash MSC");
if (!ensureDriverInstalled()) {
return false;
}
@@ -207,7 +208,7 @@ bool tusbStartMassStorageWithFlash(bool fromBootMode) {
wl_handle_t handle = tt::getDataPartitionWlHandle();
if (handle == WL_INVALID_HANDLE) {
LOGGER.error("WL not mounted for /data");
LOG_E(TAG, "WL not mounted for /data");
return false;
}
@@ -226,9 +227,9 @@ bool tusbStartMassStorageWithFlash(bool fromBootMode) {
esp_err_t result = tinyusb_msc_storage_init_spiflash(&config_flash);
if (result != ESP_OK) {
LOGGER.error("TinyUSB flash init failed: {}", esp_err_to_name(result));
LOG_E(TAG, "TinyUSB flash init failed: %s", esp_err_to_name(result));
} else {
LOGGER.info("TinyUSB flash init success");
LOG_I(TAG, "TinyUSB flash init success");
}
return result == ESP_OK;
}
+7 -6
View File
@@ -2,15 +2,16 @@
#include <Tactility/file/FileLock.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/settings/Language.h>
#include <tactility/log.h>
#include <format>
#include <utility>
namespace tt::i18n {
static const auto LOGGER = Logger("I18n");
constexpr auto* TAG = "I18n";
static std::string getFallbackLocale() {
return "en-US";
@@ -39,7 +40,7 @@ static std::string getI18nDataFilePath(const std::string& path) {
if (file::isFile(desired_file_path)) {
return desired_file_path;
} else {
LOGGER.warn("Translations not found for {} at {}", locale, desired_file_path);
LOG_W(TAG, "Translations not found for %s at %s", locale.c_str(), desired_file_path.c_str());
}
auto fallback_locale = getFallbackLocale();
@@ -47,7 +48,7 @@ static std::string getI18nDataFilePath(const std::string& path) {
if (file::isFile(fallback_file_path)) {
return fallback_file_path;
} else {
LOGGER.warn("Fallback translations not found for {} at {}", fallback_locale, fallback_file_path);
LOG_W(TAG, "Fallback translations not found for %s at %s", fallback_locale.c_str(), fallback_file_path.c_str());
return "";
}
}
@@ -60,7 +61,7 @@ bool TextResources::load() {
// Resolve the language file that we need (depends on system language selection)
auto file_path = getI18nDataFilePath(path);
if (file_path.empty()) {
LOGGER.error("Couldn't find i18n data for {}", path);
LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str());
return false;
}
@@ -69,7 +70,7 @@ bool TextResources::load() {
});
if (new_data.empty()) {
LOGGER.error("Couldn't find i18n data for {}", path);
LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str());
return false;
}
+3 -3
View File
@@ -1,15 +1,15 @@
#include <Tactility/kernel/SystemEvents.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <tactility/check.h>
#include <tactility/log.h>
#include <Tactility/CoreDefines.h>
#include <list>
namespace tt::kernel {
static const auto LOGGER = Logger("SystemEvents");
constexpr auto* TAG = "SystemEvents";
struct SubscriptionData {
SystemEventSubscription id;
@@ -42,7 +42,7 @@ static const char* getEventName(SystemEvent event) {
}
void publishSystemEvent(SystemEvent event) {
LOGGER.info("{}", getEventName(event));
LOG_I(TAG, "%s", getEventName(event));
if (mutex.lock(MAX_TICKS)) {
for (auto& subscription : subscriptions) {
+23 -23
View File
@@ -3,13 +3,13 @@
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/hal/keyboard/KeyboardDevice.h>
#include <Tactility/hal/touch/TouchDevice.h>
#include <Tactility/Logger.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/log.h>
#include <tactility/lvgl_module.h>
#include <tactility/module.h>
@@ -17,26 +17,26 @@
namespace tt::lvgl {
static const auto LOGGER = Logger("LVGL");
constexpr auto* TAG = "LVGL";
bool isStarted() {
return module_is_started(&lvgl_module);
}
void attachDevices() {
LOGGER.info("Adding devices");
LOG_I(TAG, "Adding devices");
auto lock = getSyncLock()->asScopedLock();
lock.lock();
// Start displays (their related touch devices start automatically within)
LOGGER.info("Start displays");
LOG_I(TAG, "Start displays");
auto displays = hal::findDevices<hal::display::DisplayDevice>(hal::Device::Type::Display);
for (const auto& display: displays) {
if (display->supportsLvgl()) {
if (display->startLvgl()) {
LOGGER.info("Started {}", display->getName());
LOG_I(TAG, "Started %s", display->getName().c_str());
auto lvgl_display = display->getLvglDisplay();
assert(lvgl_display != nullptr);
auto settings = settings::display::loadOrGetDefault();
@@ -45,7 +45,7 @@ void attachDevices() {
lv_display_set_rotation(lvgl_display, rotation);
}
} else {
LOGGER.error("Start failed for {}", display->getName());
LOG_E(TAG, "Start failed for %s", display->getName().c_str());
}
}
}
@@ -57,42 +57,42 @@ void attachDevices() {
// Start display-related peripherals
if (primary_display != nullptr) {
LOGGER.info("Start touch devices");
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_display->getLvglDisplay())) {
LOGGER.info("Started {}", touch_device->getName());
LOG_I(TAG, "Started %s", touch_device->getName().c_str());
} else {
LOGGER.error("Start failed for {}", touch_device->getName());
LOG_E(TAG, "Start failed for %s", touch_device->getName().c_str());
}
}
}
// Start keyboards
LOGGER.info("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_display->getLvglDisplay())) {
lv_indev_t* keyboard_indev = keyboard->getLvglIndev();
hardware_keyboard_set_indev(keyboard_indev);
LOGGER.info("Started {}", keyboard->getName());
LOG_I(TAG, "Started %s", keyboard->getName().c_str());
} else {
LOGGER.error("Start failed for {}", keyboard->getName());
LOG_E(TAG, "Start failed for %s", keyboard->getName().c_str());
}
}
}
// Start encoders
LOGGER.info("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_display->getLvglDisplay())) {
LOGGER.info("Started {}", encoder->getName());
LOG_I(TAG, "Started %s", encoder->getName().c_str());
} else {
LOGGER.error("Start failed for {}", encoder->getName());
LOG_E(TAG, "Start failed for %s", encoder->getName().c_str());
}
}
}
@@ -105,7 +105,7 @@ void attachDevices() {
if (service::getState("Gui") == service::State::Stopped) {
service::startService("Gui");
} else {
LOGGER.error("Gui service is not in Stopped state");
LOG_E(TAG, "Gui service is not in Stopped state");
}
}
@@ -115,13 +115,13 @@ void attachDevices() {
if (service::getState("Statusbar") == service::State::Stopped) {
service::startService("Statusbar");
} else {
LOGGER.error("Statusbar service is not in Stopped state");
LOG_E(TAG, "Statusbar service is not in Stopped state");
}
}
}
void detachDevices() {
LOGGER.info("Removing devices");
LOG_I(TAG, "Removing devices");
auto lock = getSyncLock()->asScopedLock();
lock.lock();
@@ -133,7 +133,7 @@ void detachDevices() {
// Stop keyboards
LOGGER.info("Stopping 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) {
@@ -143,7 +143,7 @@ void detachDevices() {
// Stop touch
LOGGER.info("Stopping 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) {
@@ -154,7 +154,7 @@ void detachDevices() {
// Stop encoders
LOGGER.info("Stopping 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) {
@@ -164,11 +164,11 @@ void detachDevices() {
}
// Stop displays (and their touch devices)
LOGGER.info("Stopping displays");
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()) {
LOGGER.error("Failed to detach display from LVGL");
LOG_E(TAG, "Failed to detach display from LVGL");
}
}
}
+12 -24
View File
@@ -1,7 +1,6 @@
#define LV_USE_PRIVATE_API 1 // For actual lv_obj_t declaration
#include <Tactility/LogMessages.h>
#include <Tactility/Logger.h>
#include <Tactility/PubSub.h>
#include <Tactility/RecursiveMutex.h>
#include <Tactility/Tactility.h>
@@ -13,6 +12,7 @@
#include <Tactility/settings/Time.h>
#include <tactility/check.h>
#include <tactility/log.h>
#include <tactility/lvgl_fonts.h>
#include <tactility/lvgl_module.h>
@@ -20,7 +20,7 @@
namespace tt::lvgl {
static const auto LOGGER = Logger("statusbar");
constexpr auto* TAG = "statusbar";
static void onUpdateTime();
@@ -62,9 +62,7 @@ static TickType_t getNextUpdateTime() {
time_t now = ::time(nullptr);
tm* tm_struct = localtime(&now);
uint32_t seconds_to_wait = 60U - tm_struct->tm_sec;
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("Update in {} s", seconds_to_wait);
}
LOG_D(TAG, "Update in %d s", (int)seconds_to_wait);
return pdMS_TO_TICKS(seconds_to_wait * 1000U);
}
@@ -107,15 +105,13 @@ static lv_obj_class_t statusbar_class = {
};
static void statusbar_pubsub_event(Statusbar* statusbar) {
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("Update event");
}
LOG_D(TAG, "Update event");
if (lock(defaultLockTime)) {
update_main(statusbar);
lv_obj_invalidate(&statusbar->obj);
unlock();
} else {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "Statusbar");
LOG_W(TAG, "Mutex acquisition timeout (%s)", "Statusbar");
}
}
@@ -247,9 +243,7 @@ int8_t statusbar_icon_add(const std::string& image, bool visible) {
statusbar_data.icons[i].visible = visible;
statusbar_data.icons[i].image = image;
result = i;
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("id {}: added", i);
}
LOG_D(TAG, "id %d: added", (int)i);
break;
}
}
@@ -263,9 +257,7 @@ int8_t statusbar_icon_add() {
}
void statusbar_icon_remove(int8_t id) {
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("id {}: remove", id);
}
LOG_D(TAG, "id %d: remove", (int)id);
check(id >= 0 && id < STATUSBAR_ICON_LIMIT);
statusbar_data.mutex.lock();
StatusbarIcon* icon = &statusbar_data.icons[id];
@@ -277,12 +269,10 @@ void statusbar_icon_remove(int8_t id) {
}
void statusbar_icon_set_image(int8_t id, const std::string& image) {
if (LOGGER.isLoggingDebug()) {
if (image.empty()) {
LOGGER.debug("id {}: set image (none)", id);
} else {
LOGGER.debug("id {}: set image {}", id, image);
}
if (image.empty()) {
LOG_D(TAG, "id %d: set image (none)", (int)id);
} else {
LOG_D(TAG, "id %d: set image %s", (int)id, image.c_str());
}
check(id >= 0 && id < STATUSBAR_ICON_LIMIT);
statusbar_data.mutex.lock();
@@ -294,9 +284,7 @@ void statusbar_icon_set_image(int8_t id, const std::string& image) {
}
void statusbar_icon_set_visibility(int8_t id, bool visible) {
if (LOGGER.isLoggingDebug()) {
LOGGER.debug("id {}: set visibility {}", id, visible);
}
LOG_D(TAG, "id %d: set visibility %d", (int)id, (int)visible);
check(id >= 0 && id < STATUSBAR_ICON_LIMIT);
statusbar_data.mutex.lock();
StatusbarIcon* icon = &statusbar_data.icons[id];
+13 -14
View File
@@ -7,10 +7,9 @@
#include <Tactility/lvgl/Keyboard.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/Logger.h>
#include <tactility/device.h>
#include <tactility/drivers/usb_host_hid.h>
#include <tactility/log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
@@ -21,7 +20,7 @@
namespace tt::lvgl {
static const auto LOGGER = Logger("UsbHidInput");
constexpr auto* TAG = "UsbHidInput";
constexpr auto HID_EVENT_QUEUE_SIZE = 64;
constexpr auto KEY_EVENT_QUEUE_SIZE = 64;
@@ -147,7 +146,7 @@ static void keyboard_read_cb(lv_indev_t* indev, lv_indev_data_t* data) {
static void usbHidInputTask(void* arg) {
auto* ctx = static_cast<UsbHidInputCtx*>(arg);
LOGGER.info("started");
LOG_I(TAG, "started");
while (!lv_is_initialized()) {
vTaskDelay(pdMS_TO_TICKS(100));
@@ -172,9 +171,9 @@ static void usbHidInputTask(void* arg) {
lv_indev_set_group(ctx->kb_indev, lv_group_get_default());
unlock();
LOGGER.info("LVGL input devices registered");
LOG_I(TAG, "LVGL input devices registered");
} else {
LOGGER.warn("could not acquire LVGL lock for indev registration");
LOG_W(TAG, "could not acquire LVGL lock for indev registration");
}
// Drain the HID event queue and route events to the appropriate destinations
@@ -270,7 +269,7 @@ static void usbHidInputTask(void* arg) {
unlock();
}
LOGGER.info("stopped");
LOG_I(TAG, "stopped");
xSemaphoreGive(ctx->task_done);
vTaskDelete(nullptr);
}
@@ -282,14 +281,14 @@ void startUsbHidInput() {
ctx->hid_queue = xQueueCreate(HID_EVENT_QUEUE_SIZE, sizeof(UsbHidEvent));
if (!ctx->hid_queue) {
LOGGER.error("failed to create HID event queue");
LOG_E(TAG, "failed to create HID event queue");
delete ctx;
return;
}
ctx->key_queue = xQueueCreate(KEY_EVENT_QUEUE_SIZE, sizeof(KeyEvent));
if (!ctx->key_queue) {
LOGGER.error("failed to create key event queue");
LOG_E(TAG, "failed to create key event queue");
vQueueDelete(ctx->hid_queue);
delete ctx;
return;
@@ -297,7 +296,7 @@ void startUsbHidInput() {
ctx->task_done = xSemaphoreCreateBinary();
if (!ctx->task_done) {
LOGGER.error("failed to create task done semaphore");
LOG_E(TAG, "failed to create task done semaphore");
vQueueDelete(ctx->hid_queue);
vQueueDelete(ctx->key_queue);
delete ctx;
@@ -309,7 +308,7 @@ void startUsbHidInput() {
ctx->running = true;
if (xTaskCreate(usbHidInputTask, "usb_hid_inp", TASK_STACK, ctx, TASK_PRIORITY, &ctx->task) != pdPASS) {
LOGGER.error("failed to create task");
LOG_E(TAG, "failed to create task");
ctx->running = false;
if (hid_dev) usb_host_hid_unsubscribe(hid_dev, ctx->hid_queue);
vQueueDelete(ctx->hid_queue);
@@ -320,7 +319,7 @@ void startUsbHidInput() {
}
s_ctx = ctx;
LOGGER.info("started");
LOG_I(TAG, "started");
}
void stopUsbHidInput() {
@@ -331,7 +330,7 @@ void stopUsbHidInput() {
ctx->running = false;
if (xSemaphoreTake(ctx->task_done, pdMS_TO_TICKS(STOP_TIMEOUT_MS)) != pdTRUE) {
LOGGER.warn("task stop timed out, force terminating");
LOG_W(TAG, "task stop timed out, force terminating");
vTaskDelete(ctx->task);
// Task was killed before it could clean up LVGL objects; do it here to
// prevent mouse_read_cb / keyboard_read_cb from running with a freed ctx.
@@ -357,7 +356,7 @@ void stopUsbHidInput() {
vSemaphoreDelete(ctx->task_done);
delete ctx;
LOGGER.info("stopped");
LOG_I(TAG, "stopped");
}
} // namespace tt::lvgl
+8 -7
View File
@@ -1,10 +1,11 @@
#include <Tactility/Tactility.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/network/Http.h>
#include "Tactility/service/gui/GuiService.h"
#include <tactility/log.h>
#ifdef ESP_PLATFORM
#include <Tactility/network/EspHttpClient.h>
#include <esp_http_client.h>
@@ -12,7 +13,7 @@
namespace tt::network::http {
static const auto LOGGER = Logger("HTTP");
constexpr auto* TAG = "HTTP";
void download(
const std::string& url,
@@ -22,10 +23,10 @@ void download(
const std::function<void(const char* errorMessage)>& onError
) {
service::gui::warnIfRunningOnGuiTask("HTTP");
LOGGER.info("Downloading from {} to {}", url, downloadFilePath);
LOG_I(TAG, "Downloading from %s to %s", url.c_str(), downloadFilePath.c_str());
#ifdef ESP_PLATFORM
getMainDispatcher().dispatch([url, certFilePath, downloadFilePath, onSuccess, onError] {
LOGGER.info("Loading certificate");
LOG_I(TAG, "Loading certificate");
auto certificate = file::readString(certFilePath);
if (certificate == nullptr) {
onError("Failed to read certificate");
@@ -71,14 +72,14 @@ void download(
auto lock = file::getLock(downloadFilePath)->asScopedLock();
lock.lock();
LOGGER.info("opening {}", downloadFilePath);
LOG_I(TAG, "opening %s", downloadFilePath.c_str());
auto* file = fopen(downloadFilePath.c_str(), "wb");
if (file == nullptr) {
onError("Failed to open file");
return;
}
LOGGER.info("Writing {} bytes to {}", bytes_left, downloadFilePath);
LOG_I(TAG, "Writing %d bytes to %s", bytes_left, downloadFilePath.c_str());
char buffer[512];
while (bytes_left > 0) {
int data_read = client->read(buffer, 512);
@@ -96,7 +97,7 @@ void download(
taskYIELD();
}
fclose(file);
LOGGER.info("Downloaded {} to {}", url, downloadFilePath);
LOG_I(TAG, "Downloaded %s to %s", url.c_str(), downloadFilePath.c_str());
onSuccess();
});
#else
+10 -9
View File
@@ -2,12 +2,13 @@
#include <Tactility/network/HttpServer.h>
#include <Tactility/Logger.h>
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/log.h>
namespace tt::network {
static const auto LOGGER = Logger("HttpServer");
constexpr auto* TAG = "HttpServer";
static constexpr size_t INTERNAL_URI_HANDLER_COUNT = 2;
@@ -19,14 +20,14 @@ bool HttpServer::startInternal() {
config.max_uri_handlers = handlers.size() + INTERNAL_URI_HANDLER_COUNT;
if (httpd_start(&server, &config) != ESP_OK) {
LOGGER.error("Failed to start http server on port {}", port);
LOG_E(TAG, "Failed to start http server on port %u", (unsigned)port);
return false;
}
bool allRegistered = true;
for (std::vector<httpd_uri_t>::reference handler : handlers) {
if (httpd_register_uri_handler(server, &handler) != ESP_OK) {
LOGGER.error("Failed to register URI handler: {}", handler.uri);
LOG_E(TAG, "Failed to register URI handler: %s", handler.uri);
allRegistered = false;
}
}
@@ -36,17 +37,17 @@ bool HttpServer::startInternal() {
return false;
}
LOGGER.info("Started on port {}", config.server_port);
LOG_I(TAG, "Started on port %u", (unsigned)config.server_port);
return true;
}
void HttpServer::stopInternal() {
LOGGER.info("Stopping server");
LOG_I(TAG, "Stopping server");
if (server != nullptr) {
if (httpd_stop(server) == ESP_OK) {
server = nullptr;
} else {
LOGGER.warn("Error while stopping");
LOG_W(TAG, "Error while stopping");
}
}
}
@@ -56,7 +57,7 @@ bool HttpServer::start() {
lock.lock();
if (isStarted()) {
LOGGER.warn("Already started");
LOG_W(TAG, "Already started");
return true;
}
@@ -68,7 +69,7 @@ void HttpServer::stop() {
lock.lock();
if (!isStarted()) {
LOGGER.warn("Not started");
LOG_W(TAG, "Not started");
return;
}
+12 -11
View File
@@ -1,8 +1,9 @@
#include <Tactility/network/HttpdReq.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/StringUtils.h>
#include <Tactility/file/File.h>
#include <Tactility/network/HttpdReq.h>
#include <tactility/log.h>
#include <memory>
#include <ranges>
@@ -12,7 +13,7 @@
namespace tt::network {
static const auto LOGGER = Logger("HttpdReq");
constexpr auto* TAG = "HttpdReq";
bool getHeaderOrSendError(httpd_req_t* request, const std::string& name, std::string& value) {
size_t header_size = httpd_req_get_hdr_value_len(request, name.c_str());
@@ -23,7 +24,7 @@ bool getHeaderOrSendError(httpd_req_t* request, const std::string& name, std::st
auto header_buffer = std::make_unique<char[]>(header_size + 1);
if (header_buffer == nullptr) {
LOGGER.error( LOG_MESSAGE_ALLOC_FAILED);
LOG_E(TAG, LOG_MESSAGE_ALLOC_FAILED);
httpd_resp_send_500(request);
return false;
}
@@ -79,7 +80,7 @@ std::unique_ptr<char[]> receiveByteArray(httpd_req_t* request, size_t length, si
// and we don't have exceptions enabled in the compiler settings
auto* buffer = static_cast<char*>(malloc(length));
if (buffer == nullptr) {
LOGGER.error(LOG_MESSAGE_ALLOC_FAILED_FMT, length);
LOG_E(TAG, "Out of memory (failed to allocated %u bytes)", (unsigned)length);
return nullptr;
}
@@ -92,16 +93,16 @@ std::unique_ptr<char[]> receiveByteArray(httpd_req_t* request, size_t length, si
// Timeout - retry with backoff
timeout_retries++;
if (timeout_retries >= MAX_TIMEOUT_RETRIES) {
LOGGER.warn("Recv timeout after {} retries, read {}/{} bytes", timeout_retries, bytesRead, length);
LOG_W(TAG, "Recv timeout after %d retries, read %u/%u bytes", timeout_retries, (unsigned)bytesRead, (unsigned)length);
free(buffer);
return nullptr;
}
LOGGER.warn("Recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES);
LOG_W(TAG, "Recv timeout, retry %d/%d", timeout_retries, MAX_TIMEOUT_RETRIES);
vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Exponential backoff
continue;
}
if (bytes_received <= 0) {
LOGGER.warn("Received error {} after reading {}/{} bytes", bytes_received, bytesRead, length);
LOG_W(TAG, "Received error %d after reading %u/%u bytes", bytes_received, (unsigned)bytesRead, (unsigned)length);
free(buffer);
return nullptr;
}
@@ -190,7 +191,7 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP
auto* file = fopen(filePath.c_str(), "wb");
if (file == nullptr) {
LOGGER.error("Failed to open file for writing: {}", filePath);
LOG_E(TAG, "Failed to open file for writing: %s", filePath.c_str());
return 0;
}
@@ -198,11 +199,11 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP
auto expected_chunk_size = std::min<size_t>(BUFFER_SIZE, length - bytes_received);
size_t receive_chunk_size = httpd_req_recv(request, buffer, expected_chunk_size);
if (receive_chunk_size <= 0) {
LOGGER.error("Receive failed");
LOG_E(TAG, "Receive failed");
break;
}
if (fwrite(buffer, 1, receive_chunk_size, file) != (size_t)receive_chunk_size) {
LOGGER.error("Failed to write all bytes");
LOG_E(TAG, "Failed to write all bytes");
break;
}
bytes_received += receive_chunk_size;
+6 -5
View File
@@ -1,7 +1,8 @@
#include <Tactility/network/NtpPrivate.h>
#include <Tactility/Logger.h>
#include <Tactility/Preferences.h>
#include <tactility/log.h>
#include <memory>
#ifdef ESP_PLATFORM
@@ -13,7 +14,7 @@
namespace tt::network::ntp {
static const auto LOGGER = Logger("NTP");
constexpr auto* TAG = "NTP";
static bool processedSyncEvent = false;
@@ -25,14 +26,14 @@ void storeTimeInNvs() {
auto preferences = std::make_unique<Preferences>("time");
preferences->putInt64("syncTime", now);
LOGGER.info("Stored time {}", now);
LOG_I(TAG, "Stored time %ld", (long)now);
}
void setTimeFromNvs() {
auto preferences = std::make_unique<Preferences>("time");
time_t synced_time;
if (preferences->optInt64("syncTime", synced_time)) {
LOGGER.info("Restoring last known time to {}", synced_time);
LOG_I(TAG, "Restoring last known time to %ld", (long)synced_time);
timeval get_nvs_time;
get_nvs_time.tv_sec = synced_time;
settimeofday(&get_nvs_time, nullptr);
@@ -40,7 +41,7 @@ void setTimeFromNvs() {
}
static void onTimeSynced(timeval* tv) {
LOGGER.info("Time synced ({})", tv->tv_sec);
LOG_I(TAG, "Time synced (%ld)", (long)tv->tv_sec);
processedSyncEvent = true;
esp_netif_sntp_deinit();
storeTimeInNvs();
@@ -1,15 +1,16 @@
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <Tactility/service/ServiceInstance.h>
#include <Tactility/service/ServiceManifest.h>
#include <string>
#include <tactility/log.h>
namespace tt::service {
static const auto LOGGER = Logger("ServiceRegistration");
constexpr auto* TAG = "ServiceRegistration";
typedef std::unordered_map<std::string, std::shared_ptr<const ServiceManifest>> ManifestMap;
typedef std::unordered_map<std::string, std::shared_ptr<ServiceInstance>> ServiceInstanceMap;
@@ -25,13 +26,13 @@ void addService(std::shared_ptr<const ServiceManifest> manifest, bool autoStart)
// We'll move the manifest pointer, but we'll need to id later
const auto& id = manifest->id;
LOGGER.info("Adding {}", id);
LOG_I(TAG, "Adding %s", id.c_str());
manifest_mutex.lock();
if (service_manifest_map[id] == nullptr) {
service_manifest_map[id] = std::move(manifest);
} else {
LOGGER.error("Service id in use: {}", id);
LOG_E(TAG, "Service id in use: %s", id.c_str());
}
manifest_mutex.unlock();
@@ -62,10 +63,10 @@ static std::shared_ptr<ServiceInstance> findServiceInstanceById(const std::strin
// TODO: Return proper error/status instead of BOOL?
bool startService(const std::string& id) {
LOGGER.info("Starting {}", id);
LOG_I(TAG, "Starting %s", id.c_str());
auto manifest = findManifestById(id);
if (manifest == nullptr) {
LOGGER.error("manifest not found for service {}", id);
LOG_E(TAG, "manifest not found for service %s", id.c_str());
return false;
}
@@ -80,14 +81,14 @@ bool startService(const std::string& id) {
if (service_instance->getService()->onStart(*service_instance)) {
service_instance->setState(State::Started);
} else {
LOGGER.error("Starting {} failed", id);
LOG_E(TAG, "Starting %s failed", id.c_str());
service_instance->setState(State::Stopped);
instance_mutex.lock();
service_instance_map.erase(manifest->id);
instance_mutex.unlock();
}
LOGGER.info("Started {}", id);
LOG_I(TAG, "Started %s", id.c_str());
return true;
}
@@ -102,10 +103,10 @@ std::shared_ptr<Service> findServiceById(const std::string& id) {
}
bool stopService(const std::string& id) {
LOGGER.info("Stopping {}", id);
LOG_I(TAG, "Stopping %s", id.c_str());
auto service_instance = findServiceInstanceById(id);
if (service_instance == nullptr) {
LOGGER.warn("Service not running: {}", id);
LOG_W(TAG, "Service not running: %s", id.c_str());
return false;
}
@@ -118,10 +119,10 @@ bool stopService(const std::string& id) {
instance_mutex.unlock();
if (service_instance.use_count() > 1) {
LOGGER.warn("Possible memory leak: service {} still has {} references", service_instance->getManifest().id, service_instance.use_count() - 1);
LOG_W(TAG, "Possible memory leak: service %s still has %d references", service_instance->getManifest().id.c_str(), (int)(service_instance.use_count() - 1));
}
LOGGER.info("Stopped {}", id);
LOG_I(TAG, "Stopped %s", id.c_str());
return true;
}
@@ -7,7 +7,6 @@
#include <Tactility/file/File.h>
#include <Tactility/network/HttpdReq.h>
#include <Tactility/network/Url.h>
#include <Tactility/Logger.h>
#include <Tactility/Paths.h>
#include <Tactility/service/development/DevelopmentSettings.h>
#include <Tactility/service/ServiceRegistration.h>
@@ -16,11 +15,13 @@
#include <ranges>
#include <sstream>
#include <tactility/log.h>
namespace tt::service::development {
extern const ServiceManifest manifest;
static const auto LOGGER = Logger("DevService");
constexpr auto* TAG = "DevService";
bool DevelopmentService::onStart(ServiceContext& service) {
std::stringstream stream;
@@ -66,26 +67,26 @@ bool DevelopmentService::isEnabled() const {
// region endpoints
esp_err_t DevelopmentService::handleGetInfo(httpd_req_t* request) {
LOGGER.info("GET /device");
LOG_I(TAG, "GET /device");
if (httpd_resp_set_type(request, "application/json") != ESP_OK) {
LOGGER.warn("Failed to send header");
LOG_W(TAG, "Failed to send header");
return ESP_FAIL;
}
auto* service = static_cast<DevelopmentService*>(request->user_ctx);
if (httpd_resp_sendstr(request, service->deviceResponse.c_str()) != ESP_OK) {
LOGGER.warn("Failed to send response body");
LOG_W(TAG, "Failed to send response body");
return ESP_FAIL;
}
LOGGER.info("[200] /device");
LOG_I(TAG, "[200] /device");
return ESP_OK;
}
esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) {
LOGGER.info("POST /app/run");
LOG_I(TAG, "POST /app/run");
std::string query;
if (!network::getQueryOrSendError(request, query)) {
@@ -95,7 +96,7 @@ esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) {
auto parameters = network::parseUrlQuery(query);
auto id_key_pos = parameters.find("id");
if (id_key_pos == parameters.end()) {
LOGGER.warn("[400] /app/run id not specified");
LOG_W(TAG, "[400] /app/run id not specified");
httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id not specified");
return ESP_FAIL;
}
@@ -107,14 +108,14 @@ esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) {
app::start(app_id);
LOGGER.info("[200] /app/run {}", id_key_pos->second);
LOG_I(TAG, "[200] /app/run %s", id_key_pos->second.c_str());
httpd_resp_send(request, nullptr, 0);
return ESP_OK;
}
esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) {
LOGGER.info("PUT /app/install");
LOG_I(TAG, "PUT /app/install");
std::string boundary;
if (!network::getMultiPartBoundaryOrSendError(request, boundary)) {
@@ -175,7 +176,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) {
content_left -= boundary_and_newlines_after_file.length();
if (content_left != 0) {
LOGGER.warn("We have more bytes at the end of the request parsing?!");
LOG_W(TAG, "We have more bytes at the end of the request parsing?!");
}
if (!app::install(file_path)) {
@@ -184,10 +185,10 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) {
}
if (!file::deleteFile(file_path)) {
LOGGER.warn("Failed to delete {}", file_path);
LOG_W(TAG, "Failed to delete %s", file_path.c_str());
}
LOGGER.info("[200] /app/install -> {}", file_path);
LOG_I(TAG, "[200] /app/install -> %s", file_path.c_str());
httpd_resp_send(request, nullptr, 0);
@@ -195,7 +196,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) {
}
esp_err_t DevelopmentService::handleAppUninstall(httpd_req_t* request) {
LOGGER.info("PUT /app/uninstall");
LOG_I(TAG, "PUT /app/uninstall");
std::string query;
if (!network::getQueryOrSendError(request, query)) {
@@ -205,23 +206,23 @@ esp_err_t DevelopmentService::handleAppUninstall(httpd_req_t* request) {
auto parameters = network::parseUrlQuery(query);
auto id_key_pos = parameters.find("id");
if (id_key_pos == parameters.end()) {
LOGGER.warn("[400] /app/uninstall id not specified");
LOG_W(TAG, "[400] /app/uninstall id not specified");
httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id not specified");
return ESP_FAIL;
}
if (!app::findAppManifestById(id_key_pos->second)) {
LOGGER.info("[200] /app/uninstall {} (app wasn't installed)", id_key_pos->second);
LOG_I(TAG, "[200] /app/uninstall %s (app wasn't installed)", id_key_pos->second.c_str());
httpd_resp_send(request, nullptr, 0);
return ESP_OK;
}
if (app::uninstall(id_key_pos->second)) {
LOGGER.info("[200] /app/uninstall {}", id_key_pos->second);
LOG_I(TAG, "[200] /app/uninstall %s", id_key_pos->second.c_str());
httpd_resp_send(request, nullptr, 0);
return ESP_OK;
} else {
LOGGER.warn("[500] /app/uninstall {}", id_key_pos->second);
LOG_W(TAG, "[500] /app/uninstall %s", id_key_pos->second.c_str());
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to uninstall");
return ESP_FAIL;
}
@@ -1,15 +1,16 @@
#ifdef ESP_PLATFORM
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Logger.h>
#include <Tactility/Paths.h>
#include <Tactility/service/development/DevelopmentSettings.h>
#include <map>
#include <string>
#include <tactility/log.h>
namespace tt::service::development {
static const auto LOGGER = Logger("DevSettings");
constexpr auto* TAG = "DevSettings";
static std::string getSettingsFilePath() {
return getUserDataPath() + "/settings/development.properties";
@@ -46,7 +47,7 @@ static bool save(const DevelopmentSettings& settings) {
map[SETTINGS_KEY_ENABLE_ON_BOOT] = settings.enableOnBoot ? "true" : "false";
auto settings_path = getSettingsFilePath();
if (!file::findOrCreateParentDirectory(settings_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", settings_path);
LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str());
return false;
}
return file::savePropertiesFile(settings_path, map);
@@ -55,7 +56,7 @@ static bool save(const DevelopmentSettings& settings) {
void setEnableOnBoot(bool enable) {
DevelopmentSettings properties { .enableOnBoot = enable };
if (!save(properties)) {
LOGGER.error("Failed to save {}", getSettingsFilePath());
LOG_E(TAG, "Failed to save %s", getSettingsFilePath().c_str());
}
}
@@ -8,7 +8,7 @@
#include "MystifyScreensaver.h"
#include "StackChanScreensaver.h"
#include <Tactility/Logger.h>
#include <tactility/log.h>
#include <Tactility/CoreDefines.h>
#include <Tactility/hal/display/DisplayDevice.h>
#include <Tactility/lvgl/LvglSync.h>
@@ -20,7 +20,7 @@
namespace tt::service::displayidle {
static const auto LOGGER = Logger("DisplayIdle");
constexpr auto* TAG = "DisplayIdle";
constexpr uint32_t kWakeActivityThresholdMs = 100;
@@ -224,7 +224,7 @@ void DisplayIdleService::onStop(ServiceContext& service) {
}
}
if (screensaverOverlay) {
LOGGER.warn("Failed to stop screensaver during shutdown - potential resource leak");
LOG_W(TAG, "Failed to stop screensaver during shutdown - potential resource leak");
}
}
screensaver.reset();
+10 -10
View File
@@ -7,18 +7,18 @@
#include <Tactility/service/espnow/EspNow.h>
#include <Tactility/service/espnow/EspNowService.h>
#include <Tactility/Logger.h>
#include <tactility/log.h>
namespace tt::service::espnow {
static const auto LOGGER = Logger("EspNow");
constexpr auto* TAG = "EspNow";
void enable(const EspNowConfig& config) {
auto service = findService();
if (service != nullptr) {
service->enable(config);
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
}
}
@@ -27,7 +27,7 @@ void disable() {
if (service != nullptr) {
service->disable();
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
}
}
@@ -36,7 +36,7 @@ bool isEnabled() {
if (service != nullptr) {
return service->isEnabled();
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
return false;
}
}
@@ -46,7 +46,7 @@ bool addPeer(const esp_now_peer_info_t& peer) {
if (service != nullptr) {
return service->addPeer(peer);
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
return false;
}
}
@@ -56,7 +56,7 @@ bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength) {
if (service != nullptr) {
return service->send(address, buffer, bufferLength);
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
return false;
}
}
@@ -66,7 +66,7 @@ ReceiverSubscription subscribeReceiver(std::function<void(const esp_now_recv_inf
if (service != nullptr) {
return service->subscribeReceiver(onReceive);
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
return -1;
}
}
@@ -76,7 +76,7 @@ void unsubscribeReceiver(ReceiverSubscription subscription) {
if (service != nullptr) {
service->unsubscribeReceiver(subscription);
} else {
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
}
}
@@ -85,7 +85,7 @@ uint32_t getVersion() {
if (service != nullptr) {
return service->getVersion();
}
LOGGER.error("Service not found");
LOG_E(TAG, "Service not found");
return 0;
}
@@ -4,7 +4,6 @@
#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED)
#include <Tactility/Logger.h>
#include <Tactility/Tactility.h>
#include <Tactility/service/espnow/EspNowService.h>
#include <Tactility/service/ServiceManifest.h>
@@ -15,11 +14,13 @@
#include <esp_now.h>
#include <esp_random.h>
#include <tactility/log.h>
namespace tt::service::espnow {
extern const ServiceManifest manifest;
static const auto LOGGER = Logger("EspNowService");
constexpr auto* TAG = "EspNowService";
static uint8_t BROADCAST_MAC[ESP_NOW_ETH_ALEN];
constexpr TickType_t MAX_DELAY = 1000U / portTICK_PERIOD_MS;
@@ -60,17 +61,17 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) {
}
if (!initWifi(config)) {
LOGGER.error("initWifi() failed");
LOG_E(TAG,"initWifi() failed");
return;
}
if (esp_now_init() != ESP_OK) {
LOGGER.error("esp_now_init() failed");
LOG_E(TAG,"esp_now_init() failed");
return;
}
if (esp_now_register_recv_cb(receiveCallback) != ESP_OK) {
LOGGER.error("esp_now_register_recv_cb() failed");
LOG_E(TAG,"esp_now_register_recv_cb() failed");
return;
}
@@ -80,15 +81,15 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) {
//#endif
if (esp_now_set_pmk(config.masterKey) != ESP_OK) {
LOGGER.error("esp_now_set_pmk() failed");
LOG_E(TAG,"esp_now_set_pmk() failed");
return;
}
espnowVersion = 0;
if (esp_now_get_version(&espnowVersion) == ESP_OK) {
LOGGER.info("ESP-NOW version: {}.0", espnowVersion);
LOG_I(TAG, "ESP-NOW version: %u.0", (unsigned)espnowVersion);
} else {
LOGGER.warn("Failed to get ESP-NOW version");
LOG_W(TAG, "Failed to get ESP-NOW version");
}
// Add default unencrypted broadcast peer
@@ -119,11 +120,11 @@ void EspNowService::disableFromDispatcher() {
}
if (esp_now_deinit() != ESP_OK) {
LOGGER.error("esp_now_deinit() failed");
LOG_E(TAG,"esp_now_deinit() failed");
}
if (!deinitWifi()) {
LOGGER.error("deinitWifi() failed");
LOG_E(TAG,"deinitWifi() failed");
}
espnowVersion = 0;
@@ -137,7 +138,7 @@ void EspNowService::disableFromDispatcher() {
void EspNowService::receiveCallback(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) {
auto service = findService();
if (service == nullptr) {
LOGGER.error("Service not running");
LOG_E(TAG,"Service not running");
return;
}
service->onReceive(receiveInfo, data, length);
@@ -147,7 +148,7 @@ void EspNowService::onReceive(const esp_now_recv_info_t* receiveInfo, const uint
auto lock = mutex.asScopedLock();
lock.lock();
LOGGER.debug("Received {} bytes", length);
LOG_D(TAG, "Received %d bytes", length);
for (const auto& item: subscriptions) {
item.onReceive(receiveInfo, data, length);
@@ -164,10 +165,10 @@ bool EspNowService::isEnabled() const {
bool EspNowService::addPeer(const esp_now_peer_info_t& peer) {
if (esp_now_add_peer(&peer) != ESP_OK) {
LOGGER.error("Failed to add peer");
LOG_E(TAG,"Failed to add peer");
return false;
} else {
LOGGER.info("Peer added");
LOG_I(TAG, "Peer added");
return true;
}
}
+12 -11
View File
@@ -4,16 +4,17 @@
#if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED)
#include <Tactility/Logger.h>
#include <Tactility/service/espnow/EspNow.h>
#include <Tactility/service/wifi/Wifi.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include <tactility/log.h>
namespace tt::service::espnow {
static const auto LOGGER = Logger("EspNowService");
constexpr auto* TAG = "EspNowService";
static bool wifiStartedByEspNow = false;
bool initWifi(const EspNowConfig& config) {
@@ -32,27 +33,27 @@ bool initWifi(const EspNowConfig& config) {
if (wifiStartedByEspNow) {
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
if (esp_wifi_init(&cfg) != ESP_OK) {
LOGGER.error("esp_wifi_init() failed");
LOG_E(TAG,"esp_wifi_init() failed");
return false;
}
if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) {
LOGGER.error("esp_wifi_set_storage() failed");
LOG_E(TAG,"esp_wifi_set_storage() failed");
return false;
}
if (esp_wifi_set_mode(mode) != ESP_OK) {
LOGGER.error("esp_wifi_set_mode() failed");
LOG_E(TAG,"esp_wifi_set_mode() failed");
return false;
}
if (esp_wifi_start() != ESP_OK) {
LOGGER.error("esp_wifi_start() failed");
LOG_E(TAG,"esp_wifi_start() failed");
return false;
}
if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) {
LOGGER.error("esp_wifi_set_channel() failed");
LOG_E(TAG,"esp_wifi_set_channel() failed");
return false;
}
}
@@ -66,11 +67,11 @@ bool initWifi(const EspNowConfig& config) {
}
if (esp_wifi_set_protocol(wifi_interface, WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR) != ESP_OK) {
LOGGER.warn("esp_wifi_set_protocol() for long range failed");
LOG_W(TAG,"esp_wifi_set_protocol() for long range failed");
}
}
LOGGER.info("WiFi initialized for ESP-NOW (wifi already running: {})", wifi_already_running ? "yes" : "no");
LOG_I(TAG, "WiFi initialized for ESP-NOW (wifi already running: %s)", wifi_already_running ? "yes" : "no");
return true;
}
@@ -79,9 +80,9 @@ bool deinitWifi() {
esp_wifi_stop();
esp_wifi_deinit();
wifiStartedByEspNow = false;
LOGGER.info("WiFi stopped (was started by ESP-NOW)");
LOG_I(TAG, "WiFi stopped (was started by ESP-NOW)");
} else {
LOGGER.info("WiFi left running (managed by WiFi service)");
LOG_I(TAG, "WiFi left running (managed by WiFi service)");
}
return true;
}
@@ -1,25 +1,26 @@
#include <Tactility/file/ObjectFile.h>
#include <Tactility/Logger.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 {
static const auto LOGGER = Logger("GpsService");
constexpr auto* TAG = "GpsService";
bool GpsService::getConfigurationFilePath(std::string& output) const {
if (paths == nullptr) {
LOGGER.error("Can't add configuration: service not started");
LOG_E(TAG, "Can't add configuration: service not started");
return false;
}
if (!file::findOrCreateDirectory(paths->getUserDataDirectory(), 0777)) {
LOGGER.error("Failed to find or create path {}", paths->getUserDataDirectory());
LOG_E(TAG, "Failed to find or create path %s", paths->getUserDataDirectory().c_str());
return false;
}
@@ -35,21 +36,21 @@ bool GpsService::getGpsConfigurations(std::vector<hal::gps::GpsConfiguration>& c
// If file does not exist, return empty list
if (access(path.c_str(), F_OK) != 0) {
LOGGER.warn("No configurations (file not found: {})", path);
LOG_W(TAG, "No configurations (file not found: %s)", path.c_str());
return true;
}
LOGGER.info("Reading configuration file {}", path);
LOG_I(TAG, "Reading configuration file %s", path.c_str());
auto reader = file::ObjectFileReader(path, sizeof(hal::gps::GpsConfiguration));
if (!reader.open()) {
LOGGER.error("Failed to open configuration file");
LOG_E(TAG, "Failed to open configuration file");
return false;
}
hal::gps::GpsConfiguration configuration;
while (reader.hasNext()) {
if (!reader.readNext(&configuration)) {
LOGGER.error("Failed to read configuration");
LOG_E(TAG, "Failed to read configuration");
reader.close();
return false;
} else {
@@ -68,12 +69,12 @@ bool GpsService::addGpsConfiguration(hal::gps::GpsConfiguration configuration) {
auto appender = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, true);
if (!appender.open()) {
LOGGER.error("Failed to open/create configuration file");
LOG_E(TAG, "Failed to open/create configuration file");
return false;
}
if (!appender.write(&configuration)) {
LOGGER.error("Failed to add configuration");
LOG_E(TAG, "Failed to add configuration");
appender.close();
return false;
}
@@ -90,7 +91,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
LOGGER.error("Failed to get gps configurations");
LOG_E(TAG, "Failed to get gps configurations");
return false;
}
@@ -102,7 +103,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration
auto writer = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, false);
if (!writer.open()) {
LOGGER.error("Failed to open configuration file");
LOG_E(TAG, "Failed to open configuration file");
return false;
}
+14 -13
View File
@@ -1,16 +1,17 @@
#include <Tactility/service/gps/GpsService.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.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 {
static const auto LOGGER = Logger("GpsService");
constexpr auto* TAG = "GpsService";
extern const ServiceManifest manifest;
constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) {
@@ -73,7 +74,7 @@ void GpsService::onStop(ServiceContext& serviceContext) {
}
bool GpsService::startGpsDevice(GpsDeviceRecord& record) {
LOGGER.info("[device {}] starting", record.device->getId());
LOG_I(TAG, "[device %u] starting", (unsigned)record.device->getId());
auto lock = mutex.asScopedLock();
lock.lock();
@@ -81,7 +82,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) {
auto device = record.device;
if (!device->start()) {
LOGGER.error("[device {}] starting failed", record.device->getId());
LOG_E(TAG, "[device %u] starting failed", (unsigned)record.device->getId());
return false;
}
@@ -109,7 +110,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) {
}
bool GpsService::stopGpsDevice(GpsDeviceRecord& record) {
LOGGER.info("[device {}] stopping", record.device->getId());
LOG_I(TAG, "[device %u] stopping", (unsigned)record.device->getId());
auto device = record.device;
@@ -120,7 +121,7 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) {
record.rmcSubscriptionId = -1;
if (!device->stop()) {
LOGGER.error("[device {}] stopping failed", record.device->getId());
LOG_E(TAG, "[device %u] stopping failed", (unsigned)record.device->getId());
return false;
}
@@ -128,10 +129,10 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) {
}
bool GpsService::startReceiving() {
LOGGER.info("Start receiving");
LOG_I(TAG, "Start receiving");
if (getState() != State::Off) {
LOGGER.error("Already receiving");
LOG_E(TAG, "Already receiving");
return false;
}
@@ -144,13 +145,13 @@ bool GpsService::startReceiving() {
std::vector<hal::gps::GpsConfiguration> configurations;
if (!getGpsConfigurations(configurations)) {
LOGGER.error("Failed to get GPS configurations");
LOG_E(TAG, "Failed to get GPS configurations");
setState(State::Off);
return false;
}
if (configurations.empty()) {
LOGGER.error("No GPS configurations");
LOG_E(TAG, "No GPS configurations");
setState(State::Off);
return false;
}
@@ -180,7 +181,7 @@ bool GpsService::startReceiving() {
}
void GpsService::stopReceiving() {
LOGGER.info("Stop receiving");
LOG_I(TAG, "Stop receiving");
setState(State::OffPending);
@@ -198,11 +199,11 @@ void GpsService::stopReceiving() {
}
void GpsService::onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga) {
LOGGER.debug("[device {}] LAT {} LON {}, satellites: {}", deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked);
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) {
LOGGER.debug("[device {}] LAT {} LON {}, speed: {}", deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed));
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 {
+20 -19
View File
@@ -2,20 +2,21 @@
#include <cstring>
#include <Tactility/app/AppInstance.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/Tactility.h>
#include <Tactility/app/AppInstance.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/lvgl/UsbHidInput.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/Tactility.h>
#include <Tactility/service/loader/Loader.h>
#include <tactility/log.h>
namespace tt::service::gui {
extern const ServiceManifest manifest;
static const auto LOGGER = Logger("GuiService");
constexpr auto* TAG = "GuiService";
using namespace loader;
constexpr auto* GUI_TASK_NAME = "gui";
@@ -23,7 +24,7 @@ constexpr auto* GUI_TASK_NAME = "gui";
void warnIfRunningOnGuiTask(const char* context) {
const char* task_name = pcTaskGetName(nullptr);
if (strcmp(GUI_TASK_NAME, task_name) == 0) {
LOGGER.warn("{} shouldn't run on the GUI task", context);
LOG_W(TAG, "%s shouldn't run on the GUI task", context);
}
}
@@ -68,7 +69,7 @@ void GuiService::onLoaderEvent(LoaderService::Event event) {
}
if (dispatcher_dispatch(dispatcher, item, onGuiDispatch) != ERROR_NONE) {
LOGGER.error("Failed to dispatch gui event");
LOG_E(TAG, "Failed to dispatch gui event");
delete item;
}
}
@@ -77,7 +78,7 @@ int32_t GuiService::guiMain() {
auto service = findServiceById<GuiService>(manifest.id);
if (!lvgl::lock(5000)) {
LOGGER.error("LVGL guiMain start failed as LVGL couldn't be locked");
LOG_E(TAG, "LVGL guiMain start failed as LVGL couldn't be locked");
return 0;
}
@@ -86,7 +87,7 @@ int32_t GuiService::guiMain() {
auto* screen_root = lv_screen_active();
if (screen_root == nullptr) {
LOGGER.error("No display found, exiting GUI task");
LOG_E(TAG, "No display found, exiting GUI task");
lvgl::unlock();
return 0;
}
@@ -150,7 +151,7 @@ void GuiService::redraw() {
lock();
if (appRootWidget == nullptr) {
LOGGER.warn("No root widget");
LOG_W(TAG, "No root widget");
unlock();
return;
}
@@ -181,13 +182,13 @@ void GuiService::redraw() {
lv_obj_t* container = createAppViews(appRootWidget);
appToRender->getApp()->onShow(*appToRender, container);
} else {
LOGGER.warn("Nothing to draw");
LOG_W(TAG, "Nothing to draw");
}
// Unlock GUI and LVGL
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
unlock();
@@ -235,7 +236,7 @@ void GuiService::onStop(ServiceContext& service) {
auto* exit_item = new GuiDispatchItem{this, GuiDispatchType::Exit, nullptr};
if (dispatcher_dispatch(dispatcher, exit_item, onGuiDispatch) != ERROR_NONE) {
LOGGER.error("Failed to dispatch gui exit event");
LOG_E(TAG, "Failed to dispatch gui exit event");
check(false, "Failed to dispatch exit signal to thread.");
delete exit_item;
}
@@ -248,7 +249,7 @@ void GuiService::onStop(ServiceContext& service) {
}
lvgl::unlock();
} else {
LOGGER.error("Failed to lock LVGL during GUI stop");
LOG_E(TAG, "Failed to lock LVGL during GUI stop");
}
delete thread;
@@ -261,16 +262,16 @@ void GuiService::showApp(std::shared_ptr<app::AppInstance> app) {
lock.lock();
if (!isStarted) {
LOGGER.error("Failed to show app {}: GUI not started", app->getManifest().appId);
LOG_E(TAG, "Failed to show app %s: GUI not started", app->getManifest().appId.c_str());
return;
}
if (appToRender != nullptr && appToRender->getLaunchId() == app->getLaunchId()) {
LOGGER.warn("Already showing {}", app->getManifest().appId);
LOG_W(TAG, "Already showing %s", app->getManifest().appId.c_str());
return;
}
LOGGER.info("Showing {}", app->getManifest().appId);
LOG_I(TAG, "Showing %s", app->getManifest().appId.c_str());
// Ensure previous app triggers onHide() logic
if (appToRender != nullptr) {
hideApp();
@@ -285,12 +286,12 @@ void GuiService::hideApp() {
lock.lock();
if (!isStarted) {
LOGGER.error("Failed to hide app: GUI not started");
LOG_E(TAG, "Failed to hide app: GUI not started");
return;
}
if (appToRender == nullptr) {
LOGGER.warn("hideApp() called but no app is currently shown");
LOG_W(TAG, "hideApp() called but no app is currently shown");
return;
}
+22 -21
View File
@@ -3,9 +3,8 @@
#include <Tactility/app/AppManifest.h>
#include <Tactility/app/AppRegistration.h>
#include <Tactility/DispatcherThread.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/DispatcherThread.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/ServiceRegistration.h>
@@ -16,9 +15,11 @@
#include <utility>
#endif
#include <tactility/log.h>
namespace tt::service::loader {
static const auto LOGGER = Logger("Loader");
constexpr auto* TAG = "Loader";
constexpr auto LOADER_TIMEOUT = (100 / portTICK_PERIOD_MS);
@@ -44,17 +45,17 @@ static const char* appStateToString(app::State state) {
}
void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launchId, std::shared_ptr<const Bundle> parameters) {
LOGGER.info("Start by id {}", id);
LOG_I(TAG, "Start by id %s", id.c_str());
auto app_manifest = app::findAppManifestById(id);
if (app_manifest == nullptr) {
LOGGER.error("App not found: {}", id);
LOG_E(TAG, "App not found: %s", id.c_str());
return;
}
auto lock = mutex.asScopedLock();
if (!lock.lock(LOADER_TIMEOUT)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -76,14 +77,14 @@ void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launc
void LoaderService::onStopTopAppMessage(const std::string& id) {
auto lock = mutex.asScopedLock();
if (!lock.lock(LOADER_TIMEOUT)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
size_t original_stack_size = appStack.size();
if (original_stack_size == 0) {
LOGGER.error("Stop app: no app running");
LOG_E(TAG, "Stop app: no app running");
return;
}
@@ -91,12 +92,12 @@ void LoaderService::onStopTopAppMessage(const std::string& id) {
auto app_to_stop = appStack[appStack.size() - 1];
if (app_to_stop->getManifest().appId != id) {
LOGGER.error("Stop app: id mismatch (wanted {} but found {} on top of stack)", id, app_to_stop->getManifest().appId);
LOG_E(TAG, "Stop app: id mismatch (wanted %s but found %s on top of stack)", id.c_str(), app_to_stop->getManifest().appId.c_str());
return;
}
if (original_stack_size == 1 && app_to_stop->getManifest().appName != "Boot") {
LOGGER.error("Stop app: can't stop root app");
LOG_E(TAG, "Stop app: can't stop root app");
return;
}
@@ -116,16 +117,16 @@ void LoaderService::onStopTopAppMessage(const std::string& id) {
// We only expect the app to be referenced within the current scope
if (app_to_stop.use_count() > 1) {
LOGGER.warn("Memory leak: Stopped {}, but use count is {}", app_to_stop->getManifest().appId, app_to_stop.use_count() - 1);
LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop.use_count() - 1));
}
// Refcount is expected to be 2: 1 within app_to_stop and 1 within the current scope
if (app_to_stop->getApp().use_count() > 2) {
LOGGER.warn("Memory leak: Stopped {}, but use count is {}", app_to_stop->getManifest().appId, app_to_stop->getApp().use_count() - 2);
LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop->getApp().use_count() - 2));
}
#ifdef ESP_PLATFORM
LOGGER.info("Free heap: {}", heap_caps_get_free_size(MALLOC_CAP_INTERNAL));
LOG_I(TAG, "Free heap: %d", (int)heap_caps_get_free_size(MALLOC_CAP_INTERNAL));
#endif
std::shared_ptr<app::AppInstance> instance_to_resume;
@@ -182,18 +183,18 @@ int LoaderService::findAppInStack(const std::string& id) const {
void LoaderService::onStopAllAppMessage(const std::string& id) {
auto lock = mutex.asScopedLock();
if (!lock.lock(LOADER_TIMEOUT)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
if (!isRunning(id)) {
LOGGER.error("Stop all: {} not running", id);
LOG_E(TAG, "Stop all: %s not running", id.c_str());
return;
}
int app_to_stop_index = findAppInStack(id);
if (app_to_stop_index < 0) {
LOGGER.error("Stop all: {} not found in stack", id);
LOG_E(TAG, "Stop all: %s not found in stack", id.c_str());
return;
}
@@ -220,7 +221,7 @@ void LoaderService::onStopAllAppMessage(const std::string& id) {
}
if (instance_to_resume != nullptr) {
LOGGER.info("Resuming {}", instance_to_resume->getManifest().appId);
LOG_I(TAG, "Resuming %s", instance_to_resume->getManifest().appId.c_str());
transitionAppToState(instance_to_resume, app::State::Showing);
instance_to_resume->getApp()->onResult(
@@ -236,8 +237,8 @@ void LoaderService::transitionAppToState(const std::shared_ptr<app::AppInstance>
const app::AppManifest& app_manifest = app->getManifest();
const app::State old_state = app->getState();
LOGGER.info( "App \"{}\" state: {} -> {}",
app_manifest.appId,
LOG_I(TAG, "App \"%s\" state: %s -> %s",
app_manifest.appId.c_str(),
appStateToString(old_state),
appStateToString(state)
);
@@ -284,14 +285,14 @@ void LoaderService::stopTop() {
}
void LoaderService::stopTop(const std::string& id) {
LOGGER.info("dispatching stopTop({})", id);
LOG_I(TAG, "dispatching stopTop(%s)", id.c_str());
dispatcherThread->dispatch([this, id] {
onStopTopAppMessage(id);
});
}
void LoaderService::stopAll(const std::string& id) {
LOGGER.info("dispatching stopAll({})", id);
LOG_I(TAG, "dispatching stopAll(%s)", id.c_str());
dispatcherThread->dispatch([this, id] {
onStopAllAppMessage(id);
});
@@ -1,14 +1,14 @@
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/service/ServiceContext.h>
#include <Tactility/service/ServiceManifest.h>
#include <Tactility/service/memorychecker/MemoryCheckerService.h>
#include <tactility/lvgl_icon_statusbar.h>
#include <tactility/log.h>
namespace tt::service::memorychecker {
static const auto LOGGER = Logger("MemoryChecker");
constexpr auto* TAG = "MemoryChecker";
// Total memory (in bytes) that should be free before warnings occur
constexpr auto TOTAL_FREE_THRESHOLD = 10'000;
@@ -37,13 +37,13 @@ static bool isMemoryLow() {
bool memory_low = false;
const auto total_free = getInternalFree();
if (total_free < TOTAL_FREE_THRESHOLD) {
LOGGER.warn("Internal memory low: {} bytes", total_free);
LOG_W(TAG, "Internal memory low: %d bytes", (int)total_free);
memory_low = true;
}
const auto largest_block = getInternalLargestFreeBlock();
if (largest_block < LARGEST_FREE_BLOCK_THRESHOLD) {
LOGGER.warn("Largest free internal memory block is {} bytes", largest_block);
LOG_W(TAG, "Largest free internal memory block is %d bytes", (int)largest_block);
memory_low = true;
}
@@ -2,17 +2,18 @@
#if TT_FEATURE_SCREENSHOT_ENABLED
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/service/screenshot/Screenshot.h>
#include <Tactility/service/ServiceRegistration.h>
#include <Tactility/service/screenshot/Screenshot.h>
#include <lvgl.h>
#include <memory>
#include <tactility/log.h>
namespace tt::service::screenshot {
static const auto LOGGER = Logger("ScreenshotService");
constexpr auto* TAG = "ScreenshotService";
extern const ServiceManifest manifest;
@@ -23,7 +24,7 @@ std::shared_ptr<ScreenshotService> optScreenshotService() {
void ScreenshotService::startApps(const std::string& path) {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -32,14 +33,14 @@ void ScreenshotService::startApps(const std::string& path) {
mode = Mode::Apps;
task->startApps(path);
} else {
LOGGER.warn("Screenshot task already running");
LOG_W(TAG,"Screenshot task already running");
}
}
void ScreenshotService::startTimed(const std::string& path, uint8_t delayInSeconds, uint8_t amount) {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -48,13 +49,13 @@ void ScreenshotService::startTimed(const std::string& path, uint8_t delayInSecon
mode = Mode::Timed;
task->startTimed(path, delayInSeconds, amount);
} else {
LOGGER.warn("Screenshot task already running");
LOG_W(TAG,"Screenshot task already running");
}
}
bool ScreenshotService::onStart(ServiceContext& serviceContext) {
if (lv_screen_active() == nullptr) {
LOGGER.error("No display found");
LOG_E(TAG, "No display found");
return false;
}
@@ -64,7 +65,7 @@ bool ScreenshotService::onStart(ServiceContext& serviceContext) {
void ScreenshotService::stop() {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -72,14 +73,14 @@ void ScreenshotService::stop() {
task = nullptr;
mode = Mode::None;
} else {
LOGGER.warn("Screenshot task not running");
LOG_W(TAG,"Screenshot task not running");
}
}
Mode ScreenshotService::getMode() const {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED);
return Mode::None;
}
@@ -2,21 +2,22 @@
#if TT_FEATURE_SCREENSHOT_ENABLED
#include <Tactility/CpuAffinity.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/screenshot/ScreenshotTask.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/CpuAffinity.h>
#include <Tactility/TactilityCore.h>
#include <Tactility/lvgl/LvglSync.h>
#include <Tactility/service/loader/Loader.h>
#include <Tactility/service/screenshot/ScreenshotTask.h>
#include <lv_screenshot.h>
#include <format>
#include <tactility/log.h>
namespace tt::service::screenshot {
static const auto LOGGER = Logger("ScreenshotTask");
constexpr auto* TAG = "ScreenshotTask";
ScreenshotTask::~ScreenshotTask() {
if (thread) {
@@ -27,7 +28,7 @@ ScreenshotTask::~ScreenshotTask() {
bool ScreenshotTask::isInterrupted() {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return true;
}
return interrupted;
@@ -36,7 +37,7 @@ bool ScreenshotTask::isInterrupted() {
bool ScreenshotTask::isFinished() {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return false;
}
return finished;
@@ -51,13 +52,13 @@ void ScreenshotTask::setFinished() {
static void makeScreenshot(const std::string& filename) {
if (lvgl::lock(50 / portTICK_PERIOD_MS)) {
if (lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, filename.c_str())) {
LOGGER.info("Screenshot saved to {}", filename);
LOG_I(TAG, "Screenshot saved to %s", filename.c_str());
} else {
LOGGER.error("Screenshot not saved to {}", filename);
LOG_E(TAG, "Screenshot not saved to %s", filename.c_str());
}
lvgl::unlock();
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL");
}
}
@@ -103,7 +104,7 @@ void ScreenshotTask::taskMain() {
void ScreenshotTask::taskStart() {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -123,7 +124,7 @@ void ScreenshotTask::taskStart() {
void ScreenshotTask::startApps(const std::string& path) {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -133,14 +134,14 @@ void ScreenshotTask::startApps(const std::string& path) {
work.path = path;
taskStart();
} else {
LOGGER.error("Task was already running");
LOG_E(TAG, "Task was already running");
}
}
void ScreenshotTask::startTimed(const std::string& path, uint8_t delay_in_seconds, uint8_t amount) {
auto lock = mutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
@@ -152,7 +153,7 @@ void ScreenshotTask::startTimed(const std::string& path, uint8_t delay_in_second
work.path = path;
taskStart();
} else {
LOGGER.error("Task was already running");
LOG_E(TAG, "Task was already running");
}
}
@@ -1,6 +1,5 @@
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <Tactility/Timer.h>
#include <Tactility/hal/power/PowerDevice.h>
@@ -27,9 +26,11 @@
#include <cstring>
#include <tactility/log.h>
namespace tt::service::statusbar {
static const auto LOGGER = Logger("StatusbarService");
constexpr auto* TAG = "StatusbarService";
// GPS
extern const ServiceManifest manifest;
@@ -302,7 +303,7 @@ public:
bool onStart(ServiceContext& serviceContext) override {
if (lv_screen_active() == nullptr) {
LOGGER.error("No display found");
LOG_E(TAG, "No display found");
return false;
}
@@ -3,7 +3,6 @@
#include <Tactility/service/webserver/AssetVersion.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <cJSON.h>
#include <cstdio>
@@ -12,9 +11,11 @@
#include <memory>
#include <esp_random.h>
#include <tactility/log.h>
namespace tt::service::webserver {
static const auto LOGGER = tt::Logger("AssetVersion");
constexpr auto* TAG = "AssetVersion";
constexpr auto* DATA_VERSION_FILE = "/system/app/WebServer/version.json";
constexpr auto* SD_VERSION_FILE = "/sdcard/tactility/webserver/version.json";
constexpr auto* DATA_ASSETS_DIR = "/system/app/WebServer";
@@ -22,65 +23,65 @@ constexpr auto* SD_ASSETS_DIR = "/sdcard/tactility/webserver";
static bool loadVersionFromFile(const char* path, AssetVersion& version) {
if (!file::isFile(path)) {
LOGGER.warn("Version file not found: {}", path);
LOG_W(TAG, "Version file not found: %s", path);
return false;
}
// Read file content
std::string content;
{
auto lock = file::getLock(path);
lock->lock(portMAX_DELAY);
FILE* fp = fopen(path, "r");
if (!fp) {
LOGGER.error("Failed to open version file: {}", path);
LOG_E(TAG, "Failed to open version file: %s", path);
lock->unlock();
return false;
}
char buffer[256];
size_t bytesRead = fread(buffer, 1, sizeof(buffer) - 1, fp);
bool readError = ferror(fp) != 0;
fclose(fp);
lock->unlock();
if (readError) {
LOGGER.error("Error reading version file: {}", path);
LOG_E(TAG, "Error reading version file: %s", path);
return false;
}
if (bytesRead == 0) {
LOGGER.error("Version file is empty: {}", path);
LOG_E(TAG, "Version file is empty: %s", path);
return false;
}
buffer[bytesRead] = '\0';
content = buffer;
}
// Parse JSON
cJSON* json = cJSON_Parse(content.c_str());
if (json == nullptr) {
LOGGER.error("Failed to parse version JSON: {}", path);
LOG_E(TAG, "Failed to parse version JSON: %s", path);
return false;
}
cJSON* versionItem = cJSON_GetObjectItem(json, "version");
if (versionItem == nullptr || !cJSON_IsNumber(versionItem)) {
LOGGER.error("Invalid version JSON format: {}", path);
LOG_E(TAG, "Invalid version JSON format: %s", path);
cJSON_Delete(json);
return false;
}
double versionValue = versionItem->valuedouble;
if (versionValue < 0 || versionValue > UINT32_MAX) {
LOGGER.error("Version out of valid range [0, {}]: {}", UINT32_MAX, path);
LOG_E(TAG, "Version out of valid range [0, %u]: %s", (unsigned)UINT32_MAX, path);
cJSON_Delete(json);
return false;
}
version.version = static_cast<uint32_t>(versionValue);
cJSON_Delete(json);
LOGGER.info("Loaded version {} from {}", version.version, path);
LOG_I(TAG, "Loaded version %u from %s", (unsigned)version.version, path);
return true;
}
@@ -92,23 +93,23 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) {
dirPath = dirPath.substr(0, lastSlash);
if (!file::isDirectory(dirPath.c_str())) {
if (!file::findOrCreateDirectory(dirPath.c_str(), 0755)) {
LOGGER.error("Failed to create directory: {}", dirPath);
LOG_E(TAG, "Failed to create directory: %s", dirPath.c_str());
return false;
}
}
}
// Create JSON
cJSON* json = cJSON_CreateObject();
if (json == nullptr) {
LOGGER.error("Failed to create JSON object for version");
LOG_E(TAG, "Failed to create JSON object for version");
return false;
}
cJSON_AddNumberToObject(json, "version", version.version);
char* jsonString = cJSON_Print(json);
if (jsonString == nullptr) {
LOGGER.error("Failed to serialize version JSON");
LOG_E(TAG, "Failed to serialize version JSON");
cJSON_Delete(json);
return false;
}
@@ -126,12 +127,12 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) {
success = (written == len);
if (success) {
if (fflush(fp) != 0) {
LOGGER.error("Failed to flush version file: {}", path);
LOG_E(TAG, "Failed to flush version file: %s", path);
success = false;
} else {
int fd = fileno(fp);
if (fd >= 0 && fsync(fd) != 0) {
LOGGER.error("Failed to fsync version file: {}", path);
LOG_E(TAG, "Failed to fsync version file: %s", path);
success = false;
}
}
@@ -145,9 +146,9 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) {
cJSON_Delete(json);
if (success) {
LOGGER.info("Saved version {} to {}", version.version, path);
LOG_I(TAG, "Saved version %u to %s", (unsigned)version.version, path);
} else {
LOGGER.error("Failed to write version file: {}", path);
LOG_E(TAG, "Failed to write version file: %s", path);
}
return success;
@@ -180,15 +181,15 @@ bool hasSdAssets() {
static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
constexpr int MAX_DEPTH = 16;
if (depth >= MAX_DEPTH) {
LOGGER.error("Max directory depth exceeded: {}", src);
LOG_E(TAG, "Max directory depth exceeded: %s", src);
return false;
}
LOGGER.info("Copying directory: {} -> {}", src, dst);
LOG_I(TAG, "Copying directory: %s -> %s", src, dst);
// Create destination directory
if (!file::isDirectory(dst)) {
if (!file::findOrCreateDirectory(dst, 0755)) {
LOGGER.error("Failed to create destination directory: {}", dst);
LOG_E(TAG, "Failed to create destination directory: %s", dst);
return false;
}
}
@@ -216,7 +217,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
isDir = S_ISDIR(st.st_mode);
isReg = S_ISREG(st.st_mode);
} else {
LOGGER.warn("Failed to stat entry, skipping: {}", srcPath);
LOG_W(TAG, "Failed to stat entry, skipping: %s", srcPath.c_str());
return;
}
}
@@ -233,14 +234,14 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
FILE* srcFile = fopen(srcPath.c_str(), "rb");
if (!srcFile) {
LOGGER.error("Failed to open source file: {}", srcPath);
LOG_E(TAG, "Failed to open source file: %s", srcPath.c_str());
copySuccess = false;
return;
}
FILE* tempFile = fopen(tempPath.c_str(), "wb");
if (!tempFile) {
LOGGER.error("Failed to create temp file: {}", tempPath);
LOG_E(TAG, "Failed to create temp file: %s", tempPath.c_str());
fclose(srcFile);
copySuccess = false;
return;
@@ -254,7 +255,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
while ((bytesRead = fread(buffer.get(), 1, COPY_BUF_SIZE, srcFile)) > 0) {
size_t bytesWritten = fwrite(buffer.get(), 1, bytesRead, tempFile);
if (bytesWritten != bytesRead) {
LOGGER.error("Failed to write to temp file: {}", tempPath);
LOG_E(TAG, "Failed to write to temp file: %s", tempPath.c_str());
fileCopySuccess = false;
copySuccess = false;
break;
@@ -262,7 +263,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
}
if (fileCopySuccess && ferror(srcFile)) {
LOGGER.error("Error reading source file: {}", srcPath);
LOG_E(TAG, "Error reading source file: %s", srcPath.c_str());
fileCopySuccess = false;
copySuccess = false;
}
@@ -272,13 +273,13 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
// Flush and sync temp file before closing
if (fileCopySuccess) {
if (fflush(tempFile) != 0) {
LOGGER.error("Failed to flush temp file: {}", tempPath);
LOG_E(TAG, "Failed to flush temp file: %s", tempPath.c_str());
fileCopySuccess = false;
copySuccess = false;
} else {
int fd = fileno(tempFile);
if (fd >= 0 && fsync(fd) != 0) {
LOGGER.error("Failed to fsync temp file: {}", tempPath);
LOG_E(TAG, "Failed to fsync temp file: %s", tempPath.c_str());
fileCopySuccess = false;
copySuccess = false;
}
@@ -292,7 +293,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
remove(dstPath.c_str());
// Rename temp file to destination
if (rename(tempPath.c_str(), dstPath.c_str()) != 0) {
LOGGER.error("Failed to rename temp file {} to {}", tempPath, dstPath);
LOG_E(TAG, "Failed to rename temp file %s to %s", tempPath.c_str(), dstPath.c_str());
remove(tempPath.c_str());
fileCopySuccess = false;
copySuccess = false;
@@ -303,13 +304,13 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
}
if (fileCopySuccess) {
LOGGER.info("Copied file: {}", entry.d_name);
LOG_I(TAG, "Copied file: %s", entry.d_name);
}
}
});
if (!listSuccess) {
LOGGER.error("Failed to list source directory: {}", src);
LOG_E(TAG, "Failed to list source directory: %s", src);
return false;
}
@@ -317,7 +318,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) {
}
bool syncAssets() {
LOGGER.info("Starting asset synchronization...");
LOG_I(TAG, "Starting asset synchronization...");
// Check if Data partition and SD card exist
bool dataExists = hasDataAssets();
@@ -325,26 +326,26 @@ bool syncAssets() {
// FIRST BOOT SCENARIO: Data has version 0, SD card is missing
if (dataExists && !sdExists) {
LOGGER.info("First boot - Data exists but SD card backup missing");
LOGGER.warn("Skipping SD backup during boot - will be created on first settings save");
LOGGER.warn("This avoids watchdog timeout if SD card is slow or corrupted");
LOG_I(TAG, "First boot - Data exists but SD card backup missing");
LOG_W(TAG, "Skipping SD backup during boot - will be created on first settings save");
LOG_W(TAG, "This avoids watchdog timeout if SD card is slow or corrupted");
return true; // Don't block boot - defer copy to runtime
}
// NO SD CARD: Just ensure Data has default structure
if (!sdExists) {
LOGGER.warn("No SD card available - creating default Data structure if needed");
LOG_W(TAG, "No SD card available - creating default Data structure if needed");
if (!dataExists) {
if (!file::findOrCreateDirectory(DATA_ASSETS_DIR, 0755)) {
LOGGER.error("Failed to create Data assets directory");
LOG_E(TAG, "Failed to create Data assets directory");
return false;
}
AssetVersion defaultVersion(0); // Start at version 0 - SD card updates will be version 1+
if (!saveDataVersion(defaultVersion)) {
LOGGER.error("Failed to save default Data version");
LOG_E(TAG, "Failed to save default Data version");
return false;
}
LOGGER.info("Created default Data assets structure (version 0)");
LOG_I(TAG, "Created default Data assets structure (version 0)");
}
return true;
}
@@ -355,39 +356,39 @@ bool syncAssets() {
bool hasSdVer = loadSdVersion(sdVersion);
if (!hasDataVer) {
LOGGER.warn("No Data version.json - assuming version 0");
LOG_W(TAG, "No Data version.json - assuming version 0");
dataVersion.version = 0;
if (!saveDataVersion(dataVersion)) {
LOGGER.warn("Failed to save default Data version (non-fatal)");
LOG_W(TAG, "Failed to save default Data version (non-fatal)");
}
}
if (!hasSdVer) {
LOGGER.warn("No SD version.json - assuming version 0");
LOG_W(TAG, "No SD version.json - assuming version 0");
sdVersion.version = 0;
// DON'T save to SD during boot - defer to runtime
LOGGER.warn("Skipping SD version.json creation during boot - will be created on first settings save");
LOG_W(TAG, "Skipping SD version.json creation during boot - will be created on first settings save");
}
LOGGER.info("Version comparison - Data: {}, SD: {}", dataVersion.version, sdVersion.version);
LOG_I(TAG, "Version comparison - Data: %u, SD: %u", (unsigned)dataVersion.version, (unsigned)sdVersion.version);
if (sdVersion.version > dataVersion.version) {
// Firmware update - copy SD -> Data
LOGGER.info("SD card newer (v{} > v{}) - copying assets SD -> Data (firmware update)",
sdVersion.version, dataVersion.version);
LOG_I(TAG, "SD card newer (v%u > v%u) - copying assets SD -> Data (firmware update)",
(unsigned)sdVersion.version, (unsigned)dataVersion.version);
if (!copyDirectory(SD_ASSETS_DIR, DATA_ASSETS_DIR)) {
LOGGER.error("Failed to copy assets from SD to Data");
LOG_E(TAG, "Failed to copy assets from SD to Data");
return false;
}
LOGGER.info("Firmware update complete - assets updated from SD card");
LOG_I(TAG, "Firmware update complete - assets updated from SD card");
} else if (dataVersion.version > sdVersion.version) {
// User customization - backup Data -> SD
LOGGER.warn("Data newer (v{} > v{}) - deferring SD backup to avoid boot watchdog",
dataVersion.version, sdVersion.version);
LOGGER.warn("SD backup will occur on first WebServer settings save");
LOG_W(TAG, "Data newer (v%u > v%u) - deferring SD backup to avoid boot watchdog",
(unsigned)dataVersion.version, (unsigned)sdVersion.version);
LOG_W(TAG, "SD backup will occur on first WebServer settings save");
return true; // Don't block boot - defer copy to runtime
} else {
LOGGER.info("Versions match (v{}) - no sync needed", dataVersion.version);
LOG_I(TAG, "Versions match (v%u) - no sync needed", (unsigned)dataVersion.version);
}
return true;
@@ -7,7 +7,6 @@
#include <Tactility/settings/WebServerSettings.h>
#include <Tactility/MountPoints.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/lvgl/Statusbar.h>
#include <Tactility/Mutex.h>
@@ -52,9 +51,11 @@
#include <mbedtls/base64.h>
#include <sstream>
#include <tactility/log.h>
namespace tt::service::webserver {
static const auto LOGGER = tt::Logger("WebServerService");
constexpr auto* TAG = "WebServerService";
// Helper to convert chip model enum to human-readable string
static const char* getChipModelName(esp_chip_model_t model) {
@@ -142,14 +143,14 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) {
std::string auth_header(auth_len + 1, '\0');
if (httpd_req_get_hdr_value_str(request, "Authorization", auth_header.data(), auth_len + 1) != ESP_OK) {
LOGGER.warn("Failed to read Authorization header");
LOG_W(TAG, "Failed to read Authorization header");
return sendUnauthorized(request, "Authorization required");
}
auth_header.resize(auth_len); // Remove null terminator from string length
// Check for "Basic " prefix
if (auth_header.rfind("Basic ", 0) != 0) {
LOGGER.warn("Authorization header is not Basic auth");
LOG_W(TAG, "Authorization header is not Basic auth");
return sendUnauthorized(request, "Basic authorization required");
}
@@ -170,7 +171,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) {
reinterpret_cast<const unsigned char*>(base64_creds.c_str()),
base64_creds.length());
if (ret != 0) {
LOGGER.warn("Failed to decode base64 credentials");
LOG_W(TAG, "Failed to decode base64 credentials");
return sendUnauthorized(request, "Invalid credentials format");
}
decoded.resize(actual_len);
@@ -178,7 +179,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) {
// Parse username:password
size_t colon_pos = decoded.find(':');
if (colon_pos == std::string::npos) {
LOGGER.warn("Invalid credentials format (no colon separator)");
LOG_W(TAG, "Invalid credentials format (no colon separator)");
return sendUnauthorized(request, "Invalid credentials format");
}
@@ -189,7 +190,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) {
bool usernameMatch = secureCompare(username, settings.webServerUsername);
bool passwordMatch = secureCompare(password, settings.webServerPassword);
if (!usernameMatch || !passwordMatch) {
LOGGER.warn("Invalid credentials for user '{}'", username);
LOG_W(TAG, "Invalid credentials for user '%s'", username.c_str());
return sendUnauthorized(request, "Invalid credentials");
}
@@ -198,7 +199,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) {
}
bool WebServerService::onStart(ServiceContext& service) {
LOGGER.info("Starting WebServer service...");
LOG_I(TAG, "Starting WebServer service...");
// Register global instance
g_webServerInstance.store(this);
@@ -228,10 +229,10 @@ bool WebServerService::onStart(ServiceContext& service) {
// Start HTTP server only if enabled in settings (default: OFF to save memory)
if (serverEnabled) {
LOGGER.info("WebServer enabled in settings, starting HTTP server...");
LOG_I(TAG, "WebServer enabled in settings, starting HTTP server...");
setEnabled(true);
} else {
LOGGER.info("WebServer disabled in settings, NOT starting HTTP server (saves ~10KB RAM)");
LOG_I(TAG, "WebServer disabled in settings, NOT starting HTTP server (saves ~10KB RAM)");
setEnabled(false);
}
@@ -288,15 +289,15 @@ bool WebServerService::startApMode() {
}
if (settings.wifiMode != settings::webserver::WiFiMode::AccessPoint) {
LOGGER.info("Not in AP mode, skipping AP WiFi initialization");
LOG_I(TAG, "Not in AP mode, skipping AP WiFi initialization");
return true; // Not an error, just not needed
}
LOGGER.info("Starting WiFi in Access Point mode...");
LOG_I(TAG, "Starting WiFi in Access Point mode...");
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
if (esp_wifi_init(&cfg) != ESP_OK) {
LOGGER.error("esp_wifi_init() failed");
LOG_E(TAG, "esp_wifi_init() failed");
return false;
}
apWifiInitialized = true;
@@ -304,14 +305,14 @@ bool WebServerService::startApMode() {
// Create the AP network interface
apNetif = esp_netif_create_default_wifi_ap();
if (apNetif == nullptr) {
LOGGER.error("esp_netif_create_default_wifi_ap() failed");
LOG_E(TAG, "esp_netif_create_default_wifi_ap() failed");
esp_wifi_deinit();
apWifiInitialized = false;
return false;
}
if (esp_wifi_set_mode(WIFI_MODE_AP) != ESP_OK) {
LOGGER.error("esp_wifi_set_mode(AP) failed");
LOG_E(TAG, "esp_wifi_set_mode(AP) failed");
stopApMode();
return false;
}
@@ -324,19 +325,19 @@ bool WebServerService::startApMode() {
ip_info.netmask.addr = ipaddr_addr("255.255.255.0");
if (esp_netif_dhcps_stop(apNetif) != ESP_OK) {
LOGGER.error("esp_netif_dhcps_stop() failed");
LOG_E(TAG, "esp_netif_dhcps_stop() failed");
stopApMode();
return false;
}
if (esp_netif_set_ip_info(apNetif, &ip_info) != ESP_OK) {
LOGGER.error("esp_netif_set_ip_info() failed");
LOG_E(TAG, "esp_netif_set_ip_info() failed");
stopApMode();
return false;
}
if (esp_netif_dhcps_start(apNetif) != ESP_OK) {
LOGGER.error("esp_netif_dhcps_start() failed");
LOG_E(TAG, "esp_netif_dhcps_start() failed");
stopApMode();
return false;
}
@@ -354,36 +355,36 @@ bool WebServerService::startApMode() {
if (settings.apOpenNetwork) {
// User explicitly chose an open network
wifi_config.ap.authmode = WIFI_AUTH_OPEN;
LOGGER.info("AP configured with OPEN authentication (user choice)");
LOG_I(TAG, "AP configured with OPEN authentication (user choice)");
} else if (settings.apPassword.length() >= 8 && settings.apPassword.length() <= 63) {
wifi_config.ap.authmode = WIFI_AUTH_WPA2_PSK;
strncpy(reinterpret_cast<char*>(wifi_config.ap.password), settings.apPassword.c_str(), sizeof(wifi_config.ap.password) - 1);
wifi_config.ap.password[sizeof(wifi_config.ap.password) - 1] = '\0';
LOGGER.info("AP configured with WPA2-PSK authentication");
LOG_I(TAG, "AP configured with WPA2-PSK authentication");
} else {
if (!settings.apPassword.empty()) {
LOGGER.warn("AP password invalid (must be 8-63 chars, got {}) - using OPEN mode", settings.apPassword.length());
LOG_W(TAG, "AP password invalid (must be 8-63 chars, got %zu) - using OPEN mode", settings.apPassword.length());
}
wifi_config.ap.authmode = WIFI_AUTH_OPEN;
LOGGER.warn("AP configured with OPEN authentication (no password)");
LOG_W(TAG, "AP configured with OPEN authentication (no password)");
}
wifi_config.ap.max_connection = 4;
wifi_config.ap.channel = settings.apChannel;
if (esp_wifi_set_config(WIFI_IF_AP, &wifi_config) != ESP_OK) {
LOGGER.error("esp_wifi_set_config(AP) failed");
LOG_E(TAG, "esp_wifi_set_config(AP) failed");
stopApMode();
return false;
}
if (esp_wifi_start() != ESP_OK) {
LOGGER.error("esp_wifi_start() failed");
LOG_E(TAG, "esp_wifi_start() failed");
stopApMode();
return false;
}
LOGGER.info("WiFi AP started - SSID: '{}', Channel: {}, IP: 192.168.4.1", settings.apSsid, settings.apChannel);
LOG_I(TAG, "WiFi AP started - SSID: '%s', Channel: %u, IP: 192.168.4.1", settings.apSsid.c_str(), (unsigned)settings.apChannel);
return true;
}
@@ -395,15 +396,15 @@ void WebServerService::stopApMode() {
}
err = esp_wifi_stop();
if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_STARTED) {
LOGGER.warn("esp_wifi_stop() in cleanup: {}", esp_err_to_name(err));
LOG_W(TAG, "esp_wifi_stop() in cleanup: %s", esp_err_to_name(err));
}
LOGGER.info("WiFi AP stopped");
LOG_I(TAG, "WiFi AP stopped");
err = esp_wifi_set_mode(WIFI_MODE_STA);
if (err != ESP_OK) {
LOGGER.warn("esp_wifi_set_mode() in cleanup: {}", esp_err_to_name(err));
LOG_W(TAG, "esp_wifi_set_mode() in cleanup: %s", esp_err_to_name(err));
}
LOGGER.info("Wifi mode set back to STA");
LOG_I(TAG, "Wifi mode set back to STA");
apWifiInitialized = false;
}
@@ -428,7 +429,7 @@ bool WebServerService::startServer() {
// Start AP mode WiFi if configured
if (settings.wifiMode == settings::webserver::WiFiMode::AccessPoint) {
if (!startApMode()) {
LOGGER.error("Failed to start AP mode WiFi - HTTP server will not start");
LOG_E(TAG, "Failed to start AP mode WiFi - HTTP server will not start");
return false;
}
}
@@ -505,19 +506,19 @@ bool WebServerService::startServer() {
httpServer->start();
if (!httpServer->isStarted()) {
LOGGER.error("Failed to start HTTP server on port {}", settings.webServerPort);
LOG_E(TAG, "Failed to start HTTP server on port %u", (unsigned)settings.webServerPort);
httpServer.reset();
return false;
}
LOGGER.info("HTTP server started successfully on port {}", settings.webServerPort);
LOG_I(TAG, "HTTP server started successfully on port %u", (unsigned)settings.webServerPort);
publish_event(this, WebServerEvent::WebServerStarted);
// Show statusbar icon
if (statusbarIconId >= 0) {
lvgl::statusbar_icon_set_image(statusbarIconId, LVGL_ICON_STATUSBAR_CLOUD);
lvgl::statusbar_icon_set_visibility(statusbarIconId, true);
LOGGER.info("WebServer statusbar icon shown ({} mode)",
LOG_I(TAG, "WebServer statusbar icon shown (%s mode)",
settings.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station");
}
@@ -537,7 +538,7 @@ void WebServerService::stopServer() {
stopApMode();
}
LOGGER.info("HTTP server stopped");
LOG_I(TAG, "HTTP server stopped");
publish_event(this, WebServerEvent::WebServerStopped);
if (statusbarIconId >= 0) {
@@ -550,7 +551,7 @@ void WebServerService::stopServer() {
esp_err_t WebServerService::handleRoot(httpd_req_t* request) {
LOGGER.info("GET / -> redirecting to /dashboard.html");
LOG_I(TAG, "GET / -> redirecting to /dashboard.html");
httpd_resp_set_status(request, "302 Found");
httpd_resp_set_hdr(request, "Location", "/dashboard.html");
return httpd_resp_send(request, nullptr, 0);
@@ -722,7 +723,7 @@ static bool uriMatches(const char* uri, const char* route) {
}
esp_err_t WebServerService::handleFileBrowser(httpd_req_t* request) {
LOGGER.info("GET /filebrowser -> redirecting to /dashboard.html#files");
LOG_I(TAG, "GET /filebrowser -> redirecting to /dashboard.html#files");
httpd_resp_set_status(request, "302 Found");
httpd_resp_set_hdr(request, "Location", "/dashboard.html#files");
return httpd_resp_send(request, nullptr, 0);
@@ -735,17 +736,17 @@ esp_err_t WebServerService::handleFsList(httpd_req_t* request) {
if (qlen > 1) {
std::unique_ptr<char[]> qbuf(new char[qlen]);
if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) {
LOGGER.info("GET /fs/list raw query: {}", qbuf.get());
LOG_I(TAG, "GET /fs/list raw query: %s", qbuf.get());
}
}
if (!getQueryParam(request, "path", path) || path.empty()) path = "/";
std::string norm = normalizePath(path);
LOGGER.info("GET /fs/list decoded path: '{}' normalized: '{}'", path, norm);
LOG_I(TAG, "GET /fs/list decoded path: '%s' normalized: '%s'", path.c_str(), norm.c_str());
// Allow root path for listing mount points
if (!isAllowedBasePath(norm, true)) {
LOGGER.warn("GET /fs/list - invalid path requested: '{}' normalized: '{}'", path, norm);
LOG_W(TAG, "GET /fs/list - invalid path requested: '%s' normalized: '%s'", path.c_str(), norm.c_str());
httpd_resp_set_type(request, "application/json");
httpd_resp_sendstr(request, "{\"error\":\"invalid path\"}");
return ESP_OK;
@@ -811,7 +812,7 @@ esp_err_t WebServerService::handleFsDownload(httpd_req_t* request) {
}
std::string norm = normalizePath(path);
if (!isAllowedBasePath(norm) || !file::isFile(norm)) {
LOGGER.warn("GET /fs/download - not found or invalid path: '{}' normalized: '{}'", path, norm);
LOG_W(TAG, "GET /fs/download - not found or invalid path: '%s' normalized: '%s'", path.c_str(), norm.c_str());
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -859,7 +860,7 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) {
if (qlen > 1) {
std::unique_ptr<char[]> qbuf(new char[qlen]);
if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) {
LOGGER.info("POST /fs/upload raw query: {}", qbuf.get());
LOG_I(TAG, "POST /fs/upload raw query: %s", qbuf.get());
}
}
@@ -872,10 +873,10 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) {
char content_type[64] = {0};
httpd_req_get_hdr_value_str(request, "Content-Type", content_type, sizeof(content_type));
std::string norm = normalizePath(path);
LOGGER.info("POST /fs/upload decoded path: '{}' normalized: '{}' Content-Length: {} Content-Type: {}", path, norm, (int)request->content_len, content_type[0] ? content_type : "(null)");
LOG_I(TAG, "POST /fs/upload decoded path: '%s' normalized: '%s' Content-Length: %d Content-Type: %s", path.c_str(), norm.c_str(), (int)request->content_len, content_type[0] ? content_type : "(null)");
if (!isAllowedBasePath(norm)) {
LOGGER.warn("POST /fs/upload - invalid path requested: '{}' normalized: '{}'", path, norm);
LOG_W(TAG, "POST /fs/upload - invalid path requested: '%s' normalized: '%s'", path.c_str(), norm.c_str());
httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path");
return ESP_FAIL;
}
@@ -902,18 +903,18 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) {
// Timeout - retry with backoff
timeout_retries++;
if (timeout_retries >= MAX_TIMEOUT_RETRIES) {
LOGGER.error("Upload recv timeout after {} retries", timeout_retries);
LOG_E(TAG, "Upload recv timeout after %d retries", timeout_retries);
fclose(fp);
remove(norm.c_str()); // Clean up partial file
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv timeout");
return ESP_FAIL;
}
LOGGER.warn("Upload recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES);
LOG_W(TAG, "Upload recv timeout, retry %d/%d", timeout_retries, MAX_TIMEOUT_RETRIES);
vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Linear backoff
continue;
}
if (ret <= 0) {
LOGGER.error("Upload recv failed with error {}", ret);
LOG_E(TAG, "Upload recv failed with error %d", ret);
fclose(fp);
remove(norm.c_str()); // Clean up partial file
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv failed");
@@ -951,7 +952,7 @@ esp_err_t WebServerService::handleFsGenericGet(httpd_req_t* request) {
if (uriMatches(uri, "/fs/list")) return handleFsList(request);
if (uriMatches(uri, "/fs/download")) return handleFsDownload(request);
if (uriMatches(uri, "/fs/tree")) return handleFsTree(request);
LOGGER.warn("GET {} - not found in fs generic dispatcher", uri);
LOG_W(TAG, "GET %s - not found in fs generic dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -970,7 +971,7 @@ esp_err_t WebServerService::handleFsGenericPost(httpd_req_t* request) {
if (uriMatches(uri, "/fs/delete")) return handleFsDelete(request);
if (uriMatches(uri, "/fs/rename")) return handleFsRename(request);
if (uriMatches(uri, "/fs/upload")) return handleFsUpload(request);
LOGGER.warn("POST {} - not found in fs generic dispatcher", uri);
LOG_W(TAG, "POST %s - not found in fs generic dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -986,7 +987,7 @@ esp_err_t WebServerService::handleAdminPost(httpd_req_t* request) {
const char* uri = request->uri;
if (strncmp(uri, "/admin/reboot", 13) == 0) return handleReboot(request);
LOGGER.info("POST {} - not found in admin dispatcher", uri);
LOG_I(TAG, "POST %s - not found in admin dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -1019,7 +1020,7 @@ esp_err_t WebServerService::handleApiGet(httpd_req_t* request) {
return handleApiScreenshot(request);
}
LOGGER.warn("GET {} - not found in api dispatcher", uri);
LOG_W(TAG, "GET %s - not found in api dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -1040,7 +1041,7 @@ esp_err_t WebServerService::handleApiPost(httpd_req_t* request) {
return handleApiAppsUninstall(request);
}
LOGGER.warn("POST {} - not found in api dispatcher", uri);
LOG_W(TAG, "POST %s - not found in api dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
@@ -1058,13 +1059,13 @@ esp_err_t WebServerService::handleApiPut(httpd_req_t* request) {
return handleApiAppsInstall(request);
}
LOGGER.warn("PUT {} - not found in api dispatcher", uri);
LOG_W(TAG, "PUT %s - not found in api dispatcher", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found");
return ESP_FAIL;
}
esp_err_t WebServerService::handleApiSysinfo(httpd_req_t* request) {
LOGGER.info("GET /api/sysinfo");
LOG_I(TAG, "GET /api/sysinfo");
std::ostringstream json;
json << "{";
@@ -1214,7 +1215,7 @@ esp_err_t WebServerService::handleApiSysinfo(httpd_req_t* request) {
// GET /api/apps - List installed apps
esp_err_t WebServerService::handleApiApps(httpd_req_t* request) {
LOGGER.info("GET /api/apps");
LOG_I(TAG, "GET /api/apps");
auto manifests = app::getAppManifests();
@@ -1255,7 +1256,7 @@ esp_err_t WebServerService::handleApiApps(httpd_req_t* request) {
// POST /api/apps/run?id=xxx - Run an app
esp_err_t WebServerService::handleApiAppsRun(httpd_req_t* request) {
LOGGER.info("POST /api/apps/run");
LOG_I(TAG, "POST /api/apps/run");
std::string appId;
if (!getQueryParam(request, "id", appId) || appId.empty()) {
@@ -1276,14 +1277,14 @@ esp_err_t WebServerService::handleApiAppsRun(httpd_req_t* request) {
app::start(appId);
LOGGER.info("[200] /api/apps/run {}", appId);
LOG_I(TAG, "[200] /api/apps/run %s", appId.c_str());
httpd_resp_sendstr(request, "ok");
return ESP_OK;
}
// POST /api/apps/uninstall?id=xxx - Uninstall an app
esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) {
LOGGER.info("POST /api/apps/uninstall");
LOG_I(TAG, "POST /api/apps/uninstall");
std::string appId;
if (!getQueryParam(request, "id", appId) || appId.empty()) {
@@ -1293,7 +1294,7 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) {
auto manifest = app::findAppManifestById(appId);
if (!manifest) {
LOGGER.info("[200] /api/apps/uninstall {} (app wasn't installed)", appId);
LOG_I(TAG, "[200] /api/apps/uninstall %s (app wasn't installed)", appId.c_str());
httpd_resp_sendstr(request, "ok");
return ESP_OK;
}
@@ -1305,11 +1306,11 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) {
}
if (app::uninstall(appId)) {
LOGGER.info("[200] /api/apps/uninstall {}", appId);
LOG_I(TAG, "[200] /api/apps/uninstall %s", appId.c_str());
httpd_resp_sendstr(request, "ok");
return ESP_OK;
} else {
LOGGER.warn("[500] /api/apps/uninstall {}", appId);
LOG_W(TAG, "[500] /api/apps/uninstall %s", appId.c_str());
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "uninstall failed");
return ESP_FAIL;
}
@@ -1317,7 +1318,7 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) {
// PUT /api/apps/install - Install an app from multipart form upload
esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) {
LOGGER.info("PUT /api/apps/install");
LOG_I(TAG, "PUT /api/apps/install");
std::string boundary;
if (!network::getMultiPartBoundaryOrSendError(request, boundary)) {
@@ -1340,14 +1341,14 @@ esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) {
auto content_disposition_map = network::parseContentDisposition(content_headers);
if (content_disposition_map.empty()) {
LOGGER.warn("parseContentDisposition returned empty map for: {}", content_headers_data);
LOG_W(TAG, "parseContentDisposition returned empty map for: %s", content_headers_data.c_str());
httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid content disposition");
return ESP_FAIL;
}
auto filename_entry = content_disposition_map.find("filename");
if (filename_entry == content_disposition_map.end()) {
LOGGER.warn("filename not found in content disposition map");
LOG_W(TAG, "filename not found in content disposition map");
httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "filename parameter missing");
return ESP_FAIL;
}
@@ -1402,10 +1403,10 @@ esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) {
// Cleanup temp file
if (!file::deleteFile(file_path)) {
LOGGER.warn("Failed to delete temp file {}", file_path);
LOG_W(TAG, "Failed to delete temp file %s", file_path.c_str());
}
LOGGER.info("[200] /api/apps/install -> {}", file_path);
LOG_I(TAG, "[200] /api/apps/install -> %s", file_path.c_str());
httpd_resp_sendstr(request, "ok");
return ESP_OK;
}
@@ -1425,7 +1426,7 @@ static const char* radioStateToJsonString(wifi::RadioState state) {
// GET /api/wifi - WiFi status
esp_err_t WebServerService::handleApiWifi(httpd_req_t* request) {
LOGGER.info("GET /api/wifi");
LOG_I(TAG, "GET /api/wifi");
auto state = wifi::getRadioState();
auto ip = wifi::getIp();
@@ -1450,7 +1451,7 @@ esp_err_t WebServerService::handleApiWifi(httpd_req_t* request) {
// GET /api/screenshot - Capture and return screenshot as PNG
// Screenshots are saved to SD card root (if available) or /data with incrementing numbers
esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
LOGGER.info("GET /api/screenshot");
LOG_I(TAG, "GET /api/screenshot");
#if TT_FEATURE_SCREENSHOT_ENABLED
// Determine save location: prefer SD card root if mounted, otherwise /data
@@ -1471,7 +1472,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
return ESP_FAIL;
}
LOGGER.info("Screenshot will be saved to: {}", screenshot_path);
LOG_I(TAG, "Screenshot will be saved to: %s", screenshot_path.c_str());
// LVGL's lodepng uses lv_fs which requires the "A:" prefix
std::string lvgl_screenshot_path = lvgl::PATH_PREFIX + screenshot_path;
@@ -1482,13 +1483,13 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
lvgl::unlock();
if (!success) {
LOGGER.error("lv_screenshot_create failed for path: {}", lvgl_screenshot_path);
LOG_E(TAG, "lv_screenshot_create failed for path: %s", lvgl_screenshot_path.c_str());
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "screenshot capture failed");
return ESP_FAIL;
}
LOGGER.info("Screenshot captured successfully");
LOG_I(TAG, "Screenshot captured successfully");
} else {
LOGGER.error("Could not acquire LVGL lock within 100ms");
LOG_E(TAG, "Could not acquire LVGL lock within 100ms");
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "could not acquire LVGL lock");
return ESP_FAIL;
}
@@ -1514,7 +1515,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
httpd_resp_send_chunk(request, nullptr, 0);
// File is kept on storage (not deleted) for user access
LOGGER.info("[200] /api/screenshot -> {}", screenshot_path);
LOG_I(TAG, "[200] /api/screenshot -> %s", screenshot_path.c_str());
return ESP_OK;
#else
httpd_resp_send_err(request, HTTPD_501_METHOD_NOT_IMPLEMENTED, "screenshot feature not enabled");
@@ -1524,7 +1525,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) {
esp_err_t WebServerService::handleFsTree(httpd_req_t* request) {
LOGGER.info("GET /fs/tree");
LOG_I(TAG, "GET /fs/tree");
std::ostringstream json;
json << "{";
@@ -1569,7 +1570,7 @@ esp_err_t WebServerService::handleFsMkdir(httpd_req_t* request) {
return ESP_FAIL;
}
std::string norm = normalizePath(path);
LOGGER.info("POST /fs/mkdir requested: '{}' normalized: '{}'", path, norm);
LOG_I(TAG, "POST /fs/mkdir requested: '%s' normalized: '%s'", path.c_str(), norm.c_str());
if (!isAllowedBasePath(norm)) {
httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path");
return ESP_FAIL;
@@ -1592,7 +1593,7 @@ esp_err_t WebServerService::handleFsDelete(httpd_req_t* request) {
return ESP_FAIL;
}
std::string norm = normalizePath(path);
LOGGER.info("POST /fs/delete requested: '{}' normalized: '{}'", path, norm);
LOG_I(TAG, "POST /fs/delete requested: '%s' normalized: '%s'", path.c_str(), norm.c_str());
if (!isAllowedBasePath(norm)) {
httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path");
return ESP_FAIL;
@@ -1623,7 +1624,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) {
return ESP_FAIL;
}
std::string norm = normalizePath(path);
LOGGER.info("POST /fs/rename requested: '{}' normalized: '{}' -> newName: '{}'", path.c_str(), norm.c_str(), newName.c_str());
LOG_I(TAG, "POST /fs/rename requested: '%s' normalized: '%s' -> newName: '%s'", path.c_str(), norm.c_str(), newName.c_str());
if (!isAllowedBasePath(norm)) {
httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path");
return ESP_FAIL;
@@ -1662,7 +1663,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) {
int r = rename(norm.c_str(), target.c_str());
if (r != 0) {
int e = errno;
LOGGER.warn("rename failed errno={} ({}) -> {} -> {}", e, strerror(e), norm, target);
LOG_W(TAG, "rename failed errno=%d (%s) -> %s -> %s", e, strerror(e), norm.c_str(), target.c_str());
// Return errno string to client to aid debugging
std::string msg = std::string("rename failed: ") + strerror(e);
httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, msg.c_str());
@@ -1676,7 +1677,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) {
esp_err_t WebServerService::handleReboot(httpd_req_t* request) {
LOGGER.info("POST /reboot");
LOG_I(TAG, "POST /reboot");
httpd_resp_sendstr(request, "Rebooting...");
// Reboot after a short delay to allow response to be sent
@@ -1695,7 +1696,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) {
}
const char* uri = request->uri;
LOGGER.info("GET {}", uri);
LOG_I(TAG, "GET %s", uri);
// Special case: serve favicon from system assets
if (strcmp(uri, "/favicon.ico") == 0) {
@@ -1721,7 +1722,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) {
fclose(fp);
lock->unlock();
httpd_resp_send_chunk(request, nullptr, 0);
LOGGER.info("[200] {} (favicon)", uri);
LOG_I(TAG, "[200] %s (favicon)", uri);
return ESP_OK;
}
lock->unlock();
@@ -1745,7 +1746,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) {
std::string dataPath = std::string("/system/app/WebServer") + requestedPath;
if (requestedPath == "/dashboard.html" && !file::isFile(dataPath.c_str())) {
LOGGER.info("dashboard.html not found, serving default.html");
LOG_I(TAG, "dashboard.html not found, serving default.html");
}
// Try to serve from Data partition first
@@ -1771,7 +1772,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) {
lock->unlock();
httpd_resp_send_chunk(request, nullptr, 0); // End of chunks
LOGGER.info("[200] {} (from Data)", uri);
LOG_I(TAG, "[200] %s (from Data)", uri);
return ESP_OK;
}
lock->unlock();
@@ -1800,14 +1801,14 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) {
lock->unlock();
httpd_resp_send_chunk(request, nullptr, 0); // End of chunks
LOGGER.info("[200] {} (from SD)", uri);
LOG_I(TAG, "[200] %s (from SD)", uri);
return ESP_OK;
}
lock->unlock();
}
// File not found
LOGGER.warn("[404] {}", uri);
LOG_W(TAG, "[404] %s", uri);
httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "File not found");
return ESP_FAIL;
}
@@ -1823,7 +1824,7 @@ void setWebServerEnabled(bool enabled) {
instance->setEnabled(enabled);
// Don't log here - startServer()/stopServer() already log the actual result
} else {
LOGGER.warn("WebServer service not available, cannot {}", enabled ? "start" : "stop");
LOG_W(TAG, "WebServer service not available, cannot %s", enabled ? "start" : "stop");
}
}
@@ -4,9 +4,11 @@
#include <Tactility/crypt/Crypt.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/service/ServicePaths.h>
#include <tactility/log.h>
#include <format>
#include <iomanip>
#include <ranges>
@@ -15,7 +17,7 @@
namespace tt::service::wifi::settings {
static const auto LOGGER = Logger("WifiApSettings");
constexpr auto* TAG = "WifiApSettings";
constexpr auto* AP_SETTINGS_FORMAT = "{}/{}.ap.properties";
@@ -34,7 +36,7 @@ std::string toHexString(const uint8_t *data, int length) {
bool readHex(const std::string& input, uint8_t* buffer, int length) {
if (input.size() / 2 != length) {
LOGGER.error("readHex() length mismatch");
LOG_E(TAG, "readHex() length mismatch");
return false;
}
@@ -64,7 +66,7 @@ static bool encrypt(const std::string& ssidInput, std::string& ssidOutput) {
crypt::getIv(ssidInput.c_str(), ssidInput.size(), iv);
if (crypt::encrypt(iv, reinterpret_cast<const uint8_t*>(ssidInput.c_str()), buffer, encrypted_length) != 0) {
LOGGER.error("Failed to encrypt");
LOG_E(TAG, "Failed to encrypt");
free(buffer);
return false;
}
@@ -80,7 +82,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) {
assert(ssidInput.size() % 2 == 0);
auto* data = static_cast<uint8_t*>(malloc(ssidInput.size() / 2));
if (!readHex(ssidInput, data, ssidInput.size() / 2)) {
LOGGER.error("Failed to read hex");
LOG_E(TAG, "Failed to read hex");
return false;
}
@@ -102,7 +104,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) {
free(data);
if (decrypt_result != 0) {
LOGGER.error("Failed to decrypt credentials for \"{}s\": {}", ssidInput, decrypt_result);
LOG_E(TAG, "Failed to decrypt credentials for \"%ss\": %d", ssidInput.c_str(), decrypt_result);
free(result);
return false;
}
@@ -186,7 +188,7 @@ bool save(const WifiApSettings& apSettings) {
const auto file_path = getApPropertiesFilePath(service_context->getPaths(), apSettings.ssid);
if (!file::findOrCreateParentDirectory(file_path, 0755)) {
LOGGER.error("Failed to create {}", file_path);
LOG_E(TAG, "Failed to create %s", file_path.c_str());
return false;
}
@@ -7,11 +7,13 @@
#include <Tactility/MountPoints.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/service/wifi/WifiApSettings.h>
#include <Tactility/Paths.h>
#include <Tactility/Tactility.h>
#include <tactility/log.h>
#include <dirent.h>
#include <format>
#include <map>
@@ -20,7 +22,7 @@
namespace tt::service::wifi {
static const auto LOGGER = Logger("WifiBootSplashInit");
constexpr auto* TAG = "WifiBootSplashInit";
constexpr auto* AP_PROPERTIES_KEY_SSID = "ssid";
constexpr auto* AP_PROPERTIES_KEY_PASSWORD = "password";
@@ -39,13 +41,13 @@ struct ApProperties {
static void importWifiAp(const std::string& filePath) {
std::map<std::string, std::string> map;
if (!file::loadPropertiesFile(filePath, map)) {
LOGGER.error("Failed to load AP properties at {}", filePath);
LOG_E(TAG, "Failed to load AP properties at %s", filePath.c_str());
return;
}
const auto ssid_iterator = map.find(AP_PROPERTIES_KEY_SSID);
if (ssid_iterator == map.end()) {
LOGGER.error("{} is missing ssid", filePath);
LOG_E(TAG, "%s is missing ssid", filePath.c_str());
return;
}
const auto ssid = ssid_iterator->second;
@@ -69,18 +71,18 @@ static void importWifiAp(const std::string& filePath) {
);
if (!settings::save(settings)) {
LOGGER.error("Failed to save settings for {}", ssid);
LOG_E(TAG, "Failed to save settings for %s", ssid.c_str());
} else {
LOGGER.info("Imported {} from {}", ssid, filePath);
LOG_I(TAG, "Imported %s from %s", ssid.c_str(), filePath.c_str());
}
}
const auto auto_remove_iterator = map.find(AP_PROPERTIES_KEY_AUTO_REMOVE);
if (auto_remove_iterator != map.end() && auto_remove_iterator->second == "true") {
if (!remove(filePath.c_str())) {
LOGGER.error("Failed to auto-remove {}", filePath);
LOG_E(TAG, "Failed to auto-remove %s", filePath.c_str());
} else {
LOGGER.info("Auto-removed {}", filePath);
LOG_I(TAG, "Auto-removed %s", filePath.c_str());
}
}
}
@@ -109,7 +111,7 @@ static void importWifiApSettingsFromDir(const std::string& path) {
}
if (dirent_list.empty()) {
LOGGER.warn("No AP files found at {}", path);
LOG_W(TAG, "No AP files found at %s", path.c_str());
return;
}
@@ -120,24 +122,24 @@ static void importWifiApSettingsFromDir(const std::string& path) {
}
void bootSplashInit() {
LOGGER.info("bootSplashInit dispatch");
LOG_I(TAG, "bootSplashInit dispatch");
getMainDispatcher().dispatch([] {
LOGGER.info("bootSplashInit dispatch begin");
LOG_I(TAG, "bootSplashInit dispatch begin");
// Import any provisioning files placed on the system data partition.
const std::string provisioning_path = file::getChildPath(getUserDataPath(), "provisioning");
if (file::isDirectory(provisioning_path)) {
importWifiApSettingsFromDir(provisioning_path);
} else {
LOGGER.info("Skip provisioning: no files at {}", provisioning_path);
LOG_I(TAG, "Skip provisioning: no files at %s", provisioning_path.c_str());
}
// Dispatch WiFi on
if (settings::shouldEnableOnBoot()) {
LOGGER.info("Auto-enabling WiFi");
LOG_I(TAG, "Auto-enabling WiFi");
getMainDispatcher().dispatch([] -> void { setEnabled(true); });
}
LOGGER.info("bootSplashInit dispatch end");
LOG_I(TAG, "bootSplashInit dispatch end");
});
}
+75 -74
View File
@@ -6,10 +6,8 @@
#include <Tactility/service/wifi/Wifi.h>
#include <tactility/check.h>
#include <Tactility/EventGroup.h>
#include <Tactility/Logger.h>
#include <Tactility/LogMessages.h>
#include <Tactility/EventGroup.h>
#include <Tactility/RecursiveMutex.h>
#include <Tactility/Tactility.h>
#include <Tactility/Timer.h>
@@ -19,6 +17,9 @@
#include <Tactility/service/wifi/WifiGlobals.h>
#include <Tactility/service/wifi/WifiSettings.h>
#include <tactility/check.h>
#include <tactility/log.h>
#include <esp_wifi_default.h>
#include <lwip/esp_netif_net_stack.h>
#include <freertos/FreeRTOS.h>
@@ -28,7 +29,7 @@
namespace tt::service::wifi {
static const auto LOGGER = Logger("WifiService");
constexpr auto* TAG = "WifiService";
constexpr auto WIFI_CONNECTED_BIT = BIT0;
constexpr auto WIFI_FAIL_BIT = BIT1;
@@ -155,7 +156,7 @@ std::string getConnectionTarget() {
}
void scan() {
LOGGER.info("scan()");
LOG_I(TAG, "scan()");
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
@@ -174,7 +175,7 @@ bool isScanning() {
}
void connect(const settings::WifiApSettings& ap, bool remember) {
LOGGER.info("connect({}, {})", ap.ssid, remember);
LOG_I(TAG, "connect(%s, %d)", ap.ssid.c_str(), (int)remember);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
@@ -198,7 +199,7 @@ void connect(const settings::WifiApSettings& ap, bool remember) {
}
void disconnect() {
LOGGER.info("disconnect()");
LOG_I(TAG, "disconnect()");
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
@@ -229,7 +230,7 @@ void clearIp() {
memset(&wifi->ip_info, 0, sizeof(esp_netif_ip_info_t));
}
void setScanRecords(uint16_t records) {
LOGGER.info("setScanRecords({})", records);
LOG_I(TAG, "setScanRecords(%u)", records);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
@@ -247,7 +248,7 @@ void setScanRecords(uint16_t records) {
}
std::vector<ApRecord> getScanResults() {
LOGGER.info("getScanResults()");
LOG_I(TAG, "getScanResults()");
auto wifi = wifi_singleton;
std::vector<ApRecord> records;
@@ -278,7 +279,7 @@ std::vector<ApRecord> getScanResults() {
}
void setEnabled(bool enabled) {
LOGGER.info("setEnabled({})", enabled);
LOG_I(TAG, "setEnabled(%d)", (int)enabled);
auto wifi = wifi_singleton;
if (wifi == nullptr) {
return;
@@ -370,7 +371,7 @@ static bool copy_scan_list(std::shared_ptr<Wifi> wifi) {
wifi->isScanActive();
if (!can_fetch_results) {
LOGGER.info("Skip scan result fetching");
LOG_I(TAG, "Skip scan result fetching");
return false;
}
@@ -387,11 +388,11 @@ static bool copy_scan_list(std::shared_ptr<Wifi> wifi) {
if (scan_result == ESP_OK) {
uint16_t safe_record_count = std::min(wifi->scan_list_limit, record_count);
wifi->scan_list_count = safe_record_count;
LOGGER.info("Scanned {} APs. Showing {}:", record_count, safe_record_count);
LOG_I(TAG, "Scanned %u APs. Showing %u:", record_count, safe_record_count);
for (uint16_t i = 0; i < safe_record_count; i++) {
wifi_ap_record_t* record = &wifi->scan_list[i];
if (record->ssid[0] != 0 && record->primary != 0) {
LOGGER.info(" - SSID {}, RSSI {}, channel {}, BSSID {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
LOG_I(TAG, " - SSID %s, RSSI %d, channel %u, BSSID %02x:%02x:%02x:%02x:%02x:%02x",
reinterpret_cast<const char*>(record->ssid),
record->rssi,
record->primary,
@@ -403,18 +404,18 @@ static bool copy_scan_list(std::shared_ptr<Wifi> wifi) {
record->bssid[5]
);
} else {
LOGGER.info(" - (missing channel info)"); // Behaviour on on P4 with C6
LOG_I(TAG, " - (missing channel info)"); // Behaviour on on P4 with C6
}
}
return true;
} else {
LOGGER.info("Failed to get scanned records: {}", esp_err_to_name(scan_result));
LOG_I(TAG, "Failed to get scanned records: %s", esp_err_to_name(scan_result));
return false;
}
}
static bool find_auto_connect_ap(std::shared_ptr<Wifi> wifi, settings::WifiApSettings& settings) {
LOGGER.info("find_auto_connect_ap()");
LOG_I(TAG, "find_auto_connect_ap()");
auto lock = wifi->dataMutex.asScopedLock();
if (lock.lock(10 / portTICK_PERIOD_MS)) {
for (int i = 0; i < wifi->scan_list_count; ++i) {
@@ -426,7 +427,7 @@ static bool find_auto_connect_ap(std::shared_ptr<Wifi> wifi, settings::WifiApSet
return true;
}
} else {
LOGGER.error("Failed to load credentials for ssid {}", ssid);
LOG_E(TAG, "Failed to load credentials for ssid %s", ssid);
}
break;
}
@@ -437,11 +438,11 @@ static bool find_auto_connect_ap(std::shared_ptr<Wifi> wifi, settings::WifiApSet
}
static void dispatchAutoConnect(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchAutoConnect()");
LOG_I(TAG, "dispatchAutoConnect()");
settings::WifiApSettings settings;
if (find_auto_connect_ap(wifi, settings)) {
LOGGER.info("Auto-connecting to {}", settings.ssid);
LOG_I(TAG, "Auto-connecting to %s", settings.ssid.c_str());
connect(settings, false);
// TODO: We currently have to manually reset it because connect() sets it.
// connect() assumes it's only being called by the user and not internally, so it disables auto-connect
@@ -452,23 +453,23 @@ static void dispatchAutoConnect(std::shared_ptr<Wifi> wifi) {
static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
auto wifi = wifi_singleton;
if (wifi == nullptr) {
LOGGER.error("eventHandler: no wifi instance");
LOG_E(TAG, "eventHandler: no wifi instance");
return;
}
if (event_base == WIFI_EVENT) {
LOGGER.info("eventHandler: WIFI_EVENT {}", event_id);
LOG_I(TAG, "eventHandler: WIFI_EVENT %d", (int)event_id);
} else if (event_base == IP_EVENT) {
LOGGER.info("eventHandler: IP_EVENT {}", event_id);
LOG_I(TAG, "eventHandler: IP_EVENT %d", (int)event_id);
}
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
LOGGER.info("eventHandler: STA_START");
LOG_I(TAG, "eventHandler: STA_START");
if (wifi->getRadioState() == RadioState::ConnectionPending) {
esp_wifi_connect();
}
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
LOGGER.info("eventHandler: STA_DISCONNECTED");
LOG_I(TAG, "eventHandler: STA_DISCONNECTED");
clearIp();
switch (wifi->getRadioState()) {
case RadioState::ConnectionPending:
@@ -487,7 +488,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
auto* event = static_cast<ip_event_got_ip_t*>(event_data);
memcpy(&wifi->ip_info, &event->ip_info, sizeof(esp_netif_ip_info_t));
LOGGER.info("eventHandler: got ip: {}.{}.{}.{}", IP2STR(&event->ip_info.ip));
LOG_I(TAG, "eventHandler: got ip: %d.%d.%d.%d", IP2STR(&event->ip_info.ip));
if (wifi->getRadioState() == RadioState::ConnectionPending) {
wifi->connection_wait_flags.set(WIFI_CONNECTED_BIT);
// We resume auto-connecting only when there was an explicit request by the user for the connection
@@ -497,7 +498,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i
kernel::publishSystemEvent(kernel::SystemEvent::NetworkConnected);
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
auto* event = static_cast<wifi_event_sta_scan_done_t*>(event_data);
LOGGER.info("eventHandler: wifi scanning done (scan id {})", event->scan_id);
LOG_I(TAG, "eventHandler: wifi scanning done (scan id %u)", event->scan_id);
bool copied_list = copy_scan_list(wifi);
auto state = wifi->getRadioState();
@@ -510,7 +511,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i
}
publish_event(wifi_singleton, WifiEvent::ScanFinished);
LOGGER.info("eventHandler: Finished scan");
LOG_I(TAG, "eventHandler: Finished scan");
if (copied_list && wifi_singleton->getRadioState() == RadioState::On && !wifi->pause_auto_connect) {
getMainDispatcher().dispatch([wifi]() { dispatchAutoConnect(wifi); });
@@ -519,7 +520,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i
}
static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchEnable()");
LOG_I(TAG, "dispatchEnable()");
RadioState state = wifi->getRadioState();
if (
@@ -527,13 +528,13 @@ static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
state == RadioState::OnPending ||
state == RadioState::OffPending
) {
LOGGER.warn("Can't enable from current state");
LOG_W(TAG, "Can't enable from current state");
return;
}
auto lock = wifi->radioMutex.asScopedLock();
if (lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.info("Enabling");
LOG_I(TAG, "Enabling");
wifi->setRadioState(RadioState::OnPending);
publish_event(wifi, WifiEvent::RadioStateOnPending);
@@ -548,9 +549,9 @@ static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT();
esp_err_t init_result = esp_wifi_init(&config);
if (init_result != ESP_OK) {
LOGGER.error("Wifi init failed");
LOG_E(TAG, "Wifi init failed");
if (init_result == ESP_ERR_NO_MEM) {
LOGGER.error("Insufficient memory");
LOG_E(TAG, "Insufficient memory");
}
wifi->setRadioState(RadioState::Off);
publish_event(wifi, WifiEvent::RadioStateOff);
@@ -578,7 +579,7 @@ static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
));
if (esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK) {
LOGGER.error("Wifi mode setting failed");
LOG_E(TAG, "Wifi mode setting failed");
wifi->setRadioState(RadioState::Off);
esp_wifi_deinit();
publish_event(wifi, WifiEvent::RadioStateOff);
@@ -587,9 +588,9 @@ static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
esp_err_t start_result = esp_wifi_start();
if (start_result != ESP_OK) {
LOGGER.error("Wifi start failed");
LOG_E(TAG, "Wifi start failed");
if (start_result == ESP_ERR_NO_MEM) {
LOGGER.error("Insufficient memory");
LOG_E(TAG, "Insufficient memory");
}
wifi->setRadioState(RadioState::Off);
esp_wifi_set_mode(WIFI_MODE_NULL);
@@ -603,18 +604,18 @@ static void dispatchEnable(std::shared_ptr<Wifi> wifi) {
wifi->pause_auto_connect = false;
LOGGER.info("Enabled");
LOG_I(TAG, "Enabled");
} else {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
}
}
static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchDisable()");
LOG_I(TAG, "dispatchDisable()");
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()");
return;
}
@@ -624,11 +625,11 @@ static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
state == RadioState::OffPending ||
state == RadioState::OnPending
) {
LOGGER.warn("Can't disable from current state");
LOG_W(TAG, "Can't disable from current state");
return;
}
LOGGER.info("Disabling");
LOG_I(TAG, "Disabling");
wifi->setRadioState(RadioState::OffPending);
publish_event(wifi, WifiEvent::RadioStateOffPending);
@@ -649,11 +650,11 @@ static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
// event handlers and subsequent disable attempts would behave incorrectly.
// If stop fails, continue the teardown anyway so we end in a clean Off state.
if (esp_wifi_stop() != ESP_OK) {
LOGGER.error("Failed to stop radio - continuing teardown");
LOG_E(TAG, "Failed to stop radio - continuing teardown");
}
if (esp_wifi_set_mode(WIFI_MODE_NULL) != ESP_OK) {
LOGGER.error("Failed to unset mode");
LOG_E(TAG, "Failed to unset mode");
}
if (esp_event_handler_instance_unregister(
@@ -661,7 +662,7 @@ static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
ESP_EVENT_ANY_ID,
wifi->event_handler_any_id
) != ESP_OK) {
LOGGER.error("Failed to unregister id event handler");
LOG_E(TAG, "Failed to unregister id event handler");
}
if (esp_event_handler_instance_unregister(
@@ -669,11 +670,11 @@ static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
IP_EVENT_STA_GOT_IP,
wifi->event_handler_got_ip
) != ESP_OK) {
LOGGER.error("Failed to unregister ip event handler");
LOG_E(TAG, "Failed to unregister ip event handler");
}
if (esp_wifi_deinit() != ESP_OK) {
LOGGER.error("Failed to deinit");
LOG_E(TAG, "Failed to deinit");
}
assert(wifi->netif != nullptr);
@@ -682,26 +683,26 @@ static void dispatchDisable(std::shared_ptr<Wifi> wifi) {
wifi->setScanActive(false);
wifi->setRadioState(RadioState::Off);
publish_event(wifi, WifiEvent::RadioStateOff);
LOGGER.info("Disabled");
LOG_I(TAG, "Disabled");
}
static void dispatchScan(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchScan()");
LOG_I(TAG, "dispatchScan()");
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(10 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
RadioState state = wifi->getRadioState();
if (state != RadioState::On && state != RadioState::ConnectionActive && state != RadioState::ConnectionPending) {
LOGGER.warn("Scan unavailable: wifi not enabled");
LOG_W(TAG, "Scan unavailable: wifi not enabled");
return;
}
if (wifi->isScanActive()) {
LOGGER.warn("Scan already pending");
LOG_W(TAG, "Scan already pending");
return;
}
@@ -709,25 +710,25 @@ static void dispatchScan(std::shared_ptr<Wifi> wifi) {
wifi->last_scan_time = tt::kernel::getTicks();
if (esp_wifi_scan_start(nullptr, false) != ESP_OK) {
LOGGER.info("Can't start scan");
LOG_I(TAG, "Can't start scan");
return;
}
LOGGER.info("Starting scan");
LOG_I(TAG, "Starting scan");
wifi->setScanActive(true);
publish_event(wifi, WifiEvent::ScanStarted);
}
static void dispatchConnect(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchConnect()");
LOG_I(TAG, "dispatchConnect()");
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()");
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()");
return;
}
LOGGER.info("Connecting to {}", wifi->connection_target.ssid);
LOG_I(TAG, "Connecting to %s", wifi->connection_target.ssid.c_str());
// Stop radio first, if needed
RadioState radio_state = wifi->getRadioState();
@@ -736,11 +737,11 @@ static void dispatchConnect(std::shared_ptr<Wifi> wifi) {
radio_state == RadioState::ConnectionActive ||
radio_state == RadioState::ConnectionPending
) {
LOGGER.info("Connecting: Stopping radio first");
LOG_I(TAG, "Connecting: Stopping radio first");
esp_err_t stop_result = esp_wifi_stop();
wifi->setScanActive(false);
if (stop_result != ESP_OK) {
LOGGER.error("Connecting: Failed to disconnect ({})", esp_err_to_name(stop_result));
LOG_E(TAG, "Connecting: Failed to disconnect (%s)", esp_err_to_name(stop_result));
return;
}
}
@@ -766,20 +767,20 @@ static void dispatchConnect(std::shared_ptr<Wifi> wifi) {
config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
}
LOGGER.info("esp_wifi_set_config()");
LOG_I(TAG, "esp_wifi_set_config()");
esp_err_t set_config_result = esp_wifi_set_config(WIFI_IF_STA, &config);
if (set_config_result != ESP_OK) {
wifi->setRadioState(RadioState::On);
LOGGER.error("Failed to set wifi config ({})", esp_err_to_name(set_config_result));
LOG_E(TAG, "Failed to set wifi config (%s)", esp_err_to_name(set_config_result));
publish_event(wifi, WifiEvent::ConnectionFailed);
return;
}
LOGGER.info("esp_wifi_start()");
LOG_I(TAG, "esp_wifi_start()");
esp_err_t wifi_start_result = esp_wifi_start();
if (wifi_start_result != ESP_OK) {
wifi->setRadioState(RadioState::On);
LOGGER.error("Failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result));
LOG_E(TAG, "Failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result));
publish_event(wifi, WifiEvent::ConnectionFailed);
return;
}
@@ -789,28 +790,28 @@ static void dispatchConnect(std::shared_ptr<Wifi> wifi) {
* The bits are set by wifi_event_handler() */
uint32_t flags;
if (wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT, false, true, &flags, kernel::MAX_TICKS)) {
LOGGER.info("Waiting for EventGroup by event_handler()");
LOG_I(TAG, "Waiting for EventGroup by event_handler()");
if (flags & WIFI_CONNECTED_BIT) {
wifi->setSecureConnection(config.sta.password[0] != 0x00U);
wifi->setRadioState(RadioState::ConnectionActive);
publish_event(wifi, WifiEvent::ConnectionSuccess);
LOGGER.info("Connected to {}", wifi->connection_target.ssid.c_str());
LOG_I(TAG, "Connected to %s", wifi->connection_target.ssid.c_str());
if (wifi->connection_target_remember) {
if (!settings::save(wifi->connection_target)) {
LOGGER.error("Failed to store credentials");
LOG_E(TAG, "Failed to store credentials");
} else {
LOGGER.info("Stored credentials");
LOG_I(TAG, "Stored credentials");
}
}
} else if (flags & WIFI_FAIL_BIT) {
wifi->setRadioState(RadioState::On);
publish_event(wifi, WifiEvent::ConnectionFailed);
LOGGER.info("Failed to connect to {}", wifi->connection_target.ssid.c_str());
LOG_I(TAG, "Failed to connect to %s", wifi->connection_target.ssid.c_str());
} else {
wifi->setRadioState(RadioState::On);
publish_event(wifi, WifiEvent::ConnectionFailed);
LOGGER.error("UNEXPECTED EVENT");
LOG_E(TAG, "UNEXPECTED EVENT");
}
wifi_singleton->connection_wait_flags.clear(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT);
@@ -818,17 +819,17 @@ static void dispatchConnect(std::shared_ptr<Wifi> wifi) {
}
static void dispatchDisconnectButKeepActive(std::shared_ptr<Wifi> wifi) {
LOGGER.info("dispatchDisconnectButKeepActive()");
LOG_I(TAG, "dispatchDisconnectButKeepActive()");
auto lock = wifi->radioMutex.asScopedLock();
if (!lock.lock(50 / portTICK_PERIOD_MS)) {
LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED);
LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED);
return;
}
esp_err_t stop_result = esp_wifi_stop();
if (stop_result != ESP_OK) {
LOGGER.error("Failed to disconnect ({})", esp_err_to_name(stop_result));
LOG_E(TAG, "Failed to disconnect (%s)", esp_err_to_name(stop_result));
return;
}
@@ -844,7 +845,7 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr<Wifi> wifi) {
if (set_config_result != ESP_OK) {
// TODO: disable radio, because radio state is in limbo between off and on
wifi->setRadioState(RadioState::Off);
LOGGER.error("failed to set wifi config ({})", esp_err_to_name(set_config_result));
LOG_E(TAG, "failed to set wifi config (%s)", esp_err_to_name(set_config_result));
publish_event(wifi, WifiEvent::RadioStateOff);
return;
}
@@ -853,14 +854,14 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr<Wifi> wifi) {
if (wifi_start_result != ESP_OK) {
// TODO: disable radio, because radio state is in limbo between off and on
wifi->setRadioState(RadioState::Off);
LOGGER.error("failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result));
LOG_E(TAG, "failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result));
publish_event(wifi, WifiEvent::RadioStateOff);
return;
}
wifi->setRadioState(RadioState::On);
publish_event(wifi, WifiEvent::Disconnected);
LOGGER.info("Disconnected");
LOG_I(TAG, "Disconnected");
}
static bool shouldScanForAutoConnect(std::shared_ptr<Wifi> wifi) {
@@ -2,13 +2,14 @@
#include <Tactility/file/File.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/Logger.h>
#include <Tactility/service/ServicePaths.h>
#include <Tactility/service/wifi/WifiPrivate.h>
#include <tactility/log.h>
namespace tt::service::wifi::settings {
static const auto LOGGER = Logger("WifiSettings");
constexpr auto* TAG = "WifiSettings";
constexpr auto* SETTINGS_KEY_ENABLE_ON_BOOT = "enableOnBoot";
struct WifiSettings {
@@ -47,7 +48,7 @@ static bool save(std::shared_ptr<ServiceContext> context, const WifiSettings& se
map[SETTINGS_KEY_ENABLE_ON_BOOT] = settings.enableOnBoot ? "true" : "false";
std::string settings_path = context->getPaths()->getUserDataPath("settings.properties");
if (!file::findOrCreateParentDirectory(settings_path, 0755)) {
LOGGER.error("Failed to create {}", settings_path);
LOG_E(TAG, "Failed to create %s", settings_path.c_str());
return false;
}
return file::savePropertiesFile(settings_path, map);
@@ -60,7 +61,7 @@ WifiSettings getCachedOrLoad() {
if (load(context, cachedSettings)) {
cached = true;
} else {
LOGGER.info("Failed to load settings, using defaults");
LOG_I(TAG, "Failed to load settings, using defaults");
}
}
}
@@ -72,7 +73,7 @@ void setEnableOnBoot(bool enable) {
cachedSettings.enableOnBoot = enable;
auto context = findServiceContext();
if (context && !save(context, cachedSettings)) {
LOGGER.error("Failed to save settings");
LOG_E(TAG, "Failed to save settings");
}
}
+4 -3
View File
@@ -1,12 +1,13 @@
#include <Tactility/Logger.h>
#include <Tactility/settings/Language.h>
#include <Tactility/settings/SystemSettings.h>
#include <tactility/log.h>
#include <utility>
namespace tt::settings {
static const auto LOGGER = Logger("Language");
constexpr auto* TAG = "Language";
void setLanguage(Language newLanguage) {
SystemSettings properties;
@@ -40,7 +41,7 @@ std::string toString(Language language) {
case Language::nl_NL:
return "nl-NL";
default:
LOGGER.error("Missing serialization for language {}", static_cast<int>(language));
LOG_E(TAG, "Missing serialization for language %d", static_cast<int>(language));
std::unreachable();
}
}
+10 -9
View File
@@ -1,4 +1,3 @@
#include <Tactility/Logger.h>
#include <Tactility/Mutex.h>
#include <Tactility/file/File.h>
#include <Tactility/file/FileLock.h>
@@ -8,11 +7,13 @@
#include "Tactility/Paths.h"
#include <tactility/log.h>
#include <format>
namespace tt::settings {
static const auto LOGGER = Logger("SystemSettings");
constexpr auto* TAG = "SystemSettings";
constexpr auto* FILE_PATH_FORMAT = "{}/settings/system.properties";
@@ -26,7 +27,7 @@ static bool hasSystemSettingsFile() {
static bool loadSystemSettingsFromFile(SystemSettings& properties) {
auto file_path = std::format(FILE_PATH_FORMAT, getUserDataPath());
LOGGER.info("System settings loading from {}", file_path);
LOG_I(TAG, "System settings loading from %s", file_path.c_str());
std::map<std::string, std::string> map;
if (!file::loadPropertiesFile(file_path, map)) {
return false;
@@ -35,7 +36,7 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) {
auto language_entry = map.find("language");
if (language_entry != map.end()) {
if (!fromString(language_entry->second, properties.language)) {
LOGGER.warn("Unknown language \"{}\" in {}", language_entry->second, file_path);
LOG_W(TAG, "Unknown language \"%s\" in %s", language_entry->second.c_str(), file_path.c_str());
properties.language = Language::en_US;
}
} else {
@@ -52,11 +53,11 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) {
if (date_format_entry != map.end() && !date_format_entry->second.empty()) {
properties.dateFormat = date_format_entry->second;
} else {
LOGGER.info("dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)");
LOG_I(TAG, "dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)");
properties.dateFormat = "MM/DD/YYYY";
}
LOGGER.info("System settings loaded");
LOG_I(TAG, "System settings loaded");
return true;
}
@@ -65,7 +66,7 @@ bool loadSystemSettings(SystemSettings& properties) {
if (loadSystemSettingsFromFile(cachedSettings)) {
cached = true;
} else {
LOGGER.error("Failed to load");
LOG_E(TAG, "Failed to load");
}
}
@@ -81,12 +82,12 @@ bool saveSystemSettings(const SystemSettings& properties) {
map["dateFormat"] = properties.dateFormat;
if (!file::findOrCreateParentDirectory(file_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", file_path);
LOG_E(TAG, "Failed to create parent dir for %s", file_path.c_str());
return false;
}
if (!file::savePropertiesFile(file_path, map)) {
LOGGER.error("Failed to save {}", file_path);
LOG_E(TAG, "Failed to save %s", file_path.c_str());
return false;
}
+12 -11
View File
@@ -1,9 +1,10 @@
#include <Tactility/settings/WebServerSettings.h>
#include <Tactility/file/PropertiesFile.h>
#include <Tactility/file/File.h>
#include <Tactility/Logger.h>
#include <Tactility/Paths.h>
#include <tactility/log.h>
#include <charconv>
#include <map>
#include <string>
@@ -18,7 +19,7 @@
namespace tt::settings::webserver {
static const auto LOGGER = Logger("WebServerSettings");
constexpr auto* TAG = "WebServerSettings";
static std::string getSettingsFilePath() {
return getUserDataPath() + "/settings/webserver.properties";
@@ -147,7 +148,7 @@ bool load(WebServerSettings& settings) {
// Skip this if user explicitly wants an open network.
// Note: We only auto-generate for EMPTY passwords, not user-set ones.
if (!settings.apOpenNetwork && isEmptyCredential(settings.apPassword)) {
LOGGER.info("AP password is empty - generating secure random password");
LOG_I(TAG, "AP password is empty - generating secure random password");
// Generate 12-character random password (alphanumeric, ~71 bits of entropy)
// WPA2 requires 8-63 characters, so 12 is well within range
@@ -156,9 +157,9 @@ bool load(WebServerSettings& settings) {
// Persist the generated password immediately
map[KEY_AP_PASSWORD] = settings.apPassword;
if (file::savePropertiesFile(getSettingsFilePath(), map)) {
LOGGER.info("Generated and saved new secure AP password");
LOG_I(TAG, "Generated and saved new secure AP password");
} else {
LOGGER.error("Failed to save generated AP password");
LOG_E(TAG, "Failed to save generated AP password");
}
}
@@ -186,7 +187,7 @@ bool load(WebServerSettings& settings) {
if (settings.webServerAuthEnabled &&
(isEmptyCredential(settings.webServerUsername) || isEmptyCredential(settings.webServerPassword))) {
LOGGER.info("Auth enabled with empty credentials - generating secure random credentials");
LOG_I(TAG, "Auth enabled with empty credentials - generating secure random credentials");
// Generate 12-character random credentials (alphanumeric, ~71 bits of entropy each)
settings.webServerUsername = generateRandomCredential(12);
@@ -197,9 +198,9 @@ bool load(WebServerSettings& settings) {
map[KEY_WEBSERVER_USERNAME] = settings.webServerUsername;
map[KEY_WEBSERVER_PASSWORD] = settings.webServerPassword;
if (file::savePropertiesFile(getSettingsFilePath(), map)) {
LOGGER.info("Generated and saved new secure credentials");
LOG_I(TAG, "Generated and saved new secure credentials");
} else {
LOGGER.error("Failed to save generated credentials - auth may be inconsistent across reboots");
LOG_E(TAG, "Failed to save generated credentials - auth may be inconsistent across reboots");
}
}
@@ -231,9 +232,9 @@ WebServerSettings loadOrGetDefault() {
settings = getDefault();
// Save defaults to flash so toggle states persist
if (save(settings)) {
LOGGER.info("First boot - saved default settings (WiFi OFF WebServer OFF)");
LOG_I(TAG, "First boot - saved default settings (WiFi OFF WebServer OFF)");
} else {
LOGGER.warn("First boot - failed to save default settings to flash");
LOG_W(TAG, "First boot - failed to save default settings to flash");
}
}
@@ -264,7 +265,7 @@ bool save(const WebServerSettings& settings) {
auto settings_path = getSettingsFilePath();
if (!file::findOrCreateParentDirectory(settings_path, 0755)) {
LOGGER.error("Failed to create parent dir for {}", settings_path);
LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str());
return false;
}
return file::savePropertiesFile(settings_path, map);