Merge branch 'dev' into ci-ban-std-bind

This commit is contained in:
J. Nick Koston
2026-03-22 21:27:45 -10:00
committed by GitHub
206 changed files with 3047 additions and 1112 deletions
+1 -1
View File
@@ -1 +1 @@
44c877ff43765562ac8298902bf2208799643b77facf09c1c0c3c8c4e17187eb
9f5d763f95ff720024f3fdddba2fad3801e2bfe00b7cc2124e6d68c17d3504c6
+1 -1
View File
@@ -339,7 +339,7 @@ jobs:
echo "binary=$BINARY" >> $GITHUB_OUTPUT
- name: Run CodSpeed benchmarks
uses: CodSpeedHQ/action@281164b0f014a4e7badd2c02cecad9b595b70537 # v4
uses: CodSpeedHQ/action@1c8ae4843586d3ba879736b7f6b7b0c990757fab # v4
with:
run: ${{ steps.build.outputs.binary }}
mode: simulation
+2 -2
View File
@@ -58,7 +58,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@b1bff81932f5cdfc8695c7752dcee935dcd061c8 # v4.33.0
uses: github/codeql-action/init@38697555549f1db7851b81482ff19f1fa5c4fedc # v4.34.1
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
@@ -86,6 +86,6 @@ jobs:
exit 1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@b1bff81932f5cdfc8695c7752dcee935dcd061c8 # v4.33.0
uses: github/codeql-action/analyze@38697555549f1db7851b81482ff19f1fa5c4fedc # v4.34.1
with:
category: "/language:${{matrix.language}}"
+1
View File
@@ -458,6 +458,7 @@ esphome/components/socket/* @esphome/core
esphome/components/sonoff_d1/* @anatoly-savchenkov
esphome/components/sound_level/* @kahrendt
esphome/components/spa06_base/* @danielkent-net
esphome/components/spa06_i2c/* @danielkent-net
esphome/components/speaker/* @jesserockz @kahrendt
esphome/components/speaker/media_player/* @kahrendt @synesthesiam
esphome/components/speaker_source/* @kahrendt
+154
View File
@@ -56,6 +56,10 @@ _COMPONENT_PREFIX_LIB = "[lib]"
_COMPONENT_CORE = f"{_COMPONENT_PREFIX_ESPHOME}core"
_COMPONENT_API = f"{_COMPONENT_PREFIX_ESPHOME}api"
# Placement new storage suffix (generated by codegen Pvariable)
_PSTORAGE_SUFFIX = "__pstorage"
# C++ namespace prefixes
_NAMESPACE_ESPHOME = "esphome::"
_NAMESPACE_STD = "std::"
@@ -201,6 +205,9 @@ class MemoryAnalyzer:
self._cswtch_symbols: list[tuple[str, int, str, str]] = []
# Library symbol mapping: symbol_name -> library_name
self._lib_symbol_map: dict[str, str] = {}
# Source file symbol mapping: symbol_name -> component_name
# Used for extern "C" and other symbols without C++ namespace
self._source_symbol_map: dict[str, str] = {}
# Library dir to name mapping: "lib641" -> "espsoftwareserial",
# "espressif__mdns" -> "mdns"
self._lib_hash_to_name: dict[str, str] = {}
@@ -214,6 +221,7 @@ class MemoryAnalyzer:
self._parse_sections()
self._parse_symbols()
self._scan_libraries()
self._scan_source_symbols()
self._categorize_symbols()
self._analyze_cswtch_symbols()
self._analyze_sdk_libraries()
@@ -328,6 +336,13 @@ class MemoryAnalyzer:
# Demangle C++ names if needed
demangled = self._demangle_symbol(symbol_name)
# Check for placement new storage symbols (generated by codegen)
# Format: {component}__{id}__pstorage
if demangled.endswith(_PSTORAGE_SUFFIX) and (
component := self._match_pstorage_component(demangled)
):
return component
# Check for special component classes first (before namespace pattern)
# This handles cases like esphome::ESPHomeOTAComponent which should map to ota
if _NAMESPACE_ESPHOME in demangled:
@@ -363,6 +378,11 @@ class MemoryAnalyzer:
if lib_name := self._lib_symbol_map.get(symbol_name):
return f"{_COMPONENT_PREFIX_LIB}{lib_name}"
# Check source file mapping (catches extern "C" functions in ESPHome sources)
# Must be before heuristic patterns since source attribution is authoritative
if component := self._source_symbol_map.get(symbol_name):
return component
# Check against symbol patterns
for component, patterns in SYMBOL_PATTERNS.items():
if any(pattern in symbol_name for pattern in patterns):
@@ -390,6 +410,24 @@ class MemoryAnalyzer:
# Track uncategorized symbols for analysis
return "other"
def _match_pstorage_component(self, symbol_name: str) -> str | None:
"""Match a __pstorage symbol to its ESPHome component.
Symbol format: {component}__{id}__pstorage
The component namespace is embedded by codegen before the double underscore.
"""
prefix = symbol_name[: -len(_PSTORAGE_SUFFIX)]
# Extract component namespace before the first double underscore
dunder_pos = prefix.find("__")
if dunder_pos == -1:
return None
component_name = prefix[:dunder_pos]
if component_name in get_esphome_components():
return f"{_COMPONENT_PREFIX_ESPHOME}{component_name}"
if component_name in self.external_components:
return f"{_COMPONENT_PREFIX_EXTERNAL}{component_name}"
return None
def _batch_demangle_symbols(self, symbols: list[str]) -> None:
"""Batch demangle C++ symbol names for efficiency."""
if not symbols:
@@ -653,6 +691,7 @@ class MemoryAnalyzer:
return None
symbol_map: dict[str, str] = {}
source_symbol_map: dict[str, str] = {}
current_symbol: str | None = None
section_prefixes = (".text.", ".rodata.", ".data.", ".bss.", ".literal.")
@@ -688,9 +727,18 @@ class MemoryAnalyzer:
if dir_key in source_path:
symbol_map[current_symbol] = lib_name
break
else:
# Map ESPHome source files to components for extern "C"
# and other symbols without C++ namespace
component = self._source_file_to_component(source_path)
if component.startswith(
(_COMPONENT_PREFIX_ESPHOME, _COMPONENT_PREFIX_EXTERNAL)
):
source_symbol_map[current_symbol] = component
current_symbol = None
self._source_symbol_map = source_symbol_map
return symbol_map or None
def _scan_libraries(self) -> None:
@@ -741,6 +789,112 @@ class MemoryAnalyzer:
len(libraries),
)
def _scan_source_symbols(self) -> None:
"""Scan ESPHome source object files to map extern "C" symbols to components.
When no linker map file is available, this uses ``nm`` to scan ``.o`` files
under ``src/esphome/`` and build a symbol-to-component mapping. This catches
``extern "C"`` functions and other symbols that lack C++ namespace prefixes.
Skips scanning if ``_source_symbol_map`` was already populated by
``_parse_map_file()``.
"""
if self._source_symbol_map or not self.nm_path:
return
obj_dir = self._find_object_files_dir()
if obj_dir is None:
return
# Find ESPHome source object files
esphome_src_dir = obj_dir / "src" / "esphome"
if not esphome_src_dir.is_dir():
return
obj_files = sorted(esphome_src_dir.rglob("*.o"))
if not obj_files:
return
# Run nm with --print-file-name to get file:symbol mapping
result = run_tool(
[self.nm_path, "--print-file-name", "-g", "--defined-only"]
+ [str(f) for f in obj_files],
)
if result is None or result.returncode != 0:
_LOGGER.debug("nm scan of source objects failed")
return
self._source_symbol_map = self._parse_nm_source_output(result.stdout, obj_dir)
if self._source_symbol_map:
_LOGGER.info(
"Built source symbol map from nm: %d symbols",
len(self._source_symbol_map),
)
def _parse_nm_source_output(self, output: str, base_dir: Path) -> dict[str, str]:
"""Parse nm output to map non-namespaced symbols to ESPHome components.
Extracts global defined symbols from ESPHome source object files that
don't use C++ namespacing (e.g. ``extern "C"`` functions).
Args:
output: Raw stdout from ``nm --print-file-name -g --defined-only``
or ``nm --print-file-name -S``.
base_dir: Build directory for computing relative paths.
Returns:
Dict mapping symbol names to component names.
"""
source_map: dict[str, str] = {}
for line in output.splitlines():
# Format: /path/to/file.o: addr type name
# or: /path/to/file.o: addr size type name (with -S)
colon_idx = line.rfind(".o:")
if colon_idx == -1:
continue
file_path = line[: colon_idx + 2]
fields = line[colon_idx + 3 :].split()
if len(fields) < 3:
continue
# With -S flag, format is: addr size type name
# Without -S flag: addr type name
# type is a single char; size is hex digits
# Detect by checking if fields[1] is a single uppercase letter (type)
if len(fields[1]) == 1 and fields[1].isalpha():
# addr type name
sym_type = fields[1]
symbol_name = fields[2]
elif len(fields) >= 4:
# addr size type name
sym_type = fields[2]
symbol_name = fields[3]
else:
continue
# Only global defined symbols (uppercase type)
if not sym_type.isupper() or sym_type == "U":
continue
# Skip symbols already in esphome:: namespace
if symbol_name.startswith("_ZN7esphome"):
continue
# Make path relative to base_dir for _source_file_to_component
try:
rel_path = str(Path(file_path).relative_to(base_dir))
except ValueError:
continue
component = self._source_file_to_component(rel_path)
if component.startswith(
(_COMPONENT_PREFIX_ESPHOME, _COMPONENT_PREFIX_EXTERNAL)
):
source_map[symbol_name] = component
return source_map
def _find_object_files_dir(self) -> Path | None:
"""Find the directory containing object files for this build.
+35 -13
View File
@@ -15,6 +15,7 @@ from . import (
_COMPONENT_PREFIX_ESPHOME,
_COMPONENT_PREFIX_EXTERNAL,
_COMPONENT_PREFIX_LIB,
_PSTORAGE_SUFFIX,
RAM_SECTIONS,
MemoryAnalyzer,
)
@@ -23,6 +24,17 @@ if TYPE_CHECKING:
from . import ComponentMemory
def _format_pstorage_name(name: str) -> str:
"""Format a __pstorage symbol as 'storage for {id}'."""
if not name.endswith(_PSTORAGE_SUFFIX):
return name
prefix = name[: -len(_PSTORAGE_SUFFIX)]
# Strip component namespace prefix: {component}__{id} -> {id}
dunder_pos = prefix.find("__")
var_id = prefix[dunder_pos + 2 :] if dunder_pos != -1 else prefix
return f"storage for {var_id}"
class MemoryAnalyzerCLI(MemoryAnalyzer):
"""Memory analyzer with CLI-specific report generation."""
@@ -148,11 +160,14 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
If section is one of the RAM sections (.data or .bss), a label like
" [data]" or " [bss]" is appended. For non-RAM sections or when
section is None, no section label is added.
Placement new storage symbols are formatted as "storage for {id}".
"""
display_name = _format_pstorage_name(demangled)
section_label = ""
if section in RAM_SECTIONS:
section_label = f" [{section[1:]}]" # .data -> [data], .bss -> [bss]
return f"{demangled} ({size:,} B){section_label}"
return f"{display_name} ({size:,} B){section_label}"
def _add_top_symbols(self, lines: list[str]) -> None:
"""Add a section showing the top largest symbols in the binary."""
@@ -175,11 +190,13 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
for i, (_, demangled, size, section, component) in enumerate(top_symbols):
# Format section label
section_label = f"[{section[1:]}]" if section else ""
# Truncate demangled name if too long
# Format storage symbols readably
display_name = _format_pstorage_name(demangled)
# Truncate if too long
demangled_display = (
f"{demangled[:truncate_limit]}..."
if len(demangled) > self.COL_TOP_SYMBOL_NAME
else demangled
f"{display_name[:truncate_limit]}..."
if len(display_name) > self.COL_TOP_SYMBOL_NAME
else display_name
)
lines.append(
f"{i + 1:>2}. {size:>7,} B {section_label:<8} {demangled_display:<{self.COL_TOP_SYMBOL_NAME}} {component}"
@@ -573,15 +590,16 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
lines.append(f"Total size: {comp_mem.flash_total:,} B")
lines.append("")
# Show all symbols above threshold for better visibility
# Show symbols above threshold, always include storage symbols
large_symbols = [
(sym, dem, size, sec)
for sym, dem, size, sec in sorted_symbols
if size > self.SYMBOL_SIZE_THRESHOLD
or dem.endswith(_PSTORAGE_SUFFIX)
]
lines.append(
f"{comp_name} Symbols > {self.SYMBOL_SIZE_THRESHOLD} B ({len(large_symbols)} symbols):"
f"{comp_name} Symbols > {self.SYMBOL_SIZE_THRESHOLD} B & storage ({len(large_symbols)} symbols):"
)
for i, (symbol, demangled, size, section) in enumerate(large_symbols):
lines.append(
@@ -604,7 +622,10 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
# Sort by size descending
sorted_ram_syms = sorted(ram_syms, key=lambda x: x[2], reverse=True)
large_ram_syms = [
s for s in sorted_ram_syms if s[2] > self.RAM_SYMBOL_SIZE_THRESHOLD
s
for s in sorted_ram_syms
if s[2] > self.RAM_SYMBOL_SIZE_THRESHOLD
or s[1].endswith(_PSTORAGE_SUFFIX)
]
lines.append(f"{name} ({mem.ram_total:,} B total RAM):")
@@ -622,13 +643,14 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
for symbol, demangled, size, section in large_ram_syms[:10]:
# Format section label consistently by stripping leading dot
section_label = section.lstrip(".") if section else ""
display_name = _format_pstorage_name(demangled)
# Add ellipsis if name is truncated
demangled_display = (
f"{demangled[:70]}..." if len(demangled) > 70 else demangled
)
lines.append(
f" {size:>6,} B [{section_label}] {demangled_display}"
display_name = (
f"{display_name[:70]}..."
if len(display_name) > 70
else display_name
)
lines.append(f" {size:>6,} B [{section_label}] {display_name}")
if len(large_ram_syms) > 10:
lines.append(f" ... and {len(large_ram_syms) - 10} more")
lines.append("")
-1
View File
@@ -408,7 +408,6 @@ SYMBOL_PATTERNS = {
],
"arduino_core": [
"pinMode",
"resetPins",
"millis",
"micros",
"delay(", # More specific - Arduino delay function with parenthesis
@@ -1,5 +1,6 @@
#pragma once
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
#include "esphome/components/sensor/sensor.h"
+3
View File
@@ -455,6 +455,9 @@ async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_PLAINTEXT")
cg.add_define("USE_API_NOISE")
cg.add_library("esphome/noise-c", "0.1.11")
# Enable optimized memzero/memcmp in libsodium instead of volatile byte loops
cg.add_build_flag("-DHAVE_WEAK_SYMBOLS=1")
cg.add_build_flag("-DHAVE_INLINE_ASM=1")
else:
cg.add_define("USE_API_PLAINTEXT")
+71 -71
View File
@@ -316,7 +316,7 @@ message ListEntitiesBinarySensorResponse {
option (ifdef) = "USE_BINARY_SENSOR";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -334,7 +334,7 @@ message BinarySensorStateResponse {
option (ifdef) = "USE_BINARY_SENSOR";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
// If the binary sensor does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -350,7 +350,7 @@ message ListEntitiesCoverResponse {
option (ifdef) = "USE_COVER";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -383,7 +383,7 @@ message CoverStateResponse {
option (ifdef) = "USE_COVER";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// legacy: state has been removed in 1.13
// clients/servers must still send/accept it until the next protocol change
// Deprecated in API version 1.1
@@ -409,7 +409,7 @@ message CoverCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// legacy: command has been removed in 1.13
// clients/servers must still send/accept it until the next protocol change
@@ -434,7 +434,7 @@ message ListEntitiesFanResponse {
option (ifdef) = "USE_FAN";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -466,7 +466,7 @@ message FanStateResponse {
option (ifdef) = "USE_FAN";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
bool oscillating = 3;
// Deprecated in API version 1.6
@@ -483,7 +483,7 @@ message FanCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_state = 2;
bool state = 3;
// Deprecated in API version 1.6
@@ -522,7 +522,7 @@ message ListEntitiesLightResponse {
option (ifdef) = "USE_LIGHT";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -551,7 +551,7 @@ message LightStateResponse {
option (ifdef) = "USE_LIGHT";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
float brightness = 3;
ColorMode color_mode = 11;
@@ -573,7 +573,7 @@ message LightCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_state = 2;
bool state = 3;
bool has_brightness = 4;
@@ -627,7 +627,7 @@ message ListEntitiesSensorResponse {
option (ifdef) = "USE_SENSOR";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -651,7 +651,7 @@ message SensorStateResponse {
option (ifdef) = "USE_SENSOR";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
float state = 2;
// If the sensor does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -667,7 +667,7 @@ message ListEntitiesSwitchResponse {
option (ifdef) = "USE_SWITCH";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -685,7 +685,7 @@ message SwitchStateResponse {
option (ifdef) = "USE_SWITCH";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -696,7 +696,7 @@ message SwitchCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -709,7 +709,7 @@ message ListEntitiesTextSensorResponse {
option (ifdef) = "USE_TEXT_SENSOR";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -726,7 +726,7 @@ message TextSensorStateResponse {
option (ifdef) = "USE_TEXT_SENSOR";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string state = 2;
// If the text sensor does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -922,7 +922,7 @@ message ListEntitiesServicesResponse {
option (ifdef) = "USE_API_USER_DEFINED_ACTIONS";
string name = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
repeated ListEntitiesServicesArgument args = 3 [(fixed_vector) = true];
SupportsResponseType supports_response = 4;
}
@@ -945,7 +945,7 @@ message ExecuteServiceRequest {
option (no_delay) = true;
option (ifdef) = "USE_API_USER_DEFINED_ACTIONS";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
repeated ExecuteServiceArgument args = 2 [(fixed_vector) = true];
uint32 call_id = 3 [(field_ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES"];
bool return_response = 4 [(field_ifdef) = "USE_API_USER_DEFINED_ACTION_RESPONSES"];
@@ -972,7 +972,7 @@ message ListEntitiesCameraResponse {
option (ifdef) = "USE_CAMERA";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
bool disabled_by_default = 5;
@@ -987,7 +987,7 @@ message CameraImageResponse {
option (source) = SOURCE_SERVER;
option (ifdef) = "USE_CAMERA";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bytes data = 2;
bool done = 3;
uint32 device_id = 4 [(field_ifdef) = "USE_DEVICES"];
@@ -1057,7 +1057,7 @@ message ListEntitiesClimateResponse {
option (ifdef) = "USE_CLIMATE";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1095,7 +1095,7 @@ message ClimateStateResponse {
option (ifdef) = "USE_CLIMATE";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
ClimateMode mode = 2;
float current_temperature = 3;
float target_temperature = 4;
@@ -1121,7 +1121,7 @@ message ClimateCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_mode = 2;
ClimateMode mode = 3;
bool has_target_temperature = 4;
@@ -1168,7 +1168,7 @@ message ListEntitiesWaterHeaterResponse {
option (ifdef) = "USE_WATER_HEATER";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
string icon = 4 [(field_ifdef) = "USE_ENTITY_ICON"];
bool disabled_by_default = 5;
@@ -1189,7 +1189,7 @@ message WaterHeaterStateResponse {
option (ifdef) = "USE_WATER_HEATER";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
float current_temperature = 2;
float target_temperature = 3;
WaterHeaterMode mode = 4;
@@ -1219,7 +1219,7 @@ message WaterHeaterCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// Bitmask of which fields are set (see WaterHeaterCommandHasField)
uint32 has_fields = 2;
WaterHeaterMode mode = 3;
@@ -1244,7 +1244,7 @@ message ListEntitiesNumberResponse {
option (ifdef) = "USE_NUMBER";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1266,7 +1266,7 @@ message NumberStateResponse {
option (ifdef) = "USE_NUMBER";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
float state = 2;
// If the number does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -1280,7 +1280,7 @@ message NumberCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
float state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -1293,7 +1293,7 @@ message ListEntitiesSelectResponse {
option (ifdef) = "USE_SELECT";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1310,7 +1310,7 @@ message SelectStateResponse {
option (ifdef) = "USE_SELECT";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string state = 2;
// If the select does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -1324,7 +1324,7 @@ message SelectCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -1337,7 +1337,7 @@ message ListEntitiesSirenResponse {
option (ifdef) = "USE_SIREN";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1356,7 +1356,7 @@ message SirenStateResponse {
option (ifdef) = "USE_SIREN";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -1367,7 +1367,7 @@ message SirenCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_state = 2;
bool state = 3;
bool has_tone = 4;
@@ -1400,7 +1400,7 @@ message ListEntitiesLockResponse {
option (ifdef) = "USE_LOCK";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1422,7 +1422,7 @@ message LockStateResponse {
option (source) = SOURCE_SERVER;
option (ifdef) = "USE_LOCK";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
LockState state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -1432,7 +1432,7 @@ message LockCommandRequest {
option (ifdef) = "USE_LOCK";
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
LockCommand command = 2;
// Not yet implemented:
@@ -1449,7 +1449,7 @@ message ListEntitiesButtonResponse {
option (ifdef) = "USE_BUTTON";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1466,7 +1466,7 @@ message ButtonCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
uint32 device_id = 2 [(field_ifdef) = "USE_DEVICES"];
}
@@ -1516,7 +1516,7 @@ message ListEntitiesMediaPlayerResponse {
option (ifdef) = "USE_MEDIA_PLAYER";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -1538,7 +1538,7 @@ message MediaPlayerStateResponse {
option (source) = SOURCE_SERVER;
option (ifdef) = "USE_MEDIA_PLAYER";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
MediaPlayerState state = 2;
float volume = 3;
bool muted = 4;
@@ -1551,7 +1551,7 @@ message MediaPlayerCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_command = 2;
MediaPlayerCommand command = 3;
@@ -2104,7 +2104,7 @@ message ListEntitiesAlarmControlPanelResponse {
option (ifdef) = "USE_ALARM_CONTROL_PANEL";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
string icon = 5 [(field_ifdef) = "USE_ENTITY_ICON"];
@@ -2122,7 +2122,7 @@ message AlarmControlPanelStateResponse {
option (source) = SOURCE_SERVER;
option (ifdef) = "USE_ALARM_CONTROL_PANEL";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
AlarmControlPanelState state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -2133,7 +2133,7 @@ message AlarmControlPanelCommandRequest {
option (ifdef) = "USE_ALARM_CONTROL_PANEL";
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
AlarmControlPanelStateCommand command = 2;
string code = 3;
uint32 device_id = 4 [(field_ifdef) = "USE_DEVICES"];
@@ -2151,7 +2151,7 @@ message ListEntitiesTextResponse {
option (ifdef) = "USE_TEXT";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
string icon = 5 [(field_ifdef) = "USE_ENTITY_ICON"];
@@ -2171,7 +2171,7 @@ message TextStateResponse {
option (ifdef) = "USE_TEXT";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string state = 2;
// If the Text does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
@@ -2185,7 +2185,7 @@ message TextCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string state = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -2199,7 +2199,7 @@ message ListEntitiesDateResponse {
option (ifdef) = "USE_DATETIME_DATE";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2215,7 +2215,7 @@ message DateStateResponse {
option (ifdef) = "USE_DATETIME_DATE";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// If the date does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
bool missing_state = 2;
@@ -2231,7 +2231,7 @@ message DateCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
uint32 year = 2;
uint32 month = 3;
uint32 day = 4;
@@ -2246,7 +2246,7 @@ message ListEntitiesTimeResponse {
option (ifdef) = "USE_DATETIME_TIME";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2262,7 +2262,7 @@ message TimeStateResponse {
option (ifdef) = "USE_DATETIME_TIME";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// If the time does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
bool missing_state = 2;
@@ -2278,7 +2278,7 @@ message TimeCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
uint32 hour = 2;
uint32 minute = 3;
uint32 second = 4;
@@ -2293,7 +2293,7 @@ message ListEntitiesEventResponse {
option (ifdef) = "USE_EVENT";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2311,7 +2311,7 @@ message EventResponse {
option (source) = SOURCE_SERVER;
option (ifdef) = "USE_EVENT";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
string event_type = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -2324,7 +2324,7 @@ message ListEntitiesValveResponse {
option (ifdef) = "USE_VALVE";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2351,7 +2351,7 @@ message ValveStateResponse {
option (ifdef) = "USE_VALVE";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
float position = 2;
ValveOperation current_operation = 3;
uint32 device_id = 4 [(field_ifdef) = "USE_DEVICES"];
@@ -2364,7 +2364,7 @@ message ValveCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool has_position = 2;
float position = 3;
bool stop = 4;
@@ -2379,7 +2379,7 @@ message ListEntitiesDateTimeResponse {
option (ifdef) = "USE_DATETIME_DATETIME";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2395,7 +2395,7 @@ message DateTimeStateResponse {
option (ifdef) = "USE_DATETIME_DATETIME";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
// If the datetime does not have a valid state yet.
// Equivalent to `!obj->has_state()` - inverse logic to make state packets smaller
bool missing_state = 2;
@@ -2409,7 +2409,7 @@ message DateTimeCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
fixed32 epoch_seconds = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -2422,7 +2422,7 @@ message ListEntitiesUpdateResponse {
option (ifdef) = "USE_UPDATE";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
reserved 4; // Deprecated: was string unique_id
@@ -2439,7 +2439,7 @@ message UpdateStateResponse {
option (ifdef) = "USE_UPDATE";
option (no_delay) = true;
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
bool missing_state = 2;
bool in_progress = 3;
bool has_progress = 4;
@@ -2463,7 +2463,7 @@ message UpdateCommandRequest {
option (no_delay) = true;
option (base_class) = "CommandProtoMessage";
fixed32 key = 1;
fixed32 key = 1 [(force) = true];
UpdateCommand command = 2;
uint32 device_id = 3 [(field_ifdef) = "USE_DEVICES"];
}
@@ -2505,7 +2505,7 @@ message ListEntitiesInfraredResponse {
option (ifdef) = "USE_INFRARED";
string object_id = 1;
fixed32 key = 2;
fixed32 key = 2 [(force) = true];
string name = 3;
string icon = 4 [(field_ifdef) = "USE_ENTITY_ICON"];
bool disabled_by_default = 5;
@@ -2521,7 +2521,7 @@ message InfraredRFTransmitRawTimingsRequest {
option (ifdef) = "USE_IR_RF";
uint32 device_id = 1 [(field_ifdef) = "USE_DEVICES"];
fixed32 key = 2; // Key identifying the transmitter instance
fixed32 key = 2 [(force) = true]; // Key identifying the transmitter instance
uint32 carrier_frequency = 3; // Carrier frequency in Hz
uint32 repeat_count = 4; // Number of times to transmit (1 = once, 2 = twice, etc.)
repeated sint32 timings = 5 [packed = true, (packed_buffer) = true]; // Raw timings in microseconds (zigzag-encoded): positive = mark (LED/TX on), negative = space (LED/TX off)
@@ -2535,7 +2535,7 @@ message InfraredRFReceiveEvent {
option (no_delay) = true;
uint32 device_id = 1 [(field_ifdef) = "USE_DEVICES"];
fixed32 key = 2; // Key identifying the receiver instance
fixed32 key = 2 [(force) = true]; // Key identifying the receiver instance
repeated sint32 timings = 3 [packed = true, (container_pointer_no_template) = "std::vector<int32_t>"]; // Raw timings in microseconds (zigzag-encoded): alternating mark/space periods
}
+10 -6
View File
@@ -64,7 +64,11 @@ static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS *
// A stalled handshake from a buggy client or network glitch holds a connection
// slot, which can prevent legitimate clients from reconnecting. Also hardens
// against the less likely case of intentional connection slot exhaustion.
static constexpr uint32_t HANDSHAKE_TIMEOUT_MS = 15000;
//
// 60s is intentionally high: on ESP8266 with power_save_mode: LIGHT and weak
// WiFi (-70 dBm+), TCP retransmissions push real-world handshake times to
// 28-30s. See https://github.com/esphome/esphome/issues/14999
static constexpr uint32_t HANDSHAKE_TIMEOUT_MS = 60000;
static constexpr auto ESPHOME_VERSION_REF = StringRef::from_lit(ESPHOME_VERSION);
@@ -230,7 +234,7 @@ void APIConnection::loop() {
this->last_traffic_ = now;
}
// read a packet
this->read_message(buffer.data_len, buffer.type, buffer.data);
this->read_message_(buffer.data_len, buffer.type, buffer.data);
if (this->flags_.remove)
return;
}
@@ -1515,16 +1519,16 @@ void APIConnection::on_serial_proxy_request(const SerialProxyRequest &msg) {
resp.instance = msg.instance;
resp.type = enums::SERIAL_PROXY_REQUEST_TYPE_FLUSH;
switch (proxies[msg.instance]->flush_port()) {
case uart::FlushResult::SUCCESS:
case uart::UARTFlushResult::UART_FLUSH_RESULT_SUCCESS:
resp.status = enums::SERIAL_PROXY_STATUS_OK;
break;
case uart::FlushResult::ASSUMED_SUCCESS:
case uart::UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS:
resp.status = enums::SERIAL_PROXY_STATUS_ASSUMED_SUCCESS;
break;
case uart::FlushResult::TIMEOUT:
case uart::UARTFlushResult::UART_FLUSH_RESULT_TIMEOUT:
resp.status = enums::SERIAL_PROXY_STATUS_TIMEOUT;
break;
case uart::FlushResult::FAILED:
case uart::UARTFlushResult::UART_FLUSH_RESULT_FAILED:
resp.status = enums::SERIAL_PROXY_STATUS_ERROR;
break;
}
+87 -69
View File
@@ -49,11 +49,29 @@ class APIConnection final : public APIServerConnectionBase {
friend class APIServer;
friend class ListEntitiesIterator;
APIConnection(std::unique_ptr<socket::Socket> socket, APIServer *parent);
virtual ~APIConnection();
~APIConnection();
void start();
void loop();
protected:
// read_message_ is defined here (instead of in APIServerConnectionBase) so the
// compiler can devirtualize and inline on_* handler calls within this final class.
void read_message_(uint32_t msg_size, uint32_t msg_type, const uint8_t *msg_data);
// Auth helpers defined here (not in ProtoService) so the compiler can
// devirtualize is_connection_setup()/on_no_setup_connection() calls
// within this final class.
inline bool check_connection_setup_() {
if (!this->is_connection_setup()) {
this->on_no_setup_connection();
return false;
}
return true;
}
inline bool check_authenticated_() { return this->check_connection_setup_(); }
public:
bool send_list_info_done() {
return this->schedule_message_(nullptr, ListEntitiesDoneResponse::MESSAGE_TYPE,
ListEntitiesDoneResponse::ESTIMATED_SIZE);
@@ -63,72 +81,72 @@ class APIConnection final : public APIServerConnectionBase {
#endif
#ifdef USE_COVER
bool send_cover_state(cover::Cover *cover);
void on_cover_command_request(const CoverCommandRequest &msg) override;
void on_cover_command_request(const CoverCommandRequest &msg);
#endif
#ifdef USE_FAN
bool send_fan_state(fan::Fan *fan);
void on_fan_command_request(const FanCommandRequest &msg) override;
void on_fan_command_request(const FanCommandRequest &msg);
#endif
#ifdef USE_LIGHT
bool send_light_state(light::LightState *light);
void on_light_command_request(const LightCommandRequest &msg) override;
void on_light_command_request(const LightCommandRequest &msg);
#endif
#ifdef USE_SENSOR
bool send_sensor_state(sensor::Sensor *sensor);
#endif
#ifdef USE_SWITCH
bool send_switch_state(switch_::Switch *a_switch);
void on_switch_command_request(const SwitchCommandRequest &msg) override;
void on_switch_command_request(const SwitchCommandRequest &msg);
#endif
#ifdef USE_TEXT_SENSOR
bool send_text_sensor_state(text_sensor::TextSensor *text_sensor);
#endif
#ifdef USE_CAMERA
void set_camera_state(std::shared_ptr<camera::CameraImage> image);
void on_camera_image_request(const CameraImageRequest &msg) override;
void on_camera_image_request(const CameraImageRequest &msg);
#endif
#ifdef USE_CLIMATE
bool send_climate_state(climate::Climate *climate);
void on_climate_command_request(const ClimateCommandRequest &msg) override;
void on_climate_command_request(const ClimateCommandRequest &msg);
#endif
#ifdef USE_NUMBER
bool send_number_state(number::Number *number);
void on_number_command_request(const NumberCommandRequest &msg) override;
void on_number_command_request(const NumberCommandRequest &msg);
#endif
#ifdef USE_DATETIME_DATE
bool send_date_state(datetime::DateEntity *date);
void on_date_command_request(const DateCommandRequest &msg) override;
void on_date_command_request(const DateCommandRequest &msg);
#endif
#ifdef USE_DATETIME_TIME
bool send_time_state(datetime::TimeEntity *time);
void on_time_command_request(const TimeCommandRequest &msg) override;
void on_time_command_request(const TimeCommandRequest &msg);
#endif
#ifdef USE_DATETIME_DATETIME
bool send_datetime_state(datetime::DateTimeEntity *datetime);
void on_date_time_command_request(const DateTimeCommandRequest &msg) override;
void on_date_time_command_request(const DateTimeCommandRequest &msg);
#endif
#ifdef USE_TEXT
bool send_text_state(text::Text *text);
void on_text_command_request(const TextCommandRequest &msg) override;
void on_text_command_request(const TextCommandRequest &msg);
#endif
#ifdef USE_SELECT
bool send_select_state(select::Select *select);
void on_select_command_request(const SelectCommandRequest &msg) override;
void on_select_command_request(const SelectCommandRequest &msg);
#endif
#ifdef USE_BUTTON
void on_button_command_request(const ButtonCommandRequest &msg) override;
void on_button_command_request(const ButtonCommandRequest &msg);
#endif
#ifdef USE_LOCK
bool send_lock_state(lock::Lock *a_lock);
void on_lock_command_request(const LockCommandRequest &msg) override;
void on_lock_command_request(const LockCommandRequest &msg);
#endif
#ifdef USE_VALVE
bool send_valve_state(valve::Valve *valve);
void on_valve_command_request(const ValveCommandRequest &msg) override;
void on_valve_command_request(const ValveCommandRequest &msg);
#endif
#ifdef USE_MEDIA_PLAYER
bool send_media_player_state(media_player::MediaPlayer *media_player);
void on_media_player_command_request(const MediaPlayerCommandRequest &msg) override;
void on_media_player_command_request(const MediaPlayerCommandRequest &msg);
#endif
bool try_send_log_message(int level, const char *tag, const char *line, size_t message_len);
#ifdef USE_API_HOMEASSISTANT_SERVICES
@@ -138,23 +156,23 @@ class APIConnection final : public APIServerConnectionBase {
this->send_message(call);
}
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
void on_homeassistant_action_response(const HomeassistantActionResponse &msg) override;
void on_homeassistant_action_response(const HomeassistantActionResponse &msg);
#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
#endif // USE_API_HOMEASSISTANT_SERVICES
#ifdef USE_BLUETOOTH_PROXY
void on_subscribe_bluetooth_le_advertisements_request(const SubscribeBluetoothLEAdvertisementsRequest &msg) override;
void on_unsubscribe_bluetooth_le_advertisements_request() override;
void on_subscribe_bluetooth_le_advertisements_request(const SubscribeBluetoothLEAdvertisementsRequest &msg);
void on_unsubscribe_bluetooth_le_advertisements_request();
void on_bluetooth_device_request(const BluetoothDeviceRequest &msg) override;
void on_bluetooth_gatt_read_request(const BluetoothGATTReadRequest &msg) override;
void on_bluetooth_gatt_write_request(const BluetoothGATTWriteRequest &msg) override;
void on_bluetooth_gatt_read_descriptor_request(const BluetoothGATTReadDescriptorRequest &msg) override;
void on_bluetooth_gatt_write_descriptor_request(const BluetoothGATTWriteDescriptorRequest &msg) override;
void on_bluetooth_gatt_get_services_request(const BluetoothGATTGetServicesRequest &msg) override;
void on_bluetooth_gatt_notify_request(const BluetoothGATTNotifyRequest &msg) override;
void on_subscribe_bluetooth_connections_free_request() override;
void on_bluetooth_scanner_set_mode_request(const BluetoothScannerSetModeRequest &msg) override;
void on_bluetooth_set_connection_params_request(const BluetoothSetConnectionParamsRequest &msg) override;
void on_bluetooth_device_request(const BluetoothDeviceRequest &msg);
void on_bluetooth_gatt_read_request(const BluetoothGATTReadRequest &msg);
void on_bluetooth_gatt_write_request(const BluetoothGATTWriteRequest &msg);
void on_bluetooth_gatt_read_descriptor_request(const BluetoothGATTReadDescriptorRequest &msg);
void on_bluetooth_gatt_write_descriptor_request(const BluetoothGATTWriteDescriptorRequest &msg);
void on_bluetooth_gatt_get_services_request(const BluetoothGATTGetServicesRequest &msg);
void on_bluetooth_gatt_notify_request(const BluetoothGATTNotifyRequest &msg);
void on_subscribe_bluetooth_connections_free_request();
void on_bluetooth_scanner_set_mode_request(const BluetoothScannerSetModeRequest &msg);
void on_bluetooth_set_connection_params_request(const BluetoothSetConnectionParamsRequest &msg);
#endif
#ifdef USE_HOMEASSISTANT_TIME
@@ -165,42 +183,42 @@ class APIConnection final : public APIServerConnectionBase {
#endif
#ifdef USE_VOICE_ASSISTANT
void on_subscribe_voice_assistant_request(const SubscribeVoiceAssistantRequest &msg) override;
void on_voice_assistant_response(const VoiceAssistantResponse &msg) override;
void on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg) override;
void on_voice_assistant_audio(const VoiceAssistantAudio &msg) override;
void on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &msg) override;
void on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &msg) override;
void on_voice_assistant_configuration_request(const VoiceAssistantConfigurationRequest &msg) override;
void on_voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &msg) override;
void on_subscribe_voice_assistant_request(const SubscribeVoiceAssistantRequest &msg);
void on_voice_assistant_response(const VoiceAssistantResponse &msg);
void on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg);
void on_voice_assistant_audio(const VoiceAssistantAudio &msg);
void on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &msg);
void on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &msg);
void on_voice_assistant_configuration_request(const VoiceAssistantConfigurationRequest &msg);
void on_voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &msg);
#endif
#ifdef USE_ZWAVE_PROXY
void on_z_wave_proxy_frame(const ZWaveProxyFrame &msg) override;
void on_z_wave_proxy_request(const ZWaveProxyRequest &msg) override;
void on_z_wave_proxy_frame(const ZWaveProxyFrame &msg);
void on_z_wave_proxy_request(const ZWaveProxyRequest &msg);
#endif
#ifdef USE_ALARM_CONTROL_PANEL
bool send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel);
void on_alarm_control_panel_command_request(const AlarmControlPanelCommandRequest &msg) override;
void on_alarm_control_panel_command_request(const AlarmControlPanelCommandRequest &msg);
#endif
#ifdef USE_WATER_HEATER
bool send_water_heater_state(water_heater::WaterHeater *water_heater);
void on_water_heater_command_request(const WaterHeaterCommandRequest &msg) override;
void on_water_heater_command_request(const WaterHeaterCommandRequest &msg);
#endif
#ifdef USE_IR_RF
void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &msg) override;
void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &msg);
void send_infrared_rf_receive_event(const InfraredRFReceiveEvent &msg);
#endif
#ifdef USE_SERIAL_PROXY
void on_serial_proxy_configure_request(const SerialProxyConfigureRequest &msg) override;
void on_serial_proxy_write_request(const SerialProxyWriteRequest &msg) override;
void on_serial_proxy_set_modem_pins_request(const SerialProxySetModemPinsRequest &msg) override;
void on_serial_proxy_get_modem_pins_request(const SerialProxyGetModemPinsRequest &msg) override;
void on_serial_proxy_request(const SerialProxyRequest &msg) override;
void on_serial_proxy_configure_request(const SerialProxyConfigureRequest &msg);
void on_serial_proxy_write_request(const SerialProxyWriteRequest &msg);
void on_serial_proxy_set_modem_pins_request(const SerialProxySetModemPinsRequest &msg);
void on_serial_proxy_get_modem_pins_request(const SerialProxyGetModemPinsRequest &msg);
void on_serial_proxy_request(const SerialProxyRequest &msg);
void send_serial_proxy_data(const SerialProxyDataReceived &msg);
#endif
@@ -210,26 +228,26 @@ class APIConnection final : public APIServerConnectionBase {
#ifdef USE_UPDATE
bool send_update_state(update::UpdateEntity *update);
void on_update_command_request(const UpdateCommandRequest &msg) override;
void on_update_command_request(const UpdateCommandRequest &msg);
#endif
void on_disconnect_response() override;
void on_ping_response() override {
void on_disconnect_response();
void on_ping_response() {
// we initiated ping
this->flags_.sent_ping = false;
}
#ifdef USE_API_HOMEASSISTANT_STATES
void on_home_assistant_state_response(const HomeAssistantStateResponse &msg) override;
void on_home_assistant_state_response(const HomeAssistantStateResponse &msg);
#endif
#ifdef USE_HOMEASSISTANT_TIME
void on_get_time_response(const GetTimeResponse &value) override;
void on_get_time_response(const GetTimeResponse &value);
#endif
void on_hello_request(const HelloRequest &msg) override;
void on_disconnect_request() override;
void on_ping_request() override;
void on_device_info_request() override;
void on_list_entities_request() override { this->begin_iterator_(ActiveIterator::LIST_ENTITIES); }
void on_subscribe_states_request() override {
void on_hello_request(const HelloRequest &msg);
void on_disconnect_request();
void on_ping_request();
void on_device_info_request();
void on_list_entities_request() { this->begin_iterator_(ActiveIterator::LIST_ENTITIES); }
void on_subscribe_states_request() {
this->flags_.state_subscription = true;
// Start initial state iterator only if no iterator is active
// If list_entities is running, we'll start initial_state when it completes
@@ -237,7 +255,7 @@ class APIConnection final : public APIServerConnectionBase {
this->begin_iterator_(ActiveIterator::INITIAL_STATE);
}
}
void on_subscribe_logs_request(const SubscribeLogsRequest &msg) override {
void on_subscribe_logs_request(const SubscribeLogsRequest &msg) {
this->flags_.log_subscription = msg.level;
if (msg.dump_config)
App.schedule_dump_config();
@@ -249,13 +267,13 @@ class APIConnection final : public APIServerConnectionBase {
#endif
}
#ifdef USE_API_HOMEASSISTANT_SERVICES
void on_subscribe_homeassistant_services_request() override { this->flags_.service_call_subscription = true; }
void on_subscribe_homeassistant_services_request() { this->flags_.service_call_subscription = true; }
#endif
#ifdef USE_API_HOMEASSISTANT_STATES
void on_subscribe_home_assistant_states_request() override;
void on_subscribe_home_assistant_states_request();
#endif
#ifdef USE_API_USER_DEFINED_ACTIONS
void on_execute_service_request(const ExecuteServiceRequest &msg) override;
void on_execute_service_request(const ExecuteServiceRequest &msg);
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
void send_execute_service_response(uint32_t call_id, bool success, StringRef error_message);
#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
@@ -265,13 +283,13 @@ class APIConnection final : public APIServerConnectionBase {
#endif // USE_API_USER_DEFINED_ACTION_RESPONSES
#endif
#ifdef USE_API_NOISE
void on_noise_encryption_set_key_request(const NoiseEncryptionSetKeyRequest &msg) override;
void on_noise_encryption_set_key_request(const NoiseEncryptionSetKeyRequest &msg);
#endif
bool is_authenticated() override {
bool is_authenticated() {
return static_cast<ConnectionState>(this->flags_.connection_state) == ConnectionState::AUTHENTICATED;
}
bool is_connection_setup() override {
bool is_connection_setup() {
return static_cast<ConnectionState>(this->flags_.connection_state) == ConnectionState::CONNECTED ||
this->is_authenticated();
}
@@ -284,8 +302,8 @@ class APIConnection final : public APIServerConnectionBase {
(this->client_api_version_major_ == major && this->client_api_version_minor_ >= minor);
}
void on_fatal_error() override;
void on_no_setup_connection() override;
void on_fatal_error();
void on_no_setup_connection();
// Function pointer type for type-erased message encoding
using MessageEncodeFn = void (*)(const void *, ProtoWriteBuffer &);
@@ -324,7 +342,7 @@ class APIConnection final : public APIServerConnectionBase {
return true;
return this->try_to_clear_buffer_slow_(log_out_of_space);
}
bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) override;
bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type);
const char *get_name() const { return this->helper_->get_client_name(); }
/// Get peer name (IP address) into caller-provided buffer, returns buf for convenience
+100 -100
View File
@@ -208,7 +208,7 @@ uint32_t DeviceInfoResponse::calculate_size() const {
#ifdef USE_BINARY_SENSOR
void ListEntitiesBinarySensorResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
buffer.encode_string(5, this->device_class);
buffer.encode_bool(6, this->is_status_binary_sensor);
@@ -224,7 +224,7 @@ void ListEntitiesBinarySensorResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesBinarySensorResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_length(1, this->device_class.size());
size += ProtoSize::calc_bool(1, this->is_status_binary_sensor);
@@ -239,7 +239,7 @@ uint32_t ListEntitiesBinarySensorResponse::calculate_size() const {
return size;
}
void BinarySensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -248,7 +248,7 @@ void BinarySensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t BinarySensorStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->state);
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -260,7 +260,7 @@ uint32_t BinarySensorStateResponse::calculate_size() const {
#ifdef USE_COVER
void ListEntitiesCoverResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
buffer.encode_bool(5, this->assumed_state);
buffer.encode_bool(6, this->supports_position);
@@ -279,7 +279,7 @@ void ListEntitiesCoverResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesCoverResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_bool(1, this->assumed_state);
size += ProtoSize::calc_bool(1, this->supports_position);
@@ -297,7 +297,7 @@ uint32_t ListEntitiesCoverResponse::calculate_size() const {
return size;
}
void CoverStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_float(3, this->position);
buffer.encode_float(4, this->tilt);
buffer.encode_uint32(5, static_cast<uint32_t>(this->current_operation));
@@ -307,7 +307,7 @@ void CoverStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t CoverStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_float(1, this->position);
size += ProtoSize::calc_float(1, this->tilt);
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->current_operation));
@@ -357,7 +357,7 @@ bool CoverCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_FAN
void ListEntitiesFanResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
buffer.encode_bool(5, this->supports_oscillation);
buffer.encode_bool(6, this->supports_speed);
@@ -378,7 +378,7 @@ void ListEntitiesFanResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesFanResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_bool(1, this->supports_oscillation);
size += ProtoSize::calc_bool(1, this->supports_speed);
@@ -400,7 +400,7 @@ uint32_t ListEntitiesFanResponse::calculate_size() const {
return size;
}
void FanStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->state);
buffer.encode_bool(3, this->oscillating);
buffer.encode_uint32(5, static_cast<uint32_t>(this->direction));
@@ -412,7 +412,7 @@ void FanStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t FanStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->state);
size += ProtoSize::calc_bool(1, this->oscillating);
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->direction));
@@ -487,7 +487,7 @@ bool FanCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_LIGHT
void ListEntitiesLightResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
for (const auto &it : *this->supported_color_modes) {
buffer.encode_uint32(12, static_cast<uint32_t>(it), true);
@@ -509,7 +509,7 @@ void ListEntitiesLightResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesLightResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
if (!this->supported_color_modes->empty()) {
for (const auto &it : *this->supported_color_modes) {
@@ -534,7 +534,7 @@ uint32_t ListEntitiesLightResponse::calculate_size() const {
return size;
}
void LightStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->state);
buffer.encode_float(3, this->brightness);
buffer.encode_uint32(11, static_cast<uint32_t>(this->color_mode));
@@ -553,7 +553,7 @@ void LightStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t LightStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->state);
size += ProtoSize::calc_float(1, this->brightness);
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->color_mode));
@@ -683,7 +683,7 @@ bool LightCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_SENSOR
void ListEntitiesSensorResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -702,7 +702,7 @@ void ListEntitiesSensorResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesSensorResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -720,7 +720,7 @@ uint32_t ListEntitiesSensorResponse::calculate_size() const {
return size;
}
void SensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_float(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -729,7 +729,7 @@ void SensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t SensorStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_float(1, this->state);
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -741,7 +741,7 @@ uint32_t SensorStateResponse::calculate_size() const {
#ifdef USE_SWITCH
void ListEntitiesSwitchResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -757,7 +757,7 @@ void ListEntitiesSwitchResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesSwitchResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -772,7 +772,7 @@ uint32_t ListEntitiesSwitchResponse::calculate_size() const {
return size;
}
void SwitchStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->state);
#ifdef USE_DEVICES
buffer.encode_uint32(3, this->device_id);
@@ -780,7 +780,7 @@ void SwitchStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t SwitchStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->state);
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
@@ -816,7 +816,7 @@ bool SwitchCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_TEXT_SENSOR
void ListEntitiesTextSensorResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -831,7 +831,7 @@ void ListEntitiesTextSensorResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesTextSensorResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -845,7 +845,7 @@ uint32_t ListEntitiesTextSensorResponse::calculate_size() const {
return size;
}
void TextSensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_string(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -854,7 +854,7 @@ void TextSensorStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t TextSensorStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->state.size());
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -1124,7 +1124,7 @@ uint32_t ListEntitiesServicesArgument::calculate_size() const {
}
void ListEntitiesServicesResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->name);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
for (auto &it : this->args) {
buffer.encode_sub_message(3, it);
}
@@ -1133,7 +1133,7 @@ void ListEntitiesServicesResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesServicesResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
if (!this->args.empty()) {
for (const auto &it : this->args) {
size += ProtoSize::calc_message_force(1, it.calculate_size());
@@ -1269,7 +1269,7 @@ uint32_t ExecuteServiceResponse::calculate_size() const {
#ifdef USE_CAMERA
void ListEntitiesCameraResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
buffer.encode_bool(5, this->disabled_by_default);
#ifdef USE_ENTITY_ICON
@@ -1283,7 +1283,7 @@ void ListEntitiesCameraResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesCameraResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_bool(1, this->disabled_by_default);
#ifdef USE_ENTITY_ICON
@@ -1296,7 +1296,7 @@ uint32_t ListEntitiesCameraResponse::calculate_size() const {
return size;
}
void CameraImageResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bytes(2, this->data_ptr_, this->data_len_);
buffer.encode_bool(3, this->done);
#ifdef USE_DEVICES
@@ -1305,7 +1305,7 @@ void CameraImageResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t CameraImageResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->data_len_);
size += ProtoSize::calc_bool(1, this->done);
#ifdef USE_DEVICES
@@ -1330,7 +1330,7 @@ bool CameraImageRequest::decode_varint(uint32_t field_id, proto_varint_value_t v
#ifdef USE_CLIMATE
void ListEntitiesClimateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
buffer.encode_bool(5, this->supports_current_temperature);
buffer.encode_bool(6, this->supports_two_point_target_temperature);
@@ -1374,7 +1374,7 @@ void ListEntitiesClimateResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesClimateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
size += ProtoSize::calc_bool(1, this->supports_current_temperature);
size += ProtoSize::calc_bool(1, this->supports_two_point_target_temperature);
@@ -1429,7 +1429,7 @@ uint32_t ListEntitiesClimateResponse::calculate_size() const {
return size;
}
void ClimateStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_uint32(2, static_cast<uint32_t>(this->mode));
buffer.encode_float(3, this->current_temperature);
buffer.encode_float(4, this->target_temperature);
@@ -1449,7 +1449,7 @@ void ClimateStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t ClimateStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->mode));
size += ProtoSize::calc_float(1, this->current_temperature);
size += ProtoSize::calc_float(1, this->target_temperature);
@@ -1563,7 +1563,7 @@ bool ClimateCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_WATER_HEATER
void ListEntitiesWaterHeaterResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(4, this->icon);
@@ -1584,7 +1584,7 @@ void ListEntitiesWaterHeaterResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesWaterHeaterResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -1606,7 +1606,7 @@ uint32_t ListEntitiesWaterHeaterResponse::calculate_size() const {
return size;
}
void WaterHeaterStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_float(2, this->current_temperature);
buffer.encode_float(3, this->target_temperature);
buffer.encode_uint32(4, static_cast<uint32_t>(this->mode));
@@ -1619,7 +1619,7 @@ void WaterHeaterStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t WaterHeaterStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_float(1, this->current_temperature);
size += ProtoSize::calc_float(1, this->target_temperature);
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->mode));
@@ -1675,7 +1675,7 @@ bool WaterHeaterCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value
#ifdef USE_NUMBER
void ListEntitiesNumberResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -1695,7 +1695,7 @@ void ListEntitiesNumberResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesNumberResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -1714,7 +1714,7 @@ uint32_t ListEntitiesNumberResponse::calculate_size() const {
return size;
}
void NumberStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_float(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -1723,7 +1723,7 @@ void NumberStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t NumberStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_float(1, this->state);
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -1760,7 +1760,7 @@ bool NumberCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_SELECT
void ListEntitiesSelectResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -1777,7 +1777,7 @@ void ListEntitiesSelectResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesSelectResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -1795,7 +1795,7 @@ uint32_t ListEntitiesSelectResponse::calculate_size() const {
return size;
}
void SelectStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_string(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -1804,7 +1804,7 @@ void SelectStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t SelectStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->state.size());
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -1849,7 +1849,7 @@ bool SelectCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_SIREN
void ListEntitiesSirenResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -1868,7 +1868,7 @@ void ListEntitiesSirenResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesSirenResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -1888,7 +1888,7 @@ uint32_t ListEntitiesSirenResponse::calculate_size() const {
return size;
}
void SirenStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->state);
#ifdef USE_DEVICES
buffer.encode_uint32(3, this->device_id);
@@ -1896,7 +1896,7 @@ void SirenStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t SirenStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->state);
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
@@ -1961,7 +1961,7 @@ bool SirenCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_LOCK
void ListEntitiesLockResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -1979,7 +1979,7 @@ void ListEntitiesLockResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesLockResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -1996,7 +1996,7 @@ uint32_t ListEntitiesLockResponse::calculate_size() const {
return size;
}
void LockStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_uint32(2, static_cast<uint32_t>(this->state));
#ifdef USE_DEVICES
buffer.encode_uint32(3, this->device_id);
@@ -2004,7 +2004,7 @@ void LockStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t LockStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->state));
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
@@ -2054,7 +2054,7 @@ bool LockCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_BUTTON
void ListEntitiesButtonResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -2069,7 +2069,7 @@ void ListEntitiesButtonResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesButtonResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -2124,7 +2124,7 @@ uint32_t MediaPlayerSupportedFormat::calculate_size() const {
}
void ListEntitiesMediaPlayerResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -2143,7 +2143,7 @@ void ListEntitiesMediaPlayerResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesMediaPlayerResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -2163,7 +2163,7 @@ uint32_t ListEntitiesMediaPlayerResponse::calculate_size() const {
return size;
}
void MediaPlayerStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_uint32(2, static_cast<uint32_t>(this->state));
buffer.encode_float(3, this->volume);
buffer.encode_bool(4, this->muted);
@@ -2173,7 +2173,7 @@ void MediaPlayerStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t MediaPlayerStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->state));
size += ProtoSize::calc_float(1, this->volume);
size += ProtoSize::calc_bool(1, this->muted);
@@ -2942,7 +2942,7 @@ bool VoiceAssistantSetConfiguration::decode_length(uint32_t field_id, ProtoLengt
#ifdef USE_ALARM_CONTROL_PANEL
void ListEntitiesAlarmControlPanelResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -2959,7 +2959,7 @@ void ListEntitiesAlarmControlPanelResponse::encode(ProtoWriteBuffer &buffer) con
uint32_t ListEntitiesAlarmControlPanelResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -2975,7 +2975,7 @@ uint32_t ListEntitiesAlarmControlPanelResponse::calculate_size() const {
return size;
}
void AlarmControlPanelStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_uint32(2, static_cast<uint32_t>(this->state));
#ifdef USE_DEVICES
buffer.encode_uint32(3, this->device_id);
@@ -2983,7 +2983,7 @@ void AlarmControlPanelStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t AlarmControlPanelStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->state));
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
@@ -3030,7 +3030,7 @@ bool AlarmControlPanelCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit
#ifdef USE_TEXT
void ListEntitiesTextResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3048,7 +3048,7 @@ void ListEntitiesTextResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesTextResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3065,7 +3065,7 @@ uint32_t ListEntitiesTextResponse::calculate_size() const {
return size;
}
void TextStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_string(2, this->state);
buffer.encode_bool(3, this->missing_state);
#ifdef USE_DEVICES
@@ -3074,7 +3074,7 @@ void TextStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t TextStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->state.size());
size += ProtoSize::calc_bool(1, this->missing_state);
#ifdef USE_DEVICES
@@ -3119,7 +3119,7 @@ bool TextCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_DATETIME_DATE
void ListEntitiesDateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3133,7 +3133,7 @@ void ListEntitiesDateResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesDateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3146,7 +3146,7 @@ uint32_t ListEntitiesDateResponse::calculate_size() const {
return size;
}
void DateStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->missing_state);
buffer.encode_uint32(3, this->year);
buffer.encode_uint32(4, this->month);
@@ -3157,7 +3157,7 @@ void DateStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t DateStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->missing_state);
size += ProtoSize::calc_uint32(1, this->year);
size += ProtoSize::calc_uint32(1, this->month);
@@ -3202,7 +3202,7 @@ bool DateCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_DATETIME_TIME
void ListEntitiesTimeResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3216,7 +3216,7 @@ void ListEntitiesTimeResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesTimeResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3229,7 +3229,7 @@ uint32_t ListEntitiesTimeResponse::calculate_size() const {
return size;
}
void TimeStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->missing_state);
buffer.encode_uint32(3, this->hour);
buffer.encode_uint32(4, this->minute);
@@ -3240,7 +3240,7 @@ void TimeStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t TimeStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->missing_state);
size += ProtoSize::calc_uint32(1, this->hour);
size += ProtoSize::calc_uint32(1, this->minute);
@@ -3285,7 +3285,7 @@ bool TimeCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_EVENT
void ListEntitiesEventResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3303,7 +3303,7 @@ void ListEntitiesEventResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesEventResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3322,7 +3322,7 @@ uint32_t ListEntitiesEventResponse::calculate_size() const {
return size;
}
void EventResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_string(2, this->event_type);
#ifdef USE_DEVICES
buffer.encode_uint32(3, this->device_id);
@@ -3330,7 +3330,7 @@ void EventResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t EventResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->event_type.size());
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
@@ -3341,7 +3341,7 @@ uint32_t EventResponse::calculate_size() const {
#ifdef USE_VALVE
void ListEntitiesValveResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3359,7 +3359,7 @@ void ListEntitiesValveResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesValveResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3376,7 +3376,7 @@ uint32_t ListEntitiesValveResponse::calculate_size() const {
return size;
}
void ValveStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_float(2, this->position);
buffer.encode_uint32(3, static_cast<uint32_t>(this->current_operation));
#ifdef USE_DEVICES
@@ -3385,7 +3385,7 @@ void ValveStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t ValveStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_float(1, this->position);
size += ProtoSize::calc_uint32(1, static_cast<uint32_t>(this->current_operation));
#ifdef USE_DEVICES
@@ -3428,7 +3428,7 @@ bool ValveCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_DATETIME_DATETIME
void ListEntitiesDateTimeResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3442,7 +3442,7 @@ void ListEntitiesDateTimeResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesDateTimeResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3455,7 +3455,7 @@ uint32_t ListEntitiesDateTimeResponse::calculate_size() const {
return size;
}
void DateTimeStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->missing_state);
buffer.encode_fixed32(3, this->epoch_seconds);
#ifdef USE_DEVICES
@@ -3464,7 +3464,7 @@ void DateTimeStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t DateTimeStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->missing_state);
size += ProtoSize::calc_fixed32(1, this->epoch_seconds);
#ifdef USE_DEVICES
@@ -3501,7 +3501,7 @@ bool DateTimeCommandRequest::decode_32bit(uint32_t field_id, Proto32Bit value) {
#ifdef USE_UPDATE
void ListEntitiesUpdateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(5, this->icon);
@@ -3516,7 +3516,7 @@ void ListEntitiesUpdateResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesUpdateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3530,7 +3530,7 @@ uint32_t ListEntitiesUpdateResponse::calculate_size() const {
return size;
}
void UpdateStateResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_fixed32(1, this->key);
buffer.write_tag_and_fixed32(13, this->key);
buffer.encode_bool(2, this->missing_state);
buffer.encode_bool(3, this->in_progress);
buffer.encode_bool(4, this->has_progress);
@@ -3546,7 +3546,7 @@ void UpdateStateResponse::encode(ProtoWriteBuffer &buffer) const {
}
uint32_t UpdateStateResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_bool(1, this->missing_state);
size += ProtoSize::calc_bool(1, this->in_progress);
size += ProtoSize::calc_bool(1, this->has_progress);
@@ -3642,7 +3642,7 @@ uint32_t ZWaveProxyRequest::calculate_size() const {
#ifdef USE_INFRARED
void ListEntitiesInfraredResponse::encode(ProtoWriteBuffer &buffer) const {
buffer.encode_string(1, this->object_id);
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
buffer.encode_string(3, this->name);
#ifdef USE_ENTITY_ICON
buffer.encode_string(4, this->icon);
@@ -3657,7 +3657,7 @@ void ListEntitiesInfraredResponse::encode(ProtoWriteBuffer &buffer) const {
uint32_t ListEntitiesInfraredResponse::calculate_size() const {
uint32_t size = 0;
size += ProtoSize::calc_length(1, this->object_id.size());
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
size += ProtoSize::calc_length(1, this->name.size());
#ifdef USE_ENTITY_ICON
size += ProtoSize::calc_length(1, this->icon.size());
@@ -3717,7 +3717,7 @@ void InfraredRFReceiveEvent::encode(ProtoWriteBuffer &buffer) const {
#ifdef USE_DEVICES
buffer.encode_uint32(1, this->device_id);
#endif
buffer.encode_fixed32(2, this->key);
buffer.write_tag_and_fixed32(21, this->key);
for (const auto &it : *this->timings) {
buffer.encode_sint32(3, it, true);
}
@@ -3727,7 +3727,7 @@ uint32_t InfraredRFReceiveEvent::calculate_size() const {
#ifdef USE_DEVICES
size += ProtoSize::calc_uint32(1, this->device_id);
#endif
size += ProtoSize::calc_fixed32(1, this->key);
size += 5;
if (!this->timings->empty()) {
for (const auto &it : *this->timings) {
size += ProtoSize::calc_sint32_force(1, it);
+2 -1
View File
@@ -1,6 +1,7 @@
// This file was automatically generated with a tool.
// See script/api_protobuf/api_protobuf.py
#include "api_pb2_service.h"
#include "api_connection.h"
#include "esphome/core/log.h"
namespace esphome::api {
@@ -20,7 +21,7 @@ void APIServerConnectionBase::log_receive_message_(const LogString *name) {
}
#endif
void APIServerConnectionBase::read_message(uint32_t msg_size, uint32_t msg_type, const uint8_t *msg_data) {
void APIConnection::read_message_(uint32_t msg_size, uint32_t msg_type, const uint8_t *msg_data) {
// Check authentication/connection requirements
switch (msg_type) {
case HelloRequest::MESSAGE_TYPE: // No setup required
+65 -69
View File
@@ -8,7 +8,7 @@
namespace esphome::api {
class APIServerConnectionBase : public ProtoService {
class APIServerConnectionBase {
public:
#ifdef HAS_PROTO_MESSAGE_DUMP
protected:
@@ -19,227 +19,223 @@ class APIServerConnectionBase : public ProtoService {
public:
#endif
virtual void on_hello_request(const HelloRequest &value){};
void on_hello_request(const HelloRequest &value){};
virtual void on_disconnect_request(){};
virtual void on_disconnect_response(){};
virtual void on_ping_request(){};
virtual void on_ping_response(){};
virtual void on_device_info_request(){};
void on_disconnect_request(){};
void on_disconnect_response(){};
void on_ping_request(){};
void on_ping_response(){};
void on_device_info_request(){};
virtual void on_list_entities_request(){};
void on_list_entities_request(){};
virtual void on_subscribe_states_request(){};
void on_subscribe_states_request(){};
#ifdef USE_COVER
virtual void on_cover_command_request(const CoverCommandRequest &value){};
void on_cover_command_request(const CoverCommandRequest &value){};
#endif
#ifdef USE_FAN
virtual void on_fan_command_request(const FanCommandRequest &value){};
void on_fan_command_request(const FanCommandRequest &value){};
#endif
#ifdef USE_LIGHT
virtual void on_light_command_request(const LightCommandRequest &value){};
void on_light_command_request(const LightCommandRequest &value){};
#endif
#ifdef USE_SWITCH
virtual void on_switch_command_request(const SwitchCommandRequest &value){};
void on_switch_command_request(const SwitchCommandRequest &value){};
#endif
virtual void on_subscribe_logs_request(const SubscribeLogsRequest &value){};
void on_subscribe_logs_request(const SubscribeLogsRequest &value){};
#ifdef USE_API_NOISE
virtual void on_noise_encryption_set_key_request(const NoiseEncryptionSetKeyRequest &value){};
void on_noise_encryption_set_key_request(const NoiseEncryptionSetKeyRequest &value){};
#endif
#ifdef USE_API_HOMEASSISTANT_SERVICES
virtual void on_subscribe_homeassistant_services_request(){};
void on_subscribe_homeassistant_services_request(){};
#endif
#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
virtual void on_homeassistant_action_response(const HomeassistantActionResponse &value){};
void on_homeassistant_action_response(const HomeassistantActionResponse &value){};
#endif
#ifdef USE_API_HOMEASSISTANT_STATES
virtual void on_subscribe_home_assistant_states_request(){};
void on_subscribe_home_assistant_states_request(){};
#endif
#ifdef USE_API_HOMEASSISTANT_STATES
virtual void on_home_assistant_state_response(const HomeAssistantStateResponse &value){};
void on_home_assistant_state_response(const HomeAssistantStateResponse &value){};
#endif
virtual void on_get_time_response(const GetTimeResponse &value){};
void on_get_time_response(const GetTimeResponse &value){};
#ifdef USE_API_USER_DEFINED_ACTIONS
virtual void on_execute_service_request(const ExecuteServiceRequest &value){};
void on_execute_service_request(const ExecuteServiceRequest &value){};
#endif
#ifdef USE_CAMERA
virtual void on_camera_image_request(const CameraImageRequest &value){};
void on_camera_image_request(const CameraImageRequest &value){};
#endif
#ifdef USE_CLIMATE
virtual void on_climate_command_request(const ClimateCommandRequest &value){};
void on_climate_command_request(const ClimateCommandRequest &value){};
#endif
#ifdef USE_WATER_HEATER
virtual void on_water_heater_command_request(const WaterHeaterCommandRequest &value){};
void on_water_heater_command_request(const WaterHeaterCommandRequest &value){};
#endif
#ifdef USE_NUMBER
virtual void on_number_command_request(const NumberCommandRequest &value){};
void on_number_command_request(const NumberCommandRequest &value){};
#endif
#ifdef USE_SELECT
virtual void on_select_command_request(const SelectCommandRequest &value){};
void on_select_command_request(const SelectCommandRequest &value){};
#endif
#ifdef USE_SIREN
virtual void on_siren_command_request(const SirenCommandRequest &value){};
void on_siren_command_request(const SirenCommandRequest &value){};
#endif
#ifdef USE_LOCK
virtual void on_lock_command_request(const LockCommandRequest &value){};
void on_lock_command_request(const LockCommandRequest &value){};
#endif
#ifdef USE_BUTTON
virtual void on_button_command_request(const ButtonCommandRequest &value){};
void on_button_command_request(const ButtonCommandRequest &value){};
#endif
#ifdef USE_MEDIA_PLAYER
virtual void on_media_player_command_request(const MediaPlayerCommandRequest &value){};
void on_media_player_command_request(const MediaPlayerCommandRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_subscribe_bluetooth_le_advertisements_request(
const SubscribeBluetoothLEAdvertisementsRequest &value){};
void on_subscribe_bluetooth_le_advertisements_request(const SubscribeBluetoothLEAdvertisementsRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_device_request(const BluetoothDeviceRequest &value){};
void on_bluetooth_device_request(const BluetoothDeviceRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_get_services_request(const BluetoothGATTGetServicesRequest &value){};
void on_bluetooth_gatt_get_services_request(const BluetoothGATTGetServicesRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_read_request(const BluetoothGATTReadRequest &value){};
void on_bluetooth_gatt_read_request(const BluetoothGATTReadRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_write_request(const BluetoothGATTWriteRequest &value){};
void on_bluetooth_gatt_write_request(const BluetoothGATTWriteRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_read_descriptor_request(const BluetoothGATTReadDescriptorRequest &value){};
void on_bluetooth_gatt_read_descriptor_request(const BluetoothGATTReadDescriptorRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_write_descriptor_request(const BluetoothGATTWriteDescriptorRequest &value){};
void on_bluetooth_gatt_write_descriptor_request(const BluetoothGATTWriteDescriptorRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_gatt_notify_request(const BluetoothGATTNotifyRequest &value){};
void on_bluetooth_gatt_notify_request(const BluetoothGATTNotifyRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_subscribe_bluetooth_connections_free_request(){};
void on_subscribe_bluetooth_connections_free_request(){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_unsubscribe_bluetooth_le_advertisements_request(){};
void on_unsubscribe_bluetooth_le_advertisements_request(){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_scanner_set_mode_request(const BluetoothScannerSetModeRequest &value){};
void on_bluetooth_scanner_set_mode_request(const BluetoothScannerSetModeRequest &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_subscribe_voice_assistant_request(const SubscribeVoiceAssistantRequest &value){};
void on_subscribe_voice_assistant_request(const SubscribeVoiceAssistantRequest &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_response(const VoiceAssistantResponse &value){};
void on_voice_assistant_response(const VoiceAssistantResponse &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_event_response(const VoiceAssistantEventResponse &value){};
void on_voice_assistant_event_response(const VoiceAssistantEventResponse &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_audio(const VoiceAssistantAudio &value){};
void on_voice_assistant_audio(const VoiceAssistantAudio &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &value){};
void on_voice_assistant_timer_event_response(const VoiceAssistantTimerEventResponse &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &value){};
void on_voice_assistant_announce_request(const VoiceAssistantAnnounceRequest &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_configuration_request(const VoiceAssistantConfigurationRequest &value){};
void on_voice_assistant_configuration_request(const VoiceAssistantConfigurationRequest &value){};
#endif
#ifdef USE_VOICE_ASSISTANT
virtual void on_voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &value){};
void on_voice_assistant_set_configuration(const VoiceAssistantSetConfiguration &value){};
#endif
#ifdef USE_ALARM_CONTROL_PANEL
virtual void on_alarm_control_panel_command_request(const AlarmControlPanelCommandRequest &value){};
void on_alarm_control_panel_command_request(const AlarmControlPanelCommandRequest &value){};
#endif
#ifdef USE_TEXT
virtual void on_text_command_request(const TextCommandRequest &value){};
void on_text_command_request(const TextCommandRequest &value){};
#endif
#ifdef USE_DATETIME_DATE
virtual void on_date_command_request(const DateCommandRequest &value){};
void on_date_command_request(const DateCommandRequest &value){};
#endif
#ifdef USE_DATETIME_TIME
virtual void on_time_command_request(const TimeCommandRequest &value){};
void on_time_command_request(const TimeCommandRequest &value){};
#endif
#ifdef USE_VALVE
virtual void on_valve_command_request(const ValveCommandRequest &value){};
void on_valve_command_request(const ValveCommandRequest &value){};
#endif
#ifdef USE_DATETIME_DATETIME
virtual void on_date_time_command_request(const DateTimeCommandRequest &value){};
void on_date_time_command_request(const DateTimeCommandRequest &value){};
#endif
#ifdef USE_UPDATE
virtual void on_update_command_request(const UpdateCommandRequest &value){};
void on_update_command_request(const UpdateCommandRequest &value){};
#endif
#ifdef USE_ZWAVE_PROXY
virtual void on_z_wave_proxy_frame(const ZWaveProxyFrame &value){};
void on_z_wave_proxy_frame(const ZWaveProxyFrame &value){};
#endif
#ifdef USE_ZWAVE_PROXY
virtual void on_z_wave_proxy_request(const ZWaveProxyRequest &value){};
void on_z_wave_proxy_request(const ZWaveProxyRequest &value){};
#endif
#ifdef USE_IR_RF
virtual void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &value){};
void on_infrared_rf_transmit_raw_timings_request(const InfraredRFTransmitRawTimingsRequest &value){};
#endif
#ifdef USE_SERIAL_PROXY
virtual void on_serial_proxy_configure_request(const SerialProxyConfigureRequest &value){};
void on_serial_proxy_configure_request(const SerialProxyConfigureRequest &value){};
#endif
#ifdef USE_SERIAL_PROXY
virtual void on_serial_proxy_write_request(const SerialProxyWriteRequest &value){};
void on_serial_proxy_write_request(const SerialProxyWriteRequest &value){};
#endif
#ifdef USE_SERIAL_PROXY
virtual void on_serial_proxy_set_modem_pins_request(const SerialProxySetModemPinsRequest &value){};
void on_serial_proxy_set_modem_pins_request(const SerialProxySetModemPinsRequest &value){};
#endif
#ifdef USE_SERIAL_PROXY
virtual void on_serial_proxy_get_modem_pins_request(const SerialProxyGetModemPinsRequest &value){};
void on_serial_proxy_get_modem_pins_request(const SerialProxyGetModemPinsRequest &value){};
#endif
#ifdef USE_SERIAL_PROXY
virtual void on_serial_proxy_request(const SerialProxyRequest &value){};
void on_serial_proxy_request(const SerialProxyRequest &value){};
#endif
#ifdef USE_BLUETOOTH_PROXY
virtual void on_bluetooth_set_connection_params_request(const BluetoothSetConnectionParamsRequest &value){};
void on_bluetooth_set_connection_params_request(const BluetoothSetConnectionParamsRequest &value){};
#endif
protected:
void read_message(uint32_t msg_size, uint32_t msg_type, const uint8_t *msg_data) override;
};
} // namespace esphome::api
+18 -23
View File
@@ -236,6 +236,21 @@ class ProtoWriteBuffer {
* Following https://protobuf.dev/programming-guides/encoding/#structure
*/
void encode_field_raw(uint32_t field_id, uint32_t type) { this->encode_varint_raw((field_id << 3) | type); }
/// Write a precomputed tag byte + 32-bit value in one operation.
/// Tag must be a single-byte varint (< 128). No zero check.
inline void write_tag_and_fixed32(uint8_t tag, uint32_t value) ESPHOME_ALWAYS_INLINE {
this->debug_check_bounds_(5);
this->pos_[0] = tag;
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
std::memcpy(this->pos_ + 1, &value, 4);
#else
this->pos_[1] = static_cast<uint8_t>(value & 0xFF);
this->pos_[2] = static_cast<uint8_t>((value >> 8) & 0xFF);
this->pos_[3] = static_cast<uint8_t>((value >> 16) & 0xFF);
this->pos_[4] = static_cast<uint8_t>((value >> 24) & 0xFF);
#endif
this->pos_ += 5;
}
void encode_string(uint32_t field_id, const char *string, size_t len, bool force = false) {
if (len == 0 && !force)
return;
@@ -276,8 +291,7 @@ class ProtoWriteBuffer {
this->debug_check_bounds_(1);
*this->pos_++ = value ? 0x01 : 0x00;
}
// noinline: 51 call sites; inlining causes net code growth vs a single out-of-line copy
__attribute__((noinline)) void encode_fixed32(uint32_t field_id, uint32_t value, bool force = false) {
void encode_fixed32(uint32_t field_id, uint32_t value, bool force = false) {
if (value == 0 && !force)
return;
@@ -697,26 +711,7 @@ inline void ProtoLengthDelimited::decode_to_message(ProtoDecodableMessage &msg)
template<typename T> const char *proto_enum_to_string(T value);
class ProtoService {
public:
protected:
virtual bool is_authenticated() = 0;
virtual bool is_connection_setup() = 0;
virtual void on_fatal_error() = 0;
virtual void on_no_setup_connection() = 0;
virtual bool send_buffer(ProtoWriteBuffer buffer, uint8_t message_type) = 0;
virtual void read_message(uint32_t msg_size, uint32_t msg_type, const uint8_t *msg_data) = 0;
// Authentication helper methods
inline bool check_connection_setup_() {
if (!this->is_connection_setup()) {
this->on_no_setup_connection();
return false;
}
return true;
}
inline bool check_authenticated_() { return this->check_connection_setup_(); }
};
// ProtoService removed — its methods were inlined into APIConnection.
// APIConnection is the concrete server-side implementation; the extra virtual layer was unnecessary.
} // namespace esphome::api
+3 -3
View File
@@ -103,17 +103,17 @@ size_t BLENUS::available() {
#endif
}
uart::FlushResult BLENUS::flush() {
uart::UARTFlushResult BLENUS::flush() {
constexpr uint32_t timeout_500ms = 500;
uint32_t start = millis();
while (atomic_get(&this->tx_status_) != TX_DISABLED && !ring_buf_is_empty(&global_ble_tx_ring_buf)) {
if (millis() - start > timeout_500ms) {
ESP_LOGW(TAG, "Flush timeout");
return uart::FlushResult::TIMEOUT;
return uart::UARTFlushResult::UART_FLUSH_RESULT_TIMEOUT;
}
delay(1);
}
return uart::FlushResult::SUCCESS;
return uart::UARTFlushResult::UART_FLUSH_RESULT_SUCCESS;
}
void BLENUS::connected(bt_conn *conn, uint8_t err) {
+1 -1
View File
@@ -26,7 +26,7 @@ class BLENUS : public uart::UARTComponent, public Component {
bool peek_byte(uint8_t *data) override;
bool read_array(uint8_t *data, size_t len) override;
size_t available() override;
uart::FlushResult flush() override;
uart::UARTFlushResult flush() override;
void check_logger_conflict() override {}
void set_expose_log(bool expose_log) { this->expose_log_ = expose_log; }
#ifdef USE_LOGGER
+17 -17
View File
@@ -4,8 +4,6 @@
#include "esphome/core/hal.h"
#include <cmath>
#include <functional>
#include <vector>
namespace esphome {
namespace combination {
@@ -20,12 +18,12 @@ void CombinationComponent::log_config_(const LogString *combo_type) {
void CombinationNoParameterComponent::add_source(Sensor *sensor) { this->sensors_.emplace_back(sensor); }
void CombinationOneParameterComponent::add_source(Sensor *sensor, std::function<float(float)> const &stddev) {
this->sensor_pairs_.emplace_back(sensor, stddev);
void CombinationOneParameterComponent::add_source(Sensor *sensor, std::function<float(float)> const &compute) {
this->sensor_sources_.push_back({sensor, compute, this});
}
void CombinationOneParameterComponent::add_source(Sensor *sensor, float stddev) {
this->add_source(sensor, std::function<float(float)>{[stddev](float x) -> float { return stddev; }});
void CombinationOneParameterComponent::add_source(Sensor *sensor, float value) {
this->add_source(sensor, std::function<float(float)>{[value](float x) -> float { return value; }});
}
void CombinationNoParameterComponent::log_source_sensors() {
@@ -37,9 +35,8 @@ void CombinationNoParameterComponent::log_source_sensors() {
void CombinationOneParameterComponent::log_source_sensors() {
ESP_LOGCONFIG(TAG, " Source Sensors:");
for (const auto &sensor : this->sensor_pairs_) {
auto &entity = *sensor.first;
ESP_LOGCONFIG(TAG, " - %s", entity.get_name().c_str());
for (const auto &source : this->sensor_sources_) {
ESP_LOGCONFIG(TAG, " - %s", source.sensor->get_name().c_str());
}
}
@@ -62,9 +59,12 @@ void KalmanCombinationComponent::dump_config() {
}
void KalmanCombinationComponent::setup() {
for (const auto &sensor : this->sensor_pairs_) {
const auto stddev = sensor.second;
sensor.first->add_on_state_callback([this, stddev](float x) -> void { this->correct_(x, stddev(x)); });
for (auto &source : this->sensor_sources_) {
// [&source] is safe: source refers to a FixedVector element that never reallocates,
// so the reference remains valid for the component's lifetime.
source.sensor->add_on_state_callback([&source](float x) -> void {
static_cast<KalmanCombinationComponent *>(source.parent)->correct_(x, source.compute(x));
});
}
}
@@ -117,10 +117,10 @@ void KalmanCombinationComponent::correct_(float value, float stddev) {
}
void LinearCombinationComponent::setup() {
for (const auto &sensor : this->sensor_pairs_) {
for (auto &source : this->sensor_sources_) {
// All sensor updates are deferred until the next loop. This avoids publishing the combined sensor's result
// repeatedly in the same loop if multiple source senors update.
sensor.first->add_on_state_callback(
source.sensor->add_on_state_callback(
[this](float value) -> void { this->defer("update", [this, value]() { this->handle_new_value(value); }); });
}
}
@@ -133,10 +133,10 @@ void LinearCombinationComponent::handle_new_value(float value) {
float sum = 0.0;
for (const auto &sensor : this->sensor_pairs_) {
const float sensor_state = sensor.first->state;
for (const auto &source : this->sensor_sources_) {
const float sensor_state = source.sensor->state;
if (std::isfinite(sensor_state)) {
sum += sensor_state * sensor.second(sensor_state);
sum += sensor_state * source.compute(sensor_state);
}
}
+13 -5
View File
@@ -1,9 +1,10 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/components/sensor/sensor.h"
#include <vector>
#include <functional>
namespace esphome {
namespace combination {
@@ -41,14 +42,21 @@ class CombinationNoParameterComponent : public CombinationComponent {
// Base class for opertions that require one parameter to compute the combination
class CombinationOneParameterComponent : public CombinationComponent {
public:
void add_source(Sensor *sensor, std::function<float(float)> const &stddev);
void add_source(Sensor *sensor, float stddev);
void set_source_count(size_t count) { this->sensor_sources_.init(count); }
void add_source(Sensor *sensor, std::function<float(float)> const &compute);
void add_source(Sensor *sensor, float value);
/// @brief Logs all source sensor's names in sensor_pairs_
/// @brief Logs all source sensors' names in sensor_sources_
void log_source_sensors() override;
protected:
std::vector<std::pair<Sensor *, std::function<float(float)>>> sensor_pairs_;
struct SensorSource {
sensor::Sensor *sensor;
std::function<float(float)> compute;
CombinationOneParameterComponent *parent;
};
FixedVector<SensorSource> sensor_sources_;
};
class KalmanCombinationComponent : public CombinationOneParameterComponent {
+3
View File
@@ -180,6 +180,9 @@ async def to_code(config):
if proces_std_dev := config.get(CONF_PROCESS_STD_DEV):
cg.add(var.set_process_std_dev(proces_std_dev))
if config[CONF_TYPE] in (CONF_KALMAN, CONF_LINEAR):
cg.add(var.set_source_count(len(config[CONF_SOURCES])))
for source_conf in config[CONF_SOURCES]:
source = await cg.get_variable(source_conf[CONF_SOURCE])
if config[CONF_TYPE] == CONF_KALMAN:
+10 -8
View File
@@ -105,17 +105,18 @@ template<typename... Ts> using CoverIsClosedCondition = CoverPositionCondition<f
template<bool OPEN> class CoverPositionTrigger : public Trigger<> {
public:
CoverPositionTrigger(Cover *a_cover) {
a_cover->add_on_state_callback([this, a_cover]() {
if (a_cover->position != this->last_position_) {
this->last_position_ = a_cover->position;
if (a_cover->position == (OPEN ? COVER_OPEN : COVER_CLOSED))
CoverPositionTrigger(Cover *a_cover) : cover_(a_cover) {
a_cover->add_on_state_callback([this]() {
if (this->cover_->position != this->last_position_) {
this->last_position_ = this->cover_->position;
if (this->cover_->position == (OPEN ? COVER_OPEN : COVER_CLOSED))
this->trigger();
}
});
}
protected:
Cover *cover_;
float last_position_{NAN};
};
@@ -124,9 +125,9 @@ using CoverClosedTrigger = CoverPositionTrigger<false>;
template<CoverOperation OP> class CoverTrigger : public Trigger<> {
public:
CoverTrigger(Cover *a_cover) {
a_cover->add_on_state_callback([this, a_cover]() {
auto current_op = a_cover->current_operation;
CoverTrigger(Cover *a_cover) : cover_(a_cover) {
a_cover->add_on_state_callback([this]() {
auto current_op = this->cover_->current_operation;
if (current_op == OP) {
if (!this->last_operation_.has_value() || this->last_operation_.value() != OP) {
this->trigger();
@@ -137,6 +138,7 @@ template<CoverOperation OP> class CoverTrigger : public Trigger<> {
}
protected:
Cover *cover_;
optional<CoverOperation> last_operation_{};
};
} // namespace esphome::cover
+5 -2
View File
@@ -33,9 +33,12 @@ class DateTimeBase : public EntityBase {
class DateTimeStateTrigger : public Trigger<ESPTime> {
public:
explicit DateTimeStateTrigger(DateTimeBase *parent) {
parent->add_on_state_callback([this, parent]() { this->trigger(parent->state_as_esptime()); });
explicit DateTimeStateTrigger(DateTimeBase *parent) : parent_(parent) {
parent->add_on_state_callback([this]() { this->trigger(this->parent_->state_as_esptime()); });
}
protected:
DateTimeBase *parent_;
};
} // namespace esphome::datetime
@@ -96,37 +96,52 @@ template<typename... Ts> class IsActiveCondition : public Condition<Ts...> {
class DisplayMenuOnEnterTrigger : public Trigger<const MenuItem *> {
public:
explicit DisplayMenuOnEnterTrigger(MenuItem *parent) {
parent->add_on_enter_callback([this, parent]() { this->trigger(parent); });
explicit DisplayMenuOnEnterTrigger(MenuItem *parent) : parent_(parent) {
parent->add_on_enter_callback([this]() { this->trigger(this->parent_); });
}
protected:
MenuItem *parent_;
};
class DisplayMenuOnLeaveTrigger : public Trigger<const MenuItem *> {
public:
explicit DisplayMenuOnLeaveTrigger(MenuItem *parent) {
parent->add_on_leave_callback([this, parent]() { this->trigger(parent); });
explicit DisplayMenuOnLeaveTrigger(MenuItem *parent) : parent_(parent) {
parent->add_on_leave_callback([this]() { this->trigger(this->parent_); });
}
protected:
MenuItem *parent_;
};
class DisplayMenuOnValueTrigger : public Trigger<const MenuItem *> {
public:
explicit DisplayMenuOnValueTrigger(MenuItem *parent) {
parent->add_on_value_callback([this, parent]() { this->trigger(parent); });
explicit DisplayMenuOnValueTrigger(MenuItem *parent) : parent_(parent) {
parent->add_on_value_callback([this]() { this->trigger(this->parent_); });
}
protected:
MenuItem *parent_;
};
class DisplayMenuOnNextTrigger : public Trigger<const MenuItem *> {
public:
explicit DisplayMenuOnNextTrigger(MenuItemCustom *parent) {
parent->add_on_next_callback([this, parent]() { this->trigger(parent); });
explicit DisplayMenuOnNextTrigger(MenuItemCustom *parent) : parent_(parent) {
parent->add_on_next_callback([this]() { this->trigger(this->parent_); });
}
protected:
MenuItemCustom *parent_;
};
class DisplayMenuOnPrevTrigger : public Trigger<const MenuItem *> {
public:
explicit DisplayMenuOnPrevTrigger(MenuItemCustom *parent) {
parent->add_on_prev_callback([this, parent]() { this->trigger(parent); });
explicit DisplayMenuOnPrevTrigger(MenuItemCustom *parent) : parent_(parent) {
parent->add_on_prev_callback([this]() { this->trigger(this->parent_); });
}
protected:
MenuItemCustom *parent_;
};
} // namespace display_menu_base
+12
View File
@@ -1920,6 +1920,18 @@ async def to_code(config):
add_idf_sdkconfig_option("CONFIG_MBEDTLS_SHA384_C", False)
add_idf_sdkconfig_option("CONFIG_MBEDTLS_SHA512_C", False)
# Disable PicolibC Newlib compatibility shim on IDF 6.0+
# IDF 6.0 switched from Newlib to PicolibC. The shim provides thread-local
# stdin/stdout/stderr and getreent() for code compiled against Newlib.
# ESPHome doesn't link against Newlib-built libraries that use stdio.
# If a component needs it (e.g. precompiled Newlib binaries), re-enable via:
# esp32:
# framework:
# sdkconfig_options:
# CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY: "y"
if idf_version() >= cv.Version(6, 0, 0):
add_idf_sdkconfig_option("CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY", False)
# Disable regi2c control functions in IRAM
# Only needed if using analog peripherals (ADC, DAC, etc.) from ISRs while cache is disabled
if advanced[CONF_DISABLE_REGI2C_IN_IRAM]:
+2 -2
View File
@@ -2,6 +2,7 @@
#include "esphome/core/defines.h"
#include "crash_handler.h"
#include "esphome/core/application.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "preferences.h"
@@ -15,7 +16,6 @@
#include <freertos/task.h>
void setup(); // NOLINT(readability-redundant-declaration)
void loop(); // NOLINT(readability-redundant-declaration)
// Weak stub for initArduino - overridden when the Arduino component is present
extern "C" __attribute__((weak)) void initArduino() {}
@@ -65,7 +65,7 @@ TaskHandle_t loop_task_handle = nullptr; // NOLINT(cppcoreguidelines-avoid-non-
void loop_task(void *pv_params) {
setup();
while (true) {
loop();
App.loop();
}
}
+5 -1
View File
@@ -28,7 +28,11 @@ def esp32_validate_gpio_pin(value: int) -> int:
raise cv.Invalid(f"Invalid pin number: {value} (must be 0-39)")
if value in _ESP_SDIO_PINS:
raise cv.Invalid(
f"This pin cannot be used on ESP32s and is already used by the flash interface (function: {_ESP_SDIO_PINS[value]})"
f"This pin cannot be used on ESP32s and is already used by the flash interface"
f" (function: {_ESP_SDIO_PINS[value]})."
f" If you are using an ESP32 module that uses a different flash pin"
f" configuration (e.g. ESP32-PICO-V3-02), you can set"
f" 'ignore_pin_validation_error: true' to bypass this check."
)
if 9 <= value <= 10:
_LOGGER.warning(
+36 -11
View File
@@ -9,12 +9,14 @@
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
#include "esphome/core/log.h"
#include "esp_random.h"
#include "esp_system.h"
namespace esphome {
uint32_t random_uint32() { return esp_random(); }
static const char *const TAG = "esp32";
bool random_bytes(uint8_t *data, size_t len) {
esp_fill_random(data, len);
return true;
@@ -64,22 +66,43 @@ LwIPLock::~LwIPLock() {
#endif
}
/// Read MAC and validate both the return code and content.
static bool read_valid_mac(uint8_t *mac, esp_err_t err) { return err == ESP_OK && mac_address_is_valid(mac); }
static constexpr size_t MAC_ADDRESS_SIZE_BITS = MAC_ADDRESS_SIZE * 8; // 48 bits
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
#if defined(CONFIG_SOC_IEEE802154_SUPPORTED)
// When CONFIG_SOC_IEEE802154_SUPPORTED is defined, esp_efuse_mac_get_default
// returns the 802.15.4 EUI-64 address, so we read directly from eFuse instead.
if (has_custom_mac_address()) {
esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48);
} else {
esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, 48);
// Both paths already read raw eFuse bytes, so there is no CRC-bypass fallback
// (unlike the non-IEEE802154 path where esp_efuse_mac_get_default does CRC checks).
if (has_custom_mac_address() &&
read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS))) {
return;
}
if (read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, MAC_ADDRESS_SIZE_BITS))) {
return;
}
#else
if (has_custom_mac_address()) {
esp_efuse_mac_get_custom(mac);
} else {
esp_efuse_mac_get_default(mac);
if (has_custom_mac_address() && read_valid_mac(mac, esp_efuse_mac_get_custom(mac))) {
return;
}
if (read_valid_mac(mac, esp_efuse_mac_get_default(mac))) {
return;
}
// Default MAC read failed (e.g., eFuse CRC error) - try reading raw eFuse bytes
// directly, bypassing CRC validation. A MAC that passes mac_address_is_valid()
// (non-zero, non-broadcast, unicast) is almost certainly the real factory MAC
// with a corrupted CRC byte, which is far better than returning garbage or zeros.
if (read_valid_mac(mac, esp_efuse_read_field_blob(ESP_EFUSE_MAC_FACTORY, mac, MAC_ADDRESS_SIZE_BITS))) {
ESP_LOGW(TAG, "eFuse MAC CRC failed but raw bytes appear valid - using raw eFuse MAC");
return;
}
#endif
// All methods failed - zero the MAC rather than returning garbage
ESP_LOGE(TAG, "Failed to read a valid MAC address from eFuse");
memset(mac, 0, MAC_ADDRESS_SIZE);
}
void set_mac_address(uint8_t *mac) { esp_base_mac_addr_set(mac); }
@@ -89,9 +112,11 @@ bool has_custom_mac_address() {
uint8_t mac[6];
// do not use 'esp_efuse_mac_get_custom(mac)' because it drops an error in the logs whenever it fails
#ifndef USE_ESP32_VARIANT_ESP32
return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
return (esp_efuse_read_field_blob(ESP_EFUSE_USER_DATA_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS) == ESP_OK) &&
mac_address_is_valid(mac);
#else
return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, 48) == ESP_OK) && mac_address_is_valid(mac);
return (esp_efuse_read_field_blob(ESP_EFUSE_MAC_CUSTOM, mac, MAC_ADDRESS_SIZE_BITS) == ESP_OK) &&
mac_address_is_valid(mac);
#endif
#else
return false;
+42 -28
View File
@@ -4,12 +4,40 @@ import re
# pylint: disable=E0602
Import("env") # noqa
# IRAM size for testing mode (2MB - large enough to accommodate grouped tests)
TESTING_IRAM_SIZE = 0x200000
# Memory sizes for testing mode (large enough to accommodate grouped tests)
TESTING_IRAM_SIZE = 0x200000 # 2MB
TESTING_DRAM_SIZE = 0x200000 # 2MB
def patch_segment(content, segment_name, new_size):
"""Patch a memory segment's length in linker script content.
Handles both single-line and multi-line segment definitions, e.g.:
iram0_0_seg (RX) : org = 0x40080000, len = 0x20000 + 0x0
or split across lines:
dram0_0_seg (RW) : org = 0x3FFB0000 + 0xdb5c,
len = 0x2c200 - 0xdb5c
Args:
content: Full linker script content as string
segment_name: Name of the segment (e.g., 'iram0_0_seg')
new_size: New size as integer
Returns:
Tuple of (new_content, was_patched)
"""
# Match segment name through to "len = <value>" allowing newlines between org and len
pattern = rf'({re.escape(segment_name)}\s*\([^)]*\)\s*:\s*org\s*=\s*.+?,\s*len\s*=\s*)(\S+[^\n]*)'
if match := re.search(pattern, content, re.DOTALL):
replacement = f"{match.group(1)}{new_size:#x}"
new_content = content[:match.start()] + replacement + content[match.end():]
if new_content != content:
return new_content, True
return content, False
def patch_idf_linker_script(source, target, env):
"""Patch ESP-IDF linker script to increase IRAM size for testing mode."""
"""Patch ESP-IDF linker script to increase IRAM and DRAM size for testing mode."""
# Check if we're in testing mode by looking for the define
build_flags = env.get("BUILD_FLAGS", [])
testing_mode = any("-DESPHOME_TESTING_MODE" in flag for flag in build_flags)
@@ -34,36 +62,22 @@ def patch_idf_linker_script(source, target, env):
print(f"ESPHome: Error reading linker script: {e}")
return
# Check if this file contains iram0_0_seg
if 'iram0_0_seg' not in content:
print(f"ESPHome: Warning - iram0_0_seg not found in {memory_ld}")
return
patches = []
# Look for iram0_0_seg definition and increase its length
# ESP-IDF format can be:
# iram0_0_seg (RX) : org = 0x40080000, len = 0x20000 + 0x0
# or more complex with nested parentheses:
# iram0_0_seg (RX) : org = (0x40370000 + 0x4000), len = (((0x403CB700 - (0x40378000 - 0x3FC88000)) - 0x3FC88000) + 0x8000 - 0x4000)
# We want to change len to TESTING_IRAM_SIZE for testing
content, patched = patch_segment(content, 'iram0_0_seg', TESTING_IRAM_SIZE)
if patched:
patches.append(f"IRAM={TESTING_IRAM_SIZE:#x}")
# Use a more robust approach: find the line and manually parse it
lines = content.split('\n')
for i, line in enumerate(lines):
if 'iram0_0_seg' in line and 'len' in line:
# Find the position of "len = " and replace everything after it until the end of the statement
match = re.search(r'(iram0_0_seg\s*\([^)]*\)\s*:\s*org\s*=\s*(?:\([^)]+\)|0x[0-9a-fA-F]+)\s*,\s*len\s*=\s*)(.+?)(\s*)$', line)
if match:
lines[i] = f"{match.group(1)}{TESTING_IRAM_SIZE:#x}{match.group(3)}"
break
content, patched = patch_segment(content, 'dram0_0_seg', TESTING_DRAM_SIZE)
if patched:
patches.append(f"DRAM={TESTING_DRAM_SIZE:#x}")
updated = '\n'.join(lines)
if updated != content:
if patches:
with open(memory_ld, "w") as f:
f.write(updated)
print(f"ESPHome: Patched IRAM size to {TESTING_IRAM_SIZE:#x} in {memory_ld} for testing mode")
f.write(content)
print(f"ESPHome: Patched {', '.join(patches)} in {memory_ld} for testing mode")
else:
print(f"ESPHome: Warning - could not patch iram0_0_seg in {memory_ld}")
print(f"ESPHome: Warning - could not patch memory segments in {memory_ld}")
# Hook into the build process before linking
+1 -1
View File
@@ -10,7 +10,7 @@
namespace esphome::esp32 {
static const char *const TAG = "esp32.preferences";
static const char *const TAG = "preferences";
// Buffer size for converting uint32_t to string: max "4294967295" (10 chars) + null terminator + 1 padding
static constexpr size_t KEY_BUFFER_SIZE = 12;
+35 -20
View File
@@ -12,58 +12,73 @@ namespace esp32_improv {
class ESP32ImprovProvisionedTrigger : public Trigger<> {
public:
explicit ESP32ImprovProvisionedTrigger(ESP32ImprovComponent *parent) {
parent->add_on_state_callback([this, parent](improv::State state, improv::Error error) {
if (state == improv::STATE_PROVISIONED && !parent->is_failed()) {
trigger();
explicit ESP32ImprovProvisionedTrigger(ESP32ImprovComponent *parent) : parent_(parent) {
parent->add_on_state_callback([this](improv::State state, improv::Error error) {
if (state == improv::STATE_PROVISIONED && !this->parent_->is_failed()) {
this->trigger();
}
});
}
protected:
ESP32ImprovComponent *parent_;
};
class ESP32ImprovProvisioningTrigger : public Trigger<> {
public:
explicit ESP32ImprovProvisioningTrigger(ESP32ImprovComponent *parent) {
parent->add_on_state_callback([this, parent](improv::State state, improv::Error error) {
if (state == improv::STATE_PROVISIONING && !parent->is_failed()) {
trigger();
explicit ESP32ImprovProvisioningTrigger(ESP32ImprovComponent *parent) : parent_(parent) {
parent->add_on_state_callback([this](improv::State state, improv::Error error) {
if (state == improv::STATE_PROVISIONING && !this->parent_->is_failed()) {
this->trigger();
}
});
}
protected:
ESP32ImprovComponent *parent_;
};
class ESP32ImprovStartTrigger : public Trigger<> {
public:
explicit ESP32ImprovStartTrigger(ESP32ImprovComponent *parent) {
parent->add_on_state_callback([this, parent](improv::State state, improv::Error error) {
explicit ESP32ImprovStartTrigger(ESP32ImprovComponent *parent) : parent_(parent) {
parent->add_on_state_callback([this](improv::State state, improv::Error error) {
if ((state == improv::STATE_AUTHORIZED || state == improv::STATE_AWAITING_AUTHORIZATION) &&
!parent->is_failed()) {
trigger();
!this->parent_->is_failed()) {
this->trigger();
}
});
}
protected:
ESP32ImprovComponent *parent_;
};
class ESP32ImprovStateTrigger : public Trigger<improv::State, improv::Error> {
public:
explicit ESP32ImprovStateTrigger(ESP32ImprovComponent *parent) {
parent->add_on_state_callback([this, parent](improv::State state, improv::Error error) {
if (!parent->is_failed()) {
trigger(state, error);
explicit ESP32ImprovStateTrigger(ESP32ImprovComponent *parent) : parent_(parent) {
parent->add_on_state_callback([this](improv::State state, improv::Error error) {
if (!this->parent_->is_failed()) {
this->trigger(state, error);
}
});
}
protected:
ESP32ImprovComponent *parent_;
};
class ESP32ImprovStoppedTrigger : public Trigger<> {
public:
explicit ESP32ImprovStoppedTrigger(ESP32ImprovComponent *parent) {
parent->add_on_state_callback([this, parent](improv::State state, improv::Error error) {
if (state == improv::STATE_STOPPED && !parent->is_failed()) {
trigger();
explicit ESP32ImprovStoppedTrigger(ESP32ImprovComponent *parent) : parent_(parent) {
parent->add_on_state_callback([this](improv::State state, improv::Error error) {
if (state == improv::STATE_STOPPED && !this->parent_->is_failed()) {
this->trigger();
}
});
}
protected:
ESP32ImprovComponent *parent_;
};
} // namespace esp32_improv
@@ -360,11 +360,16 @@ void ESP32TouchComponent::loop() {
}
// Publish initial OFF state for sensors that haven't received events yet
bool all_initial_published = true;
for (auto *child : this->children_) {
this->publish_initial_state_if_needed_(child, now);
if (!child->initial_state_published_) {
all_initial_published = false;
}
}
if (!this->setup_mode_) {
// Only disable loop once all initial states are published
if (!this->setup_mode_ && all_initial_published) {
this->disable_loop();
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ extern "C" {
namespace esphome::esp8266 {
static const char *const TAG = "esp8266.preferences";
static const char *const TAG = "preferences";
static constexpr uint32_t ESP_RTC_USER_MEM_START = 0x60001200;
static constexpr uint32_t ESP_RTC_USER_MEM_SIZE_WORDS = 128;
@@ -18,12 +18,6 @@ void EthernetComponent::set_type(EthernetType type) { this->type_ = type; }
void EthernetComponent::set_manual_ip(const ManualIP &manual_ip) { this->manual_ip_ = manual_ip; }
#endif
// set_use_address() is guaranteed to be called during component setup by Python code generation,
// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
const char *EthernetComponent::get_use_address() const { return this->use_address_; }
void EthernetComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
#ifdef USE_ETHERNET_IP_STATE_LISTENERS
void EthernetComponent::notify_ip_state_listeners_() {
auto ips = this->get_ip_addresses();
@@ -103,8 +103,8 @@ class EthernetComponent final : public Component {
network::IPAddresses get_ip_addresses();
network::IPAddress get_dns_address(uint8_t num);
const char *get_use_address() const;
void set_use_address(const char *use_address);
const char *get_use_address() const { return this->use_address_; }
void set_use_address(const char *use_address) { this->use_address_ = use_address; }
void get_eth_mac_address_raw(uint8_t *mac);
// Remove before 2026.9.0
ESPDEPRECATED("Use get_eth_mac_address_pretty_into_buffer() instead. Removed in 2026.9.0", "2026.3.0")
+29 -20
View File
@@ -113,16 +113,19 @@ template<typename... Ts> class FanIsOffCondition : public Condition<Ts...> {
class FanStateTrigger : public Trigger<Fan *> {
public:
FanStateTrigger(Fan *state) {
state->add_on_state_callback([this, state]() { this->trigger(state); });
FanStateTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() { this->trigger(this->fan_); });
}
protected:
Fan *fan_;
};
class FanTurnOnTrigger : public Trigger<> {
public:
FanTurnOnTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto is_on = state->state;
FanTurnOnTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto is_on = this->fan_->state;
auto should_trigger = is_on && !this->last_on_;
this->last_on_ = is_on;
if (should_trigger) {
@@ -133,14 +136,15 @@ class FanTurnOnTrigger : public Trigger<> {
}
protected:
Fan *fan_;
bool last_on_;
};
class FanTurnOffTrigger : public Trigger<> {
public:
FanTurnOffTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto is_on = state->state;
FanTurnOffTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto is_on = this->fan_->state;
auto should_trigger = !is_on && this->last_on_;
this->last_on_ = is_on;
if (should_trigger) {
@@ -151,14 +155,15 @@ class FanTurnOffTrigger : public Trigger<> {
}
protected:
Fan *fan_;
bool last_on_;
};
class FanDirectionSetTrigger : public Trigger<FanDirection> {
public:
FanDirectionSetTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto direction = state->direction;
FanDirectionSetTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto direction = this->fan_->direction;
auto should_trigger = direction != this->last_direction_;
this->last_direction_ = direction;
if (should_trigger) {
@@ -169,14 +174,15 @@ class FanDirectionSetTrigger : public Trigger<FanDirection> {
}
protected:
Fan *fan_;
FanDirection last_direction_;
};
class FanOscillatingSetTrigger : public Trigger<bool> {
public:
FanOscillatingSetTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto oscillating = state->oscillating;
FanOscillatingSetTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto oscillating = this->fan_->oscillating;
auto should_trigger = oscillating != this->last_oscillating_;
this->last_oscillating_ = oscillating;
if (should_trigger) {
@@ -187,14 +193,15 @@ class FanOscillatingSetTrigger : public Trigger<bool> {
}
protected:
Fan *fan_;
bool last_oscillating_;
};
class FanSpeedSetTrigger : public Trigger<int> {
public:
FanSpeedSetTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto speed = state->speed;
FanSpeedSetTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto speed = this->fan_->speed;
auto should_trigger = speed != this->last_speed_;
this->last_speed_ = speed;
if (should_trigger) {
@@ -205,14 +212,15 @@ class FanSpeedSetTrigger : public Trigger<int> {
}
protected:
Fan *fan_;
int last_speed_;
};
class FanPresetSetTrigger : public Trigger<StringRef> {
public:
FanPresetSetTrigger(Fan *state) {
state->add_on_state_callback([this, state]() {
auto preset_mode = state->get_preset_mode();
FanPresetSetTrigger(Fan *state) : fan_(state) {
state->add_on_state_callback([this]() {
auto preset_mode = this->fan_->get_preset_mode();
auto should_trigger = preset_mode != this->last_preset_mode_;
this->last_preset_mode_ = preset_mode;
if (should_trigger) {
@@ -223,6 +231,7 @@ class FanPresetSetTrigger : public Trigger<StringRef> {
}
protected:
Fan *fan_;
StringRef last_preset_mode_{};
};
@@ -5,6 +5,7 @@ namespace esphome {
namespace gpio {
static const char *const TAG = "switch.gpio";
static constexpr uint32_t INTERLOCK_TIMEOUT_ID = 0;
float GPIOSwitch::get_setup_priority() const { return setup_priority::HARDWARE; }
void GPIOSwitch::setup() {
@@ -51,7 +52,7 @@ void GPIOSwitch::write_state(bool state) {
}
}
if (found && this->interlock_wait_time_ != 0) {
this->set_timeout("interlock", this->interlock_wait_time_, [this, state] {
this->set_timeout(INTERLOCK_TIMEOUT_ID, this->interlock_wait_time_, [this, state] {
// Don't write directly, call the function again
// (some other switch may have changed state while we were waiting)
this->write_state(state);
@@ -61,7 +62,7 @@ void GPIOSwitch::write_state(bool state) {
} else if (this->interlock_wait_time_ != 0) {
// If we are switched off during the interlock wait time, cancel any pending
// re-activations
this->cancel_timeout("interlock");
this->cancel_timeout(INTERLOCK_TIMEOUT_ID);
}
this->pin_->digital_write(state);
@@ -75,9 +75,12 @@ class GraphicalDisplayMenu : public display_menu_base::DisplayMenuComponent {
class GraphicalDisplayMenuOnRedrawTrigger : public Trigger<const GraphicalDisplayMenu *> {
public:
explicit GraphicalDisplayMenuOnRedrawTrigger(GraphicalDisplayMenu *parent) {
parent->add_on_redraw_callback([this, parent]() { this->trigger(parent); });
explicit GraphicalDisplayMenuOnRedrawTrigger(GraphicalDisplayMenu *parent) : parent_(parent) {
parent->add_on_redraw_callback([this]() { this->trigger(this->parent_); });
}
protected:
GraphicalDisplayMenu *parent_;
};
} // namespace graphical_display_menu
-9
View File
@@ -8,8 +8,6 @@
#include <sys/ioctl.h>
#endif
#include <unistd.h>
#include <limits>
#include <random>
#include "esphome/core/defines.h"
#include "esphome/core/log.h"
@@ -18,13 +16,6 @@ namespace esphome {
static const char *const TAG = "helpers.host";
uint32_t random_uint32() {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<uint32_t> dist(0, std::numeric_limits<uint32_t>::max());
return dist(rng);
}
bool random_bytes(uint8_t *data, size_t len) {
FILE *fp = fopen("/dev/urandom", "r");
if (fp == nullptr) {
+1 -1
View File
@@ -9,7 +9,7 @@
namespace esphome::host {
namespace fs = std::filesystem;
static const char *const TAG = "host.preferences";
static const char *const TAG = "preferences";
void HostPreferences::setup_() {
if (this->setup_complete_)
+5 -4
View File
@@ -530,10 +530,11 @@ void LD2450Component::handle_periodic_data_() {
}
#endif
// Store target info for zone target count
this->target_info_[index].x = tx;
this->target_info_[index].y = ty;
this->target_info_[index].is_moving = is_moving;
// Store target info for zone target count. Zero out untracked targets (td==0)
// so stale coordinates don't produce ghost counts in count_targets_in_zone_().
this->target_info_[index].x = (td > 0) ? tx : 0;
this->target_info_[index].y = (td > 0) ? ty : 0;
this->target_info_[index].is_moving = (td > 0) && is_moving;
} // End loop thru targets
+2
View File
@@ -193,7 +193,9 @@ void LEDCOutput::setup() {
chan_conf.gpio_num = static_cast<gpio_num_t>(this->pin_->get_pin());
chan_conf.speed_mode = speed_mode;
chan_conf.channel = chan_num;
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0)
chan_conf.intr_type = LEDC_INTR_DISABLE;
#endif
chan_conf.timer_sel = timer_num;
chan_conf.duty = this->inverted_ == this->pin_->is_inverted() ? 0 : (1U << this->bit_depth_);
chan_conf.hpoint = hpoint;
-2
View File
@@ -8,8 +8,6 @@
namespace esphome {
uint32_t random_uint32() { return rand(); }
bool random_bytes(uint8_t *data, size_t len) {
lt_rand_bytes(data, len);
return true;
+1 -1
View File
@@ -9,7 +9,7 @@
namespace esphome::libretiny {
static const char *const TAG = "lt.preferences";
static const char *const TAG = "preferences";
// Buffer size for converting uint32_t to string: max "4294967295" (10 chars) + null terminator + 1 padding
static constexpr size_t KEY_BUFFER_SIZE = 12;
+21 -7
View File
@@ -81,18 +81,32 @@ def _get_data() -> LightData:
return CORE.data[DOMAIN]
def generate_gamma_table(gamma_correct: float) -> list[HexInt]:
"""Generate a 256-entry uint16 gamma lookup table.
For gamma > 0, non-zero indices are clamped to a minimum of 1 to preserve
the invariant that non-zero input always produces non-zero output. Without
this, small brightness values (e.g. 1%) get quantized to exactly 0.0,
which breaks zero_means_zero logic in FloatOutput.
"""
if gamma_correct > 0:
return [
HexInt(
max(1, min(65535, int(round((i / 255.0) ** gamma_correct * 65535))))
if i > 0
else HexInt(0)
)
for i in range(256)
]
return [HexInt(int(round(i / 255.0 * 65535))) for i in range(256)]
def _get_or_create_gamma_table(gamma_correct):
data = _get_data()
if gamma_correct in data.gamma_tables:
return data.gamma_tables[gamma_correct]
if gamma_correct > 0:
forward = [
HexInt(min(65535, int(round((i / 255.0) ** gamma_correct * 65535))))
for i in range(256)
]
else:
forward = [HexInt(int(round(i / 255.0 * 65535))) for i in range(256)]
forward = generate_gamma_table(gamma_correct)
gamma_str = f"{gamma_correct}".replace(".", "_")
fwd_id = ID(f"gamma_{gamma_str}_fwd", is_declaration=True, type=cg.uint16)
@@ -154,6 +154,16 @@ class LightColorValues {
}
/// Convert these light color values to an CWWW representation with the given parameters.
///
/// Note on gamma and constant_brightness: This method operates on the raw/internal channel
/// values stored in this object. For cold_white_ and warm_white_ specifically, these
/// may already be gamma-uncorrected when derived from a color_temperature value.
/// For constant_brightness=false, additional gamma for the output can be applied after
/// this method since gamma commutes with simple multiplication. For constant_brightness=true,
/// the caller (LightState::current_values_as_cwww) must apply gamma to the individual
/// channel values BEFORE the balancing formula, because the nonlinear max/sum ratio does
/// not commute with gamma. See LightState::current_values_as_cwww() for the correct
/// implementation.
void as_cwww(float *cold_white, float *warm_white, bool constant_brightness = false) const {
if (this->color_mode_ & ColorCapability::COLD_WARM_WHITE) {
const float cw_level = this->cold_white_;
+41 -6
View File
@@ -223,12 +223,11 @@ void LightState::current_values_as_rgbw(float *red, float *green, float *blue, f
}
void LightState::current_values_as_rgbww(float *red, float *green, float *blue, float *cold_white, float *warm_white,
bool constant_brightness) {
this->current_values.as_rgbww(red, green, blue, cold_white, warm_white, constant_brightness);
this->current_values.as_rgb(red, green, blue);
*red = this->gamma_correct_lut(*red);
*green = this->gamma_correct_lut(*green);
*blue = this->gamma_correct_lut(*blue);
*cold_white = this->gamma_correct_lut(*cold_white);
*warm_white = this->gamma_correct_lut(*warm_white);
this->current_values_as_cwww(cold_white, warm_white, constant_brightness);
}
void LightState::current_values_as_rgbct(float *red, float *green, float *blue, float *color_temperature,
float *white_brightness) {
@@ -241,9 +240,45 @@ void LightState::current_values_as_rgbct(float *red, float *green, float *blue,
*white_brightness = this->gamma_correct_lut(*white_brightness);
}
void LightState::current_values_as_cwww(float *cold_white, float *warm_white, bool constant_brightness) {
this->current_values.as_cwww(cold_white, warm_white, constant_brightness);
*cold_white = this->gamma_correct_lut(*cold_white);
*warm_white = this->gamma_correct_lut(*warm_white);
if (!constant_brightness) {
// Without constant_brightness, gamma commutes with simple multiplication:
// gamma(white_level * cw) = gamma(white_level) * gamma(cw)
// (since gamma(a*b) = (a*b)^g = a^g * b^g = gamma(a) * gamma(b))
// so applying gamma after is mathematically equivalent and simpler.
this->current_values.as_cwww(cold_white, warm_white, false);
*cold_white = this->gamma_correct_lut(*cold_white);
*warm_white = this->gamma_correct_lut(*warm_white);
return;
}
// For constant_brightness mode, gamma MUST be applied to the individual
// channel values BEFORE the balancing formula (max/sum ratio), not after.
//
// Why: The cold_white_ and warm_white_ values stored in LightColorValues
// are gamma-uncorrected (see transform_parameters_() which applies
// gamma_uncorrect to the linear CW/WW fractions derived from color
// temperature). Applying gamma_correct here recovers the original linear
// fractions, which the constant_brightness formula then uses to distribute
// power evenly. The max/sum formula ensures cold+warm PWM output sums to
// a constant, keeping total power (and perceived brightness) the same
// across all color temperatures.
//
// Applying gamma AFTER the formula would be incorrect because gamma is
// nonlinear: gamma(a/b) != gamma(a)/gamma(b), so the carefully balanced
// ratio would be distorted, causing a severe brightness dip at mid-range
// color temperatures.
const auto &v = this->current_values;
if (!(v.get_color_mode() & ColorCapability::COLD_WARM_WHITE)) {
*cold_white = *warm_white = 0;
return;
}
const float cw_level = this->gamma_correct_lut(v.get_cold_white());
const float ww_level = this->gamma_correct_lut(v.get_warm_white());
const float white_level = this->gamma_correct_lut(v.get_state() * v.get_brightness());
const float sum = cw_level > 0 || ww_level > 0 ? cw_level + ww_level : 1; // Don't divide by zero.
*cold_white = white_level * std::max(cw_level, ww_level) * cw_level / sum;
*warm_white = white_level * std::max(cw_level, ww_level) * ww_level / sum;
}
void LightState::current_values_as_ct(float *color_temperature, float *white_brightness) {
auto traits = this->get_traits();
+6 -3
View File
@@ -51,13 +51,16 @@ template<typename... Ts> class LockCondition : public Condition<Ts...> {
template<LockState State> class LockStateTrigger : public Trigger<> {
public:
explicit LockStateTrigger(Lock *a_lock) {
a_lock->add_on_state_callback([this, a_lock]() {
if (a_lock->state == State) {
explicit LockStateTrigger(Lock *a_lock) : lock_(a_lock) {
a_lock->add_on_state_callback([this]() {
if (this->lock_->state == State) {
this->trigger();
}
});
}
protected:
Lock *lock_;
};
using LockLockTrigger = LockStateTrigger<LockState::LOCK_STATE_LOCKED>;
+45 -24
View File
@@ -56,6 +56,7 @@ from esphome.const import (
PlatformFramework,
)
from esphome.core import CORE, CoroPriority, Lambda, coroutine_with_priority
from esphome.types import ConfigType
CODEOWNERS = ["@esphome/core"]
logger_ns = cg.esphome_ns.namespace("logger")
@@ -323,19 +324,34 @@ CONFIG_SCHEMA = cv.All(
)
@coroutine_with_priority(CoroPriority.DIAGNOSTICS)
async def to_code(config):
baud_rate = config[CONF_BAUD_RATE]
@coroutine_with_priority(CoroPriority.EARLY_INIT)
async def to_code(config: ConfigType) -> None:
baud_rate: int = config[CONF_BAUD_RATE]
level = config[CONF_LEVEL]
CORE.data.setdefault(CONF_LOGGER, {})[CONF_LEVEL] = level
initial_level = LOG_LEVELS[config.get(CONF_INITIAL_LEVEL, level)]
tx_buffer_size = config[CONF_TX_BUFFER_SIZE]
cg.add_define("ESPHOME_LOGGER_TX_BUFFER_SIZE", tx_buffer_size)
log = cg.new_Pvariable(
config[CONF_ID],
baud_rate,
)
if CORE.is_esp32:
# Determine task log buffer size and define USE_ESPHOME_TASK_LOG_BUFFER early
# so the constructor can allocate the buffer immediately, preventing a race
# where another task logs before the buffer is initialized.
task_log_buffer_size = 0
if CORE.is_esp32 or CORE.is_libretiny or CORE.is_nrf52:
task_log_buffer_size = config[CONF_TASK_LOG_BUFFER_SIZE]
elif CORE.is_host:
task_log_buffer_size = 64 # Fixed 64 slots for host
if task_log_buffer_size > 0:
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
log = cg.new_Pvariable(
config[CONF_ID],
baud_rate,
task_log_buffer_size,
)
else:
log = cg.new_Pvariable(
config[CONF_ID],
baud_rate,
)
if CORE.is_esp32 or CORE.is_host:
cg.add(log.create_pthread_key())
# set_uart_selection() must be called before pre_setup() because
# pre_setup() switches on uart_ to decide which hardware to initialize
@@ -347,24 +363,28 @@ async def to_code(config):
HARDWARE_UART_TO_UART_SELECTION[config[CONF_HARDWARE_UART]]
)
)
# pre_setup() must be called before init_log_buffer() because
# init_log_buffer() calls disable_loop() which may log at VV level,
# and global_logger must be set before any logging occurs.
# pre_setup() sets global_logger and must run before any other code
# that may call ESP_LOG* (e.g. setup_preferences contains ESP_LOGVV).
cg.add(log.pre_setup())
if CORE.is_esp32 or CORE.is_libretiny or CORE.is_nrf52:
task_log_buffer_size = config[CONF_TASK_LOG_BUFFER_SIZE]
if task_log_buffer_size > 0:
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
cg.add(log.init_log_buffer(task_log_buffer_size))
if CORE.using_zephyr:
zephyr_add_prj_conf("MPSC_PBUF", True)
elif CORE.is_host:
cg.add(log.create_pthread_key())
cg.add_define("USE_ESPHOME_TASK_LOG_BUFFER")
cg.add(log.init_log_buffer(64)) # Fixed 64 slots for host
initial_level = LOG_LEVELS[config.get(CONF_INITIAL_LEVEL, level)]
cg.add(log.set_log_level(initial_level))
# Schedule the rest of logger setup at DIAGNOSTICS priority, after
# Application is constructed (CORE priority) but before most components.
CORE.add_job(_late_logger_init, config)
@coroutine_with_priority(CoroPriority.DIAGNOSTICS)
async def _late_logger_init(config: ConfigType) -> None:
"""Finish logger setup after Application is constructed."""
log = await cg.get_variable(config[CONF_ID])
level = config[CONF_LEVEL]
baud_rate: int = config[CONF_BAUD_RATE]
if CORE.using_zephyr:
task_log_buffer_size = config.get(CONF_TASK_LOG_BUFFER_SIZE, 0)
if task_log_buffer_size > 0:
zephyr_add_prj_conf("MPSC_PBUF", True)
# Enable runtime tag levels if logs are configured or explicitly enabled
logs_config = config[CONF_LOGS]
if logs_config or config[CONF_RUNTIME_TAG_LEVELS]:
@@ -594,6 +614,7 @@ FILTER_SOURCE_FILES = filter_source_files_from_platform(
PlatformFramework.RTL87XX_ARDUINO,
PlatformFramework.LN882X_ARDUINO,
},
"task_log_buffer_zephyr.cpp": {PlatformFramework.NRF52_ZEPHYR},
}
)
+6 -5
View File
@@ -1,5 +1,6 @@
#pragma once
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
@@ -8,8 +9,8 @@ namespace esphome::logger {
// Maximum header size: 35 bytes fixed + 32 bytes tag + 16 bytes thread name = 83 bytes (45 byte safety margin)
static constexpr uint16_t MAX_HEADER_SIZE = 128;
// ANSI color code last digit (30-38 range, store only last digit to save RAM)
static constexpr char LOG_LEVEL_COLOR_DIGIT[] = {
// ANSI color code last digit (30-38 range, store only last digit to save RAM on ESP8266)
static const char LOG_LEVEL_COLOR_DIGIT[] PROGMEM = {
'\0', // NONE
'1', // ERROR (31 = red)
'3', // WARNING (33 = yellow)
@@ -20,7 +21,7 @@ static constexpr char LOG_LEVEL_COLOR_DIGIT[] = {
'8', // VERY_VERBOSE (38 = white)
};
static constexpr char LOG_LEVEL_LETTER_CHARS[] = {
static const char LOG_LEVEL_LETTER_CHARS[] PROGMEM = {
'\0', // NONE
'E', // ERROR
'W', // WARNING
@@ -64,7 +65,7 @@ struct LogBuffer {
*p++ = 'V'; // VERY_VERBOSE = "VV"
*p++ = 'V';
} else {
*p++ = LOG_LEVEL_LETTER_CHARS[level];
*p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_LETTER_CHARS[level])));
}
}
*p++ = ']';
@@ -184,7 +185,7 @@ struct LogBuffer {
*p++ = (level == 1) ? '1' : '0'; // Only ERROR is bold
*p++ = ';';
*p++ = '3';
*p++ = LOG_LEVEL_COLOR_DIGIT[level];
*p++ = static_cast<char>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&LOG_LEVEL_COLOR_DIGIT[level])));
*p++ = 'm';
}
// Copy string without null terminator, updates pointer in place
+8 -12
View File
@@ -152,29 +152,25 @@ inline uint8_t Logger::level_for(const char *tag) {
return this->current_level_;
}
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
Logger::Logger(uint32_t baud_rate, size_t task_log_buffer_size) : baud_rate_(baud_rate) {
#else
Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
#endif
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
this->main_task_ = xTaskGetCurrentTaskHandle();
#elif defined(USE_ZEPHYR)
this->main_task_ = k_current_get();
#elif defined(USE_HOST)
this->main_thread_ = pthread_self();
this->main_thread_ = pthread_self();
#endif
}
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
void Logger::init_log_buffer(size_t total_buffer_size) {
// Host uses slot count instead of byte size
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory) - allocated once, never freed
this->log_buffer_ = new logger::TaskLogBuffer(total_buffer_size);
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
// Start with loop disabled when using task buffer
// The loop will be enabled automatically when messages arrive
// Zephyr with USB CDC needs loop active to poll port readiness via cdc_loop_()
this->disable_loop_when_buffer_empty_();
this->log_buffer_ = new logger::TaskLogBuffer(task_log_buffer_size);
// Note: we don't disable loop here because the component isn't registered with App yet.
// The loop self-disables on its first iteration when it finds no messages to process.
#endif
}
#endif
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
void Logger::loop() {
+3 -2
View File
@@ -143,9 +143,10 @@ enum UARTSelection : uint8_t {
*/
class Logger final : public Component {
public:
explicit Logger(uint32_t baud_rate);
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
void init_log_buffer(size_t total_buffer_size);
explicit Logger(uint32_t baud_rate, size_t task_log_buffer_size);
#else
explicit Logger(uint32_t baud_rate);
#endif
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
void loop() override;
+1 -1
View File
@@ -280,7 +280,7 @@ SWIPE_TRIGGERS = tuple(
LV_ANIM = LvConstant(
"LV_SCR_LOAD_ANIM_",
"LV_SCREEN_LOAD_ANIM_",
"NONE",
"OVER_LEFT",
"OVER_RIGHT",
+11 -5
View File
@@ -176,7 +176,11 @@ void LvglComponent::show_page(size_t index, lv_scr_load_anim_t anim, uint32_t ti
if (index >= this->pages_.size())
return;
this->current_page_ = index;
lv_scr_load_anim(this->pages_[this->current_page_]->obj, anim, time, 0, false);
if (anim == LV_SCREEN_LOAD_ANIM_NONE) {
lv_scr_load(this->pages_[this->current_page_]->obj);
} else {
lv_scr_load_anim(this->pages_[this->current_page_]->obj, anim, time, 0, false);
}
}
void LvglComponent::show_next_page(lv_scr_load_anim_t anim, uint32_t time) {
@@ -262,8 +266,8 @@ void LvglComponent::flush_cb_(lv_display_t *disp_drv, const lv_area_t *area, uin
if (!this->is_paused()) {
auto now = millis();
this->draw_buffer_(area, reinterpret_cast<lv_color_data *>(color_p));
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", area->x1, area->y1, lv_area_get_width(area),
lv_area_get_height(area), (int) (millis() - now));
ESP_LOGV(TAG, "flush_cb, area=%d/%d, %d/%d took %dms", (int) area->x1, (int) area->y1,
(int) lv_area_get_width(area), (int) lv_area_get_height(area), (int) (millis() - now));
}
lv_display_flush_ready(disp_drv);
}
@@ -619,7 +623,7 @@ void LvglComponent::setup() {
// Rotation will be handled by our drawing function, so reset the display rotation.
for (auto *disp : this->displays_)
disp->set_rotation(display::DISPLAY_ROTATION_0_DEGREES);
this->show_page(0, LV_SCR_LOAD_ANIM_NONE, 0);
this->show_page(0, LV_SCREEN_LOAD_ANIM_NONE, 0);
lv_display_trigger_activity(this->disp_);
}
@@ -667,9 +671,10 @@ void LvglComponent::static_flush_cb(lv_display_t *disp_drv, const lv_area_t *are
* @param e The event data
* @param color_start The color to apply to the first tick
* @param color_end The color to apply to the last tick
* @param width
*/
void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_end, lv_color_t color_start,
lv_color_t color_end, bool local) {
lv_color_t color_end, int width, bool local) {
auto *scale = static_cast<lv_obj_t *>(lv_event_get_target(e));
lv_draw_task_t *task = lv_event_get_draw_task(e);
@@ -687,6 +692,7 @@ void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_
range = 1;
auto ratio = (tick * 255) / range;
line_dsc->color = lv_color_mix(color_end, color_start, ratio);
line_dsc->width += width;
}
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ extern std::string lv_event_code_name_for(lv_event_t *event);
lv_obj_t *lv_container_create(lv_obj_t *parent);
#ifdef USE_LVGL_SCALE
void lv_scale_draw_event_cb(lv_event_t *e, uint16_t range_start, uint16_t range_end, lv_color_t color_start,
lv_color_t color_end, bool local);
lv_color_t color_end, int width, bool local);
#endif
#if LV_COLOR_DEPTH == 16
static const display::ColorBitness LV_BITNESS = display::ColorBitness::COLOR_BITNESS_565;
+12 -11
View File
@@ -177,7 +177,7 @@ INDICATOR_ARC_SCHEMA = cv.Schema(
cv.Optional(CONF_VALUE): lv_float,
cv.Optional(CONF_START_VALUE): lv_float,
cv.Optional(CONF_END_VALUE): lv_float,
cv.Optional(CONF_OPA): opacity,
cv.Optional(CONF_OPA, default=1.0): opacity,
}
).add_extra(cv.has_at_most_one_key(CONF_VALUE, CONF_START_VALUE))
@@ -247,7 +247,7 @@ SCALE_SCHEMA = cv.Schema(
cv.Optional(CONF_RANGE_FROM, default=0.0): lv_int,
cv.Optional(CONF_RANGE_TO, default=100.0): lv_int,
cv.Optional(CONF_ANGLE_RANGE, default=270): lv_angle_degrees,
cv.Optional(CONF_ROTATION, default=0): lv_angle_degrees,
cv.Optional(CONF_ROTATION): lv_angle_degrees,
cv.Optional(CONF_INDICATORS): cv.ensure_list(INDICATOR_SCHEMA),
cv.Optional(CONF_DRAW_TICKS_ON_TOP, default=True): bool,
}
@@ -329,7 +329,7 @@ class MeterType(WidgetType):
)
def get_uses(self):
return CONF_SCALE, CONF_LINE
return CONF_SCALE, CONF_LINE, CONF_IMAGE
def validate(self, value):
return cv.has_at_most_one_key(CONF_INDICATOR, CONF_PIVOT)(value)
@@ -366,16 +366,17 @@ class MeterType(WidgetType):
lv.scale_set_range(scale_var, range_from, range_to)
angle_range = await lv_angle_degrees.process(scale_conf[CONF_ANGLE_RANGE])
rotation = await lv_angle_degrees.process(scale_conf[CONF_ROTATION])
if (rotation := scale_conf.get(CONF_ROTATION)) is not None:
rotation = await lv_angle_degrees.process(rotation)
else:
rotation = 90 + (360 - angle_range) // 2
# Set angle range
lv.scale_set_angle_range(
scale_var,
angle_range,
)
# Set rotation if specified
if rotation:
lv.scale_set_rotation(scale_var, rotation)
lv.scale_set_rotation(scale_var, rotation)
# Handle indicators as sections
for indicator in scale_conf.get(CONF_INDICATORS, ()):
@@ -393,10 +394,9 @@ class MeterType(WidgetType):
props = {
"arc_width": v[CONF_WIDTH],
"arc_color": v[CONF_COLOR],
"arc_opa": v[CONF_OPA],
"arc_rounded": v.get("arc_rounded", False),
}
if (opa := v.get(CONF_OPA)) is not None:
props["arc_opa"] = opa
if CONF_R_MOD in v:
get_warnings().add(
"The 'r_mod' indicator property is not supported in LVGL 9.x and will be ignored."
@@ -406,7 +406,7 @@ class MeterType(WidgetType):
lv.scale_section_set_style(
tvar, LV_PART.MAIN, await arc_style.get_var()
)
lw = Widget(tvar, arc_indicator_type)
lw = Widget.create(iid, tvar, arc_indicator_type)
await set_indicator_values(lw, v)
if t == CONF_TICK_STYLE:
@@ -424,6 +424,7 @@ class MeterType(WidgetType):
end_value,
color_start,
color_end,
v[CONF_WIDTH],
local,
)
lv_obj.add_event_cb(
+6 -3
View File
@@ -80,12 +80,15 @@ class StateTrigger : public Trigger<> {
template<MediaPlayerState State> class MediaPlayerStateTrigger : public Trigger<> {
public:
explicit MediaPlayerStateTrigger(MediaPlayer *player) {
player->add_on_state_callback([this, player]() {
if (player->state == State)
explicit MediaPlayerStateTrigger(MediaPlayer *player) : player_(player) {
player->add_on_state_callback([this]() {
if (this->player_->state == State)
this->trigger();
});
}
protected:
MediaPlayer *player_;
};
using IdleTrigger = MediaPlayerStateTrigger<MediaPlayerState::MEDIA_PLAYER_STATE_IDLE>;
+2
View File
@@ -16,6 +16,7 @@ static const uint8_t MHZ19_COMMAND_DETECTION_RANGE_0_2000PPM[] = {0xFF, 0x01, 0x
static const uint8_t MHZ19_COMMAND_DETECTION_RANGE_0_5000PPM[] = {0xFF, 0x01, 0x99, 0x00, 0x00, 0x00, 0x13, 0x88};
static const uint8_t MHZ19_COMMAND_DETECTION_RANGE_0_10000PPM[] = {0xFF, 0x01, 0x99, 0x00, 0x00, 0x00, 0x27, 0x10};
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
static const LogString *detection_range_to_log_string(MHZ19DetectionRange range) {
switch (range) {
case MHZ19_DETECTION_RANGE_0_2000PPM:
@@ -28,6 +29,7 @@ static const LogString *detection_range_to_log_string(MHZ19DetectionRange range)
return LOG_STR("default");
}
}
#endif
uint8_t mhz19_checksum(const uint8_t *command) {
uint8_t sum = 0;
+2 -2
View File
@@ -415,10 +415,10 @@ void Modbus::clear_rx_buffer_(const LogString *reason, bool warn) {
size_t at = this->rx_buffer_.size();
if (at > 0) {
if (warn) {
ESP_LOGW(TAG, "Clearing buffer of %" PRIu32 " bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
ESP_LOGW(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
millis() - this->last_send_);
} else {
ESP_LOGV(TAG, "Clearing buffer of %" PRIu32 " bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
ESP_LOGV(TAG, "Clearing buffer of %zu bytes - %s %" PRIu32 "ms after last send", at, LOG_STR_ARG(reason),
millis() - this->last_send_);
}
this->rx_buffer_.clear();
+14 -3
View File
@@ -28,6 +28,10 @@ namespace esphome::mqtt {
static const char *const TAG = "mqtt";
// Maximum number of MQTT component resends per loop iteration.
// Limits work to avoid triggering the task watchdog on reconnect.
static constexpr uint8_t MAX_RESENDS_PER_LOOP = 8;
// Disconnect reason strings indexed by MQTTClientDisconnectReason enum (0-8)
PROGMEM_STRING_TABLE(MQTTDisconnectReasonStrings, "TCP disconnected", "Unacceptable Protocol Version",
"Identifier Rejected", "Server Unavailable", "Malformed Credentials", "Not Authorized",
@@ -396,9 +400,16 @@ void MQTTClientComponent::loop() {
this->resubscribe_subscriptions_();
// Process pending resends for all MQTT components centrally
// This is more efficient than each component polling in its own loop
for (MQTTComponent *component : this->children_) {
component->process_resend();
// Limit work per loop iteration to avoid triggering task WDT on reconnect
{
uint8_t resend_count = 0;
for (MQTTComponent *component : this->children_) {
if (component->is_resend_pending()) {
component->process_resend();
if (++resend_count >= MAX_RESENDS_PER_LOOP)
break;
}
}
}
}
break;
+2 -2
View File
@@ -366,14 +366,14 @@ class MQTTJsonMessageTrigger : public Trigger<JsonObjectConst> {
class MQTTConnectTrigger : public Trigger<bool> {
public:
explicit MQTTConnectTrigger(MQTTClientComponent *&client) {
explicit MQTTConnectTrigger(MQTTClientComponent *client) {
client->set_on_connect([this](bool session_present) { this->trigger(session_present); });
}
};
class MQTTDisconnectTrigger : public Trigger<MQTTClientDisconnectReason> {
public:
explicit MQTTDisconnectTrigger(MQTTClientComponent *&client) {
explicit MQTTDisconnectTrigger(MQTTClientComponent *client) {
client->set_on_disconnect([this](MQTTClientDisconnectReason reason) { this->trigger(reason); });
}
};
+3
View File
@@ -147,6 +147,9 @@ class MQTTComponent : public Component {
/// Internal method for the MQTT client base to schedule a resend of the state on reconnect.
void schedule_resend_state();
/// Check if a resend is pending (called by MQTTClientComponent to rate-limit work)
bool is_resend_pending() const { return this->resend_state_; }
/// Process pending resend if needed (called by MQTTClientComponent)
void process_resend();
+1 -2
View File
@@ -121,8 +121,7 @@ void MQTTFanComponent::setup() {
});
}
auto f = std::bind(&MQTTFanComponent::publish_state, this);
this->state_->add_on_state_callback([this, f]() { this->defer("send", f); });
this->state_->add_on_state_callback([this]() { this->defer("send", [this]() { this->publish_state(); }); });
}
void MQTTFanComponent::dump_config() {
-24
View File
@@ -42,29 +42,5 @@ network::IPAddresses get_ip_addresses() {
return {};
}
const char *get_use_address() {
// Global component pointers are guaranteed to be set by component constructors when USE_* is defined
#ifdef USE_ETHERNET
return ethernet::global_eth_component->get_use_address();
#endif
#ifdef USE_MODEM
return modem::global_modem_component->get_use_address();
#endif
#ifdef USE_WIFI
return wifi::global_wifi_component->get_use_address();
#endif
#ifdef USE_OPENTHREAD
return openthread::global_openthread_component->get_use_address();
#endif
#if !defined(USE_ETHERNET) && !defined(USE_MODEM) && !defined(USE_WIFI) && !defined(USE_OPENTHREAD)
// Fallback when no network component is defined (e.g., host platform)
return "";
#endif
}
} // namespace esphome::network
#endif
+23 -1
View File
@@ -54,7 +54,29 @@ ESPHOME_ALWAYS_INLINE inline bool is_connected() {
/// Return whether the network is disabled (only wifi for now)
bool is_disabled();
/// Get the active network hostname
const char *get_use_address();
ESPHOME_ALWAYS_INLINE inline const char *get_use_address() {
// Global component pointers are guaranteed to be set by component constructors when USE_* is defined
#ifdef USE_ETHERNET
return ethernet::global_eth_component->get_use_address();
#endif
#ifdef USE_MODEM
return modem::global_modem_component->get_use_address();
#endif
#ifdef USE_WIFI
return wifi::global_wifi_component->get_use_address();
#endif
#ifdef USE_OPENTHREAD
return openthread::global_openthread_component->get_use_address();
#endif
#if !defined(USE_ETHERNET) && !defined(USE_MODEM) && !defined(USE_WIFI) && !defined(USE_OPENTHREAD)
// Fallback when no network component is defined (e.g., host platform)
return "";
#endif
}
IPAddresses get_ip_addresses();
} // namespace esphome::network
+6 -16
View File
@@ -80,35 +80,25 @@ void NumberCall::perform() {
target_value = max_value;
}
} else if (this->operation_ == NUMBER_OP_INCREMENT) {
ESP_LOGD(TAG, "'%s': Increment with%s cycling", name, this->cycle_ ? "" : "out");
ESP_LOGD(TAG, "'%s': Increment with%s cycling", name, this->cycle_ ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("out"));
if (!parent->has_state()) {
this->log_perform_warning_(LOG_STR("Can't increment, no state"));
return;
}
auto step = traits.get_step();
target_value = parent->state + (std::isnan(step) ? 1 : step);
if (target_value > max_value) {
if (this->cycle_ && !std::isnan(min_value)) {
target_value = min_value;
} else {
target_value = max_value;
}
}
if (target_value > max_value)
target_value = this->cycle_or_clamp_(max_value, min_value);
} else if (this->operation_ == NUMBER_OP_DECREMENT) {
ESP_LOGD(TAG, "'%s': Decrement with%s cycling", name, this->cycle_ ? "" : "out");
ESP_LOGD(TAG, "'%s': Decrement with%s cycling", name, this->cycle_ ? LOG_STR_LITERAL("") : LOG_STR_LITERAL("out"));
if (!parent->has_state()) {
this->log_perform_warning_(LOG_STR("Can't decrement, no state"));
return;
}
auto step = traits.get_step();
target_value = parent->state - (std::isnan(step) ? 1 : step);
if (target_value < min_value) {
if (this->cycle_ && !std::isnan(max_value)) {
target_value = max_value;
} else {
target_value = min_value;
}
}
if (target_value < min_value)
target_value = this->cycle_or_clamp_(min_value, max_value);
}
if (target_value < min_value) {
+3
View File
@@ -33,6 +33,9 @@ class NumberCall {
NumberCall &with_cycle(bool cycle);
protected:
float cycle_or_clamp_(float clamp, float opposite) const {
return (this->cycle_ && !std::isnan(opposite)) ? opposite : clamp;
}
void log_perform_warning_(const LogString *message);
void log_perform_warning_value_range_(const LogString *comparison, const LogString *limit_type, float val,
float limit);
@@ -257,11 +257,5 @@ void OpenThreadComponent::on_factory_reset(std::function<void()> callback) {
ESP_LOGD(TAG, "Waiting on Confirmation Removal SRP Host and Services");
}
// set_use_address() is guaranteed to be called during component setup by Python code generation,
// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
const char *OpenThreadComponent::get_use_address() const { return this->use_address_; }
void OpenThreadComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
} // namespace esphome::openthread
#endif
+2 -2
View File
@@ -37,8 +37,8 @@ class OpenThreadComponent : public Component {
void on_factory_reset(std::function<void()> callback);
void defer_factory_reset_external_callback();
const char *get_use_address() const;
void set_use_address(const char *use_address);
const char *get_use_address() const { return this->use_address_; }
void set_use_address(const char *use_address) { this->use_address_ = use_address; }
#if CONFIG_OPENTHREAD_MTD
void set_poll_period(uint32_t poll_period) { this->poll_period_ = poll_period; }
#endif
@@ -177,13 +177,19 @@ async def register_packet_transport(var, config):
cg.add(var.set_provider_encryption(name, hash_encryption_key(encryption)))
is_provider = False
for sens_conf in config.get(CONF_SENSORS, ()):
sensors = config.get(CONF_SENSORS, ())
binary_sensors = config.get(CONF_BINARY_SENSORS, ())
if sensors:
cg.add(var.set_sensor_count(len(sensors)))
if binary_sensors:
cg.add(var.set_binary_sensor_count(len(binary_sensors)))
for sens_conf in sensors:
is_provider = True
sens_id = sens_conf[CONF_ID]
sensor = await cg.get_variable(sens_id)
bcst_id = sens_conf.get(CONF_BROADCAST_ID, sens_id.id)
cg.add(var.add_sensor(bcst_id, sensor))
for sens_conf in config.get(CONF_BINARY_SENSORS, ()):
for sens_conf in binary_sensors:
is_provider = True
sens_id = sens_conf[CONF_ID]
sensor = await cg.get_variable(sens_id)
@@ -221,16 +221,20 @@ void PacketTransport::setup() {
}
#ifdef USE_SENSOR
for (auto &sensor : this->sensors_) {
sensor.sensor->add_on_state_callback([this, &sensor](float x) {
this->updated_ = true;
// [&sensor] is safe: sensor refers to a FixedVector element that never reallocates,
// so the reference remains valid for the component's lifetime.
sensor.sensor->add_on_state_callback([&sensor](float x) {
sensor.parent->updated_ = true;
sensor.updated = true;
});
}
#endif
#ifdef USE_BINARY_SENSOR
for (auto &sensor : this->binary_sensors_) {
sensor.sensor->add_on_state_callback([this, &sensor](bool value) {
this->updated_ = true;
// [&sensor] is safe: sensor refers to a FixedVector element that never reallocates,
// so the reference remains valid for the component's lifetime.
sensor.sensor->add_on_state_callback([&sensor](bool value) {
sensor.parent->updated_ = true;
sensor.updated = true;
});
}
@@ -548,11 +552,11 @@ void PacketTransport::dump_config() {
" Ping-pong: %s",
this->platform_name_, YESNO(this->is_encrypted_()), YESNO(this->ping_pong_enable_));
#ifdef USE_SENSOR
for (auto sensor : this->sensors_)
for (const auto &sensor : this->sensors_)
ESP_LOGCONFIG(TAG, " Sensor: %s", sensor.id);
#endif
#ifdef USE_BINARY_SENSOR
for (auto sensor : this->binary_sensors_)
for (const auto &sensor : this->binary_sensors_)
ESP_LOGCONFIG(TAG, " Binary Sensor: %s", sensor.id);
#endif
for (const auto &host : this->providers_) {
@@ -1,6 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/preferences.h"
#ifdef USE_SENSOR
#include "esphome/components/sensor/sensor.h"
@@ -37,11 +38,14 @@ struct Provider {
#endif
};
class PacketTransport;
#ifdef USE_SENSOR
struct Sensor {
sensor::Sensor *sensor;
const char *id;
bool updated;
PacketTransport *parent;
};
#endif
#ifdef USE_BINARY_SENSOR
@@ -49,6 +53,7 @@ struct BinarySensor {
binary_sensor::BinarySensor *sensor;
const char *id;
bool updated;
PacketTransport *parent;
};
#endif
@@ -60,8 +65,9 @@ class PacketTransport : public PollingComponent {
void dump_config() override;
#ifdef USE_SENSOR
void set_sensor_count(size_t count) { this->sensors_.init(count); }
void add_sensor(const char *id, sensor::Sensor *sensor) {
Sensor st{sensor, id, true};
Sensor st{sensor, id, true, this};
this->sensors_.push_back(st);
}
void add_remote_sensor(const char *hostname, const char *remote_id, sensor::Sensor *sensor) {
@@ -70,8 +76,9 @@ class PacketTransport : public PollingComponent {
}
#endif
#ifdef USE_BINARY_SENSOR
void set_binary_sensor_count(size_t count) { this->binary_sensors_.init(count); }
void add_binary_sensor(const char *id, binary_sensor::BinarySensor *sensor) {
BinarySensor st{sensor, id, true};
BinarySensor st{sensor, id, true, this};
this->binary_sensors_.push_back(st);
}
@@ -141,11 +148,11 @@ class PacketTransport : public PollingComponent {
std::vector<uint8_t> encryption_key_{};
#ifdef USE_SENSOR
std::vector<Sensor> sensors_{};
FixedVector<Sensor> sensors_{};
string_map_t<string_map_t<sensor::Sensor *>> remote_sensors_{};
#endif
#ifdef USE_BINARY_SENSOR
std::vector<BinarySensor> binary_sensors_{};
FixedVector<BinarySensor> binary_sensors_{};
string_map_t<string_map_t<binary_sensor::BinarySensor *>> remote_binary_sensors_{};
#endif
+5 -8
View File
@@ -95,10 +95,6 @@ void PMSX003Component::loop() {
// Just go ahead and read stuff
break;
}
} else if (now - this->last_update_ < this->update_interval_) {
// Otherwise just leave the sensor powered up and come back when we hit the update
// time
return;
}
if (now - this->last_transmission_ >= 500) {
@@ -114,10 +110,11 @@ void PMSX003Component::loop() {
this->read_byte(&this->data_[this->data_index_]);
auto check = this->check_byte_();
if (!check.has_value()) {
// finished
this->parse_data_();
if (this->update_interval_ > STABILISING_MS || now - this->last_update_ >= this->update_interval_) {
this->parse_data_();
this->last_update_ = now;
}
this->data_index_ = 0;
this->last_update_ = now;
} else if (!*check) {
// wrong data
this->data_index_ = 0;
@@ -138,7 +135,7 @@ optional<bool> PMSX003Component::check_byte_() {
return true;
}
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, START_CHARACTER_1);
ESP_LOGW(TAG, "Start character %u mismatch: 0x%02X != 0x%02X", index + 1, byte, start_char);
return false;
}
+5 -1
View File
@@ -21,5 +21,9 @@ CONFIG_SCHEMA = cv.Schema(
@coroutine_with_priority(CoroPriority.PREFERENCES)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
cg.add(var.set_write_interval(config[CONF_FLASH_WRITE_INTERVAL]))
write_interval = config[CONF_FLASH_WRITE_INTERVAL]
if write_interval.total_milliseconds == 0:
cg.add_define("USE_PREFERENCES_SYNC_EVERY_LOOP")
else:
cg.add(var.set_write_interval(write_interval))
await cg.register_component(var, config)
+7 -10
View File
@@ -8,24 +8,21 @@ namespace preferences {
class IntervalSyncer final : public Component {
public:
#ifdef USE_PREFERENCES_SYNC_EVERY_LOOP
void loop() override { global_preferences->sync(); }
#else
void set_write_interval(uint32_t write_interval) { this->write_interval_ = write_interval; }
void setup() override {
if (this->write_interval_ != 0) {
set_interval(this->write_interval_, []() { global_preferences->sync(); });
// When using interval-based syncing, we don't need the loop
this->disable_loop();
}
}
void loop() override {
if (this->write_interval_ == 0) {
global_preferences->sync();
}
this->set_interval(this->write_interval_, []() { global_preferences->sync(); });
}
#endif
void on_shutdown() override { global_preferences->sync(); }
float get_setup_priority() const override { return setup_priority::BUS; }
#ifndef USE_PREFERENCES_SYNC_EVERY_LOOP
protected:
uint32_t write_interval_{60000};
#endif
};
} // namespace preferences
+18
View File
@@ -24,6 +24,7 @@ from esphome.const import (
from esphome.core import CORE, CoroPriority, EsphomeError, coroutine_with_priority
from esphome.helpers import copy_file_if_changed, read_file, write_file_if_changed
from . import boards
from .const import KEY_BOARD, KEY_PIO_FILES, KEY_RP2040, rp2040_ns
# force import gpio to register pin schema
@@ -35,6 +36,23 @@ AUTO_LOAD = ["preferences"]
IS_TARGET_PLATFORM = True
def get_board() -> str:
"""Return the configured board name."""
return CORE.data[KEY_RP2040][KEY_BOARD]
def board_has_wifi() -> bool:
"""Return True if the configured board has WiFi (CYW43 wireless chip).
Returns True for unknown/custom boards to avoid rejecting valid
configurations for boards not in the generated list.
"""
board_info = boards.BOARDS.get(get_board())
if board_info is None:
return True
return board_info.get("wifi", False)
def set_core_data(config):
CORE.data[KEY_RP2040] = {}
CORE.data[KEY_CORE][KEY_TARGET_PLATFORM] = PLATFORM_RP2040
+10
View File
@@ -1910,6 +1910,7 @@ BOARDS = {
"name": "Pimoroni PicoPlus2W",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
"max_virtual_pin": 64,
},
"pimoroni_plasma2040": {
@@ -1926,6 +1927,7 @@ BOARDS = {
"name": "Pimoroni Plasma2350W",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
},
"pimoroni_servo2040": {
"name": "Pimoroni Servo2040",
@@ -1976,12 +1978,14 @@ BOARDS = {
"name": "Raspberry Pi Pico 2W",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
"max_virtual_pin": 64,
},
"rpipicow": {
"name": "Raspberry Pi Pico W",
"mcu": "rp2040",
"max_pin": 29,
"wifi": True,
"max_virtual_pin": 64,
},
"sea_picro": {
@@ -2013,6 +2017,7 @@ BOARDS = {
"name": "Soldered Electronics NULA RP2350",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
},
"solderparty_rp2040_stamp": {
"name": "Solder Party RP2040 Stamp",
@@ -2038,6 +2043,7 @@ BOARDS = {
"name": "SparkFun IoT RedBoard RP2350",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
},
"sparkfun_micromodrp2040": {
"name": "SparkFun MicroMod RP2040",
@@ -2063,18 +2069,21 @@ BOARDS = {
"name": "SparkFun Thing Plus RP2350",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
"max_virtual_pin": 64,
},
"sparkfun_xrp_controller": {
"name": "SparkFun XRP Controller",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
"max_virtual_pin": 64,
},
"sparkfun_xrp_controller_beta": {
"name": "SparkFun XRP Controller (Beta)",
"mcu": "rp2040",
"max_pin": 29,
"wifi": True,
"max_virtual_pin": 64,
},
"upesy_rp2040_devkit": {
@@ -2161,6 +2170,7 @@ BOARDS = {
"name": "Waveshare RP2350B Plus W",
"mcu": "rp2350",
"max_pin": 47,
"wifi": True,
},
"wiznet_5100s_evb_pico": {
"name": "WIZnet W5100S-EVB-Pico",
+7 -1
View File
@@ -78,11 +78,17 @@ def load_boards(arduino_pico_path: Path) -> tuple[dict, dict]:
display_name = f"{vendor} {name}".strip() if vendor else name
boards[board_name] = {
extra_flags = build.get("extra_flags", "")
has_wifi = "PICO_CYW43_SUPPORTED=1" in extra_flags
board_entry: dict = {
"name": display_name,
"mcu": mcu,
"max_pin": MCU_MAX_PIN.get(mcu, DEFAULT_MAX_PIN),
}
if has_wifi:
board_entry["wifi"] = True
boards[board_name] = board_entry
# Get pins for this variant
if variant not in variant_pins_cache:
+3 -9
View File
@@ -10,21 +10,13 @@
#include <pico/cyw43_arch.h> // For cyw43_arch_lwip_begin/end (LwIPLock)
#elif defined(USE_ETHERNET)
#include <LwipEthernet.h> // For ethernet_arch_lwip_begin/end (LwIPLock)
#include "esphome/components/ethernet/ethernet_component.h"
#endif
#include <hardware/structs/rosc.h>
#include <hardware/sync.h>
namespace esphome {
uint32_t random_uint32() {
uint32_t result = 0;
for (uint8_t i = 0; i < 32; i++) {
result <<= 1;
result |= rosc_hw->randombit;
}
return result;
}
bool random_bytes(uint8_t *data, size_t len) {
while (len-- != 0) {
uint8_t result = 0;
@@ -71,6 +63,8 @@ LwIPLock::~LwIPLock() {}
void get_mac_address_raw(uint8_t *mac) { // NOLINT(readability-non-const-parameter)
#ifdef USE_WIFI
WiFi.macAddress(mac);
#elif defined(USE_ETHERNET)
ethernet::global_eth_component->get_eth_mac_address_raw(mac);
#endif
}
+1 -1
View File
@@ -14,7 +14,7 @@
namespace esphome::rp2040 {
static const char *const TAG = "rp2040.preferences";
static const char *const TAG = "preferences";
static constexpr uint32_t RP2040_FLASH_STORAGE_SIZE = 512;
+37
View File
@@ -5,6 +5,30 @@
namespace esphome {
namespace sdl {
int Sdl::get_width() {
switch (this->rotation_) {
case display::DISPLAY_ROTATION_90_DEGREES:
case display::DISPLAY_ROTATION_270_DEGREES:
return this->get_height_internal();
case display::DISPLAY_ROTATION_0_DEGREES:
case display::DISPLAY_ROTATION_180_DEGREES:
default:
return this->get_width_internal();
}
}
int Sdl::get_height() {
switch (this->rotation_) {
case display::DISPLAY_ROTATION_0_DEGREES:
case display::DISPLAY_ROTATION_180_DEGREES:
return this->get_height_internal();
case display::DISPLAY_ROTATION_90_DEGREES:
case display::DISPLAY_ROTATION_270_DEGREES:
default:
return this->get_width_internal();
}
}
void Sdl::setup() {
SDL_Init(SDL_INIT_VIDEO);
this->window_ = SDL_CreateWindow(App.get_name().c_str(), this->pos_x_, this->pos_y_, this->width_, this->height_,
@@ -49,6 +73,19 @@ void Sdl::draw_pixel_at(int x, int y, Color color) {
if (!this->get_clipping().inside(x, y))
return;
if (this->rotation_ == display::DISPLAY_ROTATION_180_DEGREES) {
x = this->width_ - x - 1;
y = this->height_ - y - 1;
} else if (this->rotation_ == display::DISPLAY_ROTATION_90_DEGREES) {
auto tmp = x;
x = this->width_ - y - 1;
y = tmp;
} else if (this->rotation_ == display::DISPLAY_ROTATION_270_DEGREES) {
auto tmp = y;
y = this->height_ - x - 1;
x = tmp;
}
SDL_Rect rect{x, y, 1, 1};
auto data = (display::ColorUtil::color_to_565(color, display::COLOR_ORDER_RGB));
SDL_UpdateTexture(this->texture_, &rect, &data, 2);
+2 -2
View File
@@ -33,8 +33,8 @@ class Sdl : public display::Display {
this->pos_x_ = pos_x;
this->pos_y_ = pos_y;
}
int get_width() override { return this->width_; }
int get_height() override { return this->height_; }
int get_width() override;
int get_height() override;
float get_setup_priority() const override { return setup_priority::HARDWARE; }
void dump_config() override { LOG_DISPLAY("", "SDL", this); }
template<typename F> void add_key_listener(int32_t keycode, F &&callback) {
@@ -165,7 +165,7 @@ uint32_t SerialProxy::get_modem_pins() const {
(this->dtr_state_ ? SERIAL_PROXY_LINE_STATE_FLAG_DTR : 0u);
}
uart::FlushResult SerialProxy::flush_port() {
uart::UARTFlushResult SerialProxy::flush_port() {
ESP_LOGV(TAG, "Flushing serial proxy [%u]", this->instance_index_);
return this->flush();
}
@@ -92,7 +92,7 @@ class SerialProxy : public uart::UARTDevice, public Component {
uint32_t get_modem_pins() const;
/// Flush the serial port (block until all TX data is sent)
uart::FlushResult flush_port();
uart::UARTFlushResult flush_port();
/// Set the RTS GPIO pin (from YAML configuration)
void set_rts_pin(GPIOPin *pin) { this->rts_pin_ = pin; }
+23 -18
View File
@@ -1,4 +1,5 @@
#include "sht4x.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome {
@@ -9,14 +10,12 @@ static const char *const TAG = "sht4x";
static const uint8_t MEASURECOMMANDS[] = {0xFD, 0xF6, 0xE0};
static const uint8_t SERIAL_NUMBER_COMMAND = 0x89;
void SHT4XComponent::start_heater_() {
uint8_t cmd[] = {this->heater_command_};
ESP_LOGD(TAG, "Heater turning on");
if (this->write(cmd, 1) != i2c::ERROR_OK) {
this->status_set_error(LOG_STR("Failed to turn on heater"));
}
}
// Conversion constants from SHT4x datasheet
static constexpr float TEMPERATURE_OFFSET = -45.0f;
static constexpr float TEMPERATURE_SPAN = 175.0f;
static constexpr float HUMIDITY_OFFSET = -6.0f;
static constexpr float HUMIDITY_SPAN = 125.0f;
static constexpr float RAW_MAX = 65535.0f;
void SHT4XComponent::read_serial_number_() {
uint16_t buffer[2];
@@ -39,8 +38,8 @@ void SHT4XComponent::setup() {
this->read_serial_number_();
if (std::isfinite(this->duty_cycle_) && this->duty_cycle_ > 0.0f) {
uint32_t heater_interval = static_cast<uint32_t>(static_cast<uint16_t>(this->heater_time_) / this->duty_cycle_);
ESP_LOGD(TAG, "Heater interval: %" PRIu32, heater_interval);
this->heater_interval_ = static_cast<uint32_t>(static_cast<uint16_t>(this->heater_time_) / this->duty_cycle_);
ESP_LOGD(TAG, "Heater interval: %" PRIu32, this->heater_interval_);
if (this->heater_power_ == SHT4X_HEATERPOWER_HIGH) {
if (this->heater_time_ == SHT4X_HEATERTIME_LONG) {
@@ -62,8 +61,6 @@ void SHT4XComponent::setup() {
}
}
ESP_LOGD(TAG, "Heater command: %x", this->heater_command_);
this->set_interval(heater_interval, [this]() { this->start_heater_(); });
}
}
@@ -106,19 +103,27 @@ void SHT4XComponent::update() {
// Evaluate and publish measurements
if (this->temp_sensor_ != nullptr) {
// Temp is contained in the first result word
float sensor_value_temp = buffer[0];
float temp = -45 + 175 * sensor_value_temp / 65535;
float temp = TEMPERATURE_OFFSET + TEMPERATURE_SPAN * static_cast<float>(buffer[0]) / RAW_MAX;
this->temp_sensor_->publish_state(temp);
}
if (this->humidity_sensor_ != nullptr) {
// Relative humidity is in the second result word
float sensor_value_rh = buffer[1];
float rh = -6 + 125 * sensor_value_rh / 65535;
float rh = HUMIDITY_OFFSET + HUMIDITY_SPAN * static_cast<float>(buffer[1]) / RAW_MAX;
this->humidity_sensor_->publish_state(rh);
}
// Fire heater after measurement to maximize cooldown time before the next reading.
// The heater command produces a measurement that we don't need (datasheet 4.9).
if (this->heater_interval_ > 0) {
uint32_t now = millis();
if (now - this->last_heater_millis_ >= this->heater_interval_) {
ESP_LOGD(TAG, "Heater turning on");
if (this->write_command(this->heater_command_)) {
this->last_heater_millis_ = now;
}
}
}
});
}
+2 -1
View File
@@ -35,9 +35,10 @@ class SHT4XComponent : public PollingComponent, public sensirion_common::Sensiri
SHT4XHEATERTIME heater_time_;
float duty_cycle_;
void start_heater_();
void read_serial_number_();
uint8_t heater_command_;
uint32_t heater_interval_{0};
uint32_t last_heater_millis_{0};
uint32_t serial_number_;
sensor::Sensor *temp_sensor_{nullptr};
+1 -1
View File
@@ -125,7 +125,7 @@ size_t format_sockaddr_to(const struct sockaddr *addr_ptr, socklen_t len, std::s
/// On ESP8266, uses esp_delay() with a callback that checks socket activity.
/// On RP2040, uses __wfe() (Wait For Event) to truly sleep until an interrupt
/// (for example, CYW43 GPIO or a timer alarm) fires and wakes the CPU.
void socket_delay(uint32_t ms);
void socket_delay(uint32_t ms); // NOLINT(readability-redundant-declaration)
/// Signal socket/IO activity and wake the main loop early.
/// On ESP8266: sets flag + esp_schedule().
+23
View File
@@ -0,0 +1,23 @@
import esphome.codegen as cg
from esphome.components import i2c
import esphome.config_validation as cv
from ..spa06_base import CONFIG_SCHEMA_BASE, to_code_base
AUTO_LOAD = ["spa06_base"]
CODEOWNERS = ["@danielkent-net"]
DEPENDENCIES = ["i2c"]
spa06_ns = cg.esphome_ns.namespace("spa06_i2c")
SPA06I2CComponent = spa06_ns.class_(
"SPA06I2CComponent", cg.PollingComponent, i2c.I2CDevice
)
CONFIG_SCHEMA = CONFIG_SCHEMA_BASE.extend(
i2c.i2c_device_schema(default_address=0x77)
).extend({cv.GenerateID(): cv.declare_id(SPA06I2CComponent)})
async def to_code(config):
var = await to_code_base(config)
await i2c.register_i2c_device(var, config)
@@ -0,0 +1,14 @@
#include "spa06_i2c.h"
#include "esphome/core/hal.h"
#include "esphome/core/log.h"
namespace esphome::spa06_i2c {
static const char *const TAG = "spa06_i2c";
void SPA06I2CComponent::dump_config() {
LOG_I2C_DEVICE(this);
SPA06Component::dump_config();
}
} // namespace esphome::spa06_i2c
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "esphome/components/spa06_base/spa06_base.h"
#include "esphome/components/i2c/i2c.h"
namespace esphome::spa06_i2c {
class SPA06I2CComponent : public spa06_base::SPA06Component, public i2c::I2CDevice {
public:
bool spa_read_byte(uint8_t a_register, uint8_t *data) override { return read_byte(a_register, data); }
bool spa_write_byte(uint8_t a_register, uint8_t data) override { return write_byte(a_register, data); }
bool spa_read_bytes(uint8_t a_register, uint8_t *data, size_t len) override {
return read_bytes(a_register, data, len);
}
bool spa_write_bytes(uint8_t a_register, uint8_t *data, size_t len) override {
return write_bytes(a_register, data, len);
}
void dump_config() override;
};
} // namespace esphome::spa06_i2c
@@ -16,17 +16,15 @@ static const char *const TAG = "template.alarm_control_panel";
TemplateAlarmControlPanel::TemplateAlarmControlPanel(){};
#ifdef USE_BINARY_SENSOR
void TemplateAlarmControlPanel::add_sensor(binary_sensor::BinarySensor *sensor, uint16_t flags, AlarmSensorType type) {
// Save the flags and type. Assign a store index for the per sensor data type.
SensorDataStore sd;
sd.last_chime_state = false;
void TemplateAlarmControlPanel::add_sensor(binary_sensor::BinarySensor *sensor, uint8_t flags, AlarmSensorType type) {
// Save the sensor pointer, flags, and type in the per-sensor info structure.
AlarmSensor alarm_sensor;
alarm_sensor.sensor = sensor;
alarm_sensor.info.flags = flags;
alarm_sensor.info.type = type;
alarm_sensor.info.store_index = this->next_store_index_++;
alarm_sensor.info.chime_active = false;
alarm_sensor.info.auto_bypassed = false;
this->sensors_.push_back(alarm_sensor);
this->sensor_data_.push_back(sd);
};
// Alarm sensor type strings indexed by AlarmSensorType enum (0-3): DELAYED, INSTANT, DELAYED_FOLLOWER, INSTANT_ALWAYS
@@ -55,7 +53,7 @@ void TemplateAlarmControlPanel::dump_config() {
(this->trigger_time_ / 1000), this->get_supported_features());
#ifdef USE_BINARY_SENSOR
for (const auto &alarm_sensor : this->sensors_) {
const uint16_t flags = alarm_sensor.info.flags;
const uint8_t flags = alarm_sensor.info.flags;
ESP_LOGCONFIG(TAG,
" Binary Sensor:\n"
" Name: %s\n"
@@ -95,7 +93,7 @@ void TemplateAlarmControlPanel::loop() {
delay = this->arming_night_time_;
}
if ((millis() - this->last_update_) > delay) {
this->bypass_before_arming();
this->auto_bypass_sensors_();
this->publish_state(this->desired_state_);
}
return;
@@ -117,26 +115,25 @@ void TemplateAlarmControlPanel::loop() {
#ifdef USE_BINARY_SENSOR
// Test all of the sensors regardless of the alarm panel state
for (const auto &alarm_sensor : this->sensors_) {
const auto &info = alarm_sensor.info;
for (auto &alarm_sensor : this->sensors_) {
auto &info = alarm_sensor.info;
auto *sensor = alarm_sensor.sensor;
// Check for chime zones
if (info.flags & BINARY_SENSOR_MODE_CHIME) {
// Look for the transition from closed to open
if ((!this->sensor_data_[info.store_index].last_chime_state) && (sensor->state)) {
if ((!info.chime_active) && (sensor->state)) {
// Must be disarmed to chime
if (this->current_state_ == ACP_STATE_DISARMED) {
this->chime_callback_.call();
}
}
// Record the sensor state change
this->sensor_data_[info.store_index].last_chime_state = sensor->state;
info.chime_active = sensor->state;
}
// Check for faulted sensors
if (sensor->state) {
// Skip if auto bypassed
if (std::count(this->bypassed_sensor_indicies_.begin(), this->bypassed_sensor_indicies_.end(),
info.store_index) == 1) {
if (info.auto_bypassed) {
continue;
}
// Skip if bypass armed home
@@ -239,23 +236,33 @@ void TemplateAlarmControlPanel::arm_(optional<std::string> code, alarm_control_p
if (delay > 0) {
this->publish_state(ACP_STATE_ARMING);
} else {
this->bypass_before_arming();
this->auto_bypass_sensors_();
this->publish_state(state);
}
}
void TemplateAlarmControlPanel::bypass_before_arming() {
void TemplateAlarmControlPanel::auto_bypass_sensors_() {
#ifdef USE_BINARY_SENSOR
for (const auto &alarm_sensor : this->sensors_) {
for (auto &alarm_sensor : this->sensors_) {
auto &info = alarm_sensor.info;
auto *sensor = alarm_sensor.sensor;
// Check for faulted bypass_auto sensors and remove them from monitoring
if ((alarm_sensor.info.flags & BINARY_SENSOR_MODE_BYPASS_AUTO) && (alarm_sensor.sensor->state)) {
ESP_LOGW(TAG, "'%s' is faulted and will be automatically bypassed", alarm_sensor.sensor->get_name().c_str());
this->bypassed_sensor_indicies_.push_back(alarm_sensor.info.store_index);
if ((info.flags & BINARY_SENSOR_MODE_BYPASS_AUTO) && (sensor->state)) {
ESP_LOGW(TAG, "'%s' is faulted and will be automatically bypassed", sensor->get_name().c_str());
info.auto_bypassed = true;
}
}
#endif
}
void TemplateAlarmControlPanel::clear_auto_bypassed_sensors_() {
#ifdef USE_BINARY_SENSOR
for (auto &alarm_sensor : this->sensors_) {
alarm_sensor.info.auto_bypassed = false;
}
#endif
}
void TemplateAlarmControlPanel::control(const AlarmControlPanelCall &call) {
auto opt_state = call.get_state();
if (opt_state) {
@@ -273,9 +280,7 @@ void TemplateAlarmControlPanel::control(const AlarmControlPanelCall &call) {
}
this->desired_state_ = ACP_STATE_DISARMED;
this->publish_state(ACP_STATE_DISARMED);
#ifdef USE_BINARY_SENSOR
this->bypassed_sensor_indicies_.clear();
#endif
this->clear_auto_bypassed_sensors_();
} else if (state == ACP_STATE_TRIGGERED) {
this->publish_state(ACP_STATE_TRIGGERED);
} else if (state == ACP_STATE_PENDING) {
@@ -18,7 +18,7 @@
namespace esphome::template_ {
#ifdef USE_BINARY_SENSOR
enum BinarySensorFlags : uint16_t {
enum BinarySensorFlags : uint8_t {
BINARY_SENSOR_MODE_NORMAL = 1 << 0,
BINARY_SENSOR_MODE_BYPASS_ARMED_HOME = 1 << 1,
BINARY_SENSOR_MODE_BYPASS_ARMED_NIGHT = 1 << 2,
@@ -41,14 +41,11 @@ enum TemplateAlarmControlPanelRestoreMode {
};
#ifdef USE_BINARY_SENSOR
struct SensorDataStore {
bool last_chime_state;
};
struct SensorInfo {
uint16_t flags;
uint8_t flags;
AlarmSensorType type;
uint8_t store_index;
bool chime_active;
bool auto_bypassed;
};
struct AlarmSensor {
@@ -68,7 +65,9 @@ class TemplateAlarmControlPanel final : public alarm_control_panel::AlarmControl
bool get_requires_code_to_arm() const override { return this->requires_code_to_arm_; }
bool get_all_sensors_ready() { return this->sensors_ready_; };
void set_restore_mode(TemplateAlarmControlPanelRestoreMode restore_mode) { this->restore_mode_ = restore_mode; }
void bypass_before_arming();
// Remove before 2026.10.0
ESPDEPRECATED("bypass_before_arming() is deprecated and will be removed in 2026.10.0", "2026.4.0")
void bypass_before_arming() { this->auto_bypass_sensors_(); }
#ifdef USE_BINARY_SENSOR
/** Initialize the sensors vector with the specified capacity.
@@ -83,7 +82,7 @@ class TemplateAlarmControlPanel final : public alarm_control_panel::AlarmControl
* @param flags The OR of BinarySensorFlags for the sensor.
* @param type The sensor type which determines its triggering behaviour.
*/
void add_sensor(binary_sensor::BinarySensor *sensor, uint16_t flags = 0,
void add_sensor(binary_sensor::BinarySensor *sensor, uint8_t flags = 0,
AlarmSensorType type = ALARM_SENSOR_TYPE_DELAYED);
#endif
@@ -141,11 +140,6 @@ class TemplateAlarmControlPanel final : public alarm_control_panel::AlarmControl
#ifdef USE_BINARY_SENSOR
// List of binary sensors with their alarm-specific info
FixedVector<AlarmSensor> sensors_;
// a list of automatically bypassed sensors
std::vector<uint8_t> bypassed_sensor_indicies_;
// Per sensor data store
std::vector<SensorDataStore> sensor_data_;
uint8_t next_store_index_ = 0;
#endif
TemplateAlarmControlPanelRestoreMode restore_mode_{};
@@ -170,6 +164,8 @@ class TemplateAlarmControlPanel final : public alarm_control_panel::AlarmControl
bool is_code_valid_(optional<std::string> code);
void arm_(optional<std::string> code, alarm_control_panel::AlarmControlPanelState state, uint32_t delay);
void auto_bypass_sensors_();
void clear_auto_bypassed_sensors_();
};
} // namespace esphome::template_
+1 -1
View File
@@ -45,7 +45,7 @@ class UARTDevice {
size_t available() { return this->parent_->available(); }
FlushResult flush() { return this->parent_->flush(); }
UARTFlushResult flush() { return this->parent_->flush(); }
// Compat APIs
int read() {
+7 -7
View File
@@ -30,11 +30,11 @@ enum UARTDirection {
const LogString *parity_to_str(UARTParityOptions parity);
/// Result of a flush() call.
enum class FlushResult {
SUCCESS, ///< Confirmed: all bytes left the TX FIFO.
TIMEOUT, ///< Confirmed: timed out before TX completed.
FAILED, ///< Confirmed: driver or hardware error.
ASSUMED_SUCCESS, ///< Platform cannot report result; success is assumed.
enum class UARTFlushResult {
UART_FLUSH_RESULT_SUCCESS, ///< Confirmed: all bytes left the TX FIFO.
UART_FLUSH_RESULT_TIMEOUT, ///< Confirmed: timed out before TX completed.
UART_FLUSH_RESULT_FAILED, ///< Confirmed: driver or hardware error.
UART_FLUSH_RESULT_ASSUMED_SUCCESS, ///< Platform cannot report result; success is assumed.
};
class UARTComponent {
@@ -82,8 +82,8 @@ class UARTComponent {
virtual size_t available() = 0;
// Pure virtual method to block until all bytes have been written to the UART bus.
// @return FlushResult indicating whether the flush was confirmed, timed out, failed, or assumed successful.
virtual FlushResult flush() = 0;
// @return UARTFlushResult indicating whether the flush was confirmed, timed out, failed, or assumed successful.
virtual UARTFlushResult flush() = 0;
// Sets the maximum time to wait for TX to drain during flush().
// Only meaningful on ESP32 (IDF). Other platforms ignore this value.
@@ -213,14 +213,14 @@ size_t ESP8266UartComponent::available() {
return this->sw_serial_->available();
}
}
FlushResult ESP8266UartComponent::flush() {
UARTFlushResult ESP8266UartComponent::flush() {
ESP_LOGVV(TAG, " Flushing");
if (this->hw_serial_ != nullptr) {
this->hw_serial_->flush();
} else {
this->sw_serial_->flush();
}
return FlushResult::ASSUMED_SUCCESS;
return UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS;
}
void ESP8266SoftwareSerial::setup(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_pin, uint32_t baud_rate,
uint8_t stop_bits, uint32_t data_bits, UARTParityOptions parity,
@@ -58,7 +58,7 @@ class ESP8266UartComponent : public UARTComponent, public Component {
bool read_array(uint8_t *data, size_t len) override;
size_t available() override;
FlushResult flush() override;
UARTFlushResult flush() override;
uint32_t get_config();
@@ -7,7 +7,9 @@
#include "esphome/core/log.h"
#include "esphome/core/gpio.h"
#include "driver/gpio.h"
#include "esp_private/gpio.h"
#include "soc/gpio_num.h"
#include "soc/uart_pins.h"
#ifdef USE_UART_WAKE_LOOP_ON_RX
#include "esphome/core/application.h"
@@ -21,6 +23,20 @@ namespace esphome::uart {
static const char *const TAG = "uart.idf";
/// Check if a pin number matches one of the default UART0 GPIO pins.
/// These pins may have residual IOMUX state from the ROM bootloader that
/// must be cleared before UART reconfiguration.
///
/// ESP-IDF's uart_set_pin() has an asymmetry: when routing TX via GPIO matrix,
/// it calls gpio_func_sel(PIN_FUNC_GPIO) to clear IOMUX, but for RX it only
/// calls gpio_input_enable() which does NOT clear the IOMUX function select.
/// If a default UART0 TX pin (configured as TX via IOMUX during boot) is later
/// reassigned as RX via GPIO matrix, the old IOMUX TX function remains active,
/// causing TX data to loop back into RX on the same pin.
static constexpr bool is_default_uart0_pin(int8_t pin_num) {
return pin_num == U0TXD_GPIO_NUM || pin_num == U0RXD_GPIO_NUM;
}
uart_config_t IDFUARTComponent::get_config_() {
uart_parity_t parity = UART_PARITY_DISABLE;
if (this->parity_ == UART_CONFIG_PARITY_EVEN) {
@@ -131,6 +147,19 @@ void IDFUARTComponent::load_settings(bool dump_config) {
return;
}
int8_t tx = this->tx_pin_ != nullptr ? this->tx_pin_->get_pin() : -1;
int8_t rx = this->rx_pin_ != nullptr ? this->rx_pin_->get_pin() : -1;
int8_t flow_control = this->flow_control_pin_ != nullptr ? this->flow_control_pin_->get_pin() : -1;
// Clear residual IOMUX function on UART0 default pins left by the ROM bootloader.
// See is_default_uart0_pin() comment for details on the ESP-IDF uart_set_pin() bug.
if (is_default_uart0_pin(tx)) {
gpio_func_sel(static_cast<gpio_num_t>(tx), PIN_FUNC_GPIO);
}
if (is_default_uart0_pin(rx)) {
gpio_func_sel(static_cast<gpio_num_t>(rx), PIN_FUNC_GPIO);
}
auto setup_pin_if_needed = [](InternalGPIOPin *pin) {
if (!pin) {
return;
@@ -146,10 +175,6 @@ void IDFUARTComponent::load_settings(bool dump_config) {
setup_pin_if_needed(this->tx_pin_);
}
int8_t tx = this->tx_pin_ != nullptr ? this->tx_pin_->get_pin() : -1;
int8_t rx = this->rx_pin_ != nullptr ? this->rx_pin_->get_pin() : -1;
int8_t flow_control = this->flow_control_pin_ != nullptr ? this->flow_control_pin_->get_pin() : -1;
uint32_t invert = 0;
if (this->tx_pin_ != nullptr && this->tx_pin_->is_inverted()) {
invert |= UART_SIGNAL_TXD_INV;
@@ -335,15 +360,15 @@ size_t IDFUARTComponent::available() {
return available;
}
FlushResult IDFUARTComponent::flush() {
UARTFlushResult IDFUARTComponent::flush() {
ESP_LOGVV(TAG, " Flushing");
TickType_t ticks = this->flush_timeout_ms_ == 0 ? portMAX_DELAY : pdMS_TO_TICKS(this->flush_timeout_ms_);
esp_err_t err = uart_wait_tx_done(this->uart_num_, ticks);
if (err == ESP_OK)
return FlushResult::SUCCESS;
return UARTFlushResult::UART_FLUSH_RESULT_SUCCESS;
if (err == ESP_ERR_TIMEOUT)
return FlushResult::TIMEOUT;
return FlushResult::FAILED;
return UARTFlushResult::UART_FLUSH_RESULT_TIMEOUT;
return UARTFlushResult::UART_FLUSH_RESULT_FAILED;
}
void IDFUARTComponent::check_logger_conflict() {}
@@ -31,7 +31,7 @@ class IDFUARTComponent : public UARTComponent, public Component {
bool read_array(uint8_t *data, size_t len) override;
size_t available() override;
FlushResult flush() override;
UARTFlushResult flush() override;
void set_flush_timeout(uint32_t flush_timeout_ms) override { this->flush_timeout_ms_ = flush_timeout_ms; }
@@ -274,13 +274,13 @@ size_t HostUartComponent::available() {
return result;
};
FlushResult HostUartComponent::flush() {
UARTFlushResult HostUartComponent::flush() {
if (this->file_descriptor_ == -1) {
return FlushResult::ASSUMED_SUCCESS;
return UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS;
}
tcflush(this->file_descriptor_, TCIOFLUSH);
ESP_LOGV(TAG, " Flushing");
return FlushResult::ASSUMED_SUCCESS;
return UARTFlushResult::UART_FLUSH_RESULT_ASSUMED_SUCCESS;
}
void HostUartComponent::update_error_(const std::string &error) {

Some files were not shown because too many files have changed in this diff Show More