Compare commits

...
Author SHA1 Message Date
J. Nick Koston 8c11a3ba7d Say when console_write() can write fewer bytes 2026-11-16 23:57:47 -06:00
J. Nick Koston a2c07ae165 Describe the console limits by the IDF option, include host 2026-11-16 23:18:51 -06:00
J. Nick Koston 18eff452ba Say where request_console() does nothing 2026-11-16 23:05:22 -06:00
J. Nick Koston f81920f9e0 Mark the USB CDC console guards as needed 2026-11-16 22:54:05 -06:00
J. Nick Koston d4efd41c38 Restore the USB CDC console guards for targets without USB OTG 2026-11-16 22:53:39 -06:00
J. Nick Koston 8e54625bde Drop the USB CDC sdkconfig checks the port selection implies, use pdMS_TO_TICKS, shorten the port table test 2026-11-16 22:29:33 -06:00
J. Nick Koston 3cee50f683 Merge remote-tracking branch 'upstream/dev' into logger-console-api 2026-11-16 22:17:34 -06:00
Mark Mayo e12784543d [logger] Copy log lines that have no arguments instead of formatting them (#22644) 2026-11-16 22:16:47 -06:00
J. Nick Koston bc3e9c88f4 [select] Set a fixed option by index and look up a template lambda's option once (#22655) 2026-11-16 22:48:05 -05:00
luar123andCopilot Autofix powered by AI 7e3c2ebc10 [zigbee] refactor ZigbeeAttribute (#22765)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 22:31:05 -05:00
J. Nick Koston 3f6c0f35fe [modem] Set the APN while the SIM is powered down (#22817) 2026-11-17 16:23:11 +13:00
J. Nick Koston 200bf69035 [wifi] Join the next network after a failed hidden network probe on ESP32 (#22764) 2026-11-17 16:23:06 +13:00
huangkongshengandhuangkongsheng 0054041d6a [core] Reject sign-padded bind key pairs (#22660)
Signed-off-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
Co-authored-by: huangkongsheng <huangkongsheng@users.noreply.github.com>
2026-11-16 22:15:45 -05:00
J. Nick Koston b75b3e2bef [tuya] Register entity listeners from generated code and print their dumps from the hub (#22724) 2026-11-16 21:03:11 -06:00
J. Nick KostonandJonathan Swoboda 144c799cf5 [components] Print the xiaomi BLE sensor dumps from the tracker instead of a component per sensor (#22727)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-11-16 20:56:53 -06:00
J. Nick Koston 61cce92aaa [homeassistant] Subscribe and dump the import entities from the API server (#22725) 2026-11-16 20:56:35 -06:00
J. Nick Koston 38c1646870 [homeassistant] Share the action helpers and drop state that did nothing (#22592) 2026-11-16 20:56:35 -06:00
J. Nick Koston b60c2864ef [sml][teleinfo] Print entity dumps from their hub instead of a component per entity (#22722) 2026-11-16 21:55:49 -05:00
J. Nick Koston db0121bc21 [remote_base] Move the plain-field protocols to register_simple_protocol (#22713) 2026-11-16 20:53:05 -06:00
J. Nick Koston be8f6c5e41 [remote_base] Add register_simple_protocol for plain field protocols (#22711) 2026-11-16 20:53:04 -06:00
J. Nick Koston b621332de5 [components] Print BLE sensor dumps from the tracker instead of a component per sensor (#22728) 2026-11-16 20:52:05 -06:00
J. Nick KostonandJonathan Swoboda 982cbba291 [analyze_memory] List ESP8266 string literals in RAM by component (#22755)
Co-authored-by: Jonathan Swoboda <154711427+swoboda1337@users.noreply.github.com>
2026-11-16 20:50:51 -06:00
J. Nick Koston a2ac68faac [sun] Assign the invalid coordinates instead of copying a constant (#22741) 2026-11-16 21:47:36 -05:00
J. Nick Koston 731f6e2722 [mitsubishi] Keep the IR frame template in flash on ESP8266 (#22746) 2026-11-16 21:44:59 -05:00
J. Nick Koston 598d87836c [daikin_arc] Keep the IR frame templates in flash on ESP8266 (#22743) 2026-11-16 21:44:36 -05:00
J. Nick Koston e852e15ca3 [ble_device_base] Let BLE trackers print their device listeners' dumps (#22726) 2026-11-16 21:42:02 -05:00
Jacopo Labardi 6b82e127fe [const] Share destination between components (#22785) 2026-11-16 21:23:41 -05:00
17baeae3ea [nrf52][zephyr] Share the Zephyr SDK install steps with nrf52 (#22623)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-16 19:54:34 -05:00
J. Nick Kostonandpre-commit-ci-lite[bot] bc57ad5c87 [sntp] Pass the servers as separate constructor arguments (#22737)
Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
2026-11-16 19:09:39 -05:00
J. Nick Koston 0c1606d3b8 [analyze_memory] Count ESP8266 .rodata as RAM and list the constants GCC copies into it (#22748) 2026-11-16 18:06:26 -06:00
J. Nick Koston a155401afc [wifi_info] Publish the BSSID without copying a padded constant (#22736) 2026-11-16 19:04:39 -05:00
J. Nick Koston e3bfffc8ab [core] Use the nibble and encode_uint12 helpers in touch and BME drivers (#22761) 2026-11-17 00:04:28 +00:00
J. Nick Koston 9f5ca49e2f [light] Keep the wrapper's color mode precedence in flash on ESP8266 (#22742) 2026-11-16 19:03:43 -05:00
J. Nick Koston 7b7f3cf50b Compile init_uart only for UART selections 2026-11-16 13:07:33 -06:00
J. Nick Koston 4304a92674 Assert the port name and selection per config, define them beside each port in defines.h 2026-11-16 13:07:33 -06:00
J. Nick Koston 6b4acbcdc4 Keep the hardware_uart selection map for device-builder, check the USB CDC read count 2026-11-16 13:07:33 -06:00
J. Nick Koston d618b41db9 Name the console UART and its selection with one define each 2026-11-16 13:07:33 -06:00
J. Nick Koston 941286480f [logger] Fix the console UART at build time and add a console read/write API 2026-11-16 13:07:33 -06:00
268 changed files with 4913 additions and 2335 deletions

No files matched your search

+628 -19
View File
@@ -1,7 +1,9 @@
"""Memory usage analyzer for ESPHome compiled binaries."""
from collections import Counter, defaultdict
from collections.abc import Container
from dataclasses import dataclass, field
from functools import cached_property
import logging
from pathlib import Path
import re
@@ -55,6 +57,7 @@ _COMPONENT_PREFIX_EXTERNAL = "[external]"
_COMPONENT_PREFIX_LIB = "[lib]"
_COMPONENT_CORE = f"{_COMPONENT_PREFIX_ESPHOME}core"
_COMPONENT_API = f"{_COMPONENT_PREFIX_ESPHOME}api"
_COMPONENT_ARDUINO_CORE = "arduino_core"
# Placement new storage suffix (generated by codegen Pvariable)
_PSTORAGE_SUFFIX = "__pstorage"
@@ -83,6 +86,28 @@ _NAMESPACE_STD = "std::"
# Type alias for symbol information: (symbol_name, size, component)
SymbolInfoType = tuple[str, int, str]
# Only ESP8266 has this section; its .rodata is copied to RAM at boot like .data
_ESP8266_FLASH_CODE_SECTION = ".irom0.text"
# readelf -SW row: [Nr] Name Type Address Off Size ES Flg
_OBJ_SECTION_PATTERN = re.compile(
r"^\s*\[\s*(\d+)\]\s+(\S+)\s+(\S+)\s+[\da-f]+\s+[\da-f]+\s+([\da-f]+)\s+[\da-f]+\s+(\S*)"
)
_RELOC_SECTION_PATTERN = re.compile(r"^Relocation section '\.rela(\S+)'")
# String literal section; group 1 is the function for -fdata-sections names
_STRING_SECTION_PATTERN = re.compile(r"^\.rodata(?:\.(.+))?\.str\d+\.\d+$")
# Data section of one symbol; group 1 is the symbol
_DATA_SECTION_PATTERN = re.compile(r"^\.(?:rodata|data)\.(.+)$")
# Code section; group 1 is the function for -ffunction-sections names, after any
# placement prefix (.text.startup.<fn>, .iram.text.<fn> for IRAM_ATTR)
_CODE_SECTION_PATTERN = re.compile(
r"^\.(?:literal|text|irom0\.text|iram\.text|iram0\.text)"
r"(?:\.(?:startup|unlikely|hot|exit)(?=\.|$))?(?:\.(.+))?$"
)
# readelf -x row: " 0x00000000 0000803f 0000803f 0000803f 0000803f ...?...?...?...?"
_HEX_DUMP_PREFIX = " 0x"
_HEX_DUMP_COLUMNS = slice(13, 48)
# RAM sections - symbols in these sections consume RAM
RAM_SECTIONS = frozenset([".data", ".bss"])
@@ -119,6 +144,31 @@ class SDKSymbol:
demangled: str = "" # Demangled name (populated after analysis)
@dataclass
class UnnamedConstant:
"""Constant without a symbol in an object's .rodata (RAM on ESP8266)."""
size: int
source_file: str
component: str
functions: list[str] # Functions that reference it, mangled
jump_table: bool # Holds code addresses (a switch table), not a value
data: bytes # Leading bytes, to recognize the value
strings: list[str] = field(default_factory=list) # String literals it points to
# Every function that uses the section, which decides whether the link kept it
users: list[str] = field(default_factory=list)
@dataclass
class StringLiteral:
"""A string literal kept in RAM (.rodata on ESP8266)."""
text: str
size: int # Bytes in RAM; strings shared or merged into a longer one count once
# Component -> functions or objects that use it, mangled
users: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
@dataclass
class ComponentMemory:
"""Tracks memory usage for a component."""
@@ -152,6 +202,201 @@ class ComponentMemory:
return self.data_size + self.bss_size
@dataclass
class _RodataSection:
"""An object's .rodata section and the byte ranges its symbols cover."""
name: str
size: int
covered: list[tuple[int, int]] = field(default_factory=list) # (offset, size)
@cached_property
def _named(self) -> frozenset[int]:
return frozenset(
offset
for start, size in self.covered
for offset in range(start, min(start + size, self.size))
)
def is_unnamed(self, offset: int) -> bool:
return 0 <= offset < self.size and offset not in self._named
@property
def unnamed_size(self) -> int:
return self.size - len(self._named)
def _parse_string_sections(output: str) -> dict[str, dict[str, tuple[str, str | None]]]:
"""Find string literal sections in ``readelf -SW`` output.
Returns:
Object path -> section index -> (section name, function it is named after)
"""
sections: dict[str, dict[str, tuple[str, str | None]]] = defaultdict(dict)
file_path = ""
for line in output.splitlines():
if line.startswith("File: "):
file_path = line[6:]
elif (match := _OBJ_SECTION_PATTERN.match(line)) is not None:
index, name, section_type, size_hex, flags = match.groups()
if (
section_type == "PROGBITS"
and "S" in flags
and int(size_hex, 16)
and (string := _STRING_SECTION_PATTERN.match(name))
):
sections[file_path][index] = (name, string.group(1))
return sections
def _ram_string_size(text: bytes, rodata: bytes, literals: Container[bytes]) -> int:
"""Bytes a literal takes in RAM: 0 if dropped or only the tail of another literal."""
needle = text + b"\0"
start = rodata.find(needle)
while start != -1:
head = rodata.rfind(b"\0", 0, start) + 1
end = start + len(text)
# Only the tail of a longer literal of ours if one starts before it; other
# bytes there are data, or a literal from an object that was not scanned
if not any(rodata[k:end] in literals for k in range(head, start)):
return len(needle)
start = rodata.find(needle, start + 1)
return 0
def _parse_hex_dumps(output: str) -> dict[str, bytearray]:
"""Collect the bytes of each ``readelf -x`` section dump by section name."""
contents: dict[str, bytearray] = defaultdict(bytearray)
section: str | None = None
for line in output.splitlines():
if line.startswith("Hex dump of section"):
section = line.split("'")[1]
elif section is not None and line.startswith(_HEX_DUMP_PREFIX):
contents[section] += bytes.fromhex(line[_HEX_DUMP_COLUMNS].replace(" ", ""))
elif line and not line.startswith(" "):
section = None
return contents
def _parse_relocations(output: str) -> list[tuple[str, int, str, int]]:
"""List (relocated section, offset, target, addend) from ``readelf -rW`` output."""
relocations: list[tuple[str, int, str, int]] = []
section: str | None = None
for line in output.splitlines():
if line.startswith("Relocation section"):
match = _RELOC_SECTION_PATTERN.match(line)
section = match.group(1) if match else None
elif line[:1].isdigit() and section is not None:
# Offset Info Type Sym.Value Sym.Name + Addend
fields = line.split()
if len(fields) < 5:
continue
addend = int(fields[6], 16) if len(fields) > 6 else 0
if len(fields) > 6 and fields[5] == "-":
addend = -addend
relocations.append((section, int(fields[0], 16), fields[4], addend))
elif line and line[0] != " ":
section = None
return relocations
def _pointer_target(referrer: bytes, offset: int, addend: int) -> int | None:
"""Offset a relocated pointer at ``offset`` points to, or None if not dumped."""
if offset < 0 or offset + 4 > len(referrer):
return None
# Xtensa keeps part of the addend in the relocated word
return addend + int.from_bytes(referrer[offset : offset + 4], "little")
def _pointed_literal(
referrer: bytes, offset: int, addend: int, strings: bytes
) -> bytes | None:
"""Read the string literal a relocated pointer refers to, or None if out of range."""
start = _pointer_target(referrer, offset, addend)
if start is None or not 0 <= start < len(strings):
return None
end = strings.find(b"\0", start)
return bytes(strings[start : end if end != -1 else len(strings)])
def _section_user(section: str) -> str | None:
"""The function or data symbol a -ffunction-sections/-fdata-sections name is for."""
match = _CODE_SECTION_PATTERN.match(section) or _DATA_SECTION_PATTERN.match(section)
return match.group(1) if match else None
@dataclass
class _FunctionDefinitions:
"""Where each function is defined across the scanned objects."""
weak: dict[str, set[str]] = field(default_factory=lambda: defaultdict(set))
strong: set[str] = field(default_factory=set) # Global, non-weak
count: Counter[str] = field(default_factory=Counter) # Objects defining it
def linked_copy_unknown(self, file_path: str, functions: list[str]) -> bool:
"""True if another object's copy of these functions may be the linked one."""
if not functions:
return False
if self.weak[file_path].issuperset(functions):
# Inline copies: dropped only once a strong definition replaces every user
return self.strong.issuperset(functions)
# Same-named local functions in several objects; the ELF can't tell them apart
return all(f not in self.strong and self.count[f] > 1 for f in functions)
def _parse_unnamed_rodata(
output: str,
) -> tuple[dict[str, dict[str, _RodataSection]], _FunctionDefinitions]:
"""Find .rodata sections with bytes no symbol covers in ``readelf -SW -sW`` output.
Returns:
Object path -> section index -> section, and where functions are defined
"""
sections: dict[str, dict[str, _RodataSection]] = defaultdict(dict)
definitions = _FunctionDefinitions()
file_path = ""
for line in output.splitlines():
if line.startswith("File: "):
file_path = line[6:]
elif match := _OBJ_SECTION_PATTERN.match(line):
index, name, section_type, size_hex, flags = match.groups()
# Merged sections (string literals) are shared between objects
if (
section_type == "PROGBITS"
and name.startswith(".rodata")
and "A" in flags
and "M" not in flags
):
sections[file_path][index] = _RodataSection(name, int(size_hex, 16))
else:
# Num: Value Size Type Bind Vis Ndx Name
fields = line.split()
if len(fields) < 8:
continue
if fields[3] == "OBJECT" and (
section := sections[file_path].get(fields[6])
):
section.covered.append((int(fields[1], 16), int(fields[2], 0)))
elif fields[3] == "FUNC" and fields[6] != "UND":
definitions.count[fields[7]] += 1
if fields[4] == "WEAK":
definitions.weak[file_path].add(fields[7])
elif fields[4] == "GLOBAL":
definitions.strong.add(fields[7])
unnamed = {
path: kept
for path, file_sections in sections.items()
if (
kept := {
index: section
for index, section in file_sections.items()
if section.unnamed_size
}
)
}
return unnamed, definitions
class MemoryAnalyzer:
"""Analyzes memory usage from ELF files."""
@@ -231,6 +476,10 @@ class MemoryAnalyzer:
self._heuristic_to_lib: dict[str, str] = {}
# Function call counts: mangled_name -> call_count
self._function_call_counts: Counter[str] = Counter()
# True on ESP8266, where .rodata is RAM; it is then counted as .data
self.rodata_in_ram = False
self._unnamed_constants: list[UnnamedConstant] = []
self._string_literals: list[StringLiteral] = []
def analyze(self) -> dict[str, ComponentMemory]:
"""Analyze the ELF file and return component memory usage."""
@@ -240,6 +489,7 @@ class MemoryAnalyzer:
self._scan_source_symbols()
self._categorize_symbols()
self._analyze_cswtch_symbols()
self._analyze_object_rodata()
self._analyze_sdk_libraries()
self._analyze_function_calls()
return dict(self.components)
@@ -253,18 +503,17 @@ class MemoryAnalyzer:
check=True,
)
# Parse section headers
for line in result.stdout.splitlines():
# Look for section entries
if not (match := _READELF_SECTION_PATTERN.match(line)):
continue
raw_sections = [
(match.group(1), int(match.group(2), 16))
for line in result.stdout.splitlines()
if (match := _READELF_SECTION_PATTERN.match(line))
]
self.rodata_in_ram = any(
name == _ESP8266_FLASH_CODE_SECTION for name, _ in raw_sections
)
section_name = match.group(1)
size_hex = match.group(2)
size = int(size_hex, 16)
# Map to standard section name
mapped_section = map_section_name(section_name)
for section_name, size in raw_sections:
mapped_section = self._standard_section(map_section_name(section_name))
if not mapped_section:
continue
@@ -272,6 +521,12 @@ class MemoryAnalyzer:
self.sections[mapped_section] = MemorySection(mapped_section)
self.sections[mapped_section].total_size += size
def _standard_section(self, section: str | None) -> str | None:
"""Count .rodata as .data where it is RAM (ESP8266)."""
if section == ".rodata" and self.rodata_in_ram:
return ".data"
return section
def _parse_symbols(self) -> None:
"""Parse symbols from ELF file."""
result = subprocess.run(
@@ -289,14 +544,18 @@ class MemoryAnalyzer:
continue
section, name, size, address = symbol_info
section = self._standard_section(section)
if section not in self.sections:
continue
# Every alias is in the ELF, even when its size is counted once
self._elf_symbol_names.add(name)
# Skip duplicate symbols at the same address (e.g., C1/C2 constructors)
if address in seen_addresses or section not in self.sections:
if address in seen_addresses:
continue
self.sections[section].symbols.append((name, size, ""))
self.sections[section].symbol_size += size
self._elf_symbol_names.add(name)
seen_addresses.add(address)
def _categorize_symbols(self) -> None:
@@ -925,10 +1184,12 @@ class MemoryAnalyzer:
Path to the directory containing .o files, or None if not found.
"""
# The ELF is typically at .pioenvs/<env>/firmware.elf
# Object files are in .pioenvs/<env>/src/ and .pioenvs/<env>/lib*/
# PlatformIO puts object files in .pioenvs/<env>/src/ and .pioenvs/<env>/lib*/,
# the native ESP8266 build in .pioenvs/<env>/obj/src/ and obj/lib/
pioenvs_dir = self.elf_path.parent
if pioenvs_dir.exists() and any(pioenvs_dir.glob("src/*.o")):
return pioenvs_dir
for obj_dir in (pioenvs_dir, pioenvs_dir / "obj"):
if any(obj_dir.glob("src/*.o")):
return obj_dir
return None
@staticmethod
@@ -1110,6 +1371,12 @@ class MemoryAnalyzer:
):
return f"{_COMPONENT_PREFIX_LIB}{self._lib_hash_to_name[parts[1]]}"
# Native ESP8266 build: lib/<owner>__<Name>/... and the Arduino core in core/
if len(parts) >= 3 and parts[0] == "lib":
return f"{_COMPONENT_PREFIX_LIB}{parts[1].rsplit('__', 1)[-1].lower()}"
if len(parts) >= 2 and parts[0] == "core":
return _COMPONENT_ARDUINO_CORE
# Other framework/library files - return the first path component
# e.g., FrameworkArduino/... -> FrameworkArduino
return parts[0] if parts else source_file
@@ -1191,9 +1458,7 @@ class MemoryAnalyzer:
and other_mem is not None
):
other_mem.add_section_size(section_name, -size)
if component not in self.components:
self.components[component] = ComponentMemory(component)
self.components[component].add_section_size(section_name, size)
self._add_component_size(component, section_name, size)
# Sort by size descending
self._cswtch_symbols.sort(key=lambda x: x[1], reverse=True)
@@ -1205,6 +1470,350 @@ class MemoryAnalyzer:
total_size,
)
def _analyze_object_rodata(self) -> None:
"""Attribute .rodata without a symbol, which is RAM on ESP8266, to components."""
if not self.rodata_in_ram:
return
if (obj_dir := self._find_object_files_dir()) is None:
_LOGGER.warning(
"No object files next to the ELF, so constants in RAM are not listed"
)
return
objects = [str(f) for f in sorted(obj_dir.rglob("*.o"))]
result = run_tool([self.readelf_path, "-SW", "-sW", *objects])
if result is None:
_LOGGER.warning("readelf failed, so constants in RAM are not listed")
return
if result.returncode != 0:
# readelf still prints every object it could read
_LOGGER.warning(
"readelf could not read every object: %s", result.stderr.strip()
)
output = result.stdout
# readelf names each file only when given several
if len(objects) == 1:
output = f"File: {objects[0]}\n{output}"
self._attribute_unnamed_constants(output, obj_dir)
self._attribute_string_literals(output, obj_dir)
names = {n for c in self._unnamed_constants for n in c.functions} | {
n
for literal in self._string_literals
for users in literal.users.values()
for n in users
}
self._batch_demangle_symbols(sorted(names - self._demangle_cache.keys()))
def _attribute_unnamed_constants(self, output: str, obj_dir: Path) -> None:
"""Attribute constants GCC copies into objects built from constant initializers."""
unnamed, definitions = _parse_unnamed_rodata(output)
# Inline (weak) functions are emitted, with their constants, in every
# object that uses them; the linker keeps one copy
inline_copies: dict[tuple[tuple[str, ...], int], str] = {}
for file_path, sections in unnamed.items():
rel_path = Path(file_path).relative_to(obj_dir).as_posix()
component = self._source_file_to_component(rel_path)
for constant in self._scan_object_constants(
file_path, sections, rel_path, component
):
# Only linked users can show which object's copy survived
live = [u for u in constant.users if u in self._elf_symbol_names]
if definitions.linked_copy_unknown(file_path, live):
continue
if definitions.weak[file_path].issuperset(live):
key = (tuple(live), constant.size)
if inline_copies.setdefault(key, file_path) != file_path:
continue
self._unnamed_constants.append(constant)
self._charge_ram(component, constant.size)
self._unnamed_constants.sort(key=lambda c: c.size, reverse=True)
def _attribute_string_literals(self, output: str, obj_dir: Path) -> None:
"""Attribute string literals in RAM to the components whose code uses them.
The linker merges identical literals across objects, so each is counted
once, from the bytes it really takes in the ELF's .rodata.
"""
result = run_tool([self.readelf_path, "-x", ".rodata", str(self.elf_path)])
rodata = _parse_hex_dumps(result.stdout).get(".rodata") if result else None
if not rodata:
_LOGGER.warning(
"No .rodata dump of %s, so string literals are not listed",
self.elf_path,
)
return
rodata = bytes(rodata)
_, definitions = _parse_unnamed_rodata(output)
# Literal -> component -> functions or data using it
users: dict[bytes, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set))
for file_path, sections in _parse_string_sections(output).items():
component = self._source_file_to_component(
Path(file_path).relative_to(obj_dir).as_posix()
)
for text, found in self._scan_object_strings(file_path, sections).items():
kept = {
user
for user in found & self._elf_symbol_names
if not definitions.linked_copy_unknown(file_path, [user])
}
if text and kept:
users[text][component] |= kept
literals = (
StringLiteral(
text.decode("utf-8", "backslashreplace"),
_ram_string_size(text, rodata, users),
by_component,
)
for text, by_component in users.items()
)
self._string_literals = sorted(
(s for s in literals if s.size), key=lambda s: (-s.size, s.text)
)
for literal in self._string_literals:
# A literal used by several components is not charged to any of them
if len(literal.users) == 1:
self._charge_ram(next(iter(literal.users)), literal.size)
def _scan_object_strings(
self, file_path: str, sections: dict[str, tuple[str, str | None]]
) -> dict[bytes, set[str]]:
"""Map each string literal of one object to the functions or data using it.
Args:
file_path: Object file to read
sections: String sections by index, with the function each is named after
"""
result = run_tool(
[self.readelf_path, "-rW"]
+ [arg for index in sections for arg in ("-x", index)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading strings of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return {}
contents = _parse_hex_dumps(result.stdout)
users: dict[bytes, set[str]] = defaultdict(set)
# Section -> the function it is named after, None for the shared section
owners = dict(sections.values())
for name, function in owners.items():
# A section named after a function holds its literals; others may use them too
if function:
for text in bytes(contents[name]).split(b"\0")[:-1]:
users[text].add(function)
relocations = _parse_relocations(result.stdout)
# Functions using each unnamed table, for literals reached through a pointer in it
table_users: dict[str, set[str]] = defaultdict(set)
for section, _, target, _ in relocations:
if (
target.startswith(".rodata")
and not _STRING_SECTION_PATTERN.match(target)
and (function := _section_user(section))
and _CODE_SECTION_PATTERN.match(section)
):
table_users[target].add(function)
# Other users are found from the pointers they hold
refs = [
(section, found, offset, target, addend)
for section, offset, target, addend in relocations
if target in owners
and (
found := {u} if (u := _section_user(section)) else table_users[section]
)
and found != {owners[target]}
]
unnamed = sum(
1
for section, _, target, _ in relocations
if target in owners
and owners[target] is None
and not _section_user(section)
and not table_users[section]
)
if unnamed:
_LOGGER.debug(
"%s: %d string pointers with no named user", file_path, unnamed
)
if not refs:
return users
result = run_tool(
[self.readelf_path]
+ [arg for name in sorted({r[0] for r in refs}) for arg in ("-x", name)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading string users of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return users
referrers = _parse_hex_dumps(result.stdout)
for section, found, offset, target, addend in refs:
# A pointer that can't be read names no literal
text = _pointed_literal(
referrers.get(section, b""), offset, addend, contents[target]
)
if text is not None:
users[text] |= found
return users
def _scan_object_constants(
self,
file_path: str,
sections: dict[str, _RodataSection],
rel_path: str,
component: str,
) -> list[UnnamedConstant]:
"""Return the unnamed constants of one object that the link kept.
Args:
file_path: Object file to read
sections: Candidate sections by index
rel_path: Object path shown in the report
component: Component the object belongs to
"""
result = run_tool(
[self.readelf_path, "-rW"]
+ [arg for index in sections for arg in ("-x", index)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading constants of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return []
by_name = {section.name: section for section in sections.values()}
contents = _parse_hex_dumps(result.stdout)
# Every function using the section decides whether the link kept it
users: dict[str, set[str]] = defaultdict(set)
# Functions shown as using the unnamed bytes
functions: dict[str, set[str]] = defaultdict(set)
# (code section, offset, addend, target, function) into sections with named bytes
mixed: list[tuple[str, int, int, str, str]] = []
jump_tables: set[str] = set()
# Section -> (offset, string section, addend) of each pointer to a literal
pointers: dict[str, list[tuple[int, str, int]]] = defaultdict(list)
for section, offset, target, addend in _parse_relocations(result.stdout):
if target in by_name:
code = _CODE_SECTION_PATTERN.match(section)
if code and code.group(1):
users[target].add(code.group(1))
if by_name[target].covered:
mixed.append((section, offset, addend, target, code.group(1)))
else:
functions[target].add(code.group(1))
elif section in by_name and by_name[section].is_unnamed(offset):
if _CODE_SECTION_PATTERN.match(target):
jump_tables.add(section)
elif ".str" in target:
pointers[section].append((offset, target, addend))
self._add_mixed_section_users(file_path, mixed, by_name, functions)
strings = self._read_pointed_strings(file_path, pointers, contents)
return [
UnnamedConstant(
size=section.unnamed_size,
source_file=rel_path,
component=component,
functions=sorted(functions[name]),
jump_table=name in jump_tables,
data=bytes(
byte
for offset, byte in enumerate(contents[name])
if section.is_unnamed(offset)
)[:16],
strings=strings.get(name, []),
users=sorted(users[name]),
)
for name, section in by_name.items()
# Dropped by --gc-sections unless a function that uses it was kept
if not self._elf_symbol_names.isdisjoint(users[name])
]
def _add_mixed_section_users(
self,
file_path: str,
mixed: list[tuple[str, int, int, str, str]],
by_name: dict[str, _RodataSection],
functions: dict[str, set[str]],
) -> None:
"""Name only the functions that point at the unnamed bytes of a mixed section."""
if not mixed:
return
result = run_tool(
[self.readelf_path]
+ [arg for name in sorted({m[0] for m in mixed}) for arg in ("-x", name)]
+ [file_path]
)
code = _parse_hex_dumps(result.stdout) if result else {}
for section, offset, addend, target, function in mixed:
start = _pointer_target(code.get(section, b""), offset, addend)
# A pointer that can't be read, or lands outside the section, keeps the user
section_size = by_name[target].size
if (
start is None
or not 0 <= start < section_size
or by_name[target].is_unnamed(start)
):
functions[target].add(function)
def _read_pointed_strings(
self,
file_path: str,
pointers: dict[str, list[tuple[int, str, int]]],
contents: dict[str, bytearray],
) -> dict[str, list[str]]:
"""Resolve each constant's pointers to string literals, in offset order."""
if not pointers:
return {}
targets = sorted({t for refs in pointers.values() for _, t, _ in refs})
result = run_tool(
[self.readelf_path]
+ [arg for target in targets for arg in ("-x", target)]
+ [file_path]
)
if result is None or result.returncode != 0:
_LOGGER.warning(
"readelf failed reading strings of %s: %s",
file_path,
result.stderr.strip() if result else "not run",
)
return {}
literals = _parse_hex_dumps(result.stdout)
resolved: dict[str, list[str]] = {}
for name, refs in pointers.items():
texts = [
_pointed_literal(
contents[name], offset, addend, literals.get(target, b"")
)
for offset, target, addend in sorted(refs)
]
# One pointer that can't be read makes the list misleading; show bytes instead
if all(text is not None for text in texts):
resolved[name] = [t.decode("utf-8", "backslashreplace") for t in texts]
return resolved
def _charge_ram(self, component: str, size: int) -> None:
"""Charge RAM bytes that have no ELF symbol to a component."""
self._add_component_size(component, ".data", size)
if (data_section := self.sections.get(".data")) is not None:
data_section.symbol_size += size
def _add_component_size(self, component: str, section: str, size: int) -> None:
"""Add size to a component, creating it under its own name."""
if component not in self.components:
self.components[component] = ComponentMemory(component)
self.components[component].add_section_size(section, size)
def _analyze_function_calls(self) -> None:
"""Count function call sites by parsing disassembly output.
+88 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable
import heapq
import json
from operator import itemgetter
from pathlib import Path
import sys
@@ -23,7 +24,7 @@ from . import (
from .toolchain import find_elf_path, find_idedata_path, idedata_candidates
if TYPE_CHECKING:
from . import ComponentMemory
from . import ComponentMemory, StringLiteral
def _format_pstorage_name(name: str) -> str:
@@ -46,6 +47,8 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
)
# Lower threshold for RAM symbols (RAM is more constrained)
RAM_SYMBOL_SIZE_THRESHOLD: int = 24
# String literals listed per component in the RAM strings report
STRINGS_PER_COMPONENT: int = 10
# Number of top symbols to show in the largest symbols report
TOP_SYMBOLS_LIMIT: int = 30
# Width for symbol name display in top symbols report
@@ -204,6 +207,79 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
f"{i + 1:>2}. {size:>7,} B {section_label:<8} {demangled_display:<{self.COL_TOP_SYMBOL_NAME}} {component}"
)
def _add_unnamed_constants_analysis(self, lines: list[str]) -> None:
"""Add the unnamed constants (ESP8266 .rodata in RAM) section."""
self._add_section_header(lines, "Unnamed Constants in RAM (.rodata)")
total_size = sum(c.size for c in self._unnamed_constants)
lines.append(
f"Total: {len(self._unnamed_constants)} constant(s), {total_size:,} B. "
"GCC copies these into objects built from constant initializers;"
)
lines.append(
"PROGMEM tables, assigned fields or a user-provided constructor avoid the copy."
)
lines.append("")
for constant in self._unnamed_constants:
kind = "switch table" if constant.jump_table else "constant"
lines.append(
f"{constant.size:>6,} B {kind:<12} {constant.component} ({constant.source_file})"
)
lines.extend(
f"{'':>9} used by {self._demangle_symbol(function)}"
for function in constant.functions
)
if constant.strings:
# Escaped, so control characters in a literal can't disturb the terminal
shown = ", ".join(
json.dumps(text[:40]) for text in constant.strings[:4]
)
more = ", ..." if len(constant.strings) > 4 else ""
lines.append(f"{'':>9} points to {shown}{more}")
elif constant.data and not constant.jump_table:
more = " ..." if constant.size > len(constant.data) else ""
lines.append(f"{'':>9} bytes: {constant.data.hex(' ')}{more}")
lines.append("")
def _add_string_literals_analysis(self, lines: list[str]) -> None:
"""Add the string literals in RAM (ESP8266 .rodata) section, by component."""
self._add_section_header(lines, "String Literals in RAM (.rodata)")
total_size = sum(s.size for s in self._string_literals)
lines.append(
f"Total: {len(self._string_literals)} string(s), {total_size:,} B. "
"LOG_STR, ESPHOME_F or a PROGMEM table keeps a literal in flash."
)
lines.append(
"Only literals whose user is known are counted; one used by several components is "
"listed under each and charged to none."
)
lines.append("")
by_component: dict[str, list[StringLiteral]] = defaultdict(list)
for literal in self._string_literals:
for component in literal.users:
by_component[component].append(literal)
totals = {c: sum(s.size for s in ls) for c, ls in by_component.items()}
for component, literals in sorted(
by_component.items(), key=lambda x: (-totals[x[0]], x[0])
):
comp_total = totals[component]
lines.append(f"{component} ({comp_total:,} B, {len(literals)} strings):")
for literal in literals[: self.STRINGS_PER_COMPONENT]:
text = json.dumps(literal.text)
if len(text) > 50:
text = f'{text[:47]}..."'
users = sorted(
self._demangle_symbol(u) for u in literal.users[component]
)
used_by = users[0][:60] + (
f" (+{len(users) - 1})" if len(users) > 1 else ""
)
lines.append(f" {literal.size:>5,} B {text:<50} {used_by}")
if len(literals) > self.STRINGS_PER_COMPONENT:
lines.append(
f" ... and {len(literals) - self.STRINGS_PER_COMPONENT} more"
)
lines.append("")
def _add_cswtch_analysis(self, lines: list[str]) -> None:
"""Add CSWTCH (GCC switch table lookup) analysis section."""
self._add_section_header(lines, "CSWTCH Analysis (GCC Switch Table Lookups)")
@@ -394,6 +470,12 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
f"{total_flash:>{self.COL_TOTAL_FLASH - 2},} B | {total_ram:>{self.COL_TOTAL_RAM - 2},} B"
)
if self.rodata_in_ram:
lines.append("")
lines.append(
"ESP8266 keeps .rodata in RAM, so constants are counted in RAM (data)."
)
# Show unattributed RAM (SDK/framework overhead)
unattributed_bss, unattributed_data, unattributed_total = (
self.get_unattributed_ram()
@@ -657,6 +739,11 @@ class MemoryAnalyzerCLI(MemoryAnalyzer):
lines.append(f" ... and {len(large_ram_syms) - 10} more")
lines.append("")
if self._unnamed_constants:
self._add_unnamed_constants_analysis(lines)
if self._string_literals:
self._add_string_literals_analysis(lines)
# CSWTCH (GCC switch table) analysis
if self._cswtch_symbols:
self._add_cswtch_analysis(lines)
@@ -738,7 +825,6 @@ def main():
build_dir = sys.argv[1]
# Load build directory
import json
from esphome.platformio.toolchain import IDEData
+2 -2
View File
@@ -96,7 +96,7 @@ void AHT10Component::read_data_() {
this->restart_read_();
return;
}
if (data[1] == 0x0 && data[2] == 0x0 && (data[3] >> 4) == 0x0) {
if (data[1] == 0x0 && data[2] == 0x0 && high_nibble(data[3]) == 0x0) {
// Invalid humidity (0x0)
if (this->humidity_sensor_ == nullptr) {
ESP_LOGV(TAG, "Invalid humidity (reading not required)");
@@ -110,7 +110,7 @@ void AHT10Component::read_data_() {
if (this->read_count_ > 1) {
ESP_LOGD(TAG, "Success at %ums", (unsigned) (millis() - this->start_time_));
}
uint32_t raw_temperature = encode_uint24(data[3] & 0xF, data[4], data[5]);
uint32_t raw_temperature = encode_uint24(low_nibble(data[3]), data[4], data[5]);
uint32_t raw_humidity = encode_uint24(data[1], data[2], data[3]) >> 4;
PUBLISH_STATE(this->temperature_sensor_, ((200.0f * static_cast<float>(raw_temperature)) / AHT10_DIVISOR) - 50.0f);
+2 -2
View File
@@ -62,9 +62,9 @@ bool AM2315C::reset_register_(uint8_t reg) {
bool AM2315C::convert_(uint8_t *data, float &humidity, float &temperature) {
uint32_t raw;
raw = (data[1] << 12) | (data[2] << 4) | (data[3] >> 4);
raw = encode_uint24(data[1], data[2], data[3]) >> 4;
humidity = raw * 9.5367431640625e-5;
raw = encode_uint24(data[3] & 0x0F, data[4], data[5]);
raw = encode_uint24(low_nibble(data[3]), data[4], data[5]);
temperature = raw * 1.9073486328125e-4 - 50;
return crc8(data, 6, 0xFF, 0x31, true) == data[6];
}
+8
View File
@@ -70,6 +70,10 @@ void APIServer::setup() {
#if defined(USE_API_HOMEASSISTANT_STATES) && defined(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT)
this->state_subs_.reserve(HOMEASSISTANT_STATE_SUBSCRIPTION_COUNT);
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
if (this->homeassistant_subscribe_publisher_ != nullptr)
this->homeassistant_subscribe_publisher_();
#endif
#ifdef USE_API_NOISE
// Always reserve the slot: flash preferences are positional on esp8266, so
// a yaml key build must keep the layout of a runtime key build
@@ -389,6 +393,10 @@ void APIServer::dump_config() {
#ifdef USE_API_OUTGOING_CONNECTION
this->outgoing_conn_.dump_config();
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
if (this->homeassistant_dump_publisher_ != nullptr)
this->homeassistant_dump_publisher_();
#endif
}
void APIServer::handle_disconnect(APIConnection *conn) {}
+5
View File
@@ -272,6 +272,11 @@ class APIServer final : public Component
/// Measure again the subscriptions whose entity id is this buffer, after the wizard wrote a new id into it.
void update_state_subscription_entity_id(const char *entity_id);
#endif
#ifdef USE_API_HOMEASSISTANT_IMPORTS
// Generated: subscribes the imported Home Assistant entities, and prints their dumps
HUB_PUBLISHER(homeassistant_subscribe)
HUB_PUBLISHER(homeassistant_dump)
#endif
#endif
#ifdef USE_API_USER_DEFINED_ACTIONS
const std::vector<UserServiceDescriptor *> &get_user_services() const { return this->user_services_; }
+1 -1
View File
@@ -24,7 +24,7 @@ enum class AranetDeviceType : uint8_t {
// https://github.com/Anrijs/Aranet4-Python/blob/master/aranet4/client.py
// https://github.com/Anrijs/Aranet4-ESP32/blob/main/src/Aranet4.h
void Aranet::dump_config() {
void Aranet::dump_child_config() {
ESP_LOGCONFIG(TAG, "Aranet");
LOG_SENSOR(" ", "Carbon Dioxide", this->co2_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
+2 -3
View File
@@ -2,16 +2,15 @@
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
namespace esphome::aranet {
class Aranet final : public Component, public ble_device_base::ESPBTDeviceListener {
class Aranet final : public ble_device_base::ESPBTDeviceListener {
public:
explicit Aranet(uint64_t address) : address_(address) {}
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
static constexpr uint8_t WARNED_INVALID_LENGTH = 1 << 0;
+72 -78
View File
@@ -43,7 +43,7 @@ CONF_RADIATION_DURATION = "radiation_duration"
UNIT_NANOSIEVERT = "nSv"
aranet_ns = cg.esphome_ns.namespace("aranet")
Aranet = aranet_ns.class_("Aranet", ble_device_base.ESPBTDeviceListener, cg.Component)
Aranet = aranet_ns.class_("Aranet", ble_device_base.ESPBTDeviceListener)
DIAGNOSTIC_DURATION_SCHEMA = sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
@@ -53,86 +53,80 @@ DIAGNOSTIC_DURATION_SCHEMA = sensor.sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
)
CONFIG_SCHEMA = (
cv.Schema(
{
cv.GenerateID(): cv.declare_id(Aranet),
cv.Required(CONF_MAC_ADDRESS): cv.mac_address,
cv.Optional(CONF_CO2): sensor.sensor_schema(
unit_of_measurement=UNIT_PARTS_PER_MILLION,
accuracy_decimals=0,
device_class=DEVICE_CLASS_CARBON_DIOXIDE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=1,
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_PRESSURE): sensor.sensor_schema(
unit_of_measurement=UNIT_HECTOPASCAL,
accuracy_decimals=1,
device_class=DEVICE_CLASS_PRESSURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_MEASUREMENT_INTERVAL): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_MEASUREMENT_AGE): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_SIGNAL_STRENGTH): sensor.sensor_schema(
unit_of_measurement=UNIT_DECIBEL_MILLIWATT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_RADON): sensor.sensor_schema(
unit_of_measurement=UNIT_BECQUEREL_PER_CUBIC_METER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_RADON,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_RATE): sensor.sensor_schema(
unit_of_measurement=UNIT_MICROSILVERTS_PER_HOUR,
accuracy_decimals=3,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_TOTAL): sensor.sensor_schema(
unit_of_measurement=UNIT_NANOSIEVERT,
accuracy_decimals=0,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
cv.Optional(CONF_RADIATION_DURATION): sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DURATION,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA)
)
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(Aranet),
cv.Required(CONF_MAC_ADDRESS): cv.mac_address,
cv.Optional(CONF_CO2): sensor.sensor_schema(
unit_of_measurement=UNIT_PARTS_PER_MILLION,
accuracy_decimals=0,
device_class=DEVICE_CLASS_CARBON_DIOXIDE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_TEMPERATURE): sensor.sensor_schema(
unit_of_measurement=UNIT_CELSIUS,
accuracy_decimals=1,
device_class=DEVICE_CLASS_TEMPERATURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_HUMIDITY): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=1,
device_class=DEVICE_CLASS_HUMIDITY,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_PRESSURE): sensor.sensor_schema(
unit_of_measurement=UNIT_HECTOPASCAL,
accuracy_decimals=1,
device_class=DEVICE_CLASS_PRESSURE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema(
unit_of_measurement=UNIT_PERCENT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_BATTERY,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_MEASUREMENT_INTERVAL): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_MEASUREMENT_AGE): DIAGNOSTIC_DURATION_SCHEMA,
cv.Optional(CONF_SIGNAL_STRENGTH): sensor.sensor_schema(
unit_of_measurement=UNIT_DECIBEL_MILLIWATT,
accuracy_decimals=0,
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
state_class=STATE_CLASS_MEASUREMENT,
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
cv.Optional(CONF_RADON): sensor.sensor_schema(
unit_of_measurement=UNIT_BECQUEREL_PER_CUBIC_METER,
accuracy_decimals=0,
device_class=DEVICE_CLASS_RADON,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_RATE): sensor.sensor_schema(
unit_of_measurement=UNIT_MICROSILVERTS_PER_HOUR,
accuracy_decimals=3,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_MEASUREMENT,
),
cv.Optional(CONF_RADIATION_TOTAL): sensor.sensor_schema(
unit_of_measurement=UNIT_NANOSIEVERT,
accuracy_decimals=0,
icon=ICON_RADIOACTIVE,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
cv.Optional(CONF_RADIATION_DURATION): sensor.sensor_schema(
unit_of_measurement=UNIT_SECOND,
accuracy_decimals=0,
device_class=DEVICE_CLASS_DURATION,
state_class=STATE_CLASS_TOTAL_INCREASING,
),
}
).extend(ble_device_base.BLE_DEVICE_SCHEMA)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(
config, config[CONF_MAC_ADDRESS].as_hex
)
var = await ble_device_base.new_ble_device(config, config[CONF_MAC_ADDRESS].as_hex)
sensors = sensor.sub_sensors(config)
await sensors(CONF_CO2, var.set_co2_sensor)
@@ -6,7 +6,7 @@ namespace esphome::atc_mithermometer {
ESPHOME_LOG_TAG(TAG, "atc_mithermometer");
void ATCMiThermometer::dump_config() {
void ATCMiThermometer::dump_child_config() {
ESP_LOGCONFIG(TAG, "ATC MiThermometer");
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "Humidity", this->humidity_sensor_);
@@ -1,6 +1,5 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
@@ -16,7 +15,7 @@ struct ParseResult {
int raw_offset;
};
class ATCMiThermometer final : public Component, public ble_device_base::ESPBTDeviceListener {
class ATCMiThermometer final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
SUB_SENSOR(battery_level)
@@ -27,7 +26,7 @@ class ATCMiThermometer final : public Component, public ble_device_base::ESPBTDe
void set_address(uint64_t address) { address_ = address; };
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
uint64_t address_;
@@ -28,7 +28,7 @@ AUTO_LOAD = ["ble_device_base"]
atc_mithermometer_ns = cg.esphome_ns.namespace("atc_mithermometer")
ATCMiThermometer = atc_mithermometer_ns.class_(
"ATCMiThermometer", ble_device_base.ESPBTDeviceListener, cg.Component
"ATCMiThermometer", ble_device_base.ESPBTDeviceListener
)
CONFIG_SCHEMA = cv.All(
@@ -71,14 +71,12 @@ CONFIG_SCHEMA = cv.All(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -39,8 +39,8 @@ void AXS15231Touchscreen::update_touches() {
this->status_clear_warning();
if (data[0] != 0 || data[1] == 0) // no touches
return;
uint16_t x = encode_uint16(data[2] & 0xF, data[3]);
uint16_t y = encode_uint16(data[4] & 0xF, data[5]);
uint16_t x = encode_uint16(low_nibble(data[2]), data[3]);
uint16_t y = encode_uint16(low_nibble(data[4]), data[5]);
this->add_raw_touch_position_(0, x, y);
}
+1 -1
View File
@@ -6,7 +6,7 @@ namespace esphome::b_parasite {
ESPHOME_LOG_TAG(TAG, "b_parasite");
void BParasite::dump_config() {
void BParasite::dump_child_config() {
ESP_LOGCONFIG(TAG, "b_parasite");
LOG_SENSOR(" ", "Battery Voltage", this->battery_voltage_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
+2 -3
View File
@@ -1,12 +1,11 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
namespace esphome::b_parasite {
class BParasite final : public Component, public ble_device_base::ESPBTDeviceListener {
class BParasite final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(battery_voltage)
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
@@ -18,7 +17,7 @@ class BParasite final : public Component, public ble_device_base::ESPBTDeviceLis
void set_bindkey(const std::string &bindkey);
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
// The received advertisement packet contains an unsigned 4 bits wrap-around counter
+3 -7
View File
@@ -26,9 +26,7 @@ CODEOWNERS = ["@rbaron"]
AUTO_LOAD = ["ble_device_base"]
b_parasite_ns = cg.esphome_ns.namespace("b_parasite")
BParasite = b_parasite_ns.class_(
"BParasite", ble_device_base.ESPBTDeviceListener, cg.Component
)
BParasite = b_parasite_ns.class_("BParasite", ble_device_base.ESPBTDeviceListener)
CONFIG_SCHEMA = cv.All(
ble_device_base.rename_legacy_hub_id("b_parasite"),
@@ -68,14 +66,12 @@ CONFIG_SCHEMA = cv.All(
state_class=STATE_CLASS_MEASUREMENT,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -206,6 +206,7 @@ void BK72xxBLETracker::dump_config() {
this->scan_duration_ / 1000, ble_units_to_ms(this->scan_interval_), this->scan_interval_,
ble_units_to_ms(this->scan_window_), this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
this->scan_active_configured_ ? "ACTIVE" : "PASSIVE", YESNO(this->scan_continuous_));
this->dispatcher_.dump_child_configs();
}
// ---------------------------------------------------------------------------
@@ -35,6 +35,7 @@ from esphome.const import (
CONF_ACTIVE,
CONF_CONTINUOUS,
CONF_DURATION,
CONF_ID,
CONF_INTERVAL,
KEY_TARGET_PLATFORM,
)
@@ -193,6 +194,11 @@ def new_ble_device_component(
return cg.new_bus_component(register_ble_device, config, *args)
async def new_ble_device(config: ConfigType, *args: Any) -> cg.MockObj:
"""Construct a listener that is not a Component and attach it to the BLE hub."""
return await register_ble_device(cg.new_Pvariable(config[CONF_ID], *args), config)
# ---- shared validation / codegen helpers (platform-neutral) ----
@@ -323,6 +323,8 @@ class ESPBTDeviceListener {
/// Called at the end of each scan duration period.
virtual void on_scan_end() {}
virtual bool parse_device(const ESPBTDevice &device) = 0;
/// Called from the tracker's dump_config(); not dump_config() so Component listeners don't print twice.
virtual void dump_child_config() {}
};
} // namespace esphome::ble_device_base
@@ -58,6 +58,13 @@ class AdvDispatcher {
bool raw_only, const char *log_unclaimed_tag);
/// Fire listeners' on_scan_end and reset the per-scan discovered-log dedup.
void on_scan_end();
/// Print each listener's dump_child_config(); called from the tracker's dump_config().
void dump_child_configs() {
#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
for (auto *listener : this->listeners_)
listener->dump_child_config();
#endif
}
protected:
RawAdvertisementCallback raw_callback_{};
@@ -5,6 +5,6 @@ namespace esphome::ble_rssi {
ESPHOME_LOG_TAG(TAG, "ble_rssi");
void BLERSSISensor::dump_config() { LOG_SENSOR("", "BLE RSSI Sensor", this); }
void BLERSSISensor::dump_child_config() { LOG_SENSOR("", "BLE RSSI Sensor", this); }
} // namespace esphome::ble_rssi
@@ -1,6 +1,5 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
@@ -10,7 +9,7 @@
// guard.
namespace esphome::ble_rssi {
class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBTDeviceListener, public Component {
class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBTDeviceListener {
public:
void set_address(uint64_t address) {
this->match_by_ = MATCH_BY_MAC_ADDRESS;
@@ -100,7 +99,7 @@ class BLERSSISensor final : public sensor::Sensor, public ble_device_base::ESPBT
}
return false;
}
void dump_config() override;
void dump_child_config() override;
protected:
enum MatchType { MATCH_BY_MAC_ADDRESS, MATCH_BY_IRK, MATCH_BY_SERVICE_UUID, MATCH_BY_IBEACON_UUID };
+1 -3
View File
@@ -19,7 +19,7 @@ AUTO_LOAD = ["ble_device_base"]
ble_rssi_ns = cg.esphome_ns.namespace("ble_rssi")
BLERSSISensor = ble_rssi_ns.class_(
"BLERSSISensor", sensor.Sensor, cg.Component, ble_device_base.ESPBTDeviceListener
"BLERSSISensor", sensor.Sensor, ble_device_base.ESPBTDeviceListener
)
@@ -50,7 +50,6 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_IBEACON_UUID): ble_device_base.bt_uuid,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
cv.has_exactly_one_key(
CONF_MAC_ADDRESS, CONF_IRK, CONF_SERVICE_UUID, CONF_IBEACON_UUID
@@ -61,7 +60,6 @@ CONFIG_SCHEMA = cv.All(
async def to_code(config: ConfigType) -> None:
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
if mac_address := config.get(CONF_MAC_ADDRESS):
@@ -5,6 +5,6 @@ namespace esphome::ble_scanner {
ESPHOME_LOG_TAG(TAG, "ble_scanner");
void BLEScanner::dump_config() { LOG_TEXT_SENSOR("", "BLE Scanner", this); }
void BLEScanner::dump_child_config() { LOG_TEXT_SENSOR("", "BLE Scanner", this); }
} // namespace esphome::ble_scanner
+2 -3
View File
@@ -4,7 +4,6 @@
#include <cstdio>
#include <ctime>
#include "esphome/core/component.h"
#include "esphome/core/helpers.h"
#include "esphome/core/string_ref.h"
#include "esphome/components/ble_device_base/ble_device.h"
@@ -16,7 +15,7 @@
// guard.
namespace esphome::ble_scanner {
class BLEScanner final : public text_sensor::TextSensor, public ble_device_base::ESPBTDeviceListener, public Component {
class BLEScanner final : public text_sensor::TextSensor, public ble_device_base::ESPBTDeviceListener {
public:
bool parse_device(const ble_device_base::ESPBTDevice &device) override {
char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
@@ -31,7 +30,7 @@ class BLEScanner final : public text_sensor::TextSensor, public ble_device_base:
this->publish_state(buf);
return true;
}
void dump_config() override;
void dump_child_config() override;
};
} // namespace esphome::ble_scanner
@@ -9,19 +9,17 @@ ble_scanner_ns = cg.esphome_ns.namespace("ble_scanner")
BLEScanner = ble_scanner_ns.class_(
"BLEScanner",
text_sensor.TextSensor,
cg.Component,
ble_device_base.ESPBTDeviceListener,
)
CONFIG_SCHEMA = cv.All(
ble_device_base.rename_legacy_hub_id("ble_scanner"),
text_sensor.text_sensor_schema(BLEScanner)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
text_sensor.text_sensor_schema(BLEScanner).extend(
ble_device_base.BLE_DEVICE_SCHEMA
),
)
async def to_code(config: ConfigType) -> None:
var = await text_sensor.new_text_sensor(config)
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
@@ -114,10 +114,10 @@ void BME280Component::setup() {
this->calibration_.h1 = read_u8_(BME280_REGISTER_DIG_H1);
this->calibration_.h2 = read_s16_le_(BME280_REGISTER_DIG_H2);
this->calibration_.h3 = read_u8_(BME280_REGISTER_DIG_H3);
this->calibration_.h4 =
sign_extend<12>(read_u8_(BME280_REGISTER_DIG_H4) << 4 | (read_u8_(BME280_REGISTER_DIG_H4 + 1) & 0x0F));
this->calibration_.h5 =
sign_extend<12>(read_u8_(BME280_REGISTER_DIG_H5 + 1) << 4 | (read_u8_(BME280_REGISTER_DIG_H5) >> 4));
this->calibration_.h4 = sign_extend<12>(
encode_uint12(read_u8_(BME280_REGISTER_DIG_H4), low_nibble(read_u8_(BME280_REGISTER_DIG_H4 + 1))));
this->calibration_.h5 = sign_extend<12>(
encode_uint12(read_u8_(BME280_REGISTER_DIG_H5 + 1), high_nibble(read_u8_(BME280_REGISTER_DIG_H5))));
this->calibration_.h6 = read_u8_(BME280_REGISTER_DIG_H6);
uint8_t humid_control_val = 0;
+4 -3
View File
@@ -70,8 +70,9 @@ bool BME680Component::setup_registers_() {
this->calibration_.t2 = encode_value_le<int16_t>(&coeff1[1]);
this->calibration_.t3 = coeff1[3];
this->calibration_.h1 = coeff2[2] << 4 | (coeff2[1] & 0x0F);
this->calibration_.h2 = encode_uint16(coeff2[0], coeff2[1]) >> 4;
// H1 and H2 are 12-bit values sharing byte 1: its low nibble ends H1, its high nibble ends H2
this->calibration_.h1 = encode_uint12(coeff2[2], low_nibble(coeff2[1]));
this->calibration_.h2 = encode_uint12(coeff2[0], high_nibble(coeff2[1]));
this->calibration_.h3 = coeff2[3];
this->calibration_.h4 = coeff2[4];
this->calibration_.h5 = coeff2[5];
@@ -243,7 +244,7 @@ void BME680Component::read_data_() {
uint32_t raw_pressure = encode_uint24(data[2], data[3], data[4]) >> 4;
uint32_t raw_humidity = encode_uint16(data[8], data[9]);
uint16_t raw_gas = encode_uint16(data[13], data[14]) >> 6;
uint8_t gas_range = data[14] & 0x0F;
uint8_t gas_range = low_nibble(data[14]);
float temperature = this->calc_temperature_(raw_temperature);
float pressure = this->calc_pressure_(raw_pressure);
@@ -15,7 +15,7 @@ CONF_REPLAY_PROTECTION = "replay_protection"
bthome_mithermometer_ns = cg.esphome_ns.namespace("bthome_mithermometer")
BTHomeMiThermometer = bthome_mithermometer_ns.class_(
"BTHomeMiThermometer", ble_device_base.ESPBTDeviceListener, cg.Component
"BTHomeMiThermometer", ble_device_base.ESPBTDeviceListener
)
@@ -34,7 +34,6 @@ def bthome_mithermometer_base_schema(
cv.Optional(CONF_REPLAY_PROTECTION, default=False): cv.boolean,
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(extra_schema)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
_validate_replay_protection,
@@ -51,7 +50,6 @@ def _validate_replay_protection(config: ConfigType) -> ConfigType:
async def setup_bthome_mithermometer(var: MockObj, config: ConfigType) -> None:
await cg.register_component(var, config)
await ble_device_base.register_ble_device(var, config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
if bindkey := config.get(CONF_BINDKEY):
@@ -154,7 +154,7 @@ static bool get_bthome_value_length(uint8_t obj_type, size_t &value_length) {
}
}
void BTHomeMiThermometer::dump_config() {
void BTHomeMiThermometer::dump_child_config() {
char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
ESP_LOGCONFIG(TAG, "BTHome MiThermometer");
ESP_LOGCONFIG(TAG, " MAC Address: %s", format_mac_address(addr_buf, this->address_));
@@ -2,7 +2,6 @@
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
#include <cstdint>
#include <initializer_list>
@@ -17,7 +16,7 @@ namespace testing {
class ReplayClockAccess;
} // namespace testing
class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener, public Component {
class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(humidity)
SUB_SENSOR(battery_level)
@@ -31,7 +30,7 @@ class BTHomeMiThermometer final : public ble_device_base::ESPBTDeviceListener, p
void set_replay_protection(bool replay_protection) { this->replay_protection_ = replay_protection; }
#endif
void dump_config() override;
void dump_child_config() override;
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
protected:
+1
View File
@@ -36,6 +36,7 @@ CONF_CONVERSION_RATE = "conversion_rate"
CONF_CRC_ENABLE = "crc_enable"
CONF_DATA_BITS = "data_bits"
CONF_DESCRIPTION = "description"
CONF_DESTINATION = "destination"
CONF_DEVICE_TYPE = "device_type"
CONF_DISCONNECTS = "disconnects"
CONF_DRAW_ROUNDING = "draw_rounding"
@@ -68,7 +68,7 @@ void CST3240Touchscreen::update_touches() {
return;
}
const uint8_t count = data[cstxxx::FINGER_COUNT_IDX] & 0x0F;
const uint8_t count = low_nibble(data[cstxxx::FINGER_COUNT_IDX]);
if (count <= CST3240_MAX_TOUCHES) {
for (uint8_t i = 0; i < count; i++) {
auto touch = cstxxx::decode_touch(data, i);
@@ -1,4 +1,5 @@
#include "cst328_touchscreen.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::cst328 {
@@ -99,7 +100,7 @@ void CST328Touchscreen::update_touches() {
return;
}
uint8_t touch_cnt = touch_data[CST_REG_FINGER_COUNT_IDX] & 0x0F;
uint8_t touch_cnt = low_nibble(touch_data[CST_REG_FINGER_COUNT_IDX]);
if (touch_cnt == 0 || touch_cnt > CST328_TOUCH_MAX_POINTS) {
this->update_button_state_(false);
} else {
@@ -68,8 +68,8 @@ void CST816Touchscreen::update_touches() {
return;
}
uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]);
uint16_t x = encode_uint16(low_nibble(data[REG_XPOS_HIGH]), data[REG_XPOS_LOW]);
uint16_t y = encode_uint16(low_nibble(data[REG_YPOS_HIGH]), data[REG_YPOS_LOW]);
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
this->add_raw_touch_position_(0, x, y);
}
+10 -3
View File
@@ -37,11 +37,18 @@ struct TouchRecord {
uint8_t z;
};
/// Decodes record `index` of a touch report.
/// Decodes record `index` of a touch report. Each record is 5 bytes:
/// [id:4 | event:4] [x 11..4] [y 11..4] [x 3..0 | y 3..0] [z].
/// The first record is followed by 2 extra bytes, so later records start 2 bytes further on.
inline TouchRecord decode_touch(const uint8_t *report, uint8_t index) {
const uint8_t *r = report + index * 5 + (index == 0 ? 0 : 2);
return {static_cast<uint8_t>(r[0] >> 4), static_cast<uint8_t>(r[0] & 0x0F),
static_cast<uint16_t>(r[1] << 4 | r[3] >> 4), static_cast<uint16_t>(r[2] << 4 | (r[3] & 0x0F)), r[4]};
return {
.id = high_nibble(r[0]),
.event = low_nibble(r[0]),
.x = encode_uint12(r[1], high_nibble(r[3])),
.y = encode_uint12(r[2], low_nibble(r[3])),
.z = r[4],
};
}
class CSTTouchscreen : public touchscreen::Touchscreen, public i2c::I2CDevice {
+15 -7
View File
@@ -4,6 +4,7 @@
#include "esphome/components/remote_base/remote_base.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
namespace esphome::daikin_arc {
@@ -23,7 +24,10 @@ void DaikinArcClimate::setup() {
}
void DaikinArcClimate::transmit_query_() {
uint8_t remote_header[8] = {0x11, 0xDA, 0x27, 0x00, 0x84, 0x87, 0x20, 0x00};
// In flash: an initialized local array is copied from a RAM constant on ESP8266
static constexpr uint8_t REMOTE_HEADER_TEMPLATE[8] PROGMEM = {0x11, 0xDA, 0x27, 0x00, 0x84, 0x87, 0x20, 0x00};
uint8_t remote_header[sizeof(REMOTE_HEADER_TEMPLATE)];
progmem_memcpy(remote_header, REMOTE_HEADER_TEMPLATE, sizeof(remote_header));
// Calculate checksum
for (size_t i = 0; i < sizeof(remote_header) - 1; i++) {
@@ -50,11 +54,13 @@ void DaikinArcClimate::transmit_query_() {
void DaikinArcClimate::transmit_state() {
// 0x11, 0xDA, 0x27, 0x00, 0xC5, 0x00, 0x00, 0xD7, 0x11, 0xDA, 0x27, 0x00,
// 0x42, 0x49, 0x05, 0xA2,
uint8_t remote_header[20] = {0x11, 0xDA, 0x27, 0x00, 0x02, 0xd0, 0x02, 0x03, 0x80, 0x03, 0x82, 0x30, 0x41, 0x1f, 0x82,
0xf4,
/* とつど */
/* 0x13 */
0x00, 0x24, 0x00, 0x00};
static constexpr uint8_t REMOTE_HEADER_TEMPLATE[20] PROGMEM = {
0x11, 0xDA, 0x27, 0x00, 0x02, 0xd0, 0x02, 0x03, 0x80, 0x03, 0x82, 0x30, 0x41, 0x1f, 0x82, 0xf4,
/* とつど */
/* 0x13 */
0x00, 0x24, 0x00, 0x00};
uint8_t remote_header[sizeof(REMOTE_HEADER_TEMPLATE)];
progmem_memcpy(remote_header, REMOTE_HEADER_TEMPLATE, sizeof(remote_header));
// 05 0 [1:3]MODE 1 [OFF TMR] [ON TMR] Power
// 06-07 TEMP
@@ -68,7 +74,7 @@ void DaikinArcClimate::transmit_state() {
// 16 [0:3] 8 00 [6:7] SENSOR WIND = 11 / NORMAL = 00
// 17 24
uint8_t remote_state[19] = {
static constexpr uint8_t REMOTE_STATE_TEMPLATE[DAIKIN_STATE_FRAME_SIZE] PROGMEM = {
0x11, 0xDA, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x60, 0x00, 0x0a, 0xC4,
/* MODE TEMP HUMD FANH FANL
パワフル音声応答 */
@@ -81,6 +87,8 @@ void DaikinArcClimate::transmit_state() {
/* ON 0x83 */
/* OF 0x80 */
};
uint8_t remote_state[sizeof(REMOTE_STATE_TEMPLATE)];
progmem_memcpy(remote_state, REMOTE_STATE_TEMPLATE, sizeof(remote_state));
remote_state[5] = this->operation_mode_() | 0x08;
remote_state[6] = this->temperature_();
+3 -1
View File
@@ -605,7 +605,9 @@ async def to_code(config: ConfigType) -> None:
cg.add(var.set_type(conf[CONF_TYPE]))
for conf in config[CONF_SELECTS]:
var = await select.new_select(conf, options=conf[CONF_OPTIONS])
var = await select.new_select(
conf, options=conf[CONF_OPTIONS], fixed_options=True
)
await cg.register_component(var, conf)
for conf in config[CONF_SENSORS]:
+1 -1
View File
@@ -41,5 +41,5 @@ CONFIG_SCHEMA = (
async def to_code(config: ConfigType) -> None:
var = await select.new_select(config, options=DUCO_MODE_OPTIONS)
var = await select.new_select(config, options=DUCO_MODE_OPTIONS, fixed_options=True)
await register_duco_device(var, config, config[CONF_DUCO_ID])
@@ -35,12 +35,12 @@ void EKTF2232Touchscreen::setup() {
if (err == i2c::ERROR_OK) {
err = this->read(received, 4);
if (err == i2c::ERROR_OK) {
this->x_raw_max_ = ((received[2])) | ((received[3] & 0xf0) << 4);
this->x_raw_max_ = encode_uint16(high_nibble(received[3]), received[2]);
err = this->write(GET_Y_RES, 4);
if (err == i2c::ERROR_OK) {
err = this->read(received, 4);
if (err == i2c::ERROR_OK) {
this->y_raw_max_ = ((received[2])) | ((received[3] & 0xf0) << 4);
this->y_raw_max_ = encode_uint16(high_nibble(received[3]), received[2]);
}
}
}
@@ -74,8 +74,9 @@ void EKTF2232Touchscreen::update_touches() {
for (int i = 0; i < touch_count; i++) {
uint8_t *d = raw + 1 + (i * 3);
x_raw = (d[0] & 0xF0) << 4 | d[1];
y_raw = (d[0] & 0x0F) << 8 | d[2];
// d[0] holds the top 4 bits of X (high nibble) and of Y (low nibble)
x_raw = encode_uint16(high_nibble(d[0]), d[1]);
y_raw = encode_uint16(low_nibble(d[0]), d[2]);
this->add_raw_touch_position_(i, x_raw, y_raw);
}
}
@@ -485,6 +485,14 @@ void ESP32BLETracker::dump_config() {
if (this->scan_start_fail_count_) {
ESP_LOGCONFIG(TAG, " Scan Start Fail Count: %d", this->scan_start_fail_count_);
}
#ifdef ESPHOME_ESP32_BLE_TRACKER_LISTENER_COUNT
for (auto *listener : this->listeners_)
listener->dump_child_config();
#endif
#ifdef ESPHOME_BLE_DEVICE_BASE_LISTENER_COUNT
for (auto *listener : this->neutral_listeners_)
listener->dump_child_config();
#endif
}
#ifdef USE_ESP32_BLE_DEVICE
@@ -69,8 +69,8 @@ void FT5x06Touchscreen::update_touches() {
for (uint8_t i = 0; i != touch_cnt; i++) {
uint8_t status = data[i][0] >> 6;
uint8_t id = data[i][2] >> 3;
uint16_t x = encode_uint16(data[i][0] & 0x0F, data[i][1]);
uint16_t y = encode_uint16(data[i][2] & 0xF, data[i][3]);
uint16_t x = encode_uint16(low_nibble(data[i][0]), data[i][1]);
uint16_t y = encode_uint16(low_nibble(data[i][2]), data[i][3]);
ESP_LOGV(TAG, "Read %X status, id: %d, pos %d/%d", status, id, x, y);
if (status == 0 || status == 2) {
+5 -5
View File
@@ -90,31 +90,31 @@ void FT63X6Touchscreen::update_touches() {
}
}
uint8_t FT63X6Touchscreen::read_touch_number_() { return this->read_byte_(FT63X6_ADDR_TD_STATUS) & 0x0F; }
uint8_t FT63X6Touchscreen::read_touch_number_() { return low_nibble(this->read_byte_(FT63X6_ADDR_TD_STATUS)); }
// Touch 1 functions
uint16_t FT63X6Touchscreen::read_touch_x_(uint8_t touch) {
uint8_t read_buf[2];
read_buf[0] = this->read_byte_(FT63X6_ADDR_TOUCH1_X + (touch * 6));
read_buf[1] = this->read_byte_(FT63X6_ADDR_TOUCH1_X + 1 + (touch * 6));
return encode_uint16(read_buf[0] & 0x0f, read_buf[1]);
return encode_uint16(low_nibble(read_buf[0]), read_buf[1]);
}
uint16_t FT63X6Touchscreen::read_touch_y_(uint8_t touch) {
uint8_t read_buf[2];
read_buf[0] = this->read_byte_(FT63X6_ADDR_TOUCH1_Y + (touch * 6));
read_buf[1] = this->read_byte_(FT63X6_ADDR_TOUCH1_Y + 1 + (touch * 6));
return encode_uint16(read_buf[0] & 0x0f, read_buf[1]);
return encode_uint16(low_nibble(read_buf[0]), read_buf[1]);
}
uint8_t FT63X6Touchscreen::read_touch_event_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_X + (touch * 6)) >> 6;
}
uint8_t FT63X6Touchscreen::read_touch_id_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_ID + (touch * 6)) >> 4;
return high_nibble(this->read_byte_(FT63X6_ADDR_TOUCH1_ID + (touch * 6)));
}
uint8_t FT63X6Touchscreen::read_touch_weight_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_WEIGHT + (touch * 6));
}
uint8_t FT63X6Touchscreen::read_touch_misc_(uint8_t touch) {
return this->read_byte_(FT63X6_ADDR_TOUCH1_MISC + (touch * 6)) >> 4;
return high_nibble(this->read_byte_(FT63X6_ADDR_TOUCH1_MISC + (touch * 6)));
}
uint8_t FT63X6Touchscreen::read_byte_(uint8_t addr) {
@@ -1,6 +1,7 @@
#include "gsl3670_touchscreen.h"
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#include "esphome/core/helpers.h"
namespace esphome::gsl3670 {
@@ -66,10 +67,11 @@ void GSL3670Touchscreen::update_touches() {
// Build gsl_touch_info exactly as the Seeed driver does
for (uint8_t j = 0; j != finger_num; j++) {
// buf[(j+1)*4 + 0..3]: byte0=y_lo, byte1=y_hi, byte2=x_lo, byte3=id|x_hi
auto x = (uint16_t) (((buf[(j + 1) * 4 + 3] & 0x0f) << 8) | buf[(j + 1) * 4 + 2]);
auto y = (uint16_t) ((buf[(j + 1) * 4 + 1] << 8) | buf[(j + 1) * 4 + 0]);
auto id = (buf[(j + 1) * 4 + 3] >> 4) & 0x0f;
// Record: y_lo, y_hi, x_lo, then the id (high nibble) and the top 4 bits of X (low nibble)
const uint8_t *record = &buf[(j + 1) * 4];
auto x = encode_uint16(low_nibble(record[3]), record[2]);
auto y = encode_uint16(record[1], record[0]);
auto id = high_nibble(record[3]);
ESP_LOGV(TAG, "Touch id=%u, x=%u y=%u", id, x, y);
if (x <= 8192 && y <= 8192)
this->add_raw_touch_position_(id, x, y);
+1 -1
View File
@@ -1,5 +1,6 @@
from esphome import automation, pins
import esphome.codegen as cg
from esphome.components.const import CONF_DESTINATION
from esphome.components.esp32 import include_builtin_idf_component
import esphome.config_validation as cv
from esphome.const import (
@@ -26,7 +27,6 @@ MAX_LOGICAL_ADDRESS = 15
MAX_PAYLOAD_LENGTH = 15
CONF_PROMISCUOUS_MODE = "promiscuous_mode"
CONF_MONITOR_MODE = "monitor_mode"
CONF_DESTINATION = "destination"
CONF_OPCODE = "opcode"
hdmi_cec_ns = cg.esphome_ns.namespace("hdmi_cec")
+31 -9
View File
@@ -1,6 +1,7 @@
from collections.abc import Callable, Iterable
from dataclasses import dataclass
from esphome.automation import parent_ref
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.const import CONF_ATTRIBUTE, CONF_ENTITY_ID, CONF_ID, CONF_INTERNAL
@@ -14,6 +15,14 @@ CODEOWNERS = ["@OttoWinter", "@esphome/core"]
DOMAIN = "homeassistant"
homeassistant_ns = cg.esphome_ns.namespace("homeassistant")
# The API server subscribes the imported entities in its setup() and prints their dumps
IMPORT_SUBSCRIBE = cg.HubFunction(
"homeassistant_subscribe", cg.void, [], define="USE_API_HOMEASSISTANT_IMPORTS"
)
IMPORT_DUMP = cg.HubFunction(
"homeassistant_dump", cg.void, [], define="USE_API_HOMEASSISTANT_IMPORTS"
)
def validate_entity_domain(
platform: str, supported_domains: Iterable[str]
@@ -31,14 +40,6 @@ def validate_entity_domain(
return validator
HOME_ASSISTANT_IMPORT_SCHEMA = cv.Schema(
{
cv.Optional(CONF_ENTITY_ID): cv.entity_id,
cv.Optional(CONF_ATTRIBUTE): cv.string,
cv.Optional(CONF_INTERNAL, default=True): cv.boolean,
}
)
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA = cv.Schema(
{
cv.Optional(CONF_ENTITY_ID): cv.entity_id,
@@ -46,6 +47,12 @@ HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA = cv.Schema(
}
)
HOME_ASSISTANT_IMPORT_SCHEMA = HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA.extend(
{
cv.Optional(CONF_ATTRIBUTE): cv.string,
}
)
def final_validate_entity_id(config: ConfigType) -> ConfigType:
"""Without an entity_id, the entity must be a wizard input, as Home Assistant then supplies it."""
@@ -82,8 +89,14 @@ async def _emit_state_subscription_count_define() -> None:
def setup_home_assistant_entity(
var: MockObj, config: ConfigType, state_subscription_count: int = 1
var: MockObj,
config: ConfigType,
state_subscription_count: int = 1,
services: bool = False,
) -> None:
"""Set up an imported entity; services for one that sends actions."""
if services:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
# A wizard input has no entity_id; the api wizard sets it
cg.add_optional(var.set_entity_id, config.get(CONF_ENTITY_ID))
cg.add_optional(var.set_attribute, config.get(CONF_ATTRIBUTE))
@@ -93,3 +106,12 @@ def setup_home_assistant_entity(
if data.state_subscription_count == 0:
CORE.add_job(_emit_state_subscription_count_define)
data.state_subscription_count += state_subscription_count
async def register_home_assistant_import(var: MockObj) -> None:
"""Attach an imported entity to the API server, which subscribes it and prints its dump."""
from esphome.components.api import DOMAIN as API_DOMAIN
api = await cg.get_variable(CORE.config[API_DOMAIN][CONF_ID])
IMPORT_SUBSCRIBE.add(api, parent_ref(var).subscribe())
IMPORT_DUMP.add(api, parent_ref(var).dump_config())
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import binary_sensor
from esphome.types import ConfigType
@@ -6,6 +5,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
@@ -14,7 +14,7 @@ DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
HomeassistantBinarySensor = homeassistant_ns.class_(
"HomeassistantBinarySensor", binary_sensor.BinarySensor, cg.Component
"HomeassistantBinarySensor", binary_sensor.BinarySensor
)
CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(HomeassistantBinarySensor).extend(
@@ -26,5 +26,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await binary_sensor.new_binary_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -8,35 +8,25 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.binary_sensor");
void HomeassistantBinarySensor::setup() {
void HomeassistantBinarySensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
auto val = parse_on_off(state.c_str());
switch (val) {
case PARSE_NONE:
case PARSE_TOGGLE:
// Home Assistant sends these when there is no value, which is not an error
if (is_unset(state)) {
ESP_LOGV(TAG, "'%s': No value (%s)", this->entity_id_, state.c_str());
} else {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
}
break;
case PARSE_ON:
case PARSE_OFF:
bool new_state = val == PARSE_ON;
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_, this->attribute_, ONOFF(new_state));
} else {
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
}
if (this->initial_) {
this->publish_initial_state(new_state);
} else {
this->publish_state(new_state);
}
break;
if (val != PARSE_ON && val != PARSE_OFF) {
// Home Assistant sends these when there is no value, which is not an error
if (is_unset(state)) {
ESP_LOGV(TAG, "'%s': No value (%s)", this->entity_id_, state.c_str());
} else {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
}
return;
}
this->initial_ = false;
bool new_state = val == PARSE_ON;
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state %s", this->entity_id_, this->attribute_, ONOFF(new_state));
} else {
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
}
this->publish_state(new_state);
});
}
void HomeassistantBinarySensor::dump_config() {
@@ -46,6 +36,5 @@ void HomeassistantBinarySensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantBinarySensor::get_setup_priority() const { return setup_priority::AFTER_WIFI; }
} // namespace esphome::homeassistant
@@ -1,22 +1,19 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/binary_sensor/binary_sensor.h"
namespace esphome::homeassistant {
class HomeassistantBinarySensor final : public binary_sensor::BinarySensor, public Component {
class HomeassistantBinarySensor final : public binary_sensor::BinarySensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
const char *attribute_{nullptr};
bool initial_{true};
};
} // namespace esphome::homeassistant
@@ -1,11 +1,32 @@
#include "homeassistant.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
#ifdef USE_API_HOMEASSISTANT_SERVICES
#include "esphome/components/api/api_server.h"
#endif
namespace esphome::homeassistant {
PROGMEM_STRING_TABLE(UnsetValues, "None", "unavailable", "unknown");
bool is_unset(StringRef value) { return progmem_string_table_find<UnsetValues>(value.c_str(), value.size()) >= 0; }
#ifdef USE_API_HOMEASSISTANT_SERVICES
bool can_send_action(const char *tag, const char *entity_id, [[maybe_unused]] EntityBase *entity) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(tag, "'%s': No clients connected to API server", entity_id);
return false;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (entity_id[0] == '\0') {
ESP_LOGW(tag, "'%s': No entity ID set yet", LOG_STR_ARG(entity->get_log_name()));
return false;
}
#endif
return true;
}
#endif
} // namespace esphome::homeassistant
@@ -2,15 +2,40 @@
#include <cctype>
#include "esphome/core/defines.h"
#include "esphome/core/entity_base.h"
#include "esphome/core/helpers.h"
#include "esphome/core/progmem.h"
#include "esphome/core/string_ref.h"
#ifdef USE_API_HOMEASSISTANT_SERVICES
#include "esphome/components/api/api_pb2.h"
#endif
namespace esphome::homeassistant {
/// True for what Home Assistant reports when there is no value: "None" for an attribute that is not
/// set, "unavailable" and "unknown" for the state of an entity that is not ready
bool is_unset(StringRef value);
/// True if entity_id is an input helper; input_service must start with "input_"
inline bool is_input_helper(const char *entity_id, const char *input_service) {
return ESPHOME_strncmp_P(entity_id, input_service, sizeof("input_") - 1) == 0;
}
#ifdef USE_API_HOMEASSISTANT_SERVICES
/// Logs and returns false when no API client is connected or no entity is linked yet
bool can_send_action(const char *tag, const char *entity_id, EntityBase *entity);
/// Adds the entity_id entry to an action's data
inline void add_entity_id(api::HomeassistantActionRequest &resp, const char *entity_id) {
static constexpr char ENTITY_ID_KEY[] PROGMEM = "entity_id";
auto &entry = resp.data.emplace_back();
entry.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entry.value = ProgmemStringRef(StringRef(entity_id));
}
#endif
/// Emit the UTF-8 encoding of a code point. Rejects NUL, which would end the item early.
template<typename C> bool emit_utf8(uint32_t code_point, C &on_char) {
if (code_point == 0 || code_point > 0x10FFFF)
@@ -72,10 +72,9 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await light.new_light(config)
await cg.register_component(var, config)
cg.add(var.set_report_timeout(config[CONF_REPORT_TIMEOUT].total_seconds))
# 1 state + supported_color_modes, min/max_color_temp_kelvin, color_mode, brightness,
# color_temp_kelvin and rgb_color in HomeassistantLight::setup()
setup_home_assistant_entity(var, config, state_subscription_count=8)
setup_home_assistant_entity(var, config, state_subscription_count=8, services=True)
@@ -25,7 +25,7 @@ namespace {
// color mode, all handled as RGB: Home Assistant reports rgb_color for all of them and derives
// the white channels from rgb_color itself.
PROGMEM_STRING_TABLE(ColorModeNames, "onoff", "brightness", "white", "color_temp", "hs", "xy", "rgb", "rgbw", "rgbww");
const uint8_t COLOR_MODES[] PROGMEM = {
constexpr uint8_t COLOR_MODES[] PROGMEM = {
static_cast<uint8_t>(ColorMode::ON_OFF),
static_cast<uint8_t>(ColorMode::BRIGHTNESS),
static_cast<uint8_t>(ColorMode::WHITE),
@@ -381,27 +381,18 @@ void HomeassistantLight::write_state(LightState *state) {
}
return;
}
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "'%s': No clients connected to API server, change lost", this->entity_id_);
if (!can_send_action(TAG, this->entity_id_, state)) {
this->fall_back_();
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(state->get_log_name()));
this->fall_back_();
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_TURN_ON[] PROGMEM = "light.turn_on";
static const char SERVICE_TURN_OFF[] PROGMEM = "light.turn_off";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char BRIGHTNESS_KEY[] PROGMEM = "brightness";
static const char WHITE_KEY[] PROGMEM = "white";
static const char COLOR_TEMP_KELVIN_KEY[] PROGMEM = "color_temp_kelvin";
static const char RGB_COLOR_KEY[] PROGMEM = "rgb_color";
static constexpr char SERVICE_TURN_ON[] PROGMEM = "light.turn_on";
static constexpr char SERVICE_TURN_OFF[] PROGMEM = "light.turn_off";
static constexpr char BRIGHTNESS_KEY[] PROGMEM = "brightness";
static constexpr char WHITE_KEY[] PROGMEM = "white";
static constexpr char COLOR_TEMP_KELVIN_KEY[] PROGMEM = "color_temp_kelvin";
static constexpr char RGB_COLOR_KEY[] PROGMEM = "rgb_color";
// The request refers to these buffers until it is sent below
char level_buf[4]; // up to 255
@@ -410,9 +401,7 @@ void HomeassistantLight::write_state(LightState *state) {
api::HomeassistantActionRequest resp;
resp.data.init(3);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto add_number = [&](ProgmemStringRef key, char *buf, size_t size, unsigned number) {
auto &entry = resp.data.emplace_back();
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import number
import esphome.config_validation as cv
from esphome.types import ConfigType
@@ -7,23 +6,23 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@landonr"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = ["input_number", "number"]
HomeassistantNumber = homeassistant_ns.class_(
"HomeassistantNumber", number.Number, cg.Component
)
HomeassistantNumber = homeassistant_ns.class_("HomeassistantNumber", number.Number)
CONFIG_SCHEMA = cv.All(
number.number_schema(HomeassistantNumber)
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
number.number_schema(HomeassistantNumber).extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("number", SUPPORTED_DOMAINS),
)
@@ -31,13 +30,12 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await number.new_number(
config,
min_value=0,
max_value=0,
step=0,
)
await cg.register_component(var, config)
# 1 state + min/max/step fetches in HomeassistantNumber::setup()
setup_home_assistant_entity(var, config, state_subscription_count=4)
# 1 state + min/max/step fetches in HomeassistantNumber::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=4, services=True)
await register_home_assistant_import(var)
@@ -1,6 +1,6 @@
#include "homeassistant_number.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_server.h"
@@ -26,46 +26,32 @@ void HomeassistantNumber::state_changed_(StringRef state) {
this->publish_state(number_value.value());
}
void HomeassistantNumber::min_retrieved_(StringRef min) {
auto min_value = parse_number<float>(min.c_str());
if (!min_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_, min.c_str());
return;
optional<float> HomeassistantNumber::parse_attribute_(const char *name, StringRef value) {
auto number = parse_number<float>(value.c_str());
if (!number.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert '%s' value '%s' to number!", this->entity_id_, name, value.c_str());
return nullopt;
}
ESP_LOGD(TAG, "'%s': Min retrieved: %s", LOG_STR_ARG(this->get_log_name()), min.c_str());
this->traits.set_min_value(min_value.value());
ESP_LOGD(TAG, "'%s': Retrieved '%s': %s", LOG_STR_ARG(this->get_log_name()), name, value.c_str());
return number;
}
void HomeassistantNumber::max_retrieved_(StringRef max) {
auto max_value = parse_number<float>(max.c_str());
if (!max_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_, max.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Max retrieved: %s", LOG_STR_ARG(this->get_log_name()), max.c_str());
this->traits.set_max_value(max_value.value());
}
void HomeassistantNumber::step_retrieved_(StringRef step) {
auto step_value = parse_number<float>(step.c_str());
if (!step_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'step' value '%s' to number!", this->entity_id_, step.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Step Retrieved %s", LOG_STR_ARG(this->get_log_name()), step.c_str());
this->traits.set_step(step_value.value());
}
void HomeassistantNumber::setup() {
void HomeassistantNumber::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr,
[this](StringRef state) { this->state_changed_(state); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min",
[this](StringRef min) { this->min_retrieved_(min); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "max",
[this](StringRef max) { this->max_retrieved_(max); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "step",
[this](StringRef step) { this->step_retrieved_(step); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min", [this](StringRef value) {
if (auto min = this->parse_attribute_("min", value))
this->traits.set_min_value(*min);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "max", [this](StringRef value) {
if (auto max = this->parse_attribute_("max", value))
this->traits.set_max_value(*max);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "step", [this](StringRef value) {
if (auto step = this->parse_attribute_("step", value))
this->traits.set_step(*step);
});
}
void HomeassistantNumber::dump_config() {
@@ -73,39 +59,24 @@ void HomeassistantNumber::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantNumber::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantNumber::control(float value) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
this->publish_state(value);
// In flash on the ESP8266 and encoded from there
static const char NUMBER_SERVICE_NAME[] PROGMEM = "number.set_value";
static const char INPUT_NUMBER_SERVICE_NAME[] PROGMEM = "input_number.set_value";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char VALUE_KEY[] PROGMEM = "value";
static constexpr char NUMBER_SERVICE_NAME[] PROGMEM = "number.set_value";
static constexpr char INPUT_NUMBER_SERVICE_NAME[] PROGMEM = "input_number.set_value";
static constexpr char VALUE_KEY[] PROGMEM = "value";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, INPUT_NUMBER_SERVICE_NAME, sizeof("input_") - 1) == 0;
resp.service = input_helper ? ProgmemStringRef::from_lit(INPUT_NUMBER_SERVICE_NAME)
: ProgmemStringRef::from_lit(NUMBER_SERVICE_NAME);
resp.service = is_input_helper(this->entity_id_, INPUT_NUMBER_SERVICE_NAME)
? ProgmemStringRef::from_lit(INPUT_NUMBER_SERVICE_NAME)
: ProgmemStringRef::from_lit(NUMBER_SERVICE_NAME);
resp.data.init(2);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &entity_value = resp.data.emplace_back();
entity_value.key = ProgmemStringRef::from_lit(VALUE_KEY);
@@ -1,24 +1,21 @@
#pragma once
#include "esphome/components/number/number.h"
#include "esphome/core/component.h"
#include "esphome/core/optional.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
class HomeassistantNumber final : public number::Number, public Component {
class HomeassistantNumber final : public number::Number {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void state_changed_(StringRef state);
void min_retrieved_(StringRef min);
void max_retrieved_(StringRef max);
void step_retrieved_(StringRef step);
optional<float> parse_attribute_(const char *name, StringRef value);
void control(float value) override;
@@ -8,6 +8,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
@@ -24,9 +25,7 @@ SUPPORTED_DOMAINS = [
"select",
]
HomeassistantSelect = homeassistant_ns.class_(
"HomeassistantSelect", select.Select, cg.Component
)
HomeassistantSelect = homeassistant_ns.class_("HomeassistantSelect", select.Select)
CONFIG_SCHEMA = cv.All(
select.select_schema(HomeassistantSelect)
@@ -38,8 +37,7 @@ CONFIG_SCHEMA = cv.All(
min=2, max=4096
),
}
)
.extend(cv.COMPONENT_SCHEMA),
),
validate_entity_domain("select", SUPPORTED_DOMAINS),
)
@@ -47,13 +45,12 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await select.new_select(
config,
cg.static_buffer(config[CONF_ID], cg.char, config[CONF_OPTIONS_BUFFER_SIZE]),
cg.static_buffer(config[CONF_ID], cg.const_char_ptr, config[CONF_MAX_OPTIONS]),
options=[],
)
await cg.register_component(var, config)
# 1 state + options fetch in HomeassistantSelect::setup()
setup_home_assistant_entity(var, config, state_subscription_count=2)
# 1 state + options fetch in HomeassistantSelect::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=2, services=True)
await register_home_assistant_import(var)
@@ -1,7 +1,5 @@
#include "homeassistant_select.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
@@ -15,7 +13,7 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.select");
void HomeassistantSelect::setup() {
void HomeassistantSelect::subscribe() {
// Subscribe to the options first: Home Assistant answers subscriptions in order, so the options are
// known by the time the first state arrives.
api::global_api_server->subscribe_home_assistant_state(
@@ -110,37 +108,22 @@ void HomeassistantSelect::dump_config() {
this->entity_id_, this->max_options_, this->options_buffer_size_);
}
float HomeassistantSelect::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantSelect::control(size_t index) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_SELECT[] PROGMEM = "select.select_option";
static const char SERVICE_INPUT_SELECT[] PROGMEM = "input_select.select_option";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char OPTION_KEY[] PROGMEM = "option";
static constexpr char SERVICE_SELECT[] PROGMEM = "select.select_option";
static constexpr char SERVICE_INPUT_SELECT[] PROGMEM = "input_select.select_option";
static constexpr char OPTION_KEY[] PROGMEM = "option";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, SERVICE_INPUT_SELECT, sizeof("input_") - 1) == 0;
resp.service =
input_helper ? ProgmemStringRef::from_lit(SERVICE_INPUT_SELECT) : ProgmemStringRef::from_lit(SERVICE_SELECT);
resp.service = is_input_helper(this->entity_id_, SERVICE_INPUT_SELECT)
? ProgmemStringRef::from_lit(SERVICE_INPUT_SELECT)
: ProgmemStringRef::from_lit(SERVICE_SELECT);
resp.data.init(2);
auto &entity_id = resp.data.emplace_back();
entity_id.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &option = resp.data.emplace_back();
option.key = ProgmemStringRef::from_lit(OPTION_KEY);
@@ -5,7 +5,6 @@
#include <span>
#include "esphome/components/select/select.h"
#include "esphome/core/component.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
@@ -16,7 +15,7 @@ namespace esphome::homeassistant {
* `options_buffer_size` bytes and a list of at most `max_options` entries, both static arrays from code
* generation, so options never allocate.
*/
class HomeassistantSelect final : public select::Select, public Component {
class HomeassistantSelect final : public select::Select {
public:
HomeassistantSelect(std::span<char> options_buffer, std::span<const char *> option_list)
: options_buffer_(options_buffer.data()),
@@ -26,9 +25,8 @@ class HomeassistantSelect final : public select::Select, public Component {
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void options_changed_(StringRef options);
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import sensor
from esphome.types import ConfigType
@@ -6,6 +5,7 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
@@ -13,9 +13,7 @@ DEPENDENCIES = ["api"]
# For is_unset() in homeassistant.h
AUTO_LOAD = ["homeassistant"]
HomeassistantSensor = homeassistant_ns.class_(
"HomeassistantSensor", sensor.Sensor, cg.Component
)
HomeassistantSensor = homeassistant_ns.class_("HomeassistantSensor", sensor.Sensor)
CONFIG_SCHEMA = sensor.sensor_schema(HomeassistantSensor, accuracy_decimals=1).extend(
HOME_ASSISTANT_IMPORT_SCHEMA
@@ -26,5 +24,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await sensor.new_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -21,7 +21,7 @@ static void __attribute__((noinline, cold)) publish_not_a_number(HomeassistantSe
sensor->publish_state(NAN);
}
void HomeassistantSensor::setup() {
void HomeassistantSensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
auto val = parse_number<float>(state.c_str());
if (!val.has_value()) {
@@ -44,6 +44,5 @@ void HomeassistantSensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
} // namespace esphome::homeassistant
@@ -1,17 +1,15 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
namespace esphome::homeassistant {
class HomeassistantSensor final : public sensor::Sensor, public Component {
class HomeassistantSensor final : public sensor::Sensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
@@ -1,19 +1,19 @@
import esphome.codegen as cg
from esphome.components import switch
import esphome.config_validation as cv
from esphome.const import CONF_ID
from esphome.types import ConfigType
from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@Links2004"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = [
"automation",
@@ -27,14 +27,12 @@ SUPPORTED_DOMAINS = [
"switch",
]
HomeassistantSwitch = homeassistant_ns.class_(
"HomeassistantSwitch", switch.Switch, cg.Component
)
HomeassistantSwitch = homeassistant_ns.class_("HomeassistantSwitch", switch.Switch)
CONFIG_SCHEMA = cv.All(
switch.switch_schema(HomeassistantSwitch)
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
switch.switch_schema(HomeassistantSwitch).extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("switch", SUPPORTED_DOMAINS),
)
@@ -42,8 +40,6 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await switch.register_switch(var, config)
setup_home_assistant_entity(var, config)
var = await switch.new_switch(config)
setup_home_assistant_entity(var, config, services=True)
await register_home_assistant_import(var)
@@ -1,4 +1,5 @@
#include "homeassistant_switch.h"
#include "../homeassistant.h"
#include "esphome/components/api/api_server.h"
#include "esphome/core/log.h"
#include "esphome/core/progmem.h"
@@ -8,23 +9,16 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.switch");
using namespace esphome::switch_;
void HomeassistantSwitch::setup() {
void HomeassistantSwitch::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr, [this](StringRef state) {
auto val = parse_on_off(state.c_str());
switch (val) {
case PARSE_NONE:
case PARSE_TOGGLE:
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
break;
case PARSE_ON:
case PARSE_OFF:
bool new_state = val == PARSE_ON;
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
this->publish_state(new_state);
break;
if (val != PARSE_ON && val != PARSE_OFF) {
ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
return;
}
bool new_state = val == PARSE_ON;
ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
this->publish_state(new_state);
});
}
@@ -33,33 +27,19 @@ void HomeassistantSwitch::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantSwitch::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantSwitch::write_state(bool state) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_ON[] PROGMEM = "homeassistant.turn_on";
static const char SERVICE_OFF[] PROGMEM = "homeassistant.turn_off";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static constexpr char SERVICE_ON[] PROGMEM = "homeassistant.turn_on";
static constexpr char SERVICE_OFF[] PROGMEM = "homeassistant.turn_off";
api::HomeassistantActionRequest resp;
resp.service = state ? ProgmemStringRef::from_lit(SERVICE_ON) : ProgmemStringRef::from_lit(SERVICE_OFF);
resp.data.init(1);
auto &entity_id_kv = resp.data.emplace_back();
entity_id_kv.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id_kv.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
api::global_api_server->send_homeassistant_action(resp);
}
@@ -1,16 +1,14 @@
#pragma once
#include "esphome/components/switch/switch.h"
#include "esphome/core/component.h"
namespace esphome::homeassistant {
class HomeassistantSwitch final : public switch_::Switch, public Component {
class HomeassistantSwitch final : public switch_::Switch {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void write_state(bool state) override;
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import text
import esphome.config_validation as cv
from esphome.types import ConfigType
@@ -7,26 +6,26 @@ from .. import (
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
validate_entity_domain,
)
CODEOWNERS = ["@jesserockz"]
DEPENDENCIES = ["api"]
AUTO_LOAD = ["homeassistant"]
SUPPORTED_DOMAINS = [
"input_text",
"text",
]
HomeassistantText = homeassistant_ns.class_(
"HomeassistantText", text.Text, cg.Component
)
HomeassistantText = homeassistant_ns.class_("HomeassistantText", text.Text)
CONFIG_SCHEMA = cv.All(
text.text_schema(HomeassistantText, mode="TEXT")
.extend(HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA)
.extend(cv.COMPONENT_SCHEMA),
text.text_schema(HomeassistantText, mode="TEXT").extend(
HOME_ASSISTANT_IMPORT_CONTROL_SCHEMA
),
validate_entity_domain("text", SUPPORTED_DOMAINS),
)
@@ -34,8 +33,7 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
cg.add_define("USE_API_HOMEASSISTANT_SERVICES")
var = await text.new_text(config)
await cg.register_component(var, config)
# 1 state + min/max/mode fetches in HomeassistantText::setup()
setup_home_assistant_entity(var, config, state_subscription_count=4)
# 1 state + min/max/mode fetches in HomeassistantText::subscribe()
setup_home_assistant_entity(var, config, state_subscription_count=4, services=True)
await register_home_assistant_import(var)
@@ -1,6 +1,6 @@
#include "homeassistant_text.h"
#include <cstring>
#include "../homeassistant.h"
#include "esphome/components/api/api_pb2.h"
#include "esphome/components/api/api_server.h"
@@ -13,6 +13,9 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.text");
PROGMEM_STRING_TABLE(TextModeNames, "text", "password");
static_assert(text::TEXT_MODE_TEXT == 0 && text::TEXT_MODE_PASSWORD == 1 && TextModeNames::COUNT == 2);
void HomeassistantText::state_changed_(StringRef state) {
if (state == this->state) {
return;
@@ -21,46 +24,38 @@ void HomeassistantText::state_changed_(StringRef state) {
this->publish_state(state.c_str(), state.size());
}
void HomeassistantText::min_retrieved_(StringRef min) {
auto min_value = parse_number<int>(min.c_str());
if (!min_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'min' value '%s' to number!", this->entity_id_, min.c_str());
return;
optional<int> HomeassistantText::parse_length_(const char *name, StringRef value) {
auto length = parse_number<int>(value.c_str());
if (!length.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert '%s' value '%s' to number!", this->entity_id_, name, value.c_str());
return nullopt;
}
ESP_LOGD(TAG, "'%s': Min retrieved: %s", this->entity_id_, min.c_str());
this->traits.set_min_length(min_value.value());
}
void HomeassistantText::max_retrieved_(StringRef max) {
auto max_value = parse_number<int>(max.c_str());
if (!max_value.has_value()) {
ESP_LOGE(TAG, "'%s': Can't convert 'max' value '%s' to number!", this->entity_id_, max.c_str());
return;
}
ESP_LOGD(TAG, "'%s': Max retrieved: %s", this->entity_id_, max.c_str());
this->traits.set_max_length(max_value.value());
ESP_LOGD(TAG, "'%s': Retrieved '%s': %s", this->entity_id_, name, value.c_str());
return length;
}
void HomeassistantText::mode_retrieved_(StringRef mode) {
if (mode == "text") {
this->traits.set_mode(text::TEXT_MODE_TEXT);
} else if (mode == "password") {
this->traits.set_mode(text::TEXT_MODE_PASSWORD);
} else {
const int16_t index = progmem_string_table_find<TextModeNames>(mode.c_str(), mode.size());
if (index < 0) {
ESP_LOGW(TAG, "'%s': Unknown 'mode' value '%s'", this->entity_id_, mode.c_str());
return;
}
this->traits.set_mode(static_cast<text::TextMode>(index));
ESP_LOGD(TAG, "'%s': Mode retrieved: %s", this->entity_id_, mode.c_str());
}
void HomeassistantText::setup() {
void HomeassistantText::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullptr,
[this](StringRef state) { this->state_changed_(state); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min",
[this](StringRef min) { this->min_retrieved_(min); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "max",
[this](StringRef max) { this->max_retrieved_(max); });
api::global_api_server->get_home_assistant_state(this->entity_id_, "min", [this](StringRef value) {
if (auto min = this->parse_length_("min", value))
this->traits.set_min_length(*min);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "max", [this](StringRef value) {
if (auto max = this->parse_length_("max", value))
this->traits.set_max_length(*max);
});
api::global_api_server->get_home_assistant_state(this->entity_id_, "mode",
[this](StringRef mode) { this->mode_retrieved_(mode); });
// The "pattern" attribute is not fetched: Home Assistant sends "None" when it is unset,
@@ -72,37 +67,21 @@ void HomeassistantText::dump_config() {
ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
}
float HomeassistantText::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
void HomeassistantText::control(const std::string &value) {
if (!api::global_api_server->is_connected()) {
ESP_LOGE(TAG, "No clients connected to API server");
if (!can_send_action(TAG, this->entity_id_, this))
return;
}
#ifdef USE_API_WIZARD_LINKED_INPUTS
if (this->entity_id_[0] == '\0') {
ESP_LOGW(TAG, "'%s': No entity ID set yet", LOG_STR_ARG(this->get_log_name()));
return;
}
#endif
// In flash on the ESP8266 and encoded from there
static const char SERVICE_TEXT[] PROGMEM = "text.set_value";
static const char SERVICE_INPUT_TEXT[] PROGMEM = "input_text.set_value";
static const char ENTITY_ID_KEY[] PROGMEM = "entity_id";
static const char VALUE_KEY[] PROGMEM = "value";
static constexpr char SERVICE_TEXT[] PROGMEM = "text.set_value";
static constexpr char SERVICE_INPUT_TEXT[] PROGMEM = "input_text.set_value";
static constexpr char VALUE_KEY[] PROGMEM = "value";
api::HomeassistantActionRequest resp;
// An input helper entity id starts with the "input_" its action name starts with
const bool input_helper = ESPHOME_strncmp_P(this->entity_id_, SERVICE_INPUT_TEXT, sizeof("input_") - 1) == 0;
resp.service =
input_helper ? ProgmemStringRef::from_lit(SERVICE_INPUT_TEXT) : ProgmemStringRef::from_lit(SERVICE_TEXT);
resp.service = is_input_helper(this->entity_id_, SERVICE_INPUT_TEXT) ? ProgmemStringRef::from_lit(SERVICE_INPUT_TEXT)
: ProgmemStringRef::from_lit(SERVICE_TEXT);
resp.data.init(2);
auto &entity_id_kv = resp.data.emplace_back();
entity_id_kv.key = ProgmemStringRef::from_lit(ENTITY_ID_KEY);
entity_id_kv.value = ProgmemStringRef(StringRef(this->entity_id_));
add_entity_id(resp, this->entity_id_);
auto &value_kv = resp.data.emplace_back();
value_kv.key = ProgmemStringRef::from_lit(VALUE_KEY);
@@ -1,23 +1,21 @@
#pragma once
#include "esphome/components/text/text.h"
#include "esphome/core/component.h"
#include "esphome/core/optional.h"
#include "esphome/core/string_ref.h"
namespace esphome::homeassistant {
class HomeassistantText final : public text::Text, public Component {
class HomeassistantText final : public text::Text {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
void state_changed_(StringRef state);
void min_retrieved_(StringRef min);
void max_retrieved_(StringRef max);
optional<int> parse_length_(const char *name, StringRef value);
void mode_retrieved_(StringRef mode);
void control(const std::string &value) override;
@@ -1,4 +1,3 @@
import esphome.codegen as cg
from esphome.components import text_sensor
from esphome.types import ConfigType
@@ -6,13 +5,14 @@ from .. import (
HOME_ASSISTANT_IMPORT_SCHEMA,
final_validate_entity_id,
homeassistant_ns,
register_home_assistant_import,
setup_home_assistant_entity,
)
DEPENDENCIES = ["api"]
HomeassistantTextSensor = homeassistant_ns.class_(
"HomeassistantTextSensor", text_sensor.TextSensor, cg.Component
"HomeassistantTextSensor", text_sensor.TextSensor
)
CONFIG_SCHEMA = text_sensor.text_sensor_schema(HomeassistantTextSensor).extend(
@@ -24,5 +24,5 @@ FINAL_VALIDATE_SCHEMA = final_validate_entity_id
async def to_code(config: ConfigType) -> None:
var = await text_sensor.new_text_sensor(config)
await cg.register_component(var, config)
setup_home_assistant_entity(var, config)
await register_home_assistant_import(var)
@@ -7,7 +7,7 @@ namespace esphome::homeassistant {
ESPHOME_LOG_TAG(TAG, "homeassistant.text_sensor");
void HomeassistantTextSensor::setup() {
void HomeassistantTextSensor::subscribe() {
api::global_api_server->subscribe_home_assistant_state(this->entity_id_, this->attribute_, [this](StringRef state) {
if (this->attribute_ != nullptr) {
ESP_LOGD(TAG, "'%s::%s': Got attribute state '%s'", this->entity_id_, this->attribute_, state.c_str());
@@ -24,5 +24,4 @@ void HomeassistantTextSensor::dump_config() {
ESP_LOGCONFIG(TAG, " Attribute: '%s'", this->attribute_);
}
}
float HomeassistantTextSensor::get_setup_priority() const { return setup_priority::AFTER_CONNECTION; }
} // namespace esphome::homeassistant
@@ -1,17 +1,15 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/text_sensor/text_sensor.h"
namespace esphome::homeassistant {
class HomeassistantTextSensor final : public text_sensor::TextSensor, public Component {
class HomeassistantTextSensor final : public text_sensor::TextSensor {
public:
void set_entity_id(const char *entity_id) { this->entity_id_ = entity_id; }
void set_attribute(const char *attribute) { this->attribute_ = attribute; }
void setup() override;
void dump_config() override;
float get_setup_priority() const override;
void subscribe();
void dump_config();
protected:
const char *entity_id_{nullptr};
@@ -6,7 +6,7 @@ namespace esphome::inkbird_ibsth1_mini {
ESPHOME_LOG_TAG(TAG, "inkbird_ibsth1_mini");
void InkbirdIbstH1Mini::dump_config() {
void InkbirdIbstH1Mini::dump_child_config() {
ESP_LOGCONFIG(TAG, "Inkbird IBS TH1 MINI");
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
LOG_SENSOR(" ", "External Temperature", this->external_temperature_sensor_);
@@ -1,12 +1,11 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
namespace esphome::inkbird_ibsth1_mini {
class InkbirdIbstH1Mini final : public Component, public ble_device_base::ESPBTDeviceListener {
class InkbirdIbstH1Mini final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(temperature)
SUB_SENSOR(external_temperature)
SUB_SENSOR(humidity)
@@ -17,7 +16,7 @@ class InkbirdIbstH1Mini final : public Component, public ble_device_base::ESPBTD
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
protected:
uint64_t address_;
@@ -22,7 +22,7 @@ AUTO_LOAD = ["ble_device_base"]
inkbird_ibsth1_mini_ns = cg.esphome_ns.namespace("inkbird_ibsth1_mini")
InkbirdIbstH1Mini = inkbird_ibsth1_mini_ns.class_(
"InkbirdIbstH1Mini", ble_device_base.ESPBTDeviceListener, cg.Component
"InkbirdIbstH1Mini", ble_device_base.ESPBTDeviceListener
)
CONFIG_SCHEMA = cv.All(
@@ -57,14 +57,12 @@ CONFIG_SCHEMA = cv.All(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -1,6 +1,7 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/hal.h"
#include "addressable_light.h"
namespace esphome::light {
@@ -23,19 +24,21 @@ class AddressableLightWrapper : public light::AddressableLight {
// Choose which color mode to use.
// This is ordered by how closely each color mode matches the underlying RGBW data structure used in LightPartition.
ColorMode color_mode_precedence[] = {ColorMode::RGB_WHITE,
ColorMode::RGB_COLD_WARM_WHITE,
ColorMode::RGB_COLOR_TEMPERATURE,
ColorMode::RGB,
ColorMode::WHITE,
ColorMode::COLD_WARM_WHITE,
ColorMode::COLOR_TEMPERATURE,
ColorMode::BRIGHTNESS,
ColorMode::ON_OFF,
ColorMode::UNKNOWN};
// In flash: a local array is copied from a RAM constant on ESP8266
static constexpr ColorMode COLOR_MODE_PRECEDENCE[] PROGMEM = {ColorMode::RGB_WHITE,
ColorMode::RGB_COLD_WARM_WHITE,
ColorMode::RGB_COLOR_TEMPERATURE,
ColorMode::RGB,
ColorMode::WHITE,
ColorMode::COLD_WARM_WHITE,
ColorMode::COLOR_TEMPERATURE,
ColorMode::BRIGHTNESS,
ColorMode::ON_OFF,
ColorMode::UNKNOWN};
LightTraits parent_traits = this->light_state_->get_traits();
for (auto cm : color_mode_precedence) {
for (const auto &entry : COLOR_MODE_PRECEDENCE) {
auto cm = static_cast<ColorMode>(progmem_read_byte(reinterpret_cast<const uint8_t *>(&entry)));
if (parent_traits.supports_color_mode(cm)) {
this->color_mode_ = cm;
break;
@@ -62,7 +62,7 @@ void LilygoT547Touchscreen::update_touches() {
return;
}
point = buffer[5] & 0xF;
point = low_nibble(buffer[5]);
if (point > 2) {
ESP_LOGW(TAG, "Invalid touch point count: %d", point);
point = 2;
@@ -88,9 +88,11 @@ void LilygoT547Touchscreen::update_touches() {
uint16_t id, x_raw, y_raw;
for (uint8_t i = 0; i < point; i++) {
id = (buffer[i * 5] >> 4) & 0x0F;
y_raw = (uint16_t) ((buffer[i * 5 + 1] << 4) | ((buffer[i * 5 + 3] >> 4) & 0x0F));
x_raw = (uint16_t) ((buffer[i * 5 + 2] << 4) | (buffer[i * 5 + 3] & 0x0F));
const uint8_t *record = buffer + i * 5;
id = high_nibble(record[0]);
// The low 4 bits of Y and X share byte 3
y_raw = encode_uint12(record[1], high_nibble(record[3]));
x_raw = encode_uint12(record[2], low_nibble(record[3]));
this->add_raw_touch_position_(id, x_raw, y_raw);
}
@@ -134,6 +134,7 @@ void LN882HBLETracker::dump_config() {
this->scan_duration_ / 1000, this->scan_interval_ * BLE_SCAN_UNIT_MS, this->scan_interval_,
this->scan_window_ * BLE_SCAN_UNIT_MS, this->scan_window_, this->scan_active_ ? "ACTIVE" : "PASSIVE",
YESNO(this->scan_continuous_));
this->dispatcher_.dump_child_configs();
}
// ---------------------------------------------------------------------------
+26 -15
View File
@@ -94,6 +94,7 @@ UART_SELECTION_RP2040 = [USB_CDC, UART0, UART1]
UART_SELECTION_NRF52 = [USB_CDC, UART0]
# Read by device-builder
HARDWARE_UART_TO_UART_SELECTION = {
UART0: logger_ns.UART_SELECTION_UART0,
UART0_SWAP: logger_ns.UART_SELECTION_UART0_SWAP,
@@ -538,17 +539,17 @@ async def to_code(config: ConfigType) -> None:
cg.add(log.set_boot_log_level(tag, LOG_LEVELS[log_level]))
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
# (e.g. UART0 vs USB_SERIAL_JTAG). Without this, uart_ is still the
# default UART_SELECTION_UART0 and the wrong hardware gets initialized.
# uart_ is UART0 in C++ except on LibreTiny where it is DEFAULT; skip the
# setter when the config matches it.
cpp_default_uart = DEFAULT if CORE.is_libretiny else UART0
if (
hardware_uart := config.get(CONF_HARDWARE_UART)
) is not None and hardware_uart != cpp_default_uart:
cg.add(log.set_uart_selection(HARDWARE_UART_TO_UART_SELECTION[hardware_uart]))
if (hardware_uart := config.get(CONF_HARDWARE_UART)) is not None:
cg.add_define(f"USE_LOGGER_UART_SELECTION_{hardware_uart}")
cg.add_define(
"ESPHOME_LOGGER_UART_SELECTION",
cg.RawExpression(f"logger::UART_SELECTION_{hardware_uart}"),
)
# ESP8266 without serial logging never opens a port
cg.add_define(
"ESPHOME_LOGGER_UART_NAME",
"NONE" if CORE.is_esp8266 and baud_rate == 0 else hardware_uart,
)
# 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())
@@ -645,7 +646,6 @@ async def _late_logger_init(config: ConfigType) -> None:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_CDC", True)
elif config[CONF_HARDWARE_UART] == USB_SERIAL_JTAG:
add_idf_sdkconfig_option("CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG", True)
cg.add_define("USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG")
# Log V2 formats centrally in esp_log() (~4KB flash, ~180B RAM). 6.1
# adds CONSTRAINED_ENV_SAFE=n, keeping early/DRAM logs on
# esp_rom_printf instead of pulling ~1.2KB esp_rom_vprintf into IRAM.
@@ -663,10 +663,12 @@ async def _late_logger_init(config: ConfigType) -> None:
# --wrap: a strong definition collides; see logger_esp32.cpp
cg.add_build_flag("-Wl,--wrap=esp_log_format")
# Zephyr polls the USB port only when it logs there
if config.get(CONF_HARDWARE_UART) == USB_CDC and (
has_serial_logging or not CORE.is_nrf52
if (
CORE.using_zephyr
and has_serial_logging
and config[CONF_HARDWARE_UART] == USB_CDC
):
cg.add_define("USE_LOGGER_UART_SELECTION_USB_CDC")
cg.add_define("USE_LOGGER_ZEPHYR_CDC_LOOP")
# Define platform support flags for components that need auto-detection
try:
uart_selection(USB_SERIAL_JTAG)
@@ -884,6 +886,15 @@ def request_logger_level_listeners() -> None:
_request_log_listener_slot = cg.slot_counter("ESPHOME_LOG_MAX_LISTENERS")
def request_console() -> None:
"""Compile in Logger::console_read() and console_write(); call from to_code.
On ESP32 a USB_CDC logger only has a console where ESP-IDF sets CONFIG_ESP_CONSOLE_USB_CDC (targets with
USB OTG); elsewhere, such as the C3, C6 or H2, both do nothing. Host and Zephyr have no console API.
"""
cg.add_define("USE_LOGGER_CONSOLE")
def request_log_listener() -> None:
"""Reserve a log listener slot; call once per listener from to_code."""
cg.add_define("USE_LOG_LISTENERS")
+22 -1
View File
@@ -114,6 +114,26 @@ struct LogBuffer {
this->finalize_();
}
#endif
// Writes a message that needs no formatting, truncated and stripped of trailing newlines as format_body() does
void HOT write_unformatted_body(const char *text, size_t len) {
if (!this->full_()) {
const uint16_t limit = this->remaining_() - 1; // vsnprintf() keeps the last byte for the null terminator
const uint16_t copy_len = (len < limit) ? static_cast<uint16_t>(len) : limit;
memcpy(this->current_(), text, copy_len);
this->pos += copy_len;
this->strip_trailing_newlines_();
}
this->finalize_();
}
// write_unformatted_body() for a message in flash
inline void HOT ESPHOME_ALWAYS_INLINE write_unformatted_body_p(ESPHOME_PGM_P text) {
if (!this->full_()) {
char *const start = this->current_();
this->pos = static_cast<uint16_t>(progmem_copy_str(start, start + this->remaining_() - 1, text) - this->data);
this->strip_trailing_newlines_();
}
this->finalize_();
}
static constexpr uint16_t ANSI_COLOR_LEN = 7; // "\033[{bold};3{color}m" written by write_header for level != 0
static constexpr uint16_t ANSI_RESET_LEN = 4; // "\033[0m"
// Largest replay header: color plus "@4294967295ms "
@@ -161,7 +181,8 @@ struct LogBuffer {
this->pos += ANSI_RESET_LEN;
}
}
void strip_trailing_newlines_() {
// Forced inline: an outlined copy slows every formatted line
inline void ESPHOME_ALWAYS_INLINE strip_trailing_newlines_() {
while (this->pos > 0 && this->data[this->pos - 1] == '\n')
this->pos--;
}
+75 -8
View File
@@ -19,6 +19,15 @@ namespace esphome::logger {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes to a socket would
// take that lock again and deadlock, so such a line is queued for loop() instead. It can print after later inline
// lines, and is lost if loop() never runs again (safe_reboot()).
static inline bool HOT ESPHOME_ALWAYS_INLINE under_lwip_core_lock() {
return sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED);
}
#endif
#if defined(USE_ESP32) || defined(USE_HOST) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// Implementation for multi-threaded platforms (ESP32 with FreeRTOS, Host with pthreads, LibreTiny with FreeRTOS,
// Zephyr) Main thread/task always uses direct buffer access for console output and callbacks
@@ -51,11 +60,7 @@ void HOT Logger::log_vprintf_(uint8_t level, const char *tag, int line, const ch
// Pass nullptr for thread_name since we already know this is the main task
if (is_main_task && !this->main_task_recursion_guard_) [[likely]] {
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// lwIP code run under the core lock (tcpip_api_call, netif callbacks) can log. A listener that writes
// to a socket would take that lock again and deadlock, so queue the message for loop() instead. Such lines
// can print after later inline ones, and are lost if loop() never runs again (safe_reboot()).
if (sys_thread_tcpip(LWIP_CORE_LOCK_QUERY_HOLDER) && sys_thread_tcpip(LWIP_CORE_IS_TCPIP_INITIALIZED))
[[unlikely]] {
if (under_lwip_core_lock()) [[unlikely]] {
this->log_vprintf_non_main_thread_(level, tag, line, format, args, nullptr);
return;
}
@@ -159,6 +164,49 @@ void Logger::log_vprintf_(uint8_t level, const char *tag, int line, const __Flas
}
#endif // USE_ESP8266
// Not shared with log_message_to_buffer_and_send_(): sharing it slows formatted lines
inline void HOT ESPHOME_ALWAYS_INLINE Logger::send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf) {
#ifdef USE_LOGGER_BOOT_LOG_BUFFER
if (!this->boot_log_done_)
this->boot_log_capture_(level, tag, buf);
#endif
this->notify_listeners_(level, tag, buf);
this->write_log_buffer_to_console_(buf);
}
bool HOT Logger::log_str_(uint8_t level, const char *tag, int line, const char *msg) {
if (level > this->level_for(tag))
return true;
// Check the task first: the guard belongs to the main task and must not be read from other threads
if (!this->is_main_task_())
return false;
if (this->main_task_recursion_guard_)
return true;
#ifdef USE_LOGGER_DEFER_UNDER_LWIP_LOCK
// The formatting path queues it
if (under_lwip_core_lock()) [[unlikely]]
return false;
#endif
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body(msg, strlen(msg));
this->send_unformatted_line_(level, tag, buf);
return true;
}
#ifdef USE_ESP8266
void Logger::log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg) {
if (level > this->level_for(tag) || this->main_task_recursion_guard_)
return;
RecursionGuard guard(this->main_task_recursion_guard_);
LogBuffer buf{this->tx_buffer_, ESPHOME_LOGGER_TX_BUFFER_SIZE};
buf.write_header(level, tag, line, nullptr);
buf.write_unformatted_body_p(reinterpret_cast<PGM_P>(msg));
this->send_unformatted_line_(level, tag, buf);
}
#endif // USE_ESP8266
#if defined(USE_LOGGER_RUNTIME_TAG_LEVELS) || defined(USE_LOGGER_BOOT_LOG_PER_TAG_LEVELS)
// Level for tag from a per-tag map, or fallback when the tag has none; tags may live in flash
static inline uint8_t tag_level(const std::map<const char *, uint8_t, CStrCompare> &levels, const char *tag,
@@ -200,10 +248,10 @@ Logger::Logger(uint32_t baud_rate) : baud_rate_(baud_rate) {
#endif
}
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void Logger::loop() {
this->process_messages_();
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
this->cdc_loop_();
#endif
}
@@ -230,7 +278,7 @@ void Logger::process_messages_() {
}
}
// Zephyr with USB CDC keeps the loop running for cdc_loop_()
#if !(defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#ifndef USE_LOGGER_ZEPHYR_CDC_LOOP
else {
// A concurrent enable_loop_soon_any_context() still wakes the next iteration
this->disable_loop();
@@ -323,6 +371,25 @@ static const LogString *get_log_level_str(uint8_t level) {
return LogLevelStrings::get_log_str(level, LogLevelStrings::LAST_INDEX);
}
#ifndef USE_HOST
const LogString *Logger::get_uart_selection_() {
#ifdef USE_LOGGER_UART_SELECTION_DEFAULT
// LibreTiny resolves DEFAULT to the board's port only when serial logging is on
if (this->baud_rate_ > 0) {
switch (this->get_uart()) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
default:
return LOG_STR("UART2");
}
}
#endif
return LOG_STR(ESPHOME_LOGGER_UART_NAME);
}
#endif
void Logger::dump_config() {
ESP_LOGCONFIG(TAG,
"Logger:\n"
+57 -11
View File
@@ -124,6 +124,9 @@ enum UARTSelection : uint8_t {
UART_SELECTION_UART0_SWAP,
#endif // USE_ESP8266
};
// The port chosen by hardware_uart, fixed at build time
static constexpr UARTSelection CONFIGURED_UART_SELECTION = ESPHOME_LOGGER_UART_SELECTION;
#endif // USE_ESP32 || USE_ESP8266 || USE_RP2 || USE_LIBRETINY || USE_ZEPHYR
/**
@@ -146,7 +149,7 @@ enum UARTSelection : uint8_t {
class Logger final : public Component {
public:
explicit Logger(uint32_t baud_rate);
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || (defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC))
#if defined(USE_ESPHOME_TASK_LOG_BUFFER) || defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
void loop() override;
#endif
#if defined(USE_RP2_CRASH_HANDLER) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -160,11 +163,11 @@ class Logger final : public Component {
#endif
#ifdef USE_ESP32
/// UART_NUM_0 when logging to USB
uart_port_t get_uart_num() const {
constexpr uart_port_t get_uart_num() const {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC) || defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return UART_NUM_0;
#else
return static_cast<uart_port_t>(this->uart_);
return static_cast<uart_port_t>(CONFIGURED_UART_SELECTION);
#endif
}
#endif
@@ -172,9 +175,35 @@ class Logger final : public Component {
void create_pthread_key() { pthread_key_create(&this->log_recursion_key_, nullptr); }
#endif
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
void set_uart_selection(UARTSelection uart_selection) { this->uart_ = uart_selection; }
/// Get the UART used by the logger.
UARTSelection get_uart() const { return this->uart_; }
#ifdef USE_LIBRETINY
// DEFAULT resolves to the board's default port
constexpr UARTSelection get_uart() const {
return CONFIGURED_UART_SELECTION == UART_SELECTION_DEFAULT ? static_cast<UARTSelection>(LT_UART_DEFAULT_SERIAL + 1)
: CONFIGURED_UART_SELECTION;
}
#else
constexpr UARTSelection get_uart() const { return CONFIGURED_UART_SELECTION; }
#endif
#endif
#ifdef USE_LOGGER_CONSOLE
// Raw bytes on the console port, without log framing; request with logger.request_console()
// console_write() returns the bytes written: a UART write blocks until all are queued, but a USB write can stop
// short when the host is not reading (USB Serial/JTAG gives up after 20 ms)
#if defined(USE_ARDUINO) && !defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len) { return this->hw_serial_->write(data, len); }
bool console_read(uint8_t &byte) {
int c = this->hw_serial_->read();
if (c < 0)
return false;
byte = c;
return true;
}
#elif defined(USE_ESP32)
size_t console_write(const uint8_t *data, size_t len);
/// Non-blocking read of one byte; false if none is waiting.
bool console_read(uint8_t &byte);
#endif
#endif
/// Set the default log level for this logger.
@@ -223,6 +252,12 @@ class Logger final : public Component {
// NOLINTNEXTLINE(readability-identifier-naming)
void log_vprintf_(uint8_t level, const char *tag, int line, const __FlashStringHelper *format, va_list args);
#endif
// Copies a line with no '%' without formatting; false means the caller must format it
bool log_str_(uint8_t level, const char *tag, int line, const char *msg); // NOLINT
#ifdef USE_ESP8266
// NOLINTNEXTLINE(readability-identifier-naming)
void log_str_(uint8_t level, const char *tag, int line, const __FlashStringHelper *msg);
#endif
protected:
// RAII guard for recursion flags - sets flag on construction, clears on destruction
@@ -245,7 +280,7 @@ class Logger final : public Component {
void log_vprintf_non_main_thread_(uint8_t level, const char *tag, int line, const char *format, va_list args,
const char *thread_name);
#endif
#if defined(USE_ZEPHYR) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void cdc_loop_();
#endif
void process_messages_();
@@ -292,7 +327,7 @@ class Logger final : public Component {
}
// Helper to write log buffer to console if logging is enabled
inline void HOT write_log_buffer_to_console_(LogBuffer &buf) {
inline void HOT ESPHOME_ALWAYS_INLINE write_log_buffer_to_console_(LogBuffer &buf) {
if (this->baud_rate_ > 0)
this->write_to_console_(buf);
}
@@ -321,6 +356,21 @@ class Logger final : public Component {
this->write_log_buffer_to_console_(buf);
}
inline void send_unformatted_line_(uint8_t level, const char *tag, LogBuffer &buf);
// True on the task that runs the main loop, and always on single-task platforms
inline bool HOT is_main_task_() const {
#if defined(USE_ESP32) || defined(USE_LIBRETINY)
return xTaskGetCurrentTaskHandle() == this->main_task_;
#elif defined(USE_ZEPHYR)
return k_current_get() == this->main_task_;
#elif defined(USE_HOST)
return pthread_equal(pthread_self(), this->main_thread_);
#else
return true;
#endif
}
#ifdef USE_ESPHOME_TASK_LOG_BUFFER
// Helper to format a pre-formatted message from the task log buffer and notify listeners
inline void HOT format_buffered_message_and_notify_(uint8_t level, const char *tag, uint16_t line,
@@ -390,10 +440,6 @@ class Logger final : public Component {
bool boot_log_done_{false}; // Set on first replay; stops further capture
#endif
uint8_t current_level_{ESPHOME_LOG_LEVEL_VERY_VERBOSE};
#if defined(USE_ESP32) || defined(USE_ESP8266) || defined(USE_RP2) || defined(USE_LIBRETINY) || defined(USE_ZEPHYR)
// 0 is UART0, or DEFAULT on LibreTiny; must match cpp_default_uart in __init__.py
UARTSelection uart_{};
#endif
bool main_task_recursion_guard_{false}; // Guards tx_buffer_ on the main loop
#ifdef USE_LIBRETINY
bool non_main_task_recursion_guard_{false}; // Shared guard for all non-main tasks on LibreTiny
+35 -37
View File
@@ -17,6 +17,10 @@
#include <driver/usb_serial_jtag_vfs.h>
#endif
#endif
// The logger accepts USB_CDC on targets without USB OTG (C3, C6, H2, ...), where IDF has no CDC console
#if defined(USE_LOGGER_CONSOLE) && defined(USE_LOGGER_UART_SELECTION_USB_CDC) && defined(CONFIG_ESP_CONSOLE_USB_CDC)
#include <esp_private/usb_console.h>
#endif
#if defined(CONFIG_PM_ENABLE) && defined(CONFIG_FREERTOS_USE_TICKLESS_IDLE) && \
(ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0))
#include "esp_sleep.h"
@@ -73,6 +77,7 @@ static void init_usb_serial_jtag() {
}
#endif
#if !defined(USE_LOGGER_UART_SELECTION_USB_CDC) && !defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_size) {
uart_config_t uart_config{};
uart_config.baud_rate = (int) baud_rate;
@@ -97,6 +102,7 @@ static void init_uart(uart_port_t uart_num, uint32_t baud_rate, int tx_buffer_si
esp_sleep_set_console_uart_handling_mode(ESP_SLEEP_ALWAYS_FLUSH_UART);
#endif
}
#endif
// get_uart_num() and pre_setup() cast the selection straight to a port
static_assert(static_cast<int>(UART_SELECTION_UART0) == static_cast<int>(UART_NUM_0) &&
@@ -107,26 +113,11 @@ static_assert(static_cast<int>(UART_SELECTION_UART2) == static_cast<int>(UART_NU
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
case UART_SELECTION_UART0:
case UART_SELECTION_UART1:
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
#endif
init_uart(static_cast<uart_port_t>(this->uart_), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
break;
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
#ifdef USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG
init_usb_serial_jtag();
init_usb_serial_jtag();
#elif !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
init_uart(this->get_uart_num(), this->baud_rate_, ESPHOME_LOGGER_TX_BUFFER_SIZE);
#endif
break;
#endif
}
}
global_logger = this;
@@ -138,29 +129,36 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_ESP32_VARIANT_ESP32
case UART_SELECTION_UART2:
return LOG_STR("UART2");
#ifdef USE_LOGGER_CONSOLE
size_t Logger::console_write(const uint8_t *data, size_t len) {
int written = 0;
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
written = esp_usb_console_write_buf(reinterpret_cast<const char *>(data), len);
#endif
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
written = usb_serial_jtag_write_bytes(data, len, pdMS_TO_TICKS(20));
#else
written = uart_write_bytes(this->get_uart_num(), data, len);
#endif
#ifdef USE_LOGGER_USB_SERIAL_JTAG
case UART_SELECTION_USB_SERIAL_JTAG:
return LOG_STR("USB_SERIAL_JTAG");
#endif
default:
return LOG_STR("UNKNOWN");
}
return written > 0 ? written : 0;
}
bool Logger::console_read(uint8_t &byte) {
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#ifdef CONFIG_ESP_CONSOLE_USB_CDC // keep: not set without USB OTG, see the include above
return esp_usb_console_available_for_read() && esp_usb_console_read_buf(reinterpret_cast<char *>(&byte), 1) == 1;
#else
return false;
#endif
#elif defined(USE_LOGGER_UART_SELECTION_USB_SERIAL_JTAG)
return usb_serial_jtag_read_bytes(&byte, 1, 0) > 0;
#else
return uart_read_bytes(this->get_uart_num(), &byte, 1, 0) > 0;
#endif
}
#endif
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp32::crash_handler_has_data(); }
void log_crash_to_client() {
+3 -16
View File
@@ -14,9 +14,9 @@ void Logger::pre_setup() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
Serial.swap();
}
#ifdef USE_LOGGER_UART_SELECTION_UART0_SWAP
Serial.swap();
#endif
Serial.setDebugOutput(ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE);
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
this->hw_serial_ = &Serial1;
@@ -35,19 +35,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
#if defined(USE_ESP8266_LOGGER_SERIAL)
if (this->uart_ == UART_SELECTION_UART0_SWAP) {
return LOG_STR("UART0_SWAP");
}
return LOG_STR("UART0");
#elif defined(USE_ESP8266_LOGGER_SERIAL1)
return LOG_STR("UART1");
#else
return LOG_STR("NONE");
#endif
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return esp8266::crash_handler_has_data(); }
void log_crash_to_client() { esp8266::crash_handler_log(); }
+20 -51
View File
@@ -12,45 +12,28 @@ ESPHOME_LOG_TAG(TAG, "logger");
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
#if LT_HW_UART0
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART1
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
break;
#endif
#if LT_HW_UART2
case UART_SELECTION_UART2:
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
break;
#endif
default:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (this->uart_ != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
break;
#if defined(USE_LOGGER_UART_SELECTION_UART0) && LT_HW_UART0
this->hw_serial_ = &Serial0;
libretiny::ensure_serial_handle(0);
Serial0.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1) && LT_HW_UART1
this->hw_serial_ = &Serial1;
libretiny::ensure_serial_handle(1);
Serial1.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART2) && LT_HW_UART2
this->hw_serial_ = &Serial2;
libretiny::ensure_serial_handle(2);
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
if (CONFIGURED_UART_SELECTION != UART_SELECTION_DEFAULT) {
ESP_LOGW(TAG, " The chosen logger UART port is not available on this board."
"The default port was used instead.");
}
#endif
// change lt_log() port to match default Serial
if (this->uart_ == UART_SELECTION_DEFAULT) {
this->uart_ = (UARTSelection) (LT_UART_DEFAULT_SERIAL + 1);
lt_log_set_port(LT_UART_DEFAULT_SERIAL);
} else {
lt_log_set_port(this->uart_ - 1);
}
lt_log_set_port(this->get_uart() - 1);
}
global_logger = this;
@@ -60,20 +43,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_DEFAULT:
return LOG_STR("DEFAULT");
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_UART2:
default:
return LOG_STR("UART2");
}
}
#ifdef USE_LIBRETINY_CRASH_HANDLER
bool crash_log_pending() { return libretiny::crash_handler_has_data(); }
void log_crash_to_client() { libretiny::crash_handler_log(); }
+10 -27
View File
@@ -26,20 +26,16 @@ void Logger::setup() {
void Logger::pre_setup() {
if (this->baud_rate_ > 0) {
switch (this->uart_) {
case UART_SELECTION_UART0:
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
break;
case UART_SELECTION_UART1:
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
break;
case UART_SELECTION_USB_CDC:
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
break;
}
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
this->hw_serial_ = &Serial;
Serial.begin(this->baud_rate_);
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
this->hw_serial_ = &Serial2;
Serial2.begin(this->baud_rate_);
#else
this->hw_serial_ = &Serial1;
Serial1.begin(this->baud_rate_);
#endif
}
global_logger = this;
ESP_LOGI(TAG, "Log initialized");
@@ -49,19 +45,6 @@ void Logger::pre_setup() {
#endif
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
default:
return LOG_STR("UNKNOWN");
}
}
#ifdef USE_CRASH_HANDLER
bool crash_log_pending() { return rp2::crash_handler_has_data(); }
void log_crash_to_client() { rp2::crash_handler_log(); }
+13 -34
View File
@@ -42,7 +42,7 @@ __attribute__((section(".noinit"))) struct {
ESPHOME_LOG_TAG(TAG, "logger");
#ifdef USE_LOGGER_UART_SELECTION_USB_CDC
#ifdef USE_LOGGER_ZEPHYR_CDC_LOOP
void Logger::cdc_loop_() {
if (this->uart_dev_ == nullptr) {
return;
@@ -75,25 +75,19 @@ void Logger::pre_setup() {
#ifdef CONFIG_SERIAL
if (this->baud_rate_ > 0) {
const struct device *uart_dev = nullptr;
switch (this->uart_) {
case UART_SELECTION_UART0: // NOLINT(bugprone-branch-clone)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
break;
case UART_SELECTION_UART1:
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
break;
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
#if defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#if defined(CONFIG_USB_DEVICE_STACK) || defined(CONFIG_USB_DEVICE_STACK_NEXT)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
}
#endif
break;
#endif
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(cdc_acm_uart0));
if (device_is_ready(uart_dev)) {
// Nothing can log this early, and the logger has no output without USB anyway
zephyr::usb_device_enable();
}
#endif
#elif defined(USE_LOGGER_UART_SELECTION_UART1)
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(uart1));
#else
uart_dev = DEVICE_DT_GET_OR_NULL(DT_NODELABEL(ESPHOME_LOGGER_UART0_NODE));
#endif
if (device_is_ready(uart_dev)) {
this->uart_dev_ = uart_dev;
#if defined(USE_LOGGER_WAIT_FOR_CDC) && defined(USE_LOGGER_UART_SELECTION_USB_CDC)
@@ -117,7 +111,7 @@ void Logger::pre_setup() {
this->dump_crash_();
#endif
// Nobody reads a USB port this early; cdc_loop_() reports the dump once the port is opened
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_UART_SELECTION_USB_CDC)
#if defined(USE_CRASH_HANDLER) && !defined(USE_LOGGER_ZEPHYR_CDC_LOOP)
// Without a UART (baud_rate: 0, or one that did not come up) nothing reaches the console
if (this->uart_dev_ != nullptr)
log_crash_to_client();
@@ -139,21 +133,6 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
}
}
const LogString *Logger::get_uart_selection_() {
switch (this->uart_) {
case UART_SELECTION_UART0:
return LOG_STR("UART0");
case UART_SELECTION_UART1:
return LOG_STR("UART1");
#ifdef USE_LOGGER_USB_CDC
case UART_SELECTION_USB_CDC:
return LOG_STR("USB_CDC");
#endif
default:
return LOG_STR("UNKNOWN");
}
}
static constexpr uint8_t REASON_BUF_SIZE = 32;
static const char *reason_to_str(unsigned int reason, char *buf) {
+1 -1
View File
@@ -34,6 +34,6 @@ async def to_code(config: ConfigType) -> None:
levels = list(LOG_LEVELS)
index = levels.index(CORE.data[DOMAIN][CONF_LEVEL])
levels = levels[: index + 1]
var = await select.new_select(config, options=levels)
var = await select.new_select(config, options=levels, fixed_options=True)
await register_parented(var, parent)
await register_component(var, config)
+3 -2
View File
@@ -1,5 +1,6 @@
#include "max44009.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
namespace esphome::max44009 {
@@ -80,8 +81,8 @@ float MAX44009Sensor::read_illuminance_() {
}
float MAX44009Sensor::convert_to_lux_(uint8_t data_high, uint8_t data_low) {
uint8_t exponent = data_high >> 4;
uint32_t mantissa = ((data_high & 0x0F) << 4) + (data_low & 0x0F);
uint8_t exponent = high_nibble(data_high);
uint32_t mantissa = (low_nibble(data_high) << 4) | low_nibble(data_low);
return ((0x0001 << exponent) * 0.045) * mantissa;
}
+5 -2
View File
@@ -102,8 +102,11 @@ void MitsubishiClimate::transmit_state() {
// Byte 15: HVAC specific, i.e. POWERFUL, SMART SET, PLASMA, always 0x00
// Byte 16: Left vane control (for specific models). Constants match right vane controls.
// Byte 17: Checksum: SUM[Byte0...Byte16]
uint8_t remote_state[MITSUBISHI_FRAME_SIZE] = {0x23, 0xCB, 0x26, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
// In flash: an initialized local array is copied from a RAM constant on ESP8266
static constexpr uint8_t REMOTE_STATE_TEMPLATE[MITSUBISHI_FRAME_SIZE] PROGMEM = {
0x23, 0xCB, 0x26, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t remote_state[sizeof(REMOTE_STATE_TEMPLATE)];
progmem_memcpy(remote_state, REMOTE_STATE_TEMPLATE, sizeof(remote_state));
switch (this->mode) {
case climate::CLIMATE_MODE_HEAT:
@@ -103,7 +103,9 @@ async def to_code(config: ConfigType) -> None:
)
await cg.register_component(var, config)
await select.register_select(var, config, options=list(options_map.keys()))
await select.register_select(
var, config, options=list(options_map.keys()), fixed_options=True
)
parent = await cg.get_variable(config[CONF_MODBUS_CONTROLLER_ID])
cg.add(parent.add_sensor_item(var))
+32 -23
View File
@@ -56,7 +56,8 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
@@ -670,22 +671,28 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
int radio_state = 0;
if (this->dce_->get_radio_state(radio_state) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the radio state; skipping the radio off step");
} else if (radio_state != RADIO_STATE_RF_OFF) {
// Drops a session left by a warm reboot; unlike CFUN=0, which powers the SIM down on the SIM7600, CFUN=4
// keeps the SIM readable for the PIN and the APN. A modem that refuses is used as it is.
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio off");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
esp_modem::PdpContext pdp(this->apn_);
this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
this->dce_->set_pdp_context(pdp) != command_result::OK;
if (this->apn_pending_) {
ESP_LOGW(TAG, "Failed to set the APN with the SIM powered down; setting it after the SIM check");
}
// CFUN=4 powers the SIM up with the radio still off; a modem without it needs CFUN=1 to bring the SIM back
if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
@@ -752,7 +759,7 @@ ModemState ModemComponent::handle_state_connecting_() {
return ModemState::MODEM_STATE_ENABLING;
}
}
// ENABLING left the radio at CFUN=4, where the SIM answers but the modem cannot attach yet
// ENABLING powered the SIM up (CFUN=4, or CFUN=1 on a modem without it), so the SIM answers
switch (this->prepare_sim_()) {
case SimResult::SIM_RESULT_READY:
break;
@@ -769,13 +776,14 @@ ModemState ModemComponent::handle_state_connecting_() {
this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
return ModemState::MODEM_STATE_DISCONNECTING;
}
// The APN has to be in the PDP context before the radio comes on and the modem attaches; esp_modem only
// sends it when PPP starts
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
if (this->apn_pending_) {
esp_modem::PdpContext pdp(this->apn_);
if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
ESP_LOGW(TAG, "Failed to set the APN");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
this->apn_pending_ = false;
}
if (this->dce_->set_radio_state(1) != command_result::OK) {
ESP_LOGW(TAG, "Failed to turn the radio on");
@@ -862,11 +870,12 @@ ModemState ModemComponent::handle_state_disconnecting_() {
ESP_LOGW(TAG, "Failed to leave data mode");
this->set_teardown_fault_();
}
// Turn the radio off; waiting for the lost IP event could take up to 2 min. A reconnect keeps the SIM powered
// so it is not unlocked again; only disable() powers it down.
const bool reconnect = this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED;
if (this->dce_->set_radio_state(reconnect ? RADIO_STATE_RF_OFF : 0) == command_result::OK) {
// Turn the radio off; waiting for the lost IP event could take up to 2 min. The SIM is powered down as well, as
// ENABLING does anyway on a reconnect.
if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
ESP_LOGI(TAG, "Radio off");
} else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
ESP_LOGW(TAG, "Radio off, but the SIM could not be powered down");
} else {
ESP_LOGW(TAG, "Radio off failed");
this->set_teardown_fault_();
@@ -299,6 +299,7 @@ class ModemComponent : public Component {
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
#endif
@@ -8,7 +8,7 @@ static const uint8_t MANUFACTURER_DATA_LENGTH = 10;
static const uint16_t MANUFACTURER_ID = 0x0059;
static const double MOPEKA_LPG_COEF[] = {0.573045, -0.002822, -0.00000535}; // Magic numbers provided by Mopeka
void MopekaProCheck::dump_config() {
void MopekaProCheck::dump_child_config() {
ESP_LOGCONFIG(TAG, "Mopeka Pro Check");
LOG_SENSOR(" ", "Level", this->level_sensor_);
LOG_SENSOR(" ", "Temperature", this->temperature_sensor_);
@@ -3,7 +3,6 @@
#include <cinttypes>
#include <vector>
#include "esphome/core/component.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/components/ble_device_base/ble_device.h"
@@ -25,7 +24,7 @@ enum SensorType {
// measurement may be inaccurate.
enum SensorReadQuality { QUALITY_HIGH = 0x3, QUALITY_MED = 0x2, QUALITY_LOW = 0x1, QUALITY_ZERO = 0x0 };
class MopekaProCheck final : public Component, public ble_device_base::ESPBTDeviceListener {
class MopekaProCheck final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(level)
SUB_SENSOR(temperature)
SUB_SENSOR(battery_level)
@@ -37,7 +36,7 @@ class MopekaProCheck final : public Component, public ble_device_base::ESPBTDevi
void set_address(uint64_t address) { address_ = address; };
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
void set_min_signal_quality(SensorReadQuality min) { this->min_signal_quality_ = min; };
void set_tank_full(float full) { full_mm_ = full; };
@@ -62,7 +62,7 @@ AUTO_LOAD = ["ble_device_base"]
mopeka_pro_check_ns = cg.esphome_ns.namespace("mopeka_pro_check")
MopekaProCheck = mopeka_pro_check_ns.class_(
"MopekaProCheck", ble_device_base.ESPBTDeviceListener, cg.Component
"MopekaProCheck", ble_device_base.ESPBTDeviceListener
)
SensorReadQuality = mopeka_pro_check_ns.enum("SensorReadQuality")
@@ -124,14 +124,12 @@ CONFIG_SCHEMA = cv.All(
SIGNAL_QUALITIES, upper=True
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
@@ -13,7 +13,7 @@ static const uint16_t MANUFACTURER_ID = 0x000D;
// Maximum bytes to log in very verbose hex output
static constexpr size_t MOPEKA_MAX_LOG_BYTES = 32;
void MopekaStdCheck::dump_config() {
void MopekaStdCheck::dump_child_config() {
ESP_LOGCONFIG(TAG,
"Mopeka Std Check\n"
" Propane Butane mix: %.0f%%\n"
@@ -5,7 +5,6 @@
#include "esphome/components/ble_device_base/ble_device.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
namespace esphome::mopeka_std_check {
@@ -40,7 +39,7 @@ struct mopeka_std_package { // NOLINT(readability-identifier-naming,altera-stru
mopeka_std_values val[3];
} __attribute__((packed));
class MopekaStdCheck final : public Component, public ble_device_base::ESPBTDeviceListener {
class MopekaStdCheck final : public ble_device_base::ESPBTDeviceListener {
SUB_SENSOR(level)
SUB_SENSOR(temperature)
SUB_SENSOR(battery_level)
@@ -50,7 +49,7 @@ class MopekaStdCheck final : public Component, public ble_device_base::ESPBTDevi
void set_address(uint64_t address) { address_ = address; };
bool parse_device(const ble_device_base::ESPBTDevice &device) override;
void dump_config() override;
void dump_child_config() override;
void set_propane_butane_mix(float val) { this->propane_butane_mix_ = val; };
void set_tank_full(float full) { this->full_mm_ = full; };
@@ -56,7 +56,7 @@ AUTO_LOAD = ["ble_device_base"]
mopeka_std_check_ns = cg.esphome_ns.namespace("mopeka_std_check")
MopekaStdCheck = mopeka_std_check_ns.class_(
"MopekaStdCheck", ble_device_base.ESPBTDeviceListener, cg.Component
"MopekaStdCheck", ble_device_base.ESPBTDeviceListener
)
CONFIG_SCHEMA = cv.All(
@@ -95,14 +95,12 @@ CONFIG_SCHEMA = cv.All(
state_class=STATE_CLASS_MEASUREMENT,
),
}
)
.extend(cv.COMPONENT_SCHEMA)
.extend(ble_device_base.BLE_DEVICE_SCHEMA),
).extend(ble_device_base.BLE_DEVICE_SCHEMA),
)
async def to_code(config: ConfigType) -> None:
var = await ble_device_base.new_ble_device_component(config)
var = await ble_device_base.new_ble_device(config)
cg.add(var.set_address(config[CONF_MAC_ADDRESS].as_hex))
+13 -27
View File
@@ -19,8 +19,8 @@ from esphome.components.zephyr.framework_helpers import (
)
from esphome.components.zephyr.sdk_install import (
ARM_TOOLCHAIN,
ensure_sdk,
get_sdk_host_info,
install_sdk,
sdk_toolchain_path,
)
import esphome.config_validation as cv
@@ -610,12 +610,7 @@ def _check_and_install(version: str) -> None:
zephyr_sentinel.touch()
_patch_pyocd_nrf54lm20a_flash_algo(python_env_path)
# Shared by every SDK version that uses the same toolchain; locked only
# while missing
toolchain_version = _get_toolchain_version()
if not (_get_toolchain_path(toolchain_version) / ".ready").exists():
with install_lock(get_sdk_nrf_tools_path(), f"toolchain-{toolchain_version}"):
_install_toolchain()
_install_toolchain()
# Nordic's nrfutil launcher, one static binary per host; its commands are installed from Nordic's
@@ -718,23 +713,14 @@ def ensure_nordic_nrfutil(env: dict[str, str]) -> str:
def _install_toolchain() -> None:
toolchain_version = _get_toolchain_version()
toolchains_dir = _get_toolchain_path(toolchain_version)
sentinel = toolchains_dir / ".ready"
if not sentinel.exists():
install_sdk(toolchains_dir, toolchain_version, ARM_TOOLCHAIN)
# Best-effort prune of resume leftovers, including orphans of retired
# toolchain versions; the SDK archives are hundreds of MB. The other
# toolchain still in use may be downloading under its own lock, so its
# leftovers are kept. A locked file must not discard the just-completed
# install.
other_versions = tuple(
f"{v}." for v in _TOOLCHAIN_VERSIONS if v != toolchain_version
)
for leftover in toolchains_dir.parent.glob("*.archive.part*"):
if leftover.name.startswith(other_versions):
continue
try:
leftover.unlink()
except OSError as err:
_LOGGER.debug("Could not remove %s: %s", leftover, err)
sentinel.touch()
# The other toolchain in use may be downloading under its own lock
other_versions = tuple(
f"{v}." for v in _TOOLCHAIN_VERSIONS if v != toolchain_version
)
ensure_sdk(
_get_toolchain_path(toolchain_version),
toolchain_version,
ARM_TOOLCHAIN,
keep_leftover=lambda leftover: leftover.name.startswith(other_versions),
lock_root=get_sdk_nrf_tools_path(),
)
@@ -15,6 +15,7 @@ from dataclasses import dataclass
from typing import Any
import esphome.codegen as cg
from esphome.components.const import CONF_DESTINATION
import esphome.config_validation as cv
from esphome.const import CONF_ENCRYPTION, CONF_FRAGMENTATION, CONF_KEY, CONF_TYPE
from esphome.cpp_generator import Expression, MockObj
@@ -24,7 +25,6 @@ packet_interface_ns = cg.esphome_ns.namespace("packet_interface")
PacketInterface = packet_interface_ns.class_("PacketInterface", cg.Component)
CONF_ADDRESSING = "addressing"
CONF_DESTINATION = "destination"
CONF_PEERS = "peers"
CONF_RELIABILITY = "reliability"
CONF_SESSION = "session"
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff. Show more