Compare commits

..
118 changed files with 1243 additions and 4105 deletions

No files matched your search

-45
View File
@@ -128,51 +128,6 @@ helper; `AGENTS.md` section 4 and the `component-codegen` skill have the detail.
| action or condition class that only forwards to the parent | `register_apply_action` / `register_apply_condition` |
| enum-to-string `switch` returning literals | `PROGMEM_STRING_TABLE` with `get_log_str` / `get_progmem_str` |
| `if (x := config.get(CONF_X)) is not None: cg.add(var.set_x(x))` | `cg.add_optional(var.set_x, config.get(CONF_X))`, when the setter takes the value unchanged |
| `x = (x & ~mask) \| (on ? mask : 0)` or a bit-reversal loop | `assign_bits(x, mask, on)`, `reverse_bits(x)` (`esphome/core/helpers.h`) |
| `x < lo ? lo : (x > hi ? hi : x)` | `std::clamp(x, lo, hi)` |
| I2C read, mask, write by hand; private 16-bit register byte helpers | `update_register`, `update_register16`, `read_byte_reg16`, `write_byte_reg16` |
| custom validator that checks which keys are set, or one schema with model checks | `cv.has_exactly_one_key`, `cv.has_at_most_one_key`, `cv.Inclusive`/`cv.Exclusive`, `cv.typed_schema` per model |
## Cleanups automated reviews keep missing
Multi-pass cleanup reviews of contributor PRs find these again and again, and single-pass reviews
almost never flag them. Look for each one explicitly; the matching `AGENTS.md` section 4 entry has the
detail.
- **Copies within the PR** (the most common finding): two functions, branches, platform files or tests
that differ in a constant or two. Ask for one helper, loop or table.
- **State that copies other state:** a `write_pending_` bool beside a timer (use the return value of
`cancel_timeout(ID)`), a `has_x_` bool beside `x_` (use `NAN` or a sentinel), an enum that can be worked
out from stored fields.
- **Dead guards:** null checks on members codegen always sets, `is_failed()` checks in `loop()`, range
checks the schema already enforces, `default:` in a `switch` over every value of an `enum class` the
component sets itself (not one cast from bus data), calls that set a member to its default
(`set_cs_pin(nullptr)`).
- **Member layout:** field order that leaves padding, `int`/`uint32_t` for values that fit a `uint8_t`,
an `enum class` without `: uint8_t`, several `bool` members that could share a byte. Each costs RAM per
instance.
- **C++ work that belongs in codegen:** scaling, clamping, checksums or register bytes computed at boot
from config values; ask for the plain value from `to_code`.
- **Two `switch` ladders for one mapping:** encode and decode of the same value pairs should share one
`static constexpr` table (`PROGMEM` on ESP8266).
- **Compile-time constants:** `static const` or `#define` with a constant value (use `static constexpr`),
constant tables not in `PROGMEM`, unused constants.
- **Code for one model or feature compiled into every build:** ask for a `cg.add_define()` emitted only
when the config uses it, with the runtime check inside the `#ifdef`.
- **Failure handling:** `mark_failed()` outside `setup()` (runtime failures set a warning that the next
success clears), an error enum that only picks a log message.
- **Logging** that does not follow https://developers.esphome.io/architecture/logging/: `ESP_LOGD` on every
reading, "Setting up" or "initialized" lines in `setup()`, a `dump_config()` made of single-line
`ESP_LOGCONFIG` calls where related lines fit one call, a name helper that returns `const char *` instead
of `const LogString *`.
- **Leaf classes** that are not `final`.
- **Unused helpers, includes and imports** left behind; lint does not catch most of them.
- **Comments that restate the code** or tell its history: a block comment that walks through the next
ten lines, a docstring that repeats the signature, a derivation that a one-line note plus a datasheet
section would cover.
- **Tests:** near-identical test functions that differ only in inputs (ask for `pytest.mark.parametrize`
or a table-driven gtest), tests that repeat another test, test YAML that sets options to their defaults.
## Python conventions
+1 -24
View File
@@ -247,7 +247,6 @@ file does, and it is the authority when they disagree. The most useful starting
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
`LineReader<N>`, fixed-length binary frames with `FrameReader<N, HEADER...>`; I2C has `update_register`,
`update_register16`, `read_byte_reg16` and `write_byte_reg16` for 16-bit register addresses,
`write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id` and `read_bytes_16_le`.
`if (!this->status_comm_result(ok)) return;` sets or clears the warning; an earlier step of a multi-step
poll uses `status_comm_check(ok)`, which only sets it, so the last step must clear it; in `setup()`,
@@ -312,27 +311,6 @@ file does, and it is the authority when they disagree. The most useful starting
text::Text *source_{nullptr};
};
```
* **No state that copies other state:** a flag that mirrors a timer, a `has_x_` bool beside `x_`, or an enum
that can be worked out from fields already stored is a second source of truth. Use the source:
`pending = this->cancel_timeout(ID)`, an unset value of `NAN` or an out-of-range sentinel.
* **No dead guards:** do not check what the caller or core already guarantees: a member that codegen always
sets, `is_failed()` in `loop()` (core stops calling it), a value the config validation already limits, a
`default:` in a `switch` over every value of an `enum class` the component sets itself (keep it when the
value is cast from bus data).
* **Member layout:** order fields so the compiler adds no padding (usually largest first), store small codes
as `uint8_t`, declare `enum class X : uint8_t`, and pack flags into one byte.
* **Work out constants in Python:** math that only depends on the configuration (register bytes, scale
factors, thresholds, checksums) is done in `to_code` and passed as a plain value, not done in C++ at
boot.
* **One table for both directions:** a value that is encoded and decoded through the same mapping uses one
`static constexpr` (`PROGMEM` on ESP8266) table of `{value, code}` pairs, not two `switch` ladders.
* **Logging:** follow https://developers.esphome.io/architecture/logging/ for log levels and `dump_config()`.
In short: a reading is logged with `ESP_LOGV`, not `ESP_LOGD` on every update; `setup()` logs no
"Setting up" or "initialized" line (core logs setup); `dump_config()` combines related lines into one
`ESP_LOGCONFIG` call, within the 512-byte log buffer.
* **Leaf classes are `final`:** a component or entity class nothing derives from is declared `final`.
* **No copies within the PR:** two functions, branches or platform files that differ in a constant or two
become one helper, loop or table; helpers, includes and imports nothing uses are deleted.
* **Component Code Generation:** every component's `__init__.py` defines `DOMAIN` (its own name, checked by
CI). Hub entities go in platform files (`sensor.py`, ...) that take the hub's id, not under the hub's own
@@ -379,8 +357,7 @@ file does, and it is the authority when they disagree. The most useful starting
`script/test_build_components -c <component>`. Never define buses directly in test YAML: include the
shared packages from `tests/test_build_components/common/` with dict-style `packages:`. Test file naming,
`validate.*.yaml` config-only tests, CI grouping, C++ unit tests and integration tests are in the
`component-tests` skill. Tests that differ only in their inputs are one `pytest.mark.parametrize` test
or a table-driven gtest.
`component-tests` skill.
* **Debugging and Troubleshooting:**
* **Debug Tools:**
-1
View File
@@ -701,7 +701,6 @@ esphome/components/toshiba/* @kbx81
esphome/components/touchscreen/* @jesserockz @nielsnl68
esphome/components/tsl2591/* @wjcarpenter
esphome/components/tt21100/* @kroimon
esphome/components/tuya/* @dwmw2 @ssieb
esphome/components/tuya/binary_sensor/* @jesserockz
esphome/components/tuya/climate/* @jesserockz
esphome/components/tuya/number/* @frankiboy1
+1 -1
View File
@@ -385,7 +385,7 @@ async def to_code(config: ConfigType) -> None:
# Adds a define and IDF component for legacy `audio_decoder.cpp`.
if data.flac_support:
cg.add_define("USE_AUDIO_FLAC_SUPPORT")
add_idf_component(name="esphome/micro-flac", ref="0.3.1")
add_idf_component(name="esphome/micro-flac", ref="0.3.0")
_emit_memory_pair(
data.flac.buffer_memory,
"CONFIG_MICRO_FLAC_PREFER_PSRAM",
@@ -1,7 +1,7 @@
import logging
import esphome.codegen as cg
from esphome.components import web_server_base, web_server_idf, wifi
from esphome.components import web_server_base, wifi
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
from esphome.components.wifi import DOMAIN as WIFI_DOMAIN
import esphome.config_validation as cv
@@ -38,13 +38,6 @@ DOMAIN = "captive_portal"
captive_portal_ns = cg.esphome_ns.namespace("captive_portal")
CaptivePortal = captive_portal_ns.class_("CaptivePortal", cg.Component)
def _require_plain_http(config: ConfigType) -> ConfigType:
# Phones check for a captive portal over plain HTTP.
web_server_idf.require_plain_http(DOMAIN)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
@@ -65,7 +58,6 @@ CONFIG_SCHEMA = cv.All(
PLATFORM_RTL87XX,
]
),
_require_plain_http,
)
@@ -1,28 +0,0 @@
#include "epaper_spi_ssd1677_bwr.h"
namespace esphome::epaper_spi {
bool EPaperSSD1677BWR::reset() {
if (!EPaperBase::reset())
return false;
this->command(0x12); // SWRESET; the INITIALISE state waits for busy to clear
return true;
}
void EPaperSSD1677BWR::set_window() {
const uint16_t x_end = this->width_ - 1;
const uint16_t y_first = this->offset_height_ + this->height_ - 1;
const uint16_t y_last = this->offset_height_;
this->cmd_data(0x44, {0x00, 0x00, (uint8_t) x_end, (uint8_t) (x_end >> 8)});
// Y runs down from the last gate, to match data entry mode 0x01
this->cmd_data(0x45, {(uint8_t) y_first, (uint8_t) (y_first >> 8), (uint8_t) y_last, (uint8_t) (y_last >> 8)});
this->cmd_data(0x4E, {0x00, 0x00});
this->cmd_data(0x4F, {(uint8_t) y_first, (uint8_t) (y_first >> 8)});
}
void EPaperSSD1677BWR::refresh_screen(bool partial) {
this->cmd_data(0x22, {0xF7});
this->command(0x20);
}
} // namespace esphome::epaper_spi
@@ -1,32 +0,0 @@
#pragma once
#include "epaper_weact_3c.h"
namespace esphome::epaper_spi {
/**
* SSD1677 3-color (black/white/red) e-paper displays, e.g. the Waveshare 7.5" HD (B).
*
* Drawn and sent as EPaperWeAct3C, except that the SSD1677 addresses RAM X in pixels with two bytes, and the RAM is
* written from the last gate down (data entry mode 0x01), as in Waveshare's reference code. The controller scans
* offset_height + height gates and the panel is on the last height of them, so the RAM window covers only those.
* The window is exactly the panel, so after the first plane the address counter wraps back to the start for the
* second.
*/
class EPaperSSD1677BWR : public EPaperWeAct3C {
public:
EPaperSSD1677BWR(const char *name, uint16_t width, uint16_t height, const uint8_t *init_sequence,
size_t init_sequence_length, uint16_t offset_height)
: EPaperWeAct3C(name, width, height, init_sequence, init_sequence_length), offset_height_(offset_height) {}
protected:
bool reset() override;
void set_window() override;
// The full refresh (0x22 0xF7) powers the panel up itself, as Waveshare's reference code relies on.
void power_on() override {}
void refresh_screen(bool partial) override;
uint16_t offset_height_;
};
} // namespace esphome::epaper_spi
@@ -6,7 +6,7 @@ namespace esphome::epaper_spi {
ESPHOME_LOG_TAG(TAG, "epaper_weact_3c");
void EPaperWeAct3C::set_window() {
void EPaperWeAct3C::set_window_() {
// For full screen refresh, we always start from (0,0)
// The y_low_/y_high_ values track the dirty region for optimization,
// but for display refresh we need to write from the beginning
@@ -39,7 +39,7 @@ bool HOT EPaperWeAct3C::transfer_data() {
// A push only yields after sending some data, so it never stops at exactly 0 or half_buffer.
if (this->current_data_index_ == 0) {
ESP_LOGV(TAG, "transfer_data: sending RED buffer (0x26)");
this->set_window(); // Reset RAM X/Y counters to start position
this->set_window_(); // Reset RAM X/Y counters to start position
this->command(0x26);
this->current_data_index_ = half_buffer;
}
@@ -19,7 +19,7 @@ class EPaperWeAct3C : public EPaperBWR {
: EPaperBWR(name, width, height, init_sequence, init_sequence_length, invert_red, /*red_sets_black=*/true) {}
protected:
virtual void set_window();
void set_window_();
void refresh_screen(bool partial) override;
void power_on() override;
void power_off() override;
@@ -1,92 +0,0 @@
"""Black/White/Red e-paper displays using the SSD1677 controller.
Supported models:
- waveshare-7.5in-hd-b: 880x528 pixels (Waveshare 7.5" HD (B), EPD_7in5b_HD)
The controller scans offset_height + height gates, and the panel is on the last height of them;
offset_height (under dimensions) is a property of the panel.
"""
import esphome.config_validation as cv
from esphome.const import (
CONF_BUSY_PIN,
CONF_DIMENSIONS,
CONF_HEIGHT,
CONF_OFFSET_HEIGHT,
CONF_RESET_PIN,
CONF_WIDTH,
)
from esphome.types import ConfigType
from . import EpaperModel
# The SSD1677 drives this many sources (columns) and gates (rows)
SOURCE_COUNT = 960
GATE_COUNT = 680
class SSD1677BWR(EpaperModel):
"""EpaperModel class for Black/White/Red displays using the SSD1677 controller."""
source_files = (
"epaper_spi_bwr.cpp",
"epaper_weact_3c.cpp",
"epaper_spi_ssd1677_bwr.cpp",
)
def __init__(self, name: str, **defaults: object) -> None:
defaults.setdefault(CONF_OFFSET_HEIGHT, 0)
super().__init__(name, "EPaperSSD1677BWR", **defaults)
def option(
self, name: str, fallback: object = cv.UNDEFINED
) -> cv.Optional | cv.Required:
if name in (CONF_RESET_PIN, CONF_BUSY_PIN):
return cv.Required(name)
return super().option(name, fallback)
def validate_config(self, config: ConfigType) -> ConfigType:
width, height = self.get_dimensions(config)
if width > SOURCE_COUNT:
raise cv.Invalid(
f"The panel width must not exceed {SOURCE_COUNT} sources",
path=[CONF_DIMENSIONS, CONF_WIDTH],
)
# The model's defaults fit, so this fails only with explicit dimensions, which always have a height
if self.get_offset_height(config) + height > GATE_COUNT:
raise cv.Invalid(
f"{CONF_OFFSET_HEIGHT} plus the panel height must not exceed {GATE_COUNT} gates",
path=[CONF_DIMENSIONS, CONF_HEIGHT],
)
return config
def get_constructor_args(self, config: ConfigType) -> tuple:
return (self.get_offset_height(config),)
def get_init_sequence(self, config: ConfigType) -> tuple:
"""Follow Waveshare's EPD_7in5b_HD init, less the steps the driver does itself.
The RAM window is set before each push, the RAM fills (0x46, 0x47) are not needed as both
planes are always written in full, and the full refresh (0x22 0xF7) loads the waveform.
"""
_, height = self.get_dimensions(config)
last_gate = self.get_offset_height(config) + height - 1
return (
(0x0C, 0xAE, 0xC7, 0xC3, 0xC0, 0x40), # Booster soft start
# Driver output control: gate count, scanned bottom to top
(0x01, last_gate & 0xFF, last_gate >> 8, 0x01),
(0x11, 0x01), # Data entry mode: X increments, Y decrements
(0x3C, 0x01), # Border waveform
(0x18, 0x80), # Internal temperature sensor
)
# Model: Waveshare 7.5" HD (B) - 880x528 pixels, SSD1677 controller
# The panel is on the last 528 of the controller's 680 gates. Waveshare's code sets 688 gates (0x2AF),
# more than the controller has, which shows the image a few rows too low.
SSD1677BWR(
"waveshare-7.5in-hd-b",
width=880,
height=528,
offset_height=152,
)
+9 -31
View File
@@ -835,22 +835,6 @@ def is_idf_sdkconfig_option_enabled(name: str) -> bool:
return value is not None and _format_sdkconfig_val(value) == "y"
def task_wdt_timeout_ms() -> int:
"""Return the configured task watchdog timeout; 0 when it is disabled.
For final validation only, as it reads the full config.
"""
return fv.full_config.get()[DOMAIN][CONF_WATCHDOG_TIMEOUT].total_milliseconds
def validate_task_wdt_enabled(config: ConfigType, key: str) -> None:
"""Final-validate that ``key`` is not set while the task watchdog is disabled."""
if key in config and task_wdt_timeout_ms() == 0:
raise cv.Invalid(
f"Cannot be set when {DOMAIN}.{CONF_WATCHDOG_TIMEOUT} is 0s", path=[key]
)
def set_idf_sdkconfig_default(name: str, value: SdkconfigValueType) -> None:
"""Set an sdkconfig option unless it is already set.
@@ -2526,13 +2510,7 @@ CONFIG_SCHEMA = cv.All(
): _validate_toolchain,
cv.Optional(CONF_WATCHDOG_TIMEOUT, default="5s"): cv.All(
cv.positive_time_period_seconds,
cv.Any(
cv.Range(max=cv.TimePeriod(seconds=0)),
cv.Range(
min=cv.TimePeriod(seconds=5), max=cv.TimePeriod(seconds=60)
),
msg="must be 0s (disabled) or between 5s and 60s",
),
cv.Range(min=cv.TimePeriod(seconds=5), max=cv.TimePeriod(seconds=60)),
),
}
),
@@ -3309,14 +3287,14 @@ async def to_code(config):
add_idf_sdkconfig_option("CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH", True)
# Setup watchdog
wdt = config[CONF_WATCHDOG_TIMEOUT].total_seconds
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_INIT", wdt != 0)
if wdt:
cg.add_define("USE_ESP32_TASK_WDT")
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_PANIC", True)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0", False)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1", False)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_TIMEOUT_S", wdt)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_INIT", True)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_PANIC", True)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0", False)
add_idf_sdkconfig_option("CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1", False)
add_idf_sdkconfig_option(
"CONFIG_ESP_TASK_WDT_TIMEOUT_S",
config[CONF_WATCHDOG_TIMEOUT].total_seconds,
)
# Disable dynamic log level control to save memory
add_idf_sdkconfig_option("CONFIG_LOG_DYNAMIC_LEVEL_CONTROL", False)
-2
View File
@@ -43,9 +43,7 @@ void arch_restart() {
void arch_init() {
// Enable the task watchdog only on the loop task (from which we're currently running)
#ifdef USE_ESP32_TASK_WDT
esp_task_wdt_add(nullptr);
#endif
// Handle OTA rollback: mark partition valid immediately unless USE_OTA_ROLLBACK is enabled,
// in which case safe_mode will mark it valid after confirming successful boot.
+1 -5
View File
@@ -49,11 +49,7 @@ __attribute__((always_inline)) inline uint64_t millis_64() {
// NOLINTNEXTLINE(readability-identifier-naming)
__attribute__((always_inline)) inline void delayMicroseconds(uint32_t us) { delay_microseconds_safe(us); }
__attribute__((always_inline)) inline void arch_feed_wdt() {
#ifdef USE_ESP32_TASK_WDT
esp_task_wdt_reset();
#endif
}
__attribute__((always_inline)) inline void arch_feed_wdt() { esp_task_wdt_reset(); }
__attribute__((always_inline)) inline uint32_t arch_get_cpu_cycle_count() { return esp_cpu_get_cycle_count(); }
void arch_init();
@@ -215,9 +215,8 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
break;
}
// Indexed: a handler (an on_write lambda) can create a service, and push_back may move the vector.
for (size_t i = 0; i < this->services_.size(); i++) { // NOLINT(modernize-loop-convert)
this->services_[i].service->gatts_event_handler(event, gatts_if, param);
for (auto &entry : this->services_) {
entry.service->gatts_event_handler(event, gatts_if, param);
}
}
+5 -3
View File
@@ -22,6 +22,7 @@ from esphome.const import (
CONF_DNS2,
CONF_DOMAIN,
CONF_ENABLE_ON_BOOT,
CONF_ETHERNET,
CONF_GATEWAY,
CONF_ID,
CONF_INTERRUPT_PIN,
@@ -396,9 +397,9 @@ def _validate(config: ConfigType) -> ConfigType:
BASE_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(EthernetComponent),
cv.Optional(CONF_MANUAL_IP, visibility=cv.Visibility.ADVANCED): cv.All(
MANUAL_IP_SCHEMA, require_ipv4(DOMAIN, CONF_MANUAL_IP)
),
cv.Optional(
CONF_MANUAL_IP, visibility=cv.Visibility.ADVANCED
): MANUAL_IP_SCHEMA,
cv.Optional(CONF_DOMAIN, default=".local"): cv.domain_name,
cv.Optional(CONF_USE_ADDRESS): cv.string_strict,
cv.Optional(CONF_MAC_ADDRESS): cv.mac_address,
@@ -555,6 +556,7 @@ CONFIG_SCHEMA = cv.All(
upper=True,
),
_validate,
require_ipv4(CONF_ETHERNET),
)
@@ -14,9 +14,6 @@
#if USE_NETWORK_IPV6
#include <esp_netif_net_stack.h>
#include <lwip/netif.h>
#if !USE_NETWORK_IPV4
#include <lwip/dhcp6.h>
#endif
#endif
#ifdef USE_PSRAM
#include <esp_psram.h>
@@ -733,7 +730,6 @@ network::IPAddresses EthernetComponent::get_ip_addresses() {
network::IPAddresses addresses;
if (!this->ethernet_initialized_)
return addresses; // all-zero IPs
#if USE_NETWORK_IPV4
esp_netif_ip_info_t ip;
esp_err_t err = esp_netif_get_ip_info(this->eth_netif_, &ip);
if (err != ESP_OK) {
@@ -743,7 +739,6 @@ network::IPAddresses EthernetComponent::get_ip_addresses() {
} else {
addresses[0] = network::IPAddress(&ip.ip);
}
#endif
#if USE_NETWORK_IPV6
network::fill_ip6_addresses(this->eth_netif_, addresses);
#endif /* USE_NETWORK_IPV6 */
@@ -782,7 +777,7 @@ void EthernetComponent::eth_event_handler(void *arg, esp_event_base_t event_base
#if USE_NETWORK_IPV6
// Start SLAAC on link-up, not after the DHCPv4 lease. This also restores the
// link-local after a link flap, which clears the IPv6 addresses.
if (esp_err_t ll_err = global_eth_component->ensure_ip6_linklocal_(); ll_err != ESP_OK) {
if (esp_err_t ll_err = esp_netif_create_ip6_linklocal(global_eth_component->eth_netif_); ll_err != ESP_OK) {
ESP_LOGW(TAG, "esp_netif_create_ip6_linklocal failed on link-up: %s", esp_err_to_name(ll_err));
}
#endif /* USE_NETWORK_IPV6 */
@@ -821,9 +816,6 @@ void EthernetComponent::got_ip_event_handler(void *arg, esp_event_base_t event_b
void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id,
void *event_data) {
ip_event_got_ip6_t *event = (ip_event_got_ip6_t *) event_data;
if (event->esp_netif != global_eth_component->eth_netif_) {
return; // another interface's address (wifi alongside ethernet)
}
ESP_LOGV(TAG, "[Ethernet event] ETH Got IPv6: " IPV6STR, IPV62STR(event->ip6_info.ip));
// Count the addresses on the interface, not the events: recreating the link-local
// after a link flap fires another event for the same address.
@@ -833,8 +825,8 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
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_ = (!USE_NETWORK_IPV4 || global_eth_component->got_ipv4_address_) &&
(global_eth_component->ipv6_count_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
global_eth_component->connected_ =
global_eth_component->got_ipv4_address_ && (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
#else
global_eth_component->connected_ = global_eth_component->got_ipv4_address_;
@@ -848,31 +840,21 @@ void EthernetComponent::got_ip6_event_handler(void *arg, esp_event_base_t event_
// duplicate address detection: recreating it would restart DAD. esp_netif_get_ip6_linklocal()
// only reports a preferred address, so ask lwIP for the slot state instead.
esp_err_t EthernetComponent::ensure_ip6_linklocal_() {
auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(this->eth_netif_));
u8_t state = IP6_ADDR_INVALID;
if (netif != nullptr) {
LwIPLock lock;
state = netif_ip6_addr_state(netif, 0);
}
if (!ip6_addr_istentative(state) && !ip6_addr_isvalid(state)) {
if (esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_); err != ESP_OK) {
return err;
if (auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(this->eth_netif_)); netif != nullptr) {
u8_t state;
{
LwIPLock lock;
state = netif_ip6_addr_state(netif, 0);
}
if (ip6_addr_istentative(state) || ip6_addr_isvalid(state)) {
return ESP_OK;
}
}
esp_err_t err = esp_netif_create_ip6_linklocal(this->eth_netif_);
if (err == ESP_OK) {
ESP_LOGD(TAG, "IPv6 link-local address created");
}
#if !USE_NETWORK_IPV4
// Without DHCPv4, DNS servers come from RDNSS or stateless DHCPv6; esp_netif never starts the latter.
// Idempotent in lwIP, so the link-up and connect paths can both call it.
if (netif != nullptr) {
esp_netif_tcpip_exec(
[](void *ctx) -> esp_err_t {
dhcp6_enable_stateless(static_cast<struct netif *>(ctx));
return ESP_OK;
},
netif);
}
#endif
return ESP_OK;
return err;
}
#endif /* USE_NETWORK_IPV6 */
@@ -914,7 +896,6 @@ void EthernetComponent::start_connect_() {
ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
}
#if USE_NETWORK_IPV4
esp_netif_ip_info_t info{};
#ifdef USE_ETHERNET_MANUAL_IP
const ManualIP manual_ip = load_manual_ip();
@@ -965,7 +946,6 @@ void EthernetComponent::start_connect_() {
ESPHL_ERROR_CHECK(err, "DHCPC start error");
}
#endif
#endif // USE_NETWORK_IPV4
#if USE_NETWORK_IPV6
// Attempt to create IPv6 link-local address
// We MUST attempt this here, not just in finish_connect_(), because with
@@ -1000,13 +980,8 @@ void EthernetComponent::dump_connect_params_() {
ESP_LOGCONFIG(TAG, " uninitialized/disabled");
return;
}
#if USE_NETWORK_IPV4
esp_netif_ip_info_t ip;
esp_netif_get_ip_info(this->eth_netif_, &ip);
network::IPAddress ip4(&ip.ip), subnet(&ip.netmask), gateway(&ip.gw);
#else
network::IPAddress ip4, subnet, gateway;
#endif
const ip_addr_t *dns_ip1;
const ip_addr_t *dns_ip2;
{
@@ -1045,7 +1020,8 @@ void EthernetComponent::dump_connect_params_() {
" MAC Address: %s\n"
" Is Full Duplex: %s\n"
" Link Speed: %u",
ip4.str_to(ip_buf), App.get_name().c_str(), subnet.str_to(subnet_buf), gateway.str_to(gateway_buf),
network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
network::IPAddress(&ip.netmask).str_to(subnet_buf), network::IPAddress(&ip.gw).str_to(gateway_buf),
network::IPAddress(dns_ip1).str_to(dns1_buf), network::IPAddress(dns_ip2).str_to(dns2_buf),
this->get_eth_mac_address_pretty_into_buffer(mac_buf),
YESNO(this->get_duplex_mode() == ETH_DUPLEX_FULL), link_speed);
+6 -6
View File
@@ -17,12 +17,14 @@ from esphome.const import (
CONF_TIMEOUT,
CONF_URL,
CONF_WATCHDOG_TIMEOUT,
PLATFORM_ESP32,
PLATFORM_HOST,
PlatformFramework,
__version__,
)
from esphome.core import CORE, ID, Lambda, TimePeriodMilliseconds
from esphome.cpp_generator import MockObj, TemplateArgsType
import esphome.final_validate as fv
from esphome.helpers import IS_MACOS
from esphome.types import ConfigType
@@ -103,18 +105,16 @@ def default_watchdog_timeout(config: ConfigType) -> None:
The default never goes below the platform task watchdog, so a user who
widened `esp32.watchdog_timeout` keeps that window during requests.
When the task watchdog is disabled, the request watchdog cannot be set.
"""
if not CORE.is_esp32:
return
esp32.validate_task_wdt_enabled(config, CONF_WATCHDOG_TIMEOUT)
platform_ms = esp32.task_wdt_timeout_ms()
if platform_ms == 0 or CONF_WATCHDOG_TIMEOUT in config:
if not CORE.is_esp32 or CONF_WATCHDOG_TIMEOUT in config:
return
derived_ms = (
config[CONF_TIMEOUT].total_milliseconds * WATCHDOG_TIMEOUT_MULTIPLIER
+ WATCHDOG_TIMEOUT_MARGIN_MS
)
platform_ms = fv.full_config.get()[PLATFORM_ESP32][
CONF_WATCHDOG_TIMEOUT
].total_milliseconds
config[CONF_WATCHDOG_TIMEOUT] = TimePeriodMilliseconds(
milliseconds=max(derived_ms, platform_ms)
)
@@ -20,6 +20,8 @@
#include "esp_crt_bundle.h"
#endif
#include "esp_task_wdt.h"
namespace esphome::http_request {
ESPHOME_LOG_TAG(TAG, "http_request");
@@ -466,7 +468,12 @@ void HttpContainerIDF::end() {
this->client_ = nullptr;
}
void HttpContainerIDF::feed_wdt() { App.feed_wdt_if_watched(); }
void HttpContainerIDF::feed_wdt() {
// Tests to see if the executing task has a watchdog timer attached
if (esp_task_wdt_status(nullptr) == ESP_OK) {
App.feed_wdt();
}
}
} // namespace esphome::http_request
@@ -151,8 +151,7 @@ Color color_from_light_color_values(LightColorValues val) {
auto r = to_uint8_scale(val.get_color_brightness() * val.get_red());
auto g = to_uint8_scale(val.get_color_brightness() * val.get_green());
auto b = to_uint8_scale(val.get_color_brightness() * val.get_blue());
// White keeps its default of 100% in RGB mode, where it must not count as the strongest channel
uint8_t w = val.get_color_mode() == ColorMode::RGB ? 0 : to_uint8_scale(val.get_white());
auto w = to_uint8_scale(val.get_white());
return Color(r, g, b, w);
}
@@ -12,45 +12,6 @@ uint8_t ESPColorCorrection::gamma_correct_(uint8_t value) const {
return result;
}
uint16_t ESPColorCorrection::gamma_level_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value * 257;
return progmem_read_uint16(&this->gamma_table_[value]);
}
uint8_t ESPColorCorrection::gamma_round_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
return (progmem_read_uint16(&this->gamma_table_[value]) + 128) / 257;
}
// Lighting every non-zero channel instead would turn a dim red with a trace of green into yellow
Color ESPColorCorrection::correct_dark_pixel_(Color color) const {
// Compared without the local brightness, which is the same for every channel: the scaled 8-bit
// values are too coarse to compare at the lowest brightness
uint16_t strengths[4];
uint16_t max_strength = 0;
bool lit = false;
for (uint8_t i = 0; i < 4; i++) {
strengths[i] = color[i] * this->max_brightness_[i];
max_strength = std::max(max_strength, strengths[i]);
lit |= esp_scale8_twice(color[i], this->max_brightness_[i], this->local_brightness_) != 0;
}
Color res;
if (!lit)
return res;
// Stretch the strongest channel to full scale and round the others against it; the table is too
// coarse to compare its lowest levels
for (uint8_t i = 0; i < 4; i++) {
if (strengths[i] == max_strength) {
res[i] = 1;
} else if (strengths[i] != 0) {
res[i] = this->gamma_level_(strengths[i] * 255 / max_strength) >= 0x8000 ? 1 : 0;
}
}
return res;
}
uint8_t ESPColorCorrection::gamma_uncorrect_(uint8_t value) const {
if (this->gamma_table_ == nullptr)
return value;
@@ -40,13 +40,10 @@ class ESPColorCorrection {
#endif
void set_gamma_table(const uint16_t *table) { this->gamma_table_ = table; }
/// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma, keeping a lit pixel lit
inline Color color_correct(Color color) const ESPHOME_ALWAYS_INLINE {
Color res(this->round_channel_(COLOR_CHANNEL_R, color.red), this->round_channel_(COLOR_CHANNEL_G, color.green),
this->round_channel_(COLOR_CHANNEL_B, color.blue), this->round_channel_(COLOR_CHANNEL_W, color.white));
if (res.raw_32 == 0 && color.raw_32 != 0)
res = this->correct_dark_pixel_(color);
return Color(this->limit_(res.red), this->limit_(res.green), this->limit_(res.blue), this->limit_(res.white));
// corrected = (uncorrected * max_brightness * local_brightness) ^ gamma
return Color(this->color_correct_red(color.red), this->color_correct_green(color.green),
this->color_correct_blue(color.blue), this->color_correct_white(color.white));
}
inline uint8_t color_correct_red(uint8_t red) const ESPHOME_ALWAYS_INLINE {
return this->color_correct_channel(COLOR_CHANNEL_R, red);
@@ -93,15 +90,6 @@ class ESPColorCorrection {
#endif
return res;
}
inline uint8_t round_channel_(uint8_t channel, uint8_t value) const ESPHOME_ALWAYS_INLINE {
return this->gamma_round_(esp_scale8_twice(value, this->max_brightness_[channel], this->local_brightness_));
}
/// Forward gamma as the table's 16-bit level
uint16_t gamma_level_(uint8_t value) const;
/// Forward gamma rounded to uint8, where a low level becomes 0
uint8_t gamma_round_(uint8_t value) const;
/// The levels of a pixel whose channels all round to 0: 1 for its strongest channels, unless it is black
Color correct_dark_pixel_(Color color) const;
/// Forward gamma: read uint16 PROGMEM table, convert to uint8
uint8_t gamma_correct_(uint8_t value) const;
/// Reverse gamma and limit for one stored level
+1 -18
View File
@@ -36,10 +36,6 @@ class ESPColorAccessor {
#if defined(USE_LIGHT_PARTITION) && defined(USE_LIGHT_POWER_ESTIMATION)
virtual const ESPColorCorrection *get_color_correction_internal(int32_t index) const { return nullptr; }
#endif
#ifdef USE_LIGHT_PARTITION
// For internal use only: whether the LED at `index` stores a white level.
virtual bool has_white_internal(int32_t index) const { return true; }
#endif
};
/// Color accessor that is completely at peace with the void of nothingness.
@@ -82,10 +78,6 @@ class BufferColorAccessor : public ESPColorAccessor {
}
void set_effect_data(int32_t index, uint8_t value) override { this->effect_data[index] = value; }
#ifdef USE_LIGHT_PARTITION
bool has_white_internal(int32_t index) const override { return this->channel_colors.has_white(); }
#endif
/// Allocate a zeroed block of buffer_bytes() plus `extra_bytes` for the caller, which start at
/// `effect_data + num_leds`, and pass it to set_buffer(). Returns false if it failed.
bool allocate(RAMAllocator<uint8_t> &allocator, size_t num_leds, size_t extra_bytes = 0) {
@@ -159,12 +151,7 @@ class CorrectedBufferColorAccessor final : public BufferColorAccessor {
return this->color_correction->color_uncorrect_channel(channel, this->get_channel_raw(index, channel));
}
void set(int32_t index, Color color) override {
// A white level the strip cannot show must not count as the pixel's strongest channel
if (!this->channel_colors.has_white())
color.white = 0;
this->set_raw(index, this->color_correction->color_correct(color));
}
void set(int32_t index, Color color) override { this->set_raw(index, this->color_correction->color_correct(color)); }
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
this->set_channel_raw(index, channel, this->color_correction->color_correct_channel(channel, value));
}
@@ -286,10 +273,6 @@ class ESPColorView final : public ESPColorSettable {
return this->accessor_->get_color_correction_internal(this->index_);
}
#endif
#ifdef USE_LIGHT_PARTITION
// This method is for internal use only.
bool has_white_internal() const { return this->accessor_->has_white_internal(this->index_); }
#endif
protected:
ESPColorAccessor *const accessor_;
+7 -19
View File
@@ -293,9 +293,9 @@ def _ip_request(
return validator
def require_ipv4(*path: str) -> Callable[[ConfigType], ConfigType]:
"""Return a validator declaring that the component or option at `path` needs IPv4."""
return _ip_request(lambda data: data.require_ipv4.add(": ".join(path)))
def require_ipv4(name: str) -> Callable[[ConfigType], ConfigType]:
"""Return a validator declaring that component `name` needs IPv4."""
return _ip_request(lambda data: data.require_ipv4.add(name))
def require_ipv6(name: str) -> Callable[[ConfigType], ConfigType]:
@@ -456,10 +456,7 @@ def _final_validate(config: ConfigType) -> None:
CONF_ENABLE_IPV4,
"IPv4",
data.require_ipv4,
# Wi-Fi and Ethernet keep IPv4 unless the config turns it off explicitly
default=not data.request_ipv4_off
or CONF_WIFI in full_config
or CONF_ETHERNET in full_config,
default=not data.request_ipv4_off,
)
if not config[CONF_ENABLE_IPV4] and not config[CONF_ENABLE_IPV6]:
@@ -665,11 +662,9 @@ async def to_code(config: ConfigType) -> None:
cg.add_define("USE_NETWORK_IPV6", enable_ipv6)
if enable_ipv6:
# Without IPv4 an IPv6 address is the connection, so wait for at least one
min_count = config[CONF_MIN_IPV6_ADDR_COUNT]
if not enable_ipv4:
min_count = max(min_count, 1)
cg.add_define("USE_NETWORK_MIN_IPV6_ADDR_COUNT", min_count)
cg.add_define(
"USE_NETWORK_MIN_IPV6_ADDR_COUNT", config[CONF_MIN_IPV6_ADDR_COUNT]
)
if CORE.is_esp32:
add_idf_sdkconfig_option("CONFIG_LWIP_IPV6", enable_ipv6)
add_idf_sdkconfig_option("CONFIG_LWIP_IPV6_AUTOCONFIG", enable_ipv6)
@@ -686,13 +681,6 @@ async def to_code(config: ConfigType) -> None:
cg.add_define("USE_NETWORK_IPV4", enable_ipv4)
if CORE.is_esp32:
add_idf_sdkconfig_option("CONFIG_LWIP_IPV4", enable_ipv4)
# DNS over RDNSS or stateless DHCPv6 is for IPv6-only Wi-Fi and Ethernet; leave
# other IPv4-less builds (OpenThread) on the sdkconfig they already build with.
if not enable_ipv4 and CORE.has_at_least_one_component(
CONF_WIFI, CONF_ETHERNET
):
add_idf_sdkconfig_option("CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS", 2)
add_idf_sdkconfig_option("CONFIG_LWIP_IPV6_DHCP6", True)
# Pvariable creation lives in a separate coroutine at NETWORK_SERVICES so it
# emits after wifi/ethernet at COMMUNICATION. This keeps compile-time config
+5 -16
View File
@@ -3,8 +3,6 @@
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include <utility>
#ifdef USE_NETWORK
namespace esphome::network {
@@ -15,17 +13,8 @@ ESPHOME_LOG_TAG(TAG, "network");
void fill_ip6_addresses(esp_netif_t *netif, IPAddresses &addresses) {
esp_ip6_addr_t ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
size_t count = esp_netif_get_all_ip6(netif, ip6s);
// Slot 0 holds the IPv4 address; without IPv4 the first IPv6 address takes it, so it reads as the primary one
constexpr size_t first = USE_NETWORK_IPV4 ? 1 : 0;
if constexpr (first == 0) {
// Lead with a routable address; the link-local one comes first from esp-netif and is useless off-link
for (size_t i = 1; i < count; i++) {
if (esp_netif_ip6_get_addr_type(&ip6s[0]) != ESP_IP6_ADDR_IS_LINK_LOCAL)
break;
std::swap(ip6s[0], ip6s[i]);
}
}
if (count > addresses.size() - first) {
// Slot 0 holds the IPv4 address
if (count > addresses.size() - 1) {
// Warn once per interface
static esp_netif_t *warned[3]{};
for (auto &slot : warned) {
@@ -35,14 +24,14 @@ void fill_ip6_addresses(esp_netif_t *netif, IPAddresses &addresses) {
if (slot == nullptr) {
slot = netif;
ESP_LOGW(TAG, "%s has %zu IPv6 addresses, only %zu are reported", esp_netif_get_desc(netif), count,
addresses.size() - first);
addresses.size() - 1);
break;
}
}
count = addresses.size() - first;
count = addresses.size() - 1;
}
for (size_t i = 0; i < count; i++) {
addresses[i + first] = IPAddress(&ip6s[i]);
addresses[i + 1] = IPAddress(&ip6s[i]);
}
}
#endif
-9
View File
@@ -10,7 +10,6 @@ from esphome.const import (
PLATFORM_ESP8266,
)
from esphome.core import CORE, TimePeriod
from esphome.types import ConfigType
from . import Nextion, nextion_ref
from .base_component import (
@@ -148,14 +147,6 @@ CONFIG_SCHEMA = cv.All(
)
def _final_validate(config: ConfigType) -> None:
if CORE.is_esp32:
esp32.validate_task_wdt_enabled(config, CONF_TFT_UPLOAD_WATCHDOG_TIMEOUT)
FINAL_VALIDATE_SCHEMA = _final_validate
automation.register_apply_action(
"display.nextion.set_brightness",
cv.maybe_simple_value(
+3 -3
View File
@@ -98,8 +98,8 @@ def encryption_schema(config: ConfigType | None) -> ConfigType:
return ENCRYPTION_SCHEMA(config)
def use_registry_libsodium() -> bool:
"""Whether libsodium, and noise-c with it, come from the ESP-IDF component registry.
def _use_managed_components() -> bool:
"""Whether noise-c and libsodium come from the ESP-IDF component registry.
Both build as ESP-IDF components, so on ESP32 they skip the PlatformIO library
converter unless arduino-esp32's own libsodium cannot be replaced. Every
@@ -122,7 +122,7 @@ async def to_code(config: ConfigType) -> None:
cg.add_define("USE_NOISE")
# libsodium is declared next to noise-c so the library manager sees both up front
# and nothing else pulls a second copy; the version must match noise-c's own pin
if use_registry_libsodium():
if _use_managed_components():
from esphome.components.esp32 import add_idf_component
add_idf_component(name="esphome/noise-c", ref=NOISE_C_VERSION)
+2 -10
View File
@@ -31,12 +31,7 @@ from esphome.components.esp32 import (
require_vfs_select,
)
from esphome.components.mdns import MDNSComponent, enable_mdns_storage
from esphome.components.network import (
add_use_address,
request_ipv4_off,
require_ipv4,
require_ipv6,
)
from esphome.components.network import add_use_address, request_ipv4_off, require_ipv6
from esphome.components.nrf52.framework import include_west_project
from esphome.components.zephyr import zephyr_add_prj_conf, zephyr_add_prj_conf_min
from esphome.config_helpers import filter_source_files_from_platform
@@ -302,10 +297,7 @@ _BORDER_ROUTER_SCHEMA = cv.Schema({cv.Optional(CONF_RCP): _RCP_SCHEMA})
def _validate_border_router(value: object) -> ConfigType:
# ESP-IDF's border router library resolves DNS and runs DHCP over IPv4
return require_ipv4(CONF_OPENTHREAD, CONF_BORDER_ROUTER)(
_BORDER_ROUTER_SCHEMA({} if value is None else value)
)
return _BORDER_ROUTER_SCHEMA({} if value is None else value)
_CONNECTION_SCHEMA = cv.Schema(
@@ -22,6 +22,7 @@
#include "esp_openthread.h"
#include "esp_openthread_lock.h"
#include "esp_openthread_types.h"
#include "esp_task_wdt.h"
#include "esphome/components/network/util.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
@@ -469,11 +470,11 @@ InstanceLock InstanceLock::acquire() {
abort();
}
delay(10);
arch_feed_wdt();
esp_task_wdt_reset();
}
while (!esp_openthread_lock_acquire(100)) {
abort_if_task_exited();
arch_feed_wdt();
esp_task_wdt_reset();
}
// The clean-up may have released the lock to this waiter just before deinit destroys it
if (global_openthread_component->is_task_exited()) {
@@ -83,9 +83,6 @@ class PartitionLightOutput final : public light::AddressableLight {
void set(int32_t index, Color color) override {
light::ESPColorView color_view = this->parent_->get_color_view_(index);
// A white level the LED cannot show must not count as the pixel's strongest channel
if (!color_view.has_white_internal()) // NOLINT
color.white = 0;
color_view.set_raw(this->parent_->get_color_correction_(color_view)->color_correct(color));
}
void set_channel(int32_t index, uint8_t channel, uint8_t value) override {
@@ -101,10 +98,6 @@ class PartitionLightOutput final : public light::AddressableLight {
this->parent_->get_color_view_(index).set_effect_data(value);
}
bool has_white_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_view_(index).has_white_internal();
}
#ifdef USE_LIGHT_POWER_ESTIMATION
const light::ESPColorCorrection *get_color_correction_internal(int32_t index) const override { // NOLINT
return this->parent_->get_color_correction_(this->parent_->get_color_view_(index));
+15 -25
View File
@@ -1,5 +1,5 @@
import esphome.codegen as cg
from esphome.components import web_server_base, web_server_idf
from esphome.components import web_server_base
from esphome.components.web_server_base import CONF_WEB_SERVER_BASE_ID
import esphome.config_validation as cv
from esphome.const import CONF_ID, CONF_INCLUDE_INTERNAL, CONF_NAME, CONF_RELABEL
@@ -22,30 +22,20 @@ CUSTOMIZED_ENTITY = cv.All(
cv.has_at_least_one_key(CONF_ID, CONF_NAME),
)
def _require_plain_http(config: ConfigType) -> ConfigType:
# Prometheus is advertised over mDNS as a plain HTTP service.
web_server_idf.require_plain_http(DOMAIN)
return config
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(PrometheusHandler),
cv.GenerateID(CONF_WEB_SERVER_BASE_ID): cv.use_id(
web_server_base.WebServerBase
),
cv.Optional(CONF_INCLUDE_INTERNAL, default=False): cv.boolean,
cv.Optional(CONF_RELABEL, default={}): cv.Schema(
{
cv.use_id(EntityBase): CUSTOMIZED_ENTITY,
}
),
},
).extend(cv.COMPONENT_SCHEMA),
_require_plain_http,
)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(PrometheusHandler),
cv.GenerateID(CONF_WEB_SERVER_BASE_ID): cv.use_id(
web_server_base.WebServerBase
),
cv.Optional(CONF_INCLUDE_INTERNAL, default=False): cv.boolean,
cv.Optional(CONF_RELABEL, default={}): cv.Schema(
{
cv.use_id(EntityBase): CUSTOMIZED_ENTITY,
}
),
},
).extend(cv.COMPONENT_SCHEMA)
async def to_code(config: ConfigType) -> None:
@@ -8,6 +8,10 @@
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#ifdef USE_ESP_IDF
#include "esp_task_wdt.h"
#endif
ESPHOME_LOG_TAG(TAG, "image_decoder.jpeg");
namespace esphome::runtime_image {
@@ -47,6 +51,18 @@ void JpegDecoder::draw_rgb565(int x, int y, int w, int h, const uint8_t *pixels)
}
}
// Some very big images take too long to decode, so feed the watchdog as the decode goes
// to avoid crashing if the executing task has a watchdog enabled.
static void feed_watchdog() {
#ifdef USE_ESP_IDF
if (esp_task_wdt_status(nullptr) == ESP_OK) {
#endif
App.feed_wdt();
#ifdef USE_ESP_IDF
}
#endif
}
/**
* @brief Callback method that will be called by the JPEGDEC engine when a chunk
* of the image is decoded.
@@ -61,8 +77,7 @@ static int draw_callback(JPEGDRAW *jpeg) {
return 0;
}
// Very big images take long to decode, so feed the watchdog as the decode goes
App.feed_wdt_if_watched();
feed_watchdog();
if (decoder->uses_direct_rgb565()) {
decoder->draw_rgb565(jpeg->x, jpeg->y, jpeg->iWidth, jpeg->iHeight,
reinterpret_cast<const uint8_t *>(jpeg->pPixels));
@@ -126,7 +141,7 @@ int HOT JpegDecoder::decode(uint8_t *buffer, size_t size) {
return this->fail_();
int result;
while ((result = this->jpeg_->decodeRows(1)) == JPEG_DECODE_MORE)
App.feed_wdt_if_watched();
feed_watchdog();
if (result != 1)
return this->fail_();
this->decoded_bytes_ = size;
+2 -2
View File
@@ -41,8 +41,8 @@ from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
# mdns for autodiscovery; noise declares the noise-c and libsodium that sendspin-cpp uses
AUTO_LOAD = ["mdns", "noise"]
# mdns for autodiscovery
AUTO_LOAD = ["mdns"]
CODEOWNERS = ["@kahrendt"]
DEPENDENCIES = ["network"]
DOMAIN = "sendspin"
@@ -98,7 +98,7 @@ CONFIG_SCHEMA = cv.All(
cv.positive_time_period_milliseconds,
cv.Range(max=cv.TimePeriod(milliseconds=5000)),
),
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=True): cv.boolean,
cv.Optional(CONF_STATIC_DELAY_ADJUSTABLE, default=False): cv.boolean,
cv.Optional(CONF_FIXED_DELAY, default="0us"): cv.All(
cv.positive_time_period_microseconds,
cv.Range(max=cv.TimePeriod(microseconds=10000)),
@@ -61,7 +61,7 @@ class SendspinMediaSource final : public SendspinChild,
bool cached_muted_{false};
bool pending_start_{false};
bool static_delay_adjustable_{true};
bool static_delay_adjustable_{false};
};
} // namespace esphome::sendspin_
+30 -68
View File
@@ -4,22 +4,13 @@ import esphome.codegen as cg
from esphome.components import time, uart
import esphome.config_validation as cv
from esphome.const import CONF_SENSOR_DATAPOINT, CONF_TIME_ID
from esphome.core import CORE, AutoLoad, CoroPriority, coroutine_with_priority
from esphome.core import CORE, CoroPriority, coroutine_with_priority
from esphome.cpp_generator import MockObj
from esphome.schema_extractors import SCHEMA_EXTRACT, schema_extractor
from esphome.types import ConfigType
CODEOWNERS = ["@dwmw2", "@ssieb"]
DEPENDENCIES = ["uart"]
DOMAIN = "tuya"
# AutoLoad: another transport pulled in only the base class. None: CI dependency probe.
def AUTO_LOAD(config: ConfigType | AutoLoad | None) -> list[str]:
if isinstance(config, AutoLoad):
return []
return ["uart"]
CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS = "ignore_mcu_update_on_datapoints"
CONF_ON_DATAPOINT_UPDATE = "on_datapoint_update"
@@ -29,8 +20,7 @@ CONF_FORCE_TIME_SYNC = "force_time_sync"
tuya_ns = cg.esphome_ns.namespace("tuya")
TuyaDatapointType = tuya_ns.enum("TuyaDatapointType", is_class=True)
Tuya = tuya_ns.class_("Tuya", cg.Component)
TuyaUART = tuya_ns.class_("TuyaUART", Tuya, uart.UARTDevice)
Tuya = tuya_ns.class_("Tuya", cg.Component, uart.UARTDevice)
TuyaDatapoint = tuya_ns.struct("TuyaDatapoint")
@@ -82,50 +72,42 @@ def _validate_time_options(config: ConfigType) -> ConfigType:
return config
TUYA_SCHEMA = cv.Schema(
{
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(cv.uint8_t),
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
).extend(cv.COMPONENT_SCHEMA)
UART_SCHEMA = cv.All(
TUYA_SCHEMA.extend(
CONFIG_SCHEMA = cv.All(
cv.Schema(
{
cv.GenerateID(): cv.declare_id(TuyaUART),
cv.GenerateID(): cv.declare_id(Tuya),
cv.Optional(CONF_TIME_ID): cv.use_id(time.RealTimeClock),
cv.Optional(CONF_FORCE_TIME_SYNC, default=False): cv.boolean,
cv.Optional(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS): cv.ensure_list(
cv.uint8_t
),
cv.Optional(CONF_STATUS_PIN): pins.gpio_output_pin_schema,
cv.Optional(CONF_ON_DATAPOINT_UPDATE): automation.validate_automation(
{
cv.Required(CONF_SENSOR_DATAPOINT): cv.uint8_t,
cv.Optional(CONF_DATAPOINT_TYPE, default=DPTYPE_ANY): cv.one_of(
*DATAPOINT_TYPES, lower=True
),
}
),
}
).extend(uart.UART_DEVICE_SCHEMA),
)
.extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA),
_validate_time_options,
)
@schema_extractor("schema")
def _validate_config(value: ConfigType | AutoLoad) -> ConfigType | AutoLoad | cv.Schema:
if value is SCHEMA_EXTRACT:
# Expose the UART schema to the language-schema dumper
return UART_SCHEMA
if isinstance(value, AutoLoad):
return value
return UART_SCHEMA(value)
CONFIG_SCHEMA = _validate_config
async def setup_tuya(var: MockObj, config: ConfigType) -> None:
"""Apply the base-class options; called from a transport's to_code()."""
for dp in config.get(CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS, []):
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
async def to_code(config):
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
if CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS in config:
for dp in config[CONF_IGNORE_MCU_UPDATE_ON_DATAPOINTS]:
cg.add(var.add_ignore_mcu_update_on_datapoints(dp))
for conf in config.get(CONF_ON_DATAPOINT_UPDATE, []):
type_, expected, field = DATAPOINT_TYPES[conf[CONF_DATAPOINT_TYPE]]
forward = None
@@ -135,23 +117,3 @@ async def setup_tuya(var: MockObj, config: ConfigType) -> None:
[(type_, "x")], conf, params=[(TuyaDatapoint, "x")], forward=forward
)
cg.add(var.register_listener(conf[CONF_SENSOR_DATAPOINT], callback))
async def to_code(config: ConfigType | AutoLoad) -> None:
if isinstance(config, AutoLoad):
return
var = await uart.new_uart_component(config)
if (time_id := config.get(CONF_TIME_ID)) is not None:
await cg.add_variable(var.set_time_id, time_id)
if config[CONF_FORCE_TIME_SYNC]:
cg.add(var.set_force_time_sync(True))
await cg.add_pin(var.set_status_pin, config.get(CONF_STATUS_PIN))
await setup_tuya(var, config)
def FILTER_SOURCE_FILES() -> list[str]:
# When only auto-loaded as a base class, the UART implementation is unused
if isinstance(CORE.config.get(DOMAIN), AutoLoad):
return ["tuya_uart.cpp", "tuya_uart.h"]
return []
+684 -38
View File
@@ -1,13 +1,85 @@
#include "tuya.h"
#include <cstring>
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
void Tuya::dump_datapoints_() {
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static const int RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void Tuya::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void Tuya::loop() {
this->read_available([this](uint8_t b) { this->handle_char_(b); });
process_command_queue_();
}
void Tuya::dump_config() {
this->dump_mcu_config_();
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
// Also logged again once the MCU reports its datapoints
void Tuya::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
for (auto &info : this->datapoints_) {
if (info.type == TuyaDatapointType::RAW) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
@@ -27,36 +99,595 @@ void Tuya::dump_datapoints_() {
ESP_LOGCONFIG(TAG, " Datapoint %u: unknown", info.id);
}
}
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
void Tuya::handle_datapoint_(const TuyaDatapoint &datapoint) {
// drop update if datapoint is in ignore_mcu_datapoint_update list
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
bool Tuya::validate_message_() {
uint32_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// Byte 0: HEADER1 (always 0x55)
if (at == 0)
return new_byte == 0x55;
// Byte 1: HEADER2 (always 0xAA)
if (at == 1)
return new_byte == 0xAA;
// Byte 2: VERSION
// no validation for the following fields:
uint8_t version = data[2];
if (at == 2)
return true;
// Byte 3: COMMAND
uint8_t command = data[3];
if (at == 3)
return true;
// Byte 4: LENGTH1
// Byte 5: LENGTH2
if (at <= 5) {
// no validation for these fields
return true;
}
uint16_t length = encode_uint16(data[4], data[5]);
// wait until all data is read
if (at - 6 < length)
return true;
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
uint8_t rx_checksum = new_byte;
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
// valid message
const uint8_t *message_data = data + 6;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
// return false to reset rx buffer
return false;
}
void Tuya::handle_char_(uint8_t c) {
this->rx_message_.push_back(c);
if (!this->validate_message_()) {
this->rx_message_.clear();
} else {
this->last_rx_char_timestamp_ = millis();
}
}
void Tuya::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->initialized_callback_.call();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void Tuya::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
return;
}
}
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
// drop update if datapoint is in ignore_mcu_datapoint_update list
bool skip = false;
for (auto i : this->ignore_mcu_update_on_datapoints_) {
if (datapoint.id == i) {
ESP_LOGV(TAG, "Datapoint %u found in ignore_mcu_update_on_datapoints list, dropping MCU update", datapoint.id);
skip = true;
break;
}
}
if (skip)
continue;
// Update internal datapoints
bool found = false;
for (auto &other : this->datapoints_) {
if (other.id == datapoint.id) {
other = datapoint;
found = true;
}
}
if (!found) {
this->datapoints_.push_back(datapoint);
}
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
}
}
if (!found) {
this->datapoints_.push_back(datapoint);
}
void Tuya::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
// Run through listeners
for (auto &listener : this->listeners_) {
if (listener.datapoint_id == datapoint.id)
listener.on_datapoint.call(datapoint);
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void Tuya::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->rx_message_.clear();
}
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void Tuya::send_command_(const TuyaCommand &command) {
command_queue_.push_back(command);
process_command_queue_();
}
void Tuya::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void Tuya::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t Tuya::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t Tuya::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void Tuya::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void Tuya::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void Tuya::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void Tuya::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void Tuya::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
void Tuya::set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value) {
this->set_raw_datapoint_value_(datapoint_id, value, false);
}
@@ -113,19 +744,19 @@ void Tuya::force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t valu
this->set_numeric_datapoint_value_(datapoint_id, TuyaDatapointType::BITMASK, value, length, true);
}
const TuyaDatapoint *Tuya::get_datapoint_(uint8_t datapoint_id) const {
for (const auto &datapoint : this->datapoints_) {
optional<TuyaDatapoint> Tuya::get_datapoint_(uint8_t datapoint_id) {
for (auto &datapoint : this->datapoints_) {
if (datapoint.id == datapoint_id)
return &datapoint;
return datapoint;
}
return nullptr;
return {};
}
void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint32_t value,
uint8_t length, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %" PRIu32, datapoint_id, value);
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != datapoint_type) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -135,29 +766,30 @@ void Tuya::set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType
return;
}
uint8_t data[4];
std::vector<uint8_t> data;
switch (length) {
case 4:
put_be32(data, value);
break;
data.push_back(value >> 24);
data.push_back(value >> 16);
[[fallthrough]];
case 2:
put_be16(data, value);
break;
data.push_back(value >> 8);
[[fallthrough]];
case 1:
data[0] = value;
data.push_back(value >> 0);
break;
default:
ESP_LOGE(TAG, "Unexpected datapoint length %u", length);
return;
}
this->send_datapoint_command(datapoint_id, datapoint_type, data, length);
this->send_datapoint_command_(datapoint_id, datapoint_type, data);
}
void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced) {
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, format_hex_pretty_to(hex_buf, value.data(), value.size()));
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::RAW) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -166,13 +798,13 @@ void Tuya::set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
this->send_datapoint_command(datapoint_id, TuyaDatapointType::RAW, value.data(), value.size());
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::RAW, value);
}
void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced) {
ESP_LOGD(TAG, "Setting datapoint %u to %s", datapoint_id, value);
const TuyaDatapoint *datapoint = this->get_datapoint_(datapoint_id);
if (datapoint == nullptr) {
optional<TuyaDatapoint> datapoint = this->get_datapoint_(datapoint_id);
if (!datapoint.has_value()) {
ESP_LOGW(TAG, "Setting unknown datapoint %u", datapoint_id);
} else if (datapoint->type != TuyaDatapointType::STRING) {
ESP_LOGE(TAG, "Attempt to set datapoint %u with incorrect type", datapoint_id);
@@ -182,7 +814,19 @@ void Tuya::set_string_datapoint_value_(uint8_t datapoint_id, const char *value,
ESP_LOGV(TAG, "Not sending unchanged value");
return;
}
this->send_datapoint_command(datapoint_id, TuyaDatapointType::STRING, reinterpret_cast<const uint8_t *>(value), len);
std::vector<uint8_t> data(value, value + len);
this->send_datapoint_command_(datapoint_id, TuyaDatapointType::STRING, data);
}
void Tuya::send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data) {
std::vector<uint8_t> buffer;
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(data.size() >> 8);
buffer.push_back(data.size() >> 0);
buffer.insert(buffer.end(), data.begin(), data.end());
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = buffer});
}
void Tuya::register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func) {
@@ -206,4 +850,6 @@ const TuyaDatapoint &TuyaDatapoint::expect_type(TuyaDatapointType expected) cons
return *this;
}
TuyaInitState Tuya::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
+100 -24
View File
@@ -1,17 +1,21 @@
#pragma once
#include <cinttypes>
#include <memory>
#include <vector>
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/helpers.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
#endif
namespace esphome::tuya {
// Max bytes to log for datapoint values (larger values are truncated)
static constexpr size_t MAX_DATAPOINT_LOG_BYTES = 16;
enum class TuyaDatapointType : uint8_t {
RAW = 0x00, // variable length
BOOLEAN = 0x01, // 1 byte (0/1)
@@ -44,18 +48,53 @@ struct TuyaDatapointListener {
Callback<void(const TuyaDatapoint &)> on_datapoint;
};
/// Transport-agnostic Tuya controller. Subclasses implement send_datapoint_command(), feed received datapoints
/// to handle_datapoint_(), and call mark_initialized_() once the MCU has reported.
class Tuya : public Component {
enum class TuyaCommandType : uint8_t {
HEARTBEAT = 0x00,
PRODUCT_QUERY = 0x01,
CONF_QUERY = 0x02,
WIFI_STATE = 0x03,
WIFI_RESET = 0x04,
WIFI_SELECT = 0x05,
DATAPOINT_DELIVER = 0x06,
DATAPOINT_REPORT_ASYNC = 0x07,
DATAPOINT_QUERY = 0x08,
GMT_TIME_QUERY = 0x0C,
WIFI_TEST = 0x0E,
LOCAL_TIME_QUERY = 0x1C,
DATAPOINT_REPORT_SYNC = 0x22,
DATAPOINT_REPORT_ACK = 0x23,
WIFI_RSSI = 0x24,
VACUUM_MAP_UPLOAD = 0x28,
GET_NETWORK_STATUS = 0x2B,
EXTENDED_SERVICES = 0x34,
};
enum class TuyaExtendedServicesCommandType : uint8_t {
RESET_NOTIFICATION = 0x04,
MODULE_RESET = 0x05,
UPDATE_IN_PROGRESS = 0x0A,
};
enum class TuyaInitState : uint8_t {
INIT_HEARTBEAT = 0x00,
INIT_PRODUCT,
INIT_CONF,
INIT_WIFI,
INIT_DATAPOINT,
INIT_DONE,
};
struct TuyaCommand {
TuyaCommandType cmd;
std::vector<uint8_t> payload;
};
class Tuya final : public Component, public uart::UARTDevice {
public:
float get_setup_priority() const override { return setup_priority::LATE; }
/// Prints each child entity's dump; a transport that overrides it prints its own block first, then calls this
void dump_config() override {
#ifdef USE_TUYA_DUMP_PUBLISHER
if (this->dump_publisher_ != nullptr)
this->dump_publisher_();
#endif
}
void setup() override;
void loop() override;
void dump_config() override;
#ifdef USE_TUYA_DUMP_PUBLISHER
HUB_PUBLISHER(dump)
#endif
@@ -65,6 +104,7 @@ class Tuya : public Component {
void set_raw_datapoint_value(uint8_t datapoint_id, const std::vector<uint8_t> &value);
void set_boolean_datapoint_value(uint8_t datapoint_id, bool value);
void set_integer_datapoint_value(uint8_t datapoint_id, uint32_t value);
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
void set_string_datapoint_value(uint8_t datapoint_id, const std::string &value);
void set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
@@ -76,6 +116,11 @@ class Tuya : public Component {
void force_set_string_datapoint_value(uint8_t datapoint_id, const char *value);
void force_set_enum_datapoint_value(uint8_t datapoint_id, uint8_t value);
void force_set_bitmask_datapoint_value(uint8_t datapoint_id, uint32_t value, uint8_t length);
TuyaInitState get_init_state();
#ifdef USE_TIME
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
#endif
void add_ignore_mcu_update_on_datapoints(uint8_t ignore_mcu_update_on_datapoints) {
this->ignore_mcu_update_on_datapoints_.push_back(ignore_mcu_update_on_datapoints);
}
@@ -85,25 +130,56 @@ class Tuya : public Component {
protected:
void register_listener_(uint8_t datapoint_id, Callback<void(const TuyaDatapoint &)> func);
/// Store a datapoint received from the MCU and notify listeners.
void handle_datapoint_(const TuyaDatapoint &datapoint);
void mark_initialized_() { this->initialized_callback_.call(); }
const TuyaDatapoint *get_datapoint_(uint8_t datapoint_id) const;
void dump_datapoints_();
void dump_mcu_config_();
void handle_char_(uint8_t c);
void handle_datapoints_(const uint8_t *buffer, size_t len);
optional<TuyaDatapoint> get_datapoint_(uint8_t datapoint_id);
bool validate_message_();
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
void process_command_queue_();
void send_command_(const TuyaCommand &command);
void send_empty_command_(TuyaCommandType command);
void set_numeric_datapoint_value_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, uint32_t value,
uint8_t length, bool forced);
void set_string_datapoint_value_(uint8_t datapoint_id, const char *value, size_t len, bool forced);
void set_raw_datapoint_value_(uint8_t datapoint_id, const std::vector<uint8_t> &value, bool forced);
/// Deliver a datapoint value to the MCU over the subclass's transport.
/// The payload is borrowed for the duration of the call only.
virtual void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) = 0;
void send_datapoint_command_(uint8_t datapoint_id, TuyaDatapointType datapoint_type, std::vector<uint8_t> data);
void set_status_pin_();
void send_wifi_status_();
uint8_t get_wifi_status_code_();
uint8_t get_wifi_rssi_();
#ifdef USE_TIME
void register_local_time_sync_callback_();
void check_force_time_sync_();
void send_local_time_(bool periodic = false);
void send_gmt_time_();
time::RealTimeClock *time_id_{nullptr};
bool force_time_sync_{false};
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
bool time_sync_callback_registered_{false};
bool gmt_time_sync_callback_registered_{false};
#endif
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
bool init_failed_{false};
int init_retries_{0};
uint8_t protocol_version_ = -1;
InternalGPIOPin *status_pin_{nullptr};
int status_pin_reported_ = -1;
int reset_pin_reported_ = -1;
uint32_t last_command_timestamp_ = 0;
uint32_t last_rx_char_timestamp_ = 0;
std::unique_ptr<char[]> product_;
std::vector<TuyaDatapointListener> listeners_;
std::vector<TuyaDatapoint> datapoints_;
std::vector<uint8_t> rx_message_;
std::vector<uint8_t> ignore_mcu_update_on_datapoints_{};
private:
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
CallbackManager<void()> initialized_callback_{};
};
-656
View File
@@ -1,656 +0,0 @@
#include "tuya_uart.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/util.h"
#include <cctype>
#include <cstring>
#ifdef USE_NETWORK
#include "esphome/components/network/util.h"
#endif
#ifdef USE_WIFI
#include "esphome/components/wifi/wifi_component.h"
#endif
#ifdef USE_CAPTIVE_PORTAL
#include "esphome/components/captive_portal/captive_portal.h"
#endif
namespace esphome::tuya {
ESPHOME_LOG_TAG(TAG, "tuya");
static constexpr uint32_t HEARTBEAT_INTERVAL_ID = 0;
static constexpr uint32_t WIFI_STATUS_INTERVAL_ID = 1;
static constexpr uint32_t DATAPOINT_DUMP_TIMEOUT_ID = 2;
static constexpr uint32_t FORCE_TIME_SYNC_INTERVAL_ID = 3;
static const int COMMAND_DELAY = 10;
static const int RECEIVE_TIMEOUT = 300;
static const int MAX_RETRIES = 5;
static constexpr uint32_t FORCE_TIME_SYNC_CHECK_INTERVAL = 1000;
static bool network_is_connected() {
#ifdef USE_NETWORK
return network::is_connected();
#else
return false;
#endif
}
void TuyaUART::setup() {
this->set_interval(HEARTBEAT_INTERVAL_ID, 15000, [this] { this->send_empty_command_(TuyaCommandType::HEARTBEAT); });
#ifdef USE_TIME
if (this->force_time_sync_) {
this->register_local_time_sync_callback_();
this->set_interval(FORCE_TIME_SYNC_INTERVAL_ID, FORCE_TIME_SYNC_CHECK_INTERVAL,
[this] { this->check_force_time_sync_(); });
}
#endif
if (this->status_pin_ != nullptr) {
this->status_pin_->digital_write(false);
}
}
void TuyaUART::loop() {
this->read_available([this](uint8_t b) { this->handle_char_(b); });
process_command_queue_();
}
void TuyaUART::dump_config() {
this->dump_mcu_config_();
Tuya::dump_config();
}
// Also logged again once the MCU reports its datapoints
void TuyaUART::dump_mcu_config_() {
ESP_LOGCONFIG(TAG, "Tuya:");
if (this->init_state_ != TuyaInitState::INIT_DONE) {
if (this->init_failed_) {
ESP_LOGCONFIG(TAG, " Initialization failed. Current init_state: %u", static_cast<uint8_t>(this->init_state_));
} else {
ESP_LOGCONFIG(TAG, " Configuration will be reported when setup is complete. Current init_state: %u",
static_cast<uint8_t>(this->init_state_));
}
ESP_LOGCONFIG(TAG, " If no further output is received, confirm that this is a supported Tuya device.");
return;
}
this->dump_datapoints_();
if ((this->status_pin_reported_ != -1) || (this->reset_pin_reported_ != -1)) {
ESP_LOGCONFIG(TAG, " GPIO Configuration: status: pin %d, reset: pin %d", this->status_pin_reported_,
this->reset_pin_reported_);
}
LOG_PIN(" Status Pin: ", this->status_pin_);
ESP_LOGCONFIG(TAG, " Product: '%s'",
this->product_invalid_ ? LOG_STR_LITERAL(R"({"p":"INVALID"})")
: (this->product_ ? this->product_.get() : LOG_STR_LITERAL("")));
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
ESP_LOGCONFIG(TAG, " Force time sync: %s", YESNO(this->force_time_sync_));
}
#endif
}
bool TuyaUART::validate_message_() {
uint32_t at = this->rx_message_.size() - 1;
auto *data = &this->rx_message_[0];
uint8_t new_byte = data[at];
// Byte 0: HEADER1 (always 0x55)
if (at == 0)
return new_byte == 0x55;
// Byte 1: HEADER2 (always 0xAA)
if (at == 1)
return new_byte == 0xAA;
// Byte 2: VERSION
// no validation for the following fields:
uint8_t version = data[2];
if (at == 2)
return true;
// Byte 3: COMMAND
uint8_t command = data[3];
if (at == 3)
return true;
// Byte 4: LENGTH1
// Byte 5: LENGTH2
if (at <= 5) {
// no validation for these fields
return true;
}
uint16_t length = encode_uint16(data[4], data[5]);
// wait until all data is read
if (at - 6 < length)
return true;
// Byte 6+LEN: CHECKSUM - sum of all bytes (including header) modulo 256
uint8_t rx_checksum = new_byte;
const uint8_t calc_checksum = sum_bytes(data, 6 + length);
if (rx_checksum != calc_checksum) {
ESP_LOGW(TAG, "Tuya Received invalid message checksum %02X!=%02X", rx_checksum, calc_checksum);
return false;
}
// valid message
const uint8_t *message_data = data + 6;
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Received Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", command, version,
format_hex_pretty_to(hex_buf, message_data, length), static_cast<uint8_t>(this->init_state_));
#endif
this->handle_command_(command, version, message_data, length);
// return false to reset rx buffer
return false;
}
void TuyaUART::handle_char_(uint8_t c) {
this->rx_message_.push_back(c);
if (!this->validate_message_()) {
this->rx_message_.clear();
} else {
this->last_rx_char_timestamp_ = millis();
}
}
void TuyaUART::handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len) {
TuyaCommandType command_type = (TuyaCommandType) command;
if (this->expected_response_.has_value() && this->expected_response_ == command_type) {
this->expected_response_.reset();
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
switch (command_type) {
case TuyaCommandType::HEARTBEAT:
ESP_LOGV(TAG, "MCU Heartbeat (0x%02X)", buffer[0]);
this->protocol_version_ = version;
if (buffer[0] == 0) {
ESP_LOGI(TAG, "MCU restarted");
this->init_state_ = TuyaInitState::INIT_HEARTBEAT;
}
if (this->init_state_ == TuyaInitState::INIT_HEARTBEAT) {
this->init_state_ = TuyaInitState::INIT_PRODUCT;
this->send_empty_command_(TuyaCommandType::PRODUCT_QUERY);
}
break;
case TuyaCommandType::PRODUCT_QUERY: {
// check it is a valid string made up of printable characters
bool valid = true;
for (size_t i = 0; i < len; i++) {
if (!std::isprint(buffer[i])) {
valid = false;
break;
}
}
if (valid) {
this->product_ = std::make_unique<char[]>(len + 1);
memcpy(this->product_.get(), buffer, len);
} else {
this->product_.reset();
}
this->product_invalid_ = !valid;
if (this->init_state_ == TuyaInitState::INIT_PRODUCT) {
this->init_state_ = TuyaInitState::INIT_CONF;
this->send_empty_command_(TuyaCommandType::CONF_QUERY);
}
break;
}
case TuyaCommandType::CONF_QUERY: {
if (len >= 2) {
this->status_pin_reported_ = buffer[0];
this->reset_pin_reported_ = buffer[1];
}
if (this->init_state_ == TuyaInitState::INIT_CONF) {
// If mcu returned status gpio, then we can omit sending wifi state
if (this->status_pin_reported_ != -1) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
if (this->status_pin_ != nullptr) {
if (this->status_pin_->get_pin() != this->status_pin_reported_) {
ESP_LOGW(TAG, "Supplied status_pin does not equal the reported pin %i. Using supplied pin anyway.",
this->status_pin_reported_);
}
ESP_LOGV(TAG, "Configured status pin %i", this->status_pin_->get_pin());
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->set_status_pin_(); });
} else {
ESP_LOGW(TAG, "MCU reported status_pin %i but no status_pin was configured; running in limited mode.",
this->status_pin_reported_);
}
} else {
this->init_state_ = TuyaInitState::INIT_WIFI;
ESP_LOGV(TAG, "Configured WIFI_STATE periodic send");
this->set_interval(WIFI_STATUS_INTERVAL_ID, 1000, [this] { this->send_wifi_status_(); });
}
}
break;
}
case TuyaCommandType::WIFI_STATE:
if (this->init_state_ == TuyaInitState::INIT_WIFI) {
this->init_state_ = TuyaInitState::INIT_DATAPOINT;
this->send_empty_command_(TuyaCommandType::DATAPOINT_QUERY);
}
break;
case TuyaCommandType::WIFI_SELECT:
case TuyaCommandType::WIFI_RESET: {
const bool is_select = (len >= 1);
// Send WIFI_SELECT ACK
TuyaCommand ack;
ack.cmd = is_select ? TuyaCommandType::WIFI_SELECT : TuyaCommandType::WIFI_RESET;
ack.payload.clear();
this->send_command_(ack);
// Establish pairing mode for correct first WIFI_STATE byte, EZ (0x00) default
uint8_t first = 0x00;
const char *mode_str = "EZ";
if (is_select && buffer[0] == 0x01) {
first = 0x01;
mode_str = "AP";
}
// Send WIFI_STATE response, MCU exits pairing mode
TuyaCommand st;
st.cmd = TuyaCommandType::WIFI_STATE;
st.payload.resize(1);
st.payload[0] = first;
this->send_command_(st);
st.payload[0] = 0x02;
this->send_command_(st);
st.payload[0] = 0x03;
this->send_command_(st);
st.payload[0] = 0x04;
this->send_command_(st);
ESP_LOGI(TAG, "%s received (%s), replied with WIFI_STATE confirming connection established",
is_select ? LOG_STR_LITERAL("WIFI_SELECT") : LOG_STR_LITERAL("WIFI_RESET"), mode_str);
break;
}
case TuyaCommandType::DATAPOINT_DELIVER:
break;
case TuyaCommandType::DATAPOINT_REPORT_ASYNC:
case TuyaCommandType::DATAPOINT_REPORT_SYNC:
if (this->init_state_ == TuyaInitState::INIT_DATAPOINT) {
this->init_state_ = TuyaInitState::INIT_DONE;
this->set_timeout(DATAPOINT_DUMP_TIMEOUT_ID, 1000, [this] { this->dump_mcu_config_(); });
this->mark_initialized_();
}
this->handle_datapoints_(buffer, len);
if (command_type == TuyaCommandType::DATAPOINT_REPORT_SYNC) {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_REPORT_ACK, .payload = std::vector<uint8_t>{0x01}});
}
break;
case TuyaCommandType::DATAPOINT_QUERY:
break;
case TuyaCommandType::WIFI_TEST:
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_TEST, .payload = std::vector<uint8_t>{0x00, 0x00}});
break;
case TuyaCommandType::WIFI_RSSI:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::WIFI_RSSI, .payload = std::vector<uint8_t>{get_wifi_rssi_()}});
break;
case TuyaCommandType::LOCAL_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_local_time_();
this->register_local_time_sync_callback_();
} else
#endif
{
ESP_LOGW(TAG, "LOCAL_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::GMT_TIME_QUERY:
#ifdef USE_TIME
if (this->time_id_ != nullptr) {
this->send_gmt_time_();
if (!this->gmt_time_sync_callback_registered_) {
// tuya mcu supports time, so we let them know when our time changed
this->time_id_->add_on_time_sync_callback([this] { this->send_gmt_time_(); });
this->gmt_time_sync_callback_registered_ = true;
}
} else
#endif
{
ESP_LOGW(TAG, "GMT_TIME_QUERY is not handled because time is not configured");
}
break;
case TuyaCommandType::VACUUM_MAP_UPLOAD:
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::VACUUM_MAP_UPLOAD, .payload = std::vector<uint8_t>{0x01}});
ESP_LOGW(TAG, "Vacuum map upload requested, responding that it is not enabled.");
break;
case TuyaCommandType::GET_NETWORK_STATUS: {
uint8_t wifi_status = this->get_wifi_status_code_();
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::GET_NETWORK_STATUS, .payload = std::vector<uint8_t>{wifi_status}});
ESP_LOGV(TAG, "Network status requested, reported as %i", wifi_status);
break;
}
case TuyaCommandType::EXTENDED_SERVICES: {
uint8_t subcommand = buffer[0];
switch ((TuyaExtendedServicesCommandType) subcommand) {
case TuyaExtendedServicesCommandType::RESET_NOTIFICATION: {
this->send_command_(
TuyaCommand{.cmd = TuyaCommandType::EXTENDED_SERVICES,
.payload = std::vector<uint8_t>{
static_cast<uint8_t>(TuyaExtendedServicesCommandType::RESET_NOTIFICATION), 0x00}});
ESP_LOGV(TAG, "Reset status notification enabled");
break;
}
case TuyaExtendedServicesCommandType::MODULE_RESET: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::MODULE_RESET is not handled");
break;
}
case TuyaExtendedServicesCommandType::UPDATE_IN_PROGRESS: {
ESP_LOGE(TAG, "EXTENDED_SERVICES::UPDATE_IN_PROGRESS is not handled");
break;
}
default:
ESP_LOGE(TAG, "Invalid extended services subcommand (0x%02X) received", subcommand);
}
break;
}
default:
ESP_LOGE(TAG, "Invalid command (0x%02X) received", command);
}
}
void TuyaUART::handle_datapoints_(const uint8_t *buffer, size_t len) {
while (len >= 4) {
TuyaDatapoint datapoint{};
datapoint.id = buffer[0];
datapoint.type = (TuyaDatapointType) buffer[1];
datapoint.value_uint = 0;
size_t data_size = encode_uint16(buffer[2], buffer[3]);
const uint8_t *data = buffer + 4;
size_t data_len = len - 4;
if (data_size > data_len) {
ESP_LOGW(TAG, "Datapoint %u is truncated and cannot be parsed (%zu > %zu)", datapoint.id, data_size, data_len);
return;
}
datapoint.len = data_size;
switch (datapoint.type) {
case TuyaDatapointType::RAW:
datapoint.value_raw = std::vector<uint8_t>(data, data + data_size);
{
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id,
format_hex_pretty_to(hex_buf, datapoint.value_raw.data(), datapoint.value_raw.size()));
}
break;
case TuyaDatapointType::BOOLEAN:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad boolean len %zu", datapoint.id, data_size);
return;
}
datapoint.value_bool = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, ONOFF(datapoint.value_bool));
break;
case TuyaDatapointType::INTEGER:
if (data_size != 4) {
ESP_LOGW(TAG, "Datapoint %u has bad integer len %zu", datapoint.id, data_size);
return;
}
datapoint.value_uint = encode_uint32(data[0], data[1], data[2], data[3]);
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_int);
break;
case TuyaDatapointType::STRING:
datapoint.value_string = std::string(reinterpret_cast<const char *>(data), data_size);
ESP_LOGD(TAG, "Datapoint %u update to %s", datapoint.id, datapoint.value_string.c_str());
break;
case TuyaDatapointType::ENUM:
if (data_size != 1) {
ESP_LOGW(TAG, "Datapoint %u has bad enum len %zu", datapoint.id, data_size);
return;
}
datapoint.value_enum = data[0];
ESP_LOGD(TAG, "Datapoint %u update to %d", datapoint.id, datapoint.value_enum);
break;
case TuyaDatapointType::BITMASK:
switch (data_size) {
case 1:
datapoint.value_bitmask = encode_uint32(0, 0, 0, data[0]);
break;
case 2:
datapoint.value_bitmask = encode_uint32(0, 0, data[0], data[1]);
break;
case 4:
datapoint.value_bitmask = encode_uint32(data[0], data[1], data[2], data[3]);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has bad bitmask len %zu", datapoint.id, data_size);
return;
}
ESP_LOGD(TAG, "Datapoint %u update to %#08" PRIX32, datapoint.id, datapoint.value_bitmask);
break;
default:
ESP_LOGW(TAG, "Datapoint %u has unknown type %#02hhX", datapoint.id, static_cast<uint8_t>(datapoint.type));
return;
}
len -= data_size + 4;
buffer = data + data_size;
this->handle_datapoint_(datapoint);
}
}
void TuyaUART::send_raw_command_(TuyaCommand command) {
uint8_t len_hi = (uint8_t) (command.payload.size() >> 8);
uint8_t len_lo = (uint8_t) (command.payload.size() & 0xFF);
uint8_t version = 0;
this->last_command_timestamp_ = millis();
switch (command.cmd) {
case TuyaCommandType::HEARTBEAT:
this->expected_response_ = TuyaCommandType::HEARTBEAT;
break;
case TuyaCommandType::PRODUCT_QUERY:
this->expected_response_ = TuyaCommandType::PRODUCT_QUERY;
break;
case TuyaCommandType::CONF_QUERY:
this->expected_response_ = TuyaCommandType::CONF_QUERY;
break;
case TuyaCommandType::DATAPOINT_DELIVER:
case TuyaCommandType::DATAPOINT_QUERY:
this->expected_response_ = TuyaCommandType::DATAPOINT_REPORT_ASYNC;
break;
default:
break;
}
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
char hex_buf[format_hex_pretty_size(MAX_DATAPOINT_LOG_BYTES)];
ESP_LOGV(TAG, "Sending Tuya: CMD=0x%02X VERSION=%u DATA=[%s] INIT_STATE=%u", static_cast<uint8_t>(command.cmd),
version, format_hex_pretty_to(hex_buf, command.payload.data(), command.payload.size()),
static_cast<uint8_t>(this->init_state_));
#endif
this->write_array({0x55, 0xAA, version, (uint8_t) command.cmd, len_hi, len_lo});
if (!command.payload.empty())
this->write_array(command.payload.data(), command.payload.size());
const uint8_t header_sum = 0x55 + 0xAA + (uint8_t) command.cmd + len_hi + len_lo;
this->write_byte(sum_bytes(command.payload.data(), command.payload.size(), header_sum));
}
void TuyaUART::process_command_queue_() {
uint32_t now = millis();
uint32_t delay = now - this->last_command_timestamp_;
if (now - this->last_rx_char_timestamp_ > RECEIVE_TIMEOUT) {
this->rx_message_.clear();
}
if (this->expected_response_.has_value() && delay > RECEIVE_TIMEOUT) {
this->expected_response_.reset();
if (init_state_ != TuyaInitState::INIT_DONE) {
if (++this->init_retries_ >= MAX_RETRIES) {
this->init_failed_ = true;
ESP_LOGE(TAG, "Initialization failed at init_state %u", static_cast<uint8_t>(this->init_state_));
this->command_queue_.erase(command_queue_.begin());
this->init_retries_ = 0;
}
} else {
this->command_queue_.erase(command_queue_.begin());
}
}
// Left check of delay since last command in case there's ever a command sent by calling send_raw_command_ directly
if (delay > COMMAND_DELAY && !this->command_queue_.empty() && this->rx_message_.empty() &&
!this->expected_response_.has_value()) {
this->send_raw_command_(command_queue_.front());
if (!this->expected_response_.has_value())
this->command_queue_.erase(command_queue_.begin());
}
}
void TuyaUART::send_command_(TuyaCommand command) {
command_queue_.push_back(std::move(command));
process_command_queue_();
}
void TuyaUART::send_empty_command_(TuyaCommandType command) {
send_command_(TuyaCommand{.cmd = command, .payload = std::vector<uint8_t>{}});
}
void TuyaUART::send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) {
std::vector<uint8_t> buffer;
buffer.reserve(4 + len);
buffer.push_back(datapoint_id);
buffer.push_back(static_cast<uint8_t>(datapoint_type));
buffer.push_back(len >> 8);
buffer.push_back(len >> 0);
buffer.insert(buffer.end(), data, data + len);
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::DATAPOINT_DELIVER, .payload = std::move(buffer)});
}
void TuyaUART::set_status_pin_() {
bool is_network_ready = network_is_connected() && remote_is_connected();
this->status_pin_->digital_write(is_network_ready);
}
uint8_t TuyaUART::get_wifi_status_code_() {
uint8_t status = 0x02;
if (network_is_connected()) {
status = 0x03;
// Protocol version 3 also supports specifying when connected to "the cloud"
if (this->protocol_version_ >= 0x03 && remote_is_connected()) {
status = 0x04;
}
} else {
#ifdef USE_CAPTIVE_PORTAL
if (captive_portal::global_captive_portal != nullptr && captive_portal::global_captive_portal->is_active()) {
status = 0x01;
}
#endif
};
return status;
}
uint8_t TuyaUART::get_wifi_rssi_() {
#ifdef USE_WIFI
if (wifi::global_wifi_component != nullptr)
return wifi::global_wifi_component->wifi_rssi();
#endif
return 0;
}
void TuyaUART::send_wifi_status_() {
uint8_t status = this->get_wifi_status_code_();
if (status == this->wifi_status_) {
return;
}
ESP_LOGD(TAG, "Sending WiFi Status");
this->wifi_status_ = status;
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::WIFI_STATE, .payload = std::vector<uint8_t>{status}});
}
#ifdef USE_TIME
void TuyaUART::register_local_time_sync_callback_() {
if (this->time_sync_callback_registered_) {
return;
}
this->time_id_->add_on_time_sync_callback([this] { this->send_local_time_(); });
this->time_sync_callback_registered_ = true;
}
void TuyaUART::check_force_time_sync_() {
ESPTime now = this->time_id_->now();
if (!now.is_valid() || now.minute == this->last_force_time_sync_minute_)
return;
this->last_force_time_sync_minute_ = now.minute;
this->send_local_time_(true);
}
void TuyaUART::send_local_time_(bool periodic) {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->now();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
// Tuya days starts from Monday, esphome uses Sunday as day 1
uint8_t day_of_week = now.day_of_week - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
// The forced send repeats every minute, so it stays out of the debug log
if (periodic) {
ESP_LOGV(TAG, "Sending local time");
} else {
ESP_LOGD(TAG, "Sending local time");
}
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second, day_of_week};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing local time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::LOCAL_TIME_QUERY, .payload = payload});
}
void TuyaUART::send_gmt_time_() {
std::vector<uint8_t> payload;
ESPTime now = this->time_id_->utcnow();
if (now.is_valid()) {
uint8_t year = now.year - 2000;
uint8_t month = now.month;
uint8_t day_of_month = now.day_of_month;
uint8_t hour = now.hour;
uint8_t minute = now.minute;
uint8_t second = now.second;
ESP_LOGD(TAG, "Sending gmt time");
payload = std::vector<uint8_t>{0x01, year, month, day_of_month, hour, minute, second};
} else {
// By spec we need to notify MCU that the time was not obtained if this is a response to a query
ESP_LOGW(TAG, "Sending missing gmt time");
payload = std::vector<uint8_t>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
}
this->send_command_(TuyaCommand{.cmd = TuyaCommandType::GMT_TIME_QUERY, .payload = payload});
}
#endif
TuyaInitState TuyaUART::get_init_state() { return this->init_state_; }
} // namespace esphome::tuya
-117
View File
@@ -1,117 +0,0 @@
#pragma once
#include <cinttypes>
#include <memory>
#include <vector>
#include "tuya.h"
#include "esphome/components/uart/uart.h"
#ifdef USE_TIME
#include "esphome/components/time/real_time_clock.h"
#include "esphome/core/time.h"
#endif
namespace esphome::tuya {
enum class TuyaCommandType : uint8_t {
HEARTBEAT = 0x00,
PRODUCT_QUERY = 0x01,
CONF_QUERY = 0x02,
WIFI_STATE = 0x03,
WIFI_RESET = 0x04,
WIFI_SELECT = 0x05,
DATAPOINT_DELIVER = 0x06,
DATAPOINT_REPORT_ASYNC = 0x07,
DATAPOINT_QUERY = 0x08,
GMT_TIME_QUERY = 0x0C,
WIFI_TEST = 0x0E,
LOCAL_TIME_QUERY = 0x1C,
DATAPOINT_REPORT_SYNC = 0x22,
DATAPOINT_REPORT_ACK = 0x23,
WIFI_RSSI = 0x24,
VACUUM_MAP_UPLOAD = 0x28,
GET_NETWORK_STATUS = 0x2B,
EXTENDED_SERVICES = 0x34,
};
enum class TuyaExtendedServicesCommandType : uint8_t {
RESET_NOTIFICATION = 0x04,
MODULE_RESET = 0x05,
UPDATE_IN_PROGRESS = 0x0A,
};
enum class TuyaInitState : uint8_t {
INIT_HEARTBEAT = 0x00,
INIT_PRODUCT,
INIT_CONF,
INIT_WIFI,
INIT_DATAPOINT,
INIT_DONE,
};
struct TuyaCommand {
TuyaCommandType cmd;
std::vector<uint8_t> payload;
};
/// Tuya MCU controller connected over UART (the standard Tuya serial protocol).
class TuyaUART final : public Tuya, public uart::UARTDevice {
public:
void setup() override;
void loop() override;
void dump_config() override;
void set_status_pin(InternalGPIOPin *status_pin) { this->status_pin_ = status_pin; }
TuyaInitState get_init_state();
#ifdef USE_TIME
void set_time_id(time::RealTimeClock *time_id) { this->time_id_ = time_id; }
void set_force_time_sync(bool force_time_sync) { this->force_time_sync_ = force_time_sync; }
#endif
protected:
void dump_mcu_config_();
void handle_char_(uint8_t c);
void handle_datapoints_(const uint8_t *buffer, size_t len);
bool validate_message_();
void handle_command_(uint8_t command, uint8_t version, const uint8_t *buffer, size_t len);
void send_raw_command_(TuyaCommand command);
void process_command_queue_();
void send_command_(TuyaCommand command);
void send_empty_command_(TuyaCommandType command);
void send_datapoint_command(uint8_t datapoint_id, TuyaDatapointType datapoint_type, const uint8_t *data,
size_t len) override;
void set_status_pin_();
void send_wifi_status_();
uint8_t get_wifi_status_code_();
uint8_t get_wifi_rssi_();
#ifdef USE_TIME
void register_local_time_sync_callback_();
void check_force_time_sync_();
void send_local_time_(bool periodic = false);
void send_gmt_time_();
time::RealTimeClock *time_id_{nullptr};
bool force_time_sync_{false};
uint8_t last_force_time_sync_minute_{0xFF}; // 0xFF: no minute seen yet
bool time_sync_callback_registered_{false};
bool gmt_time_sync_callback_registered_{false};
#endif
TuyaInitState init_state_ = TuyaInitState::INIT_HEARTBEAT;
bool init_failed_{false};
int init_retries_{0};
uint8_t protocol_version_ = -1;
InternalGPIOPin *status_pin_{nullptr};
int status_pin_reported_ = -1;
int reset_pin_reported_ = -1;
uint32_t last_command_timestamp_ = 0;
uint32_t last_rx_char_timestamp_ = 0;
std::unique_ptr<char[]> product_;
std::vector<uint8_t> rx_message_;
std::vector<TuyaCommand> command_queue_;
optional<TuyaCommandType> expected_response_{};
uint8_t wifi_status_ = -1;
bool product_invalid_{false};
};
} // namespace esphome::tuya
+4 -4
View File
@@ -35,7 +35,7 @@ WatchdogManager::~WatchdogManager() {
void WatchdogManager::set_timeout_(uint32_t timeout_ms) {
ESP_LOGV(TAG, "Adjusting WDT to %" PRIu32 "ms", timeout_ms);
#ifdef USE_ESP32_TASK_WDT
#ifdef USE_ESP32
esp_task_wdt_config_t wdt_config = {
.timeout_ms = timeout_ms,
.idle_core_mask = 0,
@@ -51,7 +51,7 @@ void WatchdogManager::set_timeout_(uint32_t timeout_ms) {
wdt_config.trigger_panic = true;
#endif
esp_task_wdt_reconfigure(&wdt_config);
#endif // USE_ESP32_TASK_WDT
#endif // USE_ESP32
#ifdef USE_RP2
watchdog_enable(timeout_ms, true);
@@ -61,9 +61,9 @@ void WatchdogManager::set_timeout_(uint32_t timeout_ms) {
uint32_t WatchdogManager::get_timeout_() {
uint32_t timeout_ms = 0;
#ifdef USE_ESP32_TASK_WDT
#ifdef USE_ESP32
timeout_ms = (uint32_t) CONFIG_ESP_TASK_WDT_TIMEOUT_S * 1000;
#endif // USE_ESP32_TASK_WDT
#endif // USE_ESP32
#ifdef USE_RP2
timeout_ms = watchdog_get_count() / 1000;
+1 -3
View File
@@ -7,7 +7,7 @@ import re
from typing import Any
import esphome.codegen as cg
from esphome.components import web_server_base, web_server_idf
from esphome.components import web_server_base
from esphome.components.json import enable_arena
from esphome.components.logger import request_log_listener
from esphome.components.web_server_base import (
@@ -234,8 +234,6 @@ def _consume_web_server_sockets(config: ConfigType) -> ConfigType:
# (browser opens connections for page resources, SSE event stream, and POST
# requests for entity control which may linger before closing)
web_server_base.add_httpd_clients(5, DOMAIN)
# Event streams send from the main loop straight to the socket, which would bypass TLS.
web_server_idf.require_plain_http(DOMAIN)
return config
+1 -1
View File
@@ -273,7 +273,7 @@ void DeferredUpdateEventSource::process_deferred_queue_() {
deferred_queue_.erase(deferred_queue_.begin());
this->consecutive_send_failures_ = 0; // Reset failure count on successful send
} else {
// NOTE: Similar logic exists in web_server_idf/web_server_idf.cpp in AsyncStreamResponse::write().
// NOTE: Similar logic exists in web_server_idf/web_server_idf.cpp in AsyncEventSourceResponse::drain_tail_().
// The close mechanisms are platform-specific (this path calls close() directly; the IDF path is time-based and
// closes through HTTPD to preserve session ownership), but both drop a client after roughly 20 seconds without
// send progress. Keep that stall policy in sync when changing either side.
@@ -105,9 +105,6 @@ class WebServerBase final {
return;
}
this->server_ = new AsyncWebServer(this->port_);
#if defined(USE_ESP32) && defined(USE_WEBSERVER_SSL)
this->server_->set_ssl_credentials(this->ssl_certificate_, this->ssl_private_key_);
#endif
// All content is controlled and created by user - so allowing all origins is fine here.
// NOTE: Currently 1 header. If more are added, update in __init__.py:
// cg.add_define("WEB_SERVER_DEFAULT_HEADERS_COUNT", 1)
@@ -161,21 +158,7 @@ class WebServerBase final {
void set_port(uint16_t port) { port_ = port; }
uint16_t get_port() const { return port_; }
#if defined(USE_ESP32) && defined(USE_WEBSERVER_SSL)
/// PEM certificate and key for HTTPS. Not copied: they must stay valid. Set them, like the port, before init().
void set_ssl_credentials(const char *certificate, const char *private_key) {
this->ssl_certificate_ = certificate;
this->ssl_private_key_ = private_key;
if (this->server_ != nullptr)
this->server_->set_ssl_credentials(certificate, private_key); // used at the next init()
}
#endif
protected:
#if defined(USE_ESP32) && defined(USE_WEBSERVER_SSL)
const char *ssl_certificate_{nullptr};
const char *ssl_private_key_{nullptr};
#endif
uint8_t initialized_{0};
uint16_t port_{80}; // Keep in sync with DEFAULT_PORT in web_server/__init__.py
AsyncWebServer *server_{nullptr};
@@ -1,19 +1,14 @@
from dataclasses import dataclass, field
import logging
import esphome.codegen as cg
from esphome.components import socket, web_server_base
from esphome.components.esp32 import (
get_user_lwip_max_sockets,
idf_version,
include_builtin_idf_component,
request_tls,
require_mbedtls_tls_server,
set_idf_sdkconfig_default,
)
from esphome.config_helpers import filter_source_files_from_defines
import esphome.config_validation as cv
from esphome.core import CORE
from esphome.types import ConfigType
_LOGGER = logging.getLogger(__name__)
@@ -28,46 +23,6 @@ DEFAULT_HTTPD_MAX_OPEN_SOCKETS = 7
HTTPD_CONTROL_UDP_SOCKETS = 2
# ESP-IDF's HTTPS server allows this many open connections; each holds a TLS session.
HTTPS_MAX_CONNECTIONS = 4
@dataclass
class WebServerIdfData:
ssl: bool = False # a component serves HTTPS (consume_ssl_sockets() was called)
# Consumers that need plain HTTP (require_plain_http() was called)
plain_http: list[str] = field(default_factory=list)
def _get_data() -> WebServerIdfData:
if DOMAIN not in CORE.data:
CORE.data[DOMAIN] = WebServerIdfData()
return CORE.data[DOMAIN]
def consume_ssl_sockets(config: ConfigType) -> ConfigType:
"""Serve the shared web server over HTTPS.
The one thing a component that supplies its own certificate adds to its
schema; it then calls WebServerBase::set_ssl_credentials() before init().
This compiles HTTPS in and registers the connections it can hold open.
"""
data = _get_data()
# HTTPS exists only on ESP32. The listener is shared, so its clients are registered once.
if CORE.is_esp32 and not data.ssl:
web_server_base.add_httpd_clients(HTTPS_MAX_CONNECTIONS, DOMAIN)
data.ssl = True
return config
def require_plain_http(consumer: str) -> None:
"""Record that consumer needs the shared web server to speak plain HTTP.
Call during config validation; HTTPS is then rejected in final validation.
"""
_get_data().plain_http.append(consumer)
CONFIG_SCHEMA = cv.All(
cv.Schema({}),
cv.only_on_esp32,
@@ -82,9 +37,6 @@ def _httpd_max_open_sockets() -> int:
max_open = max(
DEFAULT_HTTPD_MAX_OPEN_SOCKETS, web_server_base.get_httpd_client_count()
)
# Each TLS session takes memory, so HTTPS keeps ESP-IDF's HTTPS connection limit.
if _get_data().ssl:
max_open = min(max_open, HTTPS_MAX_CONNECTIONS)
# Without a user override esp32 sizes CONFIG_LWIP_MAX_SOCKETS from the socket
# registry, which already holds the clients and the internal sockets.
if (user_max := get_user_lwip_max_sockets()) is None:
@@ -103,32 +55,9 @@ def _httpd_max_open_sockets() -> int:
return max_open
def _final_validate(config: ConfigType) -> None:
# Runs after every CONFIG_SCHEMA, so all require_plain_http() calls are in.
data = _get_data()
if not data.ssl:
return
# tls_handshake_timeout_ms, which keeps a stalled client from holding the server task, is new in 5.5.
if idf_version() < cv.Version(5, 5, 0):
raise cv.Invalid("HTTPS needs ESP-IDF 5.5 or later")
if data.plain_http:
names = ", ".join(data.plain_http)
raise cv.Invalid(f"HTTPS can't be used together with {names} yet")
FINAL_VALIDATE_SCHEMA = _final_validate
async def to_code(config: ConfigType) -> None:
# Runs after config validation, so every add_httpd_clients() call is counted.
cg.add_define("WEB_SERVER_MAX_OPEN_SOCKETS", _httpd_max_open_sockets())
if _get_data().ssl:
cg.add_define("USE_WEBSERVER_SSL")
request_tls()
# ESPHome builds mbedTLS client-only unless a component accepts TLS sessions.
require_mbedtls_tls_server()
include_builtin_idf_component("esp_https_server")
set_idf_sdkconfig_default("CONFIG_ESP_HTTPS_SERVER_ENABLE", True)
# Increase the maximum supported size of headers section in HTTP request packet to be processed by the server
set_idf_sdkconfig_default("CONFIG_HTTPD_MAX_REQ_HDR_LEN", 1024)
# Re-enable ESP-IDF's HTTP server (excluded by default to save compile time).
@@ -3,8 +3,6 @@
#include <cstddef>
#include <cstdint>
#include "stream_head.h"
namespace esphome::web_server_idf {
// Wire framing of one Server-Sent-Events event inside the chunked /events response:
@@ -24,17 +22,6 @@ constexpr size_t SSE_SEP_LEN = sizeof(SSE_SEP) - 1;
constexpr char SSE_SUFFIX[] = "\r\n\r\n\r\n";
constexpr size_t SSE_SUFFIX_LEN = sizeof(SSE_SUFFIX) - 1;
// Status, Content-Type and headers of the /events response head
constexpr char SSE_STATUS[] = "200 OK";
constexpr char SSE_CONTENT_TYPE[] = "text/event-stream";
constexpr HttpHeader SSE_HEADERS[] = {
{"Transfer-Encoding", "chunked"},
{"Cache-Control", "no-cache"},
{"Connection", "keep-alive"},
};
// Hand-framed first chunk holding an empty event (one blank line), as httpd_resp_send_chunk() sent it before
constexpr char SSE_FIRST_CHUNK[] = "2\r\n\r\n\r\n";
// Receives one piece of the chunk; ctx is whatever the caller passed to for_each_chunk_piece()
using ChunkPieceSink = void (*)(void *ctx, const char *piece, size_t len);
@@ -1,126 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>
#include <strings.h>
// Pure helpers of AsyncStreamResponse, kept free of httpd and lwIP so they build on the host.
// The iovec type is a template parameter: lwIP defines its own on the device, POSIX on the host.
namespace esphome::web_server_idf {
struct HttpHeader {
const char *name;
const char *value;
};
/// Drops the first sent bytes from a gather list after a write; a short write resumes inside the
/// element it stopped in. count reaches 0 once everything went out.
template<typename Iovec> void advance_iovecs(Iovec *&iov, int &count, size_t sent) {
while (count > 0 && sent >= iov->iov_len) {
sent -= iov->iov_len;
++iov;
--count;
}
if (count > 0) {
iov->iov_base = static_cast<char *>(iov->iov_base) + sent;
iov->iov_len -= sent;
}
}
/// Pieces in a head: 4 for the status line and Content-Type, 4 per header, the blank line and the body
constexpr size_t stream_head_iov_count(size_t header_count) { return 4 + 4 * header_count + 2; }
/// Pieces per batch: a head with up to four headers goes out in one write; 192 bytes on 32-bit
static constexpr int STREAM_HEAD_MAX_IOV = 24;
/// True if headers holds a header named name, compared case insensitively
inline bool has_header(std::span<const HttpHeader> headers, const char *name) {
for (const auto &header : headers) {
if (strcasecmp(header.name, name) == 0) {
return true;
}
}
return false;
}
/// Gathers the head of a stream response: "HTTP/1.1 <status>", Content-Type, headers, the default_headers that
/// headers does not replace, the blank line and body (may be null). send(Iovec *iov, int count) gets each full batch of
/// STREAM_HEAD_MAX_IOV pieces and then the rest; once it returns false the later pieces are skipped. Returns false if
/// any send failed.
template<typename Iovec, typename Send>
bool write_stream_head(Send &&send, const char *status, const char *content_type, std::span<const HttpHeader> headers,
std::span<const HttpHeader> default_headers, const char *body) {
struct Batch {
Send &send;
int count{0};
bool ok{true};
Iovec iov[STREAM_HEAD_MAX_IOV]; // left uninitialized on purpose
void flush() {
if (this->ok && this->count > 0) {
this->ok = this->send(this->iov, this->count);
}
this->count = 0;
}
void add(const char *buf, size_t len) {
if (this->count == STREAM_HEAD_MAX_IOV) {
this->flush();
}
this->iov[this->count++] = {const_cast<char *>(buf), len};
}
void add(const char *str) { this->add(str, strlen(str)); }
void add_header(const HttpHeader &header) {
this->add("\r\n", 2);
this->add(header.name);
this->add(": ", 2);
this->add(header.value);
}
} batch{send};
batch.add("HTTP/1.1 ", 9);
batch.add(status);
batch.add("\r\nContent-Type: ", 16);
batch.add(content_type);
for (const auto &header : headers) {
batch.add_header(header);
}
for (const auto &header : default_headers) {
if (!has_header(headers, header.name)) {
batch.add_header(header);
}
}
batch.add("\r\n\r\n", 4);
if (body != nullptr) {
batch.add(body);
}
batch.flush();
return batch.ok;
}
/// How long sends have made no progress. Zero means not running, so a start at millis() == 0 records 1.
/// The comparison is wraparound safe across a millis() rollover.
class StallClock {
public:
/// Starts the clock; a running clock keeps its start time.
void start(uint32_t now) {
if (this->started_ms_ == 0) {
this->started_ms_ = now != 0 ? now : 1;
}
}
void clear() { this->started_ms_ = 0; }
bool is_running() const { return this->started_ms_ != 0; }
/// True once the clock has run for timeout_ms
bool is_expired(uint32_t now, uint32_t timeout_ms) const {
return this->started_ms_ != 0 && static_cast<int32_t>(now - (this->started_ms_ + timeout_ms)) >= 0;
}
uint32_t elapsed(uint32_t now) const { return now - this->started_ms_; }
protected:
uint32_t started_ms_{0};
};
} // namespace esphome::web_server_idf
@@ -20,14 +20,6 @@
#include "sse_chunk.h"
#include "web_server_idf.h"
#ifdef USE_WEBSERVER_SSL
#include <esp_https_server.h>
#include <freertos/semphr.h>
#include <esp_idf_version.h>
#include <mbedtls/pk.h>
#include <mbedtls/x509_crt.h>
#endif
#ifdef USE_WEBSERVER_AUTH_DIGEST
#include <esp_random.h>
#include <esp_rom_md5.h>
@@ -63,6 +55,9 @@ namespace esphome::web_server_idf {
#define HTTPD_422 "422 Unprocessable Entity"
#endif
#define CRLF_STR "\r\n"
#define CRLF_LEN (sizeof(CRLF_STR) - 1)
ESPHOME_LOG_TAG(TAG, "web_server_idf");
// Only prepare_json_() may hold the JSON arena: every other frame in this file is capped below one
@@ -145,12 +140,6 @@ void AsyncWebServer::safe_close_with_shutdown(httpd_handle_t hd, int sockfd) {
//
// See: https://github.com/esphome/esphome-webserver/issues/163
AsyncStreamResponse::socket_closing(hd, sockfd);
#ifdef USE_WEBSERVER_SSL
// Keeps shutdown_clients_() from acting on a descriptor freed, and its number reused, while it walks the list.
LockGuard lock(static_cast<AsyncWebServer *>(httpd_get_global_user_ctx(hd))->close_lock_);
#endif
// Attempt shutdown - ignore errors as socket may already be closed
shutdown(sockfd, SHUT_RD);
@@ -158,144 +147,16 @@ void AsyncWebServer::safe_close_with_shutdown(httpd_handle_t hd, int sockfd) {
close(sockfd);
}
#ifdef USE_WEBSERVER_SSL
namespace {
// Local port of a socket, or 0 if the descriptor is not an open socket.
uint16_t local_port(int fd) {
struct sockaddr_storage addr{};
socklen_t len = sizeof(addr);
if (getsockname(fd, reinterpret_cast<struct sockaddr *>(&addr), &len) != 0) {
return 0;
}
if (addr.ss_family == AF_INET) {
return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
}
#if LWIP_IPV6
if (addr.ss_family == AF_INET6) {
return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
}
#endif
return 0;
}
// Stops the server for AsyncWebServer::end() on its own task and signals the caller when done.
// A semaphore, not a task notification: the main loop task already uses notifications to wake itself.
struct StopRequest {
httpd_handle_t server;
bool ssl;
esp_err_t result;
StaticSemaphore_t done_buffer;
SemaphoreHandle_t done;
};
// httpd_ssl_stop() also posts HTTPS_SERVER_EVENT_STOP, to match the start event httpd_ssl_start() posted.
esp_err_t stop_server(httpd_handle_t server, bool ssl) { return ssl ? httpd_ssl_stop(server) : httpd_stop(server); }
void stop_task(void *arg) {
auto *request = static_cast<StopRequest *>(arg);
request->result = stop_server(request->server, request->ssl);
xSemaphoreGive(request->done); // the request is not touched after this
vTaskDelete(nullptr);
}
} // namespace
void AsyncWebServer::context_free(void *ctx) {
// Waits for a running shutdown_clients_() pass, and makes later passes skip the freed server.
auto *server = static_cast<AsyncWebServer *>(ctx);
LockGuard lock(server->close_lock_);
server->running_port_ = 0;
}
void AsyncWebServer::shutdown_clients_() {
// Wakes the server task if it is blocked on a client. A just-closed client may still be listed with its number
// reused elsewhere, so only descriptors still bound to this server's port are shut down.
LockGuard lock(this->close_lock_);
if (this->running_port_ == 0) {
return; // the server is being freed (context_free() ran), so its client list is gone
}
int client_fds[CONFIG_LWIP_MAX_SOCKETS];
size_t client_count = CONFIG_LWIP_MAX_SOCKETS;
if (httpd_get_client_list(this->server_, &client_count, client_fds) != ESP_OK) {
return;
}
for (size_t i = 0; i < client_count; i++) {
if (local_port(client_fds[i]) == this->running_port_) {
shutdown(client_fds[i], SHUT_RDWR);
}
}
}
namespace {
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0)
int ssl_random(void * /*unused*/, unsigned char *buf, size_t len) {
random_bytes(buf, len);
return 0;
}
#endif
// esp_https_server parses the credentials only when a client connects, so check the pair before starting.
// Lengths include the terminating null, as mbedTLS wants for PEM.
bool ssl_credentials_valid(const uint8_t *cert_pem, size_t cert_len, const uint8_t *key_pem, size_t key_len) {
mbedtls_x509_crt crt;
mbedtls_pk_context key;
mbedtls_x509_crt_init(&crt);
mbedtls_pk_init(&key);
bool valid = mbedtls_x509_crt_parse(&crt, cert_pem, cert_len) == 0;
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
// mbedTLS 4 (ESP-IDF 6) takes its randomness from PSA Crypto instead of an RNG argument.
valid = valid && mbedtls_pk_parse_key(&key, key_pem, key_len, nullptr, 0) == 0 &&
mbedtls_pk_check_pair(&crt.pk, &key) == 0;
#else
valid = valid && mbedtls_pk_parse_key(&key, key_pem, key_len, nullptr, 0, ssl_random, nullptr) == 0 &&
mbedtls_pk_check_pair(&crt.pk, &key, ssl_random, nullptr) == 0;
#endif
mbedtls_pk_free(&key);
mbedtls_x509_crt_free(&crt);
return valid;
}
} // namespace
#endif
void AsyncWebServer::end() {
if (this->server_) {
#ifdef USE_WEBSERVER_SSL
// A stalled TLS handshake or upload can hold the server task until the socket timeout. Stop on a helper task and
// keep shutting the clients down until it is done: a client accepted before the stop message arrives is listed
// during its handshake, so a later pass reaches it. Without memory for the task, stop directly.
StopRequest request{};
request.server = this->server_;
request.ssl = httpd_get_global_transport_ctx(this->server_) != nullptr; // only HTTPS has one
request.done = xSemaphoreCreateBinaryStatic(&request.done_buffer);
if (xTaskCreate(stop_task, "httpd_stop", 3072, &request, uxTaskPriorityGet(nullptr), nullptr) == pdPASS) {
do {
this->shutdown_clients_();
App.feed_wdt();
} while (xSemaphoreTake(request.done, pdMS_TO_TICKS(100)) != pdTRUE);
} else {
this->shutdown_clients_();
request.result = stop_server(this->server_, request.ssl);
}
const esp_err_t err = request.result;
if (err != ESP_OK) {
// The listener is still running; keep its handle so begin() doesn't start a second one beside it.
ESP_LOGE(TAG, "Web server failed to stop: %s", esp_err_to_name(err));
return;
}
#else
httpd_stop(this->server_);
#endif
this->server_ = nullptr; // stopping also frees an HTTPS server's TLS context
this->server_ = nullptr;
}
}
void AsyncWebServer::begin() {
if (this->server_) {
this->end();
#ifdef USE_WEBSERVER_SSL
if (this->server_) {
return; // the old listener failed to stop
}
#endif
}
// Allow room for SerializationBuffer's 640-byte stack buffer and HTTP request handling.
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
@@ -310,50 +171,7 @@ void AsyncWebServer::begin() {
config.lru_purge_enable = true;
// Use custom close function that shuts down before closing to prevent lwIP race conditions
config.close_fn = AsyncWebServer::safe_close_with_shutdown;
esp_err_t start_err;
#ifdef USE_WEBSERVER_SSL
// Lets close_fn find this server's lock. httpd calls the free function on stop just before freeing the server.
config.global_user_ctx = this;
config.global_user_ctx_free_fn = AsyncWebServer::context_free;
if ((this->ssl_certificate_ == nullptr) != (this->ssl_private_key_ == nullptr)) {
ESP_LOGE(TAG, "HTTPS needs both a certificate and a private key");
return;
}
if (this->ssl_certificate_ != nullptr) {
const auto *cert = reinterpret_cast<const uint8_t *>(this->ssl_certificate_);
const auto *key = reinterpret_cast<const uint8_t *>(this->ssl_private_key_);
const size_t cert_len = strlen(this->ssl_certificate_) + 1;
const size_t key_len = strlen(this->ssl_private_key_) + 1;
if (!ssl_credentials_valid(cert, cert_len, key, key_len)) {
ESP_LOGE(TAG, "HTTPS certificate or key is invalid, or the key does not match the certificate");
return;
}
httpd_ssl_config_t ssl_config = HTTPD_SSL_CONFIG_DEFAULT();
// The TLS handshake needs the larger stack of the HTTPS defaults.
config.stack_size = std::max(config.stack_size, ssl_config.httpd.stack_size);
ssl_config.httpd = config;
ssl_config.port_secure = this->port_;
// A client that connects and never completes the handshake holds the server task. The check runs after each
// 5 s receive timeout, so this ends it at the first one instead of after three (the 10 s default).
ssl_config.tls_handshake_timeout_ms = 4000;
ssl_config.servercert = cert;
ssl_config.servercert_len = cert_len;
ssl_config.prvtkey_pem = key;
ssl_config.prvtkey_len = key_len;
start_err = httpd_ssl_start(&this->server_, &ssl_config);
if (start_err != ESP_OK) {
ESP_LOGE(TAG, "HTTPS server failed to start: %s", esp_err_to_name(start_err));
}
} else {
start_err = httpd_start(&this->server_, &config);
}
#else
start_err = httpd_start(&this->server_, &config);
#endif
if (start_err == ESP_OK) {
#ifdef USE_WEBSERVER_SSL
this->running_port_ = this->port_;
#endif
if (httpd_start(&this->server_, &config) == ESP_OK) {
const httpd_uri_t handler_get = {
.uri = "",
.method = HTTP_GET,
@@ -918,222 +736,6 @@ void AsyncResponseStream::printf(const char *fmt, ...) {
this->print(str);
}
void AsyncStreamResponse::begin(const AsyncWebServerRequest *request, const char *status, const char *content_type,
std::span<const HttpHeader> headers, const char *body) {
httpd_req_t *req = *request;
#ifdef USE_WEBSERVER_SSL
// Streams send straight to the socket, which would bypass TLS; only an HTTPS server has a global transport context.
// Refused before anything is sent, so the stream stays unattached and safe to delete.
if (httpd_get_global_transport_ctx(req->handle) != nullptr) {
httpd_resp_send_err(req, HTTPD_501_METHOD_NOT_IMPLEMENTED, "Streams are not supported over HTTPS");
return;
}
#endif
// Same head httpd_resp_send_chunk() writes, without its first chunk. Blocking sends: the session's non-blocking
// send override is not installed yet.
const int fd = httpd_req_to_sockfd(req);
const auto &defaults = DefaultHeaders::Instance().headers_;
const bool head_sent = write_stream_head<struct iovec>(
[fd](struct iovec *iov, int count) {
while (count > 0) {
struct msghdr msg{};
msg.msg_iov = iov;
msg.msg_iovlen = count;
const ssize_t sent = sendmsg(fd, &msg, 0);
if (sent <= 0) {
return false;
}
advance_iovecs(iov, count, sent);
}
return true;
},
status, content_type, headers, std::span<const HttpHeader>(defaults.data(), defaults.size()), body);
req->sess_ctx = this;
req->free_ctx = AsyncStreamResponse::destroy;
this->hd_ = req->handle;
this->fd_.store(fd);
// Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
httpd_sess_set_send_override(this->hd_, fd, nonblocking_send);
if (!head_sent) {
// A partly sent head must not be continued by later writes. close() is main loop only, so shut the socket
// down here; the first write() then fails and closes the stream, and httpd frees the session as usual.
shutdown(fd, SHUT_RDWR);
}
}
// Held around a stream's ownership check and send, and while its socket is marked closed.
// Created at boot, so no allocation can fail once requests arrive.
static Mutex stream_send_mutex; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
void AsyncStreamResponse::socket_closing(httpd_handle_t hd, int fd) {
// Only streams set a session context
auto *rsp = static_cast<AsyncStreamResponse *>(httpd_sess_get_ctx(hd, fd));
if (rsp == nullptr)
return;
LockGuard guard{stream_send_mutex};
rsp->socket_closed_ = true;
}
void AsyncStreamResponse::destroy(void *ptr) {
auto *rsp = static_cast<AsyncStreamResponse *>(ptr);
int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
ESP_LOGD(TAG, "Stream connection closed (fd: %d)", fd);
// Mark as dead - the owner deletes it from the main loop once safe_to_delete().
// httpd will call our custom close_fn (safe_close_with_shutdown) which handles
// shutdown() before close() to prevent lwIP race conditions
}
void AsyncStreamResponse::close() {
if (!this->loop_flags_.close_requested) {
this->loop_flags_.close_requested = true;
this->next_close_attempt_ms_ = App.get_loop_component_start_time();
}
this->process_close_();
}
void AsyncStreamResponse::loop() {
if (this->loop_flags_.close_requested) {
this->process_close_();
} else {
this->refresh_lru_();
}
}
void AsyncStreamResponse::process_close_() {
if (!this->loop_flags_.close_requested || this->close_work_queued_.load(std::memory_order_acquire)) {
return;
}
const int fd = this->fd_.load();
if (fd == 0) {
return;
}
const uint32_t now = App.get_loop_component_start_time();
if (static_cast<int32_t>(now - this->next_close_attempt_ms_) < 0) {
return;
}
// Queue an identity-checked shutdown on the HTTPD task. The public
// httpd_sess_trigger_close() queues only a reusable fd/session slot and can
// therefore close a new client if the original peer disconnects meanwhile.
this->close_work_queued_.store(true, std::memory_order_release);
const esp_err_t err = httpd_queue_work(this->hd_, &AsyncStreamResponse::close_session_work, this);
this->next_close_attempt_ms_ = now + (err == ESP_OK ? CLOSE_CONFIRM_INTERVAL_MS : CLOSE_RETRY_INTERVAL_MS);
if (err == ESP_OK) {
return;
}
this->close_work_queued_.store(false, std::memory_order_release);
if (!this->loop_flags_.close_retry_warning_logged) {
ESP_LOGW(TAG, "Failed to queue stream close (%s); retrying", esp_err_to_name(err));
this->loop_flags_.close_retry_warning_logged = true;
}
}
void AsyncStreamResponse::refresh_lru_() {
// httpd only advances a session's LRU counter when a request arrives, and a stream receives one
// request ever, so the purge that frees a socket for a new client would evict the live streams first.
// The HTTPD task owns the session table, so the refresh runs there.
// A stalled stream is the socket the purge should take, and a zeroed fd has no session left to refresh.
if (this->stall_.is_running() || this->fd_.load() == 0)
return;
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_lru_refresh_ms_ < LRU_REFRESH_INTERVAL_MS ||
this->lru_work_queued_.load(std::memory_order_acquire)) {
return;
}
this->last_lru_refresh_ms_ = now; // a full queue also waits for the next interval
this->lru_work_queued_.store(true, std::memory_order_release);
if (httpd_queue_work(this->hd_, &AsyncStreamResponse::refresh_lru_work, this) != ESP_OK) {
this->lru_work_queued_.store(false, std::memory_order_release);
}
}
void AsyncStreamResponse::refresh_lru_work(void *arg) {
auto *response = static_cast<AsyncStreamResponse *>(arg);
const int fd = response->fd_.load();
if (response->owns_session_(fd)) {
httpd_sess_update_lru_counter(response->hd_, fd);
}
// Release self only after the HTTPD-task callback has finished every access.
response->lru_work_queued_.store(false, std::memory_order_release);
}
void AsyncStreamResponse::close_session_work(void *arg) {
auto *response = static_cast<AsyncStreamResponse *>(arg);
const int fd = response->fd_.load();
if (response->owns_session_(fd)) {
// The HTTPD task remains the session owner. Shutting the socket down makes
// its next select/recv path delete the session and invoke destroy().
shutdown(fd, SHUT_RDWR);
}
// Release self only after the HTTPD-task callback has finished every access.
response->close_work_queued_.store(false, std::memory_order_release);
}
ssize_t AsyncStreamResponse::write(struct iovec *iov, int iovcnt) {
if (this->loop_flags_.close_requested) {
return -1;
}
// Nothing to send is not a stall
size_t total = 0;
for (int i = 0; i < iovcnt; i++) {
total += iov[i].iov_len;
}
if (total == 0) {
return 0;
}
// httpd closes the socket before it clears the session, so the fd number may already be a new client's.
// Treated as would-block; the stall timer ends a session that never becomes ours again.
const int fd = this->fd_.load();
// httpd freed the session, so the stream can never send again
if (fd == 0) {
this->close();
return -1;
}
ssize_t sent = 0;
int err = 0;
{
// Held across the check and the send, so socket_closing() cannot close the socket in between
LockGuard guard{stream_send_mutex};
if (!this->socket_closed_ && this->owns_session_(fd)) {
struct msghdr msg{};
msg.msg_iov = iov;
msg.msg_iovlen = iovcnt;
sent = sendmsg(fd, &msg, MSG_DONTWAIT);
err = errno;
}
}
if (sent > 0) {
this->stall_.clear();
return sent;
}
if (sent < 0 && err != EAGAIN && err != EWOULDBLOCK) {
ESP_LOGD(TAG, "send error: errno %d", err);
this->close();
return -1;
}
// Socket buffer full, try again later; a socket that stays full past the stall timeout is closed
const uint32_t now = App.get_loop_component_start_time();
this->stall_.start(now);
if (this->stall_.is_expired(now, SEND_STALL_TIMEOUT_MS)) {
ESP_LOGW(TAG, "Closing stuck stream after %" PRIu32 " ms without send progress", this->stall_.elapsed(now));
this->close();
return -1;
}
return 0;
}
ssize_t AsyncStreamResponse::write(const void *data, size_t len) {
struct iovec iov = {const_cast<void *>(data), len};
return this->write(&iov, 1);
}
#ifdef USE_WEBSERVER
AsyncEventSource::~AsyncEventSource() {
LockGuard guard{this->pending_mutex_};
@@ -1172,7 +774,7 @@ bool AsyncEventSource::loop() {
for (size_t i = 0; i < this->sessions_.size();) {
auto *ses = this->sessions_[i];
// If the session has a dead socket (marked by destroy callback)
if (ses->safe_to_delete()) {
if (ses->safe_to_delete_()) {
// destroy() already logged the close with the fd; don't double-log here.
delete ses; // NOLINT(cppcoreguidelines-owning-memory)
// Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
@@ -1196,13 +798,13 @@ void AsyncEventSource::adopt_pending_sessions_main_loop_() {
}
for (auto *rsp : incoming) {
// Already disconnected? Drop it; skip session start on a dead session.
if (rsp->safe_to_delete()) {
if (rsp->safe_to_delete_()) {
delete rsp; // NOLINT(cppcoreguidelines-owning-memory)
continue;
}
// httpd commits the session context only after the creating handler returns, so stay
// pending until then; httpd_req_cleanup() always commits it or calls destroy()
if (!rsp->is_attached()) {
if (httpd_sess_get_ctx(rsp->hd_, rsp->fd_.load()) != rsp) {
LockGuard guard{this->pending_mutex_};
this->pending_sessions_.push_back(rsp);
this->has_pending_sessions_.store(true, std::memory_order_release);
@@ -1217,7 +819,7 @@ void AsyncEventSource::adopt_pending_sessions_main_loop_() {
void AsyncEventSource::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
uint32_t reconnect) {
for (auto *ses : this->sessions_) {
if (ses->is_connected()) {
if (ses->fd_.load() != 0) { // Skip dead sessions
ses->try_send_nodefer(message, message_len, event, id, reconnect);
}
}
@@ -1228,7 +830,7 @@ void AsyncEventSource::deferrable_send_state(void *source, bool detail_all, mess
if (this->empty())
return;
for (auto *ses : this->sessions_) {
if (ses->is_connected()) {
if (ses->fd_.load() != 0) { // Skip dead sessions
ses->deferrable_send_state(source, detail_all, message_generator);
}
}
@@ -1239,10 +841,26 @@ AsyncEventSourceResponse::AsyncEventSourceResponse(const AsyncWebServerRequest *
esphome::web_server::WebServer *ws)
: server_(server), web_server_(ws), entities_iterator_(ws, server) {
// Httpd task only. start_session_main_loop_() sends the greeting and starts the iterator.
this->begin(request, SSE_STATUS, SSE_CONTENT_TYPE, SSE_HEADERS, SSE_FIRST_CHUNK);
httpd_req_t *req = *request;
httpd_resp_set_status(req, HTTPD_200);
httpd_resp_set_type(req, "text/event-stream");
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
httpd_resp_set_hdr(req, "Connection", "keep-alive");
DefaultHeaders::Instance().apply_(req);
httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
req->sess_ctx = this;
req->free_ctx = AsyncEventSourceResponse::destroy;
this->hd_ = req->handle;
this->fd_.store(httpd_req_to_sockfd(req));
// Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
}
static_assert(stream_head_iov_count(std::size(SSE_HEADERS) + WEB_SERVER_DEFAULT_HEADERS_COUNT) <= STREAM_HEAD_MAX_IOV,
"the event stream head must go out in one write");
// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
void AsyncEventSourceResponse::start_session_main_loop_() {
@@ -1253,7 +871,7 @@ void AsyncEventSourceResponse::start_session_main_loop_() {
auto message = ws->get_config_json();
if (!this->try_send_nodefer(message.c_str(), message.size(), "ping", millis(), 30000)) {
ESP_LOGW(TAG, "Config not sent to fd %d", this->fd_.load());
this->close();
this->request_close_();
return;
}
@@ -1280,6 +898,16 @@ void AsyncEventSourceResponse::start_session_main_loop_() {
}
// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
void AsyncEventSourceResponse::destroy(void *ptr) {
auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
// Mark as dead - will be cleaned up in the main loop
// Note: We don't delete or remove from set here to avoid race conditions
// httpd will call our custom close_fn (safe_close_with_shutdown) which handles
// shutdown() before close() to prevent lwIP race conditions
}
// helper for allowing only unique entries in the queue
void AsyncEventSourceResponse::deq_push_back_with_dedup_(void *source, message_generator_t *message_generator) {
DeferredEvent item(source, message_generator);
@@ -1294,13 +922,13 @@ void AsyncEventSourceResponse::deq_push_back_with_dedup_(void *source, message_g
}
void AsyncEventSourceResponse::process_deferred_queue_() {
if (this->is_closing()) {
if (this->close_requested_) {
return;
}
while (!deferred_queue_.empty()) {
DeferredEvent &de = deferred_queue_.front();
if (this->send_json_(de.source_, de.message_generator_)) {
if (this->is_closing() || deferred_queue_.empty()) {
if (this->close_requested_ || deferred_queue_.empty()) {
return;
}
// O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
@@ -1311,26 +939,145 @@ void AsyncEventSourceResponse::process_deferred_queue_() {
}
}
void AsyncEventSourceResponse::release_buffers_() {
std::vector<DeferredEvent>().swap(this->deferred_queue_);
this->tail_.reset();
this->tail_cap_ = 0;
this->tail_len_ = 0;
this->tail_sent_ = 0;
void AsyncEventSourceResponse::request_close_() {
if (!this->close_requested_) {
this->close_requested_ = true;
this->deferred_queue_.clear();
this->tail_.reset();
this->tail_cap_ = 0;
this->tail_len_ = 0;
this->tail_sent_ = 0;
this->next_close_attempt_ms_ = App.get_loop_component_start_time();
}
this->process_close_();
}
void AsyncEventSourceResponse::process_close_() {
if (!this->close_requested_ || this->close_work_queued_.load(std::memory_order_acquire)) {
return;
}
const int fd = this->fd_.load();
if (fd == 0) {
return;
}
const uint32_t now = App.get_loop_component_start_time();
if (static_cast<int32_t>(now - this->next_close_attempt_ms_) < 0) {
return;
}
// Queue an identity-checked shutdown on the HTTPD task. The public
// httpd_sess_trigger_close() queues only a reusable fd/session slot and can
// therefore close a new client if the original peer disconnects meanwhile.
this->close_work_queued_.store(true, std::memory_order_release);
const esp_err_t err = httpd_queue_work(this->hd_, &AsyncEventSourceResponse::close_session_work, this);
this->next_close_attempt_ms_ = now + (err == ESP_OK ? CLOSE_CONFIRM_INTERVAL_MS : CLOSE_RETRY_INTERVAL_MS);
if (err == ESP_OK) {
return;
}
this->close_work_queued_.store(false, std::memory_order_release);
if (!this->close_retry_warning_logged_) {
ESP_LOGW(TAG, "Failed to queue EventSource close (%s); retrying", esp_err_to_name(err));
this->close_retry_warning_logged_ = true;
}
}
void AsyncEventSourceResponse::refresh_lru_() {
// httpd only advances a session's LRU counter when a request arrives, and an event stream receives one
// request ever, so the purge that frees a socket for a new client would evict the live streams first.
// The HTTPD task owns the session table, so the refresh runs there.
// A stalled stream is the socket the purge should take, and a zeroed fd has no session left to refresh.
if (this->send_failure_started_ms_ != 0 || this->fd_.load() == 0)
return;
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_lru_refresh_ms_ < LRU_REFRESH_INTERVAL_MS ||
this->lru_work_queued_.load(std::memory_order_acquire)) {
return;
}
this->last_lru_refresh_ms_ = now; // a full queue also waits for the next interval
this->lru_work_queued_.store(true, std::memory_order_release);
if (httpd_queue_work(this->hd_, &AsyncEventSourceResponse::refresh_lru_work, this) != ESP_OK) {
this->lru_work_queued_.store(false, std::memory_order_release);
}
}
void AsyncEventSourceResponse::refresh_lru_work(void *arg) {
auto *response = static_cast<AsyncEventSourceResponse *>(arg);
const int fd = response->fd_.load();
if (response->owns_session_(fd)) {
httpd_sess_update_lru_counter(response->hd_, fd);
}
// Release self only after the HTTPD-task callback has finished every access.
response->lru_work_queued_.store(false, std::memory_order_release);
}
void AsyncEventSourceResponse::close_session_work(void *arg) {
auto *response = static_cast<AsyncEventSourceResponse *>(arg);
const int fd = response->fd_.load();
if (response->owns_session_(fd)) {
// The HTTPD task remains the session owner. Shutting the socket down makes
// its next select/recv path delete the session and invoke destroy().
shutdown(fd, SHUT_RDWR);
}
// Release self only after the HTTPD-task callback has finished every access.
response->close_work_queued_.store(false, std::memory_order_release);
}
ssize_t AsyncEventSourceResponse::send_(struct iovec *iov, int iovcnt) {
// httpd frees a session before closing its socket, so the fd may already be a new client's.
// Treated as would-block; the stall timer ends a session that never becomes ours again.
const int fd = this->fd_.load();
if (!this->owns_session_(fd)) {
return 0;
}
struct msghdr msg{};
msg.msg_iov = iov;
msg.msg_iovlen = iovcnt;
const ssize_t sent = sendmsg(fd, &msg, MSG_DONTWAIT);
if (sent >= 0) {
return sent;
}
const int err = errno;
if (err == EAGAIN || err == EWOULDBLOCK) {
return 0;
}
ESP_LOGD(TAG, "send error: errno %d", err);
this->request_close_();
return -1;
}
void AsyncEventSourceResponse::drain_tail_() {
if (this->sending_ || this->is_closing() || this->tail_len_ == 0) {
if (this->sending_ || this->close_requested_ || this->tail_len_ == 0) {
return;
}
SendGuard guard{*this};
const size_t remaining = this->tail_len_ - this->tail_sent_;
const ssize_t sent = this->write(this->tail_.get() + this->tail_sent_, remaining);
if (sent <= 0) {
return; // write() owns the stall clock and the close
struct iovec iov = {this->tail_.get() + this->tail_sent_, remaining};
const ssize_t sent = this->send_(&iov, 1);
if (sent < 0) {
return;
}
this->no_memory_logged_ = false;
if (sent == 0) {
// Socket buffer full, try again later
// NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_().
// The IDF path is intentionally time-based and closes through HTTPD to preserve session ownership.
const uint32_t now = App.get_loop_component_start_time();
if (this->send_failure_started_ms_ == 0) {
this->send_failure_started_ms_ = now != 0 ? now : 1; // Reserve zero for no stall.
}
if (static_cast<int32_t>(now - (this->send_failure_started_ms_ + SEND_STALL_TIMEOUT_MS)) >= 0) {
ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu32 " ms without send progress",
now - this->send_failure_started_ms_);
this->request_close_();
}
return;
}
this->send_failure_started_ms_ = 0;
this->tail_sent_ += sent;
if (this->tail_sent_ < this->tail_len_) {
ESP_LOGV(TAG, "Partial send: %zd/%zu bytes (total: %u/%u)", sent, remaining, this->tail_sent_, this->tail_len_);
@@ -1365,7 +1112,7 @@ bool AsyncEventSourceResponse::stash_chunk_(const char *prefix, size_t prefix_le
if (sent != 0) {
// Part of the chunk is on the wire, so the stream is broken and the client has to go
ESP_LOGW(TAG, "Cannot buffer a %zu byte chunk, closing", total);
this->close();
this->request_close_();
} else {
this->tail_alloc_failed_(total); // nothing on the wire, the caller retries on the stall clock
}
@@ -1388,16 +1135,14 @@ bool AsyncEventSourceResponse::stash_chunk_(const char *prefix, size_t prefix_le
}
void AsyncEventSourceResponse::loop() {
AsyncStreamResponse::loop();
if (this->is_closing()) {
if (this->tail_cap_ != 0 || this->deferred_queue_.capacity() != 0) {
this->release_buffers_();
}
if (this->close_requested_) {
this->process_close_();
return;
}
this->refresh_lru_();
drain_tail_();
process_deferred_queue_();
if (this->is_closing())
if (this->close_requested_)
return;
// One step per loop; refusals retry next pass
this->entities_iterator_.try_advance(1);
@@ -1480,8 +1225,7 @@ bool AsyncEventSourceResponse::send_json_(void *source, message_generator_t *gen
ESP_LOGW(TAG, "State event does not fit %zu bytes, dropped", size);
this->tail_.reset();
this->tail_cap_ = 0;
this->stall_.clear();
this->no_memory_logged_ = false;
this->send_failure_started_ms_ = 0;
return true;
}
}
@@ -1489,29 +1233,25 @@ bool AsyncEventSourceResponse::send_json_(void *source, message_generator_t *gen
}
void AsyncEventSourceResponse::tail_alloc_failed_(size_t cap) {
// Same stall clock as a socket that stops draining, so a session cannot retry forever. A refused write may
// already have started it, so the warning keeps its own flag.
if (!this->no_memory_logged_) {
this->no_memory_logged_ = true;
ESP_LOGW(TAG, "No memory for a %zu byte chunk", cap);
}
// Same stall clock as a socket that stops draining, so a session cannot retry forever
const uint32_t now = App.get_loop_component_start_time();
if (!this->stall_.is_running()) {
this->stall_.start(now);
if (this->send_failure_started_ms_ == 0) {
this->send_failure_started_ms_ = now != 0 ? now : 1; // Reserve zero for no stall.
ESP_LOGW(TAG, "No memory for a %zu byte chunk", cap);
return;
}
if (this->stall_.is_expired(now, SEND_STALL_TIMEOUT_MS)) {
ESP_LOGW(TAG, "Closing EventSource after %" PRIu32 " ms without memory", this->stall_.elapsed(now));
this->close();
if (static_cast<int32_t>(now - (this->send_failure_started_ms_ + SEND_STALL_TIMEOUT_MS)) >= 0) {
ESP_LOGW(TAG, "Closing EventSource after %" PRIu32 " ms without memory", now - this->send_failure_started_ms_);
this->request_close_();
}
}
bool AsyncEventSourceResponse::ready_to_send_() {
if (this->sending_ || !this->is_connected() || this->is_closing()) {
if (this->sending_ || this->fd_.load() == 0 || this->close_requested_) {
return false;
}
drain_tail_();
return !this->is_closing() && this->tail_len_ == 0;
return !this->close_requested_ && this->tail_len_ == 0;
}
bool AsyncEventSourceResponse::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
@@ -1561,14 +1301,12 @@ bool AsyncEventSourceResponse::try_send_nodefer(const char *message, size_t mess
g.iov[0] = {prefix, prefix_len};
// A message with more lines than the list holds skips straight to the tail
const ssize_t sent = g.fits ? this->write(g.iov, g.iovcnt) : 0;
const ssize_t sent = g.fits ? this->send_(g.iov, g.iovcnt) : 0;
if (sent < 0) {
return false;
}
if (sent > 0) {
this->no_memory_logged_ = false;
}
if (static_cast<size_t>(sent) == g.total) {
this->send_failure_started_ms_ = 0; // progress, whichever stall clock was running
return true;
}
// The caller's buffers do not outlive this call, so keep the chunk and continue from loop()
@@ -1585,7 +1323,7 @@ void AsyncEventSourceResponse::deferrable_send_state(void *source, bool detail_a
drain_tail_();
process_deferred_queue_();
if (this->is_closing()) {
if (this->close_requested_) {
return;
}
@@ -1595,7 +1333,7 @@ void AsyncEventSourceResponse::deferrable_send_state(void *source, bool detail_a
deq_push_back_with_dedup_(source, message_generator);
} else {
// A send error closes the session and clears the queue; nothing is queued after that
if (!this->send_json_(source, message_generator) && !this->is_closing()) {
if (!this->send_json_(source, message_generator) && !this->close_requested_) {
deq_push_back_with_dedup_(source, message_generator);
}
}
@@ -15,8 +15,6 @@
#include <utility>
#include <vector>
#include "stream_head.h"
#ifdef USE_WEBSERVER
#include "esphome/components/json/json_util.h"
#include "esphome/components/web_server/list_entities.h"
@@ -193,7 +191,6 @@ class AsyncWebServerRequest {
void onDisconnect(std::function<void()> fn) { this->on_disconnect_ = std::move(fn); }
#endif
/// sess_ctx is reserved for AsyncStreamResponse: the server's close_fn treats any session context as one.
operator httpd_req_t *() const { return this->req_; }
optional<std::string> get_header(const char *name) const;
/// Copy a header value into buf without heap allocation.
@@ -232,13 +229,6 @@ class AsyncWebServer {
void begin();
void end();
#ifdef USE_WEBSERVER_SSL
/// PEM certificate and key, not copied; nullptr for plain HTTP. Takes effect at the next begin().
void set_ssl_credentials(const char *certificate, const char *private_key) {
this->ssl_certificate_ = certificate;
this->ssl_private_key_ = private_key;
}
#endif
// NOLINTNEXTLINE(readability-identifier-naming)
AsyncWebHandler &addHandler(AsyncWebHandler *handler) {
@@ -250,17 +240,7 @@ class AsyncWebServer {
protected:
uint16_t port_{};
#ifdef USE_WEBSERVER_SSL
uint16_t running_port_{}; // port of the running listener, 0 once httpd frees it
#endif
httpd_handle_t server_{};
#ifdef USE_WEBSERVER_SSL
const char *ssl_certificate_{nullptr};
const char *ssl_private_key_{nullptr};
Mutex close_lock_; // held by close_fn while closing, by shutdown_clients_() and by context_free()
void shutdown_clients_();
static void context_free(void *ctx);
#endif
static esp_err_t request_handler(httpd_req_t *r);
static esp_err_t request_post_handler(httpd_req_t *r);
esp_err_t request_handler_(AsyncWebServerRequest *request) const;
@@ -289,82 +269,6 @@ class AsyncWebHandler {
virtual bool isRequestHandlerTrivial() const { return true; }
};
/// A response that keeps its connection open and is written from the main loop, such as an event stream or
/// an audio stream. Use it directly or derive from it. Call loop() and delete the object only through the type
/// it was created as: subclasses hide loop() instead of overriding it, and the destructor is not virtual.
///
/// Lifecycle:
/// 1. Httpd task, inside handleRequest(): create it and call begin(), then hand the pointer to the main loop.
/// 2. Main loop: once is_attached() is true, write() may go through. Call loop() on every pass.
/// 3. Main loop: delete it once safe_to_delete() is true. httpd owns the socket throughout.
class AsyncStreamResponse {
public:
/// Httpd task, once. Sends the status line (for example HTTPD_200), Content-Type, headers, the default headers
/// and body (a C string or null, sent as is), then makes this object the session context. A chunked response
/// passes {"Transfer-Encoding", "chunked"} as its first header and frames each chunk itself. On an HTTPS server
/// it answers 501 instead and the stream never attaches.
void begin(const AsyncWebServerRequest *request, const char *status, const char *content_type,
std::span<const HttpHeader> headers, const char *body = nullptr);
/// Main loop. Non-blocking gather write. Returns the bytes accepted, which may be fewer than offered: the caller
/// keeps the rest and continues from there. 0 means the socket is full or not ours yet; -1 means the stream failed
/// and is closing. Refused writes for SEND_STALL_TIMEOUT_MS in a row also close it.
ssize_t write(struct iovec *iov, int iovcnt);
ssize_t write(const void *data, size_t len);
/// Main loop. Shuts the connection down through httpd; safe to call more than once.
void close();
/// Main loop, every pass. Keeps the session fresh in httpd's LRU and retries a pending close.
void loop();
/// Httpd task, from the server's close_fn: no write() reaches the socket after this returns.
static void socket_closing(httpd_handle_t hd, int fd);
/// httpd holds this response as the session context; begin() has sent the whole head by then.
bool is_attached() const { return this->owns_session_(this->fd_.load()); }
/// The client is still connected; httpd has not freed the session.
bool is_connected() const { return this->fd_.load() != 0; }
bool is_closing() const { return this->loop_flags_.close_requested; }
/// The session is gone and no queued httpd work still references this object.
bool safe_to_delete() const {
return this->fd_.load() == 0 && !this->close_work_queued_.load(std::memory_order_acquire) &&
!this->lru_work_queued_.load(std::memory_order_acquire);
}
static constexpr uint32_t SEND_STALL_TIMEOUT_MS = 20000;
protected:
void process_close_();
static void close_session_work(void *arg);
void refresh_lru_();
static void refresh_lru_work(void *arg);
// httpd closes the socket before it clears the session, so this can still match a closed fd; write() also checks
// socket_closed_
bool owns_session_(int fd) const { return fd != 0 && httpd_sess_get_ctx(this->hd_, fd) == this; }
static void destroy(void *p);
httpd_handle_t hd_{};
std::atomic<int> fd_{};
// Runs while sends make no progress; a running clock keeps its start time
StallClock stall_;
uint32_t next_close_attempt_ms_{0};
uint32_t last_lru_refresh_ms_{0};
// Set on the main loop before queueing close work, cleared by the HTTPD-task callback when done.
std::atomic<bool> close_work_queued_{false};
std::atomic<bool> lru_work_queued_{false};
// Guarded by the stream send mutex
bool socket_closed_{false};
// Main-loop only; the HTTPD task never reads or writes these flags.
// One byte, so the stream's flags share a word on 32-bit targets
struct LoopFlags {
uint8_t close_requested : 1;
uint8_t close_retry_warning_logged : 1;
uint8_t reserved : 6;
} loop_flags_{};
static constexpr uint32_t CLOSE_RETRY_INTERVAL_MS = 250;
static constexpr uint32_t CLOSE_CONFIRM_INTERVAL_MS = 1000;
static constexpr uint32_t LRU_REFRESH_INTERVAL_MS = 1000;
};
#ifdef USE_WEBSERVER
class AsyncEventSource;
class AsyncEventSourceResponse;
@@ -396,7 +300,7 @@ struct DeferredEvent {
static_assert(sizeof(DeferredEvent) == sizeof(void *) + sizeof(message_generator_t *),
"DeferredEvent should have no padding");
class AsyncEventSourceResponse : public AsyncStreamResponse {
class AsyncEventSourceResponse {
friend class AsyncEventSource;
public:
@@ -419,7 +323,10 @@ class AsyncEventSourceResponse : public AsyncStreamResponse {
void process_deferred_queue_();
// A new chunk may go out: not re-entered from a log line, session alive, tail empty
bool ready_to_send_();
// Push what is left of the chunk in tail_ to the socket
// Non-blocking gather write. Returns bytes written, 0 on would-block or a socket that is not
// ours, -1 after requesting the close on any other error.
ssize_t send_(struct iovec *iov, int iovcnt);
// Push what is left of the chunk in tail_ to the socket; owns the stall timer.
void drain_tail_();
// Grow tail_ to hold len bytes, kept at its high-water mark. False on OOM.
bool reserve_tail_(size_t len);
@@ -439,8 +346,9 @@ class AsyncEventSourceResponse : public AsyncStreamResponse {
// unused for TAIL.
JsonPrepareResult __attribute__((noinline)) prepare_json_(void *source, message_generator_t *generator, char *buffer,
size_t *size_out);
// Warn once per stall, and close the session once the stall timeout passes with no memory for the tail
// Warn once, and close the session once the stall timeout passes with no memory for the tail
void tail_alloc_failed_(size_t cap);
void request_close_();
// A log line emitted inside a send re-enters try_send_nodefer on this session; refuse it
struct SendGuard {
@@ -448,22 +356,42 @@ class AsyncEventSourceResponse : public AsyncStreamResponse {
explicit SendGuard(AsyncEventSourceResponse &owner) : owner(owner) { owner.sending_ = true; }
~SendGuard() { this->owner.sending_ = false; }
};
// Frees the tail and the queue's storage once the session is closing
void release_buffers_();
void process_close_();
static void close_session_work(void *arg);
void refresh_lru_();
static void refresh_lru_work(void *arg);
// httpd frees a session before closing its socket, so the fd may already belong to a new client
bool owns_session_(int fd) const { return fd != 0 && httpd_sess_get_ctx(this->hd_, fd) == this; }
// Deletable only after destroy() zeroed fd_ and no queued HTTPD work still references this object.
bool safe_to_delete_() const {
return this->fd_.load() == 0 && !this->close_work_queued_.load(std::memory_order_acquire) &&
!this->lru_work_queued_.load(std::memory_order_acquire);
}
static void destroy(void *p);
AsyncEventSource *server_;
httpd_handle_t hd_{};
std::atomic<int> fd_{};
std::vector<DeferredEvent> deferred_queue_;
esphome::web_server::WebServer *web_server_;
esphome::web_server::ListEntitiesIterator entities_iterator_;
// One chunk the socket did not take whole, allocated on the first stall; the only heap use
// on the send path
RAMUniquePtr<uint8_t[]> tail_;
uint32_t send_failure_started_ms_{0}; // Zero means no send stall in progress.
uint32_t next_close_attempt_ms_{0};
uint32_t last_lru_refresh_ms_{0};
uint16_t tail_cap_{0};
uint16_t tail_len_{0}; // Zero means nothing pending
uint16_t tail_sent_{0};
// Set on the main loop before queueing close work, cleared by the HTTPD-task callback when done.
std::atomic<bool> close_work_queued_{false};
std::atomic<bool> lru_work_queued_{false};
// Main-loop only; the HTTPD task never reads or writes these flags.
bool close_requested_{false};
bool close_retry_warning_logged_{false};
bool sending_{false};
// The no-memory warning went out during the current stall; cleared on send progress
bool no_memory_logged_{false};
// The longest multi line log message in the tree (a climate dump_config) has 22 lines; a
// longer one goes through the tail
static constexpr size_t MAX_SEND_LINES = 22;
@@ -478,6 +406,10 @@ class AsyncEventSourceResponse : public AsyncStreamResponse {
static constexpr size_t JSON_MAX_SIZE = 5120;
// Most RAM a stalled session keeps: the largest state document plus any accepted framing
static constexpr size_t TAIL_MAX_SIZE = JSON_MAX_SIZE + PREFIX_BUF_SIZE + SSE_SUFFIX_LEN;
static constexpr uint32_t SEND_STALL_TIMEOUT_MS = 20000;
static constexpr uint32_t CLOSE_RETRY_INTERVAL_MS = 250;
static constexpr uint32_t CLOSE_CONFIRM_INTERVAL_MS = 1000;
static constexpr uint32_t LRU_REFRESH_INTERVAL_MS = 1000;
};
using AsyncEventSourceClient = AsyncEventSourceResponse;
@@ -524,10 +456,17 @@ class AsyncEventSource : public AsyncWebHandler {
};
#endif // USE_WEBSERVER
struct HttpHeader {
const char *name;
const char *value;
};
class DefaultHeaders {
friend class AsyncWebServerRequest;
friend class AsyncStreamResponse;
friend class AsyncWebServerResponse;
#ifdef USE_WEBSERVER
friend class AsyncEventSourceResponse;
#endif
static_assert(WEB_SERVER_DEFAULT_HEADERS_COUNT <= 8, "AsyncWebServerResponse::replaced_defaults_ holds 8 bits");
public:
+6 -10
View File
@@ -298,14 +298,11 @@ AP_MANUAL_IP_SCHEMA = cv.Schema(
}
)
STA_MANUAL_IP_SCHEMA = cv.All(
AP_MANUAL_IP_SCHEMA.extend(
{
cv.Optional(CONF_DNS1, default="0.0.0.0"): cv.ipv4address,
cv.Optional(CONF_DNS2, default="0.0.0.0"): cv.ipv4address,
}
),
require_ipv4(DOMAIN, CONF_MANUAL_IP),
STA_MANUAL_IP_SCHEMA = AP_MANUAL_IP_SCHEMA.extend(
{
cv.Optional(CONF_DNS1, default="0.0.0.0"): cv.ipv4address,
cv.Optional(CONF_DNS2, default="0.0.0.0"): cv.ipv4address,
}
)
TTLS_PHASE_2 = {
@@ -391,7 +388,6 @@ def wifi_network_ap(value):
if value is None:
value = {}
config = WIFI_NETWORK_AP(value)
require_ipv4(DOMAIN, CONF_AP)(config)
ap_mode = config[CONF_AP_MODE]
if ap_mode == WIFI_AP_MODE_WISP and not config.get(CONF_PASSWORD):
raise cv.Invalid(
@@ -692,7 +688,6 @@ def _lease_cache_schema(value: Any) -> ConfigType:
value = LEASE_CACHE_SCHEMA(value)
if value[CONF_ENABLED]:
cv.only_on_esp32(value)
require_ipv4(DOMAIN, CONF_LEASE_CACHE)(value)
if CONF_STORAGE not in value:
if not preferences.rtc_supported():
raise cv.Invalid(
@@ -785,6 +780,7 @@ CONFIG_SCHEMA = cv.All(
_apply_min_auth_mode_default,
_validate,
_report_provisioning_credentials,
require_ipv4(DOMAIN),
)
+2 -5
View File
@@ -471,9 +471,6 @@ class WiFiPowerSaveListener {
static constexpr uint32_t AP_HANDOVER_TIMEOUT_ID = 0;
static constexpr uint32_t LEASE_RENEW_TIMEOUT_ID = 1;
static constexpr uint32_t AP_DEAUTH_RETRY_TIMEOUT_ID = 2;
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
static constexpr uint32_t IPV6_RECOUNT_TIMEOUT_ID = 3;
#endif
/// This component is responsible for managing the ESP WiFi interface.
class WiFiComponent final : public Component {
@@ -1119,9 +1116,9 @@ class WiFiComponent final : public Component {
// so no happens-before relationship with other memory needs to be established.
std::atomic<uint8_t> roaming_suppression_count_{0};
#endif
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
#if USE_NETWORK_IPV6
uint8_t num_ipv6_addresses_{0};
#endif
#endif /* USE_NETWORK_IPV6 */
bool error_from_callback_{false};
#if defined(USE_ESP32) && !defined(USE_WIFI_MULTI_SSID)
bool scan_driver_filtered_{false};
@@ -45,9 +45,6 @@
#include <esp_netif_net_stack.h> // esp_netif_get_netif_impl()
#include "lwip/netif.h"
#endif
#if !USE_NETWORK_IPV4
#include "lwip/dhcp6.h"
#endif
#ifdef USE_WIFI_LEASE_CACHE
#include <esp_rtc_time.h> // esp_rtc_get_time_us() -- RTC-domain clock for lease age
#include "lwip/dhcp.h"
@@ -656,7 +653,7 @@ bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
void WiFiComponent::clear_sta_session_() {
s_sta_connected = false;
this->got_ipv4_address_ = false;
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
#if USE_NETWORK_IPV6
this->num_ipv6_addresses_ = 0;
#endif
}
@@ -669,11 +666,6 @@ static void disable_dhcp_sntp() {
sntp_servermode_dhcp(false);
}
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
// How long after a driver roam SLAAC gets to settle before the IPv6 addresses are recounted.
static constexpr uint32_t IPV6_ROAM_SETTLE_MS = 5000;
#endif
#ifdef USE_WIFI_LEASE_CACHE
// Minimum lease time that must remain before a cached lease is applied.
static constexpr uint32_t LEASE_APPLY_MARGIN_SECS = 60;
@@ -739,11 +731,6 @@ bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
return false;
}
#if !USE_NETWORK_IPV4
// No IPv4 stack: addresses come from SLAAC, validation rejects manual_ip
(void) manual_ip;
return true;
#else
esp_netif_dhcp_status_t dhcp_status;
esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
if (err != ESP_OK) {
@@ -825,7 +812,6 @@ bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
}
return true;
#endif // USE_NETWORK_IPV4
}
#ifdef USE_WIFI_LEASE_CACHE
@@ -898,7 +884,6 @@ network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() {
if (!this->has_sta())
return {};
network::IPAddresses addresses;
#if USE_NETWORK_IPV4
esp_netif_ip_info_t ip;
esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
if (err != ESP_OK) {
@@ -908,7 +893,6 @@ network::IPAddresses WiFiComponent::wifi_sta_ip_addresses() {
} else {
addresses[0] = network::IPAddress(&ip.ip);
}
#endif
#if USE_NETWORK_IPV6
network::fill_ip6_addresses(s_sta_netif, addresses);
#endif /* USE_NETWORK_IPV6 */
@@ -1122,12 +1106,7 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
if (auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(s_sta_netif)); netif != nullptr) {
if (esp_err_t err = esp_netif_tcpip_exec(
[](void *ctx) -> esp_err_t {
auto *netif = static_cast<struct netif *>(ctx);
netif_create_ip6_linklocal_address(netif, 1);
#if !USE_NETWORK_IPV4
// Without DHCPv4, DNS servers come from RDNSS or stateless DHCPv6; esp_netif never starts the latter
dhcp6_enable_stateless(netif);
#endif
netif_create_ip6_linklocal_address(static_cast<struct netif *>(ctx), 1);
return ESP_OK;
},
netif);
@@ -1152,26 +1131,6 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
bssid_t roam_bssid;
std::copy(it.bssid, it.bssid + 6, roam_bssid.begin());
this->handle_driver_roam_(roam_bssid, it.channel);
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
// GOT_IP6 never counts down; once SLAAC settles drop addresses the new AP did not give back,
// but never below the minimum, so a slow SLAAC does not read as a lost connection
this->set_timeout(IPV6_RECOUNT_TIMEOUT_ID, IPV6_ROAM_SETTLE_MS, [this]() {
if (!s_sta_connected)
return; // A disconnect already cleared the count
esp_ip6_addr_t addresses[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
int count;
{
LwIPLock lock;
count = esp_netif_get_all_ip6(s_sta_netif, addresses);
}
if (count < USE_NETWORK_MIN_IPV6_ADDR_COUNT || count == this->num_ipv6_addresses_)
return;
this->num_ipv6_addresses_ = static_cast<uint8_t>(count);
#ifdef USE_WIFI_IP_STATE_LISTENERS
this->notify_ip_state_listeners_();
#endif
});
#endif
}
#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
// Defer listener notification until state machine reaches STA_CONNECTED
@@ -1234,7 +1193,6 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
(data->event_id == IP_EVENT_ETH_GOT_IP || data->event_id == IP_EVENT_PPP_GOT_IP)) {
this->apply_ap_dns_();
#endif
#if USE_NETWORK_IPV4
} else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
const auto &it = data->data.ip_got_ip;
esp_netif_ip_info_t current_ip{};
@@ -1254,30 +1212,20 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
#ifdef USE_WIFI_IP_STATE_LISTENERS
this->notify_ip_state_listeners_();
#endif
#endif // USE_NETWORK_IPV4
#if USE_NETWORK_IPV6
} else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
const auto &it = data->data.ip_got_ip6;
if (it.esp_netif != s_sta_netif) {
return; // another interface's address (AP netif, or ethernet alongside wifi)
}
if (!s_sta_connected) {
ESP_LOGV(TAG, "Ignoring IPv6 address event before association");
return;
}
ESP_LOGV(TAG, "IPv6 address=" IPV6STR, IPV62STR(it.ip6_info.ip));
#if USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0
// Count addresses, not events (a roam re-fires the link-local). Never count down while associated:
// a roam briefly clears every address, which must not read as a lost connection.
esp_ip6_addr_t addresses[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
uint8_t count;
{
LwIPLock lock;
count = static_cast<uint8_t>(esp_netif_get_all_ip6(s_sta_netif, addresses));
this->num_ipv6_addresses_ = esp_netif_get_all_ip6(s_sta_netif, addresses);
}
this->num_ipv6_addresses_ = std::max(this->num_ipv6_addresses_, count);
#endif
ESP_LOGV(TAG, "IPv6 address=" IPV6STR, IPV62STR(it.ip6_info.ip));
#ifdef USE_WIFI_IP_STATE_LISTENERS
this->notify_ip_state_listeners_();
#endif
@@ -1464,7 +1412,7 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
}
WiFiSTAConnectStatus WiFiComponent::wifi_sta_connect_status_() const {
if (s_sta_connected && (!USE_NETWORK_IPV4 || this->got_ipv4_address_)) {
if (s_sta_connected && this->got_ipv4_address_) {
#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
return WiFiSTAConnectStatus::CONNECTED;
@@ -1754,7 +1702,6 @@ int32_t WiFiComponent::get_wifi_channel() {
return primary;
}
network::IPAddress WiFiComponent::wifi_subnet_mask_() {
#if USE_NETWORK_IPV4
esp_netif_ip_info_t ip;
esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
if (err != ESP_OK) {
@@ -1762,12 +1709,8 @@ network::IPAddress WiFiComponent::wifi_subnet_mask_() {
return {};
}
return network::IPAddress(&ip.netmask);
#else
return {};
#endif
}
network::IPAddress WiFiComponent::wifi_gateway_ip_() {
#if USE_NETWORK_IPV4
esp_netif_ip_info_t ip;
esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
if (err != ESP_OK) {
@@ -1775,9 +1718,6 @@ network::IPAddress WiFiComponent::wifi_gateway_ip_() {
return {};
}
return network::IPAddress(&ip.gw);
#else
return {};
#endif
}
network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
const ip_addr_t *dns_ip = dns_getserver(num);
+1 -6
View File
@@ -4,8 +4,7 @@ import re
from esphome import automation
import esphome.codegen as cg
from esphome.components import network, time
from esphome.components.esp32 import CORE, add_idf_component, add_idf_sdkconfig_option
from esphome.components.noise import LIBSODIUM_VERSION, use_registry_libsodium
from esphome.components.esp32 import CORE, add_idf_sdkconfig_option
import esphome.config_validation as cv
from esphome.const import (
CONF_ADDRESS,
@@ -154,10 +153,6 @@ async def to_code(config):
# be automatically added to the provided list.
cg.add_build_flag(f"-DCONFIG_WIREGUARD_MAX_SRC_IPS={len(allowed_ips) + 1}")
cg.add_library("esphome/wireguard", "0.4.8")
# Same rule as noise: the wireguard library then uses the registry libsodium
# instead of its own copy
if use_registry_libsodium():
add_idf_component(name="esphome/libsodium", ref=LIBSODIUM_VERSION)
await cg.register_component(var, config)
+6
View File
@@ -20,6 +20,7 @@ from esphome.const import (
CONF_WEB_SERVER,
CONF_WIFI,
KEY_CORE,
KEY_FRAMEWORK_VERSION,
KEY_TARGET_FRAMEWORK,
KEY_TARGET_PLATFORM,
NATIVE_TOOLCHAINS,
@@ -1035,6 +1036,11 @@ class EsphomeCore:
def target_framework(self):
return self.data[KEY_CORE][KEY_TARGET_FRAMEWORK]
@property
def framework_version(self) -> Version:
"""The version of the target platform's framework, set by the platform component."""
return self.data[KEY_CORE][KEY_FRAMEWORK_VERSION]
@property
def using_arduino(self):
return self.target_framework == "arduino"
-19
View File
@@ -33,9 +33,6 @@
#ifdef USE_STATUS_LED
#include "esphome/components/status_led/status_led.h"
#endif
#ifdef USE_ESP32_TASK_WDT
#include "esp_task_wdt.h"
#endif
namespace esphome {
@@ -238,27 +235,11 @@ void Application::process_dump_config_() {
this->dump_config_at_++;
}
#if !defined(USE_ESP32) || defined(USE_ESP32_TASK_WDT) || defined(USE_STATUS_LED)
void Application::feed_wdt() {
// Cold entry: callers without a millis() timestamp in hand. Fetches the
// time and defers to the hot path.
this->feed_wdt_with_time(MillisInternal::get());
}
#endif
void Application::feed_wdt_if_watched() {
#ifdef USE_ESP32_TASK_WDT
if (esp_task_wdt_status(nullptr) != ESP_OK)
return;
#elif defined(USE_ESP32) && defined(USE_STATUS_LED)
// No watchdog, but the loop task keeps the status LED blinking through a long blocking call
if (xTaskGetCurrentTaskHandle() != esphome_main_task_handle)
return;
#elif defined(USE_ESP32)
return;
#endif
this->feed_wdt();
}
void HOT Application::feed_wdt_slow_(uint32_t time) {
// Callers (both feed_wdt() and feed_wdt_with_time()) have already
+5 -18
View File
@@ -208,8 +208,8 @@ class Application {
* Each component can request a high frequency loop execution by using the HighFrequencyLoopRequester
* helper in helpers.h
*
* Sleep per wake is capped at 2 * WDT_FEED_INTERVAL_MS (except host, ESP8266, and ESP32
* with watchdog_timeout: 0s); raise the platform watchdog timeout to sleep longer.
* Sleep per wake is capped at 2 * WDT_FEED_INTERVAL_MS (except host and ESP8266);
* raise the platform watchdog timeout to sleep longer.
*
* @param loop_interval The interval in milliseconds to run the core loop at. Defaults to 16 milliseconds.
*/
@@ -239,7 +239,6 @@ class Application {
// https://github.com/libretiny-eu/framework-beken-bdk/blob/44800e7451ea30fbcbd3bb6e905315de59349fee/beken378/driver/wdt/wdt.c#L75-L87
static constexpr uint32_t WDT_FEED_INTERVAL_MS = 2000;
#elif defined(USE_ESP32)
#ifdef USE_ESP32_TASK_WDT
// Auto-scale to 1/5 of the configured ESP32 task WDT timeout so the safety
// margin stays constant when the user raises esp32.watchdog_timeout (default
// 5 s → 1000 ms feed; 10 s → 2000 ms; 60 s → 12000 ms). The esp32 component
@@ -253,10 +252,6 @@ class Application {
static_assert(CONFIG_ESP_TASK_WDT_TIMEOUT_S >= 5,
"CONFIG_ESP_TASK_WDT_TIMEOUT_S must be at least 5s for a safe WDT feed interval");
static constexpr uint32_t WDT_FEED_INTERVAL_MS = (CONFIG_ESP_TASK_WDT_TIMEOUT_S * 1000U) / 5U;
#else
// No task watchdog to feed; the rate limit never fires.
static constexpr uint32_t WDT_FEED_INTERVAL_MS = std::numeric_limits<uint32_t>::max();
#endif
#elif defined(USE_ESP8266)
// ESP8266 needs a tighter feed cadence than the other targets: the soft WDT
// is ~1.6 s and the HW WDT ~6 s, but a single long iteration (mDNS reply,
@@ -272,15 +267,7 @@ class Application {
/// Feed the task watchdog. Cold entry — callers without a millis()
/// timestamp in hand. Out of line to keep call sites tiny.
#if defined(USE_ESP32) && !defined(USE_ESP32_TASK_WDT) && !defined(USE_STATUS_LED)
// watchdog_timeout: 0s leaves no watchdog to feed, and no status LED needs the call
void feed_wdt() {}
#else
void feed_wdt();
#endif
/// Feed from code that may run off the loop task (a long download or image decode): on ESP32 only a task the
/// watchdog watches feeds it. With watchdog_timeout: 0s only the loop task calls through, to run the status LED.
void feed_wdt_if_watched();
#ifdef USE_STATUS_LED
/// Dispatch interval for the status LED update. Deliberately shorter than
@@ -872,9 +859,9 @@ inline void ESPHOME_ALWAYS_INLINE Application::loop() {
// SDK os_timer_arm() accepts at most 0x68D7A3 ms without system_timer_reinit();
// the SDK feeds both watchdogs while the cont task is suspended, so no WDT cap needed.
static constexpr uint32_t MAX_SLEEP_BASE = 0x68D7A3;
#elif defined(USE_HOST) || (defined(USE_ESP32) && !defined(USE_ESP32_TASK_WDT))
// No watchdog to feed (host, or ESP32 with watchdog_timeout: 0s), so nothing caps the sleep; with
// suspend_loop an ESP32 may sleep until a wake notification arrives.
#elif defined(USE_HOST)
// arch_feed_wdt() is a no-op on host and ESPHOME_SUSPEND_LOOP is rejected by
// the config validator, so delay_time is already bounded by loop_interval_.
static constexpr uint32_t MAX_SLEEP_BASE = std::numeric_limits<uint32_t>::max();
#else
static constexpr uint32_t MAX_SLEEP_BASE = WDT_FEED_INTERVAL_MS * 2;
+10 -32
View File
@@ -45,7 +45,9 @@ from esphome.const import (
CONF_TRIGGER_ID,
CONF_URL,
CONF_VERSION,
CONF_WATCHDOG_TIMEOUT,
KEY_CORE,
PLATFORM_ESP32,
PLATFORM_HOST,
PLATFORM_RP2,
PlatformFramework,
@@ -75,7 +77,6 @@ CONF_RELATION = "relation"
CONF_SBOM = "sbom"
CONF_SUPPLIER = "supplier"
CONF_SUSPEND_LOOP = "suspend_loop"
CONF_FRIENDLY_NAME_SEPARATOR = "friendly_name_separator"
# Application::loop_interval_ when loop_interval is not set. Make sure to align with application.h
DEFAULT_LOOP_INTERVAL = TimePeriodMilliseconds(milliseconds=16)
@@ -164,23 +165,6 @@ def validate_hostname(config):
return config
# DeviceInfoResponse sends the friendly name as a short string (encode_short_string_force in api/proto.h)
FRIENDLY_NAME_WITH_SUFFIX_MAX_LEN = 127
def validate_friendly_name_with_suffix(config: ConfigType) -> ConfigType:
if not config[CONF_NAME_ADD_MAC_SUFFIX] or not config[CONF_FRIENDLY_NAME]:
return config
full = f"{config[CONF_FRIENDLY_NAME]}{config[CONF_FRIENDLY_NAME_SEPARATOR]}{_MAC_SUFFIX_PLACEHOLDER}"
if (length := len(full.encode("utf-8"))) > FRIENDLY_NAME_WITH_SUFFIX_MAX_LEN:
raise cv.Invalid(
f"friendly_name with {CONF_FRIENDLY_NAME_SEPARATOR} and the MAC suffix is {length} "
f"bytes; at most {FRIENDLY_NAME_WITH_SUFFIX_MAX_LEN} fit",
path=[CONF_FRIENDLY_NAME],
)
return config
def validate_ids_and_references(config: ConfigType) -> ConfigType:
"""Validate that there are no hash collisions between IDs and that area_id references are valid.
@@ -243,13 +227,13 @@ def validate_loop_interval(config: ConfigType) -> ConfigType:
# max_loop interval is calculated from WDT_FEED_INTERVAL_MS. Make sure to align with application.h
max_loop = 600 # 2 * 300ms default for other platforms
if CORE.is_esp32:
from esphome.components.esp32 import task_wdt_timeout_ms
wdt_ms = task_wdt_timeout_ms()
if wdt_ms == 0:
# Task watchdog disabled: the loop sleep is not capped
return config
max_loop = 2 * wdt_ms // 5
max_loop = (
2
* fv.full_config.get()[PLATFORM_ESP32][
CONF_WATCHDOG_TIMEOUT
].total_milliseconds
// 5
)
elif CORE.is_bk72xx:
max_loop = 4000 # 10000ms / 5 * 2 default value
if config[CONF_LOOP_INTERVAL].total_milliseconds > max_loop:
@@ -464,9 +448,6 @@ CONFIG_SCHEMA = cv.All(
CONF_LIBRARIES, default=[], visibility=cv.Visibility.YAML_ONLY
): cv.ensure_list(cv.string_strict),
cv.Optional(CONF_NAME_ADD_MAC_SUFFIX, default=False): cv.boolean,
cv.Optional(
CONF_FRIENDLY_NAME_SEPARATOR, default=_APP_FRIENDLY_NAME_MAC_SEP
): cv.All(cv.string_no_slash, cv.ByteLength(max=3)),
cv.Optional(CONF_MERGE_WARNINGS, default=True): cv.boolean,
cv.Optional(
CONF_DEBUG_SCHEDULER, default=False, visibility=cv.Visibility.YAML_ONLY
@@ -519,7 +500,6 @@ CONFIG_SCHEMA = cv.All(
}
),
validate_hostname,
validate_friendly_name_with_suffix,
)
@@ -927,9 +907,7 @@ async def to_code(config: ConfigType) -> None:
name_expr, name_len = _emit_app_name(name, _APP_NAME_BUF_VAR, _APP_NAME_MAC_SEP)
friendly_expr, friendly_len = _emit_app_name(
friendly_name,
_APP_FRIENDLY_NAME_BUF_VAR,
config[CONF_FRIENDLY_NAME_SEPARATOR],
friendly_name, _APP_FRIENDLY_NAME_BUF_VAR, _APP_FRIENDLY_NAME_MAC_SEP
)
if name_add_mac_suffix:
cg.add_define("ESPHOME_NAME_ADD_MAC_SUFFIX")
-2
View File
@@ -538,7 +538,6 @@
#define USE_ESP32_MIN_CHIP_REVISION_SET
#define USE_ESP32_RTC_PREFERENCES
#define USE_ESP32_SRAM1_AS_IRAM
#define USE_ESP32_TASK_WDT
#define USE_ESPNOW
#define USE_ESPNOW_MAX_PAYLOAD_SIZE 1470
@@ -635,7 +634,6 @@
#define USE_WEBSERVER_CSS_INCLUDE
#define USE_WEBSERVER_JS_INCLUDE
#define USE_WEBSERVER_PRIVATE_NETWORK_ACCESS
#define USE_WEBSERVER_SSL
#define USE_WEBSERVER_VERSION 3
#define WEB_SERVER_DEFAULT_HEADERS_COUNT 1
#define WEB_SERVER_MAX_OPEN_SOCKETS 7
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies:
esphome/micro-decoder:
version: 0.4.0
esphome/micro-flac:
version: 0.3.1
version: 0.3.0
esphome/micro-mp3:
version: 0.4.0
esphome/micro-opus:
+26 -26
View File
@@ -71,36 +71,36 @@ def patch_file_downloader() -> None:
def patched_init(self, *args: Any, **kwargs: Any) -> None:
max_retries = 5
for attempt in range(max_retries - 1):
for attempt in range(max_retries):
try:
original_init(self, *args, **kwargs)
return
except (PackageException, OSError) as e:
delay = 2 ** (attempt + 1)
_LOGGER.warning(
"Package download failed: %s. "
"Retrying in %d seconds... (attempt %d/%d)",
str(e),
delay,
attempt + 1,
max_retries,
)
# pylint: disable=protected-access,broad-except
try:
if (
hasattr(self, "_http_response")
and self._http_response is not None
):
self._http_response.close()
if hasattr(self, "_http_session"):
self._http_session.close()
except Exception: # noqa: BLE001
pass
# pylint: enable=protected-access,broad-except
time.sleep(delay)
# Final attempt: let any failure propagate unchanged
original_init(self, *args, **kwargs)
if attempt < max_retries - 1:
delay = 2 ** (attempt + 1)
_LOGGER.warning(
"Package download failed: %s. "
"Retrying in %d seconds... (attempt %d/%d)",
str(e),
delay,
attempt + 1,
max_retries,
)
# pylint: disable=protected-access,broad-except
try:
if (
hasattr(self, "_http_response")
and self._http_response is not None
):
self._http_response.close()
if hasattr(self, "_http_session"):
self._http_session.close()
except Exception: # noqa: BLE001
pass
# pylint: enable=protected-access,broad-except
time.sleep(delay)
else:
raise
patched_init._esphome_patched = True # type: ignore[attr-defined] # pylint: disable=protected-access
FileDownloader.__init__ = patched_init
+1 -1
View File
@@ -1,4 +1,4 @@
pylint==4.1.4
pylint==4.1.3
ruff==0.17.5 # .pre-commit-config.yaml rev synced by script/sync_dependency_versions.py
pyupgrade==3.22.0 # .pre-commit-config.yaml rev synced by script/sync_dependency_versions.py
prek==0.5.10 # .github/workflows/ci.yml reads this pin
-1
View File
@@ -107,7 +107,6 @@ ISOLATED_COMPONENTS = {
"tinyusb_keyboard": "Depends on tinyusb which conflicts with usb_host",
"uart_mux": "Depends on tinyusb which conflicts with usb_host",
"usb_cdc_acm": "Depends on tinyusb which conflicts with usb_host",
"web_server_idf": "Its HTTPS variant (test-ssl) can't be merged with web_server or captive_portal, and grouped runs skip variants",
"brizlabs_led_string": "Takes SPI2_HOST for itself, which the shared spi: test bus also uses",
}
@@ -797,73 +797,6 @@ def _gdey029z95_config(**overrides: Any) -> ConfigType:
return config
def test_waveshare_7p5in_hd_b_uses_the_ssd1677_bwr_driver() -> None:
"""The 7.5" HD (B) uses EPaperSSD1677BWR, and its 528 rows are the last of the controller's 680 gates."""
model = MODELS["WAVESHARE-7.5IN-HD-B"]
assert model.class_name == "EPaperSSD1677BWR"
assert model.get_dimensions({}) == (880, 528)
assert model.get_constructor_args({}) == (152,)
assert model.get_init_sequence({}) == (
(0x0C, 0xAE, 0xC7, 0xC3, 0xC0, 0x40),
(0x01, 0xA7, 0x02, 0x01),
(0x11, 0x01),
(0x3C, 0x01),
(0x18, 0x80),
)
@pytest.mark.parametrize(
("dimensions", "error", "error_key"),
[
({"width": 880, "height": 528}, None, None),
(
{"width": 880, "height": 528, "offset_height": 153},
"must not exceed 680 gates",
"height",
),
({"width": 880, "height": 680, "offset_height": 0}, None, None),
(
{"width": 880, "height": 681, "offset_height": 0},
"must not exceed 680 gates",
"height",
),
# offset_height not written: the model's 152 applies, and the error must not point at a missing key
({"width": 880, "height": 529}, "must not exceed 680 gates", "height"),
({"width": 960, "height": 528}, None, None),
({"width": 968, "height": 528}, "must not exceed 960 sources", "width"),
],
)
def test_waveshare_7p5in_hd_b_dimensions_must_fit_the_controller(
set_core_config: SetCoreConfigCallable,
set_component_config: Callable[[str, Any], None],
dimensions: dict[str, int],
error: str | None,
error_key: str | None,
) -> None:
"""The SSD1677 has 960 sources for the width and 680 gates for offset_height plus the height."""
set_core_config(
PlatformFramework.ESP32_IDF,
platform_data={KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32},
)
set_component_config("spi", {"id": "spi_bus", "clk_pin": 18, "mosi_pin": 19})
config = {
"id": "test_display",
"model": "waveshare-7.5in-hd-b",
"dc_pin": 21,
"reset_pin": 22,
"busy_pin": 23,
"dimensions": dimensions,
}
if error is None:
run_schema_validation(config)
else:
with pytest.raises(cv.Invalid, match=error) as exc_info:
run_schema_validation(config)
assert exc_info.value.path[-2:] == ["dimensions", error_key]
def test_gdey029z95_uses_the_good_display_driver() -> None:
"""The GDEY029Z95 uses EPaperGoodDisplay3C with the WeAct init sequence."""
model = MODELS[GDEY029Z95.upper()]
@@ -1,8 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
watchdog_timeout: 10s
@@ -1,7 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
@@ -1,8 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
watchdog_timeout: 0s
-47
View File
@@ -354,28 +354,6 @@ def test_sdkconfig_cpu_frequency_errors(
assert exc_info.value.path == ["framework", "sdkconfig_options"]
@pytest.mark.parametrize("watchdog_timeout", ["0s", "5s", "60s"])
def test_esp32_watchdog_timeout_valid(
set_core_config: SetCoreConfigCallable, watchdog_timeout: str
) -> None:
"""0 disables the task watchdog; otherwise 5 to 60 seconds."""
set_core_config(PlatformFramework.ESP32_IDF)
from esphome.components.esp32 import CONFIG_SCHEMA
CONFIG_SCHEMA({"variant": VARIANT_ESP32, "watchdog_timeout": watchdog_timeout})
@pytest.mark.parametrize("watchdog_timeout", ["1s", "4s", "61s"])
def test_esp32_watchdog_timeout_invalid(
set_core_config: SetCoreConfigCallable, watchdog_timeout: str
) -> None:
set_core_config(PlatformFramework.ESP32_IDF)
from esphome.components.esp32 import CONFIG_SCHEMA
with pytest.raises(cv.Invalid, match="must be 0s"):
CONFIG_SCHEMA({"variant": VARIANT_ESP32, "watchdog_timeout": watchdog_timeout})
@pytest.mark.parametrize(
("config_toolchain", "expected"),
[
@@ -2574,28 +2552,3 @@ def test_require_idf_version_rejects_other_platforms(
set_core_config(PlatformFramework.ESP8266_ARDUINO)
with pytest.raises(cv.Invalid, match="only available on"):
require_idf_version(cv.Version(5, 5, 3))("x")
@pytest.mark.parametrize(
("config_name", "timeout"),
[("watchdog_disabled", None), ("watchdog_default", 5), ("watchdog_custom", 10)],
)
def test_task_watchdog_sdkconfig_and_define(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
config_name: str,
timeout: int | None,
) -> None:
"""watchdog_timeout: 0s turns the task watchdog off; any other value configures it."""
generate_main(component_config_path(f"{config_name}.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
defines = {define.name for define in CORE.defines}
assert sdkconfig["CONFIG_ESP_TASK_WDT_INIT"] is (timeout is not None)
assert ("USE_ESP32_TASK_WDT" in defines) is (timeout is not None)
if timeout is None:
assert "CONFIG_ESP_TASK_WDT_TIMEOUT_S" not in sdkconfig
return
assert sdkconfig["CONFIG_ESP_TASK_WDT_TIMEOUT_S"] == timeout
assert sdkconfig["CONFIG_ESP_TASK_WDT_PANIC"] is True
assert sdkconfig["CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0"] is False
assert sdkconfig["CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1"] is False
@@ -1,13 +0,0 @@
esphome:
name: test
esp32:
board: nodemcu-32s
watchdog_timeout: 0s
wifi:
ssid: test
password: testtest
http_request:
timeout: 10s
@@ -1,13 +0,0 @@
esphome:
name: test
esp32:
board: nodemcu-32s
watchdog_timeout: 0s
wifi:
ssid: test
password: testtest
http_request:
watchdog_timeout: 20s
@@ -33,29 +33,10 @@ def test_esp32_watchdog_timeout(
)
@pytest.mark.parametrize(
"yaml_file",
[
"test_esp8266.yaml",
"test_rp2040.yaml",
# esp32.watchdog_timeout: 0s disables the task watchdog
"test_esp32_platform_disabled.yaml",
],
)
@pytest.mark.parametrize("yaml_file", ["test_esp8266.yaml", "test_rp2040.yaml"])
def test_other_platforms_leave_watchdog_unset(
component_config_path: Callable[[str], Path], yaml_file: str
) -> None:
CORE.config_path = component_config_path(yaml_file)
config = read_config({})
assert CONF_WATCHDOG_TIMEOUT not in config["http_request"]
def test_explicit_watchdog_rejected_when_platform_disabled(
component_config_path: Callable[[str], Path],
capsys: pytest.CaptureFixture[str],
) -> None:
CORE.config_path = component_config_path(
"test_esp32_platform_disabled_explicit.yaml"
)
assert read_config({}) is None
assert "Cannot be set when esp32.watchdog_timeout is 0s" in capsys.readouterr().out
@@ -1,20 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
ethernet:
type: LAN8720
mdc_pin: 23
mdio_pin: 32
clk:
pin: 0
mode: CLK_EXT_IN
phy_addr: 0
@@ -1,24 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
ethernet:
type: LAN8720
mdc_pin: 23
mdio_pin: 32
clk:
pin: 0
mode: CLK_EXT_IN
phy_addr: 0
manual_ip:
static_ip: 192.168.1.10
gateway: 192.168.1.1
subnet: 255.255.255.0
@@ -1,15 +0,0 @@
esphome:
name: test
esp32:
variant: esp32c6
framework:
type: esp-idf
wifi:
ssid: test
password: password1
openthread:
border_router:
tlv: 0e080000000000010000000300001035060004001fffe00208e227ac6a7f24052f0708fdb753eb517cb4d3051062b2442a928d9ea3b947a1618fc4085a030f4f70656e5468726561642d393837330102987304105330d857354330133c05e1fd7ae81a910c0402a0f7f8
@@ -1,18 +0,0 @@
esphome:
name: test
esp32:
variant: esp32c6
framework:
type: esp-idf
ethernet:
type: W5500
clk_pin: 6
mosi_pin: 7
miso_pin: 2
cs_pin: 10
interrupt_pin: 3
openthread:
tlv: 0e080000000000010000000300001035060004001fffe00208e227ac6a7f24052f0708fdb753eb517cb4d3051062b2442a928d9ea3b947a1618fc4085a030f4f70656e5468726561642d393837330102987304105330d857354330133c05e1fd7ae81a910c0402a0f7f8
@@ -1,17 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
wifi:
ssid: "test_ssid"
password: "test_password"
ap:
ssid: "fallback"
@@ -1,16 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
min_ipv6_addr_count: 2
wifi:
ssid: "test_ssid"
password: "test_password"
@@ -1,16 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
wifi:
ssid: "test_ssid"
password: "test_password"
lease_cache: true
@@ -1,19 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
network:
enable_ipv6: true
enable_ipv4: false
wifi:
ssid: "test_ssid"
password: "test_password"
manual_ip:
static_ip: 192.168.1.10
gateway: 192.168.1.1
subnet: 255.255.255.0
+3 -40
View File
@@ -6,7 +6,6 @@ from pathlib import Path
import pytest
from voluptuous import Invalid
from esphome.components.esp32.const import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
from esphome.components.network import (
CONF_ENABLE_IPV4,
_final_validate,
@@ -58,13 +57,9 @@ def test_require_ipv6_and_request_ipv4_off_record_state() -> None:
("ipv6_off_nothing_required.yaml", "true", "false"),
("ipv4_and_ipv6_both_required.yaml", "true", "true"),
("openthread_with_wake_on_lan.yaml", "true", "true"),
("openthread_border_router_wifi.yaml", "true", "true"),
("openthread_with_ethernet.yaml", "true", "true"),
("esp32_arduino_ipv6_no_ipv4_requirement.yaml", "true", "true"),
("host_ipv6_no_ipv4_requirement.yaml", "true", "true"),
("nrf52_network_no_openthread.yaml", "false", "true"),
("wifi_ipv6_only.yaml", "false", "true"),
("ethernet_ipv6_only.yaml", "false", "true"),
],
)
def test_ip_family_defines(
@@ -83,10 +78,7 @@ def test_ip_family_defines(
@pytest.mark.parametrize(
"config_file",
[
"wifi_manual_ip_ipv4_disabled_rejected.yaml",
"wifi_ap_ipv4_disabled_rejected.yaml",
"wifi_lease_cache_ipv4_disabled_rejected.yaml",
"ethernet_manual_ip_ipv4_disabled_rejected.yaml",
"wifi_ipv4_disabled_rejected.yaml",
"wake_on_lan_ipv4_disabled_rejected.yaml",
"udp_ipv4_disabled_rejected.yaml",
"tcp_uart_ipv4_disabled_rejected.yaml",
@@ -110,18 +102,14 @@ def test_require_ipv4_registration_rejects_explicit_disable(
[
("tcp_uart_ipv4_disabled_rejected.yaml", "tcp_uart"),
("uart_tcp_ipv4_disabled_rejected.yaml", "uart_tcp"),
("wifi_manual_ip_ipv4_disabled_rejected.yaml", "wifi: manual_ip"),
("wifi_ap_ipv4_disabled_rejected.yaml", "wifi: ap"),
("wifi_lease_cache_ipv4_disabled_rejected.yaml", "wifi: lease_cache"),
("ethernet_manual_ip_ipv4_disabled_rejected.yaml", "ethernet: manual_ip"),
],
)
def test_ipv4_error_names_the_requirer(
def test_tcp_link_users_named_in_ipv4_error(
component_config_path: Callable[[str], Path],
config_file: str,
component: str,
) -> None:
"""The IPv4 error names the component or option that needs it."""
"""The IPv4 requirement registered by the socket helper names the component."""
CORE.config_path = component_config_path(config_file)
res = load_config({})
assert any(f"IPv4 is required by {component}" in str(err) for err in res.errors)
@@ -205,31 +193,6 @@ def test_no_ip_defines_without_network_component(
assert _define_value("USE_NETWORK_IPV6") is None
@pytest.mark.parametrize(
("config_file", "min_count", "ipv6_dns"),
[
("wifi_ipv6_only.yaml", "1", True),
("ethernet_ipv6_only.yaml", "1", True),
("wifi_ipv6_only_min_2.yaml", "2", True),
("ipv6_only.yaml", "0", False),
("openthread_no_explicit_network.yaml", "1", False),
],
)
def test_ipv6_minimum_and_dns_options(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
config_file: str,
min_count: str,
ipv6_dns: bool,
) -> None:
"""Without IPv4 a link needs an IPv6 address; IPv6 DNS options are only for IPv6-only Wi-Fi and Ethernet."""
generate_main(component_config_path(config_file))
assert _define_value("USE_NETWORK_MIN_IPV6_ADDR_COUNT") == min_count
options = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert ("CONFIG_LWIP_IPV6_DHCP6" in options) is ipv6_dns
assert ("CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS" in options) is ipv6_dns
@pytest.mark.parametrize(
("config_file", "tcp"),
[
@@ -1,38 +0,0 @@
"""Tests for the nextion TFT upload watchdog timeout validation."""
import pytest
from esphome.components.nextion.base_component import CONF_TFT_UPLOAD_WATCHDOG_TIMEOUT
from esphome.components.nextion.display import FINAL_VALIDATE_SCHEMA
import esphome.config_validation as cv
from esphome.const import CONF_WATCHDOG_TIMEOUT, PLATFORM_ESP32, PlatformFramework
from esphome.core import TimePeriod, TimePeriodMilliseconds
from tests.component_tests.types import SetCoreConfigCallable
NEXTION_CONFIG = {CONF_TFT_UPLOAD_WATCHDOG_TIMEOUT: TimePeriodMilliseconds(seconds=30)}
def _esp32(set_core_config: SetCoreConfigCallable, watchdog_seconds: int) -> None:
set_core_config(
PlatformFramework.ESP32_IDF,
full_config={
PLATFORM_ESP32: {
CONF_WATCHDOG_TIMEOUT: TimePeriod(seconds=watchdog_seconds)
}
},
)
def test_tft_upload_watchdog_accepted_when_platform_enabled(
set_core_config: SetCoreConfigCallable,
) -> None:
_esp32(set_core_config, 5)
FINAL_VALIDATE_SCHEMA(NEXTION_CONFIG)
def test_tft_upload_watchdog_rejected_when_platform_disabled(
set_core_config: SetCoreConfigCallable,
) -> None:
_esp32(set_core_config, 0)
with pytest.raises(cv.Invalid, match="Cannot be set when esp32.watchdog_timeout"):
FINAL_VALIDATE_SCHEMA(NEXTION_CONFIG)
@@ -1,22 +0,0 @@
"""Tests for the registry components a sendspin build declares."""
from collections.abc import Callable
from pathlib import Path
from esphome.components.esp32.const import KEY_COMPONENTS, KEY_ESP32, KEY_REF
from esphome.components.noise import LIBSODIUM_VERSION, NOISE_C_VERSION
from esphome.core import CORE
def test_noise_c_and_libsodium_are_pinned(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""The hub loads the noise component, which pins both. sendspin-cpp accepts any
noise-c from 0.1.13 up, so a build without API encryption would otherwise take
whatever version is newest."""
generate_main(component_config_path("device_info_default.yaml"))
components = CORE.data[KEY_ESP32][KEY_COMPONENTS]
assert components["esphome/noise-c"][KEY_REF] == NOISE_C_VERSION
assert components["esphome/libsodium"][KEY_REF] == LIBSODIUM_VERSION
@@ -1,19 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
external_components:
- source:
type: local
path: ../../../components/tuya/components
fake_tuya_transport:
id: my_tuya
switch:
- platform: tuya
tuya_id: my_tuya
name: Fake Switch
switch_datapoint: 1
@@ -1,25 +0,0 @@
"""End-to-end test of the base-class split through the config pipeline."""
from collections.abc import Callable
from pathlib import Path
from esphome.components.tuya import FILTER_SOURCE_FILES
from esphome.core import CORE
def test_non_uart_transport_loads_base_only(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
main_cpp = generate_main(component_config_path("fake_transport.yaml"))
# The fake transport and the tuya switch resolve through the base class
assert "fake_tuya_transport::FakeTuyaTransport" in main_cpp
assert "tuya::TuyaSwitch" in main_cpp
# The UART transport is neither loaded nor instantiated...
assert "uart" not in CORE.loaded_integrations
assert "TuyaUART" not in main_cpp
# ...and its sources are excluded from the build
assert sorted(FILTER_SOURCE_FILES()) == ["tuya_uart.cpp", "tuya_uart.h"]
+1 -6
View File
@@ -3,7 +3,7 @@
import pytest
from esphome import config_validation as cv
from esphome.components.tuya import AUTO_LOAD, CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
from esphome.components.tuya import CONF_FORCE_TIME_SYNC, CONFIG_SCHEMA
from esphome.const import CONF_TIME_ID
@@ -21,8 +21,3 @@ def test_force_time_sync_accepts_time_id() -> None:
def test_force_time_sync_requires_time_id() -> None:
with pytest.raises(cv.Invalid, match="force_time_sync requires time_id"):
CONFIG_SCHEMA({CONF_FORCE_TIME_SYNC: True})
def test_auto_load_requests_uart_for_probe_and_config() -> None:
assert AUTO_LOAD(None) == ["uart"]
assert AUTO_LOAD({"id": "x"}) == ["uart"]
@@ -1,19 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
@@ -1,19 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: arduino
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
@@ -1,20 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
version: 5.4.2
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
@@ -1,21 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
captive_portal:
@@ -1,21 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
prometheus:
@@ -1,21 +0,0 @@
esphome:
name: test
esp32:
board: esp32dev
framework:
type: esp-idf
wifi:
ssid: test
password: testtest
external_components:
- source:
type: local
path: ../../../test_build_components/common/web_server_https/components
components: [https_test]
https_test:
web_server:
@@ -1,124 +0,0 @@
"""Tests for HTTPS on the ESP32 web server."""
from collections.abc import Callable, Generator
from pathlib import Path
import sys
import pytest
from esphome import loader
from esphome.components.esp32 import KEY_BOARD, KEY_VARIANT, VARIANT_ESP32, idf_version
from esphome.components.esp32.const import (
KEY_ESP32,
KEY_EXCLUDE_COMPONENTS,
KEY_SDKCONFIG_OPTIONS,
)
from esphome.components.web_server_base import get_httpd_client_count
from esphome.components.web_server_idf import HTTPS_MAX_CONNECTIONS, consume_ssl_sockets
from esphome.config import read_config
import esphome.config_validation as cv
from esphome.const import PlatformFramework
from esphome.core import CORE
from tests.component_tests.helpers import get_define_value
from tests.component_tests.types import SetCoreConfigCallable
ESP32_PLATFORM_DATA = {KEY_BOARD: "esp32dev", KEY_VARIANT: VARIANT_ESP32}
@pytest.fixture(autouse=True)
def unload_https_test() -> Generator[None]:
"""Drop the test-only external component so later tests start clean."""
yield
loader._COMPONENT_CACHE.pop("https_test", None)
sys.modules.pop("esphome.components.https_test", None)
loader.clear_component_meta_finders()
def test_consume_ssl_sockets_sets_up_https(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""A component with consume_ssl_sockets() in its schema compiles HTTPS in, with the server side of TLS."""
generate_main(component_config_path("https.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert "USE_WEBSERVER_SSL" in {define.name for define in CORE.defines}
assert get_define_value("WEB_SERVER_MAX_OPEN_SOCKETS") == str(HTTPS_MAX_CONNECTIONS)
assert get_httpd_client_count() == HTTPS_MAX_CONNECTIONS
assert sdkconfig["CONFIG_ESP_HTTPS_SERVER_ENABLE"]
assert "esp_https_server" not in CORE.data[KEY_ESP32][KEY_EXCLUDE_COMPONENTS]
assert not sdkconfig.get("CONFIG_MBEDTLS_TLS_CLIENT_ONLY")
def test_no_https_without_consume_ssl_sockets(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""Without consume_ssl_sockets() nothing HTTPS is compiled in."""
generate_main(component_config_path("web_server.yaml"))
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
assert "USE_WEBSERVER_SSL" not in {define.name for define in CORE.defines}
assert "CONFIG_ESP_HTTPS_SERVER_ENABLE" not in sdkconfig
assert "esp_https_server" in CORE.data[KEY_ESP32][KEY_EXCLUDE_COMPONENTS]
def test_https_sockets_reserved_once(set_core_config: SetCoreConfigCallable) -> None:
"""The listener is shared, so a second component using HTTPS reserves no more connections."""
set_core_config(PlatformFramework.ESP32_IDF, platform_data=ESP32_PLATFORM_DATA)
consume_ssl_sockets({})
consume_ssl_sockets({})
assert get_httpd_client_count() == HTTPS_MAX_CONNECTIONS
def test_https_sockets_not_reserved_off_esp32(
set_core_config: SetCoreConfigCallable,
) -> None:
"""HTTPS exists only on ESP32, so other platforms reserve no connections for it."""
set_core_config(PlatformFramework.RP2040_ARDUINO)
consume_ssl_sockets({})
assert get_httpd_client_count() == 0
@pytest.mark.parametrize(
("config_file", "component"),
[
("https_with_web_server.yaml", "web_server"),
("https_with_captive_portal.yaml", "captive_portal"),
("https_with_prometheus.yaml", "prometheus"),
],
)
def test_ssl_rejects_incompatible_components(
component_config_path: Callable[[str], Path],
capsys: pytest.CaptureFixture[str],
config_file: str,
component: str,
) -> None:
"""HTTPS can't be combined with components that need plain HTTP."""
CORE.config_path = component_config_path(config_file)
assert read_config({}) is None
assert f"can't be used together with {component} yet" in capsys.readouterr().out
def test_ssl_needs_idf_5_5(
component_config_path: Callable[[str], Path],
capsys: pytest.CaptureFixture[str],
) -> None:
"""HTTPS is rejected before ESP-IDF 5.5, which added the TLS handshake timeout."""
CORE.config_path = component_config_path("https_idf_5_4.yaml")
assert read_config({}) is None
assert "HTTPS needs ESP-IDF 5.5 or later" in capsys.readouterr().out
def test_ssl_on_arduino_checks_its_idf_version(
component_config_path: Callable[[str], Path],
) -> None:
"""On Arduino the check uses the ESP-IDF the core is built on, not the Arduino version."""
CORE.config_path = component_config_path("https_arduino.yaml")
assert read_config({}) is not None
assert idf_version() >= cv.Version(5, 5, 0)
@@ -1,7 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp32:
variant: esp32
framework:
type: arduino
@@ -1,9 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp32:
variant: esp32
toolchain: platformio
framework:
type: arduino
version: 4.0.0-alpha1
@@ -1,8 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp32:
variant: esp32
toolchain: platformio
framework:
type: arduino
@@ -1,7 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp32:
variant: esp32
framework:
type: esp-idf
@@ -1,8 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp32:
variant: esp32
toolchain: platformio
framework:
type: esp-idf
@@ -1,5 +0,0 @@
packages:
common: !include libsodium_common.yaml
esp8266:
board: d1_mini
@@ -1,18 +0,0 @@
esphome:
name: test
wifi:
ssid: "MySSID1"
password: "password1"
time:
- platform: sntp
id: sntp_time
wireguard:
time_id: sntp_time
address: 172.16.34.100
# NEVER use the following keys for your VPN -- they are now public!
private_key: wPBMxtNYH3mChicrbpsRpZIasIdPq3yZuthn23FbGG8=
peer_public_key: Hs2JfikvYU03/Kv3YoAs1hrUIPPTEkpsZKSPUljE9yc=
peer_endpoint: wg.server.example
@@ -1,64 +0,0 @@
"""Tests for where the wireguard library gets libsodium from.
Another component can bring in the registry libsodium without ESPHome knowing
(sendspin-cpp does, through noise-c). The build then fails if the converted
wireguard library also brings its own copy.
"""
from collections.abc import Callable
from pathlib import Path
import pytest
from esphome.components.esp32.const import KEY_COMPONENTS, KEY_ESP32, KEY_REF
from esphome.components.noise import LIBSODIUM_VERSION
from esphome.core import CORE
_LIBSODIUM = "esphome/libsodium"
def _libraries() -> set[str]:
return {library.name for library in CORE.platformio_libraries.values()}
@pytest.mark.parametrize(
"config",
[
"esp32_idf.yaml",
"esp32_arduino.yaml",
"esp32_idf_platformio.yaml",
"esp32_arduino4_platformio.yaml",
],
)
def test_declares_the_registry_libsodium(
config: str,
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
generate_main(component_config_path(config))
components = CORE.data[KEY_ESP32][KEY_COMPONENTS]
assert components[_LIBSODIUM][KEY_REF] == LIBSODIUM_VERSION
assert "esphome/wireguard" in _libraries()
def test_arduino_3_on_platformio_keeps_the_library_dependency(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
"""arduino-esp32's own libsodium cannot be replaced there, so noise does not use
the registry copy either."""
generate_main(component_config_path("esp32_arduino_platformio.yaml"))
assert _LIBSODIUM not in CORE.data[KEY_ESP32][KEY_COMPONENTS]
assert "esphome/wireguard" in _libraries()
def test_other_platforms_have_no_idf_components(
generate_main: Callable[[str | Path], str],
component_config_path: Callable[[str], Path],
) -> None:
generate_main(component_config_path("esp8266.yaml"))
assert KEY_ESP32 not in CORE.data
assert "esphome/wireguard" in _libraries()
@@ -1,105 +0,0 @@
#include <gtest/gtest.h>
#include <vector>
#include "../common.h"
#include "esphome/components/epaper_spi/epaper_spi_ssd1677_bwr.h"
namespace esphome::epaper_spi::testing {
namespace {
class TestableSSD1677BWR : public EPaperSSD1677BWR {
public:
TestableSSD1677BWR(uint16_t width, uint16_t height, uint16_t offset_height)
: EPaperSSD1677BWR("test", width, height, nullptr, 0, offset_height) {}
void install(spi::SPIDelegate *delegate) {
this->delegate_ = delegate;
this->set_dc_pin(&this->dc);
ASSERT_TRUE(this->init_buffer_(this->buffer_length_));
}
void draw(int x, int y, Color color) { this->draw_pixel_at(x, y, color); }
/// Both planes of one push; returns how many calls it took.
int run_push() {
int calls = 1;
while (!this->transfer_data())
calls++;
return calls;
}
/// A whole update with the frame already drawn, run through loop() as the main loop would.
void run_update() {
this->set_auto_clear(false);
this->state_ = EPaperState::UPDATE;
const uint32_t deadline = millis() + 2000;
while (this->state_ != EPaperState::IDLE) {
ASSERT_LT(millis(), deadline) << "update did not finish";
this->loop();
}
}
RecordingPin dc;
};
using Bytes = std::vector<uint8_t>;
const Color RED(255, 0, 0);
/// The window is the panel's rows at the end of the gates, written from the last gate down, with X in pixels.
/// One row of 16 pixels: white, black, red, then white. The red plane goes first as 1=red, then the black/white
/// plane as 1=white with red pixels sent as 0.
TEST(EPaperSSD1677BWRTransfer, PixelsReachThePanel) {
TestableSSD1677BWR display(16, 2, 3);
RecordingDelegate bus(&display.dc);
display.install(&bus);
display.fill(Color::WHITE);
display.draw(1, 0, Color::BLACK);
display.draw(2, 0, RED);
EXPECT_EQ(display.run_push(), 1);
EXPECT_EQ(bus.commands, (Bytes{0x44, 0x45, 0x4E, 0x4F, 0x26, 0x24}));
EXPECT_EQ(bus.data[0x44], (Bytes{0x00, 0x00, 0x0F, 0x00}));
EXPECT_EQ(bus.data[0x45], (Bytes{0x04, 0x00, 0x03, 0x00}));
EXPECT_EQ(bus.data[0x4E], (Bytes{0x00, 0x00}));
EXPECT_EQ(bus.data[0x4F], (Bytes{0x04, 0x00}));
EXPECT_EQ(bus.data[0x26], (Bytes{0x20, 0x00, 0x00, 0x00}));
EXPECT_EQ(bus.data[0x24], (Bytes{0x9F, 0xFF, 0xFF, 0xFF}));
}
/// Addresses past 255 use both bytes: the 880x528 panel on the last 528 of 680 gates.
TEST(EPaperSSD1677BWRTransfer, WindowOfTheFullSizePanel) {
TestableSSD1677BWR display(880, 528, 152);
RecordingDelegate bus(&display.dc);
display.install(&bus);
display.run_push();
EXPECT_EQ(bus.data[0x44], (Bytes{0x00, 0x00, 0x6F, 0x03}));
EXPECT_EQ(bus.data[0x45], (Bytes{0xA7, 0x02, 0x98, 0x00}));
EXPECT_EQ(bus.data[0x4F], (Bytes{0xA7, 0x02}));
EXPECT_EQ(bus.data[0x26].size(), 110u * 528u);
EXPECT_EQ(bus.data[0x24].size(), 110u * 528u);
}
/// A whole update starts with a software reset, and sends no separate power-on before the refresh (0x22 0xF7).
/// Power off (0x83) and deep sleep follow.
TEST(EPaperSSD1677BWRTransfer, UpdateSequence) {
TestableSSD1677BWR display(16, 1, 0);
RecordingDelegate bus(&display.dc);
display.install(&bus);
display.fill(RED);
display.run_update();
EXPECT_EQ(bus.commands, (Bytes{0x12, 0x44, 0x45, 0x4E, 0x4F, 0x26, 0x24, 0x22, 0x20, 0x22, 0x20, 0x10}));
EXPECT_EQ(bus.data[0x26], (Bytes{0xFF, 0xFF}));
EXPECT_EQ(bus.data[0x24], (Bytes{0x00, 0x00}));
EXPECT_EQ(bus.data[0x22], (Bytes{0xF7, 0x83}));
EXPECT_EQ(bus.data[0x10], (Bytes{0x01}));
}
} // namespace
} // namespace esphome::epaper_spi::testing
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more