Compare commits

...
Author SHA1 Message Date
J. Nick Koston 8c11a3ba7d Say when console_write() can write fewer bytes 2026-11-16 23:57:47 -06:00
J. Nick Koston a2c07ae165 Describe the console limits by the IDF option, include host 2026-11-16 23:18:51 -06:00
J. Nick Koston 18eff452ba Say where request_console() does nothing 2026-11-16 23:05:22 -06:00
J. Nick Koston f81920f9e0 Mark the USB CDC console guards as needed 2026-11-16 22:54:05 -06:00
J. Nick Koston d4efd41c38 Restore the USB CDC console guards for targets without USB OTG 2026-11-16 22:53:39 -06:00
J. Nick Koston 8e54625bde Drop the USB CDC sdkconfig checks the port selection implies, use pdMS_TO_TICKS, shorten the port table test 2026-11-16 22:29:33 -06:00
J. Nick Koston 3cee50f683 Merge remote-tracking branch 'upstream/dev' into logger-console-api 2026-11-16 22:17:34 -06:00
Mark Mayo e12784543d [logger] Copy log lines that have no arguments instead of formatting them (#22644) 2026-11-16 22:16:47 -06:00
J. Nick Koston bc3e9c88f4 [select] Set a fixed option by index and look up a template lambda's option once (#22655) 2026-11-16 22:48:05 -05:00
luar123andCopilot Autofix powered by AI 7e3c2ebc10 [zigbee] refactor ZigbeeAttribute (#22765)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 22:31:05 -05:00
J. Nick Koston 3f6c0f35fe [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 16:23:11 +13:00
J. Nick Koston 200bf69035 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 16:23:06 +13:00
huangkongshengandhuangkongsheng 0054041d6a [core] Reject sign-padded bind key pairs (#22660)
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
Co-authored-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-11-16 22:15:45 -05:00
J. Nick Koston 7b7f3cf50b Compile init_uart only for UART selections 2026-11-16 13:07:33 -06:00
J. Nick Koston 4304a92674 Assert the port name and selection per config, define them beside each port in defines.h 2026-11-16 13:07:33 -06:00
J. Nick Koston 6b4acbcdc4 Keep the hardware_uart selection map for device-builder, check the USB CDC read count 2026-11-16 13:07:33 -06:00
J. Nick Koston d618b41db9 Name the console UART and its selection with one define each 2026-11-16 13:07:33 -06:00
J. Nick Koston 941286480f [logger] Fix the console UART at build time and add a console read/write API 2026-11-16 13:07:33 -06:00
45 changed files with 1247 additions and 436 deletions

No files matched your search

+3 -1
View File
@@ -605,7 +605,9 @@ async def to_code(config: ConfigType) -> None:
cg.add(var.set_type(conf[CONF_TYPE]))
for conf in config[CONF_SELECTS]:
var = await select.new_select(conf, options=conf[CONF_OPTIONS])
var = await select.new_select(
conf, options=conf[CONF_OPTIONS], fixed_options=True
)
await cg.register_component(var, conf)
for conf in config[CONF_SENSORS]:
+1 -1
View File
@@ -41,5 +41,5 @@ CONFIG_SCHEMA = (
async def to_code(config: ConfigType) -> None:
var = await select.new_select(config, options=DUCO_MODE_OPTIONS)
var = await select.new_select(config, options=DUCO_MODE_OPTIONS, fixed_options=True)
await register_duco_device(var, config, config[CONF_DUCO_ID])
+26 -15
View File
@@ -94,6 +94,7 @@ 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,
@@ -538,17 +539,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())
# 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]))
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,
)
# 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())
@@ -645,7 +646,6 @@ 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,10 +663,12 @@ 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 config.get(CONF_HARDWARE_UART) == USB_CDC and (
has_serial_logging or not CORE.is_nrf52
if (
CORE.using_zephyr
and has_serial_logging
and config[CONF_HARDWARE_UART] == USB_CDC
):
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
cg.add_define("USE_LOGGER_ZEPHYR_CDC_LOOP")
# Define platform support flags for components that need auto-detection
try:
uart_selection(USB_SERIAL_JTAG)
@@ -884,6 +886,15 @@ 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")
+22 -1
View File
@@ -114,6 +114,26 @@ struct LogBuffer {
this->finalize_();
}
#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
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->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_()) {
char *const start = this->current_();
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + this->remaining_() - 1, text) - this->data);
this->strip_trailing_newlines_();
}
this->finalize_();
}
static constexpr uint16_t ANSI_COLOR_LEN = 7; // "\033[{bold};3{color}m" written by write_header for level != 0
static constexpr uint16_t ANSI_RESET_LEN = 4; // "\033[0m"
// Largest replay header: color plus "@4294967295ms "
@@ -161,7 +181,8 @@ struct LogBuffer {
this->pos += ANSI_RESET_LEN;
}
}
void strip_trailing_newlines_() {
// 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--;
}
+75 -8
View File
@@ -19,6 +19,15 @@ namespace esphome::logger {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes to a socket would
// take that lock again and deadlock, so such a line is queued for loop() instead. It can print after later inline
// lines, and is lost if loop() never runs again (safe_reboot()).
static inline bool HOT ESPHOME_ALWAYS_INLINE under_lwip_core_lock() {
return sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED);
}
#endif
#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
@@ -51,11 +60,7 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// Pass nullptr for thread_name since we already know this is the main task
if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
// to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
// can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
[[unlikely]] {
if (under_lwip_core_lock()) [[unlikely]] {
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
return;
}
@@ -159,6 +164,49 @@ void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __Flas
}
#endif // USE_ESP8266
// Not shared with log_message_to_buffer_and_send_(): sharing it slows formatted lines
inline void HOT ESPHOME_ALWAYS_INLINE Logger::send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf) {
#ifdef USE_LOGGER_BOOT_LOG_BUFFER
if (!this->boot_log_done_)
this->boot_log_capture_(level, tag, buf);
#endif
this->notify_listeners_(level, tag, buf);
this->write_log_buffer_to_console_(buf);
}
bool HOT Logger::log_str_(uint8_t level, const char *tag, int line, const char *msg) {
if (level > this->level_for(tag))
return true;
// Check the task first: the guard belongs to the main task and must not be read from other threads
if (!this->is_main_task_())
return false;
if (this->main_task_recursion_guard_)
return true;
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// The formatting path queues it
if (under_lwip_core_lock()) [[unlikely]]
return false;
#endif
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body(msg, strlen(msg));
this->send_unformatted_line_(level, tag, buf);
return true;
}
#ifdef USE_ESP8266
void Logger::log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg) {
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
return;
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body_p(reinterpret_cast<PGM_P>(msg));
this->send_unformatted_line_(level, tag, buf);
}
#endif // USE_ESP8266
#if defined(USE_LOGGER_RUNTIME_TAG_LEVELS) || defined(USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS)
// Level for tag from a per-tag map, or fallback when the tag has none; tags may live in flash
static inline uint8_t tag_level(const std::map<const char *, uint8_t, CStrCompare> &levels, const char *tag,
@@ -200,10 +248,10 @@ Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
#endif
}
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void Logger::loop() {
this->process_messages_();
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
this->cdc_loop_();
#endif
}
@@ -230,7 +278,7 @@ void Logger::process_messages_() {
}
}
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#ifndef USE_LOGGER_ZEPHYR_CDC_LOOP
else {
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
this->disable_loop();
@@ -323,6 +371,25 @@ 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"
+57 -11
View File
@@ -124,6 +124,9 @@ 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
/**
@@ -146,7 +149,7 @@ enum UARTSelection : uint8_t {
class Logger final : public Component {
public:
explicit Logger(uint32_t baud_rate);
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void loop() override;
#endif
#if defined(USE_RP2_CRASH_HANDLER) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -160,11 +163,11 @@ class Logger final : public Component {
#endif
#ifdef USE_ESP32
/// UART_NUM_0 when logging to USB
uart_port_t get_uart_num() const {
constexpr 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>(this->uart_);
return static_cast<uart_port_t>(CONFIGURED_UART_SELECTION);
#endif
}
#endif
@@ -172,9 +175,35 @@ 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.
UARTSelection get_uart() const { return this->uart_; }
#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
#endif
/// Set the default log level for this logger.
@@ -223,6 +252,12 @@ class Logger final : public Component {
// NOLINTNEXTLINE(readability-identifier-naming)
void log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format, va_list args);
#endif
// Copies a line with no '%' without formatting; false means the caller must format it
bool log_str_(uint8_t level, const char *tag, int line, const char *msg); // NOLINT
#ifdef USE_ESP8266
// NOLINTNEXTLINE(readability-identifier-naming)
void log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg);
#endif
protected:
// RAII guard for recursion flags - sets flag on construction, clears on destruction
@@ -245,7 +280,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
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void cdc_loop_();
#endif
void process_messages_();
@@ -292,7 +327,7 @@ class Logger final : public Component {
}
// Helper to write log buffer to console if logging is enabled
inline void HOT write_log_buffer_to_console_(LogBuffer &buf) {
inline void HOT ESPHOME_ALWAYS_INLINE write_log_buffer_to_console_(LogBuffer &buf) {
if (this->baud_rate_ > 0)
this->write_to_console_(buf);
}
@@ -321,6 +356,21 @@ class Logger final : public Component {
this->write_log_buffer_to_console_(buf);
}
inline void send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf);
// True on the task that runs the main loop, and always on single-task platforms
inline bool HOT is_main_task_() const {
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
return xTaskGetCurrentTaskHandle() == this->main_task_;
#elif defined(USE_ZEPHYR)
return k_current_get() == this->main_task_;
#elif defined(USE_HOST)
return pthread_equal(pthread_self(), this->main_thread_);
#else
return true;
#endif
}
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
// Helper to format a pre-formatted message from the task log buffer and notify listeners
inline void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line,
@@ -390,10 +440,6 @@ 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
+35 -37
View File
@@ -17,6 +17,10 @@
#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"
@@ -73,6 +77,7 @@ 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;
@@ -97,6 +102,7 @@ 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) &&
@@ -107,26 +113,11 @@ static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NU
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
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();
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);
#endif
break;
#endif
}
}
global_logger = this;
@@ -138,29 +129,36 @@ 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");
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
return LOG_STR("UART2");
#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);
#endif
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#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);
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
return LOG_STR("USB_SERIAL_JTAG");
#endif
default:
return LOG_STR("UNKNOWN");
}
return written > 0 ? written : 0;
}
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() {
+3 -16
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_);
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
Serial.swap();
}
#ifdef USE_LOGGER_UART_SELECTION_UART0_SWAP
Serial.swap();
#endif
Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
this->hw_serial_ = &Serial1;
@@ -35,19 +35,6 @@ 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(); }
+20 -51
View File
@@ -12,45 +12,28 @@ ESPHOME_LOG_TAG(TAG, "logger");
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
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;
#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.");
}
#endif
// change lt_log() port to match default Serial
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);
}
lt_log_set_port(this->get_uart() - 1);
}
global_logger = this;
@@ -60,20 +43,6 @@ 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(); }
+10 -27
View File
@@ -26,20 +26,16 @@ void Logger::setup() {
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
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;
}
#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
}
global_logger = this;
ESP_LOGI(TAG, "Log initialized");
@@ -49,19 +45,6 @@ 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(); }
+13 -34
View File
@@ -42,7 +42,7 @@ __attribute__((section(".noinit"))) struct {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void Logger::cdc_loop_() {
if (this->uart_dev_ == nullptr) {
return;
@@ -75,25 +75,19 @@ void Logger::pre_setup() {
#ifdef CONFIG_SERIAL
if (this->baud_rate_ > 0) {
const struct device *uart_dev = nullptr;
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(USE_LOGGER_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();
}
#endif
break;
#endif
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
#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)
@@ -117,7 +111,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_UART_SELECTION_USB_CDC)
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
// 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();
@@ -139,21 +133,6 @@ 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) {
+1 -1
View File
@@ -34,6 +34,6 @@ async def to_code(config: ConfigType) -> None:
levels = list(LOG_LEVELS)
index = levels.index(CORE.data[DOMAIN][CONF_LEVEL])
levels = levels[: index + 1]
var = await select.new_select(config, options=levels)
var = await select.new_select(config, options=levels, fixed_options=True)
await register_parented(var, parent)
await register_component(var, config)
@@ -103,7 +103,9 @@ async def to_code(config: ConfigType) -> None:
)
await cg.register_component(var, config)
await select.register_select(var, config, options=list(options_map.keys()))
await select.register_select(
var, config, options=list(options_map.keys()), fixed_options=True
)
parent = await cg.get_variable(config[CONF_MODBUS_CONTROLLER_ID])
cg.add(parent.add_sensor_item(var))
+32 -23
View File
@@ -56,7 +56,8 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
@@ -670,22 +671,28 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
int radio_state = 0;
if (this->dce_->get_radio_state(radio_state) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the radio state; skipping the radio off step");
} else if (radio_state != RADIO_STATE_RF_OFF) {
// Drops a session left by a warm reboot; unlike CFUN=0, which powers the SIM down on the SIM7600, CFUN=4
// keeps the SIM readable for the PIN and the APN. A modem that refuses is used as it is.
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio off");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
esp_modem::PdpContext pdp(this->apn_);
this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
this->dce_->set_pdp_context(pdp) != command_result::OK;
if (this->apn_pending_) {
ESP_LOGW(TAG, "Failed to set the APN with the SIM powered down; setting it after the SIM check");
}
// CFUN=4 powers the SIM up with the radio still off; a modem without it needs CFUN=1 to bring the SIM back
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
@@ -752,7 +759,7 @@ ModemState ModemComponent::handle_state_connecting_() {
return ModemState::MODEM_STATE_ENABLING;
}
}
// ENABLING left the radio at CFUN=4, where the SIM answers but the modem cannot attach yet
// ENABLING powered the SIM up (CFUN=4, or CFUN=1 on a modem without it), so the SIM answers
switch (this->prepare_sim_()) {
case SimResult::SIM_RESULT_READY:
break;
@@ -769,13 +776,14 @@ ModemState ModemComponent::handle_state_connecting_() {
this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
return ModemState::MODEM_STATE_DISCONNECTING;
}
// The APN has to be in the PDP context before the radio comes on and the modem attaches; esp_modem only
// sends it when PPP starts
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
if (this->apn_pending_) {
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
this->apn_pending_ = false;
}
if (this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio on");
@@ -862,11 +870,12 @@ ModemState ModemComponent::handle_state_disconnecting_() {
ESP_LOGW(TAG, "Failed to leave data mode");
this->set_teardown_fault_();
}
// Turn the radio off; waiting for the lost IP event could take up to 2 min. A reconnect keeps the SIM powered
// so it is not unlocked again; only disable() powers it down.
const bool reconnect = this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED;
if (this->dce_->set_radio_state(reconnect ? RADIO_STATE_RF_OFF : 0) == command_result::OK) {
// Turn the radio off; waiting for the lost IP event could take up to 2 min. The SIM is powered down as well, as
// ENABLING does anyway on a reconnect.
if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
ESP_LOGI(TAG, "Radio off");
} else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
ESP_LOGW(TAG, "Radio off, but the SIM could not be powered down");
} else {
ESP_LOGW(TAG, "Radio off failed");
this->set_teardown_fault_();
@@ -299,6 +299,7 @@ class ModemComponent : public Component {
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
#endif
+73 -11
View File
@@ -1,3 +1,6 @@
from dataclasses import dataclass, field
import functools
from esphome import automation
import esphome.codegen as cg
import esphome.config_validation as cv
@@ -26,7 +29,7 @@ from esphome.core.entity_helpers import (
)
from esphome.cpp_generator import MockObj, MockObjClass, TemplateArguments
from esphome.cpp_types import global_ns
from esphome.types import ConfigType
from esphome.types import ConfigType, TemplateArgsType
CODEOWNERS = ["@esphome/core"]
DOMAIN = "select"
@@ -47,6 +50,25 @@ SELECT_OPERATION_OPTIONS = SelectOperation.options(
)
@dataclass
class SelectData:
# Options of each select whose option list never changes at run time, by id
fixed_options: dict[str, list[str]] = field(default_factory=dict)
def _get_data() -> SelectData:
if DOMAIN not in CORE.data:
CORE.data[DOMAIN] = SelectData()
return CORE.data[DOMAIN]
def _record_options(
config: ConfigType, options: list[str], fixed_options: bool
) -> None:
if fixed_options:
_get_data().fixed_options[config[CONF_ID].id] = options
_SELECT_SCHEMA = (
cv.ENTITY_BASE_SCHEMA.extend(entity_helpers.WEBSERVER_SORTING_SCHEMA)
.extend(cv.MQTT_COMMAND_COMPONENT_SCHEMA)
@@ -105,7 +127,11 @@ async def setup_select_core_(var, config, *, options: list[str]):
await entity_helpers.setup_entity_integrations(var, config)
async def register_select(var, config, *, options: list[str]):
async def register_select(
var, config, *, options: list[str], fixed_options: bool = False
):
"""``fixed_options=True`` when the options never change at run time, so ``select.set`` can use the index."""
_record_options(config, options, fixed_options)
if not CORE.has_id(config[CONF_ID]):
var = cg.Pvariable(config[CONF_ID], var)
queue_entity_register("select", config)
@@ -113,9 +139,9 @@ async def register_select(var, config, *, options: list[str]):
await setup_select_core_(var, config, options=options)
async def new_select(config, *args, options: list[str]):
async def new_select(config, *args, options: list[str], fixed_options: bool = False):
var = cg.new_Pvariable(config[CONF_ID], *args)
await register_select(var, config, options=options)
await register_select(var, config, options=options, fixed_options=fixed_options)
return var
@@ -131,7 +157,10 @@ def sub_selects(
config: ConfigType, *, parent: MockObj | ID | None = None
) -> SubEntities:
"""Return a SubEntities bound to new_select; ``apply`` statements can use ``entity``, ``index`` and ``option``."""
return SubEntities(new_select, config, parent, APPLY_ENTITY)
# Hub selects get their options from code generation only
return SubEntities(
functools.partial(new_select, fixed_options=True), config, parent, APPLY_ENTITY
)
@coroutine_with_priority(CoroPriority.CORE)
@@ -146,13 +175,20 @@ OPERATION_BASE_SCHEMA = cv.Schema(
)
automation.register_apply_action(
_SELECT_SET_SCHEMA = OPERATION_BASE_SCHEMA.extend(
{
cv.Required(CONF_OPTION): cv.templatable(cv.string_strict),
}
)
def _option_index(config: ConfigType, option: str) -> str:
return str(_get_data().fixed_options[config[CONF_ID].id].index(option))
_set_option_builder = automation.apply_action_builder(
"select.set",
OPERATION_BASE_SCHEMA.extend(
{
cv.Required(CONF_OPTION): cv.templatable(cv.string_strict),
}
),
_SELECT_SET_SCHEMA,
automation.ApplyField(
CONF_OPTION,
"set_option",
@@ -161,6 +197,32 @@ automation.register_apply_action(
),
call="make_call",
)
_set_index_builder = automation.apply_action_builder(
"select.set",
_SELECT_SET_SCHEMA,
automation.ApplyField(CONF_OPTION, "set_index", cg.size_t, const_fn=_option_index),
call="make_call",
)
@automation.register_action(
"select.set", automation.ApplyAction, _SELECT_SET_SCHEMA, synchronous=True
)
async def select_set_to_code(
config: ConfigType,
action_id: ID,
template_arg: TemplateArguments,
args: TemplateArgsType,
) -> MockObj:
# A constant fixed option becomes its index
await cg.get_variable(config[CONF_ID])
option = config[CONF_OPTION]
if not cg.is_template(option) and option in _get_data().fixed_options.get(
config[CONF_ID].id, ()
):
return await _set_index_builder(config, action_id, template_arg, args)
return await _set_option_builder(config, action_id, template_arg, args)
automation.register_apply_action(
"select.set_index",
@@ -113,7 +113,7 @@ async def to_code(config):
milliseconds=SCHEDULER_DONT_RUN
)
await cg.register_component(var, component_config)
await select.register_select(var, config, options=options)
await select.register_select(var, config, options=options, fixed_options=True)
if CONF_LAMBDA in config:
lambda_ = await cg.process_lambda(
@@ -36,13 +36,8 @@ void setup_with_restore(BaseTemplateSelect *sel_comp, ESPPreferenceObject &pref,
}
void update_lambda(BaseTemplateSelect *sel_comp, const optional<std::string> &val) {
if (val.has_value()) {
if (!sel_comp->has_option(*val)) {
ESP_LOGE(TAG, "Lambda returned an invalid option: %s", (*val).c_str());
return;
}
if (val.has_value())
sel_comp->publish_state(*val);
}
}
} // namespace esphome::template_
+1 -1
View File
@@ -115,7 +115,7 @@ async def to_code(config):
options = list(options_map.values())
mappings = list(options_map.keys())
var = await select.new_select(config, options=options)
var = await select.new_select(config, options=options, fixed_options=True)
if mappings:
cg.add(var.set_select_mappings(mappings))
hub = await cg.add_variable(var.set_tuya_parent, config[CONF_TUYA_ID])
+31 -21
View File
@@ -5,47 +5,57 @@
namespace esphome::wifi {
// Switching APs calls esp_wifi_disconnect(), which queues an association-leave event from the old AP. Remembers
// that AP so its leave event does not end the connection attempt started after it. Platform free for host tests.
/// Which expected leave a disconnect matched.
enum class ExpectedLeave : uint8_t {
EXPECTED_LEAVE_NONE,
EXPECTED_LEAVE_AP,
EXPECTED_LEAVE_ATTEMPT, ///< An attempt that never associated, so no BSSID
};
// Switching APs calls esp_wifi_disconnect(), which queues a leave event for the old AP, or with no BSSID for an
// attempt that never associated. Remembers it so that event does not end the next attempt. Platform free for tests.
class ExpectedDisconnect {
public:
void arm(const uint8_t *bssid) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->armed_ = true;
}
void clear() { this->armed_ = false; }
void arm(const uint8_t *bssid) { this->arm_(bssid, ExpectedLeave::EXPECTED_LEAVE_AP); }
void clear() { this->expected_ = ExpectedLeave::EXPECTED_LEAVE_NONE; }
/// Disconnects from the current AP and, once that succeeds, expects its leave event. read_bssid(uint8_t *out)
/// returns whether there was an AP and runs first, since the record is gone after the disconnect; disconnect()
/// returns whether it succeeded, which is also the result. Any earlier expectation is dropped.
/// Disconnects and, once that succeeds, expects the leave event. read_bssid(uint8_t *out) runs first, since the
/// record is gone after the disconnect, and writes the AP's BSSID only when it returns true; without an AP the
/// attempt's leave, with no BSSID, is expected. disconnect() returns whether it succeeded, which is the result.
template<typename ReadBssid, typename Disconnect>
bool disconnect_and_expect_leave(ReadBssid &&read_bssid, Disconnect &&disconnect) {
this->armed_ = false;
this->clear();
std::array<uint8_t, 6> bssid{};
const bool had_ap = read_bssid(bssid.data());
if (!disconnect())
return false;
if (had_ap)
this->arm(bssid.data());
this->arm_(bssid.data(), had_ap ? ExpectedLeave::EXPECTED_LEAVE_AP : ExpectedLeave::EXPECTED_LEAVE_ATTEMPT);
return true;
}
/// A connected event still queued from the previous AP; it keeps the expectation.
bool is_previous_ap(const uint8_t *bssid) const {
return this->armed_ && std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
return this->expected_ != ExpectedLeave::EXPECTED_LEAVE_NONE &&
std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
}
/// Whether a disconnect is the previous AP's leave. Every disconnect ends the expectation, so it matches at
/// most once; the caller handles roaming disconnects before this.
bool consume_disconnect(const uint8_t *bssid, bool assoc_leave) {
const bool expected = assoc_leave && this->is_previous_ap(bssid);
this->armed_ = false;
return expected;
/// Which expected leave a disconnect is. \p is_leave covers an AP's association leave (8) and the station leave
/// of an attempt that never associated (36). Every disconnect ends the expectation, so it matches at most once.
ExpectedLeave consume_disconnect(const uint8_t *bssid, bool is_leave) {
const ExpectedLeave matched =
is_leave && this->is_previous_ap(bssid) ? this->expected_ : ExpectedLeave::EXPECTED_LEAVE_NONE;
this->clear();
return matched;
}
protected:
void arm_(const uint8_t *bssid, ExpectedLeave expected) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->expected_ = expected;
}
std::array<uint8_t, 6> bssid_{};
bool armed_{false};
ExpectedLeave expected_{ExpectedLeave::EXPECTED_LEAVE_NONE};
};
} // namespace esphome::wifi
@@ -1158,10 +1158,12 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
return;
}
const bool expected_disconnect =
s_expected_disconnect.consume_disconnect(it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE);
const ExpectedLeave expected = s_expected_disconnect.consume_disconnect(
it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE || it.reason == WIFI_REASON_STA_LEAVING);
const bool expected_disconnect = expected != ExpectedLeave::EXPECTED_LEAVE_NONE;
if (expected_disconnect) {
ESP_LOGD(TAG, "Expected disconnect from previous AP");
ESP_LOGD(TAG, "Expected leave of the previous %s",
expected == ExpectedLeave::EXPECTED_LEAVE_AP ? LOG_STR_LITERAL("AP") : LOG_STR_LITERAL("attempt"));
} else if (it.reason == WIFI_REASON_NO_AP_FOUND) {
ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
(const char *) it.ssid);
@@ -1181,7 +1183,9 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
// Refresh is_connected() cache; the old session is no longer connected.
this->update_connected_state_();
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
this->notify_disconnect_state_listeners_();
// An attempt that never associated ended no session listeners know of
if (expected != ExpectedLeave::EXPECTED_LEAVE_ATTEMPT)
this->notify_disconnect_state_listeners_();
#endif
#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
@@ -8,18 +8,16 @@ namespace esphome::zigbee {
ESPHOME_LOG_TAG(TAG, "zigbee.attribute");
void ZigbeeAttribute::set_attr_() {
void ZigbeeAttribute::set_attr_internal() {
if (!this->zb_->is_started()) {
return;
}
if (esp_zigbee_lock_acquire(10 / portTICK_PERIOD_MS)) {
ezb_zcl_status_t state = ezb_zcl_set_attr_value(this->endpoint_id_, this->cluster_id_, this->role_, this->attr_id_,
EZB_ZCL_STD_MANUF_CODE, this->value_p_, false);
// cleared before report_() so it can disable the loop
// when the report has to wait for join
this->set_attr_requested_ = false;
if (this->force_report_) {
this->report_(true);
this->report_internal(true);
}
// Check for error
if (state != EZB_ZCL_STATUS_SUCCESS) {
@@ -30,15 +28,12 @@ void ZigbeeAttribute::set_attr_() {
}
}
void ZigbeeAttribute::report_(bool has_lock) {
void ZigbeeAttribute::report_internal(bool has_lock) {
if (!this->report_enabled) {
return;
}
if (!this->zb_->is_joined()) {
this->report_requested_ = true;
if (!this->set_attr_requested_) {
this->disable_loop();
}
return;
}
if (has_lock or esp_zigbee_lock_acquire(10 / portTICK_PERIOD_MS)) {
@@ -61,43 +56,6 @@ void ZigbeeAttribute::report_(bool has_lock) {
}
}
void ZigbeeAttribute::set_report(ZigbeeReportT report) {
if (report == ZigbeeReportT::ZIGBEE_REPORT_DEFAULT || report == ZigbeeReportT::ZIGBEE_REPORT_COORDINATOR) {
return;
}
this->report_enabled = true;
if (report == ZigbeeReportT::ZIGBEE_REPORT_FORCE) {
this->force_report_ = true;
}
this->zb_->add_on_join_callback([this](bool) {
if (this->report_requested_) {
this->enable_loop();
}
});
}
void ZigbeeAttribute::report() {
if (!this->report_enabled) {
return;
}
this->report_requested_ = true;
this->enable_loop();
}
void ZigbeeAttribute::loop() {
if (this->set_attr_requested_) {
this->set_attr_();
}
if (this->report_requested_) {
this->report_(false);
}
if (!this->report_requested_ && !this->set_attr_requested_) {
this->disable_loop();
}
}
} // namespace esphome::zigbee
#endif
@@ -4,9 +4,8 @@
#include <limits>
#include <type_traits>
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "zigbee_entity_base_esp32.h"
#ifdef USE_ESP32
#ifdef USE_ZIGBEE
@@ -29,34 +28,22 @@
namespace esphome::zigbee {
enum ZigbeeReportT {
ZIGBEE_REPORT_DEFAULT,
ZIGBEE_REPORT_COORDINATOR,
ZIGBEE_REPORT_ENABLE,
ZIGBEE_REPORT_FORCE,
};
class ZigbeeAttribute final : public Component {
class ZigbeeAttribute final : public ZigbeeEntityBase {
public:
ZigbeeAttribute(ZigbeeComponent *parent, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
uint8_t attr_type, float scale, uint8_t max_size)
: zb_(parent),
endpoint_id_(endpoint_id),
: ZigbeeEntityBase(parent, endpoint_id),
cluster_id_(cluster_id),
role_(role),
attr_id_(attr_id),
attr_type_(attr_type),
max_size_(max_size),
scale_(scale) {}
void loop() override;
template<typename T> void add_attr(T value);
template<typename T> void set_attr(const T &value);
uint8_t attr_type() { return attr_type_; }
void set_report(ZigbeeReportT report);
void report();
template<typename F> void add_on_value_callback(F &&callback) { on_value_callback_.add(std::forward<F>(callback)); }
void on_value(ezb_zcl_attribute_t attribute) {
void on_value(ezb_zcl_attribute_t attribute) override {
if (attribute.data.type == this->attr_type() && attribute.data.value) {
this->on_value_callback_.call(attribute);
}
@@ -75,13 +62,10 @@ class ZigbeeAttribute final : public Component {
#ifdef USE_NUMBER
template<typename T> void connect(number::Number *device);
#endif
bool report_enabled = false;
protected:
void set_attr_();
void report_(bool has_lock);
ZigbeeComponent *zb_;
uint8_t endpoint_id_;
void set_attr_internal() override;
void report_internal(bool has_lock) override;
uint16_t cluster_id_;
uint8_t role_;
uint16_t attr_id_;
@@ -89,9 +73,6 @@ class ZigbeeAttribute final : public Component {
uint8_t max_size_;
float scale_;
void *value_p_{nullptr};
bool set_attr_requested_{false};
bool report_requested_{false};
bool force_report_{false};
LazyCallbackManager<void(ezb_zcl_attribute_t attribute)> on_value_callback_{};
template<typename T> T scale_value_(float value);
template<typename T> T invalid_value_();
@@ -0,0 +1,51 @@
#include "zigbee_entity_base_esp32.h"
#include "esphome/core/log.h"
#include "esphome/core/defines.h"
#ifdef USE_ESP32
#ifdef USE_ZIGBEE
namespace esphome::zigbee {
ESPHOME_LOG_TAG(TAG, "zigbee.entity_base");
void ZigbeeEntityBase::set_report(ZigbeeReportT report) {
if (report == ZigbeeReportT::ZIGBEE_REPORT_DEFAULT || report == ZigbeeReportT::ZIGBEE_REPORT_COORDINATOR) {
return;
}
this->report_enabled = true;
if (report == ZigbeeReportT::ZIGBEE_REPORT_FORCE) {
this->force_report_ = true;
}
this->zb_->add_on_join_callback([this](bool) {
if (this->report_requested_) {
this->enable_loop();
}
});
}
void ZigbeeEntityBase::report() {
if (!this->report_enabled) {
return;
}
this->report_requested_ = true;
this->enable_loop();
}
void ZigbeeEntityBase::loop() {
if (this->set_attr_requested_) {
this->set_attr_internal();
}
if (this->report_requested_ && this->zb_->is_joined()) {
this->report_internal(false);
}
if ((!this->report_requested_ || !this->zb_->is_joined()) && !this->set_attr_requested_) {
this->disable_loop();
}
}
} // namespace esphome::zigbee
#endif
#endif
@@ -0,0 +1,47 @@
#pragma once
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#ifdef USE_ESP32
#ifdef USE_ZIGBEE
#include "esp_zigbee.h"
#include "zigbee_esp32.h"
namespace esphome::zigbee {
enum ZigbeeReportT {
ZIGBEE_REPORT_DEFAULT,
ZIGBEE_REPORT_COORDINATOR,
ZIGBEE_REPORT_ENABLE,
ZIGBEE_REPORT_FORCE,
};
class ZigbeeEntityBase : public Component, public ZigbeeAttributeInterface {
public:
void loop() override;
void set_report(ZigbeeReportT report);
void report() override;
bool report_enabled = false;
protected:
ZigbeeEntityBase(ZigbeeComponent *parent, uint8_t endpoint_id) : zb_(parent), endpoint_id_(endpoint_id) {}
/// Handle pending attribute writes and clear set_attr_requested_ when complete; leave it set to retry.
virtual void set_attr_internal() = 0;
/// Handle pending reports and clear report_requested_ when complete; leave it set to retry.
/// Acquire/release the Zigbee lock only when has_lock is false; otherwise the caller owns it.
virtual void report_internal(bool has_lock) = 0;
ZigbeeComponent *zb_;
uint8_t endpoint_id_;
bool set_attr_requested_{false};
bool report_requested_{false};
bool force_report_{false};
};
} // namespace esphome::zigbee
#endif
#endif
+12 -8
View File
@@ -31,7 +31,11 @@ static constexpr uint8_t MAX_ZB_QUEUE_SIZE = 32;
uint8_t *get_zcl_string(const char *str, uint8_t max_size, bool use_max_size = false);
class ZigbeeAttribute;
class ZigbeeAttributeInterface {
public:
virtual void on_value(ezb_zcl_attribute_t attribute) = 0;
virtual void report() = 0;
};
class ZigbeeComponent final : public Component {
public:
@@ -48,8 +52,8 @@ class ZigbeeComponent final : public Component {
bool register_device();
template<typename T>
void add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
uint8_t max_size, T value);
void add_attr(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
uint16_t attr_id, uint8_t max_size, T value);
template<typename T>
void add_attr(uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id, uint8_t max_size, T value);
@@ -94,13 +98,13 @@ class ZigbeeComponent final : public Component {
void end_parent_link_failures_(uint8_t seq);
void reset_parent_link_failures_();
template<typename T>
void add_attr_(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
T *value_p);
void add_attr_(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
uint16_t attr_id, T *value_p);
void handle_attribute_(ezb_zcl_message_info_t info, ezb_zcl_attribute_t attribute);
// attributes_ will be used during operation in zigbee callbacks to update the attribute values and trigger
// automations
// key tuple could be replaced by single 64 (48) bit int with bit fields for endpoint, cluster, role and attr_id
std::map<std::tuple<uint8_t, uint16_t, uint8_t, uint16_t>, ZigbeeAttribute *> attributes_;
std::map<std::tuple<uint8_t, uint16_t, uint8_t, uint16_t>, ZigbeeAttributeInterface *> attributes_;
ezb_af_device_desc_t dev_desc_ = ezb_af_create_device_desc();
CallbackManager<void(bool)> join_cb_{};
template<typename... Args> friend void enqueue_zb_event(Args... args);
@@ -133,7 +137,7 @@ void ZigbeeComponent::add_attr(uint8_t endpoint_id, uint16_t cluster_id, uint8_t
}
template<typename T>
void ZigbeeComponent::add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
void ZigbeeComponent::add_attr(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
uint16_t attr_id, uint8_t max_size, T value) {
// The size byte of the zcl_str must be set to the maximum value,
// even though the initial string may be shorter.
@@ -151,7 +155,7 @@ void ZigbeeComponent::add_attr(ZigbeeAttribute *attr, uint8_t endpoint_id, uint1
}
template<typename T>
void ZigbeeComponent::add_attr_(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
void ZigbeeComponent::add_attr_(ZigbeeAttributeInterface *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role,
uint16_t attr_id, T *value_p) {
ezb_af_ep_desc_t ep_desc = ezb_af_device_get_endpoint_desc(this->dev_desc_, endpoint_id);
if (ep_desc == NULL) {
+5 -6
View File
@@ -1497,12 +1497,11 @@ class BindKeyValidator(SensitiveValidator):
if any(len(part) != 2 for part in parts):
raise Invalid(f"{self._name} must be format XX")
for part in parts:
try:
parts_int.append(int(part, 16))
except ValueError:
raise Invalid(
f"{self._name} must be hex values from 00 to FF"
) from None
# int() also accepts surrounding whitespace and a +/- sign, which
# would silently validate a key different from the one typed
if not re.fullmatch(r"[0-9A-Fa-f]{2}", part):
raise Invalid(f"{self._name} must be hex values from 00 to FF")
parts_int.append(int(part, 16))
return "".join(f"{part:02X}" for part in parts_int)
+25 -3
View File
@@ -153,6 +153,7 @@
#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
@@ -767,16 +768,26 @@
#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_ESP32H21) || defined(USE_ESP32_VARIANT_ESP32H4) || defined(USE_ESP32_VARIANT_ESP32P4) || \
defined(USE_ESP32_VARIANT_ESP32S3) || defined(USE_ESP32_VARIANT_ESP32S31)
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
@@ -790,6 +801,9 @@
#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
@@ -835,6 +849,8 @@
#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
@@ -865,6 +881,9 @@
#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
@@ -919,8 +938,11 @@
#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
+36
View File
@@ -1472,6 +1472,42 @@ __attribute__((format(printf, 4, 5))) inline size_t buf_append_printf(char *buf,
}
#endif
/// Copy a PROGMEM string to `dst`, stopping at its null terminator or at `end`, and return the new end of `dst`.
/// No terminator is written. Flash only allows aligned 32-bit loads on ESP8266, so `src` is read a whole word at a
/// time, including the bytes after its null in the last word; `src` must be readable up to the end of that word.
inline char *ESPHOME_ALWAYS_INLINE progmem_copy_str(char *dst, const char *end, const char *src) {
const uint32_t offset = reinterpret_cast<uintptr_t>(src) & 3;
const uint32_t *word = reinterpret_cast<const uint32_t *>(src - offset);
uint32_t bytes = *word++;
// Enters the loop at the first byte of src; after that each word runs its four steps without another dispatch, and
// one step per byte keeps each a single extract
switch (offset) {
for (;;) {
bytes = *word++;
[[fallthrough]];
case 0:
if (dst >= end || static_cast<char>(bytes) == '\0')
return dst;
*dst++ = static_cast<char>(bytes);
[[fallthrough]];
case 1:
if (dst >= end || static_cast<char>(bytes >> 8) == '\0')
return dst;
*dst++ = static_cast<char>(bytes >> 8);
[[fallthrough]];
case 2:
if (dst >= end || static_cast<char>(bytes >> 16) == '\0')
return dst;
*dst++ = static_cast<char>(bytes >> 16);
[[fallthrough]];
default:
if (dst >= end || static_cast<char>(bytes >> 24) == '\0')
return dst;
*dst++ = static_cast<char>(bytes >> 24);
}
}
}
#ifdef USE_ESP8266
/// Safely append a PROGMEM string to buffer, returning new position (capped at size).
/// ESP8266 internal implementation — prefer the `buf_append_str` macro which wraps
+28
View File
@@ -48,6 +48,34 @@ void HOT esp_log_printf_(int level, const char *tag, int line, const __FlashStri
}
#endif
void HOT esp_log_str_(int level, const char *tag, int line, const char *format) { // NOLINT
#ifdef USE_LOGGER
#ifdef ESPHOME_DEBUG
// Before Logger::pre_setup(), the formatting path below reports the early call
if (logger::global_logger != nullptr)
#endif
{
if (logger::global_logger->log_str_(static_cast<uint8_t>(level), tag, line, format))
return;
}
// Formats the line log_str_() could not copy; it has no '%', so it is its own format
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
esp_log_printf_(level, tag, line, format);
#pragma GCC diagnostic pop
#endif
}
#ifdef USE_ESP8266
void HOT esp_log_str_(int level, const char *tag, int line, const __FlashStringHelper *format) {
#ifdef USE_LOGGER
ESPHOME_DEBUG_ASSERT(logger::global_logger != nullptr);
logger::global_logger->log_str_(static_cast<uint8_t>(level), tag, line, format);
#endif
}
#endif
void HOT esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args) { // NOLINT
#ifdef USE_LOGGER
#ifdef ESPHOME_DEBUG
+57 -14
View File
@@ -67,6 +67,14 @@ void esp_log_printf_(int level, const char *tag, int line, const char *format, .
// NOLINTNEXTLINE(readability-identifier-naming)
void esp_log_printf_(int level, const char *tag, int line, const __FlashStringHelper *format, ...);
#endif
// esp_log_printf_ for a line with no arguments and no '%': it is copied without formatting
void esp_log_str_(int level, const char *tag, int line, const char *format); // NOLINT
#ifdef USE_ESP8266
// NOLINTNEXTLINE(readability-identifier-naming)
void esp_log_str_(int level, const char *tag, int line, const __FlashStringHelper *format);
#endif
// Never defined or called: the ESP_LOGx macros name it in dead code so a line without arguments has its format checked
int esp_log_format_check_(const char *format, ...) __attribute__((format(printf, 1, 2))); // NOLINT
void esp_log_vprintf_(int level, const char *tag, int line, const char *format, va_list args); // NOLINT
#if defined(USE_ESP32)
int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
@@ -78,9 +86,50 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#define ESPHOME_LOG_FORMAT(format) format
#endif
#define ESPHOME_LOG_ARGS_(level, tag, format, ...) \
::esphome::esp_log_printf_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format), __VA_ARGS__)
// The format check is a statement-level if (false), not sizeof: GCC 16 skips format checks in unevaluated or folded
// expressions. __builtin_strchr folds on a literal, so only a line with '%' (such as "100%%") is formatted.
#ifdef USE_ESP8266
// F() only takes a literal, so using format more than once cannot repeat a side effect
#define ESPHOME_LOG_NO_ARGS_(level, tag, format) \
({ \
if (false) \
::esphome::esp_log_format_check_(format); \
if (__builtin_strchr(format, '%') != nullptr) \
::esphome::esp_log_printf_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format)); \
else \
::esphome::esp_log_str_(level, tag, __LINE__, ESPHOME_LOG_FORMAT(format)); \
})
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
// A function argument, so format is evaluated once and a temporary such as std::string().c_str() outlives the call
// NOLINTNEXTLINE(readability-identifier-naming)
inline void __attribute__((always_inline)) esp_log_no_args_(int level, const char *tag, int line, const char *format) {
if (__builtin_strchr(format, '%') != nullptr) {
esp_log_printf_(level, tag, line, format);
} else {
esp_log_str_(level, tag, line, format);
}
}
#pragma GCC diagnostic pop
#define ESPHOME_LOG_NO_ARGS_(level, tag, format) \
({ \
if (false) \
::esphome::esp_log_format_check_(format); \
::esphome::esp_log_no_args_(level, tag, __LINE__, format); \
})
#endif
// ESPHOME_LOG_NO_ARGS_ when there are no arguments after the format, ESPHOME_LOG_ARGS_ otherwise
#define ESPHOME_LOG_PICK_(skip, name, ...) name
#define ESPHOME_LOG_(level, tag, format, ...) \
ESPHOME_LOG_PICK_(__VA_OPT__(, ) ESPHOME_LOG_ARGS_, ESPHOME_LOG_NO_ARGS_)(level, tag, \
format __VA_OPT__(, ) __VA_ARGS__)
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
#define esph_log_vv(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_vv(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_VERY_VERBOSE, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_VERY_VERBOSE
#else
@@ -88,8 +137,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#endif
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
#define esph_log_v(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_VERBOSE, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_v(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_VERBOSE, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_VERBOSE
#else
@@ -97,10 +145,8 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#endif
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
#define esph_log_d(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_DEBUG, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_config(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_CONFIG, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_d(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_DEBUG, tag, format, __VA_ARGS__)
#define esph_log_config(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_CONFIG, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_DEBUG
#define ESPHOME_LOG_HAS_CONFIG
@@ -110,8 +156,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#endif
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
#define esph_log_i(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_i(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_INFO, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_INFO
#else
@@ -119,8 +164,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#endif
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_WARN
#define esph_log_w(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_WARN, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_w(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_WARN, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_WARN
#else
@@ -128,8 +172,7 @@ int esp_idf_log_vprintf_(const char *format, va_list args); // NOLINT
#endif
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_ERROR
#define esph_log_e(tag, format, ...) \
::esphome::esp_log_printf_(ESPHOME_LOG_LEVEL_ERROR, tag, __LINE__, ESPHOME_LOG_FORMAT(format), ##__VA_ARGS__)
#define esph_log_e(tag, format, ...) ESPHOME_LOG_(ESPHOME_LOG_LEVEL_ERROR, tag, format, __VA_ARGS__)
#define ESPHOME_LOG_HAS_ERROR
#else
+53 -44
View File
@@ -68,38 +68,6 @@ 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,
@@ -168,35 +136,76 @@ def test_log_v2_only_on_native_toolchain(
@pytest.mark.parametrize(
("config", "expected"),
("config", "port", "zephyr_cdc_loop"),
[
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.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_esp32_usb_serial_jtag.yaml",
{"USB_SERIAL_JTAG"},
"USB_SERIAL_JTAG",
False,
id="esp32_usb_serial_jtag",
),
pytest.param("test_logger_nrf52_usb_cdc.yaml", {"USB_CDC"}, id="nrf52_usb_cdc"),
pytest.param(
"test_logger_nrf52_usb_cdc.yaml", "USB_CDC", True, id="nrf52_usb_cdc"
),
# Zephyr polls the USB port only when it logs there
pytest.param(
"test_logger_nrf52_usb_cdc_no_serial.yaml", set(), id="nrf52_no_serial"
"test_logger_nrf52_usb_cdc_no_serial.yaml",
"USB_CDC",
False,
id="nrf52_no_serial",
),
],
)
def test_uart_selection_defines(
generate_main: Callable[[str | Path], str],
config: str,
expected: set[str],
port: str,
zephyr_cdc_loop: bool,
) -> None:
"""USB ports get a selection define, which gates their port code and crash replay."""
"""The chosen port is fixed at build time: one flag, its enum value and its dump_config name."""
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.name.removeprefix(prefix) for d in CORE.defines if d.name.startswith(prefix)
} == expected
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"'
def test_log_listener_slots_count_every_listener(
@@ -0,0 +1,9 @@
---
esphome:
name: test
esp8266:
board: d1_mini_lite
logger:
baud_rate: 0
@@ -0,0 +1,9 @@
---
esphome:
name: test
esp8266:
board: d1_mini_lite
logger:
hardware_uart: UART0_SWAP
@@ -0,0 +1,39 @@
esphome:
name: test
esp8266:
board: esp01_1m
button:
# Declared before the selects, so the action is generated before them
- platform: template
id: early
name: Early
on_press:
- select.set:
id: fan
option: high
- select.set:
id: fan
option: turbo
- select.set:
id: fan
option: !lambda return "low";
- select.set:
id: fan_copy
option: medium
select:
- platform: template
id: fan
name: Fan
optimistic: true
options: [low, medium, high]
on_value:
- select.set:
id: fan
option: medium
- platform: copy
id: fan_copy
name: Fan Copy
source_id: fan
@@ -0,0 +1,35 @@
---
esphome:
name: toshiba-test
esp32:
board: esp32dev
remote_transmitter:
pin: GPIO4
carrier_duty_percent: 50%
non_blocking: true
climate:
- platform: toshiba
id: ras
name: RAS
model: RAS-25J2KVSG-ND
- platform: toshiba
id: generic
name: Generic
select:
- platform: toshiba
toshiba_id: ras
power_selection:
id: power
name: Power selection
button:
- platform: template
name: Set
on_press:
- select.set:
id: power
option: Silent 1
@@ -0,0 +1,47 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
spi:
- id: spi_bus
clk_pin: GPIO18
mosi_pin: GPIO23
display:
- platform: mipi_spi
spi_id: spi_bus
model: st7789v
id: tft_display
dimensions:
width: 240
height: 320
cs_pin: GPIO22
dc_pin: GPIO21
auto_clear_enabled: false
invert_colors: false
update_interval: never
lvgl:
displays: tft_display
widgets:
- dropdown:
id: dropdown_widget
options: [low, high]
select:
- platform: lvgl
id: lv_fan
name: LVGL Fan
widget: dropdown_widget
button:
- platform: template
name: Set
on_press:
- select.set:
id: lv_fan
option: high
@@ -0,0 +1,43 @@
"""A constant select.set option of a select with a fixed option list becomes its index."""
from collections.abc import Callable
from pathlib import Path
def _call(select_id: str, statement: str) -> str:
return f"auto apply_call = ::{select_id}->make_call();\n apply_call.{statement};"
def test_select_set_constant_uses_index(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("select_set.yaml"))
# Generated before the select, and from the select's own on_value
assert _call("fan", "set_index(2)") in main_cpp
assert _call("fan", "set_index(1)") in main_cpp
assert 'set_option("high"' not in main_cpp
# Not an option: the lookup by text still logs it at run time
assert _call("fan", 'set_option("turbo", 5)') in main_cpp
# A lambda's value is only known at run time
assert _call("fan", 'set_option("low")') in main_cpp
# A copy select gets its options at run time
assert _call("fan_copy", 'set_option("medium", 6)') in main_cpp
def test_select_set_lvgl_keeps_lookup_by_text(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Lvgl dropdown options can be replaced at run time, so the index is not fixed."""
main_cpp = generate_main(component_config_path("select_set_lvgl.yaml"))
assert _call("lv_fan", 'set_option("high", 4)') in main_cpp
def test_select_set_hub_select_uses_index(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("select_set_hub.yaml"))
assert _call("power", "set_index(3)") in main_cpp
+23
View File
@@ -1,4 +1,5 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <cstring>
@@ -271,6 +272,28 @@ TEST(BufAppendStrP, AppendsAndTruncates) {
EXPECT_EQ(pos, 7u);
}
// --- progmem_copy_str() ---
TEST(ProgmemCopyStr, CopiesUpToTheNullOrTheEndAtEveryAlignment) {
static constexpr char TEXT[] = "0123456789abcdefghij";
constexpr size_t len = sizeof(TEXT) - 1;
for (size_t offset = 0; offset < 4; offset++) {
// Reads whole aligned words, so the source is a zero padded copy
alignas(4) char src[32] = {};
memcpy(src + offset, TEXT, sizeof(TEXT));
for (size_t room = 0; room <= len + 2; room++) {
SCOPED_TRACE(::testing::Message() << "offset " << offset << " room " << room);
char dst[32];
memset(dst, '#', sizeof(dst));
const char *const end = progmem_copy_str(dst, dst + room, src + offset);
const size_t copied = std::min(room, len);
EXPECT_EQ(end, dst + copied);
EXPECT_EQ(memcmp(dst, TEXT, copied), 0);
EXPECT_EQ(dst[copied], '#'); // No terminator written
}
}
}
// --- base64 encode/decode ---
static const char BASE64_ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -0,0 +1,140 @@
#include <gtest/gtest.h>
#include <cstdarg>
#include <cstring>
#include <string>
#include <thread>
#include <vector>
#include "esphome/components/logger/log_buffer.h"
#include "esphome/components/logger/logger.h"
#include "esphome/core/log.h"
namespace esphome::logger::testing {
ESPHOME_LOG_TAG(PLAIN_TAG, "plain.test");
static void format_into(LogBuffer &buf, const char *format, ...) {
va_list args;
va_start(args, format);
buf.format_body(format, args);
va_end(args);
}
TEST(UnformattedLogTest, BodyMatchesFormattedBodyAtEverySize) {
const std::string long_text(100, 'y');
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++) {
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];
memset(formatted, '#', sizeof(formatted));
memset(unformatted, '#', sizeof(unformatted));
memset(flash, '#', sizeof(flash));
LogBuffer a{formatted, size, start};
LogBuffer b{unformatted, size, start};
LogBuffer c{flash, size, start};
format_into(a, "%s", text);
b.write_unformatted_body(text, strlen(text));
// The flash copy reads whole aligned words, so give it a zero padded copy
alignas(4) char padded[128] = {};
char *const in_flash = padded + (start & 3);
memcpy(in_flash, text, strlen(text) + 1);
c.write_unformatted_body_p(in_flash);
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;
ASSERT_EQ(memcmp(formatted, unformatted, used), 0);
ASSERT_EQ(memcmp(formatted, flash, used), 0);
}
}
}
}
struct PlainLine {
uint8_t level;
std::string message;
};
static void capture_plain(void *instance, uint8_t level, const char *tag, const char *message, size_t len) {
static_cast<std::vector<PlainLine> *>(instance)->push_back({level, std::string(message, len)});
}
class UnformattedLoggerTest : public ::testing::Test {
protected:
void SetUp() override {
this->previous_ = global_logger;
this->logger_.pre_setup();
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_DEBUG);
this->logger_.add_log_callback(&this->lines_, capture_plain);
}
void TearDown() override { global_logger = this->previous_; }
Logger *previous_{nullptr};
Logger logger_{0};
std::vector<PlainLine> lines_;
};
TEST_F(UnformattedLoggerTest, LineWithoutArgumentsMatchesFormattedLine) {
esp_log_str_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "no arguments here\n");
esp_log_printf_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "%s", "no arguments here\n");
ASSERT_EQ(this->lines_.size(), 2u);
EXPECT_EQ(this->lines_[0].level, ESPHOME_LOG_LEVEL_INFO);
EXPECT_EQ(this->lines_[0].message, this->lines_[1].message);
EXPECT_NE(this->lines_[0].message.find("[I][plain.test:007]: no arguments here\033[0m"), std::string::npos)
<< this->lines_[0].message;
}
TEST_F(UnformattedLoggerTest, PercentSignIsStillFormatted) {
ESP_LOGW(PLAIN_TAG, "100%% done");
ASSERT_EQ(this->lines_.size(), 1u);
EXPECT_NE(this->lines_[0].message.find("]: 100% done"), std::string::npos) << this->lines_[0].message;
}
TEST_F(UnformattedLoggerTest, FormatExpressionIsEvaluatedOnce) {
const char *const messages[] = {"first", "second"};
int index = 0;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
ESP_LOGW(PLAIN_TAG, messages[index++]);
#pragma GCC diagnostic pop
EXPECT_EQ(index, 1);
ASSERT_EQ(this->lines_.size(), 1u);
EXPECT_NE(this->lines_[0].message.find("]: first"), std::string::npos) << this->lines_[0].message;
}
TEST_F(UnformattedLoggerTest, TemporaryFormatOutlivesTheCall) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-security"
ESP_LOGW(PLAIN_TAG, std::string(80, 'x').c_str());
#pragma GCC diagnostic pop
ASSERT_EQ(this->lines_.size(), 1u);
EXPECT_NE(this->lines_[0].message.find("]: " + std::string(80, 'x')), std::string::npos) << this->lines_[0].message;
}
TEST_F(UnformattedLoggerTest, LevelIsStillFiltered) {
this->logger_.set_log_level(ESPHOME_LOG_LEVEL_WARN);
ESP_LOGI(PLAIN_TAG, "hidden");
ESP_LOGW(PLAIN_TAG, "shown");
ASSERT_EQ(this->lines_.size(), 1u);
EXPECT_EQ(this->lines_[0].level, ESPHOME_LOG_LEVEL_WARN);
}
#ifdef USE_HOST
TEST_F(UnformattedLoggerTest, WorkerThreadLineGoesThroughTaskBuffer) {
this->logger_.create_pthread_key();
std::thread worker([]() { esp_log_str_(ESPHOME_LOG_LEVEL_INFO, PLAIN_TAG, 7, "from a worker"); });
worker.join();
EXPECT_TRUE(this->lines_.empty());
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
this->logger_.loop();
ASSERT_EQ(this->lines_.size(), 1u);
EXPECT_NE(this->lines_[0].message.find("from a worker"), std::string::npos) << this->lines_[0].message;
#endif
}
#endif // USE_HOST
} // namespace esphome::logger::testing
@@ -10,6 +10,7 @@ namespace {
constexpr uint8_t OLD_AP[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};
constexpr uint8_t NEW_AP[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x02};
constexpr uint8_t NO_AP[6] = {};
ExpectedDisconnect armed() {
ExpectedDisconnect expected;
@@ -20,20 +21,20 @@ ExpectedDisconnect armed() {
TEST(ExpectedDisconnectTest, PreviousApLeaveIsExpectedOnce) {
auto expected = armed();
EXPECT_TRUE(expected.consume_disconnect(OLD_AP, true));
EXPECT_EQ(expected.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_AP);
EXPECT_FALSE(expected.is_previous_ap(OLD_AP));
// A second leave from the same AP is a real disconnect
EXPECT_FALSE(expected.consume_disconnect(OLD_AP, true));
EXPECT_EQ(expected.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
}
TEST(ExpectedDisconnectTest, OtherDisconnectsAreRealAndEndTheExpectation) {
auto other_ap = armed();
EXPECT_FALSE(other_ap.consume_disconnect(NEW_AP, true));
EXPECT_FALSE(other_ap.consume_disconnect(OLD_AP, true));
EXPECT_EQ(other_ap.consume_disconnect(NEW_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
EXPECT_EQ(other_ap.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
auto other_reason = armed();
EXPECT_FALSE(other_reason.consume_disconnect(OLD_AP, false));
EXPECT_FALSE(other_reason.consume_disconnect(OLD_AP, true));
EXPECT_EQ(other_reason.consume_disconnect(OLD_AP, false), ExpectedLeave::EXPECTED_LEAVE_NONE);
EXPECT_EQ(other_reason.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
}
TEST(ExpectedDisconnectTest, QueuedConnectionFromPreviousApKeepsTheExpectation) {
@@ -41,17 +42,17 @@ TEST(ExpectedDisconnectTest, QueuedConnectionFromPreviousApKeepsTheExpectation)
EXPECT_TRUE(expected.is_previous_ap(OLD_AP));
EXPECT_FALSE(expected.is_previous_ap(NEW_AP));
EXPECT_TRUE(expected.consume_disconnect(OLD_AP, true));
EXPECT_EQ(expected.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_AP);
}
TEST(ExpectedDisconnectTest, NothingIsExpectedUnlessArmed) {
ExpectedDisconnect expected;
EXPECT_FALSE(expected.is_previous_ap(OLD_AP));
EXPECT_FALSE(expected.consume_disconnect(OLD_AP, true));
EXPECT_EQ(expected.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
auto cleared = armed();
cleared.clear();
EXPECT_FALSE(cleared.consume_disconnect(OLD_AP, true));
EXPECT_EQ(cleared.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
}
// Stands in for esp_wifi_sta_get_ap_info() and esp_wifi_disconnect(): the AP record is gone after disconnecting
@@ -82,16 +83,7 @@ TEST(ExpectedDisconnectTest, DisconnectExpectsTheLeaveOfTheApItLeft) {
Driver driver;
EXPECT_TRUE(disconnect(expected, driver));
EXPECT_TRUE(expected.consume_disconnect(OLD_AP, true));
}
TEST(ExpectedDisconnectTest, NoApMeansNoExpectation) {
ExpectedDisconnect expected;
Driver driver;
driver.has_ap = false;
EXPECT_TRUE(disconnect(expected, driver));
EXPECT_FALSE(expected.consume_disconnect(OLD_AP, true));
EXPECT_EQ(expected.consume_disconnect(OLD_AP, true), ExpectedLeave::EXPECTED_LEAVE_AP);
}
TEST(ExpectedDisconnectTest, FailedDisconnectExpectsNothing) {
@@ -106,5 +98,29 @@ TEST(ExpectedDisconnectTest, FailedDisconnectExpectsNothing) {
EXPECT_FALSE(expected.is_previous_ap(NEW_AP));
}
TEST(ExpectedDisconnectTest, DisconnectWithoutApExpectsTheAttemptsLeave) {
ExpectedDisconnect expected;
Driver driver;
driver.has_ap = false;
EXPECT_TRUE(disconnect(expected, driver));
// A real AP never matches the attempt's zero BSSID
EXPECT_FALSE(expected.is_previous_ap(NEW_AP));
// The driver reports the attempt as left, with no BSSID, after the next one starts
EXPECT_EQ(expected.consume_disconnect(NO_AP, true), ExpectedLeave::EXPECTED_LEAVE_ATTEMPT);
EXPECT_EQ(expected.consume_disconnect(NO_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
}
TEST(ExpectedDisconnectTest, AttemptLeaveExpectationEndsOnARealFailure) {
ExpectedDisconnect expected;
Driver driver;
driver.has_ap = false;
EXPECT_TRUE(disconnect(expected, driver));
// A probe failure of the new attempt is real, and nothing stays expected after it
EXPECT_EQ(expected.consume_disconnect(NO_AP, false), ExpectedLeave::EXPECTED_LEAVE_NONE);
EXPECT_EQ(expected.consume_disconnect(NO_AP, true), ExpectedLeave::EXPECTED_LEAVE_NONE);
}
} // namespace
} // namespace esphome::wifi::testing
-1
View File
@@ -17,7 +17,6 @@ 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
@@ -0,0 +1,62 @@
esphome:
name: select-set-constant
host:
api:
logger:
globals:
- id: next_option
type: std::string
initial_value: '"low"'
select:
- platform: template
name: "Fan"
id: fan
optimistic: true
options: [low, medium, high]
initial_option: low
- platform: template
name: "Picked"
id: picked
options: [low, medium, high]
update_interval: never
lambda: return id(next_option);
set_action:
- lambda: id(next_option) = std::string(x.c_str(), x.size());
button:
- platform: template
name: "Set High"
on_press:
- select.set:
id: fan
option: high
- platform: template
name: "Set Medium"
on_press:
- select.set:
id: fan
option: medium
- platform: template
name: "Set Invalid"
on_press:
- select.set:
id: fan
option: turbo
- platform: template
name: "Pick High"
on_press:
- lambda: id(next_option) = "high";
- component.update: picked
- platform: template
name: "Pick Invalid"
on_press:
- lambda: id(next_option) = "turbo";
- component.update: picked
- platform: template
name: "Pick Medium"
on_press:
- lambda: id(next_option) = "medium";
- component.update: picked
@@ -0,0 +1,50 @@
"""select.set with a constant option and a template select lambda, both set by index."""
from __future__ import annotations
from aioesphomeapi import SelectInfo, SelectState
import pytest
from .log_utils import LineWaiter
from .state_utils import press_and_wait, require_entity, subscribe_after_initial_states
from .types import APIClientConnectedFactory, RunCompiledFunction
from .wait_utils import wait_or_fail
@pytest.mark.asyncio
async def test_select_set_constant(
yaml_config: str,
run_compiled: RunCompiledFunction,
api_client_connected: APIClientConnectedFactory,
) -> None:
waiter_log = LineWaiter()
invalid_lambda = waiter_log.expect("'Picked': Invalid option turbo")
# An unknown constant keeps the lookup by text and its warning, never a compiled index
invalid_constant = waiter_log.expect("'Fan' - No option set")
out_of_bounds = waiter_log.expect("out of bounds")
async with (
run_compiled(yaml_config, line_callback=waiter_log.callback),
api_client_connected() as client,
):
entities, _ = await client.list_entities_services()
fan = require_entity(entities, "fan", SelectInfo, exact=True)
picked = require_entity(entities, "picked", SelectInfo, exact=True)
sub = await subscribe_after_initial_states(client, entities)
async def press(button: str, key: int) -> str:
state = await press_and_wait(
client, entities, sub.waiter, button, SelectState, key=key
)
return state.state
assert await press("set_high", fan.key) == "high"
# An option the select does not have changes nothing; the next press is the next state
client.button_command(require_entity(entities, "set_invalid").key)
assert await press("set_medium", fan.key) == "medium"
await wait_or_fail(invalid_constant, 5.0, "invalid constant was not logged")
assert not out_of_bounds.done()
assert await press("pick_high", picked.key) == "high"
client.button_command(require_entity(entities, "pick_invalid").key)
await wait_or_fail(invalid_lambda, 5.0, "invalid lambda option was not logged")
assert await press("pick_medium", picked.key) == "medium"
@@ -326,6 +326,21 @@ def test_bind_key__rejects_non_hex_pair_length() -> None:
cv.bind_key("0123456789ABCDEF0123456789ABCDE")
@pytest.mark.parametrize(
"value",
(
" A A A A A A A A A A A A A A A A",
"0123456789ABCDEF0123456789ABCD-B",
"+E123456789ABCDEF0123456789ABCDE",
),
)
def test_bind_key__rejects_sign_padded_pairs(value: str) -> None:
# int(part, 16) accepts surrounding whitespace and a +/- sign, which would
# silently validate a key different from the one the user typed.
with pytest.raises(Invalid, match="hex values"):
cv.bind_key(value)
def test_bind_key__direct_call_with_name_validates_with_that_name() -> None:
# Passing both a value and a name validates immediately using the custom
# name for error wording, and still tags the result sensitive.