Compare commits

...
Author SHA1 Message Date
J. Nick Koston 5e39b7f0bd Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 23:57:50 -06:00
J. Nick Koston e155c4ab07 Build improv_ble with web_server so its URL path compiles 2026-11-16 23:57:50 -06:00
J. Nick Koston 8c11a3ba7d Say when console_write() can write fewer bytes 2026-11-16 23:57:47 -06:00
J. Nick Koston 8484a1be7c Build improv over a USB Serial/JTAG logger on ESP32-C3 2026-11-16 23:39:03 -06:00
J. Nick Koston edfaeea190 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 23:18:54 -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 bebcd26d60 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 23:05:25 -06:00
J. Nick Koston 18eff452ba Say where request_console() does nothing 2026-11-16 23:05:22 -06:00
J. Nick Koston 42a965ad19 Build improv over a USB_CDC logger on ESP32-C3 2026-11-16 22:54:55 -06:00
J. Nick Koston eb701a1c79 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 22:54:06 -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 fb0ffad906 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 22:53:40 -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 cc813ee330 Request the console on every platform but Zephyr, parametrize the transport tests 2026-11-16 22:33:36 -06:00
J. Nick Koston 69710b9126 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 22:29:34 -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 5b3d40fcb9 Merge branch 'logger-console-api' into improv-serial-simplify 2026-11-16 22:23:29 -06:00
J. Nick Koston 3cee50f683 Merge remote-tracking branch 'upstream/dev' into logger-console-api 2026-11-16 22:17:34 -06:00
J. Nick Koston fa6ebbb564 Check the error frame for a bad checksum 2026-11-16 13:07:34 -06:00
J. Nick Koston 8a70438e28 Test that nRF52 Improv requests no console 2026-11-16 13:07:34 -06:00
J. Nick Koston 1c11d8006a Test the console transport selection, the full frame buffer and parser recovery 2026-11-16 13:07:34 -06:00
J. Nick Koston 7252d59dcd Use the improv library types, one frame buffer, and keep nRF52 builds compiling 2026-11-16 13:07:34 -06:00
J. Nick Koston 1159fec2d9 Drop a comment that restates the code 2026-11-16 13:07:34 -06:00
J. Nick Koston a8342605d4 [improv_serial] Use the logger console API and drop RAM held between sessions 2026-11-16 13:07:34 -06: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
29 changed files with 548 additions and 505 deletions

No files matched your search

