Compare commits

..
Author SHA1 Message Date
J. Nick Koston 5f8ee431fd Let ESP8266's boot replay take write_body inline; it is the only caller there 2026-11-17 00:35:00 -06:00
J. Nick Koston 373198978e Inline the no-argument writer into the per-line path again; one shared copy for replay and task lines 2026-11-17 00:32:31 -06:00
J. Nick Koston 9851b53fe2 Keep ESP8266's 32-byte tag cap so its short buffers keep the message text 2026-11-17 00:14:33 -06:00
J. Nick Koston 0a39d4b42d Keep a tag that fits; bound it by the room the header leaves instead of 32 bytes 2026-11-17 00:03:58 -06:00
J. Nick Koston 2a0f332691 Cap the tag and thread name on every platform so the header never passes the buffer 2026-11-16 23:53:35 -06:00
J. Nick Koston fe78f79469 Force the per-line reset and terminator inline 2026-11-16 23:44:21 -06:00
J. Nick Koston 480d2380ab Forward write_body() to write_unformatted_body(), the two were the same 2026-11-16 23:26:27 -06:00
J. Nick Koston 51aae78e5d State what keeps pos inside the buffer in finalize_() 2026-11-16 22:35:05 -06:00
J. Nick Koston 78a83b9bc5 Merge branch 'dev' into logger-keep-color-reset
The unformatted body writers from #22644 now follow this branch's contract: they check body_room_() and write the
color reset themselves, since finalize_() only terminates. Their test no longer starts a body at the end of the
buffer, which the header never does.
2026-11-16 22:28:03 -06:00
J. Nick Koston eaa176767e Merge remote-tracking branch 'upstream/dev' into logger-keep-color-reset 2026-11-16 22:25:51 -06:00
J. Nick Koston b27b061438 Write the reset inside the body writers, drop the dead full check, strip a newline at the cut in write_body 2026-11-16 16:44:54 -06:00
J. Nick Koston 7ddfbb6398 [logger] Keep the color reset on cut lines and the terminator out of the length 2026-11-16 16:33:03 -06:00
16 changed files with 413 additions and 319 deletions

No files matched your search

