mirror of
https://github.com/esphome/esphome.git
synced 2026-11-17 18:46:08 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
84079c07e2 | ||
|
|
b7dbf17469 | ||
|
|
b91750c325 | ||
|
|
92d2a457fa | ||
|
|
a1fecebb09 | ||
|
|
32b9d4cbe7 | ||
|
|
c53401a28d | ||
|
|
6b7d17c762 | ||
|
|
93a3306d82 | ||
|
|
54d3477240 | ||
|
|
5f9d83d293 | ||
|
|
43864283b4 | ||
|
|
4efbb38b86 | ||
|
|
045374965f | ||
|
|
39a939720f | ||
|
|
a79e51e784 | ||
|
|
517f0d6d48 | ||
|
|
1327d0ddc5 | ||
|
|
2adb544e7a | ||
|
|
48905beb96 | ||
|
|
ed401814bf | ||
|
|
0245db6285 | ||
|
|
07ee0f9f04 | ||
|
|
3d34ad572b |
No files matched your search
@@ -48,7 +48,7 @@ PROJECT_NAME = ESPHome
|
||||
# could be handy for archiving the generated documentation or if some version
|
||||
# control system is used.
|
||||
|
||||
PROJECT_NUMBER = 2026.11.0b4
|
||||
PROJECT_NUMBER = 2026.11.0b6
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ RUN \
|
||||
-r /requirements.txt
|
||||
|
||||
# Install the ESPHome Device Builder dashboard.
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.26.0
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.28.1
|
||||
|
||||
RUN \
|
||||
platformio settings set enable_telemetry No \
|
||||
|
||||
@@ -452,7 +452,8 @@ message DeviceWizardRequest {
|
||||
//
|
||||
// {"version": 1,
|
||||
// "pages": [{"title": "...", "description": "...",
|
||||
// "entities": [{"key": 123, "device_id": 456, "description": "...", "role": "..."}],
|
||||
// "entities": [{"key": 123, "platform": "sensor", "device_id": 456,
|
||||
// "description": "...", "role": "..."}],
|
||||
// "inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
// "entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
// "device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
@@ -465,6 +466,10 @@ message DeviceWizardRequest {
|
||||
// An entity is an entity of this device that the page shows to the user (for example to
|
||||
// turn it on or off). Its key is the key ListEntitiesResponse sends for it. Its
|
||||
// device_id is the device_id ListEntitiesResponse sends, and is left out when that is 0.
|
||||
// Its platform is the platform of the entity (sensor, switch and so on; date, time or
|
||||
// datetime for a datetime entity). A key is only unique within its platform and device, so
|
||||
// a client matches an entity by platform, device_id and key together. A client that does
|
||||
// not know platform ignores it, so the version stays 1.
|
||||
// Its role, when set, is a stable name that the device's firmware gives the entity
|
||||
// (always <component>.<name>), so a client can recognise it. The user cannot change it,
|
||||
// and no two entities of a wizard share one.
|
||||
|
||||
@@ -784,8 +784,9 @@ class APIConnection final : public APIServerConnectionBase {
|
||||
}
|
||||
|
||||
// Helper function to schedule a high priority message at the front of the batch
|
||||
// Out-of-line: callers (on_shutdown, check_keepalive_) are cold paths
|
||||
// Out-of-line: callers (send_shutdown_disconnect_, check_keepalive_) are cold paths
|
||||
bool schedule_message_front_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size);
|
||||
void send_shutdown_disconnect_();
|
||||
|
||||
// Helper function to log client messages with name and peername
|
||||
void log_client_(int level, const LogString *message);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <cerrno>
|
||||
#include <cinttypes>
|
||||
#include "api_connection.h"
|
||||
#include "api_connection_buffer.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/defines.h"
|
||||
@@ -794,6 +795,31 @@ void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &imag
|
||||
}
|
||||
#endif
|
||||
|
||||
// Kept out of api_connection.cpp so GCC inlines its send path as before
|
||||
void APIConnection::send_shutdown_disconnect_() {
|
||||
#ifndef USE_DEEP_SLEEP
|
||||
// Queued states first: Home Assistant mishandles states after DisconnectRequest (#22610).
|
||||
// Not with deep sleep: its entities stay available, and the disconnect must not wait on a slow link
|
||||
this->flags_.state_subscription = false;
|
||||
this->destroy_active_iterator_();
|
||||
// process_batch_ first flushes any overflow without blocking; stop once the queue stops shrinking
|
||||
for (size_t left = this->deferred_batch_.size(); left != 0;) {
|
||||
this->process_batch_();
|
||||
const size_t now_left = this->deferred_batch_.size();
|
||||
if (now_left >= left)
|
||||
break;
|
||||
left = now_left;
|
||||
}
|
||||
#endif
|
||||
DisconnectRequest req;
|
||||
if (!this->send_message(req)) {
|
||||
// tx buffer full: first in the queue, so a slow link still delivers it before the teardown timeout.
|
||||
// Due at once: teardown does not advance the cached loop time the batch_delay gate reads
|
||||
this->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
|
||||
this->make_batch_due_now_();
|
||||
}
|
||||
}
|
||||
|
||||
void APIServer::on_shutdown() {
|
||||
this->shutting_down_ = true;
|
||||
|
||||
@@ -806,15 +832,8 @@ void APIServer::on_shutdown() {
|
||||
// Change batch delay to 5ms for quick flushing during shutdown
|
||||
this->batch_delay_ = 5;
|
||||
|
||||
// Send disconnect requests to all connected clients
|
||||
for (auto &c : this->active_clients()) {
|
||||
DisconnectRequest req;
|
||||
if (!c->send_message(req)) {
|
||||
// If we can't send the disconnect request directly (tx_buffer full),
|
||||
// schedule it at the front of the batch so it will be sent with priority
|
||||
c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
|
||||
}
|
||||
}
|
||||
for (auto &c : this->active_clients())
|
||||
c->send_shutdown_disconnect_();
|
||||
}
|
||||
|
||||
bool APIServer::teardown() {
|
||||
|
||||
@@ -257,6 +257,47 @@ WIZARD_DOMAIN_LIMITED_PLATFORMS = (
|
||||
)
|
||||
|
||||
|
||||
# The C++ base class of each kind of entity a wizard page can show, and the platform an API client
|
||||
# knows it by. An entity key is only unique within its platform, so the wizard sends both.
|
||||
WIZARD_ENTITY_PLATFORMS: dict[str, str] = {
|
||||
"alarm_control_panel::AlarmControlPanel": "alarm_control_panel",
|
||||
"binary_sensor::BinarySensor": "binary_sensor",
|
||||
"button::Button": "button",
|
||||
"climate::Climate": "climate",
|
||||
"cover::Cover": "cover",
|
||||
"datetime::DateEntity": "date",
|
||||
"datetime::DateTimeEntity": "datetime",
|
||||
"datetime::TimeEntity": "time",
|
||||
"event::Event": "event",
|
||||
"fan::Fan": "fan",
|
||||
"infrared::Infrared": "infrared",
|
||||
"light::LightState": "light",
|
||||
"lock::Lock": "lock",
|
||||
"number::Number": "number",
|
||||
"radio_frequency::RadioFrequency": "radio_frequency",
|
||||
"select::Select": "select",
|
||||
"sensor::Sensor": "sensor",
|
||||
"switch_::Switch": "switch",
|
||||
"text::Text": "text",
|
||||
"text_sensor::TextSensor": "text_sensor",
|
||||
"update::UpdateEntity": "update",
|
||||
"valve::Valve": "valve",
|
||||
"water_heater::WaterHeater": "water_heater",
|
||||
}
|
||||
|
||||
|
||||
def _wizard_entity_platform(
|
||||
config: fv.FinalValidateConfig, entity_id: ID
|
||||
) -> str | None:
|
||||
"""The platform of an entity, from the C++ class it is declared with, as some entities are not
|
||||
declared under their platform (the sensors of gps:, for example)."""
|
||||
declared: ID = config.get_config_for_path(config.get_path_for_id(entity_id))
|
||||
for cls in (declared.type, *declared.type.parents):
|
||||
if (platform := WIZARD_ENTITY_PLATFORMS.get(str(cls))) is not None:
|
||||
return platform
|
||||
return None
|
||||
|
||||
|
||||
def wizard_input_ids(api_config: ConfigType) -> set[str]:
|
||||
"""The IDs of the entities that are linked inputs of the wizard in the given api config."""
|
||||
if (wizard := api_config.get(CONF_WIZARD)) is None:
|
||||
@@ -361,7 +402,8 @@ def _validate_wizard_input(conf: ConfigType) -> ConfigType:
|
||||
|
||||
|
||||
def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
"""Reject entities that are internal, as they are not exposed over the API, or have no name.
|
||||
"""Reject entities that are internal, as they are not exposed over the API, have no name, or
|
||||
are of a platform the wizard does not know.
|
||||
|
||||
The key a client knows an entity by is a hash of its name. Without a name of its own, the
|
||||
device works the name out at runtime from its friendly name, which can add the MAC address,
|
||||
@@ -378,6 +420,10 @@ def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
f"Entity '{value.id}' has no name of its own, so its key is not known "
|
||||
"when the wizard is built. Give it a name to use it in the wizard"
|
||||
)
|
||||
if _wizard_entity_platform(fv.full_config.get(), value) is None:
|
||||
raise cv.Invalid(
|
||||
f"Entity '{value.id}' is not of a platform the wizard can show"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
@@ -446,7 +492,10 @@ def _entity_document(
|
||||
) -> ConfigType:
|
||||
"""An entity of the device that the page shows, keyed as ListEntitiesResponse keys it."""
|
||||
_, declaration = _wizard_input_declaration(config, conf[CONF_ID])
|
||||
document: ConfigType = {"key": fnv1_hash_object_id(declaration[CONF_NAME])}
|
||||
document: ConfigType = {
|
||||
"key": fnv1_hash_object_id(declaration[CONF_NAME]),
|
||||
"platform": _wizard_entity_platform(config, conf[CONF_ID]),
|
||||
}
|
||||
if (device := declaration.get(CONF_DEVICE_ID)) is not None:
|
||||
document["device_id"] = fnv1a_32bit_hash(device.id)
|
||||
if description := conf.get(CONF_DESCRIPTION):
|
||||
@@ -476,7 +525,8 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
|
||||
{"version": 1,
|
||||
"pages": [{"title": "...", "description": "...",
|
||||
"entities": [{"key": 123, "device_id": 456, "description": "...", "role": "..."}],
|
||||
"entities": [{"key": 123, "platform": "sensor", "device_id": 456,
|
||||
"description": "...", "role": "..."}],
|
||||
"inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
"entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
"device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
@@ -487,6 +537,10 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
- An entity key is the key ListEntitiesResponse sends for the entity: the FNV-1 hash of the
|
||||
object id made from its name (entity_helpers). device_id is the hash of the ESPHome id of
|
||||
the device it belongs to (esphome/core/config.py), and is left out for the main device.
|
||||
- An entity platform is the platform of the entity: sensor, switch and so on, or date, time or
|
||||
datetime for an entity of the datetime component. A key is only unique within its platform
|
||||
and device, so a client matches an entity by platform, device_id and key together. A client
|
||||
that does not know platform ignores it, so the version stays 1.
|
||||
- An entity role is a stable name, always <component>.<name>, that the component of the entity
|
||||
gives it with register_entity_role, so Home Assistant can recognise the entity. The user
|
||||
cannot set or change it, and no two entities of a wizard share one. A client that does not
|
||||
|
||||
@@ -35,15 +35,23 @@ async def to_code(config: ConfigType) -> None:
|
||||
add_idf_component(name="esp32async/asynctcp", ref="3.4.91")
|
||||
elif CORE.is_libretiny:
|
||||
# https://github.com/ESP32Async/AsyncTCP
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.4.5")
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.5.0")
|
||||
# AsyncTCP 3.5.0 debug logs call xPortGetCoreID(), which LibreTiny (single core) lacks; they are compiled
|
||||
# in by LibreTiny's debug level or CONFIG_ASYNC_TCP_DEBUG, so the call always expands to int(), which is 0
|
||||
# (a function-like -D does not survive PlatformIO's build flags)
|
||||
cg.add_build_flag("-DxPortGetCoreID=int")
|
||||
elif CORE.is_esp8266:
|
||||
# https://github.com/ESP32Async/ESPAsyncTCP
|
||||
cg.add_library("ESP32Async/ESPAsyncTCP", "2.0.0")
|
||||
elif CORE.is_rp2:
|
||||
# https://github.com/ayushsharma82/RPAsyncTCP
|
||||
# RPAsyncTCP is a drop-in replacement for AsyncTCP_RP2040W with better
|
||||
# ESPAsyncWebServer compatibility
|
||||
cg.add_library("ayushsharma82/RPAsyncTCP", "1.3.2")
|
||||
# https://github.com/esphome-libs/RPAsyncTCP, a fork of ayushsharma82/RPAsyncTCP
|
||||
# 1.3.2 that counts queued bytes before lwIP can send and ACK them, so
|
||||
# canSend() does not stay false and SSE streams do not stall (wired Ethernet)
|
||||
cg.add_library(
|
||||
"RPAsyncTCP",
|
||||
"1.3.2",
|
||||
"https://github.com/esphome-libs/RPAsyncTCP#1.3.2-esphome.1",
|
||||
)
|
||||
# Other platforms (host, etc) use socket-based implementation
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef USE_ESP32
|
||||
#include <esp_err.h>
|
||||
@@ -136,6 +137,18 @@ inline void fill_128bit_uuid_array(std::array<uint64_t, 2> &out, const ble_devic
|
||||
out[1] = 0x800000805F9B34FBULL; // Base UUID bytes 0-7
|
||||
}
|
||||
|
||||
/// A 128-bit UUID in big-endian (printable) order, as its 16 or 32-bit form when it is on the Bluetooth base UUID.
|
||||
inline ble_device_base::ESPBTUUID uuid_from_be128(const uint8_t *uuid128) {
|
||||
using ble_device_base::ESPBTUUID;
|
||||
// 0000xxxx-0000-1000-8000-00805F9B34FB without its first 4 bytes
|
||||
static constexpr uint8_t BASE_UUID_TAIL[12] = {0x00, 0x00, 0x10, 0x00, 0x80, 0x00,
|
||||
0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
|
||||
if (memcmp(uuid128 + 4, BASE_UUID_TAIL, sizeof(BASE_UUID_TAIL)) != 0)
|
||||
return ESPBTUUID::from_raw_reversed(uuid128);
|
||||
const uint32_t value = encode_uint32(uuid128[0], uuid128[1], uuid128[2], uuid128[3]);
|
||||
return value <= UINT16_MAX ? ESPBTUUID::from_uint16(value) : ESPBTUUID::from_uint32(value);
|
||||
}
|
||||
|
||||
/// Fill the UUID in the appropriate wire format based on client support and
|
||||
/// UUID type (128-bit array for old clients or 128-bit UUIDs, short form
|
||||
/// otherwise).
|
||||
|
||||
@@ -16,7 +16,6 @@ namespace esphome::bluetooth_connection {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "bluetooth_connection");
|
||||
|
||||
using ble_device_base::ESPBTUUID;
|
||||
using ble_device_base::GATT_ERR_NOT_CONNECTED;
|
||||
using ble_device_base::GATT_ERR_NO_MEMORY;
|
||||
|
||||
@@ -63,14 +62,6 @@ btstack_packet_callback_registration_t RP2GattClient::sm_event_registration = {}
|
||||
RP2GattClient *RP2GattClient::connect_owner = nullptr;
|
||||
// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
static ESPBTUUID uuid_from_btstack(uint16_t uuid16, const uint8_t uuid128[16]) {
|
||||
if (uuid16 != 0) {
|
||||
return ESPBTUUID::from_uint16(uuid16);
|
||||
}
|
||||
// BTstack structs carry the 128-bit form big-endian (printable order).
|
||||
return ESPBTUUID::from_raw_reversed(uuid128);
|
||||
}
|
||||
|
||||
void RP2GattClient::setup() {
|
||||
// Pre-create every pool entry so the packet handlers' allocate() calls are
|
||||
// always a free-list pop -- the IRQ path must never reach malloc().
|
||||
@@ -300,8 +291,9 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
}
|
||||
gatt_client_service_t service;
|
||||
gatt_event_service_query_result_get_service(packet, &service);
|
||||
// Not uuid16: BTstack stores a 32-bit base UUID there truncated to its low 16 bits
|
||||
auto &dst = this->arena_->services[this->service_count_];
|
||||
dst.uuid = uuid_from_btstack(service.uuid16, service.uuid128);
|
||||
dst.uuid = uuid_from_be128(service.uuid128);
|
||||
dst.start_handle = service.start_group_handle;
|
||||
dst.end_handle = service.end_group_handle;
|
||||
dst.first_characteristic = 0;
|
||||
@@ -320,7 +312,7 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
gatt_client_characteristic_t characteristic;
|
||||
gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
|
||||
auto &dst = this->arena_->characteristics[this->char_count_];
|
||||
dst.uuid = uuid_from_btstack(characteristic.uuid16, characteristic.uuid128);
|
||||
dst.uuid = uuid_from_be128(characteristic.uuid128);
|
||||
dst.value_handle = characteristic.value_handle;
|
||||
dst.end_handle = characteristic.end_handle;
|
||||
dst.properties = static_cast<uint8_t>(characteristic.properties);
|
||||
@@ -340,7 +332,7 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
gatt_client_characteristic_descriptor_t descriptor;
|
||||
gatt_event_all_characteristic_descriptors_query_result_get_characteristic_descriptor(packet, &descriptor);
|
||||
auto &dst = this->arena_->descriptors[this->desc_count_];
|
||||
dst.uuid = uuid_from_btstack(descriptor.uuid16, descriptor.uuid128);
|
||||
dst.uuid = uuid_from_be128(descriptor.uuid128);
|
||||
dst.handle = descriptor.handle;
|
||||
this->desc_count_++;
|
||||
break;
|
||||
|
||||
@@ -195,14 +195,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
}
|
||||
} else {
|
||||
uint16_t raw_humidity = encode_uint16(data[0], data[1]);
|
||||
uint16_t raw_temperature = encode_uint16(data[2], data[3]);
|
||||
|
||||
if (raw_temperature & 0x8000) {
|
||||
if (!(raw_temperature & 0x4000))
|
||||
raw_temperature = ~(raw_temperature & 0x7FFF);
|
||||
} else if (raw_temperature & 0x800) {
|
||||
raw_temperature |= 0xf000;
|
||||
}
|
||||
const int16_t raw_temperature = decode_dht22_temperature(encode_uint16(data[2], data[3]));
|
||||
|
||||
if (raw_temperature == 1 && raw_humidity == 10) {
|
||||
if (report_errors) {
|
||||
@@ -214,7 +207,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
*humidity = static_cast<float>(raw_humidity) * 0.1f;
|
||||
if (*humidity > 100.0f)
|
||||
*humidity = NAN;
|
||||
*temperature = static_cast<int16_t>(raw_temperature) * 0.1f;
|
||||
*temperature = raw_temperature * 0.1f;
|
||||
}
|
||||
|
||||
if (*temperature == 0.0f && (*humidity == 1.0f || *humidity == 2.0f)) {
|
||||
|
||||
@@ -17,6 +17,18 @@ enum DHTModel : uint8_t {
|
||||
DHT_MODEL_DHT22_TYPE2
|
||||
};
|
||||
|
||||
/// Convert a DHT22-family temperature reading to tenths of a degree. Sensors encode negative values in one of three
|
||||
/// ways: sign and magnitude (bit 15 set, bit 14 clear), 16-bit two's complement, or 12-bit two's complement (bit 11).
|
||||
inline int16_t decode_dht22_temperature(uint16_t raw) {
|
||||
if (raw & 0x8000) {
|
||||
if (!(raw & 0x4000))
|
||||
return static_cast<int16_t>(-static_cast<int16_t>(raw & 0x7FFF));
|
||||
} else if (raw & 0x800) {
|
||||
raw |= 0xF000;
|
||||
}
|
||||
return static_cast<int16_t>(raw);
|
||||
}
|
||||
|
||||
/// Component for reading temperature/humidity measurements from DHT11/DHT22 sensors.
|
||||
class DHT final : public PollingComponent {
|
||||
SUB_SENSOR(temperature)
|
||||
|
||||
@@ -30,7 +30,7 @@ void EPaperJD79660::fill(Color color) {
|
||||
|
||||
// We store 4 pixels per byte
|
||||
this->buffer_.fill(pixel_color | (pixel_color << 2) | (pixel_color << 4) | (pixel_color << 6));
|
||||
this->drawn_since_hash_ = true;
|
||||
this->mark_all_drawn_();
|
||||
}
|
||||
|
||||
void HOT EPaperJD79660::draw_pixel_at(int x, int y, Color color) {
|
||||
|
||||
@@ -232,7 +232,7 @@ void EPaperT133A01::fill(Color color) {
|
||||
}
|
||||
auto pixel_color = color_to_index(color);
|
||||
this->buffer_.fill(pixel_color + (pixel_color << 4));
|
||||
this->drawn_since_hash_ = true;
|
||||
this->mark_all_drawn_();
|
||||
}
|
||||
|
||||
void EPaperT133A01::draw_pixel_at(int x, int y, Color color) {
|
||||
|
||||
@@ -12,7 +12,12 @@ height of them; offset_height (under dimensions) is a property of the panel.
|
||||
from typing import Any
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA_RATE, CONF_DIMENSIONS, CONF_OFFSET_HEIGHT
|
||||
from esphome.const import (
|
||||
CONF_DATA_RATE,
|
||||
CONF_DIMENSIONS,
|
||||
CONF_HEIGHT,
|
||||
CONF_OFFSET_HEIGHT,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import EpaperModel, ultrachip_resolution
|
||||
@@ -39,10 +44,11 @@ class UC8279(EpaperModel):
|
||||
|
||||
def validate_config(self, config: ConfigType) -> ConfigType:
|
||||
_width, height = self.get_dimensions(config)
|
||||
# The models' defaults fit, so this fails only with explicit dimensions, which always have a height
|
||||
if self.get_offset_height(config) + height > 0xFFFF:
|
||||
raise cv.Invalid(
|
||||
f"{CONF_OFFSET_HEIGHT} plus the panel height must not exceed {0xFFFF} gates",
|
||||
path=[CONF_DIMENSIONS, CONF_OFFSET_HEIGHT],
|
||||
path=[CONF_DIMENSIONS, CONF_HEIGHT],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
@@ -37,7 +37,10 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
|
||||
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
|
||||
}
|
||||
__attribute__((always_inline)) inline void yield() { vPortYield(); }
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { vTaskDelay(ms / portTICK_PERIOD_MS); }
|
||||
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) {
|
||||
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
|
||||
}
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(esp_timer_get_time()); }
|
||||
uint32_t millis();
|
||||
__attribute__((always_inline)) inline uint64_t millis_64() {
|
||||
|
||||
@@ -33,34 +33,18 @@ IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); }
|
||||
|
||||
LwIPLock::LwIPLock() {
|
||||
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
// When CONFIG_LWIP_TCPIP_CORE_LOCKING is enabled, lwIP uses a global mutex to protect
|
||||
// its internal state. Any thread can take this lock to safely access lwIP APIs.
|
||||
//
|
||||
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) returns true if the current thread
|
||||
// already holds the lwIP core lock. This prevents recursive locking attempts and
|
||||
// allows nested LwIPLock instances to work correctly.
|
||||
//
|
||||
// If we don't already hold the lock, acquire it. This will block until the lock
|
||||
// is available if another thread currently holds it.
|
||||
// A thread that already holds the core lock (lwIP took it for a tcpip_api_call or netif callback, or an
|
||||
// outer LwIPLock did) must not take it again, and must not release it when this nested guard ends.
|
||||
if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
|
||||
LOCK_TCPIP_CORE();
|
||||
this->locked_ = true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
LwIPLock::~LwIPLock() {
|
||||
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
// Only release the lwIP core lock if this thread currently holds it.
|
||||
//
|
||||
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) queries lwIP's internal lock
|
||||
// ownership tracking. It returns true only if the current thread is registered
|
||||
// as the lock holder.
|
||||
//
|
||||
// This check is essential because:
|
||||
// 1. We may not have acquired the lock in the constructor (if we already held it)
|
||||
// 2. The lock might have been released by other means between constructor and destructor
|
||||
// 3. Calling UNLOCK_TCPIP_CORE() without holding the lock causes undefined behavior
|
||||
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
|
||||
if (this->locked_) {
|
||||
UNLOCK_TCPIP_CORE();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -567,30 +567,46 @@ async def to_code(config: ConfigType) -> None:
|
||||
|
||||
request_bluetooth()
|
||||
|
||||
# Replace Bluedroid's only two sscanf callers so newlib's scanf engine is not
|
||||
# linked; see bluedroid_hex_wraps.cpp. IDF 6.0+ uses picolibc, not newlib.
|
||||
if (
|
||||
not CORE.using_arduino
|
||||
and idf_version() < cv.Version(6, 0, 0)
|
||||
and get_esp32_variant() not in ROM_SSCANF_VARIANTS
|
||||
# Replace Bluedroid's only two sscanf callers so the C library's scanf engine is
|
||||
# not linked; see bluedroid_hex_wraps.cpp. The ROM only provides sscanf for newlib,
|
||||
# which IDF 6.0 replaced with picolibc.
|
||||
if not CORE.using_arduino and (
|
||||
idf_version() >= cv.Version(6, 0, 0)
|
||||
or get_esp32_variant() not in ROM_SSCANF_VARIANTS
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_HEX_WRAPS")
|
||||
_wrap_bluedroid_symbols("btc_config_get_bin", "string_to_bdaddr")
|
||||
# The headers only feed bluedroid_hex_wraps.cpp's ESP-IDF drift checks
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_hex_wraps.cpp"))
|
||||
|
||||
# ESP-IDF 5.5.6 drops bond keys on re-encryption (see bluedroid_bond_keys.c). Needs the
|
||||
# native toolchain for Bluedroid's private headers; Windows response files lose them.
|
||||
# ESP-IDF 5.5.6 and 6.1.1 drop bond keys on re-encryption (see bluedroid_bond_keys.c). Needs
|
||||
# the native toolchain for Bluedroid's private headers; Windows response files lose them.
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and not IS_WINDOWS
|
||||
and cv.Version(5, 5, 6) <= idf_version() < cv.Version(6, 0, 0)
|
||||
and _drops_bond_keys(idf_version())
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_BOND_KEYS")
|
||||
_wrap_bluedroid_symbols("smp_check_auth_req", "btm_sec_clear_ble_keys")
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_bond_keys.c"))
|
||||
|
||||
# ESP-IDF 5.5.6 and 6.0.3 end GATT discovery on a response listing handles out of order
|
||||
# Bluedroid runs a queued MTU or execute write request that fails at once again until the BTU task stack
|
||||
# overflows (see bluedroid_gattc_queue.c); every ESP-IDF release so far. Private headers, as above.
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and not IS_WINDOWS
|
||||
and _has_gatt_client(CORE.config)
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE")
|
||||
_wrap_bluedroid_symbols(
|
||||
"bta_gattc_cfg_mtu",
|
||||
"bta_gattc_execute",
|
||||
"GATTC_ConfigureMTU",
|
||||
"GATTC_ExecuteWrite",
|
||||
)
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_gattc_queue.c"))
|
||||
|
||||
# ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end GATT discovery on a response listing handles out of order
|
||||
# (see bluedroid_gattc_order.cpp). It needs no Bluedroid headers, so any toolchain works.
|
||||
if _has_gatt_client(CORE.config) and _has_strict_handle_order(idf_version()):
|
||||
cg.add_define("USE_ESP32_BLE_GATTC_HANDLE_ORDER")
|
||||
@@ -667,11 +683,23 @@ def _has_gatt_client(config: ConfigType) -> bool:
|
||||
return "esp32_ble_tracker" in config or "esp32_ble_client" in config
|
||||
|
||||
|
||||
def _has_strict_handle_order(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order."""
|
||||
def _drops_bond_keys(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF clears a bonded device's keys when it re-encrypts."""
|
||||
return cv.Version(5, 5, 6) <= version < cv.Version(
|
||||
6, 0, 0
|
||||
) or version >= cv.Version(6, 0, 3)
|
||||
) or version >= cv.Version(6, 1, 1)
|
||||
|
||||
|
||||
def _has_strict_handle_order(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order.
|
||||
|
||||
ESP-IDF 6.1.0 was released before the check reached the 6.1 line.
|
||||
"""
|
||||
return (
|
||||
cv.Version(5, 5, 6) <= version < cv.Version(6, 0, 0)
|
||||
or cv.Version(6, 0, 3) <= version < cv.Version(6, 1, 0)
|
||||
or version >= cv.Version(6, 1, 1)
|
||||
)
|
||||
|
||||
|
||||
# ble_advertising.cpp is fully #ifdef'd on USE_ESP32_BLE_ADVERTISING, set
|
||||
@@ -681,6 +709,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_defines(
|
||||
"ble_advertising.cpp": "USE_ESP32_BLE_ADVERTISING",
|
||||
"bluedroid_hex_wraps.cpp": "USE_ESP32_BLE_BLUEDROID_HEX_WRAPS",
|
||||
"bluedroid_bond_keys.c": "USE_ESP32_BLE_BLUEDROID_BOND_KEYS",
|
||||
"bluedroid_gattc_queue.c": "USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE",
|
||||
"bluedroid_gattc_order.cpp": "USE_ESP32_BLE_GATTC_HANDLE_ORDER",
|
||||
}
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6).
|
||||
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6, 6.1.1).
|
||||
// Same guard as espressif/esp-idf#19322; drop once ESPHome uses an ESP-IDF release that contains it.
|
||||
// C, because Bluedroid's btm_ble_int.h does not close its extern "C" block.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Linker wrap that puts a GATT discovery response back in handle order before Bluedroid parses it.
|
||||
// ESP-IDF 5.5.6 and 6.0.3 end the whole discovery when a peer lists handles out of order (esphome#22518), which
|
||||
// ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end the whole discovery when a peer lists handles out of order (esphome#22518), which
|
||||
// earlier releases, Android and BlueZ accept.
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Linker wraps that stop Bluedroid running a failed queued MTU or execute write request again until the BTU task
|
||||
// stack overflows (esphome#17954). The same fix as removing the command from p_cmd_list in bta_gattc_act.c before
|
||||
// the failure path pops the queue; drop once an ESP-IDF release has it.
|
||||
|
||||
// Compiled only with Bluedroid's private headers (bluedroid_headers_cmake); static analysis skips it
|
||||
#ifdef USE_ESP32_BLE_BLUEDROID_HEADERS
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "bta_gattc_int.h"
|
||||
#include "osi/list.h"
|
||||
|
||||
// The command bta_gattc_cfg_mtu() or bta_gattc_execute() is running, NULL outside them
|
||||
static tBTA_GATTC_CLCB *running_clcb = NULL;
|
||||
static tBTA_GATTC_DATA *running_cmd = NULL;
|
||||
|
||||
void __real_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
|
||||
void __real_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
|
||||
tGATT_STATUS __real_GATTC_ConfigureMTU(UINT16 conn_id);
|
||||
tGATT_STATUS __real_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute);
|
||||
|
||||
// Runs on the Bluetooth host task; the failure path pops the queue again, so this nests
|
||||
static void run_command(void (*real)(tBTA_GATTC_CLCB *, tBTA_GATTC_DATA *), tBTA_GATTC_CLCB *p_clcb,
|
||||
tBTA_GATTC_DATA *p_data) {
|
||||
tBTA_GATTC_CLCB *const outer_clcb = running_clcb;
|
||||
tBTA_GATTC_DATA *const outer_cmd = running_cmd;
|
||||
running_clcb = p_clcb;
|
||||
running_cmd = p_data;
|
||||
real(p_clcb, p_data);
|
||||
running_clcb = outer_clcb;
|
||||
running_cmd = outer_cmd;
|
||||
}
|
||||
|
||||
// The send failed, so the caller clears p_q_cmd and pops the queue. A command popped from p_cmd_list is still its
|
||||
// head and would run again; remove (and free) it first. A command not from the queue is not in it: a no-op.
|
||||
static void drop_failed_command(void) {
|
||||
if (running_clcb != NULL && running_clcb->p_cmd_list != NULL && running_clcb->p_q_cmd == running_cmd) {
|
||||
list_remove(running_clcb->p_cmd_list, running_cmd);
|
||||
}
|
||||
}
|
||||
|
||||
void __wrap_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
|
||||
run_command(__real_bta_gattc_cfg_mtu, p_clcb, p_data);
|
||||
}
|
||||
|
||||
void __wrap_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
|
||||
run_command(__real_bta_gattc_execute, p_clcb, p_data);
|
||||
}
|
||||
|
||||
// The failure checks are the ones bta_gattc_cfg_mtu() and bta_gattc_execute() make
|
||||
tGATT_STATUS __wrap_GATTC_ConfigureMTU(UINT16 conn_id) {
|
||||
const tGATT_STATUS status = __real_GATTC_ConfigureMTU(conn_id);
|
||||
if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) {
|
||||
drop_failed_command();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
tGATT_STATUS __wrap_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute) {
|
||||
const tGATT_STATUS status = __real_GATTC_ExecuteWrite(conn_id, is_execute);
|
||||
if (status != BTA_GATT_OK) {
|
||||
drop_failed_command();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
#endif // USE_ESP32_BLE_BLUEDROID_HEADERS
|
||||
@@ -1,4 +1,5 @@
|
||||
// Linker wraps for the only two sscanf callers in Bluedroid, so newlib's scanf engine (~16 KB) is not linked.
|
||||
// Linker wraps for the only two sscanf callers in Bluedroid, so the C library's scanf engine is not linked
|
||||
// (~16 KB with newlib, ~4 KB with picolibc).
|
||||
// Same parsing as espressif/esp-idf#19235; drop once ESPHome uses an ESP-IDF release that contains it.
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
@@ -18,10 +18,12 @@ from esphome.components.esp32 import (
|
||||
VARIANT_ESP32S31,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
idf_version,
|
||||
)
|
||||
from esphome.components.openthread.const import CONF_POLL_PERIOD
|
||||
from esphome.components.psram import DOMAIN as PSRAM_DOMAIN
|
||||
from esphome.components.zigbee import DOMAIN as ZIGBEE_DOMAIN
|
||||
from esphome.config_helpers import filter_source_files_from_defines
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_OPENTHREAD
|
||||
from esphome.core import CORE
|
||||
@@ -32,6 +34,10 @@ from . import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
FILTER_SOURCE_FILES = filter_source_files_from_defines(
|
||||
{"tick_overflow_guard.cpp": "USE_ESP32_PM_TICK_OVERFLOW_GUARD"}
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@rwrozelle"]
|
||||
DEPENDENCIES = ["esp32"]
|
||||
|
||||
@@ -187,6 +193,15 @@ async def to_code(config: ConfigType) -> None:
|
||||
add_idf_sdkconfig_option(
|
||||
"CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP", config[CONF_IDLE_TIME_BEFORE_SLEEP]
|
||||
)
|
||||
# Stop vTaskStepTick asserting on a tick overshoot after light sleep; built into
|
||||
# IDF 6.0.1, backported by tick_overflow_guard.cpp before that.
|
||||
if idf_version() >= cv.Version(6, 0, 1):
|
||||
add_idf_sdkconfig_option("CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION", True)
|
||||
else:
|
||||
cg.add_define("USE_ESP32_PM_TICK_OVERFLOW_GUARD")
|
||||
for symbol in ("vApplicationSleep", "vTaskStepTick"):
|
||||
cg.add_build_flag(f"-Wl,--wrap={symbol}")
|
||||
cg.add_build_flag(f"-Wl,--undefined=__wrap_{symbol}")
|
||||
if config[CONF_POWER_DOWN_PERIPHERALS]:
|
||||
add_idf_sdkconfig_option("CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP", True)
|
||||
if config[CONF_POWER_DOWN_FLASH]:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace esphome::esp32_power_management {}
|
||||
|
||||
// IDF drops tickless idle on chips without light sleep support (ESP32-H4 and -H21 on 5.5), and then
|
||||
// vApplicationSleep() does not exist
|
||||
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
|
||||
// Backport of IDF 6.0.1 CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION: clamp a small tick overshoot
|
||||
// after light sleep so vTaskStepTick() does not assert.
|
||||
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
|
||||
extern "C" {
|
||||
|
||||
void __real_vApplicationSleep(TickType_t expected_idle_time);
|
||||
void __real_vTaskStepTick(TickType_t ticks_to_jump);
|
||||
|
||||
// Same default as IDF's CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_TOLERANCE; a larger overshoot still asserts
|
||||
static constexpr TickType_t TICK_OVERFLOW_TOLERANCE = 2;
|
||||
static TickType_t expected_idle_time[portNUM_PROCESSORS];
|
||||
|
||||
void __wrap_vApplicationSleep(TickType_t expected) {
|
||||
expected_idle_time[xPortGetCoreID()] = expected;
|
||||
__real_vApplicationSleep(expected);
|
||||
}
|
||||
|
||||
// Only pm_impl.c calls vTaskStepTick(), from inside vApplicationSleep() on the same core
|
||||
void __wrap_vTaskStepTick(TickType_t ticks) {
|
||||
const TickType_t expected = expected_idle_time[xPortGetCoreID()];
|
||||
if (ticks > expected && ticks <= expected + TICK_OVERFLOW_TOLERANCE)
|
||||
ticks = expected;
|
||||
__real_vTaskStepTick(ticks);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
#endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
#endif // USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
@@ -7,6 +7,8 @@
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/components/network/ip_address.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#ifdef USE_ETHERNET
|
||||
|
||||
#ifdef USE_ESP32
|
||||
@@ -366,6 +368,9 @@ class EthernetComponent final : public Component {
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
StaticVector<EthernetIPStateListener *, ESPHOME_ETHERNET_IP_STATE_LISTENERS> ip_state_listeners_;
|
||||
#ifdef USE_ESP32
|
||||
std::atomic<uint8_t> ip_state_pending_{0};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef USE_ETHERNET_CONNECT_TRIGGER
|
||||
|
||||
@@ -129,6 +129,14 @@ void EthernetComponent::log_error_and_mark_failed_(esp_err_t err, const char *me
|
||||
void EthernetComponent::loop() {
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
// The IP events arrive on the event task; the listeners publish states, so notify them here
|
||||
if (this->ip_state_pending_.load(std::memory_order_acquire) != 0) {
|
||||
this->ip_state_pending_.store(0, std::memory_order_relaxed);
|
||||
this->notify_ip_state_listeners_();
|
||||
}
|
||||
#endif
|
||||
|
||||
switch (this->state_) {
|
||||
case EthernetComponentState::STOPPED:
|
||||
if (this->started_) {
|
||||
@@ -770,7 +778,8 @@ void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base
|
||||
event_name = "ETH connected";
|
||||
// For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
|
||||
#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
global_eth_component->enable_loop_soon_any_context();
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6
|
||||
// Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
|
||||
@@ -798,6 +807,9 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
const esp_netif_ip_info_t *ip_info = &event->ip_info;
|
||||
ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
|
||||
global_eth_component->got_ipv4_address_ = true;
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
@@ -805,9 +817,6 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
global_eth_component->connected_ = true;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if USE_NETWORK_IPV6
|
||||
@@ -819,6 +828,9 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
// after a link flap fires another event for the same address.
|
||||
struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
|
||||
global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(global_eth_component->eth_netif_, if_ip6s);
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ =
|
||||
global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
|
||||
@@ -827,9 +839,6 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
global_eth_component->connected_ = global_eth_component->got_ipv4_address_;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@ void IRAM_ATTR ISRInternalGPIOPin::clear_interrupt() {
|
||||
auto *arg = reinterpret_cast<ISRPinArg *>(arg_);
|
||||
ESP_LOGD(TAG, "Clearing interrupt for pin %d", arg->pin);
|
||||
}
|
||||
void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
// pass
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
|
||||
@@ -102,6 +102,14 @@ ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffe
|
||||
|
||||
uint8_t status = 0;
|
||||
if (write_count != 0 || read_count == 0) {
|
||||
#ifdef USE_RP2
|
||||
// arduino-pico leaves a transmission open when a write overflows its buffer, and every later
|
||||
// beginTransmission() is then ignored, so refuse the write before starting it
|
||||
if (write_count > WIRE_BUFFER_SIZE) {
|
||||
ESP_LOGVV(TAG, "TX of %zu bytes exceeds the %u byte Wire buffer", write_count, WIRE_BUFFER_SIZE);
|
||||
return ERROR_TOO_LARGE;
|
||||
}
|
||||
#endif
|
||||
this->wire_->beginTransmission(address);
|
||||
size_t ret = this->wire_->write(write_buffer, write_count);
|
||||
if (ret != write_count) {
|
||||
|
||||
@@ -387,6 +387,7 @@ def _configure_lwip(config: dict) -> None:
|
||||
MEMP_NUM_NETCONN 0 10 38 4***** =sum =sum
|
||||
MEMP_NUM_NETBUF 0 2 16 2***** 8 4
|
||||
MEMP_NUM_TCPIP_MSG_INPKT 4 8 16 8***** 12 8
|
||||
TCP_MSL (ms) 60000† 60000 250 60000 60000 250
|
||||
|
||||
* ESP8266/ESP32/LN882H use MEM_LIBC_MALLOC=1 (system heap, no dedicated pool).
|
||||
ESP8266/ESP32 also use MEMP_MEM_MALLOC=1 (MEMP pools from heap, not static).
|
||||
@@ -394,6 +395,8 @@ def _configure_lwip(config: dict) -> None:
|
||||
*** BK LT overlay: MAX_SOCKETS_UDP+2+1 = 25.
|
||||
**** RTL/LN LT overlay overrides to flat 7.
|
||||
***** Not defined in RTL SDK — lwIP opt.h defaults shown.
|
||||
† ESP8266's lwIP also caps TIME_WAIT at 5 PCBs; LibreTiny's stock lwIP has no
|
||||
cap once MEMP_MEM_MALLOC=1.
|
||||
"dynamic" = auto-calculated from component socket registrations via
|
||||
socket.get_socket_counts() with minimums of 8 TCP / 6 UDP.
|
||||
"""
|
||||
@@ -470,6 +473,10 @@ def _configure_lwip(config: dict) -> None:
|
||||
# both ship with MEMP_MEM_MALLOC=1.
|
||||
lwip_opts.append("MEM_LIBC_MALLOC=1")
|
||||
lwip_opts.append("MEMP_MEM_MALLOC=1")
|
||||
# With MEMP_MEM_MALLOC=1, MEMP_NUM_TCP_PCB no longer limits PCBs, so every
|
||||
# connection the device closes keeps its ~176 B PCB on the heap for TIME_WAIT
|
||||
# (2 * TCP_MSL, 120 s by default). BK's lwIP port already uses 250.
|
||||
lwip_opts.append("TCP_MSL=250")
|
||||
|
||||
# BK72XX-specific: PBUF_POOL_SIZE override
|
||||
# BK SDK "reduced plan" sets this to only 3 — too few for multiple
|
||||
|
||||
@@ -90,7 +90,15 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
|
||||
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
|
||||
}
|
||||
__attribute__((always_inline)) inline void yield() { ::yield(); }
|
||||
#if defined(USE_LIBRETINY_VARIANT_RTL8710B)
|
||||
// Already sleeps to a deadline (rtl8710b_micros.c)
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { ::delay(ms); }
|
||||
#else
|
||||
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) {
|
||||
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
|
||||
}
|
||||
#endif
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(::micros()); }
|
||||
|
||||
// Per-variant millis() fast path — matches MillisInternal::get().
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
|
||||
#if defined(USE_ESP32) && defined(USE_NETWORK)
|
||||
#include <sdkconfig.h>
|
||||
#if defined(CONFIG_LWIP_TCPIP_CORE_LOCKING) && defined(USE_ESPHOME_TASK_LOG_BUFFER)
|
||||
#include "lwip/sys.h"
|
||||
#define USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace esphome::logger {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "logger");
|
||||
@@ -42,6 +50,16 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
|
||||
// Fast path: main thread, no recursion (99.9% of all logs)
|
||||
// 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]] {
|
||||
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ size_t TaskLogBuffer::available_contiguous_space_() const {
|
||||
// head is ahead of or equal to tail
|
||||
// Available space is from head to end, plus from start to tail
|
||||
// But for contiguous, just from head to end (minus 1 to avoid head==tail ambiguity)
|
||||
size_t space_to_end = ESPHOME_TASK_LOG_BUFFER_SIZE - this->head_;
|
||||
size_t space_to_end = CAPACITY - this->head_;
|
||||
if (this->tail_ == 0) {
|
||||
// Can't use the last byte or head would equal tail
|
||||
return space_to_end > 0 ? space_to_end - 1 : 0;
|
||||
@@ -54,19 +54,15 @@ bool TaskLogBuffer::borrow_message_main_loop(LogMessage *&message, uint16_t &tex
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read message header from tail
|
||||
LogMessage *msg = reinterpret_cast<LogMessage *>(this->storage_ + this->tail_);
|
||||
|
||||
// Check for padding marker (indicates wrap-around)
|
||||
// We check the level field since valid levels are 0-7, and 0xFF indicates padding
|
||||
if (msg->level == PADDING_MARKER_LEVEL) {
|
||||
// Skip to start of buffer and re-read
|
||||
// Less than a header before the end means the writer wrapped without a marker
|
||||
if (CAPACITY - this->tail_ < sizeof(LogMessage) ||
|
||||
reinterpret_cast<LogMessage *>(this->storage_ + this->tail_)->level == PADDING_MARKER_LEVEL) {
|
||||
this->tail_ = 0;
|
||||
msg = reinterpret_cast<LogMessage *>(this->storage_);
|
||||
}
|
||||
LogMessage *msg = reinterpret_cast<LogMessage *>(this->storage_ + this->tail_);
|
||||
message = msg;
|
||||
text_length = msg->text_length;
|
||||
this->current_message_size_ = message_total_size(msg->text_length);
|
||||
text_length = msg->text_length;
|
||||
|
||||
// Keep mutex held until release_message_main_loop()
|
||||
return true;
|
||||
@@ -77,7 +73,7 @@ void TaskLogBuffer::release_message_main_loop() {
|
||||
this->tail_ += this->current_message_size_;
|
||||
|
||||
// Handle wrap-around if we've reached the end
|
||||
if (this->tail_ >= ESPHOME_TASK_LOG_BUFFER_SIZE) {
|
||||
if (this->tail_ >= CAPACITY) {
|
||||
this->tail_ = 0;
|
||||
}
|
||||
|
||||
@@ -116,34 +112,22 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
|
||||
return false; // Mutex busy, fall back to direct output
|
||||
}
|
||||
|
||||
// Check if we have enough contiguous space
|
||||
size_t contiguous = this->available_contiguous_space_();
|
||||
|
||||
if (contiguous < total_size) {
|
||||
// Not enough contiguous space at end
|
||||
// Check if we can wrap around
|
||||
size_t space_at_start = (this->head_ >= this->tail_) ? this->tail_ : 0;
|
||||
if (space_at_start > 0) {
|
||||
space_at_start--; // Leave 1 byte gap to distinguish full from empty
|
||||
}
|
||||
|
||||
// Need at least enough space to safely write padding marker (level field is at end of struct)
|
||||
constexpr size_t padding_marker_min_space = offsetof(LogMessage, level) + 1;
|
||||
|
||||
if (space_at_start >= total_size && this->head_ > 0 && contiguous >= padding_marker_min_space) {
|
||||
// Add padding marker (set level field to indicate this is padding, not a real message)
|
||||
LogMessage *padding = reinterpret_cast<LogMessage *>(this->storage_ + this->head_);
|
||||
padding->level = PADDING_MARKER_LEVEL;
|
||||
this->head_ = 0;
|
||||
} else {
|
||||
// Not enough space anywhere, or can't safely write padding marker
|
||||
size_t write_pos = this->head_;
|
||||
if (this->available_contiguous_space_() < total_size) {
|
||||
// Wrap only if the start has room; head == tail would mean empty
|
||||
if (this->head_ < this->tail_ || this->head_ == 0 || this->tail_ <= total_size) {
|
||||
xSemaphoreGive(this->mutex_);
|
||||
return false;
|
||||
}
|
||||
// Mark the skipped end when a header fits there
|
||||
if (CAPACITY - this->head_ >= sizeof(LogMessage)) {
|
||||
reinterpret_cast<LogMessage *>(this->storage_ + this->head_)->level = PADDING_MARKER_LEVEL;
|
||||
}
|
||||
write_pos = 0;
|
||||
}
|
||||
|
||||
// Write message header
|
||||
LogMessage *msg = reinterpret_cast<LogMessage *>(this->storage_ + this->head_);
|
||||
LogMessage *msg = reinterpret_cast<LogMessage *>(this->storage_ + write_pos);
|
||||
msg->level = level;
|
||||
msg->tag = tag;
|
||||
msg->line = line;
|
||||
@@ -165,18 +149,15 @@ bool TaskLogBuffer::send_message_thread_safe(uint8_t level, const char *tag, uin
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove trailing newlines
|
||||
// Trim before storing so the next message reuses the freed bytes
|
||||
while (text_length > 0 && text_area[text_length - 1] == '\n') {
|
||||
text_length--;
|
||||
}
|
||||
|
||||
text_area[text_length] = '\0';
|
||||
msg->text_length = text_length;
|
||||
|
||||
// Advance head
|
||||
this->head_ += total_size;
|
||||
|
||||
// Handle wrap-around (shouldn't happen due to contiguous space check, but be safe)
|
||||
if (this->head_ >= ESPHOME_TASK_LOG_BUFFER_SIZE) {
|
||||
this->head_ = write_pos + message_total_size(text_length);
|
||||
if (this->head_ >= CAPACITY) {
|
||||
this->head_ = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace esphome::logger {
|
||||
* - Variable-size messages with header + text stored contiguously (NOSPLIT style)
|
||||
* - FreeRTOS mutex protects all buffer operations
|
||||
* - Volatile counter enables fast has_messages() without lock overhead
|
||||
* - If message doesn't fit at end, padding is added and message wraps to start
|
||||
* - A message that doesn't fit at the end wraps to the start, after a padding marker if a header fits there
|
||||
*/
|
||||
class TaskLogBuffer {
|
||||
public:
|
||||
@@ -77,16 +77,22 @@ class TaskLogBuffer {
|
||||
inline bool HOT has_messages() const { return this->message_count_ != 0; }
|
||||
|
||||
// Get the total buffer size in bytes
|
||||
static constexpr size_t size() { return ESPHOME_TASK_LOG_BUFFER_SIZE; }
|
||||
static constexpr size_t size() { return CAPACITY; }
|
||||
|
||||
private:
|
||||
// Calculate total size needed for a message (header + text + null terminator)
|
||||
static inline size_t message_total_size(size_t text_length) { return sizeof(LogMessage) + text_length + 1; }
|
||||
// Keep headers aligned: BK72xx silently misreads unaligned words instead of faulting
|
||||
static constexpr size_t ALIGNMENT = alignof(LogMessage);
|
||||
static constexpr size_t CAPACITY = ESPHOME_TASK_LOG_BUFFER_SIZE & ~(ALIGNMENT - 1);
|
||||
|
||||
// Header + text + null, rounded up to keep the next header aligned
|
||||
static constexpr size_t message_total_size(size_t text_length) {
|
||||
return (sizeof(LogMessage) + text_length + 1 + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
|
||||
}
|
||||
|
||||
// Calculate available contiguous space at write position
|
||||
size_t available_contiguous_space_() const;
|
||||
|
||||
uint8_t storage_[ESPHOME_TASK_LOG_BUFFER_SIZE]; // Embedded in Logger (no separate heap allocation)
|
||||
alignas(LogMessage) uint8_t storage_[CAPACITY]; // Embedded in Logger (no separate heap allocation)
|
||||
size_t head_{0}; // Write position
|
||||
size_t tail_{0}; // Read position
|
||||
|
||||
|
||||
@@ -806,10 +806,10 @@ void ModbusServerHub::process_modbus_client_frame_(uint8_t address, uint8_t func
|
||||
bool Modbus::send_frame_(const ModbusFrame &frame) {
|
||||
int32_t tx_delay_remaining = this->tx_delay_remaining();
|
||||
if (tx_delay_remaining > 0) {
|
||||
// Yield the whole-ms part: delay() never blocks past the request on FreeRTOS, and only slightly
|
||||
// over elsewhere, which just lengthens the gap. The recompute below makes the remainder exact.
|
||||
if (tx_delay_remaining >= (int32_t) US_PER_MS) {
|
||||
delay(tx_delay_remaining / US_PER_MS);
|
||||
// Yield all but the last whole ms: delay() can block up to a tick past the request, and a tick
|
||||
// longer than 1 ms just lengthens the gap. The recompute below makes the remainder exact.
|
||||
if (tx_delay_remaining >= (int32_t) (2 * US_PER_MS)) {
|
||||
delay(tx_delay_remaining / US_PER_MS - 1);
|
||||
tx_delay_remaining = this->tx_delay_remaining();
|
||||
}
|
||||
if (tx_delay_remaining > 0)
|
||||
|
||||
@@ -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;
|
||||
@@ -672,22 +673,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_);
|
||||
@@ -754,7 +761,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;
|
||||
@@ -771,13 +778,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");
|
||||
@@ -864,11 +872,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
|
||||
|
||||
@@ -2712,7 +2712,7 @@ HAIER_SCHEMA = cv.Schema(
|
||||
|
||||
@register_binary_sensor("haier", HaierBinarySensor, HAIER_SCHEMA)
|
||||
def haier_binary_sensor(var, config):
|
||||
cg.add(var.set_code(config[CONF_CODE]))
|
||||
cg.add(var.set_data(cg.StructInitializer(HaierData, ("data", config[CONF_CODE]))))
|
||||
|
||||
|
||||
@register_trigger("haier", HaierTrigger, HaierData)
|
||||
@@ -2831,7 +2831,7 @@ MIRAGE_SCHEMA = cv.Schema(
|
||||
|
||||
@register_binary_sensor("mirage", MirageBinarySensor, MIRAGE_SCHEMA)
|
||||
def mirage_binary_sensor(var, config):
|
||||
cg.add(var.set_code(config[CONF_CODE]))
|
||||
cg.add(var.set_data(cg.StructInitializer(MirageData, ("data", config[CONF_CODE]))))
|
||||
|
||||
|
||||
@register_trigger("mirage", MirageTrigger, MirageData)
|
||||
|
||||
@@ -15,7 +15,7 @@ struct CanalSatData {
|
||||
}
|
||||
};
|
||||
|
||||
struct CanalSatLDData : public CanalSatData {};
|
||||
using CanalSatLDData = CanalSatData;
|
||||
|
||||
class CanalSatBaseProtocol : public RemoteProtocol<CanalSatData> {
|
||||
public:
|
||||
|
||||
@@ -112,6 +112,16 @@ void SerialProxy::loop() {
|
||||
|
||||
#ifdef USE_API
|
||||
void __attribute__((noinline)) SerialProxy::read_and_send_(size_t available) {
|
||||
// A message the subscriber's connection cannot take is lost, so the bytes stay in the
|
||||
// UART's buffer until it can. A tap is still served: its answers must not wait on the network.
|
||||
if (this->api_connection_ != nullptr &&
|
||||
#ifdef USE_SERIAL_PROXY_TAP
|
||||
!this->tap_observing_() &&
|
||||
#endif
|
||||
!this->api_connection_->try_to_clear_buffer(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read in chunks up to SERIAL_PROXY_MAX_READ_SIZE
|
||||
uint8_t buffer[SERIAL_PROXY_MAX_READ_SIZE];
|
||||
size_t to_read = std::min(available, sizeof(buffer));
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::uart {
|
||||
|
||||
/// One software serial TX byte as line levels, one bit per slot.
|
||||
struct SoftwareSerialTxFrame {
|
||||
/// The start bit at slot 0, then the frame, then a stop bit that ends the last run
|
||||
uint32_t line;
|
||||
/// Slot of the last 0; from the edge after it the line stays high through the stop bits
|
||||
uint32_t high_from;
|
||||
/// Slots right after an edge into a run of equal bits lasting at least `min_run_cycles`, where a pending
|
||||
/// interrupt only delays bits that repeat the level
|
||||
uint32_t unlock_at;
|
||||
};
|
||||
|
||||
/// `frame` holds `num_bits` data and parity bits, LSB first. `unlock_at` stays 0 unless `find_unlocks`.
|
||||
ESPHOME_ALWAYS_INLINE inline SoftwareSerialTxFrame software_serial_tx_frame(uint32_t frame, uint32_t num_bits,
|
||||
uint32_t bit_time, uint32_t min_run_cycles,
|
||||
bool find_unlocks) {
|
||||
SoftwareSerialTxFrame tx;
|
||||
tx.line = frame << 1 | (1u << (num_bits + 1));
|
||||
// Slot 0 is the start bit, always 0, so the argument is never 0
|
||||
tx.high_from = 31 - __builtin_clz(~tx.line & ((2u << num_bits) - 1));
|
||||
tx.unlock_at = 0;
|
||||
if (find_unlocks) {
|
||||
const uint32_t edges = tx.line ^ (tx.line << 1 | 1); // the idle line before the start bit is high
|
||||
for (uint32_t pos = 0; pos <= tx.high_from; pos++) {
|
||||
if (((edges >> pos) & 1) && (__builtin_ctz(edges >> (pos + 1)) + 1) * bit_time >= min_run_cycles)
|
||||
tx.unlock_at |= 1u << pos;
|
||||
}
|
||||
}
|
||||
return tx;
|
||||
}
|
||||
|
||||
} // namespace esphome::uart
|
||||
@@ -19,9 +19,16 @@ namespace esphome::uart {
|
||||
ESPHOME_LOG_TAG(TAG, "uart");
|
||||
// Edge decoder up to this baud rate; at 38400 WiFi interrupt latency corrupts bytes.
|
||||
static constexpr uint32_t SW_SERIAL_EDGE_MODE_MAX_BAUD = 19200;
|
||||
// TX locks interrupts per bit up to this baud rate and per byte above it. At 38400 byte locks still trip the Wi-Fi
|
||||
// watchdog when every byte is below 0x80, while an interrupt between bits leaves the bytes intact; at 115200 it
|
||||
// stretches bits enough to corrupt them.
|
||||
static constexpr uint32_t SW_SERIAL_TX_BIT_LOCK_MAX_BAUD = 38400;
|
||||
// Edge decoder time base: 1/16 us from the 1 MHz system timer, which keeps its rate during a
|
||||
// CpuFrequencyBoost; the cycle counter does not.
|
||||
static constexpr uint32_t RX_TICKS_PER_SECOND = 16000000;
|
||||
// A byte lock lets pending interrupts run right after an edge when the next edge is at least this far away, so their
|
||||
// delay lands inside a run of equal bits. Locks longer than about 6 bits at 57600 trip the Wi-Fi watchdog.
|
||||
static constexpr uint32_t TX_UNLOCK_MIN_RUN_CYCLES = F_CPU / 1000000 * 30;
|
||||
// Longest per-bit TX interrupt lock; the Wi-Fi interrupt handler asserts (hardware WDT) when held off about 1 ms
|
||||
static constexpr uint32_t MAX_TX_LOCK_CYCLES = F_CPU / 1000000 * 200;
|
||||
__attribute__((always_inline)) static inline uint32_t rx_now() { return micros() << 4; }
|
||||
@@ -180,9 +187,11 @@ void ESP8266UartComponent::dump_config() {
|
||||
this->baud_rate_ <= SW_SERIAL_EDGE_MODE_MAX_BAUD ? LOG_STR_LITERAL("edge")
|
||||
: LOG_STR_LITERAL("start bit sampler"));
|
||||
}
|
||||
if (this->tx_pin_ != nullptr && this->baud_rate_ <= SW_SERIAL_EDGE_MODE_MAX_BAUD &&
|
||||
if (this->tx_pin_ != nullptr && this->baud_rate_ <= SW_SERIAL_TX_BIT_LOCK_MAX_BAUD &&
|
||||
this->sw_serial_->locks_whole_frame()) {
|
||||
ESP_LOGW(TAG, " TX locks interrupts for whole bytes: another software UART receives above %u baud",
|
||||
ESP_LOGW(TAG,
|
||||
" TX locks interrupts for whole bytes because a software UART receives above %u baud; Wi-Fi "
|
||||
"watchdog resets are possible under load",
|
||||
(unsigned) SW_SERIAL_EDGE_MODE_MAX_BAUD);
|
||||
}
|
||||
}
|
||||
@@ -270,7 +279,7 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
|
||||
if (this->gpio_rx_pin_ != nullptr)
|
||||
this->gpio_rx_pin_->detach_interrupt();
|
||||
// This instance counted itself if its RX ran the whole-byte interrupt
|
||||
if (this->lock_frame_ && this->gpio_rx_pin_ != nullptr)
|
||||
if (this->blocking_rx_ && this->gpio_rx_pin_ != nullptr)
|
||||
blocking_rx_count--;
|
||||
// RX disabled: forget the old pin, so a later reload does not remove this instance from the count again
|
||||
if (rx_pin == nullptr)
|
||||
@@ -280,9 +289,8 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
|
||||
this->data_bits_ = data_bits;
|
||||
this->parity_ = parity;
|
||||
const bool edge_mode = baud_rate <= SW_SERIAL_EDGE_MODE_MAX_BAUD;
|
||||
// Above the edge mode limit a bit is 52 us or less, so an interrupt between bits would stretch one; the whole frame
|
||||
// is locked instead, well under 1 ms
|
||||
this->lock_frame_ = !edge_mode;
|
||||
this->blocking_rx_ = !edge_mode;
|
||||
this->lock_frame_ = baud_rate > SW_SERIAL_TX_BIT_LOCK_MAX_BAUD;
|
||||
// to_isr() allocates, so call it only for a new or changed pin
|
||||
if (tx_pin != nullptr) {
|
||||
if (tx_pin != this->gpio_tx_pin_)
|
||||
@@ -390,6 +398,19 @@ void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
|
||||
|
||||
// Transmit runs from the main loop and never overlaps a CpuFrequencyBoost
|
||||
const uint32_t bit_time = this->bit_time_;
|
||||
// Data bits LSB first, then the parity bit
|
||||
uint32_t frame = data & ((1u << this->data_bits_) - 1);
|
||||
uint32_t num_bits = this->data_bits_;
|
||||
if (need_parity_bit) {
|
||||
parity_bit ^= __builtin_parity(frame);
|
||||
frame |= uint32_t(parity_bit) << num_bits++;
|
||||
}
|
||||
// Decided before the start bit so the timed loop only tests a bit
|
||||
const SoftwareSerialTxFrame tx = software_serial_tx_frame(frame, num_bits, bit_time, TX_UNLOCK_MIN_RUN_CYCLES,
|
||||
this->lock_frame_ && blocking_rx_count == 0);
|
||||
const uint32_t line = tx.line;
|
||||
const uint32_t high_from = tx.high_from;
|
||||
const uint32_t unlock_at = tx.unlock_at;
|
||||
std::optional<InterruptLock> frame_lock;
|
||||
if (this->locks_whole_frame())
|
||||
frame_lock.emplace();
|
||||
@@ -401,18 +422,17 @@ void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
|
||||
start = arch_get_cpu_cycle_count();
|
||||
}
|
||||
uint32_t wait = bit_time;
|
||||
for (int i = 0; i < this->data_bits_; i++) {
|
||||
bool bit = data & (1 << i);
|
||||
this->write_bit_(bit, &wait, start, bit_time);
|
||||
if (need_parity_bit)
|
||||
parity_bit ^= bit;
|
||||
for (uint32_t pos = 0; pos <= high_from; pos++) {
|
||||
if (pos != 0)
|
||||
this->write_bit_((line >> pos) & 1, &wait, start, bit_time);
|
||||
if ((unlock_at >> pos) & 1)
|
||||
frame_lock.emplace(); // drops the held lock first, so pending interrupts run
|
||||
}
|
||||
if (need_parity_bit)
|
||||
this->write_bit_(parity_bit, &wait, start, bit_time);
|
||||
// Stop bits: write_bit_ waits before its edge, so the stop bit is held with wait_
|
||||
this->write_bit_(true, &wait, start, bit_time);
|
||||
this->wait_(&wait, start, bit_time);
|
||||
if (this->stop_bits_ == 2)
|
||||
// Hold that high run with interrupts on: one that runs past it only delays the next start bit, and back-to-back
|
||||
// byte locks with no gap between them trip the Wi-Fi watchdog
|
||||
frame_lock.reset();
|
||||
for (uint32_t i = high_from; i < num_bits + this->stop_bits_; i++)
|
||||
this->wait_(&wait, start, bit_time);
|
||||
}
|
||||
void IRAM_ATTR ESP8266SoftwareSerial::wait_(uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "software_serial_rx_decoder.h"
|
||||
#include "software_serial_tx_frame.h"
|
||||
#include "uart_component.h"
|
||||
|
||||
namespace esphome::uart {
|
||||
@@ -26,8 +27,8 @@ class ESP8266SoftwareSerial {
|
||||
|
||||
size_t available();
|
||||
|
||||
/// TX holds interrupts off for whole frames: above the edge mode limit, or while any instance's RX interrupt reads
|
||||
/// whole bytes (it must not run between TX bits).
|
||||
/// TX holds interrupts off for each byte up to the edge into its trailing run of 1 bits, rather than per bit: above
|
||||
/// the per-bit lock limit, or while any instance's RX interrupt reads whole bytes (it must not run between TX edges).
|
||||
bool locks_whole_frame() const { return this->lock_frame_ || blocking_rx_count != 0; }
|
||||
|
||||
protected:
|
||||
@@ -56,6 +57,7 @@ class ESP8266SoftwareSerial {
|
||||
uint8_t stop_bits_;
|
||||
uint8_t data_bits_;
|
||||
bool lock_frame_{false};
|
||||
bool blocking_rx_{false}; // this instance's RX reads whole bytes in its interrupt
|
||||
static inline uint8_t blocking_rx_count = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
};
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from esphome.components.esp32 import (
|
||||
idf_version,
|
||||
only_on_variant,
|
||||
require_idf_version,
|
||||
set_idf_sdkconfig_default,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DEVICES, CONF_FRAMEWORK, CONF_ID
|
||||
@@ -304,7 +305,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
# IDF 6.0 moved USB host to an external component
|
||||
if idf_version() >= cv.Version(6, 0, 0):
|
||||
add_idf_component(name="espressif/usb", ref="1.4.1")
|
||||
add_idf_sdkconfig_option("CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE", 1024)
|
||||
set_idf_sdkconfig_default("CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE", 1024)
|
||||
if config.get(CONF_ENABLE_HUBS):
|
||||
add_idf_sdkconfig_option("CONFIG_USB_HOST_HUBS_SUPPORTED", True)
|
||||
|
||||
|
||||
@@ -220,6 +220,34 @@ EntityMatchResult UrlMatch::match_entity(EntityBase *entity) const {
|
||||
}
|
||||
|
||||
#if !defined(USE_ESP32) && defined(USE_ARDUINO)
|
||||
// BEGIN ESPAsyncWebServer 3.12.1 workaround: remove once a release containing upstream commit
|
||||
// 880c97068abb0f0e63f803cd3c0cac84fa5cd7bb is out and we bump to it.
|
||||
// 3.12.1 creates the SSE client before the head is ACKed and credits the head's ACK to its first queued messages,
|
||||
// dropping or truncating them. Create the client once the head is ACKed instead, as 3.9.6 did.
|
||||
class HeadAckedEventSourceResponse final : public AsyncEventSourceResponse {
|
||||
public:
|
||||
HeadAckedEventSourceResponse(DeferredUpdateEventSourceList *list, WebServer *ws)
|
||||
: AsyncEventSourceResponse(nullptr), list_(list), ws_(ws) {}
|
||||
void _respond(AsyncWebServerRequest *request) override {
|
||||
String head;
|
||||
this->_assembleHead(head, request->version());
|
||||
request->client()->write(head.c_str(), this->_headLength);
|
||||
}
|
||||
// Every ACK until clientRelease() is the head's, and clientRelease() unhooks this. _state must stay
|
||||
// RESPONSE_SETUP: past RESPONSE_WAIT_ACK the request would close its released (null) client after this returns.
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time) override {
|
||||
this->_ackedLength += len;
|
||||
if (this->_ackedLength >= this->_headLength)
|
||||
this->list_->add_client_(this->ws_, request->clientRelease());
|
||||
return 0;
|
||||
}
|
||||
|
||||
private:
|
||||
DeferredUpdateEventSourceList *list_;
|
||||
WebServer *ws_;
|
||||
};
|
||||
// END ESPAsyncWebServer 3.12.1 workaround
|
||||
|
||||
// helper for allowing only unique entries in the queue
|
||||
void __attribute__((flatten)) DeferredUpdateEventSource::deq_push_back_with_dedup_(
|
||||
void *source, message_generator_t *message_generator) {
|
||||
@@ -328,7 +356,13 @@ void DeferredUpdateEventSourceList::try_send_nodefer(const char *message, size_t
|
||||
}
|
||||
}
|
||||
|
||||
// BEGIN ESPAsyncWebServer 3.12.1 workaround (see HeadAckedEventSourceResponse): once removed, add_new_client creates
|
||||
// the source as add_client_ does and ends with es->handleRequest(request); add_client_ goes away.
|
||||
void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServerRequest *request) {
|
||||
request->send(new HeadAckedEventSourceResponse(this, ws)); // NOLINT
|
||||
}
|
||||
|
||||
void DeferredUpdateEventSourceList::add_client_(WebServer *ws, AsyncClient *client) {
|
||||
DeferredUpdateEventSource *es = new DeferredUpdateEventSource(ws, ESPHOME_F("/events"));
|
||||
this->push_back(es);
|
||||
|
||||
@@ -336,9 +370,10 @@ void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServer
|
||||
|
||||
es->onDisconnect([this, es](AsyncEventSourceClient *client) { this->on_client_disconnect_(es); });
|
||||
|
||||
es->handleRequest(request);
|
||||
new AsyncEventSourceClient(client, es); // NOLINT: owned by es
|
||||
ws->enable_loop_soon_any_context();
|
||||
}
|
||||
// END ESPAsyncWebServer 3.12.1 workaround
|
||||
|
||||
void DeferredUpdateEventSourceList::on_client_connect_(DeferredUpdateEventSource *source) {
|
||||
WebServer *ws = source->web_server_;
|
||||
|
||||
@@ -171,9 +171,12 @@ class DeferredUpdateEventSource final : public AsyncEventSource {
|
||||
};
|
||||
|
||||
class DeferredUpdateEventSourceList final : public std::list<DeferredUpdateEventSource *> {
|
||||
friend class HeadAckedEventSourceResponse; // ESPAsyncWebServer 3.12.1 workaround, remove with it
|
||||
|
||||
protected:
|
||||
void on_client_connect_(DeferredUpdateEventSource *source);
|
||||
void on_client_disconnect_(DeferredUpdateEventSource *source);
|
||||
void add_client_(WebServer *ws, AsyncClient *client); // ESPAsyncWebServer 3.12.1 workaround, remove with it
|
||||
|
||||
public:
|
||||
/// Returns true if there are event sources remaining (including pending cleanup).
|
||||
|
||||
@@ -132,7 +132,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
cg.add_platformio_option("extra_scripts", ["pre:fix_rp2040_hash.py"])
|
||||
# https://github.com/ESP32Async/ESPAsyncWebServer/blob/main/library.json
|
||||
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.9.6")
|
||||
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.12.1")
|
||||
|
||||
|
||||
# The DNS server used for captive portals on ESP32; other platforms use the Arduino
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
#include "web_server_base.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#if defined(USE_NETWORK) && !defined(USE_ZEPHYR) && !defined(USE_HOST)
|
||||
|
||||
namespace esphome::web_server_base {
|
||||
@@ -47,18 +52,23 @@ bool GuardMiddlewareHandler::check_auth_(AsyncWebServerRequest *request) {
|
||||
// compiled out. On ESP32 our own server picks the scheme internally.
|
||||
#if USE_ESP32 || defined(USE_WEBSERVER_AUTH_DIGEST)
|
||||
bool success = request->authenticate(credentials.username, credentials.password);
|
||||
#else
|
||||
bool success = request->authenticate(credentials.basic_auth_hash);
|
||||
#endif
|
||||
if (!success) {
|
||||
#if USE_ESP32
|
||||
if (!success)
|
||||
request->requestAuthentication();
|
||||
#elif defined(USE_WEBSERVER_AUTH_DIGEST)
|
||||
request->requestAuthentication(nullptr, true);
|
||||
#else
|
||||
request->requestAuthentication(nullptr, false);
|
||||
#endif
|
||||
// Checked here, not with the library's authenticate()/requestAuthentication(): those also link its
|
||||
// Digest code, since the scheme is only known at run time there
|
||||
const String &challenge = request->authChallenge();
|
||||
const size_t hash_len = strlen(credentials.basic_auth_hash);
|
||||
const bool success = request->authType() == AsyncAuthType::AUTH_BASIC && challenge.length() == hash_len &&
|
||||
constant_time_equals(reinterpret_cast<const uint8_t *>(challenge.c_str()),
|
||||
reinterpret_cast<const uint8_t *>(credentials.basic_auth_hash), hash_len);
|
||||
if (!success) {
|
||||
// The challenge the library sent, with the strings kept in flash on ESP8266
|
||||
AsyncWebServerResponse *response = request->beginResponse(401);
|
||||
response->addHeader(String(F("WWW-Authenticate")), String(F("Basic realm=\"Login Required\"")));
|
||||
request->send(response);
|
||||
}
|
||||
#endif
|
||||
return success;
|
||||
#else
|
||||
return true;
|
||||
|
||||
@@ -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
|
||||
@@ -2174,6 +2174,10 @@ bool WiFiComponent::transition_to_phase_(WiFiRetryPhase new_phase) {
|
||||
// Even when skipping full restart, disconnect to clear driver state
|
||||
// Without this, platforms like LibreTiny may think we're still connecting
|
||||
this->wifi_disconnect_();
|
||||
// And clear the error flag, as restart_adapter() does: COOLDOWN leads to
|
||||
// check_connecting_finished() without start_connecting(), so a stale
|
||||
// error would fail a connection the driver completes meanwhile.
|
||||
this->error_from_callback_ = false;
|
||||
}
|
||||
// Clear scan flag - we're starting a new retry cycle
|
||||
// This is critical for DPP/captive portal/improv flow: when determine_next_phase_()
|
||||
|
||||
@@ -564,7 +564,7 @@ class WiFiComponent final : public Component {
|
||||
// (In most use cases you won't need these)
|
||||
/// Setup WiFi interface.
|
||||
void setup() override;
|
||||
#if defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
#if defined(USE_ESP32) || defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
void on_powerdown() override;
|
||||
#endif
|
||||
void start();
|
||||
|
||||
@@ -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)
|
||||
@@ -1635,6 +1639,21 @@ bool WiFiComponent::wifi_dpp_start_listen_() {
|
||||
void WiFiComponent::wifi_dpp_stop_listen_() { esp_supp_dpp_stop_listen(); }
|
||||
#endif
|
||||
|
||||
void WiFiComponent::on_powerdown() {
|
||||
// Leave the AP before esp_restart() or deep sleep stops Wi-Fi. esp_wifi_stop() while associated
|
||||
// makes the ESP32 retransmit its Disassociation up to the retry limit although the AP ACKs it
|
||||
// (32 copies with protected management frames), which some APs handle badly.
|
||||
// Upstream bug: https://github.com/espressif/esp-idf/issues/19443 - remove this once it is fixed
|
||||
// in the ESP-IDF versions we support.
|
||||
// Ask the driver: s_sta_connected lags until the main loop has handled the connect event.
|
||||
wifi_ap_record_t ap_info;
|
||||
if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
|
||||
return;
|
||||
ESP_LOGD(TAG, "Disconnecting before powerdown");
|
||||
esp_wifi_disconnect();
|
||||
delay(100); // NOLINT: once per reboot or deep sleep, lets the disassociation go out
|
||||
}
|
||||
|
||||
bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
|
||||
|
||||
bssid_t WiFiComponent::wifi_bssid() {
|
||||
|
||||
@@ -20,7 +20,12 @@ void Mutex::lock() { k_mutex_lock(static_cast<k_mutex *>(this->handle_), K_FOREV
|
||||
bool Mutex::try_lock() { return k_mutex_lock(static_cast<k_mutex *>(this->handle_), K_NO_WAIT) == 0; }
|
||||
void Mutex::unlock() { k_mutex_unlock(static_cast<k_mutex *>(this->handle_)); }
|
||||
|
||||
IRAM_ATTR InterruptLock::InterruptLock() { state_ = irq_lock(); }
|
||||
IRAM_ATTR InterruptLock::InterruptLock() {
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
micros(); // Unlocked, so it catches up any sleep before timestamps are taken under the lock
|
||||
#endif
|
||||
state_ = irq_lock();
|
||||
}
|
||||
IRAM_ATTR InterruptLock::~InterruptLock() { irq_unlock(state_); }
|
||||
|
||||
// Zephyr LwIPLock is defined inline as a no-op in helpers.h
|
||||
|
||||
@@ -10,18 +10,14 @@ namespace zephyr {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "zephyr");
|
||||
|
||||
static gpio_flags_t flags_to_mode(gpio::Flags flags, bool inverted, bool value) {
|
||||
// Without a GPIO_OUTPUT_INIT_* bit, Zephyr leaves the output level as it is.
|
||||
static gpio_flags_t flags_to_mode(gpio::Flags flags) {
|
||||
gpio_flags_t ret = 0;
|
||||
if (flags & gpio::FLAG_INPUT) {
|
||||
ret |= GPIO_INPUT;
|
||||
}
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
ret |= GPIO_OUTPUT;
|
||||
if (value != inverted) {
|
||||
ret |= GPIO_OUTPUT_INIT_HIGH;
|
||||
} else {
|
||||
ret |= GPIO_OUTPUT_INIT_LOW;
|
||||
}
|
||||
}
|
||||
if (flags & gpio::FLAG_PULLUP) {
|
||||
ret |= GPIO_PULL_UP;
|
||||
@@ -123,8 +119,11 @@ void ZephyrGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
if (nullptr == this->gpio_) {
|
||||
return;
|
||||
}
|
||||
auto ret = gpio_pin_configure(this->gpio_, this->pin_ % this->gpio_size_,
|
||||
flags_to_mode(flags, this->inverted_, this->value_));
|
||||
gpio_flags_t mode = flags_to_mode(flags);
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
mode |= this->value_ != this->inverted_ ? GPIO_OUTPUT_INIT_HIGH : GPIO_OUTPUT_INIT_LOW;
|
||||
}
|
||||
auto ret = gpio_pin_configure(this->gpio_, this->pin_ % this->gpio_size_, mode);
|
||||
if (ret != 0) {
|
||||
ESP_LOGE(TAG, "gpio %u cannot be configured %d.", this->pin_, ret);
|
||||
}
|
||||
@@ -182,6 +181,14 @@ void IRAM_ATTR ISRInternalGPIOPin::digital_write(bool value) {
|
||||
gpio_pin_set(arg->gpio, arg->pin % arg->gpio_size, value != arg->inverted ? 1 : 0);
|
||||
}
|
||||
|
||||
void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
auto *arg = (zephyr::ISRPinArg *) this->arg_;
|
||||
if (arg == nullptr || arg->gpio == nullptr) {
|
||||
return;
|
||||
}
|
||||
gpio_pin_configure(arg->gpio, arg->pin % arg->gpio_size, zephyr::flags_to_mode(flags));
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,10 @@
|
||||
#include <zephyr/drivers/watchdog.h>
|
||||
#include <zephyr/sys/reboot.h>
|
||||
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
#include <cmsis_core.h>
|
||||
#endif
|
||||
|
||||
// Empty zephyr namespace block to satisfy ci-custom's lint_namespace check.
|
||||
// HAL functions live in namespace esphome (root) — they are not part of the
|
||||
// zephyr component's API.
|
||||
@@ -18,12 +22,65 @@ static int wdt_channel_id = -1; // NOLINT(cppcoreguidelines-avoid-non-const-glo
|
||||
static const device *const WDT = DEVICE_DT_GET(DT_ALIAS(watchdog0));
|
||||
#endif
|
||||
|
||||
// yield(), delay(), micros(), millis(), millis_64(), delayMicroseconds(),
|
||||
// yield(), delay(), millis(), millis_64(), delayMicroseconds(), micros() except the cycle-counter one,
|
||||
// arch_get_cpu_cycle_count(), arch_get_cpu_freq_hz() inlined in
|
||||
// components/zephyr/hal.h.
|
||||
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
// The kernel clock counts in ticks of about 30 us, and the CPU cycle counter stops while the CPU sleeps.
|
||||
// micros() adds the cycles counted since the last call. While the CPU stays busy the result and the kernel clock
|
||||
// each trail the true time by less than a tick, so they differ by less than a tick either way. A sleep shorter
|
||||
// than a tick can go unnoticed, so the result may trail the true time by up to two ticks until the next resync.
|
||||
// The CPU cannot sleep while interrupts are locked, so a lag there comes from before the lock. It and any drift
|
||||
// are left for the next unlocked call, which keeps differences inside an InterruptLock exact; InterruptLock makes that
|
||||
// call just before it locks, so timestamps taken under the lock line up with later unlocked ones. A counter that has
|
||||
// not moved since the last call is not running, and then the kernel clock is used even under a lock.
|
||||
|
||||
// One struct so the code loads a single base address.
|
||||
static struct {
|
||||
uint32_t value;
|
||||
uint32_t last_cycles; // Moves on by whole microseconds only, so the remainder carries over.
|
||||
} micros_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
static constexpr uint32_t CYCLES_PER_US = 64; // nRF52 cores always run at 64 MHz.
|
||||
// Drift between unlocked calls stays far below this; a larger lead is a lag of over 2^31 us that wrapped. A lag
|
||||
// within this of 2^32 us still looks like a lead and holds micros() for at most a second; that is accepted.
|
||||
static constexpr int32_t MAX_LEAD_US = 1000000;
|
||||
|
||||
uint32_t micros() {
|
||||
const unsigned int key = irq_lock();
|
||||
const uint32_t cycles = DWT->CYCCNT;
|
||||
const uint32_t elapsed_us = (cycles - micros_state.last_cycles) / CYCLES_PER_US;
|
||||
micros_state.last_cycles += elapsed_us * CYCLES_PER_US;
|
||||
uint32_t value = micros_state.value + elapsed_us;
|
||||
|
||||
const uint32_t kernel_us = k_ticks_to_us_floor32(k_uptime_ticks());
|
||||
// A tick, plus 1 us because kernel_us is rounded down.
|
||||
const int32_t tick_us = k_ticks_to_us_ceil32(1) + 1;
|
||||
const int32_t ahead = static_cast<int32_t>(value - kernel_us);
|
||||
const bool unlocked = arch_irq_unlocked(key);
|
||||
if ((ahead < -tick_us || ahead > MAX_LEAD_US) && (unlocked || elapsed_us == 0)) {
|
||||
// The CPU slept, so the cycle counter fell behind.
|
||||
value = kernel_us;
|
||||
micros_state.last_cycles = cycles;
|
||||
} else if (ahead >= tick_us && ahead <= MAX_LEAD_US && unlocked) {
|
||||
// The CPU clock can run fast against the RTC; cap the drift at one tick, but never below a result already
|
||||
// returned under a lock.
|
||||
const uint32_t cap = kernel_us + tick_us - 1;
|
||||
value = static_cast<int32_t>(cap - micros_state.value) > 0 ? cap : micros_state.value;
|
||||
}
|
||||
micros_state.value = value;
|
||||
irq_unlock(key);
|
||||
return value;
|
||||
}
|
||||
#endif
|
||||
|
||||
void arch_init() {
|
||||
main_loop_thread() = k_current_get();
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
|
||||
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
|
||||
#endif
|
||||
#ifdef CONFIG_WATCHDOG
|
||||
if (device_is_ready(WDT)) {
|
||||
static wdt_timeout_cfg wdt_config{};
|
||||
|
||||
@@ -27,12 +27,20 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() { return k_curr
|
||||
|
||||
__attribute__((always_inline)) inline void yield() { ::k_yield(); }
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { ::k_msleep(ms); }
|
||||
#if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 1000000
|
||||
// The system timer counts microseconds (the GRTC on nRF54L) and wraps at 2^32 like micros().
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return k_cycle_get_32(); }
|
||||
#elif defined(CONFIG_SOC_SERIES_NRF52X) || defined(CONFIG_SOC_SERIES_NRF52) // the name changed in sdk-nrf 3
|
||||
#define USE_ZEPHYR_DWT_MICROS
|
||||
uint32_t micros(); // CPU cycles kept close to the kernel clock, see hal.cpp
|
||||
#else
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return k_ticks_to_us_floor32(k_uptime_ticks()); }
|
||||
#endif
|
||||
__attribute__((always_inline)) inline uint64_t millis_64() { return static_cast<uint64_t>(k_uptime_get()); }
|
||||
__attribute__((always_inline)) inline uint32_t millis() { return static_cast<uint32_t>(millis_64()); }
|
||||
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
__attribute__((always_inline)) inline void delayMicroseconds(uint32_t us) { ::k_usleep(us); }
|
||||
__attribute__((always_inline)) inline void delayMicroseconds(uint32_t us) { ::k_busy_wait(us); }
|
||||
__attribute__((always_inline)) inline uint32_t arch_get_cpu_cycle_count() { return k_cycle_get_32(); }
|
||||
__attribute__((always_inline)) inline uint32_t arch_get_cpu_freq_hz() { return sys_clock_hw_cycles_per_sec(); }
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ from enum import Enum
|
||||
|
||||
from esphome.enum import StrEnum
|
||||
|
||||
__version__ = "2026.11.0b4"
|
||||
__version__ = "2026.11.0b6"
|
||||
|
||||
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
VALID_SUBSTITUTIONS_CHARACTERS = (
|
||||
|
||||
@@ -294,6 +294,8 @@ void Application::reboot() {
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
// No teardown on a forced reboot, but still power hardware down (Wi-Fi leaves the AP)
|
||||
this->run_powerdown_hooks();
|
||||
arch_restart();
|
||||
}
|
||||
void Application::safe_reboot() {
|
||||
|
||||
@@ -185,10 +185,12 @@ class Component {
|
||||
*/
|
||||
virtual bool teardown() { return true; }
|
||||
|
||||
/** Called after teardown is complete to power down hardware.
|
||||
/** Called last before a reboot or deep sleep to power down hardware.
|
||||
*
|
||||
* This is called after all components have finished their teardown process,
|
||||
* On a safe shutdown this is called after all components have finished their teardown process,
|
||||
* making it safe to power down hardware like ethernet PHY.
|
||||
* On a forced reboot (Application::reboot()) it is called right after on_shutdown() with no
|
||||
* teardown, so implementations must not assume teardown() has run.
|
||||
*/
|
||||
virtual void on_powerdown() {}
|
||||
|
||||
|
||||
@@ -481,6 +481,7 @@
|
||||
#ifdef USE_ESP32
|
||||
#define USE_ESP32_CRASH_HANDLER
|
||||
#define USE_ESP32_VASPRINTF_STUB
|
||||
#define USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
#define USE_MQTT_IDF_ENQUEUE
|
||||
#define USE_MQTT_TLS
|
||||
#define USE_MQTT_CERT_BUNDLE
|
||||
@@ -508,6 +509,7 @@
|
||||
#define USE_WIFI_SCAN_RESULTS_LOCK
|
||||
#define USE_ESP32_BLE
|
||||
#define USE_ESP32_BLE_BLUEDROID_BOND_KEYS
|
||||
#define USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE
|
||||
#define USE_ESP32_BLE_BLUEDROID_HEX_WRAPS
|
||||
#define USE_ESP32_BLE_GATTC_HANDLE_ORDER
|
||||
#define USE_ESP32_BLE_MAX_CONNECTIONS 3
|
||||
|
||||
@@ -2282,6 +2282,11 @@ class LwIPLock {
|
||||
// Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
|
||||
LwIPLock();
|
||||
~LwIPLock();
|
||||
#ifdef USE_ESP32
|
||||
private:
|
||||
// Only the instance that took the core lock releases it; unused without CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
[[maybe_unused]] bool locked_{false};
|
||||
#endif
|
||||
#else
|
||||
// No lwIP core locking — inline no-ops (empty bodies instead of = default
|
||||
// to prevent clang-tidy unused-variable warnings at call sites)
|
||||
|
||||
+32
-14
@@ -9,11 +9,29 @@
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
#include <hardware/sync.h>
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "scheduler");
|
||||
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
// lwIP callbacks add and cancel items from a low-priority IRQ on RP2, where lock_ is an empty Mutex: hold interrupts
|
||||
// off instead. Not the lwIP lock: each release re-arms arduino-pico's 20 ms Ethernet poll, starving reception.
|
||||
class SchedulerLockGuard {
|
||||
public:
|
||||
explicit SchedulerLockGuard(Mutex & /*mutex*/) : state_(save_and_disable_interrupts()) {}
|
||||
~SchedulerLockGuard() { restore_interrupts(this->state_); }
|
||||
|
||||
private:
|
||||
uint32_t state_;
|
||||
};
|
||||
#else
|
||||
using SchedulerLockGuard = LockGuard;
|
||||
#endif
|
||||
|
||||
// Maximum number of logically deleted (cancelled) items before forcing cleanup.
|
||||
// Empirically chosen to balance cleanup overhead against tombstone accumulation in items_.
|
||||
static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
|
||||
@@ -118,7 +136,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
if (delay == SCHEDULER_DONT_RUN) {
|
||||
// Still need to cancel existing timer if we have a name/id
|
||||
if (!skip_cancel) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, /* find_first= */ true);
|
||||
}
|
||||
return;
|
||||
@@ -140,7 +158,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
uint32_t offset = 0;
|
||||
// Take lock early to protect scheduler_item_pool_head_ access
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Create and populate the scheduler item
|
||||
SchedulerItem *item = this->get_item_from_pool_locked_();
|
||||
@@ -317,7 +335,7 @@ void Scheduler::full_cleanup_removed_items_() {
|
||||
// 2. Other threads must see either the old state or the new state, not intermediate states
|
||||
// 3. The operation is already expensive (O(n)), so lock overhead is negligible
|
||||
// 4. No operations inside can block or take other locks, so no deadlock risk
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Compact in-place: move valid items forward, recycle removed ones
|
||||
size_t write = 0;
|
||||
@@ -440,7 +458,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item;
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
item = this->pop_raw_locked_();
|
||||
}
|
||||
|
||||
@@ -457,7 +475,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
ESP_LOGD(TAG, "\n");
|
||||
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->items_ = std::move(old_items);
|
||||
// Rebuild heap after moving items back
|
||||
std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
|
||||
@@ -494,7 +512,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
|
||||
// Multi-threaded platforms without atomics: must take lock to safely read remove flag
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
if (is_item_removed_locked_(item)) {
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
@@ -504,7 +522,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#else
|
||||
// Single-threaded or multi-threaded with atomics: can check without lock
|
||||
if (is_item_removed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
continue;
|
||||
@@ -513,7 +531,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
|
||||
// Don't run on failed components (is_item_failed_ exempts SELF_POINTER delays).
|
||||
if (this->is_item_failed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
continue;
|
||||
}
|
||||
@@ -533,7 +551,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// - timeouts/intervals get cancelled
|
||||
now = this->execute_item_(item, now);
|
||||
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Only pop after function call, this ensures we were reachable
|
||||
// during the function call and know if we were cancelled.
|
||||
@@ -583,7 +601,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// every item has been returned to a container (items_, to_add_, or pool).
|
||||
// Lock needed to get a consistent snapshot of all containers.
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->debug_verify_no_leak_();
|
||||
}
|
||||
#endif
|
||||
@@ -592,7 +610,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
return now;
|
||||
}
|
||||
void HOT Scheduler::process_to_add_slow_path_() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
for (auto *&it : this->to_add_) {
|
||||
if (is_item_removed_locked_(it)) {
|
||||
// Recycle cancelled items
|
||||
@@ -616,7 +634,7 @@ bool HOT Scheduler::cleanup_slow_path_() {
|
||||
// 4. We need a consistent view of items_ and to_remove_ throughout the operation
|
||||
// Without the lock, we could access items_ while another thread is reading it,
|
||||
// leading to race conditions
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item = this->items_[0];
|
||||
if (!this->is_item_removed_locked_(item))
|
||||
@@ -664,7 +682,7 @@ uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
|
||||
// Common implementation for cancel operations - handles locking
|
||||
bool HOT Scheduler::cancel_item_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
|
||||
SchedulerItem::Type type) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
// Public cancel path uses default find_first=false to cancel ALL matches because
|
||||
// DelayAction parallel mode (skip_cancel=true) can create multiple items with the same key.
|
||||
return this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type);
|
||||
@@ -773,7 +791,7 @@ void __attribute__((noinline)) Scheduler::shrink_scheduler_vector_(std::vector<S
|
||||
}
|
||||
|
||||
void Scheduler::trim_freelist() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
SchedulerItem *item = this->scheduler_item_pool_head_;
|
||||
size_t freed = 0;
|
||||
while (item != nullptr) {
|
||||
|
||||
@@ -518,7 +518,8 @@ class Scheduler {
|
||||
uint32_t hash_or_id,
|
||||
SchedulerItem::Type type, bool find_first);
|
||||
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there; RP2 with networking locks by
|
||||
// holding interrupts off (SchedulerLockGuard in scheduler.cpp)
|
||||
[[no_unique_address]] Mutex lock_;
|
||||
std::vector<SchedulerItem *> items_;
|
||||
std::vector<SchedulerItem *> to_add_;
|
||||
|
||||
+5
-5
@@ -125,7 +125,7 @@ lib_deps =
|
||||
ESP8266WiFi ; wifi (Arduino built-in)
|
||||
Update ; ota (Arduino built-in)
|
||||
ESP32Async/ESPAsyncTCP@2.0.0 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
makuna/NeoPixelBus@2.7.3 ; neopixelbus
|
||||
ESP8266HTTPClient ; http_request (Arduino built-in)
|
||||
ESP8266mDNS ; mdns (Arduino built-in)
|
||||
@@ -216,8 +216,8 @@ framework = arduino
|
||||
lib_deps =
|
||||
${common:arduino.lib_deps}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ayushsharma82/RPAsyncTCP@1.3.2 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
https://github.com/esphome-libs/RPAsyncTCP.git#1.3.2-esphome.1 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
WiFi ; wifi (arduino-pico built-in)
|
||||
lwIP_CYW43 ; wifi (arduino-pico built-in, WiFi dependency)
|
||||
HTTPClient ; http_request (arduino-pico built-in)
|
||||
@@ -245,10 +245,10 @@ lib_compat_mode = soft
|
||||
lib_deps =
|
||||
${common.lib_deps_base}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
esphome/wireguard@0.4.8 ; wireguard
|
||||
esphome/noise-c@0.1.31 ; noise (api, ota)
|
||||
ESP32Async/AsyncTCP@3.4.5 ; async_tcp
|
||||
ESP32Async/AsyncTCP@3.5.0 ; async_tcp
|
||||
DNSServer ; captive_portal
|
||||
heman/AsyncMqttClient-esphome@2.0.0 ; mqtt
|
||||
improv/Improv@1.2.7 ; improv_serial
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for the api wizard: schema, final validation and generated tables."""
|
||||
|
||||
from collections.abc import Callable
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
@@ -8,13 +9,20 @@ import re
|
||||
import string
|
||||
import textwrap
|
||||
|
||||
from aioesphomeapi.model import COMPONENT_TYPE_TO_INFO
|
||||
import pytest
|
||||
|
||||
from esphome.components.api import wizard
|
||||
from esphome.components.homeassistant.switch import SUPPORTED_DOMAINS as SWITCH_DOMAINS
|
||||
from esphome.config import load_config
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.helpers import fnv1_hash, fnv1a_32bit_hash, zstd_module
|
||||
from esphome.cpp_generator import MockObjClass
|
||||
from esphome.helpers import (
|
||||
fnv1_hash,
|
||||
fnv1_hash_object_id,
|
||||
fnv1a_32bit_hash,
|
||||
zstd_module,
|
||||
)
|
||||
from tests.component_tests.helpers import get_define_value
|
||||
|
||||
ESP32_HEADER = """
|
||||
@@ -774,9 +782,14 @@ def test_the_blob_is_the_exact_json_document(
|
||||
"description": "Pick",
|
||||
"entities": [
|
||||
# No device_id for the main device, and no description when unset
|
||||
{"key": entity_hash(main_cpp, "sw"), "description": "Enable"},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
],
|
||||
@@ -1074,16 +1087,206 @@ def test_an_entity_role_is_sent_with_the_entity(
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
"role": "example.enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_entities_sharing_a_name_are_told_apart_by_platform(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
sensor:
|
||||
- platform: template
|
||||
id: power_sensor
|
||||
name: Power
|
||||
switch:
|
||||
- platform: template
|
||||
id: power_switch
|
||||
name: Power
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: power_sensor
|
||||
- id: power_switch
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
# The key is the same, so the platform is what says which entity is meant
|
||||
key = fnv1_hash_object_id("Power")
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": key, "platform": "sensor"},
|
||||
{"key": key, "platform": "switch"},
|
||||
]
|
||||
|
||||
|
||||
def test_a_datetime_entity_has_the_platform_of_its_type(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
datetime:
|
||||
- platform: template
|
||||
id: dt_date
|
||||
name: Day
|
||||
type: date
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_time
|
||||
name: Hour
|
||||
type: time
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_datetime
|
||||
name: Moment
|
||||
type: datetime
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: dt_date
|
||||
- id: dt_time
|
||||
- id: dt_datetime
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Day"), "platform": "date"},
|
||||
{"key": fnv1_hash_object_id("Hour"), "platform": "time"},
|
||||
{"key": fnv1_hash_object_id("Moment"), "platform": "datetime"},
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_declared_in_its_component_has_the_platform_of_its_class(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
uart:
|
||||
tx_pin: 17
|
||||
rx_pin: 16
|
||||
baud_rate: 9600
|
||||
gps:
|
||||
latitude:
|
||||
id: gps_lat
|
||||
name: Latitude
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: gps_lat
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Latitude"), "platform": "sensor"}
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_of_a_platform_the_wizard_does_not_know_is_rejected(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
entities = """
|
||||
psram:
|
||||
i2c:
|
||||
id: camera_bus
|
||||
sda: 25
|
||||
scl: 23
|
||||
esp32_camera:
|
||||
id: test_camera
|
||||
name: Camera
|
||||
data_pins: [17, 35, 34, 5, 39, 18, 36, 19]
|
||||
vsync_pin: 22
|
||||
href_pin: 26
|
||||
pixel_clock_pin: 21
|
||||
external_clock:
|
||||
pin: 27
|
||||
i2c_id: camera_bus
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: test_camera
|
||||
"""
|
||||
|
||||
errors = config_errors(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert any(
|
||||
"Entity 'test_camera' is not of a platform the wizard can show" in error
|
||||
for error in errors
|
||||
), errors
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("class_name", "platform"), wizard.WIZARD_ENTITY_PLATFORMS.items()
|
||||
)
|
||||
def test_every_wizard_entity_platform_names_a_real_entity_class(
|
||||
class_name: str, platform: str
|
||||
) -> None:
|
||||
namespace, _ = class_name.split("::")
|
||||
component = importlib.import_module(
|
||||
f"esphome.components.{namespace.removesuffix('_')}"
|
||||
)
|
||||
# Light keeps its classes in a submodule
|
||||
modules = [component, *(getattr(component, "types", None),)]
|
||||
classes = {
|
||||
str(value)
|
||||
for module in modules
|
||||
if module is not None
|
||||
for value in vars(module).values()
|
||||
if isinstance(value, MockObjClass)
|
||||
}
|
||||
assert class_name in classes
|
||||
# The name the API client knows the entity type by
|
||||
assert platform in COMPONENT_TYPE_TO_INFO
|
||||
|
||||
|
||||
# Entity platforms of the API that a wizard page cannot show
|
||||
WIZARD_UNSUPPORTED_PLATFORMS: set[str] = {
|
||||
# ESP32Camera derives from EntityBase directly, with no camera base class to recognise
|
||||
"camera",
|
||||
# MediaPlayer does not declare EntityBase, so the page's use_id(EntityBase) already rejects it
|
||||
"media_player",
|
||||
# No ESPHome component provides one
|
||||
"siren",
|
||||
}
|
||||
|
||||
|
||||
def test_every_api_entity_platform_is_known_to_the_wizard() -> None:
|
||||
"""A new entity platform needs a WIZARD_ENTITY_PLATFORMS entry, or a reason to be left out."""
|
||||
proto = (
|
||||
Path(wizard.__file__).parent.joinpath("api.proto").read_text(encoding="utf-8")
|
||||
)
|
||||
messages = re.findall(r"message ListEntities(?!Done|Services)\w+Response \{", proto)
|
||||
# The ifdef of each ListEntities message names its platform: USE_SENSOR, USE_DATETIME_DATE, ...
|
||||
ifdefs = re.findall(
|
||||
r"message ListEntities(?!Done|Services)\w+Response \{[^}]*?"
|
||||
r'option \(ifdef\) = "USE_(\w+)";',
|
||||
proto,
|
||||
)
|
||||
assert len(ifdefs) == len(messages)
|
||||
proto_platforms = {ifdef.lower().removeprefix("datetime_") for ifdef in ifdefs}
|
||||
assert (
|
||||
set(wizard.WIZARD_ENTITY_PLATFORMS.values()) | WIZARD_UNSUPPORTED_PLATFORMS
|
||||
== proto_platforms
|
||||
)
|
||||
|
||||
|
||||
def test_an_entity_with_a_role_may_be_in_the_wizard_twice(tmp_path: Path) -> None:
|
||||
wizard.register_entity_role(ID("sw", is_declaration=True), "example.enable")
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
"""LibreTiny always gets the xPortGetCoreID stand-in, whatever its log level."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_libretiny_adds_core_id_flag(
|
||||
generate_main: Callable[[str | Path], str], tmp_path: Path
|
||||
) -> None:
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\n"
|
||||
"bk72xx:\n board: generic-bk7231n-qfn32-tuya\n\n"
|
||||
"wifi:\n ssid: test\n password: testtest12\n\n"
|
||||
"async_tcp:\n"
|
||||
)
|
||||
generate_main(config)
|
||||
assert "-DxPortGetCoreID=int" in CORE.build_flags
|
||||
@@ -818,9 +818,18 @@ def test_uc8279_offset_height_configurable(
|
||||
assert resolution == (0x61, 0x00, 0x10, 0x00, 0x0A)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dimensions",
|
||||
[
|
||||
{"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
# offset_height not written: the default of 0 applies, and the error must not point at a missing key
|
||||
{"width": 16, "height": 0x10000},
|
||||
],
|
||||
)
|
||||
def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config: Callable[[str, Any], None],
|
||||
dimensions: dict[str, int],
|
||||
) -> None:
|
||||
"""offset_height plus the panel height is the gate count, which the controller holds in 16 bits."""
|
||||
set_core_config(
|
||||
@@ -829,15 +838,16 @@ def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
)
|
||||
set_component_config("spi", {"id": "spi_bus", "clk_pin": 18, "mosi_pin": 19})
|
||||
|
||||
with pytest.raises(cv.Invalid, match="must not exceed"):
|
||||
with pytest.raises(cv.Invalid, match="must not exceed") as exc_info:
|
||||
run_schema_validation(
|
||||
{
|
||||
"id": "test_display",
|
||||
"model": "uc8279",
|
||||
"dc_pin": 21,
|
||||
"dimensions": {"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
"dimensions": dimensions,
|
||||
}
|
||||
)
|
||||
assert exc_info.value.path[-2:] == ["dimensions", "height"]
|
||||
|
||||
|
||||
def test_uc8279_x4pro_explicit_dimensions_keep_the_model_offset(
|
||||
|
||||
@@ -7,8 +7,9 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SRC_CMAKE
|
||||
from esphome.components.esp32_ble import bluedroid_headers_cmake
|
||||
from esphome.components.esp32_ble import _drops_bond_keys, bluedroid_headers_cmake
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAP_FLAGS = {
|
||||
@@ -19,12 +20,31 @@ _WRAP_FLAGS = {
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "expected"),
|
||||
[
|
||||
("5.5.5", False),
|
||||
("5.5.6", True),
|
||||
("5.5.7", True),
|
||||
("6.0.0", False),
|
||||
("6.0.3", False),
|
||||
("6.1.0", False),
|
||||
("6.1.1", True),
|
||||
("6.2.0", True),
|
||||
],
|
||||
)
|
||||
def test_drops_bond_keys_versions(version: str, expected: bool) -> None:
|
||||
"""ESP-IDF added the bond clearing in 5.5.6 and 6.1.1."""
|
||||
assert _drops_bond_keys(cv.Version.parse(version)) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "windows", "expected"),
|
||||
[
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", False, True, id="idf_5_5_6"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.5}", False, False, id="idf_5_5_5"),
|
||||
pytest.param("{type: esp-idf, version: 6.0.1}", False, False, id="idf_6"),
|
||||
pytest.param("{type: esp-idf, version: 6.1.1}", False, True, id="idf_6_1_1"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", True, False, id="windows"),
|
||||
# Arduino 3.3.12 is built on ESP-IDF 5.5.6, 3.3.11 on 5.5.5
|
||||
pytest.param(
|
||||
@@ -48,7 +68,7 @@ _WRAP_FLAGS = {
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wraps_only_on_idf_5_5_6_native_builds(
|
||||
def test_wraps_only_on_affected_idf_native_builds(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -39,11 +39,14 @@ _CLIENTS = {
|
||||
("6.0.0", False),
|
||||
("6.0.2", False),
|
||||
("6.0.3", True),
|
||||
("6.1.0", True),
|
||||
("6.0.4", True),
|
||||
("6.1.0", False),
|
||||
("6.1.1", True),
|
||||
("6.2.0", True),
|
||||
],
|
||||
)
|
||||
def test_strict_handle_order_versions(version: str, expected: bool) -> None:
|
||||
"""ESP-IDF added the check in 5.5.6 and 6.0.3."""
|
||||
"""ESP-IDF added the check in 5.5.6, 6.0.3 and 6.1.1."""
|
||||
assert _has_strict_handle_order(cv.Version.parse(version)) is expected
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Tests for the Bluedroid wraps that drop a failed queued GATT client command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SRC_CMAKE
|
||||
from esphome.components.esp32_ble import bluedroid_headers_cmake
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAPPED = (
|
||||
"bta_gattc_cfg_mtu",
|
||||
"bta_gattc_execute",
|
||||
"GATTC_ConfigureMTU",
|
||||
"GATTC_ExecuteWrite",
|
||||
)
|
||||
_WRAP_FLAGS = {f"-Wl,--wrap={s}" for s in _WRAPPED} | {
|
||||
f"-Wl,--undefined=__wrap_{s}" for s in _WRAPPED
|
||||
}
|
||||
_TRACKER = "\nesp32_ble_tracker: {}\n"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "components", "windows", "expected"),
|
||||
[
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", _TRACKER, False, True, id="idf_5_5_6"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 6.0.1}", _TRACKER, False, True, id="idf_6"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.12}", _TRACKER, False, True, id="arduino"
|
||||
),
|
||||
# Without the tracker or esp32_ble_client there is no GATT client
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", "", False, False, id="no_gatt_client"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", _TRACKER, True, False, id="windows"
|
||||
),
|
||||
# PlatformIO builds cannot reach the private headers
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}\n toolchain: platformio",
|
||||
_TRACKER,
|
||||
False,
|
||||
False,
|
||||
id="platformio",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wraps_on_native_builds_with_a_gatt_client(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
framework: str,
|
||||
components: str,
|
||||
windows: bool,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("esphome.components.esp32_ble.IS_WINDOWS", windows)
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\nesp32:\n variant: esp32\n"
|
||||
f" framework: {framework}\n\nesp32_ble: {{}}\n{components}"
|
||||
)
|
||||
generate_main(config)
|
||||
assert CORE.build_flags & _WRAP_FLAGS == (_WRAP_FLAGS if expected else set())
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE" in defines) is expected
|
||||
headers = bluedroid_headers_cmake("bluedroid_gattc_queue.c")
|
||||
assert (headers in CORE.data[KEY_ESP32][KEY_SRC_CMAKE]) is expected
|
||||
@@ -28,19 +28,22 @@ _WRAP_FLAGS = {
|
||||
pytest.param("esp32c2", "{type: esp-idf}", True, id="c2"),
|
||||
pytest.param("esp32c6", "{type: esp-idf}", False, id="c6_rom_sscanf"),
|
||||
pytest.param(
|
||||
"esp32", "{type: esp-idf, version: 6.0.1}", False, id="idf6_picolibc"
|
||||
"esp32", "{type: esp-idf, version: 6.0.1}", True, id="idf6_picolibc"
|
||||
),
|
||||
pytest.param(
|
||||
"esp32c6", "{type: esp-idf, version: 6.0.1}", True, id="c6_idf6_picolibc"
|
||||
),
|
||||
pytest.param("esp32", "{type: arduino}", False, id="arduino"),
|
||||
],
|
||||
)
|
||||
def test_wraps_only_on_newlib_idf_without_rom_sscanf(
|
||||
def test_wraps_only_on_idf_without_rom_sscanf(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
variant: str,
|
||||
framework: str,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
"""The wraps are emitted only where Bluedroid's sscanf calls link newlib's engine."""
|
||||
"""The wraps are emitted only where Bluedroid's sscanf calls link a scanf engine."""
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
f"esphome:\n name: test\n\nesp32:\n variant: {variant}\n"
|
||||
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.const import CONF_DEVICE_TYPE
|
||||
from esphome.components.esp32 import (
|
||||
KEY_IDF_VERSION,
|
||||
KEY_VARIANT,
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C6,
|
||||
@@ -33,6 +34,7 @@ from esphome.types import ConfigType
|
||||
from tests.component_tests.types import SetCoreConfigCallable
|
||||
|
||||
LIGHT_SLEEP = {CONF_ENABLE_LIGHT_SLEEP: True}
|
||||
IDF_VERSION = cv.Version(5, 5, 5)
|
||||
|
||||
|
||||
def _set_variant(
|
||||
@@ -41,11 +43,12 @@ def _set_variant(
|
||||
/,
|
||||
*,
|
||||
full_config: ConfigType | None = None,
|
||||
idf_version: cv.Version = IDF_VERSION,
|
||||
) -> None:
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
core_data={KEY_FRAMEWORK_VERSION: cv.Version(5, 5, 5)},
|
||||
platform_data={KEY_VARIANT: variant},
|
||||
core_data={KEY_FRAMEWORK_VERSION: idf_version},
|
||||
platform_data={KEY_VARIANT: variant, KEY_IDF_VERSION: idf_version},
|
||||
full_config=full_config,
|
||||
)
|
||||
|
||||
@@ -360,3 +363,32 @@ async def test_to_code_sdkconfig(
|
||||
CORE.config = core_config
|
||||
await to_code(CONFIG_SCHEMA({CONF_ENABLE_LIGHT_SLEEP: light_sleep}))
|
||||
assert sdkconfig_calls.get(key, NOT_SET) is expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("idf_version", "light_sleep", "kconfig", "guard"),
|
||||
[
|
||||
pytest.param(cv.Version(5, 5, 6), True, NOT_SET, True, id="idf55_wrap"),
|
||||
pytest.param(cv.Version(6, 0, 0), True, NOT_SET, True, id="idf600_wrap"),
|
||||
pytest.param(cv.Version(6, 0, 1), True, True, False, id="idf601_kconfig"),
|
||||
pytest.param(cv.Version(5, 5, 6), False, NOT_SET, False, id="light_sleep_off"),
|
||||
],
|
||||
)
|
||||
async def test_tick_overflow_guard(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
sdkconfig_calls: dict[str, object],
|
||||
idf_version: cv.Version,
|
||||
light_sleep: bool,
|
||||
kconfig: object,
|
||||
guard: bool,
|
||||
) -> None:
|
||||
"""IDF 6.0.1 has the overflow protection built in; older releases get the --wrap backport."""
|
||||
_set_variant(set_core_config, VARIANT_ESP32H2, idf_version=idf_version)
|
||||
CORE.config = {}
|
||||
await to_code(CONFIG_SCHEMA({CONF_ENABLE_LIGHT_SLEEP: light_sleep}))
|
||||
key = "CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION"
|
||||
assert sdkconfig_calls.get(key, NOT_SET) is kconfig
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_PM_TICK_OVERFLOW_GUARD" in defines) is guard
|
||||
assert ("-Wl,--wrap=vTaskStepTick" in CORE.build_flags) is guard
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Every LibreTiny family frees closed TCP connections after about 1 s (TCP_MSL=250)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_file", ["bk72xx.yaml", "rtl8710b.yaml", "rtl8720c.yaml", "ln882x.yaml"]
|
||||
)
|
||||
def test_lwip_tcp_msl_is_250(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
config_file: str,
|
||||
) -> None:
|
||||
generate_main(component_config_path(config_file))
|
||||
assert "TCP_MSL=250" in CORE.platformio_options["custom_options.lwip"]
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Tests for the usb_host sdkconfig defaults."""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from esphome.components.esp32 import RawSdkconfigValue
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_usb_host_uses_default_control_transfer_size(
|
||||
generate_main: Callable[[str], str],
|
||||
) -> None:
|
||||
"""usb_host retains its existing 1024-byte default."""
|
||||
generate_main("tests/component_tests/usb_host/usb_host.yaml")
|
||||
|
||||
assert (
|
||||
CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS][
|
||||
"CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE"
|
||||
]
|
||||
== 1024
|
||||
)
|
||||
|
||||
|
||||
def test_usb_host_respects_explicit_control_transfer_size(
|
||||
generate_main: Callable[[str], str],
|
||||
) -> None:
|
||||
"""An explicit sdkconfig option takes precedence over the component default."""
|
||||
generate_main(
|
||||
"tests/component_tests/usb_host/usb_host_control_transfer_override.yaml"
|
||||
)
|
||||
|
||||
value = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS][
|
||||
"CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE"
|
||||
]
|
||||
assert isinstance(value, RawSdkconfigValue)
|
||||
assert value.value == "4096"
|
||||
@@ -0,0 +1,9 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
variant: esp32s3
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
usb_host:
|
||||
@@ -0,0 +1,11 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
variant: esp32s3
|
||||
framework:
|
||||
type: esp-idf
|
||||
sdkconfig_options:
|
||||
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE: "4096"
|
||||
|
||||
usb_host:
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
|
||||
namespace esphome::bluetooth_connection::testing {
|
||||
|
||||
using ble_device_base::ESPBTUUID;
|
||||
@@ -46,4 +49,59 @@ TEST(GattUuidPacking, EstimateGrowsWithCharacteristicsAndMode) {
|
||||
EXPECT_LT(estimate_service_size(1, false), estimate_service_size(2, false));
|
||||
}
|
||||
|
||||
// BTstack hands every GATT UUID over as 128 bits, big-endian; uuid_from_be128 picks the short form
|
||||
static constexpr uint8_t BASE_TAIL[12] = {0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
|
||||
|
||||
static ESPBTUUID on_base(uint32_t value) {
|
||||
uint8_t be[16] = {static_cast<uint8_t>(value >> 24), static_cast<uint8_t>(value >> 16),
|
||||
static_cast<uint8_t>(value >> 8), static_cast<uint8_t>(value)};
|
||||
memcpy(be + 4, BASE_TAIL, sizeof(BASE_TAIL));
|
||||
return uuid_from_be128(be);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, SixteenBitOnBase) {
|
||||
const ESPBTUUID uuid = on_base(0x180F);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID16);
|
||||
EXPECT_EQ(uuid.uuid16(), 0x180F);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, ThirtyTwoBitOnBaseKeepsTopHalf) {
|
||||
// 5EC10001-0000-1000-8000-00805F9B34FB: BTstack's own uuid16 is 0x0001 for this one
|
||||
const ESPBTUUID uuid = on_base(0x5EC10001);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID32);
|
||||
EXPECT_EQ(uuid.uuid32(), 0x5EC10001u);
|
||||
|
||||
std::array<uint64_t, 2> uuid128{};
|
||||
uint32_t short_uuid = 0;
|
||||
fill_gatt_uuid(uuid128, short_uuid, uuid, true);
|
||||
EXPECT_EQ(short_uuid, 0x5EC10001u);
|
||||
|
||||
short_uuid = 0;
|
||||
fill_gatt_uuid(uuid128, short_uuid, uuid, false);
|
||||
EXPECT_EQ(short_uuid, 0u);
|
||||
EXPECT_EQ(uuid128[0], 0x5EC1000100001000ULL);
|
||||
EXPECT_EQ(uuid128[1], 0x800000805F9B34FBULL);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, ShortFormBoundary) {
|
||||
EXPECT_EQ(on_base(0xFFFF).type(), ESPBTUUID::Type::UUID16);
|
||||
const ESPBTUUID uuid = on_base(0x10000);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID32);
|
||||
EXPECT_EQ(uuid.uuid32(), 0x10000u);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, OffBaseStaysFullWidth) {
|
||||
const uint8_t big_endian[16] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF,
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
|
||||
const ESPBTUUID uuid = uuid_from_be128(big_endian);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID128);
|
||||
EXPECT_EQ(uuid, ESPBTUUID::from_raw_reversed(big_endian));
|
||||
|
||||
// One byte off the base tail is a different 128-bit UUID, not a short one
|
||||
uint8_t near_base[16] = {0x00, 0x00, 0x18, 0x0F};
|
||||
memcpy(near_base + 4, BASE_TAIL, sizeof(BASE_TAIL));
|
||||
near_base[15] ^= 1;
|
||||
EXPECT_EQ(uuid_from_be128(near_base).type(), ESPBTUUID::Type::UUID128);
|
||||
}
|
||||
|
||||
} // namespace esphome::bluetooth_connection::testing
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# dht is a sensor platform; its header needs the sensor component
|
||||
manifest.dependencies = manifest.dependencies + ["sensor"]
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/dht/dht.h"
|
||||
|
||||
namespace esphome::dht::testing {
|
||||
|
||||
TEST(DHTDecodeTemperature, Positive) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0000), 0);
|
||||
EXPECT_EQ(decode_dht22_temperature(0x00E7), 231); // 23.1 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x01F4), 500); // 50.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, SignAndMagnitude) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8034), -52); // -5.2 C, read as -5.3 C before
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8001), -1); // -0.1 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8000), 0); // -0.0 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8190), -400); // -40.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, SixteenBitTwosComplement) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0xFFCC), -52); // -5.2 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0xFE70), -400); // -40.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, TwelveBitTwosComplement) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0FCC), -52); // -5.2 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0E70), -400); // -40.0 C
|
||||
}
|
||||
|
||||
} // namespace esphome::dht::testing
|
||||
@@ -0,0 +1,2 @@
|
||||
packages:
|
||||
dht: !include common.yaml
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "esphome/components/epaper_spi/epaper_spi_jd79660.h"
|
||||
#include "esphome/components/epaper_spi/epaper_spi_t133a01.h"
|
||||
#include "esphome/components/epaper_spi/epaper_waveshare_bwr.h"
|
||||
#include "esphome/components/epaper_spi/epaper_weact_3c.h"
|
||||
|
||||
namespace esphome::epaper_spi::testing {
|
||||
namespace {
|
||||
|
||||
/// Reaches the protected EPaperBase members of any driver, including final ones, through member pointers.
|
||||
class EPaperBaseAccess : public EPaperBase {
|
||||
public:
|
||||
/// Leaves the display as a completed refresh leaves it: nothing drawn and no full update pending.
|
||||
static void set_refreshed(EPaperBase &display) {
|
||||
EXPECT_TRUE((display.*&EPaperBaseAccess::init_buffer_)(display.*&EPaperBaseAccess::buffer_length_));
|
||||
(display.*&EPaperBaseAccess::reset_bounds_)();
|
||||
display.*&EPaperBaseAccess::full_update_requested_ = false;
|
||||
}
|
||||
/// The request count is shared by the whole test binary, so a display left mid-update must give its request back.
|
||||
static void stop_fast_loop(EPaperBase &display) { (display.*&EPaperBaseAccess::high_frequency_loop_).stop(); }
|
||||
};
|
||||
|
||||
template<typename Driver, typename... Args> std::unique_ptr<Driver> make_refreshed(Args... args) {
|
||||
auto display = std::make_unique<Driver>("test", 16, 2, nullptr, 0, args...);
|
||||
EPaperBaseAccess::set_refreshed(*display);
|
||||
return display;
|
||||
}
|
||||
|
||||
template<typename Driver> std::unique_ptr<Driver> make_display() { return make_refreshed<Driver>(); }
|
||||
|
||||
template<> std::unique_ptr<EPaperJD79660> make_display() { return make_refreshed<EPaperJD79660>(nullptr, 0); }
|
||||
|
||||
/// Runs the UPDATE state; true if the update goes on to send the frame.
|
||||
bool update_is_sent(EPaperBase &display) {
|
||||
display.update();
|
||||
display.loop();
|
||||
return display.is_updating();
|
||||
}
|
||||
|
||||
/// fill() writes the whole buffer without drawing pixels, so it must mark the frame drawn itself. Otherwise the
|
||||
/// UPDATE state finds nothing drawn after a refresh, and returns to idle without sending the frame.
|
||||
template<typename Driver> class EPaperFillMarksDrawn : public ::testing::Test {
|
||||
protected:
|
||||
void TearDown() override { EPaperBaseAccess::stop_fast_loop(*this->display_); }
|
||||
std::unique_ptr<Driver> display_ = make_display<Driver>();
|
||||
};
|
||||
|
||||
using Drivers = ::testing::Types<EPaperWaveshareBWR, EPaperT133A01, EPaperJD79660, EPaperWeAct3C>;
|
||||
TYPED_TEST_SUITE(EPaperFillMarksDrawn, Drivers);
|
||||
|
||||
TYPED_TEST(EPaperFillMarksDrawn, FillOnlyUpdateIsSent) {
|
||||
this->display_->set_auto_clear(false);
|
||||
this->display_->fill(Color::WHITE);
|
||||
|
||||
EXPECT_TRUE(update_is_sent(*this->display_)) << "fill-only update was skipped";
|
||||
}
|
||||
|
||||
/// Auto clear fills the frame before the lambda runs, so an update whose lambda draws nothing still erases the
|
||||
/// previous image.
|
||||
TYPED_TEST(EPaperFillMarksDrawn, AutoClearUpdateIsSentWhenTheLambdaDrawsNothing) {
|
||||
this->display_->set_writer([](display::Display &) {});
|
||||
|
||||
EXPECT_TRUE(update_is_sent(*this->display_)) << "auto clear did not erase the previous image";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace esphome::epaper_spi::testing
|
||||
@@ -2,3 +2,7 @@ packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
|
||||
# IPv6 with an IP sensor: compiles the IPv6 event handler's listener notification
|
||||
network:
|
||||
enable_ipv6: true
|
||||
@@ -1,8 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.logger import CONF_BOOT_LOG_BUFFER_SIZE, request_log_listener
|
||||
from esphome.const import CONF_ESPHOME, CONF_INCLUDES
|
||||
from esphome.core import CORE
|
||||
from esphome.loader import FileResource
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
@@ -13,6 +15,10 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# logger must run its to_code during C++ test builds because it configures
|
||||
# the logging subsystem used by ESP_LOG* macros throughout component code.
|
||||
manifest.enable_codegen()
|
||||
# Compiled into the LibreTiny task log buffer test; empty on its own without USE_LIBRETINY
|
||||
manifest.add_resources(
|
||||
FileResource("esphome.components.logger", "task_log_buffer_libretiny.cpp")
|
||||
)
|
||||
|
||||
original_to_code = manifest.to_code
|
||||
|
||||
@@ -22,6 +28,10 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
if any(Path(p) == TESTS_DIR for p in CORE.config[CONF_ESPHOME][CONF_INCLUDES]):
|
||||
config = {**config, CONF_BOOT_LOG_BUFFER_SIZE: 512}
|
||||
request_log_listener()
|
||||
# FreeRTOS doubles for the LibreTiny task log buffer test
|
||||
cg.add_build_flag(
|
||||
f"-I{CORE.relative_src_path('logger', '__libretiny_sdk')}"
|
||||
)
|
||||
await original_to_code(config)
|
||||
|
||||
manifest.to_code = to_code
|
||||
@@ -0,0 +1,2 @@
|
||||
#pragma once
|
||||
// Host double for the LibreTiny FreeRTOS headers used by task_log_buffer_libretiny.cpp
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
// Single-threaded mutex double: every take succeeds
|
||||
using SemaphoreHandle_t = int *;
|
||||
inline SemaphoreHandle_t xSemaphoreCreateMutex() {
|
||||
static int mutex;
|
||||
return &mutex;
|
||||
}
|
||||
inline void vSemaphoreDelete(SemaphoreHandle_t /*mutex*/) {}
|
||||
inline int xSemaphoreTake(SemaphoreHandle_t /*mutex*/, int /*ticks*/) { return 1; }
|
||||
inline int xSemaphoreGive(SemaphoreHandle_t /*mutex*/) { return 1; }
|
||||
@@ -0,0 +1 @@
|
||||
#pragma once
|
||||
@@ -0,0 +1,6 @@
|
||||
// The same tests with a buffer size that needs no rounding
|
||||
#define TASK_LOG_TEST_NS libretiny_task_log_768
|
||||
#define TASK_LOG_TEST_SUITE LibreTinyTaskLogBuffer768
|
||||
#define TASK_LOG_TEST_SIZE static_cast<size_t>(768)
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include): reuse the tests with another buffer size.
|
||||
#include "task_log_buffer_libretiny_test.cpp"
|
||||
@@ -0,0 +1,154 @@
|
||||
#ifdef USE_HOST
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include <FreeRTOS.h>
|
||||
#include <semphr.h>
|
||||
#include <task.h>
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
// Not a multiple of 4; task_log_buffer_libretiny_768_test.cpp reuses this file with an aligned size
|
||||
#ifndef TASK_LOG_TEST_NS
|
||||
#define TASK_LOG_TEST_NS libretiny_task_log_766
|
||||
#define TASK_LOG_TEST_SUITE LibreTinyTaskLogBuffer766
|
||||
#define TASK_LOG_TEST_SIZE static_cast<size_t>(766)
|
||||
#endif
|
||||
|
||||
// Compile the LibreTiny buffer against the FreeRTOS doubles in __libretiny_sdk, in a namespace per size
|
||||
#define USE_LIBRETINY
|
||||
#ifndef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
#define USE_ESPHOME_TASK_LOG_BUFFER
|
||||
#endif
|
||||
#undef ESPHOME_TASK_LOG_BUFFER_SIZE
|
||||
#define ESPHOME_TASK_LOG_BUFFER_SIZE TASK_LOG_TEST_SIZE
|
||||
namespace TASK_LOG_TEST_NS {
|
||||
// Not global, where speaker_source's FreeRTOS double defines it in the same build
|
||||
inline constexpr int pdTRUE = 1;
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include): exercise production code with the host FreeRTOS double.
|
||||
#include "esphome/components/logger/task_log_buffer_libretiny.cpp"
|
||||
} // namespace TASK_LOG_TEST_NS
|
||||
#undef USE_LIBRETINY
|
||||
|
||||
namespace {
|
||||
|
||||
using TaskLogBuffer = TASK_LOG_TEST_NS::esphome::logger::TaskLogBuffer;
|
||||
|
||||
const char *const TAGS[] = {"a", "bb", "ccc"};
|
||||
|
||||
bool send_format(TaskLogBuffer &buffer, const char *tag, const char *format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
bool sent = buffer.send_message_thread_safe(3, tag, 1, nullptr, format, args);
|
||||
va_end(args);
|
||||
return sent;
|
||||
}
|
||||
|
||||
class TASK_LOG_TEST_SUITE : public ::testing::Test {
|
||||
protected:
|
||||
// Records the trimmed text expected back when the buffer accepts it
|
||||
bool send_(const char *tag, const std::string &text) {
|
||||
if (!send_format(this->buffer_, tag, "%s", text.c_str()))
|
||||
return false;
|
||||
std::string trimmed = text;
|
||||
while (!trimmed.empty() && trimmed.back() == '\n')
|
||||
trimmed.pop_back();
|
||||
this->expected_.emplace_back(tag, trimmed);
|
||||
return true;
|
||||
}
|
||||
// Stops one past what was sent, so a broken ring cannot loop forever
|
||||
void drain_(size_t count = SIZE_MAX) {
|
||||
TaskLogBuffer::LogMessage *msg;
|
||||
uint16_t length;
|
||||
for (count = std::min(count, this->expected_.size() + 1);
|
||||
count > 0 && this->buffer_.borrow_message_main_loop(msg, length); count--) {
|
||||
if (reinterpret_cast<uintptr_t>(msg) % alignof(TaskLogBuffer::LogMessage) != 0)
|
||||
this->misaligned_++;
|
||||
if (this->expected_.empty() || this->expected_.front().first != msg->tag ||
|
||||
this->expected_.front().second != std::string(msg->text_data(), length) || msg->text_data()[length] != '\0') {
|
||||
this->mismatches_++;
|
||||
} else {
|
||||
this->expected_.pop_front();
|
||||
}
|
||||
this->buffer_.release_message_main_loop();
|
||||
}
|
||||
}
|
||||
|
||||
TaskLogBuffer buffer_;
|
||||
std::deque<std::pair<const char *, std::string>> expected_;
|
||||
int misaligned_{0};
|
||||
int mismatches_{0};
|
||||
};
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, HeadersStayAligned) {
|
||||
for (size_t length = 1; length <= 40; length++) {
|
||||
ASSERT_TRUE(this->send_(TAGS[0], std::string(length, 'x')));
|
||||
if (length % 4 == 0)
|
||||
this->drain_();
|
||||
}
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, TrimsTrailingNewlinesAndKeepsOrder) {
|
||||
ASSERT_TRUE(this->send_(TAGS[0], "one"));
|
||||
ASSERT_TRUE(this->send_(TAGS[1], "two\n"));
|
||||
ASSERT_TRUE(this->send_(TAGS[2], "three\n\n"));
|
||||
ASSERT_TRUE(this->send_(TAGS[0], "four\nlines"));
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
EXPECT_TRUE(this->expected_.empty());
|
||||
EXPECT_FALSE(this->buffer_.has_messages());
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, EmptyBufferAcceptsEveryLengthAcrossWraps) {
|
||||
// Every write position comes up, including a message ending less than a header before the end
|
||||
for (int round = 0; round < 8; round++) {
|
||||
for (size_t length = 1; length <= 250; length++) {
|
||||
ASSERT_TRUE(this->send_(TAGS[length % 3], std::string(length, 'a' + length % 26) + (round % 2 ? "\n" : "")))
|
||||
<< "round " << round << " length " << length;
|
||||
this->drain_();
|
||||
}
|
||||
}
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, RandomizedTrafficMatchesWhatWasSent) {
|
||||
std::mt19937 rng(1);
|
||||
for (int op = 0; op < 200000; op++) {
|
||||
if (rng() % 3 != 0) {
|
||||
std::string text(1 + rng() % 120, 'x');
|
||||
for (auto &c : text)
|
||||
c = 'a' + rng() % 26;
|
||||
if (rng() % 2)
|
||||
text += "\n";
|
||||
if (rng() % 5 == 0)
|
||||
text += "\n\n";
|
||||
this->send_(TAGS[rng() % 3], text);
|
||||
} else {
|
||||
this->drain_(rng() % 4);
|
||||
}
|
||||
}
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
EXPECT_TRUE(this->expected_.empty());
|
||||
EXPECT_TRUE(this->send_(TAGS[0], "still accepted"));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
#endif // USE_HOST
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "esphome/components/logger/logger.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/preferences.h"
|
||||
|
||||
/*
|
||||
@@ -28,7 +29,18 @@ class ResetAppListener : public ::testing::EmptyTestEventListener {
|
||||
// Entities of the same kind share preference keys, so a value an earlier test saved would be restored
|
||||
if (esphome::global_preferences != nullptr)
|
||||
esphome::global_preferences->reset();
|
||||
this->high_frequency_at_start_ = esphome::HighFrequencyLoopRequester::is_high_frequency();
|
||||
}
|
||||
|
||||
// Fail only the test that left the fast loop on, so a leak points at its culprit
|
||||
void OnTestEnd(const ::testing::TestInfo &info) override {
|
||||
if (!this->high_frequency_at_start_ && esphome::HighFrequencyLoopRequester::is_high_frequency()) {
|
||||
ADD_FAILURE() << info.test_suite_name() << "." << info.name()
|
||||
<< " left a HighFrequencyLoopRequester started; stop it before the test ends";
|
||||
}
|
||||
}
|
||||
|
||||
bool high_frequency_at_start_{false};
|
||||
};
|
||||
|
||||
void setup() {
|
||||
|
||||
@@ -28,11 +28,11 @@ on_canalsat:
|
||||
- logger.log:
|
||||
format: "on_canalsat: %u %u"
|
||||
args: ["x.address", "x.command"]
|
||||
# on_canalsatld:
|
||||
# then:
|
||||
# - logger.log:
|
||||
# format: "on_canalsatld: %u %u"
|
||||
# args: ["x.address", "x.command"]
|
||||
on_canalsatld:
|
||||
then:
|
||||
- logger.log:
|
||||
format: "on_canalsatld: %u %u"
|
||||
args: ["x.address", "x.command"]
|
||||
on_coolix:
|
||||
then:
|
||||
- logger.log:
|
||||
|
||||
@@ -10,6 +10,19 @@ remote_receiver:
|
||||
<<: !include common-actions.yaml
|
||||
|
||||
binary_sensor:
|
||||
- platform: remote_receiver
|
||||
name: CanalSatLD Remote Input
|
||||
canalsatld:
|
||||
device: 0x7F
|
||||
command: 0x12
|
||||
- platform: remote_receiver
|
||||
name: Haier Remote Input
|
||||
haier:
|
||||
code: [0xA6, 0x12, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05]
|
||||
- platform: remote_receiver
|
||||
name: Mirage Remote Input
|
||||
mirage:
|
||||
code: [0x56, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12]
|
||||
- platform: remote_receiver
|
||||
name: Panasonic Remote Input
|
||||
panasonic:
|
||||
|
||||
@@ -5,6 +5,14 @@ remote_receiver:
|
||||
<<: !include common-actions.yaml
|
||||
|
||||
binary_sensor:
|
||||
- platform: remote_receiver
|
||||
name: Haier Remote Input
|
||||
haier:
|
||||
code: [0xA6, 0x12, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05]
|
||||
- platform: remote_receiver
|
||||
name: Mirage Remote Input
|
||||
mirage:
|
||||
code: [0x56, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12]
|
||||
- platform: remote_receiver
|
||||
name: Panasonic Remote Input
|
||||
panasonic:
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/components/uart/software_serial_tx_frame.h"
|
||||
|
||||
namespace esphome::uart::testing {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t US_CYCLES_80MHZ = 80;
|
||||
constexpr uint32_t MIN_RUN_80MHZ = US_CYCLES_80MHZ * 30;
|
||||
|
||||
// Line level of a slot by reading the bits one at a time: start 0, frame LSB first, then high
|
||||
bool level_at(uint32_t frame, uint32_t num_bits, uint32_t slot) {
|
||||
if (slot == 0)
|
||||
return false;
|
||||
if (slot <= num_bits)
|
||||
return (frame >> (slot - 1)) & 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Every set slot opens the lock right after an edge into a run that lasts long enough, every such slot up to
|
||||
// high_from is set, and high_from is the slot of the last 0
|
||||
TEST(SoftwareSerialTxFrameTest, UnlockSlotsMatchBitByBitReference) {
|
||||
for (uint32_t cpu_mhz : {80u, 160u}) {
|
||||
const uint32_t min_run = cpu_mhz * 30;
|
||||
for (uint32_t baud : {57600u, 76800u, 115200u, 230400u}) {
|
||||
const uint32_t bit_time = cpu_mhz * 1000000 / baud;
|
||||
for (uint32_t num_bits = 5; num_bits <= 9; num_bits++) {
|
||||
for (uint32_t frame = 0; frame < (1u << num_bits); frame++) {
|
||||
const SoftwareSerialTxFrame tx = software_serial_tx_frame(frame, num_bits, bit_time, min_run, true);
|
||||
uint32_t last_zero = 0;
|
||||
for (uint32_t slot = 1; slot <= num_bits; slot++) {
|
||||
if (!level_at(frame, num_bits, slot))
|
||||
last_zero = slot;
|
||||
}
|
||||
ASSERT_EQ(tx.high_from, last_zero) << "frame " << frame << " bits " << num_bits;
|
||||
for (uint32_t slot = 0; slot <= num_bits + 1; slot++)
|
||||
ASSERT_EQ(((tx.line >> slot) & 1) != 0, level_at(frame, num_bits, slot));
|
||||
for (uint32_t slot = 0; slot <= tx.high_from; slot++) {
|
||||
const bool level = level_at(frame, num_bits, slot);
|
||||
const bool edge = slot == 0 || level != level_at(frame, num_bits, slot - 1);
|
||||
uint32_t run = 1;
|
||||
while (level_at(frame, num_bits, slot + run) == level)
|
||||
run++;
|
||||
const bool expected = edge && run * bit_time >= min_run;
|
||||
ASSERT_EQ(((tx.unlock_at >> slot) & 1) != 0, expected)
|
||||
<< "frame " << frame << " bits " << num_bits << " baud " << baud << " slot " << slot;
|
||||
}
|
||||
ASSERT_EQ(tx.unlock_at >> (tx.high_from + 1), 0u);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(SoftwareSerialTxFrameTest, NoUnlocksWhenNotRequested) {
|
||||
const SoftwareSerialTxFrame tx =
|
||||
software_serial_tx_frame(0x00, 8, US_CYCLES_80MHZ * 1000000 / 57600, MIN_RUN_80MHZ, false);
|
||||
EXPECT_EQ(tx.unlock_at, 0u);
|
||||
EXPECT_EQ(tx.high_from, 8u);
|
||||
}
|
||||
|
||||
// At 57600 a run of two bits is long enough; 0x55 alternates every bit, so its lock never opens
|
||||
TEST(SoftwareSerialTxFrameTest, Examples57600) {
|
||||
const uint32_t bit_time = US_CYCLES_80MHZ * 1000000 / 57600;
|
||||
EXPECT_EQ(software_serial_tx_frame(0x55, 8, bit_time, MIN_RUN_80MHZ, true).unlock_at, 0u);
|
||||
// 0x00: the start bit begins a run of nine 0s
|
||||
EXPECT_EQ(software_serial_tx_frame(0x00, 8, bit_time, MIN_RUN_80MHZ, true).unlock_at, 0b1u);
|
||||
// 0xFF: only the start bit is sent before the trailing high run, and it is a run of one
|
||||
const SoftwareSerialTxFrame ff = software_serial_tx_frame(0xFF, 8, bit_time, MIN_RUN_80MHZ, true);
|
||||
EXPECT_EQ(ff.high_from, 0u);
|
||||
EXPECT_EQ(ff.unlock_at, 0u);
|
||||
// 'A' (0x41): slots 0 1 0 0 0 0 0 1 0, so a run of five 0s starts at slot 2
|
||||
EXPECT_EQ(software_serial_tx_frame(0x41, 8, bit_time, MIN_RUN_80MHZ, true).unlock_at, 1u << 2);
|
||||
}
|
||||
|
||||
} // namespace esphome::uart::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
|
||||
@@ -11,11 +11,27 @@ api:
|
||||
- action: fire_first_then_second
|
||||
then:
|
||||
- lambda: |-
|
||||
// The client is not reading: about 110 KB of log lines fill the TCP pipe, then the overflow buffer
|
||||
// The client is not reading: log lines fill the TCP pipe, then the overflow buffer. Until the
|
||||
// client's receive window is closed, a late acknowledgement can still free send buffer space
|
||||
// and let the overflow buffer drain, so keep going until it holds data with the window closed
|
||||
auto *client = sndbuf_pin::api_log_client();
|
||||
const std::string padding(250, 'x');
|
||||
for (int i = 0; i < 400; i++) {
|
||||
ESP_LOGD("fill", "fill line %s", padding.c_str());
|
||||
const uint32_t start = millis();
|
||||
bool full = false;
|
||||
while (client != nullptr && millis() - start < 5000) {
|
||||
const bool window_closed = sndbuf_pin::api_peer_window_closed();
|
||||
if (client->try_to_clear_buffer(false)) {
|
||||
ESP_LOGD("fill", "fill line %s", padding.c_str());
|
||||
} else if (window_closed) {
|
||||
full = true;
|
||||
break;
|
||||
} else {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
// The api drops this line while the pipe is blocked; the test reads it from the console
|
||||
if (!full)
|
||||
ESP_LOGE("fill", "fill timed out");
|
||||
// The test checks that this line was dropped, which means the overflow buffer still holds data
|
||||
ESP_LOGD("fill", "last fill line");
|
||||
# So this event waits in the batch
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
esphome:
|
||||
name: api-shutdown-bp-test
|
||||
|
||||
host:
|
||||
|
||||
api:
|
||||
# One queued message, so DisconnectRequest cannot join the overflow buffer once it holds data
|
||||
max_send_queue: 1
|
||||
actions:
|
||||
- action: fill_then_restart
|
||||
then:
|
||||
- lambda: &fill_pipe |-
|
||||
// The client is not reading: log lines fill the TCP pipe, then the overflow buffer. Keep going
|
||||
// until the overflow buffer holds data with the client's window closed, so nothing drains it
|
||||
auto *client = sndbuf_pin::api_log_client();
|
||||
const std::string padding(250, 'x');
|
||||
const uint32_t start = millis();
|
||||
bool full = false;
|
||||
while (client != nullptr && millis() - start < 5000) {
|
||||
const bool window_closed = sndbuf_pin::api_peer_window_closed();
|
||||
if (client->try_to_clear_buffer(false)) {
|
||||
ESP_LOGD("fill", "fill line %s", padding.c_str());
|
||||
} else if (window_closed) {
|
||||
full = true;
|
||||
break;
|
||||
} else {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
if (!full)
|
||||
ESP_LOGE("fill", "fill timed out");
|
||||
# The test reads again once this line is on the console
|
||||
- logger.log: fill done
|
||||
# DisconnectRequest cannot be sent now, so it waits in an otherwise empty batch
|
||||
- button.press: restart_button
|
||||
- action: fill_publish_then_restart
|
||||
then:
|
||||
- lambda: *fill_pipe
|
||||
# Queued behind the blocked socket when the shutdown starts
|
||||
- lambda: id(queued_sensor).publish_state(42);
|
||||
- logger.log: fill done
|
||||
- button.press: restart_button
|
||||
|
||||
button:
|
||||
- platform: restart
|
||||
id: restart_button
|
||||
name: "Restart"
|
||||
|
||||
sensor:
|
||||
- platform: template
|
||||
id: queued_sensor
|
||||
name: "Queued sensor"
|
||||
|
||||
external_components:
|
||||
- source:
|
||||
type: local
|
||||
path: EXTERNAL_COMPONENT_PATH
|
||||
components: [sndbuf_pin_component]
|
||||
|
||||
# Pins the device's socket send buffers for deterministic TCP backpressure
|
||||
sndbuf_pin_component:
|
||||
buffer_size: SERVER_SNDBUF
|
||||
|
||||
logger:
|
||||
level: DEBUG
|
||||
@@ -0,0 +1,114 @@
|
||||
esphome:
|
||||
name: api-shutdown-order
|
||||
|
||||
host:
|
||||
|
||||
logger:
|
||||
|
||||
api:
|
||||
|
||||
switch:
|
||||
- platform: template
|
||||
id: test_switch
|
||||
name: "Test switch"
|
||||
optimistic: true
|
||||
|
||||
button:
|
||||
- platform: restart
|
||||
id: restart_button
|
||||
name: "Restart"
|
||||
- platform: template
|
||||
name: "Toggle then restart"
|
||||
on_press:
|
||||
- switch.toggle: test_switch
|
||||
- button.press: restart_button
|
||||
- platform: template
|
||||
name: "Publish then restart"
|
||||
on_press:
|
||||
- lambda: |-
|
||||
for (auto *sensor : App.get_sensors())
|
||||
sensor->publish_state(1);
|
||||
- button.press: restart_button
|
||||
|
||||
sensor:
|
||||
# More states than one batch packet holds (MAX_MESSAGES_PER_BATCH is 34)
|
||||
- platform: template
|
||||
name: "Burst 0"
|
||||
- platform: template
|
||||
name: "Burst 1"
|
||||
- platform: template
|
||||
name: "Burst 2"
|
||||
- platform: template
|
||||
name: "Burst 3"
|
||||
- platform: template
|
||||
name: "Burst 4"
|
||||
- platform: template
|
||||
name: "Burst 5"
|
||||
- platform: template
|
||||
name: "Burst 6"
|
||||
- platform: template
|
||||
name: "Burst 7"
|
||||
- platform: template
|
||||
name: "Burst 8"
|
||||
- platform: template
|
||||
name: "Burst 9"
|
||||
- platform: template
|
||||
name: "Burst 10"
|
||||
- platform: template
|
||||
name: "Burst 11"
|
||||
- platform: template
|
||||
name: "Burst 12"
|
||||
- platform: template
|
||||
name: "Burst 13"
|
||||
- platform: template
|
||||
name: "Burst 14"
|
||||
- platform: template
|
||||
name: "Burst 15"
|
||||
- platform: template
|
||||
name: "Burst 16"
|
||||
- platform: template
|
||||
name: "Burst 17"
|
||||
- platform: template
|
||||
name: "Burst 18"
|
||||
- platform: template
|
||||
name: "Burst 19"
|
||||
- platform: template
|
||||
name: "Burst 20"
|
||||
- platform: template
|
||||
name: "Burst 21"
|
||||
- platform: template
|
||||
name: "Burst 22"
|
||||
- platform: template
|
||||
name: "Burst 23"
|
||||
- platform: template
|
||||
name: "Burst 24"
|
||||
- platform: template
|
||||
name: "Burst 25"
|
||||
- platform: template
|
||||
name: "Burst 26"
|
||||
- platform: template
|
||||
name: "Burst 27"
|
||||
- platform: template
|
||||
name: "Burst 28"
|
||||
- platform: template
|
||||
name: "Burst 29"
|
||||
- platform: template
|
||||
name: "Burst 30"
|
||||
- platform: template
|
||||
name: "Burst 31"
|
||||
- platform: template
|
||||
name: "Burst 32"
|
||||
- platform: template
|
||||
name: "Burst 33"
|
||||
- platform: template
|
||||
name: "Burst 34"
|
||||
- platform: template
|
||||
name: "Burst 35"
|
||||
- platform: template
|
||||
name: "Burst 36"
|
||||
- platform: template
|
||||
name: "Burst 37"
|
||||
- platform: template
|
||||
name: "Burst 38"
|
||||
- platform: template
|
||||
name: "Burst 39"
|
||||
@@ -0,0 +1,23 @@
|
||||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_NAME
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@esphome/tests"]
|
||||
MULTI_CONF = True
|
||||
|
||||
reboot_hook_recorder_ns = cg.esphome_ns.namespace("reboot_hook_recorder")
|
||||
RebootHookRecorder = reboot_hook_recorder_ns.class_("RebootHookRecorder", cg.Component)
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(RebootHookRecorder),
|
||||
cv.Required(CONF_NAME): cv.string,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = cg.new_Pvariable(config[CONF_ID])
|
||||
await cg.register_component(var, config)
|
||||
cg.add(var.set_name(config[CONF_NAME]))
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
#include "reboot_hook_recorder.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::reboot_hook_recorder {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "reboot_hook_recorder");
|
||||
|
||||
void RebootHookRecorder::record_(const char *hook) { ESP_LOGI(TAG, "HOOK %s %s", this->name_, hook); }
|
||||
|
||||
} // namespace esphome::reboot_hook_recorder
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/core/component.h"
|
||||
|
||||
namespace esphome::reboot_hook_recorder {
|
||||
|
||||
/// Logs every shutdown lifecycle hook it receives, so a test can check their order.
|
||||
class RebootHookRecorder : public Component {
|
||||
public:
|
||||
void set_name(const char *name) { this->name_ = name; }
|
||||
|
||||
void on_safe_shutdown() override { this->record_("on_safe_shutdown"); }
|
||||
void on_shutdown() override { this->record_("on_shutdown"); }
|
||||
// Needs a second call to finish, like a component waiting for a connection to close
|
||||
bool teardown() override {
|
||||
if (++this->teardown_calls_ < 2) {
|
||||
this->record_("teardown_pending");
|
||||
return false;
|
||||
}
|
||||
if (this->teardown_calls_ == 2)
|
||||
this->record_("teardown_done");
|
||||
return true;
|
||||
}
|
||||
void on_powerdown() override { this->record_("on_powerdown"); }
|
||||
|
||||
protected:
|
||||
void record_(const char *hook);
|
||||
|
||||
const char *name_{""};
|
||||
uint8_t teardown_calls_{0};
|
||||
};
|
||||
|
||||
} // namespace esphome::reboot_hook_recorder
|
||||
+37
@@ -7,6 +7,12 @@
|
||||
#include "esphome/components/api/api_server.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
// Host only: clang-tidy also checks this file for ESP32, which has no Linux socket headers
|
||||
#if defined(USE_HOST) && defined(__linux__)
|
||||
#include <linux/sockios.h>
|
||||
#include <sys/ioctl.h>
|
||||
#endif
|
||||
|
||||
namespace esphome::sndbuf_pin {
|
||||
|
||||
static const char *const TAG = "sndbuf_pin";
|
||||
@@ -52,4 +58,35 @@ void SndbufPinComponent::setup() {
|
||||
}
|
||||
}
|
||||
|
||||
api::APIConnection *api_log_client() {
|
||||
for (const auto &conn : api::global_api_server->active_clients()) {
|
||||
if (conn->get_log_subscription_level() > 0)
|
||||
return conn.get();
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool api_peer_window_closed() {
|
||||
#if defined(USE_HOST) && defined(__linux__)
|
||||
for (int fd = FIRST_USER_FD; fd < MAX_FD_SCAN; fd++) {
|
||||
struct sockaddr_in addr{};
|
||||
socklen_t addr_len = sizeof(addr);
|
||||
if (::getsockname(fd, reinterpret_cast<struct sockaddr *>(&addr), &addr_len) != 0 ||
|
||||
ntohs(addr.sin_port) != api::global_api_server->get_port())
|
||||
continue;
|
||||
// Skips the listener: only the accepted client socket has a peer
|
||||
addr_len = sizeof(addr);
|
||||
if (::getpeername(fd, reinterpret_cast<struct sockaddr *>(&addr), &addr_len) != 0)
|
||||
continue;
|
||||
int queued = 0;
|
||||
int not_sent = 0;
|
||||
if (::ioctl(fd, SIOCOUTQ, &queued) != 0 || ::ioctl(fd, SIOCOUTQNSD, ¬_sent) != 0)
|
||||
return false;
|
||||
return not_sent > 0 && queued == not_sent;
|
||||
}
|
||||
#endif
|
||||
// Unknown elsewhere: a fill loop waiting on this times out and says so
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace esphome::sndbuf_pin
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user