mirror of
https://github.com/esphome/esphome.git
synced 2026-11-17 18:46:08 +00:00
Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84079c07e2 | ||
|
|
b7dbf17469 | ||
|
|
b91750c325 | ||
|
|
92d2a457fa | ||
|
|
a1fecebb09 | ||
|
|
32b9d4cbe7 | ||
|
|
c53401a28d | ||
|
|
6b7d17c762 | ||
|
|
93a3306d82 | ||
|
|
54d3477240 | ||
|
|
5f9d83d293 | ||
|
|
43864283b4 | ||
|
|
4efbb38b86 | ||
|
|
045374965f | ||
|
|
39a939720f | ||
|
|
a79e51e784 | ||
|
|
517f0d6d48 | ||
|
|
1327d0ddc5 | ||
|
|
2adb544e7a | ||
|
|
48905beb96 | ||
|
|
ed401814bf | ||
|
|
0245db6285 | ||
|
|
07ee0f9f04 | ||
|
|
3d34ad572b | ||
|
|
b03870b551 | ||
|
|
4a965b8b32 | ||
|
|
d826a19eb1 | ||
|
|
fb54ec51c1 | ||
|
|
04b6c0d4ca | ||
|
|
abf282dd08 | ||
|
|
e097958ad9 | ||
|
|
8a8ad4d8da | ||
|
|
09b82388c9 | ||
|
|
ea5407925a | ||
|
|
97732df3a5 | ||
|
|
04482ae0d4 | ||
|
|
ca0dd8e292 | ||
|
|
e75ac64cc9 | ||
|
|
212c0c1ea4 | ||
|
|
3e2f9bf296 | ||
|
|
b997866e86 | ||
|
|
ae89db98e4 | ||
|
|
e9bb102c1f | ||
|
|
26c4f8d40e | ||
|
|
c097fe388e | ||
|
|
21267d7421 | ||
|
|
582adc950a | ||
|
|
613319f984 | ||
|
|
4ad3cc7c0e | ||
|
|
a033260639 | ||
|
|
24f23ba3db | ||
|
|
674d593f75 | ||
|
|
c1771e002b | ||
|
|
5529e87a40 | ||
|
|
54cae78a42 | ||
|
|
e77a3bc54d | ||
|
|
af7f95a01b | ||
|
|
daf48ce4f2 |
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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.0b5
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ RUN \
|
||||
-r /requirements.txt
|
||||
|
||||
# Install the ESPHome Device Builder dashboard.
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.26.0
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.28.1
|
||||
|
||||
RUN \
|
||||
platformio settings set enable_telemetry No \
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -257,6 +257,47 @@ WIZARD_DOMAIN_LIMITED_PLATFORMS = (
|
||||
)
|
||||
|
||||
|
||||
# The C++ base class of each kind of entity a wizard page can show, and the platform an API client
|
||||
# knows it by. An entity key is only unique within its platform, so the wizard sends both.
|
||||
WIZARD_ENTITY_PLATFORMS: dict[str, str] = {
|
||||
"alarm_control_panel::AlarmControlPanel": "alarm_control_panel",
|
||||
"binary_sensor::BinarySensor": "binary_sensor",
|
||||
"button::Button": "button",
|
||||
"climate::Climate": "climate",
|
||||
"cover::Cover": "cover",
|
||||
"datetime::DateEntity": "date",
|
||||
"datetime::DateTimeEntity": "datetime",
|
||||
"datetime::TimeEntity": "time",
|
||||
"event::Event": "event",
|
||||
"fan::Fan": "fan",
|
||||
"infrared::Infrared": "infrared",
|
||||
"light::LightState": "light",
|
||||
"lock::Lock": "lock",
|
||||
"number::Number": "number",
|
||||
"radio_frequency::RadioFrequency": "radio_frequency",
|
||||
"select::Select": "select",
|
||||
"sensor::Sensor": "sensor",
|
||||
"switch_::Switch": "switch",
|
||||
"text::Text": "text",
|
||||
"text_sensor::TextSensor": "text_sensor",
|
||||
"update::UpdateEntity": "update",
|
||||
"valve::Valve": "valve",
|
||||
"water_heater::WaterHeater": "water_heater",
|
||||
}
|
||||
|
||||
|
||||
def _wizard_entity_platform(
|
||||
config: fv.FinalValidateConfig, entity_id: ID
|
||||
) -> str | None:
|
||||
"""The platform of an entity, from the C++ class it is declared with, as some entities are not
|
||||
declared under their platform (the sensors of gps:, for example)."""
|
||||
declared: ID = config.get_config_for_path(config.get_path_for_id(entity_id))
|
||||
for cls in (declared.type, *declared.type.parents):
|
||||
if (platform := WIZARD_ENTITY_PLATFORMS.get(str(cls))) is not None:
|
||||
return platform
|
||||
return None
|
||||
|
||||
|
||||
def wizard_input_ids(api_config: ConfigType) -> set[str]:
|
||||
"""The IDs of the entities that are linked inputs of the wizard in the given api config."""
|
||||
if (wizard := api_config.get(CONF_WIZARD)) is None:
|
||||
@@ -361,7 +402,8 @@ def _validate_wizard_input(conf: ConfigType) -> ConfigType:
|
||||
|
||||
|
||||
def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
"""Reject entities that are internal, as they are not exposed over the API, or have no name.
|
||||
"""Reject entities that are internal, as they are not exposed over the API, have no name, or
|
||||
are of a platform the wizard does not know.
|
||||
|
||||
The key a client knows an entity by is a hash of its name. Without a name of its own, the
|
||||
device works the name out at runtime from its friendly name, which can add the MAC address,
|
||||
@@ -378,6 +420,10 @@ def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
f"Entity '{value.id}' has no name of its own, so its key is not known "
|
||||
"when the wizard is built. Give it a name to use it in the wizard"
|
||||
)
|
||||
if _wizard_entity_platform(fv.full_config.get(), value) is None:
|
||||
raise cv.Invalid(
|
||||
f"Entity '{value.id}' is not of a platform the wizard can show"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
@@ -446,7 +492,10 @@ def _entity_document(
|
||||
) -> ConfigType:
|
||||
"""An entity of the device that the page shows, keyed as ListEntitiesResponse keys it."""
|
||||
_, declaration = _wizard_input_declaration(config, conf[CONF_ID])
|
||||
document: ConfigType = {"key": fnv1_hash_object_id(declaration[CONF_NAME])}
|
||||
document: ConfigType = {
|
||||
"key": fnv1_hash_object_id(declaration[CONF_NAME]),
|
||||
"platform": _wizard_entity_platform(config, conf[CONF_ID]),
|
||||
}
|
||||
if (device := declaration.get(CONF_DEVICE_ID)) is not None:
|
||||
document["device_id"] = fnv1a_32bit_hash(device.id)
|
||||
if description := conf.get(CONF_DESCRIPTION):
|
||||
@@ -476,7 +525,8 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
|
||||
{"version": 1,
|
||||
"pages": [{"title": "...", "description": "...",
|
||||
"entities": [{"key": 123, "device_id": 456, "description": "...", "role": "..."}],
|
||||
"entities": [{"key": 123, "platform": "sensor", "device_id": 456,
|
||||
"description": "...", "role": "..."}],
|
||||
"inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
"entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
"device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
@@ -487,6 +537,10 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
- An entity key is the key ListEntitiesResponse sends for the entity: the FNV-1 hash of the
|
||||
object id made from its name (entity_helpers). device_id is the hash of the ESPHome id of
|
||||
the device it belongs to (esphome/core/config.py), and is left out for the main device.
|
||||
- An entity platform is the platform of the entity: sensor, switch and so on, or date, time or
|
||||
datetime for an entity of the datetime component. A key is only unique within its platform
|
||||
and device, so a client matches an entity by platform, device_id and key together. A client
|
||||
that does not know platform ignores it, so the version stays 1.
|
||||
- An entity role is a stable name, always <component>.<name>, that the component of the entity
|
||||
gives it with register_entity_role, so Home Assistant can recognise the entity. The user
|
||||
cannot set or change it, and no two entities of a wizard share one. A client that does not
|
||||
|
||||
@@ -35,15 +35,23 @@ async def to_code(config: ConfigType) -> None:
|
||||
add_idf_component(name="esp32async/asynctcp", ref="3.4.91")
|
||||
elif CORE.is_libretiny:
|
||||
# https://github.com/ESP32Async/AsyncTCP
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.4.5")
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.5.0")
|
||||
# AsyncTCP 3.5.0 debug logs call xPortGetCoreID(), which LibreTiny (single core) lacks; they are compiled
|
||||
# in by LibreTiny's debug level or CONFIG_ASYNC_TCP_DEBUG, so the call always expands to int(), which is 0
|
||||
# (a function-like -D does not survive PlatformIO's build flags)
|
||||
cg.add_build_flag("-DxPortGetCoreID=int")
|
||||
elif CORE.is_esp8266:
|
||||
# https://github.com/ESP32Async/ESPAsyncTCP
|
||||
cg.add_library("ESP32Async/ESPAsyncTCP", "2.0.0")
|
||||
elif CORE.is_rp2:
|
||||
# https://github.com/ayushsharma82/RPAsyncTCP
|
||||
# RPAsyncTCP is a drop-in replacement for AsyncTCP_RP2040W with better
|
||||
# ESPAsyncWebServer compatibility
|
||||
cg.add_library("ayushsharma82/RPAsyncTCP", "1.3.2")
|
||||
# https://github.com/esphome-libs/RPAsyncTCP, a fork of ayushsharma82/RPAsyncTCP
|
||||
# 1.3.2 that counts queued bytes before lwIP can send and ACK them, so
|
||||
# canSend() does not stay false and SSE streams do not stall (wired Ethernet)
|
||||
cg.add_library(
|
||||
"RPAsyncTCP",
|
||||
"1.3.2",
|
||||
"https://github.com/esphome-libs/RPAsyncTCP#1.3.2-esphome.1",
|
||||
)
|
||||
# Other platforms (host, etc) use socket-based implementation
|
||||
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -195,14 +195,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
}
|
||||
} else {
|
||||
uint16_t raw_humidity = encode_uint16(data[0], data[1]);
|
||||
uint16_t raw_temperature = encode_uint16(data[2], data[3]);
|
||||
|
||||
if (raw_temperature & 0x8000) {
|
||||
if (!(raw_temperature & 0x4000))
|
||||
raw_temperature = ~(raw_temperature & 0x7FFF);
|
||||
} else if (raw_temperature & 0x800) {
|
||||
raw_temperature |= 0xf000;
|
||||
}
|
||||
const int16_t raw_temperature = decode_dht22_temperature(encode_uint16(data[2], data[3]));
|
||||
|
||||
if (raw_temperature == 1 && raw_humidity == 10) {
|
||||
if (report_errors) {
|
||||
@@ -214,7 +207,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
*humidity = static_cast<float>(raw_humidity) * 0.1f;
|
||||
if (*humidity > 100.0f)
|
||||
*humidity = NAN;
|
||||
*temperature = static_cast<int16_t>(raw_temperature) * 0.1f;
|
||||
*temperature = raw_temperature * 0.1f;
|
||||
}
|
||||
|
||||
if (*temperature == 0.0f && (*humidity == 1.0f || *humidity == 2.0f)) {
|
||||
|
||||
@@ -17,6 +17,18 @@ enum DHTModel : uint8_t {
|
||||
DHT_MODEL_DHT22_TYPE2
|
||||
};
|
||||
|
||||
/// Convert a DHT22-family temperature reading to tenths of a degree. Sensors encode negative values in one of three
|
||||
/// ways: sign and magnitude (bit 15 set, bit 14 clear), 16-bit two's complement, or 12-bit two's complement (bit 11).
|
||||
inline int16_t decode_dht22_temperature(uint16_t raw) {
|
||||
if (raw & 0x8000) {
|
||||
if (!(raw & 0x4000))
|
||||
return static_cast<int16_t>(-static_cast<int16_t>(raw & 0x7FFF));
|
||||
} else if (raw & 0x800) {
|
||||
raw |= 0xF000;
|
||||
}
|
||||
return static_cast<int16_t>(raw);
|
||||
}
|
||||
|
||||
/// Component for reading temperature/humidity measurements from DHT11/DHT22 sensors.
|
||||
class DHT final : public PollingComponent {
|
||||
SUB_SENSOR(temperature)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -567,11 +575,26 @@ async def to_code(config: ConfigType) -> None:
|
||||
and 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 drops bond keys on re-encryption (see bluedroid_bond_keys.c). Needs the
|
||||
# native toolchain for Bluedroid's private headers; Windows response files lose them.
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and not IS_WINDOWS
|
||||
and cv.Version(5, 5, 6) <= idf_version() < cv.Version(6, 0, 0)
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_BOND_KEYS")
|
||||
_wrap_bluedroid_symbols("smp_check_auth_req", "btm_sec_clear_ble_keys")
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_bond_keys.c"))
|
||||
|
||||
# ESP-IDF 5.5.6 and 6.0.3 end GATT discovery on a response listing handles out of order
|
||||
# (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 +662,25 @@ 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 _has_strict_handle_order(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order."""
|
||||
return cv.Version(5, 5, 6) <= version < cv.Version(
|
||||
6, 0, 0
|
||||
) or version >= cv.Version(6, 0, 3)
|
||||
|
||||
|
||||
# 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_order.cpp": "USE_ESP32_BLE_GATTC_HANDLE_ORDER",
|
||||
}
|
||||
)
|
||||
@@ -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_ =
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
// 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 and 6.0.3 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
|
||||
@@ -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};
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -94,7 +94,10 @@ __attribute__((always_inline)) inline void delay(uint32_t ms) { ::delay(ms); }
|
||||
__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
|
||||
@@ -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],
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,15 @@ 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;
|
||||
// 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 +184,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 +275,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 +309,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 +393,37 @@ 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
|
||||
const uint32_t bit_time = this->bit_time_;
|
||||
std::optional<InterruptLock> frame_lock;
|
||||
if (this->locks_whole_frame())
|
||||
frame_lock.emplace();
|
||||
uint32_t start;
|
||||
{
|
||||
// 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);
|
||||
this->tx_pin_.digital_write(false);
|
||||
start = arch_get_cpu_cycle_count();
|
||||
}
|
||||
// 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++;
|
||||
}
|
||||
// From the edge after the last 0 the line stays high through the stop bits
|
||||
const uint32_t zeros = ~frame & ((1u << num_bits) - 1);
|
||||
const uint32_t high_from = zeros == 0 ? 0 : 32 - __builtin_clz(zeros);
|
||||
uint32_t wait = bit_time;
|
||||
for (uint32_t i = 0; i < high_from; i++)
|
||||
this->write_bit_((frame >> i) & 1, &wait, start, bit_time);
|
||||
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 +434,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_();
|
||||
|
||||
@@ -26,6 +26,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 +55,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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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_{};
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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) {
|
||||
@@ -1618,6 +1635,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() {
|
||||
|
||||
@@ -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
|
||||
@@ -2,12 +2,15 @@
|
||||
#ifdef USE_ESP32
|
||||
#ifdef USE_ZIGBEE
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_check.h"
|
||||
#include "zigbee_attribute_esp32.h"
|
||||
#include "zigbee_esp32.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "zigbee_helpers_esp32.h"
|
||||
#ifdef USE_WIFI
|
||||
@@ -19,6 +22,16 @@ namespace esphome::zigbee {
|
||||
ESPHOME_LOG_TAG(TAG, "zigbee");
|
||||
|
||||
static constexpr uint32_t COMMISSIONING_RETRY_TIMEOUT_ID = 0;
|
||||
static constexpr uint32_t PARENT_LINK_TIMEOUT_ID = 1;
|
||||
static constexpr uint32_t PARENT_LINK_RETRY_TIMEOUT_ID = 2;
|
||||
|
||||
// Since esp-zigbee-lib 2.0.5 every lost poll or transmission raises PARENT_LINK_FAILURE, even during a short radio
|
||||
// outage such as a BLE scan. After a failure the device polls at least every 3 s. It rejoins only after failures in
|
||||
// 4 polls that span at least 6 s; failures less than two thirds of a polling interval apart (poll retries, fast
|
||||
// polls) count once. Two intervals without a counted failure mean that a poll got through.
|
||||
static constexpr uint8_t PARENT_LINK_MISSED_POLLS = 4;
|
||||
static constexpr uint32_t PARENT_LINK_POLL_INTERVAL_MS = 3000;
|
||||
static constexpr uint32_t PARENT_LINK_MIN_SPAN_MS = 6000;
|
||||
|
||||
static ZigbeeComponent *global_zigbee = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
@@ -130,24 +143,16 @@ bool ZigbeeComponent::app_signal_handler(const ezb_app_signal_t *app_signal) {
|
||||
esp_zigbee_factory_reset(); // triggers a reboot
|
||||
}
|
||||
global_zigbee->joined_ = false;
|
||||
// For a leave asked for by the network: failures before it must not count after the rejoin
|
||||
global_zigbee->reset_parent_link_failures_();
|
||||
} break;
|
||||
case EZB_NWK_SIGNAL_NETWORK_STATUS: {
|
||||
const ezb_nwk_signal_network_status_params_t *network_status_params =
|
||||
(const ezb_nwk_signal_network_status_params_t *) ezb_app_signal_get_params(app_signal);
|
||||
if (network_status_params->status == EZB_NWK_NETWORK_STATUS_PARENT_LINK_FAILURE) {
|
||||
global_zigbee->joined_ = false;
|
||||
ESP_LOGW(TAG, "Parent link failure, attempting rejoin");
|
||||
ezb_zdo_nwk_mgmt_leave_req_t leave_req = {
|
||||
.dst_nwk_addr = ezb_nwk_get_short_address(),
|
||||
.field =
|
||||
{
|
||||
.remove_children = false,
|
||||
.rejoin = true,
|
||||
},
|
||||
};
|
||||
// Send leave request to the network to rejoin
|
||||
// triggers EZB_ZDO_SIGNAL_LEAVE signal first, then EZB_BDB_SIGNAL_DEVICE_REBOOT
|
||||
ezb_zdo_nwk_mgmt_leave_req(&leave_req);
|
||||
if (global_zigbee->joined_) { // else not joined yet, or a rejoin is running
|
||||
global_zigbee->on_parent_link_failure_();
|
||||
}
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Zigbee APP Signal NETWORK_STATUS: 0x%02x", network_status_params->status);
|
||||
}
|
||||
@@ -159,6 +164,93 @@ bool ZigbeeComponent::app_signal_handler(const ezb_app_signal_t *app_signal) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Runs on the Zigbee task with the stack lock held
|
||||
void ZigbeeComponent::on_parent_link_failure_() {
|
||||
const uint32_t now = millis();
|
||||
if (this->link_failures_ == 0) {
|
||||
// Poll faster for now, so that a lost parent is noticed soon also with a long polling interval
|
||||
this->saved_keep_alive_ = ezb_nwk_get_keepalive_interval();
|
||||
if (this->saved_keep_alive_ > PARENT_LINK_POLL_INTERVAL_MS) {
|
||||
ezb_nwk_set_keepalive_interval(PARENT_LINK_POLL_INTERVAL_MS);
|
||||
}
|
||||
}
|
||||
// The polling interval during the series
|
||||
const uint32_t interval = std::min(this->saved_keep_alive_, PARENT_LINK_POLL_INTERVAL_MS);
|
||||
if (this->link_failures_ > 0) {
|
||||
if (now - this->last_link_failure_ms_ >= 2 * interval) {
|
||||
// The series has ended, but its timeout has not run yet: start a new one, keep the saved interval
|
||||
this->link_failures_ = 0;
|
||||
} else if (now - this->last_link_failure_ms_ < 2 * interval / 3) {
|
||||
ESP_LOGV(TAG, "Parent link failure (same poll)");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this->link_failures_ == 0) {
|
||||
this->first_link_failure_ms_ = now;
|
||||
}
|
||||
this->last_link_failure_ms_ = now;
|
||||
this->link_failure_seq_++;
|
||||
if (this->link_failures_ < UINT8_MAX) {
|
||||
this->link_failures_++;
|
||||
}
|
||||
if (this->link_failures_ < PARENT_LINK_MISSED_POLLS || now - this->first_link_failure_ms_ < PARENT_LINK_MIN_SPAN_MS) {
|
||||
ESP_LOGD(TAG, "Parent link failure %u", this->link_failures_);
|
||||
// The stack does not report a poll that got through, so the series ends when no failure follows
|
||||
const uint8_t seq = this->link_failure_seq_;
|
||||
this->set_timeout(PARENT_LINK_TIMEOUT_ID, 2 * interval, [this, seq]() { this->end_parent_link_failures_(seq); });
|
||||
return;
|
||||
}
|
||||
ESP_LOGW(TAG, "Parent link failed in %u polls, attempting rejoin", this->link_failures_);
|
||||
this->cancel_timeout(PARENT_LINK_TIMEOUT_ID);
|
||||
this->reset_parent_link_failures_();
|
||||
this->joined_ = false;
|
||||
ezb_zdo_nwk_mgmt_leave_req_t leave_req = {
|
||||
.dst_nwk_addr = ezb_nwk_get_short_address(),
|
||||
.field =
|
||||
{
|
||||
.remove_children = false,
|
||||
.rejoin = true,
|
||||
},
|
||||
};
|
||||
// Send leave request to the network to rejoin
|
||||
// triggers EZB_ZDO_SIGNAL_LEAVE signal first, then EZB_BDB_SIGNAL_DEVICE_REBOOT
|
||||
if (ezb_zdo_nwk_mgmt_leave_req(&leave_req) != EZB_ERR_NONE) {
|
||||
ESP_LOGW(TAG, "Leave request for rejoin failed");
|
||||
this->joined_ = true; // still joined, so later failures can start a rejoin again
|
||||
}
|
||||
}
|
||||
|
||||
// Runs on the main loop when no failure was counted for two poll intervals
|
||||
void ZigbeeComponent::end_parent_link_failures_(uint8_t seq) {
|
||||
if (!esp_zigbee_lock_acquire(10 / portTICK_PERIOD_MS)) {
|
||||
// Retry with its own id, so that it cannot replace the timeout of a newer failure
|
||||
this->set_timeout(PARENT_LINK_RETRY_TIMEOUT_ID, 100, [this, seq]() { this->end_parent_link_failures_(seq); });
|
||||
return;
|
||||
}
|
||||
// A newer failure has set its own timeout, which ends the series instead
|
||||
const uint8_t failures = seq == this->link_failure_seq_ ? this->link_failures_ : 0;
|
||||
if (failures > 0) {
|
||||
this->reset_parent_link_failures_();
|
||||
}
|
||||
esp_zigbee_lock_release();
|
||||
if (failures > 0) { // after the release: the main task writes log lines out at once
|
||||
ESP_LOGD(TAG, "Parent link failures ended (%u)", failures);
|
||||
}
|
||||
}
|
||||
|
||||
// Ends the current series, if any. Needs the stack lock
|
||||
void ZigbeeComponent::reset_parent_link_failures_() {
|
||||
if (this->link_failures_ == 0) {
|
||||
return; // no series: the saved interval is stale
|
||||
}
|
||||
this->link_failures_ = 0;
|
||||
// Put the polling interval back, unless something else changed it in the meantime
|
||||
if (this->saved_keep_alive_ > PARENT_LINK_POLL_INTERVAL_MS &&
|
||||
ezb_nwk_get_keepalive_interval() == PARENT_LINK_POLL_INTERVAL_MS) {
|
||||
ezb_nwk_set_keepalive_interval(this->saved_keep_alive_);
|
||||
}
|
||||
}
|
||||
|
||||
void load_zb_event(ZBEvent *event, ezb_zcl_message_info_t info, ezb_zcl_attribute_t attribute) {
|
||||
event->load_set_attr_value_event(info, attribute);
|
||||
}
|
||||
|
||||
@@ -90,6 +90,9 @@ class ZigbeeComponent final : public Component {
|
||||
ezb_nwk_device_type_t device_role_ = EZB_NWK_DEVICE_TYPE_ROUTER;
|
||||
#endif
|
||||
void update_basic_cluster_(ezb_af_ep_desc_t ep_desc);
|
||||
void on_parent_link_failure_();
|
||||
void end_parent_link_failures_(uint8_t seq);
|
||||
void reset_parent_link_failures_();
|
||||
template<typename T>
|
||||
void add_attr_(ZigbeeAttribute *attr, uint8_t endpoint_id, uint16_t cluster_id, uint8_t role, uint16_t attr_id,
|
||||
T *value_p);
|
||||
@@ -115,6 +118,12 @@ class ZigbeeComponent final : public Component {
|
||||
std::atomic<bool> joined_ = false;
|
||||
std::atomic<bool> join_pending_ = false;
|
||||
std::atomic<bool> factory_new_ = false;
|
||||
// Current series of parent link failures, only used with the Zigbee stack lock held
|
||||
uint32_t first_link_failure_ms_{0};
|
||||
uint32_t last_link_failure_ms_{0};
|
||||
uint32_t saved_keep_alive_{0};
|
||||
uint8_t link_failures_{0};
|
||||
uint8_t link_failure_seq_{0};
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ from enum import Enum
|
||||
|
||||
from esphome.enum import StrEnum
|
||||
|
||||
__version__ = "2026.11.0b2"
|
||||
__version__ = "2026.11.0b5"
|
||||
|
||||
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
VALID_SUBSTITUTIONS_CHARACTERS = (
|
||||
|
||||
@@ -294,6 +294,8 @@ void Application::reboot() {
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
// No teardown on a forced reboot, but still power hardware down (Wi-Fi leaves the AP)
|
||||
this->run_powerdown_hooks();
|
||||
arch_restart();
|
||||
}
|
||||
void Application::safe_reboot() {
|
||||
|
||||
@@ -185,10 +185,12 @@ class Component {
|
||||
*/
|
||||
virtual bool teardown() { return true; }
|
||||
|
||||
/** Called after teardown is complete to power down hardware.
|
||||
/** Called last before a reboot or deep sleep to power down hardware.
|
||||
*
|
||||
* This is called after all components have finished their teardown process,
|
||||
* On a safe shutdown this is called after all components have finished their teardown process,
|
||||
* making it safe to power down hardware like ethernet PHY.
|
||||
* On a forced reboot (Application::reboot()) it is called right after on_shutdown() with no
|
||||
* teardown, so implementations must not assume teardown() has run.
|
||||
*/
|
||||
virtual void on_powerdown() {}
|
||||
|
||||
|
||||
@@ -507,7 +507,9 @@
|
||||
#define USE_ESP32_LOG_V2
|
||||
#define USE_WIFI_SCAN_RESULTS_LOCK
|
||||
#define USE_ESP32_BLE
|
||||
#define USE_ESP32_BLE_BLUEDROID_BOND_KEYS
|
||||
#define USE_ESP32_BLE_BLUEDROID_HEX_WRAPS
|
||||
#define USE_ESP32_BLE_GATTC_HANDLE_ORDER
|
||||
#define USE_ESP32_BLE_MAX_CONNECTIONS 3
|
||||
#define USE_ESP32_BLE_CLIENT
|
||||
#define USE_ESP32_BLE_DEVICE
|
||||
@@ -531,6 +533,7 @@
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 2, 0)
|
||||
#define USE_ESP32_BLE_TRACKER_DIRECT_CONN_GUARD
|
||||
#endif
|
||||
#define USE_ESP32_BLE_TRACKER_SHORT_SCAN_WINDOW
|
||||
#define USE_BLE_GATT_CLIENT
|
||||
#define ESPHOME_BLE_GATT_CLIENT_COUNT 1
|
||||
#define ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT 1
|
||||
@@ -698,6 +701,9 @@
|
||||
#define USE_UDP_OMR_SOURCE
|
||||
#define USE_ZIGBEE
|
||||
#endif
|
||||
#if defined(USE_ESP32_VARIANT_ESP32)
|
||||
#define USE_I2C_ISR_GUARD
|
||||
#endif
|
||||
#if defined(USE_ESP32_VARIANT_ESP32S3)
|
||||
// Border router with a UART RCP; a native-radio border router (C5/C6) adds only the coexistence call
|
||||
#define USE_OPENTHREAD
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
#include <Esp.h>
|
||||
#include <core_esp8266_features.h> // xt_rsil, xt_wsr_ps
|
||||
#include <pgmspace.h>
|
||||
#endif
|
||||
|
||||
@@ -2249,8 +2250,14 @@ class LockGuard {
|
||||
*/
|
||||
class InterruptLock {
|
||||
public:
|
||||
#ifdef USE_ESP8266
|
||||
// Inline: saves two calls per lock, and the lock sits on bit-banged timing paths
|
||||
ESPHOME_ALWAYS_INLINE InterruptLock() : state_(xt_rsil(15)) {}
|
||||
ESPHOME_ALWAYS_INLINE ~InterruptLock() { xt_wsr_ps(this->state_); }
|
||||
#else
|
||||
InterruptLock();
|
||||
~InterruptLock();
|
||||
#endif
|
||||
|
||||
protected:
|
||||
#if defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_ZEPHYR)
|
||||
|
||||
@@ -35,6 +35,9 @@ class MillisInternal {
|
||||
static ESPHOME_ALWAYS_INLINE uint32_t get() {
|
||||
#if defined(USE_ESP32) && CONFIG_FREERTOS_HZ == 1000
|
||||
return xTaskGetTickCount();
|
||||
#elif defined(USE_LIBRETINY_VARIANT_RTL8710B)
|
||||
// The tick is 976.6 us here, so millis() reads the system timer (rtl8710b_micros.c)
|
||||
return millis();
|
||||
#elif defined(USE_LIBRETINY) && (defined(USE_RTL87XX) || defined(USE_LN882X))
|
||||
// 1 kHz: xTaskGetTickCount() is already ms.
|
||||
static_assert(configTICK_RATE_HZ == 1000, "MillisInternal fast path requires 1 kHz FreeRTOS tick");
|
||||
|
||||
+32
-14
@@ -9,11 +9,29 @@
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
#include <hardware/sync.h>
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "scheduler");
|
||||
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
// lwIP callbacks add and cancel items from a low-priority IRQ on RP2, where lock_ is an empty Mutex: hold interrupts
|
||||
// off instead. Not the lwIP lock: each release re-arms arduino-pico's 20 ms Ethernet poll, starving reception.
|
||||
class SchedulerLockGuard {
|
||||
public:
|
||||
explicit SchedulerLockGuard(Mutex & /*mutex*/) : state_(save_and_disable_interrupts()) {}
|
||||
~SchedulerLockGuard() { restore_interrupts(this->state_); }
|
||||
|
||||
private:
|
||||
uint32_t state_;
|
||||
};
|
||||
#else
|
||||
using SchedulerLockGuard = LockGuard;
|
||||
#endif
|
||||
|
||||
// Maximum number of logically deleted (cancelled) items before forcing cleanup.
|
||||
// Empirically chosen to balance cleanup overhead against tombstone accumulation in items_.
|
||||
static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
|
||||
@@ -118,7 +136,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
if (delay == SCHEDULER_DONT_RUN) {
|
||||
// Still need to cancel existing timer if we have a name/id
|
||||
if (!skip_cancel) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, /* find_first= */ true);
|
||||
}
|
||||
return;
|
||||
@@ -140,7 +158,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
uint32_t offset = 0;
|
||||
// Take lock early to protect scheduler_item_pool_head_ access
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Create and populate the scheduler item
|
||||
SchedulerItem *item = this->get_item_from_pool_locked_();
|
||||
@@ -317,7 +335,7 @@ void Scheduler::full_cleanup_removed_items_() {
|
||||
// 2. Other threads must see either the old state or the new state, not intermediate states
|
||||
// 3. The operation is already expensive (O(n)), so lock overhead is negligible
|
||||
// 4. No operations inside can block or take other locks, so no deadlock risk
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Compact in-place: move valid items forward, recycle removed ones
|
||||
size_t write = 0;
|
||||
@@ -440,7 +458,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item;
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
item = this->pop_raw_locked_();
|
||||
}
|
||||
|
||||
@@ -457,7 +475,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
ESP_LOGD(TAG, "\n");
|
||||
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->items_ = std::move(old_items);
|
||||
// Rebuild heap after moving items back
|
||||
std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
|
||||
@@ -494,7 +512,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
|
||||
// Multi-threaded platforms without atomics: must take lock to safely read remove flag
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
if (is_item_removed_locked_(item)) {
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
@@ -504,7 +522,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#else
|
||||
// Single-threaded or multi-threaded with atomics: can check without lock
|
||||
if (is_item_removed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
continue;
|
||||
@@ -513,7 +531,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
|
||||
// Don't run on failed components (is_item_failed_ exempts SELF_POINTER delays).
|
||||
if (this->is_item_failed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
continue;
|
||||
}
|
||||
@@ -533,7 +551,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// - timeouts/intervals get cancelled
|
||||
now = this->execute_item_(item, now);
|
||||
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Only pop after function call, this ensures we were reachable
|
||||
// during the function call and know if we were cancelled.
|
||||
@@ -583,7 +601,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// every item has been returned to a container (items_, to_add_, or pool).
|
||||
// Lock needed to get a consistent snapshot of all containers.
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->debug_verify_no_leak_();
|
||||
}
|
||||
#endif
|
||||
@@ -592,7 +610,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
return now;
|
||||
}
|
||||
void HOT Scheduler::process_to_add_slow_path_() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
for (auto *&it : this->to_add_) {
|
||||
if (is_item_removed_locked_(it)) {
|
||||
// Recycle cancelled items
|
||||
@@ -616,7 +634,7 @@ bool HOT Scheduler::cleanup_slow_path_() {
|
||||
// 4. We need a consistent view of items_ and to_remove_ throughout the operation
|
||||
// Without the lock, we could access items_ while another thread is reading it,
|
||||
// leading to race conditions
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item = this->items_[0];
|
||||
if (!this->is_item_removed_locked_(item))
|
||||
@@ -664,7 +682,7 @@ uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
|
||||
// Common implementation for cancel operations - handles locking
|
||||
bool HOT Scheduler::cancel_item_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
|
||||
SchedulerItem::Type type) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
// Public cancel path uses default find_first=false to cancel ALL matches because
|
||||
// DelayAction parallel mode (skip_cancel=true) can create multiple items with the same key.
|
||||
return this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type);
|
||||
@@ -773,7 +791,7 @@ void __attribute__((noinline)) Scheduler::shrink_scheduler_vector_(std::vector<S
|
||||
}
|
||||
|
||||
void Scheduler::trim_freelist() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
SchedulerItem *item = this->scheduler_item_pool_head_;
|
||||
size_t freed = 0;
|
||||
while (item != nullptr) {
|
||||
|
||||
@@ -518,7 +518,8 @@ class Scheduler {
|
||||
uint32_t hash_or_id,
|
||||
SchedulerItem::Type type, bool find_first);
|
||||
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there; RP2 with networking locks by
|
||||
// holding interrupts off (SchedulerLockGuard in scheduler.cpp)
|
||||
[[no_unique_address]] Mutex lock_;
|
||||
std::vector<SchedulerItem *> items_;
|
||||
std::vector<SchedulerItem *> to_add_;
|
||||
|
||||
@@ -567,6 +567,22 @@ def shared_progmem_string(value: str) -> Expression:
|
||||
return text
|
||||
|
||||
|
||||
def static_buffer(owner: ID, type_: "MockObjClass", size: int | str) -> "MockObj":
|
||||
"""Emit a zeroed file-scope ``static type_ <component>__<owner>_buffer__pstorage[size];``.
|
||||
|
||||
Named like placement new storage, so ``esphome analyze-memory`` counts it under the owner.
|
||||
``size`` may be a C++ constant expression.
|
||||
"""
|
||||
if not isinstance(owner, ID) or owner.type is None:
|
||||
raise EsphomeError(f"Buffer owner '{owner}' must be the owning component's ID")
|
||||
base = unique_global_id(f"{owner.id}_buffer", type_)
|
||||
name = _pstorage_name(owner.type, base)
|
||||
CORE.add_global(RawStatement(f"static {type_} {name}[{size}];"))
|
||||
buffer = MockObj(name, ".")
|
||||
CORE.register_variable(base, buffer)
|
||||
return buffer
|
||||
|
||||
|
||||
def static_const_array(id_, rhs) -> "MockObj":
|
||||
rhs = safe_exp(rhs)
|
||||
obj = MockObj(id_, ".")
|
||||
@@ -669,6 +685,11 @@ def new_variable(
|
||||
return obj
|
||||
|
||||
|
||||
def _pstorage_name(type_: Any, name: Any) -> str:
|
||||
"""``<component>__<name>__pstorage``, the static storage name ``esphome analyze-memory`` attributes."""
|
||||
return f"{_extract_component_ns(str(type_))}__{name}__pstorage"
|
||||
|
||||
|
||||
def _extract_component_ns(type_str: str) -> str:
|
||||
"""Extract the component namespace from a fully-qualified C++ type string.
|
||||
|
||||
@@ -726,9 +747,7 @@ def Pvariable(id_: ID, rhs: SafeExpType, type_: "MockObj" = None) -> "MockObj":
|
||||
if call_expr.template_args is not None:
|
||||
actual_type = f"{actual_type}{call_expr.template_args}"
|
||||
pointer_type = id_.type
|
||||
# Extract component namespace from type for memory analysis attribution
|
||||
component_ns = _extract_component_ns(str(actual_type))
|
||||
storage_name = f"{component_ns}__{id_.id}__pstorage"
|
||||
storage_name = _pstorage_name(actual_type, id_.id)
|
||||
|
||||
# Declare aligned byte array for the object storage
|
||||
CORE.add_global(
|
||||
|
||||
@@ -46,7 +46,7 @@ dependencies:
|
||||
rules:
|
||||
- if: "target in [esp32h2, esp32p4]"
|
||||
francescopace/espectre:
|
||||
version: "3.1.0"
|
||||
version: "3.2.0"
|
||||
rules:
|
||||
- if: "target in [esp32, esp32s2, esp32s3, esp32c3, esp32c5, esp32c6]"
|
||||
zorxx/multipart-parser:
|
||||
|
||||
+6
-6
@@ -37,7 +37,7 @@ lib_deps_base =
|
||||
wjtje/qr-code-generator-library@1.7.0 ; qr_code
|
||||
functionpointer/arduino-MLX90393@1.0.2 ; mlx90393
|
||||
pavlodn/HaierProtocol@0.9.31 ; haier
|
||||
esphome/dsmr_parser@1.10.0 ; dsmr
|
||||
esphome/dsmr_parser@1.11.0 ; dsmr
|
||||
https://github.com/esphome/TinyGPSPlus.git#v1.1.0 ; gps
|
||||
; This is using the repository until a new release is published to PlatformIO
|
||||
https://github.com/Sensirion/arduino-gas-index-algorithm.git#3.2.1 ; Sensirion Gas Index Algorithm Arduino Library
|
||||
@@ -125,7 +125,7 @@ lib_deps =
|
||||
ESP8266WiFi ; wifi (Arduino built-in)
|
||||
Update ; ota (Arduino built-in)
|
||||
ESP32Async/ESPAsyncTCP@2.0.0 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
makuna/NeoPixelBus@2.7.3 ; neopixelbus
|
||||
ESP8266HTTPClient ; http_request (Arduino built-in)
|
||||
ESP8266mDNS ; mdns (Arduino built-in)
|
||||
@@ -216,8 +216,8 @@ framework = arduino
|
||||
lib_deps =
|
||||
${common:arduino.lib_deps}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ayushsharma82/RPAsyncTCP@1.3.2 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
https://github.com/esphome-libs/RPAsyncTCP.git#1.3.2-esphome.1 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
WiFi ; wifi (arduino-pico built-in)
|
||||
lwIP_CYW43 ; wifi (arduino-pico built-in, WiFi dependency)
|
||||
HTTPClient ; http_request (arduino-pico built-in)
|
||||
@@ -245,10 +245,10 @@ lib_compat_mode = soft
|
||||
lib_deps =
|
||||
${common.lib_deps_base}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
esphome/wireguard@0.4.8 ; wireguard
|
||||
esphome/noise-c@0.1.31 ; noise (api, ota)
|
||||
ESP32Async/AsyncTCP@3.4.5 ; async_tcp
|
||||
ESP32Async/AsyncTCP@3.5.0 ; async_tcp
|
||||
DNSServer ; captive_portal
|
||||
heman/AsyncMqttClient-esphome@2.0.0 ; mqtt
|
||||
improv/Improv@1.2.7 ; improv_serial
|
||||
|
||||
@@ -212,6 +212,8 @@ def clang_options(idedata, environment):
|
||||
and not flag.startswith("-mtune=esp")
|
||||
)
|
||||
cmd.append("-std=gnu++20")
|
||||
# clang otherwise reads the `module:` bit-field in IDF's soc/regdma.h as a C++20 module directive
|
||||
cmd.append("-fno-cxx-modules")
|
||||
|
||||
if environment.startswith(("bk72xx", "ln882h", "rtl87xx")):
|
||||
# LibreTiny leaves function-like macro values unparenthesized
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for the api wizard: schema, final validation and generated tables."""
|
||||
|
||||
from collections.abc import Callable
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
@@ -8,13 +9,20 @@ import re
|
||||
import string
|
||||
import textwrap
|
||||
|
||||
from aioesphomeapi.model import COMPONENT_TYPE_TO_INFO
|
||||
import pytest
|
||||
|
||||
from esphome.components.api import wizard
|
||||
from esphome.components.homeassistant.switch import SUPPORTED_DOMAINS as SWITCH_DOMAINS
|
||||
from esphome.config import load_config
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.helpers import fnv1_hash, fnv1a_32bit_hash, zstd_module
|
||||
from esphome.cpp_generator import MockObjClass
|
||||
from esphome.helpers import (
|
||||
fnv1_hash,
|
||||
fnv1_hash_object_id,
|
||||
fnv1a_32bit_hash,
|
||||
zstd_module,
|
||||
)
|
||||
from tests.component_tests.helpers import get_define_value
|
||||
|
||||
ESP32_HEADER = """
|
||||
@@ -774,9 +782,14 @@ def test_the_blob_is_the_exact_json_document(
|
||||
"description": "Pick",
|
||||
"entities": [
|
||||
# No device_id for the main device, and no description when unset
|
||||
{"key": entity_hash(main_cpp, "sw"), "description": "Enable"},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
],
|
||||
@@ -1074,16 +1087,206 @@ def test_an_entity_role_is_sent_with_the_entity(
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
"role": "example.enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_entities_sharing_a_name_are_told_apart_by_platform(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
sensor:
|
||||
- platform: template
|
||||
id: power_sensor
|
||||
name: Power
|
||||
switch:
|
||||
- platform: template
|
||||
id: power_switch
|
||||
name: Power
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: power_sensor
|
||||
- id: power_switch
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
# The key is the same, so the platform is what says which entity is meant
|
||||
key = fnv1_hash_object_id("Power")
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": key, "platform": "sensor"},
|
||||
{"key": key, "platform": "switch"},
|
||||
]
|
||||
|
||||
|
||||
def test_a_datetime_entity_has_the_platform_of_its_type(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
datetime:
|
||||
- platform: template
|
||||
id: dt_date
|
||||
name: Day
|
||||
type: date
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_time
|
||||
name: Hour
|
||||
type: time
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_datetime
|
||||
name: Moment
|
||||
type: datetime
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: dt_date
|
||||
- id: dt_time
|
||||
- id: dt_datetime
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Day"), "platform": "date"},
|
||||
{"key": fnv1_hash_object_id("Hour"), "platform": "time"},
|
||||
{"key": fnv1_hash_object_id("Moment"), "platform": "datetime"},
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_declared_in_its_component_has_the_platform_of_its_class(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
uart:
|
||||
tx_pin: 17
|
||||
rx_pin: 16
|
||||
baud_rate: 9600
|
||||
gps:
|
||||
latitude:
|
||||
id: gps_lat
|
||||
name: Latitude
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: gps_lat
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Latitude"), "platform": "sensor"}
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_of_a_platform_the_wizard_does_not_know_is_rejected(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
entities = """
|
||||
psram:
|
||||
i2c:
|
||||
id: camera_bus
|
||||
sda: 25
|
||||
scl: 23
|
||||
esp32_camera:
|
||||
id: test_camera
|
||||
name: Camera
|
||||
data_pins: [17, 35, 34, 5, 39, 18, 36, 19]
|
||||
vsync_pin: 22
|
||||
href_pin: 26
|
||||
pixel_clock_pin: 21
|
||||
external_clock:
|
||||
pin: 27
|
||||
i2c_id: camera_bus
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: test_camera
|
||||
"""
|
||||
|
||||
errors = config_errors(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert any(
|
||||
"Entity 'test_camera' is not of a platform the wizard can show" in error
|
||||
for error in errors
|
||||
), errors
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("class_name", "platform"), wizard.WIZARD_ENTITY_PLATFORMS.items()
|
||||
)
|
||||
def test_every_wizard_entity_platform_names_a_real_entity_class(
|
||||
class_name: str, platform: str
|
||||
) -> None:
|
||||
namespace, _ = class_name.split("::")
|
||||
component = importlib.import_module(
|
||||
f"esphome.components.{namespace.removesuffix('_')}"
|
||||
)
|
||||
# Light keeps its classes in a submodule
|
||||
modules = [component, *(getattr(component, "types", None),)]
|
||||
classes = {
|
||||
str(value)
|
||||
for module in modules
|
||||
if module is not None
|
||||
for value in vars(module).values()
|
||||
if isinstance(value, MockObjClass)
|
||||
}
|
||||
assert class_name in classes
|
||||
# The name the API client knows the entity type by
|
||||
assert platform in COMPONENT_TYPE_TO_INFO
|
||||
|
||||
|
||||
# Entity platforms of the API that a wizard page cannot show
|
||||
WIZARD_UNSUPPORTED_PLATFORMS: set[str] = {
|
||||
# ESP32Camera derives from EntityBase directly, with no camera base class to recognise
|
||||
"camera",
|
||||
# MediaPlayer does not declare EntityBase, so the page's use_id(EntityBase) already rejects it
|
||||
"media_player",
|
||||
# No ESPHome component provides one
|
||||
"siren",
|
||||
}
|
||||
|
||||
|
||||
def test_every_api_entity_platform_is_known_to_the_wizard() -> None:
|
||||
"""A new entity platform needs a WIZARD_ENTITY_PLATFORMS entry, or a reason to be left out."""
|
||||
proto = (
|
||||
Path(wizard.__file__).parent.joinpath("api.proto").read_text(encoding="utf-8")
|
||||
)
|
||||
messages = re.findall(r"message ListEntities(?!Done|Services)\w+Response \{", proto)
|
||||
# The ifdef of each ListEntities message names its platform: USE_SENSOR, USE_DATETIME_DATE, ...
|
||||
ifdefs = re.findall(
|
||||
r"message ListEntities(?!Done|Services)\w+Response \{[^}]*?"
|
||||
r'option \(ifdef\) = "USE_(\w+)";',
|
||||
proto,
|
||||
)
|
||||
assert len(ifdefs) == len(messages)
|
||||
proto_platforms = {ifdef.lower().removeprefix("datetime_") for ifdef in ifdefs}
|
||||
assert (
|
||||
set(wizard.WIZARD_ENTITY_PLATFORMS.values()) | WIZARD_UNSUPPORTED_PLATFORMS
|
||||
== proto_platforms
|
||||
)
|
||||
|
||||
|
||||
def test_an_entity_with_a_role_may_be_in_the_wizard_twice(tmp_path: Path) -> None:
|
||||
wizard.register_entity_role(ID("sw", is_declaration=True), "example.enable")
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
"""LibreTiny always gets the xPortGetCoreID stand-in, whatever its log level."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_libretiny_adds_core_id_flag(
|
||||
generate_main: Callable[[str | Path], str], tmp_path: Path
|
||||
) -> None:
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\n"
|
||||
"bk72xx:\n board: generic-bk7231n-qfn32-tuya\n\n"
|
||||
"wifi:\n ssid: test\n password: testtest12\n\n"
|
||||
"async_tcp:\n"
|
||||
)
|
||||
generate_main(config)
|
||||
assert "-DxPortGetCoreID=int" in CORE.build_flags
|
||||
@@ -818,9 +818,18 @@ def test_uc8279_offset_height_configurable(
|
||||
assert resolution == (0x61, 0x00, 0x10, 0x00, 0x0A)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dimensions",
|
||||
[
|
||||
{"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
# offset_height not written: the default of 0 applies, and the error must not point at a missing key
|
||||
{"width": 16, "height": 0x10000},
|
||||
],
|
||||
)
|
||||
def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config: Callable[[str, Any], None],
|
||||
dimensions: dict[str, int],
|
||||
) -> None:
|
||||
"""offset_height plus the panel height is the gate count, which the controller holds in 16 bits."""
|
||||
set_core_config(
|
||||
@@ -829,15 +838,16 @@ def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
)
|
||||
set_component_config("spi", {"id": "spi_bus", "clk_pin": 18, "mosi_pin": 19})
|
||||
|
||||
with pytest.raises(cv.Invalid, match="must not exceed"):
|
||||
with pytest.raises(cv.Invalid, match="must not exceed") as exc_info:
|
||||
run_schema_validation(
|
||||
{
|
||||
"id": "test_display",
|
||||
"model": "uc8279",
|
||||
"dc_pin": 21,
|
||||
"dimensions": {"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
"dimensions": dimensions,
|
||||
}
|
||||
)
|
||||
assert exc_info.value.path[-2:] == ["dimensions", "height"]
|
||||
|
||||
|
||||
def test_uc8279_x4pro_explicit_dimensions_keep_the_model_offset(
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Tests for the Bluedroid wraps that keep bond keys on re-encryption."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SRC_CMAKE
|
||||
from esphome.components.esp32_ble import bluedroid_headers_cmake
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAP_FLAGS = {
|
||||
"-Wl,--wrap=smp_check_auth_req",
|
||||
"-Wl,--undefined=__wrap_smp_check_auth_req",
|
||||
"-Wl,--wrap=btm_sec_clear_ble_keys",
|
||||
"-Wl,--undefined=__wrap_btm_sec_clear_ble_keys",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "windows", "expected"),
|
||||
[
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", False, True, id="idf_5_5_6"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.5}", False, False, id="idf_5_5_5"),
|
||||
pytest.param("{type: esp-idf, version: 6.0.1}", False, False, id="idf_6"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", True, False, id="windows"),
|
||||
# Arduino 3.3.12 is built on ESP-IDF 5.5.6, 3.3.11 on 5.5.5
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.12}", False, True, id="arduino_3_3_12"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.11}", False, False, id="arduino_3_3_11"
|
||||
),
|
||||
# PlatformIO builds cannot reach the private headers
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}\n toolchain: platformio",
|
||||
False,
|
||||
False,
|
||||
id="platformio_idf_5_5_6",
|
||||
),
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.12}\n toolchain: platformio",
|
||||
False,
|
||||
False,
|
||||
id="platformio_arduino_3_3_12",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wraps_only_on_idf_5_5_6_native_builds(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
framework: str,
|
||||
windows: bool,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("esphome.components.esp32_ble.IS_WINDOWS", windows)
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\nesp32:\n variant: esp32\n"
|
||||
f" framework: {framework}\n\nesp32_ble: {{}}\n"
|
||||
)
|
||||
generate_main(config)
|
||||
assert CORE.build_flags & _WRAP_FLAGS == (_WRAP_FLAGS if expected else set())
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_BLE_BLUEDROID_BOND_KEYS" in defines) is expected
|
||||
headers = bluedroid_headers_cmake("bluedroid_bond_keys.c")
|
||||
assert (headers in CORE.data[KEY_ESP32][KEY_SRC_CMAKE]) is expected
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Tests for the wrap that sorts GATT discovery responses by handle."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp32_ble import _has_strict_handle_order
|
||||
import esphome.config_validation as cv
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAP_FLAGS = {
|
||||
"-Wl,--wrap=gatt_client_handle_server_rsp",
|
||||
"-Wl,--undefined=__wrap_gatt_client_handle_server_rsp",
|
||||
}
|
||||
_CLIENTS = {
|
||||
"ble_client": (
|
||||
"esp32_ble_tracker: {}\n\n"
|
||||
"ble_client:\n - mac_address: AA:BB:CC:DD:EE:FF\n id: client\n"
|
||||
),
|
||||
# The proxy connects through bluetooth_connection, without esp32_ble_client
|
||||
"bluetooth_proxy": (
|
||||
"wifi:\n ssid: test\n password: password1\n\napi: {}\n\n"
|
||||
"bluetooth_proxy:\n active: true\n"
|
||||
),
|
||||
"none": "",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "expected"),
|
||||
[
|
||||
("5.4.4", False),
|
||||
("5.5.5", False),
|
||||
("5.5.6", True),
|
||||
("5.5.7", True),
|
||||
("6.0.0", False),
|
||||
("6.0.2", False),
|
||||
("6.0.3", True),
|
||||
("6.1.0", True),
|
||||
],
|
||||
)
|
||||
def test_strict_handle_order_versions(version: str, expected: bool) -> None:
|
||||
"""ESP-IDF added the check in 5.5.6 and 6.0.3."""
|
||||
assert _has_strict_handle_order(cv.Version.parse(version)) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "client", "expected"),
|
||||
[
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", "ble_client", True, id="idf_5_5_6"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", "bluetooth_proxy", True, id="proxy"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.5}", "ble_client", False, id="idf_5_5_5"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 6.0.1}", "ble_client", False, id="idf_6_0_1"
|
||||
),
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", "none", False, id="no_client"),
|
||||
# Arduino 3.3.12 is built on ESP-IDF 5.5.6; no private headers are needed
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.12}", "ble_client", True, id="arduino"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}\n toolchain: platformio",
|
||||
"ble_client",
|
||||
True,
|
||||
id="platformio",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wrap_only_with_a_gatt_client_on_strict_idf(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
framework: str,
|
||||
client: str,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\nesp32:\n variant: esp32\n"
|
||||
f" framework: {framework}\n\nesp32_ble: {{}}\n\n" + _CLIENTS[client]
|
||||
)
|
||||
generate_main(config)
|
||||
assert CORE.build_flags & _WRAP_FLAGS == (_WRAP_FLAGS if expected else set())
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_BLE_GATTC_HANDLE_ORDER" in defines) is expected
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user