mirror of
https://github.com/esphome/esphome.git
synced 2026-11-17 18:46:08 +00:00
Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d6b50e947 | ||
|
|
e490785ad3 | ||
|
|
7f1ba24ab1 | ||
|
|
84dea8078b | ||
|
|
dbf6af2fd7 | ||
|
|
bc6fb7082f | ||
|
|
cfa27cea58 | ||
|
|
5c061f9e1e | ||
|
|
34b24d0cf5 | ||
|
|
e27614fda3 | ||
|
|
8426d04138 | ||
|
|
641c8bedc9 | ||
|
|
4a39ca1b71 | ||
|
|
4a218fdbd8 | ||
|
|
d8fc1cd214 | ||
|
|
1e030b7371 | ||
|
|
3b113f2c39 | ||
|
|
73468592a9 | ||
|
|
a1b456150d | ||
|
|
865a883abb | ||
|
|
357a6717c8 | ||
|
|
bcb434e05e | ||
|
|
fb65fcc5f6 | ||
|
|
b5e379a9d4 | ||
|
|
05286dfd5d | ||
|
|
36184f09aa | ||
|
|
449933891e | ||
|
|
a5bfa6dac3 | ||
|
|
5aaa5b0552 | ||
|
|
9ab090a818 | ||
|
|
02d0bb56a6 | ||
|
|
e12784543d | ||
|
|
bc3e9c88f4 | ||
|
|
7e3c2ebc10 | ||
|
|
3f6c0f35fe | ||
|
|
200bf69035 | ||
|
|
0054041d6a | ||
|
|
b75b3e2bef | ||
|
|
144c799cf5 | ||
|
|
61cce92aaa | ||
|
|
38c1646870 | ||
|
|
b60c2864ef | ||
|
|
db0121bc21 | ||
|
|
be8f6c5e41 | ||
|
|
b621332de5 | ||
|
|
982cbba291 | ||
|
|
a2ac68faac | ||
|
|
731f6e2722 | ||
|
|
598d87836c | ||
|
|
e852e15ca3 | ||
|
|
6b82e127fe | ||
|
|
17baeae3ea | ||
|
|
bc57ad5c87 | ||
|
|
0c1606d3b8 | ||
|
|
a155401afc | ||
|
|
e3bfffc8ab | ||
|
|
9f5ca49e2f | ||
|
|
205318ee1a | ||
|
|
48d8df449a | ||
|
|
383ac1b41a | ||
|
|
0ac2299482 | ||
|
|
b58038af63 | ||
|
|
c741de7a47 | ||
|
|
8a5e07e29f | ||
|
|
f7b52be670 | ||
|
|
d5317669c9 | ||
|
|
5d0bd88bc6 | ||
|
|
b714d8f69b | ||
|
|
ecabdbb24b | ||
|
|
ffbc4148fb | ||
|
|
2169167908 | ||
|
|
900574c03a | ||
|
|
7b1f9c6bf1 | ||
|
|
3587e29725 | ||
|
|
d4244c5388 | ||
|
|
bec53baf1d | ||
|
|
98fd3786dd | ||
|
|
1f531ff022 | ||
|
|
65e7eb6b06 | ||
|
|
7538864e1e | ||
|
|
c0f97475d3 | ||
|
|
df6fcaa6fe | ||
|
|
eb1b793af9 | ||
|
|
b8ce904e0c | ||
|
|
6befa73b00 | ||
|
|
02211e15d8 | ||
|
|
dbbe02f423 | ||
|
|
97a1aa781e | ||
|
|
0b67a754cd | ||
|
|
320b6a8221 | ||
|
|
4e5a5ec32d | ||
|
|
09ce8d7d6e |
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
@@ -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) {}
|
||||
|
||||
@@ -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_; }
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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_);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -515,18 +515,12 @@ void CC1101Component::dump_config() {
|
||||
}
|
||||
|
||||
void CC1101Component::begin_tx() {
|
||||
this->wake_up();
|
||||
// Read the mode before the PKTCTRL0 write below overwrites it in state_
|
||||
const bool packet_mode = this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO);
|
||||
// Ensure Packet Format is 3 (Async Serial)
|
||||
this->write_(Register::PKTCTRL0, 0x32);
|
||||
if (this->state_.PKT_FORMAT == static_cast<uint8_t>(PacketFormat::PACKET_FORMAT_FIFO)) {
|
||||
ESP_LOGW(TAG, "begin_tx is for async serial mode; use send_packet in packet mode");
|
||||
return;
|
||||
}
|
||||
ESP_LOGV(TAG, "Beginning TX sequence");
|
||||
if (this->gdo0_pin_ != nullptr) {
|
||||
// setup() only attaches the interrupt in packet mode. In async serial mode the pin may be
|
||||
// shared with remote_receiver, and detaching here would remove the receiver's interrupt.
|
||||
if (packet_mode) {
|
||||
this->gdo0_pin_->detach_interrupt();
|
||||
}
|
||||
this->gdo0_pin_->pin_mode(gpio::FLAG_OUTPUT);
|
||||
}
|
||||
// Transition through IDLE to bypass CCA (Clear Channel Assessment) which can
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -63,13 +63,25 @@ void CST816Touchscreen::update_touches() {
|
||||
uint8_t data[13];
|
||||
if (!this->status_comm_result(this->read_bytes(REG_STATUS, data, sizeof data)))
|
||||
return;
|
||||
uint8_t num_of_touches = data[REG_TOUCH_NUM] & 3;
|
||||
|
||||
// The low nibble is the touch count. CST816/CST820 are single-touch;
|
||||
// CST826/CST836 can report two points, but this driver only reads the first
|
||||
// point. Some CST8xx controllers report an all-0xFF frame when idle or after
|
||||
// disabling auto-sleep: the count lands above two and the coordinates are
|
||||
// the 0xFFF sentinel, so both guards below reject it.
|
||||
uint8_t num_of_touches = low_nibble(data[REG_TOUCH_NUM]);
|
||||
if (num_of_touches == 0) {
|
||||
return;
|
||||
}
|
||||
if (num_of_touches > 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t x = encode_uint16(data[REG_XPOS_HIGH] & 0xF, data[REG_XPOS_LOW]);
|
||||
uint16_t y = encode_uint16(data[REG_YPOS_HIGH] & 0xF, data[REG_YPOS_LOW]);
|
||||
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]);
|
||||
if (x == 0x0FFF || y == 0x0FFF) {
|
||||
return;
|
||||
}
|
||||
ESP_LOGV(TAG, "Read touch %d/%d", x, y);
|
||||
this->add_raw_touch_position_(0, x, y);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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_();
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,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")
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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--;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -223,6 +223,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
|
||||
@@ -292,7 +298,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 +327,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,
|
||||
|
||||
@@ -9,7 +9,7 @@ void HOT Logger::write_msg_(const char *msg, uint16_t len) {
|
||||
char buffer[TIMESTAMP_LEN + ESPHOME_LOGGER_TX_BUFFER_SIZE + HEADROOM];
|
||||
|
||||
time_t rawtime;
|
||||
time(&rawtime);
|
||||
::time(&rawtime);
|
||||
struct tm timeinfo;
|
||||
localtime_r(&rawtime, &timeinfo); // Thread-safe version
|
||||
size_t pos = strftime(buffer, TIMESTAMP_LEN + 1, "[%H:%M:%S]", &timeinfo);
|
||||
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from collections.abc import Callable
|
||||
import logging
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
@@ -8,6 +9,8 @@ import esphome.config_validation as cv
|
||||
from esphome.const import CONF_DURATION, CONF_ID, CONF_MODE, CONF_VOLTAGE
|
||||
from esphome.types import ConfigType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CODEOWNERS = ["@tomaszduda23"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
DOMAIN = "npm1300"
|
||||
@@ -42,20 +45,18 @@ NPM1300_CHILD_SCHEMA = cv.Schema(
|
||||
{cv.GenerateID(CONF_NPM1300_ID): cv.use_id(NPM1300Component)}
|
||||
)
|
||||
|
||||
# Status registers read on each update: VBUSINSTATUS, BCHGCHARGESTATUS and BCHGERRREASON
|
||||
NPM1300Status = npm1300_ns.struct("NPM1300Status")
|
||||
# The status registers read on each update
|
||||
STATUS_PUBLISHER = cg.HubFunction(
|
||||
"status",
|
||||
cg.void,
|
||||
[
|
||||
(cg.uint8, "vbus_status"),
|
||||
(cg.uint8, "charge_status"),
|
||||
(cg.uint8, "error_reason"),
|
||||
],
|
||||
[(NPM1300Status.operator("const").operator("ref"), "status")],
|
||||
define="USE_NPM1300_STATUS_PUBLISHER",
|
||||
)
|
||||
VBUS_STATUS = STATUS_PUBLISHER.param("vbus_status")
|
||||
CHARGE_STATUS = STATUS_PUBLISHER.param("charge_status")
|
||||
ERROR_REASON = STATUS_PUBLISHER.param("error_reason")
|
||||
STATUS = STATUS_PUBLISHER.param("status")
|
||||
VBUS_STATUS = STATUS.vbus
|
||||
CHARGE_STATUS = STATUS.charge
|
||||
ERROR_REASON = STATUS.error_reason
|
||||
# The ADC results and the amperes per code of the battery current
|
||||
DATA_PUBLISHER = cg.HubFunction(
|
||||
"data",
|
||||
@@ -77,7 +78,10 @@ OUTPUTS = NPM1300Output.options(
|
||||
# Written for a field the YAML leaves out
|
||||
NPM1300_UNSET = 0xFF
|
||||
# ADCNTCRSEL codes, by kiloohms
|
||||
THERMISTOR_NONE = "none"
|
||||
THERMISTOR_RESISTANCES = {10: 1, 47: 2, 100: 3}
|
||||
# B25/50 of the thermistors the product specification lists for each resistance, by kiloohms
|
||||
THERMISTOR_BETAS = {10: 3380, 47: 4050, 100: 4250}
|
||||
LDO_MODES = {"load_switch": 0, "ldo": 1}
|
||||
TERMINATION_CURRENTS = {"10%": 0, "20%": 1}
|
||||
# BCHGVTRICKLESEL, by millivolts
|
||||
@@ -101,14 +105,13 @@ def _one_of_units(
|
||||
validator: Callable[[object], float],
|
||||
allowed: list[int],
|
||||
unit: str,
|
||||
scale: float = 1000,
|
||||
) -> Callable[[object], float]:
|
||||
"""Validate a quantity with `validator` and accept only the listed values, given in units * `scale`."""
|
||||
"""Validate a quantity with `validator` and accept only the listed values, given in thousandths of `unit`."""
|
||||
|
||||
def validate(value: object) -> float:
|
||||
value = validator(value)
|
||||
if round(value * scale) not in allowed:
|
||||
options = ", ".join(f"{v / scale:g}{unit}" for v in allowed)
|
||||
if _millis(value) not in allowed:
|
||||
options = ", ".join(f"{v / 1000:g}{unit}" for v in allowed)
|
||||
raise cv.Invalid(f"Must be one of {options}")
|
||||
return value
|
||||
|
||||
@@ -135,6 +138,23 @@ def _stepped(
|
||||
return validate
|
||||
|
||||
|
||||
def _thermistor_resistance(value: object) -> float | str:
|
||||
if isinstance(value, str) and value.lower() == THERMISTOR_NONE:
|
||||
return THERMISTOR_NONE
|
||||
value = cv.resistance(value)
|
||||
if round(value) not in (kilohms * 1000 for kilohms in THERMISTOR_RESISTANCES):
|
||||
options = ", ".join(f"{kilohms}kOhm" for kilohms in THERMISTOR_RESISTANCES)
|
||||
raise cv.Invalid(f"Must be one of {options} or {THERMISTOR_NONE}")
|
||||
return value
|
||||
|
||||
|
||||
def thermistor_beta(config: ConfigType) -> int:
|
||||
"""The B constant of the hub's thermistor: the configured one, or the one listed for its resistance."""
|
||||
if (beta := config.get(CONF_THERMISTOR_BETA)) is not None:
|
||||
return beta
|
||||
return THERMISTOR_BETAS[round(config[CONF_THERMISTOR_RESISTANCE] / 1000)]
|
||||
|
||||
|
||||
OUTPUT_VOLTAGE = _stepped(cv.voltage, 1000, 3300, 100, "V")
|
||||
VBUS_CURRENT_LIMIT = _stepped(cv.current, 100, 1500, 100, "A")
|
||||
|
||||
@@ -150,15 +170,58 @@ LDO_SCHEMA = BUCK_SCHEMA.extend(
|
||||
}
|
||||
)
|
||||
|
||||
CHARGER_SCHEMA = cv.Schema(
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT = 3.6
|
||||
|
||||
|
||||
def _warm_termination_default(config: ConfigType) -> ConfigType:
|
||||
"""Keep the default warm termination voltage at or below the termination voltage.
|
||||
|
||||
Warn when the default stays below a higher termination voltage.
|
||||
"""
|
||||
if (
|
||||
not isinstance(config, dict)
|
||||
or CONF_WARM_TERMINATION_VOLTAGE in config
|
||||
or CONF_TERMINATION_VOLTAGE not in config
|
||||
):
|
||||
return config
|
||||
try:
|
||||
termination = cv.voltage(config[CONF_TERMINATION_VOLTAGE])
|
||||
except cv.Invalid:
|
||||
# The schema reports it
|
||||
return config
|
||||
if termination < WARM_TERMINATION_VOLTAGE_DEFAULT - 0.001:
|
||||
# A warm battery is never charged higher than a cool one
|
||||
return {
|
||||
**config,
|
||||
CONF_WARM_TERMINATION_VOLTAGE: config[CONF_TERMINATION_VOLTAGE],
|
||||
}
|
||||
if termination > WARM_TERMINATION_VOLTAGE_DEFAULT + 0.001:
|
||||
_LOGGER.warning(
|
||||
"npm1300 '%s' is not set, so a warm battery (45 °C to 60 °C by default) stops "
|
||||
"charging at %.2fV instead of the %.2fV of '%s'. Set '%s' to the value your "
|
||||
"battery allows when warm",
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
WARM_TERMINATION_VOLTAGE_DEFAULT,
|
||||
termination,
|
||||
CONF_TERMINATION_VOLTAGE,
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
_CHARGER_SETTINGS_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_CHARGE_CURRENT): _stepped(cv.current, 32, 800, 2, "A"),
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="4.2V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
# Defaults are the reset values of the product specification
|
||||
cv.Optional(CONF_CHARGE_CURRENT, default="32mA"): _stepped(
|
||||
cv.current, 32, 800, 2, "A"
|
||||
),
|
||||
cv.Optional(CONF_WARM_TERMINATION_VOLTAGE): _one_of_units(
|
||||
cv.Optional(CONF_TERMINATION_VOLTAGE, default="3.6V"): _one_of_units(
|
||||
cv.voltage, TERMINATION_VOLTAGES, "V"
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_WARM_TERMINATION_VOLTAGE,
|
||||
default=f"{WARM_TERMINATION_VOLTAGE_DEFAULT}V",
|
||||
): _one_of_units(cv.voltage, TERMINATION_VOLTAGES, "V"),
|
||||
cv.Optional(CONF_TERMINATION_CURRENT, default="10%"): cv.enum(
|
||||
TERMINATION_CURRENTS
|
||||
),
|
||||
@@ -169,22 +232,37 @@ CHARGER_SCHEMA = cv.Schema(
|
||||
cv.current, list(DISCHARGE_CURRENT_LIMITS), "A"
|
||||
),
|
||||
cv.Optional(CONF_RECHARGE, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=True): cv.boolean,
|
||||
cv.Optional(CONF_ENABLED, default=False): cv.boolean,
|
||||
}
|
||||
)
|
||||
CHARGER_SCHEMA = cv.All(_warm_termination_default, _CHARGER_SETTINGS_SCHEMA)
|
||||
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
def _check_thermistor(config: ConfigType) -> ConfigType:
|
||||
"""A wrong thermistor shifts the battery temperature the charger sees, so charging needs one chosen."""
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if CONF_CHARGER in config and resistance is None:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is required with '{CONF_CHARGER}': set the nominal "
|
||||
f"resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_THERMISTOR_RESISTANCE],
|
||||
)
|
||||
if CONF_THERMISTOR_BETA in config and resistance in (None, THERMISTOR_NONE):
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_THERMISTOR_BETA}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"resistance of the thermistor",
|
||||
path=[CONF_THERMISTOR_BETA],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(NPM1300Component),
|
||||
cv.Optional(CONF_VBUS_CURRENT_LIMIT): VBUS_CURRENT_LIMIT,
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _one_of_units(
|
||||
cv.resistance, list(THERMISTOR_RESISTANCES), "kOhm", scale=0.001
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_BETA, default=3380): cv.int_range(
|
||||
min=1, max=65535
|
||||
),
|
||||
cv.Optional(CONF_THERMISTOR_RESISTANCE): _thermistor_resistance,
|
||||
cv.Optional(CONF_THERMISTOR_BETA): cv.int_range(min=1, max=65535),
|
||||
cv.Optional(CONF_CHARGER): CHARGER_SCHEMA,
|
||||
cv.Optional(CONF_BUCK1): BUCK_SCHEMA,
|
||||
cv.Optional(CONF_BUCK2): BUCK_SCHEMA,
|
||||
@@ -193,7 +271,8 @@ CONFIG_SCHEMA = (
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(0x6B))
|
||||
.extend(i2c.i2c_device_schema(0x6B)),
|
||||
_check_thermistor,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,7 +287,7 @@ def _vbus_current_limit_code(amps: float) -> int:
|
||||
|
||||
def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
termination = _termination_voltage_code(config[CONF_TERMINATION_VOLTAGE])
|
||||
warm = config.get(CONF_WARM_TERMINATION_VOLTAGE)
|
||||
warm = _termination_voltage_code(config[CONF_WARM_TERMINATION_VOLTAGE])
|
||||
return cg.StructInitializer(
|
||||
NPM1300ChargerConfig,
|
||||
("current", _millis(config[CONF_CHARGE_CURRENT]) // 2),
|
||||
@@ -217,10 +296,7 @@ def _charger_config(config: ConfigType) -> cg.StructInitializer:
|
||||
DISCHARGE_CURRENT_LIMITS[_millis(config[CONF_DISCHARGE_CURRENT_LIMIT])],
|
||||
),
|
||||
("termination_voltage", termination),
|
||||
(
|
||||
"warm_termination_voltage",
|
||||
termination if warm is None else _termination_voltage_code(warm),
|
||||
),
|
||||
("warm_termination_voltage", warm),
|
||||
("trickle_voltage", TRICKLE_VOLTAGES[_millis(config[CONF_TRICKLE_VOLTAGE])]),
|
||||
("termination_current", TERMINATION_CURRENTS[config[CONF_TERMINATION_CURRENT]]),
|
||||
("recharge", config[CONF_RECHARGE]),
|
||||
@@ -247,6 +323,13 @@ def _output_config(config: ConfigType | None) -> cg.StructInitializer:
|
||||
def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
charger = config.get(CONF_CHARGER)
|
||||
resistance = config.get(CONF_THERMISTOR_RESISTANCE)
|
||||
if resistance is None:
|
||||
thermistor, beta = NPM1300_UNSET, 0
|
||||
elif resistance == THERMISTOR_NONE:
|
||||
thermistor, beta = 0, 0
|
||||
else:
|
||||
thermistor = THERMISTOR_RESISTANCES[round(resistance / 1000)]
|
||||
beta = thermistor_beta(config)
|
||||
return cg.StructInitializer(
|
||||
NPM1300Config,
|
||||
(
|
||||
@@ -254,13 +337,8 @@ def _config(config: ConfigType) -> cg.StructInitializer:
|
||||
cg.ArrayInitializer(*(_output_config(config.get(key)) for key in OUTPUTS)),
|
||||
),
|
||||
("charger", None if charger is None else _charger_config(charger)),
|
||||
("thermistor_beta", config[CONF_THERMISTOR_BETA]),
|
||||
(
|
||||
"thermistor",
|
||||
NPM1300_UNSET
|
||||
if resistance is None
|
||||
else THERMISTOR_RESISTANCES[round(resistance / 1000)],
|
||||
),
|
||||
("thermistor_beta", beta),
|
||||
("thermistor", thermistor),
|
||||
("charger_configured", charger is not None),
|
||||
)
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ static constexpr uint16_t REG_BCHG_VTERM = 0x030C;
|
||||
static constexpr uint16_t REG_BCHG_VTERM_R = 0x030D;
|
||||
static constexpr uint16_t REG_BCHG_VTRICKLE_SEL = 0x030E;
|
||||
static constexpr uint16_t REG_BCHG_ITERM_SEL = 0x030F;
|
||||
static constexpr uint16_t REG_BCHG_NTC_STATUS = 0x0332;
|
||||
static constexpr uint16_t REG_BCHG_CHARGE_STATUS = 0x0334;
|
||||
static constexpr uint16_t REG_BCHG_ERR_REASON = 0x0336;
|
||||
static constexpr uint16_t REG_BUCK1_ENA_SET = 0x0400;
|
||||
@@ -53,6 +54,9 @@ static constexpr uint16_t REG_SHIP_TASK_SHIP_MODE = 0x0B02;
|
||||
|
||||
// VBUSINSTATUS
|
||||
static constexpr uint8_t VBUS_PRESENT = 0x01;
|
||||
// NTCSTATUS
|
||||
static constexpr uint8_t NTC_STATUS_COLD = 0x01;
|
||||
static constexpr uint8_t NTC_STATUS_HOT = 0x08;
|
||||
// BCHGCHARGESTATUS; bit 0 (battery detected) is reserved since C00 silicon
|
||||
static constexpr uint8_t CHARGE_STATUS_COMPLETED = 0x02;
|
||||
static constexpr uint8_t CHARGE_STATUS_TRICKLE = 0x04;
|
||||
@@ -107,26 +111,36 @@ float ntc_temperature(uint16_t code, float inv_beta) {
|
||||
#endif
|
||||
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Error", "Paused, Die Too Hot", "Charge Complete", "Trickle Charge",
|
||||
"Constant Current", "Constant Voltage", "Discharging", "Not Charging");
|
||||
// BCHGCHARGESTATUS bits in order of priority; bit i is reported as string i + 1
|
||||
PROGMEM_STRING_TABLE(ChargerStatusStrings, "Discharging", "Error", "Disabled", "Paused, PMIC Too Hot",
|
||||
"Charge Complete", "Trickle Charge", "Constant Current", "Constant Voltage",
|
||||
"Paused, Battery Too Cold", "Paused, Battery Too Hot", "Not Charging");
|
||||
static constexpr uint8_t CHARGER_STATUS_FIRST_BIT = 3;
|
||||
// BCHGCHARGESTATUS bits in order of priority, reported from string CHARGER_STATUS_FIRST_BIT on
|
||||
static const uint8_t CHARGER_STATUS_BITS[] PROGMEM = {CHARGE_STATUS_DIE_TEMP_HIGH, CHARGE_STATUS_COMPLETED,
|
||||
CHARGE_STATUS_TRICKLE, CHARGE_STATUS_CONSTANT_CURRENT,
|
||||
CHARGE_STATUS_CONSTANT_VOLTAGE};
|
||||
|
||||
static uint8_t charger_status_index(uint8_t vbus_status, uint8_t charge_status, uint8_t error_reason) {
|
||||
if (error_reason != 0)
|
||||
static uint8_t charger_status_index(const NPM1300Status &status) {
|
||||
if ((status.vbus & VBUS_PRESENT) == 0)
|
||||
return 0;
|
||||
if (status.error_reason != 0)
|
||||
return 1;
|
||||
if ((status.charger_enable & 1) == 0)
|
||||
return 2;
|
||||
for (size_t i = 0; i < sizeof(CHARGER_STATUS_BITS); i++) {
|
||||
if ((charge_status & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return i + 1;
|
||||
if ((status.charge & progmem_read_byte(&CHARGER_STATUS_BITS[i])) != 0)
|
||||
return CHARGER_STATUS_FIRST_BIT + i;
|
||||
}
|
||||
return (vbus_status & VBUS_PRESENT) == 0 ? 6 : 7;
|
||||
// The charger stops without an error outside the cold and hot limits of the battery temperature
|
||||
if ((status.ntc & NTC_STATUS_COLD) != 0)
|
||||
return 8;
|
||||
if ((status.ntc & NTC_STATUS_HOT) != 0)
|
||||
return 9;
|
||||
return 10;
|
||||
}
|
||||
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason) {
|
||||
const uint8_t index = charger_status_index(vbus_status, charge_status, error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status) {
|
||||
const uint8_t index = charger_status_index(status);
|
||||
if (index == last)
|
||||
return;
|
||||
last = index;
|
||||
@@ -198,7 +212,7 @@ bool NPM1300Component::configure_charger_(const NPM1300Config &config) {
|
||||
split_9bit(charger.discharge_limit, discharge);
|
||||
uint8_t disable = charger.recharge ? 0 : CHARGER_DISABLE_RECHARGE;
|
||||
// Without a thermistor the charger reports an NTC error and does not charge
|
||||
if (config.thermistor == NPM1300_UNSET)
|
||||
if (config.thermistor == 0 || config.thermistor == NPM1300_UNSET)
|
||||
disable |= CHARGER_DISABLE_NTC;
|
||||
const uint8_t enable = (CHARGER_DISABLE_RECHARGE | CHARGER_DISABLE_NTC) & ~disable;
|
||||
if (this->write_register16(REG_BCHG_ISET_MSB, current, sizeof(current)) != i2c::ERROR_OK ||
|
||||
@@ -292,33 +306,40 @@ void NPM1300Component::hibernate(uint32_t duration_ms) {
|
||||
}
|
||||
|
||||
void NPM1300Component::update() {
|
||||
uint8_t vbus_status;
|
||||
uint8_t charge_status;
|
||||
uint8_t error_reason;
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &vbus_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_CHARGE_STATUS, &charge_status) &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &error_reason)))
|
||||
NPM1300Status status;
|
||||
// NTCSTATUS, DIETEMPSTATUS and BCHGCHARGESTATUS
|
||||
uint8_t charger_status[3];
|
||||
if (!this->status_comm_check(this->read_byte_reg16(REG_VBUSIN_STATUS, &status.vbus) &&
|
||||
this->read_byte_reg16(REG_BCHG_ENABLE_SET, &status.charger_enable) &&
|
||||
this->read_register16(REG_BCHG_NTC_STATUS, charger_status, sizeof(charger_status)) ==
|
||||
i2c::ERROR_OK &&
|
||||
this->read_byte_reg16(REG_BCHG_ERR_REASON, &status.error_reason)))
|
||||
return;
|
||||
status.ntc = charger_status[0];
|
||||
status.charge = charger_status[2];
|
||||
// Without a thermistor the NTC pin is grounded and can read as a hot battery
|
||||
if (progmem_read_byte(&this->config_->thermistor) == 0)
|
||||
status.ntc = 0;
|
||||
|
||||
// The chip goes back to its default VBUS current limit whenever VBUS is removed
|
||||
const bool vbus_present = (vbus_status & VBUS_PRESENT) != 0;
|
||||
const bool vbus_present = (status.vbus & VBUS_PRESENT) != 0;
|
||||
if (vbus_present && !this->vbus_present_ && this->vbus_current_limit_ != NPM1300_UNSET &&
|
||||
!this->status_comm_check(this->apply_vbus_current_limit_()))
|
||||
return;
|
||||
this->vbus_present_ = vbus_present;
|
||||
|
||||
if (error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = error_reason;
|
||||
if (error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", error_reason);
|
||||
if (status.error_reason != this->last_error_reason_) {
|
||||
this->last_error_reason_ = status.error_reason;
|
||||
if (status.error_reason != 0) {
|
||||
ESP_LOGW(TAG, "Charger error, BCHGERRREASON 0x%02X", status.error_reason);
|
||||
}
|
||||
}
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
if (this->status_publisher_ != nullptr)
|
||||
this->status_publisher_(vbus_status, charge_status, error_reason);
|
||||
this->status_publisher_(status);
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
if (!this->status_comm_check(this->publish_switches_()))
|
||||
if (!this->status_comm_check(this->publish_switches_(status)))
|
||||
return;
|
||||
#endif
|
||||
|
||||
@@ -348,16 +369,10 @@ void NPM1300Component::update() {
|
||||
}
|
||||
|
||||
#ifdef USE_SWITCH
|
||||
bool NPM1300Component::publish_switches_() {
|
||||
bool NPM1300Component::publish_switches_(const NPM1300Status &status) {
|
||||
PUBLISH_STATE(this->charger_switch_, (status.charger_enable & 1) != 0);
|
||||
uint8_t value;
|
||||
bool ok = true;
|
||||
if (this->charger_switch_ != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BCHG_ENABLE_SET, &value)) {
|
||||
this->charger_switch_->publish_state((value & 1) != 0);
|
||||
} else {
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
switch_::Switch *const bucks[2] = {this->buck1_switch_, this->buck2_switch_};
|
||||
if (bucks[0] != nullptr || bucks[1] != nullptr) {
|
||||
if (this->read_byte_reg16(REG_BUCK_STATUS, &value)) {
|
||||
@@ -461,7 +476,9 @@ void NPM1300Component::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, " Enabled at boot: %s", YESNO(output.enabled != 0));
|
||||
}
|
||||
}
|
||||
if (config.thermistor != NPM1300_UNSET) {
|
||||
if (config.thermistor == 0) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor: none");
|
||||
} else if (config.thermistor != NPM1300_UNSET) {
|
||||
ESP_LOGCONFIG(TAG, " Thermistor B constant: %u", config.thermistor_beta);
|
||||
}
|
||||
#ifdef USE_SENSOR
|
||||
|
||||
@@ -54,10 +54,19 @@ struct NPM1300Config {
|
||||
NPM1300OutputConfig outputs[NPM1300_OUTPUT_COUNT];
|
||||
NPM1300ChargerConfig charger; // only applied when charger_configured
|
||||
uint16_t thermistor_beta;
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
uint8_t thermistor; // ADCNTCRSEL code: 0 for none, 1 for 10 kOhm, 2 for 47 kOhm, 3 for 100 kOhm, or NPM1300_UNSET
|
||||
bool charger_configured;
|
||||
};
|
||||
|
||||
/// The status registers read on every update
|
||||
struct NPM1300Status {
|
||||
uint8_t vbus; // VBUSINSTATUS
|
||||
uint8_t charger_enable; // BCHGENABLESET
|
||||
uint8_t ntc; // NTCSTATUS
|
||||
uint8_t charge; // BCHGCHARGESTATUS
|
||||
uint8_t error_reason; // BCHGERRREASON
|
||||
};
|
||||
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
/// The 10-bit ADC result whose high 8 bits are adc[msb] and low 2 bits are at `shift` in adc[lsbs]
|
||||
inline uint16_t adc_code(const uint8_t *adc, uint8_t msb, uint8_t lsbs, uint8_t shift) {
|
||||
@@ -68,8 +77,7 @@ float ntc_temperature(uint16_t code, float inv_beta);
|
||||
#endif
|
||||
#ifdef USE_TEXT_SENSOR
|
||||
/// Publish the charger status text, only when it differs from `last`
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, uint8_t vbus_status, uint8_t charge_status,
|
||||
uint8_t error_reason);
|
||||
void publish_charger_status(text_sensor::TextSensor *sensor, uint8_t &last, const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
@@ -95,7 +103,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
float get_setup_priority() const override { return setup_priority::BUS - 1.0f; }
|
||||
|
||||
#ifdef USE_NPM1300_STATUS_PUBLISHER
|
||||
HUB_PUBLISHER(status, uint8_t, uint8_t, uint8_t)
|
||||
HUB_PUBLISHER(status, const NPM1300Status &)
|
||||
#endif
|
||||
#ifdef USE_NPM1300_DATA_PUBLISHER
|
||||
HUB_PUBLISHER(data, const uint8_t *, float)
|
||||
@@ -128,7 +136,7 @@ class NPM1300Component : public PollingComponent, public i2c::I2CDevice {
|
||||
#endif
|
||||
#ifdef USE_SWITCH
|
||||
/// Returns false when a status read failed
|
||||
bool publish_switches_();
|
||||
bool publish_switches_(const NPM1300Status &status);
|
||||
#endif
|
||||
|
||||
const NPM1300Config *config_;
|
||||
|
||||
@@ -21,7 +21,6 @@ from esphome.types import ConfigType
|
||||
from . import (
|
||||
ADC,
|
||||
CONF_NPM1300_ID,
|
||||
CONF_THERMISTOR_BETA,
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
CONF_VBUS_CURRENT_LIMIT,
|
||||
DATA_PUBLISHER,
|
||||
@@ -30,7 +29,9 @@ from . import (
|
||||
DUMP_TAG,
|
||||
IBAT_SCALE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
THERMISTOR_NONE,
|
||||
npm1300_ns,
|
||||
thermistor_beta,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -109,10 +110,10 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_BATTERY_TEMPERATURE not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
if hub.get(CONF_THERMISTOR_RESISTANCE, THERMISTOR_NONE) == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' "
|
||||
"set on the npm1300 component",
|
||||
f"'{CONF_BATTERY_TEMPERATURE}' needs '{CONF_THERMISTOR_RESISTANCE}' set to the "
|
||||
"nominal resistance of the battery thermistor on the npm1300 component",
|
||||
path=[CONF_BATTERY_TEMPERATURE],
|
||||
)
|
||||
|
||||
@@ -145,7 +146,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
if (var := await sensors(CONF_BATTERY_TEMPERATURE, None)) is not None:
|
||||
hub_config = next(c for c in CORE.config[DOMAIN] if c[CONF_ID] == hub_id)
|
||||
state = npm1300_ns.ntc_temperature(
|
||||
_adc(2, 5, 2), 1.0 / hub_config[CONF_THERMISTOR_BETA]
|
||||
_adc(2, 5, 2), 1.0 / thermistor_beta(hub_config)
|
||||
)
|
||||
_add_adc_sensor(hub, var, state, "Battery Temperature")
|
||||
await sensors(CONF_VBUS_CURRENT_LIMIT, hub.set_vbus_current_limit_sensor)
|
||||
@@ -15,6 +15,7 @@ from . import (
|
||||
CONF_THERMISTOR_RESISTANCE,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
OUTPUTS,
|
||||
THERMISTOR_NONE,
|
||||
)
|
||||
|
||||
DEPENDENCIES = ["npm1300"]
|
||||
@@ -44,11 +45,18 @@ def _final_validate(config: ConfigType) -> None:
|
||||
if CONF_CHARGER not in config:
|
||||
return
|
||||
hub = fv.get_declaring_config(config[CONF_NPM1300_ID])
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
# A wrong thermistor shifts the battery temperature the charger sees
|
||||
if CONF_THERMISTOR_RESISTANCE not in hub:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block or "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' on the npm1300 component",
|
||||
f"The '{CONF_CHARGER}' switch needs '{CONF_THERMISTOR_RESISTANCE}' on the npm1300 "
|
||||
f"component: the nominal resistance of the battery thermistor, or '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
# Only the charger block turns off the NTC check, without which the charger never starts
|
||||
if CONF_CHARGER not in hub and hub[CONF_THERMISTOR_RESISTANCE] == THERMISTOR_NONE:
|
||||
raise cv.Invalid(
|
||||
f"The '{CONF_CHARGER}' switch needs a '{CONF_CHARGER}' block when "
|
||||
f"'{CONF_THERMISTOR_RESISTANCE}' is '{THERMISTOR_NONE}'",
|
||||
path=[CONF_CHARGER],
|
||||
)
|
||||
|
||||
|
||||
@@ -11,14 +11,12 @@ from esphome.cpp_generator import (
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import (
|
||||
CHARGE_STATUS,
|
||||
CONF_NPM1300_ID,
|
||||
DUMP,
|
||||
DUMP_TAG,
|
||||
ERROR_REASON,
|
||||
NPM1300_CHILD_SCHEMA,
|
||||
STATUS,
|
||||
STATUS_PUBLISHER,
|
||||
VBUS_STATUS,
|
||||
npm1300_ns,
|
||||
)
|
||||
|
||||
@@ -48,9 +46,7 @@ async def to_code(config: ConfigType) -> None:
|
||||
)
|
||||
STATUS_PUBLISHER.add(
|
||||
hub,
|
||||
npm1300_ns.publish_charger_status(
|
||||
parent_ref(var), last, VBUS_STATUS, CHARGE_STATUS, ERROR_REASON
|
||||
),
|
||||
npm1300_ns.publish_charger_status(parent_ref(var), last, STATUS),
|
||||
)
|
||||
DUMP.add(
|
||||
hub,
|
||||
|
||||
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user