+18 -1
View File
@@ -4,12 +4,29 @@
#include "esphome/components/network/util.h"
#include "esphome/core/application.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::improv_base {
#ifdef USE_IMPROV_NEXT_URL
#if defined(USE_IMPROV_NEXT_URL) || defined(USE_WEBSERVER)
ESPHOME_LOG_TAG(TAG, "improv_base");
#endif
#ifdef USE_WEBSERVER
void ImprovBase::add_webserver_url_(improv::RpcResponseBuilder &builder, const network::IPAddress &ip) {
char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
ip.str_to(ip_buf);
// "http://" (7) + IP (40) + ":" (1) + port (5) + null (1) = 54
char webserver_url[7 + network::IP_ADDRESS_BUFFER_SIZE + 1 + 5 + 1];
size_t len = buf_append_printf(webserver_url, sizeof(webserver_url), 0, "http://%s:%u", ip_buf, USE_WEBSERVER_PORT);
if (!builder.add_string(webserver_url, len)) {
ESP_LOGW(TAG, "Response full; URL dropped");
}
}
#endif
#ifdef USE_IMPROV_NEXT_URL
static constexpr const char DEVICE_NAME_PLACEHOLDER[] = "{{device_name}}";
static constexpr size_t DEVICE_NAME_PLACEHOLDER_LEN = sizeof(DEVICE_NAME_PLACEHOLDER) - 1;
+8 -1
View File
@@ -3,9 +3,12 @@
#include <cstddef>
#include "esphome/core/defines.h"
#ifdef USE_IMPROV_NEXT_URL
#if defined(USE_IMPROV_NEXT_URL) || defined(USE_WEBSERVER)
#include <improv.h>
#endif
#ifdef USE_WEBSERVER
#include "esphome/components/network/ip_address.h"
#endif
namespace esphome::improv_base {
@@ -23,6 +26,10 @@ class ImprovBase {
void add_next_url_(improv::RpcResponseBuilder &builder, size_t max_len);
const char *next_url_{nullptr};
#endif
#ifdef USE_WEBSERVER
/// Append "http://<ip>:<port>" to the response, warning if it does not fit.
void add_webserver_url_(improv::RpcResponseBuilder &builder, const network::IPAddress &ip);
#endif
};
} // namespace esphome::improv_base
@@ -457,15 +457,7 @@ void ImprovBLEComponent::check_wifi_connection_() {
#ifdef USE_WEBSERVER
for (auto &ip : wifi::global_wifi_component->wifi_sta_ip_addresses()) {
if (ip.is_ip4()) {
char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
ip.str_to(ip_buf);
// "http://" (7) + IP (40) + ":" (1) + port (5) + null (1) = 54
char webserver_url[7 + network::IP_ADDRESS_BUFFER_SIZE + 1 + 5 + 1];
size_t len =
buf_append_printf(webserver_url, sizeof(webserver_url), 0, "http://%s:%u", ip_buf, USE_WEBSERVER_PORT);
if (!builder.add_string(webserver_url, len)) {
ESP_LOGW(TAG, "Response full; URL dropped");
}
this->add_webserver_url_(builder, ip);
break;
}
}
+5 -2
View File
@@ -1,7 +1,7 @@
import esphome.codegen as cg
from esphome.components import improv_base, uart
from esphome.components.esp32 import VARIANT_ESP32S3, get_esp32_variant
from esphome.components.logger import DOMAIN as LOGGER_DOMAIN, USB_CDC
from esphome.components.logger import DOMAIN as LOGGER_DOMAIN, USB_CDC, request_console
import esphome.config_validation as cv
from esphome.const import CONF_BAUD_RATE, CONF_HARDWARE_UART, CONF_ID, CONF_UART_ID
from esphome.core import CORE
@@ -34,7 +34,7 @@ CONFIG_SCHEMA = (
_UART_FINAL_VALIDATE = uart.final_validate_device_schema(
"improv_serial", require_tx=True, require_rx=True
DOMAIN, require_tx=True, require_rx=True
)
@@ -70,3 +70,6 @@ async def to_code(config: ConfigType) -> None:
if (uart_id := config.get(CONF_UART_ID)) is not None:
await cg.add_variable(var.set_uart, uart_id)
cg.add_define("USE_IMPROV_SERIAL_UART")
# The Zephyr logger has no console, so Improv there stays a no-op
elif not CORE.using_zephyr:
request_console()
@@ -20,26 +20,36 @@ ESPHOME_LOG_TAG(TAG, "improv_serial");
static constexpr uint32_t WIFI_CONNECT_TIMEOUT_ID = 0;
static constexpr uint8_t FRAME_PREFIX[] PROGMEM = {'I', 'M', 'P', 'R', 'O', 'V', improv::IMPROV_SERIAL_VERSION};
static_assert(sizeof(FRAME_PREFIX) + 2 == FRAME_HEADER_SIZE, "type and length follow the prefix");
#if defined(USE_NETWORK_PRIMARY_INTERFACE_WIFI) && defined(USE_WIFI)
static constexpr bool WIFI_URL_FIRST = true;
#else
static constexpr bool WIFI_URL_FIRST = false;
#endif
/// Fill the frame header and return its checksum.
static uint8_t write_header(uint8_t *frame, improv::ImprovSerialType type, uint8_t length) {
progmem_memcpy(frame, FRAME_PREFIX, sizeof(FRAME_PREFIX));
frame[FRAME_HEADER_SIZE - 2] = type;
frame[FRAME_HEADER_SIZE - 1] = length;
return sum_bytes(frame, FRAME_HEADER_SIZE);
}
void ImprovSerialComponent::setup() {
global_improv_serial_component = this;
#ifdef USE_IMPROV_SERIAL_UART
// Transport is a dedicated UART bus set via set_uart() in generated code
#elif defined(USE_ESP32)
this->uart_num_ = logger::global_logger->get_uart_num();
this->uart_selection_ = logger::global_logger->get_uart();
#elif defined(USE_ARDUINO)
this->hw_serial_ = logger::global_logger->get_hw_serial();
#endif
// The Improv state machine tracks Wi-Fi provisioning only. General device
// connectivity (e.g. Ethernet) is reported separately via GET_NETWORK_STATE.
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr && wifi::global_wifi_component->has_sta()) {
auto *wifi = wifi::global_wifi_component;
if (wifi != nullptr && wifi->has_sta()) {
this->state_ = improv::STATE_PROVISIONED;
} else if (wifi::global_wifi_component != nullptr && !wifi::global_wifi_component->is_disabled()) {
} else if (wifi != nullptr && !wifi->is_disabled()) {
// Respect Wi-Fi's disabled state; forcing a scan while disabled throws
// the wifi component into an invalid state from which it cannot recover.
wifi::global_wifi_component->start_scanning();
wifi->start_scanning();
}
#endif
}
@@ -48,33 +58,30 @@ void ImprovSerialComponent::loop() {
const uint32_t now = App.get_loop_component_start_time();
if (this->last_read_byte_ && (now - this->last_read_byte_ > IMPROV_SERIAL_TIMEOUT)) {
this->last_read_byte_ = 0;
this->rx_buffer_.clear();
this->reset_rx_buffer_();
ESP_LOGV(TAG, "Timeout");
}
while (true) {
auto byte = this->read_byte_();
if (!byte.has_value())
break;
if (this->parse_improv_serial_byte_(byte.value())) {
uint8_t byte;
while (this->read_byte_(byte)) {
if (this->parse_improv_serial_byte_(byte)) {
this->last_read_byte_ = now;
} else {
this->last_read_byte_ = 0;
this->rx_buffer_.clear();
this->reset_rx_buffer_();
}
}
#ifdef USE_WIFI
if (this->state_ == improv::STATE_PROVISIONING && wifi::global_wifi_component != nullptr &&
wifi::global_wifi_component->is_connected()) {
auto *wifi = wifi::global_wifi_component;
if (this->state_ == improv::STATE_PROVISIONING && wifi != nullptr && wifi->is_connected()) {
// Being connected is not enough: re-provisioning a device that is already online leaves the
// prior network up until it drops, so check that the joined network is the requested one
// before reporting success. Same test as the wifi.connect action.
char ssid_buf[wifi::SSID_BUFFER_SIZE];
if (strcmp(wifi::global_wifi_component->wifi_ssid_to(ssid_buf), this->connecting_sta_.get_ssid().c_str()) == 0) {
wifi::global_wifi_component->save_wifi_sta(this->connecting_sta_.get_ssid(),
this->connecting_sta_.get_password());
this->connecting_sta_ = {};
if (strcmp(wifi->wifi_ssid_to(ssid_buf), this->connecting_sta_->get_ssid().c_str()) == 0) {
wifi->save_wifi_sta(this->connecting_sta_->get_ssid(), this->connecting_sta_->get_password());
this->connecting_sta_.reset();
this->cancel_timeout(WIFI_CONNECT_TIMEOUT_ID);
this->set_state_(improv::STATE_PROVISIONED);
@@ -86,72 +93,6 @@ void ImprovSerialComponent::loop() {
void ImprovSerialComponent::dump_config() { ESP_LOGCONFIG(TAG, "Improv Serial:"); }
void ImprovSerialComponent::write_data_(const uint8_t *data, const size_t size) {
// First, set length field
this->tx_header_[TX_LENGTH_IDX] = this->tx_header_[TX_TYPE_IDX] == TYPE_RPC_RESPONSE ? size : 1;
const bool there_is_data = data != nullptr && size > 0;
// If there_is_data, checksum must not include our optional data byte
const uint8_t header_checksum_len = there_is_data ? TX_BUFFER_SIZE - 3 : TX_BUFFER_SIZE - 2;
// Only transmit the full buffer length if there is no data (only state/error byte is provided in this case)
const uint8_t header_tx_len = there_is_data ? TX_BUFFER_SIZE - 3 : TX_BUFFER_SIZE;
uint8_t checksum = sum_bytes(this->tx_header_, header_checksum_len);
if (there_is_data) {
checksum = sum_bytes(data, size, checksum);
}
this->tx_header_[TX_CHECKSUM_IDX] = checksum;
#ifdef USE_IMPROV_SERIAL_UART
this->uart_->write_array(this->tx_header_, header_tx_len);
if (there_is_data) {
this->uart_->write_array(data, size);
this->uart_->write_array(&this->tx_header_[TX_CHECKSUM_IDX], 2); // Footer: checksum and newline
}
#elif defined(USE_ESP32)
switch (this->uart_selection_) {
case logger::UART_SELECTION_UART0:
case logger::UART_SELECTION_UART1:
#if defined(USE_ESP32_VARIANT_ESP32)
case logger::UART_SELECTION_UART2:
#endif
uart_write_bytes(this->uart_num_, this->tx_header_, header_tx_len);
if (there_is_data) {
uart_write_bytes(this->uart_num_, data, size);
uart_write_bytes(this->uart_num_, &this->tx_header_[TX_CHECKSUM_IDX], 2); // Footer: checksum and newline
}
break;
#if defined(USE_LOGGER_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
case logger::UART_SELECTION_USB_CDC:
esp_usb_console_write_buf((const char *) this->tx_header_, header_tx_len);
if (there_is_data) {
esp_usb_console_write_buf((const char *) data, size);
esp_usb_console_write_buf((const char *) &this->tx_header_[TX_CHECKSUM_IDX],
2); // Footer: checksum and newline
}
break;
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case logger::UART_SELECTION_USB_SERIAL_JTAG:
usb_serial_jtag_write_bytes((const char *) this->tx_header_, header_tx_len, 20 / portTICK_PERIOD_MS);
if (there_is_data) {
usb_serial_jtag_write_bytes((const char *) data, size, 20 / portTICK_PERIOD_MS);
usb_serial_jtag_write_bytes((const char *) &this->tx_header_[TX_CHECKSUM_IDX], 2,
20 / portTICK_PERIOD_MS); // Footer: checksum and newline
}
break;
#endif
default:
break;
}
#elif defined(USE_ARDUINO)
this->hw_serial_->write(this->tx_header_, header_tx_len);
if (there_is_data) {
this->hw_serial_->write(data, size);
this->hw_serial_->write(&this->tx_header_[TX_CHECKSUM_IDX], 2); // Footer: checksum and newline
}
#endif
}
#ifdef USE_WEBSERVER
void ImprovSerialComponent::add_webserver_urls_(improv::RpcResponseBuilder &builder, [[maybe_unused]] bool wifi_first) {
// The webserver listens on every interface, so advertise each one that has a usable IPv4.
@@ -159,20 +100,10 @@ void ImprovSerialComponent::add_webserver_urls_(improv::RpcResponseBuilder &buil
// interface's addresses, which are all-unset (0.0.0.0) when e.g. Ethernet has no link while
// the device is online via Wi-Fi, and 0.0.0.0 must not become the advertised URL. OpenThread
// is omitted: it only ever has IPv6 addresses, which cannot form an IPv4 http:// URL.
const auto append_urls = [&builder](const network::IPAddresses &addresses) {
const auto append_urls = [this, &builder](const network::IPAddresses &addresses) {
for (const auto &ip : addresses) {
if (!ip.is_ip4() || !ip.is_set())
continue;
char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
ip.str_to(ip_buf);
// "http://" (7) + IP (40) + ":" (1) + port (5) + null (1) = 54
char webserver_url[7 + network::IP_ADDRESS_BUFFER_SIZE + 1 + 5 + 1];
// buf_append_printf keeps the format string in flash on ESP8266
size_t len =
buf_append_printf(webserver_url, sizeof(webserver_url), 0, "http://%s:%u", ip_buf, USE_WEBSERVER_PORT);
if (!builder.add_string(webserver_url, len)) {
ESP_LOGW(TAG, "Response full; URL dropped");
}
if (ip.is_ip4() && ip.is_set())
this->add_webserver_url_(builder, ip);
}
};
#ifdef USE_WIFI
@@ -260,39 +191,52 @@ void ImprovSerialComponent::send_version_info_() {
}
bool ImprovSerialComponent::parse_improv_serial_byte_(uint8_t byte) {
size_t at = this->rx_buffer_.size();
this->rx_buffer_.push_back(byte);
const size_t at = this->rx_len_;
ESP_LOGV(TAG, "Byte: 0x%02X", byte);
const uint8_t *raw = &this->rx_buffer_[0];
if (at == 0) {
// The parser's own first test; a stray byte then costs no heap block
if (byte != 'I')
return false;
this->rx_buffer_ = std::make_unique<uint8_t[]>(MAX_FRAME_SIZE);
} else if (at > FRAME_HEADER_SIZE && at > FRAME_HEADER_SIZE + this->rx_buffer_[FRAME_HEADER_SIZE - 1]) {
// Past the checksum, where the parser rejects the byte without reading it
return false;
}
this->rx_buffer_[at] = byte;
this->rx_len_ = at + 1;
return improv::parse_improv_serial_byte(
at, byte, raw, [this](improv::ImprovCommand command) -> bool { return this->parse_improv_payload_(command); },
at, byte, this->rx_buffer_.get(),
[this](improv::ImprovCommand command) -> bool { return this->parse_improv_payload_(command); },
[this](improv::Error error) -> void {
ESP_LOGW(TAG, "Error decoding payload");
this->set_error_(error);
this->send_state_byte_(improv::TYPE_ERROR_STATE, error);
});
}
bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command) {
#ifdef USE_WIFI
auto *wifi = wifi::global_wifi_component;
#endif
switch (command.command) {
case improv::WIFI_SETTINGS: {
#ifdef USE_WIFI
if (wifi::global_wifi_component == nullptr || wifi::global_wifi_component->is_disabled()) {
if (wifi == nullptr || wifi->is_disabled()) {
// Wi-Fi is disabled, so we can't provision. Respond immediately
// instead of letting the client wait out its provisioning timeout.
ESP_LOGW(TAG, "Wi-Fi is disabled; cannot provision");
this->set_error_(improv::ERROR_UNABLE_TO_CONNECT);
this->send_state_byte_(improv::TYPE_ERROR_STATE, improv::ERROR_UNABLE_TO_CONNECT);
return true;
}
wifi::WiFiAP sta{};
this->connecting_sta_ = std::make_unique<wifi::WiFiAP>();
auto &sta = *this->connecting_sta_;
sta.set_ssid(command.ssid.c_str());
sta.set_password(command.password.c_str());
this->connecting_sta_ = sta;
// Sampled before start_connecting(): the old connection drops asynchronously after it.
const bool switching = wifi::global_wifi_component->is_connected();
wifi::global_wifi_component->set_sta(sta);
wifi::global_wifi_component->start_connecting(sta);
const bool switching = wifi->is_connected();
wifi->set_sta(sta);
wifi->start_connecting(sta);
this->set_state_(improv::STATE_PROVISIONING);
ESP_LOGD(TAG, "Received settings: SSID=%s, password=" LOG_SECRET("%s"), command.ssid.c_str(),
command.password.c_str());
@@ -302,7 +246,7 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
#else
// No Wi-Fi support compiled in; there is nothing to provision.
ESP_LOGW(TAG, "Wi-Fi not supported; cannot provision");
this->set_error_(improv::ERROR_UNABLE_TO_CONNECT);
this->send_state_byte_(improv::TYPE_ERROR_STATE, improv::ERROR_UNABLE_TO_CONNECT);
#endif
return true;
}
@@ -312,10 +256,10 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
// offer a Wi-Fi form. General connectivity (e.g. Ethernet) is reported separately
// via GET_NETWORK_STATE.
#ifdef USE_WIFI
if (wifi::global_wifi_component == nullptr || wifi::global_wifi_component->is_disabled()) {
if (wifi == nullptr || wifi->is_disabled()) {
// Reported transiently without disturbing our internal provisioning state machine,
// so a later `wifi.enable` still reports the correct state.
this->send_current_state_(improv::STATE_STOPPED);
this->send_state_byte_(improv::TYPE_CURRENT_STATE, improv::STATE_STOPPED);
return true;
}
this->set_state_(this->state_);
@@ -323,7 +267,7 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
this->send_settings_response_(improv::GET_CURRENT_STATE);
}
#else
this->send_current_state_(improv::STATE_STOPPED);
this->send_state_byte_(improv::TYPE_CURRENT_STATE, improv::STATE_STOPPED);
#endif
return true;
}
@@ -335,7 +279,7 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
// Declared out here because the terminating empty response is sent with or without Wi-Fi
std::array<uint8_t, improv::RPC_RESPONSE_MAX_SIZE> buf;
#ifdef USE_WIFI
const auto &results = wifi::global_wifi_component->get_scan_result();
const auto &results = wifi->get_scan_result();
for (const auto &scan : results) {
bool with_auth = false;
if (!wifi::should_show_scan_entry(results, scan, with_auth))
@@ -387,20 +331,15 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
#ifdef USE_WEBSERVER
// Not tied to one interface, so follow the configured priority the way
// network::get_ip_addresses() does: a wifi-first network priority list leads with Wi-Fi.
if (flags & improv::NETWORK_IS_ONLINE) {
#if defined(USE_NETWORK_PRIMARY_INTERFACE_WIFI) && defined(USE_WIFI)
this->add_webserver_urls_(builder, /*wifi_first=*/true);
#else
this->add_webserver_urls_(builder, /*wifi_first=*/false);
#endif
}
if (flags & improv::NETWORK_IS_ONLINE)
this->add_webserver_urls_(builder, WIFI_URL_FIRST);
#endif
this->send_response_(builder.finish(false));
return true;
}
default: {
ESP_LOGW(TAG, "Unknown payload");
this->set_error_(improv::ERROR_UNKNOWN_RPC);
this->send_state_byte_(improv::TYPE_ERROR_STATE, improv::ERROR_UNKNOWN_RPC);
return false;
}
}
@@ -408,19 +347,16 @@ bool ImprovSerialComponent::parse_improv_payload_(improv::ImprovCommand &command
void ImprovSerialComponent::set_state_(improv::State state) {
this->state_ = state;
this->send_current_state_(state);
this->send_state_byte_(improv::TYPE_CURRENT_STATE, state);
}
void ImprovSerialComponent::send_current_state_(improv::State state) {
this->tx_header_[TX_TYPE_IDX] = TYPE_CURRENT_STATE;
this->tx_header_[TX_DATA_IDX] = state;
this->write_data_();
}
void ImprovSerialComponent::set_error_(improv::Error error) {
this->tx_header_[TX_TYPE_IDX] = TYPE_ERROR_STATE;
this->tx_header_[TX_DATA_IDX] = error;
this->write_data_();
void ImprovSerialComponent::send_state_byte_(improv::ImprovSerialType type, uint8_t value) {
uint8_t frame[FRAME_HEADER_SIZE + 3];
const uint8_t checksum = write_header(frame, type, 1) + value;
frame[FRAME_HEADER_SIZE] = value;
frame[FRAME_HEADER_SIZE + 1] = checksum;
frame[FRAME_HEADER_SIZE + 2] = '\n';
this->write_(frame, sizeof(frame));
}
void ImprovSerialComponent::send_response_(std::span<const uint8_t> response) {
@@ -428,16 +364,22 @@ void ImprovSerialComponent::send_response_(std::span<const uint8_t> response) {
if (response.size() > MAX_SERIAL_RESPONSE) {
ESP_LOGE(TAG, "Response too long");
// Fail fast instead of leaving the client to wait out its timeout
this->set_error_(improv::ERROR_UNKNOWN);
this->send_state_byte_(improv::TYPE_ERROR_STATE, improv::ERROR_UNKNOWN);
return;
}
this->tx_header_[TX_TYPE_IDX] = TYPE_RPC_RESPONSE;
this->write_data_(response.data(), response.size());
uint8_t header[FRAME_HEADER_SIZE];
const uint8_t footer[2] = {
sum_bytes(response.data(), response.size(), write_header(header, improv::TYPE_RPC_RESPONSE, response.size())),
'\n'};
this->write_(header, sizeof(header));
this->write_(response.data(), response.size());
this->write_(footer, sizeof(footer));
}
#ifdef USE_WIFI
void ImprovSerialComponent::on_wifi_connect_timeout_() {
this->set_error_(improv::ERROR_UNABLE_TO_CONNECT);
this->connecting_sta_.reset();
this->send_state_byte_(improv::TYPE_ERROR_STATE, improv::ERROR_UNABLE_TO_CONNECT);
this->set_state_(improv::STATE_AUTHORIZED);
ESP_LOGW(TAG, "Timed out while connecting to Wi-Fi network");
wifi::global_wifi_component->clear_sta();
@@ -8,8 +8,8 @@
#include "esphome/core/helpers.h"
#ifdef USE_IMPROV_SERIAL
#include <improv.h>
#include <memory>
#include <span>
#include <vector>
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
@@ -17,51 +17,26 @@
#ifdef USE_IMPROV_SERIAL_UART
#include "esphome/components/uart/uart_component.h"
#elif defined(USE_ESP32)
#include <driver/uart.h>
#ifdef USE_LOGGER_USB_SERIAL_JTAG
#include <driver/usb_serial_jtag.h>
#include <hal/usb_serial_jtag_ll.h>
#endif
#if defined(USE_ESP32_VARIANT_ESP32S2) || defined(USE_ESP32_VARIANT_ESP32S3)
#include <esp_private/usb_console.h>
#endif
#elif defined(USE_ARDUINO)
#include <HardwareSerial.h>
#endif
namespace esphome::improv_serial {
// TX buffer layout constants
static constexpr uint8_t TX_HEADER_SIZE = 6; // Bytes 0-5 = "IMPROV"
static constexpr uint8_t TX_VERSION_IDX = 6;
static constexpr uint8_t TX_TYPE_IDX = 7;
static constexpr uint8_t TX_LENGTH_IDX = 8;
static constexpr uint8_t TX_DATA_IDX = 9; // For state/error messages only
static constexpr uint8_t TX_CHECKSUM_IDX = 10;
static constexpr uint8_t TX_NEWLINE_IDX = 11;
static constexpr uint8_t TX_BUFFER_SIZE = 12;
enum ImprovSerialType : uint8_t {
TYPE_CURRENT_STATE = 0x01,
TYPE_ERROR_STATE = 0x02,
TYPE_RPC = 0x03,
TYPE_RPC_RESPONSE = 0x04
};
static const uint16_t IMPROV_SERIAL_TIMEOUT = 100;
static const uint8_t IMPROV_SERIAL_VERSION = 1;
static constexpr uint16_t IMPROV_SERIAL_TIMEOUT = 100;
// "IMPROV", version, type, length
static constexpr size_t FRAME_HEADER_SIZE = 9;
#ifdef USE_WIFI
// Wi-Fi connect failure timers: a fresh provision reports at 30 s (stock behavior), while
// switching networks on an already-connected device (disconnect + reconnect) can legitimately
// take longer; 90 s matches improv_ble's default wifi_timeout.
static const uint32_t WIFI_CONNECT_TIMEOUT_MS = 30000;
static const uint32_t WIFI_SWITCH_TIMEOUT_MS = 90000;
static constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 30000;
static constexpr uint32_t WIFI_SWITCH_TIMEOUT_MS = 90000;
#endif
// The serial frame length field is one byte
static constexpr size_t MAX_SERIAL_RESPONSE = 255;
// Header, payload, checksum
static constexpr size_t MAX_FRAME_SIZE = FRAME_HEADER_SIZE + MAX_SERIAL_RESPONSE + 1;
// command + data length + trailing byte
static constexpr size_t RPC_RESPONSE_OVERHEAD = 3;
static constexpr size_t MAX_SERIAL_PAYLOAD = MAX_SERIAL_RESPONSE - RPC_RESPONSE_OVERHEAD;
@@ -92,10 +67,14 @@ class ImprovSerialComponent final : public Component, public improv_base::Improv
protected:
bool parse_improv_serial_byte_(uint8_t byte);
bool parse_improv_payload_(improv::ImprovCommand &command);
/// Free the frame buffer; a session holds it only while a frame is arriving.
void reset_rx_buffer_() {
this->rx_buffer_.reset();
this->rx_len_ = 0;
}
void set_state_(improv::State state);
void send_current_state_(improv::State state);
void set_error_(improv::Error error);
void send_state_byte_(improv::ImprovSerialType type, uint8_t value);
void send_response_(std::span<const uint8_t> response);
#ifdef USE_WIFI
void on_wifi_connect_timeout_();
@@ -109,88 +88,35 @@ class ImprovSerialComponent final : public Component, public improv_base::Improv
void send_settings_response_(improv::Command command);
void send_version_info_();
ESPHOME_ALWAYS_INLINE optional<uint8_t> read_byte_() {
optional<uint8_t> byte;
uint8_t data = 0;
ESPHOME_ALWAYS_INLINE bool read_byte_(uint8_t &byte) {
#ifdef USE_IMPROV_SERIAL_UART
if (this->uart_->available() && this->uart_->read_byte(&data)) {
byte = data;
}
#elif defined(USE_ESP32)
switch (this->uart_selection_) {
case logger::UART_SELECTION_UART0:
case logger::UART_SELECTION_UART1:
#if defined(USE_ESP32_VARIANT_ESP32)
case logger::UART_SELECTION_UART2:
return this->uart_->available() && this->uart_->read_byte(&byte);
#elif defined(USE_LOGGER_CONSOLE)
return logger::global_logger->console_read(byte);
#else
return false;
#endif
}
ESPHOME_ALWAYS_INLINE void write_(const uint8_t *data, size_t len) {
#ifdef USE_IMPROV_SERIAL_UART
this->uart_->write_array(data, len);
#elif defined(USE_LOGGER_CONSOLE)
logger::global_logger->console_write(data, len);
#endif
if (this->uart_num_ >= 0) {
size_t available;
uart_get_buffered_data_len(this->uart_num_, &available);
if (available) {
uart_read_bytes(this->uart_num_, &data, 1, 0);
byte = data;
}
}
break;
#if defined(USE_LOGGER_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
case logger::UART_SELECTION_USB_CDC:
if (esp_usb_console_available_for_read()) {
esp_usb_console_read_buf((char *) &data, 1);
byte = data;
}
break;
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case logger::UART_SELECTION_USB_SERIAL_JTAG: {
if (usb_serial_jtag_read_bytes((char *) &data, 1, 0)) {
byte = data;
}
break;
}
#endif
default:
break;
}
#elif defined(USE_ARDUINO)
if (this->hw_serial_->available()) {
this->hw_serial_->readBytes(&data, 1);
byte = data;
}
#endif
return byte;
}
void write_data_(const uint8_t *data = nullptr, size_t size = 0);
uint8_t tx_header_[TX_BUFFER_SIZE] = {
'I', // 0: Header
'M', // 1: Header
'P', // 2: Header
'R', // 3: Header
'O', // 4: Header
'V', // 5: Header
IMPROV_SERIAL_VERSION, // 6: Version
0, // 7: ImprovSerialType
0, // 8: Length
0, // 9...X: Data (here, one byte reserved for state/error)
0, // X + 10: Checksum
'\n',
};
#ifdef USE_IMPROV_SERIAL_UART
uart::UARTComponent *uart_{nullptr};
#elif defined(USE_ESP32)
uart_port_t uart_num_;
logger::UARTSelection uart_selection_{logger::UART_SELECTION_UART0};
#elif defined(USE_ARDUINO)
Stream *hw_serial_{nullptr};
#endif
std::vector<uint8_t> rx_buffer_;
std::unique_ptr<uint8_t[]> rx_buffer_;
uint32_t last_read_byte_{0};
#ifdef USE_WIFI
wifi::WiFiAP connecting_sta_;
// Only held while provisioning
std::unique_ptr<wifi::WiFiAP> connecting_sta_;
#endif
improv::State state_{improv::STATE_AUTHORIZED};
uint16_t rx_len_{0};
};
extern ImprovSerialComponent
+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 -3
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_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
}
@@ -278,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();
@@ -371,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"
+35 -10
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.
@@ -251,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_();
@@ -411,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) {
+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
Whitespace-only changes.
@@ -0,0 +1,20 @@
esphome:
name: test
esp8266:
board: d1_mini
logger:
wifi:
ssid: test
password: testtesttest
uart:
id: improv_uart
tx_pin: 4
rx_pin: 5
baud_rate: 115200
improv_serial:
uart_id: improv_uart
@@ -0,0 +1,13 @@
esphome:
name: test
esp8266:
board: d1_mini
logger:
wifi:
ssid: test
password: testtesttest
improv_serial: {}
@@ -0,0 +1,16 @@
esphome:
name: test
nrf52:
board: adafruit_itsybitsy_nrf52840
bootloader: adafruit_nrf52_sd140_v6
logger:
network:
enable_ipv6: true
openthread:
tlv: 0E080000000000010000
improv_serial: {}
@@ -0,0 +1,34 @@
"""Tests for the improv_serial transport selection."""
from collections.abc import Callable
from pathlib import Path
import pytest
from esphome.core import CORE
@pytest.mark.parametrize(
("config", "console", "uart"),
[
# Without uart_id, Improv shares the logger's port through its console API
pytest.param("improv_logger_port.yaml", True, False, id="logger_port"),
# A dedicated UART leaves the logger's console API out
pytest.param("improv_dedicated_uart.yaml", False, True, id="dedicated_uart"),
# The Zephyr logger has no console, so Improv there is a no-op
pytest.param("improv_nrf52.yaml", False, False, id="nrf52"),
],
)
def test_transport_defines(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
config: str,
console: bool,
uart: bool,
) -> None:
"""Each transport compiles in only the code it uses."""
generate_main(component_config_path(config))
defines = {d.name for d in CORE.defines}
assert ("USE_LOGGER_CONSOLE" in defines) is console
assert ("USE_IMPROV_SERIAL_UART" in defines) is uart
+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,5 @@
packages:
improv_ble: !include common.yaml
web_server:
port: 80
@@ -0,0 +1,8 @@
wifi:
ssid: MySSID
password: password1
logger:
hardware_uart: USB_SERIAL_JTAG
improv_serial:
@@ -0,0 +1,2 @@
packages:
improv_serial: !include common-usb_cdc.yaml
@@ -0,0 +1,2 @@
packages:
improv_serial: !include common-usb_serial_jtag.yaml
-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
+40 -3
View File
@@ -10,10 +10,15 @@ Covered:
2. Get Device Info returns the firmware/device info RPC response
3. Get Wi-Fi Networks returns deduplicated scan results and a terminator
4. Wi-Fi Settings provisions: saves credentials and reports PROVISIONED
Between 1 and 2, a 255 byte payload, malformed input and a frame cut off past
the timeout must each leave the parser ready for the next request.
"""
from __future__ import annotations
import asyncio
import pytest
from .log_utils import LineWaiter
@@ -24,6 +29,7 @@ from .types import APIClientConnectedFactory, RunCompiledFunction
IMPROV_HEADER = b"IMPROV"
IMPROV_VERSION = 1
TYPE_CURRENT_STATE = 0x01
TYPE_ERROR_STATE = 0x02
TYPE_RPC = 0x03
TYPE_RPC_RESPONSE = 0x04
@@ -33,6 +39,9 @@ CMD_GET_DEVICE_INFO = 0x03
CMD_GET_WIFI_NETWORKS = 0x04
CMD_WIFI_SETTINGS = 0x01
# improv::Error values
ERROR_INVALID_RPC = 0x01
def build_rpc_frame(command: int, data: bytes = b"") -> list[int]:
"""Build a full improv serial frame carrying one RPC command."""
@@ -42,9 +51,9 @@ def build_rpc_frame(command: int, data: bytes = b"") -> list[int]:
return list(frame + bytes([checksum]) + b"\n")
def state_frame_hex(state: int) -> str:
"""Full 12 byte current-state frame as hex, checksum and newline included."""
frame = IMPROV_HEADER + bytes([IMPROV_VERSION, TYPE_CURRENT_STATE, 1, state])
def state_frame_hex(state: int, frame_type: int = TYPE_CURRENT_STATE) -> str:
"""Full 12 byte one-value frame as hex, checksum and newline included."""
frame = IMPROV_HEADER + bytes([IMPROV_VERSION, frame_type, 1, state])
checksum = sum(frame) & 0xFF
return ":".join(f"{b:02X}" for b in frame + bytes([checksum]) + b"\n")
@@ -89,6 +98,34 @@ async def test_improv_serial_uart(
)
await waiter.wait_for("uart_mock", f"TX 12 bytes: {state_frame_hex(0x02)}")
authorized = f"TX 12 bytes: {state_frame_hex(0x02)}"
get_state = build_rpc_frame(CMD_GET_CURRENT_STATE)
# The largest payload (255 bytes) fills the fixed frame buffer exactly
reply = waiter.expect(authorized)
await client.execute_service(
inject, {"payload": build_rpc_frame(CMD_GET_CURRENT_STATE, bytes(253))}
)
await waiter.wait(reply, msg="no reply to a 255 byte payload")
# A bad checksum is reported, and the next frame parses from the start
bad = get_state.copy()
bad[-2] ^= 0xFF
error = waiter.expect(
f"TX 12 bytes: {state_frame_hex(ERROR_INVALID_RPC, TYPE_ERROR_STATE)}"
)
reply = waiter.expect(authorized)
await client.execute_service(inject, {"payload": bad + get_state})
await waiter.wait(error, msg="no error frame for a bad checksum")
await waiter.wait(reply, msg="no reply after a bad checksum")
# A frame cut off for longer than the 100 ms timeout is discarded
await client.execute_service(inject, {"payload": get_state[:8]})
await asyncio.sleep(0.3)
reply = waiter.expect(authorized)
await client.execute_service(inject, {"payload": get_state})
await waiter.wait(reply, msg="no reply after a timed out frame")
# 2. Get Device Info: the always logged 9 byte response header, then the
# payload with the firmware name (must stay under uart_mock's 64 byte
# hex dump cap or the payload line reads "too large to log")