diff --git a/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp b/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp index 7a292c2a4..241ae3055 100644 --- a/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp +++ b/Devices/cyd-4848s040c/Source/devices/St7701Display.cpp @@ -2,9 +2,9 @@ #include #include -#include #include #include +#include #include #include @@ -16,7 +16,7 @@ #include #include -static const auto LOGGER = tt::Logger("St7701Display"); +constexpr auto* TAG = "St7701Display"; // GPIO47/48 are physically shared between this bit-banged 3-wire command bus // and the SD card's real SPI2 bus (no alternate pins exist on this PCB). @@ -171,29 +171,29 @@ bool St7701Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_lc }; if (esp_lcd_new_panel_st7701(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, false) != ESP_OK) { - LOGGER.error("Failed to invert color"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } diff --git a/Devices/guition-jc1060p470ciwy/Source/devices/Display.cpp b/Devices/guition-jc1060p470ciwy/Source/devices/Display.cpp index 08724d462..d77689c5b 100644 --- a/Devices/guition-jc1060p470ciwy/Source/devices/Display.cpp +++ b/Devices/guition-jc1060p470ciwy/Source/devices/Display.cpp @@ -3,10 +3,10 @@ #include #include -#include #include #include #include +#include constexpr auto LCD_PIN_RESET = GPIO_NUM_0; // Match P4 EV board reset line constexpr auto LCD_PIN_BACKLIGHT = GPIO_NUM_23; @@ -36,7 +36,7 @@ static std::shared_ptr createTouch() { std::shared_ptr createDisplay() { // Initialize PWM backlight if (!driver::pwmbacklight::init(LCD_PIN_BACKLIGHT, 20000, LEDC_TIMER_1, LEDC_CHANNEL_0)) { - tt::Logger("jc1060p470ciwy").warn("Failed to initialize backlight"); + LOG_W("jc1060p470ciwy", "Failed to initialize backlight"); } auto touch = createTouch(); diff --git a/Devices/guition-jc1060p470ciwy/Source/devices/Jd9165Display.cpp b/Devices/guition-jc1060p470ciwy/Source/devices/Jd9165Display.cpp index 4db014619..0451355ec 100644 --- a/Devices/guition-jc1060p470ciwy/Source/devices/Jd9165Display.cpp +++ b/Devices/guition-jc1060p470ciwy/Source/devices/Jd9165Display.cpp @@ -1,10 +1,10 @@ #include "Jd9165Display.h" -#include +#include #include -static const auto LOGGER = tt::Logger("JD9165"); +constexpr auto* TAG = "JD9165"; // MIPI DSI PHY power configuration #define MIPI_DSI_PHY_PWR_LDO_CHAN 3 // LDO_VO3 connects to VDD_MIPI_DPHY @@ -87,11 +87,11 @@ bool Jd9165Display::createMipiDsiBus() { }; if (esp_ldo_acquire_channel(&ldo_mipi_phy_config, &ldoChannel) != ESP_OK) { - LOGGER.error("Failed to acquire LDO channel for MIPI DSI PHY"); + LOG_E(TAG, "Failed to acquire LDO channel for MIPI DSI PHY"); return false; } - - LOGGER.info("MIPI DSI PHY powered on"); + + LOG_I(TAG, "MIPI DSI PHY powered on"); // Create MIPI DSI bus // TODO: use MIPI_DSI_PHY_CLK_SRC_DEFAULT() in future ESP-IDF 6.0.0 update with esp_lcd_jd9165 library version 2.x @@ -103,11 +103,11 @@ bool Jd9165Display::createMipiDsiBus() { }; if (esp_lcd_new_dsi_bus(&bus_config, &mipiDsiBus) != ESP_OK) { - LOGGER.error("Failed to create MIPI DSI bus"); + LOG_E(TAG, "Failed to create MIPI DSI bus"); return false; } - LOGGER.info("MIPI DSI bus created"); + LOG_I(TAG, "MIPI DSI bus created"); return true; } @@ -123,7 +123,7 @@ bool Jd9165Display::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { esp_lcd_dbi_io_config_t dbi_config = JD9165_PANEL_IO_DBI_CONFIG(); if (esp_lcd_new_panel_io_dbi(mipiDsiBus, &dbi_config, &ioHandle) != ESP_OK) { - LOGGER.error("Failed to create panel IO"); + LOG_E(TAG, "Failed to create panel IO"); return false; } @@ -184,11 +184,11 @@ bool Jd9165Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, const mutable_panel_config.vendor_config = &vendor_config; if (esp_lcd_new_panel_jd9165(ioHandle, &mutable_panel_config, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } - LOGGER.info("JD9165 panel created successfully"); + LOG_I(TAG, "JD9165 panel created successfully"); // Defer reset/init to base class applyConfiguration to avoid double initialization return true; } diff --git a/Devices/guition-jc1060p470ciwy/Source/devices/Power.cpp b/Devices/guition-jc1060p470ciwy/Source/devices/Power.cpp index 5b6cf83f5..e221f92db 100644 --- a/Devices/guition-jc1060p470ciwy/Source/devices/Power.cpp +++ b/Devices/guition-jc1060p470ciwy/Source/devices/Power.cpp @@ -1,14 +1,14 @@ #include "Power.h" -#include #include +#include #include #include #include using tt::hal::power::PowerDevice; -static const auto LOGGER = tt::Logger("JcPower"); +constexpr auto* TAG = "JcPower"; namespace { @@ -71,7 +71,7 @@ class JcPower final : public PowerDevice { .ulp_mode = ADC_ULP_MODE_DISABLE, }; if (adc_oneshot_new_unit(&init_cfg, &adcHandle) != ESP_OK) { - LOGGER.error("ADC unit init failed"); + LOG_E(TAG, "ADC unit init failed"); return false; } @@ -80,7 +80,7 @@ class JcPower final : public PowerDevice { .bitwidth = ADC_BITWIDTH_DEFAULT, }; if (adc_oneshot_config_channel(adcHandle, ADC_CHANNEL, &chan_cfg) != ESP_OK) { - LOGGER.error("ADC channel config failed"); + LOG_E(TAG, "ADC channel config failed"); adc_oneshot_del_unit(adcHandle); adcHandle = nullptr; return false; @@ -100,7 +100,7 @@ class JcPower final : public PowerDevice { }; if (adc_cali_create_scheme_line_fitting(&cali_config, &caliHandle) == ESP_OK) { calScheme = CaliScheme::Line; - LOGGER.info("ADC calibration (line fitting) enabled"); + LOG_I(TAG, "ADC calibration (line fitting) enabled"); return true; } #endif @@ -114,19 +114,19 @@ class JcPower final : public PowerDevice { }; if (adc_cali_create_scheme_curve_fitting(&curve_cfg, &caliHandle) == ESP_OK) { calScheme = CaliScheme::Curve; - LOGGER.info("ADC calibration (curve fitting) enabled"); + LOG_I(TAG, "ADC calibration (curve fitting) enabled"); return true; } #endif - LOGGER.warn("ADC calibration not available, using raw scaling"); + LOG_W(TAG, "ADC calibration not available, using raw scaling"); return false; } bool readBatteryMilliVolt(uint32_t& outMv) { int raw = 0; if (adc_oneshot_read(adcHandle, ADC_CHANNEL, &raw) != ESP_OK) { - LOGGER.error("ADC read failed"); + LOG_E(TAG, "ADC read failed"); return false; } diff --git a/Devices/guition-jc3248w535c/Source/Axs15231b/Axs15231bDisplay.cpp b/Devices/guition-jc3248w535c/Source/Axs15231b/Axs15231bDisplay.cpp index 762cd41ab..c358ad014 100644 --- a/Devices/guition-jc3248w535c/Source/Axs15231b/Axs15231bDisplay.cpp +++ b/Devices/guition-jc3248w535c/Source/Axs15231b/Axs15231bDisplay.cpp @@ -1,6 +1,5 @@ #include "Axs15231bDisplay.h" -#include #include #include #include @@ -9,8 +8,9 @@ #include #include #include +#include -static const auto LOGGER = tt::Logger("AXS15231B"); +constexpr auto* TAG = "AXS15231B"; static const axs15231b_lcd_init_cmd_t lcd_init_cmds[] = { {0xBB, (uint8_t[]){0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5A, 0xA5}, 8, 0}, @@ -74,7 +74,7 @@ void Axs15231bDisplay::lvgl_port_flush_callback(lv_display_t *drv, const lv_area MALLOC_CAP_SPIRAM); if (self->tempBuf == nullptr) { if (!allocationErrorLogged) { - LOGGER.error("Failed to allocate rotation buffer, drawing unrotated"); + LOG_E(TAG, "Failed to allocate rotation buffer, drawing unrotated"); allocationErrorLogged = true; } if (esp_lcd_panel_draw_bitmap(panel_handle, 0, 0, self->configuration->horizontalResolution, self->configuration->verticalResolution, draw_buf) != ESP_OK) { @@ -145,7 +145,7 @@ void Axs15231bDisplay::lvgl_port_flush_callback(lv_display_t *drv, const lv_area if (ret != ESP_OK) { // If SPI transfer failed, on_color_trans_done won't fire. // Manually signal flush ready to prevent LVGL from hanging. - LOGGER.error("draw_bitmap failed: {}", esp_err_to_name(ret)); + LOG_E(TAG, "draw_bitmap failed: %s", esp_err_to_name(ret)); lv_display_flush_ready(drv); } } @@ -169,13 +169,13 @@ void IRAM_ATTR Axs15231bDisplay::teIsrHandler(void* arg) { bool Axs15231bDisplay::setupTeSync() { if (configuration->tePin == GPIO_NUM_NC) { - LOGGER.info("TE pin not configured, skipping TE sync"); + LOG_I(TAG, "TE pin not configured, skipping TE sync"); return true; } teSyncSemaphore = xSemaphoreCreateBinary(); if (teSyncSemaphore == nullptr) { - LOGGER.error("Failed to create TE sync semaphore"); + LOG_E(TAG, "Failed to create TE sync semaphore"); return false; } @@ -187,7 +187,7 @@ bool Axs15231bDisplay::setupTeSync() { io_conf.pin_bit_mask = (1ULL << configuration->tePin); if (gpio_config(&io_conf) != ESP_OK) { - LOGGER.error("Failed to configure TE GPIO"); + LOG_E(TAG, "Failed to configure TE GPIO"); vSemaphoreDelete(teSyncSemaphore); teSyncSemaphore = nullptr; return false; @@ -197,14 +197,14 @@ bool Axs15231bDisplay::setupTeSync() { if (err == ESP_OK) { isrServiceInstalledByUs = true; } else if (err != ESP_ERR_INVALID_STATE) { - LOGGER.error("Failed to install GPIO ISR service"); + LOG_E(TAG, "Failed to install GPIO ISR service"); vSemaphoreDelete(teSyncSemaphore); teSyncSemaphore = nullptr; return false; } if (gpio_isr_handler_add(configuration->tePin, teIsrHandler, (void*)teSyncSemaphore) != ESP_OK) { - LOGGER.error("Failed to add TE ISR handler"); + LOG_E(TAG, "Failed to add TE ISR handler"); gpio_intr_disable(configuration->tePin); if (isrServiceInstalledByUs) { gpio_uninstall_isr_service(); @@ -216,7 +216,7 @@ bool Axs15231bDisplay::setupTeSync() { } teIsrInstalled = true; - LOGGER.info("TE sync enabled on GPIO {}", (int)configuration->tePin); + LOG_I(TAG, "TE sync enabled on GPIO %d", (int)configuration->tePin); return true; } @@ -285,19 +285,19 @@ bool Axs15231bDisplay::createPanelHandle() { }; if (esp_lcd_new_panel_axs15231b(ioHandle, &panel_config, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create axs15231b"); + LOG_E(TAG, "Failed to create axs15231b"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; @@ -305,28 +305,28 @@ bool Axs15231bDisplay::createPanelHandle() { //SWAPXY Doesn't work with the JC3248W535... Left in for future compatibility. if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY"); + LOG_E(TAG, "Failed to swap XY"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to mirror panel"); + LOG_E(TAG, "Failed to mirror panel"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to invert color"); + LOG_E(TAG, "Failed to invert color"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; } if (esp_lcd_panel_disp_on_off(panelHandle, false) != ESP_OK) { - LOGGER.error("Failed to turn off panel"); + LOG_E(TAG, "Failed to turn off panel"); esp_lcd_panel_del(panelHandle); panelHandle = nullptr; return false; @@ -343,19 +343,19 @@ Axs15231bDisplay::Axs15231bDisplay(std::unique_ptr inConfiguratio bool Axs15231bDisplay::start() { if (!createIoHandle()) { - LOGGER.error("Failed to create IO handle"); + LOG_E(TAG, "Failed to create IO handle"); return false; } if (!createPanelHandle()) { - LOGGER.error("Failed to create panel handle"); + LOG_E(TAG, "Failed to create panel handle"); esp_lcd_panel_io_del(ioHandle); ioHandle = nullptr; return false; } if (!setupTeSync()) { - LOGGER.warn("TE sync setup failed, continuing without TE synchronization"); + LOG_W(TAG, "TE sync setup failed, continuing without TE synchronization"); } return true; @@ -372,12 +372,12 @@ bool Axs15231bDisplay::stop() { displayDriver.reset(); if (panelHandle != nullptr && esp_lcd_panel_del(panelHandle) != ESP_OK) { - LOGGER.error("Failed to delete panel"); + LOG_E(TAG, "Failed to delete panel"); } panelHandle = nullptr; if (ioHandle != nullptr && esp_lcd_panel_io_del(ioHandle) != ESP_OK) { - LOGGER.error("Failed to delete IO"); + LOG_E(TAG, "Failed to delete IO"); } ioHandle = nullptr; @@ -386,7 +386,7 @@ bool Axs15231bDisplay::stop() { bool Axs15231bDisplay::startLvgl() { if (lvglDisplay != nullptr) { - LOGGER.error("LVGL already started"); + LOG_E(TAG, "LVGL already started"); return false; } @@ -399,7 +399,7 @@ bool Axs15231bDisplay::startLvgl() { buffer1 = (uint16_t*)heap_caps_malloc(bufferSize, MALLOC_CAP_SPIRAM); buffer2 = (uint16_t*)heap_caps_malloc(bufferSize, MALLOC_CAP_SPIRAM); if (buffer1 == nullptr || buffer2 == nullptr) { - LOGGER.error("Failed to allocate buffers"); + LOG_E(TAG, "Failed to allocate buffers"); heap_caps_free(buffer1); heap_caps_free(buffer2); buffer1 = nullptr; @@ -419,7 +419,7 @@ bool Axs15231bDisplay::startLvgl() { .on_color_trans_done = onColorTransDone, }; if (esp_lcd_panel_io_register_event_callbacks(ioHandle, &cbs, lvglDisplay) != ESP_OK) { - LOGGER.error("Failed to register panel IO callbacks"); + LOG_E(TAG, "Failed to register panel IO callbacks"); heap_caps_free(buffer1); heap_caps_free(buffer2); buffer1 = nullptr; @@ -474,11 +474,11 @@ bool Axs15231bDisplay::stopLvgl() { std::shared_ptr Axs15231bDisplay::getDisplayDriver() { if (lvglDisplay != nullptr) { - LOGGER.error("Cannot get DisplayDriver while LVGL is active - call stopLvgl() first"); + LOG_E(TAG, "Cannot get DisplayDriver while LVGL is active - call stopLvgl() first"); return nullptr; } if (panelHandle == nullptr) { - LOGGER.error("Cannot get DisplayDriver - display is not started"); + LOG_E(TAG, "Cannot get DisplayDriver - display is not started"); return nullptr; } if (displayDriver == nullptr) { diff --git a/Devices/lilygo-tdeck/Source/Init.cpp b/Devices/lilygo-tdeck/Source/Init.cpp index 14386e363..d484c39b2 100644 --- a/Devices/lilygo-tdeck/Source/Init.cpp +++ b/Devices/lilygo-tdeck/Source/Init.cpp @@ -5,11 +5,11 @@ #include #include #include -#include #include #include +#include -static const auto LOGGER = tt::Logger("T-Deck"); +constexpr auto* TAG = "T-Deck"; constexpr auto TDECK_POWERON_GPIO = GPIO_NUM_10; @@ -37,9 +37,9 @@ static bool powerOn() { } bool initBoot() { - LOGGER.info(LOG_MESSAGE_POWER_ON_START); + LOG_I(TAG, LOG_MESSAGE_POWER_ON_START); if (!powerOn()) { - LOGGER.error(LOG_MESSAGE_POWER_ON_FAILED); + LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED); return false; } @@ -47,7 +47,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)) { - LOGGER.error("Backlight init failed"); + LOG_E(TAG, "Backlight init failed"); return false; } @@ -58,9 +58,9 @@ bool initBoot() { gps_service->getGpsConfigurations(gps_configurations); if (gps_configurations.empty()) { if (gps_service->addGpsConfiguration(tt::hal::gps::GpsConfiguration {.uartName = "uart0", .baudRate = 38400, .model = tt::hal::gps::GpsModel::UBLOX10})) { - LOGGER.info("Configured internal GPS"); + LOG_I(TAG, "Configured internal GPS"); } else { - LOGGER.error("Failed to configure internal GPS"); + LOG_E(TAG, "Failed to configure internal GPS"); } } } @@ -69,23 +69,23 @@ bool initBoot() { tt::kernel::subscribeSystemEvent(tt::kernel::SystemEvent::BootSplash, [](tt::kernel::SystemEvent event) { auto kbBacklight = tt::hal::findDevice("Keyboard Backlight"); if (kbBacklight != nullptr) { - LOGGER.info("{} starting", kbBacklight->getName()); + LOG_I(TAG, "%s starting", kbBacklight->getName().c_str()); auto kbDevice = std::static_pointer_cast(kbBacklight); if (kbDevice->start()) { - LOGGER.info("{} started", kbBacklight->getName()); + LOG_I(TAG, "%s started", kbBacklight->getName().c_str()); } else { - LOGGER.error("{} start failed", kbBacklight->getName()); + LOG_E(TAG, "%s start failed", kbBacklight->getName().c_str()); } } auto trackball = tt::hal::findDevice("Trackball"); if (trackball != nullptr) { - LOGGER.info("{} starting", trackball->getName()); + LOG_I(TAG, "%s starting", trackball->getName().c_str()); auto tbDevice = std::static_pointer_cast(trackball); if (tbDevice->start()) { - LOGGER.info("{} started", trackball->getName()); + LOG_I(TAG, "%s started", trackball->getName().c_str()); } else { - LOGGER.error("{} start failed", trackball->getName()); + LOG_E(TAG, "%s start failed", trackball->getName().c_str()); } } }); diff --git a/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp b/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp index 185216cfb..e0ea70d8b 100644 --- a/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp +++ b/Devices/lilygo-tdeck/Source/KeyboardBacklight/KeyboardBacklight.cpp @@ -1,11 +1,10 @@ #include "KeyboardBacklight.h" -#include - #include #include +#include -static const auto LOGGER = tt::Logger("KeyboardBacklight"); +constexpr auto* TAG = "KeyboardBacklight"; namespace keyboardbacklight { @@ -21,16 +20,16 @@ bool init(i2c_port_t i2cPort, uint8_t slaveAddress) { g_i2cPort = i2cPort; g_slaveAddress = slaveAddress; - LOGGER.info("Initialized on I2C port {}, address 0x{:02X}", static_cast(g_i2cPort), g_slaveAddress); - + LOG_I(TAG, "Initialized on I2C port %d, address 0x%02X", static_cast(g_i2cPort), (unsigned)g_slaveAddress); + // Set a reasonable default brightness if (!setDefaultBrightness(127)) { - LOGGER.error("Failed to set default brightness"); + LOG_E(TAG, "Failed to set default brightness"); return false; } if (!setBrightness(127)) { - LOGGER.error("Failed to set brightness"); + LOG_E(TAG, "Failed to set brightness"); return false; } @@ -39,16 +38,16 @@ bool init(i2c_port_t i2cPort, uint8_t slaveAddress) { bool setBrightness(uint8_t brightness) { if (g_i2cPort >= I2C_NUM_MAX) { - LOGGER.error("Not initialized"); + LOG_E(TAG, "Not initialized"); return false; } - + // Skip if brightness is already at target value (avoid I2C spam on every keypress) if (brightness == g_currentBrightness) { return true; } - - LOGGER.info("Setting brightness to {} on I2C port {}, address 0x{:02X}", brightness, static_cast(g_i2cPort), g_slaveAddress); + + LOG_I(TAG, "Setting brightness to %d on I2C port %d, address 0x%02X", brightness, static_cast(g_i2cPort), (unsigned)g_slaveAddress); i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); @@ -62,20 +61,20 @@ bool setBrightness(uint8_t brightness) { if (ret == ESP_OK) { g_currentBrightness = brightness; - LOGGER.info("Successfully set brightness to {}", brightness); + LOG_I(TAG, "Successfully set brightness to %d", brightness); return true; } else { - LOGGER.error("Failed to set brightness: {} (0x{:02X})", esp_err_to_name(ret), ret); + LOG_E(TAG, "Failed to set brightness: %s (0x%02X)", esp_err_to_name(ret), (unsigned)ret); return false; } } bool setDefaultBrightness(uint8_t brightness) { if (g_i2cPort >= I2C_NUM_MAX) { - LOGGER.error("Not initialized"); + LOG_E(TAG, "Not initialized"); return false; } - + // Clamp to valid range for default brightness if (brightness < 30) { brightness = 30; @@ -92,17 +91,17 @@ bool setDefaultBrightness(uint8_t brightness) { i2c_cmd_link_delete(cmd); if (ret == ESP_OK) { - LOGGER.debug("Set default brightness to {}", brightness); + LOG_D(TAG, "Set default brightness to %d", brightness); return true; } else { - LOGGER.error("Failed to set default brightness: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to set default brightness: %s", esp_err_to_name(ret)); return false; } } uint8_t getBrightness() { if (g_i2cPort >= I2C_NUM_MAX) { - LOGGER.error("Not initialized"); + LOG_E(TAG, "Not initialized"); return 0; } diff --git a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp index af7650c21..98c76b683 100644 --- a/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp +++ b/Devices/lilygo-tdeck/Source/Trackball/Trackball.cpp @@ -1,10 +1,10 @@ #include "Trackball.h" #include -#include #include +#include -static const auto LOGGER = tt::Logger("Trackball"); +constexpr auto* TAG = "Trackball"; namespace trackball { @@ -133,7 +133,7 @@ static void read_cb(lv_indev_t* indev, lv_indev_data_t* data) { lv_indev_t* init(const TrackballConfig& config) { if (g_initialized.load(std::memory_order_relaxed)) { - LOGGER.warn("Already initialized"); + LOG_W(TAG, "Already initialized"); return g_indev; } @@ -177,7 +177,7 @@ lv_indev_t* init(const TrackballConfig& config) { // ESP_ERR_INVALID_STATE means already installed, which is fine isr_service_installed = true; } else { - LOGGER.error("Failed to install GPIO ISR service: {}", esp_err_to_name(err)); + LOG_E(TAG, "Failed to install GPIO ISR service: %s", esp_err_to_name(err)); return nullptr; } } @@ -190,7 +190,7 @@ lv_indev_t* init(const TrackballConfig& config) { io_conf.pin_bit_mask = (1ULL << dirPins[i]); esp_err_t err = gpio_config(&io_conf); if (err != ESP_OK) { - LOGGER.error("Failed to configure GPIO {}: {}", static_cast(dirPins[i]), esp_err_to_name(err)); + LOG_E(TAG, "Failed to configure GPIO %d: %s", static_cast(dirPins[i]), esp_err_to_name(err)); // Cleanup previously added handlers for (int j = 0; j < handlersAdded; j++) { gpio_isr_handler_remove(dirPins[j]); @@ -200,7 +200,7 @@ lv_indev_t* init(const TrackballConfig& config) { err = gpio_isr_handler_add(dirPins[i], trackball_isr_handler, reinterpret_cast(static_cast(dirPins[i]))); if (err != ESP_OK) { - LOGGER.error("Failed to add ISR for GPIO {}: {}", static_cast(dirPins[i]), esp_err_to_name(err)); + LOG_E(TAG, "Failed to add ISR for GPIO %d: %s", static_cast(dirPins[i]), esp_err_to_name(err)); // Cleanup previously added handlers for (int j = 0; j < handlersAdded; j++) { gpio_isr_handler_remove(dirPins[j]); @@ -215,7 +215,7 @@ lv_indev_t* init(const TrackballConfig& config) { io_conf.pin_bit_mask = (1ULL << config.pinClick); esp_err_t err = gpio_config(&io_conf); if (err != ESP_OK) { - LOGGER.error("Failed to configure button GPIO {}: {}", static_cast(config.pinClick), esp_err_to_name(err)); + LOG_E(TAG, "Failed to configure button GPIO %d: %s", static_cast(config.pinClick), esp_err_to_name(err)); // Cleanup direction handlers for (int i = 0; i < 4; i++) { gpio_isr_handler_remove(dirPins[i]); @@ -225,7 +225,7 @@ lv_indev_t* init(const TrackballConfig& config) { err = gpio_isr_handler_add(config.pinClick, button_isr_handler, nullptr); if (err != ESP_OK) { - LOGGER.error("Failed to add button ISR: {}", esp_err_to_name(err)); + LOG_E(TAG, "Failed to add button ISR: %s", esp_err_to_name(err)); // Cleanup direction handlers for (int i = 0; i < 4; i++) { gpio_isr_handler_remove(dirPins[i]); @@ -239,7 +239,7 @@ lv_indev_t* init(const TrackballConfig& config) { // Register as LVGL encoder input device for group navigation (default mode) g_indev = lv_indev_create(); if (g_indev == nullptr) { - LOGGER.error("Failed to register LVGL input device"); + LOG_E(TAG, "Failed to register LVGL input device"); // Cleanup ISR handlers on failure const gpio_num_t pins[5] = { config.pinRight, config.pinUp, config.pinLeft, @@ -255,7 +255,7 @@ 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); g_initialized.store(true, std::memory_order_relaxed); - LOGGER.info("Initialized with interrupts (R:{} U:{} L:{} D:{} Click:{})", + LOG_I(TAG, "Initialized with interrupts (R:%d U:%d L:%d D:%d Click:%d)", static_cast(config.pinRight), static_cast(config.pinUp), static_cast(config.pinLeft), @@ -276,7 +276,7 @@ static void createCursor() { // Set cursor image lv_image_set_src(g_cursor, TT_ASSETS_UI_CURSOR); lv_indev_set_cursor(g_indev, g_cursor); - LOGGER.debug("Cursor created"); + LOG_D(TAG, "Cursor created"); } } @@ -287,7 +287,7 @@ static void destroyCursor() { // Delete the cursor object - this automatically detaches it from the indev lv_obj_delete(g_cursor); g_cursor = nullptr; - LOGGER.debug("Cursor destroyed"); + LOG_D(TAG, "Cursor destroyed"); } void deinit() { @@ -317,14 +317,14 @@ void deinit() { g_initialized.store(false, std::memory_order_relaxed); g_mode.store(Mode::Encoder, std::memory_order_relaxed); g_enabled.store(true, std::memory_order_relaxed); - LOGGER.info("Deinitialized"); + LOG_I(TAG, "Deinitialized"); } void setEncoderSensitivity(uint8_t sensitivity) { if (sensitivity > 0) { // Only update the atomic - ISR reads from atomic, not g_config g_encoderSensitivity.store(sensitivity, std::memory_order_relaxed); - LOGGER.debug("Encoder sensitivity set to {}", sensitivity); + LOG_D(TAG, "Encoder sensitivity set to %d", sensitivity); } } @@ -332,7 +332,7 @@ void setPointerSensitivity(uint8_t sensitivity) { if (sensitivity > 0) { // Only update the atomic - ISR reads from atomic, not g_config g_pointerSensitivity.store(sensitivity, std::memory_order_relaxed); - LOGGER.debug("Pointer sensitivity set to {}", sensitivity); + LOG_D(TAG, "Pointer sensitivity set to %d", sensitivity); } } @@ -355,13 +355,13 @@ void setEnabled(bool enabled) { } } - LOGGER.info("{}", enabled ? "Enabled" : "Disabled"); + LOG_I(TAG, "%s", enabled ? "Enabled" : "Disabled"); } void setMode(Mode mode) { // Note: Must be called from LVGL thread (main thread) for thread safety if (!g_initialized.load(std::memory_order_relaxed) || g_indev == nullptr) { - LOGGER.warn("Cannot set mode - not initialized"); + LOG_W(TAG, "Cannot set mode - not initialized"); return; } @@ -381,13 +381,13 @@ void setMode(Mode mode) { // Reset cursor to center when switching modes g_cursorX.store(SCREEN_WIDTH / 2, std::memory_order_relaxed); g_cursorY.store(SCREEN_HEIGHT / 2, std::memory_order_relaxed); - LOGGER.info("Switched to Pointer mode"); + LOG_I(TAG, "Switched to Pointer mode"); } else { // Switch to encoder mode destroyCursor(); lv_indev_set_type(g_indev, LV_INDEV_TYPE_ENCODER); g_encoderDiff.store(0, std::memory_order_relaxed); // Reset encoder diff - LOGGER.info("Switched to Encoder mode"); + LOG_I(TAG, "Switched to Encoder mode"); } } diff --git a/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp b/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp index ec32b0251..5c26e0823 100644 --- a/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp +++ b/Devices/lilygo-tdeck/Source/devices/TdeckKeyboard.cpp @@ -1,16 +1,16 @@ #include "TdeckKeyboard.h" #include -#include #include #include #include #include #include +#include using tt::hal::findFirstDevice; -static const auto LOGGER = tt::Logger("TdeckKeyboard"); +constexpr auto* TAG = "TdeckKeyboard"; constexpr uint8_t TDECK_KEYBOARD_SLAVE_ADDRESS = 0x55; @@ -34,15 +34,11 @@ static void keyboard_read_callback(lv_indev_t* indev, lv_indev_data_t* data) { auto* keyboard = static_cast(lv_indev_get_user_data(indev)); if (i2c_controller_read(keyboard->getI2cController(), TDECK_KEYBOARD_SLAVE_ADDRESS, &read_buffer, 1, 100 / portTICK_PERIOD_MS) == ERROR_NONE) { if (read_buffer == 0 && read_buffer != last_buffer) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Released {}", last_buffer); - } + LOG_D(TAG, "Released %d", last_buffer); data->key = last_buffer; data->state = LV_INDEV_STATE_RELEASED; } else if (read_buffer != 0) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Pressed {}", read_buffer); - } + LOG_D(TAG, "Pressed %d", 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-tdeck/Source/devices/TrackballDevice.cpp b/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp index 9b24f10f0..11c8d5459 100644 --- a/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp +++ b/Devices/lilygo-tdeck/Source/devices/TrackballDevice.cpp @@ -1,10 +1,10 @@ #include "TrackballDevice.h" #include // Driver -#include #include #include +#include -static const auto LOGGER = tt::Logger("TrackballDevice"); +constexpr auto* TAG = "TrackballDevice"; bool TrackballDevice::start() { if (initialized) { @@ -40,7 +40,7 @@ bool TrackballDevice::start() { trackball::setEnabled(tbSettings.trackballEnabled); tt::lvgl::unlock(); } else { - LOGGER.warn("Failed to acquire LVGL lock for trackball settings"); + LOG_W(TAG, "Failed to acquire LVGL lock for trackball settings"); } return true; diff --git a/Devices/lilygo-tdisplay-s3/Source/Init.cpp b/Devices/lilygo-tdisplay-s3/Source/Init.cpp index 1ce00d086..2dc55e5d6 100644 --- a/Devices/lilygo-tdisplay-s3/Source/Init.cpp +++ b/Devices/lilygo-tdisplay-s3/Source/Init.cpp @@ -2,8 +2,9 @@ #include "devices/Display.h" #include "PwmBacklight.h" -#include "Tactility/kernel/SystemEvents.h" +#include #include +#include #define TAG "tdisplay-s3" @@ -28,14 +29,14 @@ static bool powerOn() { } bool initBoot() { - ESP_LOGI(TAG, "Powering on the board..."); + LOG_I(TAG, "Powering on"); if (!powerOn()) { - ESP_LOGE(TAG, "Failed to power on the board."); + LOG_E(TAG, "Power on failed"); return false; } if (!driver::pwmbacklight::init(DISPLAY_BL, 30000)) { - ESP_LOGE(TAG, "Failed to initialize backlight."); + LOG_E(TAG, "Backlight init failed"); return false; } diff --git a/Devices/lilygo-tdongle-s3/Source/Init.cpp b/Devices/lilygo-tdongle-s3/Source/Init.cpp index abb194ac6..57e9b18ef 100644 --- a/Devices/lilygo-tdongle-s3/Source/Init.cpp +++ b/Devices/lilygo-tdongle-s3/Source/Init.cpp @@ -1,14 +1,14 @@ #include "PwmBacklight.h" -#include #include #include +#include -static const auto LOGGER = tt::Logger("T-Dongle S3"); +constexpr auto* TAG = "T-Dongle S3"; bool initBoot() { if (!driver::pwmbacklight::init(GPIO_NUM_38, 12000)) { - LOGGER.error("Backlight init failed"); + LOG_E(TAG, "Backlight init failed"); return false; } diff --git a/Devices/lilygo-thmi/Source/Init.cpp b/Devices/lilygo-thmi/Source/Init.cpp index 0a44f1fb6..e6edc2623 100644 --- a/Devices/lilygo-thmi/Source/Init.cpp +++ b/Devices/lilygo-thmi/Source/Init.cpp @@ -2,7 +2,8 @@ #include "devices/Display.h" #include "PwmBacklight.h" -#include "Tactility/kernel/SystemEvents.h" +#include +#include #include #define TAG "thmi" @@ -32,16 +33,16 @@ static bool powerOn() { } bool initBoot() { - ESP_LOGI(TAG, "Powering on the board..."); + LOG_I(TAG, "Powering on the board..."); if (!powerOn()) { - ESP_LOGE(TAG, "Failed to power on the board."); + LOG_E(TAG, "Failed to power on the board."); return false; } if (!driver::pwmbacklight::init(DISPLAY_BL, 30000)) { - ESP_LOGE(TAG, "Failed to initialize backlight."); + LOG_E(TAG, "Failed to initialize backlight."); return false; } return true; -} \ No newline at end of file +} diff --git a/Devices/lilygo-thmi/Source/devices/Power.cpp b/Devices/lilygo-thmi/Source/devices/Power.cpp index b24a9411d..674429990 100644 --- a/Devices/lilygo-thmi/Source/devices/Power.cpp +++ b/Devices/lilygo-thmi/Source/devices/Power.cpp @@ -1,24 +1,24 @@ #include "Power.h" -#include #include +#include -static const auto LOGGER = tt::Logger("Power"); +constexpr auto* TAG = "Power"; bool Power::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) { - LOGGER.warn("Calibration scheme not supported, skip software calibration"); + LOG_W(TAG, "Calibration scheme not supported, skip software calibration"); } else if (efuse_read_result == ESP_ERR_INVALID_VERSION) { - LOGGER.warn("eFuse not burnt, skip software calibration"); + LOG_W(TAG, "eFuse not burnt, skip software calibration"); } else if (efuse_read_result == ESP_OK) { calibrated = true; - LOGGER.info("Calibration success"); + LOG_I(TAG, "Calibration success"); esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, static_cast(ADC_WIDTH_BIT_DEFAULT), 0, &adcCharacteristics); } else { - LOGGER.warn("eFuse read failed, skipping calibration"); + LOG_W(TAG, "eFuse read failed, skipping calibration"); } return calibrated; @@ -26,16 +26,16 @@ bool Power::adcInitCalibration() { uint32_t Power::adcReadValue() const { int adc_raw = adc1_get_raw(ADC1_CHANNEL_4); - LOGGER.debug("Raw data: {}", adc_raw); + LOG_D(TAG, "Raw data: %d", adc_raw); uint32_t voltage; if (calibrated) { voltage = esp_adc_cal_raw_to_voltage(adc_raw, &adcCharacteristics); - LOGGER.debug("Calibrated data: {} mV", voltage); + LOG_D(TAG, "Calibrated data: %d mV", (int)voltage); } else { voltage = (adc_raw * 3300) / 4095; // fallback - LOGGER.debug("Estimated data: {} mV", voltage); + LOG_D(TAG, "Estimated data: %d mV", (int)voltage); } return voltage; @@ -45,12 +45,12 @@ bool Power::ensureInitialized() { if (!initialized) { if (adc1_config_width(ADC_WIDTH_BIT_12) != ESP_OK) { - LOGGER.error("ADC1 config width failed"); + LOG_E(TAG, "ADC1 config width failed"); return false; } if (adc1_config_channel_atten(ADC1_CHANNEL_4, ADC_ATTEN_DB_11) != ESP_OK) { - LOGGER.error("ADC1 config attenuation failed"); + LOG_E(TAG, "ADC1 config attenuation failed"); return false; } diff --git a/Devices/lilygo-tlora-pager/Source/Init.cpp b/Devices/lilygo-tlora-pager/Source/Init.cpp index f02a8ea86..b5de9bc85 100644 --- a/Devices/lilygo-tlora-pager/Source/Init.cpp +++ b/Devices/lilygo-tlora-pager/Source/Init.cpp @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -8,17 +7,18 @@ #include #include +#include -static const auto LOGGER = tt::Logger("T-Lora Pager"); +constexpr auto* TAG = "T-Lora Pager"; bool tpagerInit() { - LOGGER.info(LOG_MESSAGE_POWER_ON_START); + LOG_I(TAG, 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)) { - LOGGER.error("Backlight init failed"); + LOG_E(TAG, "Backlight init failed"); return false; } @@ -45,9 +45,9 @@ bool tpagerInit() { .baudRate = 38400, .model = tt::hal::gps::GpsModel::UBLOX10 })) { - LOGGER.info("Configured internal GPS"); + LOG_I(TAG, "Configured internal GPS"); } else { - LOGGER.error("Failed to configure internal GPS"); + LOG_E(TAG, "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 764aaa30f..571b2b132 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerEncoder.cpp @@ -1,9 +1,9 @@ #include "TpagerEncoder.h" -#include #include +#include -static const auto LOGGER = tt::Logger("TpagerEncoder"); +constexpr auto* TAG = "TpagerEncoder"; constexpr auto ENCODER_A = GPIO_NUM_40; constexpr auto ENCODER_B = GPIO_NUM_41; @@ -58,7 +58,7 @@ bool TpagerEncoder::initEncoder() { }; if (pcnt_new_unit(&unit_config, &encPcntUnit) != ESP_OK) { - LOGGER.error("Pulsecounter initialization failed"); + LOG_E(TAG, "Pulsecounter initialization failed"); return false; } @@ -67,7 +67,7 @@ bool TpagerEncoder::initEncoder() { }; if (pcnt_unit_set_glitch_filter(encPcntUnit, &filter_config) != ESP_OK) { - LOGGER.error("Pulsecounter glitch filter config failed"); + LOG_E(TAG, "Pulsecounter glitch filter config failed"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; @@ -102,7 +102,7 @@ bool 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)) { - LOGGER.error("Pulsecounter channel config failed"); + LOG_E(TAG, "Pulsecounter channel config failed"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; @@ -111,7 +111,7 @@ bool TpagerEncoder::initEncoder() { // 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)) { - LOGGER.error("Pulsecounter edge action config failed"); + LOG_E(TAG, "Pulsecounter edge action config failed"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; @@ -120,7 +120,7 @@ bool TpagerEncoder::initEncoder() { // 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)) { - LOGGER.error("Pulsecounter level action config failed"); + LOG_E(TAG, "Pulsecounter level action config failed"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; @@ -128,28 +128,28 @@ bool TpagerEncoder::initEncoder() { if ((pcnt_unit_add_watch_point(encPcntUnit, LOW_LIMIT) != ESP_OK) || (pcnt_unit_add_watch_point(encPcntUnit, HIGH_LIMIT) != ESP_OK)) { - LOGGER.error("Pulsecounter watch point config failed"); + LOG_E(TAG, "Pulsecounter watch point config failed"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; } if (pcnt_unit_enable(encPcntUnit) != ESP_OK) { - LOGGER.error("Pulsecounter could not be enabled"); + LOG_E(TAG, "Pulsecounter could not be enabled"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; } if (pcnt_unit_clear_count(encPcntUnit) != ESP_OK) { - LOGGER.error("Pulsecounter could not be cleared"); + LOG_E(TAG, "Pulsecounter could not be cleared"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; } if (pcnt_unit_start(encPcntUnit) != ESP_OK) { - LOGGER.error("Pulsecounter could not be started"); + LOG_E(TAG, "Pulsecounter could not be started"); pcnt_del_unit(encPcntUnit); encPcntUnit = nullptr; return false; @@ -168,16 +168,16 @@ bool TpagerEncoder::deinitEncoder() { assert(encPcntUnit != nullptr); if (pcnt_unit_stop(encPcntUnit) != ESP_OK) { - LOGGER.warn("Failed to stop encoder"); + LOG_W(TAG, "Failed to stop encoder"); } if (pcnt_del_unit(encPcntUnit) != ESP_OK) { - LOGGER.warn("Failed to delete encoder"); + LOG_W(TAG, "Failed to delete encoder"); encPcntUnit = nullptr; return false; } - LOGGER.info("Deinitialized"); + LOG_I(TAG, "Deinitialized"); return true; } @@ -206,7 +206,7 @@ bool TpagerEncoder::stopLvgl() { if (encPcntUnit != nullptr && !deinitEncoder()) { // We're not returning false as LVGL as effectively deinitialized - LOGGER.warn("Deinitialization failed"); + LOG_W(TAG, "Deinitialization failed"); } return true; diff --git a/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp b/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp index 902da0f27..5bcbbc7c9 100644 --- a/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp +++ b/Devices/lilygo-tlora-pager/Source/devices/TpagerKeyboard.cpp @@ -1,11 +1,10 @@ #include "TpagerKeyboard.h" -#include - #include #include +#include -static const auto LOGGER = tt::Logger("TpagerKeyboard"); +constexpr auto* TAG = "TpagerKeyboard"; constexpr auto BACKLIGHT = GPIO_NUM_46; @@ -173,7 +172,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti }; if (ledc_timer_config(&ledc_timer) != ESP_OK) { - LOGGER.error("Backlight timer config failed"); + LOG_E(TAG, "Backlight timer config failed"); return false; } @@ -192,7 +191,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti }; if (ledc_channel_config(&ledc_channel) != ESP_OK) { - LOGGER.error("Backlight channel config failed"); + LOG_E(TAG, "Backlight channel config failed"); } return true; @@ -200,7 +199,7 @@ bool TpagerKeyboard::initBacklight(gpio_num_t pin, uint32_t frequencyHz, ledc_ti bool TpagerKeyboard::setBacklightDuty(uint8_t duty) { if (!backlightOkay) { - LOGGER.error("Backlight not ready"); + LOG_E(TAG, "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 919bff7b6..e82e1c697 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 -static const auto LOGGER = tt::Logger("TpagerPower"); +constexpr auto* TAG = "TpagerPower"; TpagerPower::~TpagerPower() {} @@ -66,7 +66,7 @@ void TpagerPower::powerOff() { }); if (device == nullptr) { - LOGGER.error("BQ25896 not found"); + LOG_E(TAG, "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 a607f0102..ab8c6df74 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 -static const auto LOGGER = tt::Logger("CardputerPower"); +constexpr auto* TAG = "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) { - LOGGER.warn("Calibration scheme not supported, skip software calibration"); + LOG_W(TAG, "Calibration scheme not supported, skip software calibration"); } else if (efuse_read_result == ESP_ERR_INVALID_VERSION) { - LOGGER.warn("eFuse not burnt, skip software calibration"); + LOG_W(TAG, "eFuse not burnt, skip software calibration"); } else if (efuse_read_result == ESP_OK) { calibrated = true; - LOGGER.info("Calibration success"); + LOG_I(TAG, "Calibration success"); esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, static_cast(ADC_WIDTH_BIT_DEFAULT), 0, &adcCharacteristics); } else { - LOGGER.warn("eFuse read failed, skipping calibration"); + LOG_W(TAG, "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); - LOGGER.debug("Raw data: {}", adc_raw); + LOG_D(TAG, "Raw data: %d", adc_raw); float voltage; if (calibrated) { voltage = esp_adc_cal_raw_to_voltage(adc_raw, &adcCharacteristics); - LOGGER.debug("Calibrated data: {} mV", voltage); + LOG_D(TAG, "Calibrated data: %f 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) { - LOGGER.error("ADC1 config width failed"); + LOG_E(TAG, "ADC1 config width failed"); return false; } if (adc1_config_channel_atten(ADC1_CHANNEL_9, ADC_ATTEN_DB_11) != ESP_OK) { - LOGGER.error("ADC1 config attenuation failed"); + LOG_E(TAG, "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 c0466db10..8f9b45659 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 -static const auto LOGGER = tt::Logger("Keyboard"); +constexpr auto* TAG = "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) { - LOGGER.info("del"); + LOG_I(TAG, "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 a607f0102..ab8c6df74 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 -static const auto LOGGER = tt::Logger("CardputerPower"); +constexpr auto* TAG = "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) { - LOGGER.warn("Calibration scheme not supported, skip software calibration"); + LOG_W(TAG, "Calibration scheme not supported, skip software calibration"); } else if (efuse_read_result == ESP_ERR_INVALID_VERSION) { - LOGGER.warn("eFuse not burnt, skip software calibration"); + LOG_W(TAG, "eFuse not burnt, skip software calibration"); } else if (efuse_read_result == ESP_OK) { calibrated = true; - LOGGER.info("Calibration success"); + LOG_I(TAG, "Calibration success"); esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, static_cast(ADC_WIDTH_BIT_DEFAULT), 0, &adcCharacteristics); } else { - LOGGER.warn("eFuse read failed, skipping calibration"); + LOG_W(TAG, "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); - LOGGER.debug("Raw data: {}", adc_raw); + LOG_D(TAG, "Raw data: %d", adc_raw); float voltage; if (calibrated) { voltage = esp_adc_cal_raw_to_voltage(adc_raw, &adcCharacteristics); - LOGGER.debug("Calibrated data: {} mV", voltage); + LOG_D(TAG, "Calibrated data: %f 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) { - LOGGER.error("ADC1 config width failed"); + LOG_E(TAG, "ADC1 config width failed"); return false; } if (adc1_config_channel_atten(ADC1_CHANNEL_9, ADC_ATTEN_DB_11) != ESP_OK) { - LOGGER.error("ADC1 config attenuation failed"); + LOG_E(TAG, "ADC1 config attenuation failed"); return false; } diff --git a/Devices/m5stack-cores3/Source/InitBoot.cpp b/Devices/m5stack-cores3/Source/InitBoot.cpp index 3699455a5..8c9e6a44c 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 -static const auto LOGGER = tt::Logger("CoreS3"); +constexpr auto* TAG = "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() { - LOGGER.info("AW9523 init"); + LOG_I(TAG, "AW9523 init"); /** * P0 pins: @@ -58,33 +58,33 @@ bool initGpioExpander() { /* AW9523 P0 is in push-pull mode */ if (!aw9523->writeCTL(0x10)) { - LOGGER.error("AW9523: Failed to set CTL"); + LOG_E(TAG, "AW9523: Failed to set CTL"); return false; } if (!aw9523->writeP0(p0_state)) { - LOGGER.error("AW9523: Failed to set P0"); + LOG_E(TAG, "AW9523: Failed to set P0"); return false; } if (!aw9523->writeP1(p1_state)) { - LOGGER.error("AW9523: Failed to set P1"); + LOG_E(TAG, "AW9523: Failed to set P1"); return false; } if (axp2101->isVBus()) { float voltage = 0.0f; axp2101->getVBusVoltage(voltage); - LOGGER.info("AXP2101: VBus at {:.2f}", voltage); + LOG_I(TAG, "AXP2101: VBus at %.2f", voltage); } else { - LOGGER.warn("AXP2101: VBus disabled"); + LOG_W(TAG, "AXP2101: VBus disabled"); } return true; } bool initPowerControl() { - LOGGER.info("Init power control (AXP2101)"); + LOG_I(TAG, "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))) { - LOGGER.info("AXP2101 initialized with {} registers", sizeof(reg_data_array) / 2); + LOG_I(TAG, "AXP2101 initialized with %d registers", (int)(sizeof(reg_data_array) / 2)); return true; } else { - LOGGER.error("AXP2101: Failed to set registers"); + LOG_E(TAG, "AXP2101: Failed to set registers"); return false; } } bool initBoot() { - LOGGER.info("initBoot()"); + LOG_I(TAG, "initBoot()"); auto controller = device_find_by_name("i2c_internal"); axp2101 = std::make_shared(controller); diff --git a/Devices/m5stack-cores3/Source/devices/Display.cpp b/Devices/m5stack-cores3/Source/devices/Display.cpp index ba6087394..ac868a841 100644 --- a/Devices/m5stack-cores3/Source/devices/Display.cpp +++ b/Devices/m5stack-cores3/Source/devices/Display.cpp @@ -3,11 +3,11 @@ #include #include #include -#include #include +#include -static const auto LOGGER = tt::Logger("CoreS3Display"); +constexpr auto* TAG = "CoreS3Display"; static void setBacklightDuty(uint8_t backlightDuty) { const uint8_t voltage = 20 + ((8 * backlightDuty) / 255); // [0b00000, 0b11100] - under 20 is too dark @@ -15,7 +15,7 @@ static void setBacklightDuty(uint8_t backlightDuty) { auto controller = device_find_by_name("i2c_internal"); check(controller); if (i2c_controller_write_register(controller, AXP2101_ADDRESS, 0x99, &voltage, 1, 1000) != ERROR_NONE) { // Sets DLD01 - LOGGER.error("Failed to set display backlight voltage"); + LOG_E(TAG, "Failed to set display backlight voltage"); } } diff --git a/Devices/m5stack-papers3/Source/Init.cpp b/Devices/m5stack-papers3/Source/Init.cpp index 2b6c6c891..995b53927 100644 --- a/Devices/m5stack-papers3/Source/Init.cpp +++ b/Devices/m5stack-papers3/Source/Init.cpp @@ -1,7 +1,7 @@ -#include #include +#include -static const auto LOGGER = tt::Logger("Paper S3"); +constexpr auto* TAG = "Paper S3"; constexpr gpio_num_t VBAT_PIN = GPIO_NUM_3; constexpr gpio_num_t CHARGE_STATUS_PIN = GPIO_NUM_4; @@ -9,38 +9,38 @@ constexpr gpio_num_t USB_DETECT_PIN = GPIO_NUM_5; static bool powerOn() { if (gpio_reset_pin(CHARGE_STATUS_PIN) != ESP_OK) { - LOGGER.error("Failed to reset CHARGE_STATUS_PIN"); + LOG_E(TAG, "Failed to reset CHARGE_STATUS_PIN"); return false; } if (gpio_set_direction(CHARGE_STATUS_PIN, GPIO_MODE_INPUT) != ESP_OK) { - LOGGER.error("Failed to set direction for CHARGE_STATUS_PIN"); + LOG_E(TAG, "Failed to set direction for CHARGE_STATUS_PIN"); return false; } if (gpio_reset_pin(USB_DETECT_PIN) != ESP_OK) { - LOGGER.error("Failed to reset USB_DETECT_PIN"); + LOG_E(TAG, "Failed to reset USB_DETECT_PIN"); return false; } if (gpio_set_direction(USB_DETECT_PIN, GPIO_MODE_INPUT) != ESP_OK) { - LOGGER.error("Failed to set direction for USB_DETECT_PIN"); + LOG_E(TAG, "Failed to set direction for USB_DETECT_PIN"); return false; } // VBAT_PIN is used as ADC input; only reset it here to clear any previous // configuration. The ADC driver (ChargeFromAdcVoltage) configures it for ADC use. if (gpio_reset_pin(VBAT_PIN) != ESP_OK) { - LOGGER.error("Failed to reset VBAT_PIN"); + LOG_E(TAG, "Failed to reset VBAT_PIN"); return false; } return true; } bool initBoot() { - LOGGER.info("Power on"); + LOG_I(TAG, "Power on"); if (!powerOn()) { - LOGGER.error("Power on failed"); + LOG_E(TAG, "Power on failed"); return false; } diff --git a/Devices/m5stack-stackchan/Source/devices/Display.cpp b/Devices/m5stack-stackchan/Source/devices/Display.cpp index 7eb756303..b06ee5fd2 100644 --- a/Devices/m5stack-stackchan/Source/devices/Display.cpp +++ b/Devices/m5stack-stackchan/Source/devices/Display.cpp @@ -3,18 +3,18 @@ #include #include #include -#include #include +#include -static const auto LOGGER = tt::Logger("StackChanDisplay"); +constexpr auto* TAG = "StackChanDisplay"; static void setBacklightDuty(uint8_t backlightDuty) { const uint8_t voltage = 20 + ((8 * backlightDuty) / 255); // [0b00000, 0b11100] auto controller = device_find_by_name("i2c_internal"); check(controller); if (i2c_controller_write_register(controller, AXP2101_ADDRESS, 0x99, &voltage, 1, 1000) != ERROR_NONE) { // Sets DLD01 - LOGGER.error("Failed to set display backlight voltage"); + LOG_E(TAG, "Failed to set display backlight voltage"); } } diff --git a/Devices/m5stack-tab5/Source/devices/Detect.cpp b/Devices/m5stack-tab5/Source/devices/Detect.cpp index e70f2663b..037036576 100644 --- a/Devices/m5stack-tab5/Source/devices/Detect.cpp +++ b/Devices/m5stack-tab5/Source/devices/Detect.cpp @@ -1,14 +1,14 @@ #include "Detect.h" -#include #include #include +#include #include #include #include #include -static const auto LOGGER = tt::Logger("Tab5Detect"); +constexpr auto* TAG = "Tab5Detect"; Tab5Variant detectVariant() { // Allow time for touch IC to fully boot after expander reset in initBoot(). @@ -27,19 +27,19 @@ Tab5Variant detectVariant() { // It may also appear at 0x14 (backup) if the pin happened to be driven low if (i2c_controller_has_device_at_address(i2c0, ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS, PROBE_TIMEOUT) == ERROR_NONE || i2c_controller_has_device_at_address(i2c0, ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS_BACKUP, PROBE_TIMEOUT) == ERROR_NONE) { - LOGGER.info("Detected GT911 touch — using ILI9881C display"); + LOG_I(TAG, "Detected GT911 touch — using ILI9881C display"); return Tab5Variant::Ili9881c_Gt911; } // Probe for ST7123 touch (new variant) if (i2c_controller_has_device_at_address(i2c0, ESP_LCD_TOUCH_IO_I2C_ST7123_ADDRESS, PROBE_TIMEOUT) == ERROR_NONE) { - LOGGER.info("Detected ST7123 touch — using ST7123 display"); + LOG_I(TAG, "Detected ST7123 touch — using ST7123 display"); return Tab5Variant::St7123; } vTaskDelay(pdMS_TO_TICKS(100)); } - LOGGER.warn("No known touch controller detected, defaulting to ST7123"); + LOG_W(TAG, "No known touch controller detected, defaulting to ST7123"); return Tab5Variant::St7123; } diff --git a/Devices/m5stack-tab5/Source/devices/Display.cpp b/Devices/m5stack-tab5/Source/devices/Display.cpp index f749f3e65..a2d8ef50a 100644 --- a/Devices/m5stack-tab5/Source/devices/Display.cpp +++ b/Devices/m5stack-tab5/Source/devices/Display.cpp @@ -6,14 +6,14 @@ #include #include -#include #include #include #include +#include #include #include -static const auto LOGGER = tt::Logger("Tab5Display"); +constexpr auto* TAG = "Tab5Display"; // LCD reset is wired to the PI4IOE5V6408 IO expander (io_expander0, bit 4), pulsed in // Configuration.cpp's initExpander0() before display creation - not a direct SoC GPIO. @@ -55,7 +55,7 @@ static std::shared_ptr createSt7123Touch() { std::shared_ptr createDisplay() { // Initialize PWM backlight if (!driver::pwmbacklight::init(LCD_PIN_BACKLIGHT, 5000, LEDC_TIMER_1, LEDC_CHANNEL_0)) { - LOGGER.warn("Failed to initialize backlight"); + LOG_W(TAG, "Failed to initialize backlight"); } Tab5Variant variant = detectVariant(); diff --git a/Devices/m5stack-tab5/Source/devices/Ili9881cDisplay.cpp b/Devices/m5stack-tab5/Source/devices/Ili9881cDisplay.cpp index 9c9d464bd..aec496bd2 100644 --- a/Devices/m5stack-tab5/Source/devices/Ili9881cDisplay.cpp +++ b/Devices/m5stack-tab5/Source/devices/Ili9881cDisplay.cpp @@ -1,10 +1,10 @@ #include "Ili9881cDisplay.h" #include "ili9881_init_data.h" -#include #include +#include -static const auto LOGGER = tt::Logger("ILI9881C"); +constexpr auto* TAG = "ILI9881C"; Ili9881cDisplay::~Ili9881cDisplay() { // TODO: This should happen during ::stop(), but this isn't currently exposed @@ -30,11 +30,11 @@ bool Ili9881cDisplay::createMipiDsiBus() { }; if (esp_ldo_acquire_channel(&ldo_mipi_phy_config, &ldoChannel) != ESP_OK) { - LOGGER.error("Failed to acquire LDO channel for MIPI DSI PHY"); + LOG_E(TAG, "Failed to acquire LDO channel for MIPI DSI PHY"); return false; } - - LOGGER.info("Powered on"); + + LOG_I(TAG, "Powered on"); // Create bus // TODO: use MIPI_DSI_PHY_CLK_SRC_DEFAULT() in future ESP-IDF 6.0.0 update with esp_lcd_jd9165 library version 2.x @@ -46,13 +46,13 @@ bool Ili9881cDisplay::createMipiDsiBus() { }; if (esp_lcd_new_dsi_bus(&bus_config, &mipiDsiBus) != ESP_OK) { - LOGGER.error("Failed to create bus"); + LOG_E(TAG, "Failed to create bus"); esp_ldo_release_channel(ldoChannel); ldoChannel = nullptr; return false; } - LOGGER.info("Bus created"); + LOG_I(TAG, "Bus created"); return true; } @@ -68,7 +68,7 @@ bool Ili9881cDisplay::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { esp_lcd_dbi_io_config_t dbi_config = ILI9881C_PANEL_IO_DBI_CONFIG(); if (esp_lcd_new_panel_io_dbi(mipiDsiBus, &dbi_config, &ioHandle) != ESP_OK) { - LOGGER.error("Failed to create panel IO"); + LOG_E(TAG, "Failed to create panel IO"); esp_lcd_del_dsi_bus(mipiDsiBus); mipiDsiBus = nullptr; esp_ldo_release_channel(ldoChannel); @@ -135,11 +135,11 @@ bool Ili9881cDisplay::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, cons mutable_panel_config.vendor_config = &vendor_config; if (esp_lcd_new_panel_ili9881c(ioHandle, &mutable_panel_config, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } - LOGGER.info("Panel created successfully"); + LOG_I(TAG, "Panel created successfully"); // Defer reset/init to base class applyConfiguration to avoid double initialization return true; } diff --git a/Devices/m5stack-tab5/Source/devices/St7123Display.cpp b/Devices/m5stack-tab5/Source/devices/St7123Display.cpp index a5d0869f4..0f47e1252 100644 --- a/Devices/m5stack-tab5/Source/devices/St7123Display.cpp +++ b/Devices/m5stack-tab5/Source/devices/St7123Display.cpp @@ -1,10 +1,10 @@ #include "St7123Display.h" #include "st7123_init_data.h" -#include #include +#include -static const auto LOGGER = tt::Logger("St7123"); +constexpr auto* TAG = "St7123"; St7123Display::~St7123Display() { // TODO: This should happen during ::stop(), but this isn't currently exposed @@ -30,11 +30,11 @@ bool St7123Display::createMipiDsiBus() { }; if (esp_ldo_acquire_channel(&ldo_mipi_phy_config, &ldoChannel) != ESP_OK) { - LOGGER.error("Failed to acquire LDO channel for MIPI DSI PHY"); + LOG_E(TAG, "Failed to acquire LDO channel for MIPI DSI PHY"); return false; } - LOGGER.info("Powered on"); + LOG_I(TAG, "Powered on"); const esp_lcd_dsi_bus_config_t bus_config = { .bus_id = 0, @@ -44,13 +44,13 @@ bool St7123Display::createMipiDsiBus() { }; if (esp_lcd_new_dsi_bus(&bus_config, &mipiDsiBus) != ESP_OK) { - LOGGER.error("Failed to create bus"); + LOG_E(TAG, "Failed to create bus"); esp_ldo_release_channel(ldoChannel); ldoChannel = nullptr; return false; } - LOGGER.info("Bus created"); + LOG_I(TAG, "Bus created"); return true; } @@ -69,7 +69,7 @@ bool St7123Display::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { }; if (esp_lcd_new_panel_io_dbi(mipiDsiBus, &dbi_config, &ioHandle) != ESP_OK) { - LOGGER.error("Failed to create panel IO"); + LOG_E(TAG, "Failed to create panel IO"); esp_lcd_del_dsi_bus(mipiDsiBus); mipiDsiBus = nullptr; esp_ldo_release_channel(ldoChannel); @@ -130,11 +130,11 @@ bool St7123Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, const mutable_panel_config.vendor_config = &vendor_config; if (esp_lcd_new_panel_st7123(ioHandle, &mutable_panel_config, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } - LOGGER.info("Panel created successfully"); + LOG_I(TAG, "Panel created successfully"); return true; } diff --git a/Devices/m5stack-tab5/Source/devices/St7123Touch.cpp b/Devices/m5stack-tab5/Source/devices/St7123Touch.cpp index a34dc208c..4492e77c9 100644 --- a/Devices/m5stack-tab5/Source/devices/St7123Touch.cpp +++ b/Devices/m5stack-tab5/Source/devices/St7123Touch.cpp @@ -1,11 +1,11 @@ #include "St7123Touch.h" -#include #include +#include #include #include -static const auto LOGGER = tt::Logger("ST7123Touch"); +constexpr auto* TAG = "ST7123Touch"; bool St7123Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { esp_lcd_panel_io_i2c_config_t io_config = ESP_LCD_TOUCH_IO_I2C_ST7123_CONFIG(); diff --git a/Devices/simulator/Source/Main.cpp b/Devices/simulator/Source/Main.cpp index 94481c1af..464607a29 100644 --- a/Devices/simulator/Source/Main.cpp +++ b/Devices/simulator/Source/Main.cpp @@ -5,7 +5,9 @@ #include "FreeRTOS.h" #include "task.h" -static const auto LOGGER = tt::Logger("FreeRTOS"); +#include + +constexpr auto* TAG = "FreeRTOS"; namespace simulator { @@ -16,10 +18,10 @@ void setMain(MainFunction newMainFunction) { } static void freertosMainTask(void* parameter) { - LOGGER.info("starting app_main()"); + LOG_I(TAG, "starting app_main()"); assert(simulator::mainFunction); mainFunction(); - LOGGER.info("returned from app_main()"); + LOG_I(TAG, "returned from app_main()"); vTaskDelete(nullptr); } diff --git a/Devices/unphone/Source/InitBoot.cpp b/Devices/unphone/Source/InitBoot.cpp index 4485b13ca..188803ab4 100644 --- a/Devices/unphone/Source/InitBoot.cpp +++ b/Devices/unphone/Source/InitBoot.cpp @@ -1,12 +1,12 @@ #include "UnPhoneFeatures.h" #include -#include #include #include #include #include +#include -static const auto LOGGER = tt::Logger("unPhone"); +constexpr auto* TAG = "unPhone"; std::shared_ptr unPhoneFeatures; static std::unique_ptr powerThread; @@ -49,10 +49,10 @@ class DeviceStats { } void printInfo() { - LOGGER.info("Device stats:"); - LOGGER.info(" boot: {}", getValue(bootCountKey)); - LOGGER.info(" power off: {}", getValue(powerOffCountKey)); - LOGGER.info(" power sleep: {}", getValue(powerSleepKey)); + LOG_I(TAG, "Device stats:"); + LOG_I(TAG, " boot: %d", (int)getValue(bootCountKey)); + LOG_I(TAG, " power off: %d", (int)getValue(powerOffCountKey)); + LOG_I(TAG, " power sleep: %d", (int)getValue(powerSleepKey)); } }; @@ -92,11 +92,11 @@ static void updatePowerSwitch() { if (!unPhoneFeatures->isPowerSwitchOn()) { if (last_state != PowerState::Off) { last_state = PowerState::Off; - LOGGER.warn("Power off"); + LOG_W(TAG, "Power off"); } if (!unPhoneFeatures->isUsbPowerConnected()) { // and usb unplugged we go into shipping mode - LOGGER.warn("Shipping mode until USB connects"); + LOG_W(TAG, "Shipping mode until USB connects"); #if DEBUG_POWER_STATES unPhoneFeatures.setExpanderPower(true); @@ -110,7 +110,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. - LOGGER.warn("Waiting for USB disconnect to power off"); + LOG_W(TAG, "Waiting for USB disconnect to power off"); #if DEBUG_POWER_STATES powerInfoBuzz(2); @@ -129,7 +129,7 @@ static void updatePowerSwitch() { } else { if (last_state != PowerState::On) { last_state = PowerState::On; - LOGGER.warn("Power on"); + LOG_W(TAG, "Power on"); #if DEBUG_POWER_STATES powerInfoBuzz(1); @@ -166,7 +166,7 @@ static bool unPhonePowerOn() { unPhoneFeatures = std::make_shared(bq24295); if (!unPhoneFeatures->init()) { - LOGGER.error("UnPhoneFeatures init failed"); + LOG_E(TAG, "UnPhoneFeatures init failed"); return false; } @@ -186,10 +186,10 @@ static bool unPhonePowerOn() { } bool initBoot() { - LOGGER.info(LOG_MESSAGE_POWER_ON_START); + LOG_I(TAG, LOG_MESSAGE_POWER_ON_START); if (!unPhonePowerOn()) { - LOGGER.error(LOG_MESSAGE_POWER_ON_FAILED); + LOG_E(TAG, LOG_MESSAGE_POWER_ON_FAILED); return false; } diff --git a/Devices/unphone/Source/UnPhoneFeatures.cpp b/Devices/unphone/Source/UnPhoneFeatures.cpp index bb579efc9..14e2a2f10 100644 --- a/Devices/unphone/Source/UnPhoneFeatures.cpp +++ b/Devices/unphone/Source/UnPhoneFeatures.cpp @@ -1,6 +1,5 @@ #include "UnPhoneFeatures.h" -#include #include #include @@ -8,8 +7,9 @@ #include #include #include +#include -static const auto LOGGER = tt::Logger("unPhoneFeatures"); +constexpr auto* TAG = "unPhoneFeatures"; namespace pin { static const gpio_num_t BUTTON1 = GPIO_NUM_45; // left button @@ -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 - LOGGER.info("Pressed button {}", pinNumber); + LOG_I(TAG, "Pressed button %d", pinNumber); if (pinNumber == pin::BUTTON1) { tt::app::stop(); } @@ -75,7 +75,7 @@ bool UnPhoneFeatures::initPowerSwitch() { }; if (gpio_config(&config) != ESP_OK) { - LOGGER.error("Power pin init failed"); + LOG_E(TAG, "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 { - LOGGER.error("Failed to set RTC for power switch"); + LOG_E(TAG, "Failed to set RTC for power switch"); return false; } } bool UnPhoneFeatures::initNavButtons() { if (!initGpioExpander()) { - LOGGER.error("GPIO expander init failed"); + LOG_E(TAG, "GPIO expander init failed"); return false; } @@ -125,7 +125,7 @@ bool UnPhoneFeatures::initNavButtons() { }; if (gpio_config(&config) != ESP_OK) { - LOGGER.error("Nav button pin init failed"); + LOG_E(TAG, "Nav button pin init failed"); return false; } @@ -135,7 +135,7 @@ bool UnPhoneFeatures::initNavButtons() { 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 ) { - LOGGER.error("Nav buttons ISR init failed"); + LOG_E(TAG, "Nav buttons ISR init failed"); return false; } @@ -156,7 +156,7 @@ bool UnPhoneFeatures::initOutputPins() { }; if (gpio_config(&config) != ESP_OK) { - LOGGER.error("Output pin init failed"); + LOG_E(TAG, "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) { - LOGGER.error("IO expander init failed"); + LOG_E(TAG, "IO expander init failed"); return false; } assert(ioExpander != nullptr); @@ -201,25 +201,25 @@ bool UnPhoneFeatures::initGpioExpander() { } bool UnPhoneFeatures::init() { - LOGGER.info("init"); + LOG_I(TAG, "init"); if (!initGpioExpander()) { - LOGGER.error("GPIO expander init failed"); + LOG_E(TAG, "GPIO expander init failed"); return false; } if (!initNavButtons()) { - LOGGER.error("Input pin init failed"); + LOG_E(TAG, "Input pin init failed"); return false; } if (!initOutputPins()) { - LOGGER.error("Output pin init failed"); + LOG_E(TAG, "Output pin init failed"); return false; } if (!initPowerSwitch()) { - LOGGER.error("Power button init failed"); + LOG_E(TAG, "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"; - LOGGER.info("Backlight: {}", backlight_power_state); + LOG_I(TAG, "Backlight: %s", 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) { - LOGGER.warn("setShipping: on"); + LOG_W(TAG, "setShipping: on"); batteryManagement->setWatchDogTimer(Bq24295::WatchDogTimer::Disabled); batteryManagement->setBatFetOn(false); } else { - LOGGER.warn("setShipping: off"); + LOG_W(TAG, "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 80a2f7f6b..db462e6a9 100644 --- a/Devices/unphone/Source/devices/Hx8357Display.cpp +++ b/Devices/unphone/Source/devices/Hx8357Display.cpp @@ -2,19 +2,19 @@ #include "Touch.h" #include -#include #include #include +#include -static const auto LOGGER = tt::Logger("Hx8357Display"); +constexpr auto* TAG = "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() { - LOGGER.info("start"); + LOG_I(TAG, "start"); disp_spi_add_device(SPI2_HOST); @@ -27,16 +27,16 @@ bool Hx8357Display::start() { } bool Hx8357Display::stop() { - LOGGER.info("stop"); + LOG_I(TAG, "stop"); disp_spi_remove_device(); return true; } bool Hx8357Display::startLvgl() { - LOGGER.info("startLvgl"); + LOG_I(TAG, "startLvgl"); if (lvglDisplay != nullptr) { - LOGGER.warn("LVGL was already started"); + LOG_W(TAG, "LVGL was already started"); return false; } @@ -59,7 +59,7 @@ bool Hx8357Display::startLvgl() { lv_display_set_flush_cb(lvglDisplay, hx8357_flush); if (lvglDisplay == nullptr) { - LOGGER.info("Failed"); + LOG_I(TAG, "Failed"); return false; } @@ -74,10 +74,10 @@ bool Hx8357Display::startLvgl() { } bool Hx8357Display::stopLvgl() { - LOGGER.info("stopLvgl"); + LOG_I(TAG, "stopLvgl"); if (lvglDisplay == nullptr) { - LOGGER.warn("LVGL was already stopped"); + LOG_W(TAG, "LVGL was already stopped"); return false; } @@ -86,7 +86,7 @@ bool Hx8357Display::stopLvgl() { auto touch_device = getTouchDevice(); if (touch_device != nullptr && touch_device->getLvglIndev() != nullptr) { - LOGGER.info("Stopping touch device"); + LOG_I(TAG, "Stopping touch device"); touch_device->stopLvgl(); } @@ -102,7 +102,7 @@ bool Hx8357Display::stopLvgl() { std::shared_ptr Hx8357Display::getTouchDevice() { if (touchDevice == nullptr) { touchDevice = std::reinterpret_pointer_cast(createTouch()); - LOGGER.info("Created touch device"); + LOG_I(TAG, "Created touch device"); } return touchDevice; diff --git a/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp b/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp index d12fe4e7c..83f92a60b 100644 --- a/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp +++ b/Devices/waveshare-s3-touch-lcd-147/Source/Init.cpp @@ -1,5 +1,6 @@ #include #include +#include #include constexpr auto* TAG = "Waveshare"; @@ -38,7 +39,7 @@ void initBacklight() { } bool initBoot() { - ESP_LOGI(TAG, LOG_MESSAGE_POWER_ON_START); + LOG_I(TAG, LOG_MESSAGE_POWER_ON_START); initBacklight(); return true; } 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 c7466ba8c..78b550d54 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,11 @@ #include "Jd9853Display.h" -#include - #include #include #include +#include -static const auto LOGGER = tt::Logger("JD9853"); +constexpr auto* TAG = "JD9853"; bool Jd9853Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { const esp_lcd_panel_io_spi_config_t panel_io_config = { @@ -54,42 +53,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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY"); + LOG_E(TAG, "Failed to swap XY"); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } if (esp_lcd_panel_set_gap(panelHandle, 34, 0) != ESP_OK) { - LOGGER.error("Failed to set panel gap"); + LOG_E(TAG, "Failed to set panel gap"); return false; } @@ -157,6 +156,6 @@ void Jd9853Display::setGammaCurve(uint8_t index) { }; if (esp_lcd_panel_io_tx_param(getIoHandle() , LCD_CMD_GAMSET, param, 1) != ESP_OK) { - LOGGER.error("Failed to set gamma"); + LOG_E(TAG, "Failed to set gamma"); } } diff --git a/Drivers/BQ24295/Source/Bq24295.cpp b/Drivers/BQ24295/Source/Bq24295.cpp index 07f3346f7..730725e01 100644 --- a/Drivers/BQ24295/Source/Bq24295.cpp +++ b/Drivers/BQ24295/Source/Bq24295.cpp @@ -1,7 +1,7 @@ #include "Bq24295.h" -#include +#include -static const auto LOGGER = tt::Logger("BQ24295"); +constexpr auto* TAG = "BQ24295"; /** Reference: * https://www.ti.com/lit/ds/symlink/bq24295.pdf @@ -50,7 +50,7 @@ bool Bq24295::setWatchDogTimer(WatchDogTimer in) const { uint8_t bits_to_set = 0b00110000 & static_cast(in); uint8_t value_cleared = value & 0b11001111; uint8_t to_set = bits_to_set | value_cleared; - LOGGER.info("WatchDogTimer: {:02x} -> {:02x}", value, to_set); + LOG_I(TAG, "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)) { - LOGGER.info("Version {}, status {:02x}, charge termination {:02x}", version, status, charge_termination); + LOG_I(TAG, "Version %d, status %02X, charge termination %02X", version, status, charge_termination); } else { - LOGGER.error("Failed to retrieve version and/or status"); + LOG_E(TAG, "Failed to retrieve version and/or status"); } } diff --git a/Drivers/BQ25896/Source/Bq25896.cpp b/Drivers/BQ25896/Source/Bq25896.cpp index e860e10d3..c15169e97 100644 --- a/Drivers/BQ25896/Source/Bq25896.cpp +++ b/Drivers/BQ25896/Source/Bq25896.cpp @@ -1,15 +1,15 @@ #include "Bq25896.h" -#include +#include -static const auto LOGGER = tt::Logger("BQ25896"); +constexpr auto* TAG = "BQ25896"; void Bq25896::powerOff() { - LOGGER.info("Power off"); + LOG_I(TAG, "Power off"); bitOn(0x09, BIT(5)); } void Bq25896::powerOn() { - LOGGER.info("Power on"); + LOG_I(TAG, "Power on"); bitOff(0x09, BIT(5)); } diff --git a/Drivers/BQ27220/Source/Bq27220.cpp b/Drivers/BQ27220/Source/Bq27220.cpp index b2d086979..8a40caab4 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" -static const auto LOGGER = tt::Logger("BQ27220"); +constexpr auto* TAG = "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)) { - LOGGER.error("Failed to set design capacity!"); + LOG_E(TAG, "Failed to set design capacity!"); return false; } vTaskDelay(10 / portTICK_PERIOD_MS); // Set full charge capacity if (!writeConfig16(registers::ROM_FULL_CHARGE_CAPACITY, fullChargeCapacity)) { - LOGGER.error("Failed to set full charge capacity!"); + LOG_E(TAG, "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); } - LOGGER.error("Subcommand 0x{:04X} failed!", subCmd); + LOG_E(TAG, "Subcommand 0x%04X failed!", subCmd); return false; } @@ -298,28 +298,28 @@ bool Bq27220::configPreamble(bool &isSealed) { // Check access settings if(!getOperationStatus(status)) { - LOGGER.error("Cannot read initial operation status!"); + LOG_E(TAG, "Cannot read initial operation status!"); return false; } if (status.reg.SEC == OperationStatusSecSealed) { isSealed = true; if (!unsealDevice()) { - LOGGER.error("Unsealing device failure!"); + LOG_E(TAG, "Unsealing device failure!"); return false; } } if (status.reg.SEC != OperationStatusSecFull) { if (!unsealFullAccess()) { - LOGGER.error("Unsealing full access failure!"); + LOG_E(TAG, "Unsealing full access failure!"); return false; } } // Send ENTER_CFG_UPDATE command (0x0090) if (!sendSubCommand(registers::SUBCMD_ENTER_CFG_UPDATE)) { - LOGGER.error("Config Update Subcommand failure!"); + LOG_E(TAG, "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) { - LOGGER.error("Update Mode timeout, maybe the access key for full permissions is invalid!"); + LOG_E(TAG, "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) { - LOGGER.error("Timed out waiting to exit update mode."); + LOG_E(TAG, "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) { - LOGGER.debug("Restore Safe Mode!"); + LOG_D(TAG, "Restore Safe Mode!"); exitSealMode(); } return true; diff --git a/Drivers/ButtonControl/Source/ButtonControl.cpp b/Drivers/ButtonControl/Source/ButtonControl.cpp index d9f4b558f..02a69635b 100644 --- a/Drivers/ButtonControl/Source/ButtonControl.cpp +++ b/Drivers/ButtonControl/Source/ButtonControl.cpp @@ -1,11 +1,11 @@ #include "ButtonControl.h" #include -#include +#include #include -static const auto LOGGER = tt::Logger("ButtonControl"); +constexpr auto* TAG = "ButtonControl"; ButtonControl::ButtonControl(const std::vector& pinConfigurations) : buttonQueue(20, sizeof(ButtonEvent)), @@ -34,7 +34,7 @@ ButtonControl::ButtonControl(const std::vector& pinConfigurati }; esp_err_t err = gpio_config(&io_conf); if (err != ESP_OK) { - LOGGER.error("Failed to configure GPIO {}: {}", static_cast(pin), esp_err_to_name(err)); + LOG_E(TAG, "Failed to configure GPIO %d: %s", static_cast(pin), esp_err_to_name(err)); continue; } @@ -103,10 +103,10 @@ void ButtonControl::updatePin(std::vector::const_reference con if (state.pressState) { auto time_passed = now - state.pressStartTime; if (time_passed < 500) { - LOGGER.info("Short press ({}ms)", time_passed); + LOG_I(TAG, "Short press (%dms)", (int)time_passed); state.triggerShortPress = true; } else { - LOGGER.info("Long press ({}ms)", time_passed); + LOG_I(TAG, "Long press (%dms)", (int)time_passed); state.triggerLongPress = true; } state.pressState = false; @@ -131,7 +131,7 @@ void ButtonControl::driverThreadMain() { if (event.pin == GPIO_NUM_NC) { break; // shutdown sentinel } - LOGGER.info("Pin {} {}", static_cast(event.pin), event.pressed ? "down" : "up"); + LOG_I(TAG, "Pin %d %s", static_cast(event.pin), event.pressed ? "down" : "up"); if (mutex.lock(portMAX_DELAY)) { // Update ALL PinConfiguration entries that share this physical pin. for (size_t i = 0; i < pinConfigurations.size(); i++) { @@ -145,11 +145,11 @@ void ButtonControl::driverThreadMain() { } bool ButtonControl::startThread() { - LOGGER.info("Start"); + LOG_I(TAG, "Start"); esp_err_t err = gpio_install_isr_service(ESP_INTR_FLAG_IRAM); if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) { - LOGGER.error("Failed to install GPIO ISR service: {}", esp_err_to_name(err)); + LOG_E(TAG, "Failed to install GPIO ISR service: %s", esp_err_to_name(err)); return false; } @@ -159,7 +159,7 @@ bool ButtonControl::startThread() { for (auto& arg : isrArgs) { err = gpio_isr_handler_add(arg.pin, gpioIsrHandler, &arg); if (err != ESP_OK) { - LOGGER.error("Failed to add ISR for GPIO {}: {}", static_cast(arg.pin), esp_err_to_name(err)); + LOG_E(TAG, "Failed to add ISR for GPIO %d: %s", static_cast(arg.pin), esp_err_to_name(err)); for (int i = 0; i < handlersAdded; i++) { gpio_isr_handler_remove(isrArgs[i].pin); } @@ -178,7 +178,7 @@ bool ButtonControl::startThread() { } void ButtonControl::stopThread() { - LOGGER.info("Stop"); + LOG_I(TAG, "Stop"); for (const auto& arg : isrArgs) { gpio_isr_handler_remove(arg.pin); diff --git a/Drivers/DRV2605/Source/Drv2605.cpp b/Drivers/DRV2605/Source/Drv2605.cpp index 596f1a41b..556e2fafb 100644 --- a/Drivers/DRV2605/Source/Drv2605.cpp +++ b/Drivers/DRV2605/Source/Drv2605.cpp @@ -1,9 +1,9 @@ #include "Drv2605.h" #include -#include +#include -static const auto LOGGER = tt::Logger("DRV2605"); +constexpr auto* TAG = "DRV2605"; Drv2605::Drv2605(::Device* controller, bool autoPlayStartupBuzz) : I2cDevice(controller, ADDRESS), autoPlayStartupBuzz(autoPlayStartupBuzz) { check(init(), "Initialize DRV2605"); @@ -17,14 +17,14 @@ Drv2605::Drv2605(::Device* controller, bool autoPlayStartupBuzz) : I2cDevice(con bool Drv2605::init() { uint8_t status; if (!readRegister8(static_cast(Register::Status), status)) { - LOGGER.error("Failed to read status"); + LOG_E(TAG, "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) { - LOGGER.error("Unknown chip id {:02x}", static_cast(chip_id)); + LOG_E(TAG, "Unknown chip id %02X", static_cast(chip_id)); return false; } @@ -39,7 +39,7 @@ bool Drv2605::init() { uint8_t feedback; if (!readRegister(Register::Feedback, feedback)) { - LOGGER.error("Failed to read feedback"); + LOG_E(TAG, "Failed to read feedback"); return false; } diff --git a/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp b/Drivers/EspLcdCompat/Source/EspLcdDisplay.cpp index 95fa9d14f..66ffef8de 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 -static const auto LOGGER = tt::Logger("EspLcdDisplay"); +constexpr auto* TAG = "EspLcdDisplay"; EspLcdDisplay::~EspLcdDisplay() { check( @@ -18,12 +18,12 @@ EspLcdDisplay::~EspLcdDisplay() { bool EspLcdDisplay::start() { if (!createIoHandle(ioHandle)) { - LOGGER.error("Failed to create IO handle"); + LOG_E(TAG, "Failed to create IO handle"); return false; } if (!createPanelHandle(ioHandle, panelHandle)) { - LOGGER.error("Failed to create panel handle"); + LOG_E(TAG, "Failed to create panel handle"); esp_lcd_panel_io_del(ioHandle); return false; } @@ -46,7 +46,7 @@ bool EspLcdDisplay::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "DisplayDriver is still in use."); } return true; @@ -56,7 +56,7 @@ bool EspLcdDisplay::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "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 6559939c8..c46a69c96 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 -static const auto LOGGER = tt::Logger("EspLcdDispV2"); +constexpr auto* TAG = "EspLcdDispV2"; inline unsigned int getBufferSize(const std::shared_ptr& configuration) { if (configuration->bufferSize != DEFAULT_BUFFER_SIZE) { @@ -26,17 +26,17 @@ EspLcdDisplayV2::~EspLcdDisplayV2() { bool EspLcdDisplayV2::applyConfiguration() const { if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (configuration->invertColor && esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } @@ -45,28 +45,28 @@ bool EspLcdDisplayV2::applyConfiguration() const { int gap_y = configuration->swapXY ? configuration->gapX : configuration->gapY; bool should_set_gap = gap_x != 0 || gap_y != 0; if (should_set_gap && esp_lcd_panel_set_gap(panelHandle, gap_x, gap_y) != ESP_OK) { - LOGGER.error("Failed to set panel gap"); + LOG_E(TAG, "Failed to set panel gap"); return false; } if (configuration->swapXY && esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } bool should_set_mirror = configuration->mirrorX || configuration->mirrorY; if (should_set_mirror && esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (configuration->invertColor && esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } @@ -75,14 +75,14 @@ bool EspLcdDisplayV2::applyConfiguration() const { bool EspLcdDisplayV2::start() { if (!createIoHandle(ioHandle)) { - LOGGER.error("Failed to create IO handle"); + LOG_E(TAG, "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)) { - LOGGER.error("Failed to create panel handle"); + LOG_E(TAG, "Failed to create panel handle"); esp_lcd_panel_io_del(ioHandle); ioHandle = nullptr; return false; @@ -114,7 +114,7 @@ bool EspLcdDisplayV2::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "DisplayDriver is still in use."); } return true; @@ -124,7 +124,7 @@ bool EspLcdDisplayV2::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "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 ab956a0ba..fbfc98cdb 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdSpiDisplay.cpp @@ -1,12 +1,12 @@ #include "EspLcdSpiDisplay.h" #include -#include +#include -static const auto LOGGER = tt::Logger("EspLcdSpiDisplay"); +constexpr auto* TAG = "EspLcdSpiDisplay"; bool EspLcdSpiDisplay::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - LOGGER.info("createIoHandle"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to set gamma"); + LOG_E(TAG, "Failed to set gamma"); } } diff --git a/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp b/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp index 073bd2f8e..eaa6ba77b 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdTouch.cpp @@ -2,21 +2,21 @@ #include -#include +#include #include -static const auto LOGGER = tt::Logger("EspLcdTouch"); +constexpr auto* TAG = "EspLcdTouch"; bool EspLcdTouch::start() { if (!createIoHandle(ioHandle) != ESP_OK) { - LOGGER.error("Touch IO failed"); + LOG_E(TAG, "Touch IO failed"); return false; } config = createEspLcdTouchConfig(); if (!createTouchHandle(ioHandle, config, touchHandle)) { - LOGGER.error("Driver init failed"); + LOG_E(TAG, "Driver init failed"); esp_lcd_panel_io_del(ioHandle); ioHandle = nullptr; return false; @@ -49,7 +49,7 @@ bool EspLcdTouch::startLvgl(lv_disp_t* display) { } if (touchDriver != nullptr && touchDriver.use_count() > 1) { - LOGGER.warn("TouchDriver is still in use."); + LOG_W(TAG, "TouchDriver is still in use."); } const lvgl_port_touch_cfg_t touch_cfg = { @@ -57,10 +57,10 @@ bool EspLcdTouch::startLvgl(lv_disp_t* display) { .handle = touchHandle, }; - LOGGER.info("Adding touch to LVGL"); + LOG_I(TAG, "Adding touch to LVGL"); lvglDevice = lvgl_port_add_touch(&touch_cfg); if (lvglDevice == nullptr) { - LOGGER.error("Adding touch failed"); + LOG_E(TAG, "Adding touch failed"); return false; } diff --git a/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp b/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp index da24f3b30..fe9cb4cfc 100644 --- a/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp +++ b/Drivers/EspLcdCompat/Source/EspLcdTouchDriver.cpp @@ -1,12 +1,12 @@ #include "EspLcdTouchDriver.h" -#include +#include -static const auto LOGGER = tt::Logger("EspLcdTouchDriver"); +constexpr auto* TAG = "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) { - LOGGER.error("Read data failed"); + LOG_E(TAG, "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 324f4fa43..954a3f8e0 100644 --- a/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp +++ b/Drivers/EstimatedPower/Source/ChargeFromAdcVoltage.cpp @@ -1,7 +1,7 @@ #include "ChargeFromAdcVoltage.h" -#include +#include -static const auto LOGGER = tt::Logger("ChargeFromAdcV"); +constexpr auto* TAG = "ChargeFromAdcV"; constexpr auto MAX_VOLTAGE_SAMPLES = 15; ChargeFromAdcVoltage::ChargeFromAdcVoltage( @@ -10,12 +10,12 @@ ChargeFromAdcVoltage::ChargeFromAdcVoltage( float voltageMax ) : configuration(configuration), chargeFromVoltage(voltageMin, voltageMax) { if (adc_oneshot_new_unit(&configuration.adcConfig, &adcHandle) != ESP_OK) { - LOGGER.error("ADC config failed"); + LOG_E(TAG, "ADC config failed"); return; } if (adc_oneshot_config_channel(adcHandle, configuration.adcChannel, &configuration.adcChannelConfig) != ESP_OK) { - LOGGER.error("ADC channel config failed"); + LOG_E(TAG, "ADC channel config failed"); adc_oneshot_del_unit(adcHandle); adcHandle = nullptr; @@ -36,12 +36,10 @@ 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; - if (LOGGER.isLoggingVerbose()) { - LOGGER.verbose("Raw = {}, voltage = {}", raw, output); - } + LOG_V(TAG, "Raw = %d, voltage = %u", raw, (unsigned)output); return true; } else { - LOGGER.error("Read failed"); + LOG_E(TAG, "Read failed"); return false; } } diff --git a/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp b/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp index a9715787c..c5f7d5df1 100644 --- a/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp +++ b/Drivers/EstimatedPower/Source/ChargeFromVoltage.cpp @@ -1,9 +1,9 @@ #include "ChargeFromVoltage.h" -#include +#include #include -const static auto LOGGER = tt::Logger("ChargeFromVoltage"); +constexpr auto* TAG = "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); - LOGGER.debug("mV = {}, scaled = {}, factor = {:.2f}, result = {}", milliVolt, volts, voltage_factor, charge_level); + LOG_D(TAG, "mV = %u, scaled = %f, factor = %.2f, result = %d", (unsigned)milliVolt, volts, voltage_factor, charge_level); return charge_level; } diff --git a/Drivers/GC9A01/Source/Gc9a01Display.cpp b/Drivers/GC9A01/Source/Gc9a01Display.cpp index 44fe1a93b..98d7bce1b 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 -static const auto LOGGER = tt::Logger("GC9A01"); +constexpr auto* TAG = "GC9A01"; bool Gc9a01Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - LOGGER.info("Starting"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } diff --git a/Drivers/GT911/Source/Gt911Touch.cpp b/Drivers/GT911/Source/Gt911Touch.cpp index 17b3c8a46..c60dc8f2b 100644 --- a/Drivers/GT911/Source/Gt911Touch.cpp +++ b/Drivers/GT911/Source/Gt911Touch.cpp @@ -1,6 +1,6 @@ #include "Gt911Touch.h" -#include +#include #include #include @@ -11,7 +11,7 @@ #include #include -static const auto LOGGER = tt::Logger("GT911"); +constexpr auto* TAG = "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(); @@ -23,7 +23,7 @@ bool Gt911Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { } else if (i2c_controller_has_device_at_address(i2c, ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS_BACKUP, pdMS_TO_TICKS(10)) == ERROR_NONE) { io_config.dev_addr = ESP_LCD_TOUCH_IO_I2C_GT911_ADDRESS_BACKUP; } else { - LOGGER.error("No device found on I2C bus"); + LOG_E(TAG, "No device found on I2C bus"); return false; } @@ -38,7 +38,7 @@ bool Gt911Touch::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { return esp_lcd_new_panel_io_i2c_v2(bus, &io_config, &outHandle) == ESP_OK; } - LOGGER.error("Unsupported I2C driver"); + LOG_E(TAG, "Unsupported I2C driver"); return false; } diff --git a/Drivers/ILI9488/Source/Ili9488Display.cpp b/Drivers/ILI9488/Source/Ili9488Display.cpp index 577bcc1a8..67273f338 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 -static const auto LOGGER = tt::Logger("ILI9488"); +constexpr auto* TAG = "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } diff --git a/Drivers/PwmBacklight/Source/PwmBacklight.cpp b/Drivers/PwmBacklight/Source/PwmBacklight.cpp index dfd6e313a..44ee5720a 100644 --- a/Drivers/PwmBacklight/Source/PwmBacklight.cpp +++ b/Drivers/PwmBacklight/Source/PwmBacklight.cpp @@ -1,8 +1,8 @@ #include "PwmBacklight.h" -#include +#include -static const auto LOGGER = tt::Logger("PwmBacklight"); +constexpr auto* TAG = "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; - LOGGER.info("Init"); + LOG_I(TAG, "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) { - LOGGER.error("Timer config failed"); + LOG_E(TAG, "Timer config failed"); return false; } @@ -46,7 +46,7 @@ bool init(gpio_num_t pin, uint32_t frequencyHz, ledc_timer_t timer, ledc_channel }; if (ledc_channel_config(&ledc_channel) != ESP_OK) { - LOGGER.error("Channel config failed"); + LOG_E(TAG, "Channel config failed"); return false; } @@ -57,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) { - LOGGER.error("Not initialized"); + LOG_E(TAG, "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 15d583472..55b40a715 100644 --- a/Drivers/RgbDisplay/Source/RgbDisplay.cpp +++ b/Drivers/RgbDisplay/Source/RgbDisplay.cpp @@ -2,14 +2,14 @@ #include #include -#include +#include #include #include #include #include -static const auto LOGGER = tt::Logger("RgbDisplay"); +constexpr auto* TAG = "RgbDisplay"; RgbDisplay::~RgbDisplay() { check( @@ -19,35 +19,35 @@ RgbDisplay::~RgbDisplay() { } bool RgbDisplay::start() { - LOGGER.info("Starting"); + LOG_I(TAG, "Starting"); if (esp_lcd_new_rgb_panel(&configuration->panelConfig, &panelHandle) != ESP_OK) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY"); + LOG_E(TAG, "Failed to swap XY"); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } @@ -65,7 +65,7 @@ bool RgbDisplay::stop() { } if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "DisplayDriver is still in use."); } auto touch_device = getTouchDevice(); @@ -81,7 +81,7 @@ bool RgbDisplay::startLvgl() { assert(lvglDisplay == nullptr); if (displayDriver != nullptr && displayDriver.use_count() > 1) { - LOGGER.warn("DisplayDriver is still in use."); + LOG_W(TAG, "DisplayDriver is still in use."); } auto display_config = getLvglPortDisplayConfig(); @@ -94,7 +94,7 @@ bool RgbDisplay::startLvgl() { }; lvglDisplay = lvgl_port_add_disp_rgb(&display_config, &rgb_config); - LOGGER.info("Finished"); + LOG_I(TAG, "Finished"); auto touch_device = getTouchDevice(); if (touch_device != nullptr) { diff --git a/Drivers/SSD1306/Source/Ssd1306Display.cpp b/Drivers/SSD1306/Source/Ssd1306Display.cpp index a03595b36..8630cde04 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 -static const auto LOGGER = tt::Logger("Ssd1306Display"); +constexpr auto* TAG = "Ssd1306Display"; // SSD1306 commands #define SSD1306_CMD_SET_CLOCK 0xD5 @@ -38,7 +38,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) { - LOGGER.error("Failed to send command 0x{:02X}: {}", cmd, ret); + LOG_E(TAG, "Failed to send command 0x%02X: %d", cmd, (int)ret); return false; } return true; @@ -61,7 +61,7 @@ bool Ssd1306Display::createIoHandle(esp_lcd_panel_io_handle_t& ioHandle) { }; if (esp_lcd_new_panel_io_i2c(static_cast(configuration->port), &io_config, &ioHandle) != ESP_OK) { - LOGGER.error("Failed to create IO handle"); + LOG_E(TAG, "Failed to create IO handle"); return false; } @@ -106,7 +106,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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } @@ -116,7 +116,7 @@ bool Ssd1306Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l auto port = configuration->port; auto addr = configuration->deviceAddress; - LOGGER.info("Sending Heltec V3 custom init sequence"); + LOG_I(TAG, "Sending Heltec V3 custom init sequence"); // Display off while configuring ssd1306_i2c_send_cmd(port, addr, SSD1306_CMD_DISPLAY_OFF); @@ -182,7 +182,7 @@ bool Ssd1306Display::createPanelHandle(esp_lcd_panel_io_handle_t ioHandle, esp_l vTaskDelay(pdMS_TO_TICKS(100)); // Let display stabilize - LOGGER.info("Heltec V3 display initialized successfully"); + LOG_I(TAG, "Heltec V3 display initialized successfully"); return true; } diff --git a/Drivers/ST7735/Source/St7735Display.cpp b/Drivers/ST7735/Source/St7735Display.cpp index 39aa6abd5..3ef322b0c 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 -static const auto LOGGER = tt::Logger("ST7735"); +constexpr auto* TAG = "ST7735"; bool St7735Display::createIoHandle(esp_lcd_panel_io_handle_t& outHandle) { - LOGGER.info("Starting"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to set panel gap"); + LOG_E(TAG, "Failed to set panel gap"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to set gamma"); + LOG_E(TAG, "Failed to set gamma"); } } diff --git a/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp b/Drivers/ST7789-i8080/Source/St7789i8080Display.cpp index 1c730f840..c9b815517 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 -static const auto LOGGER = tt::Logger("St7789i8080Display"); +constexpr auto* TAG = "St7789i8080Display"; static St7789i8080Display* g_display_instance = nullptr; // ST7789 initialization commands @@ -51,13 +51,13 @@ St7789i8080Display::St7789i8080Display(const Configuration& config) // Validate configuration if (!configuration.isValid()) { - LOGGER.error("Invalid configuration: resolution must be set"); + LOG_E(TAG, "Invalid configuration: resolution must be set"); return; } } bool St7789i8080Display::createI80Bus() { - LOGGER.info("Creating I80 bus"); + LOG_I(TAG, "Creating I80 bus"); // Create I80 bus configuration esp_lcd_i80_bus_config_t bus_cfg = { @@ -78,15 +78,15 @@ bool St7789i8080Display::createI80Bus() { esp_err_t ret = esp_lcd_new_i80_bus(&bus_cfg, &i80BusHandle); if (ret != ESP_OK) { - LOGGER.error("Failed to create I80 bus: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to create I80 bus: %s", esp_err_to_name(ret)); return false; } - + return true; } bool St7789i8080Display::createPanelIO() { - LOGGER.info("Creating panel IO"); + LOG_I(TAG, "Creating panel IO"); // Create panel IO with proper callback esp_lcd_panel_io_i80_config_t io_cfg = { @@ -114,15 +114,15 @@ bool St7789i8080Display::createPanelIO() { esp_err_t ret = esp_lcd_new_panel_io_i80(i80BusHandle, &io_cfg, &ioHandle); if (ret != ESP_OK) { - LOGGER.error("Failed to create panel IO: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to create panel IO: %s", esp_err_to_name(ret)); return false; } - + return true; } bool St7789i8080Display::createPanel() { - LOGGER.info("Configuring panel"); + LOG_I(TAG, "Configuring panel"); // Create ST7789 panel esp_lcd_panel_dev_config_t panel_config = { @@ -138,57 +138,57 @@ bool St7789i8080Display::createPanel() { esp_err_t ret = esp_lcd_new_panel_st7789(ioHandle, &panel_config, &panelHandle); if (ret != ESP_OK) { - LOGGER.error("Failed to create ST7789 panel: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to create ST7789 panel: %s", esp_err_to_name(ret)); return false; } - + // Reset panel ret = esp_lcd_panel_reset(panelHandle); if (ret != ESP_OK) { - LOGGER.error("Failed to reset panel: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to reset panel: %s", esp_err_to_name(ret)); return false; } - + // Initialize panel ret = esp_lcd_panel_init(panelHandle); if (ret != ESP_OK) { - LOGGER.error("Failed to init panel: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to init panel: %s", esp_err_to_name(ret)); return false; } - + // Set gap ret = esp_lcd_panel_set_gap(panelHandle, configuration.gapX, configuration.gapY); if (ret != ESP_OK) { - LOGGER.error("Failed to set panel gap: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to set panel gap: %s", esp_err_to_name(ret)); return false; } - + // Set inversion ret = esp_lcd_panel_invert_color(panelHandle, configuration.invertColor); if (ret != ESP_OK) { - LOGGER.error("Failed to set panel inversion: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to set panel inversion: %s", esp_err_to_name(ret)); return false; } - + // Set mirror ret = esp_lcd_panel_mirror(panelHandle, configuration.mirrorX, configuration.mirrorY); if (ret != ESP_OK) { - LOGGER.error("Failed to set panel mirror: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to set panel mirror: %s", esp_err_to_name(ret)); return false; } - + // Turn on display ret = esp_lcd_panel_disp_on_off(panelHandle, true); if (ret != ESP_OK) { - LOGGER.error("Failed to turn display on: {}", esp_err_to_name(ret)); + LOG_E(TAG, "Failed to turn display on: %s", esp_err_to_name(ret)); return false; } - + return true; } void St7789i8080Display::sendInitCommands() { - LOGGER.info("Sending ST7789 init commands"); + LOG_I(TAG, "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() { - LOGGER.info("Initializing I8080 ST7789 Display hardware..."); + LOG_I(TAG, "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) { - LOGGER.error("Failed to allocate display buffer"); + LOG_E(TAG, "Failed to allocate display buffer"); return false; } @@ -239,7 +239,7 @@ bool St7789i8080Display::start() { return false; } - LOGGER.info("Display hardware initialized"); + LOG_I(TAG, "Display hardware initialized"); return true; } @@ -278,17 +278,17 @@ bool St7789i8080Display::stop() { } bool St7789i8080Display::startLvgl() { - LOGGER.info("Initializing LVGL for ST7789 display"); + LOG_I(TAG, "Initializing LVGL for ST7789 display"); // Don't reinitialize hardware if it's already done if (!ioHandle) { - LOGGER.info("Hardware not initialized, calling start()"); + LOG_I(TAG, "Hardware not initialized, calling start()"); if (!start()) { - LOGGER.error("Hardware initialization failed"); + LOG_E(TAG, "Hardware initialization failed"); return false; } } else { - LOGGER.info("Hardware already initialized, skipping"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create LVGL display"); + LOG_E(TAG, "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; - LOGGER.info("LVGL display created successfully"); + LOG_I(TAG, "LVGL display created successfully"); return true; } diff --git a/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp b/Drivers/ST7796-i8080/Source/St7796i8080Display.cpp index 1cf9055bb..22e388f55 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 -static const auto LOGGER = tt::Logger("St7796i8080Display"); +constexpr auto* TAG = "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()) { - LOGGER.error("Invalid configuration: resolution must be set"); + LOG_E(TAG, "Invalid configuration: resolution must be set"); return; } } bool St7796i8080Display::createI80Bus() { - LOGGER.info("Creating I80 bus"); + LOG_I(TAG, "Creating I80 bus"); // Create I80 bus configuration esp_lcd_i80_bus_config_t bus_cfg = { @@ -42,15 +42,15 @@ bool St7796i8080Display::createI80Bus() { }; if (esp_lcd_new_i80_bus(&bus_cfg, &i80BusHandle) != ESP_OK) { - LOGGER.error("Failed to create I80 bus"); + LOG_E(TAG, "Failed to create I80 bus"); return false; } - + return true; } bool St7796i8080Display::createPanelIO() { - LOGGER.info("Creating panel IO"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } @@ -85,7 +85,7 @@ bool St7796i8080Display::createPanelIO() { } bool St7796i8080Display::createPanel() { - LOGGER.info("Configuring panel"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } - + // Reset panel if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } - + // Initialize panel if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } - + // Set swap XY if (esp_lcd_panel_swap_xy(panelHandle, configuration.swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } // Set mirror if (esp_lcd_panel_mirror(panelHandle, configuration.mirrorX, configuration.mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } // Set inversion if (esp_lcd_panel_invert_color(panelHandle, configuration.invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } - + // Turn on display if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "Failed to turn display on"); return false; } @@ -144,7 +144,7 @@ bool St7796i8080Display::createPanel() { } bool St7796i8080Display::start() { - LOGGER.info("Initializing I8080 ST7796 Display hardware..."); + LOG_I(TAG, "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) { - LOGGER.error("Failed to allocate display buffer"); + LOG_E(TAG, "Failed to allocate display buffer"); return false; } @@ -175,7 +175,7 @@ bool St7796i8080Display::start() { return false; } - LOGGER.info("Display hardware initialized"); + LOG_I(TAG, "Display hardware initialized"); return true; } @@ -214,17 +214,17 @@ bool St7796i8080Display::stop() { } bool St7796i8080Display::startLvgl() { - LOGGER.info("Initializing LVGL for ST7796 display"); + LOG_I(TAG, "Initializing LVGL for ST7796 display"); // Don't reinitialize hardware if it's already done if (!ioHandle) { - LOGGER.info("Hardware not initialized, calling start()"); + LOG_I(TAG, "Hardware not initialized, calling start()"); if (!start()) { - LOGGER.error("Hardware initialization failed"); + LOG_E(TAG, "Hardware initialization failed"); return false; } } else { - LOGGER.info("Hardware already initialized, skipping"); + LOG_I(TAG, "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) { - LOGGER.error("Failed to create LVGL display"); + LOG_E(TAG, "Failed to create LVGL display"); return false; } g_display_instance = this; - LOGGER.info("LVGL display created successfully"); + LOG_I(TAG, "LVGL display created successfully"); return true; } diff --git a/Drivers/ST7796/Source/St7796Display.cpp b/Drivers/ST7796/Source/St7796Display.cpp index 43bd22c6a..36b7cd10b 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 -static const auto LOGGER = tt::Logger("ST7796"); +constexpr auto* TAG = "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) { - LOGGER.error("Failed to create panel"); + LOG_E(TAG, "Failed to create panel"); return false; } if (esp_lcd_panel_reset(panelHandle) != ESP_OK) { - LOGGER.error("Failed to reset panel"); + LOG_E(TAG, "Failed to reset panel"); return false; } if (esp_lcd_panel_init(panelHandle) != ESP_OK) { - LOGGER.error("Failed to init panel"); + LOG_E(TAG, "Failed to init panel"); return false; } if (esp_lcd_panel_invert_color(panelHandle, configuration->invertColor) != ESP_OK) { - LOGGER.error("Failed to set panel to invert"); + LOG_E(TAG, "Failed to set panel to invert"); return false; } if (esp_lcd_panel_swap_xy(panelHandle, configuration->swapXY) != ESP_OK) { - LOGGER.error("Failed to swap XY "); + LOG_E(TAG, "Failed to swap XY "); return false; } if (esp_lcd_panel_mirror(panelHandle, configuration->mirrorX, configuration->mirrorY) != ESP_OK) { - LOGGER.error("Failed to set panel to mirror"); + LOG_E(TAG, "Failed to set panel to mirror"); return false; } if (esp_lcd_panel_set_gap(panelHandle, configuration->gapX, configuration->gapY) != ESP_OK) { - LOGGER.error("Failed to set panel gap"); + LOG_E(TAG, "Failed to set panel gap"); return false; } if (esp_lcd_panel_disp_on_off(panelHandle, true) != ESP_OK) { - LOGGER.error("Failed to turn display on"); + LOG_E(TAG, "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) { - LOGGER.error("Failed to set gamma"); + LOG_E(TAG, "Failed to set gamma"); }*/ } diff --git a/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp b/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp index 6fb66aab3..d1c30471b 100644 --- a/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp +++ b/Drivers/XPT2046SoftSPI/Source/Xpt2046SoftSpi.cpp @@ -1,6 +1,6 @@ #include "Xpt2046SoftSpi.h" -#include +#include #include #include @@ -11,7 +11,7 @@ #include #include -static const auto LOGGER = tt::Logger("Xpt2046SoftSpi"); +constexpr auto* TAG = "Xpt2046SoftSpi"; constexpr auto CMD_READ_Y = 0x90; constexpr auto CMD_READ_X = 0xD0; @@ -27,7 +27,7 @@ Xpt2046SoftSpi::Xpt2046SoftSpi(std::unique_ptr inConfiguration) } bool Xpt2046SoftSpi::start() { - LOGGER.info("Starting Xpt2046SoftSpi touch driver"); + LOG_I(TAG, "Starting Xpt2046SoftSpi touch driver"); // Configure GPIO pins gpio_config_t io_conf = {}; @@ -42,7 +42,7 @@ bool Xpt2046SoftSpi::start() { io_conf.pull_up_en = GPIO_PULLUP_DISABLE; if (gpio_config(&io_conf) != ESP_OK) { - LOGGER.error("Failed to configure output pins"); + LOG_E(TAG, "Failed to configure output pins"); return false; } @@ -52,7 +52,7 @@ bool Xpt2046SoftSpi::start() { io_conf.pull_up_en = GPIO_PULLUP_ENABLE; if (gpio_config(&io_conf) != ESP_OK) { - LOGGER.error("Failed to configure input pin"); + LOG_E(TAG, "Failed to configure input pin"); return false; } @@ -61,8 +61,9 @@ bool Xpt2046SoftSpi::start() { gpio_set_level(configuration->clkPin, 0); // CLK low gpio_set_level(configuration->mosiPin, 0); // MOSI low - LOGGER.info( - "GPIO configured: MOSI={}, MISO={}, CLK={}, CS={}", + LOG_I( + TAG, + "GPIO configured: MOSI=%d, MISO=%d, CLK=%d, CS=%d", static_cast(configuration->mosiPin), static_cast(configuration->misoPin), static_cast(configuration->clkPin), @@ -73,7 +74,7 @@ bool Xpt2046SoftSpi::start() { } bool Xpt2046SoftSpi::stop() { - LOGGER.info("Stopping Xpt2046SoftSpi touch driver"); + LOG_I(TAG, "Stopping Xpt2046SoftSpi touch driver"); // Stop LVLG if needed if (lvglDevice != nullptr) { @@ -86,13 +87,13 @@ bool Xpt2046SoftSpi::stop() { bool Xpt2046SoftSpi::startLvgl(lv_display_t* display) { (void)display; if (lvglDevice != nullptr) { - LOGGER.error("LVGL was already started"); + LOG_E(TAG, "LVGL was already started"); return false; } lvglDevice = lv_indev_create(); if (lvglDevice == nullptr) { - LOGGER.error("Failed to create LVGL input device"); + LOG_E(TAG, "Failed to create LVGL input device"); return false; } @@ -100,7 +101,7 @@ bool Xpt2046SoftSpi::startLvgl(lv_display_t* display) { lv_indev_set_read_cb(lvglDevice, touchReadCallback); lv_indev_set_user_data(lvglDevice, this); - LOGGER.info("Xpt2046SoftSpi touch driver started successfully"); + LOG_I(TAG, "Xpt2046SoftSpi touch driver started successfully"); return true; } diff --git a/Modules/hal-device-module/source/hal/Device.cpp b/Modules/hal-device-module/source/hal/Device.cpp index 79a4b8832..ceb17b7b4 100644 --- a/Modules/hal-device-module/source/hal/Device.cpp +++ b/Modules/hal-device-module/source/hal/Device.cpp @@ -1,24 +1,26 @@ // SPDX-License-Identifier: Apache-2.0 -#include #include #include +#include +#include -#include #include + #include +#include namespace tt::hal { RecursiveMutex mutex; static Device::Id nextId = 0; -static const auto LOGGER = Logger("Devices"); +constexpr auto* TAG = "Devices"; Device::Device() : id(nextId++) {} static std::shared_ptr createKernelDeviceHolder(const std::shared_ptr& device) { auto kernel_device_name = std::format("hal-device-{}", device->getId()); - LOGGER.info("Registering {} with id {} as kernel device {}", device->getName(), device->getId(), kernel_device_name); + LOG_I(TAG, "Registering %s with id %u as kernel device %s", device->getName().c_str(), (unsigned)device->getId(), kernel_device_name.c_str()); auto kernel_device_holder = std::make_shared(kernel_device_name); auto* kernel_device = kernel_device_holder->device.get(); check(device_construct(kernel_device) == ERROR_NONE); @@ -49,7 +51,7 @@ void registerDevice(const std::shared_ptr& device) { auto kernel_device_holder = createKernelDeviceHolder(device); device->setKernelDeviceHolder(kernel_device_holder); } else { - LOGGER.warn("Device {} with id {} was already registered", device->getName(), device->getId()); + LOG_W(TAG, "Device %s with id %u was already registered", device->getName().c_str(), (unsigned)device->getId()); } } @@ -63,7 +65,7 @@ void deregisterDevice(const std::shared_ptr& device) { destroyKernelDeviceHolder(kernel_device_holder); device->setKernelDeviceHolder(nullptr); } else { - LOGGER.warn("Device {} with id {} was not registered", device->getName(), device->getId()); + LOG_W(TAG, "Device %s with id %u was not registered", device->getName().c_str(), (unsigned)device->getId()); } } diff --git a/TactilityCore/Include/Tactility/LogMessages.h b/Tactility/Include/Tactility/LogMessages.h similarity index 94% rename from TactilityCore/Include/Tactility/LogMessages.h rename to Tactility/Include/Tactility/LogMessages.h index ec48ce802..a3acda434 100644 --- a/TactilityCore/Include/Tactility/LogMessages.h +++ b/Tactility/Include/Tactility/LogMessages.h @@ -9,11 +9,11 @@ // Alloc #define LOG_MESSAGE_ALLOC_FAILED "Out of memory" -#define LOG_MESSAGE_ALLOC_FAILED_FMT "Out of memory (failed to allocated {} bytes)" +#define LOG_MESSAGE_ALLOC_FAILED_FMT "Out of memory (failed to allocated %d bytes)" // Mutex #define LOG_MESSAGE_MUTEX_LOCK_FAILED "Mutex acquisition timeout" -#define LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT "Mutex acquisition timeout ({})" +#define LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT "Mutex acquisition timeout (%s)" // Power on #define LOG_MESSAGE_POWER_ON_START "Power on" diff --git a/Tactility/Include/Tactility/network/EspHttpClient.h b/Tactility/Include/Tactility/network/EspHttpClient.h index c8d4b4215..8153b18c1 100644 --- a/Tactility/Include/Tactility/network/EspHttpClient.h +++ b/Tactility/Include/Tactility/network/EspHttpClient.h @@ -3,13 +3,13 @@ #ifdef ESP_PLATFORM #include -#include +#include namespace tt::network { class EspHttpClient { - const Logger logger = Logger("EspHttpClient"); + static constexpr auto* TAG = "EspHttpClient"; std::unique_ptr config = nullptr; esp_http_client_handle_t client = nullptr; @@ -28,7 +28,7 @@ class EspHttpClient { } bool init(std::unique_ptr inConfig) { - logger.info("init({})", inConfig->url); + LOG_I(TAG, "init(%s)", inConfig->url); assert(this->config == nullptr); config = std::move(inConfig); client = esp_http_client_init(config.get()); @@ -37,11 +37,11 @@ class EspHttpClient { bool open() { assert(client != nullptr); - logger.info("open()"); + LOG_I(TAG, "open()"); auto result = esp_http_client_open(client, 0); if (result != ESP_OK) { - logger.error("open() failed: {}", esp_err_to_name(result)); + LOG_E(TAG, "open() failed: %s", esp_err_to_name(result)); return false; } @@ -51,7 +51,7 @@ class EspHttpClient { bool fetchHeaders() const { assert(client != nullptr); - logger.info("fetchHeaders()"); + LOG_I(TAG, "fetchHeaders()"); return esp_http_client_fetch_headers(client) >= 0; } @@ -64,7 +64,7 @@ class EspHttpClient { int getStatusCode() const { assert(client != nullptr); const auto status_code = esp_http_client_get_status_code(client); - logger.info("Status code {}", status_code); + LOG_I(TAG, "Status code %d", status_code); return status_code; } @@ -75,19 +75,19 @@ class EspHttpClient { int read(char* bytes, int size) const { assert(client != nullptr); - logger.info("read({})", size); + LOG_I(TAG, "read(%d)", size); return esp_http_client_read(client, bytes, size); } int readResponse(char* bytes, int size) const { assert(client != nullptr); - logger.info("readResponse({})", size); + LOG_I(TAG, "readResponse(%d)", size); return esp_http_client_read_response(client, bytes, size); } bool close() { assert(client != nullptr); - logger.info("close()"); + LOG_I(TAG, "close()"); if (esp_http_client_close(client) == ESP_OK) { isOpen = false; } @@ -97,7 +97,7 @@ class EspHttpClient { bool cleanup() { assert(client != nullptr); assert(!isOpen); - logger.info("cleanup()"); + LOG_I(TAG, "cleanup()"); const auto result = esp_http_client_cleanup(client); client = nullptr; return result == ESP_OK; diff --git a/Tactility/Private/Tactility/app/AppInstance.h b/Tactility/Private/Tactility/app/AppInstance.h index f671392a0..14474f950 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) { - Logger("AppInstance").warn("Manifest specifies createApp, but this is not used with external apps"); + LOG_W("AppInstance", "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 0b2ad1fc5..7b262a79d 100644 --- a/Tactility/Private/Tactility/json/Reader.h +++ b/Tactility/Private/Tactility/json/Reader.h @@ -4,14 +4,14 @@ #include #include -#include +#include namespace tt::json { class Reader { const cJSON* root; - Logger logger = Logger("json::Reader"); + static constexpr auto* TAG = "json::Reader"; public: @@ -20,7 +20,7 @@ class Reader { bool readString(const char* key, std::string& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsString(child)) { - logger.error("{} is not a string", key); + LOG_E(TAG, "%s is not a string", key); return false; } output = cJSON_GetStringValue(child); @@ -48,7 +48,7 @@ class Reader { bool readNumber(const char* key, double& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsNumber(child)) { - logger.error("{} is not a number", key); + LOG_E(TAG, "%s is not a number", key); return false; } output = cJSON_GetNumberValue(child); @@ -58,16 +58,16 @@ class Reader { bool readStringArray(const char* key, std::vector& output) const { const auto* child = cJSON_GetObjectItemCaseSensitive(root, key); if (!cJSON_IsArray(child)) { - logger.error("{} is not an array", key); + LOG_E(TAG, "%s is not an array", key); return false; } const auto size = cJSON_GetArraySize(child); - logger.info("Processing {} array children", size); + LOG_I(TAG, "Processing %d 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)) { - logger.error("Array child of {} is not a string", key); + LOG_E(TAG, "Array child of %s 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 78555593b..7759db78d 100644 --- a/Tactility/Source/PartitionsEsp.cpp +++ b/Tactility/Source/PartitionsEsp.cpp @@ -1,16 +1,16 @@ #ifdef ESP_PLATFORM #include -#include #include #include #include #include +#include namespace tt { -static const auto LOGGER = Logger("Partitions"); +constexpr auto* TAG = "Partitions"; // region file_system stub @@ -47,7 +47,7 @@ FileSystemApi partition_fs_api = { // endregion file_system stub static esp_err_t initNvsFlashSafely() { - LOGGER.info("Init NVS"); + LOG_I(TAG, "Init NVS"); esp_err_t result = nvs_flash_init(); if (result == ESP_ERR_NVS_NO_FREE_PAGES || result == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); @@ -77,7 +77,7 @@ size_t getSectorSize() { } bool initPartitionsEsp() { - LOGGER.info("Init partitions"); + LOG_I(TAG, "Init partitions"); ESP_ERROR_CHECK(initNvsFlashSafely()); const esp_vfs_fat_mount_config_t mount_config = { @@ -90,21 +90,21 @@ bool initPartitionsEsp() { auto system_result = esp_vfs_fat_spiflash_mount_ro("/system", "system", &mount_config); if (system_result != ESP_OK) { - LOGGER.error("Failed to mount /system ({})", esp_err_to_name(system_result)); + LOG_E(TAG, "Failed to mount /system (%s)", esp_err_to_name(system_result)); return false; } - LOGGER.info("Mounted /system"); + LOG_I(TAG, "Mounted /system"); static auto system_fs_data = PartitionFsData("/system"); file_system_add(&partition_fs_api, &system_fs_data); #ifdef CONFIG_TT_USER_DATA_LOCATION_INTERNAL auto data_result = esp_vfs_fat_spiflash_mount_rw_wl("/data", "data", &mount_config, &data_wl_handle); if (data_result != ESP_OK) { - LOGGER.error("Failed to mount /data ({})", esp_err_to_name(data_result)); + LOG_E(TAG, "Failed to mount /data (%s)", esp_err_to_name(data_result)); return false; } - LOGGER.info("Mounted /data"); + LOG_I(TAG, "Mounted /data"); static auto data_fs_data = PartitionFsData("/data"); file_system_add(&partition_fs_api, &data_fs_data); #endif diff --git a/Tactility/Source/PreferencesEsp.cpp b/Tactility/Source/PreferencesEsp.cpp index 61ead91c7..ccd593796 100644 --- a/Tactility/Source/PreferencesEsp.cpp +++ b/Tactility/Source/PreferencesEsp.cpp @@ -1,19 +1,19 @@ #ifdef ESP_PLATFORM -#include #include #include #include +#include namespace tt { -static const auto LOGGER = Logger("Preferences"); +constexpr auto* TAG = "Preferences"; bool Preferences::optBool(const std::string& key, bool& out) const { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); return false; } else { uint8_t out_number; @@ -29,7 +29,7 @@ bool Preferences::optBool(const std::string& key, bool& out) const { bool Preferences::optInt32(const std::string& key, int32_t& out) const { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); return false; } else { bool success = nvs_get_i32(handle, key.c_str(), &out) == ESP_OK; @@ -41,7 +41,7 @@ bool Preferences::optInt32(const std::string& key, int32_t& out) const { bool Preferences::optInt64(const std::string& key, int64_t& out) const { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); return false; } else { bool success = nvs_get_i64(handle, key.c_str(), &out) == ESP_OK; @@ -53,7 +53,7 @@ bool Preferences::optInt64(const std::string& key, int64_t& out) const { bool Preferences::optString(const std::string& key, std::string& out) const { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) != ESP_OK) { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); return false; } else { size_t out_size = 256; @@ -90,13 +90,13 @@ void Preferences::putBool(const std::string& key, bool value) { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) { if (nvs_set_u8(handle, key.c_str(), value) != ESP_OK) { - LOGGER.error("Failed to set {}:{}", namespace_, key); + LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); } else if (nvs_commit(handle) != ESP_OK) { - LOGGER.error("Failed to commit {}:{}", namespace_, key); + LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); } nvs_close(handle); } else { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); } } @@ -104,13 +104,13 @@ void Preferences::putInt32(const std::string& key, int32_t value) { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) { if (nvs_set_i32(handle, key.c_str(), value) != ESP_OK) { - LOGGER.error("Failed to set {}:{}", namespace_, key); + LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); } else if (nvs_commit(handle) != ESP_OK) { - LOGGER.error("Failed to commit {}:{}", namespace_, key); + LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); } nvs_close(handle); } else { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); } } @@ -118,13 +118,13 @@ void Preferences::putInt64(const std::string& key, int64_t value) { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) { if (nvs_set_i64(handle, key.c_str(), value) != ESP_OK) { - LOGGER.error("Failed to set {}:{}", namespace_, key); + LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); } else if (nvs_commit(handle) != ESP_OK) { - LOGGER.error("Failed to commit {}:{}", namespace_, key); + LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); } nvs_close(handle); } else { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); } } @@ -132,13 +132,13 @@ void Preferences::putString(const std::string& key, const std::string& text) { nvs_handle_t handle; if (nvs_open(namespace_, NVS_READWRITE, &handle) == ESP_OK) { if (nvs_set_str(handle, key.c_str(), text.c_str()) != ESP_OK) { - LOGGER.error("Failed to set {}:{}", namespace_, key.c_str()); + LOG_E(TAG, "Failed to set %s:%s", namespace_, key.c_str()); } else if (nvs_commit(handle) != ESP_OK) { - LOGGER.error("Failed to commit {}:{}", namespace_, key); + LOG_E(TAG, "Failed to commit %s:%s", namespace_, key.c_str()); } nvs_close(handle); } else { - LOGGER.error("Failed to open namespace {}", namespace_); + LOG_E(TAG, "Failed to open namespace %s", namespace_); } } diff --git a/Tactility/Source/Tactility.cpp b/Tactility/Source/Tactility.cpp index 2530b9328..0dda1ae54 100644 --- a/Tactility/Source/Tactility.cpp +++ b/Tactility/Source/Tactility.cpp @@ -7,10 +7,9 @@ #include #include +#include #include #include -#include -#include #include #include #include @@ -29,6 +28,7 @@ #include #include #include +#include #include #ifdef ESP_PLATFORM @@ -42,7 +42,7 @@ namespace tt { -static auto LOGGER = Logger("Tactility"); +constexpr auto* TAG = "Tactility"; static const Configuration* config_instance = nullptr; static Dispatcher mainDispatcher; @@ -139,7 +139,7 @@ namespace app { // List of all apps excluding Boot app (as Boot app calls this function indirectly) static void registerInternalApps() { - LOGGER.info("Registering internal apps"); + LOG_I(TAG, "Registering internal apps"); addAppManifest(app::alertdialog::manifest); addAppManifest(app::appdetails::manifest); @@ -210,16 +210,16 @@ static void registerInternalApps() { } static void registerInstalledApp(std::string path) { - LOGGER.info("Registering app at {}", path); + LOG_I(TAG, "Registering app at %s", path.c_str()); std::string manifest_path = path + "/manifest.properties"; if (!file::isFile(manifest_path)) { - LOGGER.error("Manifest not found at {}", manifest_path); + LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str()); return; } app::AppManifest manifest; if (!app::parseManifest(manifest_path, manifest)) { - LOGGER.error("Failed to parse manifest at {}", manifest_path); + LOG_E(TAG, "Failed to parse manifest at %s", manifest_path.c_str()); return; } @@ -230,7 +230,7 @@ static void registerInstalledApp(std::string path) { } static void registerInstalledApps(const std::string& path) { - LOGGER.info("Registering apps from {}", path); + LOG_I(TAG, "Registering apps from %s", path.c_str()); file::listDirectory(path, [&path](const auto& entry) { auto absolute_path = std::format("{}/{}", path, entry.d_name); @@ -247,7 +247,7 @@ static void registerInstalledAppsFromFileSystems() { if (file_system_get_path(fs, path, sizeof(path)) != ERROR_NONE) return true; const auto app_path = std::format("{}/tactility/app", path); if (!app_path.starts_with(file::MOUNT_POINT_SYSTEM) && file::isDirectory(app_path)) { - LOGGER.info("Registering apps from {}", app_path); + LOG_I(TAG, "Registering apps from %s", app_path.c_str()); registerInstalledApps(app_path); } return true; @@ -255,7 +255,7 @@ static void registerInstalledAppsFromFileSystems() { } static void registerAndStartSecondaryServices() { - LOGGER.info("Registering and starting secondary system services"); + LOG_I(TAG, "Registering and starting secondary system services"); addService(service::loader::manifest); addService(service::gui::manifest); addService(service::statusbar::manifest); @@ -272,7 +272,7 @@ static void registerAndStartSecondaryServices() { } static void registerAndStartPrimaryServices() { - LOGGER.info("Registering and starting primary system services"); + LOG_I(TAG, "Registering and starting primary system services"); addService(service::gps::manifest); addService(service::wifi::manifest); #ifdef ESP_PLATFORM @@ -294,17 +294,17 @@ void createTempDirectory() { auto lock = file::getLock(data_path)->asScopedLock(); if (lock.lock(1000 / portTICK_PERIOD_MS)) { if (!file::findOrCreateParentDirectory(temp_path, 0777)) { - LOGGER.error("Failed to create {}", data_path); + LOG_E(TAG, "Failed to create %s", data_path.c_str()); } else if (mkdir(temp_path.c_str(), 0777) == 0) { - LOGGER.info("Created {}", temp_path); + LOG_I(TAG, "Created %s", temp_path.c_str()); } else { - LOGGER.error("Failed to create {}", temp_path); + LOG_E(TAG, "Failed to create %s", temp_path.c_str()); } } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, data_path); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, data_path.c_str()); } } else { - LOGGER.info("Found existing {}", temp_path); + LOG_I(TAG, "Found existing %s", temp_path.c_str()); } } @@ -318,13 +318,13 @@ void registerApps() { } void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices[]) { - LOGGER.info("Tactility v{} on {} ({})", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID); + LOG_I(TAG, "Tactility v%s on %s (%s)", TT_VERSION, CONFIG_TT_DEVICE_NAME, CONFIG_TT_DEVICE_ID); assert(config.hardware); - LOGGER.info("Initializing kernel"); + LOG_I(TAG, "Initializing kernel"); if (kernel_init(dtsModules, dtsDevices) != ERROR_NONE) { - LOGGER.error("Failed to initialize kernel"); + LOG_E(TAG, "Failed to initialize kernel"); return; } @@ -363,14 +363,14 @@ void run(const Configuration& config, Module* dtsModules[], DtsDevice dtsDevices registerAndStartSecondaryServices(); - LOGGER.info("Core systems ready"); + LOG_I(TAG, "Core systems ready"); - LOGGER.info("Starting boot app"); + LOG_I(TAG, "Starting boot app"); // The boot app takes care of registering system apps, user services and user apps addAppManifest(app::boot::manifest); app::start(app::boot::manifest.appId); - LOGGER.info("Main dispatcher ready"); + LOG_I(TAG, "Main dispatcher ready"); while (true) { mainDispatcher.consume(); } diff --git a/Tactility/Source/app/AppInstall.cpp b/Tactility/Source/app/AppInstall.cpp index eef072a3c..b756a0e43 100644 --- a/Tactility/Source/app/AppInstall.cpp +++ b/Tactility/Source/app/AppInstall.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -16,21 +15,22 @@ #include #include +#include namespace tt::app { -static const auto LOGGER = Logger("App"); +constexpr auto* TAG = "App"; static bool untarFile(minitar* mp, const minitar_entry* entry, const std::string& destinationPath) { const auto absolute_path = destinationPath + "/" + entry->metadata.path; if (!file::findOrCreateDirectory(destinationPath, 0777)) { - LOGGER.error("Can't find or create directory {}", destinationPath.c_str()); + LOG_E(TAG, "Can't find or create directory %s", destinationPath.c_str()); return false; } // minitar_read_contents(&mp, &entry, file_buffer, entry.metadata.size); if (!minitar_read_contents_to_file(mp, entry, absolute_path.c_str())) { - LOGGER.error("Failed to write data to {}", absolute_path.c_str()); + LOG_E(TAG, "Failed to write data to %s", absolute_path.c_str()); return false; } @@ -59,32 +59,32 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath do { if (minitar_read_entry(&mp, &entry) == 0) { - LOGGER.info("Extracting {}", entry.metadata.path); + LOG_I(TAG, "Extracting %s", entry.metadata.path); if (entry.metadata.type == MTAR_DIRECTORY) { if (!strcmp(entry.metadata.name, ".") || !strcmp(entry.metadata.name, "..") || !strcmp(entry.metadata.name, "/")) continue; if (!untarDirectory(&entry, destinationPath)) { - LOGGER.error("Failed to create directory {}/{}: {}", destinationPath, entry.metadata.name, strerror(errno)); + LOG_E(TAG, "Failed to create directory %s/%s: %s", destinationPath.c_str(), entry.metadata.name, strerror(errno)); success = false; break; } } else if (entry.metadata.type == MTAR_REGULAR) { if (!untarFile(&mp, &entry, destinationPath)) { - LOGGER.error("Failed to extract file {}: {}", entry.metadata.path, strerror(errno)); + LOG_E(TAG, "Failed to extract file %s: %s", entry.metadata.path, strerror(errno)); success = false; break; } } else if (entry.metadata.type == MTAR_SYMLINK) { - LOGGER.error("SYMLINK not supported"); + LOG_E(TAG, "SYMLINK not supported"); } else if (entry.metadata.type == MTAR_HARDLINK) { - LOGGER.error("HARDLINK not supported"); + LOG_E(TAG, "HARDLINK not supported"); } else if (entry.metadata.type == MTAR_FIFO) { - LOGGER.error("FIFO not supported"); + LOG_E(TAG, "FIFO not supported"); } else if (entry.metadata.type == MTAR_BLKDEV) { - LOGGER.error("BLKDEV not supported"); + LOG_E(TAG, "BLKDEV not supported"); } else if (entry.metadata.type == MTAR_CHRDEV) { - LOGGER.error("CHRDEV not supported"); + LOG_E(TAG, "CHRDEV not supported"); } else { - LOGGER.error("Unknown entry type: {}", static_cast(entry.metadata.type)); + LOG_E(TAG, "Unknown entry type: %d", static_cast(entry.metadata.type)); success = false; break; } @@ -96,7 +96,7 @@ static bool untar(const std::string& tarPath, const std::string& destinationPath void cleanupInstallDirectory(const std::string& path) { if (!file::deleteRecursively(path)) { - LOGGER.warn("Failed to delete existing installation at {}", path); + LOG_W(TAG, "Failed to delete existing installation at %s", path.c_str()); } } @@ -105,16 +105,16 @@ bool install(const std::string& path) { // the lock with the display. We don't want to lock the display for very long. auto app_parent_path = getAppInstallPath(); - LOGGER.info("Installing app {} to {}", path, app_parent_path); + LOG_I(TAG, "Installing app %s to %s", path.c_str(), app_parent_path.c_str()); auto filename = file::getLastPathSegment(path); const std::string app_target_path = std::format("{}/{}", app_parent_path, filename); if (file::isDirectory(app_target_path) && !file::deleteRecursively(app_target_path)) { - LOGGER.warn("Failed to delete {}", app_target_path); + LOG_W(TAG, "Failed to delete %s", app_target_path.c_str()); } if (!file::findOrCreateDirectory(app_target_path, 0777)) { - LOGGER.info("Failed to create directory {}", app_target_path); + LOG_I(TAG, "Failed to create directory %s", app_target_path.c_str()); return false; } @@ -122,9 +122,9 @@ bool install(const std::string& path) { auto source_path_lock = file::getLock(path)->asScopedLock(); target_path_lock.lock(); source_path_lock.lock(); - LOGGER.info("Extracting app from {} to {}", path, app_target_path); + LOG_I(TAG, "Extracting app from %s to %s", path.c_str(), app_target_path.c_str()); if (!untar(path, app_target_path)) { - LOGGER.error("Failed to extract"); + LOG_E(TAG, "Failed to extract"); return false; } source_path_lock.unlock(); @@ -132,14 +132,14 @@ bool install(const std::string& path) { auto manifest_path = app_target_path + "/manifest.properties"; if (!file::isFile(manifest_path)) { - LOGGER.error("Manifest not found at {}", manifest_path); + LOG_E(TAG, "Manifest not found at %s", manifest_path.c_str()); cleanupInstallDirectory(app_target_path); return false; } AppManifest manifest; if (!parseManifest(manifest_path, manifest)) { - LOGGER.warn("Invalid manifest"); + LOG_W(TAG, "Invalid manifest"); cleanupInstallDirectory(app_target_path); return false; } @@ -152,7 +152,7 @@ bool install(const std::string& path) { const std::string renamed_target_path = std::format("{}/{}", app_parent_path, manifest.appId); if (file::isDirectory(renamed_target_path)) { if (!file::deleteRecursively(renamed_target_path)) { - LOGGER.warn("Failed to delete existing installation at {}", renamed_target_path); + LOG_W(TAG, "Failed to delete existing installation at %s", renamed_target_path.c_str()); cleanupInstallDirectory(app_target_path); return false; } @@ -163,7 +163,7 @@ bool install(const std::string& path) { target_path_lock.unlock(); if (!rename_success) { - LOGGER.error(R"(Failed to rename "{}" to "{}")", app_target_path, manifest.appId); + LOG_E(TAG, R"(Failed to rename "%s" to "%s")", app_target_path.c_str(), manifest.appId.c_str()); cleanupInstallDirectory(app_target_path); return false; } @@ -176,7 +176,7 @@ bool install(const std::string& path) { } bool uninstall(const std::string& appId) { - LOGGER.info("Uninstalling app {}", appId); + LOG_I(TAG, "Uninstalling app %s", appId.c_str()); // If the app was running, then stop it if (isRunning(appId)) { @@ -185,7 +185,7 @@ bool uninstall(const std::string& appId) { auto app_path = getAppInstallPath(appId); if (!file::isDirectory(app_path)) { - LOGGER.error("App {} not found at {}", appId, app_path); + LOG_E(TAG, "App %s not found at %s", appId.c_str(), app_path.c_str()); return false; } @@ -194,7 +194,7 @@ bool uninstall(const std::string& appId) { } if (!removeAppManifest(appId)) { - LOGGER.warn("Failed to remove app {} from registry", appId); + LOG_W(TAG, "Failed to remove app %s from registry", appId.c_str()); } return true; diff --git a/Tactility/Source/app/AppManifestParsing.cpp b/Tactility/Source/app/AppManifestParsing.cpp index 091e414b0..6a4295aff 100644 --- a/Tactility/Source/app/AppManifestParsing.cpp +++ b/Tactility/Source/app/AppManifestParsing.cpp @@ -1,16 +1,16 @@ #include #include -#include #include #include #include #include +#include namespace tt::app { -static const auto LOGGER = Logger("AppManifest"); +constexpr auto* TAG = "AppManifest"; constexpr bool validateString(const std::string& value, const std::function& isValidChar) { return std::ranges::all_of(value, isValidChar); @@ -19,7 +19,7 @@ constexpr bool validateString(const std::string& value, const std::function& map, const std::string& key, std::string& output) { const auto iterator = map.find(key); if (iterator == map.end()) { - LOGGER.error("Failed to find {} in manifest", key); + LOG_E(TAG, "Failed to find %s in manifest", key.c_str()); return false; } output = iterator->second; @@ -70,13 +70,13 @@ static bool detectIsV1Format(const std::string& filePath) { } bool parseManifest(const std::string& filePath, AppManifest& manifest) { - LOGGER.info("Parsing manifest {}", filePath); + LOG_I(TAG, "Parsing manifest %s", filePath.c_str()); bool is_v1_format = detectIsV1Format(filePath); std::map properties; if (!file::loadPropertiesFile(filePath, properties)) { - LOGGER.error("Failed to load manifest at {}", filePath); + LOG_E(TAG, "Failed to load manifest at %s", filePath.c_str()); return false; } diff --git a/Tactility/Source/app/AppManifestParsingV1.cpp b/Tactility/Source/app/AppManifestParsingV1.cpp index ab9d885ac..0858962b8 100644 --- a/Tactility/Source/app/AppManifestParsingV1.cpp +++ b/Tactility/Source/app/AppManifestParsingV1.cpp @@ -1,11 +1,11 @@ #include #include -#include +#include namespace tt::app { -static const auto LOGGER = Logger("AppManifestV1"); +constexpr auto* TAG = "AppManifestV1"; bool parseManifestV1(const std::map& map, AppManifest& manifest) { // [manifest] @@ -16,7 +16,7 @@ bool parseManifestV1(const std::map& map, AppManifest& } if (!isValidManifestVersion(manifest_version)) { - LOGGER.error("Invalid version"); + LOG_E(TAG, "Invalid version"); return false; } @@ -27,7 +27,7 @@ bool parseManifestV1(const std::map& map, AppManifest& } if (!isValidId(manifest.appId)) { - LOGGER.error("Invalid app id"); + LOG_E(TAG, "Invalid app id"); return false; } @@ -36,7 +36,7 @@ bool parseManifestV1(const std::map& map, AppManifest& } if (!isValidName(manifest.appName)) { - LOGGER.error("Invalid app name"); + LOG_E(TAG, "Invalid app name"); return false; } @@ -45,7 +45,7 @@ bool parseManifestV1(const std::map& map, AppManifest& } if (!isValidAppVersionName(manifest.appVersionName)) { - LOGGER.error("Invalid app version name"); + LOG_E(TAG, "Invalid app version name"); return false; } @@ -55,7 +55,7 @@ bool parseManifestV1(const std::map& map, AppManifest& } if (!isValidAppVersionCode(version_code_string)) { - LOGGER.error("Invalid app version code"); + LOG_E(TAG, "Invalid app version code"); return false; } diff --git a/Tactility/Source/app/AppManifestParsingV2.cpp b/Tactility/Source/app/AppManifestParsingV2.cpp index b739bfbad..b29291901 100644 --- a/Tactility/Source/app/AppManifestParsingV2.cpp +++ b/Tactility/Source/app/AppManifestParsingV2.cpp @@ -1,11 +1,11 @@ #include #include -#include +#include namespace tt::app { -static const auto LOGGER = Logger("AppManifestV2"); +constexpr auto* TAG = "AppManifestV2"; bool parseManifestV2(const std::map& map, AppManifest& manifest) { // manifest @@ -16,7 +16,7 @@ bool parseManifestV2(const std::map& map, AppManifest& } if (!isValidManifestVersion(manifest_version)) { - LOGGER.error("Invalid version"); + LOG_E(TAG, "Invalid version"); return false; } @@ -27,7 +27,7 @@ bool parseManifestV2(const std::map& map, AppManifest& } if (!isValidId(manifest.appId)) { - LOGGER.error("Invalid app id"); + LOG_E(TAG, "Invalid app id"); return false; } @@ -36,7 +36,7 @@ bool parseManifestV2(const std::map& map, AppManifest& } if (!isValidName(manifest.appName)) { - LOGGER.error("Invalid app name"); + LOG_E(TAG, "Invalid app name"); return false; } @@ -45,7 +45,7 @@ bool parseManifestV2(const std::map& map, AppManifest& } if (!isValidAppVersionName(manifest.appVersionName)) { - LOGGER.error("Invalid app version name"); + LOG_E(TAG, "Invalid app version name"); return false; } @@ -55,7 +55,7 @@ bool parseManifestV2(const std::map& map, AppManifest& } if (!isValidAppVersionCode(version_code_string)) { - LOGGER.error("Invalid app version code"); + LOG_E(TAG, "Invalid app version code"); return false; } diff --git a/Tactility/Source/app/AppRegistration.cpp b/Tactility/Source/app/AppRegistration.cpp index e2db7b4c4..8a5d60a08 100644 --- a/Tactility/Source/app/AppRegistration.cpp +++ b/Tactility/Source/app/AppRegistration.cpp @@ -1,15 +1,15 @@ #include #include -#include #include #include #include +#include namespace tt::app { -static const auto LOGGER = Logger("AppRegistration"); +constexpr auto* TAG = "AppRegistration"; typedef std::unordered_map> AppManifestMap; @@ -17,12 +17,12 @@ static AppManifestMap app_manifest_map; static Mutex hash_mutex; void addAppManifest(const AppManifest& manifest) { - LOGGER.info("Registering manifest {}", manifest.appId); + LOG_I(TAG, "Registering manifest %s", manifest.appId.c_str()); hash_mutex.lock(); if (app_manifest_map.contains(manifest.appId)) { - LOGGER.warn("Overwriting existing manifest for {}", manifest.appId); + LOG_W(TAG, "Overwriting existing manifest for %s", manifest.appId.c_str()); } app_manifest_map[manifest.appId] = std::make_shared(manifest); @@ -31,7 +31,7 @@ void addAppManifest(const AppManifest& manifest) { } bool removeAppManifest(const std::string& id) { - LOGGER.info("Removing manifest for {}", id); + LOG_I(TAG, "Removing manifest for %s", id.c_str()); auto lock = hash_mutex.asScopedLock(); lock.lock(); diff --git a/Tactility/Source/app/ElfApp.cpp b/Tactility/Source/app/ElfApp.cpp index 59d99c8a9..1354c19b2 100644 --- a/Tactility/Source/app/ElfApp.cpp +++ b/Tactility/Source/app/ElfApp.cpp @@ -4,17 +4,17 @@ #include #include #include -#include #include #include #include #include +#include #include namespace tt::app { -static auto LOGGER = Logger("ElfApp"); +constexpr auto* TAG = "ElfApp"; static std::string getErrorCodeString(int error_code) { switch (error_code) { @@ -71,7 +71,7 @@ class ElfApp final : public App { bool startElf() { const std::string elf_path = std::format("{}/elf/{}.elf", appPath, CONFIG_IDF_TARGET); - LOGGER.info("Starting ELF {}", elf_path); + LOG_I(TAG, "Starting ELF %s", elf_path.c_str()); assert(elfFileData == nullptr); size_t size = 0; @@ -85,7 +85,7 @@ class ElfApp final : public App { if (esp_elf_init(&elf) != ESP_OK) { lastError = "Failed to initialize"; - LOGGER.error("{}", lastError); + LOG_E(TAG, "%s", lastError.c_str()); elfFileData = nullptr; return false; } @@ -94,7 +94,7 @@ class ElfApp final : public App { if (relocate_result != 0) { // Note: the result code maps to values from cstdlib's errno.h lastError = getErrorCodeString(-relocate_result); - LOGGER.error("Application failed to load: {}", lastError); + LOG_E(TAG, "Application failed to load: %s", lastError.c_str()); elfFileData = nullptr; return false; } @@ -104,7 +104,7 @@ class ElfApp final : public App { if (esp_elf_request(&elf, 0, argc, argv) != ESP_OK) { lastError = "Executable returned error code"; - LOGGER.error("{}", lastError); + LOG_E(TAG, "%s", lastError.c_str()); esp_elf_deinit(&elf); elfFileData = nullptr; return false; @@ -115,7 +115,7 @@ class ElfApp final : public App { } void stopElf() { - LOGGER.info("Cleaning up ELF"); + LOG_I(TAG, "Cleaning up ELF"); if (shouldCleanupElf) { esp_elf_deinit(&elf); @@ -163,7 +163,7 @@ class ElfApp final : public App { } void onDestroy(AppContext& appContext) override { - LOGGER.info("Cleaning up app"); + LOG_I(TAG, "Cleaning up app"); if (manifest != nullptr) { if (manifest->onDestroy != nullptr) { manifest->onDestroy(&appContext, data); @@ -222,7 +222,7 @@ void setElfAppParameters( } std::shared_ptr createElfApp(const std::shared_ptr& manifest) { - LOGGER.info("createElfApp"); + LOG_I(TAG, "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 718c68417..f5bf3ba3b 100644 --- a/Tactility/Source/app/addgps/AddGps.cpp +++ b/Tactility/Source/app/addgps/AddGps.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -10,11 +9,12 @@ #include "tactility/drivers/uart_controller.h" #include #include +#include #include namespace tt::app::addgps { -static const auto LOGGER = Logger("AddGps"); +constexpr auto* TAG = "AddGps"; class AddGpsApp final : public App { @@ -50,7 +50,7 @@ class AddGpsApp final : public App { return; } - LOGGER.info("Saving: uart={}, model={}, baud={}", new_configuration.uartName, (uint32_t)new_configuration.model, new_configuration.baudRate); + LOG_I(TAG, "Saving: uart=%s, model=%d, baud=%u", new_configuration.uartName, (int)new_configuration.model, (unsigned)new_configuration.baudRate); auto service = service::gps::findGpsService(); std::vector configurations; diff --git a/Tactility/Source/app/alertdialog/AlertDialog.cpp b/Tactility/Source/app/alertdialog/AlertDialog.cpp index d865aae92..ebfa24b5c 100644 --- a/Tactility/Source/app/alertdialog/AlertDialog.cpp +++ b/Tactility/Source/app/alertdialog/AlertDialog.cpp @@ -3,10 +3,10 @@ #include "Tactility/lvgl/Toolbar.h" #include "Tactility/service/loader/Loader.h" -#include #include #include +#include namespace tt::app::alertdialog { @@ -18,7 +18,7 @@ namespace tt::app::alertdialog { #define PARAMETER_ITEM_CONCATENATION_TOKEN ";;" #define DEFAULT_TITLE "" -static const auto LOGGER = Logger("AlertDialog"); +constexpr auto* TAG = "AlertDialog"; extern const AppManifest manifest; @@ -74,7 +74,7 @@ class AlertDialogApp : public App { void onButtonClicked(lv_event_t* e) { auto index = reinterpret_cast(lv_event_get_user_data(e)); - LOGGER.info("Selected item at index {}", index); + LOG_I(TAG, "Selected item at index %d", (int)index); auto bundle = std::make_unique(); bundle->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 bc7cf9193..7410eead0 100644 --- a/Tactility/Source/app/apphub/AppHubApp.cpp +++ b/Tactility/Source/app/apphub/AppHubApp.cpp @@ -5,20 +5,20 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include namespace tt::app::apphub { -static const auto LOGGER = Logger("AppHub"); +constexpr auto* TAG = "AppHub"; extern const AppManifest manifest; @@ -57,7 +57,7 @@ class AppHubApp final : public App { } void onRefreshSuccess() { - LOGGER.info("Request success"); + LOG_I(TAG, "Request success"); auto lock = lvgl::getSyncLock()->asScopedLock(); lock.lock(); @@ -65,7 +65,7 @@ class AppHubApp final : public App { } void onRefreshError(const char* error) { - LOGGER.error("Request failed: {}", error); + LOG_E(TAG, "Request failed: %s", error); auto lock = lvgl::getSyncLock()->asScopedLock(); lock.lock(); @@ -108,7 +108,7 @@ class AppHubApp final : public App { lv_obj_set_size(list, LV_PCT(100), LV_SIZE_CONTENT); for (int i = 0; i < entries.size(); i++) { auto& entry = entries[i]; - LOGGER.info("Adding {}", entry.appName.c_str()); + LOG_I(TAG, "Adding %s", entry.appName.c_str()); const char* icon = findAppManifestById(entry.appId) != nullptr ? LV_SYMBOL_OK : nullptr; auto* entry_button = lv_list_add_button(list, icon, entry.appName.c_str()); auto int_as_voidptr = reinterpret_cast(i); diff --git a/Tactility/Source/app/apphub/AppHubEntry.cpp b/Tactility/Source/app/apphub/AppHubEntry.cpp index 8f291f738..f9179c01b 100644 --- a/Tactility/Source/app/apphub/AppHubEntry.cpp +++ b/Tactility/Source/app/apphub/AppHubEntry.cpp @@ -1,11 +1,12 @@ #include #include #include -#include + +#include namespace tt::app::apphub { -static const auto LOGGER = Logger("AppHubJson"); +constexpr auto* TAG = "AppHubJson"; static bool parseEntry(const cJSON* object, AppHubEntry& entry) { const json::Reader reader(object); @@ -25,21 +26,21 @@ bool parseJson(const std::string& filePath, std::vector& entries) { auto data = file::readString(filePath); if (data == nullptr) { - LOGGER.error("Failed to read {}", filePath); + LOG_E(TAG, "Failed to read %s", filePath.c_str()); return false; } auto data_ptr = reinterpret_cast(data.get()); auto* json = cJSON_Parse(data_ptr); if (json == nullptr) { - LOGGER.error("Failed to parse {}", filePath); + LOG_E(TAG, "Failed to parse %s", filePath.c_str()); return false; } const cJSON* apps_json = cJSON_GetObjectItemCaseSensitive(json, "apps"); if (!cJSON_IsArray(apps_json)) { cJSON_Delete(json); - LOGGER.error("apps is not an array"); + LOG_E(TAG, "apps is not an array"); return false; } @@ -49,7 +50,7 @@ bool parseJson(const std::string& filePath, std::vector& entries) { auto& entry = entries.at(i); auto* entry_json = cJSON_GetArrayItem(apps_json, i); if (!parseEntry(entry_json, entry)) { - LOGGER.error("Failed to read entry"); + LOG_E(TAG, "Failed to read entry"); cJSON_Delete(json); return false; } diff --git a/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp b/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp index 36b1a854e..aafd98913 100644 --- a/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp +++ b/Tactility/Source/app/apphubdetails/AppHubDetailsApp.cpp @@ -5,18 +5,18 @@ #include #include #include -#include #include #include #include #include #include +#include #include namespace tt::app::apphubdetails { -static const auto LOGGER = Logger("AppHubDetails"); +constexpr auto* TAG = "AppHubDetails"; extern const AppManifest manifest; @@ -85,7 +85,7 @@ class AppHubDetailsApp final : public App { } void uninstallApp() { - LOGGER.info("Uninstall"); + LOG_I(TAG, "Uninstall"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); @@ -110,9 +110,9 @@ class AppHubDetailsApp final : public App { install(temp_file_path); if (!file::deleteFile(temp_file_path)) { - LOGGER.warn("Failed to remove {}", temp_file_path); + LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str()); } else { - LOGGER.info("Deleted temporary file {}", temp_file_path); + LOG_I(TAG, "Deleted temporary file %s", temp_file_path.c_str()); } lvgl::getSyncLock()->lock(); @@ -120,18 +120,18 @@ class AppHubDetailsApp final : public App { lvgl::getSyncLock()->unlock(); }, [temp_file_path](const char* errorMessage) { - LOGGER.error("Download failed: {}", errorMessage); + LOG_E(TAG, "Download failed: %s", errorMessage); alertdialog::start("Error", "Failed to install app"); if (file::isFile(temp_file_path) && !file::deleteFile(temp_file_path.c_str())) { - LOGGER.warn("Failed to remove {}", temp_file_path); + LOG_W(TAG, "Failed to remove %s", temp_file_path.c_str()); } } ); } void installApp() { - LOGGER.info("Install"); + LOG_I(TAG, "Install"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); @@ -141,15 +141,15 @@ class AppHubDetailsApp final : public App { } void updateApp() { - LOGGER.info("Update"); + LOG_I(TAG, "Update"); lvgl::getSyncLock()->lock(); lv_obj_remove_flag(spinner, LV_OBJ_FLAG_HIDDEN); lvgl::getSyncLock()->unlock(); - LOGGER.info("Removing previous version"); + LOG_I(TAG, "Removing previous version"); uninstall(entry.appId); - LOGGER.info("Installing new version"); + LOG_I(TAG, "Installing new version"); doInstall(); } @@ -175,13 +175,13 @@ class AppHubDetailsApp final : public App { void onCreate(AppContext& appContext) override { auto parameters = appContext.getParameters(); if (parameters == nullptr) { - LOGGER.error("No parameters"); + LOG_E(TAG, "No parameters"); stop(); return; } if (!fromBundle(*parameters.get(), entry)) { - LOGGER.error("Invalid parameters"); + LOG_E(TAG, "Invalid parameters"); stop(); } } diff --git a/Tactility/Source/app/apwebserver/ApWebServer.cpp b/Tactility/Source/app/apwebserver/ApWebServer.cpp index b25cb4dda..02525f651 100644 --- a/Tactility/Source/app/apwebserver/ApWebServer.cpp +++ b/Tactility/Source/app/apwebserver/ApWebServer.cpp @@ -1,6 +1,5 @@ #ifdef ESP_PLATFORM -#include #include #include #include @@ -8,10 +7,11 @@ #include #include +#include namespace tt::app::apwebserver { -static const auto LOGGER = tt::Logger("ApWebServerApp"); +constexpr auto* TAG = "ApWebServerApp"; class ApWebServerApp final : public App { lv_obj_t* labelSsidValue = nullptr; @@ -91,7 +91,7 @@ class ApWebServerApp final : public App { // Apply settings and start services getMainDispatcher().dispatch([apSettings] { if (!settings::webserver::save(apSettings)) { - LOGGER.error("Failed to save AP settings"); + LOG_E(TAG, "Failed to save AP settings"); return; } service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged); @@ -106,13 +106,13 @@ class ApWebServerApp final : public App { getMainDispatcher().dispatch([copy, webServerChanged] { if (!settings::webserver::save(copy)) { - LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot"); + LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot"); } service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged); if (webServerChanged) { - LOGGER.info("WebServer {}", copy.webServerEnabled ? "enabling..." : "disabling..."); + LOG_I(TAG, "WebServer %s", copy.webServerEnabled ? "enabling..." : "disabling..."); service::webserver::setWebServerEnabled(copy.webServerEnabled); } }); diff --git a/Tactility/Source/app/boot/Boot.cpp b/Tactility/Source/app/boot/Boot.cpp index 5dc0d958b..9e750100b 100644 --- a/Tactility/Source/app/boot/Boot.cpp +++ b/Tactility/Source/app/boot/Boot.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include #include @@ -17,6 +16,7 @@ #include #include +#include #include @@ -31,7 +31,7 @@ namespace tt::app::boot { -static const auto LOGGER = Logger("Boot"); +constexpr auto* TAG = "Boot"; extern const AppManifest manifest; @@ -67,17 +67,17 @@ class BootApp : public App { if (settings::display::load(settings)) { if (hal_display->getGammaCurveCount() > 0) { hal_display->setGammaCurve(settings.gammaCurve); - LOGGER.info("Gamma curve {}", settings.gammaCurve); + LOG_I(TAG, "Gamma curve %d", settings.gammaCurve); } } else { settings = settings::display::getDefault(); } if (hal_display->supportsBacklightDuty()) { - LOGGER.info("Backlight {}", settings.backlightDuty); + LOG_I(TAG, "Backlight %d", settings.backlightDuty); hal_display->setBacklightDuty(settings.backlightDuty); } else { - LOGGER.info("No backlight"); + LOG_I(TAG, "No backlight"); } } @@ -86,17 +86,17 @@ class BootApp : public App { return false; } - LOGGER.info("Rebooting into mass storage device mode"); + LOG_I(TAG, "Rebooting into mass storage device mode"); auto mode = hal::usb::getUsbBootMode(); // Get mode before reset hal::usb::resetUsbBootMode(); if (mode == hal::usb::BootMode::Flash) { if (!hal::usb::startMassStorageWithFlash(true)) { - LOGGER.error("Unable to start flash mass storage"); + LOG_E(TAG, "Unable to start flash mass storage"); return false; } } else if (mode == hal::usb::BootMode::Sdmmc) { if (!hal::usb::startMassStorageWithSdmmc(true)) { - LOGGER.error("Unable to start SD mass storage"); + LOG_E(TAG, "Unable to start SD mass storage"); return false; } } @@ -114,7 +114,7 @@ class BootApp : public App { } static int32_t bootThreadCallback() { - LOGGER.info("Starting boot thread"); + LOG_I(TAG, "Starting boot thread"); const auto start_time = kernel::getTicks(); // Give the UI some time to redraw @@ -124,20 +124,20 @@ class BootApp : public App { kernel::delayMillis(10); // TODO: Support for multiple displays - LOGGER.info("Setup display"); + LOG_I(TAG, "Setup display"); setupDisplay(); // Set backlight prepareFileSystems(); #ifdef CONFIG_TT_USER_DATA_LOCATION_SD std::string sd_path; if (!findFirstMountedSdCardPath(sd_path)) { - LOGGER.error("SD card not found"); + LOG_E(TAG, "SD card not found"); sdCardMissing = true; } #endif if (!setupUsbBootMode()) { - LOGGER.info("initFromBootApp"); + LOG_I(TAG, "initFromBootApp"); registerApps(); waitForMinimalSplashDuration(start_time); // When SD card is missing, wait for dialog result @@ -147,7 +147,7 @@ class BootApp : public App { // This event will likely block as other systems are initialized // e.g. Wi-Fi reads AP configs from SD card - LOGGER.info("Publish event"); + LOG_I(TAG, "Publish event"); kernel::publishSystemEvent(kernel::SystemEvent::BootSplash); return 0; @@ -162,13 +162,13 @@ class BootApp : public App { // When boot properties didn't specify an override, return default if (boot_properties.launcherAppId.empty()) { - LOGGER.error("Failed to load launcher configuration, or launcher not configured"); + LOG_E(TAG, "Failed to load launcher configuration, or launcher not configured"); return CONFIG_TT_LAUNCHER_APP_ID; } // If the app in the boot.properties does not exist, return default if (findAppManifestById(boot_properties.launcherAppId) == nullptr) { - LOGGER.error("Launcher app {} not found", boot_properties.launcherAppId); + LOG_E(TAG, "Launcher app %s not found", boot_properties.launcherAppId.c_str()); return CONFIG_TT_LAUNCHER_APP_ID; } @@ -239,7 +239,7 @@ class BootApp : public App { logo = isUsbBootSplash ? "logo_usb.png" : "logo.png"; } const auto logo_path = lvgl::PATH_PREFIX + paths->getAssetsPath(logo); - LOGGER.info("{}", logo_path); + LOG_I(TAG, "%s", logo_path.c_str()); lv_image_set_src(image, logo_path.c_str()); #ifdef ESP_PLATFORM diff --git a/Tactility/Source/app/btmanage/BtManage.cpp b/Tactility/Source/app/btmanage/BtManage.cpp index fd31259a9..a581977ec 100644 --- a/Tactility/Source/app/btmanage/BtManage.cpp +++ b/Tactility/Source/app/btmanage/BtManage.cpp @@ -1,18 +1,18 @@ #include #include +#include +#include #include #include -#include -#include #include -#include +#include #include namespace tt::app::btmanage { -static const auto LOGGER = Logger("BtManage"); +constexpr auto* TAG = "BtManage"; extern const AppManifest manifest; @@ -83,7 +83,7 @@ void BtManage::requestViewUpdate() { view.update(); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } unlock(); @@ -91,7 +91,7 @@ void BtManage::requestViewUpdate() { void BtManage::onBtEvent(const struct BtEvent& event) { auto radio_state = bluetooth::getRadioState(); - LOGGER.info("Update with state {}", bluetooth::radioStateToString(radio_state)); + LOG_I(TAG, "Update with state %s", bluetooth::radioStateToString(radio_state)); getState().setRadioState(radio_state); switch (event.type) { case BT_EVENT_SCAN_STARTED: @@ -162,10 +162,10 @@ void BtManage::onShow(AppContext& app, lv_obj_t* parent) { auto radio_state = bluetooth::getRadioState(); bool can_scan = radio_state == bluetooth::RadioState::On; - LOGGER.info("Radio: {}, Scanning: {}, Can scan: {}", + LOG_I(TAG, "Radio: %s, Scanning: %d, Can scan: %d", bluetooth::radioStateToString(radio_state), - dev ? bluetooth_is_scanning(dev) : false, - can_scan); + (int)(dev ? bluetooth_is_scanning(dev) : false), + (int)can_scan); if (can_scan && dev && !bluetooth_is_scanning(dev)) { bluetooth_scan_start(dev); } diff --git a/Tactility/Source/app/btmanage/View.cpp b/Tactility/Source/app/btmanage/View.cpp index 81e7df51b..8003ffb17 100644 --- a/Tactility/Source/app/btmanage/View.cpp +++ b/Tactility/Source/app/btmanage/View.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include diff --git a/Tactility/Source/app/btpeersettings/BtPeerSettings.cpp b/Tactility/Source/app/btpeersettings/BtPeerSettings.cpp index 5afa21f54..a178c2900 100644 --- a/Tactility/Source/app/btpeersettings/BtPeerSettings.cpp +++ b/Tactility/Source/app/btpeersettings/BtPeerSettings.cpp @@ -3,7 +3,6 @@ #include "tactility/device.h" #include -#include #include #include #include @@ -15,12 +14,13 @@ #include #include #include +#include #include namespace tt::app::btpeersettings { -static const auto LOGGER = Logger("BtPeerSettings"); +constexpr auto* TAG = "BtPeerSettings"; extern const AppManifest manifest; @@ -77,7 +77,7 @@ class BtPeerSettings : public App { if (bluetooth::settings::load(self->addrHex, device)) { device.autoConnect = is_on; if (!bluetooth::settings::save(device)) { - LOGGER.error("Failed to save auto-connect setting"); + LOG_E(TAG, "Failed to save auto-connect setting"); } } } @@ -88,7 +88,7 @@ class BtPeerSettings : public App { updateViews(); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } } diff --git a/Tactility/Source/app/chat/ChatApp.cpp b/Tactility/Source/app/chat/ChatApp.cpp index 28ecbfd17..25fda35dd 100644 --- a/Tactility/Source/app/chat/ChatApp.cpp +++ b/Tactility/Source/app/chat/ChatApp.cpp @@ -8,18 +8,18 @@ #include #include -#include #include #include #include #include +#include #include #include namespace tt::app::chat { -static const auto LOGGER = Logger("ChatApp"); +constexpr auto* TAG = "ChatApp"; static constexpr uint8_t BROADCAST_ADDRESS[ESP_NOW_ETH_ALEN] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; void ChatApp::enableEspNow() { @@ -98,12 +98,12 @@ void ChatApp::sendMessage(const std::string& text) { std::vector wireMsg; if (!serializeTextMessage(settings.senderId, BROADCAST_ID, nickname, channel, text, wireMsg)) { - LOGGER.error("Failed to serialize message"); + LOG_E(TAG, "Failed to serialize message"); return; } if (!service::espnow::send(BROADCAST_ADDRESS, wireMsg.data(), wireMsg.size())) { - LOGGER.error("Failed to send message"); + LOG_E(TAG, "Failed to send message"); return; } @@ -144,7 +144,7 @@ void ChatApp::applySettings(const std::string& nickname, const std::string& keyH } settings.hasEncryptionKey = true; } else { - LOGGER.warn("Invalid hex characters in encryption key"); + LOG_W(TAG, "Invalid hex characters in encryption key"); } } else if (keyHex.empty()) { if (settings.hasEncryptionKey) { @@ -153,7 +153,7 @@ void ChatApp::applySettings(const std::string& nickname, const std::string& keyH needRestart = true; } } else { - LOGGER.warn("Key must be exactly {} hex characters, got {}", ESP_NOW_KEY_LEN * 2, keyHex.size()); + LOG_W(TAG, "Key must be exactly %d hex characters, got %d", (int)(ESP_NOW_KEY_LEN * 2), (int)keyHex.size()); } state.setLocalNickname(settings.nickname); diff --git a/Tactility/Source/app/chat/ChatSettings.cpp b/Tactility/Source/app/chat/ChatSettings.cpp index dabe17877..c972f2b87 100644 --- a/Tactility/Source/app/chat/ChatSettings.cpp +++ b/Tactility/Source/app/chat/ChatSettings.cpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include @@ -20,11 +19,12 @@ #include #include #include +#include #include namespace tt::app::chat { -static const auto LOGGER = Logger("ChatSettings"); +constexpr auto* TAG = "ChatSettings"; static std::string getSettingsFilePath() { return getUserDataPath() + "/settings/chat.properties"; @@ -52,7 +52,7 @@ static std::string toHexString(const uint8_t* data, size_t length) { static bool readHex(const std::string& input, uint8_t* buffer, size_t length) { if (input.size() != length * 2) { - LOGGER.error("readHex() length mismatch"); + LOG_E(TAG, "readHex() length mismatch"); return false; } @@ -63,7 +63,7 @@ static bool readHex(const std::string& input, uint8_t* buffer, size_t length) { char* endptr; unsigned long val = strtoul(hex, &endptr, 16); if (endptr != hex + 2) { - LOGGER.error("readHex() invalid hex character"); + LOG_E(TAG, "readHex() invalid hex character"); return false; } buffer[i] = static_cast(val); @@ -77,7 +77,7 @@ static bool encryptKey(const uint8_t key[ESP_NOW_KEY_LEN], std::string& hexOutpu uint8_t encrypted[ESP_NOW_KEY_LEN]; if (crypt::encrypt(iv, key, encrypted, ESP_NOW_KEY_LEN) != 0) { - LOGGER.error("Failed to encrypt key"); + LOG_E(TAG, "Failed to encrypt key"); return false; } @@ -99,7 +99,7 @@ static bool decryptKey(const std::string& hexInput, uint8_t key[ESP_NOW_KEY_LEN] crypt::getIv(IV_SEED, std::strlen(IV_SEED), iv); if (crypt::decrypt(iv, encrypted, key, ESP_NOW_KEY_LEN) != 0) { - LOGGER.error("Failed to decrypt key"); + LOG_E(TAG, "Failed to decrypt key"); return false; } return true; @@ -188,7 +188,7 @@ bool saveSettings(const ChatSettingsData& settings) { auto settings_path = getSettingsFilePath(); if (!file::findOrCreateParentDirectory(settings_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", settings_path); + LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str()); return false; } return file::savePropertiesFile(settings_path, map); diff --git a/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp b/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp index 182009d04..bfb9e482e 100644 --- a/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp +++ b/Tactility/Source/app/crashdiagnostics/CrashDiagnostics.cpp @@ -4,16 +4,16 @@ #include #include #include -#include #include #include #include #include +#include namespace tt::app::crashdiagnostics { -static const auto LOGGER = Logger("CrashDiagnostics"); +constexpr auto* TAG = "CrashDiagnostics"; extern const AppManifest manifest; @@ -44,38 +44,38 @@ class CrashDiagnosticsApp : public App { lv_obj_align(bottom_label, LV_ALIGN_BOTTOM_MID, 0, -2); std::string url = getUrlFromCrashData(); - LOGGER.info("{}", url); + LOG_I(TAG, "%s", url.c_str()); size_t url_length = url.length(); int qr_version; if (!getQrVersionForBinaryDataLength(url_length, qr_version)) { - LOGGER.error("QR is too large"); + LOG_E(TAG, "QR is too large"); stop(manifest.appId); return; } - LOGGER.info("QR version {} (length: {})", qr_version, url_length); + LOG_I(TAG, "QR version %d (length: %d)", qr_version, (int)url_length); auto qrcodeData = std::make_shared(qrcode_getBufferSize(qr_version)); if (qrcodeData == nullptr) { - LOGGER.error("Failed to allocate QR buffer"); + LOG_E(TAG, "Failed to allocate QR buffer"); stop(manifest.appId); return; } QRCode qrcode; - LOGGER.info("QR init text"); + LOG_I(TAG, "QR init text"); if (qrcode_initText(&qrcode, qrcodeData.get(), qr_version, ECC_LOW, url.c_str()) != 0) { - LOGGER.error("QR init text failed"); + LOG_E(TAG, "QR init text failed"); stop(manifest.appId); return; } - LOGGER.info("QR size: {}", qrcode.size); + LOG_I(TAG, "QR size: %d", qrcode.size); // Calculate QR dot size int32_t top_label_height = lv_obj_get_height(top_label) + 2; int32_t bottom_label_height = lv_obj_get_height(bottom_label) + 2; - LOGGER.info("Create canvas"); + LOG_I(TAG, "Create canvas"); int32_t available_height = parent_height - top_label_height - bottom_label_height; int32_t available_width = lv_display_get_horizontal_resolution(display); int32_t smallest_size = std::min(available_height, available_width); @@ -85,7 +85,7 @@ class CrashDiagnosticsApp : public App { } else if (qrcode.size <= smallest_size) { pixel_size = 1; } else { - LOGGER.error("QR code won't fit screen"); + LOG_E(TAG, "QR code won't fit screen"); stop(manifest.appId); return; } @@ -97,10 +97,10 @@ class CrashDiagnosticsApp : public App { lv_obj_set_content_height(canvas, qrcode.size * pixel_size); lv_obj_set_content_width(canvas, qrcode.size * pixel_size); - LOGGER.info("Create draw buffer"); + LOG_I(TAG, "Create draw buffer"); auto* draw_buf = lv_draw_buf_create(pixel_size * qrcode.size, pixel_size * qrcode.size, LV_COLOR_FORMAT_RGB565, LV_STRIDE_AUTO); if (draw_buf == nullptr) { - LOGGER.error("Failed to allocate draw buffer"); + LOG_E(TAG, "Failed to allocate draw buffer"); stop(manifest.appId); return; } diff --git a/Tactility/Source/app/development/Development.cpp b/Tactility/Source/app/development/Development.cpp index aa5c96563..b96241bba 100644 --- a/Tactility/Source/app/development/Development.cpp +++ b/Tactility/Source/app/development/Development.cpp @@ -7,12 +7,12 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -20,7 +20,7 @@ namespace tt::app::development { -static const auto LOGGER = Logger("Development"); +constexpr auto* TAG = "Development"; extern const AppManifest manifest; class DevelopmentApp final : public App { @@ -87,7 +87,7 @@ class DevelopmentApp final : public App { void onCreate(AppContext& appContext) override { service = service::development::findService(); if (service == nullptr) { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); stop(manifest.appId); } } diff --git a/Tactility/Source/app/display/Display.cpp b/Tactility/Source/app/display/Display.cpp index 941777325..4dcb4a1b1 100644 --- a/Tactility/Source/app/display/Display.cpp +++ b/Tactility/Source/app/display/Display.cpp @@ -6,7 +6,6 @@ #include #endif -#include #include #include #include @@ -14,11 +13,12 @@ #include #include +#include #include namespace tt::app::display { -static const auto LOGGER = Logger("Display"); +constexpr auto* TAG = "Display"; static std::shared_ptr getHalDisplay() { return hal::findFirstDevice(hal::Device::Type::Display); @@ -74,7 +74,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); - LOGGER.info("Selected {}", selected_index); + LOG_I(TAG, "Selected %u", (unsigned)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 033746e3c..6788d421b 100644 --- a/Tactility/Source/app/files/State.cpp +++ b/Tactility/Source/app/files/State.cpp @@ -1,11 +1,11 @@ #include -#include -#include -#include #include #include +#include +#include #include +#include #include #include @@ -14,7 +14,7 @@ namespace tt::app::files { -static const auto LOGGER = Logger("Files"); +constexpr auto* TAG = "Files"; State::State() { if (kernel::getPlatform() == kernel::PlatformSimulator) { @@ -22,7 +22,7 @@ State::State() { if (getcwd(cwd, sizeof(cwd)) != nullptr) { setEntriesForPath(cwd); } else { - LOGGER.error("Failed to get current work directory files"); + LOG_E(TAG, "Failed to get current work directory files"); setEntriesForPath("/"); } } else { @@ -37,11 +37,11 @@ std::string State::getSelectedChildPath() const { bool State::setEntriesForPath(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(100)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath"); + LOG_E(TAG, "Mutex acquisition timeout (%s)", "setEntriesForPath"); return false; } - LOGGER.info("Changing path: {} -> {}", current_path, path); + LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str()); /** * On PC, the root entry point ("/") is a folder. @@ -49,7 +49,7 @@ bool State::setEntriesForPath(const std::string& path) { */ bool get_mount_points = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/"); if (get_mount_points) { - LOGGER.info("Setting custom root"); + LOG_I(TAG, "Setting custom root"); dir_entries = file::getFileSystemDirents(); current_path = path; selected_child_entry = ""; @@ -59,13 +59,13 @@ bool State::setEntriesForPath(const std::string& path) { dir_entries.clear(); int count = file::scandir(path, dir_entries, &file::direntFilterDotEntries, file::direntSortAlphaAndType); if (count >= 0) { - LOGGER.info("{} has {} entries", path, count); + LOG_I(TAG, "%s has %d entries", path.c_str(), count); current_path = path; selected_child_entry = ""; action = ActionNone; return true; } else { - LOGGER.error("Failed to fetch entries for {}", path); + LOG_E(TAG, "Failed to fetch entries for %s", path.c_str()); return false; } } @@ -73,7 +73,7 @@ bool State::setEntriesForPath(const std::string& path) { bool State::setEntriesForChildPath(const std::string& childPath) { auto path = file::getChildPath(current_path, childPath); - LOGGER.info("Navigating from {} to {}", current_path, path); + LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str()); return setEntriesForPath(path); } diff --git a/Tactility/Source/app/files/View.cpp b/Tactility/Source/app/files/View.cpp index 37f87444c..a9e8de618 100644 --- a/Tactility/Source/app/files/View.cpp +++ b/Tactility/Source/app/files/View.cpp @@ -2,7 +2,6 @@ #include #include -#include #include #include #include @@ -18,6 +17,7 @@ #include #include +#include #include #include @@ -30,7 +30,7 @@ namespace tt::app::files { -static const auto LOGGER = Logger("Files"); +constexpr auto* TAG = "Files"; // region Callbacks @@ -202,11 +202,11 @@ void View::viewFile(const std::string& path, const std::string& filename) { if (kernel::getPlatform() == kernel::PlatformSimulator) { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) == nullptr) { - LOGGER.error("Failed to get current working directory"); + LOG_E(TAG, "Failed to get current working directory"); return; } if (!file_path.starts_with(cwd)) { - LOGGER.error("Can only work with files in working directory {}", cwd); + LOG_E(TAG, "Can only work with files in working directory %s", cwd); return; } processed_filepath = file_path.substr(strlen(cwd)); @@ -214,7 +214,7 @@ void View::viewFile(const std::string& path, const std::string& filename) { processed_filepath = file_path; } - LOGGER.info("Clicked {}", file_path); + LOG_I(TAG, "Clicked %s", file_path.c_str()); if (isSupportedAppFile(filename)) { #ifdef ESP_PLATFORM @@ -234,7 +234,7 @@ void View::viewFile(const std::string& path, const std::string& filename) { notes::start(processed_filepath.substr(1)); } } else { - LOGGER.warn("Opening files of this type is not supported"); + LOG_W(TAG, "Opening files of this type is not supported"); } onNavigate(); @@ -260,7 +260,7 @@ void View::onDirEntryPressed(uint32_t index) { return; } - LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type); + LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); using namespace tt::file; @@ -273,7 +273,7 @@ void View::onDirEntryPressed(uint32_t index) { break; case TT_DT_LNK: - LOGGER.warn("opening links is not supported"); + LOG_W(TAG, "opening links is not supported"); break; default: @@ -289,7 +289,7 @@ void View::onDirEntryLongPressed(int32_t index) { return; } - LOGGER.info("Long-pressed {} {}", dir_entry.d_name, dir_entry.d_type); + LOG_I(TAG, "Long-pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); if (state->getCurrentPath() == "/") { @@ -310,7 +310,7 @@ void View::onDirEntryLongPressed(int32_t index) { break; case TT_DT_LNK: - LOGGER.warn("Opening links is not supported"); + LOG_W(TAG, "Opening links is not supported"); break; default: @@ -369,7 +369,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) { void View::onNavigateUpPressed() { if (state->getCurrentPath() != "/") { - LOGGER.info("Navigating upwards"); + LOG_I(TAG, "Navigating upwards"); std::string new_absolute_path; if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) { state->setEntriesForPath(new_absolute_path); @@ -381,14 +381,14 @@ void View::onNavigateUpPressed() { void View::onRenamePressed() { std::string entry_name = state->getSelectedChildEntry(); - LOGGER.info("Pending rename {}", entry_name); + LOG_I(TAG, "Pending rename %s", entry_name.c_str()); state->setPendingAction(State::ActionRename); inputdialog::start("Rename", "", entry_name); } void View::onDeletePressed() { std::string file_path = state->getSelectedChildPath(); - LOGGER.info("Pending delete {}", file_path); + LOG_I(TAG, "Pending delete %s", file_path.c_str()); state->setPendingAction(State::ActionDelete); std::string message = "Do you want to delete this?\n" + file_path; const std::vector choices = {"Yes", "No"}; @@ -396,13 +396,13 @@ void View::onDeletePressed() { } void View::onNewFilePressed() { - LOGGER.info("Creating new file"); + LOG_I(TAG, "Creating new file"); state->setPendingAction(State::ActionCreateFile); inputdialog::start("New File", "Enter filename:", ""); } void View::onNewFolderPressed() { - LOGGER.info("Creating new folder"); + LOG_I(TAG, "Creating new folder"); state->setPendingAction(State::ActionCreateFolder); inputdialog::start("New Folder", "Enter folder name:", ""); } @@ -436,11 +436,11 @@ void View::showActionsForMountPoint() { void View::onEjectPressed() { std::string mount_path = state->getSelectedChildPath(); - LOGGER.info("Ejecting {}", mount_path); + LOG_I(TAG, "Ejecting %s", mount_path.c_str()); struct Device* msc_dev = device_find_first_active_by_type(&USB_HOST_MSC_TYPE); if (!msc_dev || !usb_msc_eject(msc_dev, mount_path.c_str())) { - LOGGER.warn("usb_msc_eject: {} not found", mount_path); + LOG_W(TAG, "usb_msc_eject: %s not found", mount_path.c_str()); alertdialog::start("Eject failed", "Could not eject \"" + file::getLastPathSegment(mount_path) + "\"."); } @@ -454,7 +454,7 @@ void View::update(size_t start_index) { auto scoped_lockable = lvgl::getSyncLock()->asScopedLock(); if (!scoped_lockable.lock(lvgl::defaultLockTime)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); + LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl"); return; } @@ -580,20 +580,20 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu } std::string filepath = state->getSelectedChildPath(); - LOGGER.info("Result for {}", filepath); + LOG_I(TAG, "Result for %s", filepath.c_str()); switch (state->getPendingAction()) { case State::ActionDelete: { if (alertdialog::getResultIndex(*bundle) == 0) { if (file::isDirectory(filepath)) { if (!file::deleteRecursively(filepath)) { - LOGGER.warn("Failed to delete {}", filepath); + LOG_W(TAG, "Failed to delete %s", filepath.c_str()); } } else if (file::isFile(filepath)) { auto lock = file::getLock(filepath); lock->lock(); if (remove(filepath.c_str()) != 0) { - LOGGER.warn("Failed to delete {}", filepath); + LOG_W(TAG, "Failed to delete %s", filepath.c_str()); } lock->unlock(); } @@ -611,16 +611,16 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu std::string rename_to = file::getChildPath(state->getCurrentPath(), new_name); struct stat st; if (stat(rename_to.c_str(), &st) == 0) { - LOGGER.warn("Rename: destination already exists: \"{}\"", rename_to); + LOG_W(TAG, "Rename: destination already exists: \"%s\"", rename_to.c_str()); lock->unlock(); state->setPendingAction(State::ActionNone); alertdialog::start("Rename failed", "\"" + new_name + "\" already exists."); break; } if (rename(filepath.c_str(), rename_to.c_str()) == 0) { - LOGGER.info("Renamed \"{}\" to \"{}\"", filepath, rename_to); + LOG_I(TAG, "Renamed \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str()); } else { - LOGGER.error("Failed to rename \"{}\" to \"{}\"", filepath, rename_to); + LOG_E(TAG, "Failed to rename \"%s\" to \"%s\"", filepath.c_str(), rename_to.c_str()); } lock->unlock(); @@ -639,7 +639,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu struct stat st; if (stat(new_file_path.c_str(), &st) == 0) { - LOGGER.warn("File already exists: \"{}\"", new_file_path); + LOG_W(TAG, "File already exists: \"%s\"", new_file_path.c_str()); lock->unlock(); break; } @@ -647,9 +647,9 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu FILE* new_file = fopen(new_file_path.c_str(), "w"); if (new_file) { fclose(new_file); - LOGGER.info("Created file \"{}\"", new_file_path); + LOG_I(TAG, "Created file \"%s\"", new_file_path.c_str()); } else { - LOGGER.error("Failed to create file \"{}\"", new_file_path); + LOG_E(TAG, "Failed to create file \"%s\"", new_file_path.c_str()); } lock->unlock(); @@ -668,15 +668,15 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu struct stat st; if (stat(new_folder_path.c_str(), &st) == 0) { - LOGGER.warn("Folder already exists: \"{}\"", new_folder_path); + LOG_W(TAG, "Folder already exists: \"%s\"", new_folder_path.c_str()); lock->unlock(); break; } if (mkdir(new_folder_path.c_str(), 0755) == 0) { - LOGGER.info("Created folder \"{}\"", new_folder_path); + LOG_I(TAG, "Created folder \"%s\"", new_folder_path.c_str()); } else { - LOGGER.error("Failed to create folder \"{}\"", new_folder_path); + LOG_E(TAG, "Failed to create folder \"%s\"", new_folder_path.c_str()); } lock->unlock(); @@ -698,7 +698,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu if (file::deleteRecursively(dst)) { doPaste(clipboard->first, clipboard->second, dst); } else { - LOGGER.error("Overwrite: failed to remove existing destination: \"{}\"", dst); + LOG_E(TAG, "Overwrite: failed to remove existing destination: \"%s\"", dst.c_str()); state->setPendingAction(State::ActionNone); alertdialog::start( "Overwrite failed", @@ -717,7 +717,7 @@ void View::onResult(LaunchId launchId, Result result, std::unique_ptr bu void View::onCopyPressed() { std::string path = state->getSelectedChildPath(); state->setClipboard(path, false); - LOGGER.info("Copied to clipboard: {}", path); + LOG_I(TAG, "Copied to clipboard: %s", path.c_str()); onNavigate(); update(); } @@ -725,7 +725,7 @@ void View::onCopyPressed() { void View::onCutPressed() { std::string path = state->getSelectedChildPath(); state->setClipboard(path, true); - LOGGER.info("Cut to clipboard: {}", path); + LOG_I(TAG, "Cut to clipboard: %s", path.c_str()); onNavigate(); update(); } @@ -744,7 +744,7 @@ void View::onPastePressed() { // between this check and the write inside doPaste. Acceptable on a // single-user embedded device; locking dst instead would be more correct. if (src == dst) { - LOGGER.info("Paste: source and destination are the same path, skipping"); + LOG_I(TAG, "Paste: source and destination are the same path, skipping"); return; } auto lock = file::getLock(src); @@ -783,7 +783,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst) success = true; } else { src_delete_failed = true; - LOGGER.error("Cut: copied \"{}\" to \"{}\" but failed to remove source — manual cleanup required", src, dst); + LOG_E(TAG, "Cut: copied \"%s\" to \"%s\" but failed to remove source — manual cleanup required", src.c_str(), dst.c_str()); } } } @@ -793,7 +793,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst) const std::string filename = file::getLastPathSegment(src); if (success) { - LOGGER.info("{} \"{}\" to \"{}\"", is_cut ? "Moved" : "Copied", src, dst); + LOG_I(TAG, "%s \"%s\" to \"%s\"", is_cut ? "Moved" : "Copied", src.c_str(), dst.c_str()); if (is_cut) { state->clearClipboard(); } @@ -801,7 +801,7 @@ void View::doPaste(const std::string& src, bool is_cut, const std::string& dst) state->setPendingAction(State::ActionNone); // prevent re-trigger on dialog dismiss alertdialog::start("Move incomplete", "\"" + filename + "\" was copied but the original could not be removed.\nPlease delete it manually."); } else { - LOGGER.error("Failed to {} \"{}\" to \"{}\"", is_cut ? "move" : "copy", src, dst); + LOG_E(TAG, "Failed to %s \"%s\" to \"%s\"", is_cut ? "move" : "copy", src.c_str(), dst.c_str()); state->setPendingAction(State::ActionNone); // prevent re-trigger on dialog dismiss alertdialog::start( std::string("Failed to ") + (is_cut ? "move" : "copy"), diff --git a/Tactility/Source/app/fileselection/State.cpp b/Tactility/Source/app/fileselection/State.cpp index 0e2419bd5..840d3294f 100644 --- a/Tactility/Source/app/fileselection/State.cpp +++ b/Tactility/Source/app/fileselection/State.cpp @@ -1,19 +1,19 @@ #include "Tactility/app/fileselection/State.h" #include -#include #include #include #include #include #include +#include #include #include namespace tt::app::fileselection { -static const auto LOGGER = Logger("FileSelection"); +constexpr auto* TAG = "FileSelection"; State::State() { if (kernel::getPlatform() == kernel::PlatformSimulator) { @@ -21,7 +21,7 @@ State::State() { if (getcwd(cwd, sizeof(cwd)) != nullptr) { setEntriesForPath(cwd); } else { - LOGGER.error("Failed to get current work directory files"); + LOG_E(TAG, "Failed to get current work directory files"); setEntriesForPath("/"); } } else { @@ -34,11 +34,11 @@ std::string State::getSelectedChildPath() const { } bool State::setEntriesForPath(const std::string& path) { - LOGGER.info("Changing path: {} -> {}", current_path, path); + LOG_I(TAG, "Changing path: %s -> %s", current_path.c_str(), path.c_str()); auto lock = mutex.asScopedLock(); if (!lock.lock(100)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "setEntriesForPath"); + LOG_E(TAG, "Mutex acquisition timeout (%s)", "setEntriesForPath"); return false; } @@ -48,7 +48,7 @@ bool State::setEntriesForPath(const std::string& path) { */ bool show_custom_root = (kernel::getPlatform() == kernel::PlatformEsp) && (path == "/"); if (show_custom_root) { - LOGGER.info("Setting custom root"); + LOG_I(TAG, "Setting custom root"); dir_entries = file::getFileSystemDirents(); current_path = path; selected_child_entry = ""; @@ -57,12 +57,12 @@ bool State::setEntriesForPath(const std::string& path) { dir_entries.clear(); int count = file::scandir(path, dir_entries, &file::direntFilterDotEntries, file::direntSortAlphaAndType); if (count >= 0) { - LOGGER.info("{} has {} entries", path, count); + LOG_I(TAG, "%s has %d entries", path.c_str(), count); current_path = path; selected_child_entry = ""; return true; } else { - LOGGER.error("Failed to fetch entries for {}", path); + LOG_E(TAG, "Failed to fetch entries for %s", path.c_str()); return false; } } @@ -70,7 +70,7 @@ bool State::setEntriesForPath(const std::string& path) { bool State::setEntriesForChildPath(const std::string& childPath) { auto path = file::getChildPath(current_path, childPath); - LOGGER.info("Navigating from {} to {}", current_path, path); + LOG_I(TAG, "Navigating from %s to %s", current_path.c_str(), path.c_str()); return setEntriesForPath(path); } diff --git a/Tactility/Source/app/fileselection/View.cpp b/Tactility/Source/app/fileselection/View.cpp index f2cf15989..10fddc689 100644 --- a/Tactility/Source/app/fileselection/View.cpp +++ b/Tactility/Source/app/fileselection/View.cpp @@ -1,15 +1,15 @@ #include #include -#include #include #include #include -#include #include #include #include #include +#include +#include #include #include @@ -20,7 +20,7 @@ namespace tt::app::fileselection { -const static Logger LOGGER = Logger("FileSelection"); +constexpr auto* TAG = "FileSelection"; // region Callbacks @@ -47,11 +47,11 @@ void View::onTapFile(const std::string& path, const std::string& filename) { if (kernel::getPlatform() == kernel::PlatformSimulator) { char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) == nullptr) { - LOGGER.error("Failed to get current working directory"); + LOG_E(TAG, "Failed to get current working directory"); return; } if (!file_path.starts_with(cwd)) { - LOGGER.error("Can only work with files in working directory {}", cwd); + LOG_E(TAG, "Can only work with files in working directory %s", cwd); return; } processed_filepath = file_path.substr(strlen(cwd)); @@ -59,7 +59,7 @@ void View::onTapFile(const std::string& path, const std::string& filename) { processed_filepath = file_path; } - LOGGER.info("Clicked {}", processed_filepath); + LOG_I(TAG, "Clicked %s", processed_filepath.c_str()); lv_textarea_set_text(path_textarea, processed_filepath.c_str()); } @@ -67,7 +67,7 @@ void View::onTapFile(const std::string& path, const std::string& filename) { void View::onDirEntryPressed(uint32_t index) { dirent dir_entry; if (state->getDirent(index, dir_entry)) { - LOGGER.info("Pressed {} {}", dir_entry.d_name, dir_entry.d_type); + LOG_I(TAG, "Pressed %s %d", dir_entry.d_name, (int)dir_entry.d_type); state->setSelectedChildEntry(dir_entry.d_name); using namespace tt::file; switch (dir_entry.d_type) { @@ -78,7 +78,7 @@ void View::onDirEntryPressed(uint32_t index) { update(); break; case TT_DT_LNK: - LOGGER.warn("Opening links is not supported"); + LOG_W(TAG, "Opening links is not supported"); break; case TT_DT_REG: onTapFile(state->getCurrentPath(), dir_entry.d_name); @@ -96,7 +96,7 @@ void View::onSelectButtonPressed(lv_event_t* event) { auto* view = static_cast(lv_event_get_user_data(event)); const char* path = lv_textarea_get_text(view->path_textarea); if (path == nullptr || strlen(path) == 0) { - LOGGER.warn("Select pressed, but not path found in textarea"); + LOG_W(TAG, "Select pressed, but not path found in textarea"); return; } @@ -140,7 +140,7 @@ void View::createDirEntryWidget(lv_obj_t* list, dirent& dir_entry) { void View::onNavigateUpPressed() { if (state->getCurrentPath() != "/") { - LOGGER.info("Navigating upwards"); + LOG_I(TAG, "Navigating upwards"); std::string new_absolute_path; if (string::getPathParent(state->getCurrentPath(), new_absolute_path)) { state->setEntriesForPath(new_absolute_path); @@ -161,7 +161,7 @@ void View::update() { state->withEntries([this](const std::vector& entries) { for (auto entry : entries) { - LOGGER.debug("Entry: {} {}", entry.d_name, entry.d_type); + LOG_D(TAG, "Entry: %s %d", entry.d_name, (int)entry.d_type); createDirEntryWidget(dir_entry_list, entry); } }); @@ -172,7 +172,7 @@ void View::update() { lv_obj_remove_flag(navigate_up_button, LV_OBJ_FLAG_HIDDEN); } } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "lvgl"); + LOG_E(TAG, "Mutex acquisition timeout (%s)", "lvgl"); } } diff --git a/Tactility/Source/app/gpssettings/GpsSettings.cpp b/Tactility/Source/app/gpssettings/GpsSettings.cpp index 9c3e7d8e6..7766b1b96 100644 --- a/Tactility/Source/app/gpssettings/GpsSettings.cpp +++ b/Tactility/Source/app/gpssettings/GpsSettings.cpp @@ -5,11 +5,11 @@ #include #include #include -#include #include #include #include +#include #include #include @@ -26,7 +26,7 @@ extern const AppManifest manifest; class GpsSettingsApp final : public App { - const Logger logger = Logger("GpsSettings"); + static constexpr auto* TAG = "GpsSettings"; std::unique_ptr timer; std::shared_ptr appReference = std::make_shared(this); @@ -101,7 +101,7 @@ class GpsSettingsApp final : public App { std::vector configurations; auto gps_service = service::gps::findGpsService(); if (gps_service && gps_service->getGpsConfigurations(configurations)) { - Logger("GpsSettings").info("Found service and configs {} {}", index, configurations.size()); + LOG_I(TAG, "Found service and configs %d %d", index, (int)configurations.size()); if (index < configurations.size()) { if (gps_service->removeGpsConfiguration(configurations[index])) { app->updateViews(); @@ -163,7 +163,7 @@ class GpsSettingsApp final : public App { // Update toolbar switch (state) { case service::gps::State::OnPending: - logger.debug("OnPending"); + LOG_D(TAG, "OnPending"); lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); lv_obj_add_state(switchWidget, LV_STATE_CHECKED); lv_obj_add_state(switchWidget, LV_STATE_DISABLED); @@ -172,7 +172,7 @@ class GpsSettingsApp final : public App { lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::On: - logger.debug("On"); + LOG_D(TAG, "On"); lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); lv_obj_add_state(switchWidget, LV_STATE_CHECKED); lv_obj_remove_state(switchWidget, LV_STATE_DISABLED); @@ -181,7 +181,7 @@ class GpsSettingsApp final : public App { lv_obj_add_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::OffPending: - logger.debug("OffPending"); + LOG_D(TAG, "OffPending"); lv_obj_remove_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_state(switchWidget, LV_STATE_CHECKED); lv_obj_add_state(switchWidget, LV_STATE_DISABLED); @@ -190,7 +190,7 @@ class GpsSettingsApp final : public App { lv_obj_remove_flag(addGpsWrapper, LV_OBJ_FLAG_HIDDEN); break; case service::gps::State::Off: - logger.debug("Off"); + LOG_D(TAG, "Off"); lv_obj_add_flag(spinnerWidget, LV_OBJ_FLAG_HIDDEN); lv_obj_remove_state(switchWidget, LV_STATE_CHECKED); lv_obj_remove_state(switchWidget, LV_STATE_DISABLED); diff --git a/Tactility/Source/app/i2cscanner/I2cScanner.cpp b/Tactility/Source/app/i2cscanner/I2cScanner.cpp index e053bee73..3d7ffa807 100644 --- a/Tactility/Source/app/i2cscanner/I2cScanner.cpp +++ b/Tactility/Source/app/i2cscanner/I2cScanner.cpp @@ -1,19 +1,19 @@ #include #include -#include -#include -#include #include -#include -#include #include #include -#include #include +#include +#include +#include +#include +#include #include +#include #include namespace tt::app::i2cscanner { @@ -22,7 +22,7 @@ extern const AppManifest manifest; class I2cScannerApp final : public App { - const Logger logger = Logger("I2cScanner"); + static constexpr auto* TAG = "I2cScanner"; static constexpr auto* START_SCAN_TEXT = "Scan"; static constexpr auto* STOP_SCAN_TEXT = "Stop scan"; @@ -190,7 +190,7 @@ bool I2cScannerApp::getPort(struct Device** outPort) { mutex.unlock(); return true; } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "getPort"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "getPort"); return false; } } @@ -201,7 +201,7 @@ bool I2cScannerApp::addAddressToList(uint8_t address) { mutex.unlock(); return true; } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "addAddressToList"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "addAddressToList"); return false; } } @@ -217,24 +217,24 @@ bool I2cScannerApp::shouldStopScanTimer() { } void I2cScannerApp::onScanTimer() { - logger.info("Scan thread started"); + LOG_I(TAG, "Scan thread started"); Device* safe_port; if (!getPort(&safe_port)) { - logger.error("Failed to get I2C port"); + LOG_E(TAG, "Failed to get I2C port"); onScanTimerFinished(); return; } if (!device_is_ready(safe_port)) { - logger.error("I2C port not started"); + LOG_E(TAG, "I2C port not started"); onScanTimerFinished(); return; } for (uint8_t address = 1; address < 128; ++address) { if (i2c_controller_has_device_at_address(safe_port, address, 10 / portTICK_PERIOD_MS) == ERROR_NONE) { - logger.info("Found device at address 0x{:02X}", address); + LOG_I(TAG, "Found device at address 0x%02X", address); if (!shouldStopScanTimer()) { addAddressToList(address); } else { @@ -247,11 +247,11 @@ void I2cScannerApp::onScanTimer() { } } - logger.info("Scan thread finalizing"); + LOG_I(TAG, "Scan thread finalizing"); onScanTimerFinished(); - logger.info("Scan timer done"); + LOG_I(TAG, "Scan timer done"); } bool I2cScannerApp::hasScanThread() { @@ -262,7 +262,7 @@ bool I2cScannerApp::hasScanThread() { return has_thread; } else { // Unsafe way - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "hasScanTimer"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "hasScanTimer"); return scanTimer != nullptr; } } @@ -285,7 +285,7 @@ void I2cScannerApp::startScanning() { scanTimer->start(); mutex.unlock(); } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "startScanning"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "startScanning"); } } void I2cScannerApp::stopScanning() { @@ -294,7 +294,7 @@ void I2cScannerApp::stopScanning() { scanState = ScanStateStopped; mutex.unlock(); } else { - logger.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); } } @@ -317,7 +317,7 @@ void I2cScannerApp::selectBus(int32_t selected) { mutex.unlock(); } - logger.info("Selected {}", selected); + LOG_I(TAG, "Selected %d", (int)selected); setLastBusIndex(selected); startScanning(); @@ -362,7 +362,7 @@ void I2cScannerApp::updateViews() { mutex.unlock(); } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViews"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "updateViews"); } } @@ -371,7 +371,7 @@ void I2cScannerApp::updateViewsSafely() { updateViews(); lvgl::unlock(); } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "updateViewsSafely"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "updateViewsSafely"); } } @@ -384,7 +384,7 @@ void I2cScannerApp::onScanTimerFinished() { updateViewsSafely(); } else { - logger.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "onScanTimerFinished"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "onScanTimerFinished"); } } diff --git a/Tactility/Source/app/imageviewer/ImageViewer.cpp b/Tactility/Source/app/imageviewer/ImageViewer.cpp index 9640035b7..1f991cd2d 100644 --- a/Tactility/Source/app/imageviewer/ImageViewer.cpp +++ b/Tactility/Source/app/imageviewer/ImageViewer.cpp @@ -2,8 +2,8 @@ #include #include #include -#include #include +#include #include @@ -11,7 +11,7 @@ namespace tt::app::imageviewer { extern const AppManifest manifest; -static const auto LOGGER = Logger("ImageViewer"); +constexpr auto* TAG = "ImageViewer"; constexpr auto* IMAGE_VIEWER_FILE_ARGUMENT = "file"; class ImageViewerApp final : public App { @@ -49,7 +49,7 @@ class ImageViewerApp final : public App { std::string file_argument; if (bundle->optString(IMAGE_VIEWER_FILE_ARGUMENT, file_argument)) { std::string prefixed_path = lvgl::PATH_PREFIX + file_argument; - LOGGER.info("Opening {}", prefixed_path); + LOG_I(TAG, "Opening %s", prefixed_path.c_str()); lv_img_set_src(image, prefixed_path.c_str()); auto path = string::getLastPathSegment(file_argument); lv_label_set_text(file_label, path.c_str()); diff --git a/Tactility/Source/app/inputdialog/InputDialog.cpp b/Tactility/Source/app/inputdialog/InputDialog.cpp index 8eb258a30..4c0184daf 100644 --- a/Tactility/Source/app/inputdialog/InputDialog.cpp +++ b/Tactility/Source/app/inputdialog/InputDialog.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include @@ -15,7 +16,7 @@ constexpr auto* RESULT_BUNDLE_KEY_RESULT = "result"; constexpr auto* DEFAULT_TITLE = "Input"; -static const auto LOGGER = Logger("InputDialog"); +constexpr auto* TAG = "InputDialog"; extern const AppManifest manifest; class InputDialogApp; @@ -62,7 +63,7 @@ class InputDialogApp final : public App { void onButtonClicked(lv_event_t* e) { auto user_data = lv_event_get_user_data(e); int index = (user_data != 0) ? 0 : 1; - LOGGER.info("Selected item at index {}", index); + LOG_I(TAG, "Selected item at index %d", index); if (index == 0) { auto bundle = std::make_unique(); 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 0146d6789..a5ee66906 100644 --- a/Tactility/Source/app/launcher/Launcher.cpp +++ b/Tactility/Source/app/launcher/Launcher.cpp @@ -11,13 +11,14 @@ #include #include +#include #include #include #include namespace tt::app::launcher { -static const auto LOGGER = Logger("Launcher"); +constexpr auto* TAG = "Launcher"; static uint32_t getButtonPadding(UiDensity density, uint32_t buttonSize) { if (density == LVGL_UI_DENSITY_COMPACT) { @@ -143,7 +144,7 @@ class LauncherApp final : public App { strcmp(CONFIG_TT_AUTO_START_APP_ID, "") != 0 && findAppManifestById(CONFIG_TT_AUTO_START_APP_ID) != nullptr ) { - LOGGER.info("Starting {}", CONFIG_TT_AUTO_START_APP_ID); + LOG_I(TAG, "Starting %s", CONFIG_TT_AUTO_START_APP_ID); start(CONFIG_TT_AUTO_START_APP_ID); } else if ( // Auto-start due to user configuration @@ -151,7 +152,7 @@ class LauncherApp final : public App { !boot_properties.autoStartAppId.empty() && findAppManifestById(boot_properties.autoStartAppId) != nullptr ) { - LOGGER.info("Starting {}", boot_properties.autoStartAppId); + LOG_I(TAG, "Starting %s", boot_properties.autoStartAppId.c_str()); start(boot_properties.autoStartAppId); } else { // No auto-start, consider running system setup diff --git a/Tactility/Source/app/notes/Notes.cpp b/Tactility/Source/app/notes/Notes.cpp index b53223a92..c2790fd93 100644 --- a/Tactility/Source/app/notes/Notes.cpp +++ b/Tactility/Source/app/notes/Notes.cpp @@ -8,11 +8,12 @@ #include #include +#include #include namespace tt::app::notes { -static const auto LOGGER = Logger("Notes"); +constexpr auto* TAG = "Notes"; constexpr auto* NOTES_FILE_ARGUMENT = "file"; class NotesApp final : public App { @@ -52,11 +53,11 @@ class NotesApp final : public App { saveBuffer = lv_textarea_get_text(uiNoteText); lvgl::getSyncLock()->unlock(); saveFileLaunchId = fileselection::startForExistingOrNewFile(); - LOGGER.info("launched with id {}", saveFileLaunchId); + LOG_I(TAG, "launched with id %u", saveFileLaunchId); break; case 3: // Load loadFileLaunchId = fileselection::startForExistingFile(); - LOGGER.info("launched with id {}", loadFileLaunchId); + LOG_I(TAG, "launched with id %u", loadFileLaunchId); break; } } else { @@ -64,7 +65,7 @@ class NotesApp final : public App { if (obj == cont) return; if (lv_obj_get_child(cont, 1)) { saveFileLaunchId = fileselection::startForExistingOrNewFile(); - LOGGER.info("launched with id {}", saveFileLaunchId); + LOG_I(TAG, "launched with id %u", saveFileLaunchId); } else { //Reset resetFileContent(); } @@ -91,7 +92,7 @@ class NotesApp final : public App { lv_textarea_set_text(uiNoteText, reinterpret_cast(data.get())); lv_label_set_text(uiCurrentFileName, path.c_str()); filePath = path; - LOGGER.info("Loaded from {}", path); + LOG_I(TAG, "Loaded from %s", path.c_str()); } }); } @@ -101,7 +102,7 @@ class NotesApp final : public App { bool result = false; file::getLock(path)->withLock([&result, this, path] { if (file::writeString(path, saveBuffer.c_str())) { - LOGGER.info("Saved to {}", path); + LOG_I(TAG, "Saved to %s", path.c_str()); filePath = path; result = true; } @@ -193,7 +194,7 @@ class NotesApp final : public App { } void onResult(AppContext& appContext, LaunchId launchId, Result result, std::unique_ptr resultData) override { - LOGGER.info("Result for launch id {}", launchId); + LOG_I(TAG, "Result for launch id %u", launchId); if (launchId == loadFileLaunchId) { loadFileLaunchId = 0; if (result == Result::Ok && resultData != nullptr) { diff --git a/Tactility/Source/app/screenshot/Screenshot.cpp b/Tactility/Source/app/screenshot/Screenshot.cpp index 88ae99163..e1bcc180a 100644 --- a/Tactility/Source/app/screenshot/Screenshot.cpp +++ b/Tactility/Source/app/screenshot/Screenshot.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include #include @@ -15,11 +14,12 @@ #include #include +#include #include namespace tt::app::screenshot { -static const auto LOGGER = Logger("Screenshot"); +constexpr auto* TAG = "Screenshot"; extern const AppManifest manifest; @@ -100,27 +100,27 @@ void ScreenshotApp::onModeSet() { void ScreenshotApp::onStartPressed() { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - LOGGER.error("Service not found/running"); + LOG_E(TAG, "Service not found/running"); return; } if (service->isTaskStarted()) { - LOGGER.info("Stop screenshot"); + LOG_I(TAG, "Stop screenshot"); service->stop(); } else { uint32_t selected = lv_dropdown_get_selected(modeDropdown); const char* path = lv_textarea_get_text(pathTextArea); if (selected == 0) { - LOGGER.info("Start timed screenshots"); + LOG_I(TAG, "Start timed screenshots"); const char* delay_text = lv_textarea_get_text(delayTextArea); int delay = atoi(delay_text); if (delay > 0) { service->startTimed(path, delay, 1); } else { - LOGGER.warn("Ignored screenshot start because delay was 0"); + LOG_W(TAG, "Ignored screenshot start because delay was 0"); } } else { - LOGGER.info("Start app screenshots"); + LOG_I(TAG, "Start app screenshots"); service->startApps(path); } } @@ -131,7 +131,7 @@ void ScreenshotApp::onStartPressed() { void ScreenshotApp::updateScreenshotMode() { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - LOGGER.error("Service not found/running"); + LOG_E(TAG, "Service not found/running"); return; } @@ -154,7 +154,7 @@ void ScreenshotApp::updateScreenshotMode() { void ScreenshotApp::createModeSettingWidgets(lv_obj_t* parent) { auto service = service::screenshot::optScreenshotService(); if (service == nullptr) { - LOGGER.error("Service not found/running"); + LOG_E(TAG, "Service not found/running"); return; } diff --git a/Tactility/Source/app/selectiondialog/SelectionDialog.cpp b/Tactility/Source/app/selectiondialog/SelectionDialog.cpp index e49334826..fe1746f87 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..."; -static const auto LOGGER = Logger("SelectionDialog"); +constexpr auto* TAG = "SelectionDialog"; extern const AppManifest manifest; @@ -53,7 +53,7 @@ class SelectionDialogApp final : public App { void onListItemSelected(lv_event_t* e) { auto index = reinterpret_cast(lv_event_get_user_data(e)); - LOGGER.info("Selected item at index {}", index); + LOG_I(TAG, "Selected item at index %d", (int)index); auto bundle = std::make_unique(); bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, (int32_t)index); setResult(Result::Ok, std::move(bundle)); @@ -85,7 +85,7 @@ class SelectionDialogApp final : public App { 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()) { - LOGGER.error("No items provided"); + LOG_E(TAG, "No items provided"); setResult(Result::Error); stop(manifest.appId); } else if (items.size() == 1) { @@ -93,7 +93,7 @@ class SelectionDialogApp final : public App { result_bundle->putInt32(RESULT_BUNDLE_KEY_INDEX, 0); setResult(Result::Ok, std::move(result_bundle)); stop(manifest.appId); - LOGGER.warn("Auto-selecting single item"); + LOG_W(TAG, "Auto-selecting single item"); } else { size_t index = 0; for (const auto& item: items) { @@ -101,7 +101,7 @@ class SelectionDialogApp final : public App { } } } else { - LOGGER.error("No items provided"); + LOG_E(TAG, "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 1c2520d02..d89a38507 100644 --- a/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp +++ b/Tactility/Source/app/timedatesettings/TimeDateSettings.cpp @@ -1,7 +1,6 @@ #include "tactility/lvgl_module.h" -#include #include #include #include @@ -13,11 +12,12 @@ #include +#include #include namespace tt::app::timedatesettings { -static const auto LOGGER = Logger("TimeDate"); +constexpr auto* TAG = "TimeDate"; extern const AppManifest manifest; @@ -149,7 +149,7 @@ class TimeDateSettingsApp final : public App { if (result == Result::Ok && bundle != nullptr) { const auto name = timezone::getResultName(*bundle); const auto code = timezone::getResultCode(*bundle); - LOGGER.info("Result name={} code={}", name, code); + LOG_I(TAG, "Result name=%s code=%s", name.c_str(), code.c_str()); // onShow() may not have (re)created the widgets yet: onResult() runs synchronously // on the loader thread and can race ahead of the async gui-task redraw. diff --git a/Tactility/Source/app/timezone/TimeZone.cpp b/Tactility/Source/app/timezone/TimeZone.cpp index a0f68d4f5..11ab9992c 100644 --- a/Tactility/Source/app/timezone/TimeZone.cpp +++ b/Tactility/Source/app/timezone/TimeZone.cpp @@ -6,7 +6,6 @@ #include #include -#include #include #include #include @@ -14,13 +13,14 @@ #include #include #include +#include #include #include namespace tt::app::timezone { -static const auto LOGGER = Logger("TimeZone"); +constexpr auto* TAG = "TimeZone"; constexpr auto* RESULT_BUNDLE_CODE_INDEX = "code"; constexpr auto* RESULT_BUNDLE_NAME_INDEX = "name"; @@ -103,7 +103,7 @@ class TimeZoneApp final : public App { } void onListItemSelected(std::size_t index) { - LOGGER.info("Selected item at index {}", index); + LOG_I(TAG, "Selected item at index %d", (int)index); auto& entry = entries[index]; @@ -128,7 +128,7 @@ class TimeZoneApp final : public App { auto path = std::string(file::MOUNT_POINT_SYSTEM) + "/timezones.csv"; auto* file = fopen(path.c_str(), "rb"); if (file == nullptr) { - LOGGER.error("Failed to open {}", path); + LOG_E(TAG, "Failed to open %s", path.c_str()); return; } char line[96]; @@ -149,7 +149,7 @@ class TimeZoneApp final : public App { } } } else { - LOGGER.error("Parse error at line {}", count); + LOG_E(TAG, "Parse error at line %llu", count); } } @@ -159,10 +159,10 @@ class TimeZoneApp final : public App { entries = std::move(new_entries); mutex.unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); } - LOGGER.info("Processed {} entries", count); + LOG_I(TAG, "Processed %llu entries", count); } void updateList() { @@ -171,7 +171,7 @@ class TimeZoneApp final : public App { readTimeZones(filter); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); return; } diff --git a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp index 5cfd11093..4af6013ab 100644 --- a/Tactility/Source/app/touchcalibration/TouchCalibration.cpp +++ b/Tactility/Source/app/touchcalibration/TouchCalibration.cpp @@ -2,15 +2,16 @@ #include -#include #include +#include + #include #include namespace tt::app::touchcalibration { -static const auto LOGGER = Logger("TouchCalibration"); +constexpr auto* TAG = "TouchCalibration"; extern const AppManifest manifest; @@ -102,7 +103,7 @@ class TouchCalibrationApp final : public App { return; } - LOGGER.info("Saved calibration x=[{}, {}] y=[{}, {}]", xMin, xMax, yMin, yMax); + LOG_I(TAG, "Saved calibration x=[%d, %d] y=[%d, %d]", xMin, xMax, yMin, yMax); lv_label_set_text(titleLabel, "Calibration Complete"); lv_label_set_text(hintLabel, "Touch anywhere to continue."); lv_obj_add_flag(target, LV_OBJ_FLAG_HIDDEN); diff --git a/Tactility/Source/app/webserversettings/WebServerSettings.cpp b/Tactility/Source/app/webserversettings/WebServerSettings.cpp index b9ae51bb2..fc4916e3f 100644 --- a/Tactility/Source/app/webserversettings/WebServerSettings.cpp +++ b/Tactility/Source/app/webserversettings/WebServerSettings.cpp @@ -9,9 +9,9 @@ #include #include #include -#include #include +#include #include #include @@ -21,7 +21,7 @@ namespace tt::app::webserversettings { -static const auto LOGGER = tt::Logger("WebServerSettingsApp"); +constexpr auto* TAG = "WebServerSettingsApp"; class WebServerSettingsApp final : public App { @@ -68,10 +68,10 @@ class WebServerSettingsApp final : public App { // Apply immediately instead of waiting for app exit const auto copy = app->wsSettings; if (!settings::webserver::save(copy)) { - LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot"); + LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot"); } service::webserver::getPubsub()->publish(service::webserver::WebServerEvent::WebServerSettingsChanged); - LOGGER.info("WebServer {}", enabled ? "enabling..." : "disabling..."); + LOG_I(TAG, "WebServer %s", enabled ? "enabling..." : "disabling..."); service::webserver::setWebServerEnabled(enabled); }); } @@ -360,7 +360,7 @@ class WebServerSettingsApp final : public App { getMainDispatcher().dispatch([copy, wifiChanged]{ // Save to flash (fast, low memory pressure) if (!settings::webserver::save(copy)) { - LOGGER.warn("Failed to persist WebServer settings; changes may be lost on reboot"); + LOG_W(TAG, "Failed to persist WebServer settings; changes may be lost on reboot"); } // Publish event immediately after save so WebServer cache refreshes BEFORE requests arrive @@ -368,7 +368,7 @@ class WebServerSettingsApp final : public App { // Only reconnect WiFi if WiFi settings actually changed if (wifiChanged) { - LOGGER.info("WiFi mode changed to {}", copy.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station"); + LOG_I(TAG, "WiFi mode changed to %s", copy.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station"); } }); } diff --git a/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp b/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp index f2ae9c3e0..72fb7b80a 100644 --- a/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp +++ b/Tactility/Source/app/wifiapsettings/WifiApSettings.cpp @@ -1,22 +1,23 @@ #include "Tactility/lvgl/LvglSync.h" #include -#include #include #include #include #include -#include #include #include #include #include +#include +#include + #include namespace tt::app::wifiapsettings { -static const auto LOGGER = Logger("WifiApSettings"); +constexpr auto* TAG = "WifiApSettings"; extern const AppManifest manifest; @@ -52,10 +53,10 @@ class WifiApSettings : public App { if (service::wifi::settings::load(self->ssid.c_str(), settings)) { settings.autoConnect = is_on; if (!service::wifi::settings::save(settings)) { - LOGGER.error("Failed to save settings"); + LOG_E(TAG, "Failed to save settings"); } } else { - LOGGER.error("Failed to load settings"); + LOG_E(TAG, "Failed to load settings"); } } @@ -91,7 +92,7 @@ class WifiApSettings : public App { updateViews(); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } } @@ -194,7 +195,7 @@ class WifiApSettings : public App { lv_obj_remove_state(auto_connect_switch, LV_STATE_CHECKED); } } else { - LOGGER.warn("No settings found"); + LOG_W(TAG, "No settings found"); lv_obj_add_flag(forget_button, LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(auto_connect_wrapper, LV_OBJ_FLAG_HIDDEN); } @@ -225,11 +226,11 @@ class WifiApSettings : public App { std::string ssid = parameters->getString("ssid"); if (!service::wifi::settings::remove(ssid.c_str())) { - LOGGER.error("Failed to remove SSID"); + LOG_E(TAG, "Failed to remove SSID"); return; } - LOGGER.info("Removed SSID"); + LOG_I(TAG, "Removed SSID"); if ( service::wifi::getRadioState() == service::wifi::RadioState::ConnectionActive && service::wifi::getConnectionTarget() == ssid diff --git a/Tactility/Source/app/wificonnect/View.cpp b/Tactility/Source/app/wificonnect/View.cpp index 578192403..faefd8e1f 100644 --- a/Tactility/Source/app/wificonnect/View.cpp +++ b/Tactility/Source/app/wificonnect/View.cpp @@ -2,18 +2,19 @@ #include #include -#include #include #include #include #include +#include + #include #include namespace tt::app::wificonnect { -static const auto LOGGER = Logger("WifiConnect"); +constexpr auto* TAG = "WifiConnect"; void View::resetErrors() { lv_obj_add_flag(password_error, LV_OBJ_FLAG_HIDDEN); @@ -31,7 +32,7 @@ static void onConnect(lv_event_t* event) { const char* ssid = lv_textarea_get_text(view.ssid_textarea); size_t ssid_len = strlen(ssid); if (ssid_len > TT_WIFI_SSID_LIMIT) { - LOGGER.error("SSID too long"); + LOG_E(TAG, "SSID too long"); lv_label_set_text(view.ssid_error, "SSID too long"); lv_obj_remove_flag(view.ssid_error, LV_OBJ_FLAG_HIDDEN); return; @@ -40,7 +41,7 @@ static void onConnect(lv_event_t* event) { const char* password = lv_textarea_get_text(view.password_textarea); size_t password_len = strlen(password); if (password_len > TT_WIFI_CREDENTIALS_PASSWORD_LIMIT) { - LOGGER.error("Password too long"); + LOG_E(TAG, "Password too long"); lv_label_set_text(view.password_error, "Password too long"); lv_obj_remove_flag(view.password_error, LV_OBJ_FLAG_HIDDEN); return; diff --git a/Tactility/Source/app/wificonnect/WifiConnect.cpp b/Tactility/Source/app/wificonnect/WifiConnect.cpp index 629c66684..32b1cbb7a 100644 --- a/Tactility/Source/app/wificonnect/WifiConnect.cpp +++ b/Tactility/Source/app/wificonnect/WifiConnect.cpp @@ -1,15 +1,16 @@ #include -#include #include #include #include #include #include +#include + namespace tt::app::wificonnect { -static const auto LOGGER = Logger("WifiConnect"); +constexpr auto* TAG = "WifiConnect"; constexpr auto* WIFI_CONNECT_PARAM_SSID = "ssid"; // String constexpr auto* WIFI_CONNECT_PARAM_PASSWORD = "password"; // String @@ -74,7 +75,7 @@ void WifiConnect::requestViewUpdate() { view.update(); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } unlock(); diff --git a/Tactility/Source/app/wifimanage/View.cpp b/Tactility/Source/app/wifimanage/View.cpp index f0ccc96c1..74ee4838f 100644 --- a/Tactility/Source/app/wifimanage/View.cpp +++ b/Tactility/Source/app/wifimanage/View.cpp @@ -2,21 +2,21 @@ #include #include -#include - #include #include #include -#include #include #include #include #include #include +#include +#include + namespace tt::app::wifimanage { -static const auto LOGGER = Logger("WifiManageView"); +constexpr auto* TAG = "WifiManageView"; std::shared_ptr optWifiManage(); @@ -68,16 +68,16 @@ static void onConnectToHiddenClicked(lv_event_t* event) { // region Secondary updates void View::connect(lv_event_t* event) { - LOGGER.debug("connect()"); + LOG_D(TAG, "connect()"); auto* widget = lv_event_get_current_target_obj(event); auto index = reinterpret_cast(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()) { - LOGGER.info("Clicked {}/{}", index, ap_records.size() - 1); + LOG_I(TAG, "Clicked %zu/%zu", index, ap_records.size() - 1); auto& ssid = ap_records[index].ssid; - LOGGER.info("Clicked AP: {}", ssid); + LOG_I(TAG, "Clicked AP: %s", ssid.c_str()); std::string connection_target = service::wifi::getConnectionTarget(); if (connection_target == ssid) { self->bindings->onDisconnect(); @@ -85,12 +85,12 @@ void View::connect(lv_event_t* event) { self->bindings->onConnectSsid(ssid); } } else { - LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1); + LOG_W(TAG, "Clicked AP: record %zu/%zu does not exist", index, ap_records.size() - 1); } } void View::showDetails(lv_event_t* event) { - LOGGER.debug("showDetails()"); + LOG_D(TAG, "showDetails()"); auto* widget = lv_event_get_current_target_obj(event); auto index = reinterpret_cast(lv_obj_get_user_data(widget)); auto* self = static_cast(lv_event_get_user_data(event)); @@ -98,10 +98,10 @@ void View::showDetails(lv_event_t* event) { if (index < ap_records.size()) { auto& ssid = ap_records[index].ssid; - LOGGER.info("Clicked AP: {}", ssid); + LOG_I(TAG, "Clicked AP: %s", ssid.c_str()); self->bindings->onShowApSettings(ssid); } else { - LOGGER.warn("Clicked AP: record {}/{} does not exist", index, ap_records.size() - 1); + LOG_W(TAG, "Clicked AP: record %zu/%zu does not exist", index, ap_records.size() - 1); } } diff --git a/Tactility/Source/app/wifimanage/WifiManage.cpp b/Tactility/Source/app/wifimanage/WifiManage.cpp index d70593b72..b45fff1c0 100644 --- a/Tactility/Source/app/wifimanage/WifiManage.cpp +++ b/Tactility/Source/app/wifimanage/WifiManage.cpp @@ -1,29 +1,29 @@ #include #include +#include #include #include #include -#include -#include #include #include +#include #include namespace tt::app::wifimanage { -static const auto LOGGER = Logger("WifiManage"); +constexpr auto* TAG = "WifiManage"; extern const AppManifest manifest; static void onConnect(const std::string& ssid) { service::wifi::settings::WifiApSettings settings; if (service::wifi::settings::load(ssid, settings)) { - LOGGER.info("Connecting with known credentials"); + LOG_I(TAG, "Connecting with known credentials"); service::wifi::connect(settings, false); } else { - LOGGER.info("Starting connection dialog"); + LOG_I(TAG, "Starting connection dialog"); wificonnect::start(ssid); } } @@ -69,7 +69,7 @@ void WifiManage::requestViewUpdate() { view.update(); lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } unlock(); @@ -77,7 +77,7 @@ void WifiManage::requestViewUpdate() { void WifiManage::onWifiEvent(service::wifi::WifiEvent event) { auto radio_state = service::wifi::getRadioState(); - LOGGER.info("Update with state {}", service::wifi::radioStateToString(radio_state)); + LOG_I(TAG, "Update with state %s", service::wifi::radioStateToString(radio_state)); getState().setRadioState(radio_state); switch (event) { using enum service::wifi::WifiEvent; @@ -123,11 +123,11 @@ void WifiManage::onShow(AppContext& app, lv_obj_t* parent) { radio_state == service::wifi::RadioState::ConnectionPending || radio_state == service::wifi::RadioState::ConnectionActive; std::string connection_target = service::wifi::getConnectionTarget(); - LOGGER.info("Radio: {}, Scanning: {}, Connected to: {}, Can scan: {}", - service::wifi::radioStateToString(radio_state), - service::wifi::isScanning(), + LOG_I(TAG, "Radio: %s, Scanning: %d, Connected to: %s, Can scan: %d", + service::wifi::radioStateToString(radio_state), + (int)service::wifi::isScanning(), connection_target.empty() ? "(none)" : connection_target.c_str(), - can_scan); + (int)can_scan); if (can_scan && !service::wifi::isScanning()) { service::wifi::scan(); } diff --git a/Tactility/Source/bluetooth/Bluetooth.cpp b/Tactility/Source/bluetooth/Bluetooth.cpp index 380b0d7fd..b3a17c923 100644 --- a/Tactility/Source/bluetooth/Bluetooth.cpp +++ b/Tactility/Source/bluetooth/Bluetooth.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -18,6 +17,7 @@ #include #include #include +#include #include #include @@ -25,7 +25,7 @@ namespace tt::bluetooth { -static const auto LOGGER = Logger("Bluetooth"); +constexpr auto* TAG = "Bluetooth"; // ---- Scan result cache (C++ PeerRecord list, updated from BT_EVENT_PEER_FOUND) ---- @@ -123,24 +123,24 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) { if (p.profileId == BT_PROFILE_HID_DEVICE) has_hid_device_auto = true; } if (has_hid_host_auto) { - LOGGER.info("HID host auto-connect peer found — starting scan"); + LOG_I(TAG, "HID host auto-connect peer found — starting scan"); if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) { bluetooth_scan_start(dev); } } else if (has_hid_device_auto) { - LOGGER.info("HID device auto-start (bonded peer found)"); + LOG_I(TAG, "HID device auto-start (bonded peer found)"); if (Device* dev = bluetooth_hid_device_get_device()) { bluetooth_hid_device_start(dev, BT_HID_DEVICE_MODE_KEYBOARD); } } else { if (settings::shouldSppAutoStart()) { - LOGGER.info("Auto-starting SPP server"); + LOG_I(TAG, "Auto-starting SPP server"); if (Device* dev = bluetooth_serial_get_device()) { bluetooth_serial_start(dev); } } if (settings::shouldMidiAutoStart()) { - LOGGER.info("Auto-starting MIDI server"); + LOG_I(TAG, "Auto-starting MIDI server"); if (Device* dev = bluetooth_midi_get_device()) { bluetooth_midi_start(dev); } @@ -186,7 +186,7 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) { dev.autoConnect = true; dev.profileId = profile_copy; if (settings::save(dev)) { - LOGGER.info("Saved paired peer {} (profile={})", hex, profile_copy); + LOG_I(TAG, "Saved paired peer %s (profile=%d)", hex.c_str(), profile_copy); } } }); @@ -251,7 +251,7 @@ static void bt_event_bridge(Device*, void* /*context*/, BtEvent event) { void systemStart() { Device* dev = findFirstRegisteredDevice(); if (dev == nullptr) { - LOGGER.warn("systemStart: no BLE device found"); + LOG_W(TAG, "systemStart: no BLE device found"); return; } @@ -268,29 +268,29 @@ bool isRadioOnOrPending(Device* dev) { } bool start(Device* dev) { - LOGGER.info("Auto-enabling BLE on boot"); + LOG_I(TAG, "Auto-enabling BLE on boot"); if (!device_is_ready(dev)) { - LOGGER.info("Starting BLE device"); + LOG_I(TAG, "Starting BLE device"); if (device_start(dev) != ERROR_NONE) { - LOGGER.error("Failed to start BLE device"); + LOG_E(TAG, "Failed to start BLE device"); return false; } } // TODO: Fix bug where repeatedly calling start would add this callback multiple times if (bluetooth_add_event_callback(dev, nullptr, bt_event_bridge) != ERROR_NONE) { - LOGGER.error("Failed to set BLE callback"); + LOG_E(TAG, "Failed to set BLE callback"); } - LOGGER.info("Enabling BT radio"); + LOG_I(TAG, "Enabling BT radio"); if (bluetooth_set_radio_enabled(dev, true) != ERROR_NONE) { - LOGGER.error("Failed to enable BLE radio"); + LOG_E(TAG, "Failed to enable BLE radio"); // Add bridge again bluetooth_remove_event_callback(dev, bt_event_bridge); return false; } - LOGGER.info("BT enabled"); + LOG_I(TAG, "BT enabled"); return true; } @@ -305,18 +305,18 @@ bool stop(Device* dev) { } if (bluetooth_remove_event_callback(dev, bt_event_bridge) != ERROR_NONE) { - LOGGER.error("Failed to remove BLE callback"); + LOG_E(TAG, "Failed to remove BLE callback"); } if (bluetooth_set_radio_enabled(dev, false) != ERROR_NONE) { - LOGGER.error("Failed to disable BT radio"); + LOG_E(TAG, "Failed to disable BT radio"); // Re-register bridge bluetooth_add_event_callback(dev, nullptr, bt_event_bridge); return false; } if (device_stop(dev) != ERROR_NONE) { - LOGGER.error("Failed to stop BT device"); + LOG_E(TAG, "Failed to stop BT device"); return false; } @@ -413,7 +413,7 @@ void unpair(const std::array& addr) { } void connect(const std::array& addr, int profileId) { - LOGGER.info("connect(profile={})", profileId); + LOG_I(TAG, "connect(profile=%d)", profileId); if (profileId == BT_PROFILE_HID_HOST) { hidHostConnect(addr); } else if (profileId == BT_PROFILE_HID_DEVICE) { @@ -434,7 +434,7 @@ void connect(const std::array& addr, int profileId) { } void disconnect(const std::array& addr, int profileId) { - LOGGER.info("disconnect(profile={})", profileId); + LOG_I(TAG, "disconnect(profile=%d)", profileId); if (profileId == BT_PROFILE_HID_HOST) { hidHostDisconnect(); } else if (profileId == BT_PROFILE_HID_DEVICE) { diff --git a/Tactility/Source/bluetooth/BluetoothHidHost.cpp b/Tactility/Source/bluetooth/BluetoothHidHost.cpp index 53c0487d4..e621ea0c9 100644 --- a/Tactility/Source/bluetooth/BluetoothHidHost.cpp +++ b/Tactility/Source/bluetooth/BluetoothHidHost.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -22,6 +21,7 @@ #include #include #include +#include #include #include @@ -30,12 +30,9 @@ #include #include -#define TAG "BtHidHost" -#include - namespace tt::bluetooth { -static const auto LOGGER = Logger("BtHidHost"); +constexpr auto* TAG = "BtHidHost"; // ---- Report type ---- @@ -229,7 +226,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) { if (hid_host_ctx && hid_host_ctx->mouseIndev == nullptr) { getMainDispatcher().dispatch([] { if (!hid_host_ctx || hid_host_ctx->mouseIndev != nullptr) return; - if (!tt::lvgl::lock(1000)) { LOGGER.warn("LVGL lock failed for mouse indev"); return; } + if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for mouse indev"); return; } auto* ms = lv_indev_create(); lv_indev_set_type(ms, LV_INDEV_TYPE_POINTER); lv_indev_set_read_cb(ms, hidHostMouseReadCb); @@ -241,7 +238,7 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) { hid_host_ctx->mouseIndev = ms; hid_host_ctx->mouseCursor = cur; tt::lvgl::unlock(); - LOGGER.info("Mouse indev registered"); + LOG_I(TAG, "Mouse indev registered"); }); } } @@ -251,11 +248,11 @@ static void hidHostHandleMouseReport(const uint8_t* data, uint16_t len) { static void hidEncRetryTimerCb(void* /*arg*/) { if (hid_host_ctx) { if (!hid_host_ctx->typeResolutionDone) { - LOGGER.warn("Post-encryption delay — type resolution timed out, proceeding"); + LOG_W(TAG, "Post-encryption delay — type resolution timed out, proceeding"); hid_host_ctx->typeResolutionDone = true; hid_host_ctx->subscribeIdx = 0; } else { - LOGGER.info("Post-encryption delay complete — starting CCCD subscriptions"); + LOG_I(TAG, "Post-encryption delay complete — starting CCCD subscriptions"); } hidHostSubscribeNext(*hid_host_ctx); } @@ -336,7 +333,7 @@ static void applyReportMapTypes(HidHostCtx& ctx) { if (zeroRptIdx < collOrder.size()) rpt.type = collOrder[zeroRptIdx]; zeroRptIdx++; } - LOGGER.info("Report val_handle={} reportId={} type={}", rpt.valHandle, rpt.reportId, (int)rpt.type); + LOG_I(TAG, "Report val_handle=%d reportId=%d type=%d", rpt.valHandle, rpt.reportId, (int)rpt.type); } ctx.rptMap.clear(); } @@ -365,7 +362,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) { uint8_t rpt_ref[2] = {}; os_mbuf_copydata(attr->om, 0, 2, rpt_ref); ctx.inputRpts[ctx.rptRefReadIdx].reportId = rpt_ref[0]; - LOGGER.info("Report[{}] val_handle={} reportId={}", ctx.rptRefReadIdx, + LOG_I(TAG, "Report[%d] val_handle=%d reportId=%d", ctx.rptRefReadIdx, ctx.inputRpts[ctx.rptRefReadIdx].valHandle, rpt_ref[0]); } } @@ -374,7 +371,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) { return 0; }, nullptr); if (rc != 0) { - LOGGER.warn("rptRef read[{}] failed rc={} — skipping", ctx.rptRefReadIdx, rc); + LOG_W(TAG, "rptRef read[%d] failed rc=%d — skipping", ctx.rptRefReadIdx, rc); ctx.rptRefReadIdx++; hidHostStartRptRefRead(ctx); } @@ -384,7 +381,7 @@ static void hidHostStartRptRefRead(HidHostCtx& ctx) { static void hidHostReadReportMap(HidHostCtx& ctx) { if (ctx.rptMapHandle == 0) { - LOGGER.info("No Report Map char — skipping type resolution"); + LOG_I(TAG, "No Report Map char — skipping type resolution"); ctx.typeResolutionDone = true; ctx.subscribeIdx = 0; hidHostSubscribeNext(ctx); @@ -404,10 +401,10 @@ static void hidHostReadReportMap(HidHostCtx& ctx) { return 0; } if (!ctx.rptMap.empty()) { - LOGGER.info("Report map read ({} bytes)", ctx.rptMap.size()); + LOG_I(TAG, "Report map read (%d bytes)", (int)ctx.rptMap.size()); applyReportMapTypes(ctx); } else { - LOGGER.warn("Report map read failed — types remain Unknown"); + LOG_W(TAG, "Report map read failed — types remain Unknown"); } ctx.typeResolutionDone = true; ctx.subscribeIdx = 0; @@ -415,7 +412,7 @@ static void hidHostReadReportMap(HidHostCtx& ctx) { return 0; }, nullptr); if (rc != 0) { - LOGGER.warn("Report map read_long failed rc={} — skipping", rc); + LOG_W(TAG, "Report map read_long failed rc=%d — skipping", rc); ctx.typeResolutionDone = true; ctx.subscribeIdx = 0; hidHostSubscribeNext(ctx); @@ -434,22 +431,22 @@ static int hidHostCccdWriteCb(uint16_t conn_handle, const struct ble_gatt_error* if ((error->status == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN) || error->status == BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC)) && !ctx.securityInitiated) { - LOGGER.info("CCCD auth required — initiating security"); + LOG_I(TAG, "CCCD auth required — initiating security"); ctx.securityInitiated = true; ble_gap_security_initiate(conn_handle); return 0; } if (error->status == BLE_HS_ETIMEOUT) { - LOGGER.warn("CCCD write timed out for report[{}] — skipping", ctx.subscribeIdx); + LOG_W(TAG, "CCCD write timed out for report[%d] — skipping", ctx.subscribeIdx); ctx.subscribeIdx++; hidHostSubscribeNext(ctx); return 0; } if (error->status == BLE_HS_ENOTCONN) { - LOGGER.warn("CCCD write failed — not connected"); + LOG_W(TAG, "CCCD write failed — not connected"); return 0; } - LOGGER.warn("CCCD write failed status={}", error->status); + LOG_W(TAG, "CCCD write failed status=%d", error->status); } ctx.subscribeIdx++; hidHostSubscribeNext(ctx); @@ -459,11 +456,11 @@ static int hidHostCccdWriteCb(uint16_t conn_handle, const struct ble_gatt_error* static void hidHostSubscribeNext(HidHostCtx& ctx) { if (ctx.subscribeIdx >= (int)ctx.inputRpts.size()) { if (ctx.readyBlockFired) { - LOGGER.info("Subscribe ready block already ran — ignoring duplicate"); + LOG_I(TAG, "Subscribe ready block already ran — ignoring duplicate"); return; } ctx.readyBlockFired = true; - LOGGER.info("All {} reports subscribed — ready", ctx.inputRpts.size()); + LOG_I(TAG, "All %d reports subscribed — ready", (int)ctx.inputRpts.size()); if (hid_enc_retry_timer) esp_timer_stop(hid_enc_retry_timer); if (!hid_host_key_queue) { @@ -471,14 +468,14 @@ static void hidHostSubscribeNext(HidHostCtx& ctx) { } getMainDispatcher().dispatch([] { if (!hid_host_ctx || hid_host_ctx->kbIndev != nullptr) return; - if (!tt::lvgl::lock(1000)) { LOGGER.warn("LVGL lock failed for kb indev"); return; } + if (!tt::lvgl::lock(1000)) { LOG_W(TAG, "LVGL lock failed for kb indev"); return; } auto* kb = lv_indev_create(); lv_indev_set_type(kb, LV_INDEV_TYPE_KEYPAD); lv_indev_set_read_cb(kb, hidHostKeyboardReadCb); hid_host_ctx->kbIndev = kb; tt::lvgl::hardware_keyboard_set_indev(kb); tt::lvgl::unlock(); - LOGGER.info("Keyboard indev registered"); + LOG_I(TAG, "Keyboard indev registered"); }); auto peer_addr = ctx.peerAddr; @@ -523,7 +520,7 @@ static void hidHostSubscribeNext(HidHostCtx& ctx) { ¬ify_val, sizeof(notify_val), hidHostCccdWriteCb, nullptr); if (rc != 0) { - LOGGER.warn("gattc_write_flat CCCD failed rc={}", rc); + LOG_W(TAG, "gattc_write_flat CCCD failed rc=%d", rc); ctx.subscribeIdx++; hidHostSubscribeNext(ctx); } @@ -554,7 +551,7 @@ static int hidHostDscDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e int rc = ble_gattc_disc_all_dscs(ctx.connHandle, next_rpt.valHandle, end, hidHostDscDiscCb, nullptr); if (rc != 0) { - LOGGER.warn("disc_all_dscs[{}] failed rc={}", next_idx, rc); + LOG_W(TAG, "disc_all_dscs[%d] failed rc=%d", next_idx, rc); ctx.rptRefReadIdx = 0; hidHostStartRptRefRead(ctx); } @@ -588,14 +585,14 @@ static int hidHostChrDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e HidHostInputRpt rpt = {}; rpt.valHandle = chr->val_handle; ctx.inputRpts.push_back(rpt); - LOGGER.info("Input Report chr val_handle={}", chr->val_handle); + LOG_I(TAG, "Input Report chr val_handle=%d", chr->val_handle); } else if (uuid16 == 0x2A4B) { ctx.rptMapHandle = chr->val_handle; } } else if (error->status == BLE_HS_EDONE) { std::sort(ctx.allChrDefHandles.begin(), ctx.allChrDefHandles.end()); if (ctx.inputRpts.empty()) { - LOGGER.warn("No Input Report chars — disconnecting"); + LOG_W(TAG, "No Input Report chars — disconnecting"); ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM); return 0; } @@ -605,7 +602,7 @@ static int hidHostChrDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e int rc = ble_gattc_disc_all_dscs(ctx.connHandle, first.valHandle, end, hidHostDscDiscCb, nullptr); if (rc != 0) { - LOGGER.warn("disc_all_dscs[0] failed rc={}", rc); + LOG_W(TAG, "disc_all_dscs[0] failed rc=%d", rc); ctx.rptRefReadIdx = 0; hidHostStartRptRefRead(ctx); } @@ -625,18 +622,18 @@ static int hidHostSvcDiscCb(uint16_t conn_handle, const struct ble_gatt_error* e if (ble_uuid_u16(&svc->uuid.u) == 0x1812) { ctx.hidSvcStart = svc->start_handle; ctx.hidSvcEnd = svc->end_handle; - LOGGER.info("HID service start={} end={}", ctx.hidSvcStart, ctx.hidSvcEnd); + LOG_I(TAG, "HID service start=%d end=%d", ctx.hidSvcStart, ctx.hidSvcEnd); } } else if (error->status == BLE_HS_EDONE) { if (ctx.hidSvcStart == 0) { - LOGGER.warn("No HID service found — disconnecting"); + LOG_W(TAG, "No HID service found — disconnecting"); ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM); return 0; } int rc = ble_gattc_disc_all_chrs(ctx.connHandle, ctx.hidSvcStart, ctx.hidSvcEnd, hidHostChrDiscCb, nullptr); if (rc != 0) { - LOGGER.warn("disc_all_chrs failed rc={}", rc); + LOG_W(TAG, "disc_all_chrs failed rc=%d", rc); ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM); } } @@ -653,14 +650,14 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { case BLE_GAP_EVENT_CONNECT: if (event->connect.status == 0) { ctx.connHandle = event->connect.conn_handle; - LOGGER.info("Connected (handle={})", ctx.connHandle); + LOG_I(TAG, "Connected (handle=%d)", ctx.connHandle); int rc = ble_gattc_disc_all_svcs(ctx.connHandle, hidHostSvcDiscCb, nullptr); if (rc != 0) { - LOGGER.warn("disc_all_svcs failed rc={}", rc); + LOG_W(TAG, "disc_all_svcs failed rc=%d", rc); ble_gap_terminate(ctx.connHandle, BLE_ERR_REM_USER_CONN_TERM); } } else { - LOGGER.warn("Connect failed status={}", event->connect.status); + LOG_W(TAG, "Connect failed status=%d", event->connect.status); hid_host_ctx.reset(); if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) { bluetooth_set_hid_host_active(dev, false); @@ -674,7 +671,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { break; case BLE_GAP_EVENT_DISCONNECT: { - LOGGER.info("Disconnected reason={}", event->disconnect.reason); + LOG_I(TAG, "Disconnected reason=%d", event->disconnect.reason); lv_indev_t* saved_kb = hid_host_ctx ? hid_host_ctx->kbIndev : nullptr; lv_indev_t* saved_mouse = hid_host_ctx ? hid_host_ctx->mouseIndev : nullptr; lv_obj_t* saved_cursor = hid_host_ctx ? hid_host_ctx->mouseCursor : nullptr; @@ -698,7 +695,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { getMainDispatcher().dispatch([saved_kb, saved_mouse, saved_cursor, saved_queue] { if (!tt::lvgl::lock(1000)) { - LOGGER.warn("Failed to acquire LVGL lock for indev cleanup"); + LOG_W(TAG, "Failed to acquire LVGL lock for indev cleanup"); if (saved_queue) vQueueDelete(saved_queue); return; } @@ -717,7 +714,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { case BLE_GAP_EVENT_ENC_CHANGE: if (event->enc_change.conn_handle == ctx.connHandle) { if (event->enc_change.status == 0) { - LOGGER.info("Encryption established — retrying CCCD in 500ms"); + LOG_I(TAG, "Encryption established — retrying CCCD in 500ms"); ctx.subscribeIdx = 0; if (hid_enc_retry_timer) { esp_timer_stop(hid_enc_retry_timer); @@ -726,7 +723,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { hidHostSubscribeNext(ctx); } } else { - LOGGER.warn("Encryption failed status={}", event->enc_change.status); + LOG_W(TAG, "Encryption failed status=%d", event->enc_change.status); } } break; @@ -743,7 +740,7 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { case HidReportType::Keyboard: hidHostHandleKeyboardReport(buf, len); break; case HidReportType::Mouse: hidHostHandleMouseReport(buf, len); break; case HidReportType::Consumer: - LOGGER.info("Consumer report len={}", len); + LOG_I(TAG, "Consumer report len=%d", len); break; case HidReportType::Unknown: if (len >= 6) hidHostHandleKeyboardReport(buf, len); @@ -766,11 +763,11 @@ static int hidHostGapCb(struct ble_gap_event* event, void* /*arg*/) { void hidHostConnect(const std::array& addr) { if (getRadioState() != RadioState::On) { - LOGGER.warn("hidHostConnect: radio not on"); + LOG_W(TAG, "hidHostConnect: radio not on"); return; } if (hid_host_ctx) { - LOGGER.warn("hidHostConnect: already connecting/connected"); + LOG_W(TAG, "hidHostConnect: already connecting/connected"); return; } @@ -789,7 +786,7 @@ void hidHostConnect(const std::array& addr) { args.dispatch_method = ESP_TIMER_TASK; args.name = "hid_enc_retry"; if (esp_timer_create(&args, &hid_enc_retry_timer) != ESP_OK) { - LOGGER.error("Failed to create hid_enc_retry timer"); + LOG_E(TAG, "Failed to create hid_enc_retry timer"); hid_enc_retry_timer = nullptr; } } @@ -813,7 +810,7 @@ void hidHostConnect(const std::array& addr) { int rc = ble_gap_connect(own_addr_type, &ble_addr, 5000, nullptr, hidHostGapCb, nullptr); if (rc != 0) { - LOGGER.warn("ble_gap_connect failed rc={}", rc); + LOG_W(TAG, "ble_gap_connect failed rc=%d", rc); hid_host_ctx.reset(); if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) { bluetooth_set_hid_host_active(dev, false); @@ -825,7 +822,7 @@ void hidHostConnect(const std::array& addr) { bluetooth_fire_event(dev, e); } } else { - LOGGER.info("Connecting..."); + LOG_I(TAG, "Connecting..."); } } @@ -858,7 +855,7 @@ void autoConnectHidHost() { if (settings::load(settings::addrToHex(r.addr), stored) && stored.autoConnect && stored.profileId == BT_PROFILE_HID_HOST) { - LOGGER.info("Auto-connecting HID host to {}", settings::addrToHex(r.addr)); + LOG_I(TAG, "Auto-connecting HID host to %s", settings::addrToHex(r.addr).c_str()); hidHostConnect(r.addr); return; } @@ -871,7 +868,7 @@ void autoConnectHidHost() { if (peer.autoConnect && peer.profileId == BT_PROFILE_HID_HOST) { if (Device* dev = device_find_first_active_by_type(&BLUETOOTH_TYPE)) { if (!bluetooth_is_scanning(dev)) { - LOGGER.info("Auto-connect HID host: device not in scan, retrying scan"); + LOG_I(TAG, "Auto-connect HID host: device not in scan, retrying scan"); bluetooth_scan_start(dev); } } diff --git a/Tactility/Source/bluetooth/BluetoothPairedDevice.cpp b/Tactility/Source/bluetooth/BluetoothPairedDevice.cpp index deb3cdee2..a6b2c99dc 100644 --- a/Tactility/Source/bluetooth/BluetoothPairedDevice.cpp +++ b/Tactility/Source/bluetooth/BluetoothPairedDevice.cpp @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include @@ -13,7 +13,7 @@ namespace tt::bluetooth::settings { -static const auto LOGGER = Logger("BluetoothPairedDevice"); +constexpr auto* TAG = "BluetoothPairedDevice"; // Use the same directory as the old service for backward compatibility. constexpr auto* DATA_DIR = "/data/service/bluetooth"; @@ -34,7 +34,7 @@ std::string addrToHex(const std::array& addr) { static bool hexToAddr(const std::string& hex, std::array& addr) { if (hex.size() != 12) { - LOGGER.error("hexToAddr() length mismatch: expected 12, got {}", hex.size()); + LOG_E(TAG, "hexToAddr() length mismatch: expected 12, got %d", (int)hex.size()); return false; } char buf[3] = { 0 }; @@ -44,7 +44,7 @@ static bool hexToAddr(const std::string& hex, std::array& addr) { char* endptr = nullptr; addr[i] = static_cast(strtoul(buf, &endptr, 16)); if (endptr != buf + 2) { - LOGGER.error("hexToAddr() invalid hex at byte {}: '{}{}'", i, buf[0], buf[1]); + LOG_E(TAG, "hexToAddr() invalid hex at byte %d: '%c%c'", i, buf[0], buf[1]); return false; } } @@ -88,7 +88,7 @@ bool save(const PairedDevice& device) { map[KEY_PROFILE_ID] = std::to_string(device.profileId); auto file_path = getFilePath(addr_hex); if (!file::findOrCreateParentDirectory(file_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", file_path); + LOG_E(TAG, "Failed to create parent dir for %s", file_path.c_str()); return false; } return file::savePropertiesFile(file_path, map); diff --git a/Tactility/Source/bluetooth/BluetoothSettings.cpp b/Tactility/Source/bluetooth/BluetoothSettings.cpp index aa1928747..6bcb70a06 100644 --- a/Tactility/Source/bluetooth/BluetoothSettings.cpp +++ b/Tactility/Source/bluetooth/BluetoothSettings.cpp @@ -2,13 +2,13 @@ #include #include -#include #include #include +#include namespace tt::bluetooth::settings { -static const auto LOGGER = Logger("BluetoothSettings"); +constexpr auto* TAG = "BluetoothSettings"; static std::string getSettingsPath() { return getUserDataPath() + "/settings/bluetooth.settings"; @@ -60,7 +60,7 @@ static bool save(const BluetoothSettings& s) { map[KEY_MIDI_AUTO_START] = s.midiAutoStart ? "true" : "false"; auto settings_path = getSettingsPath(); if (!file::findOrCreateParentDirectory(settings_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", settings_path); + LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str()); return false; } return file::savePropertiesFile(settings_path, map); @@ -84,7 +84,7 @@ void setEnableOnBoot(bool enable) { cached.enableOnBoot = enable; cached_valid = true; settings_mutex.unlock(); - if (!save(cached)) LOGGER.error("Failed to save"); + if (!save(cached)) LOG_E(TAG, "Failed to save"); } bool shouldEnableOnBoot() { @@ -96,7 +96,7 @@ void setSppAutoStart(bool enable) { cached.sppAutoStart = enable; cached_valid = true; settings_mutex.unlock(); - if (!save(cached)) LOGGER.error("Failed to save (setSppAutoStart)"); + if (!save(cached)) LOG_E(TAG, "Failed to save (setSppAutoStart)"); } bool shouldSppAutoStart() { @@ -108,7 +108,7 @@ void setMidiAutoStart(bool enable) { cached.midiAutoStart = enable; cached_valid = true; settings_mutex.unlock(); - if (!save(cached)) LOGGER.error("Failed to save (setMidiAutoStart)"); + if (!save(cached)) LOG_E(TAG, "Failed to save (setMidiAutoStart)"); } bool shouldMidiAutoStart() { diff --git a/Tactility/Source/file/ObjectFileReader.cpp b/Tactility/Source/file/ObjectFileReader.cpp index b9fe9babf..68c2fdf45 100644 --- a/Tactility/Source/file/ObjectFileReader.cpp +++ b/Tactility/Source/file/ObjectFileReader.cpp @@ -2,43 +2,43 @@ #include #include -#include +#include namespace tt::file { -static const auto LOGGER = Logger("ObjectFileReader"); +constexpr auto* TAG = "ObjectFileReader"; bool ObjectFileReader::open() { auto opening_file = std::unique_ptr(fopen(filePath.c_str(), "r")); if (opening_file == nullptr) { - LOGGER.error("Failed to open file {}", filePath.c_str()); + LOG_E(TAG, "Failed to open file %s", filePath.c_str()); return false; } FileHeader file_header; if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) { - LOGGER.error("Failed to read file header from {}", filePath); + LOG_E(TAG, "Failed to read file header from %s", filePath.c_str()); return false; } if (file_header.identifier != OBJECT_FILE_IDENTIFIER) { - LOGGER.error("Invalid file type for {}", filePath); + LOG_E(TAG, "Invalid file type for %s", filePath.c_str()); return false; } if (file_header.version != OBJECT_FILE_VERSION) { - LOGGER.error("Unknown version for {}: {}", filePath, file_header.identifier); + LOG_E(TAG, "Unknown version for %s: %u", filePath.c_str(), (unsigned)file_header.identifier); return false; } ContentHeader content_header; if (fread(&content_header, sizeof(ContentHeader), 1, opening_file.get()) != 1) { - LOGGER.error("Failed to read content header from {}", filePath); + LOG_E(TAG, "Failed to read content header from %s", filePath.c_str()); return false; } if (recordSize != content_header.recordSize) { - LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize); + LOG_E(TAG, "Record size mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordSize, (unsigned)content_header.recordSize); return false; } @@ -47,8 +47,8 @@ bool ObjectFileReader::open() { file = std::move(opening_file); - LOGGER.debug("File version: {}", file_header.version); - LOGGER.debug("Content: version = {}, size = {} bytes, count = {}", content_header.recordVersion, content_header.recordSize, content_header.recordCount); + LOG_D(TAG, "File version: %u", (unsigned)file_header.version); + LOG_D(TAG, "Content: version = %u, size = %u bytes, count = %u", (unsigned)content_header.recordVersion, (unsigned)content_header.recordSize, (unsigned)content_header.recordCount); return true; } @@ -63,7 +63,7 @@ void ObjectFileReader::close() { bool ObjectFileReader::readNext(void* output) { if (file == nullptr) { - LOGGER.error("File not open"); + LOG_E(TAG, "File not open"); return false; } diff --git a/Tactility/Source/file/ObjectFileWriter.cpp b/Tactility/Source/file/ObjectFileWriter.cpp index 471d72c81..145027b7f 100644 --- a/Tactility/Source/file/ObjectFileWriter.cpp +++ b/Tactility/Source/file/ObjectFileWriter.cpp @@ -1,24 +1,24 @@ #include #include -#include +#include #include #include namespace tt::file { -static const auto LOGGER = Logger("ObjectFileWriter"); +constexpr auto* TAG = "ObjectFileWriter"; bool ObjectFileWriter::open() { bool edit_existing = append && access(filePath.c_str(), F_OK) == 0; if (append && !edit_existing) { - LOGGER.warn("access() to {} failed: {}", filePath, strerror(errno)); + LOG_W(TAG, "access() to %s failed: %s", filePath.c_str(), strerror(errno)); } // Edit existing or create a new file auto opening_file = std::unique_ptr(std::fopen(filePath.c_str(), edit_existing ? "rb+" : "wb")); if (opening_file == nullptr) { - LOGGER.error("Failed to open file {}", filePath); + LOG_E(TAG, "Failed to open file %s", filePath.c_str()); return false; } @@ -29,17 +29,17 @@ bool ObjectFileWriter::open() { FileHeader file_header; if (fread(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) { - LOGGER.error("Failed to read file header from {}", filePath); + LOG_E(TAG, "Failed to read file header from %s", filePath.c_str()); return false; } if (file_header.identifier != OBJECT_FILE_IDENTIFIER) { - LOGGER.error("Invalid file type for {}", filePath); + LOG_E(TAG, "Invalid file type for %s", filePath.c_str()); return false; } if (file_header.version != OBJECT_FILE_VERSION) { - LOGGER.error("Unknown version for {}: {}", filePath, file_header.version); + LOG_E(TAG, "Unknown version for %s: %u", filePath.c_str(), (unsigned)file_header.version); return false; } @@ -47,17 +47,17 @@ bool ObjectFileWriter::open() { ContentHeader content_header; if (fread(&content_header, sizeof(ContentHeader), 1, opening_file.get()) != 1) { - LOGGER.error("Failed to read content header from {}", filePath); + LOG_E(TAG, "Failed to read content header from %s", filePath.c_str()); return false; } if (recordSize != content_header.recordSize) { - LOGGER.error("Record size mismatch for {}: expected {}, got {}", filePath, recordSize, content_header.recordSize); + LOG_E(TAG, "Record size mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordSize, (unsigned)content_header.recordSize); return false; } if (recordVersion != content_header.recordVersion) { - LOGGER.error("Version mismatch for {}: expected {}, got {}", filePath, recordVersion, content_header.recordVersion); + LOG_E(TAG, "Version mismatch for %s: expected %u, got %u", filePath.c_str(), (unsigned)recordVersion, (unsigned)content_header.recordVersion); return false; } @@ -66,7 +66,7 @@ bool ObjectFileWriter::open() { } else { FileHeader file_header; if (fwrite(&file_header, sizeof(FileHeader), 1, opening_file.get()) != 1) { - LOGGER.error("Failed to write file header for {}", filePath); + LOG_E(TAG, "Failed to write file header for %s", filePath.c_str()); return false; } @@ -81,12 +81,12 @@ bool ObjectFileWriter::open() { void ObjectFileWriter::close() { if (file == nullptr) { - LOGGER.error("File not opened: {}", filePath); + LOG_E(TAG, "File not opened: %s", filePath.c_str()); return; } if (fseek(file.get(), sizeof(FileHeader), SEEK_SET) != 0) { - LOGGER.error("File seek failed: {}", filePath); + LOG_E(TAG, "File seek failed: %s", filePath.c_str()); return; } @@ -97,7 +97,7 @@ void ObjectFileWriter::close() { }; if (fwrite(&content_header, sizeof(ContentHeader), 1, file.get()) != 1) { - LOGGER.error("Failed to write content header to {}", filePath); + LOG_E(TAG, "Failed to write content header to %s", filePath.c_str()); } file = nullptr; @@ -105,12 +105,12 @@ void ObjectFileWriter::close() { bool ObjectFileWriter::write(void* data) { if (file == nullptr) { - LOGGER.error("File not opened: {}", filePath); + LOG_E(TAG, "File not opened: %s", filePath.c_str()); return false; } if (fwrite(data, recordSize, 1, file.get()) != 1) { - LOGGER.error("Failed to write record to {}", filePath); + LOG_E(TAG, "Failed to write record to %s", filePath.c_str()); return false; } diff --git a/Tactility/Source/file/PropertiesFile.cpp b/Tactility/Source/file/PropertiesFile.cpp index a15c50bb3..003b4ba72 100644 --- a/Tactility/Source/file/PropertiesFile.cpp +++ b/Tactility/Source/file/PropertiesFile.cpp @@ -3,11 +3,11 @@ #include #include #include -#include +#include namespace tt::file { -static const auto LOGGER = Logger("PropertiesFile"); +constexpr auto* TAG = "PropertiesFile"; bool getKeyValuePair(const std::string& input, std::string& key, std::string& value) { auto index = input.find('='); @@ -22,7 +22,7 @@ bool getKeyValuePair(const std::string& input, std::string& key, std::string& va bool loadPropertiesFile(const std::string& filePath, std::function callback) { // Reading properties is a common operation; make this debug-level to avoid // flooding the serial console under frequent polling. - LOGGER.debug("Reading properties file {}", filePath); + LOG_D(TAG, "Reading properties file %s", filePath.c_str()); uint16_t line_count = 0; std::string key_prefix = ""; // Malformed lines are skipped, valid lines are loaded and callback is called @@ -40,7 +40,7 @@ bool loadPropertiesFile(const std::string& filePath, std::function& properties) { bool result = false; getLock(filePath)->withLock([&result, filePath, &properties] { - LOGGER.info("Saving properties file {}", filePath); + LOG_I(TAG, "Saving properties file %s", filePath.c_str()); FILE* file = fopen(filePath.c_str(), "w"); if (file == nullptr) { - LOGGER.error("Failed to open {}", filePath); + LOG_E(TAG, "Failed to open %s", filePath.c_str()); return; } diff --git a/Tactility/Source/hal/Hal.cpp b/Tactility/Source/hal/Hal.cpp index 7f7af1c07..48fcad00a 100644 --- a/Tactility/Source/hal/Hal.cpp +++ b/Tactility/Source/hal/Hal.cpp @@ -1,20 +1,20 @@ -#include #include -#include #include -#include - #include #include #include #include +#include +#include +#include + namespace tt::hal { -static const auto LOGGER = Logger("Hal"); +constexpr auto* TAG = "Hal"; void registerDevices(const Configuration& configuration) { - LOGGER.info("Registering devices"); + LOG_I(TAG, "Registering devices"); auto devices = configuration.createDevices(); for (auto& device : devices) { @@ -33,27 +33,27 @@ void registerDevices(const Configuration& configuration) { } static void startDisplays() { - LOGGER.info("Starting displays & touch"); + LOG_I(TAG, "Starting displays & touch"); auto displays = hal::findDevices(Device::Type::Display); for (auto& display : displays) { - LOGGER.info("{} starting", display->getName()); + LOG_I(TAG, "%s starting", display->getName().c_str()); if (!display->start()) { - LOGGER.error("{} start failed", display->getName()); + LOG_E(TAG, "%s start failed", display->getName().c_str()); } else { - LOGGER.info("{} started", display->getName()); + LOG_I(TAG, "%s started", display->getName().c_str()); if (display->supportsBacklightDuty()) { - LOGGER.info("Setting backlight"); + LOG_I(TAG, "Setting backlight"); display->setBacklightDuty(0); } auto touch = display->getTouchDevice(); if (touch != nullptr) { - LOGGER.info("{} starting", touch->getName()); + LOG_I(TAG, "%s starting", touch->getName().c_str()); if (!touch->start()) { - LOGGER.error("{} start failed", touch->getName()); + LOG_E(TAG, "%s start failed", touch->getName().c_str()); } else { - LOGGER.info("{} started", touch->getName()); + LOG_I(TAG, "%s started", touch->getName().c_str()); } } } diff --git a/Tactility/Source/hal/gps/GpsDevice.cpp b/Tactility/Source/hal/gps/GpsDevice.cpp index 10c964f59..b6184fa48 100644 --- a/Tactility/Source/hal/gps/GpsDevice.cpp +++ b/Tactility/Source/hal/gps/GpsDevice.cpp @@ -1,26 +1,25 @@ #include #include #include -#include +#include #include #include -#include #include namespace tt::hal::gps { constexpr uint32_t GPS_UART_BUFFER_SIZE = 256; -static const auto LOGGER = Logger("GpsDevice"); +constexpr auto* TAG = "GpsDevice"; int32_t GpsDevice::threadMain() { uint8_t buffer[GPS_UART_BUFFER_SIZE]; auto* uart = device_find_by_name(configuration.uartName); if (uart == nullptr) { - LOGGER.error("Failed to find UART {}", configuration.uartName); + LOG_E(TAG, "Failed to find UART %s", configuration.uartName); return -1; } @@ -33,13 +32,13 @@ int32_t GpsDevice::threadMain() { error_t error = uart_controller_set_config(uart, &uartConfig); if (error != ERROR_NONE) { - LOGGER.error("Failed to configure UART {}: {}", configuration.uartName, error_to_string(error)); + LOG_E(TAG, "Failed to configure UART %s: %s", configuration.uartName, error_to_string(error)); return -1; } error = uart_controller_open(uart); if (error != ERROR_NONE) { - LOGGER.error("Failed to open UART {}: {}", configuration.uartName, error_to_string(error)); + LOG_E(TAG, "Failed to open UART %s: %s", configuration.uartName, error_to_string(error)); return -1; } @@ -47,7 +46,7 @@ int32_t GpsDevice::threadMain() { if (model == GpsModel::Unknown) { model = probe(uart); if (model == GpsModel::Unknown) { - LOGGER.error("Probe failed"); + LOG_E(TAG, "Probe failed"); setState(State::Error); return -1; } @@ -57,7 +56,7 @@ int32_t GpsDevice::threadMain() { mutex.unlock(); if (!init(uart, model)) { - LOGGER.error("Init failed"); + LOG_E(TAG, "Init failed"); setState(State::Error); return -1; } @@ -76,7 +75,7 @@ int32_t GpsDevice::threadMain() { if (bytes_read > 0U) { - LOGGER.info("[{}] {}", bytes_read, reinterpret_cast(buffer)); + LOG_I(TAG, "[%d] %s", (int)bytes_read, reinterpret_cast(buffer)); switch (minmea_sentence_id((char*)buffer, false)) { case MINMEA_SENTENCE_RMC: @@ -87,11 +86,9 @@ int32_t GpsDevice::threadMain() { (*subscription.onData)(getId(), rmc_frame); } mutex.unlock(); - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("RMC {} lat, {} lon, {} m/s", minmea_tocoord(&rmc_frame.latitude), minmea_tocoord(&rmc_frame.longitude), minmea_tofloat(&rmc_frame.speed)); - } + LOG_D(TAG, "RMC %f lat, %f lon, %f m/s", minmea_tocoord(&rmc_frame.latitude), minmea_tocoord(&rmc_frame.longitude), minmea_tofloat(&rmc_frame.speed)); } else { - LOGGER.error("RMC parse error: {}", reinterpret_cast(buffer)); + LOG_E(TAG, "RMC parse error: %s", reinterpret_cast(buffer)); } break; case MINMEA_SENTENCE_GGA: @@ -102,11 +99,9 @@ int32_t GpsDevice::threadMain() { (*subscription.onData)(getId(), gga_frame); } mutex.unlock(); - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("GGA {} lat, {} lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude)); - } + LOG_D(TAG, "GGA %f lat, %f lon", minmea_tocoord(&gga_frame.latitude), minmea_tocoord(&gga_frame.longitude)); } else { - LOGGER.error("GGA parse error: {}", reinterpret_cast(buffer)); + LOG_E(TAG, "GGA parse error: %s", reinterpret_cast(buffer)); } break; default: @@ -116,7 +111,7 @@ int32_t GpsDevice::threadMain() { } if (uart_controller_close(uart) != ERROR_NONE) { - LOGGER.warn("Failed to stop UART {}", configuration.uartName); + LOG_W(TAG, "Failed to stop UART %s", configuration.uartName); } return 0; @@ -127,13 +122,13 @@ bool GpsDevice::start() { lock.lock(); if (thread != nullptr && thread->getState() != Thread::State::Stopped) { - LOGGER.warn("Already started"); + LOG_W(TAG, "Already started"); return true; } threadInterrupted = false; - LOGGER.info("Starting thread"); + LOG_I(TAG, "Starting thread"); setState(State::PendingOn); thread = std::make_unique( @@ -146,7 +141,7 @@ bool GpsDevice::start() { thread->setPriority(tt::Thread::Priority::High); thread->start(); - LOGGER.info("Starting finished"); + LOG_I(TAG, "Starting finished"); return true; } diff --git a/Tactility/Source/hal/gps/GpsInit.cpp b/Tactility/Source/hal/gps/GpsInit.cpp index 7deeb7cb1..f3501f4cf 100644 --- a/Tactility/Source/hal/gps/GpsInit.cpp +++ b/Tactility/Source/hal/gps/GpsInit.cpp @@ -1,18 +1,18 @@ -#include -#include #include #include #include #include +#include #include #include +#include #include namespace tt::hal::gps { -static const auto LOGGER = Logger("Gps"); +constexpr auto* TAG = "Gps"; bool initMtk(::Device* uart); bool initMtkL76b(::Device* uart); @@ -118,7 +118,7 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t // Check for an ACK-ACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x01) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOGGER.info("Got ACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, kernel::getMillis() - startTime); + LOG_I(TAG, "Got ACK for class %02X message %02X in %zu ms", class_id, msg_id, kernel::getMillis() - startTime); #endif return GpsResponse::Ok; } @@ -126,7 +126,7 @@ GpsResponse getACKCas(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t // Check for an ACK-NACK for the specified class and message id if ((msg_cls == 0x05) && (msg_msg_id == 0x00) && payload_cls == class_id && payload_msg == msg_id) { #ifdef GPS_DEBUG - LOGGER.warn("Got NACK for class {:02X} message {:02X} in {} ms", class_id, msg_id, millis() - startTime); + LOG_W(TAG, "Got NACK for class %02X message %02X in %zu ms", class_id, msg_id, millis() - startTime); #endif return GpsResponse::NotAck; } @@ -169,7 +169,7 @@ bool init(::Device* uart, GpsModel type) { return initUc6580(uart); } - LOGGER.info("Init not implemented {}", static_cast(type)); + LOG_I(TAG, "Init not implemented %d", static_cast(type)); return false; } @@ -219,14 +219,14 @@ bool initAtgm336h(::Device* uart) { int msglen = makeCASPacket(buffer, 0x06, 0x07, sizeof(_message_CAS_CFG_NAVX_CONF), _message_CAS_CFG_NAVX_CONF); uart_controller_write_bytes(uart, buffer, msglen, 250); if (getACKCas(uart, 0x06, 0x07, 250) != GpsResponse::Ok) { - LOGGER.warn("ATGM336H: Could not set Config"); + LOG_W(TAG, "ATGM336H: Could not set Config"); } // Set the update frequence to 1Hz msglen = makeCASPacket(buffer, 0x06, 0x04, sizeof(_message_CAS_CFG_RATE_1HZ), _message_CAS_CFG_RATE_1HZ); uart_controller_write_bytes(uart, buffer, msglen, 250); if (getACKCas(uart, 0x06, 0x04, 250) != GpsResponse::Ok) { - LOGGER.warn("ATGM336H: Could not set Update Frequency"); + LOG_W(TAG, "ATGM336H: Could not set Update Frequency"); } // Set the NEMA output messages @@ -238,7 +238,7 @@ bool initAtgm336h(::Device* uart) { msglen = makeCASPacket(buffer, 0x06, 0x01, sizeof(cas_cfg_msg_packet), cas_cfg_msg_packet); uart_controller_write_bytes(uart, buffer, msglen, 250); if (getACKCas(uart, 0x06, 0x01, 250) != GpsResponse::Ok) { - LOGGER.warn("ATGM336H: Could not enable NMEA MSG: {}", fields[i]); + LOG_W(TAG, "ATGM336H: Could not enable NMEA MSG: %u", fields[i]); } } return true; diff --git a/Tactility/Source/hal/gps/Probe.cpp b/Tactility/Source/hal/gps/Probe.cpp index 0dc2402fe..d5a8ca0bb 100644 --- a/Tactility/Source/hal/gps/Probe.cpp +++ b/Tactility/Source/hal/gps/Probe.cpp @@ -1,14 +1,14 @@ #include "Tactility/hal/gps/GpsDevice.h" #include "Tactility/hal/gps/Ublox.h" -#include #include #include #include +#include #include -static const auto LOGGER = tt::Logger("Gps"); +constexpr auto* TAG = "Gps"; #define GPS_UART_BUFFER_SIZE 256 @@ -65,13 +65,13 @@ GpsResponse getAck(::Device* uart, const char* message, uint32_t waitMillis) { if ((bytesRead == 767) || (b == '\r')) { if (strnstr((char*)buffer, message, bytesRead) != nullptr) { #ifdef GPS_DEBUG - LOGGER.debug("Found: {}", message); // Log the found message + LOG_D(TAG, "Found: %s", message); // Log the found message #endif return GpsResponse::Ok; } else { bytesRead = 0; #ifdef GPS_DEBUG - LOGGER.debug("{}", debugmsg); + LOG_D(TAG, "%s", debugmsg.c_str()); #endif } } @@ -85,11 +85,11 @@ GpsResponse getAck(::Device* uart, const char* message, uint32_t waitMillis) { */ #define PROBE_SIMPLE(UART, CHIP, TOWRITE, RESPONSE, DRIVER, TIMEOUT, ...) \ do { \ - LOGGER.info("Probing for {} ({})", CHIP, TOWRITE); \ + LOG_I(TAG, "Probing for %s (%s)", CHIP, TOWRITE); \ uart_controller_flush_input(UART); \ uart_controller_write_bytes(UART, (const uint8_t*)(TOWRITE "\r\n"), strlen(TOWRITE "\r\n"), TIMEOUT); \ if (getAck(UART, RESPONSE, TIMEOUT) == GpsResponse::Ok) { \ - LOGGER.info("Probe detected {} {}", CHIP, #DRIVER); \ + LOG_I(TAG, "Probe detected %s %s", CHIP, #DRIVER); \ return DRIVER; \ } \ } while (0) @@ -138,7 +138,7 @@ GpsModel probe(::Device* uart) { if (ublox_result != GpsModel::Unknown) { return ublox_result; } else { - LOGGER.warn("No GNSS Module"); + LOG_W(TAG, "No GNSS Module"); return GpsModel::Unknown; } } diff --git a/Tactility/Source/hal/gps/Satellites.cpp b/Tactility/Source/hal/gps/Satellites.cpp index 83e398f9e..a7d30ca4e 100644 --- a/Tactility/Source/hal/gps/Satellites.cpp +++ b/Tactility/Source/hal/gps/Satellites.cpp @@ -1,10 +1,11 @@ #include #include -#include + +#include namespace tt::hal::gps { -static const auto LOGGER = Logger("Satellites"); +constexpr auto* TAG = "Satellites"; constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) { return (TickType_t)(now - timeInThePast) >= expireTimeInTicks; @@ -33,9 +34,7 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findUnusedRecord() { if (!result.empty()) { auto* record = &result.front(); record->inUse = true; - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Found unused record"); - } + LOG_D(TAG, "Found unused record"); return record; } else { return nullptr; @@ -53,9 +52,7 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() { for (int i = 0; i < records.size(); ++i) { // First try to find a record that is "old enough" if (hasTimeElapsed(now, records[i].lastUpdated, expire_duration)) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("! [{}] {} < {}", i, records[i].lastUpdated, expire_duration); - } + LOG_D(TAG, "! [%d] %u < %u", i, records[i].lastUpdated, expire_duration); candidate_index = i; break; } @@ -64,17 +61,13 @@ SatelliteStorage::SatelliteRecord* SatelliteStorage::findRecordToRecycle() { if (records[i].inUse && records[i].lastUpdated < candidate_age) { candidate_index = i; candidate_age = records[i].lastUpdated; - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("? [{}] {} < {}", i, records[i].lastUpdated, candidate_age); - } + LOG_D(TAG, "? [%d] %u < %u", i, records[i].lastUpdated, candidate_age); } } assert(candidate_index != -1); - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Recycled record {}", candidate_index); - } + LOG_D(TAG, "Recycled record %d", candidate_index); return &records[candidate_index]; } @@ -101,9 +94,7 @@ void SatelliteStorage::notify(const minmea_sat_info& data) { record->inUse = true; record->lastUpdated = kernel::getTicks(); record->data = data; - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Updated satellite {}: elevation {}, azimuth {}, snr {}", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr); - } + LOG_D(TAG, "Updated satellite %d: elevation %d, azimuth %d, snr %d", record->data.nr, record->data.elevation, record->data.elevation, record->data.snr); } } diff --git a/Tactility/Source/hal/gps/Ublox.cpp b/Tactility/Source/hal/gps/Ublox.cpp index be8d15e48..bed6861f8 100644 --- a/Tactility/Source/hal/gps/Ublox.cpp +++ b/Tactility/Source/hal/gps/Ublox.cpp @@ -1,16 +1,16 @@ #include #include #include -#include #include #include +#include #include namespace tt::hal::gps::ublox { -static const auto LOGGER = Logger("Ublox"); +constexpr auto* TAG = "Ublox"; bool initUblox6(::Device* uart); bool initUblox789(::Device* uart, GpsModel model); @@ -21,7 +21,7 @@ bool initUblox10(::Device* uart); auto msglen = makePacket(TYPE, ID, DATA, sizeof(DATA), BUFFER); \ uart_controller_write_bytes(UART, BUFFER, msglen, TIMEOUT_MILLIS / portTICK_PERIOD_MS); \ if (getAck(UART, TYPE, ID, TIMEOUT_MILLIS) != GpsResponse::Ok) { \ - LOGGER.info("Sending packet failed: {}", #ERRMSG); \ + LOG_I(TAG, "Sending packet failed: %s", #ERRMSG); \ } \ } while (0) @@ -85,7 +85,7 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa while (kernel::getTicks() - startTime < waitTicks) { if (ack > 9) { #ifdef GPS_DEBUG - LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", class_id, msg_id, kernel::getMillis() - startTime); + LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", class_id, msg_id, kernel::getMillis() - startTime); #endif return GpsResponse::Ok; // ACK received } @@ -98,7 +98,7 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa if (sCounter == 26) { #ifdef GPS_DEBUG - LOGGER.info("%s", debugmsg.c_str()); + LOG_I(TAG, "%s", debugmsg.c_str()); #endif return GpsResponse::FrameErrors; } @@ -113,9 +113,9 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa } else { if (ack == 3 && b == 0x00) { // UBX-ACK-NAK message #ifdef GPS_DEBUG - LOGGER.info("%s", debugmsg.c_str()); + LOG_I(TAG, "%s", debugmsg.c_str()); #endif - LOGGER.warn("Got NAK for class {:02X} message {:02X}", class_id, msg_id); + LOG_W(TAG, "Got NAK for class %02X message %02X", class_id, msg_id); return GpsResponse::NotAck; // NAK received } ack = 0; // Reset the acknowledgement counter @@ -123,8 +123,8 @@ GpsResponse getAck(::Device* uart, uint8_t class_id, uint8_t msg_id, uint32_t wa } } #ifdef GPS_DEBUG - LOGGER.info("%s", debugmsg.c_str()); - LOGGER.warn("No response for class %02X message %02X", class_id, msg_id); + LOG_I(TAG, "%s", debugmsg.c_str()); + LOG_W(TAG, "No response for class %02X message %02X", class_id, msg_id); #endif return GpsResponse::None; // No response received within timeout } @@ -190,7 +190,7 @@ static int getAck(::Device* uart, uint8_t* buffer, uint16_t size, uint8_t reques } else { // return payload length #ifdef GPS_DEBUG - LOGGER.info("Got ACK for class {:02X} message {:02X} in {}ms", requestedClass, requestedId, kernel::getMillis() - startTime); + LOG_I(TAG, "Got ACK for class %02X message %02X in %zums", requestedClass, requestedId, kernel::getMillis() - startTime); #endif return needRead; } @@ -214,8 +214,7 @@ static struct uBloxGnssModelInfo { } ublox_info; GpsModel probe(::Device* uart) { - LOGGER.info("Probing for U-blox"); - constexpr auto DETECTED_MESSAGE = "{} detected, using {} Module"; + LOG_I(TAG, "Probing for U-blox"); uint8_t cfg_rate[] = {0xB5, 0x62, 0x06, 0x08, 0x00, 0x00, 0x00, 0x00}; checksum(cfg_rate, sizeof(cfg_rate)); @@ -224,10 +223,10 @@ GpsModel probe(::Device* uart) { // Check that the returned response class and message ID are correct GpsResponse response = getAck(uart, 0x06, 0x08, 750); if (response == GpsResponse::None) { - LOGGER.warn("No GNSS Module"); + LOG_W(TAG, "No GNSS Module"); return GpsModel::Unknown; } else if (response == GpsResponse::FrameErrors) { - LOGGER.warn("UBlox Frame Errors"); + LOG_W(TAG, "UBlox Frame Errors"); } uint8_t buffer[256]; @@ -265,12 +264,12 @@ GpsModel probe(::Device* uart) { break; } - LOGGER.info("Module Info:"); - LOGGER.info("Soft version: {}", ublox_info.swVersion); - LOGGER.info("Hard version: {}", ublox_info.hwVersion); - LOGGER.info("Extensions: {}", ublox_info.extensionNo); + LOG_I(TAG, "Module Info:"); + LOG_I(TAG, "Soft version: %s", ublox_info.swVersion); + LOG_I(TAG, "Hard version: %s", ublox_info.hwVersion); + LOG_I(TAG, "Extensions: %u", ublox_info.extensionNo); for (int i = 0; i < ublox_info.extensionNo; i++) { - LOGGER.info(" %s", ublox_info.extension[i]); + LOG_I(TAG, " %s", ublox_info.extension[i]); } memset(buffer, 0, sizeof(buffer)); @@ -283,29 +282,30 @@ GpsModel probe(::Device* uart) { char* ptr = nullptr; memset(buffer, 0, sizeof(buffer)); strncpy((char*)buffer, &(ublox_info.extension[i][8]), sizeof(buffer)); - LOGGER.info("Protocol Version: {}", (char*)buffer); + LOG_I(TAG, "Protocol Version: %s", (char*)buffer); if (strlen((char*)buffer)) { ublox_info.protocol_version = strtoul((char*)buffer, &ptr, 10); - LOGGER.info("ProtVer={}", ublox_info.protocol_version); + LOG_I(TAG, "ProtVer=%u", ublox_info.protocol_version); } else { ublox_info.protocol_version = 0; } } } + #define DETECTED_MESSAGE "%s detected, using %s Module" if (strncmp(ublox_info.hwVersion, "00040007", 8) == 0) { - LOGGER.info(DETECTED_MESSAGE, "U-blox 6", "6"); + LOG_I(TAG, DETECTED_MESSAGE, "U-blox 6", "6"); return GpsModel::UBLOX6; } else if (strncmp(ublox_info.hwVersion, "00070000", 8) == 0) { - LOGGER.info(DETECTED_MESSAGE, "U-blox 7", "7"); + LOG_I(TAG, DETECTED_MESSAGE, "U-blox 7", "7"); return GpsModel::UBLOX7; } else if (strncmp(ublox_info.hwVersion, "00080000", 8) == 0) { - LOGGER.info(DETECTED_MESSAGE, "U-blox 8", "8"); + LOG_I(TAG, DETECTED_MESSAGE, "U-blox 8", "8"); return GpsModel::UBLOX8; } else if (strncmp(ublox_info.hwVersion, "00190000", 8) == 0) { - LOGGER.info(DETECTED_MESSAGE, "U-blox 9", "9"); + LOG_I(TAG, DETECTED_MESSAGE, "U-blox 9", "9"); return GpsModel::UBLOX9; } else if (strncmp(ublox_info.hwVersion, "000A0000", 8) == 0) { - LOGGER.info(DETECTED_MESSAGE, "U-blox 10", "10"); + LOG_I(TAG, DETECTED_MESSAGE, "U-blox 10", "10"); return GpsModel::UBLOX10; } } @@ -314,7 +314,7 @@ GpsModel probe(::Device* uart) { } bool init(::Device* uart, GpsModel model) { - LOGGER.info("U-blox init"); + LOG_I(TAG, "U-blox init"); switch (model) { case GpsModel::UBLOX6: return initUblox6(uart); @@ -325,7 +325,7 @@ bool init(::Device* uart, GpsModel model) { case GpsModel::UBLOX10: return initUblox10(uart); default: - LOGGER.error("Unknown or unsupported U-blox model"); + LOG_E(TAG, "Unknown or unsupported U-blox model"); return false; } } @@ -374,9 +374,9 @@ bool initUblox10(::Device* uart) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE_10, sizeof(_message_SAVE_10), buffer); uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - LOGGER.warn("Unable to save GNSS module config"); + LOG_W(TAG, "Unable to save GNSS module config"); } else { - LOGGER.info("GNSS module configuration saved!"); + LOG_I(TAG, "GNSS module configuration saved!"); } return true; } @@ -384,7 +384,7 @@ bool initUblox10(::Device* uart) { bool initUblox789(::Device* uart, GpsModel model) { uint8_t buffer[256]; if (model == GpsModel::UBLOX7) { - LOGGER.debug("Set GPS+SBAS"); + LOG_D(TAG, "Set GPS+SBAS"); auto msglen = makePacket(0x06, 0x3e, _message_GNSS_7, sizeof(_message_GNSS_7), buffer); uart_controller_write_bytes(uart, buffer, msglen, 800 / portTICK_PERIOD_MS); } else { // 8,9 @@ -394,12 +394,12 @@ bool initUblox789(::Device* uart, GpsModel model) { if (getAck(uart, 0x06, 0x3e, 800) == GpsResponse::NotAck) { // It's not critical if the module doesn't acknowledge this configuration. - LOGGER.debug("reconfigure GNSS - defaults maintained. Is this module GPS-only?"); + LOG_D(TAG, "reconfigure GNSS - defaults maintained. Is this module GPS-only?"); } else { if (model == GpsModel::UBLOX7) { - LOGGER.info("GPS+SBAS configured"); + LOG_I(TAG, "GPS+SBAS configured"); } else { // 8,9 - LOGGER.info("GPS+SBAS+GLONASS+Galileo configured"); + LOG_I(TAG, "GPS+SBAS+GLONASS+Galileo configured"); } // Documentation say, we need wait at least 0.5s after reconfiguration of GNSS module, before sending next // commands for the M8 it tends to be more. 1 sec should be enough @@ -448,9 +448,9 @@ bool initUblox789(::Device* uart, GpsModel model) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); uart_controller_write_bytes(uart, buffer, packet_size, 2000 / portTICK_PERIOD_MS); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - LOGGER.warn("Unable to save GNSS module config"); + LOG_W(TAG, "Unable to save GNSS module config"); } else { - LOGGER.info("GNSS module configuration saved!"); + LOG_I(TAG, "GNSS module configuration saved!"); } return true; } @@ -482,9 +482,9 @@ bool initUblox6(::Device* uart) { auto packet_size = makePacket(0x06, 0x09, _message_SAVE, sizeof(_message_SAVE), buffer); uart_controller_write_bytes(uart, buffer, packet_size, 2000); if (getAck(uart, 0x06, 0x09, 2000) != GpsResponse::Ok) { - LOGGER.warn("Unable to save GNSS module config"); + LOG_W(TAG, "Unable to save GNSS module config"); } else { - LOGGER.info("GNSS module config saved!"); + LOG_I(TAG, "GNSS module config saved!"); } return true; } diff --git a/Tactility/Source/hal/usb/Usb.cpp b/Tactility/Source/hal/usb/Usb.cpp index 880f6ca47..f02a0b866 100644 --- a/Tactility/Source/hal/usb/Usb.cpp +++ b/Tactility/Source/hal/usb/Usb.cpp @@ -5,14 +5,14 @@ #include #include -#include #include #include #include +#include namespace tt::hal::usb { -static const auto LOGGER = Logger("USB"); +constexpr auto* TAG = "USB"; constexpr auto BOOT_FLAG_SDMMC = 42; // Existing constexpr auto BOOT_FLAG_FLASH = 43; // For flash mode @@ -38,7 +38,7 @@ sdmmc_card_t* getCard() { }); if (card == nullptr) { - LOGGER.warn("Couldn't find a mounted SD card"); + LOG_W(TAG, "Couldn't find a mounted SD card"); } return card; @@ -54,7 +54,7 @@ bool isSupported() { bool startMassStorageWithSdmmc(bool fromBootMode) { if (!canStartNewMode()) { - LOGGER.error("Can't start"); + LOG_E(TAG, "Can't start"); return false; } @@ -62,7 +62,7 @@ bool startMassStorageWithSdmmc(bool fromBootMode) { currentMode = Mode::MassStorageSdmmc; return true; } else { - LOGGER.error("Failed to init mass storage"); + LOG_E(TAG, "Failed to init mass storage"); return false; } } @@ -95,7 +95,7 @@ void rebootIntoMassStorageSdmmc() { // NEW: Flash mass storage functions bool startMassStorageWithFlash(bool fromBootMode) { if (!canStartNewMode()) { - LOGGER.error("Can't start flash mass storage"); + LOG_E(TAG, "Can't start flash mass storage"); return false; } @@ -103,7 +103,7 @@ bool startMassStorageWithFlash(bool fromBootMode) { currentMode = Mode::MassStorageFlash; return true; } else { - LOGGER.error("Failed to init flash mass storage"); + LOG_E(TAG, "Failed to init flash mass storage"); return false; } } diff --git a/Tactility/Source/hal/usb/UsbTusb.cpp b/Tactility/Source/hal/usb/UsbTusb.cpp index e68afcd29..73fc8f063 100644 --- a/Tactility/Source/hal/usb/UsbTusb.cpp +++ b/Tactility/Source/hal/usb/UsbTusb.cpp @@ -7,7 +7,6 @@ #if CONFIG_TINYUSB_MSC_ENABLED == 1 -#include #include #include #include @@ -15,6 +14,8 @@ #include #include +#include + #if CONFIG_IDF_TARGET_ESP32P4 #include "hal/usb_wrap_ll.h" #endif @@ -23,7 +24,7 @@ #define TUSB_DESC_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_MSC_DESC_LEN) #define SECTOR_SIZE 512 -static const auto LOGGER = tt::Logger("USB"); +constexpr auto* TAG = "USB"; namespace tt::hal::usb { extern sdmmc_card_t* getCard(); @@ -105,18 +106,18 @@ static uint8_t const msc_hs_configuration_desc[] = { static void storage_mount_changed_cb(tinyusb_msc_event_t* event) { if (event->mount_changed_data.is_mounted) { - LOGGER.info("MSC Mounted"); + LOG_I(TAG, "MSC Mounted"); // Storage is only (re)mounted into our own filesystem after the host sends a SCSI // START STOP UNIT eject (see tud_msc_start_stop_cb() in tusb_msc_storage.c). Windows // is known not to send this reliably, so this is a best-effort path for hosts that do // (e.g. Linux/macOS) - the "Return to OS" button on the boot screen is the primary one. // If we got here while booted into MSC mode, it's safe to reboot back into normal OS now. if (startedFromBootMode) { - LOGGER.info("MSC ejected by host, rebooting into normal OS"); + LOG_I(TAG, "MSC ejected by host, rebooting into normal OS"); esp_restart(); } } else { - LOGGER.info("MSC Unmounted"); + LOG_I(TAG, "MSC Unmounted"); } } @@ -149,7 +150,7 @@ static bool ensureDriverInstalled() { }; if (tinyusb_driver_install(&tusb_cfg) != ESP_OK) { - LOGGER.error("Failed to install TinyUSB driver"); + LOG_E(TAG, "Failed to install TinyUSB driver"); #if CONFIG_IDF_TARGET_ESP32P4 // Roll back routing when TinyUSB did not start. usb_wrap_ll_phy_select(&USB_WRAP, 1); @@ -171,7 +172,7 @@ bool tusbStartMassStorageWithSdmmc(bool fromBootMode) { auto* card = tt::hal::usb::getCard(); if (card == nullptr) { - LOGGER.error("SD card not mounted"); + LOG_E(TAG, "SD card not mounted"); return false; } @@ -190,16 +191,16 @@ bool tusbStartMassStorageWithSdmmc(bool fromBootMode) { auto result = tinyusb_msc_storage_init_sdmmc(&config_sdmmc); if (result != ESP_OK) { - LOGGER.error("TinyUSB SDMMC init failed: {}", esp_err_to_name(result)); + LOG_E(TAG, "TinyUSB SDMMC init failed: %s", esp_err_to_name(result)); } else { - LOGGER.info("TinyUSB SDMMC init success"); + LOG_I(TAG, "TinyUSB SDMMC init success"); } return result == ESP_OK; } bool tusbStartMassStorageWithFlash(bool fromBootMode) { - LOGGER.info("Starting flash MSC"); + LOG_I(TAG, "Starting flash MSC"); if (!ensureDriverInstalled()) { return false; } @@ -207,7 +208,7 @@ bool tusbStartMassStorageWithFlash(bool fromBootMode) { wl_handle_t handle = tt::getDataPartitionWlHandle(); if (handle == WL_INVALID_HANDLE) { - LOGGER.error("WL not mounted for /data"); + LOG_E(TAG, "WL not mounted for /data"); return false; } @@ -226,9 +227,9 @@ bool tusbStartMassStorageWithFlash(bool fromBootMode) { esp_err_t result = tinyusb_msc_storage_init_spiflash(&config_flash); if (result != ESP_OK) { - LOGGER.error("TinyUSB flash init failed: {}", esp_err_to_name(result)); + LOG_E(TAG, "TinyUSB flash init failed: %s", esp_err_to_name(result)); } else { - LOGGER.info("TinyUSB flash init success"); + LOG_I(TAG, "TinyUSB flash init success"); } return result == ESP_OK; } diff --git a/Tactility/Source/i18n/TextResources.cpp b/Tactility/Source/i18n/TextResources.cpp index 14c2fd76f..814dafa8d 100644 --- a/Tactility/Source/i18n/TextResources.cpp +++ b/Tactility/Source/i18n/TextResources.cpp @@ -2,15 +2,16 @@ #include #include -#include #include +#include + #include #include namespace tt::i18n { -static const auto LOGGER = Logger("I18n"); +constexpr auto* TAG = "I18n"; static std::string getFallbackLocale() { return "en-US"; @@ -39,7 +40,7 @@ static std::string getI18nDataFilePath(const std::string& path) { if (file::isFile(desired_file_path)) { return desired_file_path; } else { - LOGGER.warn("Translations not found for {} at {}", locale, desired_file_path); + LOG_W(TAG, "Translations not found for %s at %s", locale.c_str(), desired_file_path.c_str()); } auto fallback_locale = getFallbackLocale(); @@ -47,7 +48,7 @@ static std::string getI18nDataFilePath(const std::string& path) { if (file::isFile(fallback_file_path)) { return fallback_file_path; } else { - LOGGER.warn("Fallback translations not found for {} at {}", fallback_locale, fallback_file_path); + LOG_W(TAG, "Fallback translations not found for %s at %s", fallback_locale.c_str(), fallback_file_path.c_str()); return ""; } } @@ -60,7 +61,7 @@ bool TextResources::load() { // Resolve the language file that we need (depends on system language selection) auto file_path = getI18nDataFilePath(path); if (file_path.empty()) { - LOGGER.error("Couldn't find i18n data for {}", path); + LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str()); return false; } @@ -69,7 +70,7 @@ bool TextResources::load() { }); if (new_data.empty()) { - LOGGER.error("Couldn't find i18n data for {}", path); + LOG_E(TAG, "Couldn't find i18n data for %s", path.c_str()); return false; } diff --git a/Tactility/Source/kernel/SystemEvents.cpp b/Tactility/Source/kernel/SystemEvents.cpp index ae1532eaa..c729f17b4 100644 --- a/Tactility/Source/kernel/SystemEvents.cpp +++ b/Tactility/Source/kernel/SystemEvents.cpp @@ -1,15 +1,15 @@ #include -#include #include #include +#include #include #include namespace tt::kernel { -static const auto LOGGER = Logger("SystemEvents"); +constexpr auto* TAG = "SystemEvents"; struct SubscriptionData { SystemEventSubscription id; @@ -42,7 +42,7 @@ static const char* getEventName(SystemEvent event) { } void publishSystemEvent(SystemEvent event) { - LOGGER.info("{}", getEventName(event)); + LOG_I(TAG, "%s", getEventName(event)); if (mutex.lock(MAX_TICKS)) { for (auto& subscription : subscriptions) { diff --git a/Tactility/Source/lvgl/Lvgl.cpp b/Tactility/Source/lvgl/Lvgl.cpp index b6a3af208..672ab46fb 100644 --- a/Tactility/Source/lvgl/Lvgl.cpp +++ b/Tactility/Source/lvgl/Lvgl.cpp @@ -3,13 +3,13 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include @@ -17,26 +17,26 @@ namespace tt::lvgl { -static const auto LOGGER = Logger("LVGL"); +constexpr auto* TAG = "LVGL"; bool isStarted() { return module_is_started(&lvgl_module); } void attachDevices() { - LOGGER.info("Adding devices"); + LOG_I(TAG, "Adding devices"); auto lock = getSyncLock()->asScopedLock(); lock.lock(); // Start displays (their related touch devices start automatically within) - LOGGER.info("Start displays"); + LOG_I(TAG, "Start displays"); auto displays = hal::findDevices(hal::Device::Type::Display); for (const auto& display: displays) { if (display->supportsLvgl()) { if (display->startLvgl()) { - LOGGER.info("Started {}", display->getName()); + LOG_I(TAG, "Started %s", display->getName().c_str()); auto lvgl_display = display->getLvglDisplay(); assert(lvgl_display != nullptr); auto settings = settings::display::loadOrGetDefault(); @@ -45,7 +45,7 @@ void attachDevices() { lv_display_set_rotation(lvgl_display, rotation); } } else { - LOGGER.error("Start failed for {}", display->getName()); + LOG_E(TAG, "Start failed for %s", display->getName().c_str()); } } } @@ -57,42 +57,42 @@ void attachDevices() { // Start display-related peripherals if (primary_display != nullptr) { - LOGGER.info("Start touch devices"); + LOG_I(TAG, "Start touch devices"); auto touch_devices = hal::findDevices(hal::Device::Type::Touch); for (const auto& touch_device: touch_devices) { // Start any touch devices that haven't been started yet if (touch_device->supportsLvgl() && touch_device->getLvglIndev() == nullptr) { if (touch_device->startLvgl(primary_display->getLvglDisplay())) { - LOGGER.info("Started {}", touch_device->getName()); + LOG_I(TAG, "Started %s", touch_device->getName().c_str()); } else { - LOGGER.error("Start failed for {}", touch_device->getName()); + LOG_E(TAG, "Start failed for %s", touch_device->getName().c_str()); } } } // Start keyboards - LOGGER.info("Start keyboards"); + LOG_I(TAG, "Start keyboards"); auto keyboards = hal::findDevices(hal::Device::Type::Keyboard); for (const auto& keyboard: keyboards) { if (keyboard->isAttached()) { if (keyboard->startLvgl(primary_display->getLvglDisplay())) { lv_indev_t* keyboard_indev = keyboard->getLvglIndev(); hardware_keyboard_set_indev(keyboard_indev); - LOGGER.info("Started {}", keyboard->getName()); + LOG_I(TAG, "Started %s", keyboard->getName().c_str()); } else { - LOGGER.error("Start failed for {}", keyboard->getName()); + LOG_E(TAG, "Start failed for %s", keyboard->getName().c_str()); } } } // Start encoders - LOGGER.info("Start encoders"); + LOG_I(TAG, "Start encoders"); auto encoders = hal::findDevices(hal::Device::Type::Encoder); for (const auto& encoder: encoders) { if (encoder->startLvgl(primary_display->getLvglDisplay())) { - LOGGER.info("Started {}", encoder->getName()); + LOG_I(TAG, "Started %s", encoder->getName().c_str()); } else { - LOGGER.error("Start failed for {}", encoder->getName()); + LOG_E(TAG, "Start failed for %s", encoder->getName().c_str()); } } } @@ -105,7 +105,7 @@ void attachDevices() { if (service::getState("Gui") == service::State::Stopped) { service::startService("Gui"); } else { - LOGGER.error("Gui service is not in Stopped state"); + LOG_E(TAG, "Gui service is not in Stopped state"); } } @@ -115,13 +115,13 @@ void attachDevices() { if (service::getState("Statusbar") == service::State::Stopped) { service::startService("Statusbar"); } else { - LOGGER.error("Statusbar service is not in Stopped state"); + LOG_E(TAG, "Statusbar service is not in Stopped state"); } } } void detachDevices() { - LOGGER.info("Removing devices"); + LOG_I(TAG, "Removing devices"); auto lock = getSyncLock()->asScopedLock(); lock.lock(); @@ -133,7 +133,7 @@ void detachDevices() { // Stop keyboards - LOGGER.info("Stopping keyboards"); + LOG_I(TAG, "Stopping keyboards"); auto keyboards = hal::findDevices(hal::Device::Type::Keyboard); for (auto keyboard: keyboards) { if (keyboard->getLvglIndev() != nullptr) { @@ -143,7 +143,7 @@ void detachDevices() { // Stop touch - LOGGER.info("Stopping touch"); + LOG_I(TAG, "Stopping touch"); // The display generally stops their own touch devices, but we'll clean up anything that didn't auto touch_devices = hal::findDevices(hal::Device::Type::Touch); for (auto touch_device: touch_devices) { @@ -154,7 +154,7 @@ void detachDevices() { // Stop encoders - LOGGER.info("Stopping encoders"); + LOG_I(TAG, "Stopping encoders"); // The display generally stops their own touch devices, but we'll clean up anything that didn't auto encoder_devices = hal::findDevices(hal::Device::Type::Encoder); for (auto encoder_device: encoder_devices) { @@ -164,11 +164,11 @@ void detachDevices() { } // Stop displays (and their touch devices) - LOGGER.info("Stopping displays"); + LOG_I(TAG, "Stopping displays"); auto displays = hal::findDevices(hal::Device::Type::Display); for (auto display: displays) { if (display->supportsLvgl() && display->getLvglDisplay() != nullptr && !display->stopLvgl()) { - LOGGER.error("Failed to detach display from LVGL"); + LOG_E(TAG, "Failed to detach display from LVGL"); } } } diff --git a/Tactility/Source/lvgl/Statusbar.cpp b/Tactility/Source/lvgl/Statusbar.cpp index 18155f128..341edb238 100644 --- a/Tactility/Source/lvgl/Statusbar.cpp +++ b/Tactility/Source/lvgl/Statusbar.cpp @@ -1,7 +1,6 @@ #define LV_USE_PRIVATE_API 1 // For actual lv_obj_t declaration #include -#include #include #include #include @@ -13,6 +12,7 @@ #include #include +#include #include #include @@ -20,7 +20,7 @@ namespace tt::lvgl { -static const auto LOGGER = Logger("statusbar"); +constexpr auto* TAG = "statusbar"; static void onUpdateTime(); @@ -62,9 +62,7 @@ static TickType_t getNextUpdateTime() { time_t now = ::time(nullptr); tm* tm_struct = localtime(&now); uint32_t seconds_to_wait = 60U - tm_struct->tm_sec; - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Update in {} s", seconds_to_wait); - } + LOG_D(TAG, "Update in %d s", (int)seconds_to_wait); return pdMS_TO_TICKS(seconds_to_wait * 1000U); } @@ -107,15 +105,13 @@ static lv_obj_class_t statusbar_class = { }; static void statusbar_pubsub_event(Statusbar* statusbar) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("Update event"); - } + LOG_D(TAG, "Update event"); if (lock(defaultLockTime)) { update_main(statusbar); lv_obj_invalidate(&statusbar->obj); unlock(); } else { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "Statusbar"); + LOG_W(TAG, "Mutex acquisition timeout (%s)", "Statusbar"); } } @@ -247,9 +243,7 @@ int8_t statusbar_icon_add(const std::string& image, bool visible) { statusbar_data.icons[i].visible = visible; statusbar_data.icons[i].image = image; result = i; - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("id {}: added", i); - } + LOG_D(TAG, "id %d: added", (int)i); break; } } @@ -263,9 +257,7 @@ int8_t statusbar_icon_add() { } void statusbar_icon_remove(int8_t id) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("id {}: remove", id); - } + LOG_D(TAG, "id %d: remove", (int)id); check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); StatusbarIcon* icon = &statusbar_data.icons[id]; @@ -277,12 +269,10 @@ void statusbar_icon_remove(int8_t id) { } void statusbar_icon_set_image(int8_t id, const std::string& image) { - if (LOGGER.isLoggingDebug()) { - if (image.empty()) { - LOGGER.debug("id {}: set image (none)", id); - } else { - LOGGER.debug("id {}: set image {}", id, image); - } + if (image.empty()) { + LOG_D(TAG, "id %d: set image (none)", (int)id); + } else { + LOG_D(TAG, "id %d: set image %s", (int)id, image.c_str()); } check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); @@ -294,9 +284,7 @@ void statusbar_icon_set_image(int8_t id, const std::string& image) { } void statusbar_icon_set_visibility(int8_t id, bool visible) { - if (LOGGER.isLoggingDebug()) { - LOGGER.debug("id {}: set visibility {}", id, visible); - } + LOG_D(TAG, "id %d: set visibility %d", (int)id, (int)visible); check(id >= 0 && id < STATUSBAR_ICON_LIMIT); statusbar_data.mutex.lock(); StatusbarIcon* icon = &statusbar_data.icons[id]; diff --git a/Tactility/Source/lvgl/UsbHidInput.cpp b/Tactility/Source/lvgl/UsbHidInput.cpp index 63a7743d8..dae388b09 100644 --- a/Tactility/Source/lvgl/UsbHidInput.cpp +++ b/Tactility/Source/lvgl/UsbHidInput.cpp @@ -7,10 +7,9 @@ #include #include -#include - #include #include +#include #include #include @@ -21,7 +20,7 @@ namespace tt::lvgl { -static const auto LOGGER = Logger("UsbHidInput"); +constexpr auto* TAG = "UsbHidInput"; constexpr auto HID_EVENT_QUEUE_SIZE = 64; constexpr auto KEY_EVENT_QUEUE_SIZE = 64; @@ -147,7 +146,7 @@ static void keyboard_read_cb(lv_indev_t* indev, lv_indev_data_t* data) { static void usbHidInputTask(void* arg) { auto* ctx = static_cast(arg); - LOGGER.info("started"); + LOG_I(TAG, "started"); while (!lv_is_initialized()) { vTaskDelay(pdMS_TO_TICKS(100)); @@ -172,9 +171,9 @@ static void usbHidInputTask(void* arg) { lv_indev_set_group(ctx->kb_indev, lv_group_get_default()); unlock(); - LOGGER.info("LVGL input devices registered"); + LOG_I(TAG, "LVGL input devices registered"); } else { - LOGGER.warn("could not acquire LVGL lock for indev registration"); + LOG_W(TAG, "could not acquire LVGL lock for indev registration"); } // Drain the HID event queue and route events to the appropriate destinations @@ -270,7 +269,7 @@ static void usbHidInputTask(void* arg) { unlock(); } - LOGGER.info("stopped"); + LOG_I(TAG, "stopped"); xSemaphoreGive(ctx->task_done); vTaskDelete(nullptr); } @@ -282,14 +281,14 @@ void startUsbHidInput() { ctx->hid_queue = xQueueCreate(HID_EVENT_QUEUE_SIZE, sizeof(UsbHidEvent)); if (!ctx->hid_queue) { - LOGGER.error("failed to create HID event queue"); + LOG_E(TAG, "failed to create HID event queue"); delete ctx; return; } ctx->key_queue = xQueueCreate(KEY_EVENT_QUEUE_SIZE, sizeof(KeyEvent)); if (!ctx->key_queue) { - LOGGER.error("failed to create key event queue"); + LOG_E(TAG, "failed to create key event queue"); vQueueDelete(ctx->hid_queue); delete ctx; return; @@ -297,7 +296,7 @@ void startUsbHidInput() { ctx->task_done = xSemaphoreCreateBinary(); if (!ctx->task_done) { - LOGGER.error("failed to create task done semaphore"); + LOG_E(TAG, "failed to create task done semaphore"); vQueueDelete(ctx->hid_queue); vQueueDelete(ctx->key_queue); delete ctx; @@ -309,7 +308,7 @@ void startUsbHidInput() { ctx->running = true; if (xTaskCreate(usbHidInputTask, "usb_hid_inp", TASK_STACK, ctx, TASK_PRIORITY, &ctx->task) != pdPASS) { - LOGGER.error("failed to create task"); + LOG_E(TAG, "failed to create task"); ctx->running = false; if (hid_dev) usb_host_hid_unsubscribe(hid_dev, ctx->hid_queue); vQueueDelete(ctx->hid_queue); @@ -320,7 +319,7 @@ void startUsbHidInput() { } s_ctx = ctx; - LOGGER.info("started"); + LOG_I(TAG, "started"); } void stopUsbHidInput() { @@ -331,7 +330,7 @@ void stopUsbHidInput() { ctx->running = false; if (xSemaphoreTake(ctx->task_done, pdMS_TO_TICKS(STOP_TIMEOUT_MS)) != pdTRUE) { - LOGGER.warn("task stop timed out, force terminating"); + LOG_W(TAG, "task stop timed out, force terminating"); vTaskDelete(ctx->task); // Task was killed before it could clean up LVGL objects; do it here to // prevent mouse_read_cb / keyboard_read_cb from running with a freed ctx. @@ -357,7 +356,7 @@ void stopUsbHidInput() { vSemaphoreDelete(ctx->task_done); delete ctx; - LOGGER.info("stopped"); + LOG_I(TAG, "stopped"); } } // namespace tt::lvgl diff --git a/Tactility/Source/network/Http.cpp b/Tactility/Source/network/Http.cpp index 4991d6191..9e7d0b675 100644 --- a/Tactility/Source/network/Http.cpp +++ b/Tactility/Source/network/Http.cpp @@ -1,10 +1,11 @@ #include #include -#include #include #include "Tactility/service/gui/GuiService.h" +#include + #ifdef ESP_PLATFORM #include #include @@ -12,7 +13,7 @@ namespace tt::network::http { -static const auto LOGGER = Logger("HTTP"); +constexpr auto* TAG = "HTTP"; void download( const std::string& url, @@ -22,10 +23,10 @@ void download( const std::function& onError ) { service::gui::warnIfRunningOnGuiTask("HTTP"); - LOGGER.info("Downloading from {} to {}", url, downloadFilePath); + LOG_I(TAG, "Downloading from %s to %s", url.c_str(), downloadFilePath.c_str()); #ifdef ESP_PLATFORM getMainDispatcher().dispatch([url, certFilePath, downloadFilePath, onSuccess, onError] { - LOGGER.info("Loading certificate"); + LOG_I(TAG, "Loading certificate"); auto certificate = file::readString(certFilePath); if (certificate == nullptr) { onError("Failed to read certificate"); @@ -71,14 +72,14 @@ void download( auto lock = file::getLock(downloadFilePath)->asScopedLock(); lock.lock(); - LOGGER.info("opening {}", downloadFilePath); + LOG_I(TAG, "opening %s", downloadFilePath.c_str()); auto* file = fopen(downloadFilePath.c_str(), "wb"); if (file == nullptr) { onError("Failed to open file"); return; } - LOGGER.info("Writing {} bytes to {}", bytes_left, downloadFilePath); + LOG_I(TAG, "Writing %d bytes to %s", bytes_left, downloadFilePath.c_str()); char buffer[512]; while (bytes_left > 0) { int data_read = client->read(buffer, 512); @@ -96,7 +97,7 @@ void download( taskYIELD(); } fclose(file); - LOGGER.info("Downloaded {} to {}", url, downloadFilePath); + LOG_I(TAG, "Downloaded %s to %s", url.c_str(), downloadFilePath.c_str()); onSuccess(); }); #else diff --git a/Tactility/Source/network/HttpServer.cpp b/Tactility/Source/network/HttpServer.cpp index d6b9b673e..05ebc4ef7 100644 --- a/Tactility/Source/network/HttpServer.cpp +++ b/Tactility/Source/network/HttpServer.cpp @@ -2,12 +2,13 @@ #include -#include #include +#include + namespace tt::network { -static const auto LOGGER = Logger("HttpServer"); +constexpr auto* TAG = "HttpServer"; static constexpr size_t INTERNAL_URI_HANDLER_COUNT = 2; @@ -19,14 +20,14 @@ bool HttpServer::startInternal() { config.max_uri_handlers = handlers.size() + INTERNAL_URI_HANDLER_COUNT; if (httpd_start(&server, &config) != ESP_OK) { - LOGGER.error("Failed to start http server on port {}", port); + LOG_E(TAG, "Failed to start http server on port %u", (unsigned)port); return false; } bool allRegistered = true; for (std::vector::reference handler : handlers) { if (httpd_register_uri_handler(server, &handler) != ESP_OK) { - LOGGER.error("Failed to register URI handler: {}", handler.uri); + LOG_E(TAG, "Failed to register URI handler: %s", handler.uri); allRegistered = false; } } @@ -36,17 +37,17 @@ bool HttpServer::startInternal() { return false; } - LOGGER.info("Started on port {}", config.server_port); + LOG_I(TAG, "Started on port %u", (unsigned)config.server_port); return true; } void HttpServer::stopInternal() { - LOGGER.info("Stopping server"); + LOG_I(TAG, "Stopping server"); if (server != nullptr) { if (httpd_stop(server) == ESP_OK) { server = nullptr; } else { - LOGGER.warn("Error while stopping"); + LOG_W(TAG, "Error while stopping"); } } } @@ -56,7 +57,7 @@ bool HttpServer::start() { lock.lock(); if (isStarted()) { - LOGGER.warn("Already started"); + LOG_W(TAG, "Already started"); return true; } @@ -68,7 +69,7 @@ void HttpServer::stop() { lock.lock(); if (!isStarted()) { - LOGGER.warn("Not started"); + LOG_W(TAG, "Not started"); return; } diff --git a/Tactility/Source/network/HttpdReq.cpp b/Tactility/Source/network/HttpdReq.cpp index 49b211f57..1304b6c40 100644 --- a/Tactility/Source/network/HttpdReq.cpp +++ b/Tactility/Source/network/HttpdReq.cpp @@ -1,8 +1,9 @@ -#include -#include #include #include #include +#include + +#include #include #include @@ -12,7 +13,7 @@ namespace tt::network { -static const auto LOGGER = Logger("HttpdReq"); +constexpr auto* TAG = "HttpdReq"; bool getHeaderOrSendError(httpd_req_t* request, const std::string& name, std::string& value) { size_t header_size = httpd_req_get_hdr_value_len(request, name.c_str()); @@ -23,7 +24,7 @@ bool getHeaderOrSendError(httpd_req_t* request, const std::string& name, std::st auto header_buffer = std::make_unique(header_size + 1); if (header_buffer == nullptr) { - LOGGER.error( LOG_MESSAGE_ALLOC_FAILED); + LOG_E(TAG, LOG_MESSAGE_ALLOC_FAILED); httpd_resp_send_500(request); return false; } @@ -79,7 +80,7 @@ std::unique_ptr 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) { - LOGGER.error(LOG_MESSAGE_ALLOC_FAILED_FMT, length); + LOG_E(TAG, "Out of memory (failed to allocated %u bytes)", (unsigned)length); return nullptr; } @@ -92,16 +93,16 @@ std::unique_ptr receiveByteArray(httpd_req_t* request, size_t length, si // Timeout - retry with backoff timeout_retries++; if (timeout_retries >= MAX_TIMEOUT_RETRIES) { - LOGGER.warn("Recv timeout after {} retries, read {}/{} bytes", timeout_retries, bytesRead, length); + LOG_W(TAG, "Recv timeout after %d retries, read %u/%u bytes", timeout_retries, (unsigned)bytesRead, (unsigned)length); free(buffer); return nullptr; } - LOGGER.warn("Recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES); + LOG_W(TAG, "Recv timeout, retry %d/%d", timeout_retries, MAX_TIMEOUT_RETRIES); vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Exponential backoff continue; } if (bytes_received <= 0) { - LOGGER.warn("Received error {} after reading {}/{} bytes", bytes_received, bytesRead, length); + LOG_W(TAG, "Received error %d after reading %u/%u bytes", bytes_received, (unsigned)bytesRead, (unsigned)length); free(buffer); return nullptr; } @@ -190,7 +191,7 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP auto* file = fopen(filePath.c_str(), "wb"); if (file == nullptr) { - LOGGER.error("Failed to open file for writing: {}", filePath); + LOG_E(TAG, "Failed to open file for writing: %s", filePath.c_str()); return 0; } @@ -198,11 +199,11 @@ size_t receiveFile(httpd_req_t* request, size_t length, const std::string& fileP auto expected_chunk_size = std::min(BUFFER_SIZE, length - bytes_received); size_t receive_chunk_size = httpd_req_recv(request, buffer, expected_chunk_size); if (receive_chunk_size <= 0) { - LOGGER.error("Receive failed"); + LOG_E(TAG, "Receive failed"); break; } if (fwrite(buffer, 1, receive_chunk_size, file) != (size_t)receive_chunk_size) { - LOGGER.error("Failed to write all bytes"); + LOG_E(TAG, "Failed to write all bytes"); break; } bytes_received += receive_chunk_size; diff --git a/Tactility/Source/network/Ntp.cpp b/Tactility/Source/network/Ntp.cpp index 09633841e..b8e41223d 100644 --- a/Tactility/Source/network/Ntp.cpp +++ b/Tactility/Source/network/Ntp.cpp @@ -1,7 +1,8 @@ #include -#include #include +#include + #include #ifdef ESP_PLATFORM @@ -13,7 +14,7 @@ namespace tt::network::ntp { -static const auto LOGGER = Logger("NTP"); +constexpr auto* TAG = "NTP"; static bool processedSyncEvent = false; @@ -25,14 +26,14 @@ void storeTimeInNvs() { auto preferences = std::make_unique("time"); preferences->putInt64("syncTime", now); - LOGGER.info("Stored time {}", now); + LOG_I(TAG, "Stored time %ld", (long)now); } void setTimeFromNvs() { auto preferences = std::make_unique("time"); time_t synced_time; if (preferences->optInt64("syncTime", synced_time)) { - LOGGER.info("Restoring last known time to {}", synced_time); + LOG_I(TAG, "Restoring last known time to %ld", (long)synced_time); timeval get_nvs_time; get_nvs_time.tv_sec = synced_time; settimeofday(&get_nvs_time, nullptr); @@ -40,7 +41,7 @@ void setTimeFromNvs() { } static void onTimeSynced(timeval* tv) { - LOGGER.info("Time synced ({})", tv->tv_sec); + LOG_I(TAG, "Time synced (%ld)", (long)tv->tv_sec); processedSyncEvent = true; esp_netif_sntp_deinit(); storeTimeInNvs(); diff --git a/Tactility/Source/service/ServiceRegistration.cpp b/Tactility/Source/service/ServiceRegistration.cpp index f13b07173..ed2dfc78c 100644 --- a/Tactility/Source/service/ServiceRegistration.cpp +++ b/Tactility/Source/service/ServiceRegistration.cpp @@ -1,15 +1,16 @@ #include -#include #include #include #include #include +#include + namespace tt::service { -static const auto LOGGER = Logger("ServiceRegistration"); +constexpr auto* TAG = "ServiceRegistration"; typedef std::unordered_map> ManifestMap; typedef std::unordered_map> ServiceInstanceMap; @@ -25,13 +26,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; - LOGGER.info("Adding {}", id); + LOG_I(TAG, "Adding %s", id.c_str()); manifest_mutex.lock(); if (service_manifest_map[id] == nullptr) { service_manifest_map[id] = std::move(manifest); } else { - LOGGER.error("Service id in use: {}", id); + LOG_E(TAG, "Service id in use: %s", id.c_str()); } manifest_mutex.unlock(); @@ -62,10 +63,10 @@ static std::shared_ptr findServiceInstanceById(const std::strin // TODO: Return proper error/status instead of BOOL? bool startService(const std::string& id) { - LOGGER.info("Starting {}", id); + LOG_I(TAG, "Starting %s", id.c_str()); auto manifest = findManifestById(id); if (manifest == nullptr) { - LOGGER.error("manifest not found for service {}", id); + LOG_E(TAG, "manifest not found for service %s", id.c_str()); return false; } @@ -80,14 +81,14 @@ bool startService(const std::string& id) { if (service_instance->getService()->onStart(*service_instance)) { service_instance->setState(State::Started); } else { - LOGGER.error("Starting {} failed", id); + LOG_E(TAG, "Starting %s failed", id.c_str()); service_instance->setState(State::Stopped); instance_mutex.lock(); service_instance_map.erase(manifest->id); instance_mutex.unlock(); } - LOGGER.info("Started {}", id); + LOG_I(TAG, "Started %s", id.c_str()); return true; } @@ -102,10 +103,10 @@ std::shared_ptr findServiceById(const std::string& id) { } bool stopService(const std::string& id) { - LOGGER.info("Stopping {}", id); + LOG_I(TAG, "Stopping %s", id.c_str()); auto service_instance = findServiceInstanceById(id); if (service_instance == nullptr) { - LOGGER.warn("Service not running: {}", id); + LOG_W(TAG, "Service not running: %s", id.c_str()); return false; } @@ -118,10 +119,10 @@ bool stopService(const std::string& id) { instance_mutex.unlock(); if (service_instance.use_count() > 1) { - LOGGER.warn("Possible memory leak: service {} still has {} references", service_instance->getManifest().id, service_instance.use_count() - 1); + LOG_W(TAG, "Possible memory leak: service %s still has %d references", service_instance->getManifest().id.c_str(), (int)(service_instance.use_count() - 1)); } - LOGGER.info("Stopped {}", id); + LOG_I(TAG, "Stopped %s", id.c_str()); return true; } diff --git a/Tactility/Source/service/development/DevelopmentService.cpp b/Tactility/Source/service/development/DevelopmentService.cpp index df0ecf035..1ba0855f5 100644 --- a/Tactility/Source/service/development/DevelopmentService.cpp +++ b/Tactility/Source/service/development/DevelopmentService.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -16,11 +15,13 @@ #include #include +#include + namespace tt::service::development { extern const ServiceManifest manifest; -static const auto LOGGER = Logger("DevService"); +constexpr auto* TAG = "DevService"; bool DevelopmentService::onStart(ServiceContext& service) { std::stringstream stream; @@ -66,26 +67,26 @@ bool DevelopmentService::isEnabled() const { // region endpoints esp_err_t DevelopmentService::handleGetInfo(httpd_req_t* request) { - LOGGER.info("GET /device"); + LOG_I(TAG, "GET /device"); if (httpd_resp_set_type(request, "application/json") != ESP_OK) { - LOGGER.warn("Failed to send header"); + LOG_W(TAG, "Failed to send header"); return ESP_FAIL; } auto* service = static_cast(request->user_ctx); if (httpd_resp_sendstr(request, service->deviceResponse.c_str()) != ESP_OK) { - LOGGER.warn("Failed to send response body"); + LOG_W(TAG, "Failed to send response body"); return ESP_FAIL; } - LOGGER.info("[200] /device"); + LOG_I(TAG, "[200] /device"); return ESP_OK; } esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) { - LOGGER.info("POST /app/run"); + LOG_I(TAG, "POST /app/run"); std::string query; if (!network::getQueryOrSendError(request, query)) { @@ -95,7 +96,7 @@ esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) { auto parameters = network::parseUrlQuery(query); auto id_key_pos = parameters.find("id"); if (id_key_pos == parameters.end()) { - LOGGER.warn("[400] /app/run id not specified"); + LOG_W(TAG, "[400] /app/run id not specified"); httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id not specified"); return ESP_FAIL; } @@ -107,14 +108,14 @@ esp_err_t DevelopmentService::handleAppRun(httpd_req_t* request) { app::start(app_id); - LOGGER.info("[200] /app/run {}", id_key_pos->second); + LOG_I(TAG, "[200] /app/run %s", id_key_pos->second.c_str()); httpd_resp_send(request, nullptr, 0); return ESP_OK; } esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { - LOGGER.info("PUT /app/install"); + LOG_I(TAG, "PUT /app/install"); std::string boundary; if (!network::getMultiPartBoundaryOrSendError(request, boundary)) { @@ -175,7 +176,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { content_left -= boundary_and_newlines_after_file.length(); if (content_left != 0) { - LOGGER.warn("We have more bytes at the end of the request parsing?!"); + LOG_W(TAG, "We have more bytes at the end of the request parsing?!"); } if (!app::install(file_path)) { @@ -184,10 +185,10 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { } if (!file::deleteFile(file_path)) { - LOGGER.warn("Failed to delete {}", file_path); + LOG_W(TAG, "Failed to delete %s", file_path.c_str()); } - LOGGER.info("[200] /app/install -> {}", file_path); + LOG_I(TAG, "[200] /app/install -> %s", file_path.c_str()); httpd_resp_send(request, nullptr, 0); @@ -195,7 +196,7 @@ esp_err_t DevelopmentService::handleAppInstall(httpd_req_t* request) { } esp_err_t DevelopmentService::handleAppUninstall(httpd_req_t* request) { - LOGGER.info("PUT /app/uninstall"); + LOG_I(TAG, "PUT /app/uninstall"); std::string query; if (!network::getQueryOrSendError(request, query)) { @@ -205,23 +206,23 @@ esp_err_t DevelopmentService::handleAppUninstall(httpd_req_t* request) { auto parameters = network::parseUrlQuery(query); auto id_key_pos = parameters.find("id"); if (id_key_pos == parameters.end()) { - LOGGER.warn("[400] /app/uninstall id not specified"); + LOG_W(TAG, "[400] /app/uninstall id not specified"); httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "id not specified"); return ESP_FAIL; } if (!app::findAppManifestById(id_key_pos->second)) { - LOGGER.info("[200] /app/uninstall {} (app wasn't installed)", id_key_pos->second); + LOG_I(TAG, "[200] /app/uninstall %s (app wasn't installed)", id_key_pos->second.c_str()); httpd_resp_send(request, nullptr, 0); return ESP_OK; } if (app::uninstall(id_key_pos->second)) { - LOGGER.info("[200] /app/uninstall {}", id_key_pos->second); + LOG_I(TAG, "[200] /app/uninstall %s", id_key_pos->second.c_str()); httpd_resp_send(request, nullptr, 0); return ESP_OK; } else { - LOGGER.warn("[500] /app/uninstall {}", id_key_pos->second); + LOG_W(TAG, "[500] /app/uninstall %s", id_key_pos->second.c_str()); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to uninstall"); return ESP_FAIL; } diff --git a/Tactility/Source/service/development/DevelopmentSettings.cpp b/Tactility/Source/service/development/DevelopmentSettings.cpp index 15f7d0edf..5913fad2b 100644 --- a/Tactility/Source/service/development/DevelopmentSettings.cpp +++ b/Tactility/Source/service/development/DevelopmentSettings.cpp @@ -1,15 +1,16 @@ #ifdef ESP_PLATFORM #include #include -#include #include #include #include #include +#include + namespace tt::service::development { -static const auto LOGGER = Logger("DevSettings"); +constexpr auto* TAG = "DevSettings"; static std::string getSettingsFilePath() { return getUserDataPath() + "/settings/development.properties"; @@ -46,7 +47,7 @@ static bool save(const DevelopmentSettings& settings) { map[SETTINGS_KEY_ENABLE_ON_BOOT] = settings.enableOnBoot ? "true" : "false"; auto settings_path = getSettingsFilePath(); if (!file::findOrCreateParentDirectory(settings_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", settings_path); + LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str()); return false; } return file::savePropertiesFile(settings_path, map); @@ -55,7 +56,7 @@ static bool save(const DevelopmentSettings& settings) { void setEnableOnBoot(bool enable) { DevelopmentSettings properties { .enableOnBoot = enable }; if (!save(properties)) { - LOGGER.error("Failed to save {}", getSettingsFilePath()); + LOG_E(TAG, "Failed to save %s", getSettingsFilePath().c_str()); } } diff --git a/Tactility/Source/service/displayidle/DisplayIdle.cpp b/Tactility/Source/service/displayidle/DisplayIdle.cpp index 577619612..713ae276e 100644 --- a/Tactility/Source/service/displayidle/DisplayIdle.cpp +++ b/Tactility/Source/service/displayidle/DisplayIdle.cpp @@ -8,7 +8,7 @@ #include "MystifyScreensaver.h" #include "StackChanScreensaver.h" -#include +#include #include #include #include @@ -20,7 +20,7 @@ namespace tt::service::displayidle { -static const auto LOGGER = Logger("DisplayIdle"); +constexpr auto* TAG = "DisplayIdle"; constexpr uint32_t kWakeActivityThresholdMs = 100; @@ -224,7 +224,7 @@ void DisplayIdleService::onStop(ServiceContext& service) { } } if (screensaverOverlay) { - LOGGER.warn("Failed to stop screensaver during shutdown - potential resource leak"); + LOG_W(TAG, "Failed to stop screensaver during shutdown - potential resource leak"); } } screensaver.reset(); diff --git a/Tactility/Source/service/espnow/EspNow.cpp b/Tactility/Source/service/espnow/EspNow.cpp index 2fd1a06a0..aaee10d09 100644 --- a/Tactility/Source/service/espnow/EspNow.cpp +++ b/Tactility/Source/service/espnow/EspNow.cpp @@ -7,18 +7,18 @@ #include #include -#include +#include namespace tt::service::espnow { -static const auto LOGGER = Logger("EspNow"); +constexpr auto* TAG = "EspNow"; void enable(const EspNowConfig& config) { auto service = findService(); if (service != nullptr) { service->enable(config); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); } } @@ -27,7 +27,7 @@ void disable() { if (service != nullptr) { service->disable(); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); } } @@ -36,7 +36,7 @@ bool isEnabled() { if (service != nullptr) { return service->isEnabled(); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); return false; } } @@ -46,7 +46,7 @@ bool addPeer(const esp_now_peer_info_t& peer) { if (service != nullptr) { return service->addPeer(peer); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); return false; } } @@ -56,7 +56,7 @@ bool send(const uint8_t* address, const uint8_t* buffer, size_t bufferLength) { if (service != nullptr) { return service->send(address, buffer, bufferLength); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); return false; } } @@ -66,7 +66,7 @@ ReceiverSubscription subscribeReceiver(std::functionsubscribeReceiver(onReceive); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); return -1; } } @@ -76,7 +76,7 @@ void unsubscribeReceiver(ReceiverSubscription subscription) { if (service != nullptr) { service->unsubscribeReceiver(subscription); } else { - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); } } @@ -85,7 +85,7 @@ uint32_t getVersion() { if (service != nullptr) { return service->getVersion(); } - LOGGER.error("Service not found"); + LOG_E(TAG, "Service not found"); return 0; } diff --git a/Tactility/Source/service/espnow/EspNowService.cpp b/Tactility/Source/service/espnow/EspNowService.cpp index 432f33440..c008a0ffb 100644 --- a/Tactility/Source/service/espnow/EspNowService.cpp +++ b/Tactility/Source/service/espnow/EspNowService.cpp @@ -4,7 +4,6 @@ #if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) -#include #include #include #include @@ -15,11 +14,13 @@ #include #include +#include + namespace tt::service::espnow { extern const ServiceManifest manifest; -static const auto LOGGER = Logger("EspNowService"); +constexpr auto* TAG = "EspNowService"; static uint8_t BROADCAST_MAC[ESP_NOW_ETH_ALEN]; constexpr TickType_t MAX_DELAY = 1000U / portTICK_PERIOD_MS; @@ -60,17 +61,17 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) { } if (!initWifi(config)) { - LOGGER.error("initWifi() failed"); + LOG_E(TAG,"initWifi() failed"); return; } if (esp_now_init() != ESP_OK) { - LOGGER.error("esp_now_init() failed"); + LOG_E(TAG,"esp_now_init() failed"); return; } if (esp_now_register_recv_cb(receiveCallback) != ESP_OK) { - LOGGER.error("esp_now_register_recv_cb() failed"); + LOG_E(TAG,"esp_now_register_recv_cb() failed"); return; } @@ -80,15 +81,15 @@ void EspNowService::enableFromDispatcher(const EspNowConfig& config) { //#endif if (esp_now_set_pmk(config.masterKey) != ESP_OK) { - LOGGER.error("esp_now_set_pmk() failed"); + LOG_E(TAG,"esp_now_set_pmk() failed"); return; } espnowVersion = 0; if (esp_now_get_version(&espnowVersion) == ESP_OK) { - LOGGER.info("ESP-NOW version: {}.0", espnowVersion); + LOG_I(TAG, "ESP-NOW version: %u.0", (unsigned)espnowVersion); } else { - LOGGER.warn("Failed to get ESP-NOW version"); + LOG_W(TAG, "Failed to get ESP-NOW version"); } // Add default unencrypted broadcast peer @@ -119,11 +120,11 @@ void EspNowService::disableFromDispatcher() { } if (esp_now_deinit() != ESP_OK) { - LOGGER.error("esp_now_deinit() failed"); + LOG_E(TAG,"esp_now_deinit() failed"); } if (!deinitWifi()) { - LOGGER.error("deinitWifi() failed"); + LOG_E(TAG,"deinitWifi() failed"); } espnowVersion = 0; @@ -137,7 +138,7 @@ void EspNowService::disableFromDispatcher() { void EspNowService::receiveCallback(const esp_now_recv_info_t* receiveInfo, const uint8_t* data, int length) { auto service = findService(); if (service == nullptr) { - LOGGER.error("Service not running"); + LOG_E(TAG,"Service not running"); return; } service->onReceive(receiveInfo, data, length); @@ -147,7 +148,7 @@ void EspNowService::onReceive(const esp_now_recv_info_t* receiveInfo, const uint auto lock = mutex.asScopedLock(); lock.lock(); - LOGGER.debug("Received {} bytes", length); + LOG_D(TAG, "Received %d bytes", length); for (const auto& item: subscriptions) { item.onReceive(receiveInfo, data, length); @@ -164,10 +165,10 @@ bool EspNowService::isEnabled() const { bool EspNowService::addPeer(const esp_now_peer_info_t& peer) { if (esp_now_add_peer(&peer) != ESP_OK) { - LOGGER.error("Failed to add peer"); + LOG_E(TAG,"Failed to add peer"); return false; } else { - LOGGER.info("Peer added"); + LOG_I(TAG, "Peer added"); return true; } } diff --git a/Tactility/Source/service/espnow/EspNowWifi.cpp b/Tactility/Source/service/espnow/EspNowWifi.cpp index 806e3d89f..229af8868 100644 --- a/Tactility/Source/service/espnow/EspNowWifi.cpp +++ b/Tactility/Source/service/espnow/EspNowWifi.cpp @@ -4,16 +4,17 @@ #if defined(CONFIG_SOC_WIFI_SUPPORTED) && !defined(CONFIG_SLAVE_SOC_WIFI_SUPPORTED) -#include #include #include #include #include +#include + namespace tt::service::espnow { -static const auto LOGGER = Logger("EspNowService"); +constexpr auto* TAG = "EspNowService"; static bool wifiStartedByEspNow = false; bool initWifi(const EspNowConfig& config) { @@ -32,27 +33,27 @@ bool initWifi(const EspNowConfig& config) { if (wifiStartedByEspNow) { wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); if (esp_wifi_init(&cfg) != ESP_OK) { - LOGGER.error("esp_wifi_init() failed"); + LOG_E(TAG,"esp_wifi_init() failed"); return false; } if (esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK) { - LOGGER.error("esp_wifi_set_storage() failed"); + LOG_E(TAG,"esp_wifi_set_storage() failed"); return false; } if (esp_wifi_set_mode(mode) != ESP_OK) { - LOGGER.error("esp_wifi_set_mode() failed"); + LOG_E(TAG,"esp_wifi_set_mode() failed"); return false; } if (esp_wifi_start() != ESP_OK) { - LOGGER.error("esp_wifi_start() failed"); + LOG_E(TAG,"esp_wifi_start() failed"); return false; } if (esp_wifi_set_channel(config.channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) { - LOGGER.error("esp_wifi_set_channel() failed"); + LOG_E(TAG,"esp_wifi_set_channel() failed"); return false; } } @@ -66,11 +67,11 @@ bool initWifi(const EspNowConfig& config) { } if (esp_wifi_set_protocol(wifi_interface, WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR) != ESP_OK) { - LOGGER.warn("esp_wifi_set_protocol() for long range failed"); + LOG_W(TAG,"esp_wifi_set_protocol() for long range failed"); } } - LOGGER.info("WiFi initialized for ESP-NOW (wifi already running: {})", wifi_already_running ? "yes" : "no"); + LOG_I(TAG, "WiFi initialized for ESP-NOW (wifi already running: %s)", wifi_already_running ? "yes" : "no"); return true; } @@ -79,9 +80,9 @@ bool deinitWifi() { esp_wifi_stop(); esp_wifi_deinit(); wifiStartedByEspNow = false; - LOGGER.info("WiFi stopped (was started by ESP-NOW)"); + LOG_I(TAG, "WiFi stopped (was started by ESP-NOW)"); } else { - LOGGER.info("WiFi left running (managed by WiFi service)"); + LOG_I(TAG, "WiFi left running (managed by WiFi service)"); } return true; } diff --git a/Tactility/Source/service/gps/GpsConfiguration.cpp b/Tactility/Source/service/gps/GpsConfiguration.cpp index aa2783730..ce4719be4 100644 --- a/Tactility/Source/service/gps/GpsConfiguration.cpp +++ b/Tactility/Source/service/gps/GpsConfiguration.cpp @@ -1,25 +1,26 @@ #include -#include #include #include #include #include +#include + using tt::hal::gps::GpsDevice; namespace tt::service::gps { -static const auto LOGGER = Logger("GpsService"); +constexpr auto* TAG = "GpsService"; bool GpsService::getConfigurationFilePath(std::string& output) const { if (paths == nullptr) { - LOGGER.error("Can't add configuration: service not started"); + LOG_E(TAG, "Can't add configuration: service not started"); return false; } if (!file::findOrCreateDirectory(paths->getUserDataDirectory(), 0777)) { - LOGGER.error("Failed to find or create path {}", paths->getUserDataDirectory()); + LOG_E(TAG, "Failed to find or create path %s", paths->getUserDataDirectory().c_str()); return false; } @@ -35,21 +36,21 @@ bool GpsService::getGpsConfigurations(std::vector& c // If file does not exist, return empty list if (access(path.c_str(), F_OK) != 0) { - LOGGER.warn("No configurations (file not found: {})", path); + LOG_W(TAG, "No configurations (file not found: %s)", path.c_str()); return true; } - LOGGER.info("Reading configuration file {}", path); + LOG_I(TAG, "Reading configuration file %s", path.c_str()); auto reader = file::ObjectFileReader(path, sizeof(hal::gps::GpsConfiguration)); if (!reader.open()) { - LOGGER.error("Failed to open configuration file"); + LOG_E(TAG, "Failed to open configuration file"); return false; } hal::gps::GpsConfiguration configuration; while (reader.hasNext()) { if (!reader.readNext(&configuration)) { - LOGGER.error("Failed to read configuration"); + LOG_E(TAG, "Failed to read configuration"); reader.close(); return false; } else { @@ -68,12 +69,12 @@ bool GpsService::addGpsConfiguration(hal::gps::GpsConfiguration configuration) { auto appender = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, true); if (!appender.open()) { - LOGGER.error("Failed to open/create configuration file"); + LOG_E(TAG, "Failed to open/create configuration file"); return false; } if (!appender.write(&configuration)) { - LOGGER.error("Failed to add configuration"); + LOG_E(TAG, "Failed to add configuration"); appender.close(); return false; } @@ -90,7 +91,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration std::vector configurations; if (!getGpsConfigurations(configurations)) { - LOGGER.error("Failed to get gps configurations"); + LOG_E(TAG, "Failed to get gps configurations"); return false; } @@ -102,7 +103,7 @@ bool GpsService::removeGpsConfiguration(hal::gps::GpsConfiguration configuration auto writer = file::ObjectFileWriter(path, sizeof(hal::gps::GpsConfiguration), 1, false); if (!writer.open()) { - LOGGER.error("Failed to open configuration file"); + LOG_E(TAG, "Failed to open configuration file"); return false; } diff --git a/Tactility/Source/service/gps/GpsService.cpp b/Tactility/Source/service/gps/GpsService.cpp index 3b6d49757..a67685e99 100644 --- a/Tactility/Source/service/gps/GpsService.cpp +++ b/Tactility/Source/service/gps/GpsService.cpp @@ -1,16 +1,17 @@ #include #include -#include #include #include #include +#include + using tt::hal::gps::GpsDevice; namespace tt::service::gps { -static const auto LOGGER = Logger("GpsService"); +constexpr auto* TAG = "GpsService"; extern const ServiceManifest manifest; constexpr bool hasTimeElapsed(TickType_t now, TickType_t timeInThePast, TickType_t expireTimeInTicks) { @@ -73,7 +74,7 @@ void GpsService::onStop(ServiceContext& serviceContext) { } bool GpsService::startGpsDevice(GpsDeviceRecord& record) { - LOGGER.info("[device {}] starting", record.device->getId()); + LOG_I(TAG, "[device %u] starting", (unsigned)record.device->getId()); auto lock = mutex.asScopedLock(); lock.lock(); @@ -81,7 +82,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) { auto device = record.device; if (!device->start()) { - LOGGER.error("[device {}] starting failed", record.device->getId()); + LOG_E(TAG, "[device %u] starting failed", (unsigned)record.device->getId()); return false; } @@ -109,7 +110,7 @@ bool GpsService::startGpsDevice(GpsDeviceRecord& record) { } bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { - LOGGER.info("[device {}] stopping", record.device->getId()); + LOG_I(TAG, "[device %u] stopping", (unsigned)record.device->getId()); auto device = record.device; @@ -120,7 +121,7 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { record.rmcSubscriptionId = -1; if (!device->stop()) { - LOGGER.error("[device {}] stopping failed", record.device->getId()); + LOG_E(TAG, "[device %u] stopping failed", (unsigned)record.device->getId()); return false; } @@ -128,10 +129,10 @@ bool GpsService::stopGpsDevice(GpsDeviceRecord& record) { } bool GpsService::startReceiving() { - LOGGER.info("Start receiving"); + LOG_I(TAG, "Start receiving"); if (getState() != State::Off) { - LOGGER.error("Already receiving"); + LOG_E(TAG, "Already receiving"); return false; } @@ -144,13 +145,13 @@ bool GpsService::startReceiving() { std::vector configurations; if (!getGpsConfigurations(configurations)) { - LOGGER.error("Failed to get GPS configurations"); + LOG_E(TAG, "Failed to get GPS configurations"); setState(State::Off); return false; } if (configurations.empty()) { - LOGGER.error("No GPS configurations"); + LOG_E(TAG, "No GPS configurations"); setState(State::Off); return false; } @@ -180,7 +181,7 @@ bool GpsService::startReceiving() { } void GpsService::stopReceiving() { - LOGGER.info("Stop receiving"); + LOG_I(TAG, "Stop receiving"); setState(State::OffPending); @@ -198,11 +199,11 @@ void GpsService::stopReceiving() { } void GpsService::onGgaSentence(hal::Device::Id deviceId, const minmea_sentence_gga& gga) { - LOGGER.debug("[device {}] LAT {} LON {}, satellites: {}", deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked); + LOG_D(TAG, "[device %u] LAT %f LON %f, satellites: %d", (unsigned)deviceId, minmea_tocoord(&gga.latitude), minmea_tocoord(&gga.longitude), gga.satellites_tracked); } void GpsService::onRmcSentence(hal::Device::Id deviceId, const minmea_sentence_rmc& rmc) { - LOGGER.debug("[device {}] LAT {} LON {}, speed: {}", deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed)); + LOG_D(TAG, "[device %u] LAT %f LON %f, speed: %f", (unsigned)deviceId, minmea_tocoord(&rmc.latitude), minmea_tocoord(&rmc.longitude), minmea_tofloat(&rmc.speed)); } State GpsService::getState() const { diff --git a/Tactility/Source/service/gui/GuiService.cpp b/Tactility/Source/service/gui/GuiService.cpp index 235cdb59d..d5b244d1b 100644 --- a/Tactility/Source/service/gui/GuiService.cpp +++ b/Tactility/Source/service/gui/GuiService.cpp @@ -2,20 +2,21 @@ #include -#include -#include #include +#include +#include #include #include #include -#include #include -#include +#include + +#include namespace tt::service::gui { extern const ServiceManifest manifest; -static const auto LOGGER = Logger("GuiService"); +constexpr auto* TAG = "GuiService"; using namespace loader; constexpr auto* GUI_TASK_NAME = "gui"; @@ -23,7 +24,7 @@ constexpr auto* GUI_TASK_NAME = "gui"; void warnIfRunningOnGuiTask(const char* context) { const char* task_name = pcTaskGetName(nullptr); if (strcmp(GUI_TASK_NAME, task_name) == 0) { - LOGGER.warn("{} shouldn't run on the GUI task", context); + LOG_W(TAG, "%s shouldn't run on the GUI task", context); } } @@ -68,7 +69,7 @@ void GuiService::onLoaderEvent(LoaderService::Event event) { } if (dispatcher_dispatch(dispatcher, item, onGuiDispatch) != ERROR_NONE) { - LOGGER.error("Failed to dispatch gui event"); + LOG_E(TAG, "Failed to dispatch gui event"); delete item; } } @@ -77,7 +78,7 @@ int32_t GuiService::guiMain() { auto service = findServiceById(manifest.id); if (!lvgl::lock(5000)) { - LOGGER.error("LVGL guiMain start failed as LVGL couldn't be locked"); + LOG_E(TAG, "LVGL guiMain start failed as LVGL couldn't be locked"); return 0; } @@ -86,7 +87,7 @@ int32_t GuiService::guiMain() { auto* screen_root = lv_screen_active(); if (screen_root == nullptr) { - LOGGER.error("No display found, exiting GUI task"); + LOG_E(TAG, "No display found, exiting GUI task"); lvgl::unlock(); return 0; } @@ -150,7 +151,7 @@ void GuiService::redraw() { lock(); if (appRootWidget == nullptr) { - LOGGER.warn("No root widget"); + LOG_W(TAG, "No root widget"); unlock(); return; } @@ -181,13 +182,13 @@ void GuiService::redraw() { lv_obj_t* container = createAppViews(appRootWidget); appToRender->getApp()->onShow(*appToRender, container); } else { - LOGGER.warn("Nothing to draw"); + LOG_W(TAG, "Nothing to draw"); } // Unlock GUI and LVGL lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } unlock(); @@ -235,7 +236,7 @@ void GuiService::onStop(ServiceContext& service) { auto* exit_item = new GuiDispatchItem{this, GuiDispatchType::Exit, nullptr}; if (dispatcher_dispatch(dispatcher, exit_item, onGuiDispatch) != ERROR_NONE) { - LOGGER.error("Failed to dispatch gui exit event"); + LOG_E(TAG, "Failed to dispatch gui exit event"); check(false, "Failed to dispatch exit signal to thread."); delete exit_item; } @@ -248,7 +249,7 @@ void GuiService::onStop(ServiceContext& service) { } lvgl::unlock(); } else { - LOGGER.error("Failed to lock LVGL during GUI stop"); + LOG_E(TAG, "Failed to lock LVGL during GUI stop"); } delete thread; @@ -261,16 +262,16 @@ void GuiService::showApp(std::shared_ptr app) { lock.lock(); if (!isStarted) { - LOGGER.error("Failed to show app {}: GUI not started", app->getManifest().appId); + LOG_E(TAG, "Failed to show app %s: GUI not started", app->getManifest().appId.c_str()); return; } if (appToRender != nullptr && appToRender->getLaunchId() == app->getLaunchId()) { - LOGGER.warn("Already showing {}", app->getManifest().appId); + LOG_W(TAG, "Already showing %s", app->getManifest().appId.c_str()); return; } - LOGGER.info("Showing {}", app->getManifest().appId); + LOG_I(TAG, "Showing %s", app->getManifest().appId.c_str()); // Ensure previous app triggers onHide() logic if (appToRender != nullptr) { hideApp(); @@ -285,12 +286,12 @@ void GuiService::hideApp() { lock.lock(); if (!isStarted) { - LOGGER.error("Failed to hide app: GUI not started"); + LOG_E(TAG, "Failed to hide app: GUI not started"); return; } if (appToRender == nullptr) { - LOGGER.warn("hideApp() called but no app is currently shown"); + LOG_W(TAG, "hideApp() called but no app is currently shown"); return; } diff --git a/Tactility/Source/service/loader/Loader.cpp b/Tactility/Source/service/loader/Loader.cpp index 9f52c8cdf..8275dc361 100644 --- a/Tactility/Source/service/loader/Loader.cpp +++ b/Tactility/Source/service/loader/Loader.cpp @@ -3,9 +3,8 @@ #include #include -#include -#include #include +#include #include #include @@ -16,9 +15,11 @@ #include #endif +#include + namespace tt::service::loader { -static const auto LOGGER = Logger("Loader"); +constexpr auto* TAG = "Loader"; constexpr auto LOADER_TIMEOUT = (100 / portTICK_PERIOD_MS); @@ -44,17 +45,17 @@ static const char* appStateToString(app::State state) { } void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launchId, std::shared_ptr parameters) { - LOGGER.info("Start by id {}", id); + LOG_I(TAG, "Start by id %s", id.c_str()); auto app_manifest = app::findAppManifestById(id); if (app_manifest == nullptr) { - LOGGER.error("App not found: {}", id); + LOG_E(TAG, "App not found: %s", id.c_str()); return; } auto lock = mutex.asScopedLock(); if (!lock.lock(LOADER_TIMEOUT)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -76,14 +77,14 @@ void LoaderService::onStartAppMessage(const std::string& id, app::LaunchId launc void LoaderService::onStopTopAppMessage(const std::string& id) { auto lock = mutex.asScopedLock(); if (!lock.lock(LOADER_TIMEOUT)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } size_t original_stack_size = appStack.size(); if (original_stack_size == 0) { - LOGGER.error("Stop app: no app running"); + LOG_E(TAG, "Stop app: no app running"); return; } @@ -91,12 +92,12 @@ void LoaderService::onStopTopAppMessage(const std::string& id) { auto app_to_stop = appStack[appStack.size() - 1]; if (app_to_stop->getManifest().appId != id) { - LOGGER.error("Stop app: id mismatch (wanted {} but found {} on top of stack)", id, app_to_stop->getManifest().appId); + LOG_E(TAG, "Stop app: id mismatch (wanted %s but found %s on top of stack)", id.c_str(), app_to_stop->getManifest().appId.c_str()); return; } if (original_stack_size == 1 && app_to_stop->getManifest().appName != "Boot") { - LOGGER.error("Stop app: can't stop root app"); + LOG_E(TAG, "Stop app: can't stop root app"); return; } @@ -116,16 +117,16 @@ void LoaderService::onStopTopAppMessage(const std::string& id) { // We only expect the app to be referenced within the current scope if (app_to_stop.use_count() > 1) { - LOGGER.warn("Memory leak: Stopped {}, but use count is {}", app_to_stop->getManifest().appId, app_to_stop.use_count() - 1); + LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop.use_count() - 1)); } // Refcount is expected to be 2: 1 within app_to_stop and 1 within the current scope if (app_to_stop->getApp().use_count() > 2) { - LOGGER.warn("Memory leak: Stopped {}, but use count is {}", app_to_stop->getManifest().appId, app_to_stop->getApp().use_count() - 2); + LOG_W(TAG, "Memory leak: Stopped %s, but use count is %d", app_to_stop->getManifest().appId.c_str(), (int)(app_to_stop->getApp().use_count() - 2)); } #ifdef ESP_PLATFORM - LOGGER.info("Free heap: {}", heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); + LOG_I(TAG, "Free heap: %d", (int)heap_caps_get_free_size(MALLOC_CAP_INTERNAL)); #endif std::shared_ptr instance_to_resume; @@ -182,18 +183,18 @@ int LoaderService::findAppInStack(const std::string& id) const { void LoaderService::onStopAllAppMessage(const std::string& id) { auto lock = mutex.asScopedLock(); if (!lock.lock(LOADER_TIMEOUT)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } if (!isRunning(id)) { - LOGGER.error("Stop all: {} not running", id); + LOG_E(TAG, "Stop all: %s not running", id.c_str()); return; } int app_to_stop_index = findAppInStack(id); if (app_to_stop_index < 0) { - LOGGER.error("Stop all: {} not found in stack", id); + LOG_E(TAG, "Stop all: %s not found in stack", id.c_str()); return; } @@ -220,7 +221,7 @@ void LoaderService::onStopAllAppMessage(const std::string& id) { } if (instance_to_resume != nullptr) { - LOGGER.info("Resuming {}", instance_to_resume->getManifest().appId); + LOG_I(TAG, "Resuming %s", instance_to_resume->getManifest().appId.c_str()); transitionAppToState(instance_to_resume, app::State::Showing); instance_to_resume->getApp()->onResult( @@ -236,8 +237,8 @@ void LoaderService::transitionAppToState(const std::shared_ptr const app::AppManifest& app_manifest = app->getManifest(); const app::State old_state = app->getState(); - LOGGER.info( "App \"{}\" state: {} -> {}", - app_manifest.appId, + LOG_I(TAG, "App \"%s\" state: %s -> %s", + app_manifest.appId.c_str(), appStateToString(old_state), appStateToString(state) ); @@ -284,14 +285,14 @@ void LoaderService::stopTop() { } void LoaderService::stopTop(const std::string& id) { - LOGGER.info("dispatching stopTop({})", id); + LOG_I(TAG, "dispatching stopTop(%s)", id.c_str()); dispatcherThread->dispatch([this, id] { onStopTopAppMessage(id); }); } void LoaderService::stopAll(const std::string& id) { - LOGGER.info("dispatching stopAll({})", id); + LOG_I(TAG, "dispatching stopAll(%s)", id.c_str()); dispatcherThread->dispatch([this, id] { onStopAllAppMessage(id); }); diff --git a/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp b/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp index d017520b1..79cc3b712 100644 --- a/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp +++ b/Tactility/Source/service/memorychecker/MemoryCheckerService.cpp @@ -1,14 +1,14 @@ -#include #include #include #include #include #include +#include namespace tt::service::memorychecker { -static const auto LOGGER = Logger("MemoryChecker"); +constexpr auto* TAG = "MemoryChecker"; // Total memory (in bytes) that should be free before warnings occur constexpr auto TOTAL_FREE_THRESHOLD = 10'000; @@ -37,13 +37,13 @@ static bool isMemoryLow() { bool memory_low = false; const auto total_free = getInternalFree(); if (total_free < TOTAL_FREE_THRESHOLD) { - LOGGER.warn("Internal memory low: {} bytes", total_free); + LOG_W(TAG, "Internal memory low: %d bytes", (int)total_free); memory_low = true; } const auto largest_block = getInternalLargestFreeBlock(); if (largest_block < LARGEST_FREE_BLOCK_THRESHOLD) { - LOGGER.warn("Largest free internal memory block is {} bytes", largest_block); + LOG_W(TAG, "Largest free internal memory block is %d bytes", (int)largest_block); memory_low = true; } diff --git a/Tactility/Source/service/screenshot/Screenshot.cpp b/Tactility/Source/service/screenshot/Screenshot.cpp index 2a086c0d3..a85e1540f 100644 --- a/Tactility/Source/service/screenshot/Screenshot.cpp +++ b/Tactility/Source/service/screenshot/Screenshot.cpp @@ -2,17 +2,18 @@ #if TT_FEATURE_SCREENSHOT_ENABLED -#include #include -#include #include +#include #include #include +#include + namespace tt::service::screenshot { -static const auto LOGGER = Logger("ScreenshotService"); +constexpr auto* TAG = "ScreenshotService"; extern const ServiceManifest manifest; @@ -23,7 +24,7 @@ std::shared_ptr optScreenshotService() { void ScreenshotService::startApps(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -32,14 +33,14 @@ void ScreenshotService::startApps(const std::string& path) { mode = Mode::Apps; task->startApps(path); } else { - LOGGER.warn("Screenshot task already running"); + LOG_W(TAG,"Screenshot task already running"); } } void ScreenshotService::startTimed(const std::string& path, uint8_t delayInSeconds, uint8_t amount) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -48,13 +49,13 @@ void ScreenshotService::startTimed(const std::string& path, uint8_t delayInSecon mode = Mode::Timed; task->startTimed(path, delayInSeconds, amount); } else { - LOGGER.warn("Screenshot task already running"); + LOG_W(TAG,"Screenshot task already running"); } } bool ScreenshotService::onStart(ServiceContext& serviceContext) { if (lv_screen_active() == nullptr) { - LOGGER.error("No display found"); + LOG_E(TAG, "No display found"); return false; } @@ -64,7 +65,7 @@ bool ScreenshotService::onStart(ServiceContext& serviceContext) { void ScreenshotService::stop() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -72,14 +73,14 @@ void ScreenshotService::stop() { task = nullptr; mode = Mode::None; } else { - LOGGER.warn("Screenshot task not running"); + LOG_W(TAG,"Screenshot task not running"); } } Mode ScreenshotService::getMode() const { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG,LOG_MESSAGE_MUTEX_LOCK_FAILED); return Mode::None; } diff --git a/Tactility/Source/service/screenshot/ScreenshotTask.cpp b/Tactility/Source/service/screenshot/ScreenshotTask.cpp index 0f9cbdbcc..93d23381f 100644 --- a/Tactility/Source/service/screenshot/ScreenshotTask.cpp +++ b/Tactility/Source/service/screenshot/ScreenshotTask.cpp @@ -2,21 +2,22 @@ #if TT_FEATURE_SCREENSHOT_ENABLED -#include -#include #include +#include +#include #include -#include #include -#include +#include #include #include +#include + namespace tt::service::screenshot { -static const auto LOGGER = Logger("ScreenshotTask"); +constexpr auto* TAG = "ScreenshotTask"; ScreenshotTask::~ScreenshotTask() { if (thread) { @@ -27,7 +28,7 @@ ScreenshotTask::~ScreenshotTask() { bool ScreenshotTask::isInterrupted() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return true; } return interrupted; @@ -36,7 +37,7 @@ bool ScreenshotTask::isInterrupted() { bool ScreenshotTask::isFinished() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.warn(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_W(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return false; } return finished; @@ -51,13 +52,13 @@ void ScreenshotTask::setFinished() { static void makeScreenshot(const std::string& filename) { if (lvgl::lock(50 / portTICK_PERIOD_MS)) { if (lv_screenshot_create(lv_scr_act(), LV_100ASK_SCREENSHOT_SV_PNG, filename.c_str())) { - LOGGER.info("Screenshot saved to {}", filename); + LOG_I(TAG, "Screenshot saved to %s", filename.c_str()); } else { - LOGGER.error("Screenshot not saved to {}", filename); + LOG_E(TAG, "Screenshot not saved to %s", filename.c_str()); } lvgl::unlock(); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "LVGL"); } } @@ -103,7 +104,7 @@ void ScreenshotTask::taskMain() { void ScreenshotTask::taskStart() { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -123,7 +124,7 @@ void ScreenshotTask::taskStart() { void ScreenshotTask::startApps(const std::string& path) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -133,14 +134,14 @@ void ScreenshotTask::startApps(const std::string& path) { work.path = path; taskStart(); } else { - LOGGER.error("Task was already running"); + LOG_E(TAG, "Task was already running"); } } void ScreenshotTask::startTimed(const std::string& path, uint8_t delay_in_seconds, uint8_t amount) { auto lock = mutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } @@ -152,7 +153,7 @@ void ScreenshotTask::startTimed(const std::string& path, uint8_t delay_in_second work.path = path; taskStart(); } else { - LOGGER.error("Task was already running"); + LOG_E(TAG, "Task was already running"); } } diff --git a/Tactility/Source/service/statusbar/Statusbar.cpp b/Tactility/Source/service/statusbar/Statusbar.cpp index fa4bf4bfc..5269e2906 100644 --- a/Tactility/Source/service/statusbar/Statusbar.cpp +++ b/Tactility/Source/service/statusbar/Statusbar.cpp @@ -1,6 +1,5 @@ #include -#include #include #include #include @@ -27,9 +26,11 @@ #include +#include + namespace tt::service::statusbar { -static const auto LOGGER = Logger("StatusbarService"); +constexpr auto* TAG = "StatusbarService"; // GPS extern const ServiceManifest manifest; @@ -302,7 +303,7 @@ class StatusbarService final : public Service { bool onStart(ServiceContext& serviceContext) override { if (lv_screen_active() == nullptr) { - LOGGER.error("No display found"); + LOG_E(TAG, "No display found"); return false; } diff --git a/Tactility/Source/service/webserver/AssetVersion.cpp b/Tactility/Source/service/webserver/AssetVersion.cpp index 37cd4460e..db6555002 100644 --- a/Tactility/Source/service/webserver/AssetVersion.cpp +++ b/Tactility/Source/service/webserver/AssetVersion.cpp @@ -3,7 +3,6 @@ #include #include -#include #include #include @@ -12,9 +11,11 @@ #include #include +#include + namespace tt::service::webserver { -static const auto LOGGER = tt::Logger("AssetVersion"); +constexpr auto* TAG = "AssetVersion"; constexpr auto* DATA_VERSION_FILE = "/system/app/WebServer/version.json"; constexpr auto* SD_VERSION_FILE = "/sdcard/tactility/webserver/version.json"; constexpr auto* DATA_ASSETS_DIR = "/system/app/WebServer"; @@ -22,65 +23,65 @@ constexpr auto* SD_ASSETS_DIR = "/sdcard/tactility/webserver"; static bool loadVersionFromFile(const char* path, AssetVersion& version) { if (!file::isFile(path)) { - LOGGER.warn("Version file not found: {}", path); + LOG_W(TAG, "Version file not found: %s", path); return false; } - + // Read file content std::string content; { auto lock = file::getLock(path); lock->lock(portMAX_DELAY); - + FILE* fp = fopen(path, "r"); if (!fp) { - LOGGER.error("Failed to open version file: {}", path); + LOG_E(TAG, "Failed to open version file: %s", path); lock->unlock(); return false; } - + char buffer[256]; size_t bytesRead = fread(buffer, 1, sizeof(buffer) - 1, fp); bool readError = ferror(fp) != 0; fclose(fp); lock->unlock(); - + if (readError) { - LOGGER.error("Error reading version file: {}", path); + LOG_E(TAG, "Error reading version file: %s", path); return false; } if (bytesRead == 0) { - LOGGER.error("Version file is empty: {}", path); + LOG_E(TAG, "Version file is empty: %s", path); return false; } buffer[bytesRead] = '\0'; content = buffer; } - + // Parse JSON cJSON* json = cJSON_Parse(content.c_str()); if (json == nullptr) { - LOGGER.error("Failed to parse version JSON: {}", path); + LOG_E(TAG, "Failed to parse version JSON: %s", path); return false; } - + cJSON* versionItem = cJSON_GetObjectItem(json, "version"); if (versionItem == nullptr || !cJSON_IsNumber(versionItem)) { - LOGGER.error("Invalid version JSON format: {}", path); + LOG_E(TAG, "Invalid version JSON format: %s", path); cJSON_Delete(json); return false; } - + double versionValue = versionItem->valuedouble; if (versionValue < 0 || versionValue > UINT32_MAX) { - LOGGER.error("Version out of valid range [0, {}]: {}", UINT32_MAX, path); + LOG_E(TAG, "Version out of valid range [0, %u]: %s", (unsigned)UINT32_MAX, path); cJSON_Delete(json); return false; } version.version = static_cast(versionValue); cJSON_Delete(json); - - LOGGER.info("Loaded version {} from {}", version.version, path); + + LOG_I(TAG, "Loaded version %u from %s", (unsigned)version.version, path); return true; } @@ -92,23 +93,23 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) { dirPath = dirPath.substr(0, lastSlash); if (!file::isDirectory(dirPath.c_str())) { if (!file::findOrCreateDirectory(dirPath.c_str(), 0755)) { - LOGGER.error("Failed to create directory: {}", dirPath); + LOG_E(TAG, "Failed to create directory: %s", dirPath.c_str()); return false; } } } - + // Create JSON cJSON* json = cJSON_CreateObject(); if (json == nullptr) { - LOGGER.error("Failed to create JSON object for version"); + LOG_E(TAG, "Failed to create JSON object for version"); return false; } cJSON_AddNumberToObject(json, "version", version.version); - + char* jsonString = cJSON_Print(json); if (jsonString == nullptr) { - LOGGER.error("Failed to serialize version JSON"); + LOG_E(TAG, "Failed to serialize version JSON"); cJSON_Delete(json); return false; } @@ -126,12 +127,12 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) { success = (written == len); if (success) { if (fflush(fp) != 0) { - LOGGER.error("Failed to flush version file: {}", path); + LOG_E(TAG, "Failed to flush version file: %s", path); success = false; } else { int fd = fileno(fp); if (fd >= 0 && fsync(fd) != 0) { - LOGGER.error("Failed to fsync version file: {}", path); + LOG_E(TAG, "Failed to fsync version file: %s", path); success = false; } } @@ -145,9 +146,9 @@ static bool saveVersionToFile(const char* path, const AssetVersion& version) { cJSON_Delete(json); if (success) { - LOGGER.info("Saved version {} to {}", version.version, path); + LOG_I(TAG, "Saved version %u to %s", (unsigned)version.version, path); } else { - LOGGER.error("Failed to write version file: {}", path); + LOG_E(TAG, "Failed to write version file: %s", path); } return success; @@ -180,15 +181,15 @@ bool hasSdAssets() { static bool copyDirectory(const char* src, const char* dst, int depth = 0) { constexpr int MAX_DEPTH = 16; if (depth >= MAX_DEPTH) { - LOGGER.error("Max directory depth exceeded: {}", src); + LOG_E(TAG, "Max directory depth exceeded: %s", src); return false; } - LOGGER.info("Copying directory: {} -> {}", src, dst); - + LOG_I(TAG, "Copying directory: %s -> %s", src, dst); + // Create destination directory if (!file::isDirectory(dst)) { if (!file::findOrCreateDirectory(dst, 0755)) { - LOGGER.error("Failed to create destination directory: {}", dst); + LOG_E(TAG, "Failed to create destination directory: %s", dst); return false; } } @@ -216,7 +217,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { isDir = S_ISDIR(st.st_mode); isReg = S_ISREG(st.st_mode); } else { - LOGGER.warn("Failed to stat entry, skipping: {}", srcPath); + LOG_W(TAG, "Failed to stat entry, skipping: %s", srcPath.c_str()); return; } } @@ -233,14 +234,14 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { FILE* srcFile = fopen(srcPath.c_str(), "rb"); if (!srcFile) { - LOGGER.error("Failed to open source file: {}", srcPath); + LOG_E(TAG, "Failed to open source file: %s", srcPath.c_str()); copySuccess = false; return; } FILE* tempFile = fopen(tempPath.c_str(), "wb"); if (!tempFile) { - LOGGER.error("Failed to create temp file: {}", tempPath); + LOG_E(TAG, "Failed to create temp file: %s", tempPath.c_str()); fclose(srcFile); copySuccess = false; return; @@ -254,7 +255,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { while ((bytesRead = fread(buffer.get(), 1, COPY_BUF_SIZE, srcFile)) > 0) { size_t bytesWritten = fwrite(buffer.get(), 1, bytesRead, tempFile); if (bytesWritten != bytesRead) { - LOGGER.error("Failed to write to temp file: {}", tempPath); + LOG_E(TAG, "Failed to write to temp file: %s", tempPath.c_str()); fileCopySuccess = false; copySuccess = false; break; @@ -262,7 +263,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { } if (fileCopySuccess && ferror(srcFile)) { - LOGGER.error("Error reading source file: {}", srcPath); + LOG_E(TAG, "Error reading source file: %s", srcPath.c_str()); fileCopySuccess = false; copySuccess = false; } @@ -272,13 +273,13 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { // Flush and sync temp file before closing if (fileCopySuccess) { if (fflush(tempFile) != 0) { - LOGGER.error("Failed to flush temp file: {}", tempPath); + LOG_E(TAG, "Failed to flush temp file: %s", tempPath.c_str()); fileCopySuccess = false; copySuccess = false; } else { int fd = fileno(tempFile); if (fd >= 0 && fsync(fd) != 0) { - LOGGER.error("Failed to fsync temp file: {}", tempPath); + LOG_E(TAG, "Failed to fsync temp file: %s", tempPath.c_str()); fileCopySuccess = false; copySuccess = false; } @@ -292,7 +293,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { remove(dstPath.c_str()); // Rename temp file to destination if (rename(tempPath.c_str(), dstPath.c_str()) != 0) { - LOGGER.error("Failed to rename temp file {} to {}", tempPath, dstPath); + LOG_E(TAG, "Failed to rename temp file %s to %s", tempPath.c_str(), dstPath.c_str()); remove(tempPath.c_str()); fileCopySuccess = false; copySuccess = false; @@ -303,13 +304,13 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { } if (fileCopySuccess) { - LOGGER.info("Copied file: {}", entry.d_name); + LOG_I(TAG, "Copied file: %s", entry.d_name); } } }); - + if (!listSuccess) { - LOGGER.error("Failed to list source directory: {}", src); + LOG_E(TAG, "Failed to list source directory: %s", src); return false; } @@ -317,7 +318,7 @@ static bool copyDirectory(const char* src, const char* dst, int depth = 0) { } bool syncAssets() { - LOGGER.info("Starting asset synchronization..."); + LOG_I(TAG, "Starting asset synchronization..."); // Check if Data partition and SD card exist bool dataExists = hasDataAssets(); @@ -325,26 +326,26 @@ bool syncAssets() { // FIRST BOOT SCENARIO: Data has version 0, SD card is missing if (dataExists && !sdExists) { - LOGGER.info("First boot - Data exists but SD card backup missing"); - LOGGER.warn("Skipping SD backup during boot - will be created on first settings save"); - LOGGER.warn("This avoids watchdog timeout if SD card is slow or corrupted"); + LOG_I(TAG, "First boot - Data exists but SD card backup missing"); + LOG_W(TAG, "Skipping SD backup during boot - will be created on first settings save"); + LOG_W(TAG, "This avoids watchdog timeout if SD card is slow or corrupted"); return true; // Don't block boot - defer copy to runtime } // NO SD CARD: Just ensure Data has default structure if (!sdExists) { - LOGGER.warn("No SD card available - creating default Data structure if needed"); + LOG_W(TAG, "No SD card available - creating default Data structure if needed"); if (!dataExists) { if (!file::findOrCreateDirectory(DATA_ASSETS_DIR, 0755)) { - LOGGER.error("Failed to create Data assets directory"); + LOG_E(TAG, "Failed to create Data assets directory"); return false; } AssetVersion defaultVersion(0); // Start at version 0 - SD card updates will be version 1+ if (!saveDataVersion(defaultVersion)) { - LOGGER.error("Failed to save default Data version"); + LOG_E(TAG, "Failed to save default Data version"); return false; } - LOGGER.info("Created default Data assets structure (version 0)"); + LOG_I(TAG, "Created default Data assets structure (version 0)"); } return true; } @@ -355,39 +356,39 @@ bool syncAssets() { bool hasSdVer = loadSdVersion(sdVersion); if (!hasDataVer) { - LOGGER.warn("No Data version.json - assuming version 0"); + LOG_W(TAG, "No Data version.json - assuming version 0"); dataVersion.version = 0; if (!saveDataVersion(dataVersion)) { - LOGGER.warn("Failed to save default Data version (non-fatal)"); + LOG_W(TAG, "Failed to save default Data version (non-fatal)"); } } if (!hasSdVer) { - LOGGER.warn("No SD version.json - assuming version 0"); + LOG_W(TAG, "No SD version.json - assuming version 0"); sdVersion.version = 0; // DON'T save to SD during boot - defer to runtime - LOGGER.warn("Skipping SD version.json creation during boot - will be created on first settings save"); + LOG_W(TAG, "Skipping SD version.json creation during boot - will be created on first settings save"); } - LOGGER.info("Version comparison - Data: {}, SD: {}", dataVersion.version, sdVersion.version); + LOG_I(TAG, "Version comparison - Data: %u, SD: %u", (unsigned)dataVersion.version, (unsigned)sdVersion.version); if (sdVersion.version > dataVersion.version) { // Firmware update - copy SD -> Data - LOGGER.info("SD card newer (v{} > v{}) - copying assets SD -> Data (firmware update)", - sdVersion.version, dataVersion.version); + LOG_I(TAG, "SD card newer (v%u > v%u) - copying assets SD -> Data (firmware update)", + (unsigned)sdVersion.version, (unsigned)dataVersion.version); if (!copyDirectory(SD_ASSETS_DIR, DATA_ASSETS_DIR)) { - LOGGER.error("Failed to copy assets from SD to Data"); + LOG_E(TAG, "Failed to copy assets from SD to Data"); return false; } - LOGGER.info("Firmware update complete - assets updated from SD card"); + LOG_I(TAG, "Firmware update complete - assets updated from SD card"); } else if (dataVersion.version > sdVersion.version) { // User customization - backup Data -> SD - LOGGER.warn("Data newer (v{} > v{}) - deferring SD backup to avoid boot watchdog", - dataVersion.version, sdVersion.version); - LOGGER.warn("SD backup will occur on first WebServer settings save"); + LOG_W(TAG, "Data newer (v%u > v%u) - deferring SD backup to avoid boot watchdog", + (unsigned)dataVersion.version, (unsigned)sdVersion.version); + LOG_W(TAG, "SD backup will occur on first WebServer settings save"); return true; // Don't block boot - defer copy to runtime } else { - LOGGER.info("Versions match (v{}) - no sync needed", dataVersion.version); + LOG_I(TAG, "Versions match (v%u) - no sync needed", (unsigned)dataVersion.version); } return true; diff --git a/Tactility/Source/service/webserver/WebServerService.cpp b/Tactility/Source/service/webserver/WebServerService.cpp index c0289a011..12f2de647 100644 --- a/Tactility/Source/service/webserver/WebServerService.cpp +++ b/Tactility/Source/service/webserver/WebServerService.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -52,9 +51,11 @@ #include #include +#include + namespace tt::service::webserver { -static const auto LOGGER = tt::Logger("WebServerService"); +constexpr auto* TAG = "WebServerService"; // Helper to convert chip model enum to human-readable string static const char* getChipModelName(esp_chip_model_t model) { @@ -142,14 +143,14 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { std::string auth_header(auth_len + 1, '\0'); if (httpd_req_get_hdr_value_str(request, "Authorization", auth_header.data(), auth_len + 1) != ESP_OK) { - LOGGER.warn("Failed to read Authorization header"); + LOG_W(TAG, "Failed to read Authorization header"); return sendUnauthorized(request, "Authorization required"); } auth_header.resize(auth_len); // Remove null terminator from string length // Check for "Basic " prefix if (auth_header.rfind("Basic ", 0) != 0) { - LOGGER.warn("Authorization header is not Basic auth"); + LOG_W(TAG, "Authorization header is not Basic auth"); return sendUnauthorized(request, "Basic authorization required"); } @@ -170,7 +171,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { reinterpret_cast(base64_creds.c_str()), base64_creds.length()); if (ret != 0) { - LOGGER.warn("Failed to decode base64 credentials"); + LOG_W(TAG, "Failed to decode base64 credentials"); return sendUnauthorized(request, "Invalid credentials format"); } decoded.resize(actual_len); @@ -178,7 +179,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { // Parse username:password size_t colon_pos = decoded.find(':'); if (colon_pos == std::string::npos) { - LOGGER.warn("Invalid credentials format (no colon separator)"); + LOG_W(TAG, "Invalid credentials format (no colon separator)"); return sendUnauthorized(request, "Invalid credentials format"); } @@ -189,7 +190,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { bool usernameMatch = secureCompare(username, settings.webServerUsername); bool passwordMatch = secureCompare(password, settings.webServerPassword); if (!usernameMatch || !passwordMatch) { - LOGGER.warn("Invalid credentials for user '{}'", username); + LOG_W(TAG, "Invalid credentials for user '%s'", username.c_str()); return sendUnauthorized(request, "Invalid credentials"); } @@ -198,7 +199,7 @@ static esp_err_t validateRequestAuth(httpd_req_t* request, bool& authPassed) { } bool WebServerService::onStart(ServiceContext& service) { - LOGGER.info("Starting WebServer service..."); + LOG_I(TAG, "Starting WebServer service..."); // Register global instance g_webServerInstance.store(this); @@ -228,10 +229,10 @@ bool WebServerService::onStart(ServiceContext& service) { // Start HTTP server only if enabled in settings (default: OFF to save memory) if (serverEnabled) { - LOGGER.info("WebServer enabled in settings, starting HTTP server..."); + LOG_I(TAG, "WebServer enabled in settings, starting HTTP server..."); setEnabled(true); } else { - LOGGER.info("WebServer disabled in settings, NOT starting HTTP server (saves ~10KB RAM)"); + LOG_I(TAG, "WebServer disabled in settings, NOT starting HTTP server (saves ~10KB RAM)"); setEnabled(false); } @@ -288,15 +289,15 @@ bool WebServerService::startApMode() { } if (settings.wifiMode != settings::webserver::WiFiMode::AccessPoint) { - LOGGER.info("Not in AP mode, skipping AP WiFi initialization"); + LOG_I(TAG, "Not in AP mode, skipping AP WiFi initialization"); return true; // Not an error, just not needed } - LOGGER.info("Starting WiFi in Access Point mode..."); + LOG_I(TAG, "Starting WiFi in Access Point mode..."); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); if (esp_wifi_init(&cfg) != ESP_OK) { - LOGGER.error("esp_wifi_init() failed"); + LOG_E(TAG, "esp_wifi_init() failed"); return false; } apWifiInitialized = true; @@ -304,14 +305,14 @@ bool WebServerService::startApMode() { // Create the AP network interface apNetif = esp_netif_create_default_wifi_ap(); if (apNetif == nullptr) { - LOGGER.error("esp_netif_create_default_wifi_ap() failed"); + LOG_E(TAG, "esp_netif_create_default_wifi_ap() failed"); esp_wifi_deinit(); apWifiInitialized = false; return false; } if (esp_wifi_set_mode(WIFI_MODE_AP) != ESP_OK) { - LOGGER.error("esp_wifi_set_mode(AP) failed"); + LOG_E(TAG, "esp_wifi_set_mode(AP) failed"); stopApMode(); return false; } @@ -324,19 +325,19 @@ bool WebServerService::startApMode() { ip_info.netmask.addr = ipaddr_addr("255.255.255.0"); if (esp_netif_dhcps_stop(apNetif) != ESP_OK) { - LOGGER.error("esp_netif_dhcps_stop() failed"); + LOG_E(TAG, "esp_netif_dhcps_stop() failed"); stopApMode(); return false; } if (esp_netif_set_ip_info(apNetif, &ip_info) != ESP_OK) { - LOGGER.error("esp_netif_set_ip_info() failed"); + LOG_E(TAG, "esp_netif_set_ip_info() failed"); stopApMode(); return false; } if (esp_netif_dhcps_start(apNetif) != ESP_OK) { - LOGGER.error("esp_netif_dhcps_start() failed"); + LOG_E(TAG, "esp_netif_dhcps_start() failed"); stopApMode(); return false; } @@ -354,36 +355,36 @@ bool WebServerService::startApMode() { if (settings.apOpenNetwork) { // User explicitly chose an open network wifi_config.ap.authmode = WIFI_AUTH_OPEN; - LOGGER.info("AP configured with OPEN authentication (user choice)"); + LOG_I(TAG, "AP configured with OPEN authentication (user choice)"); } else if (settings.apPassword.length() >= 8 && settings.apPassword.length() <= 63) { wifi_config.ap.authmode = WIFI_AUTH_WPA2_PSK; strncpy(reinterpret_cast(wifi_config.ap.password), settings.apPassword.c_str(), sizeof(wifi_config.ap.password) - 1); wifi_config.ap.password[sizeof(wifi_config.ap.password) - 1] = '\0'; - LOGGER.info("AP configured with WPA2-PSK authentication"); + LOG_I(TAG, "AP configured with WPA2-PSK authentication"); } else { if (!settings.apPassword.empty()) { - LOGGER.warn("AP password invalid (must be 8-63 chars, got {}) - using OPEN mode", settings.apPassword.length()); + LOG_W(TAG, "AP password invalid (must be 8-63 chars, got %zu) - using OPEN mode", settings.apPassword.length()); } wifi_config.ap.authmode = WIFI_AUTH_OPEN; - LOGGER.warn("AP configured with OPEN authentication (no password)"); + LOG_W(TAG, "AP configured with OPEN authentication (no password)"); } wifi_config.ap.max_connection = 4; wifi_config.ap.channel = settings.apChannel; if (esp_wifi_set_config(WIFI_IF_AP, &wifi_config) != ESP_OK) { - LOGGER.error("esp_wifi_set_config(AP) failed"); + LOG_E(TAG, "esp_wifi_set_config(AP) failed"); stopApMode(); return false; } if (esp_wifi_start() != ESP_OK) { - LOGGER.error("esp_wifi_start() failed"); + LOG_E(TAG, "esp_wifi_start() failed"); stopApMode(); return false; } - LOGGER.info("WiFi AP started - SSID: '{}', Channel: {}, IP: 192.168.4.1", settings.apSsid, settings.apChannel); + LOG_I(TAG, "WiFi AP started - SSID: '%s', Channel: %u, IP: 192.168.4.1", settings.apSsid.c_str(), (unsigned)settings.apChannel); return true; } @@ -395,15 +396,15 @@ void WebServerService::stopApMode() { } err = esp_wifi_stop(); if (err != ESP_OK && err != ESP_ERR_WIFI_NOT_STARTED) { - LOGGER.warn("esp_wifi_stop() in cleanup: {}", esp_err_to_name(err)); + LOG_W(TAG, "esp_wifi_stop() in cleanup: %s", esp_err_to_name(err)); } - LOGGER.info("WiFi AP stopped"); + LOG_I(TAG, "WiFi AP stopped"); err = esp_wifi_set_mode(WIFI_MODE_STA); if (err != ESP_OK) { - LOGGER.warn("esp_wifi_set_mode() in cleanup: {}", esp_err_to_name(err)); + LOG_W(TAG, "esp_wifi_set_mode() in cleanup: %s", esp_err_to_name(err)); } - LOGGER.info("Wifi mode set back to STA"); + LOG_I(TAG, "Wifi mode set back to STA"); apWifiInitialized = false; } @@ -428,7 +429,7 @@ bool WebServerService::startServer() { // Start AP mode WiFi if configured if (settings.wifiMode == settings::webserver::WiFiMode::AccessPoint) { if (!startApMode()) { - LOGGER.error("Failed to start AP mode WiFi - HTTP server will not start"); + LOG_E(TAG, "Failed to start AP mode WiFi - HTTP server will not start"); return false; } } @@ -505,19 +506,19 @@ bool WebServerService::startServer() { httpServer->start(); if (!httpServer->isStarted()) { - LOGGER.error("Failed to start HTTP server on port {}", settings.webServerPort); + LOG_E(TAG, "Failed to start HTTP server on port %u", (unsigned)settings.webServerPort); httpServer.reset(); return false; } - LOGGER.info("HTTP server started successfully on port {}", settings.webServerPort); + LOG_I(TAG, "HTTP server started successfully on port %u", (unsigned)settings.webServerPort); publish_event(this, WebServerEvent::WebServerStarted); // Show statusbar icon if (statusbarIconId >= 0) { lvgl::statusbar_icon_set_image(statusbarIconId, LVGL_ICON_STATUSBAR_CLOUD); lvgl::statusbar_icon_set_visibility(statusbarIconId, true); - LOGGER.info("WebServer statusbar icon shown ({} mode)", + LOG_I(TAG, "WebServer statusbar icon shown (%s mode)", settings.wifiMode == settings::webserver::WiFiMode::AccessPoint ? "AP" : "Station"); } @@ -537,7 +538,7 @@ void WebServerService::stopServer() { stopApMode(); } - LOGGER.info("HTTP server stopped"); + LOG_I(TAG, "HTTP server stopped"); publish_event(this, WebServerEvent::WebServerStopped); if (statusbarIconId >= 0) { @@ -550,7 +551,7 @@ void WebServerService::stopServer() { esp_err_t WebServerService::handleRoot(httpd_req_t* request) { - LOGGER.info("GET / -> redirecting to /dashboard.html"); + LOG_I(TAG, "GET / -> redirecting to /dashboard.html"); httpd_resp_set_status(request, "302 Found"); httpd_resp_set_hdr(request, "Location", "/dashboard.html"); return httpd_resp_send(request, nullptr, 0); @@ -722,7 +723,7 @@ static bool uriMatches(const char* uri, const char* route) { } esp_err_t WebServerService::handleFileBrowser(httpd_req_t* request) { - LOGGER.info("GET /filebrowser -> redirecting to /dashboard.html#files"); + LOG_I(TAG, "GET /filebrowser -> redirecting to /dashboard.html#files"); httpd_resp_set_status(request, "302 Found"); httpd_resp_set_hdr(request, "Location", "/dashboard.html#files"); return httpd_resp_send(request, nullptr, 0); @@ -735,17 +736,17 @@ esp_err_t WebServerService::handleFsList(httpd_req_t* request) { if (qlen > 1) { std::unique_ptr qbuf(new char[qlen]); if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) { - LOGGER.info("GET /fs/list raw query: {}", qbuf.get()); + LOG_I(TAG, "GET /fs/list raw query: %s", qbuf.get()); } } if (!getQueryParam(request, "path", path) || path.empty()) path = "/"; std::string norm = normalizePath(path); - LOGGER.info("GET /fs/list decoded path: '{}' normalized: '{}'", path, norm); + LOG_I(TAG, "GET /fs/list decoded path: '%s' normalized: '%s'", path.c_str(), norm.c_str()); // Allow root path for listing mount points if (!isAllowedBasePath(norm, true)) { - LOGGER.warn("GET /fs/list - invalid path requested: '{}' normalized: '{}'", path, norm); + LOG_W(TAG, "GET /fs/list - invalid path requested: '%s' normalized: '%s'", path.c_str(), norm.c_str()); httpd_resp_set_type(request, "application/json"); httpd_resp_sendstr(request, "{\"error\":\"invalid path\"}"); return ESP_OK; @@ -811,7 +812,7 @@ esp_err_t WebServerService::handleFsDownload(httpd_req_t* request) { } std::string norm = normalizePath(path); if (!isAllowedBasePath(norm) || !file::isFile(norm)) { - LOGGER.warn("GET /fs/download - not found or invalid path: '{}' normalized: '{}'", path, norm); + LOG_W(TAG, "GET /fs/download - not found or invalid path: '%s' normalized: '%s'", path.c_str(), norm.c_str()); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -859,7 +860,7 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) { if (qlen > 1) { std::unique_ptr qbuf(new char[qlen]); if (httpd_req_get_url_query_str(request, qbuf.get(), qlen) == ESP_OK) { - LOGGER.info("POST /fs/upload raw query: {}", qbuf.get()); + LOG_I(TAG, "POST /fs/upload raw query: %s", qbuf.get()); } } @@ -872,10 +873,10 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) { char content_type[64] = {0}; httpd_req_get_hdr_value_str(request, "Content-Type", content_type, sizeof(content_type)); std::string norm = normalizePath(path); - LOGGER.info("POST /fs/upload decoded path: '{}' normalized: '{}' Content-Length: {} Content-Type: {}", path, norm, (int)request->content_len, content_type[0] ? content_type : "(null)"); + LOG_I(TAG, "POST /fs/upload decoded path: '%s' normalized: '%s' Content-Length: %d Content-Type: %s", path.c_str(), norm.c_str(), (int)request->content_len, content_type[0] ? content_type : "(null)"); if (!isAllowedBasePath(norm)) { - LOGGER.warn("POST /fs/upload - invalid path requested: '{}' normalized: '{}'", path, norm); + LOG_W(TAG, "POST /fs/upload - invalid path requested: '%s' normalized: '%s'", path.c_str(), norm.c_str()); httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); return ESP_FAIL; } @@ -902,18 +903,18 @@ esp_err_t WebServerService::handleFsUpload(httpd_req_t* request) { // Timeout - retry with backoff timeout_retries++; if (timeout_retries >= MAX_TIMEOUT_RETRIES) { - LOGGER.error("Upload recv timeout after {} retries", timeout_retries); + LOG_E(TAG, "Upload recv timeout after %d retries", timeout_retries); fclose(fp); remove(norm.c_str()); // Clean up partial file httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv timeout"); return ESP_FAIL; } - LOGGER.warn("Upload recv timeout, retry {}/{}", timeout_retries, MAX_TIMEOUT_RETRIES); + LOG_W(TAG, "Upload recv timeout, retry %d/%d", timeout_retries, MAX_TIMEOUT_RETRIES); vTaskDelay(pdMS_TO_TICKS(100 * timeout_retries)); // Linear backoff continue; } if (ret <= 0) { - LOGGER.error("Upload recv failed with error {}", ret); + LOG_E(TAG, "Upload recv failed with error %d", ret); fclose(fp); remove(norm.c_str()); // Clean up partial file httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "recv failed"); @@ -951,7 +952,7 @@ esp_err_t WebServerService::handleFsGenericGet(httpd_req_t* request) { if (uriMatches(uri, "/fs/list")) return handleFsList(request); if (uriMatches(uri, "/fs/download")) return handleFsDownload(request); if (uriMatches(uri, "/fs/tree")) return handleFsTree(request); - LOGGER.warn("GET {} - not found in fs generic dispatcher", uri); + LOG_W(TAG, "GET %s - not found in fs generic dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -970,7 +971,7 @@ esp_err_t WebServerService::handleFsGenericPost(httpd_req_t* request) { if (uriMatches(uri, "/fs/delete")) return handleFsDelete(request); if (uriMatches(uri, "/fs/rename")) return handleFsRename(request); if (uriMatches(uri, "/fs/upload")) return handleFsUpload(request); - LOGGER.warn("POST {} - not found in fs generic dispatcher", uri); + LOG_W(TAG, "POST %s - not found in fs generic dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -986,7 +987,7 @@ esp_err_t WebServerService::handleAdminPost(httpd_req_t* request) { const char* uri = request->uri; if (strncmp(uri, "/admin/reboot", 13) == 0) return handleReboot(request); - LOGGER.info("POST {} - not found in admin dispatcher", uri); + LOG_I(TAG, "POST %s - not found in admin dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -1019,7 +1020,7 @@ esp_err_t WebServerService::handleApiGet(httpd_req_t* request) { return handleApiScreenshot(request); } - LOGGER.warn("GET {} - not found in api dispatcher", uri); + LOG_W(TAG, "GET %s - not found in api dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -1040,7 +1041,7 @@ esp_err_t WebServerService::handleApiPost(httpd_req_t* request) { return handleApiAppsUninstall(request); } - LOGGER.warn("POST {} - not found in api dispatcher", uri); + LOG_W(TAG, "POST %s - not found in api dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } @@ -1058,13 +1059,13 @@ esp_err_t WebServerService::handleApiPut(httpd_req_t* request) { return handleApiAppsInstall(request); } - LOGGER.warn("PUT {} - not found in api dispatcher", uri); + LOG_W(TAG, "PUT %s - not found in api dispatcher", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "not found"); return ESP_FAIL; } esp_err_t WebServerService::handleApiSysinfo(httpd_req_t* request) { - LOGGER.info("GET /api/sysinfo"); + LOG_I(TAG, "GET /api/sysinfo"); std::ostringstream json; json << "{"; @@ -1214,7 +1215,7 @@ esp_err_t WebServerService::handleApiSysinfo(httpd_req_t* request) { // GET /api/apps - List installed apps esp_err_t WebServerService::handleApiApps(httpd_req_t* request) { - LOGGER.info("GET /api/apps"); + LOG_I(TAG, "GET /api/apps"); auto manifests = app::getAppManifests(); @@ -1255,7 +1256,7 @@ esp_err_t WebServerService::handleApiApps(httpd_req_t* request) { // POST /api/apps/run?id=xxx - Run an app esp_err_t WebServerService::handleApiAppsRun(httpd_req_t* request) { - LOGGER.info("POST /api/apps/run"); + LOG_I(TAG, "POST /api/apps/run"); std::string appId; if (!getQueryParam(request, "id", appId) || appId.empty()) { @@ -1276,14 +1277,14 @@ esp_err_t WebServerService::handleApiAppsRun(httpd_req_t* request) { app::start(appId); - LOGGER.info("[200] /api/apps/run {}", appId); + LOG_I(TAG, "[200] /api/apps/run %s", appId.c_str()); httpd_resp_sendstr(request, "ok"); return ESP_OK; } // POST /api/apps/uninstall?id=xxx - Uninstall an app esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) { - LOGGER.info("POST /api/apps/uninstall"); + LOG_I(TAG, "POST /api/apps/uninstall"); std::string appId; if (!getQueryParam(request, "id", appId) || appId.empty()) { @@ -1293,7 +1294,7 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) { auto manifest = app::findAppManifestById(appId); if (!manifest) { - LOGGER.info("[200] /api/apps/uninstall {} (app wasn't installed)", appId); + LOG_I(TAG, "[200] /api/apps/uninstall %s (app wasn't installed)", appId.c_str()); httpd_resp_sendstr(request, "ok"); return ESP_OK; } @@ -1305,11 +1306,11 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) { } if (app::uninstall(appId)) { - LOGGER.info("[200] /api/apps/uninstall {}", appId); + LOG_I(TAG, "[200] /api/apps/uninstall %s", appId.c_str()); httpd_resp_sendstr(request, "ok"); return ESP_OK; } else { - LOGGER.warn("[500] /api/apps/uninstall {}", appId); + LOG_W(TAG, "[500] /api/apps/uninstall %s", appId.c_str()); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "uninstall failed"); return ESP_FAIL; } @@ -1317,7 +1318,7 @@ esp_err_t WebServerService::handleApiAppsUninstall(httpd_req_t* request) { // PUT /api/apps/install - Install an app from multipart form upload esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) { - LOGGER.info("PUT /api/apps/install"); + LOG_I(TAG, "PUT /api/apps/install"); std::string boundary; if (!network::getMultiPartBoundaryOrSendError(request, boundary)) { @@ -1340,14 +1341,14 @@ esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) { auto content_disposition_map = network::parseContentDisposition(content_headers); if (content_disposition_map.empty()) { - LOGGER.warn("parseContentDisposition returned empty map for: {}", content_headers_data); + LOG_W(TAG, "parseContentDisposition returned empty map for: %s", content_headers_data.c_str()); httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "invalid content disposition"); return ESP_FAIL; } auto filename_entry = content_disposition_map.find("filename"); if (filename_entry == content_disposition_map.end()) { - LOGGER.warn("filename not found in content disposition map"); + LOG_W(TAG, "filename not found in content disposition map"); httpd_resp_send_err(request, HTTPD_400_BAD_REQUEST, "filename parameter missing"); return ESP_FAIL; } @@ -1402,10 +1403,10 @@ esp_err_t WebServerService::handleApiAppsInstall(httpd_req_t* request) { // Cleanup temp file if (!file::deleteFile(file_path)) { - LOGGER.warn("Failed to delete temp file {}", file_path); + LOG_W(TAG, "Failed to delete temp file %s", file_path.c_str()); } - LOGGER.info("[200] /api/apps/install -> {}", file_path); + LOG_I(TAG, "[200] /api/apps/install -> %s", file_path.c_str()); httpd_resp_sendstr(request, "ok"); return ESP_OK; } @@ -1425,7 +1426,7 @@ static const char* radioStateToJsonString(wifi::RadioState state) { // GET /api/wifi - WiFi status esp_err_t WebServerService::handleApiWifi(httpd_req_t* request) { - LOGGER.info("GET /api/wifi"); + LOG_I(TAG, "GET /api/wifi"); auto state = wifi::getRadioState(); auto ip = wifi::getIp(); @@ -1450,7 +1451,7 @@ esp_err_t WebServerService::handleApiWifi(httpd_req_t* request) { // GET /api/screenshot - Capture and return screenshot as PNG // Screenshots are saved to SD card root (if available) or /data with incrementing numbers esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { - LOGGER.info("GET /api/screenshot"); + LOG_I(TAG, "GET /api/screenshot"); #if TT_FEATURE_SCREENSHOT_ENABLED // Determine save location: prefer SD card root if mounted, otherwise /data @@ -1471,7 +1472,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { return ESP_FAIL; } - LOGGER.info("Screenshot will be saved to: {}", screenshot_path); + LOG_I(TAG, "Screenshot will be saved to: %s", screenshot_path.c_str()); // LVGL's lodepng uses lv_fs which requires the "A:" prefix std::string lvgl_screenshot_path = lvgl::PATH_PREFIX + screenshot_path; @@ -1482,13 +1483,13 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { lvgl::unlock(); if (!success) { - LOGGER.error("lv_screenshot_create failed for path: {}", lvgl_screenshot_path); + LOG_E(TAG, "lv_screenshot_create failed for path: %s", lvgl_screenshot_path.c_str()); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "screenshot capture failed"); return ESP_FAIL; } - LOGGER.info("Screenshot captured successfully"); + LOG_I(TAG, "Screenshot captured successfully"); } else { - LOGGER.error("Could not acquire LVGL lock within 100ms"); + LOG_E(TAG, "Could not acquire LVGL lock within 100ms"); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, "could not acquire LVGL lock"); return ESP_FAIL; } @@ -1514,7 +1515,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { httpd_resp_send_chunk(request, nullptr, 0); // File is kept on storage (not deleted) for user access - LOGGER.info("[200] /api/screenshot -> {}", screenshot_path); + LOG_I(TAG, "[200] /api/screenshot -> %s", screenshot_path.c_str()); return ESP_OK; #else httpd_resp_send_err(request, HTTPD_501_METHOD_NOT_IMPLEMENTED, "screenshot feature not enabled"); @@ -1524,7 +1525,7 @@ esp_err_t WebServerService::handleApiScreenshot(httpd_req_t* request) { esp_err_t WebServerService::handleFsTree(httpd_req_t* request) { - LOGGER.info("GET /fs/tree"); + LOG_I(TAG, "GET /fs/tree"); std::ostringstream json; json << "{"; @@ -1569,7 +1570,7 @@ esp_err_t WebServerService::handleFsMkdir(httpd_req_t* request) { return ESP_FAIL; } std::string norm = normalizePath(path); - LOGGER.info("POST /fs/mkdir requested: '{}' normalized: '{}'", path, norm); + LOG_I(TAG, "POST /fs/mkdir requested: '%s' normalized: '%s'", path.c_str(), norm.c_str()); if (!isAllowedBasePath(norm)) { httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); return ESP_FAIL; @@ -1592,7 +1593,7 @@ esp_err_t WebServerService::handleFsDelete(httpd_req_t* request) { return ESP_FAIL; } std::string norm = normalizePath(path); - LOGGER.info("POST /fs/delete requested: '{}' normalized: '{}'", path, norm); + LOG_I(TAG, "POST /fs/delete requested: '%s' normalized: '%s'", path.c_str(), norm.c_str()); if (!isAllowedBasePath(norm)) { httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); return ESP_FAIL; @@ -1623,7 +1624,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) { return ESP_FAIL; } std::string norm = normalizePath(path); - LOGGER.info("POST /fs/rename requested: '{}' normalized: '{}' -> newName: '{}'", path.c_str(), norm.c_str(), newName.c_str()); + LOG_I(TAG, "POST /fs/rename requested: '%s' normalized: '%s' -> newName: '%s'", path.c_str(), norm.c_str(), newName.c_str()); if (!isAllowedBasePath(norm)) { httpd_resp_send_err(request, HTTPD_403_FORBIDDEN, "invalid path"); return ESP_FAIL; @@ -1662,7 +1663,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) { int r = rename(norm.c_str(), target.c_str()); if (r != 0) { int e = errno; - LOGGER.warn("rename failed errno={} ({}) -> {} -> {}", e, strerror(e), norm, target); + LOG_W(TAG, "rename failed errno=%d (%s) -> %s -> %s", e, strerror(e), norm.c_str(), target.c_str()); // Return errno string to client to aid debugging std::string msg = std::string("rename failed: ") + strerror(e); httpd_resp_send_err(request, HTTPD_500_INTERNAL_SERVER_ERROR, msg.c_str()); @@ -1676,7 +1677,7 @@ esp_err_t WebServerService::handleFsRename(httpd_req_t* request) { esp_err_t WebServerService::handleReboot(httpd_req_t* request) { - LOGGER.info("POST /reboot"); + LOG_I(TAG, "POST /reboot"); httpd_resp_sendstr(request, "Rebooting..."); // Reboot after a short delay to allow response to be sent @@ -1695,7 +1696,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) { } const char* uri = request->uri; - LOGGER.info("GET {}", uri); + LOG_I(TAG, "GET %s", uri); // Special case: serve favicon from system assets if (strcmp(uri, "/favicon.ico") == 0) { @@ -1721,7 +1722,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) { fclose(fp); lock->unlock(); httpd_resp_send_chunk(request, nullptr, 0); - LOGGER.info("[200] {} (favicon)", uri); + LOG_I(TAG, "[200] %s (favicon)", uri); return ESP_OK; } lock->unlock(); @@ -1745,7 +1746,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) { std::string dataPath = std::string("/system/app/WebServer") + requestedPath; if (requestedPath == "/dashboard.html" && !file::isFile(dataPath.c_str())) { - LOGGER.info("dashboard.html not found, serving default.html"); + LOG_I(TAG, "dashboard.html not found, serving default.html"); } // Try to serve from Data partition first @@ -1771,7 +1772,7 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) { lock->unlock(); httpd_resp_send_chunk(request, nullptr, 0); // End of chunks - LOGGER.info("[200] {} (from Data)", uri); + LOG_I(TAG, "[200] %s (from Data)", uri); return ESP_OK; } lock->unlock(); @@ -1800,14 +1801,14 @@ esp_err_t WebServerService::handleAssets(httpd_req_t* request) { lock->unlock(); httpd_resp_send_chunk(request, nullptr, 0); // End of chunks - LOGGER.info("[200] {} (from SD)", uri); + LOG_I(TAG, "[200] %s (from SD)", uri); return ESP_OK; } lock->unlock(); } // File not found - LOGGER.warn("[404] {}", uri); + LOG_W(TAG, "[404] %s", uri); httpd_resp_send_err(request, HTTPD_404_NOT_FOUND, "File not found"); return ESP_FAIL; } @@ -1823,7 +1824,7 @@ void setWebServerEnabled(bool enabled) { instance->setEnabled(enabled); // Don't log here - startServer()/stopServer() already log the actual result } else { - LOGGER.warn("WebServer service not available, cannot {}", enabled ? "start" : "stop"); + LOG_W(TAG, "WebServer service not available, cannot %s", enabled ? "start" : "stop"); } } diff --git a/Tactility/Source/service/wifi/WifiApSettings.cpp b/Tactility/Source/service/wifi/WifiApSettings.cpp index 71d32536f..ab288dbcf 100644 --- a/Tactility/Source/service/wifi/WifiApSettings.cpp +++ b/Tactility/Source/service/wifi/WifiApSettings.cpp @@ -4,9 +4,11 @@ #include #include -#include #include + +#include + #include #include #include @@ -15,7 +17,7 @@ namespace tt::service::wifi::settings { -static const auto LOGGER = Logger("WifiApSettings"); +constexpr auto* TAG = "WifiApSettings"; constexpr auto* AP_SETTINGS_FORMAT = "{}/{}.ap.properties"; @@ -34,7 +36,7 @@ std::string toHexString(const uint8_t *data, int length) { bool readHex(const std::string& input, uint8_t* buffer, int length) { if (input.size() / 2 != length) { - LOGGER.error("readHex() length mismatch"); + LOG_E(TAG, "readHex() length mismatch"); return false; } @@ -64,7 +66,7 @@ static bool encrypt(const std::string& ssidInput, std::string& ssidOutput) { crypt::getIv(ssidInput.c_str(), ssidInput.size(), iv); if (crypt::encrypt(iv, reinterpret_cast(ssidInput.c_str()), buffer, encrypted_length) != 0) { - LOGGER.error("Failed to encrypt"); + LOG_E(TAG, "Failed to encrypt"); free(buffer); return false; } @@ -80,7 +82,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) { assert(ssidInput.size() % 2 == 0); auto* data = static_cast(malloc(ssidInput.size() / 2)); if (!readHex(ssidInput, data, ssidInput.size() / 2)) { - LOGGER.error("Failed to read hex"); + LOG_E(TAG, "Failed to read hex"); return false; } @@ -102,7 +104,7 @@ static bool decrypt(const std::string& ssidInput, std::string& ssidOutput) { free(data); if (decrypt_result != 0) { - LOGGER.error("Failed to decrypt credentials for \"{}s\": {}", ssidInput, decrypt_result); + LOG_E(TAG, "Failed to decrypt credentials for \"%ss\": %d", ssidInput.c_str(), decrypt_result); free(result); return false; } @@ -186,7 +188,7 @@ bool save(const WifiApSettings& apSettings) { const auto file_path = getApPropertiesFilePath(service_context->getPaths(), apSettings.ssid); if (!file::findOrCreateParentDirectory(file_path, 0755)) { - LOGGER.error("Failed to create {}", file_path); + LOG_E(TAG, "Failed to create %s", file_path.c_str()); return false; } diff --git a/Tactility/Source/service/wifi/WifiBootSplashInit.cpp b/Tactility/Source/service/wifi/WifiBootSplashInit.cpp index 50431dcbd..de9b94e7d 100644 --- a/Tactility/Source/service/wifi/WifiBootSplashInit.cpp +++ b/Tactility/Source/service/wifi/WifiBootSplashInit.cpp @@ -7,11 +7,13 @@ #include #include -#include #include #include #include + +#include + #include #include #include @@ -20,7 +22,7 @@ namespace tt::service::wifi { -static const auto LOGGER = Logger("WifiBootSplashInit"); +constexpr auto* TAG = "WifiBootSplashInit"; constexpr auto* AP_PROPERTIES_KEY_SSID = "ssid"; constexpr auto* AP_PROPERTIES_KEY_PASSWORD = "password"; @@ -39,13 +41,13 @@ struct ApProperties { static void importWifiAp(const std::string& filePath) { std::map map; if (!file::loadPropertiesFile(filePath, map)) { - LOGGER.error("Failed to load AP properties at {}", filePath); + LOG_E(TAG, "Failed to load AP properties at %s", filePath.c_str()); return; } const auto ssid_iterator = map.find(AP_PROPERTIES_KEY_SSID); if (ssid_iterator == map.end()) { - LOGGER.error("{} is missing ssid", filePath); + LOG_E(TAG, "%s is missing ssid", filePath.c_str()); return; } const auto ssid = ssid_iterator->second; @@ -69,18 +71,18 @@ static void importWifiAp(const std::string& filePath) { ); if (!settings::save(settings)) { - LOGGER.error("Failed to save settings for {}", ssid); + LOG_E(TAG, "Failed to save settings for %s", ssid.c_str()); } else { - LOGGER.info("Imported {} from {}", ssid, filePath); + LOG_I(TAG, "Imported %s from %s", ssid.c_str(), filePath.c_str()); } } const auto auto_remove_iterator = map.find(AP_PROPERTIES_KEY_AUTO_REMOVE); if (auto_remove_iterator != map.end() && auto_remove_iterator->second == "true") { if (!remove(filePath.c_str())) { - LOGGER.error("Failed to auto-remove {}", filePath); + LOG_E(TAG, "Failed to auto-remove %s", filePath.c_str()); } else { - LOGGER.info("Auto-removed {}", filePath); + LOG_I(TAG, "Auto-removed %s", filePath.c_str()); } } } @@ -109,7 +111,7 @@ static void importWifiApSettingsFromDir(const std::string& path) { } if (dirent_list.empty()) { - LOGGER.warn("No AP files found at {}", path); + LOG_W(TAG, "No AP files found at %s", path.c_str()); return; } @@ -120,24 +122,24 @@ static void importWifiApSettingsFromDir(const std::string& path) { } void bootSplashInit() { - LOGGER.info("bootSplashInit dispatch"); + LOG_I(TAG, "bootSplashInit dispatch"); getMainDispatcher().dispatch([] { - LOGGER.info("bootSplashInit dispatch begin"); + LOG_I(TAG, "bootSplashInit dispatch begin"); // Import any provisioning files placed on the system data partition. const std::string provisioning_path = file::getChildPath(getUserDataPath(), "provisioning"); if (file::isDirectory(provisioning_path)) { importWifiApSettingsFromDir(provisioning_path); } else { - LOGGER.info("Skip provisioning: no files at {}", provisioning_path); + LOG_I(TAG, "Skip provisioning: no files at %s", provisioning_path.c_str()); } // Dispatch WiFi on if (settings::shouldEnableOnBoot()) { - LOGGER.info("Auto-enabling WiFi"); + LOG_I(TAG, "Auto-enabling WiFi"); getMainDispatcher().dispatch([] -> void { setEnabled(true); }); } - LOGGER.info("bootSplashInit dispatch end"); + LOG_I(TAG, "bootSplashInit dispatch end"); }); } diff --git a/Tactility/Source/service/wifi/WifiEsp.cpp b/Tactility/Source/service/wifi/WifiEsp.cpp index 2215fe76c..a985c865b 100644 --- a/Tactility/Source/service/wifi/WifiEsp.cpp +++ b/Tactility/Source/service/wifi/WifiEsp.cpp @@ -6,10 +6,8 @@ #include -#include -#include -#include #include +#include #include #include #include @@ -19,6 +17,9 @@ #include #include +#include +#include + #include #include #include @@ -28,7 +29,7 @@ namespace tt::service::wifi { -static const auto LOGGER = Logger("WifiService"); +constexpr auto* TAG = "WifiService"; constexpr auto WIFI_CONNECTED_BIT = BIT0; constexpr auto WIFI_FAIL_BIT = BIT1; @@ -155,7 +156,7 @@ std::string getConnectionTarget() { } void scan() { - LOGGER.info("scan()"); + LOG_I(TAG, "scan()"); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -174,7 +175,7 @@ bool isScanning() { } void connect(const settings::WifiApSettings& ap, bool remember) { - LOGGER.info("connect({}, {})", ap.ssid, remember); + LOG_I(TAG, "connect(%s, %d)", ap.ssid.c_str(), (int)remember); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -198,7 +199,7 @@ void connect(const settings::WifiApSettings& ap, bool remember) { } void disconnect() { - LOGGER.info("disconnect()"); + LOG_I(TAG, "disconnect()"); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -229,7 +230,7 @@ void clearIp() { memset(&wifi->ip_info, 0, sizeof(esp_netif_ip_info_t)); } void setScanRecords(uint16_t records) { - LOGGER.info("setScanRecords({})", records); + LOG_I(TAG, "setScanRecords(%u)", records); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -247,7 +248,7 @@ void setScanRecords(uint16_t records) { } std::vector getScanResults() { - LOGGER.info("getScanResults()"); + LOG_I(TAG, "getScanResults()"); auto wifi = wifi_singleton; std::vector records; @@ -278,7 +279,7 @@ std::vector getScanResults() { } void setEnabled(bool enabled) { - LOGGER.info("setEnabled({})", enabled); + LOG_I(TAG, "setEnabled(%d)", (int)enabled); auto wifi = wifi_singleton; if (wifi == nullptr) { return; @@ -370,7 +371,7 @@ static bool copy_scan_list(std::shared_ptr wifi) { wifi->isScanActive(); if (!can_fetch_results) { - LOGGER.info("Skip scan result fetching"); + LOG_I(TAG, "Skip scan result fetching"); return false; } @@ -387,11 +388,11 @@ static bool copy_scan_list(std::shared_ptr wifi) { if (scan_result == ESP_OK) { uint16_t safe_record_count = std::min(wifi->scan_list_limit, record_count); wifi->scan_list_count = safe_record_count; - LOGGER.info("Scanned {} APs. Showing {}:", record_count, safe_record_count); + LOG_I(TAG, "Scanned %u APs. Showing %u:", record_count, safe_record_count); for (uint16_t i = 0; i < safe_record_count; i++) { wifi_ap_record_t* record = &wifi->scan_list[i]; if (record->ssid[0] != 0 && record->primary != 0) { - LOGGER.info(" - SSID {}, RSSI {}, channel {}, BSSID {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", + LOG_I(TAG, " - SSID %s, RSSI %d, channel %u, BSSID %02x:%02x:%02x:%02x:%02x:%02x", reinterpret_cast(record->ssid), record->rssi, record->primary, @@ -403,18 +404,18 @@ static bool copy_scan_list(std::shared_ptr wifi) { record->bssid[5] ); } else { - LOGGER.info(" - (missing channel info)"); // Behaviour on on P4 with C6 + LOG_I(TAG, " - (missing channel info)"); // Behaviour on on P4 with C6 } } return true; } else { - LOGGER.info("Failed to get scanned records: {}", esp_err_to_name(scan_result)); + LOG_I(TAG, "Failed to get scanned records: %s", esp_err_to_name(scan_result)); return false; } } static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSettings& settings) { - LOGGER.info("find_auto_connect_ap()"); + LOG_I(TAG, "find_auto_connect_ap()"); auto lock = wifi->dataMutex.asScopedLock(); if (lock.lock(10 / portTICK_PERIOD_MS)) { for (int i = 0; i < wifi->scan_list_count; ++i) { @@ -426,7 +427,7 @@ static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSet return true; } } else { - LOGGER.error("Failed to load credentials for ssid {}", ssid); + LOG_E(TAG, "Failed to load credentials for ssid %s", ssid); } break; } @@ -437,11 +438,11 @@ static bool find_auto_connect_ap(std::shared_ptr wifi, settings::WifiApSet } static void dispatchAutoConnect(std::shared_ptr wifi) { - LOGGER.info("dispatchAutoConnect()"); + LOG_I(TAG, "dispatchAutoConnect()"); settings::WifiApSettings settings; if (find_auto_connect_ap(wifi, settings)) { - LOGGER.info("Auto-connecting to {}", settings.ssid); + LOG_I(TAG, "Auto-connecting to %s", settings.ssid.c_str()); connect(settings, false); // TODO: We currently have to manually reset it because connect() sets it. // connect() assumes it's only being called by the user and not internally, so it disables auto-connect @@ -452,23 +453,23 @@ static void dispatchAutoConnect(std::shared_ptr wifi) { static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { auto wifi = wifi_singleton; if (wifi == nullptr) { - LOGGER.error("eventHandler: no wifi instance"); + LOG_E(TAG, "eventHandler: no wifi instance"); return; } if (event_base == WIFI_EVENT) { - LOGGER.info("eventHandler: WIFI_EVENT {}", event_id); + LOG_I(TAG, "eventHandler: WIFI_EVENT %d", (int)event_id); } else if (event_base == IP_EVENT) { - LOGGER.info("eventHandler: IP_EVENT {}", event_id); + LOG_I(TAG, "eventHandler: IP_EVENT %d", (int)event_id); } if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { - LOGGER.info("eventHandler: STA_START"); + LOG_I(TAG, "eventHandler: STA_START"); if (wifi->getRadioState() == RadioState::ConnectionPending) { esp_wifi_connect(); } } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { - LOGGER.info("eventHandler: STA_DISCONNECTED"); + LOG_I(TAG, "eventHandler: STA_DISCONNECTED"); clearIp(); switch (wifi->getRadioState()) { case RadioState::ConnectionPending: @@ -487,7 +488,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { auto* event = static_cast(event_data); memcpy(&wifi->ip_info, &event->ip_info, sizeof(esp_netif_ip_info_t)); - LOGGER.info("eventHandler: got ip: {}.{}.{}.{}", IP2STR(&event->ip_info.ip)); + LOG_I(TAG, "eventHandler: got ip: %d.%d.%d.%d", IP2STR(&event->ip_info.ip)); if (wifi->getRadioState() == RadioState::ConnectionPending) { wifi->connection_wait_flags.set(WIFI_CONNECTED_BIT); // We resume auto-connecting only when there was an explicit request by the user for the connection @@ -497,7 +498,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i kernel::publishSystemEvent(kernel::SystemEvent::NetworkConnected); } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) { auto* event = static_cast(event_data); - LOGGER.info("eventHandler: wifi scanning done (scan id {})", event->scan_id); + LOG_I(TAG, "eventHandler: wifi scanning done (scan id %u)", event->scan_id); bool copied_list = copy_scan_list(wifi); auto state = wifi->getRadioState(); @@ -510,7 +511,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i } publish_event(wifi_singleton, WifiEvent::ScanFinished); - LOGGER.info("eventHandler: Finished scan"); + LOG_I(TAG, "eventHandler: Finished scan"); if (copied_list && wifi_singleton->getRadioState() == RadioState::On && !wifi->pause_auto_connect) { getMainDispatcher().dispatch([wifi]() { dispatchAutoConnect(wifi); }); @@ -519,7 +520,7 @@ static void eventHandler(void* arg, esp_event_base_t event_base, int32_t event_i } static void dispatchEnable(std::shared_ptr wifi) { - LOGGER.info("dispatchEnable()"); + LOG_I(TAG, "dispatchEnable()"); RadioState state = wifi->getRadioState(); if ( @@ -527,13 +528,13 @@ static void dispatchEnable(std::shared_ptr wifi) { state == RadioState::OnPending || state == RadioState::OffPending ) { - LOGGER.warn("Can't enable from current state"); + LOG_W(TAG, "Can't enable from current state"); return; } auto lock = wifi->radioMutex.asScopedLock(); if (lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.info("Enabling"); + LOG_I(TAG, "Enabling"); wifi->setRadioState(RadioState::OnPending); publish_event(wifi, WifiEvent::RadioStateOnPending); @@ -548,9 +549,9 @@ static void dispatchEnable(std::shared_ptr wifi) { wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); esp_err_t init_result = esp_wifi_init(&config); if (init_result != ESP_OK) { - LOGGER.error("Wifi init failed"); + LOG_E(TAG, "Wifi init failed"); if (init_result == ESP_ERR_NO_MEM) { - LOGGER.error("Insufficient memory"); + LOG_E(TAG, "Insufficient memory"); } wifi->setRadioState(RadioState::Off); publish_event(wifi, WifiEvent::RadioStateOff); @@ -578,7 +579,7 @@ static void dispatchEnable(std::shared_ptr wifi) { )); if (esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK) { - LOGGER.error("Wifi mode setting failed"); + LOG_E(TAG, "Wifi mode setting failed"); wifi->setRadioState(RadioState::Off); esp_wifi_deinit(); publish_event(wifi, WifiEvent::RadioStateOff); @@ -587,9 +588,9 @@ static void dispatchEnable(std::shared_ptr wifi) { esp_err_t start_result = esp_wifi_start(); if (start_result != ESP_OK) { - LOGGER.error("Wifi start failed"); + LOG_E(TAG, "Wifi start failed"); if (start_result == ESP_ERR_NO_MEM) { - LOGGER.error("Insufficient memory"); + LOG_E(TAG, "Insufficient memory"); } wifi->setRadioState(RadioState::Off); esp_wifi_set_mode(WIFI_MODE_NULL); @@ -603,18 +604,18 @@ static void dispatchEnable(std::shared_ptr wifi) { wifi->pause_auto_connect = false; - LOGGER.info("Enabled"); + LOG_I(TAG, "Enabled"); } else { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); } } static void dispatchDisable(std::shared_ptr wifi) { - LOGGER.info("dispatchDisable()"); + LOG_I(TAG, "dispatchDisable()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "disable()"); return; } @@ -624,11 +625,11 @@ static void dispatchDisable(std::shared_ptr wifi) { state == RadioState::OffPending || state == RadioState::OnPending ) { - LOGGER.warn("Can't disable from current state"); + LOG_W(TAG, "Can't disable from current state"); return; } - LOGGER.info("Disabling"); + LOG_I(TAG, "Disabling"); wifi->setRadioState(RadioState::OffPending); publish_event(wifi, WifiEvent::RadioStateOffPending); @@ -649,11 +650,11 @@ static void dispatchDisable(std::shared_ptr wifi) { // event handlers and subsequent disable attempts would behave incorrectly. // If stop fails, continue the teardown anyway so we end in a clean Off state. if (esp_wifi_stop() != ESP_OK) { - LOGGER.error("Failed to stop radio - continuing teardown"); + LOG_E(TAG, "Failed to stop radio - continuing teardown"); } if (esp_wifi_set_mode(WIFI_MODE_NULL) != ESP_OK) { - LOGGER.error("Failed to unset mode"); + LOG_E(TAG, "Failed to unset mode"); } if (esp_event_handler_instance_unregister( @@ -661,7 +662,7 @@ static void dispatchDisable(std::shared_ptr wifi) { ESP_EVENT_ANY_ID, wifi->event_handler_any_id ) != ESP_OK) { - LOGGER.error("Failed to unregister id event handler"); + LOG_E(TAG, "Failed to unregister id event handler"); } if (esp_event_handler_instance_unregister( @@ -669,11 +670,11 @@ static void dispatchDisable(std::shared_ptr wifi) { IP_EVENT_STA_GOT_IP, wifi->event_handler_got_ip ) != ESP_OK) { - LOGGER.error("Failed to unregister ip event handler"); + LOG_E(TAG, "Failed to unregister ip event handler"); } if (esp_wifi_deinit() != ESP_OK) { - LOGGER.error("Failed to deinit"); + LOG_E(TAG, "Failed to deinit"); } assert(wifi->netif != nullptr); @@ -682,26 +683,26 @@ static void dispatchDisable(std::shared_ptr wifi) { wifi->setScanActive(false); wifi->setRadioState(RadioState::Off); publish_event(wifi, WifiEvent::RadioStateOff); - LOGGER.info("Disabled"); + LOG_I(TAG, "Disabled"); } static void dispatchScan(std::shared_ptr wifi) { - LOGGER.info("dispatchScan()"); + LOG_I(TAG, "dispatchScan()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(10 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } RadioState state = wifi->getRadioState(); if (state != RadioState::On && state != RadioState::ConnectionActive && state != RadioState::ConnectionPending) { - LOGGER.warn("Scan unavailable: wifi not enabled"); + LOG_W(TAG, "Scan unavailable: wifi not enabled"); return; } if (wifi->isScanActive()) { - LOGGER.warn("Scan already pending"); + LOG_W(TAG, "Scan already pending"); return; } @@ -709,25 +710,25 @@ static void dispatchScan(std::shared_ptr wifi) { wifi->last_scan_time = tt::kernel::getTicks(); if (esp_wifi_scan_start(nullptr, false) != ESP_OK) { - LOGGER.info("Can't start scan"); + LOG_I(TAG, "Can't start scan"); return; } - LOGGER.info("Starting scan"); + LOG_I(TAG, "Starting scan"); wifi->setScanActive(true); publish_event(wifi, WifiEvent::ScanStarted); } static void dispatchConnect(std::shared_ptr wifi) { - LOGGER.info("dispatchConnect()"); + LOG_I(TAG, "dispatchConnect()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()"); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED_FMT, "dispatchConnect()"); return; } - LOGGER.info("Connecting to {}", wifi->connection_target.ssid); + LOG_I(TAG, "Connecting to %s", wifi->connection_target.ssid.c_str()); // Stop radio first, if needed RadioState radio_state = wifi->getRadioState(); @@ -736,11 +737,11 @@ static void dispatchConnect(std::shared_ptr wifi) { radio_state == RadioState::ConnectionActive || radio_state == RadioState::ConnectionPending ) { - LOGGER.info("Connecting: Stopping radio first"); + LOG_I(TAG, "Connecting: Stopping radio first"); esp_err_t stop_result = esp_wifi_stop(); wifi->setScanActive(false); if (stop_result != ESP_OK) { - LOGGER.error("Connecting: Failed to disconnect ({})", esp_err_to_name(stop_result)); + LOG_E(TAG, "Connecting: Failed to disconnect (%s)", esp_err_to_name(stop_result)); return; } } @@ -766,20 +767,20 @@ static void dispatchConnect(std::shared_ptr wifi) { config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK; } - LOGGER.info("esp_wifi_set_config()"); + LOG_I(TAG, "esp_wifi_set_config()"); esp_err_t set_config_result = esp_wifi_set_config(WIFI_IF_STA, &config); if (set_config_result != ESP_OK) { wifi->setRadioState(RadioState::On); - LOGGER.error("Failed to set wifi config ({})", esp_err_to_name(set_config_result)); + LOG_E(TAG, "Failed to set wifi config (%s)", esp_err_to_name(set_config_result)); publish_event(wifi, WifiEvent::ConnectionFailed); return; } - LOGGER.info("esp_wifi_start()"); + LOG_I(TAG, "esp_wifi_start()"); esp_err_t wifi_start_result = esp_wifi_start(); if (wifi_start_result != ESP_OK) { wifi->setRadioState(RadioState::On); - LOGGER.error("Failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result)); + LOG_E(TAG, "Failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result)); publish_event(wifi, WifiEvent::ConnectionFailed); return; } @@ -789,28 +790,28 @@ static void dispatchConnect(std::shared_ptr wifi) { * The bits are set by wifi_event_handler() */ uint32_t flags; if (wifi_singleton->connection_wait_flags.wait(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT, false, true, &flags, kernel::MAX_TICKS)) { - LOGGER.info("Waiting for EventGroup by event_handler()"); + LOG_I(TAG, "Waiting for EventGroup by event_handler()"); if (flags & WIFI_CONNECTED_BIT) { wifi->setSecureConnection(config.sta.password[0] != 0x00U); wifi->setRadioState(RadioState::ConnectionActive); publish_event(wifi, WifiEvent::ConnectionSuccess); - LOGGER.info("Connected to {}", wifi->connection_target.ssid.c_str()); + LOG_I(TAG, "Connected to %s", wifi->connection_target.ssid.c_str()); if (wifi->connection_target_remember) { if (!settings::save(wifi->connection_target)) { - LOGGER.error("Failed to store credentials"); + LOG_E(TAG, "Failed to store credentials"); } else { - LOGGER.info("Stored credentials"); + LOG_I(TAG, "Stored credentials"); } } } else if (flags & WIFI_FAIL_BIT) { wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::ConnectionFailed); - LOGGER.info("Failed to connect to {}", wifi->connection_target.ssid.c_str()); + LOG_I(TAG, "Failed to connect to %s", wifi->connection_target.ssid.c_str()); } else { wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::ConnectionFailed); - LOGGER.error("UNEXPECTED EVENT"); + LOG_E(TAG, "UNEXPECTED EVENT"); } wifi_singleton->connection_wait_flags.clear(WIFI_FAIL_BIT | WIFI_CONNECTED_BIT); @@ -818,17 +819,17 @@ static void dispatchConnect(std::shared_ptr wifi) { } static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { - LOGGER.info("dispatchDisconnectButKeepActive()"); + LOG_I(TAG, "dispatchDisconnectButKeepActive()"); auto lock = wifi->radioMutex.asScopedLock(); if (!lock.lock(50 / portTICK_PERIOD_MS)) { - LOGGER.error(LOG_MESSAGE_MUTEX_LOCK_FAILED); + LOG_E(TAG, LOG_MESSAGE_MUTEX_LOCK_FAILED); return; } esp_err_t stop_result = esp_wifi_stop(); if (stop_result != ESP_OK) { - LOGGER.error("Failed to disconnect ({})", esp_err_to_name(stop_result)); + LOG_E(TAG, "Failed to disconnect (%s)", esp_err_to_name(stop_result)); return; } @@ -844,7 +845,7 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { if (set_config_result != ESP_OK) { // TODO: disable radio, because radio state is in limbo between off and on wifi->setRadioState(RadioState::Off); - LOGGER.error("failed to set wifi config ({})", esp_err_to_name(set_config_result)); + LOG_E(TAG, "failed to set wifi config (%s)", esp_err_to_name(set_config_result)); publish_event(wifi, WifiEvent::RadioStateOff); return; } @@ -853,14 +854,14 @@ static void dispatchDisconnectButKeepActive(std::shared_ptr wifi) { if (wifi_start_result != ESP_OK) { // TODO: disable radio, because radio state is in limbo between off and on wifi->setRadioState(RadioState::Off); - LOGGER.error("failed to start wifi to begin connecting ({})", esp_err_to_name(wifi_start_result)); + LOG_E(TAG, "failed to start wifi to begin connecting (%s)", esp_err_to_name(wifi_start_result)); publish_event(wifi, WifiEvent::RadioStateOff); return; } wifi->setRadioState(RadioState::On); publish_event(wifi, WifiEvent::Disconnected); - LOGGER.info("Disconnected"); + LOG_I(TAG, "Disconnected"); } static bool shouldScanForAutoConnect(std::shared_ptr wifi) { diff --git a/Tactility/Source/service/wifi/WifiSettings.cpp b/Tactility/Source/service/wifi/WifiSettings.cpp index a39762e29..7d061147a 100644 --- a/Tactility/Source/service/wifi/WifiSettings.cpp +++ b/Tactility/Source/service/wifi/WifiSettings.cpp @@ -2,13 +2,14 @@ #include #include -#include #include #include +#include + namespace tt::service::wifi::settings { -static const auto LOGGER = Logger("WifiSettings"); +constexpr auto* TAG = "WifiSettings"; constexpr auto* SETTINGS_KEY_ENABLE_ON_BOOT = "enableOnBoot"; struct WifiSettings { @@ -47,7 +48,7 @@ static bool save(std::shared_ptr context, const WifiSettings& se map[SETTINGS_KEY_ENABLE_ON_BOOT] = settings.enableOnBoot ? "true" : "false"; std::string settings_path = context->getPaths()->getUserDataPath("settings.properties"); if (!file::findOrCreateParentDirectory(settings_path, 0755)) { - LOGGER.error("Failed to create {}", settings_path); + LOG_E(TAG, "Failed to create %s", settings_path.c_str()); return false; } return file::savePropertiesFile(settings_path, map); @@ -60,7 +61,7 @@ WifiSettings getCachedOrLoad() { if (load(context, cachedSettings)) { cached = true; } else { - LOGGER.info("Failed to load settings, using defaults"); + LOG_I(TAG, "Failed to load settings, using defaults"); } } } @@ -72,7 +73,7 @@ void setEnableOnBoot(bool enable) { cachedSettings.enableOnBoot = enable; auto context = findServiceContext(); if (context && !save(context, cachedSettings)) { - LOGGER.error("Failed to save settings"); + LOG_E(TAG, "Failed to save settings"); } } diff --git a/Tactility/Source/settings/Language.cpp b/Tactility/Source/settings/Language.cpp index 3989a8e6f..52916d986 100644 --- a/Tactility/Source/settings/Language.cpp +++ b/Tactility/Source/settings/Language.cpp @@ -1,12 +1,13 @@ -#include #include #include +#include + #include namespace tt::settings { -static const auto LOGGER = Logger("Language"); +constexpr auto* TAG = "Language"; void setLanguage(Language newLanguage) { SystemSettings properties; @@ -40,7 +41,7 @@ std::string toString(Language language) { case Language::nl_NL: return "nl-NL"; default: - LOGGER.error("Missing serialization for language {}", static_cast(language)); + LOG_E(TAG, "Missing serialization for language %d", static_cast(language)); std::unreachable(); } } diff --git a/Tactility/Source/settings/SystemSettings.cpp b/Tactility/Source/settings/SystemSettings.cpp index 98c04ac5a..e8763af99 100644 --- a/Tactility/Source/settings/SystemSettings.cpp +++ b/Tactility/Source/settings/SystemSettings.cpp @@ -1,4 +1,3 @@ -#include #include #include #include @@ -8,11 +7,13 @@ #include "Tactility/Paths.h" +#include + #include namespace tt::settings { -static const auto LOGGER = Logger("SystemSettings"); +constexpr auto* TAG = "SystemSettings"; constexpr auto* FILE_PATH_FORMAT = "{}/settings/system.properties"; @@ -26,7 +27,7 @@ static bool hasSystemSettingsFile() { static bool loadSystemSettingsFromFile(SystemSettings& properties) { auto file_path = std::format(FILE_PATH_FORMAT, getUserDataPath()); - LOGGER.info("System settings loading from {}", file_path); + LOG_I(TAG, "System settings loading from %s", file_path.c_str()); std::map map; if (!file::loadPropertiesFile(file_path, map)) { return false; @@ -35,7 +36,7 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) { auto language_entry = map.find("language"); if (language_entry != map.end()) { if (!fromString(language_entry->second, properties.language)) { - LOGGER.warn("Unknown language \"{}\" in {}", language_entry->second, file_path); + LOG_W(TAG, "Unknown language \"%s\" in %s", language_entry->second.c_str(), file_path.c_str()); properties.language = Language::en_US; } } else { @@ -52,11 +53,11 @@ static bool loadSystemSettingsFromFile(SystemSettings& properties) { if (date_format_entry != map.end() && !date_format_entry->second.empty()) { properties.dateFormat = date_format_entry->second; } else { - LOGGER.info("dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)"); + LOG_I(TAG, "dateFormat missing or empty, using default MM/DD/YYYY (likely from older system.properties)"); properties.dateFormat = "MM/DD/YYYY"; } - LOGGER.info("System settings loaded"); + LOG_I(TAG, "System settings loaded"); return true; } @@ -65,7 +66,7 @@ bool loadSystemSettings(SystemSettings& properties) { if (loadSystemSettingsFromFile(cachedSettings)) { cached = true; } else { - LOGGER.error("Failed to load"); + LOG_E(TAG, "Failed to load"); } } @@ -81,12 +82,12 @@ bool saveSystemSettings(const SystemSettings& properties) { map["dateFormat"] = properties.dateFormat; if (!file::findOrCreateParentDirectory(file_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", file_path); + LOG_E(TAG, "Failed to create parent dir for %s", file_path.c_str()); return false; } if (!file::savePropertiesFile(file_path, map)) { - LOGGER.error("Failed to save {}", file_path); + LOG_E(TAG, "Failed to save %s", file_path.c_str()); return false; } diff --git a/Tactility/Source/settings/WebServerSettings.cpp b/Tactility/Source/settings/WebServerSettings.cpp index a45f67c5a..1a5860191 100644 --- a/Tactility/Source/settings/WebServerSettings.cpp +++ b/Tactility/Source/settings/WebServerSettings.cpp @@ -1,9 +1,10 @@ #include #include #include -#include #include +#include + #include #include #include @@ -18,7 +19,7 @@ namespace tt::settings::webserver { -static const auto LOGGER = Logger("WebServerSettings"); +constexpr auto* TAG = "WebServerSettings"; static std::string getSettingsFilePath() { return getUserDataPath() + "/settings/webserver.properties"; @@ -147,7 +148,7 @@ bool load(WebServerSettings& settings) { // Skip this if user explicitly wants an open network. // Note: We only auto-generate for EMPTY passwords, not user-set ones. if (!settings.apOpenNetwork && isEmptyCredential(settings.apPassword)) { - LOGGER.info("AP password is empty - generating secure random password"); + LOG_I(TAG, "AP password is empty - generating secure random password"); // Generate 12-character random password (alphanumeric, ~71 bits of entropy) // WPA2 requires 8-63 characters, so 12 is well within range @@ -156,9 +157,9 @@ bool load(WebServerSettings& settings) { // Persist the generated password immediately map[KEY_AP_PASSWORD] = settings.apPassword; if (file::savePropertiesFile(getSettingsFilePath(), map)) { - LOGGER.info("Generated and saved new secure AP password"); + LOG_I(TAG, "Generated and saved new secure AP password"); } else { - LOGGER.error("Failed to save generated AP password"); + LOG_E(TAG, "Failed to save generated AP password"); } } @@ -186,7 +187,7 @@ bool load(WebServerSettings& settings) { if (settings.webServerAuthEnabled && (isEmptyCredential(settings.webServerUsername) || isEmptyCredential(settings.webServerPassword))) { - LOGGER.info("Auth enabled with empty credentials - generating secure random credentials"); + LOG_I(TAG, "Auth enabled with empty credentials - generating secure random credentials"); // Generate 12-character random credentials (alphanumeric, ~71 bits of entropy each) settings.webServerUsername = generateRandomCredential(12); @@ -197,9 +198,9 @@ bool load(WebServerSettings& settings) { map[KEY_WEBSERVER_USERNAME] = settings.webServerUsername; map[KEY_WEBSERVER_PASSWORD] = settings.webServerPassword; if (file::savePropertiesFile(getSettingsFilePath(), map)) { - LOGGER.info("Generated and saved new secure credentials"); + LOG_I(TAG, "Generated and saved new secure credentials"); } else { - LOGGER.error("Failed to save generated credentials - auth may be inconsistent across reboots"); + LOG_E(TAG, "Failed to save generated credentials - auth may be inconsistent across reboots"); } } @@ -231,9 +232,9 @@ WebServerSettings loadOrGetDefault() { settings = getDefault(); // Save defaults to flash so toggle states persist if (save(settings)) { - LOGGER.info("First boot - saved default settings (WiFi OFF WebServer OFF)"); + LOG_I(TAG, "First boot - saved default settings (WiFi OFF WebServer OFF)"); } else { - LOGGER.warn("First boot - failed to save default settings to flash"); + LOG_W(TAG, "First boot - failed to save default settings to flash"); } } @@ -264,7 +265,7 @@ bool save(const WebServerSettings& settings) { auto settings_path = getSettingsFilePath(); if (!file::findOrCreateParentDirectory(settings_path, 0755)) { - LOGGER.error("Failed to create parent dir for {}", settings_path); + LOG_E(TAG, "Failed to create parent dir for %s", settings_path.c_str()); return false; } return file::savePropertiesFile(settings_path, map); diff --git a/TactilityC/Source/tt_app.cpp b/TactilityC/Source/tt_app.cpp index 24f6f0011..ad703b497 100644 --- a/TactilityC/Source/tt_app.cpp +++ b/TactilityC/Source/tt_app.cpp @@ -3,11 +3,11 @@ #include #include #include -#include +#include #include -static const auto LOGGER = tt::Logger("tt_app"); +constexpr auto* TAG = "tt_app"; extern "C" { @@ -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) { - LOGGER.error("Path buffer not large enough ({} < {})", *size, expected_length); + LOG_E(TAG, "Path buffer not large enough (%u < %u)", (unsigned)*size, (unsigned)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)) { - LOGGER.error("Path buffer not large enough ({} < {})", *size, (resolved_path_length + 1)); + LOG_E(TAG, "Path buffer not large enough (%u < %u)", (unsigned)*size, (unsigned)(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) { - LOGGER.error("Path buffer not large enough ({} < {})", *size, expected_length); + LOG_E(TAG, "Path buffer not large enough (%u < %u)", (unsigned)*size, (unsigned)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)) { - LOGGER.error("Path buffer not large enough ({} < {})", *size, (resolved_path_length + 1)); + LOG_E(TAG, "Path buffer not large enough (%u < %u)", (unsigned)*size, (unsigned)(resolved_path_length + 1)); *size = 0; buffer[0] = 0; return; diff --git a/TactilityCore/Include/Tactility/Logger.h b/TactilityCore/Include/Tactility/Logger.h deleted file mode 100644 index ac5f882eb..000000000 --- a/TactilityCore/Include/Tactility/Logger.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include - -#include - -namespace tt { - -class Logger { - - const char* tag; - - LogLevel level = LOG_LEVEL_INFO; - -public: - - explicit Logger(const char* tag) : tag(tag) {} - - template - void verbose(std::format_string format, Args&&... args) const { - std::string message = std::format(format, std::forward(args)...); - LOG_V(tag, "%s", message.c_str()); - } - - template - void debug(std::format_string format, Args&&... args) const { - std::string message = std::format(format, std::forward(args)...); - LOG_D(tag, "%s", message.c_str()); - } - - template - void info(std::format_string format, Args&&... args) const { - std::string message = std::format(format, std::forward(args)...); - LOG_I(tag, "%s", message.c_str()); - } - - template - void warn(std::format_string format, Args&&... args) const { - std::string message = std::format(format, std::forward(args)...); - LOG_W(tag, "%s", message.c_str()); - } - - template - void error(std::format_string format, Args&&... args) const { - std::string message = std::format(format, std::forward(args)...); - LOG_E(tag, "%s", message.c_str()); - } - - bool isLoggingVerbose() const { - return LOG_LEVEL_VERBOSE <= level; - } - - bool isLoggingDebug() const { - return LOG_LEVEL_DEBUG <= level; - } - - bool isLoggingInfo() const { - return LOG_LEVEL_INFO <= level; - } - - bool isLoggingWarning() const { - return LOG_LEVEL_WARNING <= level; - } - - bool isLoggingError() const { - return LOG_LEVEL_ERROR <= level; - } -}; - -} diff --git a/TactilityCore/Include/Tactility/TactilityCore.h b/TactilityCore/Include/Tactility/TactilityCore.h index 25c464678..0d775bc9a 100644 --- a/TactilityCore/Include/Tactility/TactilityCore.h +++ b/TactilityCore/Include/Tactility/TactilityCore.h @@ -3,4 +3,3 @@ #include #include "CoreDefines.h" -#include "Logger.h" diff --git a/TactilityCore/Source/crypt/Crypt.cpp b/TactilityCore/Source/crypt/Crypt.cpp index d8ed13cb7..b2b17e7bd 100644 --- a/TactilityCore/Source/crypt/Crypt.cpp +++ b/TactilityCore/Source/crypt/Crypt.cpp @@ -1,6 +1,6 @@ #include -#include +#include #include #include @@ -15,7 +15,7 @@ namespace tt::crypt { -static const auto LOGGER = Logger("Crypt"); +constexpr auto* TAG = "Crypt"; #define TT_NVS_NAMESPACE "tt_secure" @@ -28,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); - LOGGER.info("Using MAC with length {}", mac_length); + LOG_I(TAG, "Using MAC with length %u", (unsigned)mac_length); check(mac_length <= 8); ESP_ERROR_CHECK(esp_read_mac(mac, ESP_MAC_EFUSE_FACTORY)); @@ -67,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) { - LOGGER.error("Failed to get key from NVS ({})", esp_err_to_name(result)); + LOG_E(TAG, "Failed to get key from NVS (%s)", esp_err_to_name(result)); check(false, "NVS error"); } size_t length = 32; if (nvs_get_blob(handle, "key", key, &length) == ESP_OK) { - LOGGER.info("Fetched key from NVS ({} bytes)", length); + LOG_I(TAG, "Fetched key from NVS (%u bytes)", (unsigned)length); check(length == 32); } else { // TODO: Improved randomness @@ -84,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)); - LOGGER.info("Stored new key in NVS"); + LOG_I(TAG, "Stored new key in NVS"); } nvs_close(handle); @@ -110,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) - 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."); + LOG_W(TAG, "Using tt_secure_* code with secure boot and/or flash encryption disabled."); + LOG_W(TAG, "An attacker with physical access to your ESP32 can decrypt your secure data."); #endif #ifdef ESP_PLATFORM @@ -122,7 +122,7 @@ static void getKey(uint8_t key[32]) { get_nvs_key(nvs_key); xorKey(hardware_key, nvs_key, key, 32); #else - LOGGER.warn("Using unsafe key for debugging purposes."); + LOG_W(TAG, "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 e45c6c4be..99f998873 100644 --- a/TactilityCore/Source/file/File.cpp +++ b/TactilityCore/Source/file/File.cpp @@ -4,7 +4,7 @@ #include #include -#include +#include #include namespace tt::hal::sdcard { @@ -13,7 +13,7 @@ class SdCardDevice; namespace tt::file { -static const auto LOGGER = Logger("file"); +constexpr auto* TAG = "file"; class NoLock final : public Lock { bool lock(TickType_t timeout) const override { return true; } @@ -25,7 +25,7 @@ static std::function(const std::string&)> findLockFunction std::shared_ptr getLock(const std::string& path) { if (findLockFunction == nullptr) { - LOGGER.warn("File lock function not set!"); + LOG_W(TAG, "File lock function not set!"); return noLock; } @@ -71,10 +71,10 @@ bool listDirectory( auto lock = getLock(path)->asScopedLock(); lock.lock(); - LOGGER.info("listDir start {}", path); + LOG_I(TAG, "listDir start %s", path.c_str()); DIR* dir = opendir(path.c_str()); if (dir == nullptr) { - LOGGER.error("Failed to open dir {}", path); + LOG_E(TAG, "Failed to open dir %s", path.c_str()); return false; } @@ -85,7 +85,7 @@ bool listDirectory( closedir(dir); - LOGGER.info("listDir stop {}", path); + LOG_I(TAG, "listDir stop %s", path.c_str()); return true; } @@ -98,10 +98,10 @@ int scandir( auto lock = getLock(path)->asScopedLock(); lock.lock(); - LOGGER.info("scandir start"); + LOG_I(TAG, "scandir start"); DIR* dir = opendir(path.c_str()); if (dir == nullptr) { - LOGGER.error("Failed to open dir {}", path); + LOG_E(TAG, "Failed to open dir %s", path.c_str()); return -1; } @@ -118,7 +118,7 @@ int scandir( std::ranges::sort(outList, sortMethod); } - LOGGER.info("scandir finish"); + LOG_I(TAG, "scandir finish"); return outList.size(); } @@ -127,18 +127,18 @@ long getSize(FILE* file) { long original_offset = ftell(file); if (fseek(file, 0, SEEK_END) != 0) { - LOGGER.error("fseek failed"); + LOG_E(TAG, "fseek failed"); return -1; } long file_size = ftell(file); if (file_size == -1) { - LOGGER.error("Could not get file length"); + LOG_E(TAG, "Could not get file length"); return -1; } if (fseek(file, original_offset, SEEK_SET) != 0) { - LOGGER.error("fseek Failed"); + LOG_E(TAG, "fseek Failed"); return -1; } @@ -154,26 +154,26 @@ static std::unique_ptr readBinaryInternal(const std::string& filepath FILE* file = fopen(filepath.c_str(), "rb"); if (file == nullptr) { - LOGGER.error("Failed to open {}", filepath); + LOG_E(TAG, "Failed to open %s", filepath.c_str()); return nullptr; } long content_length = getSize(file); if (content_length == -1) { - LOGGER.error("Failed to determine content length for {}", filepath); + LOG_E(TAG, "Failed to determine content length for %s", filepath.c_str()); return nullptr; } auto data = std::make_unique(content_length + sizePadding); if (data == nullptr) { - LOGGER.error("Insufficient memory. Failed to allocate {} bytes.", content_length); + LOG_E(TAG, "Insufficient memory. Failed to allocate %ld 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); - LOGGER.debug("Read {} bytes", bytes_read); + LOG_D(TAG, "Read %u bytes", (unsigned)bytes_read); if (bytes_read > 0) { buffer_offset += bytes_read; } else { // Something went wrong? @@ -270,7 +270,7 @@ bool findOrCreateDirectory(const std::string& path, mode_t mode) { if (path.empty()) { return true; } - LOGGER.debug("findOrCreate: {} {}", path, mode); + LOG_D(TAG, "findOrCreate: %s %u", path.c_str(), (unsigned)mode); const char separator_to_find[] = {SEPARATOR, 0x00}; auto first_index = path[0] == SEPARATOR ? 1 : 0; @@ -282,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)) { - LOGGER.error("Failed to create {}", to_create); + LOG_E(TAG, "Failed to create %s", to_create.c_str()); return false; } else { - LOGGER.debug(" - got: {}", to_create); + LOG_D(TAG, " - got: %s", to_create.c_str()); } // Find next file separator index @@ -311,7 +311,7 @@ bool deleteRecursively(const std::string& path) { if (isDirectory(path)) { std::vector entries; if (scandir(path, entries) < 0) { - LOGGER.error("Failed to scan directory {}", path); + LOG_E(TAG, "Failed to scan directory %s", path.c_str()); return false; } @@ -321,16 +321,16 @@ bool deleteRecursively(const std::string& path) { return false; } } - LOGGER.info("Deleting {}", path); + LOG_I(TAG, "Deleting %s", path.c_str()); return deleteDirectory(path); } else if (isFile(path)) { - LOGGER.info("Deleting {}", path); + LOG_I(TAG, "Deleting %s", path.c_str()); return deleteFile(path); } else if (path == "/" || path == "." || path == "..") { // No-op return true; } else { - LOGGER.error("Failed to delete \"{}\": unknown type", path); + LOG_E(TAG, "Failed to delete \"%s\": unknown type", path.c_str()); return false; } }