mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 02:55:59 +00:00
Compare commits
54
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab6e3d9bf0 | ||
|
|
10ef6e371b | ||
|
|
c84cd04cf7 | ||
|
|
fb6d7bf265 | ||
|
|
3ad8e35be8 | ||
|
|
11f9f20b61 | ||
|
|
b6d0961f25 | ||
|
|
6046d067aa | ||
|
|
690c5f2fb6 | ||
|
|
654954f684 | ||
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
84079c07e2 | ||
|
|
b7dbf17469 | ||
|
|
b91750c325 | ||
|
|
92d2a457fa | ||
|
|
a1fecebb09 | ||
|
|
32b9d4cbe7 | ||
|
|
c53401a28d | ||
|
|
6b7d17c762 | ||
|
|
93a3306d82 | ||
|
|
54d3477240 | ||
|
|
5f9d83d293 | ||
|
|
43864283b4 | ||
|
|
4efbb38b86 | ||
|
|
045374965f | ||
|
|
39a939720f | ||
|
|
a79e51e784 | ||
|
|
517f0d6d48 | ||
|
|
1327d0ddc5 | ||
|
|
2adb544e7a | ||
|
|
48905beb96 | ||
|
|
ed401814bf | ||
|
|
0245db6285 | ||
|
|
07ee0f9f04 | ||
|
|
3d34ad572b |
No files matched your search
@@ -48,7 +48,7 @@ PROJECT_NAME = ESPHome
|
||||
# could be handy for archiving the generated documentation or if some version
|
||||
# control system is used.
|
||||
|
||||
PROJECT_NUMBER = 2026.11.0b4
|
||||
PROJECT_NUMBER = 2026.11.0b7
|
||||
|
||||
# Using the PROJECT_BRIEF tag one can provide an optional one line description
|
||||
# for a project that appears at the top of each page and should give viewer a
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ RUN \
|
||||
-r /requirements.txt
|
||||
|
||||
# Install the ESPHome Device Builder dashboard.
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.26.0
|
||||
RUN uv pip install --no-cache-dir esphome-device-builder==1.28.1
|
||||
|
||||
RUN \
|
||||
platformio settings set enable_telemetry No \
|
||||
|
||||
@@ -452,7 +452,8 @@ message DeviceWizardRequest {
|
||||
//
|
||||
// {"version": 1,
|
||||
// "pages": [{"title": "...", "description": "...",
|
||||
// "entities": [{"key": 123, "device_id": 456, "description": "...", "role": "..."}],
|
||||
// "entities": [{"key": 123, "platform": "sensor", "device_id": 456,
|
||||
// "description": "...", "role": "..."}],
|
||||
// "inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
// "entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
// "device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
@@ -465,6 +466,10 @@ message DeviceWizardRequest {
|
||||
// An entity is an entity of this device that the page shows to the user (for example to
|
||||
// turn it on or off). Its key is the key ListEntitiesResponse sends for it. Its
|
||||
// device_id is the device_id ListEntitiesResponse sends, and is left out when that is 0.
|
||||
// Its platform is the platform of the entity (sensor, switch and so on; date, time or
|
||||
// datetime for a datetime entity). A key is only unique within its platform and device, so
|
||||
// a client matches an entity by platform, device_id and key together. A client that does
|
||||
// not know platform ignores it, so the version stays 1.
|
||||
// Its role, when set, is a stable name that the device's firmware gives the entity
|
||||
// (always <component>.<name>), so a client can recognise it. The user cannot change it,
|
||||
// and no two entities of a wizard share one.
|
||||
|
||||
@@ -784,8 +784,9 @@ class APIConnection final : public APIServerConnectionBase {
|
||||
}
|
||||
|
||||
// Helper function to schedule a high priority message at the front of the batch
|
||||
// Out-of-line: callers (on_shutdown, check_keepalive_) are cold paths
|
||||
// Out-of-line: callers (send_shutdown_disconnect_, check_keepalive_) are cold paths
|
||||
bool schedule_message_front_(EntityBase *entity, uint16_t message_type, uint8_t estimated_size);
|
||||
void send_shutdown_disconnect_();
|
||||
|
||||
// Helper function to log client messages with name and peername
|
||||
void log_client_(int level, const LogString *message);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <cerrno>
|
||||
#include <cinttypes>
|
||||
#include "api_connection.h"
|
||||
#include "api_connection_buffer.h"
|
||||
#include "esphome/components/network/util.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/defines.h"
|
||||
@@ -794,6 +795,31 @@ void APIServer::on_camera_image(const std::shared_ptr<camera::CameraImage> &imag
|
||||
}
|
||||
#endif
|
||||
|
||||
// Kept out of api_connection.cpp so GCC inlines its send path as before
|
||||
void APIConnection::send_shutdown_disconnect_() {
|
||||
#ifndef USE_DEEP_SLEEP
|
||||
// Queued states first: Home Assistant mishandles states after DisconnectRequest (#22610).
|
||||
// Not with deep sleep: its entities stay available, and the disconnect must not wait on a slow link
|
||||
this->flags_.state_subscription = false;
|
||||
this->destroy_active_iterator_();
|
||||
// process_batch_ first flushes any overflow without blocking; stop once the queue stops shrinking
|
||||
for (size_t left = this->deferred_batch_.size(); left != 0;) {
|
||||
this->process_batch_();
|
||||
const size_t now_left = this->deferred_batch_.size();
|
||||
if (now_left >= left)
|
||||
break;
|
||||
left = now_left;
|
||||
}
|
||||
#endif
|
||||
DisconnectRequest req;
|
||||
if (!this->send_message(req)) {
|
||||
// tx buffer full: first in the queue, so a slow link still delivers it before the teardown timeout.
|
||||
// Due at once: teardown does not advance the cached loop time the batch_delay gate reads
|
||||
this->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
|
||||
this->make_batch_due_now_();
|
||||
}
|
||||
}
|
||||
|
||||
void APIServer::on_shutdown() {
|
||||
this->shutting_down_ = true;
|
||||
|
||||
@@ -806,15 +832,8 @@ void APIServer::on_shutdown() {
|
||||
// Change batch delay to 5ms for quick flushing during shutdown
|
||||
this->batch_delay_ = 5;
|
||||
|
||||
// Send disconnect requests to all connected clients
|
||||
for (auto &c : this->active_clients()) {
|
||||
DisconnectRequest req;
|
||||
if (!c->send_message(req)) {
|
||||
// If we can't send the disconnect request directly (tx_buffer full),
|
||||
// schedule it at the front of the batch so it will be sent with priority
|
||||
c->schedule_message_front_(nullptr, DisconnectRequest::MESSAGE_TYPE, DisconnectRequest::ESTIMATED_SIZE);
|
||||
}
|
||||
}
|
||||
for (auto &c : this->active_clients())
|
||||
c->send_shutdown_disconnect_();
|
||||
}
|
||||
|
||||
bool APIServer::teardown() {
|
||||
|
||||
@@ -257,6 +257,47 @@ WIZARD_DOMAIN_LIMITED_PLATFORMS = (
|
||||
)
|
||||
|
||||
|
||||
# The C++ base class of each kind of entity a wizard page can show, and the platform an API client
|
||||
# knows it by. An entity key is only unique within its platform, so the wizard sends both.
|
||||
WIZARD_ENTITY_PLATFORMS: dict[str, str] = {
|
||||
"alarm_control_panel::AlarmControlPanel": "alarm_control_panel",
|
||||
"binary_sensor::BinarySensor": "binary_sensor",
|
||||
"button::Button": "button",
|
||||
"climate::Climate": "climate",
|
||||
"cover::Cover": "cover",
|
||||
"datetime::DateEntity": "date",
|
||||
"datetime::DateTimeEntity": "datetime",
|
||||
"datetime::TimeEntity": "time",
|
||||
"event::Event": "event",
|
||||
"fan::Fan": "fan",
|
||||
"infrared::Infrared": "infrared",
|
||||
"light::LightState": "light",
|
||||
"lock::Lock": "lock",
|
||||
"number::Number": "number",
|
||||
"radio_frequency::RadioFrequency": "radio_frequency",
|
||||
"select::Select": "select",
|
||||
"sensor::Sensor": "sensor",
|
||||
"switch_::Switch": "switch",
|
||||
"text::Text": "text",
|
||||
"text_sensor::TextSensor": "text_sensor",
|
||||
"update::UpdateEntity": "update",
|
||||
"valve::Valve": "valve",
|
||||
"water_heater::WaterHeater": "water_heater",
|
||||
}
|
||||
|
||||
|
||||
def _wizard_entity_platform(
|
||||
config: fv.FinalValidateConfig, entity_id: ID
|
||||
) -> str | None:
|
||||
"""The platform of an entity, from the C++ class it is declared with, as some entities are not
|
||||
declared under their platform (the sensors of gps:, for example)."""
|
||||
declared: ID = config.get_config_for_path(config.get_path_for_id(entity_id))
|
||||
for cls in (declared.type, *declared.type.parents):
|
||||
if (platform := WIZARD_ENTITY_PLATFORMS.get(str(cls))) is not None:
|
||||
return platform
|
||||
return None
|
||||
|
||||
|
||||
def wizard_input_ids(api_config: ConfigType) -> set[str]:
|
||||
"""The IDs of the entities that are linked inputs of the wizard in the given api config."""
|
||||
if (wizard := api_config.get(CONF_WIZARD)) is None:
|
||||
@@ -361,7 +402,8 @@ def _validate_wizard_input(conf: ConfigType) -> ConfigType:
|
||||
|
||||
|
||||
def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
"""Reject entities that are internal, as they are not exposed over the API, or have no name.
|
||||
"""Reject entities that are internal, as they are not exposed over the API, have no name, or
|
||||
are of a platform the wizard does not know.
|
||||
|
||||
The key a client knows an entity by is a hash of its name. Without a name of its own, the
|
||||
device works the name out at runtime from its friendly name, which can add the MAC address,
|
||||
@@ -378,6 +420,10 @@ def _validate_wizard_entity_exposed(value: ID) -> ID:
|
||||
f"Entity '{value.id}' has no name of its own, so its key is not known "
|
||||
"when the wizard is built. Give it a name to use it in the wizard"
|
||||
)
|
||||
if _wizard_entity_platform(fv.full_config.get(), value) is None:
|
||||
raise cv.Invalid(
|
||||
f"Entity '{value.id}' is not of a platform the wizard can show"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
@@ -446,7 +492,10 @@ def _entity_document(
|
||||
) -> ConfigType:
|
||||
"""An entity of the device that the page shows, keyed as ListEntitiesResponse keys it."""
|
||||
_, declaration = _wizard_input_declaration(config, conf[CONF_ID])
|
||||
document: ConfigType = {"key": fnv1_hash_object_id(declaration[CONF_NAME])}
|
||||
document: ConfigType = {
|
||||
"key": fnv1_hash_object_id(declaration[CONF_NAME]),
|
||||
"platform": _wizard_entity_platform(config, conf[CONF_ID]),
|
||||
}
|
||||
if (device := declaration.get(CONF_DEVICE_ID)) is not None:
|
||||
document["device_id"] = fnv1a_32bit_hash(device.id)
|
||||
if description := conf.get(CONF_DESCRIPTION):
|
||||
@@ -476,7 +525,8 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
|
||||
{"version": 1,
|
||||
"pages": [{"title": "...", "description": "...",
|
||||
"entities": [{"key": 123, "device_id": 456, "description": "...", "role": "..."}],
|
||||
"entities": [{"key": 123, "platform": "sensor", "device_id": 456,
|
||||
"description": "...", "role": "..."}],
|
||||
"inputs": [{"key": 789, "description": "...", "multiple": true, "max_length": 1023,
|
||||
"entity_filters": [{"integration": "...", "domain": ["..."],
|
||||
"device_class": ["..."], "supported_features": ["..."]}]}]}]}
|
||||
@@ -487,6 +537,10 @@ def wizard_document(wizard: ConfigType, config: fv.FinalValidateConfig) -> Confi
|
||||
- An entity key is the key ListEntitiesResponse sends for the entity: the FNV-1 hash of the
|
||||
object id made from its name (entity_helpers). device_id is the hash of the ESPHome id of
|
||||
the device it belongs to (esphome/core/config.py), and is left out for the main device.
|
||||
- An entity platform is the platform of the entity: sensor, switch and so on, or date, time or
|
||||
datetime for an entity of the datetime component. A key is only unique within its platform
|
||||
and device, so a client matches an entity by platform, device_id and key together. A client
|
||||
that does not know platform ignores it, so the version stays 1.
|
||||
- An entity role is a stable name, always <component>.<name>, that the component of the entity
|
||||
gives it with register_entity_role, so Home Assistant can recognise the entity. The user
|
||||
cannot set or change it, and no two entities of a wizard share one. A client that does not
|
||||
|
||||
@@ -35,15 +35,23 @@ async def to_code(config: ConfigType) -> None:
|
||||
add_idf_component(name="esp32async/asynctcp", ref="3.4.91")
|
||||
elif CORE.is_libretiny:
|
||||
# https://github.com/ESP32Async/AsyncTCP
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.4.5")
|
||||
cg.add_library("ESP32Async/AsyncTCP", "3.5.0")
|
||||
# AsyncTCP 3.5.0 debug logs call xPortGetCoreID(), which LibreTiny (single core) lacks; they are compiled
|
||||
# in by LibreTiny's debug level or CONFIG_ASYNC_TCP_DEBUG, so the call always expands to int(), which is 0
|
||||
# (a function-like -D does not survive PlatformIO's build flags)
|
||||
cg.add_build_flag("-DxPortGetCoreID=int")
|
||||
elif CORE.is_esp8266:
|
||||
# https://github.com/ESP32Async/ESPAsyncTCP
|
||||
cg.add_library("ESP32Async/ESPAsyncTCP", "2.0.0")
|
||||
elif CORE.is_rp2:
|
||||
# https://github.com/ayushsharma82/RPAsyncTCP
|
||||
# RPAsyncTCP is a drop-in replacement for AsyncTCP_RP2040W with better
|
||||
# ESPAsyncWebServer compatibility
|
||||
cg.add_library("ayushsharma82/RPAsyncTCP", "1.3.2")
|
||||
# https://github.com/esphome-libs/RPAsyncTCP, a fork of ayushsharma82/RPAsyncTCP
|
||||
# 1.3.2 that counts queued bytes before lwIP can send and ACK them, so
|
||||
# canSend() does not stay false and SSE streams do not stall (wired Ethernet)
|
||||
cg.add_library(
|
||||
"RPAsyncTCP",
|
||||
"1.3.2",
|
||||
"https://github.com/esphome-libs/RPAsyncTCP#1.3.2-esphome.1",
|
||||
)
|
||||
# Other platforms (host, etc) use socket-based implementation
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef USE_ESP32
|
||||
#include <esp_err.h>
|
||||
@@ -136,6 +137,18 @@ inline void fill_128bit_uuid_array(std::array<uint64_t, 2> &out, const ble_devic
|
||||
out[1] = 0x800000805F9B34FBULL; // Base UUID bytes 0-7
|
||||
}
|
||||
|
||||
/// A 128-bit UUID in big-endian (printable) order, as its 16 or 32-bit form when it is on the Bluetooth base UUID.
|
||||
inline ble_device_base::ESPBTUUID uuid_from_be128(const uint8_t *uuid128) {
|
||||
using ble_device_base::ESPBTUUID;
|
||||
// 0000xxxx-0000-1000-8000-00805F9B34FB without its first 4 bytes
|
||||
static constexpr uint8_t BASE_UUID_TAIL[12] = {0x00, 0x00, 0x10, 0x00, 0x80, 0x00,
|
||||
0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
|
||||
if (memcmp(uuid128 + 4, BASE_UUID_TAIL, sizeof(BASE_UUID_TAIL)) != 0)
|
||||
return ESPBTUUID::from_raw_reversed(uuid128);
|
||||
const uint32_t value = encode_uint32(uuid128[0], uuid128[1], uuid128[2], uuid128[3]);
|
||||
return value <= UINT16_MAX ? ESPBTUUID::from_uint16(value) : ESPBTUUID::from_uint32(value);
|
||||
}
|
||||
|
||||
/// Fill the UUID in the appropriate wire format based on client support and
|
||||
/// UUID type (128-bit array for old clients or 128-bit UUIDs, short form
|
||||
/// otherwise).
|
||||
|
||||
@@ -16,7 +16,6 @@ namespace esphome::bluetooth_connection {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "bluetooth_connection");
|
||||
|
||||
using ble_device_base::ESPBTUUID;
|
||||
using ble_device_base::GATT_ERR_NOT_CONNECTED;
|
||||
using ble_device_base::GATT_ERR_NO_MEMORY;
|
||||
|
||||
@@ -63,14 +62,6 @@ btstack_packet_callback_registration_t RP2GattClient::sm_event_registration = {}
|
||||
RP2GattClient *RP2GattClient::connect_owner = nullptr;
|
||||
// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
static ESPBTUUID uuid_from_btstack(uint16_t uuid16, const uint8_t uuid128[16]) {
|
||||
if (uuid16 != 0) {
|
||||
return ESPBTUUID::from_uint16(uuid16);
|
||||
}
|
||||
// BTstack structs carry the 128-bit form big-endian (printable order).
|
||||
return ESPBTUUID::from_raw_reversed(uuid128);
|
||||
}
|
||||
|
||||
void RP2GattClient::setup() {
|
||||
// Pre-create every pool entry so the packet handlers' allocate() calls are
|
||||
// always a free-list pop -- the IRQ path must never reach malloc().
|
||||
@@ -300,8 +291,9 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
}
|
||||
gatt_client_service_t service;
|
||||
gatt_event_service_query_result_get_service(packet, &service);
|
||||
// Not uuid16: BTstack stores a 32-bit base UUID there truncated to its low 16 bits
|
||||
auto &dst = this->arena_->services[this->service_count_];
|
||||
dst.uuid = uuid_from_btstack(service.uuid16, service.uuid128);
|
||||
dst.uuid = uuid_from_be128(service.uuid128);
|
||||
dst.start_handle = service.start_group_handle;
|
||||
dst.end_handle = service.end_group_handle;
|
||||
dst.first_characteristic = 0;
|
||||
@@ -320,7 +312,7 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
gatt_client_characteristic_t characteristic;
|
||||
gatt_event_characteristic_query_result_get_characteristic(packet, &characteristic);
|
||||
auto &dst = this->arena_->characteristics[this->char_count_];
|
||||
dst.uuid = uuid_from_btstack(characteristic.uuid16, characteristic.uuid128);
|
||||
dst.uuid = uuid_from_be128(characteristic.uuid128);
|
||||
dst.value_handle = characteristic.value_handle;
|
||||
dst.end_handle = characteristic.end_handle;
|
||||
dst.properties = static_cast<uint8_t>(characteristic.properties);
|
||||
@@ -340,7 +332,7 @@ void RP2GattClient::handle_gatt_event_irq_(uint8_t event_type, const uint8_t *pa
|
||||
gatt_client_characteristic_descriptor_t descriptor;
|
||||
gatt_event_all_characteristic_descriptors_query_result_get_characteristic_descriptor(packet, &descriptor);
|
||||
auto &dst = this->arena_->descriptors[this->desc_count_];
|
||||
dst.uuid = uuid_from_btstack(descriptor.uuid16, descriptor.uuid128);
|
||||
dst.uuid = uuid_from_be128(descriptor.uuid128);
|
||||
dst.handle = descriptor.handle;
|
||||
this->desc_count_++;
|
||||
break;
|
||||
|
||||
@@ -65,13 +65,24 @@ void CST816Touchscreen::update_touches() {
|
||||
this->status_set_warning();
|
||||
return;
|
||||
}
|
||||
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
|
||||
// The low nibble is the touch count. CST816/CST820 are single-touch;
|
||||
// CST826/CST836 can report two points, but this driver only reads the first
|
||||
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
|
||||
// disabling auto-sleep: the count lands above two and the coordinates are
|
||||
// the 0xFFF sentinel, so both guards below reject it.
|
||||
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 0x0F;
|
||||
if (num_of_touches == 0) {
|
||||
return;
|
||||
}
|
||||
if (num_of_touches > 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]);
|
||||
uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]);
|
||||
if (x == 0x0FFF || y == 0x0FFF) {
|
||||
return;
|
||||
}
|
||||
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
|
||||
this->add_raw_touch_position_(0, x, y);
|
||||
}
|
||||
|
||||
@@ -195,14 +195,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
}
|
||||
} else {
|
||||
uint16_t raw_humidity = encode_uint16(data[0], data[1]);
|
||||
uint16_t raw_temperature = encode_uint16(data[2], data[3]);
|
||||
|
||||
if (raw_temperature & 0x8000) {
|
||||
if (!(raw_temperature & 0x4000))
|
||||
raw_temperature = ~(raw_temperature & 0x7FFF);
|
||||
} else if (raw_temperature & 0x800) {
|
||||
raw_temperature |= 0xf000;
|
||||
}
|
||||
const int16_t raw_temperature = decode_dht22_temperature(encode_uint16(data[2], data[3]));
|
||||
|
||||
if (raw_temperature == 1 && raw_humidity == 10) {
|
||||
if (report_errors) {
|
||||
@@ -214,7 +207,7 @@ bool HOT IRAM_ATTR DHT::read_sensor_(float *temperature, float *humidity, bool r
|
||||
*humidity = static_cast<float>(raw_humidity) * 0.1f;
|
||||
if (*humidity > 100.0f)
|
||||
*humidity = NAN;
|
||||
*temperature = static_cast<int16_t>(raw_temperature) * 0.1f;
|
||||
*temperature = raw_temperature * 0.1f;
|
||||
}
|
||||
|
||||
if (*temperature == 0.0f && (*humidity == 1.0f || *humidity == 2.0f)) {
|
||||
|
||||
@@ -17,6 +17,18 @@ enum DHTModel : uint8_t {
|
||||
DHT_MODEL_DHT22_TYPE2
|
||||
};
|
||||
|
||||
/// Convert a DHT22-family temperature reading to tenths of a degree. Sensors encode negative values in one of three
|
||||
/// ways: sign and magnitude (bit 15 set, bit 14 clear), 16-bit two's complement, or 12-bit two's complement (bit 11).
|
||||
inline int16_t decode_dht22_temperature(uint16_t raw) {
|
||||
if (raw & 0x8000) {
|
||||
if (!(raw & 0x4000))
|
||||
return static_cast<int16_t>(-static_cast<int16_t>(raw & 0x7FFF));
|
||||
} else if (raw & 0x800) {
|
||||
raw |= 0xF000;
|
||||
}
|
||||
return static_cast<int16_t>(raw);
|
||||
}
|
||||
|
||||
/// Component for reading temperature/humidity measurements from DHT11/DHT22 sensors.
|
||||
class DHT final : public PollingComponent {
|
||||
SUB_SENSOR(temperature)
|
||||
|
||||
@@ -30,7 +30,7 @@ void EPaperJD79660::fill(Color color) {
|
||||
|
||||
// We store 4 pixels per byte
|
||||
this->buffer_.fill(pixel_color | (pixel_color << 2) | (pixel_color << 4) | (pixel_color << 6));
|
||||
this->drawn_since_hash_ = true;
|
||||
this->mark_all_drawn_();
|
||||
}
|
||||
|
||||
void HOT EPaperJD79660::draw_pixel_at(int x, int y, Color color) {
|
||||
|
||||
@@ -232,7 +232,7 @@ void EPaperT133A01::fill(Color color) {
|
||||
}
|
||||
auto pixel_color = color_to_index(color);
|
||||
this->buffer_.fill(pixel_color + (pixel_color << 4));
|
||||
this->drawn_since_hash_ = true;
|
||||
this->mark_all_drawn_();
|
||||
}
|
||||
|
||||
void EPaperT133A01::draw_pixel_at(int x, int y, Color color) {
|
||||
|
||||
@@ -12,7 +12,12 @@ height of them; offset_height (under dimensions) is a property of the panel.
|
||||
from typing import Any
|
||||
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DATA_RATE, CONF_DIMENSIONS, CONF_OFFSET_HEIGHT
|
||||
from esphome.const import (
|
||||
CONF_DATA_RATE,
|
||||
CONF_DIMENSIONS,
|
||||
CONF_HEIGHT,
|
||||
CONF_OFFSET_HEIGHT,
|
||||
)
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import EpaperModel, ultrachip_resolution
|
||||
@@ -39,10 +44,11 @@ class UC8279(EpaperModel):
|
||||
|
||||
def validate_config(self, config: ConfigType) -> ConfigType:
|
||||
_width, height = self.get_dimensions(config)
|
||||
# The models' defaults fit, so this fails only with explicit dimensions, which always have a height
|
||||
if self.get_offset_height(config) + height > 0xFFFF:
|
||||
raise cv.Invalid(
|
||||
f"{CONF_OFFSET_HEIGHT} plus the panel height must not exceed {0xFFFF} gates",
|
||||
path=[CONF_DIMENSIONS, CONF_OFFSET_HEIGHT],
|
||||
path=[CONF_DIMENSIONS, CONF_HEIGHT],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
@@ -37,7 +37,10 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
|
||||
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
|
||||
}
|
||||
__attribute__((always_inline)) inline void yield() { vPortYield(); }
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { vTaskDelay(ms / portTICK_PERIOD_MS); }
|
||||
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) {
|
||||
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
|
||||
}
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(esp_timer_get_time()); }
|
||||
uint32_t millis();
|
||||
__attribute__((always_inline)) inline uint64_t millis_64() {
|
||||
|
||||
@@ -33,34 +33,18 @@ IRAM_ATTR InterruptLock::~InterruptLock() { portENABLE_INTERRUPTS(); }
|
||||
|
||||
LwIPLock::LwIPLock() {
|
||||
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
// When CONFIG_LWIP_TCPIP_CORE_LOCKING is enabled, lwIP uses a global mutex to protect
|
||||
// its internal state. Any thread can take this lock to safely access lwIP APIs.
|
||||
//
|
||||
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) returns true if the current thread
|
||||
// already holds the lwIP core lock. This prevents recursive locking attempts and
|
||||
// allows nested LwIPLock instances to work correctly.
|
||||
//
|
||||
// If we don't already hold the lock, acquire it. This will block until the lock
|
||||
// is available if another thread currently holds it.
|
||||
// A thread that already holds the core lock (lwIP took it for a tcpip_api_call or netif callback, or an
|
||||
// outer LwIPLock did) must not take it again, and must not release it when this nested guard ends.
|
||||
if (!sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
|
||||
LOCK_TCPIP_CORE();
|
||||
this->locked_ = true;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
LwIPLock::~LwIPLock() {
|
||||
#ifdef CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
// Only release the lwIP core lock if this thread currently holds it.
|
||||
//
|
||||
// sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) queries lwIP's internal lock
|
||||
// ownership tracking. It returns true only if the current thread is registered
|
||||
// as the lock holder.
|
||||
//
|
||||
// This check is essential because:
|
||||
// 1. We may not have acquired the lock in the constructor (if we already held it)
|
||||
// 2. The lock might have been released by other means between constructor and destructor
|
||||
// 3. Calling UNLOCK_TCPIP_CORE() without holding the lock causes undefined behavior
|
||||
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER)) {
|
||||
if (this->locked_) {
|
||||
UNLOCK_TCPIP_CORE();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -567,30 +567,46 @@ async def to_code(config: ConfigType) -> None:
|
||||
|
||||
request_bluetooth()
|
||||
|
||||
# Replace Bluedroid's only two sscanf callers so newlib's scanf engine is not
|
||||
# linked; see bluedroid_hex_wraps.cpp. IDF 6.0+ uses picolibc, not newlib.
|
||||
if (
|
||||
not CORE.using_arduino
|
||||
and idf_version() < cv.Version(6, 0, 0)
|
||||
and get_esp32_variant() not in ROM_SSCANF_VARIANTS
|
||||
# Replace Bluedroid's only two sscanf callers so the C library's scanf engine is
|
||||
# not linked; see bluedroid_hex_wraps.cpp. The ROM only provides sscanf for newlib,
|
||||
# which IDF 6.0 replaced with picolibc.
|
||||
if not CORE.using_arduino and (
|
||||
idf_version() >= cv.Version(6, 0, 0)
|
||||
or get_esp32_variant() not in ROM_SSCANF_VARIANTS
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_HEX_WRAPS")
|
||||
_wrap_bluedroid_symbols("btc_config_get_bin", "string_to_bdaddr")
|
||||
# The headers only feed bluedroid_hex_wraps.cpp's ESP-IDF drift checks
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_hex_wraps.cpp"))
|
||||
|
||||
# ESP-IDF 5.5.6 drops bond keys on re-encryption (see bluedroid_bond_keys.c). Needs the
|
||||
# native toolchain for Bluedroid's private headers; Windows response files lose them.
|
||||
# ESP-IDF 5.5.6 and 6.1.1 drop bond keys on re-encryption (see bluedroid_bond_keys.c). Needs
|
||||
# the native toolchain for Bluedroid's private headers; Windows response files lose them.
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and not IS_WINDOWS
|
||||
and cv.Version(5, 5, 6) <= idf_version() < cv.Version(6, 0, 0)
|
||||
and _drops_bond_keys(idf_version())
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_BOND_KEYS")
|
||||
_wrap_bluedroid_symbols("smp_check_auth_req", "btm_sec_clear_ble_keys")
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_bond_keys.c"))
|
||||
|
||||
# ESP-IDF 5.5.6 and 6.0.3 end GATT discovery on a response listing handles out of order
|
||||
# Bluedroid runs a queued MTU or execute write request that fails at once again until the BTU task stack
|
||||
# overflows (see bluedroid_gattc_queue.c); every ESP-IDF release so far. Private headers, as above.
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and not IS_WINDOWS
|
||||
and _has_gatt_client(CORE.config)
|
||||
):
|
||||
cg.add_define("USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE")
|
||||
_wrap_bluedroid_symbols(
|
||||
"bta_gattc_cfg_mtu",
|
||||
"bta_gattc_execute",
|
||||
"GATTC_ConfigureMTU",
|
||||
"GATTC_ExecuteWrite",
|
||||
)
|
||||
add_src_cmake(bluedroid_headers_cmake("bluedroid_gattc_queue.c"))
|
||||
|
||||
# ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end GATT discovery on a response listing handles out of order
|
||||
# (see bluedroid_gattc_order.cpp). It needs no Bluedroid headers, so any toolchain works.
|
||||
if _has_gatt_client(CORE.config) and _has_strict_handle_order(idf_version()):
|
||||
cg.add_define("USE_ESP32_BLE_GATTC_HANDLE_ORDER")
|
||||
@@ -667,11 +683,23 @@ def _has_gatt_client(config: ConfigType) -> bool:
|
||||
return "esp32_ble_tracker" in config or "esp32_ble_client" in config
|
||||
|
||||
|
||||
def _has_strict_handle_order(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order."""
|
||||
def _drops_bond_keys(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF clears a bonded device's keys when it re-encrypts."""
|
||||
return cv.Version(5, 5, 6) <= version < cv.Version(
|
||||
6, 0, 0
|
||||
) or version >= cv.Version(6, 0, 3)
|
||||
) or version >= cv.Version(6, 1, 1)
|
||||
|
||||
|
||||
def _has_strict_handle_order(version: cv.Version) -> bool:
|
||||
"""Whether this ESP-IDF rejects discovery responses whose handles are out of order.
|
||||
|
||||
ESP-IDF 6.1.0 was released before the check reached the 6.1 line.
|
||||
"""
|
||||
return (
|
||||
cv.Version(5, 5, 6) <= version < cv.Version(6, 0, 0)
|
||||
or cv.Version(6, 0, 3) <= version < cv.Version(6, 1, 0)
|
||||
or version >= cv.Version(6, 1, 1)
|
||||
)
|
||||
|
||||
|
||||
# ble_advertising.cpp is fully #ifdef'd on USE_ESP32_BLE_ADVERTISING, set
|
||||
@@ -681,6 +709,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_defines(
|
||||
"ble_advertising.cpp": "USE_ESP32_BLE_ADVERTISING",
|
||||
"bluedroid_hex_wraps.cpp": "USE_ESP32_BLE_BLUEDROID_HEX_WRAPS",
|
||||
"bluedroid_bond_keys.c": "USE_ESP32_BLE_BLUEDROID_BOND_KEYS",
|
||||
"bluedroid_gattc_queue.c": "USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE",
|
||||
"bluedroid_gattc_order.cpp": "USE_ESP32_BLE_GATTC_HANDLE_ORDER",
|
||||
}
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6).
|
||||
// Linker wraps that keep a bonded device's keys when it re-encrypts without pairing again (ESP-IDF 5.5.6, 6.1.1).
|
||||
// Same guard as espressif/esp-idf#19322; drop once ESPHome uses an ESP-IDF release that contains it.
|
||||
// C, because Bluedroid's btm_ble_int.h does not close its extern "C" block.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Linker wrap that puts a GATT discovery response back in handle order before Bluedroid parses it.
|
||||
// ESP-IDF 5.5.6 and 6.0.3 end the whole discovery when a peer lists handles out of order (esphome#22518), which
|
||||
// ESP-IDF 5.5.6, 6.0.3 and 6.1.1 end the whole discovery when a peer lists handles out of order (esphome#22518), which
|
||||
// earlier releases, Android and BlueZ accept.
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// Linker wraps that stop Bluedroid running a failed queued MTU or execute write request again until the BTU task
|
||||
// stack overflows (esphome#17954). The same fix as removing the command from p_cmd_list in bta_gattc_act.c before
|
||||
// the failure path pops the queue; drop once an ESP-IDF release has it.
|
||||
|
||||
// Compiled only with Bluedroid's private headers (bluedroid_headers_cmake); static analysis skips it
|
||||
#ifdef USE_ESP32_BLE_BLUEDROID_HEADERS
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "bta_gattc_int.h"
|
||||
#include "osi/list.h"
|
||||
|
||||
// The command bta_gattc_cfg_mtu() or bta_gattc_execute() is running, NULL outside them
|
||||
static tBTA_GATTC_CLCB *running_clcb = NULL;
|
||||
static tBTA_GATTC_DATA *running_cmd = NULL;
|
||||
|
||||
void __real_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
|
||||
void __real_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data);
|
||||
tGATT_STATUS __real_GATTC_ConfigureMTU(UINT16 conn_id);
|
||||
tGATT_STATUS __real_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute);
|
||||
|
||||
// Runs on the Bluetooth host task; the failure path pops the queue again, so this nests
|
||||
static void run_command(void (*real)(tBTA_GATTC_CLCB *, tBTA_GATTC_DATA *), tBTA_GATTC_CLCB *p_clcb,
|
||||
tBTA_GATTC_DATA *p_data) {
|
||||
tBTA_GATTC_CLCB *const outer_clcb = running_clcb;
|
||||
tBTA_GATTC_DATA *const outer_cmd = running_cmd;
|
||||
running_clcb = p_clcb;
|
||||
running_cmd = p_data;
|
||||
real(p_clcb, p_data);
|
||||
running_clcb = outer_clcb;
|
||||
running_cmd = outer_cmd;
|
||||
}
|
||||
|
||||
// The send failed, so the caller clears p_q_cmd and pops the queue. A command popped from p_cmd_list is still its
|
||||
// head and would run again; remove (and free) it first. A command not from the queue is not in it: a no-op.
|
||||
static void drop_failed_command(void) {
|
||||
if (running_clcb != NULL && running_clcb->p_cmd_list != NULL && running_clcb->p_q_cmd == running_cmd) {
|
||||
list_remove(running_clcb->p_cmd_list, running_cmd);
|
||||
}
|
||||
}
|
||||
|
||||
void __wrap_bta_gattc_cfg_mtu(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
|
||||
run_command(__real_bta_gattc_cfg_mtu, p_clcb, p_data);
|
||||
}
|
||||
|
||||
void __wrap_bta_gattc_execute(tBTA_GATTC_CLCB *p_clcb, tBTA_GATTC_DATA *p_data) {
|
||||
run_command(__real_bta_gattc_execute, p_clcb, p_data);
|
||||
}
|
||||
|
||||
// The failure checks are the ones bta_gattc_cfg_mtu() and bta_gattc_execute() make
|
||||
tGATT_STATUS __wrap_GATTC_ConfigureMTU(UINT16 conn_id) {
|
||||
const tGATT_STATUS status = __real_GATTC_ConfigureMTU(conn_id);
|
||||
if (status != GATT_SUCCESS && status != GATT_CMD_STARTED) {
|
||||
drop_failed_command();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
tGATT_STATUS __wrap_GATTC_ExecuteWrite(UINT16 conn_id, BOOLEAN is_execute) {
|
||||
const tGATT_STATUS status = __real_GATTC_ExecuteWrite(conn_id, is_execute);
|
||||
if (status != BTA_GATT_OK) {
|
||||
drop_failed_command();
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
#endif // USE_ESP32_BLE_BLUEDROID_HEADERS
|
||||
@@ -1,4 +1,5 @@
|
||||
// Linker wraps for the only two sscanf callers in Bluedroid, so newlib's scanf engine (~16 KB) is not linked.
|
||||
// Linker wraps for the only two sscanf callers in Bluedroid, so the C library's scanf engine is not linked
|
||||
// (~16 KB with newlib, ~4 KB with picolibc).
|
||||
// Same parsing as espressif/esp-idf#19235; drop once ESPHome uses an ESP-IDF release that contains it.
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
|
||||
@@ -18,10 +18,12 @@ from esphome.components.esp32 import (
|
||||
VARIANT_ESP32S31,
|
||||
add_idf_sdkconfig_option,
|
||||
get_esp32_variant,
|
||||
idf_version,
|
||||
)
|
||||
from esphome.components.openthread.const import CONF_POLL_PERIOD
|
||||
from esphome.components.psram import DOMAIN as PSRAM_DOMAIN
|
||||
from esphome.components.zigbee import DOMAIN as ZIGBEE_DOMAIN
|
||||
from esphome.config_helpers import filter_source_files_from_defines
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ID, CONF_OPENTHREAD
|
||||
from esphome.core import CORE
|
||||
@@ -32,6 +34,10 @@ from . import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
FILTER_SOURCE_FILES = filter_source_files_from_defines(
|
||||
{"tick_overflow_guard.cpp": "USE_ESP32_PM_TICK_OVERFLOW_GUARD"}
|
||||
)
|
||||
|
||||
CODEOWNERS = ["@rwrozelle"]
|
||||
DEPENDENCIES = ["esp32"]
|
||||
|
||||
@@ -187,6 +193,15 @@ async def to_code(config: ConfigType) -> None:
|
||||
add_idf_sdkconfig_option(
|
||||
"CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP", config[CONF_IDLE_TIME_BEFORE_SLEEP]
|
||||
)
|
||||
# Stop vTaskStepTick asserting on a tick overshoot after light sleep; built into
|
||||
# IDF 6.0.1, backported by tick_overflow_guard.cpp before that.
|
||||
if idf_version() >= cv.Version(6, 0, 1):
|
||||
add_idf_sdkconfig_option("CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION", True)
|
||||
else:
|
||||
cg.add_define("USE_ESP32_PM_TICK_OVERFLOW_GUARD")
|
||||
for symbol in ("vApplicationSleep", "vTaskStepTick"):
|
||||
cg.add_build_flag(f"-Wl,--wrap={symbol}")
|
||||
cg.add_build_flag(f"-Wl,--undefined=__wrap_{symbol}")
|
||||
if config[CONF_POWER_DOWN_PERIPHERALS]:
|
||||
add_idf_sdkconfig_option("CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP", True)
|
||||
if config[CONF_POWER_DOWN_FLASH]:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "esphome/core/defines.h"
|
||||
#ifdef USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace esphome::esp32_power_management {}
|
||||
|
||||
// IDF drops tickless idle on chips without light sleep support (ESP32-H4 and -H21 on 5.5), and then
|
||||
// vApplicationSleep() does not exist
|
||||
#if CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
|
||||
// Backport of IDF 6.0.1 CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION: clamp a small tick overshoot
|
||||
// after light sleep so vTaskStepTick() does not assert.
|
||||
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
|
||||
extern "C" {
|
||||
|
||||
void __real_vApplicationSleep(TickType_t expected_idle_time);
|
||||
void __real_vTaskStepTick(TickType_t ticks_to_jump);
|
||||
|
||||
// Same default as IDF's CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_TOLERANCE; a larger overshoot still asserts
|
||||
static constexpr TickType_t TICK_OVERFLOW_TOLERANCE = 2;
|
||||
static TickType_t expected_idle_time[portNUM_PROCESSORS];
|
||||
|
||||
void __wrap_vApplicationSleep(TickType_t expected) {
|
||||
expected_idle_time[xPortGetCoreID()] = expected;
|
||||
__real_vApplicationSleep(expected);
|
||||
}
|
||||
|
||||
// Only pm_impl.c calls vTaskStepTick(), from inside vApplicationSleep() on the same core
|
||||
void __wrap_vTaskStepTick(TickType_t ticks) {
|
||||
const TickType_t expected = expected_idle_time[xPortGetCoreID()];
|
||||
if (ticks > expected && ticks <= expected + TICK_OVERFLOW_TOLERANCE)
|
||||
ticks = expected;
|
||||
__real_vTaskStepTick(ticks);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming,cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
#endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
#endif // USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
@@ -7,6 +7,8 @@
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/components/network/ip_address.h"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#ifdef USE_ETHERNET
|
||||
|
||||
#ifdef USE_ESP32
|
||||
@@ -366,6 +368,9 @@ class EthernetComponent final : public Component {
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
StaticVector<EthernetIPStateListener *, ESPHOME_ETHERNET_IP_STATE_LISTENERS> ip_state_listeners_;
|
||||
#ifdef USE_ESP32
|
||||
std::atomic<uint8_t> ip_state_pending_{0};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef USE_ETHERNET_CONNECT_TRIGGER
|
||||
|
||||
@@ -129,6 +129,14 @@ void EthernetComponent::log_error_and_mark_failed_(esp_err_t err, const char *me
|
||||
void EthernetComponent::loop() {
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
// The IP events arrive on the event task; the listeners publish states, so notify them here
|
||||
if (this->ip_state_pending_.load(std::memory_order_acquire) != 0) {
|
||||
this->ip_state_pending_.store(0, std::memory_order_relaxed);
|
||||
this->notify_ip_state_listeners_();
|
||||
}
|
||||
#endif
|
||||
|
||||
switch (this->state_) {
|
||||
case EthernetComponentState::STOPPED:
|
||||
if (this->started_) {
|
||||
@@ -770,7 +778,8 @@ void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base
|
||||
event_name = "ETH connected";
|
||||
// For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
|
||||
#if defined(USE_ETHERNET_IP_STATE_LISTENERS) && defined(USE_ETHERNET_MANUAL_IP)
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
global_eth_component->enable_loop_soon_any_context();
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6
|
||||
// Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
|
||||
@@ -798,6 +807,9 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
const esp_netif_ip_info_t *ip_info = &event->ip_info;
|
||||
ESP_LOGV(TAG, "[Ethernet event] ETH Got IP " IPSTR, IP2STR(&ip_info->ip));
|
||||
global_eth_component->got_ipv4_address_ = true;
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ = global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
@@ -805,9 +817,6 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
|
||||
global_eth_component->connected_ = true;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if USE_NETWORK_IPV6
|
||||
@@ -819,6 +828,9 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
// after a link flap fires another event for the same address.
|
||||
struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
|
||||
global_eth_component->ipv6_count_ = esp_netif_get_all_ip6(global_eth_component->eth_netif_, if_ip6s);
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->ip_state_pending_.store(1, std::memory_order_release);
|
||||
#endif
|
||||
#if (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
|
||||
global_eth_component->connected_ =
|
||||
global_eth_component->got_ipv4_address_ && (global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
|
||||
@@ -827,9 +839,6 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
|
||||
global_eth_component->connected_ = global_eth_component->got_ipv4_address_;
|
||||
global_eth_component->enable_loop_soon_any_context(); // Enable loop when connection state changes
|
||||
#endif
|
||||
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
|
||||
global_eth_component->notify_ip_state_listeners_();
|
||||
#endif
|
||||
}
|
||||
#endif /* USE_NETWORK_IPV6 */
|
||||
|
||||
|
||||
@@ -50,6 +50,9 @@ void IRAM_ATTR ISRInternalGPIOPin::clear_interrupt() {
|
||||
auto *arg = reinterpret_cast<ISRPinArg *>(arg_);
|
||||
ESP_LOGD(TAG, "Clearing interrupt for pin %d", arg->pin);
|
||||
}
|
||||
void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
// pass
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
|
||||
@@ -102,6 +102,14 @@ ErrorCode ArduinoI2CBus::write_readv(uint8_t address, const uint8_t *write_buffe
|
||||
|
||||
uint8_t status = 0;
|
||||
if (write_count != 0 || read_count == 0) {
|
||||
#ifdef USE_RP2
|
||||
// arduino-pico leaves a transmission open when a write overflows its buffer, and every later
|
||||
// beginTransmission() is then ignored, so refuse the write before starting it
|
||||
if (write_count > WIRE_BUFFER_SIZE) {
|
||||
ESP_LOGVV(TAG, "TX of %zu bytes exceeds the %u byte Wire buffer", write_count, WIRE_BUFFER_SIZE);
|
||||
return ERROR_TOO_LARGE;
|
||||
}
|
||||
#endif
|
||||
this->wire_->beginTransmission(address);
|
||||
size_t ret = this->wire_->write(write_buffer, write_count);
|
||||
if (ret != write_count) {
|
||||
@@ -176,23 +184,18 @@ void ArduinoI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// From the specification:
|
||||
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
|
||||
// device that held the bus LOW should release it sometime within
|
||||
// those nine clocks."
|
||||
// We don't really have to detect if SDA is stuck low. We'll simply send
|
||||
// nine clock pulses here, just in case SDA is stuck. Actual checks on
|
||||
// the SDA line status will be done after the clock pulses.
|
||||
|
||||
// Make sure that switching to output mode will make SCL low, just in
|
||||
// case other code has setup the pin for a HIGH signal.
|
||||
digitalWrite(this->scl_pin_, LOW); // NOLINT
|
||||
// Activate input and pull up resistor for the SDA pin, so it can be read during the pulses.
|
||||
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
|
||||
|
||||
delayMicroseconds(half_period_usec);
|
||||
for (auto i = 0; i < 9; i++) {
|
||||
// Release pull up resistor and switch to output to make the signal LOW.
|
||||
pinMode(this->scl_pin_, INPUT); // NOLINT
|
||||
pinMode(this->scl_pin_, OUTPUT); // NOLINT
|
||||
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
|
||||
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
|
||||
for (auto i = 0; i < 9 && digitalRead(this->sda_pin_) == LOW; i++) { // NOLINT
|
||||
// Drive LOW. Set the level while the pin is a plain input: on RP2040 a write to an
|
||||
// INPUT_PULLUP pin drives it, which would leave SCL low if the loop never runs.
|
||||
pinMode(this->scl_pin_, INPUT); // NOLINT
|
||||
digitalWrite(this->scl_pin_, LOW); // NOLINT
|
||||
pinMode(this->scl_pin_, OUTPUT); // NOLINT
|
||||
delayMicroseconds(half_period_usec);
|
||||
|
||||
// Release output and activate pull up resistor to make the signal HIGH.
|
||||
@@ -219,14 +222,7 @@ void ArduinoI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// Activate input and pull resistor for the SDA pin, so we can verify
|
||||
// that SDA is pulled HIGH in the following step.
|
||||
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
|
||||
digitalWrite(this->sda_pin_, LOW); // NOLINT
|
||||
|
||||
// By now, any stuck device ought to have sent all remaining bits of its
|
||||
// transaction, meaning that it should have freed up the SDA line, resulting
|
||||
// in SDA being pulled up.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
if (digitalRead(this->sda_pin_) == LOW) { // NOLINT
|
||||
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
|
||||
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
|
||||
@@ -238,15 +234,13 @@ void ArduinoI2CBus::recover_() {
|
||||
// a START or repeated START condition such that they all anticipate
|
||||
// the sending of a target address, even if these START conditions are
|
||||
// not positioned according to the proper format."
|
||||
// While the 9 clock pulses from above might have drained all bits of a
|
||||
// single byte within a transaction, a device might have more bytes to
|
||||
// transmit. So here we'll generate a START condition to snap the device
|
||||
// out of this state.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// SCL and SDA are already high at this point, so we can generate a START
|
||||
// condition by making the SDA signal LOW.
|
||||
delayMicroseconds(half_period_usec);
|
||||
pinMode(this->sda_pin_, INPUT); // NOLINT
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
pinMode(this->sda_pin_, INPUT); // NOLINT
|
||||
digitalWrite(this->sda_pin_, LOW); // NOLINT
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
|
||||
// From the specification:
|
||||
// "A START condition immediately followed by a STOP condition (void
|
||||
|
||||
@@ -346,14 +346,9 @@ void IDFI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// From the specification:
|
||||
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
|
||||
// device that held the bus LOW should release it sometime within
|
||||
// those nine clocks."
|
||||
// We don't really have to detect if SDA is stuck low. We'll simply send
|
||||
// nine clock pulses here, just in case SDA is stuck. Actual checks on
|
||||
// the SDA line status will be done after the clock pulses.
|
||||
for (auto i = 0; i < 9; i++) {
|
||||
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
|
||||
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
|
||||
for (auto i = 0; i < 9 && gpio_get_level(sda_pin) == 0; i++) {
|
||||
gpio_set_level(scl_pin, 0);
|
||||
delayMicroseconds(half_period_usec);
|
||||
gpio_set_level(scl_pin, 1);
|
||||
@@ -378,9 +373,7 @@ void IDFI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// By now, any stuck device ought to have sent all remaining bits of its
|
||||
// transaction, meaning that it should have freed up the SDA line, resulting
|
||||
// in SDA being pulled up.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
if (gpio_get_level(sda_pin) == 0) {
|
||||
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
|
||||
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
|
||||
@@ -392,10 +385,7 @@ void IDFI2CBus::recover_() {
|
||||
// a START or repeated START condition such that they all anticipate
|
||||
// the sending of a target address, even if these START conditions are
|
||||
// not positioned according to the proper format."
|
||||
// While the 9 clock pulses from above might have drained all bits of a
|
||||
// single byte within a transaction, a device might have more bytes to
|
||||
// transmit. So here we'll generate a START condition to snap the device
|
||||
// out of this state.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// SCL and SDA are already high at this point, so we can generate a START
|
||||
// condition by making the SDA signal LOW.
|
||||
delayMicroseconds(half_period_usec);
|
||||
|
||||
@@ -387,6 +387,7 @@ def _configure_lwip(config: dict) -> None:
|
||||
MEMP_NUM_NETCONN 0 10 38 4***** =sum =sum
|
||||
MEMP_NUM_NETBUF 0 2 16 2***** 8 4
|
||||
MEMP_NUM_TCPIP_MSG_INPKT 4 8 16 8***** 12 8
|
||||
TCP_MSL (ms) 60000† 60000 250 60000 60000 250
|
||||
|
||||
* ESP8266/ESP32/LN882H use MEM_LIBC_MALLOC=1 (system heap, no dedicated pool).
|
||||
ESP8266/ESP32 also use MEMP_MEM_MALLOC=1 (MEMP pools from heap, not static).
|
||||
@@ -394,6 +395,8 @@ def _configure_lwip(config: dict) -> None:
|
||||
*** BK LT overlay: MAX_SOCKETS_UDP+2+1 = 25.
|
||||
**** RTL/LN LT overlay overrides to flat 7.
|
||||
***** Not defined in RTL SDK — lwIP opt.h defaults shown.
|
||||
† ESP8266's lwIP also caps TIME_WAIT at 5 PCBs; LibreTiny's stock lwIP has no
|
||||
cap once MEMP_MEM_MALLOC=1.
|
||||
"dynamic" = auto-calculated from component socket registrations via
|
||||
socket.get_socket_counts() with minimums of 8 TCP / 6 UDP.
|
||||
"""
|
||||
@@ -470,6 +473,10 @@ def _configure_lwip(config: dict) -> None:
|
||||
# both ship with MEMP_MEM_MALLOC=1.
|
||||
lwip_opts.append("MEM_LIBC_MALLOC=1")
|
||||
lwip_opts.append("MEMP_MEM_MALLOC=1")
|
||||
# With MEMP_MEM_MALLOC=1, MEMP_NUM_TCP_PCB no longer limits PCBs, so every
|
||||
# connection the device closes keeps its ~176 B PCB on the heap for TIME_WAIT
|
||||
# (2 * TCP_MSL, 120 s by default). BK's lwIP port already uses 250.
|
||||
lwip_opts.append("TCP_MSL=250")
|
||||
|
||||
# BK72XX-specific: PBUF_POOL_SIZE override
|
||||
# BK SDK "reduced plan" sets this to only 3 — too few for multiple
|
||||
|
||||
@@ -90,7 +90,15 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() {
|
||||
return xTaskGetCurrentTaskHandle() == esphome_main_task_handle;
|
||||
}
|
||||
__attribute__((always_inline)) inline void yield() { ::yield(); }
|
||||
#if defined(USE_LIBRETINY_VARIANT_RTL8710B)
|
||||
// Already sleeps to a deadline (rtl8710b_micros.c)
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { ::delay(ms); }
|
||||
#else
|
||||
// vTaskDelay() counts the partial tick, so one more tick makes the wait at least ms
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) {
|
||||
vTaskDelay(ms == 0 ? 0 : (ms + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS + 1);
|
||||
}
|
||||
#endif
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return static_cast<uint32_t>(::micros()); }
|
||||
|
||||
// Per-variant millis() fast path — matches MillisInternal::get().
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
|
||||
#if defined(USE_ESP32) && defined(USE_NETWORK)
|
||||
#include <sdkconfig.h>
|
||||
#if defined(CONFIG_LWIP_TCPIP_CORE_LOCKING) && defined(USE_ESPHOME_TASK_LOG_BUFFER)
|
||||
#include "lwip/sys.h"
|
||||
#define USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace esphome::logger {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "logger");
|
||||
@@ -42,6 +50,16 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
|
||||
// Fast path: main thread, no recursion (99.9% of all logs)
|
||||
// Pass nullptr for thread_name since we already know this is the main task
|
||||
if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
|
||||
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
|
||||
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
|
||||
// to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
|
||||
// can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
|
||||
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
|
||||
[[unlikely]] {
|
||||
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
this->log_message_to_buffer_and_send_(this->main_task_recursion_guard_, level, tag, line, format, args, nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
|
||||
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
|
||||
|
||||
time_t rawtime;
|
||||
time(&rawtime);
|
||||
::time(&rawtime);
|
||||
struct tm timeinfo;
|
||||
localtime_r(&rawtime, &timeinfo); // Thread-safe version
|
||||
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from esphome.const import (
|
||||
UNIT_CELSIUS,
|
||||
UNIT_MICROTESLA,
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@functionpointer"]
|
||||
@@ -148,3 +149,5 @@ async def to_code(config: ConfigType) -> None:
|
||||
await cg.add_pin(var.set_drdy_gpio, config.get(CONF_DRDY_PIN))
|
||||
|
||||
cg.add_library("functionpointer/arduino-MLX90393", "1.0.2")
|
||||
if CORE.using_arduino:
|
||||
cg.add_library("Wire", None)
|
||||
@@ -806,10 +806,10 @@ void ModbusServerHub::process_modbus_client_frame_(uint8_t address, uint8_t func
|
||||
bool Modbus::send_frame_(const ModbusFrame &frame) {
|
||||
int32_t tx_delay_remaining = this->tx_delay_remaining();
|
||||
if (tx_delay_remaining > 0) {
|
||||
// Yield the whole-ms part: delay() never blocks past the request on FreeRTOS, and only slightly
|
||||
// over elsewhere, which just lengthens the gap. The recompute below makes the remainder exact.
|
||||
if (tx_delay_remaining >= (int32_t) US_PER_MS) {
|
||||
delay(tx_delay_remaining / US_PER_MS);
|
||||
// Yield all but the last whole ms: delay() can block up to a tick past the request, and a tick
|
||||
// longer than 1 ms just lengthens the gap. The recompute below makes the remainder exact.
|
||||
if (tx_delay_remaining >= (int32_t) (2 * US_PER_MS)) {
|
||||
delay(tx_delay_remaining / US_PER_MS - 1);
|
||||
tx_delay_remaining = this->tx_delay_remaining();
|
||||
}
|
||||
if (tx_delay_remaining > 0)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
#include "at_reply.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <strings.h>
|
||||
|
||||
namespace esphome::modem {
|
||||
|
||||
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole) {
|
||||
const size_t capacity = size - 1;
|
||||
if (whole) {
|
||||
len = 0;
|
||||
}
|
||||
bool dropped = false;
|
||||
if (data_len > capacity) {
|
||||
memcpy(buf, data + data_len - capacity, capacity);
|
||||
len = capacity;
|
||||
dropped = true;
|
||||
} else {
|
||||
if (len + data_len > capacity) {
|
||||
const size_t drop = len + data_len - capacity;
|
||||
memmove(buf, buf + drop, len - drop);
|
||||
len -= drop;
|
||||
dropped = true;
|
||||
}
|
||||
memcpy(buf + len, data, data_len);
|
||||
len += data_len;
|
||||
}
|
||||
buf[len] = '\0';
|
||||
return dropped;
|
||||
}
|
||||
|
||||
ReplyEnd reply_end(const char *data, size_t len, bool skip_first) {
|
||||
const char *end = data + len;
|
||||
const char *line = data;
|
||||
if (skip_first) {
|
||||
const auto *newline = static_cast<const char *>(memchr(data, '\n', len));
|
||||
line = newline != nullptr ? newline + 1 : end;
|
||||
}
|
||||
while (line < end) {
|
||||
const auto *newline = static_cast<const char *>(memchr(line, '\n', end - line));
|
||||
if (newline == nullptr) {
|
||||
break; // the line has not ended yet
|
||||
}
|
||||
size_t size = newline - line;
|
||||
if (size != 0 && line[size - 1] == '\r') {
|
||||
size--;
|
||||
}
|
||||
if (size == 2 && memcmp(line, "OK", 2) == 0) {
|
||||
return ReplyEnd::REPLY_END_OK;
|
||||
}
|
||||
// esp_modem drops a CMUX frame without a line end, so the ": <reason>" part may be missing
|
||||
if ((size == 5 && memcmp(line, "ERROR", 5) == 0) || (size >= 10 && memcmp(line, "+CME ERROR", 10) == 0) ||
|
||||
(size >= 10 && memcmp(line, "+CMS ERROR", 10) == 0)) {
|
||||
return ReplyEnd::REPLY_END_ERROR;
|
||||
}
|
||||
line = newline + 1;
|
||||
}
|
||||
return ReplyEnd::REPLY_END_NONE;
|
||||
}
|
||||
|
||||
size_t flatten_reply(char *reply, size_t len) {
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
if (reply[i] == '\r' || reply[i] == '\n') {
|
||||
reply[i] = ' ';
|
||||
}
|
||||
}
|
||||
while (len != 0 && reply[len - 1] == ' ') {
|
||||
len--;
|
||||
}
|
||||
if (len >= 2 && memcmp(reply + len - 2, "OK", 2) == 0 && (len == 2 || reply[len - 3] == ' ')) {
|
||||
len -= 2;
|
||||
while (len != 0 && reply[len - 1] == ' ') {
|
||||
len--;
|
||||
}
|
||||
}
|
||||
size_t start = 0;
|
||||
while (start < len && reply[start] == ' ') {
|
||||
start++;
|
||||
}
|
||||
len -= start;
|
||||
memmove(reply, reply + start, len);
|
||||
reply[len] = '\0';
|
||||
return len;
|
||||
}
|
||||
|
||||
int registration_from_reply(const char *reply, const char *prefix) {
|
||||
const size_t prefix_len = strlen(prefix);
|
||||
for (const char *line = strstr(reply, prefix); line != nullptr; line = strstr(line + 1, prefix)) {
|
||||
const char *start = line + prefix_len;
|
||||
char *end = nullptr;
|
||||
strtol(start, &end, 10);
|
||||
if (end == start || *end != ',') {
|
||||
continue;
|
||||
}
|
||||
start = end + 1;
|
||||
const auto stat = static_cast<int32_t>(strtol(start, &end, 10));
|
||||
if (end != start) {
|
||||
return stat;
|
||||
}
|
||||
}
|
||||
return REGISTRATION_UNKNOWN;
|
||||
}
|
||||
|
||||
int merge_registration(int lte, int legacy) {
|
||||
// A multimode modem can be registered or still searching on one network type while the other refuses it
|
||||
if (is_registered(lte)) {
|
||||
return lte;
|
||||
}
|
||||
if (is_registered(legacy)) {
|
||||
return legacy;
|
||||
}
|
||||
// A definite answer from one query outweighs a timeout of the other
|
||||
if (lte == REGISTRATION_SEARCHING || legacy == REGISTRATION_SEARCHING) {
|
||||
return REGISTRATION_SEARCHING;
|
||||
}
|
||||
if (lte == REGISTRATION_DENIED || legacy == REGISTRATION_DENIED) {
|
||||
return REGISTRATION_DENIED;
|
||||
}
|
||||
if (lte >= 0 || legacy >= 0) {
|
||||
return lte >= 0 ? lte : legacy;
|
||||
}
|
||||
if (lte == REGISTRATION_NO_ANSWER || legacy == REGISTRATION_NO_ANSWER) {
|
||||
return REGISTRATION_NO_ANSWER;
|
||||
}
|
||||
if (lte == REGISTRATION_UNSUPPORTED && legacy == REGISTRATION_UNSUPPORTED) {
|
||||
return REGISTRATION_UNSUPPORTED;
|
||||
}
|
||||
return REGISTRATION_UNKNOWN;
|
||||
}
|
||||
|
||||
bool reply_names_unsupported(const char *reply) {
|
||||
static constexpr char PREFIX[] = "+CME ERROR:";
|
||||
static constexpr char TEXT[] = "operation not supported";
|
||||
const char *code = strstr(reply, PREFIX);
|
||||
if (code == nullptr) {
|
||||
return false;
|
||||
}
|
||||
code += sizeof(PREFIX) - 1;
|
||||
while (*code == ' ') {
|
||||
code++;
|
||||
}
|
||||
return strncasecmp(code, TEXT, sizeof(TEXT) - 1) == 0 || (code[0] == '4' && !isdigit(code[1]));
|
||||
}
|
||||
|
||||
const char *sim_status(char *reply) {
|
||||
static constexpr char PREFIX[] = "+CPIN:";
|
||||
char *status = strstr(reply, PREFIX);
|
||||
if (status == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
status += sizeof(PREFIX) - 1;
|
||||
while (*status == ' ') {
|
||||
status++;
|
||||
}
|
||||
// A URC in the same reply follows on its own line, which flatten_reply() turned into two spaces
|
||||
char *end = strstr(status, " ");
|
||||
if (end != nullptr) {
|
||||
*end = '\0';
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace esphome::modem
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
// Parsers for raw AT replies; free of esp_modem so they build and run in host unit tests
|
||||
namespace esphome::modem {
|
||||
|
||||
enum class ReplyEnd : uint8_t {
|
||||
REPLY_END_NONE, // no complete final result line yet
|
||||
REPLY_END_OK, // an OK line
|
||||
REPLY_END_ERROR, // an ERROR, +CME ERROR: or +CMS ERROR: line
|
||||
};
|
||||
|
||||
// AT+CEREG? and AT+CREG? <stat> values (3GPP TS 27.007)
|
||||
static constexpr int REGISTRATION_NOT_SEARCHING = 0;
|
||||
static constexpr int REGISTRATION_HOME = 1;
|
||||
static constexpr int REGISTRATION_SEARCHING = 2;
|
||||
static constexpr int REGISTRATION_DENIED = 3;
|
||||
static constexpr int REGISTRATION_REPORTED_UNKNOWN = 4;
|
||||
static constexpr int REGISTRATION_ROAMING = 5;
|
||||
static constexpr int REGISTRATION_SMS_ONLY_HOME = 6;
|
||||
static constexpr int REGISTRATION_SMS_ONLY_ROAMING = 7;
|
||||
static constexpr int REGISTRATION_EMERGENCY_ONLY = 8;
|
||||
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_HOME = 9;
|
||||
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_ROAMING = 10;
|
||||
// Results beyond the 3GPP values
|
||||
static constexpr int REGISTRATION_UNKNOWN = -1; // no readable answer
|
||||
static constexpr int REGISTRATION_UNSUPPORTED = -2; // the query is not supported
|
||||
static constexpr int REGISTRATION_NO_ANSWER = -3; // the query timed out
|
||||
|
||||
/// Registered on a network, so the data attach can be requested. SMS only and "CSFB not preferred" limit the
|
||||
/// circuit switched side, not the packet data attach; emergency only (8) is not a registration.
|
||||
inline bool is_registered(int registration) {
|
||||
return registration == REGISTRATION_HOME || registration == REGISTRATION_ROAMING ||
|
||||
(registration >= REGISTRATION_SMS_ONLY_HOME && registration <= REGISTRATION_SMS_ONLY_ROAMING) ||
|
||||
(registration >= REGISTRATION_CSFB_NOT_PREFERRED_HOME &&
|
||||
registration <= REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
|
||||
}
|
||||
|
||||
/// Add data to the reply in buf (size includes the terminator, len is the current length). With whole, data is
|
||||
/// everything received so far (UART) and replaces the reply; otherwise it is one new CMUX frame and is appended. A
|
||||
/// reply longer than the buffer keeps its newest bytes, where the final line is. Returns true when bytes were dropped.
|
||||
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole);
|
||||
|
||||
/// How the reply ends. Only a complete final result line counts, so ERROR inside a payload line does not; a +CME ERROR
|
||||
/// line counts even without its reason, which a dropped CMUX frame can take away. With
|
||||
/// skip_first, the first line is a cut-off fragment and is ignored.
|
||||
ReplyEnd reply_end(const char *data, size_t len, bool skip_first);
|
||||
|
||||
/// Puts a raw reply on one line for the log and drops the final OK; returns the new length
|
||||
size_t flatten_reply(char *reply, size_t len);
|
||||
|
||||
/// The <stat> after the first comma of the "<n>,<stat>" line starting with prefix (+CREG: and friends), or
|
||||
/// REGISTRATION_UNKNOWN; a one-field line is an unsolicited notification and is skipped
|
||||
int registration_from_reply(const char *reply, const char *prefix);
|
||||
|
||||
/// The state that tells most from the AT+CEREG? (LTE) and AT+CREG? (2G and 3G) results
|
||||
int merge_registration(int lte, int legacy);
|
||||
|
||||
/// Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
|
||||
bool reply_names_unsupported(const char *reply);
|
||||
|
||||
/// The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr
|
||||
const char *sim_status(char *reply);
|
||||
|
||||
} // namespace esphome::modem
|
||||
@@ -1,5 +1,6 @@
|
||||
#ifdef USE_ESP32
|
||||
#include "modem_component.h"
|
||||
#include "at_reply.h"
|
||||
#include "soc/soc_caps.h"
|
||||
#include <driver/uart.h>
|
||||
|
||||
@@ -42,6 +43,14 @@ static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
|
||||
// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
|
||||
static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
|
||||
static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
|
||||
// A modem in command mode answers the ATE0 sent before the mode detection within this time
|
||||
static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
|
||||
// The +++ escape needs a second of silence before it; esp_modem waits for the answer after it
|
||||
static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
|
||||
// A SIM7670 left in CMUX by an ESP reset ignores every frame until this many flag bytes overflow its receive buffer;
|
||||
// it then reinitialises its AT channel within about 2 s
|
||||
static constexpr size_t CMUX_FLUSH_BYTES = 4096;
|
||||
static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
|
||||
// How long the task waits for the main loop to run on_sync before attaching
|
||||
static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
|
||||
// esp_modem's command strings and the log lines are built on this stack
|
||||
@@ -56,7 +65,14 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
|
||||
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
|
||||
static constexpr uint32_t ATTACH_POLL_MS = 4000;
|
||||
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
|
||||
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
|
||||
static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15; // about a minute of polls
|
||||
// AT+CGATT=1: SIMCom documents up to 75 s, but a SIM7080G that is not registered yet held it for 141 s
|
||||
static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
|
||||
// SIM status polls that fail before a warning, and between repeats of it
|
||||
static constexpr uint8_t SIM_WARN_AFTER = 10;
|
||||
static constexpr uint8_t SIM_WARN_EVERY = 60;
|
||||
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
|
||||
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
|
||||
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
|
||||
static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
|
||||
static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
|
||||
@@ -72,8 +88,22 @@ static const LogString *state_to_str(ModemState state) {
|
||||
// Indexed by ModemFault
|
||||
PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
|
||||
"init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
|
||||
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
|
||||
"Modem teardown failed");
|
||||
"PIN record not saved", "APN or radio setup failed", "No network attachment",
|
||||
"Network registration denied", "PPP link failed", "Modem teardown failed");
|
||||
|
||||
// Indexed by the AT+CEREG? <stat> value
|
||||
PROGMEM_STRING_TABLE(RegistrationStrings, "not searching", "registered", "searching", "denied", "unknown", "roaming",
|
||||
"registered for SMS only", "roaming for SMS only", "emergency only",
|
||||
"registered, CSFB not preferred", "roaming, CSFB not preferred", "other");
|
||||
static const LogString *registration_to_str(int registration) {
|
||||
if (registration == REGISTRATION_UNSUPPORTED) {
|
||||
return LOG_STR("not supported");
|
||||
}
|
||||
if (registration < 0) {
|
||||
return LOG_STR("not reported");
|
||||
}
|
||||
return RegistrationStrings::get_log_str(static_cast<uint8_t>(registration), RegistrationStrings::LAST_INDEX);
|
||||
}
|
||||
|
||||
// Indexed by esp_modem::command_result
|
||||
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
|
||||
@@ -587,6 +617,9 @@ ModemState ModemComponent::compute_next_state_() {
|
||||
}
|
||||
|
||||
ModemState ModemComponent::handle_state_enabling_() {
|
||||
// With echo on (SIM7670G after power-up), the modem sends esp_modem's PPP probe back and the detection takes it for
|
||||
// a PPP reply; in PPP or CMUX these bytes are dropped as a bad frame
|
||||
this->at_reply_("ATE0", ECHO_OFF_TIMEOUT_MS);
|
||||
// Find the baud rate the modem answers at and leave it in command mode, synced
|
||||
if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
|
||||
// A failed detection keeps the previous mode, which would skip the baud rate search below
|
||||
@@ -612,21 +645,18 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
exited = false;
|
||||
const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
|
||||
bool found = false;
|
||||
bool probed = false;
|
||||
bool rejected = false;
|
||||
for (size_t i = 0; i != std::size(bauds) && !found; i++) {
|
||||
const int baud = bauds[i];
|
||||
if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
|
||||
continue;
|
||||
}
|
||||
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
|
||||
if (this->set_uart_baud_(baud) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
rejected = true;
|
||||
continue;
|
||||
}
|
||||
this->current_baud_rate_ = baud;
|
||||
probed = true;
|
||||
std::string output;
|
||||
found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
|
||||
if (!found) {
|
||||
@@ -634,11 +664,31 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
|
||||
if (!probed && !rejected) {
|
||||
// A modem left in data mode before PPP started, or stuck in CMUX, answers none of the probes; both recoveries
|
||||
// go out at the rate the detection used
|
||||
if (this->current_baud_rate_ != detected) {
|
||||
const esp_err_t err = this->set_uart_baud_(detected);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGW(TAG, "UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
|
||||
esp_err_to_name(err));
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
rejected = true;
|
||||
}
|
||||
}
|
||||
// The escape before the flush is what a stuck SIM7670G responds to; the order is measured, not arbitrary
|
||||
if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
|
||||
exited = true;
|
||||
break;
|
||||
}
|
||||
// A UART that refused a rate set BAUD
|
||||
if (!rejected) {
|
||||
this->not_responding_(detected);
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
const uint32_t delay_ms = this->next_probe_delay_();
|
||||
if (delay_ms == PROBE_RETRY_MAX_MS) {
|
||||
this->answered_ = false; // silent for minutes, so the wiring hint applies again
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
|
||||
}
|
||||
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
|
||||
break;
|
||||
@@ -672,33 +722,48 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
}
|
||||
this->probe_backoff_.store(0, std::memory_order_relaxed);
|
||||
// The modem answers AT, so it is in command mode. A failed data mode exit leaves esp_modem's UART side in data mode,
|
||||
// from where its later switch to CMUX fails at once, so its mode is set to match; this sends nothing to the modem.
|
||||
if (!this->dce_->set_mode(modem_mode::RESUME_COMMAND_MODE)) {
|
||||
ESP_LOGW(TAG, "esp_modem refused command mode; the switch to PPP may fail");
|
||||
}
|
||||
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
|
||||
if (this->dce_->set_echo(false) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to disable command echo");
|
||||
}
|
||||
|
||||
int radio_state = 0;
|
||||
if (this->dce_->get_radio_state(radio_state) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to read the radio state; skipping the radio off step");
|
||||
} else if (radio_state != RADIO_STATE_RF_OFF) {
|
||||
// Drops a session left by a warm reboot; unlike CFUN=0, which powers the SIM down on the SIM7600, CFUN=4
|
||||
// keeps the SIM readable for the PIN and the APN. A modem that refuses is used as it is.
|
||||
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to turn the radio off");
|
||||
}
|
||||
// Verbose +CME ERROR text, so a failed command or a missing SIM says why; a modem without it keeps plain ERROR
|
||||
if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Modem refused verbose errors (AT+CMEE=2)");
|
||||
}
|
||||
|
||||
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
|
||||
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
|
||||
esp_modem::PdpContext pdp(this->apn_);
|
||||
this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
|
||||
this->dce_->set_pdp_context(pdp) != command_result::OK;
|
||||
if (this->apn_pending_) {
|
||||
ESP_LOGW(TAG, "Failed to set the APN with the SIM powered down; setting it after the SIM check");
|
||||
}
|
||||
// CFUN=4 powers the SIM up with the radio still off; a modem without it needs CFUN=1 to bring the SIM back
|
||||
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
|
||||
this->dce_->set_radio_state(1) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to power the SIM up");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
|
||||
this->modem_synced_ = true; // it answers, so a disable() still tears it down
|
||||
this->answered_ = true;
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
}
|
||||
this->probe_backoff_.store(0, std::memory_order_relaxed);
|
||||
|
||||
if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
|
||||
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
|
||||
if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
|
||||
delay(200); // NOLINT
|
||||
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
|
||||
if (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
return ModemState::MODEM_STATE_DISCONNECTING;
|
||||
}
|
||||
this->current_baud_rate_ = this->baud_rate_;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
|
||||
@@ -726,6 +791,7 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
|
||||
}
|
||||
this->modem_synced_ = true;
|
||||
this->answered_ = true;
|
||||
return ModemState::MODEM_STATE_SYNCED;
|
||||
}
|
||||
|
||||
@@ -741,12 +807,13 @@ ModemState ModemComponent::handle_state_synced_() {
|
||||
this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
|
||||
this->sim_polls_ = 0;
|
||||
return ModemState::MODEM_STATE_CONNECTING;
|
||||
}
|
||||
|
||||
ModemState ModemComponent::handle_state_connecting_() {
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
|
||||
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
|
||||
// ENABLING just synced; a command that timed out comes back here unsure of the modem
|
||||
if (this->resync_) {
|
||||
this->resync_ = false;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
@@ -754,7 +821,7 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
return ModemState::MODEM_STATE_ENABLING;
|
||||
}
|
||||
}
|
||||
// ENABLING left the radio at CFUN=4, where the SIM answers but the modem cannot attach yet
|
||||
// ENABLING powered the SIM up (CFUN=4, or CFUN=1 on a modem without it), so the SIM answers
|
||||
switch (this->prepare_sim_()) {
|
||||
case SimResult::SIM_RESULT_READY:
|
||||
break;
|
||||
@@ -771,13 +838,14 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
|
||||
return ModemState::MODEM_STATE_DISCONNECTING;
|
||||
}
|
||||
// The APN has to be in the PDP context before the radio comes on and the modem attaches; esp_modem only
|
||||
// sends it when PPP starts
|
||||
esp_modem::PdpContext pdp(this->apn_);
|
||||
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to set the APN");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
if (this->apn_pending_) {
|
||||
esp_modem::PdpContext pdp(this->apn_);
|
||||
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to set the APN");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
this->apn_pending_ = false;
|
||||
}
|
||||
if (this->dce_->set_radio_state(1) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to turn the radio on");
|
||||
@@ -786,35 +854,78 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
|
||||
this->attach_polls_ = 0;
|
||||
}
|
||||
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
|
||||
// A modem still searching for a network refuses this; the attachment poll asks again
|
||||
if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
|
||||
ESP_LOGD(TAG, "Network attachment request refused");
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
|
||||
this->idle_polls_ = 0;
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
|
||||
int attached = 0;
|
||||
if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Failed to read the network attachment state");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
|
||||
this->resync_ = true;
|
||||
this->request_resync_();
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (!attached) {
|
||||
const int registration = this->read_registration_();
|
||||
if (registration == REGISTRATION_NO_ANSWER) {
|
||||
// The state is open, so the modem is checked with a sync instead
|
||||
ESP_LOGW(TAG, "No answer to a registration query");
|
||||
this->request_resync_();
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
// "Not searching" for a few polls in a row means the attachment is off; right after CFUN=1 it is only brief
|
||||
this->idle_polls_ = registration == REGISTRATION_NOT_SEARCHING ? static_cast<uint8_t>(this->idle_polls_ + 1) : 0;
|
||||
const bool idle = this->idle_polls_ >= ATTACH_DIAG_EVERY;
|
||||
// A state that cannot be read or means nothing here holds the request back only for a while
|
||||
const bool unknown = registration == REGISTRATION_UNKNOWN || registration == REGISTRATION_REPORTED_UNKNOWN ||
|
||||
(registration > REGISTRATION_ROAMING && !is_registered(registration));
|
||||
this->unknown_polls_ = unknown ? static_cast<uint8_t>(this->unknown_polls_ + 1) : 0;
|
||||
const bool unknown_too_long = this->unknown_polls_ >= ATTACH_UNKNOWN_POLLS;
|
||||
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON &&
|
||||
(is_registered(registration) || registration == REGISTRATION_UNSUPPORTED || idle || unknown_too_long)) {
|
||||
if (unknown_too_long) {
|
||||
ESP_LOGI(TAG, "Registration state %d (%s) for %u polls; requesting the network attachment anyway", registration,
|
||||
LOG_STR_ARG(registration_to_str(registration)), this->unknown_polls_);
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
// Before registration a modem can hold the AT channel on this for minutes and drop every command meanwhile,
|
||||
// so it waits for one; the fallbacks above send it anyway, and ATTACH_TIMEOUT_MS covers that hold
|
||||
const command_result attach = this->at_reply_("AT+CGATT=1", ATTACH_TIMEOUT_MS);
|
||||
if (attach == command_result::TIMEOUT) {
|
||||
ESP_LOGW(TAG, "No answer to the network attachment request");
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->request_resync_();
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (attach != command_result::OK) {
|
||||
ESP_LOGW(TAG, "Network attachment request refused: %s", this->reply_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
|
||||
}
|
||||
if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
|
||||
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_network_registration_state(registration);
|
||||
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_signal_quality(rssi, ber);
|
||||
this->dce_->get_network_system_mode(mode);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
|
||||
rssi, ber);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d (%s), network type %d, CSQ %d, BER %d", registration,
|
||||
LOG_STR_ARG(registration_to_str(registration)), mode, rssi, ber);
|
||||
if (unknown) {
|
||||
ESP_LOGW(TAG, "Network attachment request held back while the registration state is unknown (%u of %u polls)",
|
||||
this->unknown_polls_, ATTACH_UNKNOWN_POLLS);
|
||||
}
|
||||
if (registration == REGISTRATION_DENIED) {
|
||||
// The modem's reason tells a rejected APN (ESM failure) from a SIM the network does not serve
|
||||
const command_result reason_read = this->at_reply_("AT+CEER");
|
||||
ESP_LOGW(TAG,
|
||||
"The network refused registration (AT+CEER %s: %s); check the APN and that the SIM's plan covers "
|
||||
"this modem's network types",
|
||||
LOG_STR_ARG(result_to_str(reason_read)), this->reply_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
|
||||
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
|
||||
}
|
||||
|
||||
@@ -864,11 +975,12 @@ ModemState ModemComponent::handle_state_disconnecting_() {
|
||||
ESP_LOGW(TAG, "Failed to leave data mode");
|
||||
this->set_teardown_fault_();
|
||||
}
|
||||
// Turn the radio off; waiting for the lost IP event could take up to 2 min. A reconnect keeps the SIM powered
|
||||
// so it is not unlocked again; only disable() powers it down.
|
||||
const bool reconnect = this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED;
|
||||
if (this->dce_->set_radio_state(reconnect ? RADIO_STATE_RF_OFF : 0) == command_result::OK) {
|
||||
// Turn the radio off; waiting for the lost IP event could take up to 2 min. The SIM is powered down as well, as
|
||||
// ENABLING does anyway on a reconnect.
|
||||
if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
|
||||
ESP_LOGI(TAG, "Radio off");
|
||||
} else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
|
||||
ESP_LOGW(TAG, "Radio off, but the SIM could not be powered down");
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Radio off failed");
|
||||
this->set_teardown_fault_();
|
||||
@@ -916,11 +1028,114 @@ void ModemComponent::transition_to_(ModemState next_state) {
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t ModemComponent::set_uart_baud_(int baud) {
|
||||
const esp_err_t err = uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud);
|
||||
if (err == ESP_OK) {
|
||||
this->current_baud_rate_ = baud;
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
bool ModemComponent::escape_data_mode_() {
|
||||
delay(ESCAPE_GUARD_MS); // NOLINT
|
||||
if (this->dce_->set_command_mode() != command_result::OK) {
|
||||
ESP_LOGD(TAG, "No answer after the data mode escape");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGW(TAG, "Modem was left in data mode; escaped to command mode");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ModemComponent::flush_cmux_() {
|
||||
// With RTS/CTS a silent modem can hold CTS off; the flag bytes would then stay queued and block every later write
|
||||
if (this->rts_pin_ != nullptr) {
|
||||
ESP_LOGW(TAG, "CMUX recovery is not available with RTS/CTS flow control");
|
||||
return false;
|
||||
}
|
||||
static constexpr uint8_t CMUX_FLAG = 0xF9;
|
||||
uint8_t flags[64];
|
||||
memset(flags, CMUX_FLAG, sizeof(flags));
|
||||
const auto port = static_cast<uart_port_t>(this->uart_port_);
|
||||
for (size_t sent = 0; sent < CMUX_FLUSH_BYTES; sent += sizeof(flags)) {
|
||||
if (this->dte_->write(flags, sizeof(flags)) != static_cast<int>(sizeof(flags))) {
|
||||
ESP_LOGW(TAG, "CMUX flush: short write after %u bytes", static_cast<unsigned>(sent));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// 10 bits per byte, plus a margin
|
||||
const uint32_t send_ms = CMUX_FLUSH_BYTES * 10 * 1000 / this->current_baud_rate_ + 100;
|
||||
if (uart_wait_tx_done(port, pdMS_TO_TICKS(send_ms)) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "CMUX flush: transmit not finished after %u ms", static_cast<unsigned>(send_ms));
|
||||
return false;
|
||||
}
|
||||
delay(CMUX_FLUSH_SETTLE_MS); // NOLINT
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
ESP_LOGD(TAG, "No answer after the CMUX flush");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGW(TAG, "Modem was stuck in CMUX; reset it to command mode");
|
||||
return true;
|
||||
}
|
||||
|
||||
// A command timed out: the next pass checks with a sync that the modem still answers
|
||||
void ModemComponent::request_resync_() {
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
|
||||
this->resync_ = true;
|
||||
}
|
||||
|
||||
// One registration query: the <stat>, REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER or REGISTRATION_UNKNOWN
|
||||
int ModemComponent::read_stat_(const char *cmd, const char *prefix) {
|
||||
const command_result result = this->at_reply_(cmd);
|
||||
if (result == command_result::TIMEOUT) {
|
||||
return REGISTRATION_NO_ANSWER;
|
||||
}
|
||||
if (result == command_result::FAIL && reply_names_unsupported(this->reply_)) {
|
||||
return REGISTRATION_UNSUPPORTED;
|
||||
}
|
||||
const int stat = result == command_result::OK ? registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
|
||||
if (stat == REGISTRATION_UNKNOWN) {
|
||||
// An error such as a SIM failure is a warning on the diagnostic polls, so it shows at the default log level
|
||||
if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
|
||||
ESP_LOGW(TAG, "%s failed: %s", cmd, this->reply_);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "%s gave no state: %s", cmd, this->reply_);
|
||||
}
|
||||
}
|
||||
return stat;
|
||||
}
|
||||
|
||||
// AT+CEREG covers LTE; on 2G and 3G the network registration is in AT+CREG, and AT+CGATT=1 is answered quickly once
|
||||
// it is set. Returns the <stat> that tells most, or one of the negative REGISTRATION_ values.
|
||||
int ModemComponent::read_registration_() {
|
||||
const int lte = this->read_stat_("AT+CEREG?", "+CEREG:");
|
||||
if (is_registered(lte)) {
|
||||
return lte;
|
||||
}
|
||||
return merge_registration(lte, this->read_stat_("AT+CREG?", "+CREG:"));
|
||||
}
|
||||
|
||||
void ModemComponent::not_responding_(int baud) {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
|
||||
if (this->answered_) {
|
||||
// It answered before, so the wiring is fine; a long command or a modem restart keeps it silent for minutes
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud; it may be busy or restarting", baud);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
|
||||
}
|
||||
|
||||
void ModemComponent::sim_not_ready_(const char *reason) {
|
||||
// A missing or broken SIM never gets ready; the status is polled every second, so only some polls warn
|
||||
if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
|
||||
this->sim_polls_ = SIM_WARN_AFTER;
|
||||
}
|
||||
if (this->sim_polls_ == SIM_WARN_AFTER) {
|
||||
ESP_LOGW(TAG, "SIM not ready: %s. Check that a working SIM is inserted",
|
||||
reason[0] != '\0' ? reason : LOG_STR_LITERAL("no reply"));
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
}
|
||||
|
||||
#ifdef USE_MODEM_SEND_AT
|
||||
bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
|
||||
|
||||
@@ -947,13 +1162,54 @@ bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
|
||||
|
||||
#endif
|
||||
|
||||
// at() keeps no text from a failed command, so the raw reply is collected into reply_ to show the +CME ERROR
|
||||
command_result ModemComponent::at_reply_(const char *cmd, uint32_t timeout) {
|
||||
std::string line = cmd; // poll commands fit the short string buffer
|
||||
line += '\r';
|
||||
this->reply_len_ = 0;
|
||||
this->reply_[0] = '\0';
|
||||
#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
|
||||
// The inflatable buffer gathers CMUX frames too, so every reply comes over whole each time
|
||||
const bool whole = true;
|
||||
#else
|
||||
// esp_modem hands a UART reply over whole each time, and a CMUX reply one frame at a time
|
||||
const modem_mode mode = this->dce_->get_mode();
|
||||
const bool whole = mode != modem_mode::CMUX_MODE && mode != modem_mode::CMUX_MANUAL_MODE &&
|
||||
mode != modem_mode::CMUX_MANUAL_DATA && mode != modem_mode::CMUX_MANUAL_COMMAND;
|
||||
#endif
|
||||
struct {
|
||||
bool whole;
|
||||
bool cut;
|
||||
} state{whole, false};
|
||||
const command_result result = this->dce_->command(
|
||||
line,
|
||||
[this, &state](const uint8_t *data, size_t len) {
|
||||
// OK, or FAIL once an ERROR line has ended (the +CME ERROR reason may still be on its way), else TIMEOUT
|
||||
state.cut |= collect_reply(this->reply_, sizeof(this->reply_), this->reply_len_,
|
||||
reinterpret_cast<const char *>(data), len, state.whole);
|
||||
switch (reply_end(this->reply_, this->reply_len_, state.cut)) {
|
||||
case ReplyEnd::REPLY_END_OK:
|
||||
return command_result::OK;
|
||||
case ReplyEnd::REPLY_END_ERROR:
|
||||
return command_result::FAIL;
|
||||
default:
|
||||
return command_result::TIMEOUT;
|
||||
}
|
||||
},
|
||||
timeout);
|
||||
this->reply_len_ = flatten_reply(this->reply_, this->reply_len_);
|
||||
this->reply_cut_ = state.cut;
|
||||
return result;
|
||||
}
|
||||
|
||||
command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
|
||||
std::string output;
|
||||
const command_result result = this->dce_->at(cmd, output, timeout);
|
||||
const command_result result = this->at_reply_(cmd, timeout);
|
||||
// A reply longer than the buffer kept only its end
|
||||
const char *cut = this->reply_cut_ ? LOG_STR_LITERAL("...") : "";
|
||||
if (result == command_result::OK) {
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -966,25 +1222,27 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
|
||||
}
|
||||
#endif
|
||||
std::string output;
|
||||
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
|
||||
// The raw reply keeps the +CME ERROR text a missing SIM gives; status below points into it
|
||||
const command_result result = this->at_reply_("AT+CPIN?");
|
||||
if (result == command_result::TIMEOUT) {
|
||||
// The next pass checks with a sync whether the modem or only the SIM interface is silent
|
||||
ESP_LOGD(TAG, "No answer to the SIM status request");
|
||||
this->sim_not_ready_(LOG_STR_LITERAL("no answer to AT+CPIN?"));
|
||||
this->request_resync_();
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
if (result != command_result::OK) {
|
||||
// A SIM that is still starting answers with an error for a second or so
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
// Anything else, such as an echoed command, is not a status and must not reach the lock checks below
|
||||
const char *found = strstr(output.c_str(), "+CPIN:");
|
||||
if (found != nullptr) {
|
||||
found += sizeof("+CPIN:") - 1;
|
||||
while (*found == ' ') {
|
||||
found++;
|
||||
}
|
||||
}
|
||||
const char *found = sim_status(this->reply_);
|
||||
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
|
||||
if (status.empty()) {
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
ESP_LOGD(TAG, "SIM: %s", status.c_str());
|
||||
@@ -1012,8 +1270,8 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
|
||||
return SimResult::SIM_RESULT_LOCKED;
|
||||
}
|
||||
ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->sim_not_ready_(status.c_str());
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
|
||||
@@ -62,6 +62,7 @@ enum class ModemFault : uint8_t {
|
||||
MODEM_FAULT_PIN_RECORD,
|
||||
MODEM_FAULT_SETUP,
|
||||
MODEM_FAULT_NOT_ATTACHED,
|
||||
MODEM_FAULT_REGISTRATION_DENIED,
|
||||
MODEM_FAULT_PPP,
|
||||
MODEM_FAULT_TEARDOWN,
|
||||
};
|
||||
@@ -151,6 +152,7 @@ class ModemComponent : public Component {
|
||||
static constexpr uint32_t RETRY_DELAY_MS = 1000;
|
||||
static constexpr size_t URC_LINE_SIZE = 128;
|
||||
static constexpr size_t AT_COMMAND_SIZE = 128;
|
||||
static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
|
||||
#ifdef USE_MODEM_POLL
|
||||
static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
|
||||
static constexpr uint8_t CSQ_RSSI_MAX = 31;
|
||||
@@ -200,8 +202,20 @@ class ModemComponent : public Component {
|
||||
void hand_over_(uint32_t pending);
|
||||
/// Send an AT command from the task and log the result; blocks for up to the timeout
|
||||
esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
|
||||
/// Send an AT command; reply_ gets the whole reply on one line, including any +CME ERROR text
|
||||
esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
|
||||
void publish_status_();
|
||||
/// Send the +++ escape with its guard times; true when the modem answered
|
||||
bool escape_data_mode_();
|
||||
/// Overflow a stuck CMUX receiver with flag bytes; true when the modem answers AT afterwards
|
||||
bool flush_cmux_();
|
||||
void request_resync_();
|
||||
int read_stat_(const char *cmd, const char *prefix);
|
||||
int read_registration_();
|
||||
/// Set the UART rate; current_baud_rate_ follows when the UART takes it
|
||||
esp_err_t set_uart_baud_(int baud);
|
||||
void not_responding_(int baud);
|
||||
void sim_not_ready_(const char *reason);
|
||||
void dump_connect_params_();
|
||||
SimResult prepare_sim_();
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
@@ -221,6 +235,9 @@ class ModemComponent : public Component {
|
||||
const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
|
||||
#endif
|
||||
std::unique_ptr<esp_modem::DCE> dce_;
|
||||
char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
|
||||
size_t reply_len_{0};
|
||||
bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
|
||||
std::shared_ptr<esp_modem::DTE> dte_;
|
||||
esp_netif_t *ppp_netif_{nullptr};
|
||||
ESPPreferenceObject pref_;
|
||||
@@ -291,6 +308,9 @@ class ModemComponent : public Component {
|
||||
uint8_t init_at_count_{0};
|
||||
uint8_t uart_port_{UART_NUM_MAX};
|
||||
uint8_t attach_polls_{0};
|
||||
uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
|
||||
uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
|
||||
uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
|
||||
#ifdef USE_MODEM_POLL
|
||||
uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
|
||||
uint8_t poll_ber_{CSQ_UNKNOWN};
|
||||
@@ -298,7 +318,9 @@ class ModemComponent : public Component {
|
||||
#endif
|
||||
bool connect_timeout_armed_{false};
|
||||
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
|
||||
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
|
||||
bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
|
||||
bool resync_{false}; // a command timed out, so CONNECTING syncs again first
|
||||
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
|
||||
#ifdef USE_MODEM_SEND_AT
|
||||
char at_command_[AT_COMMAND_SIZE];
|
||||
#endif
|
||||
|
||||
@@ -323,12 +323,17 @@ bool MQTTClientComponent::can_proceed() {
|
||||
}
|
||||
|
||||
void MQTTClientComponent::start_dnslookup_() {
|
||||
this->status_set_warning();
|
||||
// No lookup can start before the network is up: there is no DNS server to ask yet.
|
||||
// Stay disconnected, and loop() calls this again.
|
||||
if (!network::is_connected())
|
||||
return;
|
||||
|
||||
for (auto &subscription : this->subscriptions_) {
|
||||
subscription.subscribed = false;
|
||||
subscription.resubscribe_timeout = 0;
|
||||
}
|
||||
|
||||
this->status_set_warning();
|
||||
this->dns_resolve_error_ = false;
|
||||
this->dns_resolved_ = false;
|
||||
ip_addr_t addr;
|
||||
@@ -358,9 +363,13 @@ void MQTTClientComponent::start_dnslookup_() {
|
||||
}
|
||||
default:
|
||||
case ERR_ARG: {
|
||||
// error
|
||||
// The lookup never started, so there is no answer to wait for; loop() tries again in 5 seconds
|
||||
ESP_LOGW(TAG, "Error resolving broker IP address: %d", err);
|
||||
break;
|
||||
this->state_ = MQTT_CLIENT_DISCONNECTED;
|
||||
this->disconnect_reason_ = MQTTClientDisconnectReason::DNS_RESOLVE_ERROR;
|
||||
this->on_disconnect_.call(MQTTClientDisconnectReason::DNS_RESOLVE_ERROR);
|
||||
this->connect_begin_ = millis();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2712,7 +2712,7 @@ HAIER_SCHEMA = cv.Schema(
|
||||
|
||||
@register_binary_sensor("haier", HaierBinarySensor, HAIER_SCHEMA)
|
||||
def haier_binary_sensor(var, config):
|
||||
cg.add(var.set_code(config[CONF_CODE]))
|
||||
cg.add(var.set_data(cg.StructInitializer(HaierData, ("data", config[CONF_CODE]))))
|
||||
|
||||
|
||||
@register_trigger("haier", HaierTrigger, HaierData)
|
||||
@@ -2831,7 +2831,7 @@ MIRAGE_SCHEMA = cv.Schema(
|
||||
|
||||
@register_binary_sensor("mirage", MirageBinarySensor, MIRAGE_SCHEMA)
|
||||
def mirage_binary_sensor(var, config):
|
||||
cg.add(var.set_code(config[CONF_CODE]))
|
||||
cg.add(var.set_data(cg.StructInitializer(MirageData, ("data", config[CONF_CODE]))))
|
||||
|
||||
|
||||
@register_trigger("mirage", MirageTrigger, MirageData)
|
||||
|
||||
@@ -15,7 +15,7 @@ struct CanalSatData {
|
||||
}
|
||||
};
|
||||
|
||||
struct CanalSatLDData : public CanalSatData {};
|
||||
using CanalSatLDData = CanalSatData;
|
||||
|
||||
class CanalSatBaseProtocol : public RemoteProtocol<CanalSatData> {
|
||||
public:
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
#ifdef USE_ESP8266
|
||||
#include <Wire.h>
|
||||
#endif
|
||||
|
||||
namespace esphome::scd30 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "scd30");
|
||||
@@ -27,10 +23,6 @@ static const uint16_t SCD30_CMD_TEMPERATURE_OFFSET = 0x5403;
|
||||
static const uint16_t SCD30_CMD_SOFT_RESET = 0xD304;
|
||||
|
||||
void SCD30Component::setup() {
|
||||
#ifdef USE_ESP8266
|
||||
Wire.setClockStretchLimit(150000);
|
||||
#endif
|
||||
|
||||
/// Firmware version identification
|
||||
uint16_t raw_firmware_version[3];
|
||||
if (!this->get_register(SCD30_CMD_GET_FIRMWARE_VERSION, raw_firmware_version, 3)) {
|
||||
|
||||
@@ -112,6 +112,16 @@ void SerialProxy::loop() {
|
||||
|
||||
#ifdef USE_API
|
||||
void __attribute__((noinline)) SerialProxy::read_and_send_(size_t available) {
|
||||
// A message the subscriber's connection cannot take is lost, so the bytes stay in the
|
||||
// UART's buffer until it can. A tap is still served: its answers must not wait on the network.
|
||||
if (this->api_connection_ != nullptr &&
|
||||
#ifdef USE_SERIAL_PROXY_TAP
|
||||
!this->tap_observing_() &&
|
||||
#endif
|
||||
!this->api_connection_->try_to_clear_buffer(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read in chunks up to SERIAL_PROXY_MAX_READ_SIZE
|
||||
uint8_t buffer[SERIAL_PROXY_MAX_READ_SIZE];
|
||||
size_t to_read = std::min(available, sizeof(buffer));
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::uart {
|
||||
|
||||
/// One software serial TX byte as line levels, one bit per slot.
|
||||
struct SoftwareSerialTxFrame {
|
||||
/// The start bit at slot 0, then the frame, then a stop bit that ends the last run
|
||||
uint32_t line;
|
||||
/// Slot of the last 0; from the edge after it the line stays high through the stop bits
|
||||
uint32_t high_from;
|
||||
/// Slots right after an edge into a run of equal bits lasting at least `min_run_cycles`, where a pending
|
||||
/// interrupt only delays bits that repeat the level
|
||||
uint32_t unlock_at;
|
||||
};
|
||||
|
||||
/// `frame` holds `num_bits` data and parity bits, LSB first. `unlock_at` stays 0 unless `find_unlocks`.
|
||||
ESPHOME_ALWAYS_INLINE inline SoftwareSerialTxFrame software_serial_tx_frame(uint32_t frame, uint32_t num_bits,
|
||||
uint32_t bit_time, uint32_t min_run_cycles,
|
||||
bool find_unlocks) {
|
||||
SoftwareSerialTxFrame tx;
|
||||
tx.line = frame << 1 | (1u << (num_bits + 1));
|
||||
// Slot 0 is the start bit, always 0, so the argument is never 0
|
||||
tx.high_from = 31 - __builtin_clz(~tx.line & ((2u << num_bits) - 1));
|
||||
tx.unlock_at = 0;
|
||||
if (find_unlocks) {
|
||||
const uint32_t edges = tx.line ^ (tx.line << 1 | 1); // the idle line before the start bit is high
|
||||
for (uint32_t pos = 0; pos <= tx.high_from; pos++) {
|
||||
if (((edges >> pos) & 1) && (__builtin_ctz(edges >> (pos + 1)) + 1) * bit_time >= min_run_cycles)
|
||||
tx.unlock_at |= 1u << pos;
|
||||
}
|
||||
}
|
||||
return tx;
|
||||
}
|
||||
|
||||
} // namespace esphome::uart
|
||||
@@ -19,9 +19,16 @@ namespace esphome::uart {
|
||||
ESPHOME_LOG_TAG(TAG, "uart");
|
||||
// Edge decoder up to this baud rate; at 38400 WiFi interrupt latency corrupts bytes.
|
||||
static constexpr uint32_t SW_SERIAL_EDGE_MODE_MAX_BAUD = 19200;
|
||||
// TX locks interrupts per bit up to this baud rate and per byte above it. At 38400 byte locks still trip the Wi-Fi
|
||||
// watchdog when every byte is below 0x80, while an interrupt between bits leaves the bytes intact; at 115200 it
|
||||
// stretches bits enough to corrupt them.
|
||||
static constexpr uint32_t SW_SERIAL_TX_BIT_LOCK_MAX_BAUD = 38400;
|
||||
// Edge decoder time base: 1/16 us from the 1 MHz system timer, which keeps its rate during a
|
||||
// CpuFrequencyBoost; the cycle counter does not.
|
||||
static constexpr uint32_t RX_TICKS_PER_SECOND = 16000000;
|
||||
// A byte lock lets pending interrupts run right after an edge when the next edge is at least this far away, so their
|
||||
// delay lands inside a run of equal bits. Locks longer than about 6 bits at 57600 trip the Wi-Fi watchdog.
|
||||
static constexpr uint32_t TX_UNLOCK_MIN_RUN_CYCLES = F_CPU / 1000000 * 30;
|
||||
// Longest per-bit TX interrupt lock; the Wi-Fi interrupt handler asserts (hardware WDT) when held off about 1 ms
|
||||
static constexpr uint32_t MAX_TX_LOCK_CYCLES = F_CPU / 1000000 * 200;
|
||||
__attribute__((always_inline)) static inline uint32_t rx_now() { return micros() << 4; }
|
||||
@@ -180,9 +187,11 @@ void ESP8266UartComponent::dump_config() {
|
||||
this->baud_rate_ <= SW_SERIAL_EDGE_MODE_MAX_BAUD ? LOG_STR_LITERAL("edge")
|
||||
: LOG_STR_LITERAL("start bit sampler"));
|
||||
}
|
||||
if (this->tx_pin_ != nullptr && this->baud_rate_ <= SW_SERIAL_EDGE_MODE_MAX_BAUD &&
|
||||
if (this->tx_pin_ != nullptr && this->baud_rate_ <= SW_SERIAL_TX_BIT_LOCK_MAX_BAUD &&
|
||||
this->sw_serial_->locks_whole_frame()) {
|
||||
ESP_LOGW(TAG, " TX locks interrupts for whole bytes: another software UART receives above %u baud",
|
||||
ESP_LOGW(TAG,
|
||||
" TX locks interrupts for whole bytes because a software UART receives above %u baud; Wi-Fi "
|
||||
"watchdog resets are possible under load",
|
||||
(unsigned) SW_SERIAL_EDGE_MODE_MAX_BAUD);
|
||||
}
|
||||
}
|
||||
@@ -270,7 +279,7 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
|
||||
if (this->gpio_rx_pin_ != nullptr)
|
||||
this->gpio_rx_pin_->detach_interrupt();
|
||||
// This instance counted itself if its RX ran the whole-byte interrupt
|
||||
if (this->lock_frame_ && this->gpio_rx_pin_ != nullptr)
|
||||
if (this->blocking_rx_ && this->gpio_rx_pin_ != nullptr)
|
||||
blocking_rx_count--;
|
||||
// RX disabled: forget the old pin, so a later reload does not remove this instance from the count again
|
||||
if (rx_pin == nullptr)
|
||||
@@ -280,9 +289,8 @@ void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_p
|
||||
this->data_bits_ = data_bits;
|
||||
this->parity_ = parity;
|
||||
const bool edge_mode = baud_rate <= SW_SERIAL_EDGE_MODE_MAX_BAUD;
|
||||
// Above the edge mode limit a bit is 52 us or less, so an interrupt between bits would stretch one; the whole frame
|
||||
// is locked instead, well under 1 ms
|
||||
this->lock_frame_ = !edge_mode;
|
||||
this->blocking_rx_ = !edge_mode;
|
||||
this->lock_frame_ = baud_rate > SW_SERIAL_TX_BIT_LOCK_MAX_BAUD;
|
||||
// to_isr() allocates, so call it only for a new or changed pin
|
||||
if (tx_pin != nullptr) {
|
||||
if (tx_pin != this->gpio_tx_pin_)
|
||||
@@ -390,6 +398,19 @@ void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
|
||||
|
||||
// Transmit runs from the main loop and never overlaps a CpuFrequencyBoost
|
||||
const uint32_t bit_time = this->bit_time_;
|
||||
// Data bits LSB first, then the parity bit
|
||||
uint32_t frame = data & ((1u << this->data_bits_) - 1);
|
||||
uint32_t num_bits = this->data_bits_;
|
||||
if (need_parity_bit) {
|
||||
parity_bit ^= __builtin_parity(frame);
|
||||
frame |= uint32_t(parity_bit) << num_bits++;
|
||||
}
|
||||
// Decided before the start bit so the timed loop only tests a bit
|
||||
const SoftwareSerialTxFrame tx = software_serial_tx_frame(frame, num_bits, bit_time, TX_UNLOCK_MIN_RUN_CYCLES,
|
||||
this->lock_frame_ && blocking_rx_count == 0);
|
||||
const uint32_t line = tx.line;
|
||||
const uint32_t high_from = tx.high_from;
|
||||
const uint32_t unlock_at = tx.unlock_at;
|
||||
std::optional<InterruptLock> frame_lock;
|
||||
if (this->locks_whole_frame())
|
||||
frame_lock.emplace();
|
||||
@@ -401,18 +422,17 @@ void IRAM_ATTR HOT ESP8266SoftwareSerial::write_byte(uint8_t data) {
|
||||
start = arch_get_cpu_cycle_count();
|
||||
}
|
||||
uint32_t wait = bit_time;
|
||||
for (int i = 0; i < this->data_bits_; i++) {
|
||||
bool bit = data & (1 << i);
|
||||
this->write_bit_(bit, &wait, start, bit_time);
|
||||
if (need_parity_bit)
|
||||
parity_bit ^= bit;
|
||||
for (uint32_t pos = 0; pos <= high_from; pos++) {
|
||||
if (pos != 0)
|
||||
this->write_bit_((line >> pos) & 1, &wait, start, bit_time);
|
||||
if ((unlock_at >> pos) & 1)
|
||||
frame_lock.emplace(); // drops the held lock first, so pending interrupts run
|
||||
}
|
||||
if (need_parity_bit)
|
||||
this->write_bit_(parity_bit, &wait, start, bit_time);
|
||||
// Stop bits: write_bit_ waits before its edge, so the stop bit is held with wait_
|
||||
this->write_bit_(true, &wait, start, bit_time);
|
||||
this->wait_(&wait, start, bit_time);
|
||||
if (this->stop_bits_ == 2)
|
||||
// Hold that high run with interrupts on: one that runs past it only delays the next start bit, and back-to-back
|
||||
// byte locks with no gap between them trip the Wi-Fi watchdog
|
||||
frame_lock.reset();
|
||||
for (uint32_t i = high_from; i < num_bits + this->stop_bits_; i++)
|
||||
this->wait_(&wait, start, bit_time);
|
||||
}
|
||||
void IRAM_ATTR ESP8266SoftwareSerial::wait_(uint32_t *wait, const uint32_t &start, uint32_t bit_time) {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "software_serial_rx_decoder.h"
|
||||
#include "software_serial_tx_frame.h"
|
||||
#include "uart_component.h"
|
||||
|
||||
namespace esphome::uart {
|
||||
@@ -26,8 +27,8 @@ class ESP8266SoftwareSerial {
|
||||
|
||||
size_t available();
|
||||
|
||||
/// TX holds interrupts off for whole frames: above the edge mode limit, or while any instance's RX interrupt reads
|
||||
/// whole bytes (it must not run between TX bits).
|
||||
/// TX holds interrupts off for each byte up to the edge into its trailing run of 1 bits, rather than per bit: above
|
||||
/// the per-bit lock limit, or while any instance's RX interrupt reads whole bytes (it must not run between TX edges).
|
||||
bool locks_whole_frame() const { return this->lock_frame_ || blocking_rx_count != 0; }
|
||||
|
||||
protected:
|
||||
@@ -56,6 +57,7 @@ class ESP8266SoftwareSerial {
|
||||
uint8_t stop_bits_;
|
||||
uint8_t data_bits_;
|
||||
bool lock_frame_{false};
|
||||
bool blocking_rx_{false}; // this instance's RX reads whole bytes in its interrupt
|
||||
static inline uint8_t blocking_rx_count = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
};
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from esphome.components.esp32 import (
|
||||
idf_version,
|
||||
only_on_variant,
|
||||
require_idf_version,
|
||||
set_idf_sdkconfig_default,
|
||||
)
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DEVICES, CONF_FRAMEWORK, CONF_ID
|
||||
@@ -304,7 +305,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
# IDF 6.0 moved USB host to an external component
|
||||
if idf_version() >= cv.Version(6, 0, 0):
|
||||
add_idf_component(name="espressif/usb", ref="1.4.1")
|
||||
add_idf_sdkconfig_option("CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE", 1024)
|
||||
set_idf_sdkconfig_default("CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE", 1024)
|
||||
if config.get(CONF_ENABLE_HUBS):
|
||||
add_idf_sdkconfig_option("CONFIG_USB_HOST_HUBS_SUPPORTED", True)
|
||||
|
||||
|
||||
@@ -220,6 +220,34 @@ EntityMatchResult UrlMatch::match_entity(EntityBase *entity) const {
|
||||
}
|
||||
|
||||
#if !defined(USE_ESP32) && defined(USE_ARDUINO)
|
||||
// BEGIN ESPAsyncWebServer 3.12.1 workaround: remove once a release containing upstream commit
|
||||
// 880c97068abb0f0e63f803cd3c0cac84fa5cd7bb is out and we bump to it.
|
||||
// 3.12.1 creates the SSE client before the head is ACKed and credits the head's ACK to its first queued messages,
|
||||
// dropping or truncating them. Create the client once the head is ACKed instead, as 3.9.6 did.
|
||||
class HeadAckedEventSourceResponse final : public AsyncEventSourceResponse {
|
||||
public:
|
||||
HeadAckedEventSourceResponse(DeferredUpdateEventSourceList *list, WebServer *ws)
|
||||
: AsyncEventSourceResponse(nullptr), list_(list), ws_(ws) {}
|
||||
void _respond(AsyncWebServerRequest *request) override {
|
||||
String head;
|
||||
this->_assembleHead(head, request->version());
|
||||
request->client()->write(head.c_str(), this->_headLength);
|
||||
}
|
||||
// Every ACK until clientRelease() is the head's, and clientRelease() unhooks this. _state must stay
|
||||
// RESPONSE_SETUP: past RESPONSE_WAIT_ACK the request would close its released (null) client after this returns.
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time) override {
|
||||
this->_ackedLength += len;
|
||||
if (this->_ackedLength >= this->_headLength)
|
||||
this->list_->add_client_(this->ws_, request->clientRelease());
|
||||
return 0;
|
||||
}
|
||||
|
||||
private:
|
||||
DeferredUpdateEventSourceList *list_;
|
||||
WebServer *ws_;
|
||||
};
|
||||
// END ESPAsyncWebServer 3.12.1 workaround
|
||||
|
||||
// helper for allowing only unique entries in the queue
|
||||
void __attribute__((flatten)) DeferredUpdateEventSource::deq_push_back_with_dedup_(
|
||||
void *source, message_generator_t *message_generator) {
|
||||
@@ -328,7 +356,13 @@ void DeferredUpdateEventSourceList::try_send_nodefer(const char *message, size_t
|
||||
}
|
||||
}
|
||||
|
||||
// BEGIN ESPAsyncWebServer 3.12.1 workaround (see HeadAckedEventSourceResponse): once removed, add_new_client creates
|
||||
// the source as add_client_ does and ends with es->handleRequest(request); add_client_ goes away.
|
||||
void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServerRequest *request) {
|
||||
request->send(new HeadAckedEventSourceResponse(this, ws)); // NOLINT
|
||||
}
|
||||
|
||||
void DeferredUpdateEventSourceList::add_client_(WebServer *ws, AsyncClient *client) {
|
||||
DeferredUpdateEventSource *es = new DeferredUpdateEventSource(ws, ESPHOME_F("/events"));
|
||||
this->push_back(es);
|
||||
|
||||
@@ -336,9 +370,10 @@ void DeferredUpdateEventSourceList::add_new_client(WebServer *ws, AsyncWebServer
|
||||
|
||||
es->onDisconnect([this, es](AsyncEventSourceClient *client) { this->on_client_disconnect_(es); });
|
||||
|
||||
es->handleRequest(request);
|
||||
new AsyncEventSourceClient(client, es); // NOLINT: owned by es
|
||||
ws->enable_loop_soon_any_context();
|
||||
}
|
||||
// END ESPAsyncWebServer 3.12.1 workaround
|
||||
|
||||
void DeferredUpdateEventSourceList::on_client_connect_(DeferredUpdateEventSource *source) {
|
||||
WebServer *ws = source->web_server_;
|
||||
|
||||
@@ -171,9 +171,12 @@ class DeferredUpdateEventSource final : public AsyncEventSource {
|
||||
};
|
||||
|
||||
class DeferredUpdateEventSourceList final : public std::list<DeferredUpdateEventSource *> {
|
||||
friend class HeadAckedEventSourceResponse; // ESPAsyncWebServer 3.12.1 workaround, remove with it
|
||||
|
||||
protected:
|
||||
void on_client_connect_(DeferredUpdateEventSource *source);
|
||||
void on_client_disconnect_(DeferredUpdateEventSource *source);
|
||||
void add_client_(WebServer *ws, AsyncClient *client); // ESPAsyncWebServer 3.12.1 workaround, remove with it
|
||||
|
||||
public:
|
||||
/// Returns true if there are event sources remaining (including pending cleanup).
|
||||
|
||||
@@ -132,7 +132,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
cg.add_platformio_option("extra_scripts", ["pre:fix_rp2040_hash.py"])
|
||||
# https://github.com/ESP32Async/ESPAsyncWebServer/blob/main/library.json
|
||||
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.9.6")
|
||||
cg.add_library("ESP32Async/ESPAsyncWebServer", "3.12.1")
|
||||
|
||||
|
||||
# The DNS server used for captive portals on ESP32; other platforms use the Arduino
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
#include "web_server_base.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
#if defined(USE_NETWORK) && !defined(USE_ZEPHYR) && !defined(USE_HOST)
|
||||
|
||||
namespace esphome::web_server_base {
|
||||
@@ -47,18 +52,23 @@ bool GuardMiddlewareHandler::check_auth_(AsyncWebServerRequest *request) {
|
||||
// compiled out. On ESP32 our own server picks the scheme internally.
|
||||
#if USE_ESP32 || defined(USE_WEBSERVER_AUTH_DIGEST)
|
||||
bool success = request->authenticate(credentials.username, credentials.password);
|
||||
#else
|
||||
bool success = request->authenticate(credentials.basic_auth_hash);
|
||||
#endif
|
||||
if (!success) {
|
||||
#if USE_ESP32
|
||||
if (!success)
|
||||
request->requestAuthentication();
|
||||
#elif defined(USE_WEBSERVER_AUTH_DIGEST)
|
||||
request->requestAuthentication(nullptr, true);
|
||||
#else
|
||||
request->requestAuthentication(nullptr, false);
|
||||
#endif
|
||||
// Checked here, not with the library's authenticate()/requestAuthentication(): those also link its
|
||||
// Digest code, since the scheme is only known at run time there
|
||||
const String &challenge = request->authChallenge();
|
||||
const size_t hash_len = strlen(credentials.basic_auth_hash);
|
||||
const bool success = request->authType() == AsyncAuthType::AUTH_BASIC && challenge.length() == hash_len &&
|
||||
constant_time_equals(reinterpret_cast<const uint8_t *>(challenge.c_str()),
|
||||
reinterpret_cast<const uint8_t *>(credentials.basic_auth_hash), hash_len);
|
||||
if (!success) {
|
||||
// The challenge the library sent, with the strings kept in flash on ESP8266
|
||||
AsyncWebServerResponse *response = request->beginResponse(401);
|
||||
response->addHeader(String(F("WWW-Authenticate")), String(F("Basic realm=\"Login Required\"")));
|
||||
request->send(response);
|
||||
}
|
||||
#endif
|
||||
return success;
|
||||
#else
|
||||
return true;
|
||||
|
||||
@@ -5,47 +5,57 @@
|
||||
|
||||
namespace esphome::wifi {
|
||||
|
||||
// Switching APs calls esp_wifi_disconnect(), which queues an association-leave event from the old AP. Remembers
|
||||
// that AP so its leave event does not end the connection attempt started after it. Platform free for host tests.
|
||||
/// Which expected leave a disconnect matched.
|
||||
enum class ExpectedLeave : uint8_t {
|
||||
EXPECTED_LEAVE_NONE,
|
||||
EXPECTED_LEAVE_AP,
|
||||
EXPECTED_LEAVE_ATTEMPT, ///< An attempt that never associated, so no BSSID
|
||||
};
|
||||
|
||||
// Switching APs calls esp_wifi_disconnect(), which queues a leave event for the old AP, or with no BSSID for an
|
||||
// attempt that never associated. Remembers it so that event does not end the next attempt. Platform free for tests.
|
||||
class ExpectedDisconnect {
|
||||
public:
|
||||
void arm(const uint8_t *bssid) {
|
||||
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
|
||||
this->armed_ = true;
|
||||
}
|
||||
void clear() { this->armed_ = false; }
|
||||
void arm(const uint8_t *bssid) { this->arm_(bssid, ExpectedLeave::EXPECTED_LEAVE_AP); }
|
||||
void clear() { this->expected_ = ExpectedLeave::EXPECTED_LEAVE_NONE; }
|
||||
|
||||
/// Disconnects from the current AP and, once that succeeds, expects its leave event. read_bssid(uint8_t *out)
|
||||
/// returns whether there was an AP and runs first, since the record is gone after the disconnect; disconnect()
|
||||
/// returns whether it succeeded, which is also the result. Any earlier expectation is dropped.
|
||||
/// Disconnects and, once that succeeds, expects the leave event. read_bssid(uint8_t *out) runs first, since the
|
||||
/// record is gone after the disconnect, and writes the AP's BSSID only when it returns true; without an AP the
|
||||
/// attempt's leave, with no BSSID, is expected. disconnect() returns whether it succeeded, which is the result.
|
||||
template<typename ReadBssid, typename Disconnect>
|
||||
bool disconnect_and_expect_leave(ReadBssid &&read_bssid, Disconnect &&disconnect) {
|
||||
this->armed_ = false;
|
||||
this->clear();
|
||||
std::array<uint8_t, 6> bssid{};
|
||||
const bool had_ap = read_bssid(bssid.data());
|
||||
if (!disconnect())
|
||||
return false;
|
||||
if (had_ap)
|
||||
this->arm(bssid.data());
|
||||
this->arm_(bssid.data(), had_ap ? ExpectedLeave::EXPECTED_LEAVE_AP : ExpectedLeave::EXPECTED_LEAVE_ATTEMPT);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// A connected event still queued from the previous AP; it keeps the expectation.
|
||||
bool is_previous_ap(const uint8_t *bssid) const {
|
||||
return this->armed_ && std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
|
||||
return this->expected_ != ExpectedLeave::EXPECTED_LEAVE_NONE &&
|
||||
std::equal(this->bssid_.begin(), this->bssid_.end(), bssid);
|
||||
}
|
||||
|
||||
/// Whether a disconnect is the previous AP's leave. Every disconnect ends the expectation, so it matches at
|
||||
/// most once; the caller handles roaming disconnects before this.
|
||||
bool consume_disconnect(const uint8_t *bssid, bool assoc_leave) {
|
||||
const bool expected = assoc_leave && this->is_previous_ap(bssid);
|
||||
this->armed_ = false;
|
||||
return expected;
|
||||
/// Which expected leave a disconnect is. \p is_leave covers an AP's association leave (8) and the station leave
|
||||
/// of an attempt that never associated (36). Every disconnect ends the expectation, so it matches at most once.
|
||||
ExpectedLeave consume_disconnect(const uint8_t *bssid, bool is_leave) {
|
||||
const ExpectedLeave matched =
|
||||
is_leave && this->is_previous_ap(bssid) ? this->expected_ : ExpectedLeave::EXPECTED_LEAVE_NONE;
|
||||
this->clear();
|
||||
return matched;
|
||||
}
|
||||
|
||||
protected:
|
||||
void arm_(const uint8_t *bssid, ExpectedLeave expected) {
|
||||
std::copy_n(bssid, this->bssid_.size(), this->bssid_.begin());
|
||||
this->expected_ = expected;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 6> bssid_{};
|
||||
bool armed_{false};
|
||||
ExpectedLeave expected_{ExpectedLeave::EXPECTED_LEAVE_NONE};
|
||||
};
|
||||
|
||||
} // namespace esphome::wifi
|
||||
@@ -2174,6 +2174,10 @@ bool WiFiComponent::transition_to_phase_(WiFiRetryPhase new_phase) {
|
||||
// Even when skipping full restart, disconnect to clear driver state
|
||||
// Without this, platforms like LibreTiny may think we're still connecting
|
||||
this->wifi_disconnect_();
|
||||
// And clear the error flag, as restart_adapter() does: COOLDOWN leads to
|
||||
// check_connecting_finished() without start_connecting(), so a stale
|
||||
// error would fail a connection the driver completes meanwhile.
|
||||
this->error_from_callback_ = false;
|
||||
}
|
||||
// Clear scan flag - we're starting a new retry cycle
|
||||
// This is critical for DPP/captive portal/improv flow: when determine_next_phase_()
|
||||
|
||||
@@ -564,7 +564,7 @@ class WiFiComponent final : public Component {
|
||||
// (In most use cases you won't need these)
|
||||
/// Setup WiFi interface.
|
||||
void setup() override;
|
||||
#if defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
#if defined(USE_ESP32) || defined(USE_LN882X) || defined(USE_BK72XX)
|
||||
void on_powerdown() override;
|
||||
#endif
|
||||
void start();
|
||||
|
||||
@@ -1158,10 +1158,12 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
|
||||
ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
|
||||
return;
|
||||
}
|
||||
const bool expected_disconnect =
|
||||
s_expected_disconnect.consume_disconnect(it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE);
|
||||
const ExpectedLeave expected = s_expected_disconnect.consume_disconnect(
|
||||
it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE || it.reason == WIFI_REASON_STA_LEAVING);
|
||||
const bool expected_disconnect = expected != ExpectedLeave::EXPECTED_LEAVE_NONE;
|
||||
if (expected_disconnect) {
|
||||
ESP_LOGD(TAG, "Expected disconnect from previous AP");
|
||||
ESP_LOGD(TAG, "Expected leave of the previous %s",
|
||||
expected == ExpectedLeave::EXPECTED_LEAVE_AP ? LOG_STR_LITERAL("AP") : LOG_STR_LITERAL("attempt"));
|
||||
} else if (it.reason == WIFI_REASON_NO_AP_FOUND) {
|
||||
ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
|
||||
(const char *) it.ssid);
|
||||
@@ -1181,7 +1183,9 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
|
||||
// Refresh is_connected() cache; the old session is no longer connected.
|
||||
this->update_connected_state_();
|
||||
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
|
||||
this->notify_disconnect_state_listeners_();
|
||||
// An attempt that never associated ended no session listeners know of
|
||||
if (expected != ExpectedLeave::EXPECTED_LEAVE_ATTEMPT)
|
||||
this->notify_disconnect_state_listeners_();
|
||||
#endif
|
||||
|
||||
#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
|
||||
@@ -1635,6 +1639,21 @@ bool WiFiComponent::wifi_dpp_start_listen_() {
|
||||
void WiFiComponent::wifi_dpp_stop_listen_() { esp_supp_dpp_stop_listen(); }
|
||||
#endif
|
||||
|
||||
void WiFiComponent::on_powerdown() {
|
||||
// Leave the AP before esp_restart() or deep sleep stops Wi-Fi. esp_wifi_stop() while associated
|
||||
// makes the ESP32 retransmit its Disassociation up to the retry limit although the AP ACKs it
|
||||
// (32 copies with protected management frames), which some APs handle badly.
|
||||
// Upstream bug: https://github.com/espressif/esp-idf/issues/19443 - remove this once it is fixed
|
||||
// in the ESP-IDF versions we support.
|
||||
// Ask the driver: s_sta_connected lags until the main loop has handled the connect event.
|
||||
wifi_ap_record_t ap_info;
|
||||
if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
|
||||
return;
|
||||
ESP_LOGD(TAG, "Disconnecting before powerdown");
|
||||
esp_wifi_disconnect();
|
||||
delay(100); // NOLINT: once per reboot or deep sleep, lets the disassociation go out
|
||||
}
|
||||
|
||||
bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
|
||||
|
||||
bssid_t WiFiComponent::wifi_bssid() {
|
||||
|
||||
@@ -20,7 +20,12 @@ void Mutex::lock() { k_mutex_lock(static_cast<k_mutex *>(this->handle_), K_FOREV
|
||||
bool Mutex::try_lock() { return k_mutex_lock(static_cast<k_mutex *>(this->handle_), K_NO_WAIT) == 0; }
|
||||
void Mutex::unlock() { k_mutex_unlock(static_cast<k_mutex *>(this->handle_)); }
|
||||
|
||||
IRAM_ATTR InterruptLock::InterruptLock() { state_ = irq_lock(); }
|
||||
IRAM_ATTR InterruptLock::InterruptLock() {
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
micros(); // Unlocked, so it catches up any sleep before timestamps are taken under the lock
|
||||
#endif
|
||||
state_ = irq_lock();
|
||||
}
|
||||
IRAM_ATTR InterruptLock::~InterruptLock() { irq_unlock(state_); }
|
||||
|
||||
// Zephyr LwIPLock is defined inline as a no-op in helpers.h
|
||||
|
||||
@@ -10,18 +10,14 @@ namespace zephyr {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "zephyr");
|
||||
|
||||
static gpio_flags_t flags_to_mode(gpio::Flags flags, bool inverted, bool value) {
|
||||
// Without a GPIO_OUTPUT_INIT_* bit, Zephyr leaves the output level as it is.
|
||||
static gpio_flags_t flags_to_mode(gpio::Flags flags) {
|
||||
gpio_flags_t ret = 0;
|
||||
if (flags & gpio::FLAG_INPUT) {
|
||||
ret |= GPIO_INPUT;
|
||||
}
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
ret |= GPIO_OUTPUT;
|
||||
if (value != inverted) {
|
||||
ret |= GPIO_OUTPUT_INIT_HIGH;
|
||||
} else {
|
||||
ret |= GPIO_OUTPUT_INIT_LOW;
|
||||
}
|
||||
}
|
||||
if (flags & gpio::FLAG_PULLUP) {
|
||||
ret |= GPIO_PULL_UP;
|
||||
@@ -123,8 +119,11 @@ void ZephyrGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
if (nullptr == this->gpio_) {
|
||||
return;
|
||||
}
|
||||
auto ret = gpio_pin_configure(this->gpio_, this->pin_ % this->gpio_size_,
|
||||
flags_to_mode(flags, this->inverted_, this->value_));
|
||||
gpio_flags_t mode = flags_to_mode(flags);
|
||||
if (flags & gpio::FLAG_OUTPUT) {
|
||||
mode |= this->value_ != this->inverted_ ? GPIO_OUTPUT_INIT_HIGH : GPIO_OUTPUT_INIT_LOW;
|
||||
}
|
||||
auto ret = gpio_pin_configure(this->gpio_, this->pin_ % this->gpio_size_, mode);
|
||||
if (ret != 0) {
|
||||
ESP_LOGE(TAG, "gpio %u cannot be configured %d.", this->pin_, ret);
|
||||
}
|
||||
@@ -182,6 +181,14 @@ void IRAM_ATTR ISRInternalGPIOPin::digital_write(bool value) {
|
||||
gpio_pin_set(arg->gpio, arg->pin % arg->gpio_size, value != arg->inverted ? 1 : 0);
|
||||
}
|
||||
|
||||
void IRAM_ATTR ISRInternalGPIOPin::pin_mode(gpio::Flags flags) {
|
||||
auto *arg = (zephyr::ISRPinArg *) this->arg_;
|
||||
if (arg == nullptr || arg->gpio == nullptr) {
|
||||
return;
|
||||
}
|
||||
gpio_pin_configure(arg->gpio, arg->pin % arg->gpio_size, zephyr::flags_to_mode(flags));
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,10 @@
|
||||
#include <zephyr/drivers/watchdog.h>
|
||||
#include <zephyr/sys/reboot.h>
|
||||
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
#include <cmsis_core.h>
|
||||
#endif
|
||||
|
||||
// Empty zephyr namespace block to satisfy ci-custom's lint_namespace check.
|
||||
// HAL functions live in namespace esphome (root) — they are not part of the
|
||||
// zephyr component's API.
|
||||
@@ -18,12 +22,65 @@ static int wdt_channel_id = -1; // NOLINT(cppcoreguidelines-avoid-non-const-glo
|
||||
static const device *const WDT = DEVICE_DT_GET(DT_ALIAS(watchdog0));
|
||||
#endif
|
||||
|
||||
// yield(), delay(), micros(), millis(), millis_64(), delayMicroseconds(),
|
||||
// yield(), delay(), millis(), millis_64(), delayMicroseconds(), micros() except the cycle-counter one,
|
||||
// arch_get_cpu_cycle_count(), arch_get_cpu_freq_hz() inlined in
|
||||
// components/zephyr/hal.h.
|
||||
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
// The kernel clock counts in ticks of about 30 us, and the CPU cycle counter stops while the CPU sleeps.
|
||||
// micros() adds the cycles counted since the last call. While the CPU stays busy the result and the kernel clock
|
||||
// each trail the true time by less than a tick, so they differ by less than a tick either way. A sleep shorter
|
||||
// than a tick can go unnoticed, so the result may trail the true time by up to two ticks until the next resync.
|
||||
// The CPU cannot sleep while interrupts are locked, so a lag there comes from before the lock. It and any drift
|
||||
// are left for the next unlocked call, which keeps differences inside an InterruptLock exact; InterruptLock makes that
|
||||
// call just before it locks, so timestamps taken under the lock line up with later unlocked ones. A counter that has
|
||||
// not moved since the last call is not running, and then the kernel clock is used even under a lock.
|
||||
|
||||
// One struct so the code loads a single base address.
|
||||
static struct {
|
||||
uint32_t value;
|
||||
uint32_t last_cycles; // Moves on by whole microseconds only, so the remainder carries over.
|
||||
} micros_state; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
|
||||
static constexpr uint32_t CYCLES_PER_US = 64; // nRF52 cores always run at 64 MHz.
|
||||
// Drift between unlocked calls stays far below this; a larger lead is a lag of over 2^31 us that wrapped. A lag
|
||||
// within this of 2^32 us still looks like a lead and holds micros() for at most a second; that is accepted.
|
||||
static constexpr int32_t MAX_LEAD_US = 1000000;
|
||||
|
||||
uint32_t micros() {
|
||||
const unsigned int key = irq_lock();
|
||||
const uint32_t cycles = DWT->CYCCNT;
|
||||
const uint32_t elapsed_us = (cycles - micros_state.last_cycles) / CYCLES_PER_US;
|
||||
micros_state.last_cycles += elapsed_us * CYCLES_PER_US;
|
||||
uint32_t value = micros_state.value + elapsed_us;
|
||||
|
||||
const uint32_t kernel_us = k_ticks_to_us_floor32(k_uptime_ticks());
|
||||
// A tick, plus 1 us because kernel_us is rounded down.
|
||||
const int32_t tick_us = k_ticks_to_us_ceil32(1) + 1;
|
||||
const int32_t ahead = static_cast<int32_t>(value - kernel_us);
|
||||
const bool unlocked = arch_irq_unlocked(key);
|
||||
if ((ahead < -tick_us || ahead > MAX_LEAD_US) && (unlocked || elapsed_us == 0)) {
|
||||
// The CPU slept, so the cycle counter fell behind.
|
||||
value = kernel_us;
|
||||
micros_state.last_cycles = cycles;
|
||||
} else if (ahead >= tick_us && ahead <= MAX_LEAD_US && unlocked) {
|
||||
// The CPU clock can run fast against the RTC; cap the drift at one tick, but never below a result already
|
||||
// returned under a lock.
|
||||
const uint32_t cap = kernel_us + tick_us - 1;
|
||||
value = static_cast<int32_t>(cap - micros_state.value) > 0 ? cap : micros_state.value;
|
||||
}
|
||||
micros_state.value = value;
|
||||
irq_unlock(key);
|
||||
return value;
|
||||
}
|
||||
#endif
|
||||
|
||||
void arch_init() {
|
||||
main_loop_thread() = k_current_get();
|
||||
#ifdef USE_ZEPHYR_DWT_MICROS
|
||||
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
|
||||
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
|
||||
#endif
|
||||
#ifdef CONFIG_WATCHDOG
|
||||
if (device_is_ready(WDT)) {
|
||||
static wdt_timeout_cfg wdt_config{};
|
||||
|
||||
@@ -27,12 +27,20 @@ __attribute__((always_inline)) inline bool is_main_loop_thread() { return k_curr
|
||||
|
||||
__attribute__((always_inline)) inline void yield() { ::k_yield(); }
|
||||
__attribute__((always_inline)) inline void delay(uint32_t ms) { ::k_msleep(ms); }
|
||||
#if CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC == 1000000
|
||||
// The system timer counts microseconds (the GRTC on nRF54L) and wraps at 2^32 like micros().
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return k_cycle_get_32(); }
|
||||
#elif defined(CONFIG_SOC_SERIES_NRF52X) || defined(CONFIG_SOC_SERIES_NRF52) // the name changed in sdk-nrf 3
|
||||
#define USE_ZEPHYR_DWT_MICROS
|
||||
uint32_t micros(); // CPU cycles kept close to the kernel clock, see hal.cpp
|
||||
#else
|
||||
__attribute__((always_inline)) inline uint32_t micros() { return k_ticks_to_us_floor32(k_uptime_ticks()); }
|
||||
#endif
|
||||
__attribute__((always_inline)) inline uint64_t millis_64() { return static_cast<uint64_t>(k_uptime_get()); }
|
||||
__attribute__((always_inline)) inline uint32_t millis() { return static_cast<uint32_t>(millis_64()); }
|
||||
|
||||
// NOLINTNEXTLINE(readability-identifier-naming)
|
||||
__attribute__((always_inline)) inline void delayMicroseconds(uint32_t us) { ::k_usleep(us); }
|
||||
__attribute__((always_inline)) inline void delayMicroseconds(uint32_t us) { ::k_busy_wait(us); }
|
||||
__attribute__((always_inline)) inline uint32_t arch_get_cpu_cycle_count() { return k_cycle_get_32(); }
|
||||
__attribute__((always_inline)) inline uint32_t arch_get_cpu_freq_hz() { return sys_clock_hw_cycles_per_sec(); }
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ from enum import Enum
|
||||
|
||||
from esphome.enum import StrEnum
|
||||
|
||||
__version__ = "2026.11.0b4"
|
||||
__version__ = "2026.11.0b7"
|
||||
|
||||
ALLOWED_NAME_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
VALID_SUBSTITUTIONS_CHARACTERS = (
|
||||
|
||||
@@ -294,6 +294,8 @@ void Application::reboot() {
|
||||
for (auto &component : std::ranges::reverse_view(this->components_)) {
|
||||
component->on_shutdown();
|
||||
}
|
||||
// No teardown on a forced reboot, but still power hardware down (Wi-Fi leaves the AP)
|
||||
this->run_powerdown_hooks();
|
||||
arch_restart();
|
||||
}
|
||||
void Application::safe_reboot() {
|
||||
|
||||
@@ -185,10 +185,12 @@ class Component {
|
||||
*/
|
||||
virtual bool teardown() { return true; }
|
||||
|
||||
/** Called after teardown is complete to power down hardware.
|
||||
/** Called last before a reboot or deep sleep to power down hardware.
|
||||
*
|
||||
* This is called after all components have finished their teardown process,
|
||||
* On a safe shutdown this is called after all components have finished their teardown process,
|
||||
* making it safe to power down hardware like ethernet PHY.
|
||||
* On a forced reboot (Application::reboot()) it is called right after on_shutdown() with no
|
||||
* teardown, so implementations must not assume teardown() has run.
|
||||
*/
|
||||
virtual void on_powerdown() {}
|
||||
|
||||
|
||||
@@ -481,6 +481,7 @@
|
||||
#ifdef USE_ESP32
|
||||
#define USE_ESP32_CRASH_HANDLER
|
||||
#define USE_ESP32_VASPRINTF_STUB
|
||||
#define USE_ESP32_PM_TICK_OVERFLOW_GUARD
|
||||
#define USE_MQTT_IDF_ENQUEUE
|
||||
#define USE_MQTT_TLS
|
||||
#define USE_MQTT_CERT_BUNDLE
|
||||
@@ -508,6 +509,7 @@
|
||||
#define USE_WIFI_SCAN_RESULTS_LOCK
|
||||
#define USE_ESP32_BLE
|
||||
#define USE_ESP32_BLE_BLUEDROID_BOND_KEYS
|
||||
#define USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE
|
||||
#define USE_ESP32_BLE_BLUEDROID_HEX_WRAPS
|
||||
#define USE_ESP32_BLE_GATTC_HANDLE_ORDER
|
||||
#define USE_ESP32_BLE_MAX_CONNECTIONS 3
|
||||
|
||||
@@ -846,7 +846,9 @@ def convert_visual_temperatures(
|
||||
that needs ``full_config`` is left for final validation, which runs this again with it."""
|
||||
if (unit := entity_temperature_unit(config, full_config)) is None:
|
||||
return config
|
||||
visual = config[CONF_VISUAL]
|
||||
# A platform entry that only holds nested entities has no visual section of its own
|
||||
if (visual := config.get(CONF_VISUAL)) is None:
|
||||
return config
|
||||
convert_temperature_keys(visual, (CONF_MIN_TEMPERATURE, CONF_MAX_TEMPERATURE), unit)
|
||||
section = visual if delta_section is None else visual.get(delta_section)
|
||||
if section is not None:
|
||||
|
||||
@@ -2282,6 +2282,11 @@ class LwIPLock {
|
||||
// Platforms with potential lwIP core locking — out-of-line implementations in helpers.cpp
|
||||
LwIPLock();
|
||||
~LwIPLock();
|
||||
#ifdef USE_ESP32
|
||||
private:
|
||||
// Only the instance that took the core lock releases it; unused without CONFIG_LWIP_TCPIP_CORE_LOCKING
|
||||
[[maybe_unused]] bool locked_{false};
|
||||
#endif
|
||||
#else
|
||||
// No lwIP core locking — inline no-ops (empty bodies instead of = default
|
||||
// to prevent clang-tidy unused-variable warnings at call sites)
|
||||
|
||||
+32
-14
@@ -9,11 +9,29 @@
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
#include <hardware/sync.h>
|
||||
#endif
|
||||
|
||||
namespace esphome {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "scheduler");
|
||||
|
||||
#if defined(USE_RP2) && (defined(USE_WIFI) || defined(USE_ETHERNET))
|
||||
// lwIP callbacks add and cancel items from a low-priority IRQ on RP2, where lock_ is an empty Mutex: hold interrupts
|
||||
// off instead. Not the lwIP lock: each release re-arms arduino-pico's 20 ms Ethernet poll, starving reception.
|
||||
class SchedulerLockGuard {
|
||||
public:
|
||||
explicit SchedulerLockGuard(Mutex & /*mutex*/) : state_(save_and_disable_interrupts()) {}
|
||||
~SchedulerLockGuard() { restore_interrupts(this->state_); }
|
||||
|
||||
private:
|
||||
uint32_t state_;
|
||||
};
|
||||
#else
|
||||
using SchedulerLockGuard = LockGuard;
|
||||
#endif
|
||||
|
||||
// Maximum number of logically deleted (cancelled) items before forcing cleanup.
|
||||
// Empirically chosen to balance cleanup overhead against tombstone accumulation in items_.
|
||||
static constexpr uint32_t MAX_LOGICALLY_DELETED_ITEMS = 5;
|
||||
@@ -118,7 +136,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
if (delay == SCHEDULER_DONT_RUN) {
|
||||
// Still need to cancel existing timer if we have a name/id
|
||||
if (!skip_cancel) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type, /* find_first= */ true);
|
||||
}
|
||||
return;
|
||||
@@ -140,7 +158,7 @@ void HOT Scheduler::set_timer_common_(Component *component, SchedulerItem::Type
|
||||
uint32_t offset = 0;
|
||||
// Take lock early to protect scheduler_item_pool_head_ access
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Create and populate the scheduler item
|
||||
SchedulerItem *item = this->get_item_from_pool_locked_();
|
||||
@@ -317,7 +335,7 @@ void Scheduler::full_cleanup_removed_items_() {
|
||||
// 2. Other threads must see either the old state or the new state, not intermediate states
|
||||
// 3. The operation is already expensive (O(n)), so lock overhead is negligible
|
||||
// 4. No operations inside can block or take other locks, so no deadlock risk
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Compact in-place: move valid items forward, recycle removed ones
|
||||
size_t write = 0;
|
||||
@@ -440,7 +458,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item;
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
item = this->pop_raw_locked_();
|
||||
}
|
||||
|
||||
@@ -457,7 +475,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
ESP_LOGD(TAG, "\n");
|
||||
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->items_ = std::move(old_items);
|
||||
// Rebuild heap after moving items back
|
||||
std::make_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp);
|
||||
@@ -494,7 +512,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#ifdef ESPHOME_THREAD_MULTI_NO_ATOMICS
|
||||
// Multi-threaded platforms without atomics: must take lock to safely read remove flag
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
if (is_item_removed_locked_(item)) {
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
@@ -504,7 +522,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
#else
|
||||
// Single-threaded or multi-threaded with atomics: can check without lock
|
||||
if (is_item_removed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
this->to_remove_decrement_locked_();
|
||||
continue;
|
||||
@@ -513,7 +531,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
|
||||
// Don't run on failed components (is_item_failed_ exempts SELF_POINTER delays).
|
||||
if (this->is_item_failed_(item)) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->recycle_item_main_loop_(this->pop_raw_locked_());
|
||||
continue;
|
||||
}
|
||||
@@ -533,7 +551,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// - timeouts/intervals get cancelled
|
||||
now = this->execute_item_(item, now);
|
||||
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
|
||||
// Only pop after function call, this ensures we were reachable
|
||||
// during the function call and know if we were cancelled.
|
||||
@@ -583,7 +601,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
// every item has been returned to a container (items_, to_add_, or pool).
|
||||
// Lock needed to get a consistent snapshot of all containers.
|
||||
{
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
this->debug_verify_no_leak_();
|
||||
}
|
||||
#endif
|
||||
@@ -592,7 +610,7 @@ uint32_t HOT Scheduler::call(uint32_t now) {
|
||||
return now;
|
||||
}
|
||||
void HOT Scheduler::process_to_add_slow_path_() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
for (auto *&it : this->to_add_) {
|
||||
if (is_item_removed_locked_(it)) {
|
||||
// Recycle cancelled items
|
||||
@@ -616,7 +634,7 @@ bool HOT Scheduler::cleanup_slow_path_() {
|
||||
// 4. We need a consistent view of items_ and to_remove_ throughout the operation
|
||||
// Without the lock, we could access items_ while another thread is reading it,
|
||||
// leading to race conditions
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
while (!this->items_.empty()) {
|
||||
SchedulerItem *item = this->items_[0];
|
||||
if (!this->is_item_removed_locked_(item))
|
||||
@@ -664,7 +682,7 @@ uint32_t HOT Scheduler::execute_item_(SchedulerItem *item, uint32_t now) {
|
||||
// Common implementation for cancel operations - handles locking
|
||||
bool HOT Scheduler::cancel_item_(Component *component, NameType name_type, const char *static_name, uint32_t hash_or_id,
|
||||
SchedulerItem::Type type) {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
// Public cancel path uses default find_first=false to cancel ALL matches because
|
||||
// DelayAction parallel mode (skip_cancel=true) can create multiple items with the same key.
|
||||
return this->cancel_item_locked_(component, name_type, static_name, hash_or_id, type);
|
||||
@@ -773,7 +791,7 @@ void __attribute__((noinline)) Scheduler::shrink_scheduler_vector_(std::vector<S
|
||||
}
|
||||
|
||||
void Scheduler::trim_freelist() {
|
||||
LockGuard guard{this->lock_};
|
||||
SchedulerLockGuard guard{this->lock_};
|
||||
SchedulerItem *item = this->scheduler_item_pool_head_;
|
||||
size_t freed = 0;
|
||||
while (item != nullptr) {
|
||||
|
||||
@@ -518,7 +518,8 @@ class Scheduler {
|
||||
uint32_t hash_or_id,
|
||||
SchedulerItem::Type type, bool find_first);
|
||||
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there
|
||||
// Empty on single-threaded platforms (ESP8266, RP2), so it takes no space there; RP2 with networking locks by
|
||||
// holding interrupts off (SchedulerLockGuard in scheduler.cpp)
|
||||
[[no_unique_address]] Mutex lock_;
|
||||
std::vector<SchedulerItem *> items_;
|
||||
std::vector<SchedulerItem *> to_add_;
|
||||
|
||||
+5
-5
@@ -125,7 +125,7 @@ lib_deps =
|
||||
ESP8266WiFi ; wifi (Arduino built-in)
|
||||
Update ; ota (Arduino built-in)
|
||||
ESP32Async/ESPAsyncTCP@2.0.0 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
makuna/NeoPixelBus@2.7.3 ; neopixelbus
|
||||
ESP8266HTTPClient ; http_request (Arduino built-in)
|
||||
ESP8266mDNS ; mdns (Arduino built-in)
|
||||
@@ -216,8 +216,8 @@ framework = arduino
|
||||
lib_deps =
|
||||
${common:arduino.lib_deps}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ayushsharma82/RPAsyncTCP@1.3.2 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
https://github.com/esphome-libs/RPAsyncTCP.git#1.3.2-esphome.1 ; async_tcp
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
WiFi ; wifi (arduino-pico built-in)
|
||||
lwIP_CYW43 ; wifi (arduino-pico built-in, WiFi dependency)
|
||||
HTTPClient ; http_request (arduino-pico built-in)
|
||||
@@ -245,10 +245,10 @@ lib_compat_mode = soft
|
||||
lib_deps =
|
||||
${common.lib_deps_base}
|
||||
${common:idf-component-libs.lib_deps}
|
||||
ESP32Async/ESPAsyncWebServer@3.9.6 ; web_server_base
|
||||
ESP32Async/ESPAsyncWebServer@3.12.1 ; web_server_base
|
||||
esphome/wireguard@0.4.8 ; wireguard
|
||||
esphome/noise-c@0.1.31 ; noise (api, ota)
|
||||
ESP32Async/AsyncTCP@3.4.5 ; async_tcp
|
||||
ESP32Async/AsyncTCP@3.5.0 ; async_tcp
|
||||
DNSServer ; captive_portal
|
||||
heman/AsyncMqttClient-esphome@2.0.0 ; mqtt
|
||||
improv/Improv@1.2.7 ; improv_serial
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Tests for the api wizard: schema, final validation and generated tables."""
|
||||
|
||||
from collections.abc import Callable
|
||||
import importlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
@@ -8,13 +9,20 @@ import re
|
||||
import string
|
||||
import textwrap
|
||||
|
||||
from aioesphomeapi.model import COMPONENT_TYPE_TO_INFO
|
||||
import pytest
|
||||
|
||||
from esphome.components.api import wizard
|
||||
from esphome.components.homeassistant.switch import SUPPORTED_DOMAINS as SWITCH_DOMAINS
|
||||
from esphome.config import load_config
|
||||
from esphome.core import CORE, ID
|
||||
from esphome.helpers import fnv1_hash, fnv1a_32bit_hash, zstd_module
|
||||
from esphome.cpp_generator import MockObjClass
|
||||
from esphome.helpers import (
|
||||
fnv1_hash,
|
||||
fnv1_hash_object_id,
|
||||
fnv1a_32bit_hash,
|
||||
zstd_module,
|
||||
)
|
||||
from tests.component_tests.helpers import get_define_value
|
||||
|
||||
ESP32_HEADER = """
|
||||
@@ -774,9 +782,14 @@ def test_the_blob_is_the_exact_json_document(
|
||||
"description": "Pick",
|
||||
"entities": [
|
||||
# No device_id for the main device, and no description when unset
|
||||
{"key": entity_hash(main_cpp, "sw"), "description": "Enable"},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
],
|
||||
@@ -1074,16 +1087,206 @@ def test_an_entity_role_is_sent_with_the_entity(
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw"),
|
||||
"platform": "switch",
|
||||
"description": "Enable",
|
||||
"role": "example.enable",
|
||||
},
|
||||
{
|
||||
"key": entity_hash(main_cpp, "sw2"),
|
||||
"platform": "switch",
|
||||
"device_id": fnv1a_32bit_hash("kitchen_dev"),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_entities_sharing_a_name_are_told_apart_by_platform(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
sensor:
|
||||
- platform: template
|
||||
id: power_sensor
|
||||
name: Power
|
||||
switch:
|
||||
- platform: template
|
||||
id: power_switch
|
||||
name: Power
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: power_sensor
|
||||
- id: power_switch
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
# The key is the same, so the platform is what says which entity is meant
|
||||
key = fnv1_hash_object_id("Power")
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": key, "platform": "sensor"},
|
||||
{"key": key, "platform": "switch"},
|
||||
]
|
||||
|
||||
|
||||
def test_a_datetime_entity_has_the_platform_of_its_type(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
datetime:
|
||||
- platform: template
|
||||
id: dt_date
|
||||
name: Day
|
||||
type: date
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_time
|
||||
name: Hour
|
||||
type: time
|
||||
optimistic: true
|
||||
- platform: template
|
||||
id: dt_datetime
|
||||
name: Moment
|
||||
type: datetime
|
||||
optimistic: true
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: dt_date
|
||||
- id: dt_time
|
||||
- id: dt_datetime
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Day"), "platform": "date"},
|
||||
{"key": fnv1_hash_object_id("Hour"), "platform": "time"},
|
||||
{"key": fnv1_hash_object_id("Moment"), "platform": "datetime"},
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_declared_in_its_component_has_the_platform_of_its_class(
|
||||
tmp_path: Path, generate_main: Callable[[str | Path], str]
|
||||
) -> None:
|
||||
entities = """
|
||||
uart:
|
||||
tx_pin: 17
|
||||
rx_pin: 16
|
||||
baud_rate: 9600
|
||||
gps:
|
||||
latitude:
|
||||
id: gps_lat
|
||||
name: Latitude
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: gps_lat
|
||||
"""
|
||||
|
||||
main_cpp = generate_main(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert wizard_entities(main_cpp) == [
|
||||
{"key": fnv1_hash_object_id("Latitude"), "platform": "sensor"}
|
||||
]
|
||||
|
||||
|
||||
def test_an_entity_of_a_platform_the_wizard_does_not_know_is_rejected(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
entities = """
|
||||
psram:
|
||||
i2c:
|
||||
id: camera_bus
|
||||
sda: 25
|
||||
scl: 23
|
||||
esp32_camera:
|
||||
id: test_camera
|
||||
name: Camera
|
||||
data_pins: [17, 35, 34, 5, 39, 18, 36, 19]
|
||||
vsync_pin: 22
|
||||
href_pin: 26
|
||||
pixel_clock_pin: 21
|
||||
external_clock:
|
||||
pin: 27
|
||||
i2c_id: camera_bus
|
||||
"""
|
||||
pages = """
|
||||
- entities:
|
||||
- id: test_camera
|
||||
"""
|
||||
|
||||
errors = config_errors(
|
||||
write_config(tmp_path, ESP32_HEADER, wizard_api(pages), entities)
|
||||
)
|
||||
|
||||
assert any(
|
||||
"Entity 'test_camera' is not of a platform the wizard can show" in error
|
||||
for error in errors
|
||||
), errors
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("class_name", "platform"), wizard.WIZARD_ENTITY_PLATFORMS.items()
|
||||
)
|
||||
def test_every_wizard_entity_platform_names_a_real_entity_class(
|
||||
class_name: str, platform: str
|
||||
) -> None:
|
||||
namespace, _ = class_name.split("::")
|
||||
component = importlib.import_module(
|
||||
f"esphome.components.{namespace.removesuffix('_')}"
|
||||
)
|
||||
# Light keeps its classes in a submodule
|
||||
modules = [component, *(getattr(component, "types", None),)]
|
||||
classes = {
|
||||
str(value)
|
||||
for module in modules
|
||||
if module is not None
|
||||
for value in vars(module).values()
|
||||
if isinstance(value, MockObjClass)
|
||||
}
|
||||
assert class_name in classes
|
||||
# The name the API client knows the entity type by
|
||||
assert platform in COMPONENT_TYPE_TO_INFO
|
||||
|
||||
|
||||
# Entity platforms of the API that a wizard page cannot show
|
||||
WIZARD_UNSUPPORTED_PLATFORMS: set[str] = {
|
||||
# ESP32Camera derives from EntityBase directly, with no camera base class to recognise
|
||||
"camera",
|
||||
# MediaPlayer does not declare EntityBase, so the page's use_id(EntityBase) already rejects it
|
||||
"media_player",
|
||||
# No ESPHome component provides one
|
||||
"siren",
|
||||
}
|
||||
|
||||
|
||||
def test_every_api_entity_platform_is_known_to_the_wizard() -> None:
|
||||
"""A new entity platform needs a WIZARD_ENTITY_PLATFORMS entry, or a reason to be left out."""
|
||||
proto = (
|
||||
Path(wizard.__file__).parent.joinpath("api.proto").read_text(encoding="utf-8")
|
||||
)
|
||||
messages = re.findall(r"message ListEntities(?!Done|Services)\w+Response \{", proto)
|
||||
# The ifdef of each ListEntities message names its platform: USE_SENSOR, USE_DATETIME_DATE, ...
|
||||
ifdefs = re.findall(
|
||||
r"message ListEntities(?!Done|Services)\w+Response \{[^}]*?"
|
||||
r'option \(ifdef\) = "USE_(\w+)";',
|
||||
proto,
|
||||
)
|
||||
assert len(ifdefs) == len(messages)
|
||||
proto_platforms = {ifdef.lower().removeprefix("datetime_") for ifdef in ifdefs}
|
||||
assert (
|
||||
set(wizard.WIZARD_ENTITY_PLATFORMS.values()) | WIZARD_UNSUPPORTED_PLATFORMS
|
||||
== proto_platforms
|
||||
)
|
||||
|
||||
|
||||
def test_an_entity_with_a_role_may_be_in_the_wizard_twice(tmp_path: Path) -> None:
|
||||
wizard.register_entity_role(ID("sw", is_declaration=True), "example.enable")
|
||||
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
"""LibreTiny always gets the xPortGetCoreID stand-in, whatever its log level."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_libretiny_adds_core_id_flag(
|
||||
generate_main: Callable[[str | Path], str], tmp_path: Path
|
||||
) -> None:
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\n"
|
||||
"bk72xx:\n board: generic-bk7231n-qfn32-tuya\n\n"
|
||||
"wifi:\n ssid: test\n password: testtest12\n\n"
|
||||
"async_tcp:\n"
|
||||
)
|
||||
generate_main(config)
|
||||
assert "-DxPortGetCoreID=int" in CORE.build_flags
|
||||
@@ -222,6 +222,20 @@ def test_a_resolved_unit_waits_for_the_full_config() -> None:
|
||||
assert config[CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(59.0)
|
||||
|
||||
|
||||
def test_final_validate_skips_a_platform_that_only_holds_nested_climates() -> None:
|
||||
"""A hub platform may put each of its climates under a key of one platform entry."""
|
||||
nested = climate_schema(climate_ns.class_("NestedClimate", Climate))
|
||||
platform_schema = cv.Schema({cv.Optional("zone_1"): nested})
|
||||
config = platform_schema(
|
||||
{"zone_1": {CONF_NAME: "Zone 1", CONF_VISUAL: {CONF_MIN_TEMPERATURE: "50°F"}}}
|
||||
)
|
||||
# The platform entry itself is not a climate and has no visual section
|
||||
assert CONF_VISUAL not in config
|
||||
_final_validate([config])
|
||||
# The nested climate was converted by its own schema
|
||||
assert config["zone_1"][CONF_VISUAL][CONF_MIN_TEMPERATURE] == pytest.approx(10.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("use_fahrenheit", "cn105_lines"),
|
||||
[
|
||||
|
||||
@@ -818,9 +818,18 @@ def test_uc8279_offset_height_configurable(
|
||||
assert resolution == (0x61, 0x00, 0x10, 0x00, 0x0A)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dimensions",
|
||||
[
|
||||
{"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
# offset_height not written: the default of 0 applies, and the error must not point at a missing key
|
||||
{"width": 16, "height": 0x10000},
|
||||
],
|
||||
)
|
||||
def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
set_component_config: Callable[[str, Any], None],
|
||||
dimensions: dict[str, int],
|
||||
) -> None:
|
||||
"""offset_height plus the panel height is the gate count, which the controller holds in 16 bits."""
|
||||
set_core_config(
|
||||
@@ -829,15 +838,16 @@ def test_uc8279_offset_height_plus_height_must_fit_16_bits(
|
||||
)
|
||||
set_component_config("spi", {"id": "spi_bus", "clk_pin": 18, "mosi_pin": 19})
|
||||
|
||||
with pytest.raises(cv.Invalid, match="must not exceed"):
|
||||
with pytest.raises(cv.Invalid, match="must not exceed") as exc_info:
|
||||
run_schema_validation(
|
||||
{
|
||||
"id": "test_display",
|
||||
"model": "uc8279",
|
||||
"dc_pin": 21,
|
||||
"dimensions": {"width": 16, "height": 2, "offset_height": 0xFFFF},
|
||||
"dimensions": dimensions,
|
||||
}
|
||||
)
|
||||
assert exc_info.value.path[-2:] == ["dimensions", "height"]
|
||||
|
||||
|
||||
def test_uc8279_x4pro_explicit_dimensions_keep_the_model_offset(
|
||||
|
||||
@@ -7,8 +7,9 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SRC_CMAKE
|
||||
from esphome.components.esp32_ble import bluedroid_headers_cmake
|
||||
from esphome.components.esp32_ble import _drops_bond_keys, bluedroid_headers_cmake
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAP_FLAGS = {
|
||||
@@ -19,12 +20,31 @@ _WRAP_FLAGS = {
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "expected"),
|
||||
[
|
||||
("5.5.5", False),
|
||||
("5.5.6", True),
|
||||
("5.5.7", True),
|
||||
("6.0.0", False),
|
||||
("6.0.3", False),
|
||||
("6.1.0", False),
|
||||
("6.1.1", True),
|
||||
("6.2.0", True),
|
||||
],
|
||||
)
|
||||
def test_drops_bond_keys_versions(version: str, expected: bool) -> None:
|
||||
"""ESP-IDF added the bond clearing in 5.5.6 and 6.1.1."""
|
||||
assert _drops_bond_keys(cv.Version.parse(version)) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "windows", "expected"),
|
||||
[
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", False, True, id="idf_5_5_6"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.5}", False, False, id="idf_5_5_5"),
|
||||
pytest.param("{type: esp-idf, version: 6.0.1}", False, False, id="idf_6"),
|
||||
pytest.param("{type: esp-idf, version: 6.1.1}", False, True, id="idf_6_1_1"),
|
||||
pytest.param("{type: esp-idf, version: 5.5.6}", True, False, id="windows"),
|
||||
# Arduino 3.3.12 is built on ESP-IDF 5.5.6, 3.3.11 on 5.5.5
|
||||
pytest.param(
|
||||
@@ -48,7 +68,7 @@ _WRAP_FLAGS = {
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wraps_only_on_idf_5_5_6_native_builds(
|
||||
def test_wraps_only_on_affected_idf_native_builds(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
|
||||
@@ -39,11 +39,14 @@ _CLIENTS = {
|
||||
("6.0.0", False),
|
||||
("6.0.2", False),
|
||||
("6.0.3", True),
|
||||
("6.1.0", True),
|
||||
("6.0.4", True),
|
||||
("6.1.0", False),
|
||||
("6.1.1", True),
|
||||
("6.2.0", True),
|
||||
],
|
||||
)
|
||||
def test_strict_handle_order_versions(version: str, expected: bool) -> None:
|
||||
"""ESP-IDF added the check in 5.5.6 and 6.0.3."""
|
||||
"""ESP-IDF added the check in 5.5.6, 6.0.3 and 6.1.1."""
|
||||
assert _has_strict_handle_order(cv.Version.parse(version)) is expected
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Tests for the Bluedroid wraps that drop a failed queued GATT client command."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SRC_CMAKE
|
||||
from esphome.components.esp32_ble import bluedroid_headers_cmake
|
||||
from esphome.core import CORE
|
||||
|
||||
_WRAPPED = (
|
||||
"bta_gattc_cfg_mtu",
|
||||
"bta_gattc_execute",
|
||||
"GATTC_ConfigureMTU",
|
||||
"GATTC_ExecuteWrite",
|
||||
)
|
||||
_WRAP_FLAGS = {f"-Wl,--wrap={s}" for s in _WRAPPED} | {
|
||||
f"-Wl,--undefined=__wrap_{s}" for s in _WRAPPED
|
||||
}
|
||||
_TRACKER = "\nesp32_ble_tracker: {}\n"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("framework", "components", "windows", "expected"),
|
||||
[
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", _TRACKER, False, True, id="idf_5_5_6"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 6.0.1}", _TRACKER, False, True, id="idf_6"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: arduino, version: 3.3.12}", _TRACKER, False, True, id="arduino"
|
||||
),
|
||||
# Without the tracker or esp32_ble_client there is no GATT client
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", "", False, False, id="no_gatt_client"
|
||||
),
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}", _TRACKER, True, False, id="windows"
|
||||
),
|
||||
# PlatformIO builds cannot reach the private headers
|
||||
pytest.param(
|
||||
"{type: esp-idf, version: 5.5.6}\n toolchain: platformio",
|
||||
_TRACKER,
|
||||
False,
|
||||
False,
|
||||
id="platformio",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_wraps_on_native_builds_with_a_gatt_client(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
framework: str,
|
||||
components: str,
|
||||
windows: bool,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("esphome.components.esp32_ble.IS_WINDOWS", windows)
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
"esphome:\n name: test\n\nesp32:\n variant: esp32\n"
|
||||
f" framework: {framework}\n\nesp32_ble: {{}}\n{components}"
|
||||
)
|
||||
generate_main(config)
|
||||
assert CORE.build_flags & _WRAP_FLAGS == (_WRAP_FLAGS if expected else set())
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_BLE_BLUEDROID_GATTC_QUEUE" in defines) is expected
|
||||
headers = bluedroid_headers_cmake("bluedroid_gattc_queue.c")
|
||||
assert (headers in CORE.data[KEY_ESP32][KEY_SRC_CMAKE]) is expected
|
||||
@@ -28,19 +28,22 @@ _WRAP_FLAGS = {
|
||||
pytest.param("esp32c2", "{type: esp-idf}", True, id="c2"),
|
||||
pytest.param("esp32c6", "{type: esp-idf}", False, id="c6_rom_sscanf"),
|
||||
pytest.param(
|
||||
"esp32", "{type: esp-idf, version: 6.0.1}", False, id="idf6_picolibc"
|
||||
"esp32", "{type: esp-idf, version: 6.0.1}", True, id="idf6_picolibc"
|
||||
),
|
||||
pytest.param(
|
||||
"esp32c6", "{type: esp-idf, version: 6.0.1}", True, id="c6_idf6_picolibc"
|
||||
),
|
||||
pytest.param("esp32", "{type: arduino}", False, id="arduino"),
|
||||
],
|
||||
)
|
||||
def test_wraps_only_on_newlib_idf_without_rom_sscanf(
|
||||
def test_wraps_only_on_idf_without_rom_sscanf(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
tmp_path: Path,
|
||||
variant: str,
|
||||
framework: str,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
"""The wraps are emitted only where Bluedroid's sscanf calls link newlib's engine."""
|
||||
"""The wraps are emitted only where Bluedroid's sscanf calls link a scanf engine."""
|
||||
config = tmp_path / "test.yaml"
|
||||
config.write_text(
|
||||
f"esphome:\n name: test\n\nesp32:\n variant: {variant}\n"
|
||||
|
||||
@@ -9,6 +9,7 @@ import pytest
|
||||
from esphome import config_validation as cv
|
||||
from esphome.components.const import CONF_DEVICE_TYPE
|
||||
from esphome.components.esp32 import (
|
||||
KEY_IDF_VERSION,
|
||||
KEY_VARIANT,
|
||||
VARIANT_ESP32,
|
||||
VARIANT_ESP32C6,
|
||||
@@ -33,6 +34,7 @@ from esphome.types import ConfigType
|
||||
from tests.component_tests.types import SetCoreConfigCallable
|
||||
|
||||
LIGHT_SLEEP = {CONF_ENABLE_LIGHT_SLEEP: True}
|
||||
IDF_VERSION = cv.Version(5, 5, 5)
|
||||
|
||||
|
||||
def _set_variant(
|
||||
@@ -41,11 +43,12 @@ def _set_variant(
|
||||
/,
|
||||
*,
|
||||
full_config: ConfigType | None = None,
|
||||
idf_version: cv.Version = IDF_VERSION,
|
||||
) -> None:
|
||||
set_core_config(
|
||||
PlatformFramework.ESP32_IDF,
|
||||
core_data={KEY_FRAMEWORK_VERSION: cv.Version(5, 5, 5)},
|
||||
platform_data={KEY_VARIANT: variant},
|
||||
core_data={KEY_FRAMEWORK_VERSION: idf_version},
|
||||
platform_data={KEY_VARIANT: variant, KEY_IDF_VERSION: idf_version},
|
||||
full_config=full_config,
|
||||
)
|
||||
|
||||
@@ -360,3 +363,32 @@ async def test_to_code_sdkconfig(
|
||||
CORE.config = core_config
|
||||
await to_code(CONFIG_SCHEMA({CONF_ENABLE_LIGHT_SLEEP: light_sleep}))
|
||||
assert sdkconfig_calls.get(key, NOT_SET) is expected
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
("idf_version", "light_sleep", "kconfig", "guard"),
|
||||
[
|
||||
pytest.param(cv.Version(5, 5, 6), True, NOT_SET, True, id="idf55_wrap"),
|
||||
pytest.param(cv.Version(6, 0, 0), True, NOT_SET, True, id="idf600_wrap"),
|
||||
pytest.param(cv.Version(6, 0, 1), True, True, False, id="idf601_kconfig"),
|
||||
pytest.param(cv.Version(5, 5, 6), False, NOT_SET, False, id="light_sleep_off"),
|
||||
],
|
||||
)
|
||||
async def test_tick_overflow_guard(
|
||||
set_core_config: SetCoreConfigCallable,
|
||||
sdkconfig_calls: dict[str, object],
|
||||
idf_version: cv.Version,
|
||||
light_sleep: bool,
|
||||
kconfig: object,
|
||||
guard: bool,
|
||||
) -> None:
|
||||
"""IDF 6.0.1 has the overflow protection built in; older releases get the --wrap backport."""
|
||||
_set_variant(set_core_config, VARIANT_ESP32H2, idf_version=idf_version)
|
||||
CORE.config = {}
|
||||
await to_code(CONFIG_SCHEMA({CONF_ENABLE_LIGHT_SLEEP: light_sleep}))
|
||||
key = "CONFIG_PM_LIGHTSLEEP_TICK_OVERFLOW_PROTECTION"
|
||||
assert sdkconfig_calls.get(key, NOT_SET) is kconfig
|
||||
defines = {define.name for define in CORE.defines}
|
||||
assert ("USE_ESP32_PM_TICK_OVERFLOW_GUARD" in defines) is guard
|
||||
assert ("-Wl,--wrap=vTaskStepTick" in CORE.build_flags) is guard
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Every LibreTiny family frees closed TCP connections after about 1 s (TCP_MSL=250)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config_file", ["bk72xx.yaml", "rtl8710b.yaml", "rtl8720c.yaml", "ln882x.yaml"]
|
||||
)
|
||||
def test_lwip_tcp_msl_is_250(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
config_file: str,
|
||||
) -> None:
|
||||
generate_main(component_config_path(config_file))
|
||||
assert "TCP_MSL=250" in CORE.platformio_options["custom_options.lwip"]
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Tests for the usb_host sdkconfig defaults."""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from esphome.components.esp32 import RawSdkconfigValue
|
||||
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
|
||||
from esphome.core import CORE
|
||||
|
||||
|
||||
def test_usb_host_uses_default_control_transfer_size(
|
||||
generate_main: Callable[[str], str],
|
||||
) -> None:
|
||||
"""usb_host retains its existing 1024-byte default."""
|
||||
generate_main("tests/component_tests/usb_host/usb_host.yaml")
|
||||
|
||||
assert (
|
||||
CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS][
|
||||
"CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE"
|
||||
]
|
||||
== 1024
|
||||
)
|
||||
|
||||
|
||||
def test_usb_host_respects_explicit_control_transfer_size(
|
||||
generate_main: Callable[[str], str],
|
||||
) -> None:
|
||||
"""An explicit sdkconfig option takes precedence over the component default."""
|
||||
generate_main(
|
||||
"tests/component_tests/usb_host/usb_host_control_transfer_override.yaml"
|
||||
)
|
||||
|
||||
value = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS][
|
||||
"CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE"
|
||||
]
|
||||
assert isinstance(value, RawSdkconfigValue)
|
||||
assert value.value == "4096"
|
||||
@@ -0,0 +1,9 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
variant: esp32s3
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
usb_host:
|
||||
@@ -0,0 +1,11 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
variant: esp32s3
|
||||
framework:
|
||||
type: esp-idf
|
||||
sdkconfig_options:
|
||||
CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE: "4096"
|
||||
|
||||
usb_host:
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
|
||||
namespace esphome::bluetooth_connection::testing {
|
||||
|
||||
using ble_device_base::ESPBTUUID;
|
||||
@@ -46,4 +49,59 @@ TEST(GattUuidPacking, EstimateGrowsWithCharacteristicsAndMode) {
|
||||
EXPECT_LT(estimate_service_size(1, false), estimate_service_size(2, false));
|
||||
}
|
||||
|
||||
// BTstack hands every GATT UUID over as 128 bits, big-endian; uuid_from_be128 picks the short form
|
||||
static constexpr uint8_t BASE_TAIL[12] = {0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB};
|
||||
|
||||
static ESPBTUUID on_base(uint32_t value) {
|
||||
uint8_t be[16] = {static_cast<uint8_t>(value >> 24), static_cast<uint8_t>(value >> 16),
|
||||
static_cast<uint8_t>(value >> 8), static_cast<uint8_t>(value)};
|
||||
memcpy(be + 4, BASE_TAIL, sizeof(BASE_TAIL));
|
||||
return uuid_from_be128(be);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, SixteenBitOnBase) {
|
||||
const ESPBTUUID uuid = on_base(0x180F);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID16);
|
||||
EXPECT_EQ(uuid.uuid16(), 0x180F);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, ThirtyTwoBitOnBaseKeepsTopHalf) {
|
||||
// 5EC10001-0000-1000-8000-00805F9B34FB: BTstack's own uuid16 is 0x0001 for this one
|
||||
const ESPBTUUID uuid = on_base(0x5EC10001);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID32);
|
||||
EXPECT_EQ(uuid.uuid32(), 0x5EC10001u);
|
||||
|
||||
std::array<uint64_t, 2> uuid128{};
|
||||
uint32_t short_uuid = 0;
|
||||
fill_gatt_uuid(uuid128, short_uuid, uuid, true);
|
||||
EXPECT_EQ(short_uuid, 0x5EC10001u);
|
||||
|
||||
short_uuid = 0;
|
||||
fill_gatt_uuid(uuid128, short_uuid, uuid, false);
|
||||
EXPECT_EQ(short_uuid, 0u);
|
||||
EXPECT_EQ(uuid128[0], 0x5EC1000100001000ULL);
|
||||
EXPECT_EQ(uuid128[1], 0x800000805F9B34FBULL);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, ShortFormBoundary) {
|
||||
EXPECT_EQ(on_base(0xFFFF).type(), ESPBTUUID::Type::UUID16);
|
||||
const ESPBTUUID uuid = on_base(0x10000);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID32);
|
||||
EXPECT_EQ(uuid.uuid32(), 0x10000u);
|
||||
}
|
||||
|
||||
TEST(GattUuidFromBe128, OffBaseStaysFullWidth) {
|
||||
const uint8_t big_endian[16] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF,
|
||||
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
|
||||
const ESPBTUUID uuid = uuid_from_be128(big_endian);
|
||||
ASSERT_EQ(uuid.type(), ESPBTUUID::Type::UUID128);
|
||||
EXPECT_EQ(uuid, ESPBTUUID::from_raw_reversed(big_endian));
|
||||
|
||||
// One byte off the base tail is a different 128-bit UUID, not a short one
|
||||
uint8_t near_base[16] = {0x00, 0x00, 0x18, 0x0F};
|
||||
memcpy(near_base + 4, BASE_TAIL, sizeof(BASE_TAIL));
|
||||
near_base[15] ^= 1;
|
||||
EXPECT_EQ(uuid_from_be128(near_base).type(), ESPBTUUID::Type::UUID128);
|
||||
}
|
||||
|
||||
} // namespace esphome::bluetooth_connection::testing
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# touchscreen.h includes display.h
|
||||
manifest.dependencies = manifest.dependencies + ["display"]
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/cst816/touchscreen/cst816_touchscreen.h"
|
||||
|
||||
namespace esphome::cst816::testing {
|
||||
|
||||
static constexpr uint8_t ADDRESS = 0x15;
|
||||
// The driver reads REG_STATUS onwards in one transfer: status, gesture, touch count, then two points.
|
||||
static constexpr size_t FRAME_SIZE = 13;
|
||||
|
||||
/// Serves one fixed status frame.
|
||||
class FrameBus final : public i2c::I2CBus {
|
||||
public:
|
||||
explicit FrameBus(std::array<uint8_t, FRAME_SIZE> frame) : frame_(frame) {}
|
||||
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *write_buffer, size_t write_count, uint8_t *read_buffer,
|
||||
size_t read_count) override {
|
||||
EXPECT_EQ(address, ADDRESS);
|
||||
for (size_t i = 0; i < read_count; i++)
|
||||
read_buffer[i] = i < FRAME_SIZE ? this->frame_[i] : 0;
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
protected:
|
||||
std::array<uint8_t, FRAME_SIZE> frame_;
|
||||
};
|
||||
|
||||
inline std::array<uint8_t, FRAME_SIZE> make_frame(uint8_t touch_num, uint16_t x = 0, uint16_t y = 0) {
|
||||
std::array<uint8_t, FRAME_SIZE> frame{};
|
||||
frame[REG_TOUCH_NUM] = touch_num;
|
||||
frame[REG_XPOS_HIGH] = (x >> 8) & 0x0F;
|
||||
frame[REG_XPOS_LOW] = x & 0xFF;
|
||||
frame[REG_YPOS_HIGH] = (y >> 8) & 0x0F;
|
||||
frame[REG_YPOS_LOW] = y & 0xFF;
|
||||
return frame;
|
||||
}
|
||||
|
||||
} // namespace esphome::cst816::testing
|
||||
@@ -0,0 +1,88 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "../common.h"
|
||||
|
||||
namespace esphome::cst816::testing {
|
||||
|
||||
class CST816TouchscreenTest : public ::testing::Test {
|
||||
protected:
|
||||
void feed_(const std::array<uint8_t, FRAME_SIZE> &frame) {
|
||||
this->bus_ = std::make_unique<FrameBus>(frame);
|
||||
this->touchscreen_.set_i2c_bus(this->bus_.get());
|
||||
this->touchscreen_.set_i2c_address(ADDRESS);
|
||||
this->touchscreen_.update_touches();
|
||||
}
|
||||
|
||||
std::unique_ptr<FrameBus> bus_;
|
||||
CST816Touchscreen touchscreen_;
|
||||
};
|
||||
|
||||
// An idle frame reports 0xFF in the touch count byte and 0xFFF coordinates. Masking 0xFF to the
|
||||
// low two bits turns that into three touches at the maximum position, a phantom tap.
|
||||
TEST_F(CST816TouchscreenTest, IdleAllOnesFrameIsIgnored) {
|
||||
this->feed_(make_frame(0xFF, 0x0FFF, 0x0FFF));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, ZeroTouchCountIsIgnored) {
|
||||
this->feed_(make_frame(0));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// Three is the boundary the guard rejects: the old mask turned a count of three into three
|
||||
// touches, so this is the value whose behaviour changes.
|
||||
TEST_F(CST816TouchscreenTest, TouchCountThreeIsIgnored) {
|
||||
this->feed_(make_frame(3, 100, 200));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// The count is the whole low nibble, so 0x05 must not be masked down to one touch by a 0x03 mask.
|
||||
TEST_F(CST816TouchscreenTest, TouchCountFiveIsIgnored) {
|
||||
this->feed_(make_frame(0x05, 100, 200));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, SingleTouchIsReported) {
|
||||
this->feed_(make_frame(1, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 300);
|
||||
EXPECT_EQ(touches[0].y_raw, 100);
|
||||
}
|
||||
|
||||
// CST826/CST836 can report two points; the driver only consumes the first one.
|
||||
TEST_F(CST816TouchscreenTest, TwoPointFrameReportsFirstPoint) {
|
||||
this->feed_(make_frame(2, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 300);
|
||||
EXPECT_EQ(touches[0].y_raw, 100);
|
||||
}
|
||||
|
||||
TEST_F(CST816TouchscreenTest, SentinelPositionIsIgnored) {
|
||||
this->feed_(make_frame(1, 0x0FFF, 100));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// The sentinel is checked on both axes; a valid X with Y=0xFFF is still an idle reading.
|
||||
TEST_F(CST816TouchscreenTest, SentinelYPositionIsIgnored) {
|
||||
this->feed_(make_frame(1, 100, 0x0FFF));
|
||||
EXPECT_TRUE(this->touchscreen_.get_touches().empty());
|
||||
}
|
||||
|
||||
// x_raw_max_/y_raw_max_ are calibration endpoints, not validity limits: the base class applies them
|
||||
// after swapping axes and clamps readings outside them. A touch beyond the calibrated maximum is
|
||||
// still a real touch and must reach the base class.
|
||||
TEST_F(CST816TouchscreenTest, CalibrationBoundsDoNotDropTouches) {
|
||||
this->touchscreen_.set_calibration(0, 240, 0, 320);
|
||||
this->touchscreen_.set_swap_xy(true);
|
||||
this->feed_(make_frame(1, 300, 100));
|
||||
auto touches = this->touchscreen_.get_touches();
|
||||
ASSERT_EQ(touches.size(), 1u);
|
||||
EXPECT_EQ(touches[0].x_raw, 100);
|
||||
EXPECT_EQ(touches[0].y_raw, 300);
|
||||
}
|
||||
|
||||
} // namespace esphome::cst816::testing
|
||||
@@ -0,0 +1,6 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# dht is a sensor platform; its header needs the sensor component
|
||||
manifest.dependencies = manifest.dependencies + ["sensor"]
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "esphome/components/dht/dht.h"
|
||||
|
||||
namespace esphome::dht::testing {
|
||||
|
||||
TEST(DHTDecodeTemperature, Positive) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0000), 0);
|
||||
EXPECT_EQ(decode_dht22_temperature(0x00E7), 231); // 23.1 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x01F4), 500); // 50.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, SignAndMagnitude) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8034), -52); // -5.2 C, read as -5.3 C before
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8001), -1); // -0.1 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8000), 0); // -0.0 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x8190), -400); // -40.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, SixteenBitTwosComplement) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0xFFCC), -52); // -5.2 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0xFE70), -400); // -40.0 C
|
||||
}
|
||||
|
||||
TEST(DHTDecodeTemperature, TwelveBitTwosComplement) {
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0FCC), -52); // -5.2 C
|
||||
EXPECT_EQ(decode_dht22_temperature(0x0E70), -400); // -40.0 C
|
||||
}
|
||||
|
||||
} // namespace esphome::dht::testing
|
||||
@@ -0,0 +1,2 @@
|
||||
packages:
|
||||
dht: !include common.yaml
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "esphome/components/epaper_spi/epaper_spi_jd79660.h"
|
||||
#include "esphome/components/epaper_spi/epaper_spi_t133a01.h"
|
||||
#include "esphome/components/epaper_spi/epaper_waveshare_bwr.h"
|
||||
#include "esphome/components/epaper_spi/epaper_weact_3c.h"
|
||||
|
||||
namespace esphome::epaper_spi::testing {
|
||||
namespace {
|
||||
|
||||
/// Reaches the protected EPaperBase members of any driver, including final ones, through member pointers.
|
||||
class EPaperBaseAccess : public EPaperBase {
|
||||
public:
|
||||
/// Leaves the display as a completed refresh leaves it: nothing drawn and no full update pending.
|
||||
static void set_refreshed(EPaperBase &display) {
|
||||
EXPECT_TRUE((display.*&EPaperBaseAccess::init_buffer_)(display.*&EPaperBaseAccess::buffer_length_));
|
||||
(display.*&EPaperBaseAccess::reset_bounds_)();
|
||||
display.*&EPaperBaseAccess::full_update_requested_ = false;
|
||||
}
|
||||
/// The request count is shared by the whole test binary, so a display left mid-update must give its request back.
|
||||
static void stop_fast_loop(EPaperBase &display) { (display.*&EPaperBaseAccess::high_frequency_loop_).stop(); }
|
||||
};
|
||||
|
||||
template<typename Driver, typename... Args> std::unique_ptr<Driver> make_refreshed(Args... args) {
|
||||
auto display = std::make_unique<Driver>("test", 16, 2, nullptr, 0, args...);
|
||||
EPaperBaseAccess::set_refreshed(*display);
|
||||
return display;
|
||||
}
|
||||
|
||||
template<typename Driver> std::unique_ptr<Driver> make_display() { return make_refreshed<Driver>(); }
|
||||
|
||||
template<> std::unique_ptr<EPaperJD79660> make_display() { return make_refreshed<EPaperJD79660>(nullptr, 0); }
|
||||
|
||||
/// Runs the UPDATE state; true if the update goes on to send the frame.
|
||||
bool update_is_sent(EPaperBase &display) {
|
||||
display.update();
|
||||
display.loop();
|
||||
return display.is_updating();
|
||||
}
|
||||
|
||||
/// fill() writes the whole buffer without drawing pixels, so it must mark the frame drawn itself. Otherwise the
|
||||
/// UPDATE state finds nothing drawn after a refresh, and returns to idle without sending the frame.
|
||||
template<typename Driver> class EPaperFillMarksDrawn : public ::testing::Test {
|
||||
protected:
|
||||
void TearDown() override { EPaperBaseAccess::stop_fast_loop(*this->display_); }
|
||||
std::unique_ptr<Driver> display_ = make_display<Driver>();
|
||||
};
|
||||
|
||||
using Drivers = ::testing::Types<EPaperWaveshareBWR, EPaperT133A01, EPaperJD79660, EPaperWeAct3C>;
|
||||
TYPED_TEST_SUITE(EPaperFillMarksDrawn, Drivers);
|
||||
|
||||
TYPED_TEST(EPaperFillMarksDrawn, FillOnlyUpdateIsSent) {
|
||||
this->display_->set_auto_clear(false);
|
||||
this->display_->fill(Color::WHITE);
|
||||
|
||||
EXPECT_TRUE(update_is_sent(*this->display_)) << "fill-only update was skipped";
|
||||
}
|
||||
|
||||
/// Auto clear fills the frame before the lambda runs, so an update whose lambda draws nothing still erases the
|
||||
/// previous image.
|
||||
TYPED_TEST(EPaperFillMarksDrawn, AutoClearUpdateIsSentWhenTheLambdaDrawsNothing) {
|
||||
this->display_->set_writer([](display::Display &) {});
|
||||
|
||||
EXPECT_TRUE(update_is_sent(*this->display_)) << "auto clear did not erase the previous image";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace esphome::epaper_spi::testing
|
||||
@@ -2,3 +2,7 @@ packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
|
||||
# IPv6 with an IP sensor: compiles the IPv6 event handler's listener notification
|
||||
network:
|
||||
enable_ipv6: true
|
||||
@@ -1,8 +1,10 @@
|
||||
from pathlib import Path
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components.logger import CONF_BOOT_LOG_BUFFER_SIZE, request_log_listener
|
||||
from esphome.const import CONF_ESPHOME, CONF_INCLUDES
|
||||
from esphome.core import CORE
|
||||
from esphome.loader import FileResource
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
@@ -13,6 +15,10 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# logger must run its to_code during C++ test builds because it configures
|
||||
# the logging subsystem used by ESP_LOG* macros throughout component code.
|
||||
manifest.enable_codegen()
|
||||
# Compiled into the LibreTiny task log buffer test; empty on its own without USE_LIBRETINY
|
||||
manifest.add_resources(
|
||||
FileResource("esphome.components.logger", "task_log_buffer_libretiny.cpp")
|
||||
)
|
||||
|
||||
original_to_code = manifest.to_code
|
||||
|
||||
@@ -22,6 +28,10 @@ def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
if any(Path(p) == TESTS_DIR for p in CORE.config[CONF_ESPHOME][CONF_INCLUDES]):
|
||||
config = {**config, CONF_BOOT_LOG_BUFFER_SIZE: 512}
|
||||
request_log_listener()
|
||||
# FreeRTOS doubles for the LibreTiny task log buffer test
|
||||
cg.add_build_flag(
|
||||
f"-I{CORE.relative_src_path('logger', '__libretiny_sdk')}"
|
||||
)
|
||||
await original_to_code(config)
|
||||
|
||||
manifest.to_code = to_code
|
||||
@@ -0,0 +1,2 @@
|
||||
#pragma once
|
||||
// Host double for the LibreTiny FreeRTOS headers used by task_log_buffer_libretiny.cpp
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
// Single-threaded mutex double: every take succeeds
|
||||
using SemaphoreHandle_t = int *;
|
||||
inline SemaphoreHandle_t xSemaphoreCreateMutex() {
|
||||
static int mutex;
|
||||
return &mutex;
|
||||
}
|
||||
inline void vSemaphoreDelete(SemaphoreHandle_t /*mutex*/) {}
|
||||
inline int xSemaphoreTake(SemaphoreHandle_t /*mutex*/, int /*ticks*/) { return 1; }
|
||||
inline int xSemaphoreGive(SemaphoreHandle_t /*mutex*/) { return 1; }
|
||||
@@ -0,0 +1 @@
|
||||
#pragma once
|
||||
@@ -0,0 +1,6 @@
|
||||
// The same tests with a buffer size that needs no rounding
|
||||
#define TASK_LOG_TEST_NS libretiny_task_log_768
|
||||
#define TASK_LOG_TEST_SUITE LibreTinyTaskLogBuffer768
|
||||
#define TASK_LOG_TEST_SIZE static_cast<size_t>(768)
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include): reuse the tests with another buffer size.
|
||||
#include "task_log_buffer_libretiny_test.cpp"
|
||||
@@ -0,0 +1,154 @@
|
||||
#ifdef USE_HOST
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include <FreeRTOS.h>
|
||||
#include <semphr.h>
|
||||
#include <task.h>
|
||||
|
||||
#include "esphome/core/defines.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
// Not a multiple of 4; task_log_buffer_libretiny_768_test.cpp reuses this file with an aligned size
|
||||
#ifndef TASK_LOG_TEST_NS
|
||||
#define TASK_LOG_TEST_NS libretiny_task_log_766
|
||||
#define TASK_LOG_TEST_SUITE LibreTinyTaskLogBuffer766
|
||||
#define TASK_LOG_TEST_SIZE static_cast<size_t>(766)
|
||||
#endif
|
||||
|
||||
// Compile the LibreTiny buffer against the FreeRTOS doubles in __libretiny_sdk, in a namespace per size
|
||||
#define USE_LIBRETINY
|
||||
#ifndef USE_ESPHOME_TASK_LOG_BUFFER
|
||||
#define USE_ESPHOME_TASK_LOG_BUFFER
|
||||
#endif
|
||||
#undef ESPHOME_TASK_LOG_BUFFER_SIZE
|
||||
#define ESPHOME_TASK_LOG_BUFFER_SIZE TASK_LOG_TEST_SIZE
|
||||
namespace TASK_LOG_TEST_NS {
|
||||
// Not global, where speaker_source's FreeRTOS double defines it in the same build
|
||||
inline constexpr int pdTRUE = 1;
|
||||
// NOLINTNEXTLINE(bugprone-suspicious-include): exercise production code with the host FreeRTOS double.
|
||||
#include "esphome/components/logger/task_log_buffer_libretiny.cpp"
|
||||
} // namespace TASK_LOG_TEST_NS
|
||||
#undef USE_LIBRETINY
|
||||
|
||||
namespace {
|
||||
|
||||
using TaskLogBuffer = TASK_LOG_TEST_NS::esphome::logger::TaskLogBuffer;
|
||||
|
||||
const char *const TAGS[] = {"a", "bb", "ccc"};
|
||||
|
||||
bool send_format(TaskLogBuffer &buffer, const char *tag, const char *format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
bool sent = buffer.send_message_thread_safe(3, tag, 1, nullptr, format, args);
|
||||
va_end(args);
|
||||
return sent;
|
||||
}
|
||||
|
||||
class TASK_LOG_TEST_SUITE : public ::testing::Test {
|
||||
protected:
|
||||
// Records the trimmed text expected back when the buffer accepts it
|
||||
bool send_(const char *tag, const std::string &text) {
|
||||
if (!send_format(this->buffer_, tag, "%s", text.c_str()))
|
||||
return false;
|
||||
std::string trimmed = text;
|
||||
while (!trimmed.empty() && trimmed.back() == '\n')
|
||||
trimmed.pop_back();
|
||||
this->expected_.emplace_back(tag, trimmed);
|
||||
return true;
|
||||
}
|
||||
// Stops one past what was sent, so a broken ring cannot loop forever
|
||||
void drain_(size_t count = SIZE_MAX) {
|
||||
TaskLogBuffer::LogMessage *msg;
|
||||
uint16_t length;
|
||||
for (count = std::min(count, this->expected_.size() + 1);
|
||||
count > 0 && this->buffer_.borrow_message_main_loop(msg, length); count--) {
|
||||
if (reinterpret_cast<uintptr_t>(msg) % alignof(TaskLogBuffer::LogMessage) != 0)
|
||||
this->misaligned_++;
|
||||
if (this->expected_.empty() || this->expected_.front().first != msg->tag ||
|
||||
this->expected_.front().second != std::string(msg->text_data(), length) || msg->text_data()[length] != '\0') {
|
||||
this->mismatches_++;
|
||||
} else {
|
||||
this->expected_.pop_front();
|
||||
}
|
||||
this->buffer_.release_message_main_loop();
|
||||
}
|
||||
}
|
||||
|
||||
TaskLogBuffer buffer_;
|
||||
std::deque<std::pair<const char *, std::string>> expected_;
|
||||
int misaligned_{0};
|
||||
int mismatches_{0};
|
||||
};
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, HeadersStayAligned) {
|
||||
for (size_t length = 1; length <= 40; length++) {
|
||||
ASSERT_TRUE(this->send_(TAGS[0], std::string(length, 'x')));
|
||||
if (length % 4 == 0)
|
||||
this->drain_();
|
||||
}
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, TrimsTrailingNewlinesAndKeepsOrder) {
|
||||
ASSERT_TRUE(this->send_(TAGS[0], "one"));
|
||||
ASSERT_TRUE(this->send_(TAGS[1], "two\n"));
|
||||
ASSERT_TRUE(this->send_(TAGS[2], "three\n\n"));
|
||||
ASSERT_TRUE(this->send_(TAGS[0], "four\nlines"));
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
EXPECT_TRUE(this->expected_.empty());
|
||||
EXPECT_FALSE(this->buffer_.has_messages());
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, EmptyBufferAcceptsEveryLengthAcrossWraps) {
|
||||
// Every write position comes up, including a message ending less than a header before the end
|
||||
for (int round = 0; round < 8; round++) {
|
||||
for (size_t length = 1; length <= 250; length++) {
|
||||
ASSERT_TRUE(this->send_(TAGS[length % 3], std::string(length, 'a' + length % 26) + (round % 2 ? "\n" : "")))
|
||||
<< "round " << round << " length " << length;
|
||||
this->drain_();
|
||||
}
|
||||
}
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
}
|
||||
|
||||
TEST_F(TASK_LOG_TEST_SUITE, RandomizedTrafficMatchesWhatWasSent) {
|
||||
std::mt19937 rng(1);
|
||||
for (int op = 0; op < 200000; op++) {
|
||||
if (rng() % 3 != 0) {
|
||||
std::string text(1 + rng() % 120, 'x');
|
||||
for (auto &c : text)
|
||||
c = 'a' + rng() % 26;
|
||||
if (rng() % 2)
|
||||
text += "\n";
|
||||
if (rng() % 5 == 0)
|
||||
text += "\n\n";
|
||||
this->send_(TAGS[rng() % 3], text);
|
||||
} else {
|
||||
this->drain_(rng() % 4);
|
||||
}
|
||||
}
|
||||
this->drain_();
|
||||
EXPECT_EQ(this->misaligned_, 0);
|
||||
EXPECT_EQ(this->mismatches_, 0);
|
||||
EXPECT_TRUE(this->expected_.empty());
|
||||
EXPECT_TRUE(this->send_(TAGS[0], "still accepted"));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
#endif // USE_HOST
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user