From f620255c415fa8a929a682506bd39223c4151dd6 Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Tue, 6 Jan 2026 22:35:39 +0100 Subject: [PATCH] New logging and more (#446) - `TT_LOG_*` macros are replaced by `Logger` via `#include` - Changed default timezone to Europe/Amsterdam - Fix for logic bug in unPhone hardware - Fix for init/deinit in DRV2605 driver - Other fixes - Removed optimization that broke unPhone (disabled the moving of heap-related functions to flash) --- Buildscripts/sdkconfig/default.properties | 1 - Data/data/settings/system.properties | 2 +- .../Source/devices/Display.cpp | 1 - .../Source/devices/St7701Display.cpp | 16 +- .../cyd-8048s043c/Source/devices/Display.cpp | 1 - .../Source/devices/Display.cpp | 1 - .../Source/devices/Display.cpp | 1 - .../Source/devices/Display.cpp | 1 - .../Source/Configuration.cpp | 4 +- Devices/lilygo-tdeck/Source/Init.cpp | 45 +++--- .../KeyboardBacklight/KeyboardBacklight.cpp | 31 ++-- .../Source/Trackball/Trackball.cpp | 30 ++-- .../Source/devices/TdeckKeyboard.cpp | 12 +- Devices/lilygo-tdongle-s3/Source/Init.cpp | 7 +- Devices/lilygo-tlora-pager/Source/Init.cpp | 13 +- .../Source/devices/TpagerEncoder.cpp | 100 ++++++++++-- .../Source/devices/TpagerEncoder.h | 3 +- .../Source/devices/TpagerKeyboard.cpp | 10 +- .../Source/devices/TpagerPower.cpp | 6 +- .../Source/devices/CardputerPower.cpp | 20 +-- .../Source/devices/CardputerKeyboard.cpp | 6 +- .../Source/devices/CardputerPower.cpp | 20 +-- Devices/m5stack-cores3/Source/InitBoot.cpp | 24 +-- .../m5stack-cores3/Source/devices/Display.cpp | 6 +- .../Source/devices/Display.cpp | 7 +- Devices/simulator/Source/LvglTask.cpp | 10 +- Devices/simulator/Source/Main.cpp | 10 +- Devices/unphone/Source/InitBoot.cpp | 26 +-- Devices/unphone/Source/UnPhoneFeatures.cpp | 44 ++--- .../unphone/Source/devices/Hx8357Display.cpp | 23 +-- Devices/unphone/Source/devices/Touch.cpp | 2 - .../Source/Init.cpp | 1 + .../Source/devices/Jd9853Display.cpp | 22 +-- Drivers/AXP2101/Source/Axp2101.cpp | 1 - Drivers/BQ24295/Source/Bq24295.cpp | 12 +- Drivers/BQ24295/Source/Bq24295.h | 1 - Drivers/BQ25896/Source/Bq25896.cpp | 8 +- Drivers/BQ27220/Source/Bq27220.cpp | 24 +-- .../ButtonControl/Source/ButtonControl.cpp | 10 +- Drivers/ButtonControl/Source/ButtonControl.h | 1 + Drivers/DRV2605/Source/Drv2605.cpp | 23 ++- Drivers/DRV2605/Source/Drv2605.h | 14 +- Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp | 14 +- .../EspLcdCompat/Source/EspLcdDisplayV2.cpp | 30 ++-- .../EspLcdCompat/Source/EspLcdSpiDisplay.cpp | 10 +- Drivers/EspLcdCompat/Source/EspLcdTouch.cpp | 19 +-- .../EspLcdCompat/Source/EspLcdTouchDriver.cpp | 6 +- .../Source/ChargeFromAdcVoltage.cpp | 15 +- .../Source/ChargeFromVoltage.cpp | 6 +- Drivers/FT5x06/Source/Ft5x06Touch.cpp | 4 - Drivers/FT6x36/Source/Ft6x36Touch.cpp | 10 +- Drivers/FT6x36/Source/Ft6x36Touch.h | 1 + Drivers/GC9A01/Source/Gc9a01Display.cpp | 22 +-- Drivers/GT911/Source/Gt911Touch.cpp | 6 +- Drivers/ILI9488/Source/Ili9488Display.cpp | 18 +-- Drivers/PwmBacklight/Source/PwmBacklight.cpp | 13 +- Drivers/RgbDisplay/Source/RgbDisplay.cpp | 28 ++-- Drivers/SSD1306/Source/Ssd1306Display.cpp | 14 +- Drivers/ST7735/Source/St7735Display.cpp | 26 +-- .../Source/St7789i8080Display.cpp | 50 +++--- .../Source/St7796i8080Display.cpp | 48 +++--- Drivers/ST7796/Source/St7796Display.cpp | 22 +-- Drivers/TCA8418/Source/Tca8418.cpp | 3 - Drivers/XPT2046/Source/Xpt2046Power.cpp | 13 +- Drivers/XPT2046/Source/Xpt2046Touch.cpp | 1 - .../XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp | 57 ++++--- .../Include/Tactility/network/EspHttpClient.h | 21 +-- Tactility/Include/Tactility/network/Http.h | 4 +- Tactility/Private/Tactility/app/AppInstance.h | 4 +- Tactility/Private/Tactility/json/Reader.h | 16 +- Tactility/Source/PartitionsEsp.cpp | 17 +- Tactility/Source/PreferencesEsp.cpp | 35 ++-- Tactility/Source/PreferencesMock.cpp | 3 +- Tactility/Source/Tactility.cpp | 42 ++--- ...tilityHeadlessEsp.cpp => TactilityEsp.cpp} | 13 +- Tactility/Source/app/AppInstall.cpp | 59 ++++--- Tactility/Source/app/AppInstance.cpp | 2 - Tactility/Source/app/AppManifestParsing.cpp | 34 ++-- Tactility/Source/app/AppRegistration.cpp | 15 +- Tactility/Source/app/ElfApp.cpp | 19 ++- Tactility/Source/app/addgps/AddGps.cpp | 23 ++- .../Source/app/alertdialog/AlertDialog.cpp | 8 +- Tactility/Source/app/apphub/AppHubApp.cpp | 9 +- Tactility/Source/app/apphub/AppHubEntry.cpp | 11 +- .../app/apphubdetails/AppHubDetailsApp.cpp | 28 ++-- Tactility/Source/app/boot/Boot.cpp | 29 ++-- Tactility/Source/app/chat/ChatApp.cpp | 5 +- .../app/crashdiagnostics/CrashDiagnostics.cpp | 32 ++-- .../Source/app/development/Development.cpp | 5 +- Tactility/Source/app/display/Display.cpp | 5 +- Tactility/Source/app/files/State.cpp | 22 +-- Tactility/Source/app/files/View.cpp | 60 +++---- Tactility/Source/app/fileselection/State.cpp | 16 +- Tactility/Source/app/fileselection/View.cpp | 31 ++-- .../Source/app/gpssettings/GpsSettings.cpp | 19 +-- .../Source/app/i2cscanner/I2cScanner.cpp | 45 +++--- .../Source/app/imageviewer/ImageViewer.cpp | 6 +- .../Source/app/inputdialog/InputDialog.cpp | 4 +- Tactility/Source/app/launcher/Launcher.cpp | 4 +- Tactility/Source/app/notes/Notes.cpp | 14 +- .../Source/app/screenshot/Screenshot.cpp | 21 +-- .../app/selectiondialog/SelectionDialog.cpp | 12 +- .../app/timedatesettings/TimeDateSettings.cpp | 7 +- Tactility/Source/app/timezone/TimeZone.cpp | 22 +-- .../app/wifiapsettings/WifiApSettings.cpp | 17 +- Tactility/Source/app/wificonnect/View.cpp | 9 +- .../Source/app/wificonnect/WifiConnect.cpp | 8 +- Tactility/Source/app/wifimanage/View.cpp | 24 ++- .../Source/app/wifimanage/WifiManage.cpp | 14 +- Tactility/Source/file/ObjectFileReader.cpp | 26 +-- Tactility/Source/file/ObjectFileWriter.cpp | 36 ++--- Tactility/Source/file/PropertiesFile.cpp | 11 +- Tactility/Source/hal/Device.cpp | 12 +- Tactility/Source/hal/Hal.cpp | 39 ++--- Tactility/Source/hal/gps/GpsDevice.cpp | 39 +++-- Tactility/Source/hal/gps/GpsInit.cpp | 16 +- Tactility/Source/hal/gps/Probe.cpp | 30 ++-- Tactility/Source/hal/gps/Satellites.cpp | 26 +-- Tactility/Source/hal/gps/Ublox.cpp | 77 +++++---- Tactility/Source/hal/i2c/I2c.cpp | 48 +++--- .../Source/hal/sdcard/SdCardMounting.cpp | 8 +- Tactility/Source/hal/sdcard/SdmmcDevice.cpp | 20 +-- .../Source/hal/sdcard/SpiSdCardDevice.cpp | 28 ++-- Tactility/Source/hal/spi/Spi.cpp | 26 +-- Tactility/Source/hal/uart/Uart.cpp | 28 ++-- Tactility/Source/hal/uart/UartEsp.cpp | 26 +-- Tactility/Source/hal/uart/UartPosix.cpp | 30 ++-- Tactility/Source/hal/usb/Usb.cpp | 17 +- Tactility/Source/hal/usb/UsbMock.cpp | 2 - Tactility/Source/hal/usb/UsbTusb.cpp | 25 +-- Tactility/Source/i18n/TextResources.cpp | 18 +-- Tactility/Source/kernel/SystemEvents.cpp | 12 +- Tactility/Source/lvgl/EspLvglPort.cpp | 15 +- Tactility/Source/lvgl/LabelUtils.cpp | 8 +- Tactility/Source/lvgl/Lvgl.cpp | 63 ++++---- Tactility/Source/lvgl/Spinner.cpp | 1 - Tactility/Source/lvgl/Statusbar.cpp | 46 ++++-- Tactility/Source/lvgl/Toolbar.cpp | 3 - Tactility/Source/network/Http.cpp | 18 +-- Tactility/Source/network/HttpServer.cpp | 14 +- Tactility/Source/network/HttpdReq.cpp | 17 +- Tactility/Source/network/Ntp.cpp | 12 +- Tactility/Source/network/Url.cpp | 2 - .../Source/service/ServiceRegistration.cpp | 24 +-- .../development/DevelopmentService.cpp | 37 ++--- .../development/DevelopmentSettings.cpp | 7 +- .../service/displayidle/DisplayIdle.cpp | 4 +- Tactility/Source/service/espnow/EspNow.cpp | 20 +-- .../Source/service/espnow/EspNowService.cpp | 31 ++-- .../Source/service/espnow/EspNowWifi.cpp | 22 +-- .../Source/service/gps/GpsConfiguration.cpp | 23 +-- Tactility/Source/service/gps/GpsService.cpp | 26 +-- Tactility/Source/service/gui/GuiService.cpp | 25 ++- .../service/keyboardidle/KeyboardIdle.cpp | 2 - Tactility/Source/service/loader/Loader.cpp | 43 ++--- .../memorychecker/MemoryCheckerService.cpp | 8 +- .../Source/service/screenshot/Screenshot.cpp | 20 +-- .../service/screenshot/ScreenshotTask.cpp | 39 ++--- Tactility/Source/service/sdcard/Sdcard.cpp | 17 +- .../Source/service/statusbar/Statusbar.cpp | 9 +- .../Source/service/wifi/WifiApSettings.cpp | 11 +- .../service/wifi/WifiBootSplashInit.cpp | 20 +-- Tactility/Source/service/wifi/WifiEsp.cpp | 151 +++++++++--------- Tactility/Source/service/wifi/WifiMock.cpp | 3 - .../Source/service/wifi/WifiSettings.cpp | 8 +- Tactility/Source/settings/BootSettings.cpp | 7 +- Tactility/Source/settings/DisplaySettings.cpp | 1 - Tactility/Source/settings/Language.cpp | 9 +- Tactility/Source/settings/SystemSettings.cpp | 21 +-- Tactility/Source/settings/Time.cpp | 4 +- TactilityC/Source/tt_app.cpp | 14 +- TactilityCore/Include/Tactility/Check.h | 19 +-- TactilityCore/Include/Tactility/Log.h | 10 -- TactilityCore/Include/Tactility/LogEsp.h | 19 --- TactilityCore/Include/Tactility/LogMessages.h | 13 +- .../Include/Tactility/LogSimulator.h | 27 ---- TactilityCore/Include/Tactility/Logger.h | 72 +++++++++ .../Include/Tactility/LoggerAdapter.h | 10 ++ .../Include/Tactility/LoggerAdapterEsp.h | 35 ++++ .../Include/Tactility/LoggerAdapterGeneric.h | 35 ++++ .../Include/Tactility/LoggerAdapterShared.h | 58 +++++++ .../Tactility/{LogCommon.h => LoggerCommon.h} | 0 .../Include/Tactility/LoggerSettings.h | 9 ++ .../Include/Tactility/TactilityCore.h | 5 +- TactilityCore/Source/Check.cpp | 24 +-- TactilityCore/Source/LogSimulator.cpp | 86 ---------- TactilityCore/Source/crypt/Crypt.cpp | 23 +-- TactilityCore/Source/file/File.cpp | 48 +++--- 188 files changed, 1973 insertions(+), 1755 deletions(-) rename Tactility/Source/{TactilityHeadlessEsp.cpp => TactilityEsp.cpp} (71%) delete mode 100644 TactilityCore/Include/Tactility/Log.h delete mode 100644 TactilityCore/Include/Tactility/LogEsp.h delete mode 100644 TactilityCore/Include/Tactility/LogSimulator.h create mode 100644 TactilityCore/Include/Tactility/Logger.h create mode 100644 TactilityCore/Include/Tactility/LoggerAdapter.h create mode 100644 TactilityCore/Include/Tactility/LoggerAdapterEsp.h create mode 100644 TactilityCore/Include/Tactility/LoggerAdapterGeneric.h create mode 100644 TactilityCore/Include/Tactility/LoggerAdapterShared.h rename TactilityCore/Include/Tactility/{LogCommon.h => LoggerCommon.h} (100%) create mode 100644 TactilityCore/Include/Tactility/LoggerSettings.h delete mode 100644 TactilityCore/Source/LogSimulator.cpp diff --git a/Buildscripts/sdkconfig/default.properties b/Buildscripts/sdkconfig/default.properties index 3c36a09e..b51bc5ef 100644 --- a/Buildscripts/sdkconfig/default.properties +++ b/Buildscripts/sdkconfig/default.properties @@ -7,7 +7,6 @@ CONFIG_IDF_EXPERIMENTAL_FEATURES=y # Free up IRAM CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y -CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH=y CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH=y # EmbedTLS CONFIG_MBEDTLS_SSL_PROTO_TLS1_3=y diff --git a/Data/data/settings/system.properties b/Data/data/settings/system.properties index 71b8b719..f8c4da64 100644 --- a/Data/data/settings/system.properties +++ b/Data/data/settings/system.properties @@ -2,4 +2,4 @@ language=en-US timeFormat24h=true dateFormat=MM/DD/YYYY region=US -timezone=America/Los_Angeles \ No newline at end of file +timezone=Europe/Amsterdam \ No newline at end of file diff --git a/Devices/btt-panda-touch/Source/devices/Display.cpp b/Devices/btt-panda-touch/Source/devices/Display.cpp index 94f68a3b..7da8e901 100644 --- a/Devices/btt-panda-touch/Source/devices/Display.cpp +++ b/Devices/btt-panda-touch/Source/devices/Display.cpp @@ -3,7 +3,6 @@ #include #include #include -#include std::shared_ptr _Nullable createTouch() { // Note for future changes: Reset pin is 41 and interrupt pin is 40 diff --git a/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp b/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp index 4ac8fb99..bc337e4e 100644 --- a/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp +++ b/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include @@ -11,7 +11,7 @@ #include #include -constexpr auto TAG = "St7701Display"; +static const auto LOGGER = tt::Logger("St7701Display"); static const st7701_lcd_init_cmd_t st7701_lcd_init_cmds[] = { // {cmd, { data }, data_size, delay_ms} @@ -153,28 +153,30 @@ bool St7701Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_st7701(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, false) != ESP_OK) { - TT_LOG_E(TAG, "Failed to invert color"); + LOGGER.error("Failed to invert color"); + return false; } esp_lcd_panel_set_gap(panelHandle, 0, 0); if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); + return false; } return true; diff --git a/Devices/cyd-8048s043c/Source/devices/Display.cpp b/Devices/cyd-8048s043c/Source/devices/Display.cpp index 6ce9afe4..65a2c522 100644 --- a/Devices/cyd-8048s043c/Source/devices/Display.cpp +++ b/Devices/cyd-8048s043c/Source/devices/Display.cpp @@ -3,7 +3,6 @@ #include #include #include -#include std::shared_ptr _Nullable createTouch() { // Note for future changes: Reset pin is 38 and interrupt pin is 18 diff --git a/Devices/cyd-jc8048w550c/Source/devices/Display.cpp b/Devices/cyd-jc8048w550c/Source/devices/Display.cpp index 6ce9afe4..65a2c522 100644 --- a/Devices/cyd-jc8048w550c/Source/devices/Display.cpp +++ b/Devices/cyd-jc8048w550c/Source/devices/Display.cpp @@ -3,7 +3,6 @@ #include #include #include -#include std::shared_ptr _Nullable createTouch() { // Note for future changes: Reset pin is 38 and interrupt pin is 18 diff --git a/Devices/elecrow-crowpanel-advance-50/Source/devices/Display.cpp b/Devices/elecrow-crowpanel-advance-50/Source/devices/Display.cpp index 57197196..9440b3d9 100644 --- a/Devices/elecrow-crowpanel-advance-50/Source/devices/Display.cpp +++ b/Devices/elecrow-crowpanel-advance-50/Source/devices/Display.cpp @@ -2,7 +2,6 @@ #include #include -#include std::shared_ptr _Nullable createTouch() { // Note for future changes: Reset pin is 38 and interrupt pin is 18 diff --git a/Devices/elecrow-crowpanel-basic-50/Source/devices/Display.cpp b/Devices/elecrow-crowpanel-basic-50/Source/devices/Display.cpp index 94689d66..72771a1a 100644 --- a/Devices/elecrow-crowpanel-basic-50/Source/devices/Display.cpp +++ b/Devices/elecrow-crowpanel-basic-50/Source/devices/Display.cpp @@ -3,7 +3,6 @@ #include #include #include -#include std::shared_ptr _Nullable createTouch() { // Note for future changes: Reset pin is 38 and interrupt pin is 18 diff --git a/Devices/heltec-wifi-lora-32-v3/Source/Configuration.cpp b/Devices/heltec-wifi-lora-32-v3/Source/Configuration.cpp index 0ae50f4c..06792bc0 100644 --- a/Devices/heltec-wifi-lora-32-v3/Source/Configuration.cpp +++ b/Devices/heltec-wifi-lora-32-v3/Source/Configuration.cpp @@ -4,11 +4,11 @@ #include #include +#include #include #include "driver/gpio.h" #include "driver/i2c.h" -#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -24,7 +24,7 @@ static void enableOledPower() { gpio_set_level(DISPLAY_PIN_POWER, 0); // Active low vTaskDelay(pdMS_TO_TICKS(500)); // Add a small delay for power to stabilize - TT_LOG_I("OLED_POWER", "OLED power enabled"); + tt::Logger("HeltecV3").info("OLED power enabled"); } static bool initBoot() { diff --git a/Devices/lilygo-tdeck/Source/Init.cpp b/Devices/lilygo-tdeck/Source/Init.cpp index 8c58d227..8b88c405 100644 --- a/Devices/lilygo-tdeck/Source/Init.cpp +++ b/Devices/lilygo-tdeck/Source/Init.cpp @@ -1,20 +1,21 @@ #include "PwmBacklight.h" -#include "Tactility/kernel/SystemEvents.h" -#include "Tactility/service/gps/GpsService.h" - -#include -#include -#include - #include "devices/KeyboardBacklight.h" #include "devices/TrackballDevice.h" -#include + +#include +#include +#include +#include +#include +#include #include -#define TAG "tdeck" +#include + +static const auto LOGGER = tt::Logger("T-Deck"); // Power on -#define TDECK_POWERON_GPIO GPIO_NUM_10 +constexpr auto TDECK_POWERON_GPIO = GPIO_NUM_10; static bool powerOn() { gpio_config_t device_power_signal_config = { @@ -37,9 +38,9 @@ static bool powerOn() { } bool initBoot() { - ESP_LOGI(TAG, LOG_MESSAGE_POWER_ON_START); + LOGGER.info(LOG_MESSAGE_POWER_ON_START); if (!powerOn()) { - TT_LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED); + LOGGER.error(LOG_MESSAGE_POWER_ON_FAILED); return false; } @@ -47,7 +48,7 @@ bool initBoot() { * when moving the brightness slider rapidly from a lower setting to 100%. * This is not a slider bug (data was debug-traced) */ if (!driver::pwmbacklight::init(GPIO_NUM_42, 30000)) { - TT_LOG_E(TAG, "Backlight init failed"); + LOGGER.error("Backlight init failed"); return false; } @@ -58,9 +59,9 @@ bool initBoot() { gps_service->getGpsConfigurations(gps_configurations); if (gps_configurations.empty()) { if (gps_service->addGpsConfiguration(tt::hal::gps::GpsConfiguration {.uartName = "Grove", .baudRate = 38400, .model = tt::hal::gps::GpsModel::UBLOX10})) { - TT_LOG_I(TAG, "Configured internal GPS"); + LOGGER.info("Configured internal GPS"); } else { - TT_LOG_E(TAG, "Failed to configure internal GPS"); + LOGGER.error("Failed to configure internal GPS"); } } } @@ -69,23 +70,23 @@ bool initBoot() { tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) { auto kbBacklight = tt::hal::findDevice("Keyboard Backlight"); if (kbBacklight != nullptr) { - TT_LOG_I(TAG, "%s starting", kbBacklight->getName().c_str()); + LOGGER.info("{} starting", kbBacklight->getName()); auto kbDevice = std::static_pointer_cast(kbBacklight); if (kbDevice->start()) { - TT_LOG_I(TAG, "%s started", kbBacklight->getName().c_str()); + LOGGER.info("{} started", kbBacklight->getName()); } else { - TT_LOG_E(TAG, "%s start failed", kbBacklight->getName().c_str()); + LOGGER.error("{} start failed", kbBacklight->getName()); } } auto trackball = tt::hal::findDevice("Trackball"); if (trackball != nullptr) { - TT_LOG_I(TAG, "%s starting", trackball->getName().c_str()); + LOGGER.info("{} starting", trackball->getName()); auto tbDevice = std::static_pointer_cast(trackball); if (tbDevice->start()) { - TT_LOG_I(TAG, "%s started", trackball->getName().c_str()); + LOGGER.info("{} started", trackball->getName()); } else { - TT_LOG_E(TAG, "%s start failed", trackball->getName().c_str()); + LOGGER.error("{} start failed", trackball->getName()); } } @@ -99,7 +100,7 @@ bool initBoot() { auto kbSettings = tt::settings::keyboard::loadOrGetDefault(); bool result = keyboardbacklight::setBrightness(kbSettings.backlightEnabled ? kbSettings.backlightBrightness : 0); if (!result) { - TT_LOG_W(TAG, "Failed to set keyboard backlight brightness"); + LOGGER.warn("Failed to set keyboard backlight brightness"); } trackball::setEnabled(kbSettings.trackballEnabled); diff --git a/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp b/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp index 32f5939b..185216cf 100644 --- a/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp +++ b/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp @@ -1,8 +1,11 @@ #include "KeyboardBacklight.h" -#include -#include -static const char* TAG = "KeyboardBacklight"; +#include + +#include +#include + +static const auto LOGGER = tt::Logger("KeyboardBacklight"); namespace keyboardbacklight { @@ -18,16 +21,16 @@ bool init(i2c_port_t i2cPort, uint8_t slaveAddress) { g_i2cPort = i2cPort; g_slaveAddress = slaveAddress; - ESP_LOGI(TAG, "Keyboard backlight initialized on I2C port %d, address 0x%02X", g_i2cPort, g_slaveAddress); + LOGGER.info("Initialized on I2C port {}, address 0x{:02X}", static_cast(g_i2cPort), g_slaveAddress); // Set a reasonable default brightness if (!setDefaultBrightness(127)) { - ESP_LOGE(TAG, "Failed to set default brightness"); + LOGGER.error("Failed to set default brightness"); return false; } if (!setBrightness(127)) { - ESP_LOGE(TAG, "Failed to set brightness"); + LOGGER.error("Failed to set brightness"); return false; } @@ -36,7 +39,7 @@ bool init(i2c_port_t i2cPort, uint8_t slaveAddress) { bool setBrightness(uint8_t brightness) { if (g_i2cPort >= I2C_NUM_MAX) { - ESP_LOGE(TAG, "Keyboard backlight not initialized"); + LOGGER.error("Not initialized"); return false; } @@ -45,7 +48,7 @@ bool setBrightness(uint8_t brightness) { return true; } - ESP_LOGI(TAG, "Setting brightness to %d on I2C port %d, address 0x%02X", brightness, g_i2cPort, g_slaveAddress); + LOGGER.info("Setting brightness to {} on I2C port {}, address 0x{:02X}", brightness, static_cast(g_i2cPort), g_slaveAddress); i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); @@ -59,17 +62,17 @@ bool setBrightness(uint8_t brightness) { if (ret == ESP_OK) { g_currentBrightness = brightness; - ESP_LOGI(TAG, "Successfully set brightness to %d", brightness); + LOGGER.info("Successfully set brightness to {}", brightness); return true; } else { - ESP_LOGE(TAG, "Failed to set brightness: %s (0x%x)", esp_err_to_name(ret), ret); + LOGGER.error("Failed to set brightness: {} (0x{:02X})", esp_err_to_name(ret), ret); return false; } } bool setDefaultBrightness(uint8_t brightness) { if (g_i2cPort >= I2C_NUM_MAX) { - ESP_LOGE(TAG, "Keyboard backlight not initialized"); + LOGGER.error("Not initialized"); return false; } @@ -89,17 +92,17 @@ bool setDefaultBrightness(uint8_t brightness) { i2c_cmd_link_delete(cmd); if (ret == ESP_OK) { - ESP_LOGD(TAG, "Set default brightness to %d", brightness); + LOGGER.debug("Set default brightness to {}", brightness); return true; } else { - ESP_LOGE(TAG, "Failed to set default brightness: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to set default brightness: {}", esp_err_to_name(ret)); return false; } } uint8_t getBrightness() { if (g_i2cPort >= I2C_NUM_MAX) { - ESP_LOGE(TAG, "Keyboard backlight not initialized"); + LOGGER.error("Not initialized"); return 0; } diff --git a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp index 74c87aeb..c59c1916 100644 --- a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp +++ b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp @@ -1,7 +1,8 @@ #include "Trackball.h" -#include -static const char* TAG = "Trackball"; +#include + +static const auto LOGGER = tt::Logger("Trackball"); namespace trackball { @@ -72,7 +73,7 @@ static void read_cb(lv_indev_t* indev, lv_indev_data_t* data) { lv_indev_t* init(const TrackballConfig& config) { if (g_initialized) { - ESP_LOGW(TAG, "Trackball already initialized"); + LOGGER.warn("Already initialized"); return g_indev; } @@ -109,16 +110,19 @@ lv_indev_t* init(const TrackballConfig& config) { lv_indev_set_type(g_indev, LV_INDEV_TYPE_ENCODER); lv_indev_set_read_cb(g_indev, read_cb); - if (g_indev) { + if (g_indev != nullptr) { g_initialized = true; - ESP_LOGI(TAG, "Trackball initialized as encoder (R:%d U:%d L:%d D:%d Click:%d)", - config.pinRight, config.pinUp, config.pinLeft, config.pinDown, - config.pinClick); - return g_indev; + LOGGER.info("Initialized as encoder (R:{} U:{} L:{} D:{} Click:{})", + static_cast(config.pinRight), + static_cast(config.pinUp), + static_cast(config.pinLeft), + static_cast(config.pinDown), + static_cast(config.pinClick)); } else { - ESP_LOGE(TAG, "Failed to register LVGL input device"); - return nullptr; + LOGGER.error("Failed to register LVGL input device"); } + + return g_indev; } void deinit() { @@ -127,19 +131,19 @@ void deinit() { g_indev = nullptr; } g_initialized = false; - ESP_LOGI(TAG, "Trackball deinitialized"); + LOGGER.info("Deinitialized"); } void setMovementStep(uint8_t step) { if (step > 0) { g_config.movementStep = step; - ESP_LOGD(TAG, "Movement step set to %d", step); + LOGGER.debug("Movement step set to {}", step); } } void setEnabled(bool enabled) { g_enabled = enabled; - ESP_LOGI(TAG, "Trackball %s", enabled ? "enabled" : "disabled"); + LOGGER.info("{}", enabled ? "Enabled" : "Disabled"); } } diff --git a/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp b/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp index 31cf0173..5d730e0b 100644 --- a/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp +++ b/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp @@ -6,11 +6,13 @@ #include #include #include +#include #include using tt::hal::findFirstDevice; -constexpr auto* TAG = "TdeckKeyboard"; +static const auto LOGGER = tt::Logger("TdeckKeyboard"); + constexpr auto TDECK_KEYBOARD_I2C_BUS_HANDLE = I2C_NUM_0; constexpr auto TDECK_KEYBOARD_SLAVE_ADDRESS = 0x55; @@ -37,11 +39,15 @@ static void keyboard_read_callback(TT_UNUSED lv_indev_t* indev, lv_indev_data_t* if (keyboard_i2c_read(&read_buffer)) { if (read_buffer == 0 && read_buffer != last_buffer) { - TT_LOG_D(TAG, "Released %d", last_buffer); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Released {}", last_buffer); + } data->key = last_buffer; data->state = LV_INDEV_STATE_RELEASED; } else if (read_buffer != 0) { - TT_LOG_D(TAG, "Pressed %d", read_buffer); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Pressed {}", read_buffer); + } data->key = read_buffer; data->state = LV_INDEV_STATE_PRESSED; // TODO: Avoid performance hit by calling loadOrGetDefault() on each key press diff --git a/Devices/lilygo-tdongle-s3/Source/Init.cpp b/Devices/lilygo-tdongle-s3/Source/Init.cpp index c185e5d5..abb194ac 100644 --- a/Devices/lilygo-tdongle-s3/Source/Init.cpp +++ b/Devices/lilygo-tdongle-s3/Source/Init.cpp @@ -1,13 +1,14 @@ #include "PwmBacklight.h" -#include "Tactility/service/gps/GpsService.h" +#include +#include #include -#define TAG "T-Dongle" +static const auto LOGGER = tt::Logger("T-Dongle S3"); bool initBoot() { if (!driver::pwmbacklight::init(GPIO_NUM_38, 12000)) { - TT_LOG_E(TAG, "Backlight init failed"); + LOGGER.error("Backlight init failed"); return false; } diff --git a/Devices/lilygo-tlora-pager/Source/Init.cpp b/Devices/lilygo-tlora-pager/Source/Init.cpp index cf1c7ce7..3a98576f 100644 --- a/Devices/lilygo-tlora-pager/Source/Init.cpp +++ b/Devices/lilygo-tlora-pager/Source/Init.cpp @@ -1,5 +1,6 @@ #include -#include +#include +#include #include #include #include @@ -8,16 +9,16 @@ #include -constexpr auto* TAG = "TLoraPager"; +static const auto LOGGER = tt::Logger("T-Lora Pager"); bool tpagerInit() { - ESP_LOGI(TAG, LOG_MESSAGE_POWER_ON_START); + LOGGER.info(LOG_MESSAGE_POWER_ON_START); /* 32 Khz and higher gives an issue where the screen starts dimming again above 80% brightness * when moving the brightness slider rapidly from a lower setting to 100%. * This is not a slider bug (data was debug-traced) */ if (!driver::pwmbacklight::init(GPIO_NUM_42, 30000)) { - TT_LOG_E(TAG, "Backlight init failed"); + LOGGER.error("Backlight init failed"); return false; } @@ -44,9 +45,9 @@ bool tpagerInit() { .baudRate = 38400, .model = tt::hal::gps::GpsModel::UBLOX10 })) { - TT_LOG_I(TAG, "Configured internal GPS"); + LOGGER.info("Configured internal GPS"); } else { - TT_LOG_E(TAG, "Failed to configure internal GPS"); + LOGGER.error("Failed to configure internal GPS"); } } } diff --git a/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp b/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp index f14b2f37..764aaa30 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp @@ -1,9 +1,10 @@ #include "TpagerEncoder.h" -#include +#include #include -constexpr auto* TAG = "TpagerEncoder"; +static const auto LOGGER = tt::Logger("TpagerEncoder"); + constexpr auto ENCODER_A = GPIO_NUM_40; constexpr auto ENCODER_B = GPIO_NUM_41; constexpr auto ENCODER_ENTER = GPIO_NUM_7; @@ -39,7 +40,9 @@ void TpagerEncoder::readCallback(lv_indev_t* indev, lv_indev_data_t* data) { } } -void TpagerEncoder::initEncoder() { +bool TpagerEncoder::initEncoder() { + assert(encPcntUnit == nullptr); + constexpr int LOW_LIMIT = -127; constexpr int HIGH_LIMIT = 126; @@ -48,11 +51,15 @@ void TpagerEncoder::initEncoder() { pcnt_unit_config_t unit_config = { .low_limit = LOW_LIMIT, .high_limit = HIGH_LIMIT, - .flags = {.accum_count = 1}, + .intr_priority = 0, + .flags = { + .accum_count = 1 + }, }; if (pcnt_new_unit(&unit_config, &encPcntUnit) != ESP_OK) { - TT_LOG_E(TAG, "Pulsecounter intialization failed"); + LOGGER.error("Pulsecounter initialization failed"); + return false; } pcnt_glitch_filter_config_t filter_config = { @@ -60,17 +67,34 @@ void TpagerEncoder::initEncoder() { }; if (pcnt_unit_set_glitch_filter(encPcntUnit, &filter_config) != ESP_OK) { - TT_LOG_E(TAG, "Pulsecounter glitch filter config failed"); + LOGGER.error("Pulsecounter glitch filter config failed"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } pcnt_chan_config_t chan_1_config = { .edge_gpio_num = ENCODER_B, .level_gpio_num = ENCODER_A, + .flags { + .invert_edge_input = 0, + .invert_level_input = 0, + .virt_edge_io_level = 0, + .virt_level_io_level = 0, + .io_loop_back = 0 + } }; pcnt_chan_config_t chan_2_config = { .edge_gpio_num = ENCODER_A, .level_gpio_num = ENCODER_B, + .flags { + .invert_edge_input = 0, + .invert_level_input = 0, + .virt_edge_io_level = 0, + .virt_level_io_level = 0, + .io_loop_back = 0 + } }; pcnt_channel_handle_t pcnt_chan_1 = nullptr; @@ -78,37 +102,60 @@ void TpagerEncoder::initEncoder() { if ((pcnt_new_channel(encPcntUnit, &chan_1_config, &pcnt_chan_1) != ESP_OK) || (pcnt_new_channel(encPcntUnit, &chan_2_config, &pcnt_chan_2) != ESP_OK)) { - TT_LOG_E(TAG, "Pulsecounter channel config failed"); + LOGGER.error("Pulsecounter channel config failed"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } // Second argument is rising edge, third argument is falling edge if ((pcnt_channel_set_edge_action(pcnt_chan_1, PCNT_CHANNEL_EDGE_ACTION_DECREASE, PCNT_CHANNEL_EDGE_ACTION_INCREASE) != ESP_OK) || (pcnt_channel_set_edge_action(pcnt_chan_2, PCNT_CHANNEL_EDGE_ACTION_INCREASE, PCNT_CHANNEL_EDGE_ACTION_DECREASE) != ESP_OK)) { - TT_LOG_E(TAG, "Pulsecounter edge action config failed"); + LOGGER.error("Pulsecounter edge action config failed"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } // Second argument is low level, third argument is high level if ((pcnt_channel_set_level_action(pcnt_chan_1, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE) != ESP_OK) || (pcnt_channel_set_level_action(pcnt_chan_2, PCNT_CHANNEL_LEVEL_ACTION_KEEP, PCNT_CHANNEL_LEVEL_ACTION_INVERSE) != ESP_OK)) { - TT_LOG_E(TAG, "Pulsecounter level action config failed"); + LOGGER.error("Pulsecounter level action config failed"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } if ((pcnt_unit_add_watch_point(encPcntUnit, LOW_LIMIT) != ESP_OK) || (pcnt_unit_add_watch_point(encPcntUnit, HIGH_LIMIT) != ESP_OK)) { - TT_LOG_E(TAG, "Pulsecounter watch point config failed"); + LOGGER.error("Pulsecounter watch point config failed"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } if (pcnt_unit_enable(encPcntUnit) != ESP_OK) { - TT_LOG_E(TAG, "Pulsecounter could not be enabled"); + LOGGER.error("Pulsecounter could not be enabled"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } if (pcnt_unit_clear_count(encPcntUnit) != ESP_OK) { - TT_LOG_E(TAG, "Pulsecounter could not be cleared"); + LOGGER.error("Pulsecounter could not be cleared"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } if (pcnt_unit_start(encPcntUnit) != ESP_OK) { - TT_LOG_E(TAG, "Pulsecounter could not be started"); + LOGGER.error("Pulsecounter could not be started"); + pcnt_del_unit(encPcntUnit); + encPcntUnit = nullptr; + return false; } + + return true; } int TpagerEncoder::getEncoderPulses() const { @@ -117,9 +164,29 @@ int TpagerEncoder::getEncoderPulses() const { return pulses; } +bool TpagerEncoder::deinitEncoder() { + assert(encPcntUnit != nullptr); + + if (pcnt_unit_stop(encPcntUnit) != ESP_OK) { + LOGGER.warn("Failed to stop encoder"); + } + + if (pcnt_del_unit(encPcntUnit) != ESP_OK) { + LOGGER.warn("Failed to delete encoder"); + encPcntUnit = nullptr; + return false; + } + + LOGGER.info("Deinitialized"); + + return true; +} + bool TpagerEncoder::startLvgl(lv_display_t* display) { - initEncoder(); + if (encPcntUnit == nullptr && !initEncoder()) { + return false; + } gpio_input_enable(ENCODER_ENTER); @@ -137,5 +204,10 @@ bool TpagerEncoder::stopLvgl() { lv_indev_delete(encHandle); encHandle = nullptr; + if (encPcntUnit != nullptr && !deinitEncoder()) { + // We're not returning false as LVGL as effectively deinitialized + LOGGER.warn("Deinitialization failed"); + } + return true; } diff --git a/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.h b/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.h index 3081af03..026d1cb9 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.h +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.h @@ -8,7 +8,8 @@ class TpagerEncoder final : public tt::hal::encoder::EncoderDevice { lv_indev_t* _Nullable encHandle = nullptr; pcnt_unit_handle_t encPcntUnit = nullptr; - void initEncoder(); + bool initEncoder(); + bool deinitEncoder(); static void readCallback(lv_indev_t* indev, lv_indev_data_t* data); diff --git a/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp b/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp index 366ac44f..ac51b44b 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp @@ -1,12 +1,12 @@ #include "TpagerKeyboard.h" #include -#include +#include #include #include -constexpr auto* TAG = "TpagerKeyboard"; +static const auto LOGGER = tt::Logger("TpagerKeyboard"); constexpr auto BACKLIGHT = GPIO_NUM_46; @@ -174,7 +174,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti }; if (ledc_timer_config(&ledc_timer) != ESP_OK) { - TT_LOG_E(TAG, "Backlight timer config failed"); + LOGGER.error("Backlight timer config failed"); return false; } @@ -193,7 +193,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti }; if (ledc_channel_config(&ledc_channel) != ESP_OK) { - TT_LOG_E(TAG, "Backlight channel config failed"); + LOGGER.error("Backlight channel config failed"); } return true; @@ -201,7 +201,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti bool TpagerKeyboard::setBacklightDuty(uint8_t duty) { if (!backlightOkay) { - TT_LOG_E(TAG, "Backlight not ready"); + LOGGER.error("Backlight not ready"); return false; } return (ledc_set_duty(LEDC_LOW_SPEED_MODE, backlightChannel, duty) == ESP_OK) && diff --git a/Devices/lilygo-tlora-pager/Source/devices/TpagerPower.cpp b/Devices/lilygo-tlora-pager/Source/devices/TpagerPower.cpp index 98dfa04e..35d291ad 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerPower.cpp +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerPower.cpp @@ -1,9 +1,9 @@ #include "TpagerPower.h" #include -#include +#include -constexpr auto* TAG = "TpagerPower"; +static const auto LOGGER = tt::Logger("TpagerPower"); constexpr auto TPAGER_GAUGE_I2C_BUS_HANDLE = I2C_NUM_0; @@ -68,7 +68,7 @@ void TpagerPower::powerOff() { }); if (device == nullptr) { - TT_LOG_E(TAG, "BQ25896 not found"); + LOGGER.error("BQ25896 not found"); return; } diff --git a/Devices/m5stack-cardputer-adv/Source/devices/CardputerPower.cpp b/Devices/m5stack-cardputer-adv/Source/devices/CardputerPower.cpp index ebd3b65d..a607f010 100644 --- a/Devices/m5stack-cardputer-adv/Source/devices/CardputerPower.cpp +++ b/Devices/m5stack-cardputer-adv/Source/devices/CardputerPower.cpp @@ -1,24 +1,24 @@ #include "CardputerPower.h" -#include +#include #include -constexpr auto* TAG = "CardputerPower"; +static const auto LOGGER = tt::Logger("CardputerPower"); bool CardputerPower::adcInitCalibration() { bool calibrated = false; esp_err_t efuse_read_result = esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_TP_FIT); if (efuse_read_result == ESP_ERR_NOT_SUPPORTED) { - TT_LOG_W(TAG, "Calibration scheme not supported, skip software calibration"); + LOGGER.warn("Calibration scheme not supported, skip software calibration"); } else if (efuse_read_result == ESP_ERR_INVALID_VERSION) { - TT_LOG_W(TAG, "eFuse not burnt, skip software calibration"); + LOGGER.warn("eFuse not burnt, skip software calibration"); } else if (efuse_read_result == ESP_OK) { calibrated = true; - TT_LOG_I(TAG, "Calibration success"); + LOGGER.info("Calibration success"); esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, static_cast(ADC_WIDTH_BIT_DEFAULT), 0, &adcCharacteristics); } else { - TT_LOG_W(TAG, "eFuse read failed, skipping calibration"); + LOGGER.warn("eFuse read failed, skipping calibration"); } return calibrated; @@ -26,11 +26,11 @@ bool CardputerPower::adcInitCalibration() { uint32_t CardputerPower::adcReadValue() const { int adc_raw = adc1_get_raw(ADC1_CHANNEL_9); - TT_LOG_D(TAG, "Raw data: %d", adc_raw); + LOGGER.debug("Raw data: {}", adc_raw); float voltage; if (calibrated) { voltage = esp_adc_cal_raw_to_voltage(adc_raw, &adcCharacteristics); - TT_LOG_D(TAG, "Calibrated data: %d mV", voltage); + LOGGER.debug("Calibrated data: {} mV", voltage); } else { voltage = 0.0f; } @@ -42,11 +42,11 @@ bool CardputerPower::ensureInitialized() { calibrated = adcInitCalibration(); if (adc1_config_width(static_cast(ADC_WIDTH_BIT_DEFAULT)) != ESP_OK) { - TT_LOG_E(TAG, "ADC1 config width failed"); + LOGGER.error("ADC1 config width failed"); return false; } if (adc1_config_channel_atten(ADC1_CHANNEL_9, ADC_ATTEN_DB_11) != ESP_OK) { - TT_LOG_E(TAG, "ADC1 config attenuation failed"); + LOGGER.error("ADC1 config attenuation failed"); return false; } diff --git a/Devices/m5stack-cardputer/Source/devices/CardputerKeyboard.cpp b/Devices/m5stack-cardputer/Source/devices/CardputerKeyboard.cpp index 1e2a0a32..c0466db1 100644 --- a/Devices/m5stack-cardputer/Source/devices/CardputerKeyboard.cpp +++ b/Devices/m5stack-cardputer/Source/devices/CardputerKeyboard.cpp @@ -1,8 +1,8 @@ #include "CardputerKeyboard.h" -#include +#include -constexpr auto* TAG = "Keyboard"; +static const auto LOGGER = tt::Logger("Keyboard"); bool CardputerKeyboard::startLvgl(lv_display_t* display) { keyboard.init(); @@ -56,7 +56,7 @@ void CardputerKeyboard::readCallback(lv_indev_t* indev, lv_indev_data_t* data) { } } else { if (self->keyboard.keysState().del) { - TT_LOG_I(TAG, "del"); + LOGGER.info("del"); data->key = LV_KEY_DEL; data->state = LV_INDEV_STATE_PRESSED; } else { diff --git a/Devices/m5stack-cardputer/Source/devices/CardputerPower.cpp b/Devices/m5stack-cardputer/Source/devices/CardputerPower.cpp index ebd3b65d..a607f010 100644 --- a/Devices/m5stack-cardputer/Source/devices/CardputerPower.cpp +++ b/Devices/m5stack-cardputer/Source/devices/CardputerPower.cpp @@ -1,24 +1,24 @@ #include "CardputerPower.h" -#include +#include #include -constexpr auto* TAG = "CardputerPower"; +static const auto LOGGER = tt::Logger("CardputerPower"); bool CardputerPower::adcInitCalibration() { bool calibrated = false; esp_err_t efuse_read_result = esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_TP_FIT); if (efuse_read_result == ESP_ERR_NOT_SUPPORTED) { - TT_LOG_W(TAG, "Calibration scheme not supported, skip software calibration"); + LOGGER.warn("Calibration scheme not supported, skip software calibration"); } else if (efuse_read_result == ESP_ERR_INVALID_VERSION) { - TT_LOG_W(TAG, "eFuse not burnt, skip software calibration"); + LOGGER.warn("eFuse not burnt, skip software calibration"); } else if (efuse_read_result == ESP_OK) { calibrated = true; - TT_LOG_I(TAG, "Calibration success"); + LOGGER.info("Calibration success"); esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, static_cast(ADC_WIDTH_BIT_DEFAULT), 0, &adcCharacteristics); } else { - TT_LOG_W(TAG, "eFuse read failed, skipping calibration"); + LOGGER.warn("eFuse read failed, skipping calibration"); } return calibrated; @@ -26,11 +26,11 @@ bool CardputerPower::adcInitCalibration() { uint32_t CardputerPower::adcReadValue() const { int adc_raw = adc1_get_raw(ADC1_CHANNEL_9); - TT_LOG_D(TAG, "Raw data: %d", adc_raw); + LOGGER.debug("Raw data: {}", adc_raw); float voltage; if (calibrated) { voltage = esp_adc_cal_raw_to_voltage(adc_raw, &adcCharacteristics); - TT_LOG_D(TAG, "Calibrated data: %d mV", voltage); + LOGGER.debug("Calibrated data: {} mV", voltage); } else { voltage = 0.0f; } @@ -42,11 +42,11 @@ bool CardputerPower::ensureInitialized() { calibrated = adcInitCalibration(); if (adc1_config_width(static_cast(ADC_WIDTH_BIT_DEFAULT)) != ESP_OK) { - TT_LOG_E(TAG, "ADC1 config width failed"); + LOGGER.error("ADC1 config width failed"); return false; } if (adc1_config_channel_atten(ADC1_CHANNEL_9, ADC_ATTEN_DB_11) != ESP_OK) { - TT_LOG_E(TAG, "ADC1 config attenuation failed"); + LOGGER.error("ADC1 config attenuation failed"); return false; } diff --git a/Devices/m5stack-cores3/Source/InitBoot.cpp b/Devices/m5stack-cores3/Source/InitBoot.cpp index 956ab56f..f188ccd9 100644 --- a/Devices/m5stack-cores3/Source/InitBoot.cpp +++ b/Devices/m5stack-cores3/Source/InitBoot.cpp @@ -1,9 +1,9 @@ #include "InitBoot.h" -#include +#include #include -constexpr auto* TAG = "CoreS3"; +static const auto LOGGER = tt::Logger("CoreS3"); std::shared_ptr axp2101; std::shared_ptr aw9523; @@ -13,7 +13,7 @@ std::shared_ptr aw9523; * and schematic: https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/docs/datasheet/core/K128%20CoreS3/Sch_M5_CoreS3_v1.0.pdf */ bool initGpioExpander() { - TT_LOG_I(TAG, "AW9523 init"); + LOGGER.info("AW9523 init"); /** * P0 pins: @@ -58,33 +58,33 @@ bool initGpioExpander() { /* AW9523 P0 is in push-pull mode */ if (!aw9523->writeCTL(0x10)) { - TT_LOG_E(TAG, "AW9523: Failed to set CTL"); + LOGGER.error("AW9523: Failed to set CTL"); return false; } if (!aw9523->writeP0(p0_state)) { - TT_LOG_E(TAG, "AW9523: Failed to set P0"); + LOGGER.error("AW9523: Failed to set P0"); return false; } if (!aw9523->writeP1(p1_state)) { - TT_LOG_E(TAG, "AW9523: Failed to set P1"); + LOGGER.error("AW9523: Failed to set P1"); return false; } if (axp2101->isVBus()) { float voltage = 0.0f; axp2101->getVBusVoltage(voltage); - TT_LOG_I(TAG, "AXP2101: VBus at %.2f", voltage); + LOGGER.info("AXP2101: VBus at {:.2f}", voltage); } else { - TT_LOG_W(TAG, "AXP2101: VBus disabled"); + LOGGER.warn("AXP2101: VBus disabled"); } return true; } bool initPowerControl() { - TT_LOG_I(TAG, "Init power control (AXP2101)"); + LOGGER.info("Init power control (AXP2101)"); // Source: https://github.com/m5stack/M5Unified/blob/b8cfec7fed046242da7f7b8024a4e92004a51ff7/src/utility/Power_Class.cpp#L61 aw9523->bitOnP1(0b10000000); // SY7088 boost enable @@ -135,16 +135,16 @@ bool initPowerControl() { }; if (axp2101->setRegisters((uint8_t*)reg_data_array, sizeof(reg_data_array))) { - TT_LOG_I(TAG, "AXP2101 initialized with %d registers", sizeof(reg_data_array) / 2); + LOGGER.info("AXP2101 initialized with {} registers", sizeof(reg_data_array) / 2); return true; } else { - TT_LOG_E(TAG, "AXP2101: Failed to set registers"); + LOGGER.error("AXP2101: Failed to set registers"); return false; } } bool initBoot() { - TT_LOG_I(TAG, "initBoot()"); + LOGGER.info("initBoot()"); axp2101 = std::make_shared(I2C_NUM_0); aw9523 = std::make_shared(I2C_NUM_0); diff --git a/Devices/m5stack-cores3/Source/devices/Display.cpp b/Devices/m5stack-cores3/Source/devices/Display.cpp index b7350d11..b7e71677 100644 --- a/Devices/m5stack-cores3/Source/devices/Display.cpp +++ b/Devices/m5stack-cores3/Source/devices/Display.cpp @@ -3,16 +3,16 @@ #include #include #include -#include +#include #include -constexpr auto* TAG = "CoreS3Display"; +static const auto LOGGER = tt::Logger("CoreS3Display"); static void setBacklightDuty(uint8_t backlightDuty) { const uint8_t voltage = 20 + ((8 * backlightDuty) / 255); // [0b00000, 0b11100] - under 20 is too dark // TODO: Refactor to use Axp2102 driver subproject. Reference: https://github.com/m5stack/M5Unified/blob/b8cfec7fed046242da7f7b8024a4e92004a51ff7/src/utility/AXP2101_Class.cpp#L42 if (!tt::hal::i2c::masterWriteRegister(I2C_NUM_0, AXP2101_ADDRESS, 0x99, &voltage, 1, 1000)) { // Sets DLD01 - TT_LOG_E(TAG, "Failed to set display backlight voltage"); + LOGGER.error("Failed to set display backlight voltage"); } } diff --git a/Devices/m5stack-stickc-plus/Source/devices/Display.cpp b/Devices/m5stack-stickc-plus/Source/devices/Display.cpp index c05719ff..f6fba81a 100644 --- a/Devices/m5stack-stickc-plus/Source/devices/Display.cpp +++ b/Devices/m5stack-stickc-plus/Source/devices/Display.cpp @@ -1,18 +1,19 @@ #include "Display.h" - #include "Power.h" +#include + #include #include -constexpr auto* TAG = "StickCPlus"; +static const auto LOGGER = tt::Logger("StickCPlus"); static void setBacklightOn(bool on) { const auto axp = getAxp192(); const auto* driver = axp->getAxp192(); uint8_t state; if (axp192_read(driver, AXP192_DCDC13_LDO23_CONTROL, &state) != AXP192_OK) { - TT_LOG_I(TAG, "Failed to read LCD brightness state"); + LOGGER.info("Failed to read LCD brightness state"); return; } std::bitset<8> new_state = state; diff --git a/Devices/simulator/Source/LvglTask.cpp b/Devices/simulator/Source/LvglTask.cpp index 8946df34..b0631dc6 100644 --- a/Devices/simulator/Source/LvglTask.cpp +++ b/Devices/simulator/Source/LvglTask.cpp @@ -1,14 +1,14 @@ #include "LvglTask.h" +#include #include -#include +#include #include #include -#include #include -constexpr auto TAG = "lvgl_task"; +static const auto LOGGER = tt::Logger("LvglTask"); // Mutex for LVGL drawing static tt::RecursiveMutex lvgl_mutex; @@ -58,7 +58,7 @@ void lvgl_task_interrupt() { } void lvgl_task_start() { - TT_LOG_I(TAG, "lvgl task starting"); + LOGGER.info("LVGL task starting"); tt::lvgl::syncSet(&lvgl_lock, &lvgl_unlock); @@ -76,7 +76,7 @@ void lvgl_task_start() { } static void lvgl_task(TT_UNUSED void* arg) { - TT_LOG_I(TAG, "lvgl task started"); + LOGGER.info("LVGL task started"); /** Ideally. the display handle would be created during Simulator.start(), * but somehow that doesn't work. Waiting here from a ThreadFlag when that happens diff --git a/Devices/simulator/Source/Main.cpp b/Devices/simulator/Source/Main.cpp index bebf8326..2aa69536 100644 --- a/Devices/simulator/Source/Main.cpp +++ b/Devices/simulator/Source/Main.cpp @@ -5,7 +5,7 @@ #include "FreeRTOS.h" #include "task.h" -#define TAG "freertos" +static const auto LOGGER = tt::Logger("FreeRTOS"); namespace simulator { @@ -16,10 +16,10 @@ void setMain(MainFunction newMainFunction) { } static void freertosMainTask(TT_UNUSED void* parameter) { - TT_LOG_I(TAG, "starting app_main()"); + LOGGER.info("starting app_main()"); assert(simulator::mainFunction); mainFunction(); - TT_LOG_I(TAG, "returned from app_main()"); + LOGGER.info("returned from app_main()"); vTaskDelete(nullptr); } @@ -46,10 +46,8 @@ void freertosMain() { * It allows you to set breakpoints and debug asserts. */ void vAssertCalled(unsigned long line, const char* const file) { - static portBASE_TYPE xPrinted = pdFALSE; volatile uint32_t set_to_nonzero_in_debugger_to_continue = 0; - - TT_LOG_E(TAG, "assert triggered at %s:%d", file, line); + LOGGER.error("Assert triggered at {}:{}", file, line); taskENTER_CRITICAL(); { // Step out by attaching a debugger and setting set_to_nonzero_in_debugger_to_continue diff --git a/Devices/unphone/Source/InitBoot.cpp b/Devices/unphone/Source/InitBoot.cpp index 3f60a4e6..ddcfe6d6 100644 --- a/Devices/unphone/Source/InitBoot.cpp +++ b/Devices/unphone/Source/InitBoot.cpp @@ -1,9 +1,11 @@ #include "UnPhoneFeatures.h" +#include +#include #include #include #include -constexpr auto* TAG = "unPhone"; +static const auto LOGGER = tt::Logger("unPhone"); std::shared_ptr unPhoneFeatures; static std::unique_ptr powerThread; @@ -46,10 +48,10 @@ public: } void printInfo() { - TT_LOG_I("TAG", "Device stats:"); - TT_LOG_I("TAG", " boot: %ld", getValue(bootCountKey)); - TT_LOG_I("TAG", " power off: %ld", getValue(powerOffCountKey)); - TT_LOG_I("TAG", " power sleep: %ld", getValue(powerSleepKey)); + LOGGER.info("Device stats:"); + LOGGER.info(" boot: {}", getValue(bootCountKey)); + LOGGER.info(" power off: {}", getValue(powerOffCountKey)); + LOGGER.info(" power sleep: {}", getValue(powerSleepKey)); } }; @@ -89,11 +91,11 @@ static void updatePowerSwitch() { if (!unPhoneFeatures->isPowerSwitchOn()) { if (last_state != PowerState::Off) { last_state = PowerState::Off; - TT_LOG_W(TAG, "Power off"); + LOGGER.warn("Power off"); } if (!unPhoneFeatures->isUsbPowerConnected()) { // and usb unplugged we go into shipping mode - TT_LOG_W(TAG, "Shipping mode until USB connects"); + LOGGER.warn("Shipping mode until USB connects"); #if DEBUG_POWER_STATES unPhoneFeatures.setExpanderPower(true); @@ -107,7 +109,7 @@ static void updatePowerSwitch() { unPhoneFeatures->setShipping(true); // tell BM to stop supplying power until USB connects } else { // When power switch is off, but USB is plugged in, we wait (deep sleep) until USB is unplugged. - TT_LOG_W(TAG, "Waiting for USB disconnect to power off"); + LOGGER.warn("Waiting for USB disconnect to power off"); #if DEBUG_POWER_STATES powerInfoBuzz(2); @@ -126,7 +128,7 @@ static void updatePowerSwitch() { } else { if (last_state != PowerState::On) { last_state = PowerState::On; - TT_LOG_W(TAG, "Power on"); + LOGGER.warn("Power on"); #if DEBUG_POWER_STATES powerInfoBuzz(1); @@ -163,7 +165,7 @@ static bool unPhonePowerOn() { unPhoneFeatures = std::make_shared(bq24295); if (!unPhoneFeatures->init()) { - TT_LOG_E(TAG, "UnPhoneFeatures init failed"); + LOGGER.error("UnPhoneFeatures init failed"); return false; } @@ -183,10 +185,10 @@ static bool unPhonePowerOn() { } bool initBoot() { - ESP_LOGI(TAG, LOG_MESSAGE_POWER_ON_START); + LOGGER.info(LOG_MESSAGE_POWER_ON_START); if (!unPhonePowerOn()) { - TT_LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED); + LOGGER.error(LOG_MESSAGE_POWER_ON_FAILED); return false; } diff --git a/Devices/unphone/Source/UnPhoneFeatures.cpp b/Devices/unphone/Source/UnPhoneFeatures.cpp index 186d58e2..bb579efc 100644 --- a/Devices/unphone/Source/UnPhoneFeatures.cpp +++ b/Devices/unphone/Source/UnPhoneFeatures.cpp @@ -1,6 +1,6 @@ #include "UnPhoneFeatures.h" -#include +#include #include #include @@ -9,6 +9,8 @@ #include #include +static const auto LOGGER = tt::Logger("unPhoneFeatures"); + namespace pin { static const gpio_num_t BUTTON1 = GPIO_NUM_45; // left button static const gpio_num_t BUTTON2 = GPIO_NUM_0; // middle button @@ -27,8 +29,6 @@ namespace expanderpin { static const esp_io_expander_pin_num_t VIBE = IO_EXPANDER_PIN_NUM_7; } // namespace expanderpin -#define TAG "unhpone_features" - // TODO: Make part of a new type of UnPhoneFeatures data struct that holds all the thread-related data QueueHandle_t interruptQueue; @@ -42,7 +42,7 @@ static int32_t buttonHandlingThreadMain(const bool* interrupted) { while (!*interrupted) { if (xQueueReceive(interruptQueue, &pinNumber, portMAX_DELAY)) { // The buttons might generate more than 1 click because of how they are built - TT_LOG_I(TAG, "Pressed button %d", pinNumber); + LOGGER.info("Pressed button {}", pinNumber); if (pinNumber == pin::BUTTON1) { tt::app::stop(); } @@ -75,7 +75,7 @@ bool UnPhoneFeatures::initPowerSwitch() { }; if (gpio_config(&config) != ESP_OK) { - TT_LOG_E(TAG, "Power pin init failed"); + LOGGER.error("Power pin init failed"); return false; } @@ -83,14 +83,14 @@ bool UnPhoneFeatures::initPowerSwitch() { rtc_gpio_pulldown_en(pin::POWER_SWITCH) == ESP_OK) { return true; } else { - TT_LOG_E(TAG, "Failed to set RTC for power switch"); + LOGGER.error("Failed to set RTC for power switch"); return false; } } bool UnPhoneFeatures::initNavButtons() { if (!initGpioExpander()) { - TT_LOG_E(TAG, "GPIO expander init failed"); + LOGGER.error("GPIO expander init failed"); return false; } @@ -125,17 +125,17 @@ bool UnPhoneFeatures::initNavButtons() { }; if (gpio_config(&config) != ESP_OK) { - TT_LOG_E(TAG, "Nav button pin init failed"); + LOGGER.error("Nav button pin init failed"); return false; } if ( gpio_install_isr_service(0) != ESP_OK || - gpio_isr_handler_add(pin::BUTTON1, navButtonInterruptHandler, (void*)pin::BUTTON1) != ESP_OK || - gpio_isr_handler_add(pin::BUTTON2, navButtonInterruptHandler, (void*)pin::BUTTON2) != ESP_OK || - gpio_isr_handler_add(pin::BUTTON3, navButtonInterruptHandler, (void*)pin::BUTTON3) != ESP_OK + gpio_isr_handler_add(pin::BUTTON1, navButtonInterruptHandler, reinterpret_cast(pin::BUTTON1)) != ESP_OK || + gpio_isr_handler_add(pin::BUTTON2, navButtonInterruptHandler, reinterpret_cast(pin::BUTTON2)) != ESP_OK || + gpio_isr_handler_add(pin::BUTTON3, navButtonInterruptHandler, reinterpret_cast(pin::BUTTON3)) != ESP_OK ) { - TT_LOG_E(TAG, "Nav buttons ISR init failed"); + LOGGER.error("Nav buttons ISR init failed"); return false; } @@ -156,7 +156,7 @@ bool UnPhoneFeatures::initOutputPins() { }; if (gpio_config(&config) != ESP_OK) { - TT_LOG_E(TAG, "Output pin init failed"); + LOGGER.error("Output pin init failed"); return false; } @@ -167,7 +167,7 @@ bool UnPhoneFeatures::initGpioExpander() { // ESP_IO_EXPANDER_I2C_TCA9555_ADDRESS_110 corresponds with 0x26 from the docs at // https://gitlab.com/hamishcunningham/unphonelibrary/-/blob/main/unPhone.h?ref_type=heads#L206 if (esp_io_expander_new_i2c_tca95xx_16bit(I2C_NUM_0, ESP_IO_EXPANDER_I2C_TCA9555_ADDRESS_110, &ioExpander) != ESP_OK) { - TT_LOG_E(TAG, "IO expander init failed"); + LOGGER.error("IO expander init failed"); return false; } assert(ioExpander != nullptr); @@ -201,25 +201,25 @@ bool UnPhoneFeatures::initGpioExpander() { } bool UnPhoneFeatures::init() { - TT_LOG_I(TAG, "init"); + LOGGER.info("init"); if (!initGpioExpander()) { - TT_LOG_E(TAG, "GPIO expander init failed"); + LOGGER.error("GPIO expander init failed"); return false; } if (!initNavButtons()) { - TT_LOG_E(TAG, "Input pin init failed"); + LOGGER.error("Input pin init failed"); return false; } if (!initOutputPins()) { - TT_LOG_E(TAG, "Output pin init failed"); + LOGGER.error("Output pin init failed"); return false; } if (!initPowerSwitch()) { - TT_LOG_E(TAG, "Power button init failed"); + LOGGER.error("Power button init failed"); return false; } @@ -231,7 +231,7 @@ void UnPhoneFeatures::printInfo() const { batteryManagement->printInfo(); bool backlight_power; const char* backlight_power_state = getBacklightPower(backlight_power) && backlight_power ? "on" : "off"; - TT_LOG_I(TAG, "Backlight: %s", backlight_power_state); + LOGGER.info("Backlight: {}", backlight_power_state); } bool UnPhoneFeatures::setRgbLed(bool red, bool green, bool blue) const { @@ -286,11 +286,11 @@ void UnPhoneFeatures::turnPeripheralsOff() const { bool UnPhoneFeatures::setShipping(bool on) const { if (on) { - TT_LOG_W(TAG, "setShipping: on"); + LOGGER.warn("setShipping: on"); batteryManagement->setWatchDogTimer(Bq24295::WatchDogTimer::Disabled); batteryManagement->setBatFetOn(false); } else { - TT_LOG_W(TAG, "setShipping: off"); + LOGGER.warn("setShipping: off"); batteryManagement->setWatchDogTimer(Bq24295::WatchDogTimer::Enabled40s); batteryManagement->setBatFetOn(true); } diff --git a/Devices/unphone/Source/devices/Hx8357Display.cpp b/Devices/unphone/Source/devices/Hx8357Display.cpp index 323f37ae..3bd0f0ff 100644 --- a/Devices/unphone/Source/devices/Hx8357Display.cpp +++ b/Devices/unphone/Source/devices/Hx8357Display.cpp @@ -2,18 +2,19 @@ #include "Touch.h" #include -#include +#include #include #include -constexpr auto TAG = "Hx8357Display"; +static const auto LOGGER = tt::Logger("Hx8357Display"); + constexpr auto BUFFER_SIZE = (UNPHONE_LCD_HORIZONTAL_RESOLUTION * UNPHONE_LCD_DRAW_BUFFER_HEIGHT * LV_COLOR_DEPTH / 8); extern std::shared_ptr unPhoneFeatures; bool Hx8357Display::start() { - TT_LOG_I(TAG, "start"); + LOGGER.info("start"); disp_spi_add_device(SPI2_HOST); @@ -26,16 +27,16 @@ bool Hx8357Display::start() { } bool Hx8357Display::stop() { - TT_LOG_I(TAG, "stop"); + LOGGER.info("stop"); disp_spi_remove_device(); return true; } bool Hx8357Display::startLvgl() { - TT_LOG_I(TAG, "startLvgl"); + LOGGER.info("startLvgl"); if (lvglDisplay != nullptr) { - TT_LOG_W(TAG, "LVGL was already started"); + LOGGER.warn("LVGL was already started"); return false; } @@ -58,7 +59,7 @@ bool Hx8357Display::startLvgl() { lv_display_set_flush_cb(lvglDisplay, hx8357_flush); if (lvglDisplay == nullptr) { - TT_LOG_I(TAG, "Failed"); + LOGGER.info("Failed"); return false; } @@ -73,10 +74,10 @@ bool Hx8357Display::startLvgl() { } bool Hx8357Display::stopLvgl() { - TT_LOG_I(TAG, "stopLvgl"); + LOGGER.info("stopLvgl"); if (lvglDisplay == nullptr) { - TT_LOG_W(TAG, "LVGL was already stopped"); + LOGGER.warn("LVGL was already stopped"); return false; } @@ -85,7 +86,7 @@ bool Hx8357Display::stopLvgl() { auto touch_device = getTouchDevice(); if (touch_device != nullptr && touch_device->getLvglIndev() != nullptr) { - TT_LOG_I(TAG, "Stopping touch device"); + LOGGER.info("Stopping touch device"); touch_device->stopLvgl(); } @@ -101,7 +102,7 @@ bool Hx8357Display::stopLvgl() { std::shared_ptr _Nullable Hx8357Display::getTouchDevice() { if (touchDevice == nullptr) { touchDevice = std::reinterpret_pointer_cast(createTouch()); - TT_LOG_I(TAG, "Created touch device"); + LOGGER.info("Created touch device"); } return touchDevice; diff --git a/Devices/unphone/Source/devices/Touch.cpp b/Devices/unphone/Source/devices/Touch.cpp index 6e189068..8c9a19b4 100644 --- a/Devices/unphone/Source/devices/Touch.cpp +++ b/Devices/unphone/Source/devices/Touch.cpp @@ -1,7 +1,5 @@ #include "Touch.h" -#include - std::shared_ptr createTouch() { auto configuration = std::make_unique( SPI2_HOST, diff --git a/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp b/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp index 99080dab..d12fe4e7 100644 --- a/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp +++ b/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp @@ -1,3 +1,4 @@ +#include #include #include diff --git a/Devices/waveshare-s3-touch-lcd-147/Source/devices/Jd9853Display.cpp b/Devices/waveshare-s3-touch-lcd-147/Source/devices/Jd9853Display.cpp index 1f7b1299..c7466ba8 100644 --- a/Devices/waveshare-s3-touch-lcd-147/Source/devices/Jd9853Display.cpp +++ b/Devices/waveshare-s3-touch-lcd-147/Source/devices/Jd9853Display.cpp @@ -1,12 +1,12 @@ #include "Jd9853Display.h" -#include +#include #include #include #include -constexpr const char* TAG = "JD9853"; +static const auto LOGGER = tt::Logger("JD9853"); bool Jd9853Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { const esp_lcd_panel_io_spi_config_t panel_io_config = { @@ -54,42 +54,42 @@ bool Jd9853Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_jd9853(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY"); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } if (esp_lcd_panel_set_gap(panelHandle, 34, 0) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel gap"); + LOGGER.error("Failed to set panel gap"); return false; } @@ -157,6 +157,6 @@ void Jd9853Display::setGammaCurve(uint8_t index) { }; if (esp_lcd_panel_io_tx_param(getIoHandle() , LCD_CMD_GAMSET, param, 1) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set gamma"); + LOGGER.error("Failed to set gamma"); } } diff --git a/Drivers/AXP2101/Source/Axp2101.cpp b/Drivers/AXP2101/Source/Axp2101.cpp index f4e15c49..e43cf7b5 100644 --- a/Drivers/AXP2101/Source/Axp2101.cpp +++ b/Drivers/AXP2101/Source/Axp2101.cpp @@ -1,5 +1,4 @@ #include "Axp2101.h" -#include bool Axp2101::getBatteryVoltage(float& vbatMillis) const { return readRegister14(0x34, vbatMillis); diff --git a/Drivers/BQ24295/Source/Bq24295.cpp b/Drivers/BQ24295/Source/Bq24295.cpp index 4dfae7bf..07f3346f 100644 --- a/Drivers/BQ24295/Source/Bq24295.cpp +++ b/Drivers/BQ24295/Source/Bq24295.cpp @@ -1,7 +1,7 @@ #include "Bq24295.h" -#include +#include -#define TAG "bq24295" +static const auto LOGGER = tt::Logger("BQ24295"); /** Reference: * https://www.ti.com/lit/ds/symlink/bq24295.pdf @@ -49,8 +49,8 @@ bool Bq24295::setWatchDogTimer(WatchDogTimer in) const { if (readChargeTermination(value)) { uint8_t bits_to_set = 0b00110000 & static_cast(in); uint8_t value_cleared = value & 0b11001111; - uint8_t to_set = bits_to_set & value_cleared; - TT_LOG_I(TAG, "WatchDogTimer: %02x -> %02x", value, to_set); + uint8_t to_set = bits_to_set | value_cleared; + LOGGER.info("WatchDogTimer: {:02x} -> {:02x}", value, to_set); return writeRegister8(registers::CHARGE_TERMINATION, to_set); } @@ -96,9 +96,9 @@ bool Bq24295::getVersion(uint8_t& value) const { void Bq24295::printInfo() const { uint8_t version, status, charge_termination; if (getStatus(status) && getVersion(version) && readChargeTermination(charge_termination)) { - TT_LOG_I(TAG, "Version %d, status %02x, charge termination %02x", version, status, charge_termination); + LOGGER.info("Version {}, status {:02x}, charge termination {:02x}", version, status, charge_termination); } else { - TT_LOG_E(TAG, "Failed to retrieve version and/or status"); + LOGGER.error("Failed to retrieve version and/or status"); } } diff --git a/Drivers/BQ24295/Source/Bq24295.h b/Drivers/BQ24295/Source/Bq24295.h index 0ed4ce7f..fa016fed 100644 --- a/Drivers/BQ24295/Source/Bq24295.h +++ b/Drivers/BQ24295/Source/Bq24295.h @@ -6,7 +6,6 @@ class Bq24295 final : public tt::hal::i2c::I2cDevice { -private: bool readChargeTermination(uint8_t& out) const; diff --git a/Drivers/BQ25896/Source/Bq25896.cpp b/Drivers/BQ25896/Source/Bq25896.cpp index 0b305495..e860e10d 100644 --- a/Drivers/BQ25896/Source/Bq25896.cpp +++ b/Drivers/BQ25896/Source/Bq25896.cpp @@ -1,15 +1,15 @@ #include "Bq25896.h" -#include +#include -constexpr auto* TAG = "BQ25896"; +static const auto LOGGER = tt::Logger("BQ25896"); void Bq25896::powerOff() { - TT_LOG_I(TAG, "Power off"); + LOGGER.info("Power off"); bitOn(0x09, BIT(5)); } void Bq25896::powerOn() { - TT_LOG_I(TAG, "Power on"); + LOGGER.info("Power on"); bitOff(0x09, BIT(5)); } diff --git a/Drivers/BQ27220/Source/Bq27220.cpp b/Drivers/BQ27220/Source/Bq27220.cpp index 1596af07..b2d08697 100644 --- a/Drivers/BQ27220/Source/Bq27220.cpp +++ b/Drivers/BQ27220/Source/Bq27220.cpp @@ -1,9 +1,9 @@ #include "Bq27220.h" -#include +#include #include "esp_sleep.h" -#define TAG "bq27220" +static const auto LOGGER = tt::Logger("BQ27220"); #define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a))) @@ -93,14 +93,14 @@ bool Bq27220::configureCapacity(uint16_t designCapacity, uint16_t fullChargeCapa return performConfigUpdate([this, designCapacity, fullChargeCapacity]() { // Set the design capacity if (!writeConfig16(registers::ROM_DESIGN_CAPACITY, designCapacity)) { - TT_LOG_E(TAG, "Failed to set design capacity!"); + LOGGER.error("Failed to set design capacity!"); return false; } vTaskDelay(10 / portTICK_PERIOD_MS); // Set full charge capacity if (!writeConfig16(registers::ROM_FULL_CHARGE_CAPACITY, fullChargeCapacity)) { - TT_LOG_E(TAG, "Failed to set full charge capacity!"); + LOGGER.error("Failed to set full charge capacity!"); return false; } vTaskDelay(10 / portTICK_PERIOD_MS); @@ -260,7 +260,7 @@ bool Bq27220::sendSubCommand(uint16_t subCmd, bool waitConfirm) } vTaskDelay(100 / portTICK_PERIOD_MS); } - TT_LOG_E(TAG, "Subcommand x%X failed!", subCmd); + LOGGER.error("Subcommand 0x{:04X} failed!", subCmd); return false; } @@ -298,28 +298,28 @@ bool Bq27220::configPreamble(bool &isSealed) { // Check access settings if(!getOperationStatus(status)) { - TT_LOG_E(TAG, "Cannot read initial operation status!"); + LOGGER.error("Cannot read initial operation status!"); return false; } if (status.reg.SEC == OperationStatusSecSealed) { isSealed = true; if (!unsealDevice()) { - TT_LOG_E(TAG, "Unsealing device failure!"); + LOGGER.error("Unsealing device failure!"); return false; } } if (status.reg.SEC != OperationStatusSecFull) { if (!unsealFullAccess()) { - TT_LOG_E(TAG, "Unsealing full access failure!"); + LOGGER.error("Unsealing full access failure!"); return false; } } // Send ENTER_CFG_UPDATE command (0x0090) if (!sendSubCommand(registers::SUBCMD_ENTER_CFG_UPDATE)) { - TT_LOG_E(TAG, "Config Update Subcommand failure!"); + LOGGER.error("Config Update Subcommand failure!"); } // Confirm CFUPDATE mode by polling the OperationStatus() register until Bit 2 is set. @@ -333,7 +333,7 @@ bool Bq27220::configPreamble(bool &isSealed) { vTaskDelay(100 / portTICK_PERIOD_MS); } if (!isConfigUpdate) { - TT_LOG_E(TAG, "Update Mode timeout, maybe the access key for full permissions is invalid!"); + LOGGER.error("Update Mode timeout, maybe the access key for full permissions is invalid!"); return false; } @@ -357,13 +357,13 @@ bool Bq27220::configEpilouge(const bool isSealed) { vTaskDelay(100 / portTICK_PERIOD_MS); } if (timeout == 0) { - TT_LOG_E(TAG, "Timed out waiting to exit update mode."); + LOGGER.error("Timed out waiting to exit update mode."); return false; } // If the device was previously in SEALED state, return to SEALED mode by sending the Control(0x0030) subcommand if (isSealed) { - TT_LOG_D(TAG, "Restore Safe Mode!"); + LOGGER.debug("Restore Safe Mode!"); exitSealMode(); } return true; diff --git a/Drivers/ButtonControl/Source/ButtonControl.cpp b/Drivers/ButtonControl/Source/ButtonControl.cpp index b8e4a2a9..e7607b5b 100644 --- a/Drivers/ButtonControl/Source/ButtonControl.cpp +++ b/Drivers/ButtonControl/Source/ButtonControl.cpp @@ -1,10 +1,10 @@ #include "ButtonControl.h" -#include +#include #include -constexpr auto* TAG = "ButtonControl"; +static const auto LOGGER = tt::Logger("ButtonControl"); ButtonControl::ButtonControl(const std::vector& pinConfigurations) : pinConfigurations(pinConfigurations) { pinStates.resize(pinConfigurations.size()); @@ -73,7 +73,7 @@ void ButtonControl::updatePin(std::vector::const_reference con if (state.pressState) { auto time_passed = tt::kernel::getMillis() - state.pressStartTime; if (time_passed < 500) { - TT_LOG_D(TAG, "Trigger short press"); + LOGGER.debug("Trigger short press"); state.triggerShortPress = true; } state.pressState = false; @@ -103,7 +103,7 @@ bool ButtonControl::shouldInterruptDriverThread() const { } void ButtonControl::startThread() { - TT_LOG_I(TAG, "Start"); + LOGGER.info("Start"); mutex.lock(); @@ -120,7 +120,7 @@ void ButtonControl::startThread() { } void ButtonControl::stopThread() { - TT_LOG_I(TAG, "Stop"); + LOGGER.info("Stop"); mutex.lock(); interruptDriverThread = true; diff --git a/Drivers/ButtonControl/Source/ButtonControl.h b/Drivers/ButtonControl/Source/ButtonControl.h index 60bd4231..74886ce6 100644 --- a/Drivers/ButtonControl/Source/ButtonControl.h +++ b/Drivers/ButtonControl/Source/ButtonControl.h @@ -3,6 +3,7 @@ #include #include #include +#include class ButtonControl final : public tt::hal::encoder::EncoderDevice { diff --git a/Drivers/DRV2605/Source/Drv2605.cpp b/Drivers/DRV2605/Source/Drv2605.cpp index a554ce02..b5bb4358 100644 --- a/Drivers/DRV2605/Source/Drv2605.cpp +++ b/Drivers/DRV2605/Source/Drv2605.cpp @@ -1,16 +1,33 @@ #include "Drv2605.h" +#include +#include + +static const auto LOGGER = tt::Logger("DRV2605"); + +Drv2605::Drv2605(i2c_port_t port, bool autoPlayStartupBuzz) : I2cDevice(port, ADDRESS), autoPlayStartupBuzz(autoPlayStartupBuzz) { + if (!init()) { + LOGGER.error("Failed to initialize DRV2605"); + tt_crash(); + } + + if (autoPlayStartupBuzz) { + setWaveFormForBuzz(); + startPlayback(); + } +} + bool Drv2605::init() { uint8_t status; if (!readRegister8(static_cast(Register::Status), status)) { - TT_LOG_E(TAG, "Failed to read status"); + LOGGER.error("Failed to read status"); return false; } status >>= 5; ChipId chip_id = static_cast(status); if (chip_id != ChipId::DRV2604 && chip_id != ChipId::DRV2604L && chip_id != ChipId::DRV2605 && chip_id != ChipId::DRV2605L) { - TT_LOG_E(TAG, "Unknown chip id %02x", chip_id); + LOGGER.error("Unknown chip id {:02x}", static_cast(chip_id)); return false; } @@ -25,7 +42,7 @@ bool Drv2605::init() { uint8_t feedback; if (!readRegister(Register::Feedback, feedback)) { - TT_LOG_E(TAG, "Failed to read feedback"); + LOGGER.error("Failed to read feedback"); return false; } diff --git a/Drivers/DRV2605/Source/Drv2605.h b/Drivers/DRV2605/Source/Drv2605.h index 781f95fb..9bf93aa3 100644 --- a/Drivers/DRV2605/Source/Drv2605.h +++ b/Drivers/DRV2605/Source/Drv2605.h @@ -1,11 +1,9 @@ #pragma once #include -#include class Drv2605 : public tt::hal::i2c::I2cDevice { - static constexpr auto* TAG = "DRV2605"; static constexpr auto ADDRESS = 0x5A; bool autoPlayStartupBuzz; @@ -64,16 +62,7 @@ class Drv2605 : public tt::hal::i2c::I2cDevice { public: - explicit Drv2605(i2c_port_t port, bool autoPlayStartupBuzz = true) : I2cDevice(port, ADDRESS), autoPlayStartupBuzz(autoPlayStartupBuzz) { - if (!init()) { - TT_LOG_E(TAG, "Failed to initialize DRV2605"); - } - - if (autoPlayStartupBuzz) { - setWaveFormForBuzz(); - startPlayback(); - } - } + explicit Drv2605(i2c_port_t port, bool autoPlayStartupBuzz = true); std::string getName() const final { return "DRV2605"; } std::string getDescription() const final { return "Haptic driver for ERM/LRA with waveform library & auto-resonance tracking"; } @@ -84,7 +73,6 @@ public: void setWaveFormForClick(); /** - * * @param slot a value from 0 to 7 * @param waveform */ diff --git a/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp b/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp index 87a39e8e..7aacd821 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp @@ -1,13 +1,13 @@ #include "EspLcdDisplay.h" #include "EspLcdDisplayDriver.h" -#include +#include #include #include -#include +#include #include -constexpr const char* TAG = "EspLcdDispDrv"; +static const auto LOGGER = tt::Logger("EspLcdDisplay"); EspLcdDisplay::~EspLcdDisplay() { if (displayDriver != nullptr && displayDriver.use_count() > 1) { @@ -17,12 +17,12 @@ EspLcdDisplay::~EspLcdDisplay() { bool EspLcdDisplay::start() { if (!createIoHandle(ioHandle)) { - TT_LOG_E(TAG, "Failed to create IO handle"); + LOGGER.error("Failed to create IO handle"); return false; } if (!createPanelHandle(ioHandle, panelHandle)) { - TT_LOG_E(TAG, "Failed to create panel handle"); + LOGGER.error("Failed to create panel handle"); esp_lcd_panel_io_del(ioHandle); return false; } @@ -45,7 +45,7 @@ bool EspLcdDisplay::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } return true; @@ -55,7 +55,7 @@ bool EspLcdDisplay::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } auto lvgl_port_config = getLvglPortDisplayConfig(ioHandle, panelHandle); diff --git a/Drivers/EspLcdCompat/Source/EspLcdDisplayV2.cpp b/Drivers/EspLcdCompat/Source/EspLcdDisplayV2.cpp index 0d39e782..01e018ba 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdDisplayV2.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdDisplayV2.cpp @@ -1,13 +1,13 @@ #include "EspLcdDisplayV2.h" #include "EspLcdDisplayDriver.h" -#include +#include #include #include -#include +#include #include -constexpr auto* TAG = "EspLcdDispV2"; +static const auto LOGGER = tt::Logger("EspLcdDispV2"); inline unsigned int getBufferSize(const std::shared_ptr& configuration) { if (configuration->bufferSize != DEFAULT_BUFFER_SIZE) { @@ -25,17 +25,17 @@ EspLcdDisplayV2::~EspLcdDisplayV2() { bool EspLcdDisplayV2::applyConfiguration() const { if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } @@ -43,27 +43,27 @@ bool EspLcdDisplayV2::applyConfiguration() const { int gap_x = configuration->swapXY ? configuration->gapY : configuration->gapX; int gap_y = configuration->swapXY ? configuration->gapX : configuration->gapY; if (esp_lcd_panel_set_gap(panelHandle, gap_x, gap_y) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel gap"); + LOGGER.error("Failed to set panel gap"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } @@ -72,14 +72,14 @@ bool EspLcdDisplayV2::applyConfiguration() const { bool EspLcdDisplayV2::start() { if (!createIoHandle(ioHandle)) { - TT_LOG_E(TAG, "Failed to create IO handle"); + LOGGER.error("Failed to create IO handle"); return false; } esp_lcd_panel_dev_config_t panel_config = createPanelConfig(configuration, configuration->resetPin); if (!createPanelHandle(ioHandle, panel_config, panelHandle)) { - TT_LOG_E(TAG, "Failed to create panel handle"); + LOGGER.error("Failed to create panel handle"); esp_lcd_panel_io_del(ioHandle); ioHandle = nullptr; return false; @@ -111,7 +111,7 @@ bool EspLcdDisplayV2::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } return true; @@ -121,7 +121,7 @@ bool EspLcdDisplayV2::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } auto lvgl_port_config = getLvglPortDisplayConfig(configuration, ioHandle, panelHandle); diff --git a/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp b/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp index 48c5b0c4..ab956a0b 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp @@ -1,12 +1,12 @@ #include "EspLcdSpiDisplay.h" #include -#include +#include -constexpr auto* TAG = "EspLcdSpiDsp"; +static const auto LOGGER = tt::Logger("EspLcdSpiDisplay"); bool EspLcdSpiDisplay::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - TT_LOG_I(TAG, "createIoHandle"); + LOGGER.info("createIoHandle"); const esp_lcd_panel_io_spi_config_t panel_io_config = { .cs_gpio_num = spiConfiguration->csPin, @@ -33,7 +33,7 @@ bool EspLcdSpiDisplay::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { }; if (esp_lcd_new_panel_io_spi(spiConfiguration->spiHostDevice, &panel_io_config, &outHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } @@ -65,6 +65,6 @@ void EspLcdSpiDisplay::setGammaCurve(uint8_t index) { auto io_handle = getIoHandle(); assert(io_handle != nullptr); if (esp_lcd_panel_io_tx_param(io_handle, LCD_CMD_GAMSET, param, 1) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set gamma"); + LOGGER.error("Failed to set gamma"); } } diff --git a/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp b/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp index 03ca52e3..073bd2f8 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp @@ -1,21 +1,22 @@ #include "EspLcdTouch.h" -#include -#include -#include -constexpr const char* TAG = "EspLcdTouch"; +#include +#include +#include + +static const auto LOGGER = tt::Logger("EspLcdTouch"); bool EspLcdTouch::start() { if (!createIoHandle(ioHandle) != ESP_OK) { - TT_LOG_E(TAG, "Touch IO failed"); + LOGGER.error("Touch IO failed"); return false; } config = createEspLcdTouchConfig(); if (!createTouchHandle(ioHandle, config, touchHandle)) { - TT_LOG_E(TAG, "Driver init failed"); + LOGGER.error("Driver init failed"); esp_lcd_panel_io_del(ioHandle); ioHandle = nullptr; return false; @@ -48,7 +49,7 @@ bool EspLcdTouch::startLvgl(lv_disp_t* display) { } if (touchDriver != nullptr && touchDriver.use_count() > 1) { - TT_LOG_W(TAG, "TouchDriver is still in use."); + LOGGER.warn("TouchDriver is still in use."); } const lvgl_port_touch_cfg_t touch_cfg = { @@ -56,10 +57,10 @@ bool EspLcdTouch::startLvgl(lv_disp_t* display) { .handle = touchHandle, }; - TT_LOG_I(TAG, "Adding touch to LVGL"); + LOGGER.info("Adding touch to LVGL"); lvglDevice = lvgl_port_add_touch(&touch_cfg); if (lvglDevice == nullptr) { - TT_LOG_E(TAG, "Adding touch failed"); + LOGGER.error("Adding touch failed"); return false; } diff --git a/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp b/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp index 56b0c526..da24f3b3 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp @@ -1,12 +1,12 @@ #include "EspLcdTouchDriver.h" -#include +#include -constexpr const char* TAG = "EspLcdTouchDriver"; +static const auto LOGGER = tt::Logger("EspLcdTouchDriver"); bool EspLcdTouchDriver::getTouchedPoints(uint16_t* x, uint16_t* y, uint16_t* _Nullable strength, uint8_t* pointCount, uint8_t maxPointCount) { if (esp_lcd_touch_read_data(handle) != ESP_OK) { - TT_LOG_E(TAG, "Read data failed"); + LOGGER.error("Read data failed"); return false; } return esp_lcd_touch_get_coordinates(handle, x, y, strength, pointCount, maxPointCount); diff --git a/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp b/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp index c4318c8a..d747bce8 100644 --- a/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp +++ b/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp @@ -1,8 +1,7 @@ #include "ChargeFromAdcVoltage.h" -#include -#include +#include -constexpr auto TAG = "ChargeFromAdcV"; +static const auto LOGGER = tt::Logger("ChargeFromAdcV"); constexpr auto MAX_VOLTAGE_SAMPLES = 15; ChargeFromAdcVoltage::ChargeFromAdcVoltage( @@ -11,12 +10,12 @@ ChargeFromAdcVoltage::ChargeFromAdcVoltage( float voltageMax ) : configuration(configuration), chargeFromVoltage(voltageMin, voltageMax) { if (adc_oneshot_new_unit(&configuration.adcConfig, &adcHandle) != ESP_OK) { - TT_LOG_E(TAG, "ADC config failed"); + LOGGER.error("ADC config failed"); return; } if (adc_oneshot_config_channel(adcHandle, configuration.adcChannel, &configuration.adcChannelConfig) != ESP_OK) { - TT_LOG_E(TAG, "ADC channel config failed"); + LOGGER.error("ADC channel config failed"); adc_oneshot_del_unit(adcHandle); return; @@ -33,10 +32,12 @@ bool ChargeFromAdcVoltage::readBatteryVoltageOnce(uint32_t& output) const { int raw; if (adc_oneshot_read(adcHandle, configuration.adcChannel, &raw) == ESP_OK) { output = configuration.adcMultiplier * ((1000.f * configuration.adcRefVoltage) / 4096.f) * (float)raw; - TT_LOG_V(TAG, "Raw = %d, voltage = %lu", raw, output); + if (LOGGER.isLoggingVerbose()) { + LOGGER.verbose("Raw = {}, voltage = {}", raw, output); + } return true; } else { - TT_LOG_E(TAG, "Read failed"); + LOGGER.error("Read failed"); return false; } } diff --git a/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp b/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp index a8dbd03a..a9715787 100644 --- a/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp +++ b/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp @@ -1,9 +1,9 @@ #include "ChargeFromVoltage.h" +#include #include -#include -constexpr auto* TAG = "ChargeFromVoltage"; +const static auto LOGGER = tt::Logger("ChargeFromVoltage"); uint8_t ChargeFromVoltage::estimateCharge(uint32_t milliVolt) const { const float volts = std::min((float)milliVolt / 1000.f, batteryVoltageMax); @@ -13,6 +13,6 @@ uint8_t ChargeFromVoltage::estimateCharge(uint32_t milliVolt) const { const float voltage_percentage = (volts - batteryVoltageMin) / (batteryVoltageMax - batteryVoltageMin); const float voltage_factor = std::min(1.0f, voltage_percentage); const auto charge_level = (uint8_t) (voltage_factor * 100.f); - TT_LOG_D(TAG, "mV = %lu, scaled = %.2f, factor = %.2f, result = %d", milliVolt, volts, voltage_factor, charge_level); + LOGGER.debug("mV = {}, scaled = {}, factor = {:.2f}, result = {}", milliVolt, volts, voltage_factor, charge_level); return charge_level; } diff --git a/Drivers/FT5x06/Source/Ft5x06Touch.cpp b/Drivers/FT5x06/Source/Ft5x06Touch.cpp index 12f6339a..974c70a6 100644 --- a/Drivers/FT5x06/Source/Ft5x06Touch.cpp +++ b/Drivers/FT5x06/Source/Ft5x06Touch.cpp @@ -1,13 +1,9 @@ #include "Ft5x06Touch.h" -#include - #include #include #include -#define TAG "ft5x06" - bool Ft5x06Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { esp_lcd_panel_io_i2c_config_t io_config = ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG(); return esp_lcd_new_panel_io_i2c(configuration->port, &io_config, &outHandle) == ESP_OK; diff --git a/Drivers/FT6x36/Source/Ft6x36Touch.cpp b/Drivers/FT6x36/Source/Ft6x36Touch.cpp index ed4ef07a..0ff7848a 100644 --- a/Drivers/FT6x36/Source/Ft6x36Touch.cpp +++ b/Drivers/FT6x36/Source/Ft6x36Touch.cpp @@ -1,12 +1,12 @@ #include "Ft6x36Touch.h" #include -#include +#include #include #include -#define TAG "ft6x36" +static const auto LOGGER = tt::Logger("FT6x36"); void Ft6x36Touch::touchReadCallback(lv_indev_t* indev, lv_indev_data_t* data) { auto* touch = (Ft6x36Touch*)lv_indev_get_driver_data(indev); @@ -71,10 +71,10 @@ bool Ft6x36Touch::shouldInterruptDriverThread() const { } bool Ft6x36Touch::start() { - TT_LOG_I(TAG, "Start"); + LOGGER.info("Start"); if (!driver.begin(FT6X36_DEFAULT_THRESHOLD, configuration->width, configuration->height)) { - TT_LOG_E(TAG, "driver.begin() failed"); + LOGGER.error("driver.begin() failed"); return false; } @@ -95,7 +95,7 @@ bool Ft6x36Touch::start() { } bool Ft6x36Touch::stop() { - TT_LOG_I(TAG, "Stop"); + LOGGER.info("Stop"); mutex.lock(); interruptDriverThread = true; diff --git a/Drivers/FT6x36/Source/Ft6x36Touch.h b/Drivers/FT6x36/Source/Ft6x36Touch.h index 2c4cd864..e7328a30 100644 --- a/Drivers/FT6x36/Source/Ft6x36Touch.h +++ b/Drivers/FT6x36/Source/Ft6x36Touch.h @@ -2,6 +2,7 @@ #include #include +#include #include #include "ft6x36/FT6X36.h" diff --git a/Drivers/GC9A01/Source/Gc9a01Display.cpp b/Drivers/GC9A01/Source/Gc9a01Display.cpp index e6f17f8f..44fe1a93 100644 --- a/Drivers/GC9A01/Source/Gc9a01Display.cpp +++ b/Drivers/GC9A01/Source/Gc9a01Display.cpp @@ -1,15 +1,15 @@ #include "Gc9a01Display.h" -#include +#include #include #include #include -constexpr auto TAG = "GC9A01"; +static const auto LOGGER = tt::Logger("GC9A01"); bool Gc9a01Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - TT_LOG_I(TAG, "Starting"); + LOGGER.info("Starting"); const esp_lcd_panel_io_spi_config_t panel_io_config = { .cs_gpio_num = configuration->csPin, @@ -36,7 +36,7 @@ bool Gc9a01Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { }; if (esp_lcd_new_panel_io_spi(configuration->spiHostDevice, &panel_io_config, &outHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } @@ -56,37 +56,37 @@ bool Gc9a01Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_gc9a01(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } diff --git a/Drivers/GT911/Source/Gt911Touch.cpp b/Drivers/GT911/Source/Gt911Touch.cpp index b2959a9e..06fbf660 100644 --- a/Drivers/GT911/Source/Gt911Touch.cpp +++ b/Drivers/GT911/Source/Gt911Touch.cpp @@ -1,12 +1,12 @@ #include "Gt911Touch.h" -#include +#include #include #include #include -#define TAG "GT911" +static const auto LOGGER = tt::Logger("GT911"); bool Gt911Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { esp_lcd_panel_io_i2c_config_t io_config = ESP_LCD_TOUCH_IO_I2C_GT911_CONFIG(); @@ -21,7 +21,7 @@ bool Gt911Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { } else if (tt::hal::i2c::masterHasDeviceAtAddress(configuration->port, ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS_BACKUP)) { io_config.dev_addr = ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS_BACKUP; } else { - TT_LOG_E(TAG, "No device found on I2C bus"); + LOGGER.error("No device found on I2C bus"); return false; } diff --git a/Drivers/ILI9488/Source/Ili9488Display.cpp b/Drivers/ILI9488/Source/Ili9488Display.cpp index 6773c832..577bcc1a 100644 --- a/Drivers/ILI9488/Source/Ili9488Display.cpp +++ b/Drivers/ILI9488/Source/Ili9488Display.cpp @@ -1,12 +1,12 @@ #include "Ili9488Display.h" -#include +#include #include #include #include -#define TAG "ILI9488" +static const auto LOGGER = tt::Logger("ILI9488"); bool Ili9488Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { const esp_lcd_panel_io_spi_config_t panel_io_config = { @@ -50,37 +50,37 @@ bool Ili9488Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l }; if (esp_lcd_new_panel_ili9488(ioHandle, &panel_config, configuration->bufferSize, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } diff --git a/Drivers/PwmBacklight/Source/PwmBacklight.cpp b/Drivers/PwmBacklight/Source/PwmBacklight.cpp index b19c1836..dfd6e313 100644 --- a/Drivers/PwmBacklight/Source/PwmBacklight.cpp +++ b/Drivers/PwmBacklight/Source/PwmBacklight.cpp @@ -1,8 +1,8 @@ #include "PwmBacklight.h" -#include +#include -#define TAG "pwm_backlight" +static const auto LOGGER = tt::Logger("PwmBacklight"); namespace driver::pwmbacklight { @@ -16,7 +16,7 @@ bool init(gpio_num_t pin, uint32_t frequencyHz, ledc_timer_t timer, ledc_channel backlightTimer = timer; backlightChannel = channel; - TT_LOG_I(TAG, "Init"); + LOGGER.info("Init"); ledc_timer_config_t ledc_timer = { .speed_mode = LEDC_LOW_SPEED_MODE, .duty_resolution = LEDC_TIMER_8_BIT, @@ -27,7 +27,7 @@ bool init(gpio_num_t pin, uint32_t frequencyHz, ledc_timer_t timer, ledc_channel }; if (ledc_timer_config(&ledc_timer) != ESP_OK) { - TT_LOG_E(TAG, "Timer config failed"); + LOGGER.error("Timer config failed"); return false; } @@ -46,7 +46,8 @@ bool init(gpio_num_t pin, uint32_t frequencyHz, ledc_timer_t timer, ledc_channel }; if (ledc_channel_config(&ledc_channel) != ESP_OK) { - TT_LOG_E(TAG, "Channel config failed"); + LOGGER.error("Channel config failed"); + return false; } isBacklightInitialized = true; @@ -56,7 +57,7 @@ bool init(gpio_num_t pin, uint32_t frequencyHz, ledc_timer_t timer, ledc_channel bool setBacklightDuty(uint8_t duty) { if (!isBacklightInitialized) { - TT_LOG_E(TAG, "Not initialized"); + LOGGER.error("Not initialized"); return false; } return ledc_set_duty(LEDC_LOW_SPEED_MODE, backlightChannel, duty) == ESP_OK && diff --git a/Drivers/RgbDisplay/Source/RgbDisplay.cpp b/Drivers/RgbDisplay/Source/RgbDisplay.cpp index 88007e3d..fdd4499e 100644 --- a/Drivers/RgbDisplay/Source/RgbDisplay.cpp +++ b/Drivers/RgbDisplay/Source/RgbDisplay.cpp @@ -1,15 +1,15 @@ #include "RgbDisplay.h" -#include +#include +#include +#include #include #include #include #include -#include -#include -constexpr auto TAG = "RgbDisplay"; +static const auto LOGGER = tt::Logger("RgbDisplay"); RgbDisplay::~RgbDisplay() { if (displayDriver != nullptr && displayDriver.use_count() > 1) { @@ -18,35 +18,35 @@ RgbDisplay::~RgbDisplay() { } bool RgbDisplay::start() { - TT_LOG_I(TAG, "Starting"); + LOGGER.info("Starting"); if (esp_lcd_new_rgb_panel(&configuration->panelConfig, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY"); + LOGGER.error("Failed to swap XY"); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } @@ -64,7 +64,7 @@ bool RgbDisplay::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } auto touch_device = getTouchDevice(); @@ -80,7 +80,7 @@ bool RgbDisplay::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - TT_LOG_W(TAG, "DisplayDriver is still in use."); + LOGGER.warn("DisplayDriver is still in use."); } auto display_config = getLvglPortDisplayConfig(); @@ -93,7 +93,7 @@ bool RgbDisplay::startLvgl() { }; lvglDisplay = lvgl_port_add_disp_rgb(&display_config, &rgb_config); - TT_LOG_I(TAG, "Finished"); + LOGGER.info("Finished"); auto touch_device = getTouchDevice(); if (touch_device != nullptr) { diff --git a/Drivers/SSD1306/Source/Ssd1306Display.cpp b/Drivers/SSD1306/Source/Ssd1306Display.cpp index 930441cb..7cda1adb 100644 --- a/Drivers/SSD1306/Source/Ssd1306Display.cpp +++ b/Drivers/SSD1306/Source/Ssd1306Display.cpp @@ -1,6 +1,6 @@ #include "Ssd1306Display.h" -#include +#include #include #include #include @@ -10,7 +10,7 @@ #include #include -#define TAG "ssd1306_display" +static const auto LOGGER = tt::Logger("Ssd1306Display"); // SSD1306 commands #define SSD1306_CMD_SET_CHARGE_PUMP 0x8D @@ -31,7 +31,7 @@ static bool ssd1306_i2c_send_cmd(i2c_port_t port, uint8_t addr, uint8_t cmd) { uint8_t data[2] = {0x00, cmd}; // 0x00 = command mode esp_err_t ret = i2c_master_write_to_device(port, addr, data, sizeof(data), pdMS_TO_TICKS(1000)); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to send command 0x%02X: %d", cmd, ret); + LOGGER.error("Failed to send command 0x{:02X}: {}", cmd, ret); return false; } return true; @@ -49,7 +49,7 @@ bool Ssd1306Display::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { }; if (esp_lcd_new_panel_io_i2c((esp_lcd_i2c_bus_handle_t)configuration->port, &io_config, &ioHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create IO handle"); + LOGGER.error("Failed to create IO handle"); return false; } @@ -93,7 +93,7 @@ bool Ssd1306Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l #endif if (esp_lcd_new_panel_ssd1306(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } @@ -103,7 +103,7 @@ bool Ssd1306Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l auto port = configuration->port; auto addr = configuration->deviceAddress; - TT_LOG_I(TAG, "Sending Heltec V3 custom init sequence"); + LOGGER.info("Sending Heltec V3 custom init sequence"); // Display off while configuring ssd1306_i2c_send_cmd(port, addr, 0xAE); @@ -170,7 +170,7 @@ bool Ssd1306Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l vTaskDelay(pdMS_TO_TICKS(100)); // Let display stabilize - TT_LOG_I(TAG, "Heltec V3 display initialized successfully"); + LOGGER.info("Heltec V3 display initialized successfully"); return true; } diff --git a/Drivers/ST7735/Source/St7735Display.cpp b/Drivers/ST7735/Source/St7735Display.cpp index 32503b9e..39aa6abd 100644 --- a/Drivers/ST7735/Source/St7735Display.cpp +++ b/Drivers/ST7735/Source/St7735Display.cpp @@ -1,16 +1,16 @@ #include "St7735Display.h" -#include +#include #include #include #include #include -constexpr auto TAG = "ST7735"; +static const auto LOGGER = tt::Logger("ST7735"); bool St7735Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - TT_LOG_I(TAG, "Starting"); + LOGGER.info("Starting"); const esp_lcd_panel_io_spi_config_t panel_io_config = { .cs_gpio_num = configuration->csPin, @@ -37,7 +37,7 @@ bool St7735Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { }; if (esp_lcd_new_panel_io_spi(configuration->spiHostDevice, &panel_io_config, &outHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } @@ -58,22 +58,22 @@ bool St7735Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_st7735(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } @@ -81,22 +81,22 @@ bool St7735Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc int gap_x = configuration->swapXY ? configuration->gapY : configuration->gapX; int gap_y = configuration->swapXY ? configuration->gapX : configuration->gapY; if (esp_lcd_panel_set_gap(panelHandle, gap_x, gap_y) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel gap"); + LOGGER.error("Failed to set panel gap"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } @@ -165,6 +165,6 @@ void St7735Display::setGammaCurve(uint8_t index) { auto io_handle = getIoHandle(); assert(io_handle != nullptr); if (esp_lcd_panel_io_tx_param(io_handle, LCD_CMD_GAMSET, param, 1) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set gamma"); + LOGGER.error("Failed to set gamma"); } } diff --git a/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp b/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp index c0995ee2..1c730f84 100644 --- a/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp +++ b/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp @@ -1,5 +1,5 @@ #include "St7789i8080Display.h" -#include +#include #include #include #include @@ -8,7 +8,7 @@ #include #include -constexpr auto TAG = "St7789i8080Display"; +static const auto LOGGER = tt::Logger("St7789i8080Display"); static St7789i8080Display* g_display_instance = nullptr; // ST7789 initialization commands @@ -51,13 +51,13 @@ St7789i8080Display::St7789i8080Display(const Configuration& config) // Validate configuration if (!configuration.isValid()) { - TT_LOG_E(TAG, "Invalid configuration: resolution must be set"); + LOGGER.error("Invalid configuration: resolution must be set"); return; } } bool St7789i8080Display::createI80Bus() { - TT_LOG_I(TAG, "Creating I80 bus"); + LOGGER.info("Creating I80 bus"); // Create I80 bus configuration esp_lcd_i80_bus_config_t bus_cfg = { @@ -78,7 +78,7 @@ bool St7789i8080Display::createI80Bus() { esp_err_t ret = esp_lcd_new_i80_bus(&bus_cfg, &i80BusHandle); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to create I80 bus: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to create I80 bus: {}", esp_err_to_name(ret)); return false; } @@ -86,7 +86,7 @@ bool St7789i8080Display::createI80Bus() { } bool St7789i8080Display::createPanelIO() { - TT_LOG_I(TAG, "Creating panel IO"); + LOGGER.info("Creating panel IO"); // Create panel IO with proper callback esp_lcd_panel_io_i80_config_t io_cfg = { @@ -114,7 +114,7 @@ bool St7789i8080Display::createPanelIO() { esp_err_t ret = esp_lcd_new_panel_io_i80(i80BusHandle, &io_cfg, &ioHandle); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel IO: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to create panel IO: {}", esp_err_to_name(ret)); return false; } @@ -122,7 +122,7 @@ bool St7789i8080Display::createPanelIO() { } bool St7789i8080Display::createPanel() { - TT_LOG_I(TAG, "Configuring panel"); + LOGGER.info("Configuring panel"); // Create ST7789 panel esp_lcd_panel_dev_config_t panel_config = { @@ -138,49 +138,49 @@ bool St7789i8080Display::createPanel() { esp_err_t ret = esp_lcd_new_panel_st7789(ioHandle, &panel_config, &panelHandle); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to create ST7789 panel: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to create ST7789 panel: {}", esp_err_to_name(ret)); return false; } // Reset panel ret = esp_lcd_panel_reset(panelHandle); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to reset panel: {}", esp_err_to_name(ret)); return false; } // Initialize panel ret = esp_lcd_panel_init(panelHandle); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to init panel: {}", esp_err_to_name(ret)); return false; } // Set gap ret = esp_lcd_panel_set_gap(panelHandle, configuration.gapX, configuration.gapY); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel gap: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to set panel gap: {}", esp_err_to_name(ret)); return false; } // Set inversion ret = esp_lcd_panel_invert_color(panelHandle, configuration.invertColor); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel inversion: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to set panel inversion: {}", esp_err_to_name(ret)); return false; } // Set mirror ret = esp_lcd_panel_mirror(panelHandle, configuration.mirrorX, configuration.mirrorY); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel mirror: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to set panel mirror: {}", esp_err_to_name(ret)); return false; } // Turn on display ret = esp_lcd_panel_disp_on_off(panelHandle, true); if (ret != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on: %s", esp_err_to_name(ret)); + LOGGER.error("Failed to turn display on: {}", esp_err_to_name(ret)); return false; } @@ -188,7 +188,7 @@ bool St7789i8080Display::createPanel() { } void St7789i8080Display::sendInitCommands() { - TT_LOG_I(TAG, "Sending ST7789 init commands"); + LOGGER.info("Sending ST7789 init commands"); for (const auto& cmd : st7789_init_cmds) { esp_lcd_panel_io_tx_param(ioHandle, cmd.cmd, cmd.data, cmd.len & 0x7F); if (cmd.len & 0x80) { @@ -198,7 +198,7 @@ void St7789i8080Display::sendInitCommands() { } bool St7789i8080Display::start() { - TT_LOG_I(TAG, "Initializing I8080 ST7789 Display hardware..."); + LOGGER.info("Initializing I8080 ST7789 Display hardware..."); // Configure RD pin if needed if (configuration.rdPin != GPIO_NUM_NC) { @@ -220,7 +220,7 @@ bool St7789i8080Display::start() { size_t buffer_size = configuration.bufferSize * LV_COLOR_FORMAT_GET_SIZE(LV_COLOR_FORMAT_RGB565); buf1 = (uint8_t*)heap_caps_malloc(buffer_size, MALLOC_CAP_DMA); if (!buf1) { - TT_LOG_E(TAG, "Failed to allocate display buffer"); + LOGGER.error("Failed to allocate display buffer"); return false; } @@ -239,7 +239,7 @@ bool St7789i8080Display::start() { return false; } - TT_LOG_I(TAG, "Display hardware initialized"); + LOGGER.info("Display hardware initialized"); return true; } @@ -278,17 +278,17 @@ bool St7789i8080Display::stop() { } bool St7789i8080Display::startLvgl() { - TT_LOG_I(TAG, "Initializing LVGL for ST7789 display"); + LOGGER.info("Initializing LVGL for ST7789 display"); // Don't reinitialize hardware if it's already done if (!ioHandle) { - TT_LOG_I(TAG, "Hardware not initialized, calling start()"); + LOGGER.info("Hardware not initialized, calling start()"); if (!start()) { - TT_LOG_E(TAG, "Hardware initialization failed"); + LOGGER.error("Hardware initialization failed"); return false; } } else { - TT_LOG_I(TAG, "Hardware already initialized, skipping"); + LOGGER.info("Hardware already initialized, skipping"); } // Create LVGL display using lvgl_port @@ -321,7 +321,7 @@ bool St7789i8080Display::startLvgl() { // Create the LVGL display lvglDisplay = lvgl_port_add_disp(&display_cfg); if (!lvglDisplay) { - TT_LOG_E(TAG, "Failed to create LVGL display"); + LOGGER.error("Failed to create LVGL display"); return false; } @@ -332,7 +332,7 @@ bool St7789i8080Display::startLvgl() { esp_lcd_panel_io_register_event_callbacks(ioHandle, &cbs, lvglDisplay); g_display_instance = this; - TT_LOG_I(TAG, "LVGL display created successfully"); + LOGGER.info("LVGL display created successfully"); return true; } diff --git a/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp b/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp index bd0784e8..1cf9055b 100644 --- a/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp +++ b/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp @@ -1,5 +1,5 @@ #include "St7796i8080Display.h" -#include +#include #include #include #include @@ -8,7 +8,7 @@ #include #include -constexpr auto TAG = "St7796i8080Display"; +static const auto LOGGER = tt::Logger("St7796i8080Display"); static St7796i8080Display* g_display_instance = nullptr; St7796i8080Display::St7796i8080Display(const Configuration& config) @@ -16,13 +16,13 @@ St7796i8080Display::St7796i8080Display(const Configuration& config) // Validate configuration if (!configuration.isValid()) { - TT_LOG_E(TAG, "Invalid configuration: resolution must be set"); + LOGGER.error("Invalid configuration: resolution must be set"); return; } } bool St7796i8080Display::createI80Bus() { - TT_LOG_I(TAG, "Creating I80 bus"); + LOGGER.info("Creating I80 bus"); // Create I80 bus configuration esp_lcd_i80_bus_config_t bus_cfg = { @@ -42,7 +42,7 @@ bool St7796i8080Display::createI80Bus() { }; if (esp_lcd_new_i80_bus(&bus_cfg, &i80BusHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create I80 bus"); + LOGGER.error("Failed to create I80 bus"); return false; } @@ -50,7 +50,7 @@ bool St7796i8080Display::createI80Bus() { } bool St7796i8080Display::createPanelIO() { - TT_LOG_I(TAG, "Creating panel IO"); + LOGGER.info("Creating panel IO"); // Create panel IO esp_lcd_panel_io_i80_config_t io_cfg = { @@ -77,7 +77,7 @@ bool St7796i8080Display::createPanelIO() { }; if (esp_lcd_new_panel_io_i80(i80BusHandle, &io_cfg, &ioHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } @@ -85,7 +85,7 @@ bool St7796i8080Display::createPanelIO() { } bool St7796i8080Display::createPanel() { - TT_LOG_I(TAG, "Configuring panel"); + LOGGER.info("Configuring panel"); // Create ST7796 panel esp_lcd_panel_dev_config_t panel_config = { @@ -100,43 +100,43 @@ bool St7796i8080Display::createPanel() { }; if (esp_lcd_new_panel_st7796(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } // Reset panel if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } // Initialize panel if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } // Set swap XY if (esp_lcd_panel_swap_xy(panelHandle, configuration.swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } // Set mirror if (esp_lcd_panel_mirror(panelHandle, configuration.mirrorX, configuration.mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } // Set inversion if (esp_lcd_panel_invert_color(panelHandle, configuration.invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } // Turn on display if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } @@ -144,7 +144,7 @@ bool St7796i8080Display::createPanel() { } bool St7796i8080Display::start() { - TT_LOG_I(TAG, "Initializing I8080 ST7796 Display hardware..."); + LOGGER.info("Initializing I8080 ST7796 Display hardware..."); // Calculate buffer size if needed configuration.calculateBufferSize(); @@ -153,7 +153,7 @@ bool St7796i8080Display::start() { size_t buffer_size = configuration.bufferSize * LV_COLOR_FORMAT_GET_SIZE(LV_COLOR_FORMAT_RGB565); displayBuffer = (uint8_t*)heap_caps_malloc(buffer_size, MALLOC_CAP_DMA); if (!displayBuffer) { - TT_LOG_E(TAG, "Failed to allocate display buffer"); + LOGGER.error("Failed to allocate display buffer"); return false; } @@ -175,7 +175,7 @@ bool St7796i8080Display::start() { return false; } - TT_LOG_I(TAG, "Display hardware initialized"); + LOGGER.info("Display hardware initialized"); return true; } @@ -214,17 +214,17 @@ bool St7796i8080Display::stop() { } bool St7796i8080Display::startLvgl() { - TT_LOG_I(TAG, "Initializing LVGL for ST7796 display"); + LOGGER.info("Initializing LVGL for ST7796 display"); // Don't reinitialize hardware if it's already done if (!ioHandle) { - TT_LOG_I(TAG, "Hardware not initialized, calling start()"); + LOGGER.info("Hardware not initialized, calling start()"); if (!start()) { - TT_LOG_E(TAG, "Hardware initialization failed"); + LOGGER.error("Hardware initialization failed"); return false; } } else { - TT_LOG_I(TAG, "Hardware already initialized, skipping"); + LOGGER.info("Hardware already initialized, skipping"); } // Create LVGL display using lvgl_port @@ -257,12 +257,12 @@ bool St7796i8080Display::startLvgl() { // Create the LVGL display lvglDisplay = lvgl_port_add_disp(&display_cfg); if (!lvglDisplay) { - TT_LOG_E(TAG, "Failed to create LVGL display"); + LOGGER.error("Failed to create LVGL display"); return false; } g_display_instance = this; - TT_LOG_I(TAG, "LVGL display created successfully"); + LOGGER.info("LVGL display created successfully"); return true; } diff --git a/Drivers/ST7796/Source/St7796Display.cpp b/Drivers/ST7796/Source/St7796Display.cpp index ccb5c1c3..43bd22c6 100644 --- a/Drivers/ST7796/Source/St7796Display.cpp +++ b/Drivers/ST7796/Source/St7796Display.cpp @@ -1,12 +1,12 @@ #include "St7796Display.h" -#include +#include #include #include #include -constexpr auto TAG = "ST7796"; +static const auto LOGGER = tt::Logger("ST7796"); bool St7796Display::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { const esp_lcd_panel_io_spi_config_t panel_io_config = { @@ -74,42 +74,42 @@ bool St7796Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_st7796(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to create panel"); + LOGGER.error("Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to reset panel"); + LOGGER.error("Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to init panel"); + LOGGER.error("Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to invert"); + LOGGER.error("Failed to set panel to invert"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to swap XY "); + LOGGER.error("Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel to mirror"); + LOGGER.error("Failed to set panel to mirror"); return false; } if (esp_lcd_panel_set_gap(panelHandle, configuration->gapX, configuration->gapY) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set panel gap"); + LOGGER.error("Failed to set panel gap"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - TT_LOG_E(TAG, "Failed to turn display on"); + LOGGER.error("Failed to turn display on"); return false; } @@ -168,6 +168,6 @@ void St7796Display::setGammaCurve(uint8_t index) { }; /*if (esp_lcd_panel_io_tx_param(ioHandle , LCD_CMD_GAMSET, param, 1) != ESP_OK) { - TT_LOG_E(TAG, "Failed to set gamma"); + LOGGER.error("Failed to set gamma"); }*/ } diff --git a/Drivers/TCA8418/Source/Tca8418.cpp b/Drivers/TCA8418/Source/Tca8418.cpp index da0c6522..2e6e1b6a 100644 --- a/Drivers/TCA8418/Source/Tca8418.cpp +++ b/Drivers/TCA8418/Source/Tca8418.cpp @@ -1,7 +1,4 @@ #include "Tca8418.h" -#include - -constexpr auto TAG = "TCA8418"; namespace registers { static const uint8_t CFG = 0x01U; diff --git a/Drivers/XPT2046/Source/Xpt2046Power.cpp b/Drivers/XPT2046/Source/Xpt2046Power.cpp index a2e0126d..ebf040f6 100644 --- a/Drivers/XPT2046/Source/Xpt2046Power.cpp +++ b/Drivers/XPT2046/Source/Xpt2046Power.cpp @@ -1,10 +1,11 @@ #include "Xpt2046Power.h" #include "Xpt2046Touch.h" -#include +#include #include -constexpr auto TAG = "Xpt2046Power"; +static const auto LOGGER = tt::Logger("Xpt2046Power"); + constexpr auto BATTERY_VOLTAGE_MIN = 3.2f; constexpr auto BATTERY_VOLTAGE_MAX = 4.2f; constexpr auto MAX_VOLTAGE_SAMPLES = 15; @@ -13,12 +14,12 @@ static std::shared_ptr findXp2046TouchDevice() { // Make a safe copy auto touch = tt::hal::findFirstDevice(tt::hal::Device::Type::Touch); if (touch == nullptr) { - TT_LOG_E(TAG, "Touch device not found"); + LOGGER.error("Touch device not found"); return nullptr; } if (touch->getName() != "XPT2046") { - TT_LOG_E(TAG, "Touch device name mismatch"); + LOGGER.error("Touch device name mismatch"); return nullptr; } @@ -30,7 +31,7 @@ static uint8_t estimateChargeLevelFromVoltage(uint32_t milliVolt) { float voltage_percentage = (volts - BATTERY_VOLTAGE_MIN) / (BATTERY_VOLTAGE_MAX - BATTERY_VOLTAGE_MIN); float voltage_factor = std::min(1.0f, voltage_percentage); auto charge_level = (uint8_t) (voltage_factor * 100.f); - TT_LOG_V(TAG, "mV = %lu, scaled = %.2f, factor = %.2f, result = %d", milliVolt, volts, voltage_factor, charge_level); + LOGGER.verbose("mV = {}, scaled = {}, factor = {}, result = {}", milliVolt, volts, voltage_factor, charge_level); return charge_level; } @@ -68,7 +69,7 @@ bool Xpt2046Power::readBatteryVoltageOnce(uint32_t& output) { if (xptTouch == nullptr) { xptTouch = findXp2046TouchDevice(); if (xptTouch == nullptr) { - TT_LOG_E(TAG, "XPT2046 touch device not found"); + LOGGER.error("XPT2046 touch device not found"); return false; } } diff --git a/Drivers/XPT2046/Source/Xpt2046Touch.cpp b/Drivers/XPT2046/Source/Xpt2046Touch.cpp index 16980d5d..50c5ca15 100644 --- a/Drivers/XPT2046/Source/Xpt2046Touch.cpp +++ b/Drivers/XPT2046/Source/Xpt2046Touch.cpp @@ -1,6 +1,5 @@ #include "Xpt2046Touch.h" -#include #include #include diff --git a/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp b/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp index 174d916c..7b8f771d 100644 --- a/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp +++ b/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp @@ -1,6 +1,6 @@ #include "Xpt2046SoftSpi.h" -#include +#include #include #include @@ -13,7 +13,7 @@ #include #include -constexpr auto* TAG = "Xpt2046SoftSpi"; +static const auto LOGGER = tt::Logger("Xpt2046SoftSpi"); constexpr auto RERUN_CALIBRATE = false; constexpr auto CMD_READ_Y = 0x90; // Try different commands if these don't work @@ -55,7 +55,7 @@ static void ensureNvsInitialized() { bool Xpt2046SoftSpi::start() { ensureNvsInitialized(); - TT_LOG_I(TAG, "Starting Xpt2046SoftSpi touch driver"); + LOGGER.info("Starting Xpt2046SoftSpi touch driver"); // Configure GPIO pins gpio_config_t io_conf = {}; @@ -70,7 +70,7 @@ bool Xpt2046SoftSpi::start() { io_conf.pull_up_en = GPIO_PULLUP_DISABLE; if (gpio_config(&io_conf) != ESP_OK) { - TT_LOG_E(TAG, "Failed to configure output pins"); + LOGGER.error("Failed to configure output pins"); return false; } @@ -80,7 +80,7 @@ bool Xpt2046SoftSpi::start() { io_conf.pull_up_en = GPIO_PULLUP_ENABLE; if (gpio_config(&io_conf) != ESP_OK) { - TT_LOG_E(TAG, "Failed to configure input pin"); + LOGGER.error("Failed to configure input pin"); return false; } @@ -89,31 +89,36 @@ bool Xpt2046SoftSpi::start() { gpio_set_level(configuration->clkPin, 0); // CLK low gpio_set_level(configuration->mosiPin, 0); // MOSI low - TT_LOG_I(TAG, "GPIO configured: MOSI=%d, MISO=%d, CLK=%d, CS=%d", configuration->mosiPin, configuration->misoPin, configuration->clkPin, configuration->csPin); + LOGGER.info("GPIO configured: MOSI={}, MISO={}, CLK={}, CS={}", + static_cast(configuration->mosiPin), + static_cast(configuration->misoPin), + static_cast(configuration->clkPin), + static_cast(configuration->csPin) + ); // Load or perform calibration bool calibrationValid = true; //loadCalibration() && !RERUN_CALIBRATE; if (calibrationValid) { // Check if calibration values are valid (xMin != xMax, yMin != yMax) if (cal.xMin == cal.xMax || cal.yMin == cal.yMax) { - TT_LOG_W(TAG, "Invalid calibration detected: xMin=%d, xMax=%d, yMin=%d, yMax=%d", cal.xMin, cal.xMax, cal.yMin, cal.yMax); + LOGGER.warn("Invalid calibration detected: xMin={}, xMax={}, yMin={}, yMax={}", cal.xMin, cal.xMax, cal.yMin, cal.yMax); calibrationValid = false; } } if (!calibrationValid) { - TT_LOG_W(TAG, "Calibration data not found, invalid, or forced recalibration"); + LOGGER.warn("Calibration data not found, invalid, or forced recalibration"); calibrate(); saveCalibration(); } else { - TT_LOG_I(TAG, "Loaded calibration: xMin=%d, yMin=%d, xMax=%d, yMax=%d", cal.xMin, cal.yMin, cal.xMax, cal.yMax); + LOGGER.info("Loaded calibration: xMin={}, yMin={}, xMax={}, yMax={}", cal.xMin, cal.yMin, cal.xMax, cal.yMax); } return true; } bool Xpt2046SoftSpi::stop() { - TT_LOG_I(TAG, "Stopping Xpt2046SoftSpi touch driver"); + LOGGER.info("Stopping Xpt2046SoftSpi touch driver"); // Stop LVLG if needed if (lvglDevice != nullptr) { @@ -125,13 +130,13 @@ bool Xpt2046SoftSpi::stop() { bool Xpt2046SoftSpi::startLvgl(lv_display_t* display) { if (lvglDevice != nullptr) { - TT_LOG_E(TAG, "LVGL was already started"); + LOGGER.error("LVGL was already started"); return false; } lvglDevice = lv_indev_create(); if (!lvglDevice) { - TT_LOG_E(TAG, "Failed to create LVGL input device"); + LOGGER.error("Failed to create LVGL input device"); return false; } @@ -139,7 +144,7 @@ bool Xpt2046SoftSpi::startLvgl(lv_display_t* display) { lv_indev_set_read_cb(lvglDevice, touchReadCallback); lv_indev_set_user_data(lvglDevice, this); - TT_LOG_I(TAG, "Xpt2046SoftSpi touch driver started successfully"); + LOGGER.info("Xpt2046SoftSpi touch driver started successfully"); return true; } @@ -186,9 +191,9 @@ int Xpt2046SoftSpi::readSPI(uint8_t command) { void Xpt2046SoftSpi::calibrate() { const int samples = 8; // More samples for better accuracy - TT_LOG_I(TAG, "Calibration starting..."); + LOGGER.info("Calibration starting..."); - TT_LOG_I(TAG, "Touch TOP-LEFT corner"); + LOGGER.info("Touch TOP-LEFT corner"); while (!isTouched()) { vTaskDelay(pdMS_TO_TICKS(50)); @@ -203,9 +208,9 @@ void Xpt2046SoftSpi::calibrate() { cal.xMin = sumX / samples; cal.yMin = sumY / samples; - TT_LOG_I(TAG, "Top-left calibrated: xMin=%d, yMin=%d", cal.xMin, cal.yMin); + LOGGER.info("Top-left calibrated: xMin={}, yMin={}", cal.xMin, cal.yMin); - TT_LOG_I(TAG, "Touch BOTTOM-RIGHT corner"); + LOGGER.info("Touch BOTTOM-RIGHT corner"); while (!isTouched()) { vTaskDelay(pdMS_TO_TICKS(50)); @@ -220,13 +225,13 @@ void Xpt2046SoftSpi::calibrate() { cal.xMax = sumX / samples; cal.yMax = sumY / samples; - TT_LOG_I(TAG, "Bottom-right calibrated: xMax=%d, yMax=%d", cal.xMax, cal.yMax); + LOGGER.info("Bottom-right calibrated: xMax={}, yMax={}", cal.xMax, cal.yMax); - TT_LOG_I(TAG, "Calibration completed! xMin=%d, yMin=%d, xMax=%d, yMax=%d", cal.xMin, cal.yMin, cal.xMax, cal.yMax); + LOGGER.info("Calibration completed! xMin={}, yMin={}, xMax={}, yMax={}", cal.xMin, cal.yMin, cal.xMax, cal.yMax); } bool Xpt2046SoftSpi::loadCalibration() { - TT_LOG_W(TAG, "Calibration load disabled (using fresh calibration only)."); + LOGGER.warn("Calibration load disabled (using fresh calibration only)."); return false; } @@ -234,16 +239,16 @@ void Xpt2046SoftSpi::saveCalibration() { nvs_handle_t handle; esp_err_t err = nvs_open("xpt2046", NVS_READWRITE, &handle); if (err != ESP_OK) { - TT_LOG_E(TAG, "Failed to open NVS for writing (%s)", esp_err_to_name(err)); + LOGGER.error("Failed to open NVS for writing ({})", esp_err_to_name(err)); return; } err = nvs_set_blob(handle, "cal", &cal, sizeof(cal)); if (err == ESP_OK) { nvs_commit(handle); - TT_LOG_I(TAG, "Calibration saved to NVS"); + LOGGER.info("Calibration saved to NVS"); } else { - TT_LOG_E(TAG, "Failed to write calibration data to NVS (%s)", esp_err_to_name(err)); + LOGGER.error("Failed to write calibration data to NVS ({})", esp_err_to_name(err)); } nvs_close(handle); @@ -254,7 +259,7 @@ void Xpt2046SoftSpi::setCalibration(int xMin, int yMin, int xMax, int yMax) { cal.yMin = yMin; cal.xMax = xMax; cal.yMax = yMax; - TT_LOG_I(TAG, "Manual calibration set: xMin=%d, yMin=%d, xMax=%d, yMax=%d", xMin, yMin, xMax, yMax); + LOGGER.info("Manual calibration set: xMin={}, yMin={}, xMax={}, yMax={}", xMin, yMin, xMax, yMax); } bool Xpt2046SoftSpi::getTouchPoint(Point& point) { @@ -292,7 +297,7 @@ bool Xpt2046SoftSpi::getTouchPoint(Point& point) { const int yRange = cal.yMax - cal.yMin; if (xRange <= 0 || yRange <= 0) { - TT_LOG_W(TAG, "Invalid calibration: xRange=%d, yRange=%d", xRange, yRange); + LOGGER.warn("Invalid calibration: xRange={}, yRange={}", xRange, yRange); return false; } @@ -337,7 +342,7 @@ bool Xpt2046SoftSpi::isTouched() { // Debug logging (remove this once working) if (touched) { - TT_LOG_D(TAG, "Touch detected: validSamples=%d, avgX=%d, avgY=%d", validSamples, xTotal / validSamples, yTotal / validSamples); + LOGGER.debug("Touch detected: validSamples={}, avgX={}, avgY={}", validSamples, xTotal / validSamples, yTotal / validSamples); } return touched; diff --git a/Tactility/Include/Tactility/network/EspHttpClient.h b/Tactility/Include/Tactility/network/EspHttpClient.h index 9cd26c9a..c8d4b421 100644 --- a/Tactility/Include/Tactility/network/EspHttpClient.h +++ b/Tactility/Include/Tactility/network/EspHttpClient.h @@ -3,12 +3,13 @@ #ifdef ESP_PLATFORM #include +#include namespace tt::network { class EspHttpClient { - static constexpr auto* TAG = "EspHttpClient"; + const Logger logger = Logger("EspHttpClient"); std::unique_ptr config = nullptr; esp_http_client_handle_t client = nullptr; @@ -27,7 +28,7 @@ public: } bool init(std::unique_ptr inConfig) { - TT_LOG_I(TAG, "init(%s)", inConfig->url); + logger.info("init({})", inConfig->url); assert(this->config == nullptr); config = std::move(inConfig); client = esp_http_client_init(config.get()); @@ -36,11 +37,11 @@ public: bool open() { assert(client != nullptr); - TT_LOG_I(TAG, "open()"); + logger.info("open()"); auto result = esp_http_client_open(client, 0); if (result != ESP_OK) { - TT_LOG_E(TAG, "open() failed: %s", esp_err_to_name(result)); + logger.error("open() failed: {}", esp_err_to_name(result)); return false; } @@ -50,7 +51,7 @@ public: bool fetchHeaders() const { assert(client != nullptr); - TT_LOG_I(TAG, "fetchHeaders()"); + logger.info("fetchHeaders()"); return esp_http_client_fetch_headers(client) >= 0; } @@ -63,7 +64,7 @@ public: int getStatusCode() const { assert(client != nullptr); const auto status_code = esp_http_client_get_status_code(client); - TT_LOG_I(TAG, "Status code %d", status_code); + logger.info("Status code {}", status_code); return status_code; } @@ -74,19 +75,19 @@ public: int read(char* bytes, int size) const { assert(client != nullptr); - TT_LOG_I(TAG, "read(%d)", size); + logger.info("read({})", size); return esp_http_client_read(client, bytes, size); } int readResponse(char* bytes, int size) const { assert(client != nullptr); - TT_LOG_I(TAG, "readResponse(%d)", size); + logger.info("readResponse({})", size); return esp_http_client_read_response(client, bytes, size); } bool close() { assert(client != nullptr); - TT_LOG_I(TAG, "close()"); + logger.info("close()"); if (esp_http_client_close(client) == ESP_OK) { isOpen = false; } @@ -96,7 +97,7 @@ public: bool cleanup() { assert(client != nullptr); assert(!isOpen); - TT_LOG_I(TAG, "cleanup()"); + logger.info("cleanup()"); const auto result = esp_http_client_cleanup(client); client = nullptr; return result == ESP_OK; diff --git a/Tactility/Include/Tactility/network/Http.h b/Tactility/Include/Tactility/network/Http.h index 316d02e6..9be0ac78 100644 --- a/Tactility/Include/Tactility/network/Http.h +++ b/Tactility/Include/Tactility/network/Http.h @@ -17,8 +17,8 @@ namespace tt::network::http { const std::string& url, const std::string& certFilePath, const std::string &downloadFilePath, - std::function onSuccess, - std::function onError + const std::function& onSuccess, + const std::function& onError ); } diff --git a/Tactility/Private/Tactility/app/AppInstance.h b/Tactility/Private/Tactility/app/AppInstance.h index fc55a731..2df6a712 100644 --- a/Tactility/Private/Tactility/app/AppInstance.h +++ b/Tactility/Private/Tactility/app/AppInstance.h @@ -6,7 +6,7 @@ #include #include -#include +#include #include #include @@ -48,7 +48,7 @@ class AppInstance : public AppContext { return manifest->createApp(); } else if (manifest->appLocation.isExternal()) { if (manifest->createApp != nullptr) { - TT_LOG_W("", "Manifest specifies createApp, but this is not used with external apps"); + Logger("AppInstance").warn("Manifest specifies createApp, but this is not used with external apps"); } #ifdef ESP_PLATFORM return createElfApp(manifest); diff --git a/Tactility/Private/Tactility/json/Reader.h b/Tactility/Private/Tactility/json/Reader.h index 12644a24..0b2ad1fc 100644 --- a/Tactility/Private/Tactility/json/Reader.h +++ b/Tactility/Private/Tactility/json/Reader.h @@ -4,12 +4,14 @@ #include #include +#include + namespace tt::json { class Reader { const cJSON* root; - static constexpr const char* TAG = "json::Reader"; + Logger logger = Logger("json::Reader"); public: @@ -18,7 +20,7 @@ public: bool readString(const char* key, std::string& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsString(child)) { - TT_LOG_E(TAG, "%s is not a string", key); + logger.error("{} is not a string", key); return false; } output = cJSON_GetStringValue(child); @@ -30,7 +32,7 @@ public: if (!readNumber(key, buffer)) { return false; } - output = buffer; + output = static_cast(buffer); return true; } @@ -46,7 +48,7 @@ public: bool readNumber(const char* key, double& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsNumber(child)) { - TT_LOG_E(TAG, "%s is not a number", key); + logger.error("{} is not a number", key); return false; } output = cJSON_GetNumberValue(child); @@ -56,16 +58,16 @@ public: bool readStringArray(const char* key, std::vector& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsArray(child)) { - TT_LOG_E(TAG, "%s is not an array", key); + logger.error("{} is not an array", key); return false; } const auto size = cJSON_GetArraySize(child); - TT_LOG_I(TAG, "Processing %d array children", size); + logger.info("Processing {} array children", size); output.resize(size); for (int i = 0; i < size; ++i) { const auto string_json = cJSON_GetArrayItem(child, i); if (!cJSON_IsString(string_json)) { - TT_LOG_E(TAG, "array child of %s is not a string", key); + logger.error("Array child of {} is not a string", key); return false; } output[i] = cJSON_GetStringValue(string_json); diff --git a/Tactility/Source/PartitionsEsp.cpp b/Tactility/Source/PartitionsEsp.cpp index ac110e02..b1b79a5a 100644 --- a/Tactility/Source/PartitionsEsp.cpp +++ b/Tactility/Source/PartitionsEsp.cpp @@ -1,15 +1,14 @@ #ifdef ESP_PLATFORM -#include "Tactility/PartitionsEsp.h" - -#include +#include +#include #include #include namespace tt { -constexpr auto* TAG = "Partitions"; +static const auto LOGGER = Logger("Partitions"); static esp_err_t initNvsFlashSafely() { esp_err_t result = nvs_flash_init(); @@ -41,7 +40,7 @@ size_t getSectorSize() { } esp_err_t initPartitionsEsp() { - TT_LOG_I(TAG, "Init partitions"); + LOGGER.info("Init partitions"); ESP_ERROR_CHECK(initNvsFlashSafely()); const esp_vfs_fat_mount_config_t mount_config = { @@ -54,16 +53,16 @@ esp_err_t initPartitionsEsp() { auto system_result = esp_vfs_fat_spiflash_mount_ro("/system", "system", &mount_config); if (system_result != ESP_OK) { - TT_LOG_E(TAG, "Failed to mount /system (%s)", esp_err_to_name(system_result)); + LOGGER.error("Failed to mount /system ({})", esp_err_to_name(system_result)); } else { - TT_LOG_I(TAG, "Mounted /system"); + LOGGER.info("Mounted /system"); } auto data_result = esp_vfs_fat_spiflash_mount_rw_wl("/data", "data", &mount_config, &data_wl_handle); if (data_result != ESP_OK) { - TT_LOG_E(TAG, "Failed to mount /data (%s)", esp_err_to_name(data_result)); + LOGGER.error("Failed to mount /data ({})", esp_err_to_name(data_result)); } else { - TT_LOG_I(TAG, "Mounted /data"); + LOGGER.info("Mounted /data"); } return system_result == ESP_OK && data_result == ESP_OK; diff --git a/Tactility/Source/PreferencesEsp.cpp b/Tactility/Source/PreferencesEsp.cpp index 239a2d1e..61ead91c 100644 --- a/Tactility/Source/PreferencesEsp.cpp +++ b/Tactility/Source/PreferencesEsp.cpp @@ -1,5 +1,6 @@ #ifdef ESP_PLATFORM +#include #include #include @@ -7,12 +8,12 @@ namespace tt { -constexpr auto* TAG = "Preferences"; +static const auto LOGGER = Logger("Preferences"); bool Preferences::optBool(const std::string& key, bool& out) const { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); return false; } else { uint8_t out_number; @@ -28,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) { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); return false; } else { bool success = nvs_get_i32(handle, key.c_str(), &out) == ESP_OK; @@ -40,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) { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); return false; } else { bool success = nvs_get_i64(handle, key.c_str(), &out) == ESP_OK; @@ -52,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) { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); return false; } else { size_t out_size = 256; @@ -89,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) { - TT_LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to set {}:{}", namespace_, key); } else if (nvs_commit(handle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to commit {}:{}", namespace_, key); } nvs_close(handle); } else { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); } } @@ -103,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) { - TT_LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to set {}:{}", namespace_, key); } else if (nvs_commit(handle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to commit {}:{}", namespace_, key); } nvs_close(handle); } else { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); } } @@ -117,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) { - TT_LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to set {}:{}", namespace_, key); } else if (nvs_commit(handle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to commit {}:{}", namespace_, key); } nvs_close(handle); } else { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); } } @@ -131,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) { - TT_LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to set {}:{}", namespace_, key.c_str()); } else if (nvs_commit(handle) != ESP_OK) { - TT_LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); + LOGGER.error("Failed to commit {}:{}", namespace_, key); } nvs_close(handle); } else { - TT_LOG_E(TAG, "Failed to open namespace %s", namespace_); + LOGGER.error("Failed to open namespace {}", namespace_); } } diff --git a/Tactility/Source/PreferencesMock.cpp b/Tactility/Source/PreferencesMock.cpp index d6536079..a524cb65 100644 --- a/Tactility/Source/PreferencesMock.cpp +++ b/Tactility/Source/PreferencesMock.cpp @@ -1,7 +1,6 @@ #ifndef ESP_PLATFOM -#include "Tactility/Preferences.h" - +#include #include namespace tt { diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index d8ae7d23..a82faa22 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -5,15 +5,17 @@ #include #include -#include -#include #include #include +#include #include #include #include #include +#include +#include #include +#include #include #include #include @@ -29,7 +31,7 @@ namespace tt { -constexpr auto* TAG = "Tactility"; +static auto LOGGER = Logger("Tactility"); static const Configuration* config_instance = nullptr; static Dispatcher mainDispatcher; @@ -117,7 +119,7 @@ namespace app { // List of all apps excluding Boot app (as Boot app calls this function indirectly) static void registerInternalApps() { - TT_LOG_I(TAG, "Registering internal apps"); + LOGGER.info("Registering internal apps"); addAppManifest(app::alertdialog::manifest); addAppManifest(app::appdetails::manifest); @@ -178,22 +180,22 @@ static void registerInternalApps() { } static void registerInstalledApp(std::string path) { - TT_LOG_I(TAG, "Registering app at %s", path.c_str()); + LOGGER.info("Registering app at {}", path); std::string manifest_path = path + "/manifest.properties"; if (!file::isFile(manifest_path)) { - TT_LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str()); + LOGGER.error("Manifest not found at {}", manifest_path); return; } std::map properties; if (!file::loadPropertiesFile(manifest_path, properties)) { - TT_LOG_E(TAG, "Failed to load manifest at %s", manifest_path.c_str()); + LOGGER.error("Failed to load manifest at {}", manifest_path); return; } app::AppManifest manifest; if (!app::parseManifest(properties, manifest)) { - TT_LOG_E(TAG, "Failed to parse manifest at %s", manifest_path.c_str()); + LOGGER.error("Failed to parse manifest at {}", manifest_path); return; } @@ -204,7 +206,7 @@ static void registerInstalledApp(std::string path) { } static void registerInstalledApps(const std::string& path) { - TT_LOG_I(TAG, "Registering apps from %s", path.c_str()); + LOGGER.info("Registering apps from {}", path); file::listDirectory(path, [&path](const auto& entry) { auto absolute_path = std::format("{}/{}", path, entry.d_name); @@ -226,14 +228,14 @@ static void registerInstalledAppsFromSdCards() { auto sdcard_devices = hal::findDevices(hal::Device::Type::SdCard); for (const auto& sdcard : sdcard_devices) { if (sdcard->isMounted()) { - TT_LOG_I(TAG, "Registering apps from %s", sdcard->getMountPath().c_str()); + LOGGER.info("Registering apps from {}", sdcard->getMountPath()); registerInstalledAppsFromSdCard(sdcard); } } } static void registerAndStartSecondaryServices() { - TT_LOG_I(TAG, "Registering and starting system services"); + LOGGER.info("Registering and starting secondary system services"); addService(service::loader::manifest); addService(service::gui::manifest); addService(service::statusbar::manifest); @@ -248,7 +250,7 @@ static void registerAndStartSecondaryServices() { } static void registerAndStartPrimaryServices() { - TT_LOG_I(TAG, "Registering and starting system services"); + LOGGER.info("Registering and starting primary system services"); addService(service::gps::manifest); if (hal::hasDevice(hal::Device::Type::SdCard)) { addService(service::sdcard::manifest); @@ -269,15 +271,15 @@ void createTempDirectory(const std::string& rootPath) { auto lock = file::getLock(rootPath)->asScopedLock(); if (lock.lock(1000 / portTICK_PERIOD_MS)) { if (mkdir(temp_path.c_str(), 0777) == 0) { - TT_LOG_I(TAG, "Created %s", temp_path.c_str()); + LOGGER.info("Created {}", temp_path); } else { - TT_LOG_E(TAG, "Failed to create %s", temp_path.c_str()); + LOGGER.error("Failed to create {}", temp_path); } } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, rootPath.c_str()); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, rootPath); } } else { - TT_LOG_I(TAG, "Found existing %s", temp_path.c_str()); + LOGGER.info("Found existing {}", temp_path); } } @@ -305,7 +307,7 @@ void registerApps() { } void run(const Configuration& config) { - TT_LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID); + LOGGER.info("Tactility v{} on {} ({})", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID); assert(config.hardware); const hal::Configuration& hardware = *config.hardware; @@ -325,14 +327,14 @@ void run(const Configuration& config) { lvgl::init(hardware); registerAndStartSecondaryServices(); - TT_LOG_I(TAG, "Core systems ready"); + LOGGER.info("Core systems ready"); - TT_LOG_I(TAG, "Starting boot app"); + LOGGER.info("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); - TT_LOG_I(TAG, "Main dispatcher ready"); + LOGGER.info("Main dispatcher ready"); while (true) { mainDispatcher.consume(); } diff --git a/Tactility/Source/TactilityHeadlessEsp.cpp b/Tactility/Source/TactilityEsp.cpp similarity index 71% rename from Tactility/Source/TactilityHeadlessEsp.cpp rename to Tactility/Source/TactilityEsp.cpp index 32e64769..44111c9d 100644 --- a/Tactility/Source/TactilityHeadlessEsp.cpp +++ b/Tactility/Source/TactilityEsp.cpp @@ -1,7 +1,8 @@ #ifdef ESP_PLATFORM -#include "Tactility/PartitionsEsp.h" -#include "Tactility/TactilityCore.h" +#include +#include +#include #include "esp_event.h" #include "esp_netif.h" @@ -9,14 +10,14 @@ namespace tt { -constexpr auto* TAG = "Tactility"; +static auto LOGGER = Logger("Tactility"); // Initialize NVS static void initNvs() { - TT_LOG_I(TAG, "Init NVS"); + LOGGER.info("Init NVS"); esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { - TT_LOG_I(TAG, "NVS erasing"); + LOGGER.info("NVS erasing"); ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } @@ -24,7 +25,7 @@ static void initNvs() { } static void initNetwork() { - TT_LOG_I(TAG, "Init network"); + LOGGER.info("Init network"); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); } diff --git a/Tactility/Source/app/AppInstall.cpp b/Tactility/Source/app/AppInstall.cpp index 0a84d878..f3b87815 100644 --- a/Tactility/Source/app/AppInstall.cpp +++ b/Tactility/Source/app/AppInstall.cpp @@ -6,35 +6,32 @@ #include #include #include -#include +#include #include #include #include #include -#include #include -#include #include -#include #include #include -constexpr auto* TAG = "App"; - namespace tt::app { +static const auto LOGGER = Logger("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)) { - TT_LOG_E(TAG, "Can't find or create directory %s", destinationPath.c_str()); + LOGGER.error("Can't find or create directory {}", 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())) { - TT_LOG_E(TAG, "Failed to write data to %s", absolute_path.c_str()); + LOGGER.error("Failed to write data to {}", absolute_path.c_str()); return false; } @@ -63,32 +60,32 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath do { if (minitar_read_entry(&mp, &entry) == 0) { - TT_LOG_I(TAG, "Extracting %s", entry.metadata.path); + LOGGER.info("Extracting {}", 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)) { - TT_LOG_E(TAG, "Failed to create directory %s/%s: %s", destinationPath.c_str(), entry.metadata.name, strerror(errno)); + LOGGER.error("Failed to create directory {}/{}: {}", destinationPath, entry.metadata.name, strerror(errno)); success = false; break; } } else if (entry.metadata.type == MTAR_REGULAR) { if (!untarFile(&mp, &entry, destinationPath)) { - TT_LOG_E(TAG, "Failed to extract file %s: %s", entry.metadata.path, strerror(errno)); + LOGGER.error("Failed to extract file {}: {}", entry.metadata.path, strerror(errno)); success = false; break; } } else if (entry.metadata.type == MTAR_SYMLINK) { - TT_LOG_E(TAG, "SYMLINK not supported"); + LOGGER.error("SYMLINK not supported"); } else if (entry.metadata.type == MTAR_HARDLINK) { - TT_LOG_E(TAG, "HARDLINK not supported"); + LOGGER.error("HARDLINK not supported"); } else if (entry.metadata.type == MTAR_FIFO) { - TT_LOG_E(TAG, "FIFO not supported"); + LOGGER.error("FIFO not supported"); } else if (entry.metadata.type == MTAR_BLKDEV) { - TT_LOG_E(TAG, "BLKDEV not supported"); + LOGGER.error("BLKDEV not supported"); } else if (entry.metadata.type == MTAR_CHRDEV) { - TT_LOG_E(TAG, "CHRDEV not supported"); + LOGGER.error("CHRDEV not supported"); } else { - TT_LOG_E(TAG, "Unknown entry type: %d", entry.metadata.type); + LOGGER.error("Unknown entry type: {}", static_cast(entry.metadata.type)); success = false; break; } @@ -100,7 +97,7 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath void cleanupInstallDirectory(const std::string& path) { if (!file::deleteRecursively(path)) { - TT_LOG_W(TAG, "Failed to delete existing installation at %s", path.c_str()); + LOGGER.warn("Failed to delete existing installation at {}", path); } } @@ -109,16 +106,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(); - TT_LOG_I(TAG, "Installing app %s to %s", path.c_str(), app_parent_path.c_str()); + LOGGER.info("Installing app {} to {}", path, app_parent_path); 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)) { - TT_LOG_W(TAG, "Failed to delete %s", app_target_path.c_str()); + LOGGER.warn("Failed to delete {}", app_target_path); } if (!file::findOrCreateDirectory(app_target_path, 0777)) { - TT_LOG_I(TAG, "Failed to create directory %s", app_target_path.c_str()); + LOGGER.info("Failed to create directory {}", app_target_path); return false; } @@ -126,9 +123,9 @@ bool install(const std::string& path) { auto source_path_lock = file::getLock(path)->asScopedLock(); target_path_lock.lock(); source_path_lock.lock(); - TT_LOG_I(TAG, "Extracting app from %s to %s", path.c_str(), app_target_path.c_str()); + LOGGER.info("Extracting app from {} to {}", path, app_target_path); if (!untar(path, app_target_path)) { - TT_LOG_E(TAG, "Failed to extract"); + LOGGER.error("Failed to extract"); return false; } source_path_lock.unlock(); @@ -136,21 +133,21 @@ bool install(const std::string& path) { auto manifest_path = app_target_path + "/manifest.properties"; if (!file::isFile(manifest_path)) { - TT_LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str()); + LOGGER.error("Manifest not found at {}", manifest_path); cleanupInstallDirectory(app_target_path); return false; } std::map properties; if (!file::loadPropertiesFile(manifest_path, properties)) { - TT_LOG_E(TAG, "Failed to load manifest at %s", manifest_path.c_str()); + LOGGER.error("Failed to load manifest at {}", manifest_path); cleanupInstallDirectory(app_target_path); return false; } AppManifest manifest; if (!parseManifest(properties, manifest)) { - TT_LOG_W(TAG, "Invalid manifest"); + LOGGER.warn("Invalid manifest"); cleanupInstallDirectory(app_target_path); return false; } @@ -163,7 +160,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)) { - TT_LOG_W(TAG, "Failed to delete existing installation at %s", renamed_target_path.c_str()); + LOGGER.warn("Failed to delete existing installation at {}", renamed_target_path); cleanupInstallDirectory(app_target_path); return false; } @@ -174,7 +171,7 @@ bool install(const std::string& path) { target_path_lock.unlock(); if (!rename_success) { - TT_LOG_E(TAG, "Failed to rename \"%s\" to \"%s\"", app_target_path.c_str(), manifest.appId.c_str()); + LOGGER.error(R"(Failed to rename "{}" to "{}")", app_target_path, manifest.appId); cleanupInstallDirectory(app_target_path); return false; } @@ -187,7 +184,7 @@ bool install(const std::string& path) { } bool uninstall(const std::string& appId) { - TT_LOG_I(TAG, "Uninstalling app %s", appId.c_str()); + LOGGER.info("Uninstalling app {}", appId); // If the app was running, then stop it if (isRunning(appId)) { @@ -196,7 +193,7 @@ bool uninstall(const std::string& appId) { auto app_path = getAppInstallPath(appId); if (!file::isDirectory(app_path)) { - TT_LOG_E(TAG, "App %s not found at %s", appId.c_str(), app_path.c_str()); + LOGGER.error("App {} not found at {}", appId, app_path); return false; } @@ -205,7 +202,7 @@ bool uninstall(const std::string& appId) { } if (!removeAppManifest(appId)) { - TT_LOG_W(TAG, "Failed to remove app %s from registry", appId.c_str()); + LOGGER.warn("Failed to remove app {} from registry", appId); } return true; diff --git a/Tactility/Source/app/AppInstance.cpp b/Tactility/Source/app/AppInstance.cpp index d3d00c54..16acc888 100644 --- a/Tactility/Source/app/AppInstance.cpp +++ b/Tactility/Source/app/AppInstance.cpp @@ -3,8 +3,6 @@ namespace tt::app { -#define TAG "app" - void AppInstance::setState(State newState) { mutex.lock(); state = newState; diff --git a/Tactility/Source/app/AppManifestParsing.cpp b/Tactility/Source/app/AppManifestParsing.cpp index 7b4ccb23..4235b70d 100644 --- a/Tactility/Source/app/AppManifestParsing.cpp +++ b/Tactility/Source/app/AppManifestParsing.cpp @@ -1,25 +1,21 @@ #include -#include +#include +#include #include namespace tt::app { -constexpr auto* TAG = "App"; +static const auto LOGGER = Logger("AppManifest"); -static bool validateString(const std::string& value, const std::function& isValidChar) { - for (const auto& c : value) { - if (!isValidChar(c)) { - return false; - } - } - return true; +constexpr bool validateString(const std::string& value, const std::function& isValidChar) { + return std::ranges::all_of(value, isValidChar); } static bool getValueFromManifest(const std::map& map, const std::string& key, std::string& output) { const auto iterator = map.find(key); if (iterator == map.end()) { - TT_LOG_E(TAG, "Failed to find %s in manifest", key.c_str()); + LOGGER.error("Failed to find {} in manifest", key); return false; } output = iterator->second; @@ -33,19 +29,19 @@ bool isValidId(const std::string& id) { } static bool isValidManifestVersion(const std::string& version) { - return version.size() > 0 && validateString(version, [](const char c) { + return !version.empty() && validateString(version, [](const char c) { return std::isalnum(c) != 0 || c == '.'; }); } static bool isValidAppVersionName(const std::string& version) { - return version.size() > 0 && validateString(version, [](const char c) { + return !version.empty() && validateString(version, [](const char c) { return std::isalnum(c) != 0 || c == '.' || c == '-' || c == '_'; }); } static bool isValidAppVersionCode(const std::string& version) { - return version.size() > 0 && validateString(version, [](const char c) { + return !version.empty() && validateString(version, [](const char c) { return std::isdigit(c) != 0; }); } @@ -57,7 +53,7 @@ static bool isValidName(const std::string& name) { } bool parseManifest(const std::map& map, AppManifest& manifest) { - TT_LOG_I(TAG, "Parsing manifest"); + LOGGER.info("Parsing manifest"); // [manifest] @@ -67,7 +63,7 @@ bool parseManifest(const std::map& map, AppManifest& m } if (!isValidManifestVersion(manifest_version)) { - TT_LOG_E(TAG, "Invalid version"); + LOGGER.error("Invalid version"); return false; } @@ -78,7 +74,7 @@ bool parseManifest(const std::map& map, AppManifest& m } if (!isValidId(manifest.appId)) { - TT_LOG_E(TAG, "Invalid app id"); + LOGGER.error("Invalid app id"); return false; } @@ -87,7 +83,7 @@ bool parseManifest(const std::map& map, AppManifest& m } if (!isValidName(manifest.appName)) { - TT_LOG_I(TAG, "Invalid app name"); + LOGGER.error("Invalid app name"); return false; } @@ -96,7 +92,7 @@ bool parseManifest(const std::map& map, AppManifest& m } if (!isValidAppVersionName(manifest.appVersionName)) { - TT_LOG_E(TAG, "Invalid app version name"); + LOGGER.error("Invalid app version name"); return false; } @@ -106,7 +102,7 @@ bool parseManifest(const std::map& map, AppManifest& m } if (!isValidAppVersionCode(version_code_string)) { - TT_LOG_E(TAG, "Invalid app version code"); + LOGGER.error("Invalid app version code"); return false; } diff --git a/Tactility/Source/app/AppRegistration.cpp b/Tactility/Source/app/AppRegistration.cpp index 897546c6..1fa97976 100644 --- a/Tactility/Source/app/AppRegistration.cpp +++ b/Tactility/Source/app/AppRegistration.cpp @@ -1,27 +1,28 @@ -#include "Tactility/app/AppRegistration.h" -#include "Tactility/app/AppManifest.h" +#include +#include +#include #include #include #include -#define TAG "app" - namespace tt::app { +static const auto LOGGER = Logger("AppRegistration"); + typedef std::unordered_map> AppManifestMap; static AppManifestMap app_manifest_map; static Mutex hash_mutex; void addAppManifest(const AppManifest& manifest) { - TT_LOG_I(TAG, "Registering manifest %s", manifest.appId.c_str()); + LOGGER.info("Registering manifest {}", manifest.appId); hash_mutex.lock(); if (app_manifest_map.contains(manifest.appId)) { - TT_LOG_W(TAG, "Overwriting existing manifest for %s", manifest.appId.c_str()); + LOGGER.warn("Overwriting existing manifest for {}", manifest.appId); } app_manifest_map[manifest.appId] = std::make_shared(manifest); @@ -30,7 +31,7 @@ void addAppManifest(const AppManifest& manifest) { } bool removeAppManifest(const std::string& id) { - TT_LOG_I(TAG, "Removing manifest for %s", id.c_str()); + LOGGER.info("Removing manifest for {}", id); auto lock = hash_mutex.asScopedLock(); lock.lock(); diff --git a/Tactility/Source/app/ElfApp.cpp b/Tactility/Source/app/ElfApp.cpp index 927aedd3..384a9a99 100644 --- a/Tactility/Source/app/ElfApp.cpp +++ b/Tactility/Source/app/ElfApp.cpp @@ -4,18 +4,17 @@ #include #include #include -#include +#include #include #include #include - #include #include namespace tt::app { -constexpr auto* TAG = "ElfApp"; +static auto LOGGER = Logger("ElfApp"); static std::string getErrorCodeString(int error_code) { switch (error_code) { @@ -72,7 +71,7 @@ private: bool startElf() { const std::string elf_path = std::format("{}/elf/{}.elf", appPath, CONFIG_IDF_TARGET); - TT_LOG_I(TAG, "Starting ELF %s", elf_path.c_str()); + LOGGER.info("Starting ELF {}", elf_path); assert(elfFileData == nullptr); size_t size = 0; @@ -86,7 +85,7 @@ private: if (esp_elf_init(&elf) != ESP_OK) { lastError = "Failed to initialize"; - TT_LOG_E(TAG, "%s", lastError.c_str()); + LOGGER.error("{}", lastError); elfFileData = nullptr; return false; } @@ -95,7 +94,7 @@ private: if (relocate_result != 0) { // Note: the result code maps to values from cstdlib's errno.h lastError = getErrorCodeString(-relocate_result); - TT_LOG_E(TAG, "Application failed to load: %s", lastError.c_str()); + LOGGER.error("Application failed to load: {}", lastError); elfFileData = nullptr; return false; } @@ -105,7 +104,7 @@ private: if (esp_elf_request(&elf, 0, argc, argv) != ESP_OK) { lastError = "Executable returned error code"; - TT_LOG_E(TAG, "%s", lastError.c_str()); + LOGGER.error("{}", lastError); esp_elf_deinit(&elf); elfFileData = nullptr; return false; @@ -116,7 +115,7 @@ private: } void stopElf() { - TT_LOG_I(TAG, "Cleaning up ELF"); + LOGGER.info("Cleaning up ELF"); if (shouldCleanupElf) { esp_elf_deinit(&elf); @@ -164,7 +163,7 @@ public: } void onDestroy(AppContext& appContext) override { - TT_LOG_I(TAG, "Cleaning up app"); + LOGGER.info("Cleaning up app"); if (manifest != nullptr) { if (manifest->onDestroy != nullptr) { manifest->onDestroy(&appContext, data); @@ -223,7 +222,7 @@ void setElfAppParameters( } std::shared_ptr createElfApp(const std::shared_ptr& manifest) { - TT_LOG_I(TAG, "createElfApp"); + LOGGER.info("createElfApp"); assert(manifest != nullptr); assert(manifest->appLocation.isExternal()); return std::make_shared(manifest->appLocation.getPath()); diff --git a/Tactility/Source/app/addgps/AddGps.cpp b/Tactility/Source/app/addgps/AddGps.cpp index bd165f22..c589580c 100644 --- a/Tactility/Source/app/addgps/AddGps.cpp +++ b/Tactility/Source/app/addgps/AddGps.cpp @@ -1,23 +1,22 @@ -#include "Tactility/StringUtils.h" -#include "Tactility/app/AppManifest.h" -#include "Tactility/app/alertdialog/AlertDialog.h" -#include "Tactility/hal/gps/GpsDevice.h" -#include "Tactility/hal/uart/Uart.h" -#include "Tactility/lvgl/Style.h" -#include "Tactility/lvgl/Toolbar.h" -#include "Tactility/service/gps/GpsService.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include namespace tt::app::addgps { -constexpr const char* TAG = "AddGps"; +static const auto LOGGER = Logger("AddGps"); class AddGpsApp final : public App { -private: - lv_obj_t* uartDropdown = nullptr; lv_obj_t* modelDropdown = nullptr; lv_obj_t* baudDropdown = nullptr; @@ -48,7 +47,7 @@ private: return; } - TT_LOG_I(TAG, "Saving: uart=%s, model=%lu, baud=%lu", new_configuration.uartName, (uint32_t)new_configuration.model, new_configuration.baudRate); + LOGGER.info("Saving: uart={}, model={}, baud={}", new_configuration.uartName, (uint32_t)new_configuration.model, new_configuration.baudRate); auto service = service::gps::findGpsService(); std::vector configurations; diff --git a/Tactility/Source/app/alertdialog/AlertDialog.cpp b/Tactility/Source/app/alertdialog/AlertDialog.cpp index 27c09f9a..bbd09359 100644 --- a/Tactility/Source/app/alertdialog/AlertDialog.cpp +++ b/Tactility/Source/app/alertdialog/AlertDialog.cpp @@ -3,8 +3,8 @@ #include "Tactility/lvgl/Toolbar.h" #include "Tactility/service/loader/Loader.h" +#include #include -#include #include @@ -16,9 +16,9 @@ namespace tt::app::alertdialog { #define RESULT_BUNDLE_KEY_INDEX "index" #define PARAMETER_ITEM_CONCATENATION_TOKEN ";;" -#define DEFAULT_TITLE "Select..." +#define DEFAULT_TITLE "" -#define TAG "selection_dialog" +static const auto LOGGER = Logger("AlertDialog"); extern const AppManifest manifest; @@ -74,7 +74,7 @@ class AlertDialogApp : public App { void onButtonClicked(lv_event_t* e) { auto index = reinterpret_cast(lv_event_get_user_data(e)); - TT_LOG_I(TAG, "Selected item at index %d", index); + LOGGER.info("Selected item at index {}", index); auto bundle = std::make_unique(); bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, (int32_t)index); diff --git a/Tactility/Source/app/apphub/AppHubApp.cpp b/Tactility/Source/app/apphub/AppHubApp.cpp index 0a5ee588..f14ccf39 100644 --- a/Tactility/Source/app/apphub/AppHubApp.cpp +++ b/Tactility/Source/app/apphub/AppHubApp.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -16,7 +17,7 @@ namespace tt::app::apphub { -constexpr auto* TAG = "AppHub"; +static const auto LOGGER = Logger("AppHub"); extern const AppManifest manifest; @@ -55,7 +56,7 @@ class AppHubApp final : public App { } void onRefreshSuccess() { - TT_LOG_I(TAG, "Request success"); + LOGGER.info("Request success"); auto lock = lvgl::getSyncLock()->asScopedLock(); lock.lock(); @@ -63,7 +64,7 @@ class AppHubApp final : public App { } void onRefreshError(const char* error) { - TT_LOG_E(TAG, "Request failed: %s", error); + LOGGER.error("Request failed: {}", error); auto lock = lvgl::getSyncLock()->asScopedLock(); lock.lock(); @@ -106,7 +107,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]; - TT_LOG_I(TAG, "Adding %s", entry.appName.c_str()); + LOGGER.info("Adding {}", 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(i); diff --git a/Tactility/Source/app/apphub/AppHubEntry.cpp b/Tactility/Source/app/apphub/AppHubEntry.cpp index 68c6ada0..8f291f73 100644 --- a/Tactility/Source/app/apphub/AppHubEntry.cpp +++ b/Tactility/Source/app/apphub/AppHubEntry.cpp @@ -1,10 +1,11 @@ #include #include #include +#include namespace tt::app::apphub { -constexpr auto* TAG = "AppHubJson"; +static const auto LOGGER = Logger("AppHubJson"); static bool parseEntry(const cJSON* object, AppHubEntry& entry) { const json::Reader reader(object); @@ -24,21 +25,21 @@ bool parseJson(const std::string& filePath, std::vector& entries) { auto data = file::readString(filePath); if (data == nullptr) { - TT_LOG_E(TAG, "Failed to read %s", filePath.c_str()); + LOGGER.error("Failed to read {}", filePath); return false; } auto data_ptr = reinterpret_cast(data.get()); auto* json = cJSON_Parse(data_ptr); if (json == nullptr) { - TT_LOG_E(TAG, "Failed to parse %s", filePath.c_str()); + LOGGER.error("Failed to parse {}", filePath); return false; } const cJSON* apps_json = cJSON_GetObjectItemCaseSensitive(json, "apps"); if (!cJSON_IsArray(apps_json)) { cJSON_Delete(json); - TT_LOG_E(TAG, "apps is not an array"); + LOGGER.error("apps is not an array"); return false; } @@ -48,7 +49,7 @@ bool parseJson(const std::string& filePath, std::vector& entries) { auto& entry = entries.at(i); auto* entry_json = cJSON_GetArrayItem(apps_json, i); if (!parseEntry(entry_json, entry)) { - TT_LOG_E(TAG, "Failed to read entry"); + LOGGER.error("Failed to read entry"); cJSON_Delete(json); return false; } diff --git a/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp b/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp index 1bde0a75..980bb8e2 100644 --- a/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp +++ b/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -15,8 +16,9 @@ namespace tt::app::apphubdetails { +static const auto LOGGER = Logger("AppHubDetails"); + extern const AppManifest manifest; -constexpr auto* TAG = "AppHubDetails"; static std::shared_ptr toBundle(const apphub::AppHubEntry& entry) { auto bundle = std::make_shared(); @@ -83,7 +85,7 @@ class AppHubDetailsApp final : public App { } void uninstallApp() { - TT_LOG_I(TAG, "Uninstall"); + LOGGER.info("Uninstall"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); @@ -107,10 +109,10 @@ class AppHubDetailsApp final : public App { [this, temp_file_path] { install(temp_file_path); - if (!file::deleteFile(temp_file_path.c_str())) { - TT_LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str()); + if (!file::deleteFile(temp_file_path)) { + LOGGER.warn("Failed to remove {}", temp_file_path); } else { - TT_LOG_I(TAG, "Deleted temporary file %s", temp_file_path.c_str()); + LOGGER.info("Deleted temporary file {}", temp_file_path); } lvgl::getSyncLock()->lock(); @@ -118,18 +120,18 @@ class AppHubDetailsApp final : public App { lvgl::getSyncLock()->unlock(); }, [temp_file_path](const char* errorMessage) { - TT_LOG_E(TAG, "Download failed: %s", errorMessage); + LOGGER.error("Download failed: {}", errorMessage); alertdialog::start("Error", "Failed to install app"); if (file::isFile(temp_file_path) && !file::deleteFile(temp_file_path.c_str())) { - TT_LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str()); + LOGGER.warn("Failed to remove {}", temp_file_path); } } ); } void installApp() { - TT_LOG_I(TAG, "Install"); + LOGGER.info("Install"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); @@ -139,15 +141,15 @@ class AppHubDetailsApp final : public App { } void updateApp() { - TT_LOG_I(TAG, "Update"); + LOGGER.info("Update"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); lvgl::getSyncLock()->unlock(); - TT_LOG_I(TAG, "Removing previous version"); + LOGGER.info("Removing previous version"); uninstall(entry.appId); - TT_LOG_I(TAG, "Installing new version"); + LOGGER.info("Installing new version"); doInstall(); } @@ -173,13 +175,13 @@ public: void onCreate(AppContext& appContext) override { auto parameters = appContext.getParameters(); if (parameters == nullptr) { - TT_LOG_E(TAG, "No parameters"); + LOGGER.error("No parameters"); stop(); return; } if (!fromBundle(*parameters.get(), entry)) { - TT_LOG_E(TAG, "Invalid parameters"); + LOGGER.error("Invalid parameters"); stop(); } } diff --git a/Tactility/Source/app/boot/Boot.cpp b/Tactility/Source/app/boot/Boot.cpp index 5970929b..e4460249 100644 --- a/Tactility/Source/app/boot/Boot.cpp +++ b/Tactility/Source/app/boot/Boot.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -25,7 +26,8 @@ namespace tt::app::boot { -constexpr auto* TAG = "Boot"; +static const auto LOGGER = Logger("Boot"); + extern const AppManifest manifest; static std::shared_ptr getHalDisplay() { @@ -51,17 +53,17 @@ class BootApp : public App { if (settings::display::load(settings)) { if (hal_display->getGammaCurveCount() > 0) { hal_display->setGammaCurve(settings.gammaCurve); - TT_LOG_I(TAG, "Gamma curve %du", settings.gammaCurve); + LOGGER.info("Gamma curve {}", settings.gammaCurve); } } else { settings = settings::display::getDefault(); } if (hal_display->supportsBacklightDuty()) { - TT_LOG_I(TAG, "Backlight %du", settings.backlightDuty); + LOGGER.info("Backlight {}", settings.backlightDuty); hal_display->setBacklightDuty(settings.backlightDuty); } else { - TT_LOG_I(TAG, "no backlight"); + LOGGER.info("No backlight"); } } @@ -70,17 +72,17 @@ class BootApp : public App { return false; } - TT_LOG_I(TAG, "Rebooting into mass storage device mode"); + LOGGER.info("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()) { - TT_LOG_E(TAG, "Unable to start flash mass storage"); + LOGGER.error("Unable to start flash mass storage"); return false; } } else if (mode == hal::usb::BootMode::Sdmmc) { if (!hal::usb::startMassStorageWithSdmmc()) { - TT_LOG_E(TAG, "Unable to start SD mass storage"); + LOGGER.error("Unable to start SD mass storage"); return false; } } @@ -98,23 +100,22 @@ class BootApp : public App { } static int32_t bootThreadCallback() { - TT_LOG_I(TAG, "Starting boot thread"); + LOGGER.info("Starting boot thread"); const auto start_time = kernel::getTicks(); // Give the UI some time to redraw // If we don't do this, various init calls will read files and block SPI IO for the display // This would result in a blank/black screen being shown during this phase of the boot process // This works with 5 ms on a T-Lora Pager, so we give it 10 ms to be safe - TT_LOG_I(TAG, "Delay"); kernel::delayMillis(10); // TODO: Support for multiple displays - TT_LOG_I(TAG, "Setup display"); + LOGGER.info("Setup display"); setupDisplay(); // Set backlight prepareFileSystems(); if (!setupUsbBootMode()) { - TT_LOG_I(TAG, "initFromBootApp"); + LOGGER.info("initFromBootApp"); registerApps(); waitForMinimalSplashDuration(start_time); stop(manifest.appId); @@ -123,7 +124,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 - TT_LOG_I(TAG, "Publish event"); + LOGGER.info("Publish event"); kernel::publishSystemEvent(kernel::SystemEvent::BootSplash); return 0; @@ -140,7 +141,7 @@ class BootApp : public App { settings::BootSettings boot_properties; std::string launcher_app_id; if (settings::loadBootSettings(boot_properties) && boot_properties.launcherAppId.empty()) { - TT_LOG_E(TAG, "Failed to load launcher configuration, or launcher not configured"); + LOGGER.error("Failed to load launcher configuration, or launcher not configured"); launcher_app_id = boot_properties.launcherAppId; } else { launcher_app_id = "Launcher"; @@ -187,7 +188,7 @@ public: logo = hal::usb::isUsbBootMode() ? "logo_usb.png" : "logo.png"; } const auto logo_path = lvgl::PATH_PREFIX + paths->getAssetsPath(logo); - TT_LOG_I(TAG, "%s", logo_path.c_str()); + LOGGER.info("{}", logo_path); lv_image_set_src(image, logo_path.c_str()); } }; diff --git a/Tactility/Source/app/chat/ChatApp.cpp b/Tactility/Source/app/chat/ChatApp.cpp index 885db4bf..d79d91fa 100644 --- a/Tactility/Source/app/chat/ChatApp.cpp +++ b/Tactility/Source/app/chat/ChatApp.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "Tactility/lvgl/LvglSync.h" @@ -18,7 +19,7 @@ namespace tt::app::chat { -constexpr const char* TAG = "ChatApp"; +static const auto LOGGER = Logger("ChatApp"); constexpr uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; class ChatApp : public App { @@ -46,7 +47,7 @@ class ChatApp : public App { self->addMessage(msg); if (!service::espnow::send(BROADCAST_ADDRESS, reinterpret_cast(msg), msg_len)) { - TT_LOG_E(TAG, "Failed to send message"); + LOGGER.error("Failed to send message"); } lv_textarea_set_text(self->input_field, ""); diff --git a/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp b/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp index e179e3ee..16981ec4 100644 --- a/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp +++ b/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp @@ -1,20 +1,20 @@ #ifdef ESP_PLATFORM -#include "Tactility/hal/Device.h" - #include #include #include +#include +#include #include #include #include #include -#define TAG "CrashDiagnostics" - namespace tt::app::crashdiagnostics { +static const auto LOGGER = Logger("CrashDiagnostics"); + extern const AppManifest manifest; void onContinuePressed(TT_UNUSED lv_event_t* event) { @@ -44,38 +44,38 @@ public: lv_obj_align(bottom_label, LV_ALIGN_BOTTOM_MID, 0, -2); std::string url = getUrlFromCrashData(); - TT_LOG_I(TAG, "%s", url.c_str()); + LOGGER.info("{}", url); size_t url_length = url.length(); int qr_version; if (!getQrVersionForBinaryDataLength(url_length, qr_version)) { - TT_LOG_E(TAG, "QR is too large"); + LOGGER.error("QR is too large"); stop(manifest.appId); return; } - TT_LOG_I(TAG, "QR version %d (length: %d)", qr_version, url_length); + LOGGER.info("QR version {} (length: {})", qr_version, url_length); auto qrcodeData = std::make_shared(qrcode_getBufferSize(qr_version)); if (qrcodeData == nullptr) { - TT_LOG_E(TAG, "Failed to allocate QR buffer"); - stop(); + LOGGER.error("Failed to allocate QR buffer"); + stop(manifest.appId); return; } QRCode qrcode; - TT_LOG_I(TAG, "QR init text"); + LOGGER.info("QR init text"); if (qrcode_initText(&qrcode, qrcodeData.get(), qr_version, ECC_LOW, url.c_str()) != 0) { - TT_LOG_E(TAG, "QR init text failed"); + LOGGER.error("QR init text failed"); stop(manifest.appId); return; } - TT_LOG_I(TAG, "QR size: %d", qrcode.size); + LOGGER.info("QR size: {}", 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; - TT_LOG_I(TAG, "Create canvas"); + LOGGER.info("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 { - TT_LOG_E(TAG, "QR code won't fit screen"); + LOGGER.error("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); - TT_LOG_I(TAG, "Create draw buffer"); + LOGGER.info("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) { - TT_LOG_E(TAG, "Draw buffer alloc"); + LOGGER.error("Failed to allocate draw buffer"); stop(manifest.appId); return; } diff --git a/Tactility/Source/app/development/Development.cpp b/Tactility/Source/app/development/Development.cpp index 6ca32ca5..d2ddf5d4 100644 --- a/Tactility/Source/app/development/Development.cpp +++ b/Tactility/Source/app/development/Development.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -17,7 +18,7 @@ namespace tt::app::development { -constexpr const char* TAG = "Development"; +static const auto LOGGER = Logger("Development"); extern const AppManifest manifest; class DevelopmentApp final : public App { @@ -84,7 +85,7 @@ public: void onCreate(AppContext& appContext) override { service = service::development::findService(); if (service == nullptr) { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); stop(manifest.appId); } } diff --git a/Tactility/Source/app/display/Display.cpp b/Tactility/Source/app/display/Display.cpp index 3dbcd5b5..4361329e 100644 --- a/Tactility/Source/app/display/Display.cpp +++ b/Tactility/Source/app/display/Display.cpp @@ -3,13 +3,14 @@ #include #include #include +#include #include #include namespace tt::app::display { -constexpr auto* TAG = "Display"; +static const auto LOGGER = Logger("Display"); static std::shared_ptr getHalDisplay() { return hal::findFirstDevice(hal::Device::Type::Display); @@ -54,7 +55,7 @@ class DisplayApp final : public App { auto* app = static_cast(lv_event_get_user_data(event)); auto* dropdown = static_cast(lv_event_get_target(event)); uint32_t selected_index = lv_dropdown_get_selected(dropdown); - TT_LOG_I(TAG, "Selected %ld", selected_index); + LOGGER.info("Selected {}", selected_index); auto selected_orientation = static_cast(selected_index); if (selected_orientation != app->displaySettings.orientation) { app->displaySettings.orientation = selected_orientation; diff --git a/Tactility/Source/app/files/State.cpp b/Tactility/Source/app/files/State.cpp index 115d61c2..8a7bb485 100644 --- a/Tactility/Source/app/files/State.cpp +++ b/Tactility/Source/app/files/State.cpp @@ -3,18 +3,19 @@ #include #include #include -#include +#include +#include #include #include #include +#include #include #include -#include namespace tt::app::files { -constexpr auto* TAG = "Files"; +static const auto LOGGER = Logger("Files"); State::State() { if (kernel::getPlatform() == kernel::PlatformSimulator) { @@ -22,7 +23,7 @@ State::State() { if (getcwd(cwd, sizeof(cwd)) != nullptr) { setEntriesForPath(cwd); } else { - TT_LOG_E(TAG, "Failed to get current work directory files"); + LOGGER.error("Failed to get current work directory files"); setEntriesForPath("/"); } } else { @@ -37,11 +38,11 @@ std::string State::getSelectedChildPath() const { bool State::setEntriesForPath(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(100)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath"); return false; } - TT_LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str()); + LOGGER.info("Changing path: {} -> {}", current_path, path); /** * On PC, the root entry point ("/") is a folder. @@ -49,7 +50,7 @@ bool State::setEntriesForPath(const std::string& path) { */ bool get_mount_points = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/"); if (get_mount_points) { - TT_LOG_I(TAG, "Setting custom root"); + LOGGER.info("Setting custom root"); dir_entries = file::getMountPoints(); current_path = path; selected_child_entry = ""; @@ -59,13 +60,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) { - TT_LOG_I(TAG, "%s has %u entries", path.c_str(), count); + LOGGER.info("{} has {} entries", path, count); current_path = path; selected_child_entry = ""; action = ActionNone; return true; } else { - TT_LOG_E(TAG, "Failed to fetch entries for %s", path.c_str()); + LOGGER.error("Failed to fetch entries for {}", path); return false; } } @@ -73,7 +74,7 @@ bool State::setEntriesForPath(const std::string& path) { bool State::setEntriesForChildPath(const std::string& childPath) { auto path = file::getChildPath(current_path, childPath); - TT_LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str()); + LOGGER.info("Navigating from {} to {}", current_path, path); return setEntriesForPath(path); } @@ -90,4 +91,5 @@ bool State::getDirent(uint32_t index, dirent& dirent) { return false; } } + } diff --git a/Tactility/Source/app/files/View.cpp b/Tactility/Source/app/files/View.cpp index 24839a62..96d17a2f 100644 --- a/Tactility/Source/app/files/View.cpp +++ b/Tactility/Source/app/files/View.cpp @@ -2,21 +2,21 @@ #include #include -#include #include #include #include #include #include #include -#include +#include +#include #include #include #include #include -#include #include +#include #include #ifdef ESP_PLATFORM @@ -25,7 +25,7 @@ namespace tt::app::files { -constexpr auto* TAG = "Files"; +static const auto LOGGER = Logger("Files"); // region Callbacks @@ -84,11 +84,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) { - TT_LOG_E(TAG, "Failed to get current working directory"); + LOGGER.error("Failed to get current working directory"); return; } if (!file_path.starts_with(cwd)) { - TT_LOG_E(TAG, "Can only work with files in working directory %s", cwd); + LOGGER.error("Can only work with files in working directory {}", cwd); return; } processed_filepath = file_path.substr(strlen(cwd)); @@ -96,7 +96,7 @@ void View::viewFile(const std::string& path, const std::string& filename) { processed_filepath = file_path; } - TT_LOG_I(TAG, "Clicked %s", file_path.c_str()); + LOGGER.info("Clicked {}", file_path); if (isSupportedAppFile(filename)) { #ifdef ESP_PLATFORM @@ -116,7 +116,7 @@ void View::viewFile(const std::string& path, const std::string& filename) { notes::start(processed_filepath.substr(1)); } } else { - TT_LOG_W(TAG, "opening files of this type is not supported"); + LOGGER.warn("Opening files of this type is not supported"); } onNavigate(); @@ -125,7 +125,7 @@ void View::viewFile(const std::string& path, const std::string& filename) { void View::onDirEntryPressed(uint32_t index) { dirent dir_entry; if (state->getDirent(index, dir_entry)) { - TT_LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, dir_entry.d_type); + LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); using namespace tt::file; switch (dir_entry.d_type) { @@ -136,7 +136,7 @@ void View::onDirEntryPressed(uint32_t index) { update(); break; case TT_DT_LNK: - TT_LOG_W(TAG, "opening links is not supported"); + LOGGER.warn("opening links is not supported"); break; case TT_DT_REG: viewFile(state->getCurrentPath(), dir_entry.d_name); @@ -155,7 +155,7 @@ void View::onDirEntryPressed(uint32_t index) { void View::onDirEntryLongPressed(int32_t index) { dirent dir_entry; if (state->getDirent(index, dir_entry)) { - TT_LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, dir_entry.d_type); + LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); using namespace file; switch (dir_entry.d_type) { @@ -164,7 +164,7 @@ void View::onDirEntryLongPressed(int32_t index) { showActionsForDirectory(); break; case TT_DT_LNK: - TT_LOG_W(TAG, "opening links is not supported"); + LOGGER.warn("Opening links is not supported"); break; case TT_DT_REG: showActionsForFile(); @@ -228,7 +228,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) { void View::onNavigateUpPressed() { if (state->getCurrentPath() != "/") { - TT_LOG_I(TAG, "Navigating upwards"); + LOGGER.info("Navigating upwards"); std::string new_absolute_path; if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) { state->setEntriesForPath(new_absolute_path); @@ -240,14 +240,14 @@ void View::onNavigateUpPressed() { void View::onRenamePressed() { std::string entry_name = state->getSelectedChildEntry(); - TT_LOG_I(TAG, "Pending rename %s", entry_name.c_str()); + LOGGER.info("Pending rename {}", entry_name); state->setPendingAction(State::ActionRename); inputdialog::start("Rename", "", entry_name); } void View::onDeletePressed() { std::string file_path = state->getSelectedChildPath(); - TT_LOG_I(TAG, "Pending delete %s", file_path.c_str()); + LOGGER.info("Pending delete {}", file_path); state->setPendingAction(State::ActionDelete); std::string message = "Do you want to delete this?\n" + file_path; const std::vector choices = { "Yes", "No" }; @@ -255,13 +255,13 @@ void View::onDeletePressed() { } void View::onNewFilePressed() { - TT_LOG_I(TAG, "Creating new file"); + LOGGER.info("Creating new file"); state->setPendingAction(State::ActionCreateFile); inputdialog::start("New File", "Enter filename:", ""); } void View::onNewFolderPressed() { - TT_LOG_I(TAG, "Creating new folder"); + LOGGER.info("Creating new folder"); state->setPendingAction(State::ActionCreateFolder); inputdialog::start("New Folder", "Enter folder name:", ""); } @@ -295,7 +295,7 @@ void View::update() { state->withEntries([this](const std::vector& entries) { for (auto entry : entries) { - TT_LOG_D(TAG, "Entry: %s %d", entry.d_name, entry.d_type); + LOGGER.debug("Entry: {} {}", entry.d_name, entry.d_type); createDirEntryWidget(dir_entry_list, entry); } }); @@ -306,7 +306,7 @@ void View::update() { lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN); } } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); } } @@ -369,20 +369,20 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu } std::string filepath = state->getSelectedChildPath(); - TT_LOG_I(TAG, "Result for %s", filepath.c_str()); + LOGGER.info("Result for {}", filepath); switch (state->getPendingAction()) { case State::ActionDelete: { if (alertdialog::getResultIndex(*bundle) == 0) { if (file::isDirectory(filepath)) { if (!file::deleteRecursively(filepath)) { - TT_LOG_W(TAG, "Failed to delete %s", filepath.c_str()); + LOGGER.warn("Failed to delete {}", filepath); } } else if (file::isFile(filepath)) { auto lock = file::getLock(filepath); lock->lock(); if (remove(filepath.c_str()) <= 0) { - TT_LOG_W(TAG, "Failed to delete %s", filepath.c_str()); + LOGGER.warn("Failed to delete {}", filepath); } lock->unlock(); } @@ -399,9 +399,9 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu lock->lock(); std::string rename_to = file::getChildPath(state->getCurrentPath(), new_name); if (rename(filepath.c_str(), rename_to.c_str())) { - TT_LOG_I(TAG, "Renamed \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str()); + LOGGER.info("Renamed \"{}\" to \"{}\"", filepath, rename_to); } else { - TT_LOG_E(TAG, "Failed to rename \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str()); + LOGGER.error("Failed to rename \"{}\" to \"{}\"", filepath, rename_to); } lock->unlock(); @@ -420,7 +420,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu struct stat st; if (stat(new_file_path.c_str(), &st) == 0) { - TT_LOG_W(TAG, "File already exists: \"%s\"", new_file_path.c_str()); + LOGGER.warn("File already exists: \"{}\"", new_file_path); lock->unlock(); break; } @@ -428,9 +428,9 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu FILE* new_file = fopen(new_file_path.c_str(), "w"); if (new_file) { fclose(new_file); - TT_LOG_I(TAG, "Created file \"%s\"", new_file_path.c_str()); + LOGGER.info("Created file \"{}\"", new_file_path); } else { - TT_LOG_E(TAG, "Failed to create file \"%s\"", new_file_path.c_str()); + LOGGER.error("Failed to create file \"{}\"", new_file_path); } lock->unlock(); @@ -449,15 +449,15 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu struct stat st; if (stat(new_folder_path.c_str(), &st) == 0) { - TT_LOG_W(TAG, "Folder already exists: \"%s\"", new_folder_path.c_str()); + LOGGER.warn("Folder already exists: \"{}\"", new_folder_path); lock->unlock(); break; } if (mkdir(new_folder_path.c_str(), 0755) == 0) { - TT_LOG_I(TAG, "Created folder \"%s\"", new_folder_path.c_str()); + LOGGER.info("Created folder \"{}\"", new_folder_path); } else { - TT_LOG_E(TAG, "Failed to create folder \"%s\"", new_folder_path.c_str()); + LOGGER.error("Failed to create folder \"{}\"", new_folder_path); } lock->unlock(); diff --git a/Tactility/Source/app/fileselection/State.cpp b/Tactility/Source/app/fileselection/State.cpp index cc3c2b89..78b99747 100644 --- a/Tactility/Source/app/fileselection/State.cpp +++ b/Tactility/Source/app/fileselection/State.cpp @@ -2,7 +2,7 @@ #include #include "Tactility/hal/sdcard/SdCardDevice.h" -#include +#include #include #include @@ -13,7 +13,7 @@ namespace tt::app::fileselection { -constexpr auto* TAG = "FileSelection"; +static const auto LOGGER = Logger("FileSelection"); State::State() { if (kernel::getPlatform() == kernel::PlatformSimulator) { @@ -21,7 +21,7 @@ State::State() { if (getcwd(cwd, sizeof(cwd)) != nullptr) { setEntriesForPath(cwd); } else { - TT_LOG_E(TAG, "Failed to get current work directory files"); + LOGGER.error("Failed to get current work directory files"); setEntriesForPath("/"); } } else { @@ -34,7 +34,7 @@ std::string State::getSelectedChildPath() const { } bool State::setEntriesForPath(const std::string& path) { - TT_LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str()); + LOGGER.info("Changing path: {} -> {}", current_path, path); /** * ESP32 does not have a root directory, so we have to create it manually. @@ -42,7 +42,7 @@ bool State::setEntriesForPath(const std::string& path) { */ bool show_custom_root = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/"); if (show_custom_root) { - TT_LOG_I(TAG, "Setting custom root"); + LOGGER.info("Setting custom root"); dir_entries = file::getMountPoints(); current_path = path; selected_child_entry = ""; @@ -51,12 +51,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) { - TT_LOG_I(TAG, "%s has %u entries", path.c_str(), count); + LOGGER.info("{} has {} entries", path, count); current_path = path; selected_child_entry = ""; return true; } else { - TT_LOG_E(TAG, "Failed to fetch entries for %s", path.c_str()); + LOGGER.error("Failed to fetch entries for {}", path); return false; } } @@ -64,7 +64,7 @@ bool State::setEntriesForPath(const std::string& path) { bool State::setEntriesForChildPath(const std::string& childPath) { auto path = file::getChildPath(current_path, childPath); - TT_LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str()); + LOGGER.info("Navigating from {} to {}", current_path, path); return setEntriesForPath(path); } diff --git a/Tactility/Source/app/fileselection/View.cpp b/Tactility/Source/app/fileselection/View.cpp index 136f72ec..95cd43e8 100644 --- a/Tactility/Source/app/fileselection/View.cpp +++ b/Tactility/Source/app/fileselection/View.cpp @@ -1,14 +1,15 @@ #include #include +#include +#include +#include #include #include - -#include -#include -#include - #include +#include +#include + #include #include @@ -18,7 +19,7 @@ namespace tt::app::fileselection { -constexpr auto* TAG = "FileSelection"; +const static Logger LOGGER = Logger("FileSelection"); // region Callbacks @@ -45,11 +46,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) { - TT_LOG_E(TAG, "Failed to get current working directory"); + LOGGER.error("Failed to get current working directory"); return; } if (!file_path.starts_with(cwd)) { - TT_LOG_E(TAG, "Can only work with files in working directory %s", cwd); + LOGGER.error("Can only work with files in working directory {}", cwd); return; } processed_filepath = file_path.substr(strlen(cwd)); @@ -57,7 +58,7 @@ void View::onTapFile(const std::string& path, const std::string& filename) { processed_filepath = file_path; } - TT_LOG_I(TAG, "Clicked %s", processed_filepath.c_str()); + LOGGER.info("Clicked {}", processed_filepath); lv_textarea_set_text(path_textarea, processed_filepath.c_str()); } @@ -65,7 +66,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)) { - TT_LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, dir_entry.d_type); + LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); using namespace tt::file; switch (dir_entry.d_type) { @@ -76,7 +77,7 @@ void View::onDirEntryPressed(uint32_t index) { update(); break; case TT_DT_LNK: - TT_LOG_W(TAG, "opening links is not supported"); + LOGGER.warn("Opening links is not supported"); break; case TT_DT_REG: onTapFile(state->getCurrentPath(), dir_entry.d_name); @@ -94,7 +95,7 @@ void View::onSelectButtonPressed(lv_event_t* event) { auto* view = static_cast(lv_event_get_user_data(event)); const char* path = lv_textarea_get_text(view->path_textarea); if (path == nullptr || strlen(path) == 0) { - TT_LOG_W(TAG, "Select pressed, but not path found in textarea"); + LOGGER.warn("Select pressed, but not path found in textarea"); return; } @@ -138,7 +139,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) { void View::onNavigateUpPressed() { if (state->getCurrentPath() != "/") { - TT_LOG_I(TAG, "Navigating upwards"); + LOGGER.info("Navigating upwards"); std::string new_absolute_path; if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) { state->setEntriesForPath(new_absolute_path); @@ -159,7 +160,7 @@ void View::update() { state->withEntries([this](const std::vector& entries) { for (auto entry : entries) { - TT_LOG_D(TAG, "Entry: %s %d", entry.d_name, entry.d_type); + LOGGER.debug("Entry: {} {}", entry.d_name, entry.d_type); createDirEntryWidget(dir_entry_list, entry); } }); @@ -170,7 +171,7 @@ void View::update() { lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN); } } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); } } diff --git a/Tactility/Source/app/gpssettings/GpsSettings.cpp b/Tactility/Source/app/gpssettings/GpsSettings.cpp index 54bc89b2..2316648b 100644 --- a/Tactility/Source/app/gpssettings/GpsSettings.cpp +++ b/Tactility/Source/app/gpssettings/GpsSettings.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -23,7 +24,7 @@ extern const AppManifest manifest; class GpsSettingsApp final : public App { - static constexpr auto* TAG = "GpsSettings"; + const Logger logger = Logger("GpsSettings"); std::unique_ptr timer; std::shared_ptr appReference = std::make_shared(this); @@ -92,8 +93,8 @@ class GpsSettingsApp final : public App { std::vector configurations; auto gps_service = service::gps::findGpsService(); if (gps_service && gps_service->getGpsConfigurations(configurations)) { - TT_LOG_I(TAG, "Found service and configs %d %d", index, configurations.size()); - if (index <= configurations.size()) { + Logger("GpsSettings").info("Found service and configs {} {}", index, configurations.size()); + if (index < configurations.size()) { if (gps_service->removeGpsConfiguration(configurations[index])) { app->updateViews(); } else { @@ -154,7 +155,7 @@ class GpsSettingsApp final : public App { // Update toolbar switch (state) { case service::gps::State::OnPending: - TT_LOG_D(TAG, "OnPending"); + logger.debug("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); @@ -163,7 +164,7 @@ class GpsSettingsApp final : public App { lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::On: - TT_LOG_D(TAG, "On"); + logger.debug("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); @@ -172,7 +173,7 @@ class GpsSettingsApp final : public App { lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::OffPending: - TT_LOG_D(TAG, "OffPending"); + logger.debug("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); @@ -181,7 +182,7 @@ class GpsSettingsApp final : public App { lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::Off: - TT_LOG_D(TAG, "Off"); + logger.debug("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); @@ -254,11 +255,11 @@ class GpsSettingsApp final : public App { if (wants_on != is_on) { // start/stop are potentially blocking calls, so we use a dispatcher to not block the UI if (wants_on) { - getMainDispatcher().dispatch([this]() { + getMainDispatcher().dispatch([this] { service->startReceiving(); }); } else { - getMainDispatcher().dispatch([this]() { + getMainDispatcher().dispatch([this] { service->stopReceiving(); }); } diff --git a/Tactility/Source/app/i2cscanner/I2cScanner.cpp b/Tactility/Source/app/i2cscanner/I2cScanner.cpp index fea6fba7..e0698b2d 100644 --- a/Tactility/Source/app/i2cscanner/I2cScanner.cpp +++ b/Tactility/Source/app/i2cscanner/I2cScanner.cpp @@ -1,17 +1,18 @@ #include #include -#include +#include #include #include +#include +#include #include #include -#include - -#include -#include +#include #include +#include #include +#include #include @@ -21,6 +22,8 @@ extern const AppManifest manifest; class I2cScannerApp final : public App { + const Logger logger = Logger("I2cScanner"); + static constexpr auto* START_SCAN_TEXT = "Scan"; static constexpr auto* STOP_SCAN_TEXT = "Stop scan"; @@ -189,7 +192,7 @@ bool I2cScannerApp::getPort(i2c_port_t* outPort) { mutex.unlock(); return true; } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "getPort"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "getPort"); return false; } } @@ -200,7 +203,7 @@ bool I2cScannerApp::addAddressToList(uint8_t address) { mutex.unlock(); return true; } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "addAddressToList"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "addAddressToList"); return false; } } @@ -216,24 +219,24 @@ bool I2cScannerApp::shouldStopScanTimer() { } void I2cScannerApp::onScanTimer() { - TT_LOG_I(TAG, "Scan thread started"); + logger.info("Scan thread started"); i2c_port_t safe_port; if (!getPort(&safe_port)) { - TT_LOG_E(TAG, "Failed to get I2C port"); + logger.error("Failed to get I2C port"); onScanTimerFinished(); return; } if (!hal::i2c::isStarted(safe_port)) { - TT_LOG_E(TAG, "I2C port not started"); + logger.error("I2C port not started"); onScanTimerFinished(); return; } for (uint8_t address = 0; address < 128; ++address) { - if (hal::i2c::masterHasDeviceAtAddress(port, address, 10 / portTICK_PERIOD_MS)) { - TT_LOG_I(TAG, "Found device at address 0x%02X", address); + if (hal::i2c::masterHasDeviceAtAddress(safe_port, address, 10 / portTICK_PERIOD_MS)) { + logger.info("Found device at address 0x{:02X}", address); if (!shouldStopScanTimer()) { addAddressToList(address); } else { @@ -246,11 +249,11 @@ void I2cScannerApp::onScanTimer() { } } - TT_LOG_I(TAG, "Scan thread finalizing"); + logger.info("Scan thread finalizing"); onScanTimerFinished(); - TT_LOG_I(TAG, "Scan timer done"); + logger.info("Scan timer done"); } bool I2cScannerApp::hasScanThread() { @@ -261,7 +264,7 @@ bool I2cScannerApp::hasScanThread() { return has_thread; } else { // Unsafe way - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "hasScanTimer"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "hasScanTimer"); return scanTimer != nullptr; } } @@ -284,7 +287,7 @@ void I2cScannerApp::startScanning() { scanTimer->start(); mutex.unlock(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "startScanning"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "startScanning"); } } void I2cScannerApp::stopScanning() { @@ -293,7 +296,7 @@ void I2cScannerApp::stopScanning() { scanState = ScanStateStopped; mutex.unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + logger.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); } } @@ -314,7 +317,7 @@ void I2cScannerApp::selectBus(int32_t selected) { mutex.unlock(); } - TT_LOG_I(TAG, "Selected %ld", selected); + logger.info("Selected {}", selected); setLastBusIndex(selected); startScanning(); @@ -377,7 +380,7 @@ void I2cScannerApp::updateViews() { mutex.unlock(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViews"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViews"); } } @@ -386,7 +389,7 @@ void I2cScannerApp::updateViewsSafely() { updateViews(); lvgl::unlock(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViewsSafely"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViewsSafely"); } } @@ -399,7 +402,7 @@ void I2cScannerApp::onScanTimerFinished() { updateViewsSafely(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "onScanTimerFinished"); + logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "onScanTimerFinished"); } } diff --git a/Tactility/Source/app/imageviewer/ImageViewer.cpp b/Tactility/Source/app/imageviewer/ImageViewer.cpp index 1922239f..401d30ad 100644 --- a/Tactility/Source/app/imageviewer/ImageViewer.cpp +++ b/Tactility/Source/app/imageviewer/ImageViewer.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include @@ -11,7 +11,7 @@ namespace tt::app::imageviewer { extern const AppManifest manifest; -constexpr auto* TAG = "ImageViewer"; +static const auto LOGGER = Logger("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; - TT_LOG_I(TAG, "Opening %s", prefixed_path.c_str()); + LOGGER.info("Opening {}", prefixed_path); lv_img_set_src(image, prefixed_path.c_str()); auto path = string::getLastPathSegment(file_argument); lv_label_set_text(file_label, path.c_str()); diff --git a/Tactility/Source/app/inputdialog/InputDialog.cpp b/Tactility/Source/app/inputdialog/InputDialog.cpp index 75f3b207..a330bb52 100644 --- a/Tactility/Source/app/inputdialog/InputDialog.cpp +++ b/Tactility/Source/app/inputdialog/InputDialog.cpp @@ -15,7 +15,7 @@ constexpr auto* RESULT_BUNDLE_KEY_RESULT = "result"; constexpr auto* DEFAULT_TITLE = "Input"; -constexpr auto* TAG = "InputDialog"; +static const auto LOGGER = Logger("InputDialog"); extern const AppManifest manifest; class InputDialogApp; @@ -62,7 +62,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; - TT_LOG_I(TAG, "Selected item at index %d", index); + LOGGER.info("Selected item at index {}", index); if (index == 0) { auto bundle = std::make_unique(); const char* text = lv_textarea_get_text((lv_obj_t*)user_data); diff --git a/Tactility/Source/app/launcher/Launcher.cpp b/Tactility/Source/app/launcher/Launcher.cpp index dee92d9f..6bb705aa 100644 --- a/Tactility/Source/app/launcher/Launcher.cpp +++ b/Tactility/Source/app/launcher/Launcher.cpp @@ -12,7 +12,7 @@ namespace tt::app::launcher { -constexpr auto* TAG = "Launcher"; +static const auto LOGGER = Logger("Launcher"); static int getButtonSize(hal::UiScale scale) { if (scale == hal::UiScale::Smallest) { @@ -93,7 +93,7 @@ public: void onCreate(TT_UNUSED AppContext& app) override { settings::BootSettings boot_properties; if (settings::loadBootSettings(boot_properties) && !boot_properties.autoStartAppId.empty()) { - TT_LOG_I(TAG, "Starting %s", boot_properties.autoStartAppId.c_str()); + LOGGER.info("Starting {}", boot_properties.autoStartAppId); start(boot_properties.autoStartAppId); } } diff --git a/Tactility/Source/app/notes/Notes.cpp b/Tactility/Source/app/notes/Notes.cpp index f40f0679..bd3068c0 100644 --- a/Tactility/Source/app/notes/Notes.cpp +++ b/Tactility/Source/app/notes/Notes.cpp @@ -12,7 +12,7 @@ namespace tt::app::notes { -constexpr auto* TAG = "Notes"; +static const auto LOGGER = Logger("Notes"); constexpr auto* NOTES_FILE_ARGUMENT = "file"; class NotesApp final : public App { @@ -52,11 +52,11 @@ class NotesApp final : public App { saveBuffer = lv_textarea_get_text(uiNoteText); lvgl::getSyncLock()->unlock(); saveFileLaunchId = fileselection::startForExistingOrNewFile(); - TT_LOG_I(TAG, "launched with id %d", loadFileLaunchId); + LOGGER.info("launched with id {}", saveFileLaunchId); break; case 3: // Load loadFileLaunchId = fileselection::startForExistingFile(); - TT_LOG_I(TAG, "launched with id %d", loadFileLaunchId); + LOGGER.info("launched with id {}", loadFileLaunchId); break; } } else { @@ -64,7 +64,7 @@ class NotesApp final : public App { if (obj == cont) return; if (lv_obj_get_child(cont, 1)) { saveFileLaunchId = fileselection::startForExistingOrNewFile(); - TT_LOG_I(TAG, "launched with id %d", loadFileLaunchId); + LOGGER.info("launched with id {}", saveFileLaunchId); } else { //Reset resetFileContent(); } @@ -91,7 +91,7 @@ class NotesApp final : public App { lv_textarea_set_text(uiNoteText, reinterpret_cast(data.get())); lv_label_set_text(uiCurrentFileName, path.c_str()); filePath = path; - TT_LOG_I(TAG, "Loaded from %s", path.c_str()); + LOGGER.info("Loaded from {}", path); } }); } @@ -101,7 +101,7 @@ class NotesApp final : public App { bool result = false; file::getLock(path)->withLock([&result, this, path] { if (file::writeString(path, saveBuffer.c_str())) { - TT_LOG_I(TAG, "Saved to %s", path.c_str()); + LOGGER.info("Saved to {}", path); filePath = path; result = true; } @@ -186,7 +186,7 @@ class NotesApp final : public App { } void onResult(AppContext& appContext, LaunchId launchId, Result result, std::unique_ptr resultData) override { - TT_LOG_I(TAG, "Result for launch id %d", launchId); + LOGGER.info("Result for launch id {}", launchId); if (launchId == loadFileLaunchId) { loadFileLaunchId = 0; if (result == Result::Ok && resultData != nullptr) { diff --git a/Tactility/Source/app/screenshot/Screenshot.cpp b/Tactility/Source/app/screenshot/Screenshot.cpp index 346a0025..82d172e9 100644 --- a/Tactility/Source/app/screenshot/Screenshot.cpp +++ b/Tactility/Source/app/screenshot/Screenshot.cpp @@ -9,15 +9,16 @@ #include #include #include +#include #include #include #include #include -constexpr auto* TAG = "Screenshot"; - namespace tt::app::screenshot { +static const auto LOGGER = Logger("Screenshot"); + extern const AppManifest manifest; class ScreenshotApp final : public App { @@ -97,27 +98,27 @@ void ScreenshotApp::onModeSet() { void ScreenshotApp::onStartPressed() { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - TT_LOG_E(TAG, "Service not found/running"); + LOGGER.error("Service not found/running"); return; } if (service->isTaskStarted()) { - TT_LOG_I(TAG, "Stop screenshot"); + LOGGER.info("Stop screenshot"); service->stop(); } else { uint32_t selected = lv_dropdown_get_selected(modeDropdown); const char* path = lv_textarea_get_text(pathTextArea); if (selected == 0) { - TT_LOG_I(TAG, "Start timed screenshots"); + LOGGER.info("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 { - TT_LOG_W(TAG, "Ignored screenshot start because delay was 0"); + LOGGER.warn("Ignored screenshot start because delay was 0"); } } else { - TT_LOG_I(TAG, "Start app screenshots"); + LOGGER.info("Start app screenshots"); service->startApps(path); } } @@ -128,7 +129,7 @@ void ScreenshotApp::onStartPressed() { void ScreenshotApp::updateScreenshotMode() { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - TT_LOG_E(TAG, "Service not found/running"); + LOGGER.error("Service not found/running"); return; } @@ -151,7 +152,7 @@ void ScreenshotApp::updateScreenshotMode() { void ScreenshotApp::createModeSettingWidgets(lv_obj_t* parent) { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - TT_LOG_E(TAG, "Service not found/running"); + LOGGER.error("Service not found/running"); return; } @@ -203,7 +204,7 @@ void ScreenshotApp::createFilePathWidgets(lv_obj_t* parent) { if (kernel::getPlatform() == kernel::PlatformEsp) { auto sdcard_devices = tt::hal::findDevices(tt::hal::Device::Type::SdCard); if (sdcard_devices.size() > 1) { - TT_LOG_W(TAG, "Found multiple SD card devices - picking first"); + LOGGER.warn("Found multiple SD card devices - picking first"); } if (!sdcard_devices.empty() && sdcard_devices.front()->isMounted()) { std::string lvgl_mount_path = lvgl::PATH_PREFIX + sdcard_devices.front()->getMountPath(); diff --git a/Tactility/Source/app/selectiondialog/SelectionDialog.cpp b/Tactility/Source/app/selectiondialog/SelectionDialog.cpp index 4bae6773..0cd15a70 100644 --- a/Tactility/Source/app/selectiondialog/SelectionDialog.cpp +++ b/Tactility/Source/app/selectiondialog/SelectionDialog.cpp @@ -1,9 +1,9 @@ #include +#include #include #include #include -#include #include @@ -16,7 +16,7 @@ constexpr auto* RESULT_BUNDLE_KEY_INDEX = "index"; constexpr auto* PARAMETER_ITEM_CONCATENATION_TOKEN = ";;"; constexpr auto* DEFAULT_TITLE = "Select..."; -constexpr auto* TAG = "SelectionDialog"; +static const auto LOGGER = Logger("SelectionDialog"); extern const AppManifest manifest; @@ -53,7 +53,7 @@ class SelectionDialogApp final : public App { void onListItemSelected(lv_event_t* e) { auto index = reinterpret_cast(lv_event_get_user_data(e)); - TT_LOG_I(TAG, "Selected item at index %d", index); + LOGGER.info("Selected item at index {}", index); auto bundle = std::make_unique(); 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 items = string::split(items_concatenated, PARAMETER_ITEM_CONCATENATION_TOKEN); if (items.empty() || items.front().empty()) { - TT_LOG_E(TAG, "No items provided"); + LOGGER.error("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); - TT_LOG_W(TAG, "Auto-selecting single item"); + LOGGER.warn("Auto-selecting single item"); } else { size_t index = 0; for (const auto& item: items) { @@ -101,7 +101,7 @@ public: } } } else { - TT_LOG_E(TAG, "No items provided"); + LOGGER.error("No items provided"); setResult(Result::Error); stop(manifest.appId); } diff --git a/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp b/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp index bc521ebb..df98d8bc 100644 --- a/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp +++ b/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp @@ -1,9 +1,10 @@ #include #include #include +#include #include -#include #include +#include #include #include #include @@ -12,7 +13,7 @@ namespace tt::app::timedatesettings { -constexpr auto* TAG = "TimeDate"; +static const auto LOGGER = Logger("TimeDate"); extern const AppManifest manifest; @@ -137,7 +138,7 @@ public: if (result == Result::Ok && bundle != nullptr) { const auto name = timezone::getResultName(*bundle); const auto code = timezone::getResultCode(*bundle); - TT_LOG_I(TAG, "Result name=%s code=%s", name.c_str(), code.c_str()); + LOGGER.info("Result name={} code={}", name, code); settings::setTimeZone(name, code); if (!name.empty()) { diff --git a/Tactility/Source/app/timezone/TimeZone.cpp b/Tactility/Source/app/timezone/TimeZone.cpp index 7de026c8..5059cb9a 100644 --- a/Tactility/Source/app/timezone/TimeZone.cpp +++ b/Tactility/Source/app/timezone/TimeZone.cpp @@ -2,21 +2,23 @@ #include #include #include +#include +#include #include #include #include -#include - -#include #include +#include #include +#include #include #include namespace tt::app::timezone { -constexpr auto* TAG = "TimeZone"; +static const auto LOGGER = Logger("TimeZone"); + constexpr auto* RESULT_BUNDLE_CODE_INDEX = "code"; constexpr auto* RESULT_BUNDLE_NAME_INDEX = "name"; @@ -96,7 +98,7 @@ class TimeZoneApp final : public App { } void onListItemSelected(std::size_t index) { - TT_LOG_I(TAG, "Selected item at index %zu", index); + LOGGER.info("Selected item at index {}", index); auto& entry = entries[index]; @@ -117,7 +119,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) { - TT_LOG_E(TAG, "Failed to open %s", path.c_str()); + LOGGER.error("Failed to open {}", path); return; } char line[96]; @@ -138,7 +140,7 @@ class TimeZoneApp final : public App { } } } else { - TT_LOG_E(TAG, "Parse error at line %lu", count); + LOGGER.error("Parse error at line {}", count); } } @@ -148,10 +150,10 @@ class TimeZoneApp final : public App { entries = std::move(new_entries); mutex.unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); } - TT_LOG_I(TAG, "Processed %lu entries", count); + LOGGER.info("Processed {} entries", count); } void updateList() { @@ -160,7 +162,7 @@ class TimeZoneApp final : public App { readTimeZones(filter); lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); return; } diff --git a/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp b/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp index bb2e8f02..eba75f7c 100644 --- a/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp +++ b/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp @@ -6,15 +6,16 @@ #include #include #include +#include +#include #include #include -#include #include namespace tt::app::wifiapsettings { -constexpr auto* TAG = "WifiApSettings"; +static const auto LOGGER = Logger("WifiApSettings"); extern const AppManifest manifest; @@ -50,10 +51,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)) { - TT_LOG_E(TAG, "Failed to save settings"); + LOGGER.error("Failed to save settings"); } } else { - TT_LOG_E(TAG, "Failed to load settings"); + LOGGER.error("Failed to load settings"); } } @@ -89,7 +90,7 @@ class WifiApSettings : public App { updateViews(); lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } } @@ -192,7 +193,7 @@ public: lv_obj_remove_state(auto_connect_switch, LV_STATE_CHECKED); } } else { - TT_LOG_W(TAG, "No settings found"); + LOGGER.warn("No settings found"); lv_obj_add_flag(forget_button, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(auto_connect_wrapper, LV_OBJ_FLAG_HIDDEN); } @@ -223,11 +224,11 @@ public: std::string ssid = parameters->getString("ssid"); if (!service::wifi::settings::remove(ssid.c_str())) { - TT_LOG_E(TAG, "Failed to remove SSID"); + LOGGER.error("Failed to remove SSID"); return; } - TT_LOG_I(TAG, "Removed SSID"); + LOGGER.info("Removed SSID"); if ( service::wifi::getRadioState() == service::wifi::RadioState::ConnectionActive && service::wifi::getConnectionTarget() == ssid diff --git a/Tactility/Source/app/wificonnect/View.cpp b/Tactility/Source/app/wificonnect/View.cpp index 92c2c048..9f79dcb0 100644 --- a/Tactility/Source/app/wificonnect/View.cpp +++ b/Tactility/Source/app/wificonnect/View.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -12,7 +13,7 @@ namespace tt::app::wificonnect { -constexpr auto* TAG = "WifiConnect"; +static const auto LOGGER = Logger("WifiConnect"); void View::resetErrors() { lv_obj_add_flag(password_error, LV_OBJ_FLAG_HIDDEN); @@ -30,7 +31,7 @@ static void onConnect(TT_UNUSED 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) { - TT_LOG_E(TAG, "SSID too long"); + LOGGER.error("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; @@ -39,7 +40,7 @@ static void onConnect(TT_UNUSED 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) { - TT_LOG_E(TAG, "Password too long"); + LOGGER.error("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; @@ -199,7 +200,7 @@ void View::init(AppContext& app, lv_obj_t* parent) { } std::string password; - if (optPasswordParameter(bundle, ssid)) { + if (optPasswordParameter(bundle, password)) { lv_textarea_set_text(password_textarea, password.c_str()); } } diff --git a/Tactility/Source/app/wificonnect/WifiConnect.cpp b/Tactility/Source/app/wificonnect/WifiConnect.cpp index 65b6fb28..3bd24f7a 100644 --- a/Tactility/Source/app/wificonnect/WifiConnect.cpp +++ b/Tactility/Source/app/wificonnect/WifiConnect.cpp @@ -1,13 +1,15 @@ #include +#include +#include #include +#include #include #include -#include namespace tt::app::wificonnect { -constexpr auto* TAG = "WifiConnect"; +static const auto LOGGER = Logger("WifiConnect"); constexpr auto* WIFI_CONNECT_PARAM_SSID = "ssid"; // String constexpr auto* WIFI_CONNECT_PARAM_PASSWORD = "password"; // String @@ -72,7 +74,7 @@ void WifiConnect::requestViewUpdate() { view.update(); lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } unlock(); diff --git a/Tactility/Source/app/wifimanage/View.cpp b/Tactility/Source/app/wifimanage/View.cpp index b921db24..159d839e 100644 --- a/Tactility/Source/app/wifimanage/View.cpp +++ b/Tactility/Source/app/wifimanage/View.cpp @@ -1,24 +1,20 @@ #include #include - -#include #include - +#include #include #include - -#include #include +#include #include #include #include -#include namespace tt::app::wifimanage { -constexpr auto* TAG = "WifiManageView"; +static const auto LOGGER = Logger("WifiManageView"); std::shared_ptr _Nullable optWifiManage(); @@ -70,16 +66,16 @@ static void onConnectToHiddenClicked(lv_event_t* event) { // region Secondary updates void View::connect(lv_event_t* event) { - TT_LOG_D(TAG, "connect()"); + LOGGER.debug("connect()"); auto* widget = lv_event_get_current_target_obj(event); auto index = reinterpret_cast(lv_obj_get_user_data(widget)); auto* self = static_cast(lv_event_get_user_data(event)); auto ap_records = self->state->getApRecords(); if (index < ap_records.size()) { - TT_LOG_I(TAG, "Clicked %d/%d", index, ap_records.size() - 1); + LOGGER.info("Clicked {}/{}", index, ap_records.size() - 1); auto& ssid = ap_records[index].ssid; - TT_LOG_I(TAG, "Clicked AP: %s", ssid.c_str()); + LOGGER.info("Clicked AP: {}", ssid); std::string connection_target = service::wifi::getConnectionTarget(); if (connection_target == ssid) { self->bindings->onDisconnect(); @@ -87,12 +83,12 @@ void View::connect(lv_event_t* event) { self->bindings->onConnectSsid(ssid); } } else { - TT_LOG_W(TAG, "Clicked AP: record %d/%d does not exist", index, ap_records.size() - 1); + LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1); } } void View::showDetails(lv_event_t* event) { - TT_LOG_D(TAG, "showDetails()"); + LOGGER.debug("showDetails()"); auto* widget = lv_event_get_current_target_obj(event); auto index = reinterpret_cast(lv_obj_get_user_data(widget)); auto* self = static_cast(lv_event_get_user_data(event)); @@ -100,10 +96,10 @@ void View::showDetails(lv_event_t* event) { if (index < ap_records.size()) { auto& ssid = ap_records[index].ssid; - TT_LOG_I(TAG, "Clicked AP: %s", ssid.c_str()); + LOGGER.info("Clicked AP: {}", ssid); self->bindings->onShowApSettings(ssid); } else { - TT_LOG_W(TAG, "Clicked AP: record %d/%d does not exist", index, ap_records.size() - 1); + LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1); } } diff --git a/Tactility/Source/app/wifimanage/WifiManage.cpp b/Tactility/Source/app/wifimanage/WifiManage.cpp index e411d936..252815c9 100644 --- a/Tactility/Source/app/wifimanage/WifiManage.cpp +++ b/Tactility/Source/app/wifimanage/WifiManage.cpp @@ -4,22 +4,24 @@ #include #include #include +#include +#include #include #include namespace tt::app::wifimanage { -constexpr auto TAG = "WifiManage"; +static const auto LOGGER = Logger("WifiManage"); extern const AppManifest manifest; static void onConnect(const std::string& ssid) { service::wifi::settings::WifiApSettings settings; if (service::wifi::settings::load(ssid, settings)) { - TT_LOG_I(TAG, "Connecting with known credentials"); + LOGGER.info("Connecting with known credentials"); service::wifi::connect(settings, false); } else { - TT_LOG_I(TAG, "Starting connection dialog"); + LOGGER.info("Starting connection dialog"); wificonnect::start(ssid); } } @@ -65,7 +67,7 @@ void WifiManage::requestViewUpdate() { view.update(); lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } unlock(); @@ -73,7 +75,7 @@ void WifiManage::requestViewUpdate() { void WifiManage::onWifiEvent(service::wifi::WifiEvent event) { auto radio_state = service::wifi::getRadioState(); - TT_LOG_I(TAG, "Update with state %s", service::wifi::radioStateToString(radio_state)); + LOGGER.info("Update with state {}", service::wifi::radioStateToString(radio_state)); getState().setRadioState(radio_state); switch (event) { using enum service::wifi::WifiEvent; @@ -118,7 +120,7 @@ void WifiManage::onShow(AppContext& app, lv_obj_t* parent) { bool can_scan = radio_state == service::wifi::RadioState::On || radio_state == service::wifi::RadioState::ConnectionPending || radio_state == service::wifi::RadioState::ConnectionActive; - TT_LOG_I(TAG, "%s %d", service::wifi::radioStateToString(radio_state), (int)service::wifi::isScanning()); + LOGGER.info("{} {}", service::wifi::radioStateToString(radio_state), service::wifi::isScanning()); if (can_scan && !service::wifi::isScanning()) { service::wifi::scan(); } diff --git a/Tactility/Source/file/ObjectFileReader.cpp b/Tactility/Source/file/ObjectFileReader.cpp index 12691264..b9fe9bab 100644 --- a/Tactility/Source/file/ObjectFileReader.cpp +++ b/Tactility/Source/file/ObjectFileReader.cpp @@ -1,44 +1,44 @@ -#include "Tactility/file/ObjectFile.h" -#include "Tactility/file/ObjectFilePrivate.h" +#include +#include #include -#include +#include namespace tt::file { -constexpr auto* TAG = "ObjectFileReader"; +static const auto LOGGER = Logger("ObjectFileReader"); bool ObjectFileReader::open() { auto opening_file = std::unique_ptr(fopen(filePath.c_str(), "r")); if (opening_file == nullptr) { - TT_LOG_E(TAG, "Failed to open file %s", filePath.c_str()); + LOGGER.error("Failed to open file {}", filePath.c_str()); return false; } FileHeader file_header; if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) { - TT_LOG_E(TAG, "Failed to read file header from %s", filePath.c_str()); + LOGGER.error("Failed to read file header from {}", filePath); return false; } if (file_header.identifier != OBJECT_FILE_IDENTIFIER) { - TT_LOG_E(TAG, "Invalid file type for %s", filePath.c_str()); + LOGGER.error("Invalid file type for {}", filePath); return false; } if (file_header.version != OBJECT_FILE_VERSION) { - TT_LOG_E(TAG, "Unknown version for %s: %lu", filePath.c_str(), file_header.identifier); + LOGGER.error("Unknown version for {}: {}", filePath, file_header.identifier); return false; } ContentHeader content_header; if (fread(&content_header, sizeof(ContentHeader), 1, opening_file.get()) != 1) { - TT_LOG_E(TAG, "Failed to read content header from %s", filePath.c_str()); + LOGGER.error("Failed to read content header from {}", filePath); return false; } if (recordSize != content_header.recordSize) { - TT_LOG_E(TAG, "Record size mismatch for %s: expected %lu, got %lu", filePath.c_str(), recordSize, content_header.recordSize); + LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize); return false; } @@ -47,8 +47,8 @@ bool ObjectFileReader::open() { file = std::move(opening_file); - TT_LOG_D(TAG, "File version: %lu", file_header.version); - TT_LOG_D(TAG, "Content: version = %lu, size = %lu bytes, count = %lu", content_header.recordVersion, content_header.recordSize, content_header.recordCount); + LOGGER.debug("File version: {}", file_header.version); + LOGGER.debug("Content: version = {}, size = {} bytes, count = {}", content_header.recordVersion, content_header.recordSize, content_header.recordCount); return true; } @@ -63,7 +63,7 @@ void ObjectFileReader::close() { bool ObjectFileReader::readNext(void* output) { if (file == nullptr) { - TT_LOG_E(TAG, "File not open"); + LOGGER.error("File not open"); return false; } diff --git a/Tactility/Source/file/ObjectFileWriter.cpp b/Tactility/Source/file/ObjectFileWriter.cpp index f90fc995..c94a34eb 100644 --- a/Tactility/Source/file/ObjectFileWriter.cpp +++ b/Tactility/Source/file/ObjectFileWriter.cpp @@ -1,24 +1,24 @@ -#include "../../Include/Tactility/file/ObjectFile.h" -#include "Tactility/file/ObjectFilePrivate.h" +#include +#include +#include #include -#include #include namespace tt::file { -constexpr auto* TAG = "ObjectFileWriter"; +static const auto LOGGER = Logger("ObjectFileWriter"); bool ObjectFileWriter::open() { bool edit_existing = append && access(filePath.c_str(), F_OK) == 0; if (append && !edit_existing) { - TT_LOG_W(TAG, "access() to %s failed: %s", filePath.c_str(), strerror(errno)); + LOGGER.warn("access() to {} failed: {}", filePath, strerror(errno)); } // Edit existing or create a new file auto opening_file = std::unique_ptr(std::fopen(filePath.c_str(), "wb")); if (opening_file == nullptr) { - TT_LOG_E(TAG, "Failed to open file %s", filePath.c_str()); + LOGGER.error("Failed to open file {}", filePath); return false; } @@ -29,17 +29,17 @@ bool ObjectFileWriter::open() { FileHeader file_header; if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) { - TT_LOG_E(TAG, "Failed to read file header from %s", filePath.c_str()); + LOGGER.error("Failed to read file header from {}", filePath); return false; } if (file_header.identifier != OBJECT_FILE_IDENTIFIER) { - TT_LOG_E(TAG, "Invalid file type for %s", filePath.c_str()); + LOGGER.error("Invalid file type for {}", filePath); return false; } if (file_header.version != OBJECT_FILE_VERSION) { - TT_LOG_E(TAG, "Unknown version for %s: %lu", filePath.c_str(), file_header.identifier); + LOGGER.error("Unknown version for {}: {}", filePath, 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) { - TT_LOG_E(TAG, "Failed to read content header from %s", filePath.c_str()); + LOGGER.error("Failed to read content header from {}", filePath); return false; } if (recordSize != content_header.recordSize) { - TT_LOG_E(TAG, "Record size mismatch for %s: expected %lu, got %lu", filePath.c_str(), recordSize, content_header.recordSize); + LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize); return false; } if (recordVersion != content_header.recordVersion) { - TT_LOG_E(TAG, "Version mismatch for %s: expected %lu, got %lu", filePath.c_str(), recordVersion, content_header.recordVersion); + LOGGER.error("Version mismatch for {}: expected {}, got {}", filePath, recordVersion, 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) { - TT_LOG_E(TAG, "Failed to write file header for %s", filePath.c_str()); + LOGGER.error("Failed to write file header for {}", filePath); return false; } @@ -81,12 +81,12 @@ bool ObjectFileWriter::open() { void ObjectFileWriter::close() { if (file == nullptr) { - TT_LOG_E(TAG, "File not opened: %s", filePath.c_str()); + LOGGER.error("File not opened: {}", filePath); return; } if (fseek(file.get(), sizeof(FileHeader), SEEK_SET) != 0) { - TT_LOG_E(TAG, "File seek failed: %s", filePath.c_str()); + LOGGER.error("File seek failed: {}", filePath); return; } @@ -97,7 +97,7 @@ void ObjectFileWriter::close() { }; if (fwrite(&content_header, sizeof(ContentHeader), 1, file.get()) != 1) { - TT_LOG_E(TAG, "Failed to write content header to %s", filePath.c_str()); + LOGGER.error("Failed to write content header to {}", filePath); } file = nullptr; @@ -105,12 +105,12 @@ void ObjectFileWriter::close() { bool ObjectFileWriter::write(void* data) { if (file == nullptr) { - TT_LOG_E(TAG, "File not opened: %s", filePath.c_str()); + LOGGER.error("File not opened: {}", filePath); return false; } if (fwrite(data, recordSize, 1, file.get()) != 1) { - TT_LOG_E(TAG, "Failed to write record to %s", filePath.c_str()); + LOGGER.error("Failed to write record to {}", filePath); return false; } diff --git a/Tactility/Source/file/PropertiesFile.cpp b/Tactility/Source/file/PropertiesFile.cpp index e6bc3a31..a15c50bb 100644 --- a/Tactility/Source/file/PropertiesFile.cpp +++ b/Tactility/Source/file/PropertiesFile.cpp @@ -3,10 +3,11 @@ #include #include #include +#include namespace tt::file { -static auto TAG = "PropertiesFile"; +static const auto LOGGER = Logger("PropertiesFile"); bool getKeyValuePair(const std::string& input, std::string& key, std::string& value) { auto index = input.find('='); @@ -21,7 +22,7 @@ bool getKeyValuePair(const std::string& input, std::string& key, std::string& va bool loadPropertiesFile(const std::string& filePath, std::function callback) { // Reading properties is a common operation; make this debug-level to avoid // flooding the serial console under frequent polling. - TT_LOG_D(TAG, "Reading properties file %s", filePath.c_str()); + LOGGER.debug("Reading properties file {}", filePath); uint16_t line_count = 0; std::string key_prefix = ""; // Malformed lines are skipped, valid lines are loaded and callback is called @@ -39,7 +40,7 @@ bool loadPropertiesFile(const std::string& filePath, std::function& properties) { bool result = false; getLock(filePath)->withLock([&result, filePath, &properties] { - TT_LOG_I(TAG, "Saving properties file %s", filePath.c_str()); + LOGGER.info("Saving properties file {}", filePath); FILE* file = fopen(filePath.c_str(), "w"); if (file == nullptr) { - TT_LOG_E(TAG, "Failed to open %s", filePath.c_str()); + LOGGER.error("Failed to open {}", filePath); return; } diff --git a/Tactility/Source/hal/Device.cpp b/Tactility/Source/hal/Device.cpp index 7d4f02f9..06905887 100644 --- a/Tactility/Source/hal/Device.cpp +++ b/Tactility/Source/hal/Device.cpp @@ -1,6 +1,6 @@ #include -#include +#include #include #include @@ -10,7 +10,7 @@ std::vector> devices; RecursiveMutex mutex; static Device::Id nextId = 0; -constexpr auto TAG = "devices"; +static const auto LOGGER = Logger("Devices"); Device::Device() : id(nextId++) {} @@ -26,9 +26,9 @@ void registerDevice(const std::shared_ptr& device) { if (findDevice(device->getId()) == nullptr) { devices.push_back(device); - TT_LOG_I(TAG, "Registered %s with id %lu", device->getName().c_str(), device->getId()); + LOGGER.info("Registered {} with id {}", device->getName(), device->getId()); } else { - TT_LOG_W(TAG, "Device %s with id %lu was already registered", device->getName().c_str(), device->getId()); + LOGGER.warn("Device {} with id {} was already registered", device->getName(), device->getId()); } } @@ -41,10 +41,10 @@ void deregisterDevice(const std::shared_ptr& device) { return device->getId() == id_to_remove; }); if (remove_iterator != devices.end()) { - TT_LOG_I(TAG, "Deregistering %s with id %lu", device->getName().c_str(), device->getId()); + LOGGER.info("Deregistering {} with id {}", device->getName(), device->getId()); devices.erase(remove_iterator); } else { - TT_LOG_W(TAG, "Deregistering %s with id %lu failed: not found", device->getName().c_str(), device->getId()); + LOGGER.warn("Deregistering {} with id {} failed: not found", device->getName(), device->getId()); } } diff --git a/Tactility/Source/hal/Hal.cpp b/Tactility/Source/hal/Hal.cpp index 4cb315f9..4e26fb72 100644 --- a/Tactility/Source/hal/Hal.cpp +++ b/Tactility/Source/hal/Hal.cpp @@ -1,11 +1,12 @@ -#include "Tactility/Tactility.h" -#include "Tactility/hal/Configuration.h" -#include "Tactility/hal/Device.h" -#include "Tactility/hal/gps/GpsInit.h" -#include "Tactility/hal/i2c/I2cInit.h" -#include "Tactility/hal/power/PowerDevice.h" -#include "Tactility/hal/spi/SpiInit.h" -#include "Tactility/hal/uart/UartInit.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -14,10 +15,10 @@ namespace tt::hal { -constexpr auto* TAG = "Hal"; +static const auto LOGGER = Logger("Hal"); void registerDevices(const Configuration& configuration) { - TT_LOG_I(TAG, "Registering devices"); + LOGGER.info("Registering devices"); auto devices = configuration.createDevices(); for (auto& device : devices) { @@ -36,27 +37,27 @@ void registerDevices(const Configuration& configuration) { } static void startDisplays() { - TT_LOG_I(TAG, "Starting displays & touch"); + LOGGER.info("Starting displays & touch"); auto displays = hal::findDevices(Device::Type::Display); for (auto& display : displays) { - TT_LOG_I(TAG, "%s starting", display->getName().c_str()); + LOGGER.info("{} starting", display->getName()); if (!display->start()) { - TT_LOG_E(TAG, "%s start failed", display->getName().c_str()); + LOGGER.error("{} start failed", display->getName()); } else { - TT_LOG_I(TAG, "%s started", display->getName().c_str()); + LOGGER.info("{} started", display->getName()); if (display->supportsBacklightDuty()) { - TT_LOG_I(TAG, "Setting backlight"); + LOGGER.info("Setting backlight"); display->setBacklightDuty(0); } auto touch = display->getTouchDevice(); if (touch != nullptr) { - TT_LOG_I(TAG, "%s starting", touch->getName().c_str()); + LOGGER.info("{} starting", touch->getName()); if (!touch->start()) { - TT_LOG_E(TAG, "%s start failed", touch->getName().c_str()); + LOGGER.error("{} start failed", touch->getName()); } else { - TT_LOG_I(TAG, "%s started", touch->getName().c_str()); + LOGGER.info("{} started", touch->getName()); } } } @@ -79,7 +80,7 @@ void init(const Configuration& configuration) { kernel::publishSystemEvent(kernel::SystemEvent::BootInitUartEnd); if (configuration.initBoot != nullptr) { - TT_LOG_I(TAG, "Init power"); + LOGGER.info("Init power"); tt_check(configuration.initBoot(), "Init power failed"); } diff --git a/Tactility/Source/hal/gps/GpsDevice.cpp b/Tactility/Source/hal/gps/GpsDevice.cpp index 8abfd574..a78eea00 100644 --- a/Tactility/Source/hal/gps/GpsDevice.cpp +++ b/Tactility/Source/hal/gps/GpsDevice.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include @@ -10,24 +10,25 @@ namespace tt::hal::gps { constexpr uint32_t GPS_UART_BUFFER_SIZE = 256; -constexpr const char* TAG = "GpsDevice"; + +static const auto LOGGER = Logger("GpsDevice"); int32_t GpsDevice::threadMain() { uint8_t buffer[GPS_UART_BUFFER_SIZE]; auto uart = uart::open(configuration.uartName); if (uart == nullptr) { - TT_LOG_E(TAG, "Failed to open UART %s", configuration.uartName); + LOGGER.error("Failed to open UART {}", configuration.uartName); return -1; } if (!uart->start()) { - TT_LOG_E(TAG, "Failed to start UART %s", configuration.uartName); + LOGGER.error("Failed to start UART {}", configuration.uartName); return -1; } - if (!uart->setBaudRate((int)configuration.baudRate)) { - TT_LOG_E(TAG, "Failed to set baud rate to %lu for UART %s", configuration.baudRate, configuration.uartName); + if (!uart->setBaudRate(static_cast(configuration.baudRate))) { + LOGGER.error("Failed to set baud rate to {} for UART {}", configuration.baudRate, configuration.uartName); return -1; } @@ -35,7 +36,7 @@ int32_t GpsDevice::threadMain() { if (model == GpsModel::Unknown) { model = probe(*uart); if (model == GpsModel::Unknown) { - TT_LOG_E(TAG, "Probe failed"); + LOGGER.error("Probe failed"); setState(State::Error); return -1; } @@ -45,7 +46,7 @@ int32_t GpsDevice::threadMain() { mutex.unlock(); if (!init(*uart, model)) { - TT_LOG_E(TAG, "Init failed"); + LOGGER.error("Init failed"); setState(State::Error); return -1; } @@ -63,7 +64,7 @@ int32_t GpsDevice::threadMain() { if (bytes_read > 0U) { - TT_LOG_I(TAG, "[%ul] %s", bytes_read, buffer); + LOGGER.info("[{}] {}", bytes_read, reinterpret_cast(buffer)); switch (minmea_sentence_id((char*)buffer, false)) { case MINMEA_SENTENCE_RMC: @@ -74,9 +75,11 @@ int32_t GpsDevice::threadMain() { (*subscription.onData)(getId(), rmc_frame); } mutex.unlock(); - TT_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)); + 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)); + } } else { - TT_LOG_W(TAG, "RMC parse error: %s", buffer); + LOGGER.error("RMC parse error: {}", reinterpret_cast(buffer)); } break; case MINMEA_SENTENCE_GGA: @@ -87,9 +90,11 @@ int32_t GpsDevice::threadMain() { (*subscription.onData)(getId(), gga_frame); } mutex.unlock(); - TT_LOG_D(TAG, "GGA %f lat, %f lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude)); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("GGA {} lat, {} lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude)); + } } else { - TT_LOG_W(TAG, "GGA parse error: %s", buffer); + LOGGER.error("GGA parse error: {}", reinterpret_cast(buffer)); } break; default: @@ -99,7 +104,7 @@ int32_t GpsDevice::threadMain() { } if (uart->isStarted() && !uart->stop()) { - TT_LOG_W(TAG, "Failed to stop UART %s", configuration.uartName); + LOGGER.warn("Failed to stop UART {}", configuration.uartName); } return 0; @@ -110,13 +115,13 @@ bool GpsDevice::start() { lock.lock(); if (thread != nullptr && thread->getState() != Thread::State::Stopped) { - TT_LOG_W(TAG, "Already started"); + LOGGER.warn("Already started"); return true; } threadInterrupted = false; - TT_LOG_I(TAG, "Starting thread"); + LOGGER.info("Starting thread"); setState(State::PendingOn); thread = std::make_unique( @@ -129,7 +134,7 @@ bool GpsDevice::start() { thread->setPriority(tt::Thread::Priority::High); thread->start(); - TT_LOG_I(TAG, "Starting finished"); + LOGGER.info("Starting finished"); return true; } diff --git a/Tactility/Source/hal/gps/GpsInit.cpp b/Tactility/Source/hal/gps/GpsInit.cpp index de5dc06d..1a7c7a4a 100644 --- a/Tactility/Source/hal/gps/GpsInit.cpp +++ b/Tactility/Source/hal/gps/GpsInit.cpp @@ -3,13 +3,13 @@ #include #include #include -#include +#include #include namespace tt::hal::gps { -constexpr auto TAG = "gps"; +static const auto LOGGER = Logger("Gps"); bool initMtk(uart::Uart& uart); bool initMtkL76b(uart::Uart& uart); @@ -112,7 +112,7 @@ GpsResponse getACKCas(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32 // Check for an ACK-ACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOG_INFO("Got ACK for class %02X message %02X in %dms", class_id, msg_id, millis() - startTime); + LOGGER.info("Got ACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, kernel::getMillis() - startTime); #endif return GpsResponse::Ok; } @@ -120,7 +120,7 @@ GpsResponse getACKCas(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32 // Check for an ACK-NACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOG_WARN("Got NACK for class %02X message %02X in %dms", class_id, msg_id, millis() - startTime); + LOGGER.warn("Got NACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, millis() - startTime); #endif return GpsResponse::NotAck; } @@ -163,7 +163,7 @@ bool init(uart::Uart& uart, GpsModel type) { return initUc6580(uart); } - TT_LOG_I(TAG, "Init not implemented %d", static_cast(type)); + LOGGER.info("Init not implemented {}", static_cast(type)); return false; } @@ -213,14 +213,14 @@ bool initAtgm336h(uart::Uart& uart) { int msglen = makeCASPacket(buffer, 0x06, 0x07, sizeof(_message_CAS_CFG_NAVX_CONF), _message_CAS_CFG_NAVX_CONF); uart.writeBytes(buffer, msglen); if (getACKCas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) { - TT_LOG_W(TAG, "ATGM336H: Could not set Config"); + LOGGER.warn("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.writeBytes(buffer, msglen); if (getACKCas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) { - TT_LOG_W(TAG, "ATGM336H: Could not set Update Frequency"); + LOGGER.warn("ATGM336H: Could not set Update Frequency"); } // Set the NEMA output messages @@ -232,7 +232,7 @@ bool initAtgm336h(uart::Uart& uart) { msglen = makeCASPacket(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet); uart.writeBytes(buffer, msglen); if (getACKCas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) { - TT_LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %d", fields[i]); + LOGGER.warn("ATGM336H: Could not enable NMEA MSG: {}", fields[i]); } } return true; diff --git a/Tactility/Source/hal/gps/Probe.cpp b/Tactility/Source/hal/gps/Probe.cpp index 71142c37..18431f82 100644 --- a/Tactility/Source/hal/gps/Probe.cpp +++ b/Tactility/Source/hal/gps/Probe.cpp @@ -1,11 +1,13 @@ #include "Tactility/hal/gps/GpsDevice.h" #include "Tactility/hal/gps/Ublox.h" -#include +#include #include #include + #include -#define TAG "gps" +static const auto LOGGER = tt::Logger("Gps"); + #define GPS_UART_BUFFER_SIZE 256 using namespace tt; @@ -59,13 +61,13 @@ GpsResponse getAck(uart::Uart& uart, const char* message, uint32_t waitMillis) { if ((bytesRead == 767) || (b == '\r')) { if (strnstr((char*)buffer, message, bytesRead) != nullptr) { #ifdef GPS_DEBUG - LOG_DEBUG("Found: %s", message); // Log the found message + LOGGER.debug("Found: {}", message); // Log the found message #endif return GpsResponse::Ok; } else { bytesRead = 0; #ifdef GPS_DEBUG - LOG_DEBUG(debugmsg.c_str()); + LOGGER.debug("{}", debugmsg); #endif } } @@ -77,15 +79,15 @@ GpsResponse getAck(uart::Uart& uart, const char* message, uint32_t waitMillis) { /** * From: https://github.com/meshtastic/firmware/blob/f81d3b045dd1b7e3ca7870af3da915ff4399ea98/src/gps/GPS.cpp */ -#define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \ - do { \ - TT_LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \ - UART.flushInput(); \ - UART.writeString(TOWRITE "\r\n", TIMEOUT); \ - if (getAck(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \ - TT_LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \ - return DRIVER; \ - } \ +#define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \ + do { \ + LOGGER.info("Probing for {} ({})", CHIP, TOWRITE); \ + UART.flushInput(); \ + UART.writeString(TOWRITE "\r\n", TIMEOUT); \ + if (getAck(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \ + LOGGER.info("Probe detected {} {}", CHIP, #DRIVER); \ + return DRIVER; \ + } \ } while (0) /** @@ -132,7 +134,7 @@ GpsModel probe(uart::Uart& uart) { if (ublox_result != GpsModel::Unknown) { return ublox_result; } else { - TT_LOG_W(TAG, "No GNSS Module (baudrate %lu)", uart.getBaudRate()); + LOGGER.warn("No GNSS Module (baud rate {})", uart.getBaudRate()); return GpsModel::Unknown; } } diff --git a/Tactility/Source/hal/gps/Satellites.cpp b/Tactility/Source/hal/gps/Satellites.cpp index 1570b54c..83e398f9 100644 --- a/Tactility/Source/hal/gps/Satellites.cpp +++ b/Tactility/Source/hal/gps/Satellites.cpp @@ -1,12 +1,10 @@ #include #include -#include - -#include +#include namespace tt::hal::gps { -constexpr auto TAG = "Satellites"; +static const auto LOGGER = Logger("Satellites"); constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) { return (TickType_t)(now - timeInThePast) >= expireTimeInTicks; @@ -35,7 +33,9 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findUnusedRecord() { if (!result.empty()) { auto* record = &result.front(); record->inUse = true; - TT_LOG_D(TAG, "Found unused record"); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Found unused record"); + } return record; } else { return nullptr; @@ -53,7 +53,9 @@ 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)) { - TT_LOG_D(TAG, "! [%d] %lu < %lu", i, records[i].lastUpdated, expire_duration); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("! [{}] {} < {}", i, records[i].lastUpdated, expire_duration); + } candidate_index = i; break; } @@ -62,13 +64,17 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() { if (records[i].inUse && records[i].lastUpdated < candidate_age) { candidate_index = i; candidate_age = records[i].lastUpdated; - TT_LOG_D(TAG, "? [%d] %lu < %lu", i, records[i].lastUpdated, candidate_age); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("? [{}] {} < {}", i, records[i].lastUpdated, candidate_age); + } } } assert(candidate_index != -1); - TT_LOG_D(TAG, "Recycled record %d", candidate_index); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Recycled record {}", candidate_index); + } return &records[candidate_index]; } @@ -95,7 +101,9 @@ void SatelliteStorage::notify(const minmea_sat_info& data) { record->inUse = true; record->lastUpdated = kernel::getTicks(); record->data = data; - TT_LOG_D(TAG, "Updated satellite %d: elevation %d, azimuth %d, snr %d", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Updated satellite {}: elevation {}, azimuth {}, snr {}", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr); + } } } diff --git a/Tactility/Source/hal/gps/Ublox.cpp b/Tactility/Source/hal/gps/Ublox.cpp index 22491fd0..778f71c9 100644 --- a/Tactility/Source/hal/gps/Ublox.cpp +++ b/Tactility/Source/hal/gps/Ublox.cpp @@ -2,13 +2,13 @@ #include #include #include -#include +#include #include namespace tt::hal::gps::ublox { -constexpr auto TAG = "ublox"; +static const auto LOGGER = Logger("Ublox"); bool initUblox6(uart::Uart& uart); bool initUblox789(uart::Uart& uart, GpsModel model); @@ -19,7 +19,7 @@ bool initUblox10(uart::Uart& uart); auto msglen = makePacket(TYPE, ID, DATA, sizeof(DATA), BUFFER); \ UART.writeBytes(BUFFER, sizeof(BUFFER)); \ if (getAck(UART, TYPE, ID, TIMEOUT) != GpsResponse::Ok) { \ - TT_LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \ + LOGGER.info("Sending packet failed: {}", #ERRMSG); \ } \ } while (0) @@ -82,7 +82,7 @@ GpsResponse getAck(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t while (kernel::getTicks() - startTime < waitMillis) { if (ack > 9) { #ifdef GPS_DEBUG - TT_LOG_I(TAG, "Got ACK for class %02X message %02X in %lums", class_id, msg_id, kernel::getMillis() - startTime); + LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", class_id, msg_id, kernel::getMillis() - startTime); #endif return GpsResponse::Ok; // ACK received } @@ -93,7 +93,7 @@ GpsResponse getAck(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t if (sCounter == 26) { #ifdef GPS_DEBUG - TT_LOG_I(TAG, "%s", debugmsg.c_str()); + LOGGER.info("%s", debugmsg.c_str()); #endif return GpsResponse::FrameErrors; } @@ -108,9 +108,9 @@ GpsResponse getAck(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t } else { if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message #ifdef GPS_DEBUG - TT_LOG_I(TAG, "%s", debugmsg.c_str()); + LOGGER.info("%s", debugmsg.c_str()); #endif - TT_LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id); + LOGGER.warn("Got NAK for class {:02X} message {:02X}", class_id, msg_id); return GpsResponse::NotAck; // NAK received } ack = 0; // Reset the acknowledgement counter @@ -118,8 +118,8 @@ GpsResponse getAck(uart::Uart& uart, uint8_t class_id, uint8_t msg_id, uint32_t } } #ifdef GPS_DEBUG - TT_LOG_I(TAG, "%s", debugmsg.c_str()); - TT_LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id); + LOGGER.info("%s", debugmsg.c_str()); + LOGGER.warn("No response for class %02X message %02X", class_id, msg_id); #endif return GpsResponse::None; // No response received within timeout } @@ -180,7 +180,7 @@ static int getAck(uart::Uart& uart, uint8_t* buffer, uint16_t size, uint8_t requ } else { // return payload length #ifdef GPS_DEBUG - TT_LOG_I(TAG, "Got ACK for class %02X message %02X in %lums", requestedClass, requestedId, kernel::getMillis() - startTime); + LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", requestedClass, requestedId, kernel::getMillis() - startTime); #endif return needRead; } @@ -195,8 +195,6 @@ static int getAck(uart::Uart& uart, uint8_t* buffer, uint16_t size, uint8_t requ return 0; } -#define DETECTED_MESSAGE "%s detected, using %s Module" - static struct uBloxGnssModelInfo { char swVersion[30]; char hwVersion[10]; @@ -206,7 +204,8 @@ static struct uBloxGnssModelInfo { } ublox_info; GpsModel probe(uart::Uart& uart) { - TT_LOG_I(TAG, "Probing for U-blox"); + LOGGER.info("Probing for U-blox"); + constexpr auto DETECTED_MESSAGE = "{} detected, using {} Module"; uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00}; checksum(cfg_rate, sizeof(cfg_rate)); @@ -215,10 +214,10 @@ GpsModel probe(uart::Uart& uart) { // Check that the returned response class and message ID are correct GpsResponse response = getAck(uart, 0x06, 0x08, 750); if (response == GpsResponse::None) { - TT_LOG_W(TAG, "No GNSS Module (baudrate %lu)", uart.getBaudRate()); + LOGGER.warn("No GNSS Module (baudrate {})", uart.getBaudRate()); return GpsModel::Unknown; } else if (response == GpsResponse::FrameErrors) { - TT_LOG_W(TAG, "UBlox Frame Errors (baudrate %lu)", uart.getBaudRate()); + LOGGER.warn("UBlox Frame Errors (baudrate {})", uart.getBaudRate()); } uint8_t buffer[256]; @@ -256,12 +255,12 @@ GpsModel probe(uart::Uart& uart) { break; } - TT_LOG_I(TAG, "Module Info : "); - TT_LOG_I(TAG, "Soft version: %s", ublox_info.swVersion); - TT_LOG_I(TAG, "Hard version: %s", ublox_info.hwVersion); - TT_LOG_I(TAG, "Extensions:%d", ublox_info.extensionNo); + LOGGER.info("Module Info:"); + LOGGER.info("Soft version: {}", ublox_info.swVersion); + LOGGER.info("Hard version: {}", ublox_info.hwVersion); + LOGGER.info("Extensions: {}", ublox_info.extensionNo); for (int i = 0; i < ublox_info.extensionNo; i++) { - TT_LOG_I(TAG, " %s", ublox_info.extension[i]); + LOGGER.info(" %s", ublox_info.extension[i]); } memset(buffer, 0, sizeof(buffer)); @@ -274,29 +273,29 @@ GpsModel probe(uart::Uart& uart) { char* ptr = nullptr; memset(buffer, 0, sizeof(buffer)); strncpy((char*)buffer, &(ublox_info.extension[i][8]), sizeof(buffer)); - TT_LOG_I(TAG, "Protocol Version:%s", (char*)buffer); + LOGGER.info("Protocol Version: {}", (char*)buffer); if (strlen((char*)buffer)) { ublox_info.protocol_version = strtoul((char*)buffer, &ptr, 10); - TT_LOG_I(TAG, "ProtVer=%d", ublox_info.protocol_version); + LOGGER.info("ProtVer={}", ublox_info.protocol_version); } else { ublox_info.protocol_version = 0; } } } if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) { - TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6"); + LOGGER.info(DETECTED_MESSAGE, "U-blox 6", "6"); return GpsModel::UBLOX6; } else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) { - TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7"); + LOGGER.info(DETECTED_MESSAGE, "U-blox 7", "7"); return GpsModel::UBLOX7; } else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) { - TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8"); + LOGGER.info(DETECTED_MESSAGE, "U-blox 8", "8"); return GpsModel::UBLOX8; } else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) { - TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9"); + LOGGER.info(DETECTED_MESSAGE, "U-blox 9", "9"); return GpsModel::UBLOX9; } else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) { - TT_LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10"); + LOGGER.info(DETECTED_MESSAGE, "U-blox 10", "10"); return GpsModel::UBLOX10; } } @@ -305,7 +304,7 @@ GpsModel probe(uart::Uart& uart) { } bool init(uart::Uart& uart, GpsModel model) { - TT_LOG_I(TAG, "U-blox init"); + LOGGER.info("U-blox init"); switch (model) { case GpsModel::UBLOX6: return initUblox6(uart); @@ -316,7 +315,7 @@ bool init(uart::Uart& uart, GpsModel model) { case GpsModel::UBLOX10: return initUblox10(uart); default: - TT_LOG_E(TAG, "Unknown or unsupported U-blox model"); + LOGGER.error("Unknown or unsupported U-blox model"); return false; } } @@ -365,9 +364,9 @@ bool initUblox10(uart::Uart& uart) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer); uart.writeBytes(buffer, packet_size); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - TT_LOG_W(TAG, "Unable to save GNSS module config"); + LOGGER.warn("Unable to save GNSS module config"); } else { - TT_LOG_I(TAG, "GNSS module configuration saved!"); + LOGGER.info("GNSS module configuration saved!"); } return true; } @@ -375,7 +374,7 @@ bool initUblox10(uart::Uart& uart) { bool initUblox789(uart::Uart& uart, GpsModel model) { uint8_t buffer[256]; if (model == GpsModel::UBLOX7) { - TT_LOG_D(TAG, "Set GPS+SBAS"); + LOGGER.debug("Set GPS+SBAS"); auto msglen = makePacket(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer); uart.writeBytes(buffer, msglen); } else { // 8,9 @@ -385,12 +384,12 @@ bool initUblox789(uart::Uart& uart, GpsModel model) { if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) { // It's not critical if the module doesn't acknowledge this configuration. - TT_LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?"); + LOGGER.debug("reconfigure GNSS - defaults maintained. Is this module GPS-only?"); } else { if (model == GpsModel::UBLOX7) { - TT_LOG_I(TAG, "GPS+SBAS configured"); + LOGGER.info("GPS+SBAS configured"); } else { // 8,9 - TT_LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured"); + LOGGER.info("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 @@ -439,9 +438,9 @@ bool initUblox789(uart::Uart& uart, GpsModel model) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); uart.writeBytes(buffer, packet_size); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - TT_LOG_W(TAG, "Unable to save GNSS module config"); + LOGGER.warn("Unable to save GNSS module config"); } else { - TT_LOG_I(TAG, "GNSS module configuration saved!"); + LOGGER.info("GNSS module configuration saved!"); } return true; } @@ -473,9 +472,9 @@ bool initUblox6(uart::Uart& uart) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); uart.writeBytes(buffer, packet_size); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - TT_LOG_W(TAG, "Unable to save GNSS module config"); + LOGGER.warn("Unable to save GNSS module config"); } else { - TT_LOG_I(TAG, "GNSS module config saved!"); + LOGGER.info("GNSS module config saved!"); } return true; } diff --git a/Tactility/Source/hal/i2c/I2c.cpp b/Tactility/Source/hal/i2c/I2c.cpp index e417bdf5..defa39ac 100644 --- a/Tactility/Source/hal/i2c/I2c.cpp +++ b/Tactility/Source/hal/i2c/I2c.cpp @@ -1,12 +1,12 @@ -#include "Tactility/hal/i2c/I2c.h" +#include -#include -#include #include +#include +#include namespace tt::hal::i2c { -constexpr auto TAG = "i2c"; +static const auto LOGGER = Logger("I2C"); struct Data { Mutex mutex; @@ -18,12 +18,12 @@ struct Data { static const uint8_t ACK_CHECK_EN = 1; static Data dataArray[I2C_NUM_MAX]; -bool init(const std::vector& configurations) { - TT_LOG_I(TAG, "Init"); +bool init(const std::vector& configurations) { + LOGGER.info("Init"); for (const auto& configuration: configurations) { #ifdef ESP_PLATFORM if (configuration.config.mode != I2C_MODE_MASTER) { - TT_LOG_E(TAG, "Currently only master mode is supported"); + LOGGER.error("Currently only master mode is supported"); return false; } #endif // ESP_PLATFORM @@ -51,10 +51,10 @@ bool configure(i2c_port_t port, const i2c_config_t& configuration) { Data& data = dataArray[port]; if (data.isStarted) { - TT_LOG_E(TAG, "(%d) Cannot reconfigure while interface is started", port); + LOGGER.error("({}) Cannot reconfigure while interface is started", static_cast(port)); return false; } else if (!data.configuration.isMutable) { - TT_LOG_E(TAG, "(%d) Mutation not allowed because configuration is immutable", port); + LOGGER.error("({}) Mutation not allowed because configuration is immutable", static_cast(port)); return false; } else { data.configuration.config = configuration; @@ -70,32 +70,32 @@ bool start(i2c_port_t port) { Configuration& config = data.configuration; if (data.isStarted) { - TT_LOG_E(TAG, "(%d) Starting: Already started", port); + LOGGER.error("({}) Starting: Already started", static_cast(port)); return false; } if (!data.isConfigured) { - TT_LOG_E(TAG, "(%d) Starting: Not configured", port); + LOGGER.error("({}) Starting: Not configured", static_cast(port)); return false; } #ifdef ESP_PLATFORM esp_err_t result = i2c_param_config(port, &config.config); if (result != ESP_OK) { - TT_LOG_E(TAG, "(%d) Starting: Failed to configure: %s", port, esp_err_to_name(result)); + LOGGER.error("({}) Starting: Failed to configure: {}", static_cast(port), esp_err_to_name(result)); return false; } result = i2c_driver_install(port, config.config.mode, 0, 0, 0); if (result != ESP_OK) { - TT_LOG_E(TAG, "(%d) Starting: Failed to install driver: %s", port, esp_err_to_name(result)); + LOGGER.error("({}) Starting: Failed to install driver: {}", static_cast(port), esp_err_to_name(result)); return false; } #endif // ESP_PLATFORM data.isStarted = true; - TT_LOG_I(TAG, "(%d) Started", port); + LOGGER.info("({}) Started", static_cast(port)); return true; } @@ -107,26 +107,26 @@ bool stop(i2c_port_t port) { Configuration& config = data.configuration; if (!config.isMutable) { - TT_LOG_E(TAG, "(%d) Stopping: Not allowed for immutable configuration", port); + LOGGER.error("({}) Stopping: Not allowed for immutable configuration", static_cast(port)); return false; } if (!data.isStarted) { - TT_LOG_E(TAG, "(%d) Stopping: Not started", port); + LOGGER.error("({}) Stopping: Not started", static_cast(port)); return false; } #ifdef ESP_PLATFORM esp_err_t result = i2c_driver_delete(port); if (result != ESP_OK) { - TT_LOG_E(TAG, "(%d) Stopping: Failed to delete driver: %s", port, esp_err_to_name(result)); + LOGGER.error("({}) Stopping: Failed to delete driver: {}", static_cast(port), esp_err_to_name(result)); return false; } #endif // ESP_PLATFORM data.isStarted = false; - TT_LOG_I(TAG, "(%d) Stopped", port); + LOGGER.info("({}) Stopped", static_cast(port)); return true; } @@ -139,7 +139,7 @@ bool isStarted(i2c_port_t port) { bool masterRead(i2c_port_t port, uint8_t address, uint8_t* data, size_t dataSize, TickType_t timeout) { auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } @@ -155,7 +155,7 @@ bool masterRead(i2c_port_t port, uint8_t address, uint8_t* data, size_t dataSize bool masterReadRegister(i2c_port_t port, uint8_t address, uint8_t reg, uint8_t* data, size_t dataSize, TickType_t timeout) { auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } @@ -188,7 +188,7 @@ bool masterReadRegister(i2c_port_t port, uint8_t address, uint8_t reg, uint8_t* bool masterWrite(i2c_port_t port, uint8_t address, const uint8_t* data, uint16_t dataSize, TickType_t timeout) { auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } @@ -206,7 +206,7 @@ bool masterWriteRegister(i2c_port_t port, uint8_t address, uint8_t reg, const ui auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } @@ -248,7 +248,7 @@ bool masterWriteRegisterArray(i2c_port_t port, uint8_t address, const uint8_t* d bool masterWriteRead(i2c_port_t port, uint8_t address, const uint8_t* writeData, size_t writeDataSize, uint8_t* readData, size_t readDataSize, TickType_t timeout) { auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } @@ -264,7 +264,7 @@ bool masterWriteRead(i2c_port_t port, uint8_t address, const uint8_t* writeData, bool masterHasDeviceAtAddress(i2c_port_t port, uint8_t address, TickType_t timeout) { auto lock = getLock(port).asScopedLock(); if (!lock.lock(timeout)) { - TT_LOG_E(TAG, "(%d) Mutex timeout", port); + LOGGER.error("({}) Mutex timeout", static_cast(port)); return false; } diff --git a/Tactility/Source/hal/sdcard/SdCardMounting.cpp b/Tactility/Source/hal/sdcard/SdCardMounting.cpp index 8bd81195..b7152117 100644 --- a/Tactility/Source/hal/sdcard/SdCardMounting.cpp +++ b/Tactility/Source/hal/sdcard/SdCardMounting.cpp @@ -1,17 +1,19 @@ #include #include +#include + #include namespace tt::hal::sdcard { -constexpr auto* TAG = "SdCardMounting"; +static const auto LOGGER = Logger("SdCardMounting"); constexpr auto* TT_SDCARD_MOUNT_POINT = "/sdcard"; static void mount(const std::shared_ptr& sdcard, const std::string& path) { - TT_LOG_I(TAG, "Mounting sdcard at %s", path.c_str()); + LOGGER.info("Mounting sdcard at {}", path); if (!sdcard->mount(path)) { - TT_LOG_W(TAG, "SD card mount failed for %s (init can continue)", path.c_str()); + LOGGER.warn("SD card mount failed for {} (init can continue)", path); } } diff --git a/Tactility/Source/hal/sdcard/SdmmcDevice.cpp b/Tactility/Source/hal/sdcard/SdmmcDevice.cpp index b0875ab1..036ebee2 100644 --- a/Tactility/Source/hal/sdcard/SdmmcDevice.cpp +++ b/Tactility/Source/hal/sdcard/SdmmcDevice.cpp @@ -5,7 +5,7 @@ #if defined(ESP_PLATFORM) && defined(SOC_SDMMC_HOST_SUPPORTED) #include -#include +#include #include #include @@ -13,10 +13,10 @@ namespace tt::hal::sdcard { -constexpr auto* TAG = "SdmmcDevice"; +static const auto LOGGER = Logger("SdmmcDevice"); bool SdmmcDevice::mountInternal(const std::string& newMountPath) { - TT_LOG_I(TAG, "Mounting %s", newMountPath.c_str()); + LOGGER.info("Mounting {}", newMountPath); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = config->formatOnMountFailed, @@ -49,9 +49,9 @@ bool SdmmcDevice::mountInternal(const std::string& newMountPath) { if (result != ESP_OK || card == nullptr) { if (result == ESP_FAIL) { - TT_LOG_E(TAG, "Mounting failed. Ensure the card is formatted with FAT."); + LOGGER.error("Mounting failed. Ensure the card is formatted with FAT."); } else { - TT_LOG_E(TAG, "Mounting failed (%s)", esp_err_to_name(result)); + LOGGER.error("Mounting failed ({})", esp_err_to_name(result)); } return false; } @@ -66,11 +66,11 @@ bool SdmmcDevice::mount(const std::string& newMountPath) { lock.lock(); if (mountInternal(newMountPath)) { - TT_LOG_I(TAG, "Mounted at %s", newMountPath.c_str()); + LOGGER.info("Mounted at {}", newMountPath); sdmmc_card_print_info(stdout, card); return true; } else { - TT_LOG_E(TAG, "Mount failed for %s", newMountPath.c_str()); + LOGGER.error("Mount failed for {}", newMountPath); return false; } } @@ -80,16 +80,16 @@ bool SdmmcDevice::unmount() { lock.lock(); if (card == nullptr) { - TT_LOG_E(TAG, "Can't unmount: not mounted"); + LOGGER.error("Can't unmount: not mounted"); return false; } if (esp_vfs_fat_sdcard_unmount(mountPath.c_str(), card) != ESP_OK) { - TT_LOG_E(TAG, "Unmount failed for %s", mountPath.c_str()); + LOGGER.error("Unmount failed for {}", mountPath); return false; } - TT_LOG_I(TAG, "Unmounted %s", mountPath.c_str()); + LOGGER.info("Unmounted {}", mountPath); mountPath = ""; card = nullptr; return true; diff --git a/Tactility/Source/hal/sdcard/SpiSdCardDevice.cpp b/Tactility/Source/hal/sdcard/SpiSdCardDevice.cpp index 2fb682ec..7cfa0b1c 100644 --- a/Tactility/Source/hal/sdcard/SpiSdCardDevice.cpp +++ b/Tactility/Source/hal/sdcard/SpiSdCardDevice.cpp @@ -2,14 +2,14 @@ #include #include -#include +#include #include #include namespace tt::hal::sdcard { -constexpr auto* TAG = "SpiSdCardDevice"; +static const auto LOGGER = Logger("SpiSdCardDevice"); /** * Before we can initialize the sdcard's SPI communications, we have to set all @@ -19,7 +19,7 @@ constexpr auto* TAG = "SpiSdCardDevice"; * @return success result */ bool SpiSdCardDevice::applyGpioWorkAround() { - TT_LOG_D(TAG, "init"); + LOGGER.info("applyGpioWorkAround"); uint64_t pin_bit_mask = BIT64(config->spiPinCs); for (auto const& pin: config->csPinWorkAround) { @@ -27,13 +27,13 @@ bool SpiSdCardDevice::applyGpioWorkAround() { } if (!gpio::configureWithPinBitmask(pin_bit_mask, gpio::Mode::Output, false, false)) { - TT_LOG_E(TAG, "GPIO init failed"); + LOGGER.error("GPIO work-around failed"); return false; } for (auto const& pin: config->csPinWorkAround) { if (!gpio::setLevel(pin, true)) { - TT_LOG_E(TAG, "Failed to set board CS pin high"); + LOGGER.error("Failed to set board CS pin high"); return false; } } @@ -42,7 +42,7 @@ bool SpiSdCardDevice::applyGpioWorkAround() { } bool SpiSdCardDevice::mountInternal(const std::string& newMountPath) { - TT_LOG_I(TAG, "Mounting %s", newMountPath.c_str()); + LOGGER.info("Mounting {}", newMountPath); esp_vfs_fat_sdmmc_mount_config_t mount_config = { .format_if_mount_failed = config->formatOnMountFailed, @@ -71,9 +71,9 @@ bool SpiSdCardDevice::mountInternal(const std::string& newMountPath) { if (result != ESP_OK || card == nullptr) { if (result == ESP_FAIL) { - TT_LOG_E(TAG, "Mounting failed. Ensure the card is formatted with FAT."); + LOGGER.error("Mounting failed. Ensure the card is formatted with FAT."); } else { - TT_LOG_E(TAG, "Mounting failed (%s)", esp_err_to_name(result)); + LOGGER.error("Mounting failed ({})", esp_err_to_name(result)); } return false; } @@ -88,16 +88,16 @@ bool SpiSdCardDevice::mount(const std::string& newMountPath) { lock.lock(); if (!applyGpioWorkAround()) { - TT_LOG_E(TAG, "Failed to apply GPIO work-around"); + LOGGER.error("Failed to apply GPIO work-around"); return false; } if (mountInternal(newMountPath)) { - TT_LOG_I(TAG, "Mounted at %s", newMountPath.c_str()); + LOGGER.info("Mounted at {}", newMountPath); sdmmc_card_print_info(stdout, card); return true; } else { - TT_LOG_E(TAG, "Mount failed for %s", newMountPath.c_str()); + LOGGER.error("Mount failed for {}", newMountPath); return false; } } @@ -107,16 +107,16 @@ bool SpiSdCardDevice::unmount() { lock.lock(); if (card == nullptr) { - TT_LOG_E(TAG, "Can't unmount: not mounted"); + LOGGER.error("Can't unmount: not mounted"); return false; } if (esp_vfs_fat_sdcard_unmount(mountPath.c_str(), card) != ESP_OK) { - TT_LOG_E(TAG, "Unmount failed for %s", mountPath.c_str()); + LOGGER.error("Unmount failed for {}", mountPath); return false; } - TT_LOG_I(TAG, "Unmounted %s", mountPath.c_str()); + LOGGER.info("Unmounted {}", mountPath); mountPath = ""; card = nullptr; return true; diff --git a/Tactility/Source/hal/spi/Spi.cpp b/Tactility/Source/hal/spi/Spi.cpp index e1b3e3ea..06166419 100644 --- a/Tactility/Source/hal/spi/Spi.cpp +++ b/Tactility/Source/hal/spi/Spi.cpp @@ -1,11 +1,11 @@ #include -#include +#include #include namespace tt::hal::spi { -constexpr auto* TAG = "SPI"; +static const auto LOGGER = Logger("SPI"); struct Data { std::shared_ptr lock; @@ -17,7 +17,7 @@ struct Data { static Data dataArray[SPI_HOST_MAX]; bool init(const std::vector& configurations) { - TT_LOG_I(TAG, "Init"); + LOGGER.info("Init"); for (const auto& configuration: configurations) { Data& data = dataArray[configuration.device]; data.configuration = configuration; @@ -48,10 +48,10 @@ bool configure(spi_host_device_t device, const spi_bus_config_t& configuration) Data& data = dataArray[device]; if (data.isStarted) { - TT_LOG_E(TAG, "(%d) Cannot reconfigure while interface is started", device); + LOGGER.error("({}) Cannot reconfigure while interface is started", static_cast(device)); return false; } else if (!data.configuration.isMutable) { - TT_LOG_E(TAG, "(%d) Mutation not allowed by original configuration", device); + LOGGER.error("({}) Mutation not allowed by original configuration", static_cast(device)); return false; } else { data.configuration.config = configuration; @@ -66,12 +66,12 @@ bool start(spi_host_device_t device) { Data& data = dataArray[device]; if (data.isStarted) { - TT_LOG_E(TAG, "(%d) Starting: Already started", device); + LOGGER.error("({}) Starting: Already started", static_cast(device)); return false; } if (!data.isConfigured) { - TT_LOG_E(TAG, "(%d) Starting: Not configured", device); + LOGGER.error("({}) Starting: Not configured", static_cast(device)); return false; } @@ -79,7 +79,7 @@ bool start(spi_host_device_t device) { auto result = spi_bus_initialize(device, &data.configuration.config, data.configuration.dma); if (result != ESP_OK) { - TT_LOG_E(TAG, "(%d) Starting: Failed to initialize: %s", device, esp_err_to_name(result)); + LOGGER.error("({}) Starting: Failed to initialize: {}", static_cast(device), esp_err_to_name(result)); return false; } else { data.isStarted = true; @@ -91,7 +91,7 @@ bool start(spi_host_device_t device) { #endif - TT_LOG_I(TAG, "(%d) Started", device); + LOGGER.info("({}) Started", static_cast(device)); return true; } @@ -103,12 +103,12 @@ bool stop(spi_host_device_t device) { Configuration& config = data.configuration; if (!config.isMutable) { - TT_LOG_E(TAG, "(%d) Stopping: Not allowed, immutable", device); + LOGGER.error("({}) Stopping: Not allowed, immutable", static_cast(device)); return false; } if (!data.isStarted) { - TT_LOG_E(TAG, "(%d) Stopping: Not started", device); + LOGGER.error("({}) Stopping: Not started", static_cast(device)); return false; } @@ -116,7 +116,7 @@ bool stop(spi_host_device_t device) { auto result = spi_bus_free(device); if (result != ESP_OK) { - TT_LOG_E(TAG, "(%d) Stopping: Failed to free device: %s", device, esp_err_to_name(result)); + LOGGER.error("({}) Stopping: Failed to free device: {}", static_cast(device), esp_err_to_name(result)); return false; } else { data.isStarted = false; @@ -128,7 +128,7 @@ bool stop(spi_host_device_t device) { #endif - TT_LOG_I(TAG, "(%d) Stopped", device); + LOGGER.info("({}) Stopped", static_cast(device)); return true; } diff --git a/Tactility/Source/hal/uart/Uart.cpp b/Tactility/Source/hal/uart/Uart.cpp index c647b8f1..444fe274 100644 --- a/Tactility/Source/hal/uart/Uart.cpp +++ b/Tactility/Source/hal/uart/Uart.cpp @@ -1,6 +1,6 @@ #include "Tactility/hal/uart/Uart.h" -#include +#include #include #include @@ -15,10 +15,10 @@ #include #endif -#define TAG "uart" - namespace tt::hal::uart { +static const auto LOGGER = Logger("UART"); + constexpr uint32_t uartIdNotInUse = 0; struct UartEntry { @@ -30,7 +30,7 @@ static std::vector uartEntries = {}; static uint32_t lastUartId = uartIdNotInUse; bool init(const std::vector& configurations) { - TT_LOG_I(TAG, "Init"); + LOGGER.info("Init"); for (const auto& configuration: configurations) { uartEntries.push_back({ .usageId = uartIdNotInUse, @@ -78,7 +78,7 @@ size_t Uart::readUntil(std::byte* buffer, size_t bufferSize, uint8_t untilByte, TickType_t now = kernel::getTicks(); if (now > (start_time + timeout)) { #ifdef DEBUG_READ_UNTIL - TT_LOG_W(TAG, "readUntil() timeout"); + LOGGER.warn("readUntil() timeout"); #endif break; } else { @@ -102,26 +102,26 @@ size_t Uart::readUntil(std::byte* buffer, size_t bufferSize, uint8_t untilByte, static std::unique_ptr open(UartEntry& entry) { if (entry.usageId != uartIdNotInUse) { - TT_LOG_E(TAG, "UART in use: %s", entry.configuration.name.c_str()); + LOGGER.error("UART in use: {}", entry.configuration.name); return nullptr; } auto uart = create(entry.configuration); assert(uart != nullptr); entry.usageId = uart->getId(); - TT_LOG_I(TAG, "Opened %lu", entry.usageId); + LOGGER.info("Opened {}", entry.usageId); return uart; } std::unique_ptr open(uart_port_t port) { - TT_LOG_I(TAG, "Open %d", port); + LOGGER.info("Open {}", static_cast(port)); auto result = std::views::filter(uartEntries, [port](auto& entry) { return entry.configuration.port == port; }); if (result.empty()) { - TT_LOG_E(TAG, "UART not found: %d", port); + LOGGER.error("UART not found: {}", static_cast(port)); return nullptr; } @@ -129,14 +129,14 @@ std::unique_ptr open(uart_port_t port) { } std::unique_ptr open(std::string name) { - TT_LOG_I(TAG, "Open %s", name.c_str()); + LOGGER.info("Open {}", name); auto result = std::views::filter(uartEntries, [&name](auto& entry) { return entry.configuration.name == name; }); if (result.empty()) { - TT_LOG_E(TAG, "UART not found: %s", name.c_str()); + LOGGER.error("UART not found: {}", name); return nullptr; } @@ -144,7 +144,7 @@ std::unique_ptr open(std::string name) { } void close(uint32_t uartId) { - TT_LOG_I(TAG, "Close %lu", uartId); + LOGGER.info("Close {}", uartId); auto result = std::views::filter(uartEntries, [&uartId](auto& entry) { return entry.usageId == uartId; }); @@ -153,7 +153,7 @@ void close(uint32_t uartId) { auto& entry = *result.begin(); entry.usageId = uartIdNotInUse; } else { - TT_LOG_W(TAG, "Auto-closing UART, but can't find it"); + LOGGER.warn("Auto-closing UART, but can't find it"); } } @@ -166,7 +166,7 @@ std::vector getNames() { #else DIR* dir = opendir("/dev"); if (dir == nullptr) { - TT_LOG_E(TAG, "Failed to read /dev"); + LOGGER.error("Failed to read /dev"); return names; } struct dirent* current_entry; diff --git a/Tactility/Source/hal/uart/UartEsp.cpp b/Tactility/Source/hal/uart/UartEsp.cpp index 77cb11d3..6b6fb2bc 100644 --- a/Tactility/Source/hal/uart/UartEsp.cpp +++ b/Tactility/Source/hal/uart/UartEsp.cpp @@ -2,7 +2,7 @@ #include -#include +#include #include #include @@ -11,16 +11,16 @@ namespace tt::hal::uart { -constexpr auto TAG = "uart"; +static const auto LOGGER = Logger("UART"); bool UartEsp::start() { - TT_LOG_I(TAG, "[%s] Starting", configuration.name.c_str()); + LOGGER.info("[{}] Starting", configuration.name); auto lock = mutex.asScopedLock(); lock.lock(); if (started) { - TT_LOG_E(TAG, "[%s] Starting: Already started", configuration.name.c_str()); + LOGGER.error("[{}] Starting: Already started", configuration.name); return false; } @@ -33,53 +33,53 @@ bool UartEsp::start() { esp_err_t result = uart_param_config(configuration.port, &configuration.config); if (result != ESP_OK) { - TT_LOG_E(TAG, "[%s] Starting: Failed to configure: %s", configuration.name.c_str(), esp_err_to_name(result)); + LOGGER.error("[{}] Starting: Failed to configure: {}", configuration.name, esp_err_to_name(result)); return false; } if (uart_is_driver_installed(configuration.port)) { - TT_LOG_W(TAG, "[%s] Driver was still installed. You probably forgot to stop, or another system uses/used the driver.", configuration.name.c_str()); + LOGGER.error("[{}] Driver was still installed. You probably forgot to stop, or another system uses/used the driver.", configuration.name); uart_driver_delete(configuration.port); } result = uart_set_pin(configuration.port, configuration.txPin, configuration.rxPin, configuration.rtsPin, configuration.ctsPin); if (result != ESP_OK) { - TT_LOG_E(TAG, "[%s] Starting: Failed set pins: %s", configuration.name.c_str(), esp_err_to_name(result)); + LOGGER.error("[{}] Starting: Failed set pins: {}", configuration.name, esp_err_to_name(result)); return false; } result = uart_driver_install(configuration.port, (int)configuration.rxBufferSize, (int)configuration.txBufferSize, 0, nullptr, intr_alloc_flags); if (result != ESP_OK) { - TT_LOG_E(TAG, "[%s] Starting: Failed to install driver: %s", configuration.name.c_str(), esp_err_to_name(result)); + LOGGER.error("[{}] Starting: Failed to install driver: {}", configuration.name, esp_err_to_name(result)); return false; } started = true; - TT_LOG_I(TAG, "[%s] Started", configuration.name.c_str()); + LOGGER.info("[{}] Started", configuration.name); return true; } bool UartEsp::stop() { - TT_LOG_I(TAG, "[%s] Stopping", configuration.name.c_str()); + LOGGER.info("[{}] Stopping", configuration.name); auto lock = mutex.asScopedLock(); lock.lock(); if (!started) { - TT_LOG_E(TAG, "[%s] Stopping: Not started", configuration.name.c_str()); + LOGGER.error("[{}] Stopping: Not started", configuration.name); return false; } esp_err_t result = uart_driver_delete(configuration.port); if (result != ESP_OK) { - TT_LOG_E(TAG, "[%s] Stopping: Failed to delete driver: %s", configuration.name.c_str(), esp_err_to_name(result)); + LOGGER.error("[{}] Stopping: Failed to delete driver: {}", configuration.name, esp_err_to_name(result)); return false; } started = false; - TT_LOG_I(TAG, "[%s] Stopped", configuration.name.c_str()); + LOGGER.info("[{}] Stopped", configuration.name); return true; } diff --git a/Tactility/Source/hal/uart/UartPosix.cpp b/Tactility/Source/hal/uart/UartPosix.cpp index 28ce68c4..74d13987 100644 --- a/Tactility/Source/hal/uart/UartPosix.cpp +++ b/Tactility/Source/hal/uart/UartPosix.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include @@ -12,20 +12,20 @@ namespace tt::hal::uart { -constexpr auto TAG = "uart"; +static const auto LOGGER = Logger("UART"); bool UartPosix::start() { auto lock = mutex.asScopedLock(); lock.lock(); if (device != nullptr) { - TT_LOG_E(TAG, "[%s] Starting: Already started", configuration.name.c_str()); + LOGGER.error("[{}] Starting: Already started", configuration.name); return false; } auto file = fopen(configuration.name.c_str(), "w"); if (file == nullptr) { - TT_LOG_E(TAG, "[%s] Open device failed", configuration.name.c_str()); + LOGGER.error("[{}] Open device failed", configuration.name); return false; } @@ -33,16 +33,16 @@ bool UartPosix::start() { struct termios tty; if (tcgetattr(fileno(file), &tty) < 0) { - printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno)); + LOGGER.error("[{}] tcgetattr failed: {}", configuration.name, strerror(errno)); return false; } if (cfsetospeed(&tty, (speed_t)configuration.baudRate) == -1) { - TT_LOG_E(TAG, "[%s] Setting output speed failed", configuration.name.c_str()); + LOGGER.error("[{}] Setting output speed failed", configuration.name); } if (cfsetispeed(&tty, (speed_t)configuration.baudRate) == -1) { - TT_LOG_E(TAG, "[%s] Setting input speed failed", configuration.name.c_str()); + LOGGER.error("[{}] Setting input speed failed", configuration.name); } tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */ @@ -61,13 +61,13 @@ bool UartPosix::start() { tty.c_cc[VTIME] = 1; if (tcsetattr(fileno(file), TCSANOW, &tty) != 0) { - printf("[%s] tcsetattr failed: %s\n", configuration.name.c_str(), strerror(errno)); + LOGGER.error("[{}] tcsetattr failed: {}", configuration.name, strerror(errno)); return false; } device = std::move(new_device); - TT_LOG_I(TAG, "[%s] Started", configuration.name.c_str()); + LOGGER.info("[{}] Started", configuration.name); return true; } @@ -76,13 +76,13 @@ bool UartPosix::stop() { lock.lock(); if (device == nullptr) { - TT_LOG_E(TAG, "[%s] Stopping: Not started", configuration.name.c_str()); + LOGGER.error("[{}] Stopping: Not started", configuration.name); return false; } device = nullptr; - TT_LOG_I(TAG, "[%s] Stopped", configuration.name.c_str()); + LOGGER.info("[{}] Stopped", configuration.name); return true; } @@ -139,7 +139,7 @@ void UartPosix::flushInput() { uint32_t UartPosix::getBaudRate() { struct termios tty; if (tcgetattr(fileno(device.get()), &tty) < 0) { - printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno)); + LOGGER.error("[{}] tcgetattr failed: {}", configuration.name, strerror(errno)); return false; } else { return (uint32_t)cfgetispeed(&tty); @@ -154,17 +154,17 @@ bool UartPosix::setBaudRate(uint32_t baudRate, TickType_t timeout) { struct termios tty; if (tcgetattr(fileno(device.get()), &tty) < 0) { - printf("[%s] tcgetattr failed: %s\n", configuration.name.c_str(), strerror(errno)); + LOGGER.error("[{}] tcgetattr failed: {}", configuration.name, strerror(errno)); return false; } if (cfsetospeed(&tty, (speed_t)configuration.baudRate) == -1) { - TT_LOG_E(TAG, "[%s] Failed to set output speed", configuration.name.c_str()); + LOGGER.error("[{}] Failed to set output speed", configuration.name); return false; } if (cfsetispeed(&tty, (speed_t)configuration.baudRate) == -1) { - TT_LOG_E(TAG, "[%s] Failed to set input speed", configuration.name.c_str()); + LOGGER.error("[{}] Failed to set input speed", configuration.name); return false; } diff --git a/Tactility/Source/hal/usb/Usb.cpp b/Tactility/Source/hal/usb/Usb.cpp index a8d5056b..f8c1ceee 100644 --- a/Tactility/Source/hal/usb/Usb.cpp +++ b/Tactility/Source/hal/usb/Usb.cpp @@ -4,11 +4,12 @@ #include #include -#include +#include namespace tt::hal::usb { -constexpr auto* TAG = "usb"; +static const auto LOGGER = Logger("USB"); + constexpr auto BOOT_FLAG_SDMMC = 42; // Existing constexpr auto BOOT_FLAG_FLASH = 43; // For flash mode @@ -32,13 +33,13 @@ sdmmc_card_t* _Nullable getCard() { } if (usable_sdcard == nullptr) { - TT_LOG_W(TAG, "Couldn't find a mounted SpiSdCard"); + LOGGER.warn("Couldn't find a mounted SpiSdCard"); return nullptr; } auto* sdmmc_card = usable_sdcard->getCard(); if (sdmmc_card == nullptr) { - TT_LOG_W(TAG, "SD card has no card object available"); + LOGGER.warn("SD card has no card object available"); return nullptr; } @@ -55,7 +56,7 @@ bool isSupported() { bool startMassStorageWithSdmmc() { if (!canStartNewMode()) { - TT_LOG_E(TAG, "Can't start"); + LOGGER.error("Can't start"); return false; } @@ -63,7 +64,7 @@ bool startMassStorageWithSdmmc() { currentMode = Mode::MassStorageSdmmc; return true; } else { - TT_LOG_E(TAG, "Failed to init mass storage"); + LOGGER.error("Failed to init mass storage"); return false; } } @@ -96,7 +97,7 @@ void rebootIntoMassStorageSdmmc() { // NEW: Flash mass storage functions bool startMassStorageWithFlash() { if (!canStartNewMode()) { - TT_LOG_E(TAG, "Can't start flash mass storage"); + LOGGER.error("Can't start flash mass storage"); return false; } @@ -104,7 +105,7 @@ bool startMassStorageWithFlash() { currentMode = Mode::MassStorageFlash; return true; } else { - TT_LOG_E(TAG, "Failed to init flash mass storage"); + LOGGER.error("Failed to init flash mass storage"); return false; } } diff --git a/Tactility/Source/hal/usb/UsbMock.cpp b/Tactility/Source/hal/usb/UsbMock.cpp index 3ce6fb9c..5e602cee 100644 --- a/Tactility/Source/hal/usb/UsbMock.cpp +++ b/Tactility/Source/hal/usb/UsbMock.cpp @@ -2,8 +2,6 @@ #include "Tactility/hal/usb/Usb.h" -#define TAG "usb" - namespace tt::hal::usb { bool startMassStorageWithSdmmc() { return false; } diff --git a/Tactility/Source/hal/usb/UsbTusb.cpp b/Tactility/Source/hal/usb/UsbTusb.cpp index 455ccc08..12a550df 100644 --- a/Tactility/Source/hal/usb/UsbTusb.cpp +++ b/Tactility/Source/hal/usb/UsbTusb.cpp @@ -7,16 +7,17 @@ #if CONFIG_TINYUSB_MSC_ENABLED == 1 -#include +#include #include #include #include -#define TAG "usb" #define EPNUM_MSC 1 #define TUSB_DESC_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MSC_DESC_LEN) #define SECTOR_SIZE 512 +static const auto LOGGER = tt::Logger("USB"); + namespace tt::hal::usb { extern sdmmc_card_t* _Nullable getCard(); } @@ -93,9 +94,9 @@ 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) { - TT_LOG_I(TAG, "MSC Mounted"); + LOGGER.info("MSC Mounted"); } else { - TT_LOG_I(TAG, "MSC Unmounted"); + LOGGER.info("MSC Unmounted"); } } @@ -121,7 +122,7 @@ static bool ensureDriverInstalled() { }; if (tinyusb_driver_install(&tusb_cfg) != ESP_OK) { - TT_LOG_E(TAG, "Failed to install TinyUSB driver"); + LOGGER.error("Failed to install TinyUSB driver"); return false; } @@ -136,7 +137,7 @@ bool tusbStartMassStorageWithSdmmc() { auto* card = tt::hal::usb::getCard(); if (card == nullptr) { - TT_LOG_E(TAG, "SD card not mounted"); + LOGGER.error("SD card not mounted"); return false; } @@ -155,21 +156,21 @@ bool tusbStartMassStorageWithSdmmc() { auto result = tinyusb_msc_storage_init_sdmmc(&config_sdmmc); if (result != ESP_OK) { - TT_LOG_E(TAG, "TinyUSB SDMMC init failed: %s", esp_err_to_name(result)); + LOGGER.error("TinyUSB SDMMC init failed: {}", esp_err_to_name(result)); } else { - TT_LOG_I(TAG, "TinyUSB SDMMC init success"); + LOGGER.info("TinyUSB SDMMC init success"); } return result == ESP_OK; } bool tusbStartMassStorageWithFlash() { - TT_LOG_I(TAG, "Starting flash MSC"); + LOGGER.info("Starting flash MSC"); ensureDriverInstalled(); wl_handle_t handle = tt::getDataPartitionWlHandle(); if (handle == WL_INVALID_HANDLE) { - TT_LOG_E(TAG, "WL not mounted for /data"); + LOGGER.error("WL not mounted for /data"); return false; } @@ -188,9 +189,9 @@ bool tusbStartMassStorageWithFlash() { esp_err_t result = tinyusb_msc_storage_init_spiflash(&config_flash); if (result != ESP_OK) { - TT_LOG_E(TAG, "TinyUSB flash init failed: %s", esp_err_to_name(result)); + LOGGER.error("TinyUSB flash init failed: {}", esp_err_to_name(result)); } else { - TT_LOG_I(TAG, "TinyUSB flash init success"); + LOGGER.info("TinyUSB flash init success"); } return result == ESP_OK; } diff --git a/Tactility/Source/i18n/TextResources.cpp b/Tactility/Source/i18n/TextResources.cpp index 11ee4b49..14c2fd76 100644 --- a/Tactility/Source/i18n/TextResources.cpp +++ b/Tactility/Source/i18n/TextResources.cpp @@ -1,16 +1,16 @@ -#include "Tactility/i18n/TextResources.h" -#include "Tactility/file/FileLock.h" +#include +#include #include +#include +#include -#include #include #include -#include namespace tt::i18n { -constexpr auto* TAG = "I18n"; +static const auto LOGGER = Logger("I18n"); static std::string getFallbackLocale() { return "en-US"; @@ -39,7 +39,7 @@ static std::string getI18nDataFilePath(const std::string& path) { if (file::isFile(desired_file_path)) { return desired_file_path; } else { - TT_LOG_W(TAG, "Translations not found for %s at %s", locale.c_str(), desired_file_path.c_str()); + LOGGER.warn("Translations not found for {} at {}", locale, desired_file_path); } auto fallback_locale = getFallbackLocale(); @@ -47,7 +47,7 @@ static std::string getI18nDataFilePath(const std::string& path) { if (file::isFile(fallback_file_path)) { return fallback_file_path; } else { - TT_LOG_W(TAG, "Fallback translations not found for %s at %s", fallback_locale.c_str(), fallback_file_path.c_str()); + LOGGER.warn("Fallback translations not found for {} at {}", fallback_locale, fallback_file_path); return ""; } } @@ -60,7 +60,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()) { - TT_LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str()); + LOGGER.error("Couldn't find i18n data for {}", path); return false; } @@ -69,7 +69,7 @@ bool TextResources::load() { }); if (new_data.empty()) { - TT_LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str()); + LOGGER.error("Couldn't find i18n data for {}", path); return false; } diff --git a/Tactility/Source/kernel/SystemEvents.cpp b/Tactility/Source/kernel/SystemEvents.cpp index e326bc7a..58839bdd 100644 --- a/Tactility/Source/kernel/SystemEvents.cpp +++ b/Tactility/Source/kernel/SystemEvents.cpp @@ -1,14 +1,14 @@ #include #include -#include +#include #include #include namespace tt::kernel { -constexpr auto* TAG = "SystemEvents"; +static const auto LOGGER = Logger("SystemEvents"); struct SubscriptionData { SystemEventSubscription id; @@ -57,9 +57,9 @@ static const char* getEventName(SystemEvent event) { } void publishSystemEvent(SystemEvent event) { - TT_LOG_I(TAG, "%s", getEventName(event)); + LOGGER.info("{}", getEventName(event)); - if (mutex.lock(kernel::MAX_TICKS)) { + if (mutex.lock(MAX_TICKS)) { for (auto& subscription : subscriptions) { if (subscription.event == event) { subscription.handler(event); @@ -71,7 +71,7 @@ void publishSystemEvent(SystemEvent event) { } SystemEventSubscription subscribeSystemEvent(SystemEvent event, OnSystemEvent handler) { - if (mutex.lock(kernel::MAX_TICKS)) { + if (mutex.lock(MAX_TICKS)) { auto id = ++subscriptionCounter; subscriptions.push_back({ @@ -88,7 +88,7 @@ SystemEventSubscription subscribeSystemEvent(SystemEvent event, OnSystemEvent ha } void unsubscribeSystemEvent(SystemEventSubscription subscription) { - if (mutex.lock(kernel::MAX_TICKS)) { + if (mutex.lock(MAX_TICKS)) { std::erase_if(subscriptions, [subscription](auto& item) { return (item.id == subscription); }); diff --git a/Tactility/Source/lvgl/EspLvglPort.cpp b/Tactility/Source/lvgl/EspLvglPort.cpp index b1510627..1114b3cd 100644 --- a/Tactility/Source/lvgl/EspLvglPort.cpp +++ b/Tactility/Source/lvgl/EspLvglPort.cpp @@ -2,32 +2,33 @@ #include #include -#include +#include #include #include #include +namespace tt::lvgl { + // LVGL // The minimum task stack seems to be about 3500, but that crashes the wifi app in some scenarios // At 8192, it sometimes crashes when wifi-auto enables and is busy connecting and then you open WifiManage -#define TDECK_LVGL_TASK_STACK_DEPTH 9216 -auto constexpr TAG = "lvgl"; +constexpr auto LVGL_TASK_STACK_DEPTH = 9216; -namespace tt::lvgl { +static const auto LOGGER = Logger("EspLvglPort"); bool initEspLvglPort() { - TT_LOG_D(TAG, "Port init"); + LOGGER.debug("Init"); const lvgl_port_cfg_t lvgl_cfg = { .task_priority = static_cast(Thread::Priority::Critical), - .task_stack = TDECK_LVGL_TASK_STACK_DEPTH, + .task_stack = LVGL_TASK_STACK_DEPTH, .task_affinity = getCpuAffinityConfiguration().graphics, .task_max_sleep_ms = 500, .timer_period_ms = 5 }; if (lvgl_port_init(&lvgl_cfg) != ESP_OK) { - TT_LOG_E(TAG, "Port init failed"); + LOGGER.error("Init failed"); return false; } diff --git a/Tactility/Source/lvgl/LabelUtils.cpp b/Tactility/Source/lvgl/LabelUtils.cpp index 9f6ffd82..23493e6c 100644 --- a/Tactility/Source/lvgl/LabelUtils.cpp +++ b/Tactility/Source/lvgl/LabelUtils.cpp @@ -1,11 +1,9 @@ -#include "Tactility/lvgl/LabelUtils.h" -#include "Tactility/file/File.h" -#include "Tactility/file/FileLock.h" +#include +#include +#include namespace tt::lvgl { -constexpr auto* TAG = "LabelUtils"; - bool label_set_text_file(lv_obj_t* label, const char* filepath) { std::unique_ptr text; file::getLock(filepath)->withLock([&text, filepath] { diff --git a/Tactility/Source/lvgl/Lvgl.cpp b/Tactility/Source/lvgl/Lvgl.cpp index 52c284c0..fc60155c 100644 --- a/Tactility/Source/lvgl/Lvgl.cpp +++ b/Tactility/Source/lvgl/Lvgl.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -18,12 +19,12 @@ namespace tt::lvgl { -constexpr auto* TAG = "Lvgl"; +static const auto LOGGER = Logger("Lvgl"); static bool started = false; void init(const hal::Configuration& config) { - TT_LOG_I(TAG, "Init started"); + LOGGER.info("Init started"); #ifdef ESP_PLATFORM if (config.lvglInit == hal::LvglInit::Default && !initEspLvglPort()) { @@ -33,7 +34,7 @@ void init(const hal::Configuration& config) { start(); - TT_LOG_I(TAG, "Init finished"); + LOGGER.info("Init finished"); } bool isStarted() { @@ -41,10 +42,10 @@ bool isStarted() { } void start() { - TT_LOG_I(TAG, "Start LVGL"); + LOGGER.info("Start LVGL"); if (started) { - TT_LOG_W(TAG, "Can't start LVGL twice"); + LOGGER.warn("Can't start LVGL twice"); return; } @@ -53,12 +54,12 @@ void start() { // Start displays (their related touch devices start automatically within) - TT_LOG_I(TAG, "Start displays"); + LOGGER.info("Start displays"); auto displays = hal::findDevices(hal::Device::Type::Display); - for (auto display : displays) { + for (const auto& display : displays) { if (display->supportsLvgl()) { if (display->startLvgl()) { - TT_LOG_I(TAG, "Started %s", display->getName().c_str()); + LOGGER.info("Started {}", display->getName()); auto lvgl_display = display->getLvglDisplay(); assert(lvgl_display != nullptr); auto settings = settings::display::loadOrGetDefault(); @@ -67,7 +68,7 @@ void start() { lv_display_set_rotation(lvgl_display, rotation); } } else { - TT_LOG_E(TAG, "Start failed for %s", display->getName().c_str()); + LOGGER.error("Start failed for {}", display->getName()); } } } @@ -79,42 +80,42 @@ void start() { // Start display-related peripherals if (primary_display != nullptr) { - TT_LOG_I(TAG, "Start touch devices"); + LOGGER.info("Start touch devices"); auto touch_devices = hal::findDevices(hal::Device::Type::Touch); - for (auto touch_device : touch_devices) { + 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())) { - TT_LOG_I(TAG, "Started %s", touch_device->getName().c_str()); + LOGGER.info("Started {}", touch_device->getName()); } else { - TT_LOG_E(TAG, "Start failed for %s", touch_device->getName().c_str()); + LOGGER.error("Start failed for {}", touch_device->getName()); } } } // Start keyboards - TT_LOG_I(TAG, "Start keyboards"); + LOGGER.info("Start keyboards"); auto keyboards = hal::findDevices(hal::Device::Type::Keyboard); - for (auto keyboard : keyboards) { + 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); - TT_LOG_I(TAG, "Started %s", keyboard->getName().c_str()); + LOGGER.info("Started {}", keyboard->getName()); } else { - TT_LOG_E(TAG, "Start failed for %s", keyboard->getName().c_str()); + LOGGER.error("Start failed for {}", keyboard->getName()); } } } // Start encoders - TT_LOG_I(TAG, "Start encoders"); + LOGGER.info("Start encoders"); auto encoders = hal::findDevices(hal::Device::Type::Encoder); - for (auto encoder : encoders) { + for (const auto& encoder : encoders) { if (encoder->startLvgl(primary_display->getLvglDisplay())) { - TT_LOG_I(TAG, "Started %s", encoder->getName().c_str()); + LOGGER.info("Started {}", encoder->getName()); } else { - TT_LOG_E(TAG, "Start failed for %s", encoder->getName().c_str()); + LOGGER.error("Start failed for {}", encoder->getName()); } } } @@ -127,7 +128,7 @@ void start() { if (service::getState("Gui") == service::State::Stopped) { service::startService("Gui"); } else { - TT_LOG_E(TAG, "Gui service is not in Stopped state"); + LOGGER.error("Gui service is not in Stopped state"); } } @@ -137,7 +138,7 @@ void start() { if (service::getState("Statusbar") == service::State::Stopped) { service::startService("Statusbar"); } else { - TT_LOG_E(TAG, "Statusbar service is not in Stopped state"); + LOGGER.error("Statusbar service is not in Stopped state"); } } @@ -149,10 +150,10 @@ void start() { } void stop() { - TT_LOG_I(TAG, "Stopping LVGL"); + LOGGER.info("Stopping LVGL"); if (!started) { - TT_LOG_W(TAG, "Can't stop LVGL: not started"); + LOGGER.warn("Can't stop LVGL: not started"); return; } @@ -166,7 +167,7 @@ void stop() { // Stop keyboards - TT_LOG_I(TAG, "Stopping keyboards"); + LOGGER.info("Stopping keyboards"); auto keyboards = hal::findDevices(hal::Device::Type::Keyboard); for (auto keyboard : keyboards) { if (keyboard->getLvglIndev() != nullptr) { @@ -176,7 +177,7 @@ void stop() { // Stop touch - TT_LOG_I(TAG, "Stopping touch"); + LOGGER.info("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::Device::Type::Touch); for (auto touch_device : touch_devices) { @@ -187,7 +188,7 @@ void stop() { // Stop encoders - TT_LOG_I(TAG, "Stopping encoders"); + LOGGER.info("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::Device::Type::Encoder); for (auto encoder_device : encoder_devices) { @@ -197,11 +198,11 @@ void stop() { } // Stop displays (and their touch devices) - TT_LOG_I(TAG, "Stopping displays"); + LOGGER.info("Stopping displays"); auto displays = hal::findDevices(hal::Device::Type::Display); for (auto display : displays) { if (display->supportsLvgl() && display->getLvglDisplay() != nullptr && !display->stopLvgl()) { - TT_LOG_E("HelloWorld", "Failed to detach display from LVGL"); + LOGGER.error("Failed to detach display from LVGL"); } } @@ -209,7 +210,7 @@ void stop() { kernel::publishSystemEvent(kernel::SystemEvent::LvglStopped); - TT_LOG_I(TAG, "Stopped LVGL"); + LOGGER.info("Stopped LVGL"); } } // namespace diff --git a/Tactility/Source/lvgl/Spinner.cpp b/Tactility/Source/lvgl/Spinner.cpp index 111f32aa..205eb162 100644 --- a/Tactility/Source/lvgl/Spinner.cpp +++ b/Tactility/Source/lvgl/Spinner.cpp @@ -2,7 +2,6 @@ #include #include -#include #include diff --git a/Tactility/Source/lvgl/Statusbar.cpp b/Tactility/Source/lvgl/Statusbar.cpp index b4f94f48..649fefab 100644 --- a/Tactility/Source/lvgl/Statusbar.cpp +++ b/Tactility/Source/lvgl/Statusbar.cpp @@ -1,22 +1,23 @@ #define LV_USE_PRIVATE_API 1 // For actual lv_obj_t declaration -#include -#include - -#include -#include -#include #include +#include +#include #include #include #include +#include +#include #include +#include +#include +#include #include namespace tt::lvgl { -constexpr auto TAG = "statusbar"; +static const auto LOGGER = Logger("statusbar"); static void onUpdateTime(); @@ -58,7 +59,9 @@ static TickType_t getNextUpdateTime() { time_t now = ::time(nullptr); tm* tm_struct = localtime(&now); uint32_t seconds_to_wait = 60U - tm_struct->tm_sec; - TT_LOG_D(TAG, "Update in %lu s", seconds_to_wait); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Update in {} s", seconds_to_wait); + } return pdMS_TO_TICKS(seconds_to_wait * 1000U); } @@ -101,13 +104,15 @@ static const lv_obj_class_t statusbar_class = { }; static void statusbar_pubsub_event(Statusbar* statusbar) { - TT_LOG_D(TAG, "Update event"); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("Update event"); + } if (lock(defaultLockTime)) { update_main(statusbar); lv_obj_invalidate(&statusbar->obj); unlock(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "Statusbar"); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "Statusbar"); } } @@ -152,7 +157,6 @@ static void update_icon(lv_obj_t* image, const StatusbarIcon* icon) { } lv_obj_t* statusbar_create(lv_obj_t* parent) { - LV_LOG_INFO("begin"); lv_obj_t* obj = lv_obj_class_create_obj(&statusbar_class, parent); lv_obj_class_init_obj(obj); @@ -235,7 +239,9 @@ 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; - TT_LOG_D(TAG, "id %d: added", i); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("id {}: added", i); + } break; } } @@ -249,7 +255,9 @@ int8_t statusbar_icon_add() { } void statusbar_icon_remove(int8_t id) { - TT_LOG_D(TAG, "id %d: remove", id); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("id {}: remove", id); + } tt_check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); StatusbarIcon* icon = &statusbar_data.icons[id]; @@ -261,7 +269,13 @@ void statusbar_icon_remove(int8_t id) { } void statusbar_icon_set_image(int8_t id, const std::string& image) { - TT_LOG_D(TAG, "id %d: set image %s", id, image.empty() ? "(none)" : image.c_str()); + if (LOGGER.isLoggingDebug()) { + if (image.empty()) { + LOGGER.debug("id {}: set image (none)", id); + } else { + LOGGER.debug("id {}: set image {}", id, image); + } + } tt_check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); StatusbarIcon* icon = &statusbar_data.icons[id]; @@ -272,7 +286,9 @@ void statusbar_icon_set_image(int8_t id, const std::string& image) { } void statusbar_icon_set_visibility(int8_t id, bool visible) { - TT_LOG_D(TAG, "id %d: set visibility %d", id, visible); + if (LOGGER.isLoggingDebug()) { + LOGGER.debug("id {}: set visibility {}", id, visible); + } tt_check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); StatusbarIcon* icon = &statusbar_data.icons[id]; diff --git a/Tactility/Source/lvgl/Toolbar.cpp b/Tactility/Source/lvgl/Toolbar.cpp index 68e0e5d7..fdc9c321 100644 --- a/Tactility/Source/lvgl/Toolbar.cpp +++ b/Tactility/Source/lvgl/Toolbar.cpp @@ -1,11 +1,8 @@ #define LV_USE_PRIVATE_API 1 // For actual lv_obj_t declaration -#include -#include #include #include -#include #include namespace tt::lvgl { diff --git a/Tactility/Source/network/Http.cpp b/Tactility/Source/network/Http.cpp index 6b5eb6d6..59dba22e 100644 --- a/Tactility/Source/network/Http.cpp +++ b/Tactility/Source/network/Http.cpp @@ -1,28 +1,28 @@ #include #include +#include #include #ifdef ESP_PLATFORM #include -#include #include #endif namespace tt::network::http { -constexpr auto* TAG = "HTTP"; +static const auto LOGGER = Logger("HTTP"); void download( const std::string& url, const std::string& certFilePath, const std::string &downloadFilePath, - std::function onSuccess, - std::function onError + const std::function& onSuccess, + const std::function& onError ) { - TT_LOG_I(TAG, "Downloading %s to %s", url.c_str(), downloadFilePath.c_str()); + LOGGER.info("Downloading {} to {}", url, downloadFilePath); #ifdef ESP_PLATFORM getMainDispatcher().dispatch([url, certFilePath, downloadFilePath, onSuccess, onError] { - TT_LOG_I(TAG, "Loading certificate"); + LOGGER.info("Loading certificate"); auto certificate = file::readString(certFilePath); if (certificate == nullptr) { onError("Failed to read certificate"); @@ -68,14 +68,14 @@ void download( auto lock = file::getLock(downloadFilePath)->asScopedLock(); lock.lock(); - TT_LOG_I(TAG, "opening %s", downloadFilePath.c_str()); + LOGGER.info("opening {}", downloadFilePath); auto* file = fopen(downloadFilePath.c_str(), "wb"); if (file == nullptr) { onError("Failed to open file"); return; } - TT_LOG_I(TAG, "Writing %d bytes to %s", bytes_left, downloadFilePath.c_str()); + LOGGER.info("Writing {} bytes to {}", bytes_left, downloadFilePath); char buffer[512]; while (bytes_left > 0) { int data_read = client->read(buffer, 512); @@ -92,7 +92,7 @@ void download( } } fclose(file); - TT_LOG_I(TAG, "Downloaded %s to %s", url.c_str(), downloadFilePath.c_str()); + LOGGER.info("Downloaded {} to {}", url, downloadFilePath); onSuccess(); }); #else diff --git a/Tactility/Source/network/HttpServer.cpp b/Tactility/Source/network/HttpServer.cpp index 95be72c1..03792700 100644 --- a/Tactility/Source/network/HttpServer.cpp +++ b/Tactility/Source/network/HttpServer.cpp @@ -2,12 +2,12 @@ #include -#include +#include #include namespace tt::network { -constexpr auto* TAG = "HttpServer"; +static const auto LOGGER = Logger("HttpServer"); bool HttpServer::startInternal() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); @@ -16,7 +16,7 @@ bool HttpServer::startInternal() { config.uri_match_fn = matchUri; if (httpd_start(&server, &config) != ESP_OK) { - TT_LOG_E(TAG, "Failed to start http server on port %lu", port); + LOGGER.error("Failed to start http server on port {}", port); return false; } @@ -24,15 +24,15 @@ bool HttpServer::startInternal() { httpd_register_uri_handler(server, &handler); } - TT_LOG_I(TAG, "Started on port %lu", config.server_port); + LOGGER.info("Started on port {}", config.server_port); return true; } void HttpServer::stopInternal() { - TT_LOG_I(TAG, "Stopping server"); + LOGGER.info("Stopping server"); if (server != nullptr && httpd_stop(server) != ESP_OK) { - TT_LOG_W(TAG, "Error while stopping"); + LOGGER.warn("Error while stopping"); server = nullptr; } } @@ -49,7 +49,7 @@ void HttpServer::stop() { lock.lock(); if (!isStarted()) { - TT_LOG_W(TAG, "Not started"); + LOGGER.warn("Not started"); } stopInternal(); diff --git a/Tactility/Source/network/HttpdReq.cpp b/Tactility/Source/network/HttpdReq.cpp index 08200f9c..d142f2fb 100644 --- a/Tactility/Source/network/HttpdReq.cpp +++ b/Tactility/Source/network/HttpdReq.cpp @@ -1,5 +1,6 @@ #include -#include +#include +#include #include #include @@ -11,7 +12,7 @@ namespace tt::network { -constexpr auto* TAG = "HttpdReq"; +static const auto LOGGER = Logger("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()); @@ -22,7 +23,7 @@ bool getHeaderOrSendError(httpd_req_t* request, const std::string& name, std::st auto header_buffer = std::make_unique(header_size + 1); if (header_buffer == nullptr) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error( LOG_MESSAGE_ALLOC_FAILED); httpd_resp_send_500(request); return false; } @@ -78,7 +79,7 @@ std::unique_ptr receiveByteArray(httpd_req_t* request, size_t length, si // and we don't have exceptions enabled in the compiler settings auto* buffer = static_cast(malloc(length)); if (buffer == nullptr) { - TT_LOG_E(TAG, LOG_MESSAGE_ALLOC_FAILED_FMT, length); + LOGGER.error(LOG_MESSAGE_ALLOC_FAILED_FMT, length); return nullptr; } @@ -86,7 +87,7 @@ std::unique_ptr receiveByteArray(httpd_req_t* request, size_t length, si size_t read_size = length - bytesRead; size_t bytes_received = httpd_req_recv(request, buffer + bytesRead, read_size); if (bytes_received <= 0) { - TT_LOG_W(TAG, "Received %zu / %zu", bytesRead + bytes_received, length); + LOGGER.warn("Received error {} after reading {}/{} bytes", bytes_received, bytesRead, length); return nullptr; } @@ -172,7 +173,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) { - TT_LOG_E(TAG, "Failed to open file for writing: %s", filePath.c_str()); + LOGGER.error("Failed to open file for writing: {}", filePath); return 0; } @@ -180,11 +181,11 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP auto expected_chunk_size = std::min(BUFFER_SIZE, length - bytes_received); size_t receive_chunk_size = httpd_req_recv(request, buffer, expected_chunk_size); if (receive_chunk_size <= 0) { - TT_LOG_E(TAG, "Receive failed"); + LOGGER.error("Receive failed"); break; } if (fwrite(buffer, 1, receive_chunk_size, file) != receive_chunk_size) { - TT_LOG_E(TAG, "Failed to write all bytes"); + LOGGER.error("Failed to write all bytes"); break; } bytes_received += receive_chunk_size; diff --git a/Tactility/Source/network/Ntp.cpp b/Tactility/Source/network/Ntp.cpp index 8ff265df..09633841 100644 --- a/Tactility/Source/network/Ntp.cpp +++ b/Tactility/Source/network/Ntp.cpp @@ -1,6 +1,9 @@ #include +#include #include +#include + #ifdef ESP_PLATFORM #include #include @@ -10,7 +13,8 @@ namespace tt::network::ntp { -constexpr auto* TAG = "NTP"; +static const auto LOGGER = Logger("NTP"); + static bool processedSyncEvent = false; #ifdef ESP_PLATFORM @@ -21,14 +25,14 @@ void storeTimeInNvs() { auto preferences = std::make_unique("time"); preferences->putInt64("syncTime", now); - TT_LOG_I(TAG, "Stored time %llu", now); + LOGGER.info("Stored time {}", now); } void setTimeFromNvs() { auto preferences = std::make_unique("time"); time_t synced_time; if (preferences->optInt64("syncTime", synced_time)) { - TT_LOG_I(TAG, "Restoring last known time to %llu", synced_time); + LOGGER.info("Restoring last known time to {}", synced_time); timeval get_nvs_time; get_nvs_time.tv_sec = synced_time; settimeofday(&get_nvs_time, nullptr); @@ -36,7 +40,7 @@ void setTimeFromNvs() { } static void onTimeSynced(timeval* tv) { - TT_LOG_I(TAG, "Time synced (%llu)", tv->tv_sec); + LOGGER.info("Time synced ({})", tv->tv_sec); processedSyncEvent = true; esp_netif_sntp_deinit(); storeTimeInNvs(); diff --git a/Tactility/Source/network/Url.cpp b/Tactility/Source/network/Url.cpp index 7cbdca85..cc3525d6 100644 --- a/Tactility/Source/network/Url.cpp +++ b/Tactility/Source/network/Url.cpp @@ -1,7 +1,5 @@ #include "Tactility/network/Url.h" -#include - namespace tt::network { std::map parseUrlQuery(std::string query) { diff --git a/Tactility/Source/service/ServiceRegistration.cpp b/Tactility/Source/service/ServiceRegistration.cpp index b89afe9e..3e24e7b1 100644 --- a/Tactility/Source/service/ServiceRegistration.cpp +++ b/Tactility/Source/service/ServiceRegistration.cpp @@ -1,6 +1,6 @@ #include -#include +#include #include #include #include @@ -9,7 +9,7 @@ namespace tt::service { -constexpr auto* TAG = "ServiceRegistry"; +static const auto LOGGER = Logger("ServiceRegistration"); typedef std::unordered_map> ManifestMap; typedef std::unordered_map> ServiceInstanceMap; @@ -25,13 +25,13 @@ void addService(std::shared_ptr manifest, bool autoStart) // We'll move the manifest pointer, but we'll need to id later const auto& id = manifest->id; - TT_LOG_I(TAG, "Adding %s", id.c_str()); + LOGGER.info("Adding {}", id); manifest_mutex.lock(); if (service_manifest_map[id] == nullptr) { service_manifest_map[id] = std::move(manifest); } else { - TT_LOG_E(TAG, "Service id in use: %s", id.c_str()); + LOGGER.error("Service id in use: {}", id); } manifest_mutex.unlock(); @@ -62,10 +62,10 @@ static std::shared_ptr _Nullable findServiceInstanceById(const // TODO: Return proper error/status instead of BOOL? bool startService(const std::string& id) { - TT_LOG_I(TAG, "Starting %s", id.c_str()); + LOGGER.info("Starting {}", id); auto manifest = findManifestById(id); if (manifest == nullptr) { - TT_LOG_E(TAG, "manifest not found for service %s", id.c_str()); + LOGGER.error("manifest not found for service {}", id); return false; } @@ -80,14 +80,14 @@ bool startService(const std::string& id) { if (service_instance->getService()->onStart(*service_instance)) { service_instance->setState(State::Started); } else { - TT_LOG_E(TAG, "Starting %s failed", id.c_str()); + LOGGER.error("Starting {} failed", id); service_instance->setState(State::Stopped); instance_mutex.lock(); service_instance_map.erase(manifest->id); instance_mutex.unlock(); } - TT_LOG_I(TAG, "Started %s", id.c_str()); + LOGGER.info("Started {}", id); return true; } @@ -102,10 +102,10 @@ std::shared_ptr _Nullable findServiceById(const std::string& id) { } bool stopService(const std::string& id) { - TT_LOG_I(TAG, "Stopping %s", id.c_str()); + LOGGER.info("Stopping {}", id); auto service_instance = findServiceInstanceById(id); if (service_instance == nullptr) { - TT_LOG_W(TAG, "Service not running: %s", id.c_str()); + LOGGER.warn("Service not running: {}", id); return false; } @@ -118,10 +118,10 @@ bool stopService(const std::string& id) { instance_mutex.unlock(); if (service_instance.use_count() > 1) { - TT_LOG_W(TAG, "Possible memory leak: service %s still has %ld references", service_instance->getManifest().id.c_str(), service_instance.use_count() - 1); + LOGGER.warn("Possible memory leak: service {} still has {} references", service_instance->getManifest().id, service_instance.use_count() - 1); } - TT_LOG_I(TAG, "Stopped %s", id.c_str()); + LOGGER.info("Stopped {}", id); return true; } diff --git a/Tactility/Source/service/development/DevelopmentService.cpp b/Tactility/Source/service/development/DevelopmentService.cpp index 04a4cf12..df0ecf03 100644 --- a/Tactility/Source/service/development/DevelopmentService.cpp +++ b/Tactility/Source/service/development/DevelopmentService.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -19,7 +20,7 @@ namespace tt::service::development { extern const ServiceManifest manifest; -constexpr const char* TAG = "DevService"; +static const auto LOGGER = Logger("DevService"); bool DevelopmentService::onStart(ServiceContext& service) { std::stringstream stream; @@ -65,26 +66,26 @@ bool DevelopmentService::isEnabled() const { // region endpoints esp_err_t DevelopmentService::handleGetInfo(httpd_req_t* request) { - TT_LOG_I(TAG, "GET /device"); + LOGGER.info("GET /device"); if (httpd_resp_set_type(request, "application/json") != ESP_OK) { - TT_LOG_W(TAG, "Failed to send header"); + LOGGER.warn("Failed to send header"); return ESP_FAIL; } auto* service = static_cast(request->user_ctx); if (httpd_resp_sendstr(request, service->deviceResponse.c_str()) != ESP_OK) { - TT_LOG_W(TAG, "Failed to send response body"); + LOGGER.warn("Failed to send response body"); return ESP_FAIL; } - TT_LOG_I(TAG, "[200] /device"); + LOGGER.info("[200] /device"); return ESP_OK; } esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) { - TT_LOG_I(TAG, "POST /app/run"); + LOGGER.info("POST /app/run"); std::string query; if (!network::getQueryOrSendError(request, query)) { @@ -94,7 +95,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()) { - TT_LOG_W(TAG, "[400] /app/run id not specified"); + LOGGER.warn("[400] /app/run id not specified"); httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id not specified"); return ESP_FAIL; } @@ -106,14 +107,14 @@ esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) { app::start(app_id); - TT_LOG_I(TAG, "[200] /app/run %s", id_key_pos->second.c_str()); + LOGGER.info("[200] /app/run {}", id_key_pos->second); httpd_resp_send(request, nullptr, 0); return ESP_OK; } esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { - TT_LOG_I(TAG, "PUT /app/install"); + LOGGER.info("PUT /app/install"); std::string boundary; if (!network::getMultiPartBoundaryOrSendError(request, boundary)) { @@ -174,7 +175,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { content_left -= boundary_and_newlines_after_file.length(); if (content_left != 0) { - TT_LOG_W(TAG, "We have more bytes at the end of the request parsing?!"); + LOGGER.warn("We have more bytes at the end of the request parsing?!"); } if (!app::install(file_path)) { @@ -182,11 +183,11 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { return ESP_FAIL; } - if (!file::deleteFile(file_path.c_str())) { - TT_LOG_W(TAG, "Failed to delete %s", file_path.c_str()); + if (!file::deleteFile(file_path)) { + LOGGER.warn("Failed to delete {}", file_path); } - TT_LOG_I(TAG, "[200] /app/install -> %s", file_path.c_str()); + LOGGER.info("[200] /app/install -> {}", file_path); httpd_resp_send(request, nullptr, 0); @@ -194,7 +195,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { } esp_err_t DevelopmentService::handleAppUninstall(httpd_req_t* request) { - TT_LOG_I(TAG, "PUT /app/uninstall"); + LOGGER.info("PUT /app/uninstall"); std::string query; if (!network::getQueryOrSendError(request, query)) { @@ -204,23 +205,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()) { - TT_LOG_W(TAG, "[400] /app/uninstall id not specified"); + LOGGER.warn("[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)) { - TT_LOG_I(TAG, "[200] /app/uninstall %s (app wasn't installed)", id_key_pos->second.c_str()); + LOGGER.info("[200] /app/uninstall {} (app wasn't installed)", id_key_pos->second); httpd_resp_send(request, nullptr, 0); return ESP_OK; } if (app::uninstall(id_key_pos->second)) { - TT_LOG_I(TAG, "[200] /app/uninstall %s", id_key_pos->second.c_str()); + LOGGER.info("[200] /app/uninstall {}", id_key_pos->second); httpd_resp_send(request, nullptr, 0); return ESP_OK; } else { - TT_LOG_W(TAG, "[500] /app/uninstall %s", id_key_pos->second.c_str()); + LOGGER.warn("[500] /app/uninstall {}", id_key_pos->second); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to uninstall"); return ESP_FAIL; } diff --git a/Tactility/Source/service/development/DevelopmentSettings.cpp b/Tactility/Source/service/development/DevelopmentSettings.cpp index 74153141..04b2fccf 100644 --- a/Tactility/Source/service/development/DevelopmentSettings.cpp +++ b/Tactility/Source/service/development/DevelopmentSettings.cpp @@ -1,13 +1,14 @@ #ifdef ESP_PLATFORM #include -#include +#include #include #include #include namespace tt::service::development { -constexpr auto* TAG = "DevSettings"; +static const auto LOGGER = Logger("DevSettings"); + constexpr auto* SETTINGS_FILE = "/data/settings/development.properties"; constexpr auto* SETTINGS_KEY_ENABLE_ON_BOOT = "enableOnBoot"; @@ -39,7 +40,7 @@ static bool save(const DevelopmentSettings& settings) { void setEnableOnBoot(bool enable) { DevelopmentSettings properties { .enableOnBoot = enable }; if (!save(properties)) { - TT_LOG_E(TAG, "Failed to save %s", SETTINGS_FILE); + LOGGER.error("Failed to save {}", SETTINGS_FILE); } } diff --git a/Tactility/Source/service/displayidle/DisplayIdle.cpp b/Tactility/Source/service/displayidle/DisplayIdle.cpp index 94daafff..06424c6e 100644 --- a/Tactility/Source/service/displayidle/DisplayIdle.cpp +++ b/Tactility/Source/service/displayidle/DisplayIdle.cpp @@ -1,16 +1,14 @@ #include -#include #include #include #include #include #include #include +#include namespace tt::service::displayidle { -constexpr auto* TAG = "DisplayIdle"; - class DisplayIdleService final : public Service { std::unique_ptr timer; diff --git a/Tactility/Source/service/espnow/EspNow.cpp b/Tactility/Source/service/espnow/EspNow.cpp index ca1aec11..1834b062 100644 --- a/Tactility/Source/service/espnow/EspNow.cpp +++ b/Tactility/Source/service/espnow/EspNow.cpp @@ -4,21 +4,21 @@ #ifdef CONFIG_ESP_WIFI_ENABLED -#include "Tactility/service/espnow/EspNow.h" -#include "Tactility/service/espnow/EspNowService.h" +#include +#include -#include +#include namespace tt::service::espnow { -constexpr const char* TAG = "EspNow"; +static const auto LOGGER = Logger("EspNow"); void enable(const EspNowConfig& config) { auto service = findService(); if (service != nullptr) { service->enable(config); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); } } @@ -27,7 +27,7 @@ void disable() { if (service != nullptr) { service->disable(); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); } } @@ -45,7 +45,7 @@ bool addPeer(const esp_now_peer_info_t& peer) { if (service != nullptr) { return service->addPeer(peer); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); return false; } } @@ -55,7 +55,7 @@ bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength) { if (service != nullptr) { return service->send(address, buffer, bufferLength); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); return false; } } @@ -65,7 +65,7 @@ ReceiverSubscription subscribeReceiver(std::functionsubscribeReceiver(onReceive); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); return -1; } } @@ -75,7 +75,7 @@ void unsubscribeReceiver(ReceiverSubscription subscription) { if (service != nullptr) { service->unsubscribeReceiver(subscription); } else { - TT_LOG_E(TAG, "Service not found"); + LOGGER.error("Service not found"); } } diff --git a/Tactility/Source/service/espnow/EspNowService.cpp b/Tactility/Source/service/espnow/EspNowService.cpp index 393491d1..0fa9357a 100644 --- a/Tactility/Source/service/espnow/EspNowService.cpp +++ b/Tactility/Source/service/espnow/EspNowService.cpp @@ -4,6 +4,7 @@ #ifdef CONFIG_ESP_WIFI_ENABLED +#include #include #include #include @@ -18,10 +19,10 @@ namespace tt::service::espnow { extern const ServiceManifest manifest; -constexpr const char* TAG = "EspNowService"; -constexpr TickType_t MAX_DELAY = 1000U / portTICK_PERIOD_MS; +static const auto LOGGER = Logger("EspNowService"); static uint8_t BROADCAST_MAC[ESP_NOW_ETH_ALEN]; +constexpr TickType_t MAX_DELAY = 1000U / portTICK_PERIOD_MS; constexpr bool isBroadcastAddress(uint8_t address[ESP_NOW_ETH_ALEN]) { return memcmp(address, BROADCAST_MAC, ESP_NOW_ETH_ALEN) == 0; } bool EspNowService::onStart(ServiceContext& service) { @@ -45,7 +46,7 @@ void EspNowService::onStop(ServiceContext& service) { // region Enable void EspNowService::enable(const EspNowConfig& config) { - getMainDispatcher().dispatch([this, config]() { + getMainDispatcher().dispatch([this, config] { enableFromDispatcher(config); }); } @@ -59,17 +60,17 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) { } if (!initWifi(config)) { - TT_LOG_E(TAG, "initWifi() failed"); + LOGGER.error("initWifi() failed"); return; } if (esp_now_init() != ESP_OK) { - TT_LOG_E(TAG, "esp_now_init() failed"); + LOGGER.error("esp_now_init() failed"); return; } if (esp_now_register_recv_cb(receiveCallback) != ESP_OK) { - TT_LOG_E(TAG, "esp_now_register_recv_cb() failed"); + LOGGER.error("esp_now_register_recv_cb() failed"); return; } @@ -79,7 +80,7 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) { //#endif if (esp_now_set_pmk(config.masterKey) != ESP_OK) { - TT_LOG_E(TAG, "esp_now_set_pmk() failed"); + LOGGER.error("esp_now_set_pmk() failed"); return; } @@ -111,11 +112,11 @@ void EspNowService::disableFromDispatcher() { } if (esp_now_deinit() != ESP_OK) { - TT_LOG_E(TAG, "esp_now_deinit() failed"); + LOGGER.error("esp_now_deinit() failed"); } if (!deinitWifi()) { - TT_LOG_E(TAG, "deinitWifi() failed"); + LOGGER.error("deinitWifi() failed"); } enabled = false; @@ -128,7 +129,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) { - TT_LOG_E(TAG, "Service not running"); + LOGGER.error("Service not running"); return; } service->onReceive(receiveInfo, data, length); @@ -138,7 +139,7 @@ void EspNowService::onReceive(const esp_now_recv_info_t* receiveInfo, const uint auto lock = mutex.asScopedLock(); lock.lock(); - TT_LOG_D(TAG, "Received %d bytes", length); + LOGGER.debug("Received {} bytes", length); for (const auto& item: subscriptions) { item.onReceive(receiveInfo, data, length); @@ -155,10 +156,10 @@ bool EspNowService::isEnabled() const { bool EspNowService::addPeer(const esp_now_peer_info_t& peer) { if (esp_now_add_peer(&peer) != ESP_OK) { - TT_LOG_E(TAG, "Failed to add peer"); + LOGGER.error("Failed to add peer"); return false; } else { - TT_LOG_I(TAG, "Peer added"); + LOGGER.info("Peer added"); return true; } } @@ -188,7 +189,7 @@ ReceiverSubscription EspNowService::subscribeReceiver(std::function findService() { return std::static_pointer_cast( - service::findServiceById(manifest.id) + findServiceById(manifest.id) ); } diff --git a/Tactility/Source/service/espnow/EspNowWifi.cpp b/Tactility/Source/service/espnow/EspNowWifi.cpp index 53d69582..db727ad9 100644 --- a/Tactility/Source/service/espnow/EspNowWifi.cpp +++ b/Tactility/Source/service/espnow/EspNowWifi.cpp @@ -5,7 +5,7 @@ #ifdef CONFIG_ESP_WIFI_ENABLED #include -#include +#include #include #include @@ -14,7 +14,7 @@ namespace tt::service::espnow { -constexpr const char* TAG = "EspNowService"; +static const auto LOGGER = Logger("EspNowService"); static bool disableWifiService() { auto wifi_state = wifi::getRadioState(); @@ -43,7 +43,7 @@ bool initWifi(const EspNowConfig& config) { // If WiFi is already connected, keep it running and just add ESP-NOW on top if (!wifi_was_connected && wifi_state != wifi::RadioState::Off && wifi_state != wifi::RadioState::OffPending) { if (!disableWifiService()) { - TT_LOG_E(TAG, "Failed to disable wifi"); + LOGGER.error("Failed to disable wifi"); return false; } } @@ -60,28 +60,28 @@ bool initWifi(const EspNowConfig& config) { if (wifi::getRadioState() == wifi::RadioState::Off) { wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); if (esp_wifi_init(&cfg) != ESP_OK) { - TT_LOG_E(TAG, "esp_wifi_init() failed"); + LOGGER.error("esp_wifi_init() failed"); return false; } if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) { - TT_LOG_E(TAG, "esp_wifi_set_storage() failed"); + LOGGER.error("esp_wifi_set_storage() failed"); return false; } if (esp_wifi_set_mode(mode) != ESP_OK) { - TT_LOG_E(TAG, "esp_wifi_set_mode() failed"); + LOGGER.error("esp_wifi_set_mode() failed"); return false; } if (esp_wifi_start() != ESP_OK) { - TT_LOG_E(TAG, "esp_wifi_start() failed"); + LOGGER.error("esp_wifi_start() failed"); return false; } } if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) { - TT_LOG_E(TAG, "esp_wifi_set_channel() failed"); + LOGGER.error("esp_wifi_set_channel() failed"); return false; } @@ -94,11 +94,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) { - TT_LOG_W(TAG, "esp_wifi_set_protocol() for long range failed"); + LOGGER.warn("esp_wifi_set_protocol() for long range failed"); } } - TT_LOG_I(TAG, "WiFi initialized for ESP-NOW (preserved existing connection: %s)", wifi_was_connected ? "yes" : "no"); + LOGGER.info("WiFi initialized for ESP-NOW (preserved existing connection: {})", wifi_was_connected ? "yes" : "no"); return true; } @@ -110,7 +110,7 @@ bool deinitWifi() { // Since we're only using WiFi for ESP-NOW, we can safely keep it in a minimal state // or shut it down. For now, keep it running to support STA + ESP-NOW coexistence. - TT_LOG_I(TAG, "ESP-NOW WiFi deinitialized (WiFi service continues independently)"); + LOGGER.info("ESP-NOW WiFi deinitialized (WiFi service continues independently)"); return true; } diff --git a/Tactility/Source/service/gps/GpsConfiguration.cpp b/Tactility/Source/service/gps/GpsConfiguration.cpp index e1414e54..aa278373 100644 --- a/Tactility/Source/service/gps/GpsConfiguration.cpp +++ b/Tactility/Source/service/gps/GpsConfiguration.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -9,16 +10,16 @@ using tt::hal::gps::GpsDevice; namespace tt::service::gps { -constexpr const char* TAG = "GpsService"; +static const auto LOGGER = Logger("GpsService"); bool GpsService::getConfigurationFilePath(std::string& output) const { if (paths == nullptr) { - TT_LOG_E(TAG, "Can't add configuration: service not started"); + LOGGER.error("Can't add configuration: service not started"); return false; } if (!file::findOrCreateDirectory(paths->getUserDataDirectory(), 0777)) { - TT_LOG_E(TAG, "Failed to find or create path %s", paths->getUserDataDirectory().c_str()); + LOGGER.error("Failed to find or create path {}", paths->getUserDataDirectory()); return false; } @@ -34,21 +35,21 @@ bool GpsService::getGpsConfigurations(std::vector& c // If file does not exist, return empty list if (access(path.c_str(), F_OK) != 0) { - TT_LOG_W(TAG, "No configurations (file not found: %s)", path.c_str()); + LOGGER.warn("No configurations (file not found: {})", path); return true; } - TT_LOG_I(TAG, "Reading configuration file %s", path.c_str()); + LOGGER.info("Reading configuration file {}", path); auto reader = file::ObjectFileReader(path, sizeof(hal::gps::GpsConfiguration)); if (!reader.open()) { - TT_LOG_E(TAG, "Failed to open configuration file"); + LOGGER.error("Failed to open configuration file"); return false; } hal::gps::GpsConfiguration configuration; while (reader.hasNext()) { if (!reader.readNext(&configuration)) { - TT_LOG_E(TAG, "Failed to read configuration"); + LOGGER.error("Failed to read configuration"); reader.close(); return false; } else { @@ -67,12 +68,12 @@ bool GpsService::addGpsConfiguration(hal::gps::GpsConfiguration configuration) { auto appender = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, true); if (!appender.open()) { - TT_LOG_E(TAG, "Failed to open/create configuration file"); + LOGGER.error("Failed to open/create configuration file"); return false; } if (!appender.write(&configuration)) { - TT_LOG_E(TAG, "Failed to add configuration"); + LOGGER.error("Failed to add configuration"); appender.close(); return false; } @@ -89,7 +90,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration std::vector configurations; if (!getGpsConfigurations(configurations)) { - TT_LOG_E(TAG, "Failed to get gps configurations"); + LOGGER.error("Failed to get gps configurations"); return false; } @@ -101,7 +102,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration auto writer = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, false); if (!writer.open()) { - TT_LOG_E(TAG, "Failed to open configuration file"); + LOGGER.error("Failed to open configuration file"); return false; } diff --git a/Tactility/Source/service/gps/GpsService.cpp b/Tactility/Source/service/gps/GpsService.cpp index eff34464..69cc251c 100644 --- a/Tactility/Source/service/gps/GpsService.cpp +++ b/Tactility/Source/service/gps/GpsService.cpp @@ -1,7 +1,7 @@ #include #include -#include +#include #include #include #include @@ -10,7 +10,7 @@ using tt::hal::gps::GpsDevice; namespace tt::service::gps { -constexpr const char* TAG = "GpsService"; +static const auto LOGGER = Logger("GpsService"); extern const ServiceManifest manifest; constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) { @@ -73,7 +73,7 @@ void GpsService::onStop(ServiceContext& serviceContext) { } bool GpsService::startGpsDevice(GpsDeviceRecord& record) { - TT_LOG_I(TAG, "[device %lu] starting", record.device->getId()); + LOGGER.info("[device {}] starting", record.device->getId()); auto lock = mutex.asScopedLock(); lock.lock(); @@ -81,7 +81,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) { auto device = record.device; if (!device->start()) { - TT_LOG_E(TAG, "[device %lu] starting failed", record.device->getId()); + LOGGER.error("[device {}] starting failed", record.device->getId()); return false; } @@ -105,7 +105,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) { } bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { - TT_LOG_I(TAG, "[device %lu] stopping", record.device->getId()); + LOGGER.info("[device {}] stopping", record.device->getId()); auto device = record.device; @@ -116,7 +116,7 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { record.rmcSubscriptionId = -1; if (!device->stop()) { - TT_LOG_E(TAG, "[device %lu] stopping failed", record.device->getId()); + LOGGER.error("[device {}] stopping failed", record.device->getId()); return false; } @@ -124,10 +124,10 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { } bool GpsService::startReceiving() { - TT_LOG_I(TAG, "Start receiving"); + LOGGER.info("Start receiving"); if (getState() != State::Off) { - TT_LOG_E(TAG, "Already receiving"); + LOGGER.error("Already receiving"); return false; } @@ -140,13 +140,13 @@ bool GpsService::startReceiving() { std::vector configurations; if (!getGpsConfigurations(configurations)) { - TT_LOG_E(TAG, "Failed to get GPS configurations"); + LOGGER.error("Failed to get GPS configurations"); setState(State::Off); return false; } if (configurations.empty()) { - TT_LOG_E(TAG, "No GPS configurations"); + LOGGER.error("No GPS configurations"); setState(State::Off); return false; } @@ -174,7 +174,7 @@ bool GpsService::startReceiving() { } void GpsService::stopReceiving() { - TT_LOG_I(TAG, "Stop receiving"); + LOGGER.info("Stop receiving"); setState(State::OffPending); @@ -191,11 +191,11 @@ void GpsService::stopReceiving() { } void GpsService::onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga) { - TT_LOG_D(TAG, "[device %lu] LAT %f LON %f, satellites: %d", deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked); + LOGGER.debug("[device {}] LAT {} LON {}, satellites: {}", deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked); } void GpsService::onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc) { - TT_LOG_D(TAG, "[device %lu] LAT %f LON %f, speed: %.2f", deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed)); + LOGGER.debug("[device {}] LAT {} LON {}, speed: {}", deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed)); } State GpsService::getState() const { diff --git a/Tactility/Source/service/gui/GuiService.cpp b/Tactility/Source/service/gui/GuiService.cpp index 963f826b..2a98df34 100644 --- a/Tactility/Source/service/gui/GuiService.cpp +++ b/Tactility/Source/service/gui/GuiService.cpp @@ -1,6 +1,8 @@ #include #include +#include +#include #include #include #include @@ -10,7 +12,7 @@ namespace tt::service::gui { extern const ServiceManifest manifest; -constexpr auto* TAG = "GuiService"; +static const auto LOGGER = Logger("GuiService"); using namespace loader; // region AppManifest @@ -39,10 +41,7 @@ int32_t GuiService::guiMain() { // Process and dispatch draw call if (flags & GUI_THREAD_FLAG_DRAW) { service->threadFlags.clear(GUI_THREAD_FLAG_DRAW); - auto service = findService(); - if (service != nullptr) { - service->redraw(); - } + service->redraw(); } if (flags & GUI_THREAD_FLAG_EXIT) { @@ -103,13 +102,13 @@ void GuiService::redraw() { lv_obj_t* container = createAppViews(appRootWidget); appToRender->getApp()->onShow(*appToRender, container); } else { - TT_LOG_W(TAG, "nothing to draw"); + LOGGER.warn("nothing to draw"); } // Unlock GUI and LVGL lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } unlock(); @@ -118,7 +117,7 @@ void GuiService::redraw() { bool GuiService::onStart(TT_UNUSED ServiceContext& service) { auto* screen_root = lv_screen_active(); if (screen_root == nullptr) { - TT_LOG_E(TAG, "No display found"); + LOGGER.error("No display found"); return false; } @@ -202,16 +201,16 @@ void GuiService::showApp(std::shared_ptr app) { lock.lock(); if (!isStarted) { - TT_LOG_E(TAG, "Failed to show app %s: GUI not started", app->getManifest().appId.c_str()); + LOGGER.error("Failed to show app {}: GUI not started", app->getManifest().appId); return; } if (appToRender != nullptr && appToRender->getLaunchId() == app->getLaunchId()) { - TT_LOG_W(TAG, "Already showing %s", app->getManifest().appId.c_str()); + LOGGER.warn("Already showing {}", app->getManifest().appId); return; } - TT_LOG_I(TAG, "Showing %s", app->getManifest().appId.c_str()); + LOGGER.info("Showing {}", app->getManifest().appId); // Ensure previous app triggers onHide() logic if (appToRender != nullptr) { hideApp(); @@ -226,12 +225,12 @@ void GuiService::hideApp() { lock.lock(); if (!isStarted) { - TT_LOG_E(TAG, "Failed to hide app: GUI not started"); + LOGGER.error("Failed to hide app: GUI not started"); return; } if (appToRender == nullptr) { - TT_LOG_W(TAG, "hideApp() called but no app is currently shown"); + LOGGER.warn("hideApp() called but no app is currently shown"); return; } diff --git a/Tactility/Source/service/keyboardidle/KeyboardIdle.cpp b/Tactility/Source/service/keyboardidle/KeyboardIdle.cpp index e595d5f9..feab24f8 100644 --- a/Tactility/Source/service/keyboardidle/KeyboardIdle.cpp +++ b/Tactility/Source/service/keyboardidle/KeyboardIdle.cpp @@ -15,8 +15,6 @@ namespace keyboardbacklight { namespace tt::service::keyboardidle { -constexpr auto* TAG = "KeyboardIdle"; - class KeyboardIdleService final : public Service { std::unique_ptr timer; diff --git a/Tactility/Source/service/loader/Loader.cpp b/Tactility/Source/service/loader/Loader.cpp index bca45bc2..dc4cccc4 100644 --- a/Tactility/Source/service/loader/Loader.cpp +++ b/Tactility/Source/service/loader/Loader.cpp @@ -4,6 +4,8 @@ #include #include +#include +#include #include #include @@ -16,7 +18,8 @@ namespace tt::service::loader { -constexpr auto* TAG = "Loader"; +static const auto LOGGER = Logger("Boot"); + constexpr auto LOADER_TIMEOUT = (100 / portTICK_PERIOD_MS); // Forward declaration @@ -41,17 +44,17 @@ static const char* appStateToString(app::State state) { } void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launchId, std::shared_ptr parameters) { - TT_LOG_I(TAG, "Start by id %s", id.c_str()); + LOGGER.info("Start by id {}", id); auto app_manifest = app::findAppManifestById(id); if (app_manifest == nullptr) { - TT_LOG_E(TAG, "App not found: %s", id.c_str()); + LOGGER.error("App not found: {}", id); return; } auto lock = mutex.asScopedLock(); if (!lock.lock(LOADER_TIMEOUT)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -73,14 +76,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)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } size_t original_stack_size = appStack.size(); if (original_stack_size == 0) { - TT_LOG_E(TAG, "Stop app: no app running"); + LOGGER.error("Stop app: no app running"); return; } @@ -88,12 +91,12 @@ void LoaderService::onStopTopAppMessage(const std::string& id) { auto app_to_stop = appStack[appStack.size() - 1]; if (app_to_stop->getManifest().appId != id) { - TT_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()); + LOGGER.error("Stop app: id mismatch (wanted {} but found {} on top of stack)", id, app_to_stop->getManifest().appId); return; } if (original_stack_size == 1 && app_to_stop->getManifest().appName != "Boot") { - TT_LOG_E(TAG, "Stop app: can't stop root app"); + LOGGER.error("Stop app: can't stop root app"); return; } @@ -113,16 +116,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) { - TT_LOG_W(TAG, "Memory leak: Stopped %s, but use count is %ld", app_to_stop->getManifest().appId.c_str(), 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); } // 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) { - TT_LOG_W(TAG, "Memory leak: Stopped %s, but use count is %ld", app_to_stop->getManifest().appId.c_str(), 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); } #ifdef ESP_PLATFORM - TT_LOG_I(TAG, "Free heap: %zu", heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); + LOGGER.info("Free heap: {}", heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); #endif std::shared_ptr instance_to_resume; @@ -179,18 +182,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)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } if (!isRunning(id)) { - TT_LOG_E(TAG, "Stop all: %s not running", id.c_str()); + LOGGER.error("Stop all: {} not running", id); return; } int app_to_stop_index = findAppInStack(id); if (app_to_stop_index < 0) { - TT_LOG_E(TAG, "Stop all: %s not found in stack", id.c_str()); + LOGGER.error("Stop all: {} not found in stack", id); return; } @@ -217,7 +220,7 @@ void LoaderService::onStopAllAppMessage(const std::string& id) { } if (instance_to_resume != nullptr) { - TT_LOG_I(TAG, "Resuming %s", instance_to_resume->getManifest().appId.c_str()); + LOGGER.info("Resuming {}", instance_to_resume->getManifest().appId); transitionAppToState(instance_to_resume, app::State::Showing); instance_to_resume->getApp()->onResult( @@ -233,10 +236,8 @@ void LoaderService::transitionAppToState(const std::shared_ptr const app::AppManifest& app_manifest = app->getManifest(); const app::State old_state = app->getState(); - TT_LOG_I( - TAG, - "App \"%s\" state: %s -> %s", - app_manifest.appId.c_str(), + LOGGER.info( "App \"{}\" state: {} -> {}", + app_manifest.appId, appStateToString(old_state), appStateToString(state) ); @@ -283,14 +284,14 @@ void LoaderService::stopTop() { } void LoaderService::stopTop(const std::string& id) { - TT_LOG_I(TAG, "dispatching stopTop(%s)", id.c_str()); + LOGGER.info("dispatching stopTop({})", id); dispatcherThread->dispatch([this, id] { onStopTopAppMessage(id); }); } void LoaderService::stopAll(const std::string& id) { - TT_LOG_I(TAG, "dispatching stopAll(%s)", id.c_str()); + LOGGER.info("dispatching stopAll({})", id); dispatcherThread->dispatch([this, id] { onStopAllAppMessage(id); }); diff --git a/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp b/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp index 7bf7c5c2..ff051095 100644 --- a/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp +++ b/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp @@ -1,4 +1,6 @@ #include + +#include #include #include #include @@ -7,7 +9,7 @@ namespace tt::service::memorychecker { -constexpr const char* TAG = "MemoryChecker"; +static const auto LOGGER = Logger("MemoryChecker"); // Total memory (in bytes) that should be free before warnings occur constexpr auto TOTAL_FREE_THRESHOLD = 10'000; @@ -36,13 +38,13 @@ static bool isMemoryLow() { bool memory_low = false; const auto total_free = getInternalFree(); if (total_free < TOTAL_FREE_THRESHOLD) { - TT_LOG_W(TAG, "Internal memory low: %zu bytes", total_free); + LOGGER.warn("Internal memory low: {} bytes", total_free); memory_low = true; } const auto largest_block = getInternalLargestFreeBlock(); if (largest_block < LARGEST_FREE_BLOCK_THRESHOLD) { - TT_LOG_W(TAG, "Largest free internal memory block is %zu bytes", largest_block); + LOGGER.warn("Largest free internal memory block is {} bytes", largest_block); memory_low = true; } diff --git a/Tactility/Source/service/screenshot/Screenshot.cpp b/Tactility/Source/service/screenshot/Screenshot.cpp index 14d0782b..64d57a46 100644 --- a/Tactility/Source/service/screenshot/Screenshot.cpp +++ b/Tactility/Source/service/screenshot/Screenshot.cpp @@ -2,7 +2,7 @@ #if TT_FEATURE_SCREENSHOT_ENABLED -#include +#include #include #include #include @@ -12,7 +12,7 @@ namespace tt::service::screenshot { -constexpr auto* TAG = "ScreenshotService"; +static const auto LOGGER = Logger("ScreenshotService"); extern const ServiceManifest manifest; @@ -23,7 +23,7 @@ std::shared_ptr _Nullable optScreenshotService() { void ScreenshotService::startApps(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -32,14 +32,14 @@ void ScreenshotService::startApps(const std::string& path) { mode = Mode::Apps; task->startApps(path); } else { - TT_LOG_W(TAG, "Screenshot task already running"); + LOGGER.warn("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)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -48,13 +48,13 @@ void ScreenshotService::startTimed(const std::string& path, uint8_t delayInSecon mode = Mode::Timed; task->startTimed(path, delayInSeconds, amount); } else { - TT_LOG_W(TAG, "Screenshot task already running"); + LOGGER.warn("Screenshot task already running"); } } bool ScreenshotService::onStart(ServiceContext& serviceContext) { if (lv_screen_active() == nullptr) { - TT_LOG_E(TAG, "No display found"); + LOGGER.error("No display found"); return false; } @@ -64,7 +64,7 @@ bool ScreenshotService::onStart(ServiceContext& serviceContext) { void ScreenshotService::stop() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -72,14 +72,14 @@ void ScreenshotService::stop() { task = nullptr; mode = Mode::None; } else { - TT_LOG_W(TAG, "Screenshot task not running"); + LOGGER.warn("Screenshot task not running"); } } Mode ScreenshotService::getMode() const { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return Mode::None; } diff --git a/Tactility/Source/service/screenshot/ScreenshotTask.cpp b/Tactility/Source/service/screenshot/ScreenshotTask.cpp index 2c32f997..00511628 100644 --- a/Tactility/Source/service/screenshot/ScreenshotTask.cpp +++ b/Tactility/Source/service/screenshot/ScreenshotTask.cpp @@ -1,21 +1,22 @@ -#include "Tactility/TactilityConfig.h" +#include #if TT_FEATURE_SCREENSHOT_ENABLED -#include "Tactility/service/screenshot/ScreenshotTask.h" - -#include "Tactility/service/loader/Loader.h" -#include "Tactility/lvgl/LvglSync.h" - -#include +#include +#include +#include +#include +#include +#include #include +#include + #include -#include namespace tt::service::screenshot { -#define TAG "screenshot_task" +static const auto LOGGER = Logger("ScreenshotTask"); ScreenshotTask::~ScreenshotTask() { if (thread) { @@ -26,7 +27,7 @@ ScreenshotTask::~ScreenshotTask() { bool ScreenshotTask::isInterrupted() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return true; } return interrupted; @@ -35,7 +36,7 @@ bool ScreenshotTask::isInterrupted() { bool ScreenshotTask::isFinished() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); return false; } return finished; @@ -50,13 +51,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())) { - TT_LOG_I(TAG, "Screenshot saved to %s", filename.c_str()); + LOGGER.info("Screenshot saved to {}", filename); } else { - TT_LOG_E(TAG, "Screenshot not saved to %s", filename.c_str()); + LOGGER.error("Screenshot not saved to {}", filename); } lvgl::unlock(); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } @@ -102,7 +103,7 @@ void ScreenshotTask::taskMain() { void ScreenshotTask::taskStart() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -122,7 +123,7 @@ void ScreenshotTask::taskStart() { void ScreenshotTask::startApps(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -132,14 +133,14 @@ void ScreenshotTask::startApps(const std::string& path) { work.path = path; taskStart(); } else { - TT_LOG_E(TAG, "Task was already running"); + LOGGER.error("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)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -151,7 +152,7 @@ void ScreenshotTask::startTimed(const std::string& path, uint8_t delay_in_second work.path = path; taskStart(); } else { - TT_LOG_E(TAG, "Task was already running"); + LOGGER.error("Task was already running"); } } diff --git a/Tactility/Source/service/sdcard/Sdcard.cpp b/Tactility/Source/service/sdcard/Sdcard.cpp index 4668daa9..1cbddb82 100644 --- a/Tactility/Source/service/sdcard/Sdcard.cpp +++ b/Tactility/Source/service/sdcard/Sdcard.cpp @@ -1,14 +1,15 @@ +#include +#include +#include +#include #include #include - -#include -#include #include -#include +#include namespace tt::service::sdcard { -constexpr auto* TAG = "SdcardService"; +static const auto LOGGER = Logger("SdcardService"); extern const ServiceManifest manifest; @@ -37,7 +38,7 @@ class SdCardService final : public Service { auto new_state = sdcard->getState(); if (new_state == hal::sdcard::SdCardDevice::State::Error) { - TT_LOG_E(TAG, "Sdcard error - unmounting. Did you eject the card in an unsafe manner?"); + LOGGER.error("Sdcard error - unmounting. Did you eject the card in an unsafe manner?"); sdcard->unmount(); } @@ -47,7 +48,7 @@ class SdCardService final : public Service { unlock(); } else { - TT_LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); } } @@ -55,7 +56,7 @@ public: bool onStart(ServiceContext& serviceContext) override { if (hal::findFirstDevice(hal::Device::Type::SdCard) == nullptr) { - TT_LOG_W(TAG, "No SD card device found - not starting Service"); + LOGGER.warn("No SD card device found - not starting Service"); return false; } diff --git a/Tactility/Source/service/statusbar/Statusbar.cpp b/Tactility/Source/service/statusbar/Statusbar.cpp index 1cd89faa..636d33a9 100644 --- a/Tactility/Source/service/statusbar/Statusbar.cpp +++ b/Tactility/Source/service/statusbar/Statusbar.cpp @@ -1,20 +1,21 @@ #include -#include -#include #include #include +#include #include #include +#include #include #include #include #include #include +#include namespace tt::service::statusbar { -constexpr auto* TAG = "StatusbarService"; +static const auto LOGGER = Logger("StatusbarService"); // SD card status constexpr auto* STATUSBAR_ICON_SDCARD = "sdcard.png"; @@ -252,7 +253,7 @@ public: bool onStart(ServiceContext& serviceContext) override { if (lv_screen_active() == nullptr) { - TT_LOG_E(TAG, "No display found"); + LOGGER.error("No display found"); return false; } diff --git a/Tactility/Source/service/wifi/WifiApSettings.cpp b/Tactility/Source/service/wifi/WifiApSettings.cpp index 3f704a44..292062ad 100644 --- a/Tactility/Source/service/wifi/WifiApSettings.cpp +++ b/Tactility/Source/service/wifi/WifiApSettings.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -14,7 +15,7 @@ namespace tt::service::wifi::settings { -constexpr auto* TAG = "WifiApSettings"; +static const auto LOGGER = Logger("WifiApSettings"); constexpr auto* AP_SETTINGS_FORMAT = "{}/{}.ap.properties"; @@ -33,7 +34,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) { - TT_LOG_E(TAG, "readHex() length mismatch"); + LOGGER.error("readHex() length mismatch"); return false; } @@ -63,7 +64,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(ssidInput.c_str()), buffer, encrypted_length) != 0) { - TT_LOG_E(TAG, "Failed to encrypt"); + LOGGER.error("Failed to encrypt"); free(buffer); return false; } @@ -79,7 +80,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) { assert(ssidInput.size() % 2 == 0); auto* data = static_cast(malloc(ssidInput.size() / 2)); if (!readHex(ssidInput, data, ssidInput.size() / 2)) { - TT_LOG_E(TAG, "Failed to read hex"); + LOGGER.error("Failed to read hex"); return false; } @@ -101,7 +102,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) { free(data); if (decrypt_result != 0) { - TT_LOG_E(TAG, "Failed to decrypt credentials for \"%s\": %d", ssidInput.c_str(), decrypt_result); + LOGGER.error("Failed to decrypt credentials for \"{}s\": {}", ssidInput, decrypt_result); free(result); return false; } diff --git a/Tactility/Source/service/wifi/WifiBootSplashInit.cpp b/Tactility/Source/service/wifi/WifiBootSplashInit.cpp index 250158bc..04bd0417 100644 --- a/Tactility/Source/service/wifi/WifiBootSplashInit.cpp +++ b/Tactility/Source/service/wifi/WifiBootSplashInit.cpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include @@ -16,7 +16,7 @@ namespace tt::service::wifi { -constexpr auto* TAG = "WifiBootSplashInit"; +static const auto LOGGER = Logger("WifiBootSplashInit"); constexpr auto* AP_PROPERTIES_KEY_SSID = "ssid"; constexpr auto* AP_PROPERTIES_KEY_PASSWORD = "password"; @@ -35,13 +35,13 @@ struct ApProperties { static void importWifiAp(const std::string& filePath) { std::map map; if (!file::loadPropertiesFile(filePath, map)) { - TT_LOG_E(TAG, "Failed to load AP properties at %s", filePath.c_str()); + LOGGER.error("Failed to load AP properties at {}", filePath); return; } const auto ssid_iterator = map.find(AP_PROPERTIES_KEY_SSID); if (ssid_iterator == map.end()) { - TT_LOG_E(TAG, "%s is missing ssid", filePath.c_str()); + LOGGER.error("{} is missing ssid", filePath); return; } const auto ssid = ssid_iterator->second; @@ -65,18 +65,18 @@ static void importWifiAp(const std::string& filePath) { ); if (!settings::save(settings)) { - TT_LOG_E(TAG, "Failed to save settings for %s", ssid.c_str()); + LOGGER.error("Failed to save settings for {}", ssid); } else { - TT_LOG_I(TAG, "Imported %s from %s", ssid.c_str(), filePath.c_str()); + LOGGER.info("Imported {} from {}", ssid, filePath); } } 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())) { - TT_LOG_E(TAG, "Failed to auto-remove %s", filePath.c_str()); + LOGGER.error("Failed to auto-remove {}", filePath); } else { - TT_LOG_I(TAG, "Auto-removed %s", filePath.c_str()); + LOGGER.info("Auto-removed {}", filePath); } } } @@ -105,7 +105,7 @@ static void importWifiApSettingsFromDir(const std::string& path) { } if (dirent_list.empty()) { - TT_LOG_W(TAG, "No AP files found at %s", path.c_str()); + LOGGER.warn("No AP files found at {}", path); return; } @@ -128,7 +128,7 @@ void bootSplashInit() { const std::string settings_path = file::getChildPath(sdcard->getMountPath(), "settings"); importWifiApSettingsFromDir(settings_path); } else { - TT_LOG_W(TAG, "Skipping unmounted SD card %s", sdcard->getMountPath().c_str()); + LOGGER.warn("Skipping unmounted SD card {}", sdcard->getMountPath()); } } }); diff --git a/Tactility/Source/service/wifi/WifiEsp.cpp b/Tactility/Source/service/wifi/WifiEsp.cpp index 8fb5bdf8..fe70032f 100644 --- a/Tactility/Source/service/wifi/WifiEsp.cpp +++ b/Tactility/Source/service/wifi/WifiEsp.cpp @@ -6,10 +6,12 @@ #include -#include #include +#include +#include #include #include +#include #include #include #include @@ -24,7 +26,8 @@ namespace tt::service::wifi { -constexpr auto* TAG = "WifiService"; +static const auto LOGGER = Logger("WifiService"); + constexpr auto WIFI_CONNECTED_BIT = BIT0; constexpr auto WIFI_FAIL_BIT = BIT1; constexpr auto AUTO_SCAN_INTERVAL = 10000; // ms @@ -170,7 +173,7 @@ std::string getConnectionTarget() { } void scan() { - TT_LOG_I(TAG, "scan()"); + LOGGER.info("scan()"); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -189,7 +192,7 @@ bool isScanning() { } void connect(const settings::WifiApSettings& ap, bool remember) { - TT_LOG_I(TAG, "connect(%s, %d)", ap.ssid.c_str(), remember); + LOGGER.info("connect({}, {})", ap.ssid, remember); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -213,7 +216,7 @@ void connect(const settings::WifiApSettings& ap, bool remember) { } void disconnect() { - TT_LOG_I(TAG, "disconnect()"); + LOGGER.info("disconnect()"); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -244,7 +247,7 @@ void clearIp() { memset(&wifi->ip_info, 0, sizeof(esp_netif_ip_info_t)); } void setScanRecords(uint16_t records) { - TT_LOG_I(TAG, "setScanRecords(%d)", records); + LOGGER.info("setScanRecords({})", records); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -262,7 +265,7 @@ void setScanRecords(uint16_t records) { } std::vector getScanResults() { - TT_LOG_I(TAG, "getScanResults()"); + LOGGER.info("getScanResults()"); auto wifi = wifi_singleton; std::vector records; @@ -293,7 +296,7 @@ std::vector getScanResults() { } void setEnabled(bool enabled) { - TT_LOG_I(TAG, "setEnabled(%d)", enabled); + LOGGER.info("setEnabled({})", enabled); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -390,7 +393,7 @@ static bool copy_scan_list(std::shared_ptr wifi) { wifi->isScanActive(); if (!can_fetch_results) { - TT_LOG_I(TAG, "Skip scan result fetching"); + LOGGER.info("Skip scan result fetching"); return false; } @@ -407,11 +410,11 @@ static bool copy_scan_list(std::shared_ptr 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; - TT_LOG_I(TAG, "Scanned %u APs. Showing %u:", record_count, safe_record_count); + LOGGER.info("Scanned {} APs. Showing {}:", record_count, safe_record_count); for (uint16_t i = 0; i < safe_record_count; i++) { wifi_ap_record_t* record = &wifi->scan_list[i]; - TT_LOG_I(TAG, " - SSID %s, RSSI %d, channel %d, BSSID %02X%02X%02X%02X%02X%02X", - record->ssid, + LOGGER.info(" - SSID {}, RSSI {}, channel {}, BSSID {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", + reinterpret_cast(record->ssid), record->rssi, record->primary, record->bssid[0], @@ -424,13 +427,13 @@ static bool copy_scan_list(std::shared_ptr wifi) { } return true; } else { - TT_LOG_I(TAG, "Failed to get scanned records: %s", esp_err_to_name(scan_result)); + LOGGER.info("Failed to get scanned records: {}", esp_err_to_name(scan_result)); return false; } } static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSettings& settings) { - TT_LOG_I(TAG, "find_auto_connect_ap()"); + LOGGER.info("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) { @@ -442,7 +445,7 @@ static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSet return true; } } else { - TT_LOG_E(TAG, "Failed to load credentials for ssid %s", ssid); + LOGGER.error("Failed to load credentials for ssid {}", ssid); } break; } @@ -453,11 +456,11 @@ static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSet } static void dispatchAutoConnect(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchAutoConnect()"); + LOGGER.info("dispatchAutoConnect()"); settings::WifiApSettings settings; if (find_auto_connect_ap(wifi, settings)) { - TT_LOG_I(TAG, "Auto-connecting to %s", settings.ssid.c_str()); + LOGGER.info("Auto-connecting to {}", settings.ssid); 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 @@ -468,23 +471,23 @@ static void dispatchAutoConnect(std::shared_ptr wifi) { static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { auto wifi = wifi_singleton; if (wifi == nullptr) { - TT_LOG_E(TAG, "eventHandler: no wifi instance"); + LOGGER.error("eventHandler: no wifi instance"); return; } if (event_base == WIFI_EVENT) { - TT_LOG_I(TAG, "eventHandler: WIFI_EVENT (%ld)", event_id); + LOGGER.info("eventHandler: WIFI_EVENT {}", event_id); } else if (event_base == IP_EVENT) { - TT_LOG_I(TAG, "eventHandler: IP_EVENT (%ld)", event_id); + LOGGER.info("eventHandler: IP_EVENT {}", event_id); } if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { - TT_LOG_I(TAG, "eventHandler: sta start"); + LOGGER.info("eventHandler: STA_START"); if (wifi->getRadioState() == RadioState::ConnectionPending) { esp_wifi_connect(); } } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { - TT_LOG_I(TAG, "eventHandler: disconnected"); + LOGGER.info("eventHandler: STA_DISCONNECTED"); clearIp(); switch (wifi->getRadioState()) { case RadioState::ConnectionPending: @@ -503,7 +506,7 @@ static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { auto* event = static_cast(event_data); memcpy(&wifi->ip_info, &event->ip_info, sizeof(esp_netif_ip_info_t)); - TT_LOG_I(TAG, "eventHandler: got ip:" IPSTR, IP2STR(&event->ip_info.ip)); + LOGGER.info("eventHandler: got ip: {}.{}.{}.{}", 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 @@ -513,7 +516,7 @@ static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32 kernel::publishSystemEvent(kernel::SystemEvent::NetworkConnected); } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) { auto* event = static_cast(event_data); - TT_LOG_I(TAG, "eventHandler: wifi scanning done (scan id %u)", event->scan_id); + LOGGER.info("eventHandler: wifi scanning done (scan id {})", event->scan_id); bool copied_list = copy_scan_list(wifi); auto state = wifi->getRadioState(); @@ -526,7 +529,7 @@ static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32 } publish_event(wifi_singleton, WifiEvent::ScanFinished); - TT_LOG_I(TAG, "eventHandler: Finished scan"); + LOGGER.info("eventHandler: Finished scan"); if (copied_list && wifi_singleton->getRadioState() == RadioState::On && !wifi->pause_auto_connect) { getMainDispatcher().dispatch([wifi]() { dispatchAutoConnect(wifi); }); @@ -535,7 +538,7 @@ static void eventHandler(TT_UNUSED void* arg, esp_event_base_t event_base, int32 } static void dispatchEnable(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchEnable()"); + LOGGER.info("dispatchEnable()"); RadioState state = wifi->getRadioState(); if ( @@ -543,13 +546,13 @@ static void dispatchEnable(std::shared_ptr wifi) { state == RadioState::OnPending || state == RadioState::OffPending ) { - TT_LOG_W(TAG, "Can't enable from current state"); + LOGGER.warn("Can't enable from current state"); return; } auto lock = wifi->radioMutex.asScopedLock(); if (lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_I(TAG, "Enabling"); + LOGGER.info("Enabling"); wifi->setRadioState(RadioState::OnPending); publish_event(wifi, WifiEvent::RadioStateOnPending); @@ -563,9 +566,9 @@ static void dispatchEnable(std::shared_ptr wifi) { wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); esp_err_t init_result = esp_wifi_init(&config); if (init_result != ESP_OK) { - TT_LOG_E(TAG, "Wifi init failed"); + LOGGER.error("Wifi init failed"); if (init_result == ESP_ERR_NO_MEM) { - TT_LOG_E(TAG, "Insufficient memory"); + LOGGER.error("Insufficient memory"); } wifi->setRadioState(RadioState::Off); publish_event(wifi, WifiEvent::RadioStateOff); @@ -593,7 +596,7 @@ static void dispatchEnable(std::shared_ptr wifi) { )); if (esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK) { - TT_LOG_E(TAG, "Wifi mode setting failed"); + LOGGER.error("Wifi mode setting failed"); wifi->setRadioState(RadioState::Off); esp_wifi_deinit(); publish_event(wifi, WifiEvent::RadioStateOff); @@ -602,9 +605,9 @@ static void dispatchEnable(std::shared_ptr wifi) { esp_err_t start_result = esp_wifi_start(); if (start_result != ESP_OK) { - TT_LOG_E(TAG, "Wifi start failed"); + LOGGER.error("Wifi start failed"); if (start_result == ESP_ERR_NO_MEM) { - TT_LOG_E(TAG, "Insufficient memory"); + LOGGER.error("Insufficient memory"); } wifi->setRadioState(RadioState::Off); esp_wifi_set_mode(WIFI_MODE_NULL); @@ -618,18 +621,18 @@ static void dispatchEnable(std::shared_ptr wifi) { wifi->pause_auto_connect = false; - TT_LOG_I(TAG, "Enabled"); + LOGGER.info("Enabled"); } else { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); } } static void dispatchDisable(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchDisable()"); + LOGGER.info("dispatchDisable()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()"); return; } @@ -639,11 +642,11 @@ static void dispatchDisable(std::shared_ptr wifi) { state == RadioState::OffPending || state == RadioState::OnPending ) { - TT_LOG_W(TAG, "Can't disable from current state"); + LOGGER.warn("Can't disable from current state"); return; } - TT_LOG_I(TAG, "Disabling"); + LOGGER.info("Disabling"); wifi->setRadioState(RadioState::OffPending); publish_event(wifi, WifiEvent::RadioStateOffPending); @@ -651,14 +654,14 @@ static void dispatchDisable(std::shared_ptr wifi) { scan_list_free_safely(wifi_singleton); if (esp_wifi_stop() != ESP_OK) { - TT_LOG_E(TAG, "Failed to stop radio"); + LOGGER.error("Failed to stop radio"); wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::RadioStateOn); return; } if (esp_wifi_set_mode(WIFI_MODE_NULL) != ESP_OK) { - TT_LOG_E(TAG, "Failed to unset mode"); + LOGGER.error("Failed to unset mode"); } if (esp_event_handler_instance_unregister( @@ -666,7 +669,7 @@ static void dispatchDisable(std::shared_ptr wifi) { ESP_EVENT_ANY_ID, wifi->event_handler_any_id ) != ESP_OK) { - TT_LOG_E(TAG, "Failed to unregister id event handler"); + LOGGER.error("Failed to unregister id event handler"); } if (esp_event_handler_instance_unregister( @@ -674,11 +677,11 @@ static void dispatchDisable(std::shared_ptr wifi) { IP_EVENT_STA_GOT_IP, wifi->event_handler_got_ip ) != ESP_OK) { - TT_LOG_E(TAG, "Failed to unregister ip event handler"); + LOGGER.error("Failed to unregister ip event handler"); } if (esp_wifi_deinit() != ESP_OK) { - TT_LOG_E(TAG, "Failed to deinit"); + LOGGER.error("Failed to deinit"); } assert(wifi->netif != nullptr); @@ -687,26 +690,26 @@ static void dispatchDisable(std::shared_ptr wifi) { wifi->setScanActive(false); wifi->setRadioState(RadioState::Off); publish_event(wifi, WifiEvent::RadioStateOff); - TT_LOG_I(TAG, "Disabled"); + LOGGER.info("Disabled"); } static void dispatchScan(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchScan()"); + LOGGER.info("dispatchScan()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(10 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } RadioState state = wifi->getRadioState(); if (state != RadioState::On && state != RadioState::ConnectionActive && state != RadioState::ConnectionPending) { - TT_LOG_W(TAG, "Scan unavailable: wifi not enabled"); + LOGGER.warn("Scan unavailable: wifi not enabled"); return; } if (wifi->isScanActive()) { - TT_LOG_W(TAG, "Scan already pending"); + LOGGER.warn("Scan already pending"); return; } @@ -714,25 +717,25 @@ static void dispatchScan(std::shared_ptr wifi) { wifi->last_scan_time = tt::kernel::getTicks(); if (esp_wifi_scan_start(nullptr, false) != ESP_OK) { - TT_LOG_I(TAG, "Can't start scan"); + LOGGER.info("Can't start scan"); return; } - TT_LOG_I(TAG, "Starting scan"); + LOGGER.info("Starting scan"); wifi->setScanActive(true); publish_event(wifi, WifiEvent::ScanStarted); } static void dispatchConnect(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchConnect()"); + LOGGER.info("dispatchConnect()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()"); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()"); return; } - TT_LOG_I(TAG, "Connecting to %s", wifi->connection_target.ssid.c_str()); + LOGGER.info("Connecting to {}", wifi->connection_target.ssid); // Stop radio first, if needed RadioState radio_state = wifi->getRadioState(); @@ -741,11 +744,11 @@ static void dispatchConnect(std::shared_ptr wifi) { radio_state == RadioState::ConnectionActive || radio_state == RadioState::ConnectionPending ) { - TT_LOG_I(TAG, "Connecting: Stopping radio first"); + LOGGER.info("Connecting: Stopping radio first"); esp_err_t stop_result = esp_wifi_stop(); wifi->setScanActive(false); if (stop_result != ESP_OK) { - TT_LOG_E(TAG, "Connecting: Failed to disconnect (%s)", esp_err_to_name(stop_result)); + LOGGER.error("Connecting: Failed to disconnect ({})", esp_err_to_name(stop_result)); return; } } @@ -771,20 +774,20 @@ static void dispatchConnect(std::shared_ptr wifi) { config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK; } - TT_LOG_I(TAG, "esp_wifi_set_config()"); + LOGGER.info("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); - TT_LOG_E(TAG, "Failed to set wifi config (%s)", esp_err_to_name(set_config_result)); + LOGGER.error("Failed to set wifi config ({})", esp_err_to_name(set_config_result)); publish_event(wifi, WifiEvent::ConnectionFailed); return; } - TT_LOG_I(TAG, "esp_wifi_start()"); + LOGGER.info("esp_wifi_start()"); esp_err_t wifi_start_result = esp_wifi_start(); if (wifi_start_result != ESP_OK) { wifi->setRadioState(RadioState::On); - TT_LOG_E(TAG, "Failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result)); + LOGGER.error("Failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result)); publish_event(wifi, WifiEvent::ConnectionFailed); return; } @@ -794,28 +797,28 @@ static void dispatchConnect(std::shared_ptr wifi) { * The bits are set by wifi_event_handler() */ uint32_t bits; if (wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT, false, true, kernel::MAX_TICKS, &bits)) { - TT_LOG_I(TAG, "Waiting for EventGroup by event_handler()"); + LOGGER.info("Waiting for EventGroup by event_handler()"); if (bits & WIFI_CONNECTED_BIT) { wifi->setSecureConnection(config.sta.password[0] != 0x00U); wifi->setRadioState(RadioState::ConnectionActive); publish_event(wifi, WifiEvent::ConnectionSuccess); - TT_LOG_I(TAG, "Connected to %s", wifi->connection_target.ssid.c_str()); + LOGGER.info("Connected to {}", wifi->connection_target.ssid.c_str()); if (wifi->connection_target_remember) { if (!settings::save(wifi->connection_target)) { - TT_LOG_E(TAG, "Failed to store credentials"); + LOGGER.error("Failed to store credentials"); } else { - TT_LOG_I(TAG, "Stored credentials"); + LOGGER.info("Stored credentials"); } } } else if (bits & WIFI_FAIL_BIT) { wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::ConnectionFailed); - TT_LOG_I(TAG, "Failed to connect to %s", wifi->connection_target.ssid.c_str()); + LOGGER.info("Failed to connect to {}", wifi->connection_target.ssid.c_str()); } else { wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::ConnectionFailed); - TT_LOG_E(TAG, "UNEXPECTED EVENT"); + LOGGER.error("UNEXPECTED EVENT"); } wifi_singleton->connection_wait_flags.clear(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT); @@ -823,17 +826,17 @@ static void dispatchConnect(std::shared_ptr wifi) { } static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { - TT_LOG_I(TAG, "dispatchDisconnectButKeepActive()"); + LOGGER.info("dispatchDisconnectButKeepActive()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - TT_LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } esp_err_t stop_result = esp_wifi_stop(); if (stop_result != ESP_OK) { - TT_LOG_E(TAG, "Failed to disconnect (%s)", esp_err_to_name(stop_result)); + LOGGER.error("Failed to disconnect ({})", esp_err_to_name(stop_result)); return; } @@ -849,7 +852,7 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { if (set_config_result != ESP_OK) { // TODO: disable radio, because radio state is in limbo between off and on wifi->setRadioState(RadioState::Off); - TT_LOG_E(TAG, "failed to set wifi config (%s)", esp_err_to_name(set_config_result)); + LOGGER.error("failed to set wifi config ({})", esp_err_to_name(set_config_result)); publish_event(wifi, WifiEvent::RadioStateOff); return; } @@ -858,14 +861,14 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { if (wifi_start_result != ESP_OK) { // TODO: disable radio, because radio state is in limbo between off and on wifi->setRadioState(RadioState::Off); - TT_LOG_E(TAG, "failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result)); + LOGGER.error("failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result)); publish_event(wifi, WifiEvent::RadioStateOff); return; } wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::Disconnected); - TT_LOG_I(TAG, "Disconnected"); + LOGGER.info("Disconnected"); } static bool shouldScanForAutoConnect(std::shared_ptr wifi) { @@ -882,7 +885,7 @@ static bool shouldScanForAutoConnect(std::shared_ptr wifi) { return false; } - TickType_t current_time = tt::kernel::getTicks(); + TickType_t current_time = kernel::getTicks(); bool scan_time_has_looped = (current_time < wifi->last_scan_time); bool no_recent_scan = (current_time - wifi->last_scan_time) > (AUTO_SCAN_INTERVAL / portTICK_PERIOD_MS); @@ -928,7 +931,7 @@ public: wifi_singleton->autoConnectTimer->start(); if (settings::shouldEnableOnBoot()) { - TT_LOG_I(TAG, "Auto-enabling due to setting"); + LOGGER.info("Auto-enabling due to setting"); getMainDispatcher().dispatch([] { dispatchEnable(wifi_singleton); }); } diff --git a/Tactility/Source/service/wifi/WifiMock.cpp b/Tactility/Source/service/wifi/WifiMock.cpp index 5a5ff44e..6d86312b 100644 --- a/Tactility/Source/service/wifi/WifiMock.cpp +++ b/Tactility/Source/service/wifi/WifiMock.cpp @@ -8,15 +8,12 @@ #include #include -#include #include #include #include namespace tt::service::wifi { -constexpr auto* TAG = "Wifi"; - struct Wifi { /** @brief Locking mechanism for modifying the Wifi instance */ RecursiveMutex mutex; diff --git a/Tactility/Source/service/wifi/WifiSettings.cpp b/Tactility/Source/service/wifi/WifiSettings.cpp index b2969e24..e712ffc9 100644 --- a/Tactility/Source/service/wifi/WifiSettings.cpp +++ b/Tactility/Source/service/wifi/WifiSettings.cpp @@ -1,14 +1,14 @@ #include -#include #include #include +#include #include #include namespace tt::service::wifi::settings { -constexpr auto* TAG = "WifiSettings"; +static const auto LOGGER = Logger("WifiSettings"); constexpr auto* SETTINGS_KEY_ENABLE_ON_BOOT = "enableOnBoot"; struct WifiSettings { @@ -56,7 +56,7 @@ static bool save(const WifiSettings& settings) { WifiSettings getCachedOrLoad() { if (!cached) { if (!load(cachedSettings)) { - TT_LOG_E(TAG, "Failed to load"); + LOGGER.error("Failed to load"); } else { cached = true; } @@ -68,7 +68,7 @@ WifiSettings getCachedOrLoad() { void setEnableOnBoot(bool enable) { cachedSettings.enableOnBoot = enable; if (!save(cachedSettings)) { - TT_LOG_E(TAG, "Failed to save"); + LOGGER.error("Failed to save"); } } diff --git a/Tactility/Source/settings/BootSettings.cpp b/Tactility/Source/settings/BootSettings.cpp index 564028ee..816e6eec 100644 --- a/Tactility/Source/settings/BootSettings.cpp +++ b/Tactility/Source/settings/BootSettings.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include @@ -11,7 +11,8 @@ namespace tt::settings { -constexpr auto* TAG = "BootSettings"; +static const auto LOGGER = Logger("BootSettings"); + constexpr auto* PROPERTIES_FILE_FORMAT = "{}/settings/boot.properties"; constexpr auto* PROPERTIES_KEY_LAUNCHER_APP_ID = "launcherAppId"; constexpr auto* PROPERTIES_KEY_AUTO_START_APP_ID = "autoStartAppId"; @@ -36,7 +37,7 @@ bool loadBootSettings(BootSettings& properties) { properties.launcherAppId = value; } })) { - TT_LOG_E(TAG, "Failed to load %s", path.c_str()); + LOGGER.error("Failed to load {}", path); return false; } diff --git a/Tactility/Source/settings/DisplaySettings.cpp b/Tactility/Source/settings/DisplaySettings.cpp index 6290530f..84e04705 100644 --- a/Tactility/Source/settings/DisplaySettings.cpp +++ b/Tactility/Source/settings/DisplaySettings.cpp @@ -10,7 +10,6 @@ namespace tt::settings::display { -constexpr auto* TAG = "DisplaySettings"; constexpr auto* SETTINGS_FILE = "/data/settings/display.properties"; constexpr auto* SETTINGS_KEY_ORIENTATION = "orientation"; constexpr auto* SETTINGS_KEY_GAMMA_CURVE = "gammaCurve"; diff --git a/Tactility/Source/settings/Language.cpp b/Tactility/Source/settings/Language.cpp index b84e669a..3989a8e6 100644 --- a/Tactility/Source/settings/Language.cpp +++ b/Tactility/Source/settings/Language.cpp @@ -1,11 +1,12 @@ -#include +#include #include -#include #include +#include + namespace tt::settings { -constexpr auto* TAG = "Language"; +static const auto LOGGER = Logger("Language"); void setLanguage(Language newLanguage) { SystemSettings properties; @@ -39,7 +40,7 @@ std::string toString(Language language) { case Language::nl_NL: return "nl-NL"; default: - TT_LOG_E(TAG, "Missing serialization for language %d", static_cast(language)); + LOGGER.error("Missing serialization for language {}", static_cast(language)); std::unreachable(); } } diff --git a/Tactility/Source/settings/SystemSettings.cpp b/Tactility/Source/settings/SystemSettings.cpp index 9ce01fae..163a847a 100644 --- a/Tactility/Source/settings/SystemSettings.cpp +++ b/Tactility/Source/settings/SystemSettings.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -6,11 +7,11 @@ #include #include -#include namespace tt::settings { -constexpr auto* TAG = "SystemSettings"; +static const auto LOGGER = Logger("SystemSettings"); + constexpr auto* FILE_PATH_FORMAT = "{}/settings/system.properties"; static Mutex mutex; @@ -19,17 +20,17 @@ static SystemSettings cachedSettings; static bool loadSystemSettingsFromFile(SystemSettings& properties) { auto file_path = std::format(FILE_PATH_FORMAT, file::MOUNT_POINT_DATA); - TT_LOG_I(TAG, "System settings loading from %s", file_path.c_str()); + LOGGER.info("System settings loading from {}", file_path); std::map map; if (!file::loadPropertiesFile(file_path, map)) { - TT_LOG_E(TAG, "Failed to load %s", file_path.c_str()); + LOGGER.error("Failed to load {}", file_path); return false; } auto language_entry = map.find("language"); if (language_entry != map.end()) { if (!fromString(language_entry->second, properties.language)) { - TT_LOG_W(TAG, "Unknown language \"%s\" in %s", language_entry->second.c_str(), file_path.c_str()); + LOGGER.warn("Unknown language \"{}\" in {}", language_entry->second, file_path); properties.language = Language::en_US; } } else { @@ -46,7 +47,7 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) { if (date_format_entry != map.end() && !date_format_entry->second.empty()) { properties.dateFormat = date_format_entry->second; } else { - TT_LOG_I(TAG, "dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)"); + LOGGER.info("dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)"); properties.dateFormat = "MM/DD/YYYY"; } @@ -55,11 +56,11 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) { if (region_entry != map.end() && !region_entry->second.empty()) { properties.region = region_entry->second; } else { - TT_LOG_I(TAG, "region missing or empty, using default US"); - properties.region = "US"; + LOGGER.info("Region missing or empty, using default EU"); + properties.region = "EU"; } - TT_LOG_I(TAG, "System settings loaded"); + LOGGER.info("System settings loaded"); return true; } @@ -84,7 +85,7 @@ bool saveSystemSettings(const SystemSettings& properties) { map["region"] = properties.region; if (!file::savePropertiesFile(file_path, map)) { - TT_LOG_E(TAG, "Failed to save %s", file_path.c_str()); + LOGGER.error("Failed to save {}", file_path); return false; } diff --git a/Tactility/Source/settings/Time.cpp b/Tactility/Source/settings/Time.cpp index c0051717..8a9de319 100644 --- a/Tactility/Source/settings/Time.cpp +++ b/Tactility/Source/settings/Time.cpp @@ -45,7 +45,7 @@ std::string getTimeZoneName() { if (preferences.optString(TIMEZONE_PREFERENCES_KEY_NAME, result)) { return result; } else { - return "America/Los_Angeles"; // Default: Pacific Time (PST/PDT) + return "Europe/Amsterdam"; } } @@ -55,7 +55,7 @@ std::string getTimeZoneCode() { if (preferences.optString(TIMEZONE_PREFERENCES_KEY_CODE, result)) { return result; } else { - return "PST8PDT,M3.2.0,M11.1.0"; // Default: Pacific Time POSIX string + return "CET-1CEST,M3.5.0,M10.5.0/3"; // Default: Europe/Amsterdam } } diff --git a/TactilityC/Source/tt_app.cpp b/TactilityC/Source/tt_app.cpp index 0c400477..4e9df28f 100644 --- a/TactilityC/Source/tt_app.cpp +++ b/TactilityC/Source/tt_app.cpp @@ -3,13 +3,13 @@ #include #include #include -#include +#include #include -extern "C" { +static const auto LOGGER = tt::Logger("tt_app"); -constexpr auto* TAG = "tt_app"; +extern "C" { #define HANDLE_AS_APP_CONTEXT(handle) ((tt::app::AppContext*)(handle)) @@ -65,7 +65,7 @@ void tt_app_get_user_data_path(AppHandle handle, char* buffer, size_t* size) { const auto data_path = paths->getUserDataPath(); const auto expected_length = data_path.length() + 1; if (*size < expected_length) { - TT_LOG_E(TAG, "Path buffer not large enough (%d < %d)", *size, expected_length); + LOGGER.error("Path buffer not large enough ({} < {})", *size, expected_length); *size = 0; buffer[0] = 0; return; @@ -83,7 +83,7 @@ void tt_app_get_user_data_child_path(AppHandle handle, const char* childPath, ch const auto resolved_path = paths->getUserDataPath(childPath); const auto resolved_path_length = resolved_path.length(); if (*size < (resolved_path_length + 1)) { - TT_LOG_E(TAG, "Path buffer not large enough (%d < %d)", *size, (resolved_path_length + 1)); + LOGGER.error("Path buffer not large enough ({} < {})", *size, (resolved_path_length + 1)); *size = 0; buffer[0] = 0; return; @@ -101,7 +101,7 @@ void tt_app_get_assets_path(AppHandle handle, char* buffer, size_t* size) { const auto assets_path = paths->getAssetsPath(); const auto expected_length = assets_path.length() + 1; if (*size < expected_length) { - TT_LOG_E(TAG, "Path buffer not large enough (%d < %d)", *size, expected_length); + LOGGER.error("Path buffer not large enough ({} < {})", *size, expected_length); *size = 0; buffer[0] = 0; return; @@ -119,7 +119,7 @@ void tt_app_get_assets_child_path(AppHandle handle, const char* childPath, char* const auto resolved_path = paths->getAssetsPath(childPath); const auto resolved_path_length = resolved_path.length(); if (*size < (resolved_path_length + 1)) { - TT_LOG_E(TAG, "Path buffer not large enough (%d < %d)", *size, (resolved_path_length + 1)); + LOGGER.error("Path buffer not large enough ({} < {})", *size, (resolved_path_length + 1)); *size = 0; buffer[0] = 0; return; diff --git a/TactilityCore/Include/Tactility/Check.h b/TactilityCore/Include/Tactility/Check.h index c5078d50..c0f93c94 100644 --- a/TactilityCore/Include/Tactility/Check.h +++ b/TactilityCore/Include/Tactility/Check.h @@ -14,7 +14,7 @@ #pragma once #include "CoreDefines.h" -#include "Log.h" +#include "Logger.h" #include @@ -28,17 +28,18 @@ namespace tt { TT_NORETURN void _crash(); } +// TODO: Move crash logic to kernel namespace and consider refactoring to C++ /** Crash system with message. */ #define tt_crash(...) TT_ARG_CAT(_tt_crash,TT_ARGCOUNT(__VA_ARGS__))(__VA_ARGS__) #define _tt_crash0() do { \ - TT_LOG_E("crash", "at %s:%d", __FILE__, __LINE__); \ + tt::Logger("Kernel").error("Crash at {}:{}", __FILE__, __LINE__); \ tt::_crash(); \ } while (0) -#define _tt_crash1(message) do { \ - TT_LOG_E("crash", "%s\n\tat %s:%d", message, __FILE__, __LINE__); \ - tt::_crash(); \ +#define _tt_crash1(message) do { \ + tt::Logger("Kernel").error("Crash: {}\n\tat {}:{}", message, __FILE__, __LINE__); \ + tt::_crash(); \ } while (0) /** Halt the system @@ -50,11 +51,11 @@ namespace tt { #define tt_check_internal(__e, __m) \ do { \ if (!(__e)) { \ - TT_LOG_E("check", "%s", #__e); \ + tt::Logger("Kernel").error("Check failed: {}", #__e); \ if (__m) { \ - tt_crash_internal(#__m); \ + tt_crash(__m); \ } else { \ - tt_crash_internal(""); \ + tt_crash(""); \ } \ } \ } while (0) @@ -65,4 +66,4 @@ namespace tt { * @param[in] optional message (const char*) */ -#define tt_check(x, ...) if (!(x)) { TT_LOG_E("check", "Failed: %s", #x); tt::_crash(); } +#define tt_check(x, ...) if (!(x)) { tt::Logger("Kernel").error("Check failed: {}", #x); tt::_crash(); } diff --git a/TactilityCore/Include/Tactility/Log.h b/TactilityCore/Include/Tactility/Log.h deleted file mode 100644 index 0b0cab09..00000000 --- a/TactilityCore/Include/Tactility/Log.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#ifdef ESP_PLATFORM -#include "LogEsp.h" -#else -#include "LogSimulator.h" -#endif - -#include "LogMessages.h" -#include "LogCommon.h" diff --git a/TactilityCore/Include/Tactility/LogEsp.h b/TactilityCore/Include/Tactility/LogEsp.h deleted file mode 100644 index b3d78a41..00000000 --- a/TactilityCore/Include/Tactility/LogEsp.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#ifdef ESP_PLATFORM - -#include -#include "Tactility/LogCommon.h" - -#define TT_LOG_E(tag, format, ...) \ - ESP_LOGE(tag, format, ##__VA_ARGS__) -#define TT_LOG_W(tag, format, ...) \ - ESP_LOGW(tag, format, ##__VA_ARGS__) -#define TT_LOG_I(tag, format, ...) \ - ESP_LOGI(tag, format, ##__VA_ARGS__) -#define TT_LOG_D(tag, format, ...) \ - ESP_LOGD(tag, format, ##__VA_ARGS__) -#define TT_LOG_V(tag, format, ...) \ - ESP_LOGV(tag, format, ##__VA_ARGS__) - -#endif // ESP_PLATFORM diff --git a/TactilityCore/Include/Tactility/LogMessages.h b/TactilityCore/Include/Tactility/LogMessages.h index d5f6e6d8..ec48ce80 100644 --- a/TactilityCore/Include/Tactility/LogMessages.h +++ b/TactilityCore/Include/Tactility/LogMessages.h @@ -9,20 +9,11 @@ // Alloc #define LOG_MESSAGE_ALLOC_FAILED "Out of memory" -#define LOG_MESSAGE_ALLOC_FAILED_FMT "Out of memory (failed to allocated %zu bytes)" +#define LOG_MESSAGE_ALLOC_FAILED_FMT "Out of memory (failed to allocated {} bytes)" // Mutex #define LOG_MESSAGE_MUTEX_LOCK_FAILED "Mutex acquisition timeout" -#define LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT "Mutex acquisition timeout (%s)" - -// SPI -#define LOG_MESSAGE_SPI_INIT_START_FMT "SPI %d init" -#define LOG_MESSAGE_SPI_INIT_FAILED_FMT "SPI %d init failed" - -// I2C -#define LOG_MESSAGE_I2C_INIT_START "I2C init" -#define LOG_MESSAGE_I2C_INIT_CONFIG_FAILED "I2C config failed" -#define LOG_MESSAGE_I2C_INIT_DRIVER_INSTALL_FAILED "I2C driver install failed" +#define LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT "Mutex acquisition timeout ({})" // Power on #define LOG_MESSAGE_POWER_ON_START "Power on" diff --git a/TactilityCore/Include/Tactility/LogSimulator.h b/TactilityCore/Include/Tactility/LogSimulator.h deleted file mode 100644 index 787e1b1d..00000000 --- a/TactilityCore/Include/Tactility/LogSimulator.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#ifndef ESP_PLATFORM - -#include "LogCommon.h" - -#include -#include - -namespace tt { - -void log(LogLevel level, const char* tag, const char* format, ...); - -} // namespace - -#define TT_LOG_E(tag, format, ...) \ - tt::log(tt::LogLevel::Error, tag, format, ##__VA_ARGS__) -#define TT_LOG_W(tag, format, ...) \ - tt::log(tt::LogLevel::Warning, tag, format, ##__VA_ARGS__) -#define TT_LOG_I(tag, format, ...) \ - tt::log(tt::LogLevel::Info, tag, format, ##__VA_ARGS__) -#define TT_LOG_D(tag, format, ...) \ - tt::log(tt::LogLevel::Debug, tag, format, ##__VA_ARGS__) -#define TT_LOG_V(tag, format, ...) \ - tt::log(tt::LogLevel::Verbose, tag, format, ##__VA_ARGS__) - -#endif // ESP_PLATFORM diff --git a/TactilityCore/Include/Tactility/Logger.h b/TactilityCore/Include/Tactility/Logger.h new file mode 100644 index 00000000..6155a06b --- /dev/null +++ b/TactilityCore/Include/Tactility/Logger.h @@ -0,0 +1,72 @@ +#pragma once + +#include "LoggerAdapter.h" +#include "LoggerSettings.h" + +#ifdef ESP_PLATFORM +#include "LoggerAdapterEsp.h" +#else +#include "LoggerAdapterGeneric.h" +#endif + +#include + +namespace tt { + +#ifdef ESP_PLATFORM +static LoggerAdapter defaultLoggerAdapter = espLoggerAdapter; +#else +static LoggerAdapter defaultLoggerAdapter = genericLoggerAdapter; +#endif + +class Logger { + + const char* tag; + +public: + + explicit Logger(const char* tag) : tag(tag) {} + + template + void log(LogLevel level, std::format_string format, Args&&... args) const { + std::string message = std::format(format, std::forward(args)...); + defaultLoggerAdapter(level, tag, message.c_str()); + } + + template + void verbose(std::format_string format, Args&&... args) const { + log(LogLevel::Verbose, format, std::forward(args)...); + } + + template + void debug(std::format_string format, Args&&... args) const { + log(LogLevel::Debug, format, std::forward(args)...); + } + + template + void info(std::format_string format, Args&&... args) const { + log(LogLevel::Info, format, std::forward(args)...); + } + + template + void warn(std::format_string format, Args&&... args) const { + log(LogLevel::Warning, format, std::forward(args)...); + } + + template + void error(std::format_string format, Args&&... args) const { + log(LogLevel::Error, format, std::forward(args)...); + } + + bool isLoggingVerbose() const { return LogLevel::Verbose <= LOG_LEVEL; } + + bool isLoggingDebug() const { return LogLevel::Debug <= LOG_LEVEL; } + + bool isLoggingInfo() const { return LogLevel::Info <= LOG_LEVEL; } + + bool isLoggingWarning() const { return LogLevel::Warning <= LOG_LEVEL; } + + bool isLoggingError() const { return LogLevel::Error <= LOG_LEVEL; } +}; + +} diff --git a/TactilityCore/Include/Tactility/LoggerAdapter.h b/TactilityCore/Include/Tactility/LoggerAdapter.h new file mode 100644 index 00000000..2288bca5 --- /dev/null +++ b/TactilityCore/Include/Tactility/LoggerAdapter.h @@ -0,0 +1,10 @@ +#pragma once + +#include "LoggerCommon.h" +#include + +namespace tt { + +typedef std::function LoggerAdapter; + +} diff --git a/TactilityCore/Include/Tactility/LoggerAdapterEsp.h b/TactilityCore/Include/Tactility/LoggerAdapterEsp.h new file mode 100644 index 00000000..f9861034 --- /dev/null +++ b/TactilityCore/Include/Tactility/LoggerAdapterEsp.h @@ -0,0 +1,35 @@ +#pragma once + +#include "LoggerAdapter.h" +#include "LoggerAdapterShared.h" + +#include +#include + +namespace tt { + +inline esp_log_level_t toEspLogLevel(LogLevel level) { + switch (level) { + case LogLevel::Error: + return ESP_LOG_ERROR; + case LogLevel::Warning: + return ESP_LOG_WARN; + case LogLevel::Info: + return ESP_LOG_INFO; + case LogLevel::Debug: + return ESP_LOG_DEBUG; + case LogLevel::Verbose: + default: + return ESP_LOG_VERBOSE; + } +} + +static const LoggerAdapter espLoggerAdapter = [](LogLevel level, const char* tag, const char* message) { + constexpr auto COLOR_RESET = "\033[0m"; + constexpr auto COLOR_GREY = "\033[37m"; + std::stringstream buffer; + buffer << COLOR_GREY << esp_log_timestamp() << ' ' << toTagColour(level) << toPrefix(level) << COLOR_GREY << " [" << COLOR_RESET << tag << COLOR_GREY << "] " << toMessageColour(level) << message << COLOR_RESET << std::endl; + esp_log_write(toEspLogLevel(level), tag, "%s", buffer.str().c_str()); +}; + +} diff --git a/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h b/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h new file mode 100644 index 00000000..6ed0a26f --- /dev/null +++ b/TactilityCore/Include/Tactility/LoggerAdapterGeneric.h @@ -0,0 +1,35 @@ +#pragma once + +#include "LoggerAdapter.h" +#include "LoggerAdapterShared.h" + +#include +#include +#include +#include + +namespace tt { + +static uint64_t getLogTimestamp() { + static uint64_t base = 0U; + static std::once_flag init_flag; + std::call_once(init_flag, []() { + timeval time {}; + gettimeofday(&time, nullptr); + base = ((uint64_t)time.tv_sec * 1000U) + (time.tv_usec / 1000U); + }); + timeval time {}; + gettimeofday(&time, nullptr); + uint64_t now = ((uint64_t)time.tv_sec * 1000U) + (time.tv_usec / 1000U); + return now - base; +} + +static const LoggerAdapter genericLoggerAdapter = [](LogLevel level, const char* tag, const char* message) { + constexpr auto COLOR_RESET = "\033[0m"; + constexpr auto COLOR_GREY = "\033[37m"; + std::stringstream buffer; + buffer << COLOR_GREY << getLogTimestamp() << ' ' << toTagColour(level) << toPrefix(level) << COLOR_GREY << " [" << COLOR_RESET << tag << COLOR_GREY << "] " << toMessageColour(level) << message << COLOR_RESET << std::endl; + printf(buffer.str().c_str()); +}; + +} \ No newline at end of file diff --git a/TactilityCore/Include/Tactility/LoggerAdapterShared.h b/TactilityCore/Include/Tactility/LoggerAdapterShared.h new file mode 100644 index 00000000..af4527cc --- /dev/null +++ b/TactilityCore/Include/Tactility/LoggerAdapterShared.h @@ -0,0 +1,58 @@ +#pragma once + +#include "LoggerCommon.h" + +namespace tt { + +inline const char* toTagColour(LogLevel level) { + using enum LogLevel; + switch (level) { + case Error: + return "\033[1;31m"; + case Warning: + return "\033[1;33m"; + case Info: + return "\033[32m"; + case Debug: + return "\033[36m"; + case Verbose: + return "\033[37m"; + default: + return ""; + } +} + +inline const char* toMessageColour(LogLevel level) { + using enum LogLevel; + switch (level) { + case Error: + return "\033[1;31m"; + case Warning: + return "\033[1;33m"; + case Info: + case Debug: + case Verbose: + return "\033[0m"; + default: + return ""; + } +} + +inline char toPrefix(LogLevel level) { + using enum LogLevel; + switch (level) { + case Error: + return 'E'; + case Warning: + return 'W'; + case Info: + return 'I'; + case Debug: + return 'D'; + case Verbose: + default: + return 'V'; + } +} + +} \ No newline at end of file diff --git a/TactilityCore/Include/Tactility/LogCommon.h b/TactilityCore/Include/Tactility/LoggerCommon.h similarity index 100% rename from TactilityCore/Include/Tactility/LogCommon.h rename to TactilityCore/Include/Tactility/LoggerCommon.h diff --git a/TactilityCore/Include/Tactility/LoggerSettings.h b/TactilityCore/Include/Tactility/LoggerSettings.h new file mode 100644 index 00000000..3bb5105a --- /dev/null +++ b/TactilityCore/Include/Tactility/LoggerSettings.h @@ -0,0 +1,9 @@ +#pragma once + +#include "LoggerCommon.h" + +namespace tt { + +constexpr auto LOG_LEVEL = LogLevel::Info; + +} \ No newline at end of file diff --git a/TactilityCore/Include/Tactility/TactilityCore.h b/TactilityCore/Include/Tactility/TactilityCore.h index d107dc4a..88ccddf9 100644 --- a/TactilityCore/Include/Tactility/TactilityCore.h +++ b/TactilityCore/Include/Tactility/TactilityCore.h @@ -2,9 +2,6 @@ #include -#include "Tactility/Thread.h" #include "Check.h" #include "CoreDefines.h" -#include "Log.h" - -#include +#include "Logger.h" diff --git a/TactilityCore/Source/Check.cpp b/TactilityCore/Source/Check.cpp index beb0c2aa..07a57e7a 100644 --- a/TactilityCore/Source/Check.cpp +++ b/TactilityCore/Source/Check.cpp @@ -1,28 +1,28 @@ #include -#include +#include #include -constexpr auto TAG = "kernel"; +static const auto LOGGER = tt::Logger("kernel"); static void logMemoryInfo() { #ifdef ESP_PLATFORM - TT_LOG_E(TAG, "default caps:"); - TT_LOG_E(TAG, " total: %u", heap_caps_get_total_size(MALLOC_CAP_DEFAULT)); - TT_LOG_E(TAG, " free: %u", heap_caps_get_free_size(MALLOC_CAP_DEFAULT)); - TT_LOG_E(TAG, " min free: %u", heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT)); - TT_LOG_E(TAG, "internal caps:"); - TT_LOG_E(TAG, " total: %u", heap_caps_get_total_size(MALLOC_CAP_INTERNAL)); - TT_LOG_E(TAG, " free: %u", heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); - TT_LOG_E(TAG, " min free: %u", heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL)); + LOGGER.error("default caps:"); + LOGGER.error(" total: {}", heap_caps_get_total_size(MALLOC_CAP_DEFAULT)); + LOGGER.error(" free: {}", heap_caps_get_free_size(MALLOC_CAP_DEFAULT)); + LOGGER.error(" min free: {}", heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT)); + LOGGER.error("internal caps:"); + LOGGER.error(" total: {}", heap_caps_get_total_size(MALLOC_CAP_INTERNAL)); + LOGGER.error(" free: {}", heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); + LOGGER.error(" min free: {}", heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL)); #endif } static void logTaskInfo() { const char* name = pcTaskGetName(nullptr); const char* safe_name = name ? name : "main"; - TT_LOG_E(TAG, "Task: %s", safe_name); - TT_LOG_E(TAG, "Stack watermark: %u", uxTaskGetStackHighWaterMark(NULL) * 4); + LOGGER.error("Task: {}", safe_name); + LOGGER.error("Stack watermark: {}", uxTaskGetStackHighWaterMark(NULL) * 4); } namespace tt { diff --git a/TactilityCore/Source/LogSimulator.cpp b/TactilityCore/Source/LogSimulator.cpp deleted file mode 100644 index 5bf95cf4..00000000 --- a/TactilityCore/Source/LogSimulator.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#ifndef ESP_PLATFORM - -#include "Tactility/Log.h" - -#include -#include -#include -#include - -namespace tt { - -static char toPrefix(LogLevel level) { - using enum LogLevel; - switch (level) { - case Error: - return 'E'; - case Warning: - return 'W'; - case Info: - return 'I'; - case Debug: - return 'D'; - case Verbose: - return 'V'; - default: - return ' '; - } -} - -static const char* toTagColour(LogLevel level) { - using enum LogLevel; - switch (level) { - case Error: - return "\033[1;31m"; - case Warning: - return "\033[1;33m"; - case Info: - return "\033[32m"; - case Debug: - return "\033[36m"; - case Verbose: - return "\033[37m"; - default: - return ""; - } -} - -static const char* toMessageColour(LogLevel level) { - using enum LogLevel; - switch (level) { - case Error: - return "\033[1;31m"; - case Warning: - return "\033[1;33m"; - case Info: - case Debug: - case Verbose: - return "\033[0m"; - default: - return ""; - } -} -static uint64_t getLogTimestamp() { - static uint64_t base = 0U; - struct timeval time {}; - gettimeofday(&time, nullptr); - uint64_t now = ((uint64_t)time.tv_sec * 1000U) + (time.tv_usec / 1000U); - if (base == 0U) { - base = now; - } - return now - base; -} - -void log(LogLevel level, const char* tag, const char* format, ...) { - std::stringstream buffer; - buffer << getLogTimestamp() << " [" << toTagColour(level) << toPrefix(level) << "\033[0m" << "] [" << tag << "] " << toMessageColour(level) << format << "\033[0m\n"; - - va_list args; - va_start(args, format); - vprintf(buffer.str().c_str(), args); - va_end(args); -} - -} // namespace tt - -#endif \ No newline at end of file diff --git a/TactilityCore/Source/crypt/Crypt.cpp b/TactilityCore/Source/crypt/Crypt.cpp index d8d8741c..2b306764 100644 --- a/TactilityCore/Source/crypt/Crypt.cpp +++ b/TactilityCore/Source/crypt/Crypt.cpp @@ -1,7 +1,7 @@ -#include "Tactility/crypt/Crypt.h" +#include -#include "Tactility/Check.h" -#include "Tactility/Log.h" +#include +#include #include #include @@ -15,7 +15,8 @@ namespace tt::crypt { -#define TAG "secure" +static const auto LOGGER = Logger("Crypt"); + #define TT_NVS_NAMESPACE "tt_secure" #ifdef ESP_PLATFORM @@ -27,7 +28,7 @@ static void get_hardware_key(uint8_t key[32]) { uint8_t mac[8]; // MAC can be 6 or 8 bytes size_t mac_length = esp_mac_addr_len_get(ESP_MAC_EFUSE_FACTORY); - TT_LOG_I(TAG, "Using MAC with length %u", mac_length); + LOGGER.info("Using MAC with length {}", mac_length); tt_check(mac_length <= 8); ESP_ERROR_CHECK(esp_read_mac(mac, ESP_MAC_EFUSE_FACTORY)); @@ -66,13 +67,13 @@ static void get_nvs_key(uint8_t key[32]) { esp_err_t result = nvs_open(TT_NVS_NAMESPACE, NVS_READWRITE, &handle); if (result != ESP_OK) { - TT_LOG_E(TAG, "Failed to get key from NVS (%s)", esp_err_to_name(result)); + LOGGER.error("Failed to get key from NVS ({})", esp_err_to_name(result)); tt_crash("NVS error"); } size_t length = 32; if (nvs_get_blob(handle, "key", key, &length) == ESP_OK) { - TT_LOG_I(TAG, "Fetched key from NVS (%d bytes)", length); + LOGGER.info("Fetched key from NVS ({} bytes)", length); tt_check(length == 32); } else { // TODO: Improved randomness @@ -83,7 +84,7 @@ static void get_nvs_key(uint8_t key[32]) { key[i] = (uint8_t)(rand()); } ESP_ERROR_CHECK(nvs_set_blob(handle, "key", key, 32)); - TT_LOG_I(TAG, "Stored new key in NVS"); + LOGGER.info("Stored new key in NVS"); } nvs_close(handle); @@ -109,8 +110,8 @@ static void xorKey(const uint8_t* inLeft, const uint8_t* inRight, uint8_t* out, */ static void getKey(uint8_t key[32]) { #if !defined(CONFIG_SECURE_BOOT) || !defined(CONFIG_SECURE_FLASH_ENC_ENABLED) - TT_LOG_W(TAG, "Using tt_secure_* code with secure boot and/or flash encryption disabled."); - TT_LOG_W(TAG, "An attacker with physical access to your ESP32 can decrypt your secure data."); + LOGGER.warn("Using tt_secure_* code with secure boot and/or flash encryption disabled."); + LOGGER.warn("An attacker with physical access to your ESP32 can decrypt your secure data."); #endif #ifdef ESP_PLATFORM @@ -121,7 +122,7 @@ static void getKey(uint8_t key[32]) { get_nvs_key(nvs_key); xorKey(hardware_key, nvs_key, key, 32); #else - TT_LOG_W(TAG, "Using unsafe key for debugging purposes."); + LOGGER.warn("Using unsafe key for debugging purposes."); memset(key, 0, 32); #endif } diff --git a/TactilityCore/Source/file/File.cpp b/TactilityCore/Source/file/File.cpp index 20ae6617..c84bc86a 100644 --- a/TactilityCore/Source/file/File.cpp +++ b/TactilityCore/Source/file/File.cpp @@ -1,8 +1,10 @@ -#include "Tactility/file/File.h" +#include #include #include #include + +#include #include namespace tt::hal::sdcard { @@ -11,7 +13,7 @@ class SdCardDevice; namespace tt::file { -constexpr auto* TAG = "file"; +static const auto LOGGER = Logger("file"); class NoLock final : public Lock { bool lock(TickType_t timeout) const override { return true; } @@ -23,7 +25,7 @@ static std::function(const std::string&)> findLockFunction std::shared_ptr getLock(const std::string& path) { if (findLockFunction == nullptr) { - TT_LOG_W(TAG, "File lock function not set!"); + LOGGER.warn("File lock function not set!"); return noLock; } @@ -69,10 +71,10 @@ bool listDirectory( auto lock = getLock(path)->asScopedLock(); lock.lock(); - TT_LOG_I(TAG, "listDir start %s", path.c_str()); + LOGGER.info("listDir start {}", path); DIR* dir = opendir(path.c_str()); if (dir == nullptr) { - TT_LOG_E(TAG, "Failed to open dir %s", path.c_str()); + LOGGER.error("Failed to open dir {}", path); return false; } @@ -83,7 +85,7 @@ bool listDirectory( closedir(dir); - TT_LOG_I(TAG, "listDir stop %s", path.c_str()); + LOGGER.info("listDir stop {}", path); return true; } @@ -96,10 +98,10 @@ int scandir( auto lock = getLock(path)->asScopedLock(); lock.lock(); - TT_LOG_I(TAG, "scandir start"); + LOGGER.info("scandir start"); DIR* dir = opendir(path.c_str()); if (dir == nullptr) { - TT_LOG_E(TAG, "Failed to open dir %s", path.c_str()); + LOGGER.error("Failed to open dir {}", path); return -1; } @@ -116,7 +118,7 @@ int scandir( std::ranges::sort(outList, sortMethod); } - TT_LOG_I(TAG, "scandir finish"); + LOGGER.info("scandir finish"); return outList.size(); } @@ -125,18 +127,18 @@ long getSize(FILE* file) { long original_offset = ftell(file); if (fseek(file, 0, SEEK_END) != 0) { - TT_LOG_E(TAG, "fseek failed"); + LOGGER.error("fseek failed"); return -1; } long file_size = ftell(file); if (file_size == -1) { - TT_LOG_E(TAG, "Could not get file length"); + LOGGER.error("Could not get file length"); return -1; } if (fseek(file, original_offset, SEEK_SET) != 0) { - TT_LOG_E(TAG, "fseek Failed"); + LOGGER.error("fseek Failed"); return -1; } @@ -152,26 +154,26 @@ static std::unique_ptr readBinaryInternal(const std::string& filepath FILE* file = fopen(filepath.c_str(), "rb"); if (file == nullptr) { - TT_LOG_E(TAG, "Failed to open %s", filepath.c_str()); + LOGGER.error("Failed to open {}", filepath); return nullptr; } long content_length = getSize(file); if (content_length == -1) { - TT_LOG_E(TAG, "Failed to determine content length for %s", filepath.c_str()); + LOGGER.error("Failed to determine content length for {}", filepath); return nullptr; } auto data = std::make_unique(content_length + sizePadding); if (data == nullptr) { - TT_LOG_E(TAG, "Insufficient memory. Failed to allocate %ldl bytes.", content_length); + LOGGER.error("Insufficient memory. Failed to allocate {} bytes.", content_length); return nullptr; } size_t buffer_offset = 0; while (buffer_offset < content_length) { size_t bytes_read = fread(&data.get()[buffer_offset], 1, content_length - buffer_offset, file); - TT_LOG_D(TAG, "Read %d bytes", bytes_read); + LOGGER.debug("Read {} bytes", bytes_read); if (bytes_read > 0) { buffer_offset += bytes_read; } else { // Something went wrong? @@ -268,7 +270,7 @@ bool findOrCreateDirectory(const std::string& path, mode_t mode) { if (path.empty()) { return true; } - TT_LOG_D(TAG, "findOrCreate: %s %lu", path.c_str(), mode); + LOGGER.debug("findOrCreate: {} {}", path, mode); const char separator_to_find[] = {SEPARATOR, 0x00}; auto first_index = path[0] == SEPARATOR ? 1 : 0; @@ -280,10 +282,10 @@ bool findOrCreateDirectory(const std::string& path, mode_t mode) { auto to_create = is_last_segment ? path : path.substr(0, separator_index); should_break = is_last_segment; if (!findOrCreateDirectoryInternal(to_create, mode)) { - TT_LOG_E(TAG, "Failed to create %s", to_create.c_str()); + LOGGER.error("Failed to create {}", to_create); return false; } else { - TT_LOG_D(TAG, " - got: %s", to_create.c_str()); + LOGGER.debug(" - got: {}", to_create); } // Find next file separator index @@ -309,7 +311,7 @@ bool deleteRecursively(const std::string& path) { if (isDirectory(path)) { std::vector entries; if (scandir(path, entries) < 0) { - TT_LOG_E(TAG, "Failed to scan directory %s", path.c_str()); + LOGGER.error("Failed to scan directory {}", path); return false; } @@ -319,16 +321,16 @@ bool deleteRecursively(const std::string& path) { return false; } } - TT_LOG_I(TAG, "Deleting %s", path.c_str()); + LOGGER.info("Deleting {}", path); return deleteDirectory(path); } else if (isFile(path)) { - TT_LOG_I(TAG, "Deleting %s", path.c_str()); + LOGGER.info("Deleting {}", path); return deleteFile(path); } else if (path == "/" || path == "." || path == "..") { // No-op return true; } else { - TT_LOG_E(TAG, "Failed to delete \"%s\": unknown type", path.c_str()); + LOGGER.error("Failed to delete \"{}\": unknown type", path); return false; } }