mirror of
https://github.com/esphome/esphome.git
synced 2026-10-27 00:12:11 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc063c5d98 | ||
|
|
be585d8885 | ||
|
|
d76c8b7de0 | ||
|
|
38295397a4 | ||
|
|
6c68985c14 | ||
|
|
7be8a7c390 | ||
|
|
f503b7d431 | ||
|
|
49e5e050df | ||
|
|
4f717006fd | ||
|
|
7d3c5eea0e | ||
|
|
eb8cf139d7 | ||
|
|
b30ac789d1 | ||
|
|
903c343bb8 | ||
|
|
ab6ebac628 | ||
|
|
6cb622417a | ||
|
|
960316abd6 | ||
|
|
87341dc136 | ||
|
|
cfe5809654 | ||
|
|
9c54f96520 | ||
|
|
0cc5b372fb | ||
|
|
f7c8cba8b7 | ||
|
|
79a22e9a9a | ||
|
|
103023737d | ||
|
|
6b6b70a8b6 |
No files matched your search
+17
-48
@@ -1305,10 +1305,7 @@ def upload_program(
|
||||
f"{option_string} is only supported with the esphome OTA platform; "
|
||||
"the web_server OTA path can only update the firmware image."
|
||||
)
|
||||
binary = CORE.firmware_bin
|
||||
if getattr(args, "file", None) is not None:
|
||||
binary = Path(args.file)
|
||||
return _upload_via_web_server(config, network_devices, binary)
|
||||
return _upload_via_web_server(config, network_devices, _app_ota_image(args))
|
||||
|
||||
return _upload_via_native_api(config, network_devices, args)
|
||||
|
||||
@@ -1364,6 +1361,16 @@ def _esphome_ota_conf(config: ConfigType) -> ConfigType | None:
|
||||
return next(iter(esphome_ota_items(config)), None)
|
||||
|
||||
|
||||
def _app_ota_image(args: ArgsProtocol) -> Path:
|
||||
"""The file an app update sends: ``--file`` or the build output, as the
|
||||
target platform's ota_image hook picks it."""
|
||||
binary = CORE.firmware_bin
|
||||
if (file := getattr(args, "file", None)) is not None:
|
||||
binary = Path(file)
|
||||
ota_image = platform_hooks.get_platform_hook(CORE.target_platform, "ota_image")
|
||||
return ota_image(binary) if ota_image is not None else binary
|
||||
|
||||
|
||||
def _upload_via_native_api(
|
||||
config: ConfigType, network_devices: list[str], args: ArgsProtocol
|
||||
) -> tuple[int, str | None]:
|
||||
@@ -1413,27 +1420,27 @@ def _upload_via_native_api(
|
||||
f"flash a build with the option enabled, and then retry {option_string}."
|
||||
)
|
||||
|
||||
binary = CORE.firmware_bin
|
||||
ota_type = espota2.OTA_TYPE_UPDATE_APP
|
||||
file = getattr(args, "file", None)
|
||||
if getattr(args, "partition_table", False):
|
||||
# Fail fast if the resolved ESPHome OTA config does not enable allow_partition_access.
|
||||
# The device-side handshake also rejects this with "Device only supports app updates",
|
||||
# but checking here surfaces the misconfiguration before opening a network connection.
|
||||
check_partition_access("--partition-table")
|
||||
binary = CORE.partition_table_bin
|
||||
binary = Path(file) if file is not None else CORE.partition_table_bin
|
||||
ota_type = espota2.OTA_TYPE_UPDATE_PARTITION_TABLE
|
||||
elif getattr(args, "bootloader", False):
|
||||
check_partition_access("--bootloader")
|
||||
if (
|
||||
getattr(args, "file", None) is None
|
||||
file is None
|
||||
and (native := native_backend())
|
||||
and (hint := getattr(native, "missing_image_hint", lambda: None)())
|
||||
):
|
||||
raise EsphomeError(hint)
|
||||
binary = CORE.bootloader_bin
|
||||
binary = Path(file) if file is not None else CORE.bootloader_bin
|
||||
ota_type = espota2.OTA_TYPE_UPDATE_BOOTLOADER
|
||||
if getattr(args, "file", None) is not None:
|
||||
binary = Path(args.file)
|
||||
else:
|
||||
binary = _app_ota_image(args)
|
||||
|
||||
if ota_type == espota2.OTA_TYPE_UPDATE_PARTITION_TABLE:
|
||||
_validate_partition_table_binary(binary)
|
||||
@@ -2233,12 +2240,6 @@ def command_analyze_memory(args: ArgsProtocol, config: ConfigType) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def command_rotate_key(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
from esphome.cli.rotate_key import command_rotate_key as run
|
||||
|
||||
return run(args, config)
|
||||
|
||||
|
||||
def command_rename(args: ArgsProtocol, config: ConfigType) -> int | None:
|
||||
from esphome.cli.rename import command_rename as run
|
||||
|
||||
@@ -2265,7 +2266,6 @@ POST_CONFIG_ACTIONS = {
|
||||
"clean-mqtt": command_clean_mqtt,
|
||||
"idedata": command_idedata,
|
||||
"rename": command_rename,
|
||||
"rotate-key": command_rotate_key,
|
||||
"discover": command_discover,
|
||||
"analyze-memory": command_analyze_memory,
|
||||
"bundle": command_bundle,
|
||||
@@ -2663,37 +2663,6 @@ def parse_args(argv):
|
||||
)
|
||||
parser_rename.add_argument("name", help="The new name for the device.", type=str)
|
||||
|
||||
parser_rotate_key = subparsers.add_parser(
|
||||
"rotate-key",
|
||||
help=(
|
||||
"Change the OTA encryption key over the air: write a new key to the "
|
||||
"yaml, build with it, upload with the current key, confirm."
|
||||
),
|
||||
parents=[mqtt_options],
|
||||
)
|
||||
parser_rotate_key.add_argument(
|
||||
"configuration", help="Your YAML configuration file.", nargs=1
|
||||
)
|
||||
parser_rotate_key.add_argument(
|
||||
"--device",
|
||||
action="append",
|
||||
help=ARGUMENT_HELP_DEVICE,
|
||||
)
|
||||
parser_rotate_key.add_argument(
|
||||
"--prompt-new-key",
|
||||
action="store_true",
|
||||
help=(
|
||||
"Ask for the new key instead of generating one; read without echo, "
|
||||
"or as one line from stdin when that is not a terminal."
|
||||
),
|
||||
)
|
||||
parser_rotate_key.add_argument(
|
||||
"-y",
|
||||
"--yes",
|
||||
action="store_true",
|
||||
help="Do not ask for confirmation when the api encryption key changes too.",
|
||||
)
|
||||
|
||||
parser_analyze_memory = subparsers.add_parser(
|
||||
"analyze-memory",
|
||||
help="Analyze memory usage by component.",
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
"""``esphome rotate-key``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from esphome import espota2
|
||||
from esphome.components.noise import (
|
||||
generate_encryption_key,
|
||||
static_encryption_key,
|
||||
validate_encryption_key,
|
||||
)
|
||||
from esphome.config_validation import Invalid
|
||||
from esphome.const import CONF_API, CONF_PASSWORD, CONF_PORT
|
||||
from esphome.core import CORE, EsphomeError
|
||||
from esphome.espota2 import ProbeResult
|
||||
from esphome.log import AnsiFore, color
|
||||
from esphome.ota_key_edit import locate_key_edits, old_key_edit, with_sharers
|
||||
from esphome.types import ConfigType
|
||||
from esphome.upload_targets import PortType, get_port_type
|
||||
from esphome.util import (
|
||||
ESPHOME_COMMAND,
|
||||
read_secret_line,
|
||||
run_external_process,
|
||||
safe_input,
|
||||
safe_print,
|
||||
)
|
||||
from esphome.yaml_edit import RestoreError, Snapshot, apply_line_edits, restore_files
|
||||
|
||||
PRECHECK_TIMEOUT = 15.0
|
||||
# What to do when the device does not accept the key in the yaml before anything is written
|
||||
PRECHECK_ADVICE = {
|
||||
ProbeResult.UNREACHABLE: (
|
||||
"The device could not be reached; check that it is online, then try again."
|
||||
),
|
||||
ProbeResult.REJECTED: (
|
||||
"The device runs a different key than the yaml. Install the current "
|
||||
"configuration first, presenting its key with --prompt-ota-key, then rotate."
|
||||
),
|
||||
ProbeResult.NOT_OFFERED: (
|
||||
"The device does not offer encryption: it runs a firmware older than "
|
||||
"ESPHome 2026.9.0 or without a key. Install the current configuration "
|
||||
"first, then rotate."
|
||||
),
|
||||
ProbeResult.DEVICE_ERROR: (
|
||||
"The device answered with an error (see the warning above); fix that first."
|
||||
),
|
||||
}
|
||||
# Why the device did not confirm the new key after the upload
|
||||
CONFIRM_FAILURE = {
|
||||
ProbeResult.REJECTED: "The device still answers with the previous key.",
|
||||
ProbeResult.NOT_OFFERED: "The device came back without encryption.",
|
||||
ProbeResult.DEVICE_ERROR: "The device answered with an error (see the warning above).",
|
||||
ProbeResult.UNREACHABLE: "The device did not come back to confirm the new key.",
|
||||
}
|
||||
|
||||
|
||||
def command_rotate_key(args: argparse.Namespace, config: ConfigType) -> int | None:
|
||||
"""Write a new key, build with it, upload with the current one, confirm."""
|
||||
from esphome.__main__ import (
|
||||
Purpose,
|
||||
_esphome_ota_conf,
|
||||
_resolve_network_devices,
|
||||
choose_upload_log_host,
|
||||
)
|
||||
|
||||
def fail(message: str) -> int:
|
||||
safe_print(color(AnsiFore.BOLD_RED, message))
|
||||
return 1
|
||||
|
||||
ota_conf = _esphome_ota_conf(config)
|
||||
if ota_conf is None:
|
||||
return fail("rotate-key needs the esphome OTA platform in the configuration")
|
||||
old_key = static_encryption_key(ota_conf)
|
||||
if old_key is None:
|
||||
return fail(
|
||||
"rotate-key needs 'encryption:' under the esphome OTA platform with a "
|
||||
"key in the yaml; a key provisioned at runtime is rotated from Home "
|
||||
"Assistant"
|
||||
)
|
||||
if CORE.is_host:
|
||||
return fail("rotate-key is for devices updated over the air")
|
||||
old_key = str(old_key)
|
||||
remote_port = int(ota_conf[CONF_PORT])
|
||||
|
||||
devices = choose_upload_log_host(
|
||||
default=args.device, check_default=None, purpose=Purpose.UPLOADING
|
||||
)
|
||||
if get_port_type(devices[0]) in (PortType.SERIAL, PortType.BOOTSEL):
|
||||
return fail(
|
||||
"rotate-key works over the air; on a serial connection change the "
|
||||
"key in the yaml and run 'esphome run' instead"
|
||||
)
|
||||
network_devices = _resolve_network_devices(devices, config, args)
|
||||
|
||||
if args.prompt_new_key:
|
||||
new_key = read_secret_line("New OTA encryption key: ")
|
||||
else:
|
||||
new_key = generate_encryption_key()
|
||||
try:
|
||||
validate_encryption_key(new_key)
|
||||
except Invalid as err:
|
||||
return fail(f"Invalid new key: {err}")
|
||||
if new_key == old_key:
|
||||
return fail("The new key is the same as the current one")
|
||||
|
||||
try:
|
||||
edits = locate_key_edits(old_key, new_key)
|
||||
# The previous key stays in the config as old_key so an install still
|
||||
# reaches the device if it ends up running either key
|
||||
edits += old_key_edit(old_key)
|
||||
unchecked = with_sharers(edits)
|
||||
except EsphomeError as err:
|
||||
return fail(str(err))
|
||||
|
||||
warnings = []
|
||||
# With the recommended shape the ota inherits the api key, so rotating
|
||||
# it changes what Home Assistant connects with
|
||||
if str(static_encryption_key(config.get(CONF_API) or {})) == old_key:
|
||||
warnings.append(
|
||||
"The api encryption key changes too; Home Assistant will ask for "
|
||||
"the new key after the install."
|
||||
)
|
||||
shared: dict[str, set[str]] = {}
|
||||
for edit in edits:
|
||||
what = f"secret '{edit.secret}'" if edit.secret else edit.path.name
|
||||
for path in edit.shared_with:
|
||||
shared.setdefault(
|
||||
str(path.relative_to(CORE.config_dir.resolve())), set()
|
||||
).add(what)
|
||||
if unchecked:
|
||||
warnings.append(
|
||||
"Could not check every configuration for shared use: "
|
||||
+ "; ".join(unchecked)
|
||||
)
|
||||
if shared:
|
||||
warnings.append(
|
||||
"Other configurations share what is rewritten: "
|
||||
+ "; ".join(
|
||||
f"{p} ({', '.join(sorted(w))})" for p, w in sorted(shared.items())
|
||||
)
|
||||
+ ". Their devices keep the previous key until their next install; "
|
||||
"make sure those configurations carry it as old_key."
|
||||
)
|
||||
if warnings:
|
||||
for warning in warnings:
|
||||
safe_print(color(AnsiFore.BOLD_YELLOW, warning))
|
||||
if not args.yes:
|
||||
if not sys.stdin.isatty():
|
||||
return fail("Confirm with --yes when there is no terminal")
|
||||
if safe_input("Continue? [y/N] ").strip().lower() not in ("y", "yes"):
|
||||
return 1
|
||||
|
||||
safe_print("Checking that the device accepts the current key...")
|
||||
found = espota2.probe_ota_key(
|
||||
network_devices,
|
||||
remote_port,
|
||||
old_key,
|
||||
timeout=PRECHECK_TIMEOUT,
|
||||
retry_rejected=False,
|
||||
)
|
||||
if found is not ProbeResult.ACCEPTED:
|
||||
return fail(PRECHECK_ADVICE[found])
|
||||
|
||||
# Both keys are shown only when a file could not be put back
|
||||
keys = f"Previous key: {old_key}\nNew key: {new_key}"
|
||||
try:
|
||||
originals = apply_line_edits(edits)
|
||||
except RestoreError as err:
|
||||
safe_print(keys)
|
||||
return fail(str(err))
|
||||
except EsphomeError as err:
|
||||
return fail(str(err))
|
||||
except KeyboardInterrupt as err:
|
||||
if notes := getattr(err, "__notes__", None): # a rollback that failed too
|
||||
safe_print(keys)
|
||||
return fail("Interrupted; " + "; ".join(notes))
|
||||
return fail("Interrupted before the upload")
|
||||
# From here every exit restores or reports, so nothing sits outside the try
|
||||
uploaded = False
|
||||
try:
|
||||
safe_print(
|
||||
"Wrote the new key to "
|
||||
+ ", ".join(color(AnsiFore.CYAN, str(p)) for p in originals)
|
||||
)
|
||||
# Global options go before the subcommand; the compile parser is strict
|
||||
cli_args = ["--dashboard"] if CORE.dashboard else []
|
||||
if args.toolchain:
|
||||
cli_args += ["--toolchain", str(args.toolchain)]
|
||||
for key, value in args.substitution or []:
|
||||
cli_args += ["-s", key, value]
|
||||
cli_args += ["compile", str(CORE.config_path)]
|
||||
if run_external_process(*ESPHOME_COMMAND, *cli_args) != 0:
|
||||
return fail("Compiling with the new key failed")
|
||||
|
||||
def image_sent() -> None:
|
||||
# The device accepted the session and may commit from here on;
|
||||
# the edited config reaches it on either key
|
||||
nonlocal uploaded
|
||||
uploaded = True
|
||||
|
||||
rc, _ = espota2.run_ota(
|
||||
network_devices,
|
||||
remote_port,
|
||||
ota_conf.get(CONF_PASSWORD),
|
||||
CORE.firmware_bin,
|
||||
noise_psk=old_key,
|
||||
plaintext_fallback=False,
|
||||
on_upload_start=image_sent,
|
||||
)
|
||||
if rc != 0:
|
||||
return fail(
|
||||
"Uploading with the current key failed. The configuration keeps "
|
||||
"the new key with the previous one as old_key, so the next "
|
||||
"install reaches the device whichever key it runs."
|
||||
if uploaded
|
||||
else "The upload failed before the image was sent (see the error "
|
||||
"above); nothing changed on the device."
|
||||
)
|
||||
safe_print("Waiting for the device to come back with the new key...")
|
||||
found = espota2.probe_ota_key(network_devices, remote_port, new_key)
|
||||
if found is not ProbeResult.ACCEPTED:
|
||||
return fail(
|
||||
CONFIRM_FAILURE[found]
|
||||
+ " The configuration keeps the new key, with the previous one as "
|
||||
"old_key, so the next install reaches the device either way."
|
||||
)
|
||||
except KeyboardInterrupt:
|
||||
return fail(
|
||||
"Interrupted; the device's key was not confirmed"
|
||||
if uploaded
|
||||
else "Interrupted before the upload"
|
||||
)
|
||||
finally:
|
||||
# Before the upload nothing changed on the device; after it the device
|
||||
# most likely runs the new key, and old_key covers the other case
|
||||
if uploaded:
|
||||
safe_print(f"New OTA encryption key: {color(AnsiFore.CYAN, new_key)}")
|
||||
else:
|
||||
_restore(originals, keys)
|
||||
|
||||
safe_print(color(AnsiFore.BOLD_GREEN, "SUCCESS"))
|
||||
return 0
|
||||
|
||||
|
||||
def _restore(originals: dict[Path, Snapshot], keys: str) -> None:
|
||||
"""Put the previous key back, and drop the images a build made with the
|
||||
new key; both keys are shown when a step fails."""
|
||||
files = ", ".join(str(p) for p in originals)
|
||||
try:
|
||||
restore_files(originals)
|
||||
except (EsphomeError, KeyboardInterrupt) as err:
|
||||
# An interrupted restore carries its report as a note
|
||||
why = str(err) or "; ".join(getattr(err, "__notes__", ()))
|
||||
safe_print(color(AnsiFore.BOLD_RED, why or f"Interrupted restoring {files}"))
|
||||
safe_print(keys)
|
||||
else:
|
||||
safe_print(color(AnsiFore.BOLD_YELLOW, f"Restored the previous key in {files}"))
|
||||
build_dir = CORE.firmware_bin.parent
|
||||
failed: list[str] = []
|
||||
images: list[Path] = []
|
||||
try:
|
||||
images = [p for s in (".bin", ".uf2") for p in build_dir.glob(f"*{s}")]
|
||||
for image in images: # every one is tried, whatever the others did
|
||||
try:
|
||||
image.unlink()
|
||||
except OSError as err:
|
||||
failed.append(f"{image}: {err}")
|
||||
except (OSError, KeyboardInterrupt) as err:
|
||||
failed.append(f"{build_dir}: {str(err) or 'interrupted'}")
|
||||
if failed:
|
||||
safe_print(
|
||||
color(
|
||||
AnsiFore.BOLD_RED,
|
||||
"Could not remove images that may hold the new key: "
|
||||
+ "; ".join(failed),
|
||||
)
|
||||
)
|
||||
safe_print(keys)
|
||||
elif images:
|
||||
safe_print(
|
||||
color(
|
||||
AnsiFore.BOLD_YELLOW,
|
||||
f"Removed the images in {build_dir}, which may hold the new key; "
|
||||
"compile again before the next upload.",
|
||||
)
|
||||
)
|
||||
@@ -59,6 +59,7 @@ from esphome.cpp_helpers import ( # noqa: F401
|
||||
add_variable,
|
||||
build_registry_entry,
|
||||
build_registry_list,
|
||||
build_registry_list_merged,
|
||||
extract_registry_entry_config,
|
||||
get_slot_count,
|
||||
gpio_pin_expression,
|
||||
|
||||
@@ -297,9 +297,7 @@ void ADE7880::init_device_() {
|
||||
void ADE7880::reset_device_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
ESP_LOGD(TAG, "Reset device using RESET pin");
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(1);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 1});
|
||||
} else {
|
||||
ESP_LOGD(TAG, "Reset device using SWRST command");
|
||||
this->write_u16_register16_(CONFIG, CONFIG_SWRST);
|
||||
|
||||
@@ -16,13 +16,7 @@ constexpr static const uint8_t AXS_READ_TOUCHPAD[11] = {0xb5, 0xab, 0xa5, 0x5a,
|
||||
}
|
||||
|
||||
void AXS15231Touchscreen::setup() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(10);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 5, .high_after_ms = 10});
|
||||
if (this->interrupt_pin_ != nullptr) {
|
||||
this->interrupt_pin_->pin_mode(gpio::FLAG_INPUT);
|
||||
this->interrupt_pin_->setup();
|
||||
|
||||
@@ -78,3 +78,7 @@ async def pin_to_code(config: ConfigType) -> MockObj:
|
||||
# Called by writer.py; delegates to the shared libretiny implementation.
|
||||
def copy_files() -> None:
|
||||
libretiny.copy_files()
|
||||
|
||||
|
||||
# Called by the OTA upload; the shared libretiny implementation.
|
||||
ota_image = libretiny.device_ota_image
|
||||
@@ -6,12 +6,7 @@ ESPHOME_LOG_TAG(TAG, "cst226.touchscreen");
|
||||
|
||||
void CST226Touchscreen::setup() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
this->set_timeout(30, [this] { this->continue_setup_(); });
|
||||
} else {
|
||||
this->continue_setup_();
|
||||
|
||||
@@ -43,9 +43,7 @@ void CST328Touchscreen::setup() {
|
||||
}
|
||||
|
||||
void CST328Touchscreen::reset_device_() {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 5});
|
||||
this->set_timeout(CST328_TRANSITION_TIMEOUT, [this] { this->continue_setup_(); });
|
||||
}
|
||||
|
||||
|
||||
@@ -52,12 +52,7 @@ void CST816Touchscreen::continue_setup_() {
|
||||
|
||||
void CST816Touchscreen::setup() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
this->set_timeout(30, [this] { this->continue_setup_(); });
|
||||
} else {
|
||||
this->continue_setup_();
|
||||
|
||||
@@ -10,14 +10,7 @@ static constexpr uint32_t REREAD_TIMEOUT_ID = 1;
|
||||
static constexpr uint32_t REREAD_DELAY_MS = 20;
|
||||
|
||||
void CST9220Touchscreen::setup() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 10});
|
||||
// Wait for the controller to leave its bootloader before talking to it.
|
||||
this->set_timeout(30, [this] { this->continue_setup_(); });
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ CONFIG_SCHEMA = cv.All(
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
cg.add_define("USE_LINE_READER")
|
||||
await uart.new_uart_component(config)
|
||||
|
||||
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
namespace esphome::dfrobot_sen0395 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "dfrobot_sen0395");
|
||||
static constexpr char ASCII_CR = 0x0D;
|
||||
static constexpr char ASCII_LF = 0x0A;
|
||||
static constexpr float DET_RANGE_STEP_M = 0.15f;
|
||||
static constexpr float LATENCY_STEP_S = 0.025f;
|
||||
// Sent after a reset with no line end
|
||||
static constexpr char PROMPT[] PROGMEM = "leapMMW:/>";
|
||||
|
||||
// What each CommandType cannot do while the sensor runs; empty for commands that do not need it stopped
|
||||
PROGMEM_STRING_TABLE(BusyActions, "", "configure range config", "configure output latency",
|
||||
@@ -121,9 +121,9 @@ bool DfrobotSen0395Component::run_command_(const Command &cmd, uint32_t now) {
|
||||
return false; // Command not done yet
|
||||
}
|
||||
|
||||
if (this->read_message_()) {
|
||||
if (ESPHOME_strstr_P(this->read_buffer_, ESPHOME_PSTR("is not recognized as a CLI command")) == nullptr) {
|
||||
if (!this->handle_reply_(cmd))
|
||||
if (const char *message = this->read_message_()) {
|
||||
if (ESPHOME_strstr_P(message, ESPHOME_PSTR("is not recognized as a CLI command")) == nullptr) {
|
||||
if (!this->handle_reply_(cmd, message))
|
||||
return false; // Command not done yet
|
||||
this->read_message_(); // Skip the prompt
|
||||
return true;
|
||||
@@ -146,12 +146,13 @@ bool DfrobotSen0395Component::run_command_(const Command &cmd, uint32_t now) {
|
||||
}
|
||||
|
||||
void DfrobotSen0395Component::read_state_() {
|
||||
if (!this->read_message_())
|
||||
const char *message = this->read_message_();
|
||||
if (message == nullptr)
|
||||
return;
|
||||
if (ESPHOME_strstr_P(this->read_buffer_, ESPHOME_PSTR("$JYBSS,0, , , *")) != nullptr) {
|
||||
if (ESPHOME_strstr_P(message, ESPHOME_PSTR("$JYBSS,0, , , *")) != nullptr) {
|
||||
this->set_detected_(false);
|
||||
this->set_active(true);
|
||||
} else if (ESPHOME_strstr_P(this->read_buffer_, ESPHOME_PSTR("$JYBSS,1, , , *")) != nullptr) {
|
||||
} else if (ESPHOME_strstr_P(message, ESPHOME_PSTR("$JYBSS,1, , , *")) != nullptr) {
|
||||
this->set_detected_(true);
|
||||
this->set_active(true);
|
||||
}
|
||||
@@ -206,8 +207,7 @@ void DfrobotSen0395Component::format_command(const Command &cmd, char *buf, size
|
||||
}
|
||||
}
|
||||
|
||||
bool DfrobotSen0395Component::handle_reply_(const Command &cmd) {
|
||||
const char *message = this->read_buffer_;
|
||||
bool DfrobotSen0395Component::handle_reply_(const Command &cmd, const char *message) {
|
||||
auto is = [message](ESPHOME_PGM_P text) { return ESPHOME_strcmp_P(message, text) == 0; };
|
||||
|
||||
// Commands with their own replies
|
||||
@@ -230,7 +230,7 @@ bool DfrobotSen0395Component::handle_reply_(const Command &cmd) {
|
||||
}
|
||||
return true;
|
||||
case CommandType::COMMAND_TYPE_RESET_SYSTEM:
|
||||
if (!is(ESPHOME_PSTR("leapMMW:/>")))
|
||||
if (!is(PROMPT))
|
||||
return false;
|
||||
ESP_LOGI(TAG, "Restarted sensor.");
|
||||
return true;
|
||||
@@ -300,34 +300,24 @@ bool DfrobotSen0395Component::handle_reply_(const Command &cmd) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DfrobotSen0395Component::read_message_() {
|
||||
const char *DfrobotSen0395Component::read_message_() {
|
||||
while (this->available()) {
|
||||
uint8_t byte;
|
||||
this->read_byte(&byte);
|
||||
|
||||
if (this->read_pos_ == MMWAVE_READ_BUFFER_LENGTH)
|
||||
this->read_pos_ = 0;
|
||||
|
||||
ESP_LOGVV(TAG, "Buffer pos: %u %d", this->read_pos_, byte);
|
||||
|
||||
if (byte == ASCII_CR)
|
||||
continue;
|
||||
if (byte >= 0x7F)
|
||||
byte = '?'; // needs to be valid utf8 string for log functions.
|
||||
this->read_buffer_[this->read_pos_] = byte;
|
||||
|
||||
if (this->read_pos_ == 9 && byte == '>')
|
||||
this->read_buffer_[++this->read_pos_] = ASCII_LF;
|
||||
|
||||
if (this->read_buffer_[this->read_pos_] == ASCII_LF) {
|
||||
this->read_buffer_[this->read_pos_] = 0;
|
||||
this->read_pos_ = 0;
|
||||
ESP_LOGV(TAG, "Message: %s", this->read_buffer_);
|
||||
return true; // Full message in buffer
|
||||
const char *line = this->line_reader_.feed(byte);
|
||||
if (line == nullptr && byte == '>' && this->line_reader_.length() == sizeof(PROMPT) - 1) {
|
||||
line = this->line_reader_.partial();
|
||||
this->line_reader_.reset();
|
||||
}
|
||||
this->read_pos_++;
|
||||
if (line != nullptr) {
|
||||
ESP_LOGV(TAG, "Message: %s", line);
|
||||
return line;
|
||||
}
|
||||
this->line_reader_.log_if_overflowed(TAG);
|
||||
}
|
||||
return false; // No full message yet
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void DfrobotSen0395Component::set_detected_(bool detected) {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "esphome/core/automation.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/line_reader.h"
|
||||
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
#include "esphome/components/binary_sensor/binary_sensor.h"
|
||||
@@ -14,7 +15,7 @@
|
||||
|
||||
namespace esphome::dfrobot_sen0395 {
|
||||
|
||||
static constexpr uint8_t MMWAVE_READ_BUFFER_LENGTH = 255;
|
||||
static constexpr uint8_t MMWAVE_READ_BUFFER_LENGTH = 253; // largest LineReader size with a one byte position
|
||||
static constexpr uint8_t COMMAND_QUEUE_SIZE = 20;
|
||||
|
||||
// Keep in sync with the BusyActions table in dfrobot_sen0395.cpp
|
||||
@@ -121,8 +122,7 @@ class DfrobotSen0395Component final : public uart::UARTDevice, public Component
|
||||
bool led_active_{false};
|
||||
bool uart_presence_active_{false};
|
||||
bool start_after_boot_{false};
|
||||
char read_buffer_[MMWAVE_READ_BUFFER_LENGTH];
|
||||
size_t read_pos_{0};
|
||||
LineReader<MMWAVE_READ_BUFFER_LENGTH> line_reader_;
|
||||
bool cmd_sent_{false};
|
||||
uint8_t retries_left_{2};
|
||||
StaticRingBuffer<Command, COMMAND_QUEUE_SIZE> cmd_queue_;
|
||||
@@ -131,12 +131,13 @@ class DfrobotSen0395Component final : public uart::UARTDevice, public Component
|
||||
int16_t det_range_steps_[8]{};
|
||||
uint16_t latency_steps_[2]{};
|
||||
|
||||
bool read_message_();
|
||||
/// The next complete line, valid until the next call, or nullptr
|
||||
const char *read_message_();
|
||||
void read_state_();
|
||||
/// Run the command at the front of the queue; true when it is done
|
||||
bool run_command_(const Command &cmd, uint32_t now);
|
||||
/// Handle a reply to a sent command; true when the command is done
|
||||
bool handle_reply_(const Command &cmd);
|
||||
bool handle_reply_(const Command &cmd, const char *message);
|
||||
|
||||
void set_detected_(bool detected);
|
||||
};
|
||||
|
||||
@@ -22,7 +22,7 @@ CONF_CUSTOM_PATTERNS = "custom_patterns"
|
||||
CONF_SKIP_CRC = "skip_crc"
|
||||
CONF_DEFAULT_OBIS = "default_obis"
|
||||
|
||||
DLMS_PARSER_VERSION = "2.2.0"
|
||||
DLMS_PARSER_VERSION = "2.2.2"
|
||||
|
||||
dlms_meter_component_ns = cg.esphome_ns.namespace("dlms_meter")
|
||||
DlmsMeterComponent = dlms_meter_component_ns.class_(
|
||||
|
||||
@@ -20,9 +20,7 @@ void EKTF2232Touchscreen::setup() {
|
||||
|
||||
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_FALLING_EDGE);
|
||||
|
||||
this->reset_pin_->setup();
|
||||
|
||||
this->hard_reset_();
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 15, .high_after_ms = 15});
|
||||
if (!this->soft_reset_()) {
|
||||
ESP_LOGE(TAG, "Failed to soft reset EKT2232!");
|
||||
this->interrupt_pin_->detach_interrupt();
|
||||
@@ -96,13 +94,6 @@ bool EKTF2232Touchscreen::get_power_state() {
|
||||
return (received[1] >> 3) & 1;
|
||||
}
|
||||
|
||||
void EKTF2232Touchscreen::hard_reset_() {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(15);
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(15);
|
||||
}
|
||||
|
||||
bool EKTF2232Touchscreen::soft_reset_() {
|
||||
auto err = this->write(SOFT_RESET_CMD, 4);
|
||||
if (err != i2c::ERROR_OK)
|
||||
|
||||
@@ -22,7 +22,6 @@ class EKTF2232Touchscreen final : public Touchscreen, public i2c::I2CDevice {
|
||||
bool get_power_state();
|
||||
|
||||
protected:
|
||||
void hard_reset_();
|
||||
bool soft_reset_();
|
||||
void update_touches() override;
|
||||
|
||||
|
||||
@@ -72,9 +72,7 @@ bool EPaperJD79660::reset() {
|
||||
|
||||
// As commented on SLEEP_MS_RESET1: Reset pulse must happen within time window.
|
||||
// So do not use FSM loop, and avoid other calls/logs during pulse below.
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(SLEEP_MS_RESET1);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.low_ms = SLEEP_MS_RESET1});
|
||||
|
||||
this->reset_duration_ = SLEEP_MS_RESET2;
|
||||
this->step_ = FSMState::RESET_STEP2_IDLECHECK;
|
||||
|
||||
@@ -2389,7 +2389,9 @@ FRAMEWORK_SCHEMA = cv.Schema(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_NAME): cv.string_strict,
|
||||
cv.Optional(CONF_SOURCE): cv.git_ref,
|
||||
cv.Optional(CONF_SOURCE): cv.All(
|
||||
cv.string_strict, cv.Length(min=1)
|
||||
),
|
||||
cv.Optional(CONF_REF): cv.string,
|
||||
cv.Optional(CONF_PATH): cv.string,
|
||||
}
|
||||
|
||||
@@ -34,10 +34,7 @@ void FT63X6Touchscreen::setup() {
|
||||
this->attach_interrupt_(this->interrupt_pin_, gpio::INTERRUPT_ANY_EDGE);
|
||||
}
|
||||
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->hard_reset_();
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 10});
|
||||
|
||||
// Get touch resolution
|
||||
if (this->x_raw_max_ == this->x_raw_min_) {
|
||||
@@ -57,14 +54,6 @@ void FT63X6Touchscreen::setup() {
|
||||
this->write_byte(FT6X36_ADDR_TOUCHRATE_ACTIVE, 0x0E);
|
||||
}
|
||||
|
||||
void FT63X6Touchscreen::hard_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
|
||||
void FT63X6Touchscreen::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "FT63X6 Touchscreen:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
|
||||
@@ -27,7 +27,6 @@ class FT63X6Touchscreen final : public Touchscreen, public i2c::I2CDevice {
|
||||
void set_threshold(uint8_t threshold) { this->threshold_ = threshold; }
|
||||
|
||||
protected:
|
||||
void hard_reset_();
|
||||
void update_touches() override;
|
||||
|
||||
InternalGPIOPin *interrupt_pin_{nullptr};
|
||||
|
||||
@@ -83,13 +83,7 @@ void GSL3670Touchscreen::update_touches() {
|
||||
void GSL3670Touchscreen::clear_reg_() {
|
||||
ESP_LOGD(TAG, "clear_reg");
|
||||
|
||||
// GPIO reset pulse
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(1);
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 1, .high_after_ms = 5});
|
||||
|
||||
this->write_reg8_(0x88, 0x01);
|
||||
// delay(5);
|
||||
@@ -106,12 +100,7 @@ void GSL3670Touchscreen::clear_reg_() {
|
||||
void GSL3670Touchscreen::reset_() {
|
||||
ESP_LOGD(TAG, "reset");
|
||||
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(1);
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 1, .high_after_ms = 5});
|
||||
|
||||
this->write_reg8_(0xe4, 0x04);
|
||||
|
||||
|
||||
@@ -19,12 +19,7 @@ void ICNT86Touchscreen::setup() {
|
||||
}
|
||||
|
||||
// Perform reset if necessary
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 10});
|
||||
|
||||
if (this->x_raw_max_ == this->x_raw_min_) {
|
||||
this->x_raw_max_ = this->display_->get_native_width();
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"""Shared base for the infrared and radio_frequency entity components."""
|
||||
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import remote_base
|
||||
from esphome.components.api import DOMAIN as API_DOMAIN
|
||||
from esphome.const import CONF_API
|
||||
from esphome.core import CORE
|
||||
from esphome.core.entity_helpers import queue_entity_register
|
||||
from esphome.types import ConfigType
|
||||
@@ -24,8 +23,10 @@ async def attach_transmitter(var: cg.MockObj, config: ConfigType, key: str) -> N
|
||||
does. Without this call anywhere in the build a request is answered as
|
||||
soon as the frame is handed over.
|
||||
"""
|
||||
from esphome.components import remote_base
|
||||
|
||||
await remote_base.register_transmittable(var, config, key)
|
||||
if API_DOMAIN in CORE.config:
|
||||
if CONF_API in CORE.config:
|
||||
cg.add_define("USE_IR_RF_TRANSMIT_COMPLETE")
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ from esphome.const import (
|
||||
)
|
||||
from esphome.core import CORE
|
||||
from esphome.core.config import BOARD_MAX_LENGTH
|
||||
from esphome.helpers import copy_file_if_changed
|
||||
from esphome.helpers import copy_file_if_changed, write_file
|
||||
from esphome.platformio.toolchain import copy_ccache_script
|
||||
from esphome.storage_json import StorageJSON
|
||||
|
||||
@@ -656,6 +656,26 @@ async def component_to_code(config):
|
||||
await cg.register_component(var, config)
|
||||
|
||||
|
||||
# Called by the OTA upload through the platforms' ota_image hook
|
||||
def device_ota_image(firmware: Path) -> Path:
|
||||
"""The file to send for an app update: the UF2 without the images the
|
||||
device skips, written next to the build output, or ``firmware`` itself
|
||||
when there is nothing to drop."""
|
||||
from .ota_uf2 import device_ota_uf2
|
||||
|
||||
data = firmware.read_bytes()
|
||||
if (trimmed := device_ota_uf2(data)) is None:
|
||||
return firmware
|
||||
image = CORE.relative_pioenvs_path(CORE.name, "firmware.ota.uf2")
|
||||
write_file(image, trimmed)
|
||||
_LOGGER.info(
|
||||
"Sending the images this device writes: %s of %s bytes",
|
||||
len(trimmed),
|
||||
len(data),
|
||||
)
|
||||
return image
|
||||
|
||||
|
||||
# Called by writer.py
|
||||
def copy_files() -> None:
|
||||
script_dir = Path(__file__).parent
|
||||
|
||||
@@ -91,6 +91,10 @@ async def pin_to_code(config: ConfigType) -> MockObj:
|
||||
# Called by writer.py; delegates to the shared libretiny implementation.
|
||||
def copy_files() -> None:
|
||||
libretiny.copy_files()
|
||||
|
||||
|
||||
# Called by the OTA upload; the shared libretiny implementation.
|
||||
ota_image = libretiny.device_ota_image
|
||||
'''
|
||||
|
||||
BASE_CODE_BOARDS = '''
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Trim a LibreTiny UF2 package to the images a device writes over OTA.
|
||||
|
||||
A LibreTiny UF2 holds one image per OTA scheme: the device schemes (single,
|
||||
dual slot 1, dual slot 2) and the flasher schemes used over UART. The device
|
||||
skips every block of an image whose scheme it does not run (uf2ota), so an
|
||||
image no device scheme writes is only sent to be thrown away. On single OTA
|
||||
chips (BK72xx, LN882H) that is the whole flasher image, more than half the
|
||||
package. The legacy OTA format names the same device partitions, so devices
|
||||
that read it write the same images.
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
UF2_BLOCK_SIZE = 512
|
||||
UF2_MAGIC_HEAD = struct.pack("<2I", 0x0A324655, 0x9E5D5157)
|
||||
UF2_MAGIC_TAIL = struct.pack("<I", 0x0AB16F30)
|
||||
UF2_FLAG_HAS_TAGS = 0x8000
|
||||
# Header words after the magic: flags, target address, payload length, block
|
||||
# number, block count
|
||||
_HEADER_WORDS = struct.Struct("<5I")
|
||||
_SEQ_OFFSET = 20
|
||||
_DATA_START = 32
|
||||
_DATA_END = UF2_BLOCK_SIZE - len(UF2_MAGIC_TAIL)
|
||||
|
||||
# One partition index nibble per scheme, high nibble first: device single,
|
||||
# dual 1 and dual 2 are the first three, the flasher schemes the next three
|
||||
UF2_TAG_OTA_PART_INFO = 0xC0EE0C
|
||||
# Tags uf2ota acts on beyond the image they sit in; one in an image that
|
||||
# would be dropped leaves the package untrimmed
|
||||
_KEEP_TAGS = frozenset(
|
||||
{
|
||||
0x5D57D0, # OTA_FORMAT_1
|
||||
0x6C8492, # OTA_FORMAT_2
|
||||
0x6EC68A, # OTA_PART_LIST
|
||||
0xB948DE, # BINPATCH
|
||||
0x8288ED, # FAL_PTABLE
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _tags(block: bytes, length: int) -> dict[int, bytes] | None:
|
||||
"""The extension tags after a block's payload, or None if malformed."""
|
||||
tags: dict[int, bytes] = {}
|
||||
pos = _DATA_START + length
|
||||
while pos + 4 <= _DATA_END and (size := block[pos]):
|
||||
if size < 4 or pos + size > _DATA_END:
|
||||
return None
|
||||
tags[int.from_bytes(block[pos + 1 : pos + 4], "little")] = block[
|
||||
pos + 4 : pos + size
|
||||
]
|
||||
pos += (size + 3) & ~3
|
||||
return tags
|
||||
|
||||
|
||||
def device_ota_uf2(data: bytes) -> bytes | None:
|
||||
"""``data`` without the images no device scheme writes.
|
||||
|
||||
None when there is nothing to drop, or when ``data`` is not a well
|
||||
formed UF2, so the caller sends the file as it is.
|
||||
"""
|
||||
if len(data) % UF2_BLOCK_SIZE:
|
||||
return None
|
||||
count = len(data) // UF2_BLOCK_SIZE
|
||||
kept: list[bytes] = []
|
||||
keep = True
|
||||
for seq in range(count):
|
||||
block = data[seq * UF2_BLOCK_SIZE : (seq + 1) * UF2_BLOCK_SIZE]
|
||||
flags, _, length, block_seq, block_count = _HEADER_WORDS.unpack_from(block, 8)
|
||||
# A missing or repeated block must stay visible to the device, which
|
||||
# takes the update size from the block count
|
||||
if (
|
||||
block[:8] != UF2_MAGIC_HEAD
|
||||
or block[_DATA_END:] != UF2_MAGIC_TAIL
|
||||
or _DATA_START + length > _DATA_END
|
||||
or (block_seq, block_count) != (seq, count)
|
||||
):
|
||||
return None
|
||||
tags = _tags(block, length) if flags & UF2_FLAG_HAS_TAGS else {}
|
||||
if tags is None:
|
||||
return None
|
||||
if (part_info := tags.get(UF2_TAG_OTA_PART_INFO)) is not None:
|
||||
# uf2ota rejects a selector without the whole scheme map
|
||||
if len(part_info) < 3:
|
||||
return None
|
||||
# Any of the three device scheme nibbles names a partition
|
||||
keep = int.from_bytes(part_info[:2], "big") >> 4 != 0
|
||||
if keep:
|
||||
kept.append(block)
|
||||
elif not _KEEP_TAGS.isdisjoint(tags):
|
||||
# Without its image's OTA_PART_INFO the device would write this
|
||||
# block to the partition of the image before it
|
||||
return None
|
||||
if len(kept) == count:
|
||||
return None
|
||||
out = bytearray(b"".join(kept))
|
||||
for seq in range(len(kept)):
|
||||
struct.pack_into("<2I", out, seq * UF2_BLOCK_SIZE + _SEQ_OFFSET, seq, len(kept))
|
||||
return bytes(out)
|
||||
@@ -77,3 +77,7 @@ async def pin_to_code(config: ConfigType) -> MockObj:
|
||||
# Called by writer.py; delegates to the shared libretiny implementation.
|
||||
def copy_files() -> None:
|
||||
libretiny.copy_files()
|
||||
|
||||
|
||||
# Called by the OTA upload; the shared libretiny implementation.
|
||||
ota_image = libretiny.device_ota_image
|
||||
@@ -607,9 +607,10 @@ async def _late_logger_init(config: ConfigType) -> None:
|
||||
# esp_rom_printf instead of pulling ~1.2KB esp_rom_vprintf into IRAM.
|
||||
# S2/C2 have a ROM vprintf, so IDF forces CONSTRAINED_ENV_SAFE=1 and
|
||||
# cache-off DRAM logs would reach the flash-resident wrapper; keep V1.
|
||||
if idf_version() >= cv.Version(6, 1, 0) and get_esp32_variant() not in (
|
||||
VARIANT_ESP32C2,
|
||||
VARIANT_ESP32S2,
|
||||
if (
|
||||
CORE.using_toolchain_esp_idf
|
||||
and idf_version() >= cv.Version(6, 1, 0)
|
||||
and get_esp32_variant() not in (VARIANT_ESP32C2, VARIANT_ESP32S2)
|
||||
):
|
||||
add_idf_sdkconfig_option("CONFIG_LOG_VERSION_1", False)
|
||||
add_idf_sdkconfig_option("CONFIG_LOG_VERSION_2", True)
|
||||
|
||||
@@ -2,7 +2,6 @@ from collections.abc import Callable
|
||||
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import audio
|
||||
from esphome.components.const import CONF_BITRATE
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
@@ -116,6 +115,8 @@ def validate_preferred_format(
|
||||
"""
|
||||
|
||||
def validator(config: ConfigType) -> ConfigType:
|
||||
from esphome.components import audio
|
||||
|
||||
# Inherit settings from audio device if not manually set
|
||||
inherit_property_from(CONF_NUM_CHANNELS, audio_device_key)(config)
|
||||
inherit_property_from(CONF_SAMPLE_RATE, audio_device_key)(config)
|
||||
@@ -155,6 +156,8 @@ def request_codecs_for_format_configs(
|
||||
|
||||
Public API for external components. Do not remove.
|
||||
"""
|
||||
from esphome.components import audio
|
||||
|
||||
needed_formats: set[str] = set()
|
||||
need_all = False
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <span>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
@@ -53,16 +54,25 @@ using DataCallbackManagerBase = CallbackManager<void(const AudioCapture &)>;
|
||||
|
||||
class DataCallbackManager : public DataCallbackManagerBase {
|
||||
public:
|
||||
explicit DataCallbackManager(const audio::AudioStreamInfo *stream_info) : stream_info_(stream_info) {}
|
||||
DataCallbackManager(const audio::AudioStreamInfo *stream_info, const bool *mute_state)
|
||||
: stream_info_(stream_info), mute_state_(mute_state) {}
|
||||
|
||||
using DataCallbackManagerBase::call;
|
||||
|
||||
// Remove before 2027.5.0, along with this class (use a plain CallbackManager)
|
||||
ESPDEPRECATED("Use Microphone::publish_audio_() instead. Removed in 2027.5.0", "2026.11.0")
|
||||
void call(const std::vector<uint8_t> &data) { this->call(AudioCapture{data, *this->stream_info_, 0}); }
|
||||
void call(const std::vector<uint8_t> &data) {
|
||||
if (*this->mute_state_) {
|
||||
const std::vector<uint8_t> zeros(data.size(), 0);
|
||||
this->call(AudioCapture{zeros, *this->stream_info_, 0});
|
||||
} else {
|
||||
this->call(AudioCapture{data, *this->stream_info_, 0});
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
const audio::AudioStreamInfo *stream_info_;
|
||||
const bool *mute_state_;
|
||||
};
|
||||
|
||||
class Microphone {
|
||||
@@ -72,15 +82,7 @@ class Microphone {
|
||||
|
||||
/// Callbacks take (const AudioCapture &) and run on the microphone's task.
|
||||
template<typename F> void add_data_callback(F &&data_callback) {
|
||||
this->data_callbacks_.add(
|
||||
[this, callback = as_capture_callback(std::forward<F>(data_callback))](const AudioCapture &capture) {
|
||||
if (this->mute_state_) {
|
||||
const std::vector<uint8_t> zeros(capture.data.size(), 0);
|
||||
callback(AudioCapture{zeros, capture.stream_info, capture.capture_time_us});
|
||||
} else {
|
||||
callback(capture);
|
||||
}
|
||||
});
|
||||
this->data_callbacks_.add(as_capture_callback(std::forward<F>(data_callback)));
|
||||
}
|
||||
|
||||
bool is_running() const { return this->state_ == STATE_RUNNING; }
|
||||
@@ -92,8 +94,11 @@ class Microphone {
|
||||
audio::AudioStreamInfo get_audio_stream_info() { return this->audio_stream_info_; }
|
||||
|
||||
protected:
|
||||
void publish_audio_(std::span<const uint8_t> data, const audio::AudioStreamInfo &stream_info,
|
||||
int64_t capture_time_us = 0) {
|
||||
/// While muted, data is zeroed first, so it must be a buffer the platform owns.
|
||||
void publish_audio_(std::span<uint8_t> data, const audio::AudioStreamInfo &stream_info, int64_t capture_time_us = 0) {
|
||||
if (this->mute_state_) {
|
||||
std::memset(data.data(), 0, data.size());
|
||||
}
|
||||
this->data_callbacks_.call(AudioCapture{data, stream_info, capture_time_us});
|
||||
}
|
||||
|
||||
@@ -105,7 +110,7 @@ class Microphone {
|
||||
audio::AudioStreamInfo audio_stream_info_;
|
||||
|
||||
// Make private when the deprecated call(data) is removed in 2027.5.0
|
||||
DataCallbackManager data_callbacks_{&this->audio_stream_info_};
|
||||
DataCallbackManager data_callbacks_{&this->audio_stream_info_, &this->mute_state_};
|
||||
};
|
||||
|
||||
} // namespace esphome::microphone
|
||||
@@ -107,12 +107,7 @@ void MipiDsi::setup() {
|
||||
}
|
||||
#endif
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
} else {
|
||||
esp_lcd_panel_io_tx_param(this->io_handle_, SW_RESET_CMD, nullptr, 0);
|
||||
}
|
||||
|
||||
@@ -33,14 +33,7 @@ void MipiRgb::setup_enables_() {
|
||||
}
|
||||
delay(10);
|
||||
}
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
}
|
||||
|
||||
#ifdef USE_SPI
|
||||
|
||||
@@ -151,15 +151,8 @@ class MipiSpi : public display::Display,
|
||||
pin->setup();
|
||||
pin->digital_write(true);
|
||||
}
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
// required delay after reset is already in the init sequence, don't duplicate
|
||||
}
|
||||
// required delay after reset is already in the init sequence, don't duplicate
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
|
||||
// need to know when the display is ready for SLPOUT command - will be 120ms after reset
|
||||
auto when = millis() + 120;
|
||||
|
||||
@@ -226,6 +226,12 @@ def set_sdkconfig_options(config: ConfigType) -> None:
|
||||
add_idf_sdkconfig_option("CONFIG_OPENTHREAD_DNS64_CLIENT", not border_router)
|
||||
add_idf_sdkconfig_option("CONFIG_OPENTHREAD_SRP_CLIENT", not border_router)
|
||||
if not border_router:
|
||||
# The DNS64 hook breaks IPv6 literal lookups; see openthread_esp.cpp.
|
||||
# Fixed upstream on ESP-IDF master, remove this once a release includes
|
||||
# "fix(openthread): bypass DNS64 synthesis for IPv6 literals",
|
||||
# https://github.com/espressif/esp-idf/commit/87b133ee1a7e91c1ee95176b4733b7f72236e5da
|
||||
# (merged in https://github.com/espressif/esp-idf/commit/83239509832bf5d427935cd365f4b62a320e8765)
|
||||
cg.add_build_flag("-Wl,--wrap=lwip_hook_dns_external_resolve")
|
||||
add_idf_sdkconfig_option("CONFIG_OPENTHREAD_SRP_CLIENT_MAX_SERVICES", 5)
|
||||
|
||||
if border_router:
|
||||
|
||||
@@ -35,6 +35,10 @@
|
||||
#include "esp_vfs_eventfd.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#ifndef USE_OPENTHREAD_BORDER_ROUTER
|
||||
#include "lwip/dns.h"
|
||||
#include "lwip/ip_addr.h"
|
||||
#endif
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "openthread");
|
||||
|
||||
@@ -489,4 +493,26 @@ InstanceLock::~InstanceLock() {
|
||||
}
|
||||
|
||||
} // namespace esphome::openthread
|
||||
|
||||
#ifndef USE_OPENTHREAD_BORDER_ROUTER
|
||||
// ESP-IDF's DNS64 hook runs before lwIP's literal address check and retries every lookup as IPv4,
|
||||
// so an IPv6 literal never resolves. Let lwIP handle those; linked with --wrap from __init__.py.
|
||||
// Fixed upstream on ESP-IDF master, remove this once a release includes
|
||||
// "fix(openthread): bypass DNS64 synthesis for IPv6 literals",
|
||||
// https://github.com/espressif/esp-idf/commit/87b133ee1a7e91c1ee95176b4733b7f72236e5da
|
||||
// (merged in https://github.com/espressif/esp-idf/commit/83239509832bf5d427935cd365f4b62a320e8765)
|
||||
// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
|
||||
extern "C" {
|
||||
int __real_lwip_hook_dns_external_resolve(const char *name, ip_addr_t *addr, dns_found_callback found,
|
||||
void *callback_arg, u8_t addrtype, err_t *err);
|
||||
int __wrap_lwip_hook_dns_external_resolve(const char *name, ip_addr_t *addr, dns_found_callback found,
|
||||
void *callback_arg, u8_t addrtype, err_t *err) {
|
||||
ip_addr_t literal;
|
||||
if (ipaddr_aton(name, &literal) && IP_IS_V6_VAL(literal))
|
||||
return 0;
|
||||
return __real_lwip_hook_dns_external_resolve(name, addr, found, callback_arg, addrtype, err);
|
||||
}
|
||||
} // extern "C"
|
||||
// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
|
||||
#endif // USE_OPENTHREAD_BORDER_ROUTER
|
||||
#endif
|
||||
@@ -9,23 +9,10 @@ ESPHOME_LOG_TAG(TAG, "pcd_8544");
|
||||
|
||||
void PCD8544::setup_pins_() {
|
||||
this->spi_setup();
|
||||
this->init_reset_();
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10});
|
||||
this->dc_pin_->setup();
|
||||
}
|
||||
|
||||
void PCD8544::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
|
||||
void PCD8544::initialize() {
|
||||
this->init_internal_(this->get_buffer_length_());
|
||||
|
||||
|
||||
@@ -57,8 +57,6 @@ class PCD8544 final : public display::DisplayBuffer,
|
||||
|
||||
void setup_pins_();
|
||||
|
||||
void init_reset_();
|
||||
|
||||
size_t get_buffer_length_();
|
||||
|
||||
void start_command_();
|
||||
|
||||
@@ -90,6 +90,7 @@ bool ResamplerMicrophone::init_resampler_(const audio::AudioStreamInfo &input_st
|
||||
|
||||
if (input_stream_info.get_sample_rate() == this->target_sample_rate_) {
|
||||
// The source already delivers the target sample rate, so its audio is passed through unchanged
|
||||
this->output_buffer_.reserve(input_stream_info.ms_to_bytes(BUFFER_DURATION_MS));
|
||||
this->input_stream_info_ = input_stream_info;
|
||||
this->resampler_ready_ = true;
|
||||
return true;
|
||||
@@ -137,7 +138,23 @@ void ResamplerMicrophone::process_audio_(const microphone::AudioCapture &capture
|
||||
}
|
||||
|
||||
if (this->resampler_ == nullptr) {
|
||||
this->publish_audio_(capture.data, input_stream_info, capture.capture_time_us);
|
||||
if (this->mute_state_) {
|
||||
// The source's buffer is shared with its other consumers, so publish zeros from our own buffer, in pieces that
|
||||
// fit its reserved size so muting never allocates
|
||||
const uint32_t max_frames = input_stream_info.ms_to_frames(BUFFER_DURATION_MS);
|
||||
const uint32_t total_frames = input_stream_info.bytes_to_frames(capture.data.size());
|
||||
for (uint32_t done = 0; done < total_frames;) {
|
||||
const uint32_t frames = std::min(total_frames - done, max_frames);
|
||||
this->output_buffer_.assign(input_stream_info.frames_to_bytes(frames), 0);
|
||||
const int64_t time_us =
|
||||
capture.capture_time_us == 0 ? 0 : capture.capture_time_us + input_stream_info.frames_to_microseconds(done);
|
||||
this->publish_audio_(this->output_buffer_, input_stream_info, time_us);
|
||||
done += frames;
|
||||
}
|
||||
} else {
|
||||
// Needs a protected forwarding method once data_callbacks_ is made private in 2027.5.0
|
||||
this->data_callbacks_.call(microphone::AudioCapture{capture.data, input_stream_info, capture.capture_time_us});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -77,3 +77,7 @@ async def pin_to_code(config: ConfigType) -> MockObj:
|
||||
# Called by writer.py; delegates to the shared libretiny implementation.
|
||||
def copy_files() -> None:
|
||||
libretiny.copy_files()
|
||||
|
||||
|
||||
# Called by the OTA upload; the shared libretiny implementation.
|
||||
ota_image = libretiny.device_ota_image
|
||||
@@ -45,7 +45,6 @@ from esphome.const import (
|
||||
CONF_TIMEOUT,
|
||||
CONF_TO,
|
||||
CONF_TRIGGER_ID,
|
||||
CONF_TYPE_ID,
|
||||
CONF_UNIT_OF_MEASUREMENT,
|
||||
CONF_USE_FAHRENHEIT,
|
||||
CONF_VALUE,
|
||||
@@ -1009,26 +1008,17 @@ def _timeout_throttle_period(
|
||||
return timeout[CONF_TIMEOUT]
|
||||
|
||||
|
||||
def _timeout_throttle_merge(first: ConfigType, second: ConfigType) -> tuple | None:
|
||||
if (period := _timeout_throttle_period(first, second)) is None:
|
||||
return None
|
||||
return TimeoutThrottleFilter, [period]
|
||||
|
||||
|
||||
async def _build_chain_filters(config: list[ConfigType]) -> list:
|
||||
"""Like build_filters, but merges the radar `timeout` + `throttle_with_priority` pair into one filter."""
|
||||
filters = []
|
||||
i = 0
|
||||
while i < len(config):
|
||||
if (
|
||||
i + 1 < len(config)
|
||||
and (period := _timeout_throttle_period(config[i], config[i + 1]))
|
||||
is not None
|
||||
):
|
||||
filter_id = config[i][CONF_TYPE_ID].copy()
|
||||
filter_id.type = TimeoutThrottleFilter
|
||||
var = cg.new_Pvariable(filter_id, period)
|
||||
await cg.register_component(var, {})
|
||||
filters.append(var)
|
||||
i += 2
|
||||
continue
|
||||
filters.append(await cg.build_registry_entry(FILTER_REGISTRY, config[i]))
|
||||
i += 1
|
||||
return filters
|
||||
return await cg.build_registry_list_merged(
|
||||
FILTER_REGISTRY, config, _timeout_throttle_merge
|
||||
)
|
||||
|
||||
|
||||
_CALLBACK_AUTOMATIONS = (
|
||||
|
||||
@@ -122,18 +122,7 @@ void SH1122::fill(Color color) {
|
||||
const uint8_t fill = (color4 & SH1122_COLORMASK) | ((color4 & SH1122_COLORMASK) << SH1122_COLORSHIFT);
|
||||
memset(this->buffer_, fill, this->get_buffer_length_());
|
||||
}
|
||||
void SH1122::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SH1122::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const LogString *SH1122::model_str_() {
|
||||
switch (this->model_) {
|
||||
case SH1122_MODEL_256_64:
|
||||
|
||||
@@ -355,18 +355,7 @@ void SSD1306::fill(Color color) {
|
||||
for (uint32_t i = 0; i < this->get_buffer_length_(); i++)
|
||||
this->buffer_[i] = fill;
|
||||
}
|
||||
void SSD1306::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1306::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const LogString *SSD1306::model_str_() {
|
||||
return ModelStrings::get_log_str(static_cast<uint8_t>(this->model_), ModelStrings::LAST_INDEX);
|
||||
}
|
||||
|
||||
@@ -184,18 +184,7 @@ void SSD1322::fill(Color color) {
|
||||
for (uint32_t i = 0; i < this->get_buffer_length_(); i++)
|
||||
this->buffer_[i] = fill;
|
||||
}
|
||||
void SSD1322::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1322::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const char *SSD1322::model_str_() {
|
||||
switch (this->model_) {
|
||||
case SSD1322_MODEL_256_64:
|
||||
|
||||
@@ -211,18 +211,7 @@ void SSD1325::fill(Color color) {
|
||||
for (uint32_t i = 0; i < this->get_buffer_length_(); i++)
|
||||
this->buffer_[i] = fill;
|
||||
}
|
||||
void SSD1325::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1325::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const char *SSD1325::model_str_() {
|
||||
switch (this->model_) {
|
||||
case SSD1325_MODEL_128_32:
|
||||
|
||||
@@ -160,18 +160,7 @@ void SSD1327::fill(Color color) {
|
||||
for (uint32_t i = 0; i < this->get_buffer_length_(); i++)
|
||||
this->buffer_[i] = fill;
|
||||
}
|
||||
void SSD1327::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1327::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const char *SSD1327::model_str_() {
|
||||
switch (this->model_) {
|
||||
case SSD1327_MODEL_128_128:
|
||||
|
||||
@@ -142,17 +142,6 @@ void SSD1331::fill(Color color) {
|
||||
}
|
||||
}
|
||||
}
|
||||
void SSD1331::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1331::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
|
||||
} // namespace esphome::ssd1331_base
|
||||
@@ -174,18 +174,7 @@ void SSD1351::fill(Color color) {
|
||||
}
|
||||
}
|
||||
}
|
||||
void SSD1351::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void SSD1351::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
const char *SSD1351::model_str_() {
|
||||
switch (this->model_) {
|
||||
case SSD1351_MODEL_128_96:
|
||||
|
||||
@@ -9,12 +9,8 @@ ESPHOME_LOG_TAG(TAG, "st7123.touchscreen");
|
||||
|
||||
void ST7123Touchscreen::setup() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(false); // TP_RESX is active low, assert for at least tRSTW (2ms)
|
||||
delay(5);
|
||||
this->reset_pin_->digital_write(true);
|
||||
// TP_RESX is active low, assert for at least tRSTW (2ms)
|
||||
pulse_reset(this->reset_pin_, {.high_before_ms = 5, .low_ms = 5});
|
||||
// The controller needs up to 20ms to initialize after reset before it can be accessed.
|
||||
this->setup_time_ = millis() + 30;
|
||||
}
|
||||
|
||||
@@ -137,18 +137,7 @@ void ST7567::fill(Color color) {
|
||||
memset(buffer_, fill, this->get_buffer_length_());
|
||||
}
|
||||
|
||||
void ST7567::init_reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(1);
|
||||
// Trigger Reset
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
// Wake up
|
||||
this->reset_pin_->digital_write(true);
|
||||
}
|
||||
}
|
||||
void ST7567::init_reset_() { pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}); }
|
||||
|
||||
const char *ST7567::model_str_() { return "ST7567 128x64"; }
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from esphome.automation import maybe_simple_id
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
from esphome.components.audio_dac import AudioDac
|
||||
from esphome.components.const import CONF_MODULATION
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ENABLE_PIN, CONF_ID, CONF_MODEL
|
||||
from esphome.cpp_generator import MockObj
|
||||
@@ -19,6 +20,7 @@ DEPENDENCIES = ["i2c"]
|
||||
|
||||
CONF_ANALOG_GAIN = "analog_gain"
|
||||
CONF_DAC_MODE = "dac_mode"
|
||||
CONF_FAULT_OUTPUT = "fault_output"
|
||||
CONF_IGNORE_ENABLE_PIN_WARNING = "ignore_enable_pin_warning"
|
||||
CONF_MIXER_MODE = "mixer_mode"
|
||||
CONF_VOLUME_MIN_DB = "volume_min_db"
|
||||
@@ -39,6 +41,11 @@ MIXER_MODES = MixerMode.options(
|
||||
"stereo", "stereo_inverse", "mono", "left", "right", prefix="MIXER_MODE_"
|
||||
)
|
||||
|
||||
Modulation = tas58xx_ns.enum("Modulation")
|
||||
MODULATIONS = Modulation.options("bd_mode", "1spw_mode", prefix="MODULATION_")
|
||||
|
||||
FAULT_OUTPUT_NONE = "none"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Model:
|
||||
@@ -49,6 +56,9 @@ class Model:
|
||||
volume_min_db: float
|
||||
volume_max_db: float
|
||||
default_address: int
|
||||
# Pins that can report FAULTZ: name -> pin number n, selected at 0x61 + n (ModelInfo::fault_output_pins)
|
||||
fault_outputs: dict[str, int]
|
||||
default_fault_output: str
|
||||
|
||||
|
||||
MODELS: dict[str, Model] = {
|
||||
@@ -58,6 +68,8 @@ MODELS: dict[str, Model] = {
|
||||
volume_min_db=-103.0,
|
||||
volume_max_db=24.0,
|
||||
default_address=0x2D,
|
||||
fault_outputs={"adr": 0},
|
||||
default_fault_output="adr",
|
||||
),
|
||||
DAC_TAS5825M: Model(
|
||||
model_info=tas58xx_ns.TAS5825M_MODEL,
|
||||
@@ -65,6 +77,8 @@ MODELS: dict[str, Model] = {
|
||||
volume_min_db=-103.0,
|
||||
volume_max_db=24.0,
|
||||
default_address=0x4C,
|
||||
fault_outputs={"gpio0": 0, "gpio1": 1, "gpio2": 2},
|
||||
default_fault_output="gpio1",
|
||||
),
|
||||
}
|
||||
|
||||
@@ -100,9 +114,15 @@ def _model_schema(model: Model) -> cv.Schema:
|
||||
cv.Optional(CONF_DAC_MODE, default="btl"): cv.enum(
|
||||
DAC_MODES, lower=True
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_FAULT_OUTPUT, default=model.default_fault_output
|
||||
): cv.one_of(FAULT_OUTPUT_NONE, *model.fault_outputs, lower=True),
|
||||
cv.Optional(CONF_MIXER_MODE, default="stereo"): cv.enum(
|
||||
MIXER_MODES, lower=True
|
||||
),
|
||||
cv.Optional(CONF_MODULATION, default="bd_mode"): cv.enum(
|
||||
MODULATIONS, lower=True
|
||||
),
|
||||
cv.Optional(
|
||||
CONF_VOLUME_MIN_DB, default=model.volume_min_db
|
||||
): volume_validator,
|
||||
@@ -172,7 +192,10 @@ async def to_code(config: ConfigType) -> None:
|
||||
|
||||
cg.add(var.set_analog_gain(config[CONF_ANALOG_GAIN]))
|
||||
cg.add(var.set_dac_mode(config[CONF_DAC_MODE]))
|
||||
if (fault_output := config[CONF_FAULT_OUTPUT]) != FAULT_OUTPUT_NONE:
|
||||
cg.add(var.set_fault_output(model.fault_outputs[fault_output]))
|
||||
cg.add(var.set_mixer_mode(config[CONF_MIXER_MODE]))
|
||||
cg.add(var.set_modulation(config[CONF_MODULATION]))
|
||||
cg.add(var.set_volume_min_db(config[CONF_VOLUME_MIN_DB]))
|
||||
cg.add(var.set_volume_max_db(config[CONF_VOLUME_MAX_DB]))
|
||||
await cg.add_pin(var.set_enable_pin, config.get(CONF_ENABLE_PIN))
|
||||
@@ -8,11 +8,8 @@ namespace esphome::tas58xx {
|
||||
// Registers 0x46, 0x7D, 0x7E and page 1 register 0x51 are not documented in the datasheet.
|
||||
static constexpr i2c::I2CRegValue STARTUP_SEQUENCE[] PROGMEM = {
|
||||
{0x03, 0x00}, // DEVICE_CTRL_2: deep sleep
|
||||
{0x46, 0x01},
|
||||
{0x46, 0x01}, // PPC 96 kHz process flow value (its 48 kHz FIR flows write 0x11)
|
||||
{0x03, 0x02}, // DEVICE_CTRL_2: Hi-Z
|
||||
// The I2C address is latched at power up, after which the ADR pin can report faults
|
||||
{0x61, 0x0B}, // ADR_PIN_CONFIG: FAULTZ
|
||||
{0x60, 0x01}, // ADR_PIN_CTRL: output
|
||||
{0x7D, 0x11},
|
||||
{0x7E, 0xFF},
|
||||
{0x00, 0x01}, // Page 1
|
||||
@@ -25,6 +22,8 @@ static constexpr i2c::I2CRegValue STARTUP_SEQUENCE[] PROGMEM = {
|
||||
|
||||
static const LogString *model_name() { return LOG_STR("TAS5805M"); }
|
||||
|
||||
static const LogString *fault_output_name(uint8_t) { return LOG_STR("ADR"); }
|
||||
|
||||
// An if chain rather than a switch: a switch table would land in rodata, which is RAM on ESP8266.
|
||||
static const LogString *fault_name(uint8_t index) {
|
||||
if (index == 0)
|
||||
@@ -88,6 +87,8 @@ const ModelInfo TAS5805M_MODEL = {
|
||||
NO_BIT, // FAULT_SENSOR_RIGHT_CHANNEL_CBC_OVER_CURRENT_WARNING
|
||||
NO_BIT, // FAULT_SENSOR_OVER_TEMP_146C_WARNING
|
||||
},
|
||||
.fault_output_pins = 1, // ADR
|
||||
.fault_output_name = fault_output_name,
|
||||
};
|
||||
|
||||
} // namespace esphome::tas58xx
|
||||
@@ -6,7 +6,7 @@ namespace esphome::tas58xx {
|
||||
|
||||
// Remainder of the startup sequence, run after the reset in TAS58xx::init_(). Register 0x00 selects the page.
|
||||
// Based on the TI PurePath Console (PPC) export for "TAS5825M 2-Band DRC&AGL 2.0 96k".
|
||||
// Registers 0x46, 0x7D, 0x7E, page 1 register 0x51 and page 2 registers 0x1D, 0x19 are not documented in datasheet.
|
||||
// Registers 0x7D, 0x7E, page 1 register 0x51 and page 2 registers 0x1D, 0x19 are not documented in datasheet.
|
||||
static constexpr i2c::I2CRegValue STARTUP_SEQUENCE[] PROGMEM = {
|
||||
{0x03, 0x00}, // DEVICE_CTRL_2: deep sleep, the state the PPC sequence starts from
|
||||
{0x7D, 0x11},
|
||||
@@ -17,20 +17,25 @@ static constexpr i2c::I2CRegValue STARTUP_SEQUENCE[] PROGMEM = {
|
||||
{0x1D, 0x00},
|
||||
{0x19, 0x80},
|
||||
{0x00, 0x00}, // Page 0
|
||||
{0x46, 0x11},
|
||||
{0x46, 0x11}, // DSP_CTRL: 96 kHz processing (bits 4-3 = 10), use default coefficients (bit 0 = 1)
|
||||
// PPC also writes 0x02 (DEVICE_CTRL_1) and 0x54 (AGAIN) here; init_() writes both from YAML
|
||||
{0x53, 0x01}, // ANA_CTRL: in phase, 100kHz bandwidth for high audio performance with Fsw=384kHz
|
||||
{0x03, 0x02}, // DEVICE_CTRL_2: Hi-Z
|
||||
|
||||
// Additional register configuration
|
||||
// GPIO1 is a dedicated pin on TAS5825M (separate from ADR), used as FAULTZ
|
||||
{0x62, 0x0B}, // GPIO1_SEL: GPIO1 as FAULTZ
|
||||
{0x60, 0x02}, // GPIO_CTRL: GPIO1 is output
|
||||
{0x77, 0x07}, // CBC_CONTROL: enable cycle-by-cycle current limit for warnings and faults
|
||||
};
|
||||
|
||||
static const LogString *model_name() { return LOG_STR("TAS5825M"); }
|
||||
|
||||
static const LogString *fault_output_name(uint8_t pin) {
|
||||
if (pin == 0)
|
||||
return LOG_STR("GPIO0");
|
||||
if (pin == 1)
|
||||
return LOG_STR("GPIO1");
|
||||
return LOG_STR("GPIO2");
|
||||
}
|
||||
|
||||
// An if chain rather than a switch: a switch table would land in rodata, which is RAM on ESP8266.
|
||||
static const LogString *fault_name(uint8_t index) {
|
||||
if (index == 0)
|
||||
@@ -113,6 +118,8 @@ const ModelInfo TAS5825M_MODEL = {
|
||||
// 25, // FAULT_SENSOR_OVER_TEMP_122C_WARNING // not currently included
|
||||
// 24, // FAULT_SENSOR_OVER_TEMP_112C_WARNING // not currently included
|
||||
},
|
||||
.fault_output_pins = 3, // GPIO0, GPIO1, GPIO2 (ADR is an analog input only on TAS5825M)
|
||||
.fault_output_name = fault_output_name,
|
||||
};
|
||||
|
||||
} // namespace esphome::tas58xx
|
||||
@@ -20,6 +20,7 @@ static constexpr uint8_t TAS58XX_RESET_CTRL = 0x01;
|
||||
static constexpr uint8_t TAS58XX_RESET_CTRL_ALL = 0x11; // Reset DSP/control port and registers
|
||||
static constexpr uint8_t TAS58XX_DEVICE_CTRL_1 = 0x02;
|
||||
static constexpr uint8_t TAS58XX_DEVICE_CTRL_1_PBTL = (1 << 2);
|
||||
static constexpr uint8_t TAS58XX_DEVICE_CTRL_1_1SPW = 0x01; // DAMP_MOD = 01
|
||||
static constexpr uint8_t TAS58XX_DEVICE_CTRL_2 = 0x03;
|
||||
static constexpr uint8_t TAS58XX_DEVICE_CTRL_2_MUTE = (1 << 3);
|
||||
static constexpr uint8_t TAS58XX_CTRL_STATE_MASK = 0x03; // DEVICE_CTRL_2 and POWER_STATE
|
||||
@@ -33,6 +34,9 @@ static constexpr uint8_t TAS58XX_DIG_VOL_0DB = 0x30;
|
||||
static constexpr uint8_t TAS58XX_DIG_VOL_MINUS_103DB = 0xFE;
|
||||
static constexpr uint8_t TAS58XX_AGAIN = 0x54; // 0x00 = 0 dB to 0x1F = -15.5 dB in 0.5 dB steps
|
||||
static constexpr uint8_t TAS58XX_AGAIN_MINUS_15_5DB = 0x1F;
|
||||
static constexpr uint8_t TAS58XX_GPIO_CTRL = 0x60; // ADR_PIN_CTRL on TAS5805M: output enable, bit n for pin n
|
||||
static constexpr uint8_t TAS58XX_GPIO0_SEL = 0x61; // ADR_PIN_CONFIG on TAS5805M: pin n is selected at 0x61 + n
|
||||
static constexpr uint8_t TAS58XX_GPIO_SEL_FAULTZ = 0x0B; // pin function: FAULTZ output
|
||||
static constexpr uint8_t TAS58XX_POWER_STATE = 0x68;
|
||||
static constexpr uint8_t TAS58XX_CHAN_FAULT = 0x70; // GLOBAL_FAULT1, GLOBAL_FAULT2 and OT_WARNING follow
|
||||
static constexpr uint8_t TAS58XX_FAULT_REGISTER_COUNT = 4;
|
||||
@@ -98,12 +102,26 @@ bool TAS58xx::init_() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Setters are public, so keep the value inside the register range
|
||||
// The I2C address is latched at power up, so ADR can now be an output. The pin function is written before the
|
||||
// output enable, so the pin never drives another function.
|
||||
if (this->fault_output_pin_ != FAULT_OUTPUT_NONE) {
|
||||
// The setter is public, so only write this model's pins; YAML only allows the pins of the model
|
||||
if (this->fault_output_pin_ >= this->model_->fault_output_pins) {
|
||||
ESP_LOGW(TAG, "Invalid fault output index %u", this->fault_output_pin_);
|
||||
} else if (!this->write_byte(TAS58XX_GPIO0_SEL + this->fault_output_pin_, TAS58XX_GPIO_SEL_FAULTZ) ||
|
||||
!this->write_byte(TAS58XX_GPIO_CTRL, static_cast<uint8_t>(1 << this->fault_output_pin_))) {
|
||||
ESP_LOGE(TAG, "I2C write failed during init");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Setters are public, so keep the values inside the register ranges
|
||||
const uint8_t again =
|
||||
static_cast<uint8_t>(lroundf(clamp(-this->analog_gain_db_ * 2.0f, 0.0f, float{TAS58XX_AGAIN_MINUS_15_5DB})));
|
||||
if (!this->write_byte(TAS58XX_DEVICE_CTRL_1, this->dac_mode_ == DAC_MODE_PBTL ? TAS58XX_DEVICE_CTRL_1_PBTL : 0) ||
|
||||
!this->write_byte(TAS58XX_AGAIN, again) || !this->write_volume_() ||
|
||||
!this->write_ctrl_state_(TAS58XX_CTRL_STATE_PLAY, this->is_muted_) ||
|
||||
const uint8_t device_ctrl_1 = (this->dac_mode_ == DAC_MODE_PBTL ? TAS58XX_DEVICE_CTRL_1_PBTL : 0) |
|
||||
(this->modulation_ == MODULATION_1SPW_MODE ? TAS58XX_DEVICE_CTRL_1_1SPW : 0);
|
||||
if (!this->write_byte(TAS58XX_DEVICE_CTRL_1, device_ctrl_1) || !this->write_byte(TAS58XX_AGAIN, again) ||
|
||||
!this->write_volume_() || !this->write_ctrl_state_(TAS58XX_CTRL_STATE_PLAY, this->is_muted_) ||
|
||||
!this->write_byte(TAS58XX_FAULT_CLEAR, TAS58XX_FAULT_CLEAR_ANALOG)) {
|
||||
ESP_LOGE(TAG, "I2C write failed during init");
|
||||
return false;
|
||||
@@ -263,6 +281,14 @@ void TAS58xx::dump_config() {
|
||||
} else {
|
||||
mixer_mode = LOG_STR("Stereo");
|
||||
}
|
||||
const LogString *fault_output;
|
||||
if (this->fault_output_pin_ == FAULT_OUTPUT_NONE) {
|
||||
fault_output = LOG_STR("None");
|
||||
} else if (this->fault_output_pin_ >= this->model_->fault_output_pins) {
|
||||
fault_output = LOG_STR("Invalid");
|
||||
} else {
|
||||
fault_output = this->model_->fault_output_name(this->fault_output_pin_);
|
||||
}
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Audio Amplifier:\n"
|
||||
" Model: %s",
|
||||
@@ -273,11 +299,14 @@ void TAS58xx::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
" Analog Gain: %.1f dB\n"
|
||||
" DAC Mode: %s\n"
|
||||
" Modulation: %s\n"
|
||||
" Mixer Mode: %s\n"
|
||||
" Volume Range: %.1f dB to %.1f dB",
|
||||
" Volume Range: %.1f dB to %.1f dB\n"
|
||||
" Fault Output: %s",
|
||||
this->analog_gain_db_,
|
||||
this->dac_mode_ == DAC_MODE_PBTL ? LOG_STR_LITERAL("PBTL") : LOG_STR_LITERAL("BTL"),
|
||||
LOG_STR_ARG(mixer_mode), this->volume_min_db_, this->volume_max_db_);
|
||||
this->modulation_ == MODULATION_1SPW_MODE ? LOG_STR_LITERAL("1SPW") : LOG_STR_LITERAL("BD"),
|
||||
LOG_STR_ARG(mixer_mode), this->volume_min_db_, this->volume_max_db_, LOG_STR_ARG(fault_output));
|
||||
#ifdef USE_BINARY_SENSOR
|
||||
LOG_BINARY_SENSOR(" ", "Any Fault", this->have_fault_binary_sensor_);
|
||||
for (auto *sensor : this->fault_binary_sensors_) {
|
||||
|
||||
@@ -22,6 +22,12 @@ enum DacMode : uint8_t {
|
||||
DAC_MODE_PBTL = 1, // Parallel bridge tied load, one speaker
|
||||
};
|
||||
|
||||
/// DEVICE_CTRL_1 DAMP_MOD values, the same on all models
|
||||
enum Modulation : uint8_t {
|
||||
MODULATION_BD_MODE = 0,
|
||||
MODULATION_1SPW_MODE = 1,
|
||||
};
|
||||
|
||||
enum MixerMode : uint8_t {
|
||||
MIXER_MODE_STEREO = 0,
|
||||
MIXER_MODE_STEREO_INVERSE,
|
||||
@@ -64,6 +70,8 @@ static_assert(
|
||||
|
||||
/// ModelInfo::fault_sensor_bits value for a FaultSensor that the model does not have.
|
||||
static constexpr uint8_t NO_BIT = 0xFF;
|
||||
/// fault_output_pin_ value for no fault output
|
||||
static constexpr uint8_t FAULT_OUTPUT_NONE = 0xFF;
|
||||
|
||||
/// Everything that differs between models of the family. One constant instance exists per model, see
|
||||
/// model_*.cpp, and each TAS58xx instance points to the one for its model.
|
||||
@@ -91,6 +99,10 @@ struct ModelInfo {
|
||||
const LogString *(*fault_name)(uint8_t index);
|
||||
/// Bit index for each FaultSensor, NO_BIT used where the model does not have that fault bit
|
||||
uint8_t fault_sensor_bits[FAULT_SENSOR_COUNT];
|
||||
/// Number of pins that can report FAULTZ: pin n is selected at 0x61 + n and enabled by bit n of 0x60
|
||||
uint8_t fault_output_pins;
|
||||
/// Name of FAULTZ pin n, for dump_config
|
||||
const LogString *(*fault_output_name)(uint8_t pin);
|
||||
};
|
||||
|
||||
#ifdef USE_TAS58XX_TAS5805M
|
||||
@@ -127,7 +139,10 @@ class TAS58xx : public audio_dac::AudioDac, public PollingComponent, public i2c:
|
||||
void set_enable_pin(GPIOPin *enable_pin) { this->enable_pin_ = enable_pin; }
|
||||
void set_analog_gain(float analog_gain_db) { this->analog_gain_db_ = analog_gain_db; }
|
||||
void set_dac_mode(DacMode dac_mode) { this->dac_mode_ = dac_mode; }
|
||||
/// pin: 0 to 2 for GPIOn on TAS5825M, 0 for ADR on TAS5805M; leave unset for no fault output
|
||||
void set_fault_output(uint8_t pin) { this->fault_output_pin_ = pin; }
|
||||
void set_mixer_mode(MixerMode mixer_mode) { this->mixer_mode_ = mixer_mode; }
|
||||
void set_modulation(Modulation modulation) { this->modulation_ = modulation; }
|
||||
void set_volume_min_db(float volume_min_db) { this->volume_min_db_ = volume_min_db; }
|
||||
void set_volume_max_db(float volume_max_db) { this->volume_max_db_ = volume_max_db; }
|
||||
|
||||
@@ -171,7 +186,9 @@ class TAS58xx : public audio_dac::AudioDac, public PollingComponent, public i2c:
|
||||
float volume_max_db_{24.0f};
|
||||
uint32_t logged_faults_{0}; // Fault bits as last logged, packed like the fault masks
|
||||
DacMode dac_mode_{DAC_MODE_BTL};
|
||||
uint8_t fault_output_pin_{FAULT_OUTPUT_NONE}; // No fault output: the pin keeps its power on state
|
||||
MixerMode mixer_mode_{MIXER_MODE_STEREO};
|
||||
Modulation modulation_{MODULATION_BD_MODE};
|
||||
uint8_t ctrl_state_{0};
|
||||
uint8_t power_state_{0xFF}; // Last POWER_STATE seen by update(), 0xFF until the first read
|
||||
bool mixer_written_{false}; // Mixer written since the last reset
|
||||
|
||||
@@ -13,7 +13,9 @@ from esphome.const import (
|
||||
CONF_ON_RAW_VALUE,
|
||||
CONF_ON_VALUE,
|
||||
CONF_STATE,
|
||||
CONF_TIMEOUT,
|
||||
CONF_TO,
|
||||
CONF_VALUE,
|
||||
DEVICE_CLASS_DATE,
|
||||
DEVICE_CLASS_EMPTY,
|
||||
DEVICE_CLASS_TIMESTAMP,
|
||||
@@ -59,6 +61,18 @@ AppendFilter = text_sensor_ns.class_("AppendFilter", Filter)
|
||||
PrependFilter = text_sensor_ns.class_("PrependFilter", Filter)
|
||||
SubstituteFilter = text_sensor_ns.class_("SubstituteFilter", Filter)
|
||||
MapFilter = text_sensor_ns.class_("MapFilter", Filter)
|
||||
ThrottleFilter = text_sensor_ns.class_("ThrottleFilter", Filter)
|
||||
ThrottleWithPriorityFilter = text_sensor_ns.class_(
|
||||
"ThrottleWithPriorityFilter", ThrottleFilter
|
||||
)
|
||||
TimeoutFilterBase = text_sensor_ns.class_("TimeoutFilterBase", Filter, cg.Component)
|
||||
TimeoutFilterLast = text_sensor_ns.class_("TimeoutFilterLast", TimeoutFilterBase)
|
||||
TimeoutFilterConfigured = text_sensor_ns.class_(
|
||||
"TimeoutFilterConfigured", TimeoutFilterBase
|
||||
)
|
||||
TimeoutThrottleFilter = text_sensor_ns.class_(
|
||||
"TimeoutThrottleFilter", TimeoutFilterLast
|
||||
)
|
||||
Substitution = text_sensor_ns.struct("Substitution")
|
||||
|
||||
|
||||
@@ -128,6 +142,80 @@ async def substitution_filter_to_code(
|
||||
return cg.new_Pvariable(filter_id, _substitution_table(config))
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register(
|
||||
"throttle", ThrottleFilter, cv.positive_time_period_milliseconds
|
||||
)
|
||||
async def throttle_filter_to_code(config: ConfigType, filter_id: ID) -> MockObj:
|
||||
return cg.new_Pvariable(filter_id, config)
|
||||
|
||||
|
||||
THROTTLE_WITH_PRIORITY_SCHEMA = cv.maybe_simple_value(
|
||||
{
|
||||
cv.Required(CONF_TIMEOUT): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_VALUE, default=[]): cv.ensure_list(cv.string),
|
||||
},
|
||||
key=CONF_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register(
|
||||
"throttle_with_priority", ThrottleWithPriorityFilter, THROTTLE_WITH_PRIORITY_SCHEMA
|
||||
)
|
||||
async def throttle_with_priority_filter_to_code(
|
||||
config: ConfigType, filter_id: ID
|
||||
) -> MockObj:
|
||||
if not (values := config[CONF_VALUE]):
|
||||
filter_id = filter_id.copy()
|
||||
filter_id.type = ThrottleFilter
|
||||
return cg.new_Pvariable(filter_id, config[CONF_TIMEOUT])
|
||||
return cg.new_Pvariable(filter_id, config[CONF_TIMEOUT], _priority_table(values))
|
||||
|
||||
|
||||
def _priority_table(values: list[str]) -> MockObj:
|
||||
"""Shared PROGMEM list of priority texts, ended by nullptr; nullptr without any."""
|
||||
if not values:
|
||||
return cg.nullptr
|
||||
return cg.shared_progmem_array(
|
||||
"text_sensor_priorities",
|
||||
cg.const_char_ptr,
|
||||
cg.ArrayInitializer(*values, cg.nullptr),
|
||||
)
|
||||
|
||||
|
||||
def timeout_throttle_filters(priority: str, period_ms: int = 1000) -> list[ConfigType]:
|
||||
"""Default filters for a text entity: resend the last value after a pause, at most one value a period,
|
||||
`priority` at once. Built as one filter, like sensor.TIMEOUT_THROTTLE_FILTERS."""
|
||||
period = cv.TimePeriod(milliseconds=period_ms)
|
||||
return [
|
||||
{"timeout": {CONF_TIMEOUT: period, CONF_VALUE: "last"}},
|
||||
{"throttle_with_priority": {CONF_TIMEOUT: period, CONF_VALUE: [priority]}},
|
||||
]
|
||||
|
||||
|
||||
TIMEOUT_SCHEMA = cv.maybe_simple_value(
|
||||
{
|
||||
cv.Required(CONF_TIMEOUT): cv.positive_time_period_milliseconds,
|
||||
cv.Optional(CONF_VALUE, default="last"): cv.string,
|
||||
},
|
||||
key=CONF_TIMEOUT,
|
||||
)
|
||||
|
||||
|
||||
@FILTER_REGISTRY.register("timeout", TimeoutFilterBase, TIMEOUT_SCHEMA)
|
||||
async def timeout_filter_to_code(config: ConfigType, filter_id: ID) -> MockObj:
|
||||
filter_id = filter_id.copy()
|
||||
args = [config[CONF_TIMEOUT]]
|
||||
# "last" is a keyword, so a timeout cannot send that literal text
|
||||
if (value := config[CONF_VALUE]) == "last":
|
||||
filter_id.type = TimeoutFilterLast
|
||||
else:
|
||||
filter_id.type = TimeoutFilterConfigured
|
||||
args.append(value)
|
||||
var = cg.new_Pvariable(filter_id, *args)
|
||||
await cg.register_component(var, {})
|
||||
return var
|
||||
|
||||
|
||||
validate_device_class = cv.one_of(*DEVICE_CLASSES, lower=True, space="_")
|
||||
|
||||
_TEXT_SENSOR_SCHEMA = (
|
||||
@@ -184,6 +272,32 @@ async def build_filters(config):
|
||||
return await cg.build_registry_list(FILTER_REGISTRY, config)
|
||||
|
||||
|
||||
def _timeout_throttle_pair(first: ConfigType, second: ConfigType) -> tuple | None:
|
||||
"""Period and priority texts of a `timeout` (value `last`) directly followed by a
|
||||
`throttle_with_priority` with the same period, or None."""
|
||||
if (timeout := first.get(CONF_TIMEOUT)) is None or (
|
||||
throttle := second.get("throttle_with_priority")
|
||||
) is None:
|
||||
return None
|
||||
if timeout[CONF_VALUE] != "last" or timeout[CONF_TIMEOUT] != throttle[CONF_TIMEOUT]:
|
||||
return None
|
||||
return timeout[CONF_TIMEOUT], throttle[CONF_VALUE]
|
||||
|
||||
|
||||
def _timeout_throttle_merge(first: ConfigType, second: ConfigType) -> tuple | None:
|
||||
if (pair := _timeout_throttle_pair(first, second)) is None:
|
||||
return None
|
||||
period, values = pair
|
||||
return TimeoutThrottleFilter, [period, _priority_table(values)]
|
||||
|
||||
|
||||
async def _build_chain_filters(config: list[ConfigType]) -> list:
|
||||
"""Like build_filters, but merges a `timeout` + `throttle_with_priority` pair into one filter."""
|
||||
return await cg.build_registry_list_merged(
|
||||
FILTER_REGISTRY, config, _timeout_throttle_merge
|
||||
)
|
||||
|
||||
|
||||
_CALLBACK_AUTOMATIONS = (
|
||||
automation.CallbackAutomation(
|
||||
CONF_ON_VALUE, "add_on_state_callback", [(cg.std_string, "x")]
|
||||
@@ -205,7 +319,7 @@ async def setup_text_sensor_core_(var, config):
|
||||
|
||||
if config.get(CONF_FILTERS): # must exist and not be empty
|
||||
cg.add_define("USE_TEXT_SENSOR_FILTER")
|
||||
filters = await build_filters(config[CONF_FILTERS])
|
||||
filters = await _build_chain_filters(config[CONF_FILTERS])
|
||||
for filter_ in filters:
|
||||
cg.add(var.add_filter(filter_))
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "filter.h"
|
||||
#include "text_sensor.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
@@ -98,6 +99,65 @@ bool MapFilter::new_value(std::string &value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Throttle
|
||||
// True when a value may pass: the period is over, or the value is in the nullptr-ended `prioritized` list
|
||||
static bool throttle_passes(uint32_t &last_input, uint32_t period, const std::string &value,
|
||||
const char *const *prioritized) {
|
||||
const uint32_t now = App.get_loop_component_start_time();
|
||||
bool pass = last_input == 0 || now - last_input >= period;
|
||||
for (const char *const *p = prioritized; !pass && p != nullptr && *p != nullptr; p++)
|
||||
pass = value == *p;
|
||||
if (pass)
|
||||
last_input = now;
|
||||
return pass;
|
||||
}
|
||||
|
||||
bool ThrottleFilter::new_value(std::string &value) {
|
||||
return throttle_passes(this->last_input_, this->min_time_between_inputs_, value, nullptr);
|
||||
}
|
||||
|
||||
bool ThrottleWithPriorityFilter::new_value(std::string &value) {
|
||||
return throttle_passes(this->last_input_, this->min_time_between_inputs_, value, this->prioritized_);
|
||||
}
|
||||
|
||||
// Timeout
|
||||
bool TimeoutFilterBase::new_value(std::string &value) {
|
||||
this->timeout_start_time_ = App.get_loop_component_start_time();
|
||||
this->enable_loop();
|
||||
return true;
|
||||
}
|
||||
|
||||
void TimeoutFilterBase::loop() {
|
||||
if (App.get_loop_component_start_time() - this->timeout_start_time_ < this->time_period_)
|
||||
return;
|
||||
// Before sending, so a callback that publishes to this sensor again re-arms the timeout
|
||||
this->disable_loop();
|
||||
this->send_timeout_value();
|
||||
}
|
||||
|
||||
void TimeoutFilterBase::send_(const char *text, size_t len) {
|
||||
if (this->next_ == nullptr) {
|
||||
this->parent_->internal_send_state_to_frontend(text, len);
|
||||
} else {
|
||||
this->next_->input(std::string(text, len));
|
||||
}
|
||||
}
|
||||
|
||||
bool TimeoutFilterLast::new_value(std::string &value) {
|
||||
this->last_ = value; // reuses last_'s buffer
|
||||
return TimeoutFilterBase::new_value(value);
|
||||
}
|
||||
|
||||
bool TimeoutThrottleFilter::new_value(std::string &value) {
|
||||
TimeoutFilterLast::new_value(value);
|
||||
return throttle_passes(this->last_input_, this->time_period_, value, this->prioritized_);
|
||||
}
|
||||
|
||||
void TimeoutThrottleFilter::send_timeout_value() {
|
||||
if (throttle_passes(this->last_input_, this->time_period_, this->last_, this->prioritized_))
|
||||
this->send_(this->last_.data(), this->last_.size());
|
||||
}
|
||||
|
||||
} // namespace esphome::text_sensor
|
||||
|
||||
#endif // USE_TEXT_SENSOR_FILTER
|
||||
@@ -169,6 +169,82 @@ class MapFilter : public Filter {
|
||||
const Substitution *mappings_;
|
||||
};
|
||||
|
||||
/// Drops a value that comes sooner than `min_time_between_inputs` after the last one let through.
|
||||
class ThrottleFilter : public Filter {
|
||||
public:
|
||||
explicit ThrottleFilter(uint32_t min_time_between_inputs) : min_time_between_inputs_(min_time_between_inputs) {}
|
||||
bool new_value(std::string &value) override;
|
||||
|
||||
protected:
|
||||
uint32_t last_input_{0};
|
||||
uint32_t min_time_between_inputs_;
|
||||
};
|
||||
|
||||
/// Same as ThrottleFilter, but a value in `prioritized` always passes. `prioritized` is a codegen table
|
||||
/// in flash, shared by filters with the same list and ended by nullptr.
|
||||
class ThrottleWithPriorityFilter : public ThrottleFilter {
|
||||
public:
|
||||
ThrottleWithPriorityFilter(uint32_t min_time_between_inputs, const char *const *prioritized)
|
||||
: ThrottleFilter(min_time_between_inputs), prioritized_(prioritized) {}
|
||||
bool new_value(std::string &value) override;
|
||||
|
||||
protected:
|
||||
const char *const *prioritized_;
|
||||
};
|
||||
|
||||
/// Passes every value on and, once none has come for `time_period`, sends one value again. A Component rather than
|
||||
/// a scheduler timeout for the reason given on the sensor's TimeoutFilterBase: it re-arms on every value.
|
||||
class TimeoutFilterBase : public Filter, public Component {
|
||||
public:
|
||||
bool new_value(std::string &value) override;
|
||||
void loop() override;
|
||||
float get_setup_priority() const override { return setup_priority::HARDWARE; }
|
||||
|
||||
protected:
|
||||
explicit TimeoutFilterBase(uint32_t time_period) : time_period_(time_period) { this->disable_loop(); }
|
||||
/// Sends `text`; never moves a stored string on, so it keeps its buffer.
|
||||
void send_(const char *text, size_t len);
|
||||
virtual void send_timeout_value() = 0;
|
||||
|
||||
uint32_t time_period_;
|
||||
uint32_t timeout_start_time_{0};
|
||||
};
|
||||
|
||||
/// Sends the last value again.
|
||||
class TimeoutFilterLast : public TimeoutFilterBase {
|
||||
public:
|
||||
explicit TimeoutFilterLast(uint32_t time_period) : TimeoutFilterBase(time_period) {}
|
||||
bool new_value(std::string &value) override;
|
||||
|
||||
protected:
|
||||
void send_timeout_value() override { this->send_(this->last_.data(), this->last_.size()); }
|
||||
std::string last_;
|
||||
};
|
||||
|
||||
/// Codegen use only: `timeout` (value `last`) followed by `throttle_with_priority` with the same period, as one
|
||||
/// object. Output matches the two filter chain exactly.
|
||||
class TimeoutThrottleFilter : public TimeoutFilterLast {
|
||||
public:
|
||||
TimeoutThrottleFilter(uint32_t time_period, const char *const *prioritized)
|
||||
: TimeoutFilterLast(time_period), prioritized_(prioritized) {}
|
||||
bool new_value(std::string &value) override;
|
||||
|
||||
protected:
|
||||
void send_timeout_value() override;
|
||||
const char *const *prioritized_;
|
||||
uint32_t last_input_{0}; // When the throttle stage last let a value through
|
||||
};
|
||||
|
||||
/// Sends the configured text.
|
||||
class TimeoutFilterConfigured : public TimeoutFilterBase {
|
||||
public:
|
||||
TimeoutFilterConfigured(uint32_t time_period, const char *value) : TimeoutFilterBase(time_period), value_(value) {}
|
||||
|
||||
protected:
|
||||
void send_timeout_value() override { this->send_(this->value_, strlen(this->value_)); }
|
||||
const char *value_;
|
||||
};
|
||||
|
||||
} // namespace esphome::text_sensor
|
||||
|
||||
#endif // USE_TEXT_SENSOR_FILTER
|
||||
@@ -54,10 +54,7 @@ void TT21100Touchscreen::setup() {
|
||||
}
|
||||
|
||||
// Perform reset if necessary
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->setup();
|
||||
this->reset_();
|
||||
}
|
||||
pulse_reset(this->reset_pin_, {.low_ms = 10, .high_after_ms = 10});
|
||||
|
||||
// Update display dimensions if they were updated during display setup
|
||||
if (this->display_ != nullptr) {
|
||||
@@ -122,15 +119,6 @@ void TT21100Touchscreen::update_touches() {
|
||||
}
|
||||
}
|
||||
|
||||
void TT21100Touchscreen::reset_() {
|
||||
if (this->reset_pin_ != nullptr) {
|
||||
this->reset_pin_->digital_write(false);
|
||||
delay(10);
|
||||
this->reset_pin_->digital_write(true);
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
|
||||
void TT21100Touchscreen::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "TT21100 Touchscreen:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
|
||||
@@ -28,8 +28,6 @@ class TT21100Touchscreen final : public Touchscreen, public i2c::I2CDevice {
|
||||
void register_button_listener(TT21100ButtonListener *listener) { this->button_listeners_.push_back(listener); }
|
||||
|
||||
protected:
|
||||
void reset_();
|
||||
|
||||
void update_touches() override;
|
||||
|
||||
InternalGPIOPin *interrupt_pin_;
|
||||
|
||||
@@ -245,6 +245,22 @@ WiFiConfigureAction = wifi_ns.class_(
|
||||
)
|
||||
|
||||
|
||||
# The supplicant parses the bootstrapping key as a DER encoded P-256 private key in hex; these wrap the
|
||||
# 32 byte key the way the ESP-IDF enrollee example does
|
||||
DPP_KEY_DER_PREFIX = "30310201010420"
|
||||
DPP_KEY_DER_SUFFIX = "a00a06082a8648ce3d030107"
|
||||
|
||||
|
||||
def _validate_dpp_private_key(value: object) -> str:
|
||||
"""The key is 32 bytes written as 64 hexadecimal characters."""
|
||||
value = cv.string_strict(value)
|
||||
if len(value) != 64 or any(c not in "0123456789abcdefABCDEF" for c in value):
|
||||
raise cv.Invalid(
|
||||
"private_key must be 32 bytes written as 64 hexadecimal characters"
|
||||
)
|
||||
return value.lower()
|
||||
|
||||
|
||||
def _validate_dpp_device_info(value: object) -> str:
|
||||
"""The supplicant puts the text on a space separated command line and reads it up to the next space."""
|
||||
value = cv.string_strict(value)
|
||||
@@ -322,7 +338,7 @@ EAP_AUTH_SCHEMA = cv.All(
|
||||
# Wi-Fi Easy Connect (DPP) enrollee; the ESP-IDF supplicant supports the QR code method
|
||||
DPP_SCHEMA = cv.Schema(
|
||||
{
|
||||
cv.Optional(CONF_PRIVATE_KEY): cv.sensitive(cv.string_strict),
|
||||
cv.Optional(CONF_PRIVATE_KEY): cv.sensitive(_validate_dpp_private_key),
|
||||
cv.Optional(CONF_DEVICE_INFO): _validate_dpp_device_info,
|
||||
cv.Optional(CONF_CHANNELS, default=[6]): cv.ensure_list(
|
||||
cv.int_range(min=1, max=14)
|
||||
@@ -904,7 +920,7 @@ async def to_code(config):
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_WIFI_DPP_SUPPORT", True)
|
||||
add_idf_sdkconfig_option("CONFIG_ESP_HOSTED_HOST_FEAT_WIFI_EXT_DPP", True)
|
||||
if (key := dpp.get(CONF_PRIVATE_KEY)) is not None:
|
||||
cg.add(var.set_dpp_key(key))
|
||||
cg.add(var.set_dpp_key(f"{DPP_KEY_DER_PREFIX}{key}{DPP_KEY_DER_SUFFIX}"))
|
||||
if (info := dpp.get(CONF_DEVICE_INFO)) is not None:
|
||||
cg.add(var.set_dpp_device_info(info))
|
||||
cg.add(var.set_dpp_channels(",".join(str(c) for c in dpp[CONF_CHANNELS])))
|
||||
|
||||
@@ -2744,8 +2744,13 @@ def url(value):
|
||||
raise Invalid("Expected a file scheme or a URL scheme with host")
|
||||
|
||||
|
||||
def git_ref(value):
|
||||
if re.match(r"[a-zA-Z0-9_./-]+", value) is None:
|
||||
# Characters git never allows in a branch or tag name (git check-ref-format)
|
||||
GIT_REF_PATTERN = r"[^\s~^:?*\[\\]+"
|
||||
|
||||
|
||||
def git_ref(value: typing.Any) -> str:
|
||||
value = string_strict(value)
|
||||
if re.fullmatch(GIT_REF_PATTERN, value) is None:
|
||||
raise Invalid("Not a valid git ref")
|
||||
return value
|
||||
|
||||
@@ -3000,9 +3005,8 @@ def validate_source_shorthand(value):
|
||||
except Invalid:
|
||||
pass
|
||||
# Regex for GitHub repo name with optional branch/tag
|
||||
# Note: git allows other branch/tag names as well, but never seen them used before
|
||||
m = re.match(
|
||||
r"github://(?:([a-zA-Z0-9\-]+)/([a-zA-Z0-9\-\._]+)(?:@([a-zA-Z0-9\-_.\./]+))?|pr#([0-9]+))",
|
||||
m = re.fullmatch(
|
||||
rf"github://(?:([a-zA-Z0-9\-]+)/([a-zA-Z0-9\-\._]+)(?:@({GIT_REF_PATTERN}))?|pr#([0-9]+))",
|
||||
value,
|
||||
)
|
||||
if m is None:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome {
|
||||
@@ -18,4 +19,18 @@ void log_pin(const char *tag, const char *prefix, GPIOPin *pin) {
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace internal {
|
||||
void pulse_reset_ms(GPIOPin *pin, uint32_t high_before_ms, uint32_t low_ms, uint32_t high_after_ms) {
|
||||
if (pin == nullptr)
|
||||
return;
|
||||
pin->setup();
|
||||
const uint32_t waits[] = {high_before_ms, low_ms, high_after_ms};
|
||||
// Level for each step is high, low, high; a zero high_before_ms skips the first step
|
||||
for (size_t i = high_before_ms == 0; i < 3; i++) {
|
||||
pin->digital_write(i != 1);
|
||||
delay(waits[i]);
|
||||
}
|
||||
}
|
||||
} // namespace internal
|
||||
|
||||
} // namespace esphome
|
||||
@@ -144,4 +144,24 @@ void log_pin(const char *tag, const __FlashStringHelper *prefix, GPIOPin *pin);
|
||||
void log_pin(const char *tag, const char *prefix, GPIOPin *pin);
|
||||
#endif
|
||||
|
||||
/// Waveform for pulse_reset(): high, low, then high again. Name the fields at the call site, e.g.
|
||||
/// pulse_reset(this->reset_pin_, {.high_before_ms = 1, .low_ms = 10}).
|
||||
struct ResetPulse {
|
||||
uint32_t high_before_ms{0}; ///< Drive high this long first; skipped when 0
|
||||
uint32_t low_ms{0}; ///< Hold the pin low (in reset) this long
|
||||
uint32_t high_after_ms{0}; ///< Wait this long after releasing the pin
|
||||
};
|
||||
|
||||
namespace internal {
|
||||
/// Out-of-line body of pulse_reset(); call that instead.
|
||||
void pulse_reset_ms(GPIOPin *pin, uint32_t high_before_ms, uint32_t low_ms, uint32_t high_after_ms);
|
||||
} // namespace internal
|
||||
|
||||
/// Set up an active-low reset pin and drive it through \p pulse. Blocks for the whole sequence;
|
||||
/// does nothing when pin is null. Inline so the fields reach pulse_reset_ms() in registers
|
||||
/// (RISC-V would otherwise pass the struct by reference).
|
||||
ESPHOME_ALWAYS_INLINE inline void pulse_reset(GPIOPin *pin, ResetPulse pulse) {
|
||||
internal::pulse_reset_ms(pin, pulse.high_before_ms, pulse.low_ms, pulse.high_after_ms);
|
||||
}
|
||||
|
||||
} // namespace esphome
|
||||
@@ -372,6 +372,31 @@ async def build_registry_list(registry, config):
|
||||
return actions
|
||||
|
||||
|
||||
async def build_registry_list_merged(
|
||||
registry: Registry,
|
||||
config: list[ConfigType],
|
||||
merge: Callable[[ConfigType, ConfigType], tuple[Any, list] | None],
|
||||
) -> list[MockObj]:
|
||||
"""Like build_registry_list, but two neighbouring entries that ``merge`` accepts are built as one Component.
|
||||
|
||||
``merge(first, second)`` returns the merged class and its constructor arguments, or None.
|
||||
"""
|
||||
built = []
|
||||
i = 0
|
||||
while i < len(config):
|
||||
if i + 1 < len(config) and (merged := merge(config[i], config[i + 1])):
|
||||
type_id = config[i][CONF_TYPE_ID].copy()
|
||||
type_id.type, args = merged
|
||||
var = new_Pvariable(type_id, *args)
|
||||
await register_component(var, {})
|
||||
built.append(var)
|
||||
i += 2
|
||||
continue
|
||||
built.append(await build_registry_entry(registry, config[i]))
|
||||
i += 1
|
||||
return built
|
||||
|
||||
|
||||
async def past_safe_mode():
|
||||
if CONF_SAFE_MODE not in CORE.config:
|
||||
return None
|
||||
|
||||
+5
-5
@@ -718,9 +718,9 @@ def _clone_or_update_locked(
|
||||
# compute the same cache key as this one.
|
||||
original_url = url
|
||||
if username is not None and password is not None:
|
||||
url = url.replace(
|
||||
"://", f"://{urllib.parse.quote(username)}:{urllib.parse.quote(password)}@"
|
||||
)
|
||||
user = urllib.parse.quote(username, safe="")
|
||||
token = urllib.parse.quote(password, safe="")
|
||||
url = url.replace("://", f"://{user}:{token}@")
|
||||
|
||||
hash_dir_name = _compute_destination_path(key, domain).name
|
||||
repo_dir = _repo_entry_dir(key, domain, subpath)
|
||||
@@ -1051,8 +1051,8 @@ class GitFile:
|
||||
"""Parse a git shorthand URL into its components."""
|
||||
if not isinstance(shorthand, str):
|
||||
raise ValueError("Git shorthand must be a string")
|
||||
m = re.match(
|
||||
r"(?P<domain>[a-zA-Z0-9\-]+)://(?P<owner>[a-zA-Z0-9\-]+)/(?P<repo>[a-zA-Z0-9\-\._]+)/(?P<filename>[a-zA-Z0-9\-_.\./]+)(?:@(?P<ref>[a-zA-Z0-9\-_.\./]+))?(?:\?(?P<query>[a-zA-Z0-9\-_.\./]+))?",
|
||||
m = re.fullmatch(
|
||||
rf"(?P<domain>[a-zA-Z0-9\-]+)://(?P<owner>[a-zA-Z0-9\-]+)/(?P<repo>[a-zA-Z0-9\-\._]+)/(?P<filename>[a-zA-Z0-9\-_.\./]+)(?:@(?P<ref>{cv.GIT_REF_PATTERN}))?(?:\?(?P<query>[a-zA-Z0-9\-_.\./]+))?",
|
||||
shorthand,
|
||||
)
|
||||
if m is None:
|
||||
|
||||
@@ -2,7 +2,7 @@ dependencies:
|
||||
bblanchon/arduinojson:
|
||||
version: "7.4.3"
|
||||
esphome/dlms_parser:
|
||||
version: 2.2.0
|
||||
version: 2.2.2
|
||||
esphome/esp-audio-libs:
|
||||
version: 4.1.0
|
||||
esphome/esp-micro-speech-features:
|
||||
|
||||
+7
-2
@@ -284,12 +284,17 @@ def _lookup_module(domain: str, exception: bool) -> ComponentManifest | None:
|
||||
_COMPONENT_CACHE[domain] = manif
|
||||
return manif
|
||||
|
||||
module_name = f"esphome.components.{domain}"
|
||||
try:
|
||||
module = importlib.import_module(f"esphome.components.{domain}")
|
||||
module = importlib.import_module(module_name)
|
||||
except ImportError as e:
|
||||
if exception:
|
||||
raise
|
||||
if "No module named" in str(e):
|
||||
if (
|
||||
isinstance(e, ModuleNotFoundError)
|
||||
and e.name is not None
|
||||
and f"{module_name}.".startswith(f"{e.name}.")
|
||||
):
|
||||
_LOGGER.info(
|
||||
"Unable to import component %s: %s", domain, str(e), exc_info=False
|
||||
)
|
||||
|
||||
@@ -1,385 +0,0 @@
|
||||
"""Rewrite the OTA encryption key in place: the `key:` line the loader read
|
||||
it from, or the secrets.yaml line a `!secret` on it points to."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from esphome.components.noise import static_encryption_key
|
||||
from esphome.const import CONF_API, CONF_ENCRYPTION, CONF_KEY
|
||||
from esphome.core import CORE, EsphomeError
|
||||
from esphome.espota2 import CONF_OLD_KEY, esphome_ota_items
|
||||
from esphome.types import ConfigType
|
||||
from esphome.yaml_edit import (
|
||||
LineEdit,
|
||||
editable_file,
|
||||
field_line_re,
|
||||
own_documents,
|
||||
read_text,
|
||||
rewrite,
|
||||
source_line,
|
||||
source_of,
|
||||
)
|
||||
from esphome.yaml_util import secrets_path_for
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_DOMAIN = "ota_key_edit"
|
||||
|
||||
|
||||
@dataclass
|
||||
class KeyEdit(LineEdit):
|
||||
"""A line edit with the secret it holds and the other configs using it."""
|
||||
|
||||
secret: str | None = None
|
||||
shared_with: list[Path] = field(default_factory=list)
|
||||
|
||||
|
||||
def _api_encryption() -> ConfigType:
|
||||
return ((CORE.raw_config or {}).get(CONF_API) or {}).get(CONF_ENCRYPTION) or {}
|
||||
|
||||
|
||||
def _key_blocks(raw: ConfigType, key: str) -> list[ConfigType]:
|
||||
"""The api and esphome ota ``encryption:`` mappings whose key is ``key``."""
|
||||
blocks = [raw.get(CONF_API) or {}, *esphome_ota_items(raw)]
|
||||
found = []
|
||||
for block in blocks:
|
||||
if (node := static_encryption_key(block)) is None or str(node) != key:
|
||||
continue
|
||||
encryption = block[CONF_ENCRYPTION]
|
||||
if source_of(encryption, CONF_KEY) is not None:
|
||||
found.append(encryption)
|
||||
elif hasattr(next(k for k in encryption if k == CONF_KEY), "esp_range"):
|
||||
# Read from a file but not on a line of its own, as with a merge
|
||||
# key; only a key validation added, which has no range at all,
|
||||
# is passed over (a bare ota block takes the api key)
|
||||
raise EsphomeError(
|
||||
f"The '{CONF_KEY}' of an '{CONF_ENCRYPTION}:' block is not on a "
|
||||
"line of its own; edit the key by hand"
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
_INDENT_RE = re.compile(r"\s*")
|
||||
_KEY_FIELD_RE = re.compile(rf"^\s*{CONF_KEY}\s*:")
|
||||
_BARE_BLOCK_RE = re.compile(rf"^\s*{CONF_ENCRYPTION}\s*:\s*(#.*)?$")
|
||||
_YAML_SUFFIXES = (".yaml", ".yml")
|
||||
_INCLUDE_DIR_RE = re.compile(r"!include_dir_\w+\s+(?P<dir>[^\s#]+)")
|
||||
# An include or package file whose path holds a substitution
|
||||
_SUBSTITUTED_INCLUDE_RE = re.compile(
|
||||
r"(?:!include\w*\s+|\bfile:\s*)[\"']?(?P<target>[^\s#\"']*\$[^\s#\"']*)"
|
||||
)
|
||||
|
||||
|
||||
def _secret_ref(name: str = r"[^\s\"']+") -> str:
|
||||
"""`!secret name` as the whole scalar: `!secret ota key` is not `ota`, and
|
||||
a comment needs whitespace before its `#`, so `a#b` is one name."""
|
||||
return rf"!secret\s+(?P<q>[\"']?)(?P<name>{name})(?P=q)(?=\s+#|\s*$)"
|
||||
|
||||
|
||||
def _secret_field_re(name: str) -> re.Pattern[str]:
|
||||
"""``name: !secret <any>``."""
|
||||
return re.compile(rf"^\s*{name}\s*:\s*{_secret_ref()}")
|
||||
|
||||
|
||||
def _secret_use_re(name: str) -> re.Pattern[str]:
|
||||
"""A use of the secret ``name`` anywhere on a line."""
|
||||
return re.compile(_secret_ref(re.escape(name)))
|
||||
|
||||
|
||||
_KEY_SECRET_RE = _secret_field_re(CONF_KEY)
|
||||
_OLD_KEY_SECRET_RE = _secret_field_re(CONF_OLD_KEY)
|
||||
|
||||
|
||||
def _indent(text: str) -> str:
|
||||
return _INDENT_RE.match(text).group()
|
||||
|
||||
|
||||
def _without_comment(text: str) -> str:
|
||||
"""The line up to its comment: a `#` after whitespace that is not inside
|
||||
a quoted scalar, so `!include "shared # ota.yaml"` keeps its name."""
|
||||
quote = ""
|
||||
for i, char in enumerate(text):
|
||||
if quote:
|
||||
if char == quote:
|
||||
quote = ""
|
||||
elif char in "\"'":
|
||||
quote = char
|
||||
elif char == "#" and (i == 0 or text[i - 1].isspace()):
|
||||
return text[:i]
|
||||
return text
|
||||
|
||||
|
||||
def _file_use_re(file_name: str) -> re.Pattern[str]:
|
||||
"""The file name at a path boundary; `wifi_api.yaml` is not `api.yaml`."""
|
||||
return re.compile(rf"(?<![\w.-]){re.escape(file_name)}(?![\w.])")
|
||||
|
||||
|
||||
def _root_indent(lines: list[str]) -> str:
|
||||
"""The indent of the first content line; a root mapping may be indented."""
|
||||
content = (
|
||||
t for t in lines if t.strip() and not t.strip().startswith(("#", "---", "%"))
|
||||
)
|
||||
return next((_indent(t) for t in content), "")
|
||||
|
||||
|
||||
def _config_texts() -> tuple[list[tuple[Path, str]], list[str]]:
|
||||
"""Every yaml file under the config dir with its text, and what could
|
||||
not be read (a symlinked directory is not walked); walked once per run."""
|
||||
if (found := CORE.data.get(_DOMAIN)) is None:
|
||||
found = CORE.data[_DOMAIN] = _walk_config_texts()
|
||||
return found
|
||||
|
||||
|
||||
def _walk_config_texts() -> tuple[list[tuple[Path, str]], list[str]]:
|
||||
data_dir = CORE.data_dir.resolve()
|
||||
found = []
|
||||
skipped: list[str] = []
|
||||
|
||||
def skip(what: object) -> None:
|
||||
skipped.append(str(what))
|
||||
_LOGGER.debug("Skipping %s", what)
|
||||
|
||||
for dirpath, dirnames, filenames in os.walk(
|
||||
CORE.config_dir.resolve(), onerror=skip
|
||||
):
|
||||
for name in list(dirnames):
|
||||
path = Path(dirpath, name)
|
||||
if path == data_dir:
|
||||
dirnames.remove(name)
|
||||
elif path.is_symlink():
|
||||
dirnames.remove(name)
|
||||
skip(f"{path} is a link")
|
||||
for filename in filenames:
|
||||
path = Path(dirpath, filename)
|
||||
if path.suffix not in _YAML_SUFFIXES:
|
||||
continue
|
||||
try:
|
||||
text = read_text(path)
|
||||
except EsphomeError as err:
|
||||
skip(err)
|
||||
continue
|
||||
# Searched, never edited: comments do not count
|
||||
found.append((path, "\n".join(map(_without_comment, text.splitlines()))))
|
||||
return sorted(found), skipped
|
||||
|
||||
|
||||
def with_sharers(edits: list[KeyEdit]) -> list[str]:
|
||||
"""Fill in ``shared_with``: the other configs that use each rewritten
|
||||
line's secret or include, directly or through further includes. Returns
|
||||
what the scan could not follow (unreadable files, directory and
|
||||
substituted includes)."""
|
||||
main = CORE.config_path.resolve()
|
||||
own = own_documents()
|
||||
# This config's own includes stay in: another device may reach a line
|
||||
# through one of them
|
||||
texts, skipped = _config_texts()
|
||||
texts = [(path, text) for path, text in texts if path.resolve() != main]
|
||||
unchecked = [*skipped]
|
||||
for path, text in texts:
|
||||
if match := _INCLUDE_DIR_RE.search(text):
|
||||
unchecked.append(f"{path} includes the directory {match['dir']}")
|
||||
if match := _SUBSTITUTED_INCLUDE_RE.search(text):
|
||||
unchecked.append(
|
||||
f"{path} includes {match['target']} through a substitution"
|
||||
)
|
||||
for edit in edits:
|
||||
if edit.insert_after and edit.secret:
|
||||
continue # a new secrets line has no users yet
|
||||
ref = (
|
||||
_secret_use_re(edit.secret) if edit.secret else _file_use_re(edit.path.name)
|
||||
)
|
||||
users = {path for path, text in texts if ref.search(text)}
|
||||
frontier = users
|
||||
while frontier:
|
||||
frontier = {
|
||||
path
|
||||
for name in {p.name for p in frontier}
|
||||
for path, text in texts
|
||||
if path not in users and _file_use_re(name).search(text)
|
||||
}
|
||||
users |= frontier
|
||||
edit.shared_with = sorted(p for p in users if p.resolve() not in own)
|
||||
return unchecked
|
||||
|
||||
|
||||
def _secret_file(doc: Path) -> Path:
|
||||
return editable_file(secrets_path_for(doc))
|
||||
|
||||
|
||||
def _secret_line(
|
||||
secrets_path: Path, name: str, value: str | None = None
|
||||
) -> tuple[int, re.Match[str]] | None:
|
||||
"""The root level ``name:`` line, None when absent."""
|
||||
lines = read_text(secrets_path).splitlines()
|
||||
line_re = field_line_re(name, value, re.escape(_root_indent(lines)))
|
||||
return next(
|
||||
((i, m) for i, text in enumerate(lines) if (m := line_re.match(text))), None
|
||||
)
|
||||
|
||||
|
||||
def _secret_rewrite(
|
||||
secrets_path: Path, name: str, value: str, expect: str | None = None
|
||||
) -> KeyEdit | None:
|
||||
"""Set the root level ``name:`` line to ``value``; None when it is not a
|
||||
plain scalar holding ``expect``."""
|
||||
if (hit := _secret_line(secrets_path, name, expect)) is None:
|
||||
return None
|
||||
i, m = hit
|
||||
return KeyEdit(secrets_path, i, m.string, rewrite(m, value), secret=name)
|
||||
|
||||
|
||||
def _secret_insert(secrets_path: Path, after: str, name: str, value: str) -> KeyEdit:
|
||||
"""Add ``name: value`` under the root level ``after`` line."""
|
||||
if (hit := _secret_line(secrets_path, after)) is None:
|
||||
raise EsphomeError(
|
||||
f"No plain '{after}:' line in {secrets_path}; edit it by hand"
|
||||
)
|
||||
i, m = hit
|
||||
return KeyEdit(
|
||||
secrets_path,
|
||||
i,
|
||||
m.string,
|
||||
f'{_indent(m.string)}{name}: "{value}"',
|
||||
insert_after=True,
|
||||
secret=name,
|
||||
)
|
||||
|
||||
|
||||
def locate_key_edits(old_key: str, new_key: str) -> list[KeyEdit]:
|
||||
"""The edits that replace the current key; refuses a substitution, flow
|
||||
mapping or remote package."""
|
||||
literal_re = field_line_re(CONF_KEY, old_key)
|
||||
blocks = _key_blocks(CORE.raw_config or {}, old_key)
|
||||
if not blocks:
|
||||
raise EsphomeError("The current key was not found on a line of the yaml")
|
||||
edits: list[KeyEdit] = []
|
||||
key_lines: set[tuple[Path, int]] = set()
|
||||
for block in blocks:
|
||||
doc, line_no, text = source_line(block, CONF_KEY)
|
||||
key_lines.add((doc.resolve(), line_no))
|
||||
if match := _KEY_SECRET_RE.match(text):
|
||||
name, secrets_path = match["name"], _secret_file(doc)
|
||||
edit = _secret_rewrite(secrets_path, name, new_key, expect=old_key)
|
||||
if edit is None:
|
||||
raise EsphomeError(
|
||||
f"No '{name}:' line with the current key in {secrets_path}"
|
||||
)
|
||||
elif match := literal_re.match(text):
|
||||
edit = KeyEdit(doc, line_no, text, rewrite(match, new_key))
|
||||
else:
|
||||
raise EsphomeError(
|
||||
f"{doc}:{line_no + 1} does not hold the key as a plain value or "
|
||||
"a !secret; edit the key by hand"
|
||||
)
|
||||
# The api and ota blocks may share one !secret line
|
||||
if edit not in edits:
|
||||
edits.append(edit)
|
||||
for edit in edits:
|
||||
if edit.secret:
|
||||
_refuse_other_own_uses(edit.secret, key_lines)
|
||||
return edits
|
||||
|
||||
|
||||
def _refuse_other_own_uses(name: str, allowed: set[tuple[Path, int]]) -> None:
|
||||
"""The secret may only feed the ``allowed`` lines; a wifi password on it
|
||||
would change too."""
|
||||
ref = _secret_use_re(name)
|
||||
for doc in own_documents():
|
||||
for i, text in enumerate(read_text(doc).splitlines()):
|
||||
if ref.search(_without_comment(text)) and (doc, i) not in allowed:
|
||||
raise EsphomeError(
|
||||
f"'{name}' is also used at {doc}:{i + 1}; a rotation would "
|
||||
"change that value too, edit the key by hand"
|
||||
)
|
||||
|
||||
|
||||
def _secret_name(block: ConfigType) -> str | None:
|
||||
"""The secrets file name a ``key: !secret <name>`` line of ``block`` holds."""
|
||||
if source_of(block, CONF_KEY) is None:
|
||||
return None
|
||||
match = _KEY_SECRET_RE.match(source_line(block, CONF_KEY)[2])
|
||||
return match["name"] if match else None
|
||||
|
||||
|
||||
def old_key_edit(old_key: str) -> list[KeyEdit]:
|
||||
"""Set ``old_key:`` on the esphome ota block, rewriting or adding it. A
|
||||
key from secrets.yaml stays there as ``<name>_old``. Of several entries
|
||||
the one with its own old_key or key line gets it."""
|
||||
items = [
|
||||
(item, item[CONF_ENCRYPTION] or {})
|
||||
for item in esphome_ota_items(CORE.raw_config or {})
|
||||
if CONF_ENCRYPTION in item
|
||||
]
|
||||
if not items:
|
||||
raise EsphomeError("The esphome OTA platform has no 'encryption:' block")
|
||||
item, encryption = next(
|
||||
(
|
||||
pair
|
||||
for name in (CONF_OLD_KEY, CONF_KEY)
|
||||
for pair in items
|
||||
if source_of(pair[1], name) is not None
|
||||
),
|
||||
items[0],
|
||||
)
|
||||
if (existing := encryption.get(CONF_OLD_KEY)) is not None:
|
||||
doc, line_no, text = source_line(encryption, CONF_OLD_KEY)
|
||||
if match := _OLD_KEY_SECRET_RE.match(text):
|
||||
name, secrets_path = match["name"], _secret_file(doc)
|
||||
if (edit := _secret_rewrite(secrets_path, name, old_key)) is None:
|
||||
raise EsphomeError(
|
||||
f"No plain '{name}:' line in {secrets_path}; edit it by hand"
|
||||
)
|
||||
_refuse_other_own_uses(name, {(doc.resolve(), line_no)})
|
||||
return [edit]
|
||||
match = field_line_re(CONF_OLD_KEY, str(existing)).match(text)
|
||||
if match is None:
|
||||
raise EsphomeError(
|
||||
f"{doc}:{line_no + 1} does not hold '{CONF_OLD_KEY}' as a plain "
|
||||
"value; edit it by hand"
|
||||
)
|
||||
return [KeyEdit(doc, line_no, text, rewrite(match, old_key))]
|
||||
# Indent from the block's own key line, else one level under `encryption:`
|
||||
if source_of(encryption, CONF_KEY) is not None:
|
||||
mapping, anchor, anchor_re, step = encryption, CONF_KEY, _KEY_FIELD_RE, ""
|
||||
else:
|
||||
mapping, anchor, anchor_re, step = item, CONF_ENCRYPTION, _BARE_BLOCK_RE, " "
|
||||
doc, line_no, text = source_line(mapping, anchor)
|
||||
if not anchor_re.match(text):
|
||||
raise EsphomeError(
|
||||
f"{doc}:{line_no + 1} does not hold '{anchor}:' as a block line; "
|
||||
"edit it by hand"
|
||||
)
|
||||
# The block's own key line decides; a bare block takes after the api key
|
||||
keyed = encryption if mapping is encryption else _api_encryption()
|
||||
if (secret := _secret_name(keyed)) is None:
|
||||
rendered = f'{CONF_OLD_KEY}: "{old_key}"'
|
||||
extra = []
|
||||
else:
|
||||
rendered = f"{CONF_OLD_KEY}: !secret {secret}_old"
|
||||
secrets_path = _secret_file(doc) # the file that gets old_key
|
||||
# An existing `<secret>_old` line is reused only when nothing uses it
|
||||
if (
|
||||
kept := _secret_rewrite(secrets_path, f"{secret}_old", old_key)
|
||||
) is not None:
|
||||
ref = _secret_use_re(f"{secret}_old")
|
||||
texts, skipped = _config_texts()
|
||||
if skipped: # an unread file might use the line
|
||||
raise EsphomeError(
|
||||
"Could not read every configuration to check the secret: "
|
||||
+ skipped[0]
|
||||
)
|
||||
if users := [p for p, t in texts if ref.search(t)]:
|
||||
raise EsphomeError(
|
||||
f"'{secret}_old:' in {secrets_path} is used by "
|
||||
+ ", ".join(str(p) for p in users)
|
||||
+ f"; rename it or add '{CONF_OLD_KEY}' by hand"
|
||||
)
|
||||
extra = [kept or _secret_insert(secrets_path, secret, f"{secret}_old", old_key)]
|
||||
edit = KeyEdit(
|
||||
doc, line_no, text, f"{_indent(text)}{step}{rendered}", insert_after=True
|
||||
)
|
||||
return [edit, *extra]
|
||||
@@ -26,17 +26,20 @@ from esphome.const import (
|
||||
PLATFORM_BK72XX,
|
||||
PLATFORM_ESP32,
|
||||
PLATFORM_ESP8266,
|
||||
PLATFORM_LN882X,
|
||||
PLATFORM_NRF52,
|
||||
PLATFORM_RP2,
|
||||
PLATFORM_RTL87XX,
|
||||
Platform,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Hooks whose loss only degrades diagnostics; skipping one of these is
|
||||
# logged at debug, while skipping a hook that changes what the CLI does
|
||||
# (upload method, log transport) warns. A new hook is loud by default.
|
||||
COSMETIC_HOOKS: Final = frozenset({"process_stacktrace"})
|
||||
# Hooks whose loss only degrades diagnostics or upload size; skipping one
|
||||
# of these is logged at debug, while skipping a hook that changes what the
|
||||
# CLI does (upload method, log transport) warns. A new hook is loud by
|
||||
# default.
|
||||
COSMETIC_HOOKS: Final = frozenset({"process_stacktrace", "ota_image"})
|
||||
|
||||
# Platforms whose firmware prints the crash handler report share one gate.
|
||||
_CRASH_HANDLER_GATE = r"0x[0-9a-fA-F]{3,}\b|CRASH DETECTED ON PREVIOUS BOOT"
|
||||
@@ -71,6 +74,8 @@ PLATFORM_HOOKS: Final[dict[str, frozenset[str]]] = {
|
||||
"show_logs": frozenset({PLATFORM_NRF52}),
|
||||
"upload_program": frozenset({PLATFORM_NRF52}),
|
||||
"process_stacktrace": frozenset(STACKTRACE_GATES),
|
||||
# The file an app update sends, when it is not the build output itself
|
||||
"ota_image": frozenset({PLATFORM_BK72XX, PLATFORM_LN882X, PLATFORM_RTL87XX}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
+3
-15
@@ -966,7 +966,9 @@ class ESPHomeLoaderMixin:
|
||||
if self.name == CORE.config_path:
|
||||
raise e
|
||||
try:
|
||||
secrets = self.yaml_loader(CORE.config_path.parent / SECRET_YAML)
|
||||
main_config_dir = CORE.config_path.parent
|
||||
main_secret_yml = main_config_dir / SECRET_YAML
|
||||
secrets = self.yaml_loader(main_secret_yml)
|
||||
except EsphomeError as er:
|
||||
raise EsphomeError(f"{e}\n{er}") from er
|
||||
|
||||
@@ -1355,20 +1357,6 @@ def find_files(directory: Path, pattern: str) -> Iterator[Path]:
|
||||
yield filename
|
||||
|
||||
|
||||
def secrets_path_for(document: Path) -> Path:
|
||||
"""The secrets.yaml a ``!secret`` in ``document`` resolves against: the
|
||||
one beside the document when it loads, else the main config's, the
|
||||
way construct_secret falls back."""
|
||||
beside = document.parent / SECRET_YAML
|
||||
if document == CORE.config_path:
|
||||
return beside
|
||||
try:
|
||||
load_yaml(beside, clear_secrets=False, track_document_range=False)
|
||||
except EsphomeError:
|
||||
return CORE.config_path.parent / SECRET_YAML
|
||||
return beside
|
||||
|
||||
|
||||
def is_secret(value):
|
||||
try:
|
||||
return _SECRET_VALUES[str(value)]
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ build_unflags =
|
||||
; esp32 envs (which would double-include them).
|
||||
[common:idf-component-libs]
|
||||
lib_deps =
|
||||
esphome/dlms_parser@2.2.0 ; dlms_meter
|
||||
esphome/dlms_parser@2.2.2 ; dlms_meter
|
||||
bblanchon/ArduinoJson@7.4.3 ; json
|
||||
lvgl/lvgl@9.6.0 ; lvgl
|
||||
|
||||
|
||||
@@ -138,3 +138,26 @@ def test_task_log_buffer_size_unaligned_allowed_on_libretiny(
|
||||
) -> None:
|
||||
set_core_config(PlatformFramework.BK72XX_ARDUINO)
|
||||
assert validate_task_log_buffer_alignment(641) == 641
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "log_v2"),
|
||||
[
|
||||
pytest.param("test_logger_idf6_esp_idf.yaml", True, id="native"),
|
||||
pytest.param("test_logger_idf6_platformio.yaml", False, id="platformio"),
|
||||
],
|
||||
)
|
||||
def test_log_v2_only_on_native_toolchain(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
config: str,
|
||||
log_v2: bool,
|
||||
) -> None:
|
||||
"""PlatformIO links the bootloader with the app's build flags, so the wrap has no target there."""
|
||||
from esphome.components.esp32 import KEY_ESP32, KEY_SDKCONFIG_OPTIONS
|
||||
|
||||
generate_main(f"tests/component_tests/logger/{config}")
|
||||
|
||||
assert ("-Wl,--wrap=esp_log_format" in CORE.build_flags) is log_v2
|
||||
assert ("USE_ESP32_LOG_V2" in {d.name for d in CORE.defines}) is log_v2
|
||||
sdkconfig = CORE.data[KEY_ESP32][KEY_SDKCONFIG_OPTIONS]
|
||||
assert ("CONFIG_LOG_VERSION_2" in sdkconfig) is log_v2
|
||||
@@ -0,0 +1,11 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
toolchain: esp-idf
|
||||
framework:
|
||||
type: esp-idf
|
||||
version: 6.1.0
|
||||
|
||||
logger:
|
||||
@@ -0,0 +1,12 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
toolchain: platformio
|
||||
framework:
|
||||
type: esp-idf
|
||||
version: 6.1.0
|
||||
platform_version: 61.4.0-RC1
|
||||
|
||||
logger:
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Tests that the TAS58xx fault_output and modulation defaults keep the existing behaviour."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_tas58xx_defaults_keep_the_fault_pin_and_bd_modulation(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
) -> None:
|
||||
"""Without fault_output or modulation each model keeps its usual fault pin and BD modulation."""
|
||||
main_cpp = generate_main(
|
||||
"tests/component_tests/tas58xx/test_tas58xx_fault_output_modulation.yaml"
|
||||
)
|
||||
|
||||
assert "amp_5805_default->set_fault_output(0);" in main_cpp
|
||||
assert "amp_5825_default->set_fault_output(1);" in main_cpp
|
||||
for amp in ("amp_5805_default", "amp_5825_default", "amp_5805_none"):
|
||||
assert f"{amp}->set_modulation(tas58xx::MODULATION_BD_MODE);" in main_cpp
|
||||
|
||||
|
||||
def test_tas58xx_fault_output_none_leaves_the_pin_alone(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
) -> None:
|
||||
"""fault_output: none does not configure a fault pin."""
|
||||
main_cpp = generate_main(
|
||||
"tests/component_tests/tas58xx/test_tas58xx_fault_output_modulation.yaml"
|
||||
)
|
||||
|
||||
assert "amp_5805_none->set_fault_output(" not in main_cpp
|
||||
@@ -0,0 +1,26 @@
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
|
||||
i2c:
|
||||
id: i2c_bus
|
||||
sda: 21
|
||||
scl: 22
|
||||
|
||||
audio_dac:
|
||||
- platform: tas58xx
|
||||
model: tas5805m
|
||||
id: amp_5805_default
|
||||
ignore_enable_pin_warning: true
|
||||
- platform: tas58xx
|
||||
model: tas5825m
|
||||
id: amp_5825_default
|
||||
ignore_enable_pin_warning: true
|
||||
- platform: tas58xx
|
||||
model: tas5805m
|
||||
id: amp_5805_none
|
||||
address: 0x2C
|
||||
ignore_enable_pin_warning: true
|
||||
fault_output: none
|
||||
@@ -100,3 +100,43 @@ def test_substitution_table_names_avoid_user_ids(
|
||||
assert len(tables) == 2
|
||||
assert "text_sensor_substitutions" not in tables
|
||||
assert "text_sensor_mapfilter_id_table" not in tables
|
||||
|
||||
|
||||
def test_throttle_and_timeout_filters(generate_main: Callable[[str], str]) -> None:
|
||||
"""Priority values go in a PROGMEM table ended by nullptr; no priority is a plain throttle."""
|
||||
main_cpp = generate_main(
|
||||
"tests/component_tests/text_sensor/test_text_sensor_throttle_timeout.yaml"
|
||||
)
|
||||
|
||||
table = re.search(
|
||||
r'static constexpr const char \* (\w+)\[\] PROGMEM = \{"NA", nullptr\}',
|
||||
main_cpp,
|
||||
)
|
||||
assert table is not None
|
||||
# timeout (last) then throttle_with_priority with the same period merge into one filter
|
||||
assert f"text_sensor::TimeoutThrottleFilter(1000, {table.group(1)})" in main_cpp
|
||||
alone = re.search(
|
||||
r'static constexpr const char \* (\w+)\[\] PROGMEM = \{"Off", "NA", nullptr\}',
|
||||
main_cpp,
|
||||
)
|
||||
assert alone is not None
|
||||
assert f"text_sensor::ThrottleWithPriorityFilter(300, {alone.group(1)})" in main_cpp
|
||||
assert "text_sensor::ThrottleFilter(500)" in main_cpp
|
||||
assert "text_sensor::TimeoutThrottleFilter(2000, nullptr)" in main_cpp
|
||||
assert 'text_sensor::TimeoutFilterConfigured(30000, "Offline")' in main_cpp
|
||||
|
||||
|
||||
def test_timeout_throttle_filters_default_merges() -> None:
|
||||
"""The validated default is a pair the chain builder merges into one filter."""
|
||||
from esphome.components.text_sensor import (
|
||||
_timeout_throttle_pair,
|
||||
timeout_throttle_filters,
|
||||
validate_filters,
|
||||
)
|
||||
|
||||
first, second = validate_filters(timeout_throttle_filters("NA"))
|
||||
pair = _timeout_throttle_pair(first, second)
|
||||
assert pair is not None
|
||||
period, values = pair
|
||||
assert period.total_milliseconds == 1000
|
||||
assert values == ["NA"]
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp8266:
|
||||
board: d1_mini_lite
|
||||
|
||||
text_sensor:
|
||||
- platform: template
|
||||
id: ts_position
|
||||
filters:
|
||||
- timeout: 1s
|
||||
- throttle_with_priority:
|
||||
timeout: 1s
|
||||
value: NA
|
||||
- platform: template
|
||||
id: ts_plain
|
||||
filters:
|
||||
- throttle_with_priority: 500ms
|
||||
- timeout:
|
||||
timeout: 30s
|
||||
value: Offline
|
||||
- platform: template
|
||||
id: ts_merged_plain
|
||||
filters:
|
||||
- timeout: 2s
|
||||
- throttle_with_priority: 2s
|
||||
- platform: template
|
||||
id: ts_priority_alone
|
||||
filters:
|
||||
- throttle_with_priority:
|
||||
timeout: 300ms
|
||||
value:
|
||||
- "Off"
|
||||
- NA
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
esphome:
|
||||
name: test
|
||||
|
||||
esp32:
|
||||
board: esp32dev
|
||||
framework:
|
||||
type: esp-idf
|
||||
|
||||
wifi:
|
||||
dpp:
|
||||
private_key: 00112233445566778899AABBCCDDEEFF00112233445566778899aabbccddeeff
|
||||
@@ -0,0 +1,42 @@
|
||||
"""The DPP bootstrapping key is given as 32 raw bytes in hex and handed to the supplicant DER encoded."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components import wifi
|
||||
import esphome.config_validation as cv
|
||||
|
||||
RAW_KEY = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
RAW_KEY[:-2],
|
||||
RAW_KEY + "00",
|
||||
"zz" + RAW_KEY[2:],
|
||||
wifi.DPP_KEY_DER_PREFIX + RAW_KEY + wifi.DPP_KEY_DER_SUFFIX,
|
||||
],
|
||||
)
|
||||
def test_key_must_be_64_hex_digits(value: str) -> None:
|
||||
with pytest.raises(cv.Invalid, match="64 hexadecimal characters"):
|
||||
wifi._validate_dpp_private_key(value)
|
||||
|
||||
|
||||
def test_key_is_lower_cased() -> None:
|
||||
assert wifi._validate_dpp_private_key(RAW_KEY.upper()) == RAW_KEY
|
||||
|
||||
|
||||
def test_generated_key_is_der_encoded(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
"""The ESP-IDF supplicant expects the P-256 DER header around the raw key."""
|
||||
main_cpp = generate_main(component_config_path("dpp_key.yaml"))
|
||||
|
||||
assert (
|
||||
f'set_dpp_key("{wifi.DPP_KEY_DER_PREFIX}{RAW_KEY}{wifi.DPP_KEY_DER_SUFFIX}")'
|
||||
in main_cpp
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::core::testing {
|
||||
|
||||
class RecordingPin : public GPIOPin {
|
||||
public:
|
||||
void setup() override { this->events += 'S'; }
|
||||
void pin_mode(gpio::Flags /*flags*/) override {}
|
||||
gpio::Flags get_flags() const override { return gpio::FLAG_OUTPUT; }
|
||||
bool digital_read() override { return false; }
|
||||
void digital_write(bool value) override {
|
||||
this->events += value ? 'H' : 'L';
|
||||
this->write_ms.push_back(millis());
|
||||
}
|
||||
|
||||
std::string events;
|
||||
std::vector<uint32_t> write_ms;
|
||||
};
|
||||
|
||||
TEST(PulseReset, NullPinIsIgnored) { pulse_reset(nullptr, {.low_ms = 1}); }
|
||||
|
||||
TEST(PulseReset, LowThenHigh) {
|
||||
RecordingPin pin;
|
||||
pulse_reset(&pin, {.low_ms = 1});
|
||||
EXPECT_EQ(pin.events, "SLH");
|
||||
}
|
||||
|
||||
TEST(PulseReset, PreHighDrivesHighFirst) {
|
||||
RecordingPin pin;
|
||||
pulse_reset(&pin, {.high_before_ms = 1, .low_ms = 1, .high_after_ms = 1});
|
||||
EXPECT_EQ(pin.events, "SHLH");
|
||||
}
|
||||
|
||||
// Distinct waits, so dropping or swapping one shows up; only lower bounds, a busy host can run long
|
||||
TEST(PulseReset, HoldsEachLevelForItsTime) {
|
||||
RecordingPin pin;
|
||||
pulse_reset(&pin, {.high_before_ms = 10, .low_ms = 20, .high_after_ms = 30});
|
||||
const uint32_t end = millis();
|
||||
ASSERT_EQ(pin.events, "SHLH");
|
||||
EXPECT_GE(pin.write_ms[1] - pin.write_ms[0], 10u);
|
||||
EXPECT_GE(pin.write_ms[2] - pin.write_ms[1], 20u);
|
||||
EXPECT_GE(end - pin.write_ms[2], 30u);
|
||||
}
|
||||
|
||||
} // namespace esphome::core::testing
|
||||
@@ -0,0 +1,14 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# One empty config entry so to_code runs and sets the define that keeps
|
||||
# core/line_reader.cpp in the test build.
|
||||
manifest.multi_conf = False
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
cg.add_define("USE_LINE_READER")
|
||||
|
||||
manifest.to_code = to_code
|
||||
@@ -17,7 +17,7 @@ class TestMicrophone : public Microphone {
|
||||
void start() override {}
|
||||
void stop() override {}
|
||||
|
||||
void publish(std::span<const uint8_t> data, const audio::AudioStreamInfo &stream_info, int64_t capture_time_us) {
|
||||
void publish(std::span<uint8_t> data, const audio::AudioStreamInfo &stream_info, int64_t capture_time_us) {
|
||||
this->publish_audio_(data, stream_info, capture_time_us);
|
||||
}
|
||||
bool has_callbacks() const { return this->has_data_callbacks_(); }
|
||||
@@ -56,20 +56,24 @@ TEST(MicrophoneDataCallbacks, CallbackGetsDataFormatAndCaptureTime) {
|
||||
});
|
||||
EXPECT_TRUE(mic.has_callbacks());
|
||||
|
||||
mic.publish(SAMPLES, STEREO_48K, 123456);
|
||||
std::vector<uint8_t> buffer = SAMPLES;
|
||||
mic.publish(buffer, STEREO_48K, 123456);
|
||||
EXPECT_EQ(data, SAMPLES);
|
||||
EXPECT_EQ(stream_info, STEREO_48K);
|
||||
EXPECT_EQ(capture_time_us, 123456);
|
||||
}
|
||||
|
||||
TEST(MicrophoneDataCallbacks, MutedCallbackGetsZeros) {
|
||||
TEST(MicrophoneDataCallbacks, MuteZeroesTheBufferInPlace) {
|
||||
TestMicrophone mic;
|
||||
std::vector<uint8_t> data;
|
||||
mic.add_data_callback([&](const AudioCapture &capture) { data.assign(capture.data.begin(), capture.data.end()); });
|
||||
|
||||
mic.set_mute_state(true);
|
||||
mic.publish(SAMPLES, STEREO_48K, 0);
|
||||
EXPECT_EQ(data, std::vector<uint8_t>(SAMPLES.size(), 0));
|
||||
std::vector<uint8_t> buffer = SAMPLES;
|
||||
mic.publish(buffer, STEREO_48K, 0);
|
||||
const std::vector<uint8_t> zeros(SAMPLES.size(), 0);
|
||||
EXPECT_EQ(data, zeros);
|
||||
EXPECT_EQ(buffer, zeros);
|
||||
}
|
||||
|
||||
TEST(MicrophoneDataCallbacks, DataTriggerPassesACopy) {
|
||||
@@ -115,4 +119,17 @@ TEST(MicrophoneDataCallbacks, DeprecatedCallUsesMicrophoneFormat) {
|
||||
EXPECT_EQ(capture_time_us, 0);
|
||||
}
|
||||
|
||||
// Remove in 2027.5.0 with the deprecated DataCallbackManager::call(data)
|
||||
TEST(MicrophoneDataCallbacks, DeprecatedCallDeliversZerosWhileMuted) {
|
||||
TestMicrophone mic;
|
||||
std::vector<uint8_t> data;
|
||||
mic.add_data_callback([&](const AudioCapture &capture) { data.assign(capture.data.begin(), capture.data.end()); });
|
||||
|
||||
mic.set_mute_state(true);
|
||||
const std::vector<uint8_t> buffer = SAMPLES;
|
||||
mic.publish_deprecated(buffer);
|
||||
EXPECT_EQ(data, std::vector<uint8_t>(SAMPLES.size(), 0));
|
||||
EXPECT_EQ(buffer, SAMPLES);
|
||||
}
|
||||
|
||||
} // namespace esphome::microphone::testing
|
||||
@@ -7,7 +7,9 @@ audio_dac:
|
||||
enable_pin: GPIO12
|
||||
analog_gain: -15.5dB
|
||||
dac_mode: btl
|
||||
fault_output: adr
|
||||
mixer_mode: stereo
|
||||
modulation: 1SPW_MODE
|
||||
volume_min_db: -60dB
|
||||
volume_max_db: 0dB
|
||||
update_interval: 1s
|
||||
|
||||
@@ -9,3 +9,4 @@ audio_dac:
|
||||
dac_mode: PBTL
|
||||
mixer_mode: mono
|
||||
analog_gain: -3.5dB
|
||||
fault_output: none
|
||||
@@ -0,0 +1,11 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
async def to_code_testing(config: ConfigType) -> None:
|
||||
# filter.cpp only compiles with the define the real to_code emits for configured filters
|
||||
cg.add_define("USE_TEXT_SENSOR_FILTER")
|
||||
|
||||
manifest.to_code = to_code_testing
|
||||
@@ -30,6 +30,29 @@ text_sensor:
|
||||
- substitute:
|
||||
- BAR -> baz
|
||||
|
||||
- platform: template
|
||||
name: "Test Throttle"
|
||||
id: test_throttle
|
||||
filters:
|
||||
- throttle: 1s
|
||||
|
||||
- platform: template
|
||||
name: "Test Throttle With Priority"
|
||||
id: test_throttle_with_priority
|
||||
filters:
|
||||
- timeout: 1s
|
||||
- throttle_with_priority:
|
||||
timeout: 1s
|
||||
value: NA
|
||||
|
||||
- platform: template
|
||||
name: "Test Timeout Value"
|
||||
id: test_timeout_value
|
||||
filters:
|
||||
- timeout:
|
||||
timeout: 30s
|
||||
value: Offline
|
||||
|
||||
- platform: template
|
||||
name: "Test Map Single"
|
||||
id: test_map_single
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/text_sensor/filter.h"
|
||||
#include "esphome/components/text_sensor/text_sensor.h"
|
||||
#include "esphome/core/application.h"
|
||||
|
||||
namespace esphome::text_sensor::testing {
|
||||
|
||||
class TextFilterTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
this->sensor_.add_on_state_callback([this](const std::string &state) { this->seen_.push_back(state); });
|
||||
}
|
||||
void publish_at(uint32_t now, const char *value) {
|
||||
LoopBlockingGuard guard{nullptr, nullptr, now};
|
||||
this->sensor_.publish_state(value);
|
||||
}
|
||||
static void loop_at(Component &filter, uint32_t now) {
|
||||
LoopBlockingGuard guard{nullptr, nullptr, now};
|
||||
filter.loop();
|
||||
}
|
||||
|
||||
TextSensor sensor_;
|
||||
std::vector<std::string> seen_;
|
||||
};
|
||||
|
||||
static constexpr const char *PRIORITIZED[] = {"NA", nullptr};
|
||||
|
||||
TEST_F(TextFilterTest, ThrottleDropsValuesInsideThePeriod) {
|
||||
ThrottleFilter throttle(1000);
|
||||
this->sensor_.add_filter(&throttle);
|
||||
this->publish_at(1000, "a");
|
||||
this->publish_at(1500, "b");
|
||||
this->publish_at(2000, "c");
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "c"}));
|
||||
}
|
||||
|
||||
TEST_F(TextFilterTest, PrioritizedValuePassesAtOnce) {
|
||||
ThrottleWithPriorityFilter throttle(1000, PRIORITIZED);
|
||||
this->sensor_.add_filter(&throttle);
|
||||
this->publish_at(1000, "a");
|
||||
this->publish_at(1100, "NA");
|
||||
this->publish_at(1200, "b");
|
||||
this->publish_at(2100, "c");
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "NA", "c"}));
|
||||
}
|
||||
|
||||
TEST_F(TextFilterTest, TimeoutRearmsOnEachValueAndFiresOnce) {
|
||||
TimeoutFilterLast timeout(1000);
|
||||
this->sensor_.add_filter(&timeout);
|
||||
this->publish_at(1000, "a");
|
||||
this->publish_at(1800, "b");
|
||||
loop_at(timeout, 2500);
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "b"}));
|
||||
EXPECT_FALSE(timeout.is_idle());
|
||||
loop_at(timeout, 2800);
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "b", "b"}));
|
||||
EXPECT_TRUE(timeout.is_idle());
|
||||
}
|
||||
|
||||
TEST_F(TextFilterTest, TimeoutSendsTheConfiguredValue) {
|
||||
TimeoutFilterConfigured timeout(1000, "Offline");
|
||||
this->sensor_.add_filter(&timeout);
|
||||
this->publish_at(1000, "a");
|
||||
loop_at(timeout, 2000);
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "Offline"}));
|
||||
}
|
||||
|
||||
// Feeds the same values to the timeout + throttle chain and to the merged filter
|
||||
static std::vector<std::string> run_sequence(std::initializer_list<Filter *> filters, Component &timeout) {
|
||||
TextSensor sensor;
|
||||
std::vector<std::string> seen;
|
||||
sensor.add_on_state_callback([&seen](const std::string &state) { seen.push_back(state); });
|
||||
sensor.add_filters(filters);
|
||||
const auto publish_at = [&sensor](uint32_t now, const char *value) {
|
||||
LoopBlockingGuard guard{nullptr, nullptr, now};
|
||||
sensor.publish_state(value);
|
||||
};
|
||||
const auto loop_at = [&timeout](uint32_t now) {
|
||||
LoopBlockingGuard guard{nullptr, nullptr, now};
|
||||
timeout.loop();
|
||||
};
|
||||
publish_at(1000, "a");
|
||||
publish_at(1200, "b"); // held by the throttle, sent once updates pause
|
||||
loop_at(2200);
|
||||
publish_at(2300, "c");
|
||||
publish_at(2400, "NA"); // a priority value passes at once
|
||||
publish_at(2500, "d");
|
||||
loop_at(3500);
|
||||
return seen;
|
||||
}
|
||||
|
||||
TEST(TextFilterChain, CombinedTimeoutThrottleMatchesTheChain) {
|
||||
TimeoutFilterLast timeout(1000);
|
||||
ThrottleWithPriorityFilter throttle(1000, PRIORITIZED);
|
||||
const auto chain = run_sequence({&timeout, &throttle}, timeout);
|
||||
TimeoutThrottleFilter combined(1000, PRIORITIZED);
|
||||
EXPECT_EQ(run_sequence({&combined}, combined), chain);
|
||||
EXPECT_EQ(chain, (std::vector<std::string>{"a", "b", "NA", "d"}));
|
||||
}
|
||||
|
||||
TEST_F(TextFilterTest, CombinedWithoutPriorityIsAPlainThrottle) {
|
||||
TimeoutThrottleFilter combined(1000, nullptr);
|
||||
this->sensor_.add_filter(&combined);
|
||||
this->publish_at(1000, "a");
|
||||
this->publish_at(1300, "NA");
|
||||
loop_at(combined, 2300);
|
||||
EXPECT_EQ(this->seen_, (std::vector<std::string>{"a", "NA"}));
|
||||
}
|
||||
|
||||
} // namespace esphome::text_sensor::testing
|
||||
@@ -2,6 +2,7 @@ wifi:
|
||||
dpp:
|
||||
channels: [1, 6, 11]
|
||||
device_info: ESPHome
|
||||
private_key: 00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff
|
||||
timeout: 30s
|
||||
on_dpp_uri:
|
||||
- logger.log:
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
esphome:
|
||||
name: uart-mock-dfrobot-sen0395
|
||||
|
||||
host:
|
||||
api:
|
||||
batch_delay: 0ms # Disable batching to receive all state updates
|
||||
logger:
|
||||
level: VERBOSE
|
||||
|
||||
external_components:
|
||||
- source:
|
||||
type: local
|
||||
path: EXTERNAL_COMPONENT_PATH
|
||||
|
||||
# Dummy uart entry to satisfy DEPENDENCIES = ["uart"]
|
||||
uart:
|
||||
baud_rate: 115200
|
||||
port: /dev/null
|
||||
|
||||
uart_mock:
|
||||
id: mock_uart
|
||||
baud_rate: 115200
|
||||
# A small model of the module's command line: echo, answer and the prompt (no line end)
|
||||
on_tx:
|
||||
- then:
|
||||
- lambda: |-
|
||||
std::string cmd(data.begin(), data.end());
|
||||
std::string reply = cmd + "\r\n";
|
||||
if (cmd == "resetSystem") {
|
||||
// The restart only answers with the prompt
|
||||
} else {
|
||||
reply += "Done\r\n";
|
||||
}
|
||||
reply += "leapMMW:/>";
|
||||
id(mock_uart).inject_to_rx_buffer(std::vector<uint8_t>(reply.begin(), reply.end()));
|
||||
|
||||
dfrobot_sen0395:
|
||||
id: sen0395
|
||||
uart_id: mock_uart
|
||||
|
||||
binary_sensor:
|
||||
- platform: dfrobot_sen0395
|
||||
name: Detected
|
||||
|
||||
switch:
|
||||
- platform: dfrobot_sen0395
|
||||
type: sensor_active
|
||||
name: Sensor Active
|
||||
|
||||
button:
|
||||
- platform: template
|
||||
name: Inject Present
|
||||
on_press:
|
||||
- lambda: |-
|
||||
// '$' is kept apart so it is not read as a substitution
|
||||
std::string frame = std::string(1, '$') + "JYBSS,1, , , *\r\n";
|
||||
id(mock_uart).inject_to_rx_buffer(std::vector<uint8_t>(frame.begin(), frame.end()));
|
||||
- platform: template
|
||||
name: Inject Overlong Then Absent
|
||||
on_press:
|
||||
- lambda: |-
|
||||
// An overlong line is dropped up to its line end; the next frame still parses
|
||||
std::string data(300, 'x');
|
||||
data += "\r\n" + std::string(1, '$') + "JYBSS,0, , , *\r\n";
|
||||
id(mock_uart).inject_to_rx_buffer(std::vector<uint8_t>(data.begin(), data.end()));
|
||||
- platform: template
|
||||
name: Reset Sensor
|
||||
on_press:
|
||||
- dfrobot_sen0395.reset:
|
||||
id: sen0395
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Integration test for the DFRobot SEN0395 component against a model of the module's command line.
|
||||
|
||||
Checks presence frames, recovery after an overlong line, a command answered by "Done" and the
|
||||
reset command, which the module answers only with its "leapMMW:/>" prompt (no line end).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from aioesphomeapi import (
|
||||
BinarySensorInfo,
|
||||
ButtonInfo,
|
||||
EntityInfo,
|
||||
EntityState,
|
||||
SwitchInfo,
|
||||
)
|
||||
import pytest
|
||||
|
||||
from .state_utils import require_entity
|
||||
from .types import APIClientConnectedFactory, RunCompiledFunction
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uart_mock_dfrobot_sen0395(
|
||||
yaml_config: str,
|
||||
run_compiled: RunCompiledFunction,
|
||||
api_client_connected: APIClientConnectedFactory,
|
||||
) -> None:
|
||||
"""Frames parse, an overlong line is dropped and the prompt completes the reset."""
|
||||
external_components_path = str(
|
||||
Path(__file__).parent / "fixtures" / "external_components"
|
||||
)
|
||||
yaml_config = yaml_config.replace(
|
||||
"EXTERNAL_COMPONENT_PATH", external_components_path
|
||||
)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
dropped = loop.create_future()
|
||||
restarted = loop.create_future()
|
||||
|
||||
def line_callback(line: str) -> None:
|
||||
if "Line over 252 chars dropped" in line and not dropped.done():
|
||||
dropped.set_result(True)
|
||||
if "Restarted sensor." in line and not restarted.done():
|
||||
restarted.set_result(True)
|
||||
|
||||
states: dict[int, EntityState] = {}
|
||||
|
||||
async def wait_for(condition: Callable[[], bool], what: str) -> None:
|
||||
try:
|
||||
async with asyncio.timeout(10.0):
|
||||
while not condition():
|
||||
await asyncio.sleep(0.05)
|
||||
except TimeoutError:
|
||||
pytest.fail(f"Timeout waiting for {what}; states: {states}")
|
||||
|
||||
async with (
|
||||
run_compiled(yaml_config, line_callback=line_callback),
|
||||
api_client_connected() as client,
|
||||
):
|
||||
entities, _ = await client.list_entities_services()
|
||||
detected = require_entity(entities, "detected", BinarySensorInfo)
|
||||
active = require_entity(entities, "sensor_active", SwitchInfo)
|
||||
present = require_entity(entities, "inject_present", ButtonInfo)
|
||||
overlong = require_entity(entities, "inject_overlong_then_absent", ButtonInfo)
|
||||
reset = require_entity(entities, "reset_sensor", ButtonInfo)
|
||||
|
||||
client.subscribe_states(lambda state: states.__setitem__(state.key, state))
|
||||
|
||||
def state_of(entity: EntityInfo) -> object | None:
|
||||
state = states.get(entity.key)
|
||||
return None if state is None or state.missing_state else state.state
|
||||
|
||||
client.button_command(present.key)
|
||||
await wait_for(lambda: state_of(detected) is True, "presence")
|
||||
|
||||
client.button_command(overlong.key)
|
||||
await wait_for(
|
||||
lambda: state_of(detected) is False, "absence after overlong line"
|
||||
)
|
||||
await asyncio.wait_for(dropped, timeout=5.0)
|
||||
|
||||
client.switch_command(active.key, False)
|
||||
await wait_for(lambda: state_of(active) is False, "sensor stopped")
|
||||
|
||||
client.button_command(reset.key)
|
||||
try:
|
||||
await asyncio.wait_for(restarted, timeout=10.0)
|
||||
except TimeoutError:
|
||||
pytest.fail("The reset was not completed by the prompt")
|
||||
@@ -1,494 +0,0 @@
|
||||
"""Tests for ``esphome rotate-key``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import ANY, Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome import yaml_util
|
||||
from esphome.cli.rotate_key import PRECHECK_ADVICE, command_rotate_key
|
||||
from esphome.const import (
|
||||
CONF_API,
|
||||
CONF_ENCRYPTION,
|
||||
CONF_ESPHOME,
|
||||
CONF_KEY,
|
||||
CONF_OTA,
|
||||
CONF_PLATFORM,
|
||||
CONF_PORT,
|
||||
CONF_WEB_SERVER,
|
||||
KEY_CORE,
|
||||
KEY_TARGET_PLATFORM,
|
||||
PLATFORM_ESP32,
|
||||
)
|
||||
from esphome.core import CORE, EsphomeError, Toolchain
|
||||
from esphome.espota2 import ProbeResult
|
||||
from esphome.ota_key_edit import KeyEdit
|
||||
from esphome.upload_targets import PortType
|
||||
from esphome.util import ESPHOME_COMMAND
|
||||
from esphome.yaml_edit import RestoreError
|
||||
|
||||
|
||||
@dataclass
|
||||
class MockArgs:
|
||||
device: list[str] | None = None
|
||||
prompt_new_key: bool = False
|
||||
yes: bool = False
|
||||
substitution: list[list[str]] | None = None
|
||||
toolchain: Toolchain | None = None
|
||||
|
||||
|
||||
def _interrupt_after(writes: int) -> Any:
|
||||
"""A write_keeping_mode that lets ``writes`` calls through, then Ctrl-C."""
|
||||
from esphome.yaml_edit import write_keeping_mode
|
||||
|
||||
calls = 0
|
||||
|
||||
def write(*args: Any, **kwargs: Any) -> None:
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls > writes:
|
||||
raise KeyboardInterrupt
|
||||
write_keeping_mode(*args, **kwargs)
|
||||
|
||||
return write
|
||||
|
||||
|
||||
def setup_core(tmp_path: Path) -> None:
|
||||
CORE.reset()
|
||||
CORE.config_path = tmp_path / "test.yaml"
|
||||
CORE.name = "test"
|
||||
CORE.build_path = tmp_path / ".esphome" / "build" / "test"
|
||||
CORE.data[KEY_CORE] = {KEY_TARGET_PLATFORM: PLATFORM_ESP32}
|
||||
|
||||
|
||||
OLD_KEY = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8="
|
||||
NEW_KEY = "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="
|
||||
API_YAML = f"""esphome:
|
||||
name: test
|
||||
|
||||
api:
|
||||
encryption:
|
||||
key: "{OLD_KEY}"
|
||||
|
||||
ota:
|
||||
- platform: esphome
|
||||
encryption:
|
||||
"""
|
||||
OTA_CONF = {
|
||||
CONF_PLATFORM: CONF_ESPHOME,
|
||||
CONF_PORT: 3232,
|
||||
CONF_ENCRYPTION: {CONF_KEY: OLD_KEY},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path: Path) -> Generator[dict[str, Mock]]:
|
||||
"""A config with an inline api key, loaded the way read_config does so
|
||||
the key node carries its source range, and every network step mocked."""
|
||||
setup_core(tmp_path)
|
||||
CORE.config_path.write_text(API_YAML, encoding="utf-8")
|
||||
CORE.raw_config = yaml_util.load_yaml(CORE.config_path)
|
||||
CORE.config = {
|
||||
CONF_API: {CONF_ENCRYPTION: {CONF_KEY: OLD_KEY}},
|
||||
CONF_OTA: [OTA_CONF],
|
||||
}
|
||||
with (
|
||||
patch("esphome.__main__.choose_upload_log_host", return_value=["dev.local"]),
|
||||
patch("esphome.__main__._resolve_network_devices", return_value=["dev.local"]),
|
||||
patch("esphome.cli.rotate_key.get_port_type", return_value=PortType.NETWORK),
|
||||
patch(
|
||||
"esphome.espota2.probe_ota_key", return_value=ProbeResult.ACCEPTED
|
||||
) as probe,
|
||||
patch(
|
||||
"esphome.cli.rotate_key.run_external_process", return_value=0
|
||||
) as compile_,
|
||||
patch("esphome.espota2.run_ota") as upload,
|
||||
patch("esphome.cli.rotate_key.safe_input", return_value="y") as confirm,
|
||||
patch("esphome.cli.rotate_key.sys.stdin") as stdin,
|
||||
patch(
|
||||
"esphome.components.noise.secrets.token_bytes",
|
||||
return_value=bytes(range(1, 33)),
|
||||
),
|
||||
):
|
||||
stdin.isatty.return_value = True
|
||||
# The real upload reports the connection before its result
|
||||
upload.return_value = (0, "dev.local")
|
||||
|
||||
def upload_after_connecting(
|
||||
*_args: Any, **kwargs: Any
|
||||
) -> tuple[int, str | None]:
|
||||
kwargs["on_upload_start"]()
|
||||
return upload.return_value
|
||||
|
||||
upload.side_effect = upload_after_connecting
|
||||
yield {
|
||||
"probe": probe,
|
||||
"compile": compile_,
|
||||
"upload": upload,
|
||||
"confirm": confirm,
|
||||
"stdin": stdin,
|
||||
}
|
||||
|
||||
|
||||
def test_success(env: dict[str, Mock], capfd: pytest.CaptureFixture[str]) -> None:
|
||||
"""Generate, write, compile in a child, upload with the old key, confirm
|
||||
with the new one, print it."""
|
||||
args = MockArgs()
|
||||
assert command_rotate_key(args, CORE.config) == 0
|
||||
|
||||
assert (
|
||||
CORE.config_path.read_text()
|
||||
== API_YAML.replace(OLD_KEY, NEW_KEY) + f' old_key: "{OLD_KEY}"\n'
|
||||
)
|
||||
env["confirm"].assert_called_once()
|
||||
precheck, confirm = env["probe"].call_args_list
|
||||
assert precheck.args[2] == OLD_KEY
|
||||
assert precheck.kwargs["retry_rejected"] is False
|
||||
assert confirm.args[2] == NEW_KEY
|
||||
compile_args = env["compile"].call_args.args
|
||||
assert compile_args[-2:] == ("compile", str(CORE.config_path))
|
||||
env["upload"].assert_called_once_with(
|
||||
["dev.local"],
|
||||
3232,
|
||||
None,
|
||||
CORE.firmware_bin,
|
||||
noise_psk=OLD_KEY,
|
||||
plaintext_fallback=False,
|
||||
on_upload_start=ANY,
|
||||
)
|
||||
out = capfd.readouterr().out
|
||||
assert NEW_KEY in out
|
||||
assert "SUCCESS" in out
|
||||
|
||||
|
||||
def test_yes_skips_confirmation(
|
||||
env: dict[str, Mock],
|
||||
) -> None:
|
||||
assert command_rotate_key(MockArgs(yes=True), CORE.config) == 0
|
||||
env["confirm"].assert_not_called()
|
||||
|
||||
|
||||
def test_declined(env: dict[str, Mock]) -> None:
|
||||
env["confirm"].return_value = "n"
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
env["probe"].assert_not_called()
|
||||
|
||||
|
||||
def test_warns_about_a_shared_secret(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""Other configurations using the rewritten secret are named before the
|
||||
confirmation."""
|
||||
|
||||
def scan(edits: list[KeyEdit]) -> list[str]:
|
||||
edits[0].secret = "device_key"
|
||||
edits[0].shared_with = [CORE.config_dir / "b.yaml"]
|
||||
return ["c.yaml is a link"]
|
||||
|
||||
with patch("esphome.cli.rotate_key.with_sharers", side_effect=scan):
|
||||
env["confirm"].return_value = "n"
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert "b.yaml (secret 'device_key')" in out
|
||||
assert "Could not check every configuration for shared use: c.yaml is a link" in out
|
||||
|
||||
|
||||
def test_no_terminal_needs_yes(
|
||||
env: dict[str, Mock],
|
||||
) -> None:
|
||||
env["stdin"].isatty.return_value = False
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
|
||||
|
||||
def test_own_ota_key_asks_nothing(
|
||||
env: dict[str, Mock],
|
||||
) -> None:
|
||||
"""Without an api key nothing changes for Home Assistant."""
|
||||
config = {CONF_OTA: [OTA_CONF]}
|
||||
assert command_rotate_key(MockArgs(), config) == 0
|
||||
env["confirm"].assert_not_called()
|
||||
assert NEW_KEY in CORE.config_path.read_text()
|
||||
|
||||
|
||||
def test_prompted_new_key(env: dict[str, Mock]) -> None:
|
||||
key = "AgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICE="
|
||||
with patch("esphome.cli.rotate_key.read_secret_line", return_value=key):
|
||||
assert command_rotate_key(MockArgs(prompt_new_key=True), CORE.config) == 0
|
||||
assert key in CORE.config_path.read_text()
|
||||
assert env["probe"].call_args_list[1].args[2] == key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["not-base64", OLD_KEY], ids=["invalid", "same"])
|
||||
def test_rejects_bad_new_key(env: dict[str, Mock], key: str) -> None:
|
||||
with patch("esphome.cli.rotate_key.read_secret_line", return_value=key):
|
||||
assert command_rotate_key(MockArgs(prompt_new_key=True), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
env["probe"].assert_not_called()
|
||||
|
||||
|
||||
def test_precheck_fails_writes_nothing(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env["probe"].return_value = ProbeResult.REJECTED
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
env["compile"].assert_not_called()
|
||||
assert "runs a different key than the yaml" in capfd.readouterr().out
|
||||
for found in (
|
||||
ProbeResult.UNREACHABLE,
|
||||
ProbeResult.NOT_OFFERED,
|
||||
ProbeResult.DEVICE_ERROR,
|
||||
):
|
||||
env["probe"].return_value = found
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert PRECHECK_ADVICE[found] in capfd.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", ["compile", "interrupt"])
|
||||
def test_restores_before_the_upload(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str], step: str
|
||||
) -> None:
|
||||
if step == "compile":
|
||||
env["compile"].return_value = 1
|
||||
else:
|
||||
env["compile"].side_effect = KeyboardInterrupt
|
||||
image = CORE.firmware_bin
|
||||
image.parent.mkdir(parents=True)
|
||||
factory = image.with_name("firmware.factory.bin")
|
||||
for built in (image, factory):
|
||||
built.write_bytes(b"built with the new key")
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
assert env["probe"].call_count == 1
|
||||
out = capfd.readouterr().out
|
||||
assert ("Interrupted before the upload" in out) is (step == "interrupt")
|
||||
# The images may hold the new key, so no upload can install them
|
||||
assert not image.exists() and not factory.exists()
|
||||
assert "compile again before the next upload" in out
|
||||
assert NEW_KEY not in out
|
||||
|
||||
|
||||
def test_a_build_that_cannot_be_removed_shows_the_new_key(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""Every image is tried; the ones that stay are all named."""
|
||||
env["compile"].return_value = 1
|
||||
image = CORE.firmware_bin
|
||||
image.mkdir(parents=True) # unlink fails on a directory
|
||||
stuck = image.with_name("firmware.factory.bin")
|
||||
stuck.mkdir()
|
||||
removable = image.with_name("firmware.ota.bin")
|
||||
removable.write_bytes(b"")
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert str(image) in out and str(stuck) in out
|
||||
assert not removable.exists()
|
||||
assert OLD_KEY in out and NEW_KEY in out
|
||||
|
||||
|
||||
def test_an_interrupt_during_the_image_cleanup_shows_the_keys(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env["compile"].return_value = 1
|
||||
CORE.firmware_bin.parent.mkdir(parents=True)
|
||||
CORE.firmware_bin.write_bytes(b"")
|
||||
with patch("pathlib.Path.glob", side_effect=KeyboardInterrupt):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert f"{CORE.firmware_bin.parent}: interrupted" in out
|
||||
assert OLD_KEY in out and NEW_KEY in out
|
||||
|
||||
|
||||
def test_a_build_from_before_the_rotation_is_kept(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env["probe"].return_value = ProbeResult.UNREACHABLE
|
||||
image = CORE.firmware_bin
|
||||
image.parent.mkdir(parents=True)
|
||||
image.write_bytes(b"built with the current key")
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert image.exists()
|
||||
assert "compile again" not in capfd.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rollback", ["succeeded", "failed"])
|
||||
def test_an_interrupt_while_writing_reports_a_failed_rollback(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str], rollback: str
|
||||
) -> None:
|
||||
"""apply_line_edits keeps an interrupt an interrupt and notes a rollback
|
||||
that failed too; then a file still holds the new key, so both are shown."""
|
||||
interrupt = KeyboardInterrupt()
|
||||
if rollback == "failed":
|
||||
interrupt.add_note("Could not restore test.yaml: disk")
|
||||
with patch("esphome.cli.rotate_key.apply_line_edits", side_effect=interrupt):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert ("Could not restore test.yaml: disk" in out) is (rollback == "failed")
|
||||
assert (NEW_KEY in out) is (rollback == "failed")
|
||||
assert ("Interrupted before the upload" in out) is (rollback == "succeeded")
|
||||
|
||||
|
||||
def test_a_second_interrupt_during_the_restore_shows_the_keys(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env["compile"].return_value = 1
|
||||
with patch("esphome.yaml_edit.write_keeping_mode", side_effect=_interrupt_after(1)):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert f"Could not restore {CORE.config_path}: interrupted" in out
|
||||
assert OLD_KEY in out and NEW_KEY in out
|
||||
|
||||
|
||||
def test_restores_when_the_device_was_never_reached(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""An upload that fails before the image is sent cannot have committed."""
|
||||
env["upload"].side_effect = None
|
||||
env["upload"].return_value = (1, None)
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
out = capfd.readouterr().out
|
||||
assert "failed before the image was sent" in out
|
||||
assert "put back" not in out
|
||||
assert "Restored the previous key" in out
|
||||
|
||||
|
||||
def test_keeps_the_edit_after_a_failed_upload(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""An attempted upload may have committed, so the config keeps both keys
|
||||
and the new one is printed."""
|
||||
env["upload"].return_value = (1, None)
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
text = CORE.config_path.read_text()
|
||||
assert NEW_KEY in text and f'old_key: "{OLD_KEY}"' in text
|
||||
assert NEW_KEY in capfd.readouterr().out
|
||||
assert env["probe"].call_count == 1
|
||||
|
||||
|
||||
def test_shows_both_keys_only_when_a_file_stayed_rewritten(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
with patch(
|
||||
"esphome.cli.rotate_key.apply_line_edits", side_effect=RestoreError("stuck")
|
||||
):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert "stuck" in out and OLD_KEY in out and NEW_KEY in out
|
||||
|
||||
|
||||
def test_reports_a_failed_restore(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env["compile"].return_value = 1
|
||||
with patch(
|
||||
"esphome.cli.rotate_key.restore_files",
|
||||
side_effect=RestoreError("Could not restore x"),
|
||||
):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert "Could not restore x" in out
|
||||
assert OLD_KEY in out and NEW_KEY in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"outcome", ["unreachable", "rejected", "not_offered", "device_error", "interrupted"]
|
||||
)
|
||||
def test_keeps_the_new_key_after_the_upload(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str], outcome: str
|
||||
) -> None:
|
||||
"""Once the upload went through the device most likely runs the new key
|
||||
and old_key covers the other case, so the files stay and the key is
|
||||
printed."""
|
||||
env["probe"].side_effect = [
|
||||
ProbeResult.ACCEPTED,
|
||||
{
|
||||
"interrupted": KeyboardInterrupt,
|
||||
"unreachable": ProbeResult.UNREACHABLE,
|
||||
"rejected": ProbeResult.REJECTED,
|
||||
"not_offered": ProbeResult.NOT_OFFERED,
|
||||
"device_error": ProbeResult.DEVICE_ERROR,
|
||||
}[outcome],
|
||||
]
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
assert NEW_KEY in CORE.config_path.read_text()
|
||||
assert f'old_key: "{OLD_KEY}"' in CORE.config_path.read_text()
|
||||
out = capfd.readouterr().out
|
||||
assert NEW_KEY in out
|
||||
assert ("Interrupted" in out) is (outcome == "interrupted")
|
||||
assert ("still answers with the previous key" in out) is (outcome == "rejected")
|
||||
assert ("did not come back" in out) is (outcome == "unreachable")
|
||||
assert ("came back without encryption" in out) is (outcome == "not_offered")
|
||||
assert ("answered with an error" in out) is (outcome == "device_error")
|
||||
|
||||
|
||||
def test_child_compile_gets_global_options_first(
|
||||
env: dict[str, Mock],
|
||||
) -> None:
|
||||
"""The compile parser is strict, so -s and --toolchain precede it."""
|
||||
args = MockArgs(substitution=[["name", "kitchen"]])
|
||||
CORE.dashboard = True
|
||||
args.toolchain = Toolchain.PLATFORMIO
|
||||
assert command_rotate_key(args, CORE.config) == 0
|
||||
assert env["compile"].call_args.args[len(ESPHOME_COMMAND) :] == (
|
||||
"--dashboard",
|
||||
"--toolchain",
|
||||
"platformio",
|
||||
"-s",
|
||||
"name",
|
||||
"kitchen",
|
||||
"compile",
|
||||
str(CORE.config_path),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "port_type", "match"),
|
||||
[
|
||||
(
|
||||
{CONF_OTA: [{CONF_PLATFORM: CONF_ESPHOME, CONF_PORT: 3232}]},
|
||||
"NETWORK",
|
||||
"needs 'encryption:'",
|
||||
),
|
||||
({CONF_OTA: [{CONF_PLATFORM: CONF_WEB_SERVER}]}, "NETWORK", "esphome OTA"),
|
||||
({CONF_OTA: [OTA_CONF]}, PortType.SERIAL, "over the air"),
|
||||
],
|
||||
ids=["no_encryption", "web_server_only", "serial"],
|
||||
)
|
||||
def test_refuses(
|
||||
env: dict[str, Mock],
|
||||
capfd: pytest.CaptureFixture[str],
|
||||
config: dict[str, Any],
|
||||
port_type: str,
|
||||
match: str,
|
||||
) -> None:
|
||||
with patch("esphome.cli.rotate_key.get_port_type", return_value=port_type):
|
||||
assert command_rotate_key(MockArgs(), config) == 1
|
||||
assert match in capfd.readouterr().out
|
||||
env["probe"].assert_not_called()
|
||||
|
||||
|
||||
def test_refuses_host(env: dict[str, Mock]) -> None:
|
||||
CORE.data[KEY_CORE][KEY_TARGET_PLATFORM] = "host"
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
env["probe"].assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("helper", ["locate_key_edits", "apply_line_edits"])
|
||||
def test_reports_edit_errors(
|
||||
env: dict[str, Mock], capfd: pytest.CaptureFixture[str], helper: str
|
||||
) -> None:
|
||||
with patch(f"esphome.cli.rotate_key.{helper}", side_effect=EsphomeError("nope")):
|
||||
assert command_rotate_key(MockArgs(), CORE.config) == 1
|
||||
out = capfd.readouterr().out
|
||||
assert "nope" in out
|
||||
# A refusal, or an edit rolled back cleanly, shows no key
|
||||
assert NEW_KEY not in out
|
||||
assert CORE.config_path.read_text() == API_YAML
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Tests for the esp32 framework ``components:`` schema."""
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components import esp32
|
||||
import esphome.config_validation as cv
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
"https://github.com/owner/component.git",
|
||||
"git@github.com:owner/component.git",
|
||||
],
|
||||
)
|
||||
def test_component_source_accepts_repository_url(source: str) -> None:
|
||||
config = esp32.FRAMEWORK_SCHEMA(
|
||||
{"components": [{"name": "owner/component", "source": source}]}
|
||||
)
|
||||
assert config["components"][0]["source"] == source
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", [1.0, ""])
|
||||
def test_component_source_rejects_invalid(source: object) -> None:
|
||||
with pytest.raises(cv.Invalid):
|
||||
esp32.FRAMEWORK_SCHEMA(
|
||||
{"components": [{"name": "owner/component", "source": source}]}
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Tests for trimming a LibreTiny UF2 to the images a device writes over OTA."""
|
||||
|
||||
from pathlib import Path
|
||||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
from esphome.components.libretiny import device_ota_image
|
||||
from esphome.components.libretiny.ota_uf2 import UF2_TAG_OTA_PART_INFO, device_ota_uf2
|
||||
from esphome.core import CORE
|
||||
|
||||
# Written from the UF2 and LibreTiny formats, not from the module under test
|
||||
MAGIC_1, MAGIC_2, MAGIC_3 = 0x0A324655, 0x9E5D5157, 0x0AB16F30
|
||||
FLAG_FAMILY, FLAG_TAGS = 0x2000, 0x8000
|
||||
FAMILY = 0x7B3EF230
|
||||
TAG_OTA_FORMAT_2 = 0x6C8492
|
||||
TAG_BINPATCH = 0xB948DE
|
||||
# OTA_PART_INFO index nibbles: device single, dual 1, dual 2, flasher single, dual 1, dual 2
|
||||
DEVICE_SINGLE = b"\x10\x00\x00"
|
||||
FLASHER_SINGLE = b"\x00\x01\x00"
|
||||
DEVICE_DUAL_1 = b"\x01\x00\x00"
|
||||
DEVICE_DUAL_2 = b"\x00\x10\x00"
|
||||
|
||||
|
||||
def _tag(tag: int, value: bytes) -> bytes:
|
||||
size = 4 + len(value)
|
||||
return bytes([size]) + tag.to_bytes(3, "little") + value + bytes(-size % 4)
|
||||
|
||||
|
||||
def _block(payload: bytes = b"", tags: dict[int, bytes] | None = None) -> bytes:
|
||||
"""A block numbered 0 of 0; _package numbers it."""
|
||||
flags = FLAG_FAMILY | (FLAG_TAGS if tags else 0)
|
||||
header = struct.pack("<8I", MAGIC_1, MAGIC_2, flags, 0, len(payload), 0, 0, FAMILY)
|
||||
body = payload + b"".join(_tag(t, v) for t, v in (tags or {}).items())
|
||||
return header + body + bytes(512 - 32 - 4 - len(body)) + struct.pack("<I", MAGIC_3)
|
||||
|
||||
|
||||
def _image(part_info: bytes, blocks: int, fill: int) -> list[bytes]:
|
||||
"""An image: its first block names the partitions, the rest carry data."""
|
||||
data = bytes([fill]) * 256
|
||||
first = _block(data, {UF2_TAG_OTA_PART_INFO: part_info + b"part\x00"})
|
||||
return [first] + [_block(data) for _ in range(blocks - 1)]
|
||||
|
||||
|
||||
def _package(*blocks: bytes) -> bytes:
|
||||
"""The blocks numbered in order, as a UF2 file."""
|
||||
return b"".join(
|
||||
block[:20] + struct.pack("<2I", seq, len(blocks)) + block[28:]
|
||||
for seq, block in enumerate(blocks)
|
||||
)
|
||||
|
||||
|
||||
HEADER = _block(tags={TAG_OTA_FORMAT_2: b"\x02"})
|
||||
FLASHER = _image(FLASHER_SINGLE, 5, 0xAA)
|
||||
DEVICE = _image(DEVICE_SINGLE, 3, 0xBB)
|
||||
SLOT_1 = _image(DEVICE_DUAL_1, 2, 0x11)
|
||||
SLOT_2 = _image(DEVICE_DUAL_2, 2, 0x22)
|
||||
PATCHED = _block(bytes([0xAA]) * 256, {TAG_BINPATCH: b"\x01\x02\x03\x04"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("blocks", "expected"),
|
||||
[
|
||||
pytest.param([HEADER, *FLASHER, *DEVICE], [HEADER, *DEVICE], id="single_ota"),
|
||||
pytest.param(
|
||||
[HEADER, *SLOT_1, *FLASHER, *SLOT_2],
|
||||
[HEADER, *SLOT_1, *SLOT_2],
|
||||
id="dual_ota_keeps_both_slots",
|
||||
),
|
||||
pytest.param(
|
||||
[HEADER, *FLASHER, PATCHED, *DEVICE],
|
||||
None,
|
||||
id="dropped_image_carries_a_tag_the_device_acts_on",
|
||||
),
|
||||
pytest.param([HEADER, *DEVICE], None, id="nothing_to_drop"),
|
||||
],
|
||||
)
|
||||
def test_device_ota_uf2(blocks: list[bytes], expected: list[bytes] | None) -> None:
|
||||
trimmed = device_ota_uf2(_package(*blocks))
|
||||
assert trimmed == (_package(*expected) if expected is not None else None)
|
||||
|
||||
|
||||
def test_data_that_is_not_a_well_formed_uf2_is_left_alone() -> None:
|
||||
package = _package(HEADER, *FLASHER, *DEVICE)
|
||||
bad_magic = package[:512] + b"\x00" + package[513:]
|
||||
# A tag that runs past the data area of the first flasher block
|
||||
at = 512 + 32 + 256
|
||||
bad_tag = package[:at] + bytes([250]) + package[at + 1 :]
|
||||
|
||||
# A whole block missing, or repeated, keeps the original numbering
|
||||
missing = package[:1024] + package[1536:]
|
||||
repeated = package[:1536] + package[1024:]
|
||||
# OTA_PART_INFO too short to hold the scheme map, which uf2ota rejects
|
||||
short_selectors = [
|
||||
_package(HEADER, _block(bytes(256), {UF2_TAG_OTA_PART_INFO: bytes(n)}), *DEVICE)
|
||||
for n in range(3)
|
||||
]
|
||||
|
||||
for data in (
|
||||
b"",
|
||||
bytes(range(256)) * 4,
|
||||
package[:-1],
|
||||
bad_magic,
|
||||
bad_tag,
|
||||
missing,
|
||||
repeated,
|
||||
*short_selectors,
|
||||
):
|
||||
assert device_ota_uf2(data) is None
|
||||
|
||||
|
||||
def test_device_ota_image(setup_core: Path) -> None:
|
||||
tmp_path = setup_core
|
||||
CORE.build_path = tmp_path / "build"
|
||||
CORE.name = "test"
|
||||
firmware = tmp_path / "firmware.uf2"
|
||||
|
||||
firmware.write_bytes(_package(HEADER, *FLASHER, *DEVICE))
|
||||
image = device_ota_image(firmware)
|
||||
assert image == CORE.relative_pioenvs_path("test", "firmware.ota.uf2")
|
||||
assert image.read_bytes() == _package(HEADER, *DEVICE)
|
||||
|
||||
# Nothing to drop: the firmware itself is sent
|
||||
firmware.write_bytes(_package(HEADER, *DEVICE))
|
||||
assert device_ota_image(firmware) == firmware
|
||||
@@ -3121,9 +3121,21 @@ def test_git_ref_valid() -> None:
|
||||
assert cv.git_ref("v1.2.3") == "v1.2.3"
|
||||
|
||||
|
||||
def test_git_ref_invalid() -> None:
|
||||
@pytest.mark.parametrize("ref", ["main", "release/v6.0", "feat+x", "a1b2c3d4"])
|
||||
def test_git_ref_valid_chars(ref: str) -> None:
|
||||
assert cv.git_ref(ref) == ref
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ref", ["main hi there", "a:b", "x~1", "", "main\n"])
|
||||
def test_git_ref_invalid(ref: str) -> None:
|
||||
with pytest.raises(Invalid, match="Not a valid git ref"):
|
||||
cv.git_ref("!!!")
|
||||
cv.git_ref(ref)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ref", [1.0, 2025, None])
|
||||
def test_git_ref_not_string(ref: object) -> None:
|
||||
with pytest.raises(Invalid, match="Must be string"):
|
||||
cv.git_ref(ref)
|
||||
|
||||
|
||||
def test_source_refresh_always() -> None:
|
||||
@@ -3291,6 +3303,34 @@ def test_validate_source_shorthand_github_pr(setup_core: Path) -> None:
|
||||
assert result[CONF_REF] == "pull/1234/head"
|
||||
|
||||
|
||||
def test_validate_source_shorthand_github_ref_with_slash(setup_core: Path) -> None:
|
||||
result = cv.validate_source_shorthand("github://user/repo@release/v1")
|
||||
assert result[CONF_REF] == "release/v1"
|
||||
|
||||
|
||||
def test_validate_source_shorthand_github_ref_keeps_all_chars(
|
||||
setup_core: Path,
|
||||
) -> None:
|
||||
result = cv.validate_source_shorthand("github://user/repo@feat+x")
|
||||
assert result[CONF_REF] == "feat+x"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
"github://esphome/esphome/esphome/components@dev",
|
||||
"github://user/repo/",
|
||||
"github://user/repo@main hi",
|
||||
"github://pr#1234abc",
|
||||
],
|
||||
)
|
||||
def test_validate_source_shorthand_rejects_trailing_text(
|
||||
setup_core: Path, value: str
|
||||
) -> None:
|
||||
with pytest.raises(Invalid, match="not a file system path"):
|
||||
cv.validate_source_shorthand(value)
|
||||
|
||||
|
||||
def test_validate_source_shorthand_invalid(setup_core: Path) -> None:
|
||||
with pytest.raises(Invalid, match="not a file system path"):
|
||||
cv.validate_source_shorthand("notvalid")
|
||||
|
||||
@@ -10,6 +10,7 @@ import threading
|
||||
import time
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
import urllib.parse
|
||||
|
||||
from filelock import FileLock
|
||||
import pytest
|
||||
@@ -2097,6 +2098,48 @@ def test_recovery_reclone_keeps_credentials_and_cache_key(
|
||||
assert clone_url.count("@") == 1
|
||||
|
||||
|
||||
def test_clone_credentials_with_slash_are_escaped(
|
||||
tmp_path: Path, mock_run_git_command: Mock
|
||||
) -> None:
|
||||
"""A "/" in the username or password must be percent-encoded, or the
|
||||
userinfo ends at the "/" and git reports the password in its error."""
|
||||
CORE.config_path = tmp_path / "test.yaml"
|
||||
|
||||
url = "https://github.com/test/repo"
|
||||
domain = "test"
|
||||
repo_dir = _compute_repo_dir(url, None, domain)
|
||||
|
||||
def git_command_side_effect(
|
||||
cmd: list[str], cwd: str | None = None, **kwargs: Any
|
||||
) -> str:
|
||||
if _get_git_command_type(cmd) == "clone":
|
||||
_simulate_cloned_repo(repo_dir)
|
||||
return ""
|
||||
|
||||
mock_run_git_command.side_effect = git_command_side_effect
|
||||
|
||||
git.clone_or_update(
|
||||
url=url,
|
||||
ref=None,
|
||||
refresh=TimePeriodSeconds(days=1),
|
||||
domain=domain,
|
||||
username="team/user",
|
||||
password="ab/cd@ef",
|
||||
)
|
||||
|
||||
clone_cmds = [
|
||||
c[0][0]
|
||||
for c in mock_run_git_command.call_args_list
|
||||
if _get_git_command_type(c[0][0]) == "clone"
|
||||
]
|
||||
assert clone_cmds
|
||||
clone_url = clone_cmds[0][-2]
|
||||
assert clone_url == "https://team%2Fuser:ab%2Fcd%40ef@github.com/test/repo"
|
||||
assert urllib.parse.urlsplit(clone_url).hostname == "github.com"
|
||||
redacted = git._redact_url_credentials(f"fatal: unable to access '{clone_url}/'")
|
||||
assert redacted == "fatal: unable to access 'https://***@github.com/test/repo/'"
|
||||
|
||||
|
||||
def test_refresh_submodule_failure_recovers_then_raises(
|
||||
tmp_path: Path, mock_run_git_command: Mock
|
||||
) -> None:
|
||||
@@ -3289,6 +3332,26 @@ def test_git_file_from_shorthand_without_ref_or_query() -> None:
|
||||
assert gf == git.GitFile("codeberg.org", "owner", "repo", "file.yaml")
|
||||
|
||||
|
||||
def test_git_file_from_shorthand_keeps_whole_ref() -> None:
|
||||
gf = git.GitFile.from_shorthand("github://owner/repo/file.yaml@feat+x?full_config")
|
||||
|
||||
assert gf.ref == "feat+x"
|
||||
assert gf.query == "full_config"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"shorthand",
|
||||
[
|
||||
"github://owner/repo/file.yaml@main hi",
|
||||
"github://owner/repo/my file.yaml",
|
||||
"github://owner/repo/file.yaml?full config",
|
||||
],
|
||||
)
|
||||
def test_git_file_from_shorthand_rejects_trailing_text(shorthand: str) -> None:
|
||||
with pytest.raises(ValueError, match="not in expected"):
|
||||
git.GitFile.from_shorthand(shorthand)
|
||||
|
||||
|
||||
def test_git_file_from_shorthand_requires_string() -> None:
|
||||
with pytest.raises(ValueError, match="must be a string"):
|
||||
git.GitFile.from_shorthand(123)
|
||||
|
||||
@@ -222,15 +222,9 @@ def test_api_client_does_not_import_heavy_modules() -> None:
|
||||
|
||||
# Packages a domain needs for its own schema; cheap and never an integration
|
||||
_ENTITY_COMPONENT_DEPENDENCIES = {
|
||||
"infrared": ("esphome.components.ir_rf_base",),
|
||||
"light": ("esphome.components.power_supply", "esphome.components.const.css_colors"),
|
||||
}
|
||||
|
||||
|
||||
# Entity domains that still import integrations at top level
|
||||
_ENTITY_COMPONENT_KNOWN_LEAKS = {
|
||||
"infrared": "imports remote_base and api at top level",
|
||||
"media_player": "audio pulls in the esp32 chain",
|
||||
"radio_frequency": "imports remote_base and api at top level",
|
||||
"radio_frequency": ("esphome.components.ir_rf_base",),
|
||||
}
|
||||
|
||||
|
||||
@@ -248,26 +242,11 @@ def _entity_components() -> list[str]:
|
||||
def test_entity_component_tables_match_discovery() -> None:
|
||||
"""Catch stale table entries and a discovery that silently finds nothing."""
|
||||
found = set(_entity_components())
|
||||
stale = (
|
||||
_ENTITY_COMPONENT_KNOWN_LEAKS.keys() | _ENTITY_COMPONENT_DEPENDENCIES.keys()
|
||||
) - found
|
||||
stale = _ENTITY_COMPONENT_DEPENDENCIES.keys() - found
|
||||
assert not stale, f"not discovered as entity components: {sorted(stale)}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"component",
|
||||
[
|
||||
pytest.param(
|
||||
c,
|
||||
marks=pytest.mark.xfail(
|
||||
reason=_ENTITY_COMPONENT_KNOWN_LEAKS[c], strict=True
|
||||
),
|
||||
)
|
||||
if c in _ENTITY_COMPONENT_KNOWN_LEAKS
|
||||
else c
|
||||
for c in _entity_components()
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("component", _entity_components())
|
||||
def test_entity_component_does_not_import_integrations(component: str) -> None:
|
||||
"""An entity component must not drag in its optional integrations.
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ from esphome.loader import (
|
||||
clear_component_meta_finders,
|
||||
get_alias_metadata,
|
||||
get_component,
|
||||
get_platform,
|
||||
install_meta_finder,
|
||||
)
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
@@ -809,6 +810,44 @@ def test_lookup_module_import_error_missing_module_returns_none(
|
||||
assert "definitely_missing_component_xyz" not in _COMPONENT_CACHE
|
||||
|
||||
|
||||
def test_lookup_module_missing_platform_returns_none(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""A platform file that does not exist is "not found", not an error."""
|
||||
with caplog.at_level(logging.INFO, logger="esphome.loader"):
|
||||
assert get_platform("definitely_missing_platform_xyz", "template") is None
|
||||
assert "Unable to import component template.definitely_missing_platform_xyz" in (
|
||||
caplog.text
|
||||
)
|
||||
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
|
||||
|
||||
|
||||
def test_lookup_module_missing_dependency_is_logged_as_error(
|
||||
tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""A component that exists but imports a missing package reports that
|
||||
package as an error, instead of looking like a missing component."""
|
||||
comp = tmp_path / "depfailcomp"
|
||||
comp.mkdir()
|
||||
(comp / "__init__.py").write_text("import definitely_missing_package_xyz\n")
|
||||
saved = list(sys.meta_path)
|
||||
try:
|
||||
install_meta_finder(tmp_path)
|
||||
with caplog.at_level(logging.INFO, logger="esphome.loader"):
|
||||
assert get_component("depfailcomp") is None
|
||||
finally:
|
||||
sys.meta_path[:] = saved
|
||||
for name in [
|
||||
m for m in sys.modules if m.startswith("esphome.components.depfailcomp")
|
||||
]:
|
||||
del sys.modules[name]
|
||||
errors = [r for r in caplog.records if r.levelno >= logging.ERROR]
|
||||
assert len(errors) == 1
|
||||
assert errors[0].getMessage() == "Unable to import component depfailcomp:"
|
||||
assert errors[0].exc_info is not None
|
||||
assert errors[0].exc_info[1].name == "definitely_missing_package_xyz"
|
||||
|
||||
|
||||
def test_lookup_module_missing_module_raises_when_requested() -> None:
|
||||
"""With ``exception=True`` the ImportError propagates."""
|
||||
with pytest.raises(ImportError):
|
||||
|
||||
+112
-29
@@ -2135,6 +2135,118 @@ def test_upload_program_ota_success(
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config", "uploader", "image_arg"),
|
||||
[
|
||||
pytest.param(
|
||||
{CONF_OTA: [{CONF_PLATFORM: CONF_ESPHOME, CONF_PORT: 8892}]},
|
||||
"mock_run_ota",
|
||||
3,
|
||||
id="native",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
CONF_OTA: [{CONF_PLATFORM: CONF_WEB_SERVER}],
|
||||
CONF_WEB_SERVER: {CONF_PORT: 80},
|
||||
},
|
||||
"mock_run_web_server_ota",
|
||||
4,
|
||||
id="web_server",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_upload_program_ota_sends_the_platform_ota_image(
|
||||
config: ConfigType,
|
||||
uploader: str,
|
||||
image_arg: int,
|
||||
mock_get_port_type: Mock,
|
||||
tmp_path: Path,
|
||||
request: pytest.FixtureRequest,
|
||||
) -> None:
|
||||
"""An app update sends the file the platform's ota_image hook picks."""
|
||||
setup_core(platform=PLATFORM_BK72XX, tmp_path=tmp_path)
|
||||
mock_get_port_type.return_value = "NETWORK"
|
||||
mock_upload = request.getfixturevalue(uploader)
|
||||
mock_upload.return_value = (0, "192.168.1.100")
|
||||
image = tmp_path / "firmware.ota.uf2"
|
||||
|
||||
with patch(
|
||||
"esphome.components.bk72xx.ota_image", return_value=image
|
||||
) as mock_ota_image:
|
||||
exit_code, _ = upload_program(config, MockArgs(), ["192.168.1.100"])
|
||||
|
||||
assert exit_code == 0
|
||||
mock_ota_image.assert_called_once_with(CORE.firmware_bin)
|
||||
assert mock_upload.call_args.args[image_arg] == image
|
||||
|
||||
|
||||
def test_upload_program_ota_file_goes_through_the_ota_image_hook(
|
||||
mock_run_ota: Mock,
|
||||
mock_get_port_type: Mock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""--file is the firmware the platform's ota_image hook starts from."""
|
||||
setup_core(platform=PLATFORM_BK72XX, tmp_path=tmp_path)
|
||||
mock_get_port_type.return_value = "NETWORK"
|
||||
mock_run_ota.return_value = (0, "192.168.1.100")
|
||||
other = tmp_path / "other.uf2"
|
||||
image = tmp_path / "firmware.ota.uf2"
|
||||
|
||||
config = {CONF_OTA: [{CONF_PLATFORM: CONF_ESPHOME, CONF_PORT: 8892}]}
|
||||
with patch(
|
||||
"esphome.components.bk72xx.ota_image", return_value=image
|
||||
) as mock_ota_image:
|
||||
upload_program(config, MockArgs(file=str(other)), ["192.168.1.100"])
|
||||
|
||||
mock_ota_image.assert_called_once_with(other)
|
||||
assert mock_run_ota.call_args.args[3] == image
|
||||
|
||||
|
||||
def test_upload_program_ota_partition_table_skips_the_ota_image_hook(
|
||||
mock_run_ota: Mock,
|
||||
mock_get_port_type: Mock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Only app updates go through the ota_image hook."""
|
||||
setup_core(platform=PLATFORM_BK72XX, tmp_path=tmp_path)
|
||||
mock_get_port_type.return_value = "NETWORK"
|
||||
mock_run_ota.return_value = (0, "192.168.1.100")
|
||||
partition_file = tmp_path / "partitions.bin"
|
||||
partition_file.write_bytes(_make_partition_table_bytes())
|
||||
|
||||
config = {
|
||||
CONF_OTA: [
|
||||
{
|
||||
CONF_PLATFORM: CONF_ESPHOME,
|
||||
CONF_PORT: 8892,
|
||||
"allow_partition_access": True,
|
||||
}
|
||||
]
|
||||
}
|
||||
args = MockArgs(file=str(partition_file), partition_table=True)
|
||||
with patch("esphome.components.bk72xx.ota_image") as mock_ota_image:
|
||||
upload_program(config, args, ["192.168.1.100"])
|
||||
|
||||
mock_ota_image.assert_not_called()
|
||||
assert mock_run_ota.call_args.args[3] == partition_file
|
||||
|
||||
|
||||
def test_upload_program_ota_without_a_hook_sends_the_firmware(
|
||||
mock_run_ota: Mock,
|
||||
mock_get_port_type: Mock,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""A platform without an ota_image hook sends its build output."""
|
||||
setup_core(platform=PLATFORM_ESP32, tmp_path=tmp_path)
|
||||
mock_get_port_type.return_value = "NETWORK"
|
||||
mock_run_ota.return_value = (0, "192.168.1.100")
|
||||
|
||||
config = {CONF_OTA: [{CONF_PLATFORM: CONF_ESPHOME, CONF_PORT: 3232}]}
|
||||
upload_program(config, MockArgs(), ["192.168.1.100"])
|
||||
|
||||
assert mock_run_ota.call_args.args[3].name == "firmware.bin"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"old_key",
|
||||
[None, "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA="],
|
||||
@@ -8136,32 +8248,3 @@ def test_command_rename_is_dispatched_to_the_cli_module() -> None:
|
||||
with patch("esphome.cli.rename.command_rename", return_value=7) as run:
|
||||
assert main.command_rename(args, {}) == 7
|
||||
run.assert_called_once_with(args, {})
|
||||
|
||||
|
||||
def test_command_rotate_key_is_dispatched_to_the_cli_module() -> None:
|
||||
args = MockArgs()
|
||||
with patch("esphome.cli.rotate_key.command_rotate_key", return_value=7) as run:
|
||||
assert main.command_rotate_key(args, {}) == 7
|
||||
run.assert_called_once_with(args, {})
|
||||
|
||||
|
||||
def test_parse_args_rotate_key() -> None:
|
||||
args = parse_args(
|
||||
[
|
||||
"esphome",
|
||||
"rotate-key",
|
||||
"--device",
|
||||
"dev.local",
|
||||
"--prompt-new-key",
|
||||
"-y",
|
||||
"--username",
|
||||
"mqtt-user",
|
||||
"device.yaml",
|
||||
]
|
||||
)
|
||||
assert args.command == "rotate-key"
|
||||
assert args.device == ["dev.local"]
|
||||
assert args.prompt_new_key is True
|
||||
assert args.yes is True
|
||||
# MQTT device resolution reads these like upload does
|
||||
assert args.username == "mqtt-user"
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user