Compare commits

...
78 Commits
Author SHA1 Message Date
Jesse Hills e27614fda3 Merge pull request #22833 from esphome/bump-2026.11.0b6
2026.11.0b6
2026-11-17 22:24:55 +13:00
J. Nick Koston 8426d04138 [api] Make the event order backpressure test wait until the pipe is full (#22112) 2026-11-17 21:09:01 +13:00
Jesse Hills 4a39ca1b71 Fix 2026-11-17 20:54:40 +13:00
Jesse Hills 4a218fdbd8 Remove extra test 2026-11-17 20:47:40 +13:00
Jesse Hills d8fc1cd214 Bump version to 2026.11.0b6 2026-11-17 18:54:23 +13:00
J. Nick Koston 1e030b7371 [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 18:54:20 +13:00
J. Nick Koston 3b113f2c39 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 18:54:20 +13:00
J. Nick Koston 73468592a9 [remote_base] Fix the Haier and Mirage remote_receiver binary sensors failing to compile 2026-11-17 18:54:06 +13:00
Jonathan Swoboda a1b456150d [esp32][libretiny] Make delay() wait at least the requested time (#22822) 2026-11-17 18:53:11 +13:00
J. Nick Koston 865a883abb [remote_base] Fix the canalsatld binary sensor and trigger build 2026-11-17 18:53:11 +13:00
J. Nick Koston 357a6717c8 [core] Release only the lwIP core lock a LwIPLock took (#22683) 2026-11-17 18:53:11 +13:00
J. Nick Koston bcb434e05e [esp32_ble] Stop Bluedroid re-running a failed queued MTU or execute write request (#22670) 2026-11-17 18:53:11 +13:00
J. Nick Koston fb65fcc5f6 [esp32_power_management] Clamp the tick step after light sleep so it cannot trip vTaskStepTick (#22637) 2026-11-17 18:53:11 +13:00
J. Nick Koston b5e379a9d4 [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog at 57600 baud (#22641) 2026-11-17 18:53:11 +13:00
J. Nick Kostonandpre-commit-ci-lite[bot] 05286dfd5d [api] Send queued entity states before DisconnectRequest on shutdown (#22625)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-17 18:53:11 +13:00
J. Nick Koston 36184f09aa [zephyr] Count micros() in microseconds and busy-wait in delayMicroseconds() (#22612) 2026-11-17 18:53:11 +13:00
Adam Matthews 449933891e [wifi] Clear the error flag when the adapter restart is skipped (#22797) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda a5bfa6dac3 [esp32_ble] Apply the Bluedroid workarounds to the ESP-IDF 6.1 releases that need them (#22806) 2026-11-17 18:53:11 +13:00
Jonathan Swoboda 5aaa5b0552 [esp32_ble] Replace Bluedroid's sscanf callers on ESP-IDF 6 too (#22805) 2026-11-17 18:53:11 +13:00
J. Nick Koston 9ab090a818 [i2c] Refuse RP2040 writes larger than the Wire buffer instead of leaving the bus stuck (#22791) 2026-11-17 18:53:10 +13:00
Jesse Hills 84079c07e2 Merge pull request #22804 from esphome/bump-2026.11.0b5
2026.11.0b5
2026-11-17 10:27:35 +13:00
J. Nick Koston b7dbf17469 [core] Brace the fast loop check in the unit test main (#22640) 2026-11-17 09:54:53 +13:00
Jesse Hills b91750c325 [tests] Add RawApiClient.read_frame for the serial proxy backpressure test
The serial proxy test from #22687 calls RawApiClient.read_frame, which was
added on dev as part of the store_yaml feature (#16445) and is not on this
release branch. Take tests/integration/raw_api_client.py from that PR so the
test can run; no firmware code changes.
2026-11-17 09:33:39 +13:00
J. Nick Koston 92d2a457fa [epaper_spi] Stop the fast loop after the fill tests (#22638) 2026-11-17 09:00:52 +13:00
Jesse Hills a1fecebb09 Bump version to 2026.11.0b5 2026-11-17 07:30:12 +13:00
J. Nick Koston 32b9d4cbe7 [web_server_base] Bump ESPAsyncWebServer to 3.12.1 (#22682) 2026-11-17 07:30:09 +13:00
Chris c53401a28d [ethernet] Notify IP state listeners from the main loop (#22657) 2026-11-17 07:30:09 +13:00
Miguel Angel Nubla 6b7d17c762 [wifi] Leave the AP before restarting on ESP32 (#22715) 2026-11-17 07:30:09 +13:00
J. Nick Koston 93a3306d82 [libretiny] Free closed TCP connections after about 1 s instead of 120 s (#22696) 2026-11-17 07:30:09 +13:00
J. Nick Koston 54d3477240 [bluetooth_connection] Keep the top half of 32-bit GATT UUIDs on RP2 (#22679) 2026-11-17 07:30:09 +13:00
J. Nick Koston 5f9d83d293 [async_tcp] Use the esphome-libs RPAsyncTCP fork so SSE streams do not stall on RP2040 (#22686) 2026-11-17 07:30:09 +13:00
J. Nick Koston 43864283b4 [web_server_base] Check Basic auth without linking the library's Digest code (#22684) 2026-11-17 07:30:09 +13:00
J. Nick Koston 4efbb38b86 [core] Lock the scheduler against lwIP callbacks on RP2 (#22688) 2026-11-17 07:30:09 +13:00
Keith Burzinski 045374965f [serial_proxy] Keep received bytes when the client's connection is blocked (#22687) 2026-11-17 07:30:09 +13:00
Craig Andrews 39a939720f [epaper_spi] Point the UC8279 gate-count error at the height (#22628) 2026-11-17 07:30:09 +13:00
esphome[bot] a79e51e784 Bump bundled esphome-device-builder to 1.28.1 (#22630)
Co-authored-by: esphome[bot] <115708604+esphome[bot]@users.noreply.github.com>
2026-11-17 07:29:59 +13:00
Chris 517f0d6d48 [usb_host] Respect explicit control transfer size (#22629) 2026-11-17 07:29:14 +13:00
Craig Andrews 1327d0ddc5 [epaper_spi] Mark the frame drawn after fill() (#21505) 2026-11-17 07:29:14 +13:00
J. Nick Koston 2adb544e7a [uart] Stop ESP8266 software serial TX from tripping the Wi-Fi watchdog above 19200 baud (#22603) 2026-11-17 07:29:14 +13:00
J. Nick Koston 48905beb96 [zephyr] Add ISR pin_mode so dht links on nRF52 2026-11-17 07:29:14 +13:00
J. Nick Koston ed401814bf [dht] Negate sign-and-magnitude negative temperatures instead of inverting them (#22615) 2026-11-17 07:29:14 +13:00
J. Nick Koston 0245db6285 [host] Add the empty ISRInternalGPIOPin::pin_mode (#22616) 2026-11-17 07:29:14 +13:00
J. Nick Koston 07ee0f9f04 [logger] Fix LibreTiny task log messages landing unaligned and out of step (#22594) 2026-11-17 07:29:14 +13:00
Jesse HillsandJ. Nick Koston 3d34ad572b [api] Send the platform of each wizard entity (#22580)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-17 07:29:13 +13:00
Jesse Hills b03870b551 Merge pull request #22583 from esphome/bump-2026.11.0b4
2026.11.0b4
2026-11-12 16:26:56 +13:00
Jesse Hills 4a965b8b32 Bump version to 2026.11.0b4 2026-11-12 15:42:05 +13:00
J. Nick Koston d826a19eb1 [esp32_ble] Sort GATT discovery responses by handle for ESP-IDF 5.5.6 and 6.0.3 (#22576) 2026-11-12 15:42:02 +13:00
J. Nick Koston fb54ec51c1 [gpio] Lock interrupts per slot on the one_wire bus (#22452) 2026-11-12 15:42:02 +13:00
J. Nick Koston 04b6c0d4ca [esp32_ble] Keep bond keys when a bonded device re-encrypts on ESP-IDF 5.5.6 (#22559) 2026-11-12 15:42:02 +13:00
J. Nick Koston abf282dd08 [esp32_ble_tracker] Scan at the short window while the wifi AP is running (#22566) 2026-11-12 15:41:58 +13:00
J. Nick Koston e097958ad9 [remote_transmitter] Lock interrupts only near each edge on ESP8266 (#22453) 2026-11-12 15:41:24 +13:00
jabla 8a8ad4d8da [zigbee] Rejoin only after the parent missed several polls (#22405) 2026-11-12 15:41:24 +13:00
J. Nick Koston 09b82388c9 [uart] Lock interrupts per bit in ESP8266 software serial TX at 19200 baud and below (#22450) 2026-11-12 15:41:23 +13:00
J. Nick Koston ea5407925a [wifi] Apply power save when the AP starts without networks (#22564) 2026-11-12 15:41:20 +13:00
J. Nick Koston 97732df3a5 [esp32_ble][ble_device_base][improv_ble] Send advertising as raw packets and keep Improv in the advertising packet (#22499) 2026-11-12 15:40:20 +13:00
Francesco Pace 04482ae0d4 [espectre] Update to SDK 3.2.0 (#22570) 2026-11-12 15:40:20 +13:00
Clyde Stubbs ca0dd8e292 [mipi_dsi] Keep the panel running while flash is written (#22535) 2026-11-12 15:40:20 +13:00
J. Nick Koston e75ac64cc9 [esp8266] Skip other devices' known mDNS answers without allocating (Arduino core 3.1.2-esphome.4) (#22533) 2026-11-12 15:40:20 +13:00
PolarGooseandJ. Nick Koston 212c0c1ea4 [dsmr] Update dsmr_parser to 1.11.0 (#22530)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
2026-11-12 15:40:20 +13:00
Jonathan Swoboda 3e2f9bf296 [ota] Skip the auth request when the password is empty at run time (#22485) 2026-11-12 15:40:20 +13:00
J. Nick Koston b997866e86 [esp32_ble_server] Size the BLE2902 value buffer to its 2 byte value (#22454) 2026-11-12 15:40:20 +13:00
J. Nick Koston ae89db98e4 [core] Inline InterruptLock on ESP8266 (#22455) 2026-11-12 15:40:19 +13:00
Kevin Ahrendt e9bb102c1f [sendspin] Add bits_per_sample to the media source (#22313) 2026-11-12 15:40:19 +13:00
Jesse Hills 26c4f8d40e Merge pull request #22442 from esphome/bump-2026.11.0b3
2026.11.0b3
2026-11-09 14:04:52 +13:00
Jesse Hills c097fe388e Bump version to 2026.11.0b3 2026-11-09 13:36:04 +13:00
J. Nick Koston 21267d7421 [libretiny] Interrupt on both edges for any edge pins on RTL8710B (#22403) 2026-11-09 13:36:03 +13:00
J. Nick Koston 582adc950a [libretiny] Run millis(), micros() and delays on real time on RTL8710B (#22404) 2026-11-09 13:36:03 +13:00
J. Nick Koston 613319f984 [i2c] Mask I2C interrupts after an error on classic ESP32 (#22396) 2026-11-09 13:36:02 +13:00
J. Nick Koston 4ad3cc7c0e [light] Keep power estimation state in codegen static storage (#22370) 2026-11-09 13:36:02 +13:00
J. Nick Koston a033260639 [libretiny] Read pins in interrupts without detaching the interrupt on Realtek (#22400) 2026-11-09 13:36:02 +13:00
24f23ba3db [i2s_audio] Fix APLL clock source on ESP32-P4 (#22402)
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-09 13:36:02 +13:00
Roman PriesolandJ. Nick Koston 674d593f75 [wifi] Create the IPv6 link-local through lwIP on connect (#22364)
Co-authored-by: J. Nick Koston <nick@koston.org>
2026-11-09 13:36:02 +13:00
Jonathan Swoboda c1771e002b [ld2410][ld2412][ld2420] Drop device classes from unitless gate and light entities (#22374) 2026-11-09 13:36:02 +13:00
Jonathan Swoboda 5529e87a40 [tsl2591][seeed_mr24hpc1] Drop device classes from unitless sensors (#22375) 2026-11-09 13:36:02 +13:00
J. Nick Koston 54cae78a42 [ht16k33_char] Name the I2C bus in the component test (#22372) 2026-11-09 13:36:02 +13:00
J. Nick Koston e77a3bc54d [core] Add cg.static_buffer for config-sized static buffers (#22326) 2026-11-09 13:36:02 +13:00
guillempages af7f95a01b [ht16k33] Rename display_off method (#22352) 2026-11-09 13:36:02 +13:00
daf48ce4f2 [vl53l0x] Recover from a failed I2C read instead of stalling (#19235)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Co-authored-by: Tekla Bania <[EMAIL]>
Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
Co-authored-by: J. Nick Koston <nick@home-assistant.io>
Signed-off-by: Tekla Bania <8668038+teklabania@users.noreply.github.com>
Signed-off-by: Tekla Bania <[EMAIL]>
2026-11-09 13:36:02 +13:00
190 changed files with 4931 additions and 638 deletions

No files matched your search

@@ -201,6 +201,9 @@ virtual listener base (a second vptr per entity).
- `uart.new_uart_component(config, *ctor_args)` (and `i2c.new_i2c_component`, `spi.new_spi_component`,
`modbus.new_modbus_client_component`, `ble_client.new_ble_node_component`) constructs, registers and
attaches in one call.
- A fixed buffer sized from the config is a file-scope static (BSS, not heap):
`buf = cg.static_buffer(config[CONF_ID], cg.uint8, size)`, named after its owner so `esphome analyze-memory`
counts it there; pass `buf` to the constructor.
- `display.add_writer(var, config)` sets the lambda.
- `MyEnum.options("on", prefix="MY_ENUM_")` builds an enum dict.
- `button.restart_button_schema(cls)` (and `factory_reset_`, `query_`) are button presets.
+2
View File
@@ -42,6 +42,8 @@ APIs.
// Or if size is constant:
std::array<uint8_t, 256> buffer;
```
When the size comes from the config, declare it with `cg.static_buffer()` in `to_code` and pass the pointer
to the constructor, so it lands in BSS (see the `component-codegen` skill).
2. **Compile-time-known fixed sizes with vector-like API:** use `StaticVector` from
`esphome/core/helpers.h` for compile-time fixed size with a `push_back()` interface (no dynamic
+1 -1
View File
@@ -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.0b2
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
View File
@@ -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 \
+3 -3
View File
@@ -49,9 +49,9 @@ class FrameworkRelease(NamedTuple):
# Arduino core version -> its build in esphome-libs/arduino-esp8266
FRAMEWORK_RELEASES: dict[Version, FrameworkRelease] = {
Version(3, 1, 2): FrameworkRelease(
"3.1.2-esphome.3",
"3af533a85163804e164500a5b254dc23b922080e25ecb7dc37b3dd8ac84651db",
37185650,
"3.1.2-esphome.4",
"d215e439e5592ca6ecac283825d08044b2bfce9cf592e03cf33dcbcec69365e2",
37192995,
),
}
+1
View File
@@ -46,6 +46,7 @@ from esphome.cpp_generator import ( # noqa: F401
shared_progmem_array,
shared_progmem_string,
statement,
static_buffer,
static_const_array,
static_function,
templatable,
+6 -1
View File
@@ -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.
+2 -1
View File
@@ -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);
+28 -9
View File
@@ -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() {
+57 -3
View File
@@ -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
+13 -5
View File
@@ -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
@@ -0,0 +1,161 @@
#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/core/helpers.h"
namespace esphome::ble_device_base {
/// A 31 byte advertising or scan response payload, packed in the order and with the fit rules of Bluedroid's
/// btm_ble_build_adv_data, so the raw bytes match what the esp_ble_adv_data_t API put on air.
class AdvPayload {
public:
static constexpr size_t MAX_LEN = 31;
const uint8_t *data() const { return this->buf_.data(); }
size_t size() const { return this->len_; }
void add_flags(uint8_t flags) {
if (flags != 0 && this->left_() >= 3)
this->add_(0x01, &flags, 1);
}
void add_appearance(uint16_t appearance) {
if (appearance == 0 || this->left_() <= 3)
return;
uint8_t value[2];
put_le16(value, appearance);
this->add_(0x19, value, sizeof(value));
}
/// Complete name, or the shortened name type with what fits.
void add_name(const char *name, size_t len) {
if (this->left_() <= 2)
return;
const size_t fit = std::min(len, this->left_() - 2);
this->add_(fit < len ? 0x08 : 0x09, reinterpret_cast<const uint8_t *>(name), fit);
}
/// Truncated to what fits.
void add_manufacturer_data(std::span<const uint8_t> data) {
if (!data.empty() && this->left_() > 2)
this->add_(0xFF, data.data(), std::min(data.size(), this->left_() - 2));
}
void add_tx_power(int8_t dbm) {
if (this->left_() > 2)
this->add_(0x0A, reinterpret_cast<const uint8_t *>(&dbm), 1);
}
/// 16 and 32-bit lists (partial when they do not all fit), then the first 128-bit UUID; `skip` is left out.
void add_uuids(std::span<const ESPBTUUID> uuids, const ESPBTUUID &skip = {}) {
this->add_short_uuids_(uuids, skip, 2, 0x02);
this->add_short_uuids_(uuids, skip, 4, 0x04);
if (this->left_() < 18)
return;
for (const auto &uuid : uuids) {
if (uuid != skip && uuid_size(uuid) == 16) {
this->add_(0x07, uuid.uuid128(), 16);
return;
}
}
}
/// Raw service data element (its first bytes are the UUID); dropped whole when it does not fit.
void add_service_data(std::span<const uint8_t> data) {
if (!data.empty() && this->left_() >= data.size() + 2)
this->add_(0x16, data.data(), data.size());
}
/// Bluedroid's width for `uuid`: 2 or 4 (and its value) when it has a 16 or 32-bit form, else 16.
static size_t uuid_size(const ESPBTUUID &uuid, uint32_t *value = nullptr) {
static constexpr uint8_t BASE[12] = {0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00};
uint32_t short_value;
if (uuid.type() == ESPBTUUID::Type::UUID16) {
short_value = uuid.uuid16();
} else if (uuid.type() == ESPBTUUID::Type::UUID32) {
short_value = uuid.uuid32();
} else {
const uint8_t *raw = uuid.uuid128();
if (memcmp(raw, BASE, sizeof(BASE)) != 0)
return 16;
short_value = encode_value_le<uint32_t>(raw + 12);
}
if (value != nullptr)
*value = short_value;
return short_value <= 0xFFFF ? 2 : 4;
}
protected:
size_t left_() const { return MAX_LEN - this->len_; }
void add_(uint8_t type, const uint8_t *value, size_t len) {
this->buf_[this->len_++] = len + 1;
this->buf_[this->len_++] = type;
memcpy(this->buf_.data() + this->len_, value, len);
this->len_ += len;
}
void add_short_uuids_(std::span<const ESPBTUUID> uuids, const ESPBTUUID &skip, size_t size, uint8_t partial_type) {
const size_t count =
std::count_if(uuids.begin(), uuids.end(), [&](const auto &u) { return u != skip && uuid_size(u) == size; });
if (count == 0 || this->left_() < 2 + size)
return;
size_t fit = std::min(count, (this->left_() - 2) / size);
this->buf_[this->len_++] = 1 + fit * size;
this->buf_[this->len_++] = fit < count ? partial_type : partial_type + 1;
for (const auto &uuid : uuids) {
if (fit == 0)
break;
uint32_t value;
if (uuid == skip || uuid_size(uuid, &value) != size)
continue;
if (size == 2) {
put_le16(this->buf_.data() + this->len_, value);
} else {
put_le32(this->buf_.data() + this->len_, value);
}
this->len_ += size;
fit--;
}
}
std::array<uint8_t, MAX_LEN> buf_{};
uint8_t len_{0};
};
/// What the services advertising carries. A set `priority_uuid` (also in `uuids`) gets the advertising packet.
struct AdvContent {
std::span<const ESPBTUUID> uuids;
ESPBTUUID priority_uuid;
std::span<const uint8_t> manufacturer_data;
std::span<const uint8_t> service_data;
const char *name;
size_t name_len;
uint16_t appearance;
int8_t tx_power_dbm;
bool name_in_adv;
};
/// Split `content` between the advertising packet and the scan response. With a priority UUID, appearance,
/// manufacturer data and the other UUIDs move to the scan response, and the service data stays only in `adv`.
inline void build_adv_packets(const AdvContent &content, AdvPayload &adv, AdvPayload &rsp) {
const bool priority = content.priority_uuid.is_set();
AdvPayload &extras = priority ? rsp : adv;
adv.add_flags(0x06); // LE general discoverable, BR/EDR not supported
extras.add_appearance(content.appearance);
if (content.name_in_adv)
adv.add_name(content.name, content.name_len);
rsp.add_name(content.name, content.name_len);
extras.add_manufacturer_data(content.manufacturer_data);
rsp.add_tx_power(content.tx_power_dbm);
if (priority) {
adv.add_uuids({&content.priority_uuid, 1});
} else {
adv.add_uuids(content.uuids);
}
rsp.add_uuids(content.uuids, content.priority_uuid);
adv.add_service_data(content.service_data);
if (!priority)
rsp.add_service_data(content.service_data);
}
} // namespace esphome::ble_device_base
@@ -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;
+2 -9
View File
@@ -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)) {
+12
View File
@@ -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)
+1 -1
View File
@@ -87,7 +87,7 @@ async def to_code(config: ConfigType) -> None:
cg.add_build_flag("-DDSMR_WATER_MBUS_ID=" + str(config[CONF_WATER_MBUS_ID]))
cg.add_build_flag("-DDSMR_THERMAL_MBUS_ID=" + str(config[CONF_THERMAL_MBUS_ID]))
cg.add_library("esphome/dsmr_parser", "1.10.0")
cg.add_library("esphome/dsmr_parser", "1.11.0")
def final_validate(config: ConfigType) -> None:
@@ -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
+4 -1
View File
@@ -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() {
+4 -20
View File
@@ -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
+86 -20
View File
@@ -39,6 +39,7 @@ from esphome.const import (
)
from esphome.core import CORE, TimePeriod
import esphome.final_validate as fv
from esphome.helpers import IS_WINDOWS
from esphome.types import ConfigType
AUTO_LOAD = ["ble_device_base"] # ble_uuid.h builds on the neutral ESPBTUUID
@@ -296,19 +297,28 @@ __all__ = [
NO_BLUETOOTH_VARIANTS = [const.VARIANT_ESP32S2]
# Give bluedroid_hex_wraps.cpp Bluedroid's private headers so its ESP-IDF drift
# checks compile; the bt target's include dirs are read at generate time. Only
# the native ESP-IDF toolchain generates src/CMakeLists.txt.
BLUEDROID_HEADERS_CMAKE = """\
def _wrap_bluedroid_symbols(*symbols: str) -> None:
"""Link calls to each Bluedroid symbol to its ``__wrap_`` replacement."""
for symbol in symbols:
cg.add_build_flag(f"-Wl,--wrap={symbol}")
# libsrc.a is scanned before libbt.a, so pull the wrap in explicitly
cg.add_build_flag(f"-Wl,--undefined=__wrap_{symbol}")
def bluedroid_headers_cmake(source: str) -> str:
"""Give one esp32_ble source Bluedroid's private include dirs (native ESP-IDF toolchain only)."""
return f"""\
idf_component_get_property(esphome_bt_lib bt COMPONENT_LIB)
set_source_files_properties(
"${CMAKE_CURRENT_SOURCE_DIR}/esphome/components/esp32_ble/bluedroid_hex_wraps.cpp"
"${{CMAKE_CURRENT_SOURCE_DIR}}/esphome/components/esp32_ble/{source}"
PROPERTIES
INCLUDE_DIRECTORIES "$<TARGET_PROPERTY:${esphome_bt_lib},INCLUDE_DIRECTORIES>"
INCLUDE_DIRECTORIES "$<TARGET_PROPERTY:${{esphome_bt_lib}},INCLUDE_DIRECTORIES>"
COMPILE_DEFINITIONS USE_ESP32_BLE_BLUEDROID_HEADERS
)
"""
esp32_ble_ns = cg.esphome_ns.namespace("esp32_ble")
ESP32BLE = esp32_ble_ns.class_("ESP32BLE", cg.Component)
@@ -496,9 +506,7 @@ def final_validation(config: ConfigType) -> None:
add_idf_sdkconfig_option("CONFIG_ESP_HOSTED_HOST_FEAT_BT", True)
# Check if BLE Client is needed (via esp32_ble_tracker or esp32_ble_client)
has_ble_client = (
"esp32_ble_tracker" in full_config or "esp32_ble_client" in full_config
)
has_ble_client = _has_gatt_client(full_config)
# Check if BLE Server is needed
has_ble_server = "esp32_ble_server" in full_config
@@ -559,19 +567,50 @@ 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")
for symbol in ("btc_config_get_bin", "string_to_bdaddr"):
cg.add_build_flag(f"-Wl,--wrap={symbol}")
# libsrc.a is scanned before libbt.a, so pull the wrap in explicitly
cg.add_build_flag(f"-Wl,--undefined=__wrap_{symbol}")
add_src_cmake(BLUEDROID_HEADERS_CMAKE)
_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 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 _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"))
# 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")
_wrap_bluedroid_symbols("gatt_client_handle_server_rsp")
# When PSRAM and BT are used together, Bluedroid should prefer SPIRAM for
# heap allocations and use dynamic (heap-based) environment memory tables
@@ -639,11 +678,38 @@ for _name, _call in (("ble.enable", "enable()"), ("ble.disable", "disable()")):
)
def _has_gatt_client(config: ConfigType) -> bool:
"""Whether Bluedroid's GATT client is built: the tracker (and bluetooth_proxy) or esp32_ble_client."""
return "esp32_ble_tracker" in config or "esp32_ble_client" in config
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, 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
# when advertising is enabled here or by esp32_ble_server / esp32_ble_beacon.
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",
}
)
+45 -36
View File
@@ -195,7 +195,8 @@ void ESP32BLE::advertising_refresh() {
if (this->advertising_ref_count_ == 0) {
this->advertising_->stop();
} else {
this->advertising_->start();
this->advertising_->request_start();
App.wake_loop_threadsafe();
}
}
@@ -244,6 +245,16 @@ void ESP32BLE::advertising_add_service_uuid(ESPBTUUID uuid) {
this->advertising_refresh();
}
void ESP32BLE::advertising_set_priority_uuid(ESPBTUUID uuid) {
this->advertising_init_();
this->advertising_->set_priority_uuid(uuid);
}
void ESP32BLE::advertising_clear_priority_uuid() {
if (this->advertising_ != nullptr)
this->advertising_->clear_priority_uuid();
}
void ESP32BLE::advertising_remove_service_uuid(ESPBTUUID uuid) {
this->advertising_init_();
this->advertising_->remove_service_uuid(uuid);
@@ -257,12 +268,28 @@ void ESP32BLE::advertising_init_() {
return;
this->advertising_ = new BLEAdvertising(this->advertising_cycle_time_); // NOLINT(cppcoreguidelines-owning-memory)
this->advertising_->set_scan_response(true);
this->advertising_->set_min_preferred_interval(0x06);
this->advertising_->set_appearance(this->appearance_);
}
#endif
const char *ESP32BLE::device_name(char *buffer) const {
if (this->name_ != nullptr) {
if (!App.is_name_add_mac_suffix_enabled())
return this->name_;
// Last 6 characters of the 12 character MAC address string
constexpr size_t mac_address_suffix_len = 6;
char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
get_mac_address_into_buffer(mac_addr);
make_name_with_suffix_to(buffer, DEVICE_NAME_BUFFER_SIZE, this->name_, strlen(this->name_), '-',
mac_addr + mac_address_suffix_len, mac_address_suffix_len);
return buffer;
}
const auto &app_name = App.get_name();
truncate_name_to(buffer, DEVICE_NAME_BUFFER_SIZE, app_name.c_str(), app_name.length(),
App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
return buffer;
}
bool ESP32BLE::ble_setup_() {
esp_err_t err;
#ifdef CONFIG_BT_CONTROLLER_DISABLED
@@ -373,32 +400,8 @@ bool ESP32BLE::ble_setup_() {
}
#endif
// BLE device names are limited to 20 characters
// Buffer: 20 chars + null terminator
constexpr size_t ble_name_max_len = 21;
char name_buffer[ble_name_max_len];
const char *device_name;
if (this->name_ != nullptr) {
if (App.is_name_add_mac_suffix_enabled()) {
// MAC address suffix length (last 6 characters of 12-char MAC address string)
constexpr size_t mac_address_suffix_len = 6;
char mac_addr[MAC_ADDRESS_BUFFER_SIZE];
get_mac_address_into_buffer(mac_addr);
const char *mac_suffix_ptr = mac_addr + mac_address_suffix_len;
make_name_with_suffix_to(name_buffer, sizeof(name_buffer), this->name_, strlen(this->name_), '-', mac_suffix_ptr,
mac_address_suffix_len);
device_name = name_buffer;
} else {
device_name = this->name_;
}
} else {
const auto &app_name = App.get_name();
truncate_name_to(name_buffer, sizeof(name_buffer), app_name.c_str(), app_name.length(),
App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
device_name = name_buffer;
}
char name_buffer[DEVICE_NAME_BUFFER_SIZE];
const char *device_name = this->device_name(name_buffer);
err = esp_ble_gap_set_device_name(device_name);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_set_device_name failed: %d", err);
@@ -507,15 +510,11 @@ void ESP32BLE::loop() {
return;
}
#ifdef USE_ESP32_BLE_ADVERTISING
if (this->advertising_ != nullptr) {
this->advertising_->loop();
}
#endif
BLEEvent *ble_event = this->ble_events_.pop();
if (ble_event == nullptr)
if (ble_event == nullptr) {
this->advertising_loop_();
return;
}
do {
switch (ble_event->type_) {
@@ -525,6 +524,11 @@ void ESP32BLE::loop() {
esp_gatt_if_t gatts_if = ble_event->event_.gatts.gatts_if;
esp_ble_gatts_cb_param_t *param = &ble_event->event_.gatts.gatts_param;
ESP_LOGV(TAG, "gatts_event [esp_gatt_if: %d] - %d", gatts_if, event);
#ifdef USE_ESP32_BLE_ADVERTISING
// A peripheral connect stops advertising, so drop a queued send; a handler that wants more refreshes again
if (event == ESP_GATTS_CONNECT_EVT && param->connect.link_role == 1)
this->advertising_cancel_start_();
#endif
this->gatts_event_callbacks_.call(event, gatts_if, param);
break;
}
@@ -614,6 +618,8 @@ void ESP32BLE::loop() {
if (dropped > 0) {
ESP_LOGW(TAG, "Dropped %u BLE events due to buffer overflow", dropped);
}
// After the events, so refreshes they trigger go out in this pass
this->advertising_loop_();
}
void ESP32BLE::loop_handle_state_transition_not_active_() {
@@ -631,6 +637,9 @@ void ESP32BLE::loop_handle_state_transition_not_active_() {
return;
}
this->drain_ble_events_();
#ifdef USE_ESP32_BLE_ADVERTISING
this->advertising_cancel_start_();
#endif
// A status callback may have asked for BLE back; the stack is down now, so
// that request becomes a bring-up.
this->state_ =
+17
View File
@@ -112,6 +112,10 @@ class ESP32BLE final : public Component {
void get_mac_msb_first(uint8_t out[MAC_ADDRESS_SIZE]) const;
float get_setup_priority() const override;
void set_name(const char *name) { this->name_ = name; }
// BLE device names are limited to 20 characters
static constexpr size_t DEVICE_NAME_BUFFER_SIZE = 21;
/// The device name; written to `buffer` unless the configured name is used as is.
const char *device_name(char *buffer) const;
#ifdef USE_ESP32_BLE_ADVERTISING
/** Request advertising on behalf of a component.
@@ -131,6 +135,9 @@ class ESP32BLE final : public Component {
void advertising_set_service_data_and_name(std::span<const uint8_t> data, bool include_name);
void advertising_add_service_uuid(ESPBTUUID uuid);
void advertising_remove_service_uuid(ESPBTUUID uuid);
/// Keep `uuid` and the service data alone in the advertising packet; applies on the next refresh.
void advertising_set_priority_uuid(ESPBTUUID uuid);
void advertising_clear_priority_uuid();
void advertising_register_raw_advertisement_callback(std::function<void(bool)> &&callback);
#endif
@@ -188,8 +195,18 @@ class ESP32BLE final : public Component {
}
this->ble_events_.get_and_reset_dropped_count();
}
ESPHOME_ALWAYS_INLINE void advertising_loop_() {
#ifdef USE_ESP32_BLE_ADVERTISING
if (this->advertising_ != nullptr)
this->advertising_->loop();
#endif
}
#ifdef USE_ESP32_BLE_ADVERTISING
void advertising_init_();
void advertising_cancel_start_() {
if (this->advertising_ != nullptr)
this->advertising_->cancel_start();
}
#endif
// BLE uses the core wake_loop_threadsafe() mechanism to wake the main event loop
@@ -3,31 +3,41 @@
#ifdef USE_ESP32
#ifdef USE_ESP32_BLE_ADVERTISING
#include <cstdio>
#include <algorithm>
#include <cstring>
#include "esphome/components/ble_device_base/adv_payload.h"
#include "ble.h"
#include "ble_uuid.h"
#include "esphome/core/log.h"
#include "esphome/core/application.h"
#ifndef CONFIG_BT_CONTROLLER_DISABLED
#include <esp_bt.h>
#endif
namespace esphome::esp32_ble {
using ble_device_base::AdvPayload;
using ble_device_base::build_adv_packets;
ESPHOME_LOG_TAG(TAG, "esp32_ble.advertising");
BLEAdvertising::BLEAdvertising(uint32_t advertising_cycle_time) : advertising_cycle_time_(advertising_cycle_time) {
this->advertising_data_.set_scan_rsp = false;
this->advertising_data_.include_name = true;
this->advertising_data_.include_txpower = true;
this->advertising_data_.min_interval = 0;
this->advertising_data_.max_interval = 0;
this->advertising_data_.appearance = 0x00;
this->advertising_data_.manufacturer_len = 0;
this->advertising_data_.p_manufacturer_data = nullptr;
this->advertising_data_.service_data_len = 0;
this->advertising_data_.p_service_data = nullptr;
this->advertising_data_.service_uuid_len = 0;
this->advertising_data_.p_service_uuid = nullptr;
this->advertising_data_.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT);
// The TX power Bluedroid advertised, from its BTM_BLE_ADV_TX_POWER table
static int8_t adv_tx_power_dbm() {
#ifdef CONFIG_IDF_TARGET_ESP32
static constexpr int8_t TX_POWER_DBM[] = {-12, -9, -6, -3, 0, 3, 6, 9};
#else
static constexpr int8_t TX_POWER_DBM[] = {-24, -21, -18, -15, -12, -9, -6, -3, 0, 3, 6, 9, 12, 15, 18, 20};
#endif
#ifdef CONFIG_BT_CONTROLLER_DISABLED
const size_t level = 0; // a hosted controller; Bluedroid sends level 0 too
#else
const size_t level = esp_ble_tx_power_get(ESP_BLE_PWR_TYPE_ADV);
#endif
return TX_POWER_DBM[std::min(level, std::size(TX_POWER_DBM) - 1)];
}
BLEAdvertising::BLEAdvertising(uint32_t advertising_cycle_time) : advertising_cycle_time_(advertising_cycle_time) {
this->advertising_params_.adv_int_min = 0x20;
this->advertising_params_.adv_int_max = 0x40;
this->advertising_params_.adv_type = ADV_TYPE_IND;
@@ -44,14 +54,9 @@ void BLEAdvertising::remove_service_uuid(ESPBTUUID uuid) {
}
void BLEAdvertising::set_service_data(std::span<const uint8_t> data) {
delete[] this->advertising_data_.p_service_data;
this->advertising_data_.p_service_data = nullptr;
this->advertising_data_.service_data_len = data.size();
if (!data.empty()) {
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
this->advertising_data_.p_service_data = new uint8_t[data.size()];
memcpy(this->advertising_data_.p_service_data, data.data(), data.size());
}
// Too long to fit is the same as none
this->service_data_len_ = data.size() <= MAX_DATA_LEN ? data.size() : 0;
memcpy(this->service_data_.data(), data.data(), this->service_data_len_);
}
void BLEAdvertising::set_service_data(const std::vector<uint8_t> &data) {
@@ -59,69 +64,43 @@ void BLEAdvertising::set_service_data(const std::vector<uint8_t> &data) {
}
void BLEAdvertising::set_manufacturer_data(const std::vector<uint8_t> &data) {
delete[] this->advertising_data_.p_manufacturer_data;
this->advertising_data_.p_manufacturer_data = nullptr;
this->advertising_data_.manufacturer_len = data.size();
if (!data.empty()) {
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
this->advertising_data_.p_manufacturer_data = new uint8_t[data.size()];
memcpy(this->advertising_data_.p_manufacturer_data, data.data(), data.size());
}
// Only what fits goes on air
this->manufacturer_data_len_ = std::min(data.size(), MAX_DATA_LEN);
memcpy(this->manufacturer_data_.data(), data.data(), this->manufacturer_data_len_);
}
esp_err_t BLEAdvertising::services_advertisement_() {
int num_services = this->advertising_uuids_.size();
if (num_services == 0) {
this->advertising_data_.service_uuid_len = 0;
} else {
this->advertising_data_.service_uuid_len = 16 * num_services;
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
this->advertising_data_.p_service_uuid = new uint8_t[this->advertising_data_.service_uuid_len];
uint8_t *p = this->advertising_data_.p_service_uuid;
for (int i = 0; i < num_services; i++) {
ESPBTUUID uuid = this->advertising_uuids_[i];
memcpy(p, uuid.as_128bit().get_uuid().uuid.uuid128, 16);
p += 16;
}
}
char name_buffer[ESP32BLE::DEVICE_NAME_BUFFER_SIZE];
const char *name = global_ble->device_name(name_buffer);
AdvPayload adv;
AdvPayload rsp;
build_adv_packets({.uuids = this->advertising_uuids_,
.priority_uuid = this->priority_uuid_,
.manufacturer_data = {this->manufacturer_data_.data(), this->manufacturer_data_len_},
.service_data = {this->service_data_.data(), this->service_data_len_},
.name = name,
.name_len = strlen(name),
.appearance = this->appearance_,
.tx_power_dbm = adv_tx_power_dbm(),
.name_in_adv = this->include_name_in_adv_},
adv, rsp);
esp_err_t err;
this->advertising_data_.set_scan_rsp = false;
this->advertising_data_.include_name = this->include_name_in_adv_ || !this->scan_response_;
this->advertising_data_.include_txpower = !this->scan_response_;
err = esp_ble_gap_config_adv_data(&this->advertising_data_);
// Bluedroid copies the bytes during each call
esp_err_t err = esp_ble_gap_config_adv_data_raw(const_cast<uint8_t *>(adv.data()), adv.size());
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Advertising): %s", esp_err_to_name(err));
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data_raw failed: %s", esp_err_to_name(err));
return err;
}
if (this->scan_response_) {
memcpy(&this->scan_response_data_, &this->advertising_data_, sizeof(esp_ble_adv_data_t));
this->scan_response_data_.set_scan_rsp = true;
this->scan_response_data_.include_name = true;
this->scan_response_data_.include_txpower = true;
this->scan_response_data_.manufacturer_len = 0;
this->scan_response_data_.appearance = 0;
this->scan_response_data_.flag = 0;
err = esp_ble_gap_config_adv_data(&this->scan_response_data_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_adv_data failed (Scan response): %s", esp_err_to_name(err));
return err;
}
err = esp_ble_gap_config_scan_rsp_data_raw(const_cast<uint8_t *>(rsp.data()), rsp.size());
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_config_scan_rsp_data_raw failed: %s", esp_err_to_name(err));
return err;
}
if (this->advertising_data_.service_uuid_len > 0) {
delete[] this->advertising_data_.p_service_uuid;
this->advertising_data_.p_service_uuid = nullptr;
}
err = esp_ble_gap_start_advertising(&this->advertising_params_);
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_start_advertising failed: %s", esp_err_to_name(err));
return err;
}
return ESP_OK;
}
@@ -134,6 +113,7 @@ void BLEAdvertising::start() {
}
void BLEAdvertising::stop() {
this->start_pending_ = false;
esp_err_t err = esp_ble_gap_stop_advertising();
if (err != ESP_OK) {
ESP_LOGE(TAG, "esp_ble_gap_stop_advertising failed: %d", err);
@@ -145,6 +125,11 @@ void BLEAdvertising::stop() {
}
void BLEAdvertising::loop() {
// Send a queued start after the event drain
if (this->start_pending_) {
this->start_pending_ = false;
this->start();
}
if (this->raw_advertisements_callbacks_.empty()) {
return;
}
+18 -8
View File
@@ -12,7 +12,6 @@
#ifdef USE_ESP32_BLE_ADVERTISING
#include <esp_gap_ble_api.h>
#include <esp_gatts_api.h>
namespace esphome::esp32_ble {
@@ -24,25 +23,28 @@ class BLEAdvertising {
void add_service_uuid(ESPBTUUID uuid);
void remove_service_uuid(ESPBTUUID uuid);
void set_scan_response(bool scan_response) { this->scan_response_ = scan_response; }
void set_min_preferred_interval(uint16_t interval) { this->advertising_data_.min_interval = interval; }
void set_manufacturer_data(const std::vector<uint8_t> &data);
void set_appearance(uint16_t appearance) { this->advertising_data_.appearance = appearance; }
void set_appearance(uint16_t appearance) { this->appearance_ = appearance; }
void set_service_data(const std::vector<uint8_t> &data);
void set_service_data(std::span<const uint8_t> data);
void set_include_name(bool include_name) { this->include_name_in_adv_ = include_name; }
/// Give `uuid` and the service data the advertising packet; the rest moves to the scan response.
void set_priority_uuid(ESPBTUUID uuid) { this->priority_uuid_ = uuid; }
void clear_priority_uuid() { this->priority_uuid_ = {}; }
void register_raw_advertisement_callback(std::function<void(bool)> &&callback);
void start();
void stop();
/// Send from the next loop(): a burst of refreshes becomes one send instead of flooding the Bluetooth task queue.
void request_start() { this->start_pending_ = true; }
void cancel_start() { this->start_pending_ = false; }
protected:
// An element longer than this never fits in a 31 byte packet
static constexpr size_t MAX_DATA_LEN = 29;
esp_err_t services_advertisement_();
bool scan_response_;
bool include_name_in_adv_{false};
esp_ble_adv_data_t advertising_data_;
esp_ble_adv_data_t scan_response_data_;
esp_ble_adv_params_t advertising_params_;
std::vector<ESPBTUUID> advertising_uuids_;
@@ -50,7 +52,15 @@ class BLEAdvertising {
const uint32_t advertising_cycle_time_;
uint32_t last_advertisement_time_{0};
std::array<uint8_t, MAX_DATA_LEN> manufacturer_data_;
std::array<uint8_t, MAX_DATA_LEN> service_data_;
ESPBTUUID priority_uuid_; // unset when no service has priority
uint16_t appearance_{0};
int8_t current_adv_index_{-1}; // -1 means standard scan response
uint8_t manufacturer_data_len_{0};
uint8_t service_data_len_{0};
bool include_name_in_adv_{false};
bool start_pending_{false};
};
} // namespace esphome::esp32_ble
@@ -0,0 +1,38 @@
// 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.
// Compiled only with Bluedroid's private headers (bluedroid_headers_cmake); static analysis skips it
#ifdef USE_ESP32_BLE_BLUEDROID_HEADERS
#include <stdbool.h>
#include <stddef.h>
#include "btm_int.h"
#include "smp_int.h"
// The device record whose keys smp_check_auth_req() must keep, or NULL
static tBTM_SEC_DEV_REC *keep_keys_of = NULL;
void __real_smp_check_auth_req(tSMP_CB *p_cb, tSMP_INT_DATA *p_data);
void __real_btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC *p_dev_rec);
// Runs on the Bluetooth host task. Encryption that succeeded without a Pairing Request or Response reused the bond.
void __wrap_smp_check_auth_req(tSMP_CB *p_cb, tSMP_INT_DATA *p_data) {
const bool reused_bond = *(UINT8 *) p_data == 1 && !(p_cb->flags & SMP_PAIR_FLAG_ENC_AFTER_PAIR);
// The same lookup as smp_check_auth_req(): it also matches a pseudo or resolvable private address
keep_keys_of = reused_bond ? btm_find_dev(p_cb->pairing_bda) : NULL;
__real_smp_check_auth_req(p_cb, p_data);
keep_keys_of = NULL;
}
void __wrap_btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC *p_dev_rec) {
// Only the first clear, the one the upstream guard skips; later callers are not affected
if (keep_keys_of != NULL && p_dev_rec == keep_keys_of) {
keep_keys_of = NULL;
return;
}
__real_btm_sec_clear_ble_keys(p_dev_rec);
}
#endif // USE_ESP32_BLE_BLUEDROID_HEADERS
@@ -0,0 +1,30 @@
// Linker wrap that puts a GATT discovery response back in handle order before Bluedroid parses it.
// 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"
#ifdef USE_ESP32_BLE_GATTC_HANDLE_ORDER
#include "bluedroid_gattc_order.h"
namespace esphome::esp32_ble {}
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
extern "C" {
// tGATT_TCB is only passed through
void __real_gatt_client_handle_server_rsp(void *p_tcb, uint8_t op_code, uint16_t len, uint8_t *p_data,
uint16_t eatt_bearer_lcid);
// Runs on the Bluetooth host task
void __wrap_gatt_client_handle_server_rsp(void *p_tcb, uint8_t op_code, uint16_t len, uint8_t *p_data,
uint16_t eatt_bearer_lcid) {
esphome::esp32_ble::sort_att_response_by_handle(op_code, p_data, len);
__real_gatt_client_handle_server_rsp(p_tcb, op_code, len, p_data, eatt_bearer_lcid);
}
} // extern "C"
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
#endif // USE_ESP32_BLE_GATTC_HANDLE_ORDER
@@ -0,0 +1,57 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include "esphome/core/helpers.h"
namespace esphome::esp32_ble {
static constexpr uint8_t ATT_FIND_INFO_RSP = 0x05;
static constexpr uint8_t ATT_FIND_BY_TYPE_VALUE_RSP = 0x07;
static constexpr uint8_t ATT_READ_BY_TYPE_RSP = 0x09;
static constexpr uint8_t ATT_READ_BY_GRP_TYPE_RSP = 0x11;
static constexpr size_t ATT_MAX_MTU = 517;
/// Sort records of `size` bytes that each start with a little-endian handle, in place; a partial tail is left alone.
inline void sort_records_by_handle(uint8_t *records, size_t len, size_t size) {
const size_t count = len / size;
auto handle = [records, size](size_t i) { return encode_uint16(records[i * size + 1], records[i * size]); };
for (size_t i = 1; i < count; i++) {
const uint16_t current = handle(i);
size_t j = i;
while (j > 0 && handle(j - 1) > current)
j--;
if (j != i)
std::rotate(records + j * size, records + i * size, records + (i + 1) * size);
}
}
/// Sort the records of an ATT discovery response by handle, in place; `data` is the PDU after the opcode.
/// A body longer than any ATT_MTU allows is left for Bluedroid to reject, so a peer cannot make the sort costly.
inline void sort_att_response_by_handle(uint8_t op_code, uint8_t *data, size_t len) {
if (len < 1 || len >= ATT_MAX_MTU)
return;
switch (op_code) {
case ATT_READ_BY_TYPE_RSP:
case ATT_READ_BY_GRP_TYPE_RSP:
// Length byte, then records of that length
if (data[0] >= 2)
sort_records_by_handle(data + 1, len - 1, data[0]);
break;
case ATT_FIND_INFO_RSP:
// Format byte: handle and 16-bit UUID, or handle and 128-bit UUID
if (data[0] == 1 || data[0] == 2)
sort_records_by_handle(data + 1, len - 1, data[0] == 1 ? 4 : 18);
break;
case ATT_FIND_BY_TYPE_VALUE_RSP:
// Found handle and group end handle, no header
sort_records_by_handle(data, len, 4);
break;
default:
break;
}
}
} // namespace esphome::esp32_ble
@@ -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"
@@ -3,14 +3,13 @@
#ifdef USE_ESP32
#include <cstring>
#include <esp_gatt_defs.h>
namespace esphome::esp32_ble_server {
BLE2902::BLE2902() : BLEDescriptor(esp32_ble::ESPBTUUID::from_uint16(0x2902)) {
this->value_.attr_len = 2;
uint8_t data[2] = {0, 0};
memcpy(this->value_.attr_value, data, 2);
// The client configuration value is always 2 bytes
BLE2902::BLE2902() : BLEDescriptor(esp32_ble::ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG), 2) {
this->set_value({0, 0});
}
} // namespace esphome::esp32_ble_server
@@ -27,9 +27,11 @@ from esphome.components.esp32_ble import (
bt_uuid32_format,
bt_uuid128_format,
)
from esphome.components.wifi import DOMAIN as WIFI_DOMAIN
import esphome.config_validation as cv
from esphome.const import (
CONF_ACTIVE,
CONF_AP,
CONF_CONTINUOUS,
CONF_DURATION,
CONF_ID,
@@ -78,6 +80,7 @@ def _get_required_features() -> set[BLEFeatures]:
# Slot counters sizing the tracker's StaticVector storage; one request per
# registered listener or client.
CLIENT_COUNT_DEFINE = "ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT"
SHORT_SCAN_WINDOW_DEFINE = "USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW"
_request_listener_slot = cg.slot_counter("ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT")
_request_client_slot = cg.slot_counter(CLIENT_COUNT_DEFINE)
@@ -137,7 +140,9 @@ def validate_max_connections_deprecated(config: ConfigType) -> ConfigType:
# listens 9.4 % of the time and misses most advertisements when wifi shares
# the radio. Espressif recommends setting the window equal to the interval in
# that case: the coexistence arbiter still shares the radio with wifi, and
# BLE uses the airtime wifi does not claim.
# BLE uses the airtime wifi does not claim. Full duty leaves the AP no airtime
# for joins though, so while the AP runs the tracker drops back to the short
# window (esphome/esphome#22534).
IDF_SCAN_WINDOW_FIX_VERSION = cv.Version(5, 5, 5)
# Above this the scanner holds the shared radio long enough that wifi drops
@@ -181,6 +186,8 @@ def _raise_defaulted_scan_window(config: ConfigType) -> ConfigType:
present iff wifi is configured and not disabled by the user) and the IDF
honors the window strictly (>= 5.5.5); without the arbiter a full-duty
scan would starve wifi outright, and a user-set window is never touched.
The raise also arms the short window used while a GATT connection or the
wifi AP is active.
Raising to the interval cannot invalidate the already-validated
parameters, so no re-validation is needed. The connection window is
checked against the window here, after the raise.
@@ -194,7 +201,7 @@ def _raise_defaulted_scan_window(config: ConfigType) -> ConfigType:
# Copy so the config dump shows a plain value instead of a YAML
# anchor/alias pair pointing at the interval.
params[CONF_WINDOW] = copy.copy(params[CONF_INTERVAL])
# Arm the connection-time fallback unless the user set one. Injected
# Arm the connection and AP fallback unless the user set one. Injected
# after validation; safe because it equals the validated window default.
if CONF_CONNECTION_SCAN_WINDOW not in params:
params[CONF_CONNECTION_SCAN_WINDOW] = cv.positive_time_period(
@@ -353,20 +360,22 @@ async def to_code(config: ConfigType) -> None:
cg.add(var.set_scan_interval(ble_device_base.to_ble_units(params[CONF_INTERVAL])))
cg.add(var.set_scan_window(ble_device_base.to_ble_units(params[CONF_WINDOW])))
if (connection_window := params.get(CONF_CONNECTION_SCAN_WINDOW)) is not None:
# Emitted at FINAL so a scan-only build, where the guarded C++ path
# compiles out, skips the call entirely.
# Emitted at FINAL, once the client count is known: a build with
# neither clients nor a wifi AP compiles the short-window path out.
window_units = ble_device_base.to_ble_units(connection_window)
@coroutine_with_priority(CoroPriority.FINAL)
async def _emit_connection_scan_window() -> None:
if cg.get_slot_count(CLIENT_COUNT_DEFINE):
has_ap = CONF_AP in CORE.config.get(WIFI_DOMAIN, {})
if cg.get_slot_count(CLIENT_COUNT_DEFINE) or has_ap:
cg.add_define(SHORT_SCAN_WINDOW_DEFINE)
cg.add(var.set_connection_scan_window(window_units))
elif not _get_data().connection_window_injected:
# Warn only for a user-set value; the injected default drops silently.
_LOGGER.warning(
"'%s' has no effect because this build has no BLE client "
"components (for example bluetooth_proxy with active "
"connections, or ble_client)",
"connections, or ble_client) and no wifi access point",
CONF_CONNECTION_SCAN_WINDOW,
)
@@ -26,6 +26,10 @@
#include <esp_coexist.h>
#endif
#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
#include "esphome/components/wifi/wifi_component.h"
#endif
// bt_trace.h
#undef TAG
@@ -80,6 +84,15 @@ void ESP32BLETracker::loop() {
if (!this->parent_->is_active()) {
return;
}
#if defined(USE_WIFI_AP) && defined(USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW)
// The AP state is not versioned; fold its changes in so the window restart runs.
const bool ap_active = wifi::global_wifi_component->is_ap_active();
if (ap_active != this->ap_active_) {
this->ap_active_ = ap_active;
this->state_version_++;
}
#endif
if (this->ble_was_disabled_) {
this->ble_was_disabled_ = false;
// First start after boot or after the stack came back.
@@ -126,9 +139,10 @@ void ESP32BLETracker::loop() {
// - start_scan_(): scanner_state_ becomes IDLE via set_scanner_state_() in cleanup_scan_state_()
// - try_promote_discovered_clients_(): client enters DISCOVERED via set_state(), or
// connecting client finishes (state change), or scanner reaches RUNNING/IDLE
// - connection-window restart: scan_params_ is only written in start_scan_()
// (which changes scanner state via set_scanner_state_()), and
// counts.active/disconnecting only change on client state changes
// - short-window restart: scan_params_ is only written in start_scan_()
// (which changes scanner state via set_scanner_state_()),
// counts.active/disconnecting only change on client state changes, and
// ap_active_ changes bump state_version_ at the top of loop()
//
// All conditions that affect the logic below are tied to state changes that increment
// state_version_, so the fast path is safe.
@@ -152,11 +166,12 @@ void ESP32BLETracker::loop() {
this->handle_scanner_failure_();
}
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
// The programmed window no longer matches the connection state (typically
// the last connection dropped): restart so the right window applies now
// instead of at the end of the scan period. Continuous only (a user-started
// scan would not restart); !disconnecting matches the restart gate below.
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
// The programmed window no longer matches the connection or AP state
// (typically the last connection dropped, or the AP started or stopped):
// restart so the right window applies now instead of at the end of the scan
// period. Continuous only (a user-started scan would not restart);
// !disconnecting matches the restart gate below.
if (this->scanner_state_ == ScannerState::RUNNING && this->scan_continuous_ && !counts.disconnecting &&
this->scan_params_.scan_window != this->desired_scan_window_(counts.active)) {
// Same logical scan period continues: no on_scan_end sweeps for this
@@ -215,7 +230,7 @@ void ESP32BLETracker::stop_scan() {
// reason at D themselves, and the user-facing stop action is deliberate.
ESP_LOGV(TAG, "Stopping scan.");
this->scan_continuous_ = false;
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
// The window-change restart is abandoned with continuous scanning.
this->skip_next_scan_end_ = false;
#endif
@@ -231,6 +246,8 @@ void ESP32BLETracker::ble_before_disabled_event_handler() {
for (auto *client : this->clients_) {
client->ble_before_disabled_event_handler();
}
#endif
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
this->skip_next_scan_end_ = false;
#endif
// The stop above never completes (stack torn down, events dropped); settle
@@ -277,7 +294,7 @@ void ESP32BLETracker::start_scan_(bool first) {
ESP_LOGV(TAG, "Starting scan, set scanner state to STARTING.");
if (!first)
this->notify_scan_end_();
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
this->skip_next_scan_end_ = false;
#endif
#ifdef USE_ESP32_BLE_DEVICE
@@ -287,12 +304,12 @@ void ESP32BLETracker::start_scan_(bool first) {
this->scan_params_.own_addr_type = BLE_ADDR_TYPE_PUBLIC;
this->scan_params_.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL;
this->scan_params_.scan_interval = this->scan_interval_;
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
// Count fresh: an automation can start a scan before loop() refreshes the counts.
const uint32_t window = this->desired_scan_window_(this->count_client_states_().active);
if (window != this->scan_window_) {
// Guarantee the connection airtime instead of scanning wall to wall.
ESP_LOGV(TAG, "Connection active, using %" PRIu32 " unit scan window", window);
// Leave airtime for the connection or the AP instead of scanning wall to wall.
ESP_LOGV(TAG, "Connection or AP active, using %" PRIu32 " unit scan window", window);
}
#else
const uint32_t window = this->scan_window_;
@@ -458,7 +475,7 @@ void ESP32BLETracker::dump_config() {
" Continuous Scanning: %s",
this->scan_duration_, this->scan_interval_ * 0.625f, this->scan_window_ * 0.625f,
this->scan_active_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
if (this->connection_scan_window_ != 0) {
ESP_LOGCONFIG(TAG, " Connection Scan Window: %.1f ms", this->connection_scan_window_ * 0.625f);
}
@@ -548,7 +565,7 @@ void ESP32BLETracker::cleanup_scan_state_(bool is_stop_complete) {
}
void ESP32BLETracker::notify_scan_end_() {
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
// Window-change restart continues the same scan period; the flag stays set
// across the stop and is cleared by the restart in start_scan_.
if (this->skip_next_scan_end_)
@@ -599,8 +616,10 @@ void ESP32BLETracker::try_promote_discovered_clients_() {
}
ESP_LOGD(TAG, "Promoting client to connect");
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
// A connect ends the scan period a window-change restart was continuing.
this->skip_next_scan_end_ = false;
#endif
#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
this->update_coex_preference_(true);
#endif
@@ -172,7 +172,7 @@ class ESP32BLETracker final : public Component,
void set_scan_duration(uint32_t scan_duration) { scan_duration_ = scan_duration; }
void set_scan_interval(uint32_t scan_interval) { scan_interval_ = scan_interval; }
void set_scan_window(uint32_t scan_window) { scan_window_ = scan_window; }
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
void set_connection_scan_window(uint32_t scan_window) { connection_scan_window_ = scan_window; }
#endif
void set_scan_active(bool scan_active) { scan_active_ = scan_active; }
@@ -328,13 +328,15 @@ class ESP32BLETracker final : public Component,
uint32_t scan_duration_;
uint32_t scan_interval_;
uint32_t scan_window_;
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
/// Window used while a GATT connection is active; set by the user, or
/// defaulted when the window was raised to full duty (0 = no fallback).
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
/// Window used while a GATT connection or the wifi AP is active; set by the
/// user, or defaulted when the window was raised to full duty (0 = none).
uint32_t connection_scan_window_{0};
/// The window to scan at for the given number of active GATT connections.
/// The window to scan at for the given number of active GATT connections
/// and the last seen AP state.
uint32_t desired_scan_window_(uint8_t active) const {
return (this->connection_scan_window_ != 0 && active > 0) ? this->connection_scan_window_ : this->scan_window_;
return (this->connection_scan_window_ != 0 && (active > 0 || this->ap_active_)) ? this->connection_scan_window_
: this->scan_window_;
}
#endif
esp_bt_status_t scan_start_failed_{ESP_BT_STATUS_SUCCESS};
@@ -362,9 +364,11 @@ class ESP32BLETracker final : public Component,
#endif
bool ble_was_disabled_ : 1 {true};
bool parse_advertisements_ : 1 {false};
#ifdef ESPHOME_ESP32_BLE_TRACKER_CLIENT_COUNT
#ifdef USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
/// Suppress the window-change restart's on_scan_end sweeps (stop and start).
bool skip_next_scan_end_ : 1 {false};
/// Last seen wifi AP state, polled by loop(); stays false without an AP.
bool ap_active_ : 1 {false};
#endif
#ifdef USE_ESP32_BLE_SOFTWARE_COEXISTENCE
bool coex_prefer_ble_ : 1 {false};
@@ -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
-5
View File
@@ -4,8 +4,6 @@
#include <osapi.h>
#include <user_interface.h>
// for xt_rsil()/xt_wsr_ps()
#include <Arduino.h>
namespace esphome {
@@ -15,9 +13,6 @@ bool random_bytes(uint8_t *data, size_t len) { return os_get_random(data, len) =
// ESP8266 Mutex is defined inline as a no-op in helpers.h when USE_ESP8266 (or USE_RP2) is set,
// independent of the ESPHOME_THREAD_SINGLE thread model define.
IRAM_ATTR InterruptLock::InterruptLock() { state_ = xt_rsil(15); }
IRAM_ATTR InterruptLock::~InterruptLock() { xt_wsr_ps(state_); }
// ESP8266 LwIPLock is defined inline as a no-op in helpers.h
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
+1 -1
View File
@@ -248,7 +248,7 @@ async def to_code(config: ConfigType) -> None:
)
wifi.enable_runtime_roaming_suppression()
esp32.add_idf_component(name="francescopace/espectre", ref="3.1.0")
esp32.add_idf_component(name="francescopace/espectre", ref="3.2.0")
esp32.add_idf_sdkconfig_option("CONFIG_ESP_WIFI_CSI_ENABLED", True)
# CSI is reported once per received transmission, so aggregation hides frames from sensing.
# Disabling TX aggregation also lets the SDK fix the station TX rate (6.5 Mbps on ESP32).
@@ -422,10 +422,15 @@ void ESPHomeOTAComponent::handle_handshake_() {
} else
#endif
{
// No password, move directly to data phase
// No password, move directly to data phase. Not a fallthrough: the next
// case is AUTH_SEND, which would demand a password that is not set.
this->transition_ota_state_(OTAState::DATA);
this->handle_data_();
return;
}
#ifdef USE_OTA_PASSWORD
[[fallthrough]];
#endif
}
#ifdef USE_OTA_PASSWORD
@@ -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 */
@@ -22,8 +22,9 @@ void GPIOOneWireBus::dump_config() {
this->dump_devices_(TAG);
}
// Lock only what must not stretch; the ESP8266 Wi-Fi interrupt handler asserts (hardware WDT) when held off ~1 ms.
// A longer gap between slots is within spec.
int HOT IRAM_ATTR GPIOOneWireBus::reset_int() {
InterruptLock lock;
// See reset here:
// https://www.maximintegrated.com/en/design/technical-documents/app-notes/1/126.html
// Wait for communication to clear (delay G)
@@ -36,27 +37,31 @@ int HOT IRAM_ATTR GPIOOneWireBus::reset_int() {
} while (!this->pin_.digital_read());
bool r = false;
uint32_t start;
{
// Locked from the reset pulse through presence detection (at most about 780 us): a reset pulse stretched past
// 960 us power-resets a parasite-powered sensor
InterruptLock lock;
// Send 480µs LOW TX reset pulse (drive bus low, delay H)
this->pin_.digital_write(false);
this->pin_.pin_mode(gpio::FLAG_OUTPUT);
delayMicroseconds(480);
// Send 480µs LOW TX reset pulse (drive bus low, delay H)
this->pin_.digital_write(false);
this->pin_.pin_mode(gpio::FLAG_OUTPUT);
delayMicroseconds(480);
// Release the bus, delay I
this->pin_.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
start = micros();
delayMicroseconds(30);
// Release the bus, delay I
this->pin_.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
uint32_t start = micros();
delayMicroseconds(30);
while (micros() - start < 300) {
// sample bus, 0=device(s) present, 1=no device present
r = !this->pin_.digital_read();
if (r)
break;
delayMicroseconds(1);
while (micros() - start < 300) {
// sample bus, 0=device(s) present, 1=no device present
r = !this->pin_.digital_read();
if (r)
break;
delayMicroseconds(1);
}
}
// delay J: finish the 480us slot, but never spin if it already elapsed
// (unsigned wrap here would busy-wait for minutes with interrupts off)
// delay J: finish the 480us slot, but never spin if it already elapsed (unsigned wrap)
uint32_t elapsed = micros() - start;
if (elapsed < 480)
delayMicroseconds(480 - elapsed);
@@ -66,9 +71,6 @@ int HOT IRAM_ATTR GPIOOneWireBus::reset_int() {
}
void HOT IRAM_ATTR GPIOOneWireBus::write_bit_(bool bit) {
// drive bus low
this->pin_.digital_write(false);
// from datasheet:
// write 0 low time: t_low0: min=60µs, max=120µs
// write 1 low time: t_low1: min=1µs, max=15µs
@@ -78,27 +80,36 @@ void HOT IRAM_ATTR GPIOOneWireBus::write_bit_(bool bit) {
uint32_t delay0 = bit ? 6 : 60;
uint32_t delay1 = bit ? 64 : 10;
// delay A/C
delayMicroseconds(delay0);
// release bus
this->pin_.digital_write(true);
{
InterruptLock lock;
// drive bus low
this->pin_.digital_write(false);
// delay A/C
delayMicroseconds(delay0);
// release bus
this->pin_.digital_write(true);
}
// delay B/D
delayMicroseconds(delay1);
}
bool HOT IRAM_ATTR GPIOOneWireBus::read_bit_() {
// drive bus low
this->pin_.digital_write(false);
bool r;
{
InterruptLock lock;
// drive bus low
this->pin_.digital_write(false);
// datasheet says >= 1µs
delayMicroseconds(5);
// datasheet says >= 1µs
delayMicroseconds(5);
// release bus, delay E
this->pin_.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
// release bus, delay E
this->pin_.pin_mode(gpio::FLAG_INPUT | gpio::FLAG_PULLUP);
delayMicroseconds(8);
// sample bus to read bit from peer
bool r = this->pin_.digital_read();
delayMicroseconds(8);
// sample bus to read bit from peer
r = this->pin_.digital_read();
}
// read slot is at least 60µs
delayMicroseconds(50);
@@ -109,21 +120,18 @@ bool HOT IRAM_ATTR GPIOOneWireBus::read_bit_() {
}
void IRAM_ATTR GPIOOneWireBus::write8(uint8_t val) {
InterruptLock lock;
for (uint8_t i = 0; i < 8; i++) {
this->write_bit_(bool((1u << i) & val));
}
}
void IRAM_ATTR GPIOOneWireBus::write64(uint64_t val) {
InterruptLock lock;
for (uint8_t i = 0; i < 64; i++) {
this->write_bit_(bool((1ULL << i) & val));
}
}
uint8_t IRAM_ATTR GPIOOneWireBus::read8() {
InterruptLock lock;
uint8_t ret = 0;
for (uint8_t i = 0; i < 8; i++)
ret |= (uint8_t(this->read_bit_()) << i);
@@ -131,7 +139,6 @@ uint8_t IRAM_ATTR GPIOOneWireBus::read8() {
}
uint64_t IRAM_ATTR GPIOOneWireBus::read64() {
InterruptLock lock;
uint64_t ret = 0;
for (uint8_t i = 0; i < 64; i++) {
ret |= (uint64_t(this->read_bit_()) << i);
@@ -146,7 +153,6 @@ void GPIOOneWireBus::reset_search() {
}
uint64_t IRAM_ATTR GPIOOneWireBus::search_int() {
InterruptLock lock;
if (this->last_device_flag_)
return 0u;
+3
View File
@@ -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
@@ -233,8 +233,8 @@ void HT16K33CharDisplay::set_blink(uint8_t blink) {
this->send_(this->display_setup_command_());
}
void HT16K33CharDisplay::display_off(bool turn_off) {
assign_bits(this->display_setup_, DISPLAY_ON, !turn_off);
void HT16K33CharDisplay::display_power(bool power_status) {
assign_bits(this->display_setup_, DISPLAY_ON, power_status);
this->send_(this->display_setup_command_());
}
@@ -52,7 +52,8 @@ class HT16K33CharDisplay final : public PollingComponent, public i2c::I2CDevice
/// 0 steady, 1 at 2 Hz, 2 at 1 Hz, 3 at 0.5 Hz; before setup only the value is kept
void set_blink(uint8_t blink);
void display_off(bool turn_off);
/// Turn the display on or off
void display_power(bool power_status);
/// Stop the oscillator, the lowest power state; before setup only the value is kept
void display_standby(bool standby);
/// Clear the display memory; the next update redraws the message
+4
View File
@@ -325,6 +325,10 @@ async def to_code(config: ConfigType) -> None:
# Re-enable the I2C driver (excluded by default to save compile time)
include_builtin_idf_component("esp_driver_i2c")
if get_esp32_variant() == VARIANT_ESP32:
# ACK_ERR interrupt storm after a NACK; see i2c_bus_esp_idf.cpp
cg.add_define("USE_I2C_ISR_GUARD")
cg.add_build_flag("-Wl,--wrap=esp_intr_alloc_intrstatus")
if CORE.is_host:
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
@@ -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) {
@@ -10,6 +10,70 @@
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#ifdef USE_I2C_ISR_GUARD
#include <esp_intr_alloc.h>
#include <hal/i2c_ll.h> // declares i2c_periph_signal (IDF 5: soc/, IDF 6: hal/)
#if SOC_I2C_SUPPORT_HW_FSM_RST || I2C_LL_SUPPORT_HW_FSM_RST
#error "This chip has an I2C FSM reset; the ISR guard is no longer needed"
#endif
namespace esphome::i2c {
// Without an FSM reset ACK_ERR can stay raised and the IDF ISR never masks it (esp-idf#17690). Mask the master
// events until the next transaction when an error is raised both before and after the handler clears it.
static constexpr uint32_t I2C_ERROR_INTR = I2C_LL_INTR_NACK | I2C_LL_INTR_TIMEOUT | I2C_LL_INTR_ARBITRATION;
static_assert((I2C_LL_MASTER_EVENT_INTR & I2C_ERROR_INTR) == I2C_ERROR_INTR,
"The master event mask must cover the error interrupts");
struct I2CIsrGuard {
intr_handler_t handler;
void *arg;
i2c_dev_t *dev;
};
static I2CIsrGuard i2c_isr_guards[SOC_HP_I2C_NUM]; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
static void IRAM_ATTR i2c_isr_guard(void *arg) {
auto *guard = static_cast<I2CIsrGuard *>(arg);
uint32_t before;
i2c_ll_get_intr_mask(guard->dev, &before);
guard->handler(guard->arg);
uint32_t after;
i2c_ll_get_intr_mask(guard->dev, &after);
if (before & after & I2C_ERROR_INTR)
i2c_ll_disable_intr_mask(guard->dev, I2C_LL_MASTER_EVENT_INTR);
}
static int i2c_port_for_source(int source) {
for (int port = 0; port < SOC_HP_I2C_NUM; port++) {
if (source == i2c_periph_signal[port].irq)
return port;
}
return -1;
}
} // namespace esphome::i2c
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
extern "C" {
esp_err_t __real_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler,
void *arg, intr_handle_t *ret_handle);
esp_err_t __wrap_esp_intr_alloc_intrstatus(int source, int flags, uint32_t reg, uint32_t mask, intr_handler_t handler,
void *arg, intr_handle_t *ret_handle) {
int port = esphome::i2c::i2c_port_for_source(source);
if (port < 0)
return __real_esp_intr_alloc_intrstatus(source, flags, reg, mask, handler, arg, ret_handle);
auto &guard = esphome::i2c::i2c_isr_guards[port];
auto previous = guard;
guard = {handler, arg, I2C_LL_GET_HW(port)};
esp_err_t err =
__real_esp_intr_alloc_intrstatus(source, flags, reg, mask, esphome::i2c::i2c_isr_guard, &guard, ret_handle);
if (err != ESP_OK)
guard = previous; // a failed allocation leaves the live guard alone
return err;
}
} // extern "C"
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
#endif // USE_I2C_ISR_GUARD
namespace esphome::i2c {
ESPHOME_LOG_TAG(TAG, "i2c");
@@ -116,6 +180,12 @@ void IDFI2CBus::dump_config() {
if (this->timeout_ > 0) {
ESP_LOGCONFIG(TAG, " Timeout: %" PRIu32 "us", this->timeout_);
}
#ifdef USE_I2C_ISR_GUARD
// Null when the IDF driver no longer allocates its interrupt through the wrapped call
if (i2c_isr_guards[this->port_].handler == nullptr) {
ESP_LOGW(TAG, " Interrupt guard inactive");
}
#endif
switch (this->recovery_result_) {
case RECOVERY_COMPLETED:
ESP_LOGCONFIG(TAG, " Recovery: bus successfully recovered");
+2 -1
View File
@@ -7,6 +7,7 @@
#include "esphome/core/helpers.h"
#include <esp_idf_version.h>
#include <driver/i2s_std.h>
#include <soc/soc_caps.h>
namespace esphome::i2s_audio {
@@ -24,7 +25,7 @@ class I2SAudioBase : public Parented<I2SAudioComponent> {
protected:
i2s_clock_src_t get_clock_source_() const {
#ifdef I2S_CLK_SRC_APLL
#if SOC_CLK_APLL_SUPPORTED
if (this->use_apll_) {
return I2S_CLK_SRC_APLL;
}
@@ -527,6 +527,8 @@ void ImprovBLEComponent::request_advertising_() {
if (this->advertising_requested_)
return;
this->advertising_requested_ = true;
// Passive scanners only see the advertising packet
esp32_ble::global_ble->advertising_set_priority_uuid(ESPBTUUID::from_raw(improv::SERVICE_UUID));
esp32_ble::global_ble->advertising_start();
}
@@ -534,6 +536,7 @@ void ImprovBLEComponent::release_advertising_() {
if (!this->advertising_requested_)
return;
this->advertising_requested_ = false;
esp32_ble::global_ble->advertising_clear_priority_uuid();
esp32_ble::global_ble->advertising_stop();
}
-5
View File
@@ -8,8 +8,6 @@ from esphome.const import (
CONF_MOVE_THRESHOLD,
CONF_STILL_THRESHOLD,
CONF_TIMEOUT,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
ENTITY_CATEGORY_CONFIG,
ICON_LIGHTBULB,
ICON_MOTION_SENSOR,
@@ -39,19 +37,16 @@ CONFIG_SCHEMA = cv.Schema(
),
cv.Inclusive(CONF_MAX_MOVE_DISTANCE_GATE, TIMEOUT_GROUP): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
cv.Inclusive(CONF_MAX_STILL_DISTANCE_GATE, TIMEOUT_GROUP): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
cv.Optional(CONF_LIGHT_THRESHOLD): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_ILLUMINANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_LIGHTBULB,
),
-2
View File
@@ -6,7 +6,6 @@ from esphome.const import (
CONF_LIGHT,
CONF_MOVING_DISTANCE,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
ENTITY_CATEGORY_DIAGNOSTIC,
ICON_FLASH,
ICON_LIGHTBULB,
@@ -55,7 +54,6 @@ CONFIG_SCHEMA = cv.Schema(
unit_of_measurement=UNIT_PERCENT,
),
cv.Optional(CONF_LIGHT): sensor.sensor_schema(
device_class=DEVICE_CLASS_ILLUMINANCE,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
filters=sensor.TIMEOUT_THROTTLE_FILTERS,
icon=ICON_LIGHTBULB,
-5
View File
@@ -8,8 +8,6 @@ from esphome.const import (
CONF_MOVE_THRESHOLD,
CONF_STILL_THRESHOLD,
CONF_TIMEOUT,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
ENTITY_CATEGORY_CONFIG,
ICON_LIGHTBULB,
ICON_MOTION_SENSOR,
@@ -33,19 +31,16 @@ CONFIG_SCHEMA = cv.Schema(
cv.GenerateID(CONF_LD2412_ID): cv.use_id(LD2412Component),
cv.Optional(CONF_LIGHT_THRESHOLD): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_ILLUMINANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_LIGHTBULB,
),
cv.Optional(CONF_MAX_DISTANCE_GATE): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
cv.Optional(CONF_MIN_DISTANCE_GATE): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
-4
View File
@@ -6,14 +6,12 @@ from esphome.const import (
CONF_LIGHT,
CONF_MOVING_DISTANCE,
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ILLUMINANCE,
ENTITY_CATEGORY_DIAGNOSTIC,
ICON_FLASH,
ICON_LIGHTBULB,
ICON_MOTION_SENSOR,
ICON_SIGNAL,
UNIT_CENTIMETER,
UNIT_EMPTY,
UNIT_PERCENT,
)
from esphome.types import ConfigType
@@ -39,11 +37,9 @@ CONFIG_SCHEMA = cv.Schema(
unit_of_measurement=UNIT_CENTIMETER,
),
cv.Optional(CONF_LIGHT): sensor.sensor_schema(
device_class=DEVICE_CLASS_ILLUMINANCE,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
filters=sensor.TIMEOUT_THROTTLE_FILTERS,
icon=ICON_LIGHTBULB,
unit_of_measurement=UNIT_EMPTY, # No standard unit for this light sensor
),
cv.Optional(CONF_MOVING_DISTANCE): sensor.sensor_schema(
device_class=DEVICE_CLASS_DISTANCE,
@@ -6,7 +6,6 @@ import esphome.config_validation as cv
from esphome.const import (
CONF_MOVE_THRESHOLD,
CONF_STILL_THRESHOLD,
DEVICE_CLASS_DISTANCE,
ENTITY_CATEGORY_CONFIG,
ICON_MOTION_SENSOR,
ICON_SCALE,
@@ -41,19 +40,16 @@ CONFIG_SCHEMA = cv.Schema(
),
cv.Inclusive(CONF_MIN_GATE_DISTANCE, TIMEOUT_GROUP): number.number_schema(
LD2420MinDistanceNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
cv.Inclusive(CONF_MAX_GATE_DISTANCE, TIMEOUT_GROUP): number.number_schema(
LD2420MaxDistanceNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
cv.Inclusive(CONF_GATE_SELECT, GATE_GROUP): number.number_schema(
LD2420GateSelectNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_MOTION_SENSOR,
),
@@ -69,13 +65,11 @@ CONFIG_SCHEMA = cv.Schema(
),
cv.Optional(CONF_GATE_MOVE_SENSITIVITY): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_SCALE,
),
cv.Optional(CONF_GATE_STILL_SENSITIVITY): number.number_schema(
number.ApplyNumber,
device_class=DEVICE_CLASS_DISTANCE,
entity_category=ENTITY_CATEGORY_CONFIG,
icon=ICON_SCALE,
),
+22
View File
@@ -61,6 +61,8 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
# Fault handlers the crash handler wraps (BK7238, BK7231N)
BK_TRAP_HANDLERS = ("bk_trap_udef", "bk_trap_pabt", "bk_trap_dabt")
# Timing functions RTL8710B builds replace (rtl8710b_micros.c)
RTL8710B_TIME_WRAPS = ("millis", "micros", "delay", "delayMicroseconds")
# Families with a crash handler; the Cortex-M ones install it at run time (no wraps).
CRASH_HANDLER_FAMILIES = (
FAMILY_BK7231N,
@@ -158,6 +160,16 @@ def _update_core_data(config):
return config
def FILTER_SOURCE_FILES() -> list[str]:
"""Leave the RTL8710B timing wrappers out of every other family's build."""
if (data := CORE.data.get(KEY_LIBRETINY)) is None or data.get(KEY_FAMILY) in (
None,
FAMILY_RTL8710B,
):
return []
return ["rtl8710b_micros.c"]
def get_libretiny_component(core_obj=None):
return (core_obj or CORE).data[KEY_LIBRETINY][KEY_COMPONENT]
@@ -375,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).
@@ -382,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.
"""
@@ -458,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
@@ -529,6 +548,9 @@ async def component_to_code(config):
# RTL8720C (ambz2) requires FreeRTOS 10.x so this only applies to RTL8710B
if config[CONF_FAMILY] == FAMILY_RTL8710B:
cg.add_platformio_option("custom_versions.freertos", "8.2.3")
# millis(), micros() and delays on the system timer and CPU cycles (see rtl8710b_micros.c)
for func in RTL8710B_TIME_WRAPS:
cg.add_build_flag(f"-Wl,--wrap={func}")
# LibreTiny bundles BDK 3.0.33 for these two but already builds BK7238 with 3.0.78,
# where STA+AP works (esphome#19430), the web server OTA does not trip the watchdog
@@ -37,6 +37,33 @@ ISRInternalGPIOPin ArduinoInternalGPIOPin::to_isr() const {
const_cast<ArduinoInternalGPIOPin *>(this)); // NOLINT(cppcoreguidelines-pro-type-const-cast)
}
#if defined(USE_LIBRETINY_VARIANT_RTL8710B) && !defined(CLANG_TIDY)
// RTL8710B GPIO interrupts on one edge only and LibreTiny maps CHANGE to rising, so flip the edge on every interrupt.
// Mirrors LibreTiny 1.14.0 wiring_irq.c (PinData is the SDK handler id); drop once libretiny-eu/libretiny#155 is fixed.
// Re-reads the level after each write; a pin still bouncing after four tries is corrected at its next edge.
static void IRAM_ATTR rtl8710b_arm_next_edge(gpio_irq_t *irq) {
uint32_t level = GPIO_ReadDataBit(irq->pin);
for (int i = 0; i < 4; i++) {
// gpio_irq_set() without its flash wrapper, so the handler runs from RAM and mask ROM only
GPIO_INTMode(irq->pin, ENABLE, GPIO_INT_Trigger_EDGE,
level ? GPIO_INT_POLARITY_ACTIVE_LOW : GPIO_INT_POLARITY_ACTIVE_HIGH, GPIO_INT_DEBOUNCE_ENABLE);
const uint32_t now = GPIO_ReadDataBit(irq->pin);
if (now == level)
return;
level = now;
}
}
static void IRAM_ATTR rtl8710b_change_handler(uint32_t id, gpio_irq_event event) {
auto *data = reinterpret_cast<PinData *>(id); // NOLINT(performance-no-int-to-ptr)
// A later attach with another mode keeps this handler
if (data->irqMode == CHANGE)
rtl8710b_arm_next_edge(data->irq);
if (data->irqHandler != nullptr)
reinterpret_cast<void (*)(void *)>(data->irqHandler)(data->irqParam);
}
#endif
void ArduinoInternalGPIOPin::attach_interrupt_(void (*func)(void *), void *arg, gpio::InterruptType type) const {
PinStatus arduino_mode = (PinStatus) 255;
switch (type) {
@@ -58,6 +85,20 @@ void ArduinoInternalGPIOPin::attach_interrupt_(void (*func)(void *), void *arg,
}
attachInterruptParam(pin_, func, arduino_mode, arg);
#if defined(USE_LIBRETINY_VARIANT_RTL8710B) && !defined(CLANG_TIDY)
if (arduino_mode == CHANGE) {
PinInfo *info = pinInfo(this->pin_);
PinData *data = info != nullptr ? info->data : nullptr;
if (data != nullptr && data->irq != nullptr) {
// The interrupt is already live: keep it from arming an edge between the level read and the write below
const uint32_t primask = __get_PRIMASK();
__disable_irq();
GPIO_UserRegIrq(data->irq->pin, reinterpret_cast<void *>(rtl8710b_change_handler), data);
rtl8710b_arm_next_edge(data->irq);
__set_PRIMASK(primask);
}
}
#endif
}
#ifdef USE_BK72XX
@@ -120,6 +161,13 @@ size_t ArduinoInternalGPIOPin::dump_summary(char *buffer, size_t len) const {
}
bool ArduinoInternalGPIOPin::digital_read() {
#if defined(USE_LIBRETINY_VARIANT_RTL8720C) && !defined(CLANG_TIDY)
// The Arduino read switches the pin back to GPIO and frees its interrupt, so read through the interrupt instead.
// Remove once LibreTiny's Arduino pin read handles this. The IRQ bit is only set once data->irq exists.
PinInfo *info = pinInfo(this->pin_);
if (info != nullptr && (info->enabled & PIN_IRQ))
return bool(gpio_irq_read(info->data->irq)) ^ this->inverted_;
#endif
return bool(digitalRead(this->pin_)) ^ this->inverted_; // NOLINT
}
void ArduinoInternalGPIOPin::digital_write(bool value) {
+12 -1
View File
@@ -90,11 +90,22 @@ __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().
#if defined(USE_RTL87XX) || defined(USE_LN882X)
#if defined(USE_LIBRETINY_VARIANT_RTL8710B)
// The RTL8710B tick is 976.6 us; millis() comes from the system timer instead (rtl8710b_micros.c)
__attribute__((always_inline)) inline uint32_t millis() { return static_cast<uint32_t>(::millis()); }
#elif defined(USE_RTL87XX) || defined(USE_LN882X)
static_assert(configTICK_RATE_HZ == 1000, "millis() fast path requires 1 kHz FreeRTOS tick");
__attribute__((always_inline)) inline uint32_t millis() {
// xTaskGetTickCountFromISR is mandatory in interrupt context per the FreeRTOS API contract.
@@ -0,0 +1,71 @@
// RTL8710B: the FreeRTOS tick is 1/1024 s, so millis(), micros() and delay() use the 32.768 kHz system timer instead
// and delayMicroseconds() the DWT cycle counter. Linked with -Wl,--wrap (RTL8710B_TIME_WRAPS in __init__.py).
#ifdef USE_LIBRETINY_VARIANT_RTL8710B
#include <stdint.h>
#include <FreeRTOS.h>
#include <task.h>
extern uint32_t SystemCoreClock;
__attribute__((long_call)) uint32_t SYSTIMER_TickGet(void); // mask ROM, rtl8710b_delay.h
#define DEMCR (*(volatile uint32_t *) 0xE000EDFC)
#define DEMCR_TRCENA (1UL << 24)
#define DWT_CTRL (*(volatile uint32_t *) 0xE0001000)
#define DWT_CYCCNT (*(volatile uint32_t *) 0xE0001004)
// Interrupt handlers call these, so they live in RAM like IRAM_ATTR (hal.h)
#define RTL8710B_RAM_TEXT __attribute__((noinline, section(".sram.text")))
// Extends the 32-bit timer, which wraps every 36.4 hours; the main loop calls millis() far more often
static inline __attribute__((always_inline)) uint64_t timer_ticks(void) {
static uint64_t ticks;
uint32_t primask;
__asm volatile("mrs %0, primask\n cpsid i" : "=r"(primask)::"memory");
ticks += (uint32_t) (SYSTIMER_TickGet() - (uint32_t) ticks);
const uint64_t now = ticks;
__asm volatile("msr primask, %0" ::"r"(primask) : "memory");
return now;
}
RTL8710B_RAM_TEXT unsigned long __wrap_micros(void) { // NOLINT(readability-identifier-naming)
// 1000000 / 32768 = 15625 / 512
return (uint32_t) ((timer_ticks() * 15625) >> 9);
}
RTL8710B_RAM_TEXT unsigned long __wrap_millis(void) { // NOLINT(readability-identifier-naming)
// 1000 / 32768 = 125 / 4096
return (uint32_t) ((timer_ticks() * 125) >> 12);
}
void __wrap_delay(uint32_t ms) { // NOLINT(readability-identifier-naming)
if (ms == 0) {
vTaskDelay(0);
return;
}
// vTaskDelay() counts the partial tick, so sleep to a deadline; +1 covers the elapsed part of the current count
const uint64_t deadline = timer_ticks() + ((uint64_t) ms * 32768 + 999) / 1000 + 1;
// Sleeps are capped at 1024 s so a delay longer than the 36.4 hour timer wrap still sees every wrap
for (uint64_t now = timer_ticks(); now < deadline; now = timer_ticks()) {
const uint64_t ticks = (deadline - now + 31) / 32;
vTaskDelay((TickType_t) (ticks < 0x100000 ? ticks : 0x100000));
}
}
RTL8710B_RAM_TEXT void __wrap_delayMicroseconds(unsigned int us) { // NOLINT(readability-identifier-naming)
DEMCR |= DEMCR_TRCENA;
DWT_CTRL |= 1;
uint32_t start = DWT_CYCCNT;
// Rounded up: the BW12 runs at 62.5 MHz
uint64_t cycles = (uint64_t) us * ((SystemCoreClock + 999999) / 1000000);
// Steps of at most 2^31 cycles keep the 32-bit difference from wrapping
while (cycles > 0) {
const uint32_t step = cycles > 0x80000000UL ? 0x80000000UL : (uint32_t) cycles;
while (DWT_CYCCNT - start < step) {
}
start += step;
cycles -= step;
}
}
#endif // USE_LIBRETINY_VARIANT_RTL8710B
+2
View File
@@ -88,6 +88,7 @@ from .types import ( # noqa: F401
LightStateTrigger,
LightTurnOffTrigger,
LightTurnOnTrigger,
PowerEstimation,
light_ns,
)
@@ -702,6 +703,7 @@ async def setup_light_core_(light_var, config, output_var):
cg.add_define("USE_LIGHT_POWER_ESTIMATION")
cg.add(
output_var.set_power_estimation(
cg.static_buffer(config[CONF_OUTPUT_ID], PowerEstimation, 1),
power_estimation[CONF_MA_PER_LED_RED],
power_estimation[CONF_MA_PER_LED_GREEN],
power_estimation[CONF_MA_PER_LED_BLUE],
+9 -10
View File
@@ -34,7 +34,7 @@ class AddressableLightState final : public LightState {
};
#ifdef USE_LIGHT_POWER_ESTIMATION
// Allocated only for a strip with power_estimation configured
// Static storage from codegen, only for a strip with power_estimation configured
struct PowerEstimation {
float ma_per_level[4];
float idle_ma_per_led;
@@ -87,15 +87,14 @@ class AddressableLight : public LightOutput, public Component {
}
#ifdef USE_LIGHT_POWER_ESTIMATION
// Per-channel draw at full level and idle draw per LED
void set_power_estimation(float ma_red, float ma_green, float ma_blue, float ma_white, float idle_ma_per_led) {
if (this->power_estimation_ == nullptr)
this->power_estimation_ = new PowerEstimation(); // NOLINT(cppcoreguidelines-owning-memory)
auto *power = this->power_estimation_;
power->ma_per_level[0] = ma_red / 255.0f;
power->ma_per_level[1] = ma_green / 255.0f;
power->ma_per_level[2] = ma_blue / 255.0f;
power->ma_per_level[3] = ma_white / 255.0f;
power->idle_ma_per_led = idle_ma_per_led;
void set_power_estimation(PowerEstimation *storage, float ma_red, float ma_green, float ma_blue, float ma_white,
float idle_ma_per_led) {
this->power_estimation_ = storage;
storage->ma_per_level[0] = ma_red / 255.0f;
storage->ma_per_level[1] = ma_green / 255.0f;
storage->ma_per_level[2] = ma_blue / 255.0f;
storage->ma_per_level[3] = ma_white / 255.0f;
storage->idle_ma_per_led = idle_ma_per_led;
}
// Called after set_power_estimation()
void set_max_current_ma(float max_current_ma) { this->power_estimation_->max_current_ma = max_current_ma; }
+1
View File
@@ -18,6 +18,7 @@ LightStateRTCState = light_ns.struct("LightStateRTCState")
# Addressable strips
ChannelColors = light_ns.struct("ChannelColors")
PowerEstimation = light_ns.struct("PowerEstimation")
# Color modes
ColorMode = light_ns.enum("ColorMode", is_class=True)
+18
View File
@@ -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
+17 -1
View File
@@ -12,7 +12,12 @@ from esphome.components.const import (
CONF_DRAW_ROUNDING,
)
from esphome.components.display import CONF_SHOW_TEST_CARD
from esphome.components.esp32 import VARIANT_ESP32P4, only_on_variant
from esphome.components.esp32 import (
CONF_EXECUTE_FROM_PSRAM,
VARIANT_ESP32P4,
add_idf_sdkconfig_option,
only_on_variant,
)
from esphome.components.mipi import (
COLOR_ORDERS,
CONF_COLOR_DEPTH,
@@ -38,10 +43,12 @@ from esphome.components.mipi import (
)
import esphome.config_validation as cv
from esphome.const import (
CONF_ADVANCED,
CONF_AUTO_CLEAR_ENABLED,
CONF_COLOR_ORDER,
CONF_DIMENSIONS,
CONF_ENABLE_PIN,
CONF_FRAMEWORK,
CONF_ID,
CONF_INIT_SEQUENCE,
CONF_INVERT_COLORS,
@@ -50,7 +57,9 @@ from esphome.const import (
CONF_ROTATION,
CONF_TRANSFORM,
CONF_WIDTH,
KEY_ESP32,
)
from esphome.core import CORE
from esphome.final_validate import full_config
from esphome.types import ConfigType
@@ -187,6 +196,13 @@ FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config: ConfigType) -> None:
# While flash is written (NVS, OTA) the cache is off; a DSI interrupt that waits for it makes the
# panel miss a frame, seen as a white flash. Code run from PSRAM does not wait for the flash.
if not CORE.config[KEY_ESP32][CONF_FRAMEWORK][CONF_ADVANCED][
CONF_EXECUTE_FROM_PSRAM
]:
add_idf_sdkconfig_option("CONFIG_LCD_DSI_ISR_CACHE_SAFE", True)
model = MODELS[config[CONF_MODEL].upper()]
color_depth = COLOR_DEPTHS[get_color_depth(config)]
pixel_mode = int(config[CONF_PIXEL_MODE].removesuffix("bit"))
+9 -1
View File
@@ -15,7 +15,15 @@ static constexpr size_t MIPI_DSI_MAX_CMD_LOG_BYTES = 64;
// Highest AXI QoS priority (4 bits); all masters start at 0
static constexpr uint32_t DSI_DMA_READ_PRIORITY = 15;
static bool notify_refresh_ready(esp_lcd_panel_handle_t panel, esp_lcd_dpi_panel_event_data_t *edata, void *user_ctx) {
// With CONFIG_LCD_DSI_ISR_CACHE_SAFE the DPI driver only accepts callbacks in IRAM
#if CONFIG_LCD_DSI_ISR_CACHE_SAFE
#define MIPI_DSI_ISR_ATTR IRAM_ATTR
#else
#define MIPI_DSI_ISR_ATTR
#endif
static bool MIPI_DSI_ISR_ATTR notify_refresh_ready(esp_lcd_panel_handle_t panel, esp_lcd_dpi_panel_event_data_t *edata,
void *user_ctx) {
SemaphoreHandle_t sem = static_cast<SemaphoreHandle_t>(user_ctx);
BaseType_t need_yield = pdFALSE;
xSemaphoreGiveFromISR(sem, &need_yield);
+4 -4
View File
@@ -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)
+32 -23
View File
@@ -56,7 +56,8 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
@@ -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
+2 -2
View File
@@ -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:
@@ -1,4 +1,5 @@
#include "remote_transmitter.h"
#include <optional>
#include "esphome/core/log.h"
#include "esphome/core/application.h"
@@ -8,6 +9,15 @@
namespace esphome::remote_transmitter {
ESPHOME_LOG_TAG(TAG, "remote_transmitter");
// Holding interrupts off about 1 ms makes the ESP8266 Wi-Fi SDK hang until a watchdog resets the chip, so a frame
// is not locked whole there: interrupts are on until EDGE_LOCK_US before each edge. Elsewhere micros() can jump
// when interrupts come back on, so the whole frame stays locked.
#ifdef USE_ESP8266
static constexpr bool LOCK_PER_EDGE = true;
#else
static constexpr bool LOCK_PER_EDGE = false;
#endif
static constexpr int32_t EDGE_LOCK_US = 50;
void RemoteTransmitterComponent::setup() {
this->pin_->setup();
@@ -35,44 +45,62 @@ void RemoteTransmitterComponent::calculate_on_off_time_(uint32_t carrier_frequen
*off_time_period = period - *on_time_period;
}
void RemoteTransmitterComponent::await_target_time_() {
void RemoteTransmitterComponent::await_target_time_(int32_t lead_us) {
const uint32_t current_time = micros();
if (this->target_time_ == 0) {
this->target_time_ = current_time;
} else if ((int32_t) (this->target_time_ - current_time) > 0) {
// busy loop is required as interrupts are disabled and delayMicroseconds()
} else if ((int32_t) (this->target_time_ - current_time) > lead_us) {
// busy loop, as interrupts can be disabled here and delayMicroseconds()
// may not work correctly in interrupt-disabled contexts on all platforms
while ((int32_t) (this->target_time_ - micros()) > 0)
while ((int32_t) (this->target_time_ - micros()) > lead_us)
;
}
}
void RemoteTransmitterComponent::mark_(uint32_t on_time, uint32_t off_time, uint32_t usec) {
void RemoteTransmitterComponent::write_at_target_(bool value) {
std::optional<InterruptLock> edge_lock;
if (LOCK_PER_EDGE) {
// The first edge anchors the frame, so it takes the time under the lock, right before the write
if (this->target_time_ != 0)
this->await_target_time_(EDGE_LOCK_US);
edge_lock.emplace();
}
this->await_target_time_();
this->pin_->digital_write(true);
this->pin_->digital_write(value);
}
void RemoteTransmitterComponent::mark_(uint32_t on_time, uint32_t off_time, uint32_t usec) {
this->write_at_target_(true);
const uint32_t target = this->target_time_ + usec;
if (this->carrier_duty_percent_ < 100 && (on_time > 0 || off_time > 0)) {
while (true) { // Modulate with carrier frequency
// When an interrupt made the falling edge late by a whole period or more, skip the periods it used up
// instead of catching up with runt pulses. Computed once from one timestamp; lateness under a period
// (call overhead at a fast carrier) and an on time that rounds to 0 are left alone. With a frame lock no
// interrupt can delay an edge, so the check is compiled out there.
if (LOCK_PER_EDGE && on_time > 0) {
const uint32_t period = on_time + off_time;
const uint32_t late = micros() - (this->target_time_ + on_time);
if ((int32_t) late >= (int32_t) period)
this->target_time_ += (late / period + 1) * period;
}
this->target_time_ += on_time;
if ((int32_t) (this->target_time_ - target) >= 0)
break;
this->await_target_time_();
this->pin_->digital_write(false);
this->write_at_target_(false);
this->target_time_ += off_time;
if ((int32_t) (this->target_time_ - target) >= 0)
break;
this->await_target_time_();
this->pin_->digital_write(true);
this->write_at_target_(true);
}
}
this->target_time_ = target;
}
void RemoteTransmitterComponent::space_(uint32_t usec) {
this->await_target_time_();
this->pin_->digital_write(false);
this->write_at_target_(false);
this->target_time_ += usec;
}
@@ -85,10 +113,13 @@ void RemoteTransmitterComponent::send_internal(uint32_t send_times, uint32_t sen
this->transmit_trigger_.trigger();
for (uint32_t i = 0; i < send_times; i++) {
{
InterruptLock lock;
// Re-anchor every iteration: timing must never span a lock boundary, as micros() can
std::optional<InterruptLock> frame_lock;
if (!LOCK_PER_EDGE)
frame_lock.emplace();
// Re-anchor every iteration: outside ESP8266 timing must never span a lock boundary, as micros() can
// jump when interrupts are re-enabled between repeats (e.g. LibreTiny's Beken micros()
// discards its interrupt-lock correction, stretching the repeat gap by the lock duration)
// discards its interrupt-lock correction, stretching the repeat gap by the lock duration).
// ESP8266 micros() does not jump, so there the lock is taken per edge in write_at_target_().
this->target_time_ = 0;
for (int32_t item : this->temp_.get_data()) {
if (item > 0) {
@@ -100,8 +131,7 @@ void RemoteTransmitterComponent::send_internal(uint32_t send_times, uint32_t sen
}
App.feed_wdt();
}
this->await_target_time_(); // wait for duration of last pulse
this->pin_->digital_write(false);
this->write_at_target_(false); // wait for duration of last pulse
}
if (i + 1 < send_times) {
@@ -95,7 +95,7 @@ class RemoteTransmitterComponent final : public remote_base::RemoteTransmitterBa
#if defined(USE_ESP8266) || \
(defined(USE_LIBRETINY) && !defined(USE_LIBRETINY_VARIANT_RTL8720C) && !defined(REMOTE_TRANSMITTER_BK_PWM)) || \
defined(USE_RP2) || (defined(USE_ESP32) && !SOC_RMT_SUPPORTED)
void await_target_time_();
void await_target_time_(int32_t lead_us = 0);
uint32_t target_time_{0};
#endif
#if defined(USE_ESP8266) || \
@@ -106,6 +106,7 @@ class RemoteTransmitterComponent final : public remote_base::RemoteTransmitterBa
void mark_(uint32_t on_time, uint32_t off_time, uint32_t usec);
void space_(uint32_t usec);
void write_at_target_(bool value);
#endif
#ifdef USE_RTL87XX
// Carrier frequency the PWM is currently configured for; 0 = not yet configured
@@ -133,12 +133,12 @@ void IRAM_ATTR RemoteTransmitterComponent::stop_envelope_timer_() { gtimer_stop(
#else // !USE_LIBRETINY_VARIANT_RTL8720C -- AmebaZ (RTL8710B): spin-based envelope, per-frame priority boost
void RemoteTransmitterComponent::await_target_time_() {
void RemoteTransmitterComponent::await_target_time_(int32_t lead_us) {
const uint32_t current_time = micros();
if (this->target_time_ == 0) {
this->target_time_ = current_time;
} else {
while ((int32_t) (this->target_time_ - micros()) > 0) {
while ((int32_t) (this->target_time_ - micros()) > lead_us) {
}
}
}
@@ -3,7 +3,6 @@ from esphome.components import sensor
import esphome.config_validation as cv
from esphome.const import (
DEVICE_CLASS_DISTANCE,
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_SPEED,
STATE_CLASS_MEASUREMENT,
UNIT_METER,
@@ -40,11 +39,9 @@ CONFIG_SCHEMA = cv.Schema(
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_CUSTOM_SPATIAL_STATIC_VALUE): sensor.sensor_schema(
device_class=DEVICE_CLASS_ENERGY,
icon="mdi:counter",
),
cv.Optional(CONF_CUSTOM_SPATIAL_MOTION_VALUE): sensor.sensor_schema(
device_class=DEVICE_CLASS_ENERGY,
icon="mdi:counter",
),
cv.Optional(CONF_CUSTOM_MOTION_SPEED): sensor.sensor_schema(
+11 -10
View File
@@ -36,7 +36,6 @@ from esphome.const import (
CONF_WIDTH,
)
from esphome.core import CORE
from esphome.cpp_generator import MockObj
import esphome.final_validate as fv
from esphome.types import ConfigType
@@ -601,25 +600,27 @@ async def to_code(config: ConfigType) -> None:
if data.player_support:
cg.add_define("USE_SENDSPIN_PLAYER", True)
# Configures the player role. Each configured codec is advertised for 16 bits per sample
# mono and stereo at the configured sample rate. The order is a preference order, both for
# the codecs themselves and for stereo over mono.
# Configures the player role. Each configured codec is advertised for mono and stereo at the
# configured sample rate and bits per sample, except Opus, which sendspin-cpp only decodes to
# 16 bits per sample. The order is a preference order, both for the codecs themselves and for
# stereo over mono.
player_cfg = data.player_config
sample_rate = player_cfg[CONF_SAMPLE_RATE]
bits_per_sample = player_cfg[CONF_BITS_PER_SAMPLE]
codecs = [CODECS[codec] for codec in player_cfg[CONF_CODECS]]
def _audio_format(codec: MockObj, channels: int) -> cg.StructInitializer:
def _audio_format(codec: str, channels: int) -> cg.StructInitializer:
return cg.StructInitializer(
AudioSupportedFormatObject,
("codec", codec),
("codec", CODECS[codec]),
("channels", channels),
("sample_rate", sample_rate),
("bit_depth", 16),
("bit_depth", 16 if codec == CODEC_OPUS else bits_per_sample),
)
audio_format_structs = [
_audio_format(codec, channels) for codec in codecs for channels in (2, 1)
_audio_format(codec, channels)
for codec in player_cfg[CONF_CODECS]
for channels in (2, 1)
]
psram_stack = player_cfg.get(CONF_TASK_STACK_IN_PSRAM, False)
@@ -3,6 +3,7 @@ import esphome.codegen as cg
from esphome.components import media_source, psram
import esphome.config_validation as cv
from esphome.const import (
CONF_BITS_PER_SAMPLE,
CONF_BUFFER_SIZE,
CONF_ID,
CONF_SAMPLE_RATE,
@@ -74,6 +75,7 @@ def _register(config: ConfigType) -> ConfigType:
{
CONF_CODECS: config[CONF_CODECS],
CONF_SAMPLE_RATE: config[CONF_SAMPLE_RATE],
CONF_BITS_PER_SAMPLE: config[CONF_BITS_PER_SAMPLE],
CONF_BUFFER_SIZE: config[CONF_BUFFER_SIZE],
CONF_INITIAL_STATIC_DELAY: config[CONF_INITIAL_STATIC_DELAY],
CONF_FIXED_DELAY: config[CONF_FIXED_DELAY],
@@ -104,6 +106,7 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_SAMPLE_RATE, default=48000): cv.int_range(
min=16000, max=96000
),
cv.Optional(CONF_BITS_PER_SAMPLE, default=16): cv.one_of(16, 24, int=True),
cv.Optional(CONF_DECODE_MEMORY): cv.one_of(*MEMORY_LOCATIONS, lower=True),
cv.Optional(CONF_CODECS): cv.All(
cv.ensure_list(cv.enum(CODECS, lower=True)), cv.Length(min=1)
@@ -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));
-1
View File
@@ -112,7 +112,6 @@ CONFIG_SCHEMA = (
cv.Optional(CONF_ACTUAL_GAIN): sensor.sensor_schema(
icon=ICON_BRIGHTNESS_6,
accuracy_decimals=0,
device_class=DEVICE_CLASS_ILLUMINANCE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(
@@ -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
@@ -1,6 +1,7 @@
#ifdef USE_ESP8266
#include "uart_component_esp8266.h"
#include <esp8266_peri.h>
#include <optional>
#include "esphome/core/application.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
@@ -18,9 +19,18 @@ 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; }
bool ESP8266UartComponent::serial0_in_use = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
@@ -177,6 +187,13 @@ 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_TX_BIT_LOCK_MAX_BAUD &&
this->sw_serial_->locks_whole_frame()) {
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);
}
}
this->check_logger_conflict();
}
@@ -261,10 +278,19 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
// load_settings() re-enters here
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->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)
this->gpio_rx_pin_ = nullptr;
this->bit_time_ = F_CPU / baud_rate;
this->stop_bits_ = stop_bits;
this->data_bits_ = data_bits;
this->parity_ = parity;
const bool edge_mode = baud_rate <= SW_SERIAL_EDGE_MODE_MAX_BAUD;
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_)
@@ -286,10 +312,11 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
this->rx_.setup((RX_TICKS_PER_SECOND + baud_rate / 2) / baud_rate, data_bits, parity != UART_CONFIG_PARITY_NONE,
stop_bits, buffer, rx_buffer_size);
this->rx_.reset(rx_now(), this->rx_pin_.digital_read());
if (baud_rate <= SW_SERIAL_EDGE_MODE_MAX_BAUD) {
if (edge_mode) {
gpio_rx_pin_->attach_interrupt(ESP8266SoftwareSerial::gpio_intr_edge, this, gpio::INTERRUPT_ANY_EDGE);
} else {
gpio_rx_pin_->attach_interrupt(ESP8266SoftwareSerial::gpio_intr, this, gpio::INTERRUPT_FALLING_EDGE);
blocking_rx_count++;
}
}
}
@@ -369,27 +396,44 @@ void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
need_parity_bit = false;
}
{
// Transmit runs from the main loop and never overlaps a CpuFrequencyBoost
InterruptLock lock;
const uint32_t bit_time = this->bit_time_;
uint32_t wait = bit_time;
const uint32_t start = arch_get_cpu_cycle_count();
// Start bit
this->write_bit_(false, &wait, start, 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;
}
if (need_parity_bit)
this->write_bit_(parity_bit, &wait, start, bit_time);
// Stop bit
this->write_bit_(true, &wait, start, bit_time);
if (this->stop_bits_ == 2)
this->wait_(&wait, start, bit_time);
// 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();
uint32_t start;
{
InterruptLock lock;
// Start bit
this->tx_pin_.digital_write(false);
start = arch_get_cpu_cycle_count();
}
uint32_t wait = bit_time;
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
}
this->write_bit_(true, &wait, start, bit_time);
// 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) {
while (arch_get_cpu_cycle_count() - start < *wait)
@@ -400,9 +444,14 @@ bool IRAM_ATTR ESP8266SoftwareSerial::read_bit_(uint32_t *wait, const uint32_t &
this->wait_(wait, start, bit_time);
return this->rx_pin_.digital_read();
}
// Locks only from MAX_TX_LOCK_CYCLES before the edge to the edge, so a pending interrupt runs right after it; a bit
// longer than that (below about 5000 baud) spins with interrupts on first. Nests inside a frame lock.
void IRAM_ATTR ESP8266SoftwareSerial::write_bit_(bool bit, uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
this->tx_pin_.digital_write(bit);
while (arch_get_cpu_cycle_count() - start + MAX_TX_LOCK_CYCLES < *wait)
;
InterruptLock lock;
this->wait_(wait, start, bit_time);
this->tx_pin_.digital_write(bit);
}
uint8_t ESP8266SoftwareSerial::read_byte() {
this->rx_sync_();
@@ -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,6 +27,10 @@ class ESP8266SoftwareSerial {
size_t available();
/// 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:
/// Above SW_SERIAL_EDGE_MODE_MAX_BAUD; reads the whole byte in the ISR.
static void gpio_intr(ESP8266SoftwareSerial *arg);
@@ -51,6 +56,9 @@ class ESP8266SoftwareSerial {
UARTParityOptions parity_;
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)
};
class ESP8266UartComponent final : public UARTComponent, public Component {
+2 -1
View File
@@ -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)
+24 -6
View File
@@ -1,6 +1,7 @@
#include "vl53l0x_sensor.h"
#include "esphome/core/log.h"
#include <algorithm>
#include <cinttypes>
/*
@@ -268,8 +269,16 @@ void VL53L0XSensor::update() {
this->status_momentary_warning(5000);
ESP_LOGW(TAG, "%s - update called before prior reading complete - initiated:%d waiting_for_interrupt:%d",
LOG_STR_ARG(this->get_log_name()), this->initiated_read_, this->waiting_for_interrupt_);
return;
// A measurement gets its timing budget plus one more interval; one still pending after that is stalled
const uint32_t interval_ms = std::max<uint32_t>(this->get_update_interval(), 1);
const uint32_t grace = std::min<uint32_t>(this->measurement_timing_budget_us_ / 1000 / interval_ms + 1, UINT8_MAX);
if (this->pending_updates_ < grace) {
this->pending_updates_++;
return;
}
reg(0x0B) = 0x01;
}
this->pending_updates_ = 0;
// initiate single shot measurement
reg(0x80) = 0x01;
@@ -288,10 +297,12 @@ void VL53L0XSensor::update() {
}
void VL53L0XSensor::loop() {
// A failed read must not advance the state: it reads as 0, which looks like a finished measurement
uint8_t value;
if (this->initiated_read_) {
if (reg(0x00).get() & 0x01) {
// waiting
} else {
if (!this->read_byte(0x00, &value))
return;
if (!(value & 0x01)) {
// done
// wait until reg(0x13) & 0x07 is set
this->initiated_read_ = false;
@@ -299,11 +310,18 @@ void VL53L0XSensor::loop() {
}
}
if (this->waiting_for_interrupt_) {
if (reg(0x13).get() & 0x07) {
if (!this->read_byte(0x13, &value))
return;
if (value & 0x07) {
uint16_t range_mm = 0;
this->read_byte_16(0x14 + 10, &range_mm);
const bool ok = this->read_byte_16(0x14 + 10, &range_mm);
reg(0x0B) = 0x01;
this->waiting_for_interrupt_ = false;
if (!ok) {
this->publish_state(NAN);
this->status_momentary_warning(5000);
return;
}
if (range_mm >= 8190) {
ESP_LOGD(TAG, "'%s' - Distance is out of range, please move the target closer",
+3 -1
View File
@@ -61,7 +61,9 @@ class VL53L0XSensor final : public sensor::Sensor, public PollingComponent, publ
uint32_t measurement_timing_budget_us_{0};
bool initiated_read_{false};
bool waiting_for_interrupt_{false};
uint8_t stop_variable_;
uint8_t stop_variable_{0};
// Updates that found the measurement still pending; past the grace period the next one restarts it
uint8_t pending_updates_{0};
uint32_t timeout_us_{};
+36 -1
View File
@@ -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;
+31 -21
View File
@@ -5,47 +5,57 @@
namespace esphome::wifi {
// Switching APs calls esp_wifi_disconnect(), which queues an association-leave event from the old AP. Remembers
// that AP so its leave event does not end the connection attempt started after it. Platform free for host tests.
/// Which expected leave a disconnect matched.
enum class ExpectedLeave : uint8_t {
EXPECTED_LEAVE_NONE,
EXPECTED_LEAVE_AP,
EXPECTED_LEAVE_ATTEMPT, ///< An attempt that never associated, so no BSSID
};
// Switching APs calls esp_wifi_disconnect(), which queues a leave event for the old AP, or with no BSSID for an
// attempt that never associated. Remembers it so that event does not end the next attempt. Platform free for tests.
class ExpectedDisconnect {
public:
void arm(const uint8_t *bssid) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->armed_ = true;
}
void clear() { this->armed_ = false; }
void arm(const uint8_t *bssid) { this->arm_(bssid, ExpectedLeave::EXPECTED_LEAVE_AP); }
void clear() { this->expected_ = ExpectedLeave::EXPECTED_LEAVE_NONE; }
/// Disconnects from the current AP and, once that succeeds, expects its leave event. read_bssid(uint8_t *out)
/// returns whether there was an AP and runs first, since the record is gone after the disconnect; disconnect()
/// returns whether it succeeded, which is also the result. Any earlier expectation is dropped.
/// Disconnects and, once that succeeds, expects the leave event. read_bssid(uint8_t *out) runs first, since the
/// record is gone after the disconnect, and writes the AP's BSSID only when it returns true; without an AP the
/// attempt's leave, with no BSSID, is expected. disconnect() returns whether it succeeded, which is the result.
template<typename ReadBssid, typename Disconnect>
bool disconnect_and_expect_leave(ReadBssid &&read_bssid, Disconnect &&disconnect) {
this->armed_ = false;
this->clear();
std::array<uint8_t, 6> bssid{};
const bool had_ap = read_bssid(bssid.data());
if (!disconnect())
return false;
if (had_ap)
this->arm(bssid.data());
this->arm_(bssid.data(), had_ap ? ExpectedLeave::EXPECTED_LEAVE_AP : ExpectedLeave::EXPECTED_LEAVE_ATTEMPT);
return true;
}
/// A connected event still queued from the previous AP; it keeps the expectation.
bool is_previous_ap(const uint8_t *bssid) const {
return this->armed_ && std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
return this->expected_ != ExpectedLeave::EXPECTED_LEAVE_NONE &&
std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
}
/// Whether a disconnect is the previous AP's leave. Every disconnect ends the expectation, so it matches at
/// most once; the caller handles roaming disconnects before this.
bool consume_disconnect(const uint8_t *bssid, bool assoc_leave) {
const bool expected = assoc_leave && this->is_previous_ap(bssid);
this->armed_ = false;
return expected;
/// Which expected leave a disconnect is. \p is_leave covers an AP's association leave (8) and the station leave
/// of an attempt that never associated (36). Every disconnect ends the expectation, so it matches at most once.
ExpectedLeave consume_disconnect(const uint8_t *bssid, bool is_leave) {
const ExpectedLeave matched =
is_leave && this->is_previous_ap(bssid) ? this->expected_ : ExpectedLeave::EXPECTED_LEAVE_NONE;
this->clear();
return matched;
}
protected:
void arm_(const uint8_t *bssid, ExpectedLeave expected) {
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
this->expected_ = expected;
}
std::array<uint8_t, 6> bssid_{};
bool armed_{false};
ExpectedLeave expected_{ExpectedLeave::EXPECTED_LEAVE_NONE};
};
} // namespace esphome::wifi
+18 -12
View File
@@ -707,6 +707,15 @@ void WiFiComponent::setup() {
}
}
void WiFiComponent::apply_radio_settings_() {
if (!std::isnan(this->output_power_) && !this->wifi_apply_output_power_(this->output_power_)) {
ESP_LOGV(TAG, "Setting Output Power Option failed");
}
if (!this->wifi_apply_power_save_()) {
ESP_LOGV(TAG, "Setting Power Save Option failed");
}
}
void WiFiComponent::start() {
ESP_LOGCONFIG(TAG, "Starting");
// The loop's time, not millis(): a wifi.enable from a trigger in this pass must not stamp a time after now
@@ -750,10 +759,6 @@ void WiFiComponent::start() {
if (this->has_sta()) {
this->wifi_sta_pre_setup_();
if (!std::isnan(this->output_power_) && !this->wifi_apply_output_power_(this->output_power_)) {
ESP_LOGV(TAG, "Setting Output Power Option failed");
}
#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
// Synchronize power_save_ with semaphore state before applying
if (this->high_performance_semaphore_ != nullptr) {
@@ -767,9 +772,7 @@ void WiFiComponent::start() {
}
}
#endif
if (!this->wifi_apply_power_save_()) {
ESP_LOGV(TAG, "Setting Power Save Option failed");
}
this->apply_radio_settings_();
this->transition_to_phase_(WiFiRetryPhase::INITIAL_CONNECT);
#ifdef USE_WIFI_FAST_CONNECT
@@ -1119,11 +1122,10 @@ void WiFiComponent::setup_ap_config_() {
// Reset before the AP exists: afterwards only the platform's event path writes the counter
this->ap_clients_ = 0;
this->ap_setup_ = this->wifi_start_ap_(this->ap_);
// The station path applied it in start(); without a station the radio only exists from here
if (this->ap_setup_ && !this->has_sta() && !std::isnan(this->output_power_) &&
!this->wifi_apply_output_power_(this->output_power_)) {
ESP_LOGV(TAG, "Setting Output Power Option failed");
}
// The station path applied these in start(); without a station the radio only exists from here,
// and credentials saved through the portal connect without another start()
if (this->ap_setup_ && !this->has_sta())
this->apply_radio_settings_();
#if defined(USE_WIFI_AP_EXCLUSIVE) || defined(USE_WIFI_AP_PERSISTENT)
// A failed start must not leave the radio in AP mode: on an exclusive radio it would refuse
// the STA attempts until the next try, and an AP that stays up would take clients it cannot serve.
@@ -2172,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_()
+3 -1
View File
@@ -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();
@@ -847,6 +847,8 @@ class WiFiComponent final : public Component {
bool wifi_sta_pre_setup_();
bool wifi_apply_output_power_(float output_power);
bool wifi_apply_power_save_();
/// Output power and power save, wherever the radio first comes up: start() with networks, the AP without.
void apply_radio_settings_();
#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
bool wifi_apply_band_mode_();
#endif
@@ -41,12 +41,14 @@
#include "lwip/apps/sntp.h"
#include "lwip/dns.h"
#include "lwip/err.h"
#ifdef USE_WIFI_LEASE_CACHE
#if USE_NETWORK_IPV6 || defined(USE_WIFI_LEASE_CACHE)
#include <esp_netif_net_stack.h> // esp_netif_get_netif_impl()
#include <esp_rtc_time.h> // esp_rtc_get_time_us() -- RTC-domain clock for lease age
#include "lwip/dhcp.h"
#include "lwip/netif.h"
#endif
#ifdef USE_WIFI_LEASE_CACHE
#include <esp_rtc_time.h> // esp_rtc_get_time_us() -- RTC-domain clock for lease age
#include "lwip/dhcp.h"
#endif
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
@@ -1098,8 +1100,23 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
s_sta_connected = true;
#if USE_NETWORK_IPV6
// Start SLAAC on association, not after a DHCPv4 lease that may never arrive.
if (esp_err_t ll_err = esp_netif_create_ip6_linklocal(s_sta_netif); ll_err != ESP_OK) {
ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed: %s", esp_err_to_name(ll_err));
// Not esp_netif_create_ip6_linklocal(): it returns ESP_FAIL while the netif is down, and this queued event
// can be handled before esp-netif's own STA_CONNECTED handler brings the netif up. lwIP accepts the
// address on a down netif and starts DAD and router solicitation once it comes up.
if (auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(s_sta_netif)); netif != nullptr) {
if (esp_err_t err = esp_netif_tcpip_exec(
[](void *ctx) -> esp_err_t {
netif_create_ip6_linklocal_address(static_cast<struct netif *>(ctx), 1);
return ESP_OK;
},
netif);
err != ESP_OK) {
ESP_LOGW(TAG, "IPv6 link-local not created: %s", esp_err_to_name(err));
} else {
ESP_LOGD(TAG, "IPv6 link-local address created");
}
} else {
ESP_LOGW(TAG, "No lwIP netif, IPv6 link-local not created");
}
#endif /* USE_NETWORK_IPV6 */
if (this->state_ == WIFI_COMPONENT_STATE_STA_CONNECTED) {
@@ -1141,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);
@@ -1164,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)
@@ -1618,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() {
+6 -1
View File
@@ -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
+15 -8
View File
@@ -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
+58 -1
View File
@@ -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{};
+9 -1
View File
@@ -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(); }
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff. Show more