+15 -26
View File
@@ -94,7 +94,6 @@ UART_SELECTION_RP2040 = [USB_CDC, UART0, UART1]
UART_SELECTION_NRF52 = [USB_CDC, UART0]
# Read by device-builder
HARDWARE_UART_TO_UART_SELECTION = {
UART0: logger_ns.UART_SELECTION_UART0,
UART0_SWAP: logger_ns.UART_SELECTION_UART0_SWAP,
@@ -539,17 +538,17 @@ async def to_code(config: ConfigType) -> None:
cg.add(log.set_boot_log_level(tag, LOG_LEVELS[log_level]))
if CORE.is_esp32 or CORE.is_host:
cg.add(log.create_pthread_key())
if (hardware_uart := config.get(CONF_HARDWARE_UART)) is not None:
cg.add_define(f"USE_LOGGER_UART_SELECTION_{hardware_uart}")
cg.add_define(
"ESPHOME_LOGGER_UART_SELECTION",
cg.RawExpression(f"logger::UART_SELECTION_{hardware_uart}"),
)
# ESP8266 without serial logging never opens a port
cg.add_define(
"ESPHOME_LOGGER_UART_NAME",
"NONE" if CORE.is_esp8266 and baud_rate == 0 else hardware_uart,
)
# set_uart_selection() must be called before pre_setup() because
# pre_setup() switches on uart_ to decide which hardware to initialize
# (e.g. UART0 vs USB_SERIAL_JTAG). Without this, uart_ is still the
# default UART_SELECTION_UART0 and the wrong hardware gets initialized.
# uart_ is UART0 in C++ except on LibreTiny where it is DEFAULT; skip the
# setter when the config matches it.
cpp_default_uart = DEFAULT if CORE.is_libretiny else UART0
if (
hardware_uart := config.get(CONF_HARDWARE_UART)
) is not None and hardware_uart != cpp_default_uart:
cg.add(log.set_uart_selection(HARDWARE_UART_TO_UART_SELECTION[hardware_uart]))
# pre_setup() sets global_logger and must run before any other code
# that may call ESP_LOG* (e.g. setup_preferences contains ESP_LOGVV).
cg.add(log.pre_setup())
@@ -646,6 +645,7 @@ async def _late_logger_init(config: ConfigType) -> None:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_CDC", True)
elif config[CONF_HARDWARE_UART] == USB_SERIAL_JTAG:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG", True)
cg.add_define("USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG")
# Log V2 formats centrally in esp_log() (~4KB flash, ~180B RAM). 6.1
# adds CONSTRAINED_ENV_SAFE=n, keeping early/DRAM logs on
# esp_rom_printf instead of pulling ~1.2KB esp_rom_vprintf into IRAM.
@@ -663,12 +663,10 @@ async def _late_logger_init(config: ConfigType) -> None:
# --wrap: a strong definition collides; see logger_esp32.cpp
cg.add_build_flag("-Wl,--wrap=esp_log_format")
# Zephyr polls the USB port only when it logs there
if (
CORE.using_zephyr
and has_serial_logging
and config[CONF_HARDWARE_UART] == USB_CDC
if config.get(CONF_HARDWARE_UART) == USB_CDC and (
has_serial_logging or not CORE.is_nrf52
):
cg.add_define("USE_LOGGER_ZEPHYR_CDC_LOOP")
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
# Define platform support flags for components that need auto-detection
try:
uart_selection(USB_SERIAL_JTAG)
@@ -886,15 +884,6 @@ def request_logger_level_listeners() -> None:
_request_log_listener_slot = cg.slot_counter("ESPHOME_LOG_MAX_LISTENERS")
def request_console() -> None:
"""Compile in Logger::console_read() and console_write(); call from to_code.
On ESP32 a USB_CDC logger only has a console where ESP-IDF sets CONFIG_ESP_CONSOLE_USB_CDC (targets with
USB OTG); elsewhere, such as the C3, C6 or H2, both do nothing. Host and Zephyr have no console API.
"""
cg.add_define("USE_LOGGER_CONSOLE")
def request_log_listener() -> None:
"""Reserve a log listener slot; call once per listener from to_code."""
cg.add_define("USE_LOG_LISTENERS")
+64 -56
View File
@@ -7,9 +7,11 @@
namespace esphome::logger {
// Maximum header size: 35 bytes fixed + 32 bytes tag + 16 bytes thread name = 83 bytes (45 byte safety margin)
// Space write_header() needs free. Without the tag the header takes at most 68 bytes (20 fixed, 48 for a thread name
// of up to MAX_TAG_LENGTH); the tag gets the rest of the line's room minus that budget, so at least MAX_TAG_LENGTH
// (on ESP8266 exactly MAX_TAG_LENGTH)
static constexpr uint16_t MAX_HEADER_SIZE = 128;
// Longest tag the header budget allows
// Longest thread name in the header, and the shortest tag it always keeps
static constexpr size_t MAX_TAG_LENGTH = 32;
// ANSI color code last digit (30-38 range, store only last digit to save RAM on ESP8266)
@@ -42,15 +44,8 @@ struct LogBuffer {
// Replaces the null terminator with a newline for console output.
// Must be called after notify_listeners_() since listeners need null-terminated strings.
// Console output uses length-based writes (buf.pos), so null terminator is not needed.
void terminate_with_newline() {
if (this->pos < this->size) {
this->data[this->pos++] = '\n';
} else if (this->size > 0) {
// Buffer was full - replace last char with newline to ensure it's visible
this->data[this->size - 1] = '\n';
this->pos = this->size;
}
}
// The body writers keep the terminator's byte inside the buffer, so the newline always fits
void terminate_with_newline() { this->data[this->pos++] = '\n'; }
void HOT write_header(uint8_t level, const char *tag, int line, const char *thread_name) {
// Early return if insufficient space - intentionally don't update pos to prevent partial writes
if (this->pos + MAX_HEADER_SIZE > this->size)
@@ -75,7 +70,13 @@ struct LogBuffer {
*p++ = '[';
// Copy tag
p = copy_string(p, tag);
#ifdef USE_ESP8266
// ESP8266 has always cut tags at MAX_TAG_LENGTH, which leaves the message more of a short buffer
p = copy_string(p, tag, MAX_TAG_LENGTH);
#else
// The early return above leaves at least MAX_HEADER_SIZE, so the tag keeps MAX_TAG_LENGTH or more
p = copy_string(p, tag, this->remaining_() - (MAX_HEADER_SIZE - MAX_TAG_LENGTH));
#endif
*p++ = ':';
@@ -93,7 +94,7 @@ struct LogBuffer {
if (thread_name != nullptr) {
p = write_ansi_color(p, 1); // Bold red for thread name
*p++ = '[';
p = copy_string(p, thread_name);
p = copy_string(p, thread_name, MAX_TAG_LENGTH);
*p++ = ']';
p = write_ansi_color(p, level); // Restore original color
}
@@ -115,22 +116,27 @@ struct LogBuffer {
}
#endif
// Writes a message that needs no formatting, truncated and stripped of trailing newlines as format_body() does
void HOT write_unformatted_body(const char *text, size_t len) {
if (!this->full_()) {
const uint16_t limit = this->remaining_() - 1; // vsnprintf() keeps the last byte for the null terminator
// Forced inline: as on dev, the per-line path keeps it in its caller instead of calling out on every line
inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body(const char *text, size_t len) {
const int room = this->body_room_();
if (room > 0) {
const uint16_t limit = room - 1; // vsnprintf() keeps the last byte for the null terminator
const uint16_t copy_len = (len < limit) ? static_cast<uint16_t>(len) : limit;
memcpy(this->current_(), text, copy_len);
this->pos += copy_len;
this->strip_trailing_newlines_();
this->write_ansi_reset_();
}
this->finalize_();
}
// write_unformatted_body() for a message in flash
inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text) {
if (!this->full_()) {
const int room = this->body_room_();
if (room > 0) {
char *const start = this->current_();
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + this->remaining_() - 1, text) - this->data);
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + room - 1, text) - this->data);
this->strip_trailing_newlines_();
this->write_ansi_reset_();
}
this->finalize_();
}
@@ -151,58 +157,59 @@ struct LogBuffer {
*p++ = ' ';
this->pos = static_cast<uint16_t>(p - this->data);
}
void write_body(const char *text, uint16_t text_length) {
const uint16_t available = this->remaining_();
const uint16_t copy_len = (text_length < available) ? text_length : available;
if (copy_len > 0) {
memcpy(this->current_(), text, copy_len);
this->pos += copy_len;
}
this->finalize_();
// Same as write_unformatted_body(), for the boot replay and the task log buffer
#ifdef USE_ESP8266
// No task log buffer here, so the boot replay is the only caller and takes it inline
void write_body(const char *text, uint16_t text_length) { this->write_unformatted_body(text, text_length); }
#else
// One out-of-line copy shared by both callers
void __attribute__((noinline)) write_body(const char *text, uint16_t text_length) {
this->write_unformatted_body(text, text_length);
}
#endif
private:
bool full_() const { return this->pos >= this->size; }
uint16_t remaining_() const { return this->size - this->pos; }
// Room for the body and its null terminator with the color reset behind it; 0 or less when there is none
int body_room_() const { return this->remaining_() - ANSI_RESET_LEN; }
char *current_() { return this->data + this->pos; }
void finalize_() {
this->write_ansi_reset_();
// Null terminate
this->data[this->full_() ? this->size - 1 : this->pos] = '\0';
}
// Write ANSI reset sequence inline ("\033[0m") - avoids write_() call overhead
void write_ansi_reset_() {
if (this->remaining_() >= ANSI_RESET_LEN) {
char *p = this->current_();
*p++ = '\033';
*p++ = '[';
*p++ = '0';
*p++ = 'm';
this->pos += ANSI_RESET_LEN;
}
// The body starts inside the buffer (write_header() needs MAX_HEADER_SIZE free) and the body writers keep a byte
// for the terminator, so pos is inside the buffer here
inline void ESPHOME_ALWAYS_INLINE finalize_() { this->data[this->pos] = '\0'; }
// Write ANSI reset sequence inline ("\033[0m"); forced inline, since it runs on every log line
// Callers have checked body_room_(), which keeps space for the reset and the terminator after it
inline void ESPHOME_ALWAYS_INLINE write_ansi_reset_() {
char *p = this->current_();
*p++ = '\033';
*p++ = '[';
*p++ = '0';
*p++ = 'm';
this->pos += ANSI_RESET_LEN;
}
// Forced inline: an outlined copy slows every formatted line
inline void ESPHOME_ALWAYS_INLINE strip_trailing_newlines_() {
while (this->pos > 0 && this->data[this->pos - 1] == '\n')
this->pos--;
}
void process_vsnprintf_result_(int ret) {
if (ret < 0)
return;
const uint16_t rem = this->remaining_();
this->pos += (ret >= rem) ? (rem - 1) : static_cast<uint16_t>(ret);
this->strip_trailing_newlines_();
void process_vsnprintf_result_(int ret, int room) {
if (ret >= 0) {
this->pos += (ret >= room) ? (room - 1) : ret;
this->strip_trailing_newlines_();
}
this->write_ansi_reset_();
}
void format_vsnprintf_(const char *format, va_list args) {
if (this->full_())
const int room = this->body_room_();
if (room <= 0)
return;
this->process_vsnprintf_result_(vsnprintf(this->current_(), this->remaining_(), format, args));
this->process_vsnprintf_result_(vsnprintf(this->current_(), room, format, args), room);
}
#ifdef USE_ESP8266
void format_vsnprintf_p_(PGM_P format, va_list args) {
if (this->full_())
const int room = this->body_room_();
if (room <= 0)
return;
this->process_vsnprintf_result_(vsnprintf_P(this->current_(), this->remaining_(), format, args));
this->process_vsnprintf_result_(vsnprintf_P(this->current_(), room, format, args), room);
}
#endif
// Extract one decimal digit via subtraction (no division - important for ESP8266)
@@ -230,17 +237,18 @@ struct LogBuffer {
return p;
}
// Copies str unchecked and without its null terminator, so the caller reserves space; returns the new end
static char *copy_string(char *p, const char *str) {
// Copies at most max_len bytes, so the header stays within MAX_HEADER_SIZE and the body starts inside the buffer
static char *copy_string(char *p, const char *str, size_t max_len) {
#ifdef USE_ESP8266
// Only ESP8266 caps the length; tags may be in PROGMEM, so read each byte once
for (size_t i = 0; i < MAX_TAG_LENGTH; i++) {
// Tags may be in PROGMEM, so read each byte once
for (size_t i = 0; i < max_len; i++) {
const char c = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(str + i)));
if (c == '\0')
break;
*p++ = c;
}
#else
const size_t len = strlen(str);
const size_t len = strnlen(str, max_len);
memcpy(p, str, len); // NOLINT(bugprone-not-null-terminated-result) - the header is built piece by piece
p += len;
#endif
+3 -22
View File
@@ -248,10 +248,10 @@ Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
#endif
}
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
void Logger::loop() {
this->process_messages_();
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
this->cdc_loop_();
#endif
}
@@ -278,7 +278,7 @@ void Logger::process_messages_() {
}
}
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
#ifndef USE_LOGGER_ZEPHYR_CDC_LOOP
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
else {
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
this->disable_loop();
@@ -371,25 +371,6 @@ static const LogString *get_log_level_str(uint8_t level) {
return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
}
#ifndef USE_HOST
const LogString *Logger::get_uart_selection_() {
#ifdef USE_LOGGER_UART_SELECTION_DEFAULT
// LibreTiny resolves DEFAULT to the board's port only when serial logging is on
if (this->baud_rate_ > 0) {
switch (this->get_uart()) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
default:
return LOG_STR("UART2");
}
}
#endif
return LOG_STR(ESPHOME_LOGGER_UART_NAME);
}
#endif
void Logger::dump_config() {
ESP_LOGCONFIG(TAG,
"Logger:\n"
+10 -35
View File
@@ -124,9 +124,6 @@ enum UARTSelection : uint8_t {
UART_SELECTION_UART0_SWAP,
#endif // USE_ESP8266
};
// The port chosen by hardware_uart, fixed at build time
static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_SELECTION;
#endif // USE_ESP32 || USE_ESP8266 || USE_RP2 || USE_LIBRETINY || USE_ZEPHYR
/**
@@ -149,7 +146,7 @@ static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_S
class Logger final : public Component {
public:
explicit Logger(uint32_t baud_rate);
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
void loop() override;
#endif
#if defined(USE_RP2_CRASH_HANDLER) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -163,11 +160,11 @@ class Logger final : public Component {
#endif
#ifdef USE_ESP32
/// UART_NUM_0 when logging to USB
constexpr uart_port_t get_uart_num() const {
uart_port_t get_uart_num() const {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC) || defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return UART_NUM_0;
#else
return static_cast<uart_port_t>(CONFIGURED_UART_SELECTION);
return static_cast<uart_port_t>(this->uart_);
#endif
}
#endif
@@ -175,35 +172,9 @@ class Logger final : public Component {
void create_pthread_key() { pthread_key_create(&this->log_recursion_key_, nullptr); }
#endif
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
void set_uart_selection(UARTSelection uart_selection) { this->uart_ = uart_selection; }
/// Get the UART used by the logger.
#ifdef USE_LIBRETINY
// DEFAULT resolves to the board's default port
constexpr UARTSelection get_uart() const {
return CONFIGURED_UART_SELECTION == UART_SELECTION_DEFAULT ? static_cast<UARTSelection>(LT_UART_DEFAULT_SERIAL + 1)
: CONFIGURED_UART_SELECTION;
}
#else
constexpr UARTSelection get_uart() const { return CONFIGURED_UART_SELECTION; }
#endif
#endif
#ifdef USE_LOGGER_CONSOLE
// Raw bytes on the console port, without log framing; request with logger.request_console()
// console_write() returns the bytes written: a UART write blocks until all are queued, but a USB write can stop
// short when the host is not reading (USB Serial/JTAG gives up after 20 ms)
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len) { return this->hw_serial_->write(data, len); }
bool console_read(uint8_t &byte) {
int c = this->hw_serial_->read();
if (c < 0)
return false;
byte = c;
return true;
}
#elif defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len);
/// Non-blocking read of one byte; false if none is waiting.
bool console_read(uint8_t &byte);
#endif
UARTSelection get_uart() const { return this->uart_; }
#endif
/// Set the default log level for this logger.
@@ -280,7 +251,7 @@ class Logger final : public Component {
void log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
const char *thread_name);
#endif
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
void cdc_loop_();
#endif
void process_messages_();
@@ -440,6 +411,10 @@ class Logger final : public Component {
bool boot_log_done_{false}; // Set on first replay; stops further capture
#endif
uint8_t current_level_{ESPHOME_LOG_LEVEL_VERY_VERBOSE};
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// 0 is UART0, or DEFAULT on LibreTiny; must match cpp_default_uart in __init__.py
UARTSelection uart_{};
#endif
bool main_task_recursion_guard_{false}; // Guards tx_buffer_ on the main loop
#ifdef USE_LIBRETINY
bool non_main_task_recursion_guard_{false}; // Shared guard for all non-main tasks on LibreTiny
+38 -36
View File
@@ -17,10 +17,6 @@
#include <driver/usb_serial_jtag_vfs.h>
#endif
#endif
// The logger accepts USB_CDC on targets without USB OTG (C3, C6, H2, ...), where IDF has no CDC console
#if defined(USE_LOGGER_CONSOLE) && defined(USE_LOGGER_UART_SELECTION_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
#include <esp_private/usb_console.h>
#endif
#if defined(CONFIG_PM_ENABLE) && defined(CONFIG_FREERTOS_USE_TICKLESS_IDLE) && \
(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0))
#include "esp_sleep.h"
@@ -77,7 +73,6 @@ static void init_usb_serial_jtag() {
}
#endif
#if !defined(USE_LOGGER_UART_SELECTION_USB_CDC) && !defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
uart_config_t uart_config{};
uart_config.baud_rate = (int) baud_rate;
@@ -102,7 +97,6 @@ static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_si
esp_sleep_set_console_uart_handling_mode(ESP_SLEEP_ALWAYS_FLUSH_UART);
#endif
}
#endif
// get_uart_num() and pre_setup() cast the selection straight to a port
static_assert(static_cast<int>(UART_SELECTION_UART0) == static_cast<int>(UART_NUM_0) &&
@@ -113,11 +107,26 @@ static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NU
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
init_usb_serial_jtag();
#elif !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
init_uart(this->get_uart_num(), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
switch (this->uart_) {
case UART_SELECTION_UART0:
case UART_SELECTION_UART1:
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
#endif
init_uart(static_cast<uart_port_t>(this->uart_), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
break;
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
init_usb_serial_jtag();
#endif
break;
#endif
}
}
global_logger = this;
@@ -129,36 +138,29 @@ void Logger::pre_setup() {
#endif
}
#ifdef USE_LOGGER_CONSOLE
size_t Logger::console_write(const uint8_t *data, size_t len) {
int written = 0;
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
written = esp_usb_console_write_buf(reinterpret_cast<const char *>(data), len);
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
return LOG_STR("UART2");
#endif
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
written = usb_serial_jtag_write_bytes(data, len, pdMS_TO_TICKS(20));
#else
written = uart_write_bytes(this->get_uart_num(), data, len);
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#endif
return written > 0 ? written : 0;
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
return LOG_STR("USB_SERIAL_JTAG");
#endif
default:
return LOG_STR("UNKNOWN");
}
}
bool Logger::console_read(uint8_t &byte) {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
return esp_usb_console_available_for_read() && esp_usb_console_read_buf(reinterpret_cast<char *>(&byte), 1) == 1;
#else
return false;
#endif
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return usb_serial_jtag_read_bytes(&byte, 1, 0) > 0;
#else
return uart_read_bytes(this->get_uart_num(), &byte, 1, 0) > 0;
#endif
}
#endif
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp32::crash_handler_has_data(); }
void log_crash_to_client() {
+16 -3
View File
@@ -14,9 +14,9 @@ void Logger::pre_setup() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
#ifdef USE_LOGGER_UART_SELECTION_UART0_SWAP
Serial.swap();
#endif
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
Serial.swap();
}
Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
this->hw_serial_ = &Serial1;
@@ -35,6 +35,19 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
return LOG_STR("UART0_SWAP");
}
return LOG_STR("UART0");
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
return LOG_STR("UART1");
#else
return LOG_STR("NONE");
#endif
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp8266::crash_handler_has_data(); }
void log_crash_to_client() { esp8266::crash_handler_log(); }
+51 -20
View File
@@ -12,28 +12,45 @@ ESPHOME_LOG_TAG(TAG, "logger");
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
#if defined(USE_LOGGER_UART_SELECTION_UART0) && LT_HW_UART0
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1) && LT_HW_UART1
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART2) && LT_HW_UART2
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (CONFIGURED_UART_SELECTION != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
switch (this->uart_) {
#if LT_HW_UART0
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART1
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART2
case UART_SELECTION_UART2:
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
break;
#endif
default:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (this->uart_ != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
break;
}
// change lt_log() port to match default Serial
lt_log_set_port(this->get_uart() - 1);
if (this->uart_ == UART_SELECTION_DEFAULT) {
this->uart_ = (UARTSelection) (LT_UART_DEFAULT_SERIAL + 1);
lt_log_set_port(LT_UART_DEFAULT_SERIAL);
} else {
lt_log_set_port(this->uart_ - 1);
}
}
global_logger = this;
@@ -43,6 +60,20 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_DEFAULT:
return LOG_STR("DEFAULT");
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_UART2:
default:
return LOG_STR("UART2");
}
}
#ifdef USE_LIBRETINY_CRASH_HANDLER
bool crash_log_pending() { return libretiny::crash_handler_has_data(); }
void log_crash_to_client() { libretiny::crash_handler_log(); }
+27 -10
View File
@@ -26,16 +26,20 @@ void Logger::setup() {
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
#endif
switch (this->uart_) {
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
break;
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
break;
case UART_SELECTION_USB_CDC:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
break;
}
}
global_logger = this;
ESP_LOGI(TAG, "Log initialized");
@@ -45,6 +49,19 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
default:
return LOG_STR("UNKNOWN");
}
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return rp2::crash_handler_has_data(); }
void log_crash_to_client() { rp2::crash_handler_log(); }
+34 -13
View File
@@ -42,7 +42,7 @@ __attribute__((section(".noinit"))) struct {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
void Logger::cdc_loop_() {
if (this->uart_dev_ == nullptr) {
return;
@@ -75,19 +75,25 @@ void Logger::pre_setup() {
#ifdef CONFIG_SERIAL
if (this->baud_rate_ > 0) {
const struct device *uart_dev = nullptr;
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
switch (this->uart_) {
case UART_SELECTION_UART0: // NOLINT(bugprone-branch-clone)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
break;
case UART_SELECTION_UART1:
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
#if defined(CONFIG_USB_DEVICE_STACK) || defined(CONFIG_USB_DEVICE_STACK_NEXT)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
}
#endif
break;
#endif
}
#endif
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
#else
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
#endif
if (device_is_ready(uart_dev)) {
this->uart_dev_ = uart_dev;
#if defined(USE_LOGGER_WAIT_FOR_CDC) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -111,7 +117,7 @@ void Logger::pre_setup() {
this->dump_crash_();
#endif
// Nobody reads a USB port this early; cdc_loop_() reports the dump once the port is opened
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
// Without a UART (baud_rate: 0, or one that did not come up) nothing reaches the console
if (this->uart_dev_ != nullptr)
log_crash_to_client();
@@ -133,6 +139,21 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
}
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#endif
default:
return LOG_STR("UNKNOWN");
}
}
static constexpr uint8_t REASON_BUF_SIZE = 32;
static const char *reason_to_str(unsigned int reason, char *buf) {
+3 -25
View File
@@ -153,7 +153,6 @@
#define USE_LINE_READER
#define USE_LOCK
#define USE_LOGGER
#define USE_LOGGER_CONSOLE
#define USE_LOGGER_LEVEL_LISTENERS
#define USE_LOGGER_RUNTIME_TAG_LEVELS
#define USE_LVGL
@@ -768,26 +767,16 @@
#if defined(USE_ESP32_VARIANT_ESP32S2)
#define USE_LOGGER_USB_CDC
#define USE_LOGGER_UART_SELECTION_USB_CDC
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
#elif defined(USE_ESP32_VARIANT_ESP32H21)
#define USE_LOGGER_USB_SERIAL_JTAG
#define USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
#define ESPHOME_LOGGER_UART_NAME "USB_SERIAL_JTAG"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_SERIAL_JTAG
#elif defined(USE_ESP32_VARIANT_ESP32C3) || defined(USE_ESP32_VARIANT_ESP32C5) || \
defined(USE_ESP32_VARIANT_ESP32C6) || defined(USE_ESP32_VARIANT_ESP32C61) || defined(USE_ESP32_VARIANT_ESP32H2) || \
defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ESP32_VARIANT_ESP32P4) || defined(USE_ESP32_VARIANT_ESP32S3) || \
defined(USE_ESP32_VARIANT_ESP32S31)
defined(USE_ESP32_VARIANT_ESP32H21) || defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ESP32_VARIANT_ESP32P4) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32S31)
#define USE_LOGGER_USB_CDC
#define USE_LOGGER_UART_SELECTION_USB_CDC
#define USE_LOGGER_USB_SERIAL_JTAG
#define USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
#define ESPHOME_LOGGER_UART_NAME "USB_SERIAL_JTAG"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_SERIAL_JTAG
#else
#define USE_LOGGER_UART_SELECTION_UART0
#define ESPHOME_LOGGER_UART_NAME "UART0"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_UART0
#endif
#endif
@@ -801,9 +790,6 @@
#define USE_WIFI_SCAN_RESULTS_LOCK
#define USE_ESP8266_LOGGER_SERIAL
#define USE_ESP8266_LOGGER_SERIAL1
#define USE_LOGGER_UART_SELECTION_UART0
#define ESPHOME_LOGGER_UART_NAME "UART0"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_UART0
#define USE_ESP8266_PREFERENCES_FLASH
#define ESP8266_PREFERENCES_FLASH_WORDS 128
#define ESP8266_PREFERENCES_RTC_EBOOT_WORDS 32
@@ -849,8 +835,6 @@
#define USE_I2C
#define USE_LOGGER_USB_CDC
#define USE_LOGGER_UART_SELECTION_USB_CDC
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
#define USE_SOCKET_IMPL_LWIP_TCP
#define USE_RP2040_BLE
#define USE_RP2_BLE_TRACKER
@@ -881,9 +865,6 @@
#if defined(USE_BK72XX) || defined(USE_RTL87XX) || defined(USE_LN882X)
#define USE_LIBRETINY_CRASH_HANDLER
#endif
#define USE_LOGGER_UART_SELECTION_DEFAULT
#define ESPHOME_LOGGER_UART_NAME "DEFAULT"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_DEFAULT
#ifdef USE_BK72XX
#define USE_REMOTE_RECEIVER_TIMER_SAMPLING
#endif
@@ -938,11 +919,8 @@
#define ESPHOME_TASK_LOG_BUFFER_SIZE 768
#define USE_LOGGER_EARLY_MESSAGE
#define USE_LOGGER_UART_SELECTION_USB_CDC
#define ESPHOME_LOGGER_UART_NAME "USB_CDC"
#define ESPHOME_LOGGER_UART_SELECTION logger::UART_SELECTION_USB_CDC
#define USE_LOGGER_USB_CDC
#define USE_LOGGER_WAIT_FOR_CDC
#define USE_LOGGER_ZEPHYR_CDC_LOOP
#define USE_NRF52_DFU
#define USE_NRF52_REG0_VOUT 5
#define USE_NRF52_UICR_ERASE
+44 -53
View File
@@ -68,6 +68,38 @@ def test_logger_pre_setup_before_other_components(generate_main):
)
def test_default_uart_selection_is_not_emitted(generate_main):
"""UART0 is the C++ initializer on ESP8266, so the setter is skipped."""
main_cpp = generate_main("tests/component_tests/logger/test_logger.yaml")
assert "set_uart_selection(" not in main_cpp
def test_custom_uart_selection_is_emitted(generate_main):
"""A non default UART still reaches the setter before pre_setup()."""
main_cpp = generate_main("tests/component_tests/logger/test_logger_uart1.yaml")
assert "set_uart_selection(logger::UART_SELECTION_UART1);" in main_cpp
def test_libretiny_default_uart_selection_is_not_emitted(generate_main):
"""DEFAULT is the C++ initializer on LibreTiny, so the setter is skipped."""
main_cpp = generate_main(
"tests/component_tests/logger/test_logger_libretiny_default.yaml"
)
assert "set_uart_selection(" not in main_cpp
def test_libretiny_uart0_is_emitted(generate_main):
"""UART0 is not the LibreTiny initializer, so it must still be set."""
main_cpp = generate_main(
"tests/component_tests/logger/test_logger_libretiny_uart0.yaml"
)
assert "set_uart_selection(logger::UART_SELECTION_UART0);" in main_cpp
def test_ram_log_strings_is_deprecated(
generate_main: Callable[[str | Path], str],
caplog: pytest.LogCaptureFixture,
@@ -136,76 +168,35 @@ def test_log_v2_only_on_native_toolchain(
@pytest.mark.parametrize(
("config", "port", "zephyr_cdc_loop"),
("config", "expected"),
[
pytest.param("test_logger.yaml", "UART0", False, id="esp8266_default"),
pytest.param("test_logger_uart1.yaml", "UART1", False, id="esp8266_uart1"),
pytest.param(
"test_logger_uart0_swap.yaml", "UART0_SWAP", False, id="esp8266_uart0_swap"
),
pytest.param(
"test_logger_libretiny_default.yaml",
"DEFAULT",
False,
id="libretiny_default",
),
pytest.param(
"test_logger_libretiny_uart0.yaml", "UART0", False, id="libretiny_uart0"
),
pytest.param(
"test_logger_rp2_usb_cdc.yaml", "USB_CDC", False, id="rp2_usb_cdc"
),
pytest.param("test_logger_rp2_uart0.yaml", "UART0", False, id="rp2_uart0"),
pytest.param(
"test_logger_esp32_usb_cdc.yaml", "USB_CDC", False, id="esp32_usb_cdc"
),
pytest.param("test_logger_rp2_usb_cdc.yaml", {"USB_CDC"}, id="rp2_usb_cdc"),
pytest.param("test_logger_rp2_uart0.yaml", set(), id="rp2_uart0"),
pytest.param("test_logger_esp32_usb_cdc.yaml", {"USB_CDC"}, id="esp32_usb_cdc"),
pytest.param(
"test_logger_esp32_usb_serial_jtag.yaml",
"USB_SERIAL_JTAG",
False,
{"USB_SERIAL_JTAG"},
id="esp32_usb_serial_jtag",
),
pytest.param(
"test_logger_nrf52_usb_cdc.yaml", "USB_CDC", True, id="nrf52_usb_cdc"
),
pytest.param("test_logger_nrf52_usb_cdc.yaml", {"USB_CDC"}, id="nrf52_usb_cdc"),
# Zephyr polls the USB port only when it logs there
pytest.param(
"test_logger_nrf52_usb_cdc_no_serial.yaml",
"USB_CDC",
False,
id="nrf52_no_serial",
"test_logger_nrf52_usb_cdc_no_serial.yaml", set(), id="nrf52_no_serial"
),
],
)
def test_uart_selection_defines(
generate_main: Callable[[str | Path], str],
config: str,
port: str,
zephyr_cdc_loop: bool,
expected: set[str],
) -> None:
"""The chosen port is fixed at build time: one flag, its enum value and its dump_config name."""
"""USB ports get a selection define, which gates their port code and crash replay."""
generate_main(f"tests/component_tests/logger/{config}")
defines = {d.name: d.value for d in CORE.defines}
prefix = "USE_LOGGER_UART_SELECTION_"
assert {d.removeprefix(prefix) for d in defines if d.startswith(prefix)} == {port}
assert (
str(defines["ESPHOME_LOGGER_UART_SELECTION"])
== f"logger::UART_SELECTION_{port}"
)
assert str(defines["ESPHOME_LOGGER_UART_NAME"]) == f'"{port}"'
assert ("USE_LOGGER_ZEPHYR_CDC_LOOP" in defines) is zephyr_cdc_loop
def test_esp8266_without_serial_dumps_no_port(
generate_main: Callable[[str | Path], str],
) -> None:
"""ESP8266 without serial logging keeps UART0 selected but never opens it."""
generate_main("tests/component_tests/logger/test_logger_no_serial.yaml")
defines = {d.name: d.value for d in CORE.defines}
assert "USE_LOGGER_UART_SELECTION_UART0" in defines
assert str(defines["ESPHOME_LOGGER_UART_NAME"]) == '"NONE"'
assert {
d.name.removeprefix(prefix) for d in CORE.defines if d.name.startswith(prefix)
} == expected
def test_log_listener_slots_count_every_listener(
@@ -1,9 +0,0 @@
---
esphome:
name: test
esp8266:
board: d1_mini_lite
logger:
baud_rate: 0
@@ -1,9 +0,0 @@
---
esphome:
name: test
esp8266:
board: d1_mini_lite
logger:
hardware_uart: UART0_SWAP
+104
View File
@@ -0,0 +1,104 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <cstdarg>
#include <cstring>
#include <string>
#include "esphome/components/logger/log_buffer.h"
namespace esphome::logger::testing {
static void format_into(LogBuffer &buf, const char *format, ...) {
va_list args;
va_start(args, format);
buf.format_body(format, args);
va_end(args);
}
// A cut line keeps its whole color reset, and the terminator is never counted in pos
static void expect_reset_and_terminator(const LogBuffer &buf, uint16_t start) {
ASSERT_LT(buf.pos, buf.size);
EXPECT_EQ(buf.data[buf.pos], '\0');
if (buf.size - start > LogBuffer::ANSI_RESET_LEN) {
ASSERT_GE(buf.pos, start + LogBuffer::ANSI_RESET_LEN);
EXPECT_EQ(memcmp(buf.data + buf.pos - LogBuffer::ANSI_RESET_LEN, "\033[0m", LogBuffer::ANSI_RESET_LEN), 0);
}
}
TEST(LogBufferTest, CutLineKeepsColorResetAndTerminator) {
constexpr uint16_t max_size = 48;
const std::string text(max_size + 8, 'x');
for (uint16_t size = 1; size <= max_size; size++) {
for (uint16_t start = 0; start < size; start++) {
for (size_t len = 0; len <= text.size(); len++) {
SCOPED_TRACE(::testing::Message() << "size " << size << " start " << start << " text " << len);
const std::string body = text.substr(0, len);
char formatted[max_size], copied[max_size];
memset(formatted, '#', sizeof(formatted));
memset(copied, '#', sizeof(copied));
LogBuffer a{formatted, size, start};
format_into(a, "%s", body.c_str());
expect_reset_and_terminator(a, start);
LogBuffer b{copied, size, start};
b.write_body(body.data(), static_cast<uint16_t>(len));
expect_reset_and_terminator(b, start);
EXPECT_EQ(a.pos, b.pos);
// The text keeps every character that fits in front of the reset and the terminator
const int room = size - start - LogBuffer::ANSI_RESET_LEN;
const size_t kept = room > 0 ? std::min(len, static_cast<size_t>(room - 1)) : 0;
EXPECT_EQ(a.pos, start + kept + (room > 0 ? LogBuffer::ANSI_RESET_LEN : 0));
EXPECT_EQ(memcmp(formatted + start, text.data(), kept), 0);
EXPECT_EQ(memcmp(copied + start, text.data(), kept), 0);
}
}
}
}
TEST(LogBufferTest, CutAfterNewlineDropsIt) {
char formatted[16], copied[16];
LogBuffer a{formatted, sizeof(formatted)};
LogBuffer b{copied, sizeof(copied)};
// 11 bytes of text fit in 16 after the reset and the terminator; the 11th is the newline
format_into(a, "%s", "0123456789\nabc");
b.write_body("0123456789\nabc", 14);
EXPECT_EQ(std::string(formatted, a.pos), "0123456789\033[0m");
EXPECT_EQ(std::string(copied, b.pos), "0123456789\033[0m");
}
TEST(LogBufferTest, LineThatFitsIsUnchanged) {
char data[64];
LogBuffer buf{data, sizeof(data)};
format_into(buf, "%s", "hello");
EXPECT_EQ(std::string(data, buf.pos), "hello\033[0m");
}
static std::string header_line(uint16_t size, const std::string &tag, const std::string &thread) {
std::string data(size, '#');
const std::string text(600, 'x');
LogBuffer buf{data.data(), size};
buf.write_header(ESPHOME_LOG_LEVEL_DEBUG, tag.c_str(), 123, thread.c_str());
EXPECT_LT(buf.pos, size);
format_into(buf, "%s", text.c_str());
expect_reset_and_terminator(buf, 0);
return data.substr(0, buf.pos);
}
TEST(LogBufferTest, LongTagIsKeptWhenItFits) {
const std::string tag(200, 't');
const std::string line = header_line(512, tag, "main");
EXPECT_NE(line.find("[" + tag + ":123]"), std::string::npos);
}
TEST(LogBufferTest, LongTagAndThreadNameAreCutToTheRoomLeft) {
// The smallest tx_buffer_size; an overlong tag or thread name must not push the header past the buffer
constexpr uint16_t size = 160;
constexpr size_t tag_room = size - (MAX_HEADER_SIZE - MAX_TAG_LENGTH);
const std::string line = header_line(size, std::string(200, 't'), std::string(200, 'n'));
EXPECT_NE(line.find("[" + std::string(tag_room, 't') + ":123]"), std::string::npos);
EXPECT_EQ(line.find(std::string(tag_room + 1, 't')), std::string::npos);
EXPECT_NE(line.find(std::string(MAX_TAG_LENGTH, 'n')), std::string::npos);
EXPECT_EQ(line.find(std::string(MAX_TAG_LENGTH + 1, 'n')), std::string::npos);
}
} // namespace esphome::logger::testing
@@ -26,7 +26,8 @@ TEST(UnformattedLogTest, BodyMatchesFormattedBodyAtEverySize) {
const char *texts[] = {"", "short", "ends with newlines\n\n", "\n", "a\nb", long_text.c_str()};
constexpr uint16_t max_size = 48;
for (uint16_t size = 1; size <= max_size; size++) {
for (uint16_t start = 0; start <= size; start++) {
// The header always leaves room for the terminator, so the body starts inside the buffer
for (uint16_t start = 0; start < size; start++) {
for (const char *text : texts) {
SCOPED_TRACE(::testing::Message() << "size " << size << " start " << start << " text '" << text << "'");
char formatted[max_size], unformatted[max_size], flash[max_size];
@@ -46,7 +47,7 @@ TEST(UnformattedLogTest, BodyMatchesFormattedBodyAtEverySize) {
ASSERT_EQ(a.pos, b.pos);
ASSERT_EQ(a.pos, c.pos);
// Up to and including the null terminator; vsnprintf() may leave bytes after it that nothing reads
const size_t used = (a.pos < size) ? a.pos + 1 : size;
const size_t used = a.pos + 1;
ASSERT_EQ(memcmp(formatted, unformatted, used), 0);
ASSERT_EQ(memcmp(formatted, flash, used), 0);
}
+1
View File
@@ -17,6 +17,7 @@ void setup() {
App.pre_setup(name, sizeof(name) - 1, friendly_name, sizeof(friendly_name) - 1);
auto *log = new logger::Logger(115200); // NOLINT
log->pre_setup();
log->set_uart_selection(logger::UART_SELECTION_UART0);
App.register_component_(log);
auto *wifi = new wifi::WiFiComponent(); // NOLINT