From 641180b477578201344e225af142a026d6859b82 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 22:48:46 +0100 Subject: [PATCH 1/8] feat: optional WashData coupling Link an advanced_device entry to a ha_washdata entry (extras step and options flow). Cycles and the shutdown release follow WashData's state; mirror sensors expose program, time remaining and progress. Without the WashData entry the own logic is used and a repair issue is raised. Co-Authored-By: Claude Sonnet 5.5 --- .../advanced_device/config_flow.py | 63 ++++- .../advanced_device/config_mapping.py | 5 +- custom_components/advanced_device/const.py | 2 +- .../advanced_device/device_trigger.py | 5 +- custom_components/advanced_device/entity.py | 10 +- custom_components/advanced_device/runtime.py | 55 ++++- custom_components/advanced_device/sensor.py | 69 +++++- .../advanced_device/strings.json | 27 +- .../advanced_device/translations/de.json | 27 +- .../advanced_device/translations/en.json | 27 +- custom_components/advanced_device/washdata.py | 101 ++++++++ tests/integration/test_washdata.py | 230 ++++++++++++++++++ 12 files changed, 595 insertions(+), 26 deletions(-) create mode 100644 custom_components/advanced_device/washdata.py create mode 100644 tests/integration/test_washdata.py diff --git a/custom_components/advanced_device/config_flow.py b/custom_components/advanced_device/config_flow.py index ba082b6..5a6bf24 100644 --- a/custom_components/advanced_device/config_flow.py +++ b/custom_components/advanced_device/config_flow.py @@ -9,7 +9,7 @@ import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME -from homeassistant.core import callback +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.selector import ( BooleanSelector, EntitySelector, @@ -46,11 +46,15 @@ CONF_STANDBY_S, CONF_STANDBY_W, CONF_SWITCH_ENTITY, + CONF_WASHDATA_ENTRY, DEFAULT_LOCK_DEFAULT_MIN, DOMAIN, ) from .core.model import Status from .core.profiles import PROFILES, Profile, get_profile +from .washdata import WASHDATA_DOMAIN + +WASHDATA_NONE = "none" def _watts() -> NumberSelector: @@ -147,7 +151,20 @@ def _icon_defaults(stored: Mapping[str, str], profile: Profile) -> dict[str, str return {status.value: stored.get(status.value, profile.icons[status]) for status in Status} -def _extras_schema(defaults: Mapping[str, Any], *, has_power: bool) -> vol.Schema: +def _washdata_choices(hass: HomeAssistant) -> list[dict[str, str]]: + """Known ha_washdata entries as select options; empty when WashData is not installed.""" + return [ + {"value": entry.entry_id, "label": entry.title} + for entry in hass.config_entries.async_entries(WASHDATA_DOMAIN) + ] + + +def _extras_schema( + defaults: Mapping[str, Any], + *, + has_power: bool, + washdata_choices: list[dict[str, str]], +) -> vol.Schema: fields: dict[Any, Any] = {} if has_power: fields[ @@ -158,6 +175,18 @@ def _extras_schema(defaults: Mapping[str, Any], *, has_power: bool) -> vol.Schem ] = EntitySelector(EntitySelectorConfig(domain=["sensor", "input_number"])) fields[vol.Required(CONF_AUTO_OFF_MIN, default=defaults[CONF_AUTO_OFF_MIN])] = _minutes() fields[vol.Required(CONF_MAX_CYCLE_MIN, default=defaults[CONF_MAX_CYCLE_MIN])] = _minutes() + if washdata_choices: + fields[ + vol.Optional( + CONF_WASHDATA_ENTRY, + description={"suggested_value": defaults.get(CONF_WASHDATA_ENTRY) or WASHDATA_NONE}, + ) + ] = SelectSelector( + SelectSelectorConfig( + options=[{"value": WASHDATA_NONE, "label": "None"}, *washdata_choices], + mode=SelectSelectorMode.DROPDOWN, + ) + ) fields[vol.Required(CONF_MAINTENANCE_H, default=defaults[CONF_MAINTENANCE_H])] = _hours() for status in Status: fields[vol.Required(f"icon_{status.value}", default=defaults[CONF_ICONS][status.value])] = ( @@ -166,8 +195,17 @@ def _extras_schema(defaults: Mapping[str, Any], *, has_power: bool) -> vol.Schem return vol.Schema(fields) -def _store_extras(options: dict[str, Any], user_input: Mapping[str, Any], has_power: bool) -> None: - """Write the extras form into options. The icon_* form keys are not stored.""" +def _store_extras( + options: dict[str, Any], + user_input: Mapping[str, Any], + has_power: bool, + has_washdata: bool, +) -> None: + """Write the extras form into options. The icon_* form keys are not stored. + + The WashData link is only changed when the field was shown; without any + WashData entry the stored link is kept. + """ options[CONF_ICONS] = {status.value: user_input[f"icon_{status.value}"] for status in Status} options[CONF_MAINTENANCE_H] = user_input[CONF_MAINTENANCE_H] if has_power: @@ -176,6 +214,11 @@ def _store_extras(options: dict[str, Any], user_input: Mapping[str, Any], has_po options[CONF_PRICE_ENTITY] = user_input[CONF_PRICE_ENTITY] options[CONF_AUTO_OFF_MIN] = user_input[CONF_AUTO_OFF_MIN] options[CONF_MAX_CYCLE_MIN] = user_input[CONF_MAX_CYCLE_MIN] + if has_washdata: + options.pop(CONF_WASHDATA_ENTRY, None) + washdata_entry = user_input.get(CONF_WASHDATA_ENTRY) + if washdata_entry and washdata_entry != WASHDATA_NONE: + options[CONF_WASHDATA_ENTRY] = washdata_entry _POWER_KEYS = ( @@ -303,8 +346,9 @@ async def async_step_extras( ) -> config_entries.ConfigFlowResult: """Last step: price, auto-off, max cycle, maintenance and icons.""" has_power = bool(self._data.get(CONF_POWER_ENTITY)) + washdata = _washdata_choices(self.hass) if user_input is not None: - _store_extras(self._options, user_input, has_power) + _store_extras(self._options, user_input, has_power, bool(washdata)) return self._create_entry() profile = get_profile(self._options[CONF_PROFILE]) @@ -312,12 +356,13 @@ async def async_step_extras( CONF_PRICE_ENTITY: None, CONF_AUTO_OFF_MIN: profile.auto_off_s / 60, CONF_MAX_CYCLE_MIN: 0, + CONF_WASHDATA_ENTRY: None, CONF_MAINTENANCE_H: 0, CONF_ICONS: _icon_defaults({}, profile), } return self.async_show_form( step_id="extras", - data_schema=_extras_schema(defaults, has_power=has_power), + data_schema=_extras_schema(defaults, has_power=has_power, washdata_choices=washdata), ) def _create_entry(self) -> config_entries.ConfigFlowResult: @@ -460,8 +505,9 @@ async def async_step_extras( ) -> config_entries.ConfigFlowResult: """Price, auto-off, max cycle, maintenance and icons; stored values are the defaults.""" has_power = self._has_power() + washdata = _washdata_choices(self.hass) if user_input is not None: - _store_extras(self._options, user_input, has_power) + _store_extras(self._options, user_input, has_power, bool(washdata)) return self.async_create_entry(data=self._options) profile = get_profile(self._options[CONF_PROFILE]) @@ -469,10 +515,11 @@ async def async_step_extras( CONF_PRICE_ENTITY: self._options.get(CONF_PRICE_ENTITY), CONF_AUTO_OFF_MIN: self._options.get(CONF_AUTO_OFF_MIN, profile.auto_off_s / 60), CONF_MAX_CYCLE_MIN: self._options.get(CONF_MAX_CYCLE_MIN, 0), + CONF_WASHDATA_ENTRY: self._options.get(CONF_WASHDATA_ENTRY), CONF_MAINTENANCE_H: self._options.get(CONF_MAINTENANCE_H, 0), CONF_ICONS: _icon_defaults(self._options.get(CONF_ICONS, {}), profile), } return self.async_show_form( step_id="extras", - data_schema=_extras_schema(defaults, has_power=has_power), + data_schema=_extras_schema(defaults, has_power=has_power, washdata_choices=washdata), ) diff --git a/custom_components/advanced_device/config_mapping.py b/custom_components/advanced_device/config_mapping.py index 693b9a5..015c46d 100644 --- a/custom_components/advanced_device/config_mapping.py +++ b/custom_components/advanced_device/config_mapping.py @@ -20,6 +20,7 @@ CONF_SMOOTHING_S, CONF_STANDBY_S, CONF_STANDBY_W, + CONF_WASHDATA_ENTRY, DEFAULT_LOCK_DEFAULT_MIN, ) from .core.model import MachineConfig, PowerConfig @@ -30,7 +31,8 @@ def build_machine_config(data: Mapping, options: Mapping) -> MachineConfig: """Build a MachineConfig from entry data and options. Power fields fall back to the selected profile. Protection is forced off - when the device has no power sensor. + when the device has no power sensor. WashData is requested by the + washdata_entry option; the runtime drops it if the entry is missing. """ has_power = bool(data.get(CONF_POWER_ENTITY)) profile = get_profile(options.get(CONF_PROFILE, "generic")) @@ -65,4 +67,5 @@ def build_machine_config(data: Mapping, options: Mapping) -> MachineConfig: auto_off_s=auto_off_min * 60 if has_power else 0, max_cycle_s=max_cycle_min * 60 if has_power else 0, maintenance_interval_h=float(options.get(CONF_MAINTENANCE_H, 0)), + washdata=bool(options.get(CONF_WASHDATA_ENTRY)), ) diff --git a/custom_components/advanced_device/const.py b/custom_components/advanced_device/const.py index a27591f..3e0ee6d 100644 --- a/custom_components/advanced_device/const.py +++ b/custom_components/advanced_device/const.py @@ -27,6 +27,6 @@ CONF_MAX_CYCLE_MIN = "max_cycle_min" CONF_MAINTENANCE_H = "maintenance_h" CONF_ICONS = "icons" -CONF_WASHDATA_ENTRY = "washdata_entry" # Platzhalter, Feld folgt mit ha_washdata (Task 17) +CONF_WASHDATA_ENTRY = "washdata_entry" # Options: entry_id of a ha_washdata config entry DEFAULT_LOCK_DEFAULT_MIN = 60 diff --git a/custom_components/advanced_device/device_trigger.py b/custom_components/advanced_device/device_trigger.py index c0b42a6..81b2a19 100644 --- a/custom_components/advanced_device/device_trigger.py +++ b/custom_components/advanced_device/device_trigger.py @@ -22,7 +22,7 @@ from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo from homeassistant.helpers.typing import ConfigType -from .const import CONF_POWER_ENTITY, DOMAIN +from .const import CONF_POWER_ENTITY, CONF_WASHDATA_ENTRY, DOMAIN from .core.model import Status from .runtime import AdvancedDeviceConfigEntry @@ -67,9 +67,8 @@ async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict[s return [] types: list[str] = [TRIGGER_SHUTDOWN_BLOCKED, TRIGGER_STATUS_CHANGED] - if entry.data.get(CONF_POWER_ENTITY): + if entry.data.get(CONF_POWER_ENTITY) or entry.options.get(CONF_WASHDATA_ENTRY): types = [TRIGGER_CYCLE_STARTED, TRIGGER_CYCLE_FINISHED, *types] - # WashData cycle triggers are added here in Task 17 (CONF_WASHDATA_ENTRY). triggers: list[dict[str, Any]] = [] for trigger_type in types: diff --git a/custom_components/advanced_device/entity.py b/custom_components/advanced_device/entity.py index 731b6b9..f8a6b84 100644 --- a/custom_components/advanced_device/entity.py +++ b/custom_components/advanced_device/entity.py @@ -6,7 +6,13 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity -from .const import CONF_MAINTENANCE_H, CONF_POWER_ENTITY, CONF_PRICE_ENTITY, DOMAIN +from .const import ( + CONF_MAINTENANCE_H, + CONF_POWER_ENTITY, + CONF_PRICE_ENTITY, + CONF_WASHDATA_ENTRY, + DOMAIN, +) from .runtime import AdvancedDeviceConfigEntry @@ -32,6 +38,8 @@ def expected_keys(entry: AdvancedDeviceConfigEntry) -> set[str]: if entry.options.get(CONF_PRICE_ENTITY): keys.add("last_cycle_cost") keys |= {"operating_hours", "operating_hours_since_maintenance"} + if entry.options.get(CONF_WASHDATA_ENTRY): + keys |= {"washdata_program", "washdata_time_remaining", "washdata_progress"} if float(entry.options.get(CONF_MAINTENANCE_H, 0)) > 0: keys |= {"maintenance_due", "reset_maintenance"} return keys diff --git a/custom_components/advanced_device/runtime.py b/custom_components/advanced_device/runtime.py index 272fc0a..8e52937 100644 --- a/custom_components/advanced_device/runtime.py +++ b/custom_components/advanced_device/runtime.py @@ -6,6 +6,7 @@ import logging import math from collections.abc import Callable +from dataclasses import replace from datetime import datetime from typing import Any @@ -13,6 +14,7 @@ from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import Event, EventStateChangedData, HomeAssistant, State, callback from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.event import async_track_point_in_time, async_track_state_change_event from homeassistant.helpers.storage import Store @@ -25,10 +27,12 @@ CONF_PRICE_ENTITY, CONF_PROTECTION, CONF_SWITCH_ENTITY, + CONF_WASHDATA_ENTRY, DOMAIN, ) from .core.model import FireEvent, PlugState, RunPreAction, SwitchPlug from .core.state_machine import DeviceMachine +from .washdata import WashDataLink _LOGGER = logging.getLogger(__name__) @@ -37,6 +41,8 @@ _STORE_VERSION = 1 _SAVE_DELAY_S = 30 +_WASHDATA_ISSUE = "washdata_missing" + _PRE_ACTION_CALLS: dict[str, tuple[str, str]] = { "script": ("script", "turn_on"), "button": ("button", "press"), @@ -83,7 +89,9 @@ def __init__(self, hass: HomeAssistant, entry: AdvancedDeviceConfigEntry) -> Non self.entry = entry self.signal = f"{DOMAIN}_{entry.entry_id}" self.device_id = "" - self.machine = DeviceMachine(build_machine_config(entry.data, entry.options), _now()) + self._config = build_machine_config(entry.data, entry.options) + self.machine = DeviceMachine(self._config, _now()) + self._washdata: WashDataLink | None = None self._unsubs: list[Callable[[], None]] = [] self._timer: Callable[[], None] | None = None self._store: Store[dict[str, Any]] = Store( @@ -99,6 +107,8 @@ async def async_start(self) -> None: ) self.device_id = device.id if device else "" + self._washdata = await self._async_start_washdata() + data = await self._store.async_load() if data: self.machine.restore(data.get("machine", {}), _now()) @@ -137,9 +147,44 @@ async def async_stop(self) -> None: for unsub in self._unsubs: unsub() self._unsubs.clear() + if self._washdata is not None: + self._washdata.async_stop() self._cancel_timer() await self._store.async_save(self._data_to_save()) + @property + def washdata(self) -> WashDataLink | None: + """The active WashData link, or None when not configured or not found.""" + return self._washdata + + async def _async_start_washdata(self) -> WashDataLink | None: + """Link the configured WashData entry. Without it, fall back to the own logic.""" + issue_id = f"{_WASHDATA_ISSUE}_{self.entry.entry_id}" + washdata_entry = self.entry.options.get(CONF_WASHDATA_ENTRY) + if not washdata_entry: + ir.async_delete_issue(self.hass, DOMAIN, issue_id) + return None + + link = WashDataLink( + self.hass, washdata_entry, self._on_washdata_state, self._on_washdata_cycle + ) + if await link.async_start(): + ir.async_delete_issue(self.hass, DOMAIN, issue_id) + return link + + _LOGGER.warning("WashData entry %s not found, using own cycle logic", washdata_entry) + ir.async_create_issue( + self.hass, + DOMAIN, + issue_id, + is_fixable=False, + severity=ir.IssueSeverity.WARNING, + translation_key=_WASHDATA_ISSUE, + translation_placeholders={"name": self.entry.title}, + ) + self.machine = DeviceMachine(replace(self._config, washdata=False), _now()) + return None + # ----- user commands --------------------------------------------------- async def async_turn_on(self) -> None: @@ -184,6 +229,14 @@ def _on_price_event(self, event: Event[EventStateChangedData]) -> None: self.machine.set_price(_number(event.data["new_state"])) self._after_input([]) + @callback + def _on_washdata_state(self, state: str | None) -> None: + self._after_input(self.machine.on_washdata_state(_now(), state)) + + @callback + def _on_washdata_cycle(self, started: bool) -> None: + self._after_input(self.machine.on_washdata_cycle(_now(), started)) + @callback def _on_timer(self, _now_dt: datetime) -> None: self._timer = None diff --git a/custom_components/advanced_device/sensor.py b/custom_components/advanced_device/sensor.py index 929285b..cbedab2 100644 --- a/custom_components/advanced_device/sensor.py +++ b/custom_components/advanced_device/sensor.py @@ -9,14 +9,24 @@ SensorEntity, SensorStateClass, ) -from homeassistant.const import EntityCategory, UnitOfEnergy, UnitOfTime -from homeassistant.core import HomeAssistant +from homeassistant.const import ( + STATE_UNAVAILABLE, + STATE_UNKNOWN, + EntityCategory, + UnitOfEnergy, + UnitOfTime, +) +from homeassistant.core import Event, EventStateChangedData, HomeAssistant, State, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.event import async_track_state_change_event from homeassistant.util import dt as dt_util from .core.model import Status from .entity import AdvancedDeviceEntity, expected_keys from .runtime import AdvancedDeviceConfigEntry +from .washdata import MIRROR_SENSORS + +_NUMERIC_MIRRORS = frozenset({"washdata_time_remaining", "washdata_progress"}) async def async_setup_entry( @@ -46,6 +56,12 @@ async def async_setup_entry( entities.append(AdvancedDeviceOperatingHoursSensor(entry)) if "operating_hours_since_maintenance" in keys: entities.append(AdvancedDeviceOperatingHoursSinceMaintenanceSensor(entry)) + link = entry.runtime_data.washdata + if link is not None: + for key, source_key in MIRROR_SENSORS.items(): + source = link.entity_ids.get(source_key) + if key in keys and source is not None: + entities.append(AdvancedDeviceWashDataSensor(entry, key, source)) async_add_entities(entities) @@ -196,3 +212,52 @@ def __init__(self, entry: AdvancedDeviceConfigEntry) -> None: @property def native_value(self) -> float: return round(self._runtime.machine.operating_s_since_maintenance / 3600, 2) + + +class AdvancedDeviceWashDataSensor(AdvancedDeviceEntity, SensorEntity): + """Mirror of a WashData sensor: state, unit and device class follow the source.""" + + def __init__(self, entry: AdvancedDeviceConfigEntry, key: str, source_entity_id: str) -> None: + super().__init__(entry, key) + self._source = source_entity_id + self._numeric = key in _NUMERIC_MIRRORS + if self._numeric: + self._attr_state_class = SensorStateClass.MEASUREMENT + + def _source_state(self) -> State | None: + return self.hass.states.get(self._source) + + @property + def native_unit_of_measurement(self) -> str | None: + source = self._source_state() + return None if source is None else source.attributes.get("unit_of_measurement") + + @property + def device_class(self) -> str | None: + source = self._source_state() + device_class = None if source is None else source.attributes.get("device_class") + # WashData's program enum has dynamic options that cannot be mirrored. + return None if device_class == SensorDeviceClass.ENUM else device_class + + @property + def native_value(self) -> str | float | None: + source = self._source_state() + if source is None or source.state in (STATE_UNAVAILABLE, STATE_UNKNOWN): + return None + if not self._numeric: + return source.state + try: + return float(source.state) + except ValueError: + return None + + async def async_added_to_hass(self) -> None: + """Refresh the mirror whenever the WashData entity changes.""" + await super().async_added_to_hass() + self.async_on_remove( + async_track_state_change_event(self.hass, [self._source], self._on_source_change) + ) + + @callback + def _on_source_change(self, _event: Event[EventStateChangedData]) -> None: + self.async_write_ha_state() diff --git a/custom_components/advanced_device/strings.json b/custom_components/advanced_device/strings.json index ffb17c3..1a9888a 100644 --- a/custom_components/advanced_device/strings.json +++ b/custom_components/advanced_device/strings.json @@ -66,12 +66,14 @@ "icon_idle": "Icon: idle", "icon_running": "Icon: running", "icon_shutting_down": "Icon: shutting down", - "icon_unavailable": "Icon: unavailable" + "icon_unavailable": "Icon: unavailable", + "washdata_entry": "WashData device (optional)" }, "data_description": { "price_entity": "Electricity price for cost calculation: a sensor or an input number.", "auto_off_min": "Switches the device off after this long in uninterrupted standby.", - "maintenance_h": "Operating hours until maintenance is due. 0 disables the reminder." + "maintenance_h": "Operating hours until maintenance is due. 0 disables the reminder.", + "washdata_entry": "Takes cycles and the release state from a WashData device (ha_washdata) instead of the own thresholds." } }, "reconfigure": { @@ -158,7 +160,11 @@ "icon_idle": "Icon: idle", "icon_running": "Icon: running", "icon_shutting_down": "Icon: shutting down", - "icon_unavailable": "Icon: unavailable" + "icon_unavailable": "Icon: unavailable", + "washdata_entry": "WashData device (optional)" + }, + "data_description": { + "washdata_entry": "Takes cycles and the release state from a WashData device (ha_washdata) instead of the own thresholds." } } }, @@ -216,6 +222,15 @@ }, "one_time_lock_until": { "name": "One-time lock until" + }, + "washdata_program": { + "name": "WashData program" + }, + "washdata_time_remaining": { + "name": "WashData time remaining" + }, + "washdata_progress": { + "name": "WashData progress" } }, "binary_sensor": { @@ -292,5 +307,11 @@ "extra_fields": { "to": "To status" } + }, + "issues": { + "washdata_missing": { + "title": "WashData device not found", + "description": "The device {name} is linked to a WashData device that no longer exists. Its own cycle detection is used until the link is changed in the extras settings." + } } } diff --git a/custom_components/advanced_device/translations/de.json b/custom_components/advanced_device/translations/de.json index e079c74..8f83f9b 100644 --- a/custom_components/advanced_device/translations/de.json +++ b/custom_components/advanced_device/translations/de.json @@ -66,12 +66,14 @@ "icon_idle": "Icon: Leerlauf", "icon_running": "Icon: Läuft", "icon_shutting_down": "Icon: Schaltet ab", - "icon_unavailable": "Icon: Nicht verfügbar" + "icon_unavailable": "Icon: Nicht verfügbar", + "washdata_entry": "WashData-Gerät (optional)" }, "data_description": { "price_entity": "Strompreis für die Kostenberechnung: ein Sensor oder eine Input-Number.", "auto_off_min": "Schaltet das Gerät nach dieser Zeit ununterbrochenem Standby aus.", - "maintenance_h": "Betriebsstunden bis zur Wartung. 0 deaktiviert die Erinnerung." + "maintenance_h": "Betriebsstunden bis zur Wartung. 0 deaktiviert die Erinnerung.", + "washdata_entry": "Übernimmt Zyklen und die Freigabe von einem WashData-Gerät (ha_washdata) statt der eigenen Schwellwerte." } }, "reconfigure": { @@ -158,7 +160,11 @@ "icon_idle": "Icon: Leerlauf", "icon_running": "Icon: Läuft", "icon_shutting_down": "Icon: Schaltet ab", - "icon_unavailable": "Icon: Nicht verfügbar" + "icon_unavailable": "Icon: Nicht verfügbar", + "washdata_entry": "WashData-Gerät (optional)" + }, + "data_description": { + "washdata_entry": "Übernimmt Zyklen und die Freigabe von einem WashData-Gerät (ha_washdata) statt der eigenen Schwellwerte." } } }, @@ -216,6 +222,15 @@ }, "one_time_lock_until": { "name": "Einmal-Sperre bis" + }, + "washdata_program": { + "name": "WashData Programm" + }, + "washdata_time_remaining": { + "name": "WashData Restzeit" + }, + "washdata_progress": { + "name": "WashData Fortschritt" } }, "binary_sensor": { @@ -292,5 +307,11 @@ "extra_fields": { "to": "Neuer Status" } + }, + "issues": { + "washdata_missing": { + "title": "WashData-Gerät nicht gefunden", + "description": "Das Gerät {name} ist mit einem WashData-Gerät verknüpft, das nicht mehr existiert. Bis die Verknüpfung in den Extras geändert wird, gilt die eigene Zyklenerkennung." + } } } diff --git a/custom_components/advanced_device/translations/en.json b/custom_components/advanced_device/translations/en.json index ffb17c3..1a9888a 100644 --- a/custom_components/advanced_device/translations/en.json +++ b/custom_components/advanced_device/translations/en.json @@ -66,12 +66,14 @@ "icon_idle": "Icon: idle", "icon_running": "Icon: running", "icon_shutting_down": "Icon: shutting down", - "icon_unavailable": "Icon: unavailable" + "icon_unavailable": "Icon: unavailable", + "washdata_entry": "WashData device (optional)" }, "data_description": { "price_entity": "Electricity price for cost calculation: a sensor or an input number.", "auto_off_min": "Switches the device off after this long in uninterrupted standby.", - "maintenance_h": "Operating hours until maintenance is due. 0 disables the reminder." + "maintenance_h": "Operating hours until maintenance is due. 0 disables the reminder.", + "washdata_entry": "Takes cycles and the release state from a WashData device (ha_washdata) instead of the own thresholds." } }, "reconfigure": { @@ -158,7 +160,11 @@ "icon_idle": "Icon: idle", "icon_running": "Icon: running", "icon_shutting_down": "Icon: shutting down", - "icon_unavailable": "Icon: unavailable" + "icon_unavailable": "Icon: unavailable", + "washdata_entry": "WashData device (optional)" + }, + "data_description": { + "washdata_entry": "Takes cycles and the release state from a WashData device (ha_washdata) instead of the own thresholds." } } }, @@ -216,6 +222,15 @@ }, "one_time_lock_until": { "name": "One-time lock until" + }, + "washdata_program": { + "name": "WashData program" + }, + "washdata_time_remaining": { + "name": "WashData time remaining" + }, + "washdata_progress": { + "name": "WashData progress" } }, "binary_sensor": { @@ -292,5 +307,11 @@ "extra_fields": { "to": "To status" } + }, + "issues": { + "washdata_missing": { + "title": "WashData device not found", + "description": "The device {name} is linked to a WashData device that no longer exists. Its own cycle detection is used until the link is changed in the extras settings." + } } } diff --git a/custom_components/advanced_device/washdata.py b/custom_components/advanced_device/washdata.py new file mode 100644 index 0000000..0796b01 --- /dev/null +++ b/custom_components/advanced_device/washdata.py @@ -0,0 +1,101 @@ +"""Optional coupling to a ha_washdata config entry. + +Reads only public interfaces of WashData: the cycle events (filtered by the +entry id in their data) and the entities of the WashData device, found through +the entity registry by ``config_entry_id`` and ``translation_key``. +""" + +from __future__ import annotations + +import logging +from collections.abc import Callable + +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.event import async_track_state_change_event + +_LOGGER = logging.getLogger(__name__) + +WASHDATA_DOMAIN = "ha_washdata" +EVENT_CYCLE_STARTED = "ha_washdata_cycle_started" +EVENT_CYCLE_ENDED = "ha_washdata_cycle_ended" + +KEY_STATE = "washer_state" +# Own sensor key -> WashData translation_key whose state it mirrors. +MIRROR_SENSORS: dict[str, str] = { + "washdata_program": "washer_program", + "washdata_time_remaining": "time_remaining", + "washdata_progress": "cycle_progress", +} +_TRANSLATION_KEYS = (KEY_STATE, *MIRROR_SENSORS.values()) + + +class WashDataLink: + """Forwards WashData state and cycle changes to the runtime.""" + + def __init__( + self, + hass: HomeAssistant, + washdata_entry_id: str, + on_state: Callable[[str | None], None], + on_cycle: Callable[[bool], None], + ) -> None: + self.hass = hass + self.washdata_entry_id = washdata_entry_id + self._on_state = on_state + self._on_cycle = on_cycle + self.entity_ids: dict[str, str] = {} + self._unsubs: list[Callable[[], None]] = [] + + async def async_start(self) -> bool: + """Subscribe to the cycle events and the state entity. False if the entry is missing.""" + if self.hass.config_entries.async_get_entry(self.washdata_entry_id) is None: + return False + + ent_reg = er.async_get(self.hass) + for reg_entry in er.async_entries_for_config_entry(ent_reg, self.washdata_entry_id): + if reg_entry.translation_key in _TRANSLATION_KEYS: + self.entity_ids[reg_entry.translation_key] = reg_entry.entity_id + + for event_type in (EVENT_CYCLE_STARTED, EVENT_CYCLE_ENDED): + self._unsubs.append( + self.hass.bus.async_listen(event_type, self._make_cycle_handler(event_type)) + ) + + state_entity = self.entity_ids.get(KEY_STATE) + if state_entity is not None: + self._unsubs.append( + async_track_state_change_event(self.hass, [state_entity], self._on_state_event) + ) + current = self.hass.states.get(state_entity) + self._on_state(_state_value(current.state) if current else None) + else: + _LOGGER.debug("WashData entry %s has no state entity yet", self.washdata_entry_id) + return True + + @callback + def async_stop(self) -> None: + """Remove all listeners.""" + for unsub in self._unsubs: + unsub() + self._unsubs.clear() + + def _make_cycle_handler(self, event_type: str) -> Callable[[Event], None]: + started = event_type == EVENT_CYCLE_STARTED + + @callback + def _handle(event: Event) -> None: + if event.data.get("entry_id") == self.washdata_entry_id: + self._on_cycle(started) + + return _handle + + @callback + def _on_state_event(self, event: Event[EventStateChangedData]) -> None: + new_state = event.data["new_state"] + self._on_state(_state_value(new_state.state) if new_state else None) + + +def _state_value(raw: str) -> str | None: + return None if raw in (STATE_UNAVAILABLE, STATE_UNKNOWN) else raw diff --git a/tests/integration/test_washdata.py b/tests/integration/test_washdata.py new file mode 100644 index 0000000..252f237 --- /dev/null +++ b/tests/integration/test_washdata.py @@ -0,0 +1,230 @@ +"""Optional WashData coupling: field, cycle events, release, mirror sensors, fallback.""" + +from dataclasses import asdict +from datetime import timedelta +from unittest.mock import patch + +from homeassistant import config_entries +from homeassistant.config_entries import ConfigEntryState +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import issue_registry as ir +from pytest_homeassistant_custom_component.common import ( + MockConfigEntry, + async_capture_events, +) + +from custom_components.advanced_device.const import ( + CONF_POWER_ENTITY, + CONF_SWITCH_ENTITY, + CONF_WASHDATA_ENTRY, + DOMAIN, +) +from custom_components.advanced_device.core.profiles import get_profile + +from .cycle_helpers import POWER, SWITCH, run_cycle, set_power + +WASHDATA = "ha_washdata" +WD_KEYS = ("washer_state", "washer_program", "time_remaining", "cycle_progress") + + +def _options(**overrides): + options = { + "profile": "generic", + "hide_original": True, + "protection": False, + "delay_s": 0, + "max_wait_s": 0, + "reenable": False, + "lock_default_min": 60, + **asdict(get_profile("generic").power), + } + options.update(overrides) + return options + + +def _wd_entities(hass, washdata): + """Register the WashData entities with their translation keys.""" + ent_reg = er.async_get(hass) + return { + key: ent_reg.async_get_or_create( + "sensor", + WASHDATA, + f"{washdata.entry_id}_{key}", + config_entry=washdata, + translation_key=key, + suggested_object_id=f"washer_{key}", + ).entity_id + for key in WD_KEYS + } + + +def _entry(hass, washdata, **overrides): + """Advanced Device entry linked to ``washdata``; ``overrides`` go into the options.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="Washer", + data={CONF_SWITCH_ENTITY: SWITCH, CONF_POWER_ENTITY: POWER}, + options=_options(**{CONF_WASHDATA_ENTRY: washdata.entry_id}, **overrides), + unique_id=SWITCH, + ) + entry.add_to_hass(hass) + return entry + + +async def _setup(hass, entry): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +async def _extras_keys(hass) -> set: + with patch("custom_components.advanced_device.async_setup_entry", return_value=True): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "name": "Washer", + "profile": "generic", + "switch_entity": SWITCH, + "hide_original": True, + }, + ) + assert result["step_id"] == "extras" + keys = {getattr(marker, "schema", marker) for marker in result["data_schema"].schema} + hass.config_entries.flow.async_abort(result["flow_id"]) + return keys + + +async def test_field_hidden_without_washdata(hass): + assert CONF_WASHDATA_ENTRY not in await _extras_keys(hass) + + MockConfigEntry(domain=WASHDATA, title="Washer WD").add_to_hass(hass) + + assert CONF_WASHDATA_ENTRY in await _extras_keys(hass) + + +async def test_cycles_follow_washdata_events(hass, freezer, plug_device): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + _wd_entities(hass, washdata) + entry = _entry(hass, washdata) + await _setup(hass, entry) + + started = async_capture_events(hass, "advanced_device_cycle_started") + finished = async_capture_events(hass, "advanced_device_cycle_finished") + + hass.bus.async_fire("ha_washdata_cycle_started", {"entry_id": "other-entry"}) + await hass.async_block_till_done() + assert started == [] + + hass.bus.async_fire("ha_washdata_cycle_started", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + assert len(started) == 1 + + freezer.tick(timedelta(seconds=120)) + hass.bus.async_fire("ha_washdata_cycle_ended", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + assert len(finished) == 1 + + +async def test_release_only_on_finished(hass, freezer, plug_device, service_calls): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + wd = _wd_entities(hass, washdata) + entry = _entry(hass, washdata, protection=True) + hass.states.async_set(SWITCH, "on") + hass.states.async_set(wd["washer_state"], "running") + await _setup(hass, entry) + + hass.bus.async_fire("ha_washdata_cycle_started", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + await set_power(hass, freezer, 50, 60) + + # User requests off while WashData says running: the plug must stay on. + await entry.runtime_data.async_turn_off() + await set_power(hass, freezer, 0, 120) + assert not [c for c in service_calls if c[1] == "turn_off"] + + hass.states.async_set(wd["washer_state"], "finished") + await hass.async_block_till_done() + assert [c for c in service_calls if c[1] == "turn_off"] + + +async def test_external_off_tolerated_when_paused(hass, freezer, plug_device, service_calls): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + wd = _wd_entities(hass, washdata) + entry = _entry(hass, washdata, protection=True, reenable=True) + hass.states.async_set(SWITCH, "on") + await _setup(hass, entry) + + hass.bus.async_fire("ha_washdata_cycle_started", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + hass.states.async_set(wd["washer_state"], "paused") + await hass.async_block_till_done() + + hass.states.async_set(SWITCH, "off") + await hass.async_block_till_done() + assert not [c for c in service_calls if c[1] == "turn_on"] + + # Contrast: while running, an external off is re-enabled. + hass.states.async_set(SWITCH, "on") + hass.states.async_set(wd["washer_state"], "running") + await hass.async_block_till_done() + hass.states.async_set(SWITCH, "off") + await hass.async_block_till_done() + assert [c for c in service_calls if c[1] == "turn_on"] + + +async def test_mirror_sensors(hass, plug_device): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + wd = _wd_entities(hass, washdata) + hass.states.async_set(wd["washer_program"], "cotton") + hass.states.async_set( + wd["time_remaining"], "42", {"unit_of_measurement": "min", "device_class": "duration"} + ) + hass.states.async_set(wd["cycle_progress"], "55", {"unit_of_measurement": "%"}) + entry = _entry(hass, washdata) + await _setup(hass, entry) + + ent_reg = er.async_get(hass) + program = ent_reg.async_get_entity_id("sensor", DOMAIN, f"{entry.entry_id}_washdata_program") + remaining = ent_reg.async_get_entity_id( + "sensor", DOMAIN, f"{entry.entry_id}_washdata_time_remaining" + ) + progress = ent_reg.async_get_entity_id("sensor", DOMAIN, f"{entry.entry_id}_washdata_progress") + + assert hass.states.get(program).state == "cotton" + assert hass.states.get(remaining).state == "42.0" + assert hass.states.get(remaining).attributes["unit_of_measurement"] == "min" + assert hass.states.get(remaining).attributes["device_class"] == "duration" + assert hass.states.get(progress).state == "55.0" + + hass.states.async_set(wd["cycle_progress"], "80", {"unit_of_measurement": "%"}) + await hass.async_block_till_done() + assert hass.states.get(progress).state == "80.0" + + +async def test_missing_washdata_creates_repair_and_falls_back(hass, freezer, plug_device): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + _wd_entities(hass, washdata) + entry = _entry(hass, washdata) + await hass.config_entries.async_remove(washdata.entry_id) + await hass.async_block_till_done() + + await _setup(hass, entry) + + assert entry.state is ConfigEntryState.LOADED + assert entry.runtime_data.washdata is None + issue = ir.async_get(hass).async_get_issue(DOMAIN, f"washdata_missing_{entry.entry_id}") + assert issue is not None + assert issue.translation_key == "washdata_missing" + + started = async_capture_events(hass, "advanced_device_cycle_started") + finished = async_capture_events(hass, "advanced_device_cycle_finished") + await run_cycle(hass, freezer) + assert len(started) == 1 + assert len(finished) == 1 From 0f03529e9bdc8560ea5aac2fdc6234ec685f8402 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 22:51:45 +0100 Subject: [PATCH 2/8] docs: readme, reference, migration Co-Authored-By: Claude Sonnet 5.5 --- README.md | 87 ++++++- template.yaml => docs/blueprint-template.yaml | 0 docs/integration.md | 226 ++++++++++++++++++ docs/migration-from-blueprint.md | 78 ++++++ info.md | 6 +- 5 files changed, 394 insertions(+), 3 deletions(-) rename template.yaml => docs/blueprint-template.yaml (100%) create mode 100644 docs/integration.md create mode 100644 docs/migration-from-blueprint.md diff --git a/README.md b/README.md index 31f4ca8..d74afdd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,88 @@ +Advanced Device icon + # Advanced Device -Home Assistant custom integration for per-device cycle and state tracking (work in progress). +A Home Assistant custom integration that turns a switchable power plug with a power sensor into its own smart device for the appliance plugged into it, such as a washing machine, PC, TV or printer. + +## Concept + +Each configured plug becomes one Home Assistant device with its own entities. The plug's original switch is hidden, and the new device is the one you control. Status, shutdown protection, cycles and maintenance are tracked and exposed by the integration itself, not written as attributes into entities owned by other integrations. + +The focus is on **control, status and protection**. It is not a program recognition engine. For detecting washing programs, remaining time and cycle phases, use [WashData](https://github.com/3dg1luk43/ha_washdata), which this integration can be linked to. + +## Features + +- **Status from power.** `off`, `starting`, `on`, `standby`, `idle`, `running`, `shutting_down` and `unavailable`, derived from smoothed power with configurable thresholds and durations. +- **Shutdown lock.** A switch-off waits until the appliance is in standby. An optional action runs first (for example a script that enables the appliance's own shutdown), and a delay and maximum wait can be set. +- **Re-enable after external off.** If the plug is switched off by something other than this integration while the device is running, it is switched back on, up to three times. +- **One-time lock.** Blocks the next switch-off once, with an optional expiry. Useful for a nightly "everything off" automation. +- **Cycles and statistics.** Start and end of each run, with duration, energy and cost (when a price sensor is set). +- **Auto-off.** Switches the plug off after a configurable time in standby. +- **Device profiles.** Starting values for common appliance types. +- **Problem and maintenance.** A problem sensor for a missing power sensor or an overlong cycle, and operating hours with a maintenance reminder. +- **Automation hooks.** Events, device triggers and actions for use in automations. +- **Fully configurable in the UI.** German and English translations. + +## Installation + +[![Open your Home Assistant instance and open this repository in the HACS Integration category.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=Developer-Simon&repository=ha-advanced-device&category=integration) + +1. In HACS, open **Custom repositories** and add `https://github.com/Developer-Simon/ha-advanced-device` with category **Integration**. +2. Search for **Advanced Device** in HACS and download it. +3. Restart Home Assistant. + +## Setup + +1. Go to **Settings → Devices & Services → Add Integration** and search for **Advanced Device**. +2. **Device:** enter a name, choose a profile, select the plug switch and, optionally, the power sensor. Keep "Hide original switch" enabled to use only this integration's switch. +3. **Power thresholds:** only if a power sensor is set. Values are prefilled from the profile. +4. **Shutdown lock:** optional. Requires a standby threshold above 0 W. +5. **Extras:** price sensor, auto-off, maximum cycle duration, maintenance interval, WashData link and status icons. + +Every option except the plug switch and power sensor can be changed later under **Configure**. The plug switch and power sensor are changed under **Reconfigure**. + +Without a power sensor, the device only tracks on and off. Shutdown lock, cycles and power-based functions are not available. + +## Profiles + +Profiles set starting values. All values can be changed afterwards. + +| Profile | Standby (W / s) | Idle (s) | Running (W / s) | Smoothing (s) | Min. cycle | Shutdown lock | Auto-off | +|---|---|---|---|---|---|---|---| +| Generic | 1.0 / 60 | 120 | 10.0 / 30 | 10 | 1 min | no | off | +| Washing machine | 2.5 / 300 | 600 | 15.0 / 60 | 30 | 10 min | yes | 60 min | +| Dryer | 1.5 / 300 | 300 | 100.0 / 60 | 30 | 10 min | yes | 60 min | +| Dishwasher | 1.0 / 300 | 300 | 30.0 / 60 | 30 | 15 min | yes | 60 min | +| PC | 5.0 / 60 | 600 | 40.0 / 30 | 20 | 1 min | no | off | +| TV | 3.0 / 60 | 300 | 80.0 / 60 | 30 | 5 min | no | off | +| Printer | 1.0 / 120 | 300 | 20.0 / 10 | 5 | 30 s | no | 15 min | +| Coffee machine | 0.5 / 60 | 180 | 800.0 / 30 | 10 | 1 min | no | 30 min | + +The values are starting points based on typical consumption, not measurements. Measurements from real devices are welcome through the "Device profile" issue template. + +## WashData + +[WashData](https://github.com/3dg1luk43/ha_washdata) (`ha_washdata`) detects cycles and programs. If you select a WashData device under **Extras**: + +- Cycles and cycle events follow WashData instead of this integration's own thresholds. +- The shutdown lock is released only when WashData reports `finished`, `clean`, `off` or `idle`. It is never released while WashData reports `running`, `paused`, `user_paused`, `ending` or `anti_wrinkle`. +- Program, time remaining and progress sensors are added to the device and mirror WashData. + +**Recommendation:** in WashData, use the **original plug switch** (the one this integration hides) as the pause/resume switch, not the Advanced Device switch. Pausing turns the plug off from outside this integration. While WashData reports a pause, the integration tolerates that off and does not switch the plug back on. + +If the linked WashData device is removed, the coupling is inactive, a repair issue is shown, and the integration uses its own logic. Setup does not fail. + +**Program detection?** Use WashData. This integration does not recognise programs. + +## Documentation + +- [Reference: configuration, entities, events, actions and triggers](docs/integration.md) +- [Migrating from the blueprint](docs/migration-from-blueprint.md) + +## Built with AI + +This integration was written with AI assistance and is reviewed and maintained by [@Developer-Simon](https://github.com/Developer-Simon). See the [AI disclaimer](AI-DISCLAIMER.md) for details and for the disclosure rules that apply to contributions. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/template.yaml b/docs/blueprint-template.yaml similarity index 100% rename from template.yaml rename to docs/blueprint-template.yaml diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..9bb7c8a --- /dev/null +++ b/docs/integration.md @@ -0,0 +1,226 @@ +# Advanced Device: configuration, entities, events and actions + +Reference for the Advanced Device integration. For installation and an overview, see the [README](../README.md). + +## Configuration + +Add the integration under **Settings → Devices & Services → Add Integration → Advanced Device**. Each config entry is one plug and creates one device. + +Steps that do not apply are skipped. Without a power sensor, the power and shutdown-lock steps are not shown, and the auto-off and cycle-limit fields are hidden. + +### Add device (`user`) + +| Field | Required | Default | Notes | +|---|---|---|---| +| Name | yes | | Name of the new device. Also the name of the main switch. | +| Device profile | yes | Generic | Starting values for the following steps. See the profile table in the README. | +| Plug switch | yes | | A `switch` entity. | +| Power sensor | no | | A `sensor` with device class `power`. Without it, only on and off are tracked. | +| Hide original switch | yes | on | Hides the plug's original switch. Restored when the entry is removed. | + +### Power thresholds (`power`, only with a power sensor) + +| Field | Unit | Default | Meaning | +|---|---|---|---| +| Standby threshold | W | from profile | Below this power the device counts as standby once the standby duration is reached. Must not be above the running threshold. | +| Standby duration | s | from profile | How long the power must stay below the standby threshold. | +| Idle duration | s | from profile | How long the power must stay in the idle band before the status becomes `idle`. | +| Running threshold | W | from profile | Above this power the device counts as running once the running duration is reached. | +| Running duration | s | from profile | How long the power must stay above the running threshold. | +| Smoothing window | s | from profile | Moving average over this window. 0 uses the raw value. | + +Validation: the standby threshold must not be above the running threshold. + +### Shutdown lock (`protection`, only with a power sensor) + +| Field | Unit | Default | Meaning | +|---|---|---|---| +| Enable shutdown lock | | from profile | A switch-off waits until the device is in standby. | +| Action before switching off | | none | Optional. A `script`, `button` or `input_button` entity. It runs when a switch-off is requested, before waiting for standby. | +| Delay from standby to off | s | 0 | Extra wait after standby is reached. | +| Maximum wait | s | 0 | Longest time a switch-off waits for standby. 0 waits without limit. | +| Switch back on after external off | | off | See [Re-enable after external off](#re-enable-after-external-off). | +| Default expiry of one-time lock | min | 60 | Default duration of a one-time lock. 0 means the lock ends only when the device consumes power again. | + +Validation: the shutdown lock needs a standby threshold above 0 W. + +### Extras (`extras`) + +| Field | Unit | Default | Meaning | +|---|---|---|---| +| Electricity price sensor | | none | Optional `sensor` or `input_number` with the price per kWh. Enables the last cycle cost sensor. | +| Auto-off after standby | min | from profile | Switches the plug off after this long in uninterrupted standby. 0 disables it. | +| Maximum cycle duration | min | 0 | A longer cycle sets the problem sensor. 0 disables it. | +| Maintenance interval | operating hours | 0 | Reminder interval. 0 disables the reminder. | +| WashData device | | none | Only shown if `ha_washdata` is installed. See the README. | +| Icon per status | | from profile | One icon for each of the eight statuses. | + +## Options and reconfigure + +- **Configure** (options flow) changes profile, hide-original, thresholds, shutdown lock, extras and icons. The steps are the same as above, prefilled with the stored values. + - Changing the profile alone only stores the new profile key. + - **Apply profile values to thresholds and protection** overwrites thresholds and the shutdown lock with the profile's values. It is off by default. +- **Reconfigure** changes the plug switch and the power sensor. The device is reloaded afterwards. + +## Entities + +All entities belong to the device of the config entry. Entity IDs are derived from the device name. + +| Key | Platform | Condition | Notes | +|---|---|---|---| +| `main` | `switch` | always | Main switch, named after the device. Follows the plug, including during `shutting_down`. | +| `status` | `sensor` | always | Enum sensor with the states listed below. | +| `one_time_lock` | `switch` | always | One-time lock. | +| `one_time_lock_until` | `sensor` | always | Timestamp of the lock expiry. Empty when the lock is off or has no expiry. | +| `force_off` | `button` | always | Switches off now, ignoring the one-time lock. | +| `protection` | `switch` | power sensor | Shutdown lock (configuration category). | +| `shutdown_at` | `sensor` | power sensor | Timestamp of the planned shutdown. | +| `running` | `binary_sensor` | power sensor | On while a cycle is active. | +| `problem` | `binary_sensor` | power sensor | Device class `problem`. The reasons are in the `reasons` attribute. | +| `last_cycle_duration` | `sensor` | power sensor | Duration of the last cycle. | +| `last_cycle_energy` | `sensor` | power sensor | Energy of the last cycle. | +| `last_cycle_cost` | `sensor` | power sensor and price sensor | Cost of the last cycle. | +| `last_cycle_end` | `sensor` | power sensor | Timestamp of the end of the last cycle. | +| `cycles` | `sensor` | power sensor | Number of cycles (`total_increasing`). | +| `operating_hours` | `sensor` | always | Total operating hours (diagnostic). | +| `operating_hours_since_maintenance` | `sensor` | always | Operating hours since the last maintenance reset (diagnostic). | +| `maintenance_due` | `binary_sensor` | maintenance interval above 0 | On when the maintenance interval is reached. | +| `reset_maintenance` | `button` | maintenance interval above 0 | Resets the maintenance counter (configuration category). | +| `washdata_program` | `sensor` | WashData device | Mirrors the WashData program. | +| `washdata_time_remaining` | `sensor` | WashData device | Mirrors the WashData time remaining. | +| `washdata_progress` | `sensor` | WashData device | Mirrors the WashData progress. | + +Operating hours count the time in `running` when a power sensor is set. Without a power sensor, they count the time the plug is on. + +## Status values + +The `status` sensor reports one of these states. + +| State | Meaning | +|---|---| +| `off` | The plug is off. | +| `starting` | The plug is on, but the power has not been classified yet. | +| `on` | The plug is on and no standby threshold is used (no power sensor, or standby threshold 0). | +| `standby` | Smoothed power is below the standby threshold for at least the standby duration. | +| `idle` | Smoothed power is between the standby and running thresholds for at least the idle duration. | +| `running` | Smoothed power is at or above the running threshold for at least the running duration. | +| `shutting_down` | A switch-off was requested and is waiting for standby, the delay, or the pre-action. | +| `unavailable` | The plug switch is unavailable. | + +If the power sensor becomes unavailable, the status keeps its last value and the problem sensor reports `power_missing`. The integration does not switch the plug off in this case. + +## Events + +Events are fired on the Home Assistant event bus. Every event contains these fields: + +| Field | Content | +|---|---| +| `entry_id` | Config entry ID. | +| `device_id` | Device registry ID. | +| `name` | Name of the device. | + +Additional fields per event: + +| Event | Additional fields | When | +|---|---|---| +| `advanced_device_cycle_started` | none | A cycle starts (transition to `running`). | +| `advanced_device_cycle_finished` | `duration_s`, `energy_kwh`, `cost` | A cycle ends. `cost` is empty without a price sensor. Cycles shorter than the profile's minimum duration are not counted. | +| `advanced_device_shutdown_blocked` | `reason`: `one_time_lock` or `external_off` | A switch-off was blocked by the one-time lock, or an external off was reversed. | +| `advanced_device_shutdown_aborted` | none | A switch-off was cancelled because the maximum wait was exceeded. The plug stays on. | + +Example automation trigger: + +```yaml +trigger: + - platform: event + event_type: advanced_device_cycle_finished + event_data: + entry_id: 01J0EXAMPLE +``` + +## Actions + +All actions take a device target. Select Advanced Device devices in the UI, or pass `device_id` as a list. + +| Action | Fields | Effect | +|---|---|---| +| `advanced_device.force_off` | `device_id` (required) | Switches the plug off now, ignoring the one-time lock. Same as the **Force off** button. | +| `advanced_device.lock_shutdown` | `device_id` (required), `duration` (optional) | Blocks the next switch-off once. `duration` is a time period. If empty, the default expiry from the options is used. | +| `advanced_device.unlock_shutdown` | `device_id` (required) | Removes the one-time lock. | + +```yaml +action: advanced_device.lock_shutdown +target: + device_id: 0123456789abcdef +data: + duration: "00:30:00" +``` + +## Device triggers + +Device triggers are available under the device's **Automations** tab. + +| Trigger type | Available | Fires on | +|---|---|---| +| Cycle started | with a power sensor or WashData device | `advanced_device_cycle_started` event | +| Cycle finished | with a power sensor or WashData device | `advanced_device_cycle_finished` event | +| Shutdown blocked | always | `advanced_device_shutdown_blocked` event | +| Status changed | always | Change of the `status` sensor. Optional field **To status** limits it to one state. | + +## Behaviour + +### Switch-off sequence + +A switch-off from the main switch, the `force_off` button or the auto-off is handled in this order: + +1. **One-time lock active:** the switch-off is discarded and the lock is used up. The plug stays on, and `advanced_device_shutdown_blocked` fires with `reason: one_time_lock`. The **Force off** button and the `force_off` action skip this check and also remove an active lock. +2. **Shutdown lock off:** the plug switches off immediately. +3. **Shutdown lock on and status `standby`:** the plug switches off after the delay. +4. **Shutdown lock on, any other status:** the status becomes `shutting_down`. The pre-action runs, and the integration waits for `standby`. Then it waits for the delay and switches off. + - If the maximum wait is exceeded, the plug is **not** switched off. The shutdown is cancelled, the status returns to the value derived from the power, and `advanced_device_shutdown_aborted` fires. + +Switching the main switch on during `shutting_down` cancels the shutdown. + +### Re-enable after external off + +If the plug is switched off by something other than this integration (a physical button, another integration) while the device is `running`, the shutdown lock is on, and **Switch back on after external off** is enabled, the integration switches the plug back on. This happens at most three times. `advanced_device_shutdown_blocked` fires with `reason: external_off`. + +An external off while WashData reports `paused` or `user_paused` is tolerated and not reversed. + +### One-time lock + +- Turning on the **One-time lock** switch, or calling `lock_shutdown`, arms the lock. The switch uses the default expiry from the options. +- The lock ends at the first switch-off it blocks, at its expiry, when the switch is turned off manually, or when `unlock_shutdown` is called, whichever happens first. +- The lock does not block **Force off**. +- Expiry is stored. A lock whose expiry passed while Home Assistant was stopped is off after the restart. + +### Auto-off + +After the configured time in uninterrupted `standby`, the integration switches the plug off through the normal switch-off path. The one-time lock and the shutdown lock are respected. + +### Problem sensor + +The problem sensor reports these reasons in its `reasons` attribute: + +- `power_missing`: the plug is on and the power sensor is unavailable. +- `cycle_too_long`: the running cycle exceeds the maximum cycle duration. + +### Safety principle + +The integration must not switch a device off unexpectedly. If the state is unclear (missing power data, unavailable sensor, restart during a pending shutdown), the plug stays on. A pending shutdown is discarded on restart. + +### Persistence + +Cycle counter, operating hours, maintenance counter, last cycle values and the one-time lock expiry are stored with Home Assistant's storage helper. They survive restarts. + +### Removing the entry + +When the config entry is removed, the original switch is shown again, but only if it is still hidden by this integration. A switch that you hid yourself stays hidden. + +## WashData + +See the [WashData section in the README](../README.md#washdata). In short: + +- Cycle events and cycle sensors come from WashData when a WashData device is linked. +- The shutdown lock is released only in WashData states `finished`, `clean`, `off` and `idle`. +- Use the original plug switch, not the Advanced Device switch, as WashData's pause/resume switch. diff --git a/docs/migration-from-blueprint.md b/docs/migration-from-blueprint.md new file mode 100644 index 0000000..a81ebe2 --- /dev/null +++ b/docs/migration-from-blueprint.md @@ -0,0 +1,78 @@ +# Migrating from the blueprint + +The Advanced Device integration replaces the blueprint "🔝 Advanced devices" (`template.yaml`, kept for reference as [`blueprint-template.yaml`](blueprint-template.yaml)). The blueprint wrote status and icons as attributes onto a template switch and relied on the `python_script` helper. The integration owns its entities, so none of that is needed. + +Set up the integration first, then remove the blueprint automation. + +## Input mapping + +Each blueprint input maps to a setting of the integration. The setting is in the step named in the last column. + +| Blueprint input | Advanced Device setting | Step | +|---|---|---| +| `input_switch_state` (Status switch) | Plug switch | Add device | +| `input_switch_action` (Action switch) | not needed; the integration switches the plug directly | | +| `input_power_entity` (Power sensor) | Power sensor | Add device | +| `input_power_standby_threshold` | Standby threshold (W) | Power thresholds | +| `input_power_standby_duration` | Standby duration (s) | Power thresholds | +| `input_power_running_threshold` | Running threshold (W) | Power thresholds | +| `input_power_running_duration` | Running duration (s) | Power thresholds | +| (uses the running duration) | Idle duration (s), new own field | Power thresholds | +| (not in the blueprint) | Smoothing window (s) | Power thresholds | +| `input_icon_on` | Icon: on | Extras | +| `input_icon_off` | Icon: off | Extras | +| `input_icon_running` | Icon: running | Extras | +| `input_icon_unavailable` | Icon: unavailable | Extras | +| `input_bool_protect_shutdown` | Enable shutdown lock | Shutdown lock | +| `input_action_before_shutdown` (Action to enable shutdown) | Action before switching off: a `script`, `button` or `input_button` entity | Shutdown lock | +| `input_delay_before_off` | Delay from standby to off (s) | Shutdown lock | +| `input_switch_force_enabled` (Switch force enabled) | One-time lock switch, or the `advanced_device.lock_shutdown` action | Entities / Actions | +| `input_name_status` (Status attribute name) | not needed; the status is a sensor entity | | + +Notes on the mapping: + +- **Action before switching off.** The blueprint accepted an inline action. The integration accepts only an entity from the domains `script`, `button` or `input_button`. If your action is inline, create a script with those actions and select the script. +- **Icons.** The blueprint set icons for four states. The integration has an icon for each of the eight statuses. Icons not set in the blueprint take the profile's value. +- **Thresholds.** Values are not copied automatically. Enter them again in the Power thresholds step. Choose the profile that matches the appliance first, because its values prefill that step. +- **Shutdown lock.** The integration requires a standby threshold above 0 W when the shutdown lock is on. + +## What is removed + +These parts of the blueprint setup are no longer needed. Delete them after the integration works. + +- **Template switch.** The integration's main switch replaces it. Remove the template switch and the automation that updated it. +- **The blueprint automation instance.** Delete it under **Settings → Automations & Scenes**. +- **The `python_script` helper** (`python_script.hass_entities`). The integration needs no `python_script` integration or script. +- **Status and icon attributes** on the template switch. + +## Update automations and dashboards + +The blueprint exposed the status as an attribute `status` on the template switch. The integration exposes it as the entity `sensor._status`, with the states `off`, `starting`, `on`, `standby`, `idle`, `running`, `shutting_down` and `unavailable`. + +Replace templates and conditions that read the attribute: + +```yaml +# Before +condition: state +entity_id: switch.washer_template +attribute: status +state: running + +# After +condition: state +entity_id: sensor.washer_status +state: running +``` + +Use the status sensor's entity ID in triggers, conditions and dashboard cards. The main switch of the device (`switch.`) replaces the template switch for turning the plug on and off. + +For event-based automations, see the events and device triggers in the [reference](integration.md#events). The blueprint's "switch force enabled" logic is replaced by the one-time lock, which expires; see [One-time lock](integration.md#one-time-lock). + +## Behaviour differences + +- The blueprint's status for an unavailable plug was never set, because of a typo (`unavaiable`). The integration reports `unavailable` correctly. +- The idle status used the running duration. The integration has its own idle duration. +- **Maximum wait (new).** The blueprint has no maximum wait. In the integration, if the device does not reach standby within the maximum wait, the shutdown is cancelled and the plug stays on. The default is 0, which waits without limit. +- **Lock expiry (new).** A one-time lock expires after a set time, by default 60 minutes. Set the default to 0 for a lock that ends only when the device consumes power again. +- **Re-enable after external off (new).** Optional, and limited to three attempts. +- **Missing power data.** The integration keeps the plug on when the power sensor is unavailable or data is missing. diff --git a/info.md b/info.md index 062f1de..933e603 100644 --- a/info.md +++ b/info.md @@ -1,3 +1,5 @@ -# Advanced Device +Advanced Device icon -Work in progress. Per-device cycle and state tracking for smart plugs with power sensors. +Turns a switchable power plug with a power sensor into its own smart device. Status from power (off, standby, idle, running), a shutdown lock that waits for standby before switching off, a one-time lock, cycle statistics, auto-off, device profiles and an optional link to WashData. + +Program detection is not included; use WashData for that. From 87284999bc4b6ed59efb654a86fca6b4d9619130 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 22:59:04 +0100 Subject: [PATCH 3/8] fix(core): no off on missing data, cycle survives blips and restarts Co-Authored-By: Claude Sonnet 5.5 --- .../advanced_device/core/cycle.py | 12 ++++ .../advanced_device/core/power.py | 6 ++ .../advanced_device/core/state_machine.py | 62 +++++++++++++++++-- tests/core/test_state_lock.py | 19 +++++- tests/core/test_state_restore.py | 25 +++++++- tests/core/test_state_shutdown.py | 31 ++++++++++ tests/core/test_state_status.py | 15 +++++ 7 files changed, 162 insertions(+), 8 deletions(-) diff --git a/custom_components/advanced_device/core/cycle.py b/custom_components/advanced_device/core/cycle.py index 4eae750..4748253 100644 --- a/custom_components/advanced_device/core/cycle.py +++ b/custom_components/advanced_device/core/cycle.py @@ -39,6 +39,18 @@ def active(self) -> bool: def started_at(self) -> float | None: return self._started_at + @property + def energy_ws(self) -> float: + return self._energy_ws + + def resume(self, start: float, energy_ws: float, ts: float) -> None: + """Re-open a cycle that was active before a restart, without a start event.""" + self._active = True + self._started_at = start + self._last_ts = ts + self._last_watts = 0.0 + self._energy_ws = energy_ws + def start(self, ts: float) -> bool: if self._active: return False diff --git a/custom_components/advanced_device/core/power.py b/custom_components/advanced_device/core/power.py index 37124db..a6b6cba 100644 --- a/custom_components/advanced_device/core/power.py +++ b/custom_components/advanced_device/core/power.py @@ -81,6 +81,12 @@ def update(self, ts: float, watts: float) -> Band | None: def tick(self, ts: float) -> Band | None: return self._confirm_if_due(ts) + def drop_pending(self) -> None: + """Forget an unconfirmed candidate (power gap). The confirmed band is kept.""" + self._candidate = None + self._candidate_start = None + self.pending_until = None + def reset(self) -> None: self.confirmed = None self.pending_until = None diff --git a/custom_components/advanced_device/core/state_machine.py b/custom_components/advanced_device/core/state_machine.py index 055c576..2637404 100644 --- a/custom_components/advanced_device/core/state_machine.py +++ b/custom_components/advanced_device/core/state_machine.py @@ -22,7 +22,7 @@ Status, SwitchPlug, ) -from .power import BandClassifier, PowerSmoother +from .power import BandClassifier, PowerSmoother, band_for _BAND_STATUS: dict[Band, Status] = { Band.STANDBY: Status.STANDBY, @@ -115,15 +115,28 @@ def on_plug(self, ts: float, state: PlugState) -> list[Action]: self._last_raw = None self._settle_until = None if state is PlugState.ON: + self._expect_off = False if self._reenabling: self._reenabling = False return [] - if not self._cfg.has_power or self._cfg.power.standby_w == 0: + if self._cycle.active: + # Plug blip: the cycle went on, so restore the band instead of STARTING. + self._set_status(ts, self._confirmed_status()) + elif not self._cfg.has_power or self._cfg.power.standby_w == 0: self._set_status(ts, Status.ON) else: self._set_status(ts, Status.STARTING) return [] - if state is PlugState.OFF and not self._expect_off and self._may_reenable(): + if state is PlugState.UNAVAILABLE: + # A gap, not an end: the cycle, smoother and classifier survive it. + self._clear_shutdown() + self._expect_off = False + self._reenabling = False + self._reenable_count = 0 + self._auto_off_fired = False + self._set_status(ts, Status.UNAVAILABLE) + return [] + if not self._expect_off and self._may_reenable(): self._reenable_count += 1 self._reenabling = True return [ @@ -136,7 +149,7 @@ def on_plug(self, ts: float, state: PlugState) -> list[Action]: self._reenabling = False self._reenable_count = 0 self._auto_off_fired = False - self._set_status(ts, Status.OFF if state is PlugState.OFF else Status.UNAVAILABLE) + self._set_status(ts, Status.OFF) if self._cfg.washdata: return [] return self._end_cycle(ts) @@ -149,6 +162,8 @@ def on_power(self, ts: float, watts: float | None) -> list[Action]: self._settle_until = None if watts is None: self._feed_gap(ts) + self._standby_since = None + self._classifier.drop_pending() if watts is None and self._shutting_down: self._shutdown_at = None if watts is None or not self._sensing(): @@ -162,6 +177,13 @@ def _evaluate_power(self, ts: float, watts: float) -> list[Action]: self._last_smoothed = smoothed band = self._classifier.update(ts, smoothed) actions = self._on_confirmed(ts, band) + # A new standby phase starts only with a numeric reading in the standby band. + if ( + self._status is Status.STANDBY + and self._standby_since is None + and band_for(smoothed, self._cfg.power) is Band.STANDBY + ): + self._standby_since = ts if self._cycle.active: self._cycle.add_power(ts, smoothed) return actions @@ -236,6 +258,17 @@ def set_price(self, price: float | None) -> None: def reset_maintenance(self) -> None: self._counter.reset_maintenance() + def on_switch_failed(self, ts: float, wanted_on: bool) -> list[Action]: + if wanted_on: + self._reenabling = False + return [] + self._expect_off = False + if not self._shutting_down: + return [] + self._clear_shutdown() + self._set_status(ts, self._confirmed_status()) + return [FireEvent("shutdown_aborted", {"reason": "switch_failed"})] + def on_washdata_state(self, ts: float, state: str | None) -> list[Action]: self._washdata_state = state if not self._shutting_down or self._expect_off: @@ -278,6 +311,9 @@ def snapshot(self) -> dict: }, "operating_s_total": self._counter.total_s, "operating_s_since_maintenance": self._counter.since_maintenance_s, + "cycle": None + if not self._cycle.active or self._cycle.started_at is None + else {"start": self._cycle.started_at, "energy_ws": self._cycle.energy_ws}, } def restore(self, data: dict, now: float) -> None: @@ -296,6 +332,16 @@ def restore(self, data: dict, now: float) -> None: self._counter.since_maintenance_s = ( _as_float(data.get("operating_s_since_maintenance"), 0.0) or 0.0 ) + self._restore_cycle(data.get("cycle"), now) + + def _restore_cycle(self, value: object, now: float) -> None: + if not isinstance(value, dict): + return + start = _as_float(value.get("start")) + energy_ws = _as_float(value.get("energy_ws")) + if start is None or energy_ws is None or energy_ws < 0 or start > now: + return + self._cycle.resume(start, energy_ws, now) def _reevaluate_smoothed(self, ts: float) -> list[Action]: """Let the smoothed power settle towards the last raw reading without new samples.""" @@ -404,7 +450,7 @@ def _reset_sensing(self) -> None: self._last_smoothed = None def _on_confirmed(self, ts: float, band: Band | None) -> list[Action]: - if band is None: + if band is None or self._power_missing: return [] return self._set_band(ts, band) @@ -459,7 +505,10 @@ def _request_off(self, ts: float, source: str) -> list[Action]: if not self._protection or not self._sensing(): return self._send_off() verdict = self._washdata_verdict() - standby_path = self._status is Status.STANDBY if verdict is None else verdict + if verdict is None: + standby_path = self._status is Status.STANDBY and not self._power_missing + else: + standby_path = verdict if standby_path: if self._cfg.delay_s <= 0: return self._send_off() @@ -587,6 +636,7 @@ def _auto_off_due_at(self) -> float | None: or self._auto_off_fired or self._status is not Status.STANDBY or self._plug is not PlugState.ON + or self._power_missing or self._standby_since is None ): return None diff --git a/tests/core/test_state_lock.py b/tests/core/test_state_lock.py index ba22f02..637cf79 100644 --- a/tests/core/test_state_lock.py +++ b/tests/core/test_state_lock.py @@ -116,7 +116,8 @@ def test_turn_on_clears_pending_reenable(m_running_reenable): m_running_reenable.on_plug(30, PlugState.OFF) # re-enable pending m_running_reenable.turn_on(31) assert m_running_reenable.on_plug(32, PlugState.ON) == [] - assert m_running_reenable.status is Status.STARTING + # Zyklus lief weiter, das bestätigte Band bleibt RUNNING (kein STARTING mehr) + assert m_running_reenable.status is Status.RUNNING def test_auto_off_not_rearmed_by_abort(make): @@ -130,3 +131,19 @@ def test_auto_off_not_rearmed_by_abort(make): m.on_tick(410) # max wait reached: shutdown aborted, back to standby assert m.status is Status.STANDBY assert SwitchPlug(False) not in m.on_tick(800) + m.on_tick(1500) + + +def test_auto_off_not_while_power_missing(m_standby_autooff): + m = m_standby_autooff + m.on_power(100, None) + assert m.on_tick(400) == [] # Auto-Off wäre bei 360 fällig gewesen + assert m.on_tick(1000) == [] + + +def test_auto_off_restarts_after_power_returns(m_standby_autooff): + m = m_standby_autooff + m.on_power(100, None) + m.on_tick(400) + m.on_power(1000, 1) # neue Standby-Phase beginnt mit dem bestätigenden Messwert + assert m.on_tick(1299) == [] + assert m.on_tick(1300) == [SwitchPlug(False)] diff --git a/tests/core/test_state_restore.py b/tests/core/test_state_restore.py index a767419..515d6f4 100644 --- a/tests/core/test_state_restore.py +++ b/tests/core/test_state_restore.py @@ -1,5 +1,5 @@ import pytest -from core.model import PlugState, Status, SwitchPlug +from core.model import FireEvent, PlugState, Status, SwitchPlug def test_restore_expired_lock_is_off(make): @@ -91,3 +91,26 @@ def test_restore_non_dict_is_ignored(make): m.restore("garbage", now=0) assert m.cycles_total == 0 assert not m.lock_active + + +def test_restore_resumes_active_cycle(make): + m = make(min_cycle_s=0) + m.on_plug(0, PlugState.ON) + m.on_power(0, 1000) + m.on_tick(20) # RUNNING, Zyklus beginnt bei 20 + m.on_power(100, 1000) + snap = m.snapshot() + m2 = make(min_cycle_s=0) + m2.restore(snap, now=200) + assert m2.cycle_active + acts = m2.on_plug(200, PlugState.ON) + m2.on_power(200, 1000) + m2.on_tick(220) + assert FireEvent("cycle_started", {}) not in acts + m2.on_plug(300, PlugState.OFF) + assert m2.cycles_total == 1 + assert m2.last_cycle_duration_s == 280 # ab dem ursprünglichen Start bei 20 + + +def test_restore_invalid_cycle_ignored(make): + m = make(min_cycle_s=0) + m.restore({"version": 1, "cycle": {"start": "x", "energy_ws": 1}}, now=0) + assert not m.cycle_active diff --git a/tests/core/test_state_shutdown.py b/tests/core/test_state_shutdown.py index dbec635..059779a 100644 --- a/tests/core/test_state_shutdown.py +++ b/tests/core/test_state_shutdown.py @@ -81,3 +81,34 @@ def test_turn_on_while_off_in_flight_switches_back_on(m_standby): m_standby.turn_off(100) m_standby.on_tick(130) assert m_standby.turn_on(131) == [SwitchPlug(True)] + + +def test_no_shutdown_when_power_lost_with_pending_standby(m_running): + m = m_running + m.turn_off(30) + m.on_power(40, 1) # Standby-Kandidat, frühestens bestätigt bei 100 + m.on_power(50, None) # Messwert weg + acts = [] + for ts in range(100, 1001, 10): + acts += m.on_tick(ts) + assert SwitchPlug(False) not in acts + assert m.shutdown_at is None + + +def test_turn_off_with_power_missing_takes_running_path(m_standby): + m = m_standby + m.on_power(50, None) + assert m.turn_off(60) == [RunPreAction()] + assert m.status is Status.SHUTTING_DOWN + assert m.shutdown_at is None + + +def test_switch_failure_aborts_shutdown(m_standby): + m = m_standby + assert m.turn_off(100) == [] + assert m.on_tick(130) == [SwitchPlug(False)] + acts = m.on_switch_failed(131, False) + assert FireEvent("shutdown_aborted", {"reason": "switch_failed"}) in acts + assert m.status is Status.STANDBY + assert m.shutdown_at is None + assert m.on_tick(500) == [] diff --git a/tests/core/test_state_status.py b/tests/core/test_state_status.py index 23ee431..1f81c7f 100644 --- a/tests/core/test_state_status.py +++ b/tests/core/test_state_status.py @@ -85,3 +85,18 @@ def test_smoothing_settles_without_new_samples(make): now = m.next_wakeup() assert m.status is Status.STANDBY + + +def test_plug_unavailable_blip_keeps_cycle(make): + m = make(min_cycle_s=0) + m.on_plug(0, PlugState.ON) + m.on_power(0, 50) + m.on_tick(20) + assert m.status is Status.RUNNING + assert m.cycle_active + acts = m.on_plug(100, PlugState.UNAVAILABLE) + assert m.cycle_active + assert all(getattr(a, "kind", None) != "cycle_finished" for a in acts) + assert m.on_plug(110, PlugState.ON) == [] + assert m.status is Status.RUNNING + assert m.cycle_active From 126acc3e9972fd2c740e9361c07b34366862e826 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 23:03:14 +0100 Subject: [PATCH 4/8] fix: persistence with WashData, stale links, reconfigure unhide, safer defaults Co-Authored-By: Claude Sonnet 5.5 --- custom_components/advanced_device/__init__.py | 2 + .../advanced_device/config_flow.py | 20 ++++++ .../advanced_device/core/profiles.py | 6 +- custom_components/advanced_device/runtime.py | 19 ++++-- custom_components/advanced_device/services.py | 2 +- .../advanced_device/strings.json | 2 +- custom_components/advanced_device/switch.py | 11 ++- .../advanced_device/translations/de.json | 2 +- .../advanced_device/translations/en.json | 2 +- custom_components/advanced_device/washdata.py | 6 +- tests/core/test_profiles.py | 6 ++ tests/integration/test_options_flow.py | 30 +++++++++ tests/integration/test_services.py | 12 ++++ tests/integration/test_switch.py | 45 ++++++++++++- tests/integration/test_washdata.py | 67 ++++++++++++++++--- 15 files changed, 209 insertions(+), 23 deletions(-) diff --git a/custom_components/advanced_device/__init__.py b/custom_components/advanced_device/__init__.py index c8ce247..a7087ee 100644 --- a/custom_components/advanced_device/__init__.py +++ b/custom_components/advanced_device/__init__.py @@ -7,6 +7,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers import device_registry as dr from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.storage import Store from .const import ( @@ -64,6 +65,7 @@ async def async_remove_entry(hass: HomeAssistant, entry: AdvancedDeviceConfigEnt reg_entry = ent_reg.async_get(switch) if reg_entry is not None and reg_entry.hidden_by == er.RegistryEntryHider.INTEGRATION: ent_reg.async_update_entity(switch, hidden_by=None) + ir.async_delete_issue(hass, DOMAIN, f"washdata_missing_{entry.entry_id}") await Store(hass, 1, f"{DOMAIN}.{entry.entry_id}").async_remove() diff --git a/custom_components/advanced_device/config_flow.py b/custom_components/advanced_device/config_flow.py index 5a6bf24..6df0192 100644 --- a/custom_components/advanced_device/config_flow.py +++ b/custom_components/advanced_device/config_flow.py @@ -10,6 +10,7 @@ from homeassistant import config_entries from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.selector import ( BooleanSelector, EntitySelector, @@ -195,6 +196,21 @@ def _extras_schema( return vol.Schema(fields) +def _drop_stale_washdata(hass: HomeAssistant, options: dict[str, Any]) -> None: + """Forget a WashData link whose config entry no longer exists.""" + link = options.get(CONF_WASHDATA_ENTRY) + if link and hass.config_entries.async_get_entry(link) is None: + options.pop(CONF_WASHDATA_ENTRY, None) + + +def _unhide_switch(hass: HomeAssistant, switch: str) -> None: + """Show a switch that this integration hid; a switch the user hid stays hidden.""" + ent_reg = er.async_get(hass) + reg_entry = ent_reg.async_get(switch) + if reg_entry is not None and reg_entry.hidden_by == er.RegistryEntryHider.INTEGRATION: + ent_reg.async_update_entity(switch, hidden_by=None) + + def _store_extras( options: dict[str, Any], user_input: Mapping[str, Any], @@ -380,6 +396,9 @@ async def async_step_reconfigure( for other in self.hass.config_entries.async_entries(DOMAIN) ): return self.async_abort(reason="already_configured") + old_switch = entry.data.get(CONF_SWITCH_ENTITY) + if old_switch and old_switch != switch: + _unhide_switch(self.hass, old_switch) data: dict[str, Any] = {CONF_SWITCH_ENTITY: switch} if user_input.get(CONF_POWER_ENTITY): data[CONF_POWER_ENTITY] = user_input[CONF_POWER_ENTITY] @@ -507,6 +526,7 @@ async def async_step_extras( has_power = self._has_power() washdata = _washdata_choices(self.hass) if user_input is not None: + _drop_stale_washdata(self.hass, self._options) _store_extras(self._options, user_input, has_power, bool(washdata)) return self.async_create_entry(data=self._options) diff --git a/custom_components/advanced_device/core/profiles.py b/custom_components/advanced_device/core/profiles.py index 414b174..be74051 100644 --- a/custom_components/advanced_device/core/profiles.py +++ b/custom_components/advanced_device/core/profiles.py @@ -62,7 +62,7 @@ def _icons(on: str, running: str, off: str) -> dict[Status, str]: min_cycle_s=600, # Annahme: kürzester Waschgang ca. 10 min icons=_icons("mdi:washing-machine", "mdi:washing-machine", "mdi:washing-machine-off"), protection=True, - auto_off_s=3600, # Annahme: 1 h nach Ende aus + auto_off_s=0, # verzögerter Start möglich: kein Auto-Off ), "dryer": Profile( key="dryer", @@ -77,7 +77,7 @@ def _icons(on: str, running: str, off: str) -> dict[Status, str]: min_cycle_s=600, # Annahme: kürzester Trockenlauf ca. 10 min icons=_icons("mdi:tumble-dryer", "mdi:tumble-dryer", "mdi:power-plug-off"), protection=True, - auto_off_s=3600, # Annahme: 1 h nach Ende aus + auto_off_s=0, # verzögerter Start möglich: kein Auto-Off ), "dishwasher": Profile( key="dishwasher", @@ -92,7 +92,7 @@ def _icons(on: str, running: str, off: str) -> dict[Status, str]: min_cycle_s=900, # Annahme: kürzestes Programm ca. 15 min icons=_icons("mdi:dishwasher", "mdi:dishwasher", "mdi:power-plug-off"), protection=True, - auto_off_s=3600, # Annahme: 1 h nach Ende aus + auto_off_s=0, # verzögerter Start möglich: kein Auto-Off ), "pc": Profile( key="pc", diff --git a/custom_components/advanced_device/runtime.py b/custom_components/advanced_device/runtime.py index 8e52937..58d857e 100644 --- a/custom_components/advanced_device/runtime.py +++ b/custom_components/advanced_device/runtime.py @@ -94,6 +94,7 @@ def __init__(self, hass: HomeAssistant, entry: AdvancedDeviceConfigEntry) -> Non self._washdata: WashDataLink | None = None self._unsubs: list[Callable[[], None]] = [] self._timer: Callable[[], None] | None = None + self._started = False self._store: Store[dict[str, Any]] = Store( hass, _STORE_VERSION, f"{DOMAIN}.{entry.entry_id}" ) @@ -107,9 +108,10 @@ async def async_start(self) -> None: ) self.device_id = device.id if device else "" + # Load the saved state before WashData feeds its state in; no save runs before the end. + data = await self._store.async_load() self._washdata = await self._async_start_washdata() - data = await self._store.async_load() if data: self.machine.restore(data.get("machine", {}), _now()) protection = data.get("protection") @@ -140,6 +142,7 @@ async def async_start(self) -> None: actions = self.machine.on_plug(ts, _plug_state(self.hass.states.get(switch))) if power: actions += self.machine.on_power(ts, _power_watts(self.hass.states.get(power))) + self._started = True self._after_input(actions) async def async_stop(self) -> None: @@ -250,7 +253,8 @@ def _after_input(self, actions: list[Any]) -> None: self._execute(action) self._schedule_timer() async_dispatcher_send(self.hass, self.signal) - self._store.async_delay_save(self._data_to_save, _SAVE_DELAY_S) + if self._started: + self._store.async_delay_save(self._data_to_save, _SAVE_DELAY_S) def _data_to_save(self) -> dict[str, Any]: return { @@ -281,7 +285,10 @@ def _execute(self, action: object) -> None: service = "turn_on" if action.on else "turn_off" self._create_task( self._async_call_service( - "switch", service, {"entity_id": self.entry.data[CONF_SWITCH_ENTITY]} + "switch", + service, + {"entity_id": self.entry.data[CONF_SWITCH_ENTITY]}, + wanted_on=action.on, ), f"switch.{service}", ) @@ -313,8 +320,12 @@ def _execute(self, action: object) -> None: def _create_task(self, coro: Any, name: str) -> None: self.entry.async_create_background_task(self.hass, coro, name=f"{DOMAIN}_{name}") - async def _async_call_service(self, domain: str, service: str, data: dict) -> None: + async def _async_call_service( + self, domain: str, service: str, data: dict, wanted_on: bool | None = None + ) -> None: try: await self.hass.services.async_call(domain, service, data, blocking=True) except Exception: _LOGGER.exception("Service %s.%s failed for %s", domain, service, data) + if wanted_on is not None: + self._after_input(self.machine.on_switch_failed(_now(), wanted_on)) diff --git a/custom_components/advanced_device/services.py b/custom_components/advanced_device/services.py index d898501..5f889a3 100644 --- a/custom_components/advanced_device/services.py +++ b/custom_components/advanced_device/services.py @@ -20,7 +20,7 @@ ATTR_DURATION = "duration" _DEVICE_SCHEMA = vol.Schema({vol.Required(ATTR_DEVICE_ID): vol.All(cv.ensure_list, [cv.string])}) -_LOCK_SCHEMA = _DEVICE_SCHEMA.extend({vol.Optional(ATTR_DURATION): cv.time_period}) +_LOCK_SCHEMA = _DEVICE_SCHEMA.extend({vol.Optional(ATTR_DURATION): cv.positive_time_period}) def _runtimes_for(hass: HomeAssistant, device_ids: list[str]) -> list[AdvancedDeviceRuntime]: diff --git a/custom_components/advanced_device/strings.json b/custom_components/advanced_device/strings.json index 1a9888a..caa7412 100644 --- a/custom_components/advanced_device/strings.json +++ b/custom_components/advanced_device/strings.json @@ -311,7 +311,7 @@ "issues": { "washdata_missing": { "title": "WashData device not found", - "description": "The device {name} is linked to a WashData device that no longer exists. Its own cycle detection is used until the link is changed in the extras settings." + "description": "The device {name} is linked to a WashData device that no longer exists or is not loaded. Its own cycle detection is used until WashData is loaded again or the link is removed. To remove the link, open the options and save the extras step." } } } diff --git a/custom_components/advanced_device/switch.py b/custom_components/advanced_device/switch.py index 3cd7073..69ab627 100644 --- a/custom_components/advanced_device/switch.py +++ b/custom_components/advanced_device/switch.py @@ -5,7 +5,7 @@ from typing import Any from homeassistant.components.switch import SwitchEntity -from homeassistant.const import STATE_ON, EntityCategory +from homeassistant.const import STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN, EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddEntitiesCallback @@ -46,6 +46,15 @@ def is_on(self) -> bool: state = self.hass.states.get(self._switch_entity_id) return state is not None and state.state == STATE_ON + @property + def available(self) -> bool: + state = self.hass.states.get(self._switch_entity_id) + return ( + super().available + and state is not None + and state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN) + ) + @property def icon(self) -> str | None: status = self._runtime.machine.status diff --git a/custom_components/advanced_device/translations/de.json b/custom_components/advanced_device/translations/de.json index 8f83f9b..7aaaafa 100644 --- a/custom_components/advanced_device/translations/de.json +++ b/custom_components/advanced_device/translations/de.json @@ -311,7 +311,7 @@ "issues": { "washdata_missing": { "title": "WashData-Gerät nicht gefunden", - "description": "Das Gerät {name} ist mit einem WashData-Gerät verknüpft, das nicht mehr existiert. Bis die Verknüpfung in den Extras geändert wird, gilt die eigene Zyklenerkennung." + "description": "Das Gerät {name} ist mit einem WashData-Gerät verknüpft, das nicht mehr existiert oder nicht geladen ist. Bis WashData wieder geladen ist oder die Verknüpfung entfernt wird, gilt die eigene Zyklenerkennung. Zum Entfernen der Verknüpfung die Optionen öffnen und den Schritt Extras speichern." } } } diff --git a/custom_components/advanced_device/translations/en.json b/custom_components/advanced_device/translations/en.json index 1a9888a..caa7412 100644 --- a/custom_components/advanced_device/translations/en.json +++ b/custom_components/advanced_device/translations/en.json @@ -311,7 +311,7 @@ "issues": { "washdata_missing": { "title": "WashData device not found", - "description": "The device {name} is linked to a WashData device that no longer exists. Its own cycle detection is used until the link is changed in the extras settings." + "description": "The device {name} is linked to a WashData device that no longer exists or is not loaded. Its own cycle detection is used until WashData is loaded again or the link is removed. To remove the link, open the options and save the extras step." } } } diff --git a/custom_components/advanced_device/washdata.py b/custom_components/advanced_device/washdata.py index 0796b01..e0e0f2a 100644 --- a/custom_components/advanced_device/washdata.py +++ b/custom_components/advanced_device/washdata.py @@ -10,6 +10,7 @@ import logging from collections.abc import Callable +from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback from homeassistant.helpers import entity_registry as er @@ -49,8 +50,9 @@ def __init__( self._unsubs: list[Callable[[], None]] = [] async def async_start(self) -> bool: - """Subscribe to the cycle events and the state entity. False if the entry is missing.""" - if self.hass.config_entries.async_get_entry(self.washdata_entry_id) is None: + """Subscribe to the cycle events and the state entity. False unless the entry is loaded.""" + entry = self.hass.config_entries.async_get_entry(self.washdata_entry_id) + if entry is None or entry.state is not ConfigEntryState.LOADED: return False ent_reg = er.async_get(self.hass) diff --git a/tests/core/test_profiles.py b/tests/core/test_profiles.py index 3a9e9bb..825956b 100644 --- a/tests/core/test_profiles.py +++ b/tests/core/test_profiles.py @@ -31,3 +31,9 @@ def test_profile_consistent(key): def test_unknown_falls_back(): assert get_profile("nope").key == "generic" + + +@pytest.mark.parametrize("key", ["washing_machine", "dryer", "dishwasher"]) +def test_delayed_start_profiles_have_no_auto_off(key): + # A delayed start would be cut off by auto-off, so these profiles default to 0. + assert PROFILES[key].auto_off_s == 0 diff --git a/tests/integration/test_options_flow.py b/tests/integration/test_options_flow.py index 91030bf..a252216 100644 --- a/tests/integration/test_options_flow.py +++ b/tests/integration/test_options_flow.py @@ -5,6 +5,7 @@ import voluptuous as vol from homeassistant import config_entries from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import entity_registry as er from pytest_homeassistant_custom_component.common import MockConfigEntry from custom_components.advanced_device.const import DOMAIN @@ -289,3 +290,32 @@ async def test_options_extras_roundtrip(hass): assert defaults["max_cycle_min"] == 120 assert defaults["maintenance_h"] == 50 assert defaults["icon_off"] == "mdi:lightbulb" + + +async def test_options_drops_stale_washdata_link(hass): + entry = _entry(hass, options=_current_options(washdata_entry="gone-entry")) + with patch("custom_components.advanced_device.async_setup_entry", return_value=True): + result = await _to_extras(hass, entry) + result = await hass.config_entries.options.async_configure( + result["flow_id"], _extras_input() + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert "washdata_entry" not in entry.options + + +async def test_reconfigure_unhides_old_switch(hass): + ent_reg = er.async_get(hass) + ent_reg.async_get_or_create("switch", "test", "old-uid", suggested_object_id="washer_plug") + ent_reg.async_update_entity(SWITCH, hidden_by=er.RegistryEntryHider.INTEGRATION) + entry = _entry(hass) + with patch("custom_components.advanced_device.async_setup_entry", return_value=True): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_RECONFIGURE, "entry_id": entry.entry_id}, + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"switch_entity": "switch.new_plug", "power_entity": POWER}, + ) + assert result["reason"] == "reconfigure_successful" + assert ent_reg.async_get(SWITCH).hidden_by is None diff --git a/tests/integration/test_services.py b/tests/integration/test_services.py index 5f81fcb..9458ef9 100644 --- a/tests/integration/test_services.py +++ b/tests/integration/test_services.py @@ -1,6 +1,7 @@ """Actions of the integration: registration and device resolution.""" import pytest +import voluptuous as vol from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import device_registry as dr @@ -28,3 +29,14 @@ async def test_service_unknown_device(hass, entry, plug_device): assert err.value.translation_key == "unknown_device" assert err.value.translation_placeholders == {"device_id": bad_id} assert entry.runtime_data.machine.lock_active is False + + +async def test_lock_duration_must_be_positive(hass, entry, plug_device): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + own = dr.async_get(hass).async_get_device(identifiers={(DOMAIN, entry.entry_id)}) + with pytest.raises(vol.Invalid): + await hass.services.async_call( + DOMAIN, "lock_shutdown", {"device_id": [own.id], "duration": -5}, blocking=True + ) + assert entry.runtime_data.machine.lock_active is False diff --git a/tests/integration/test_switch.py b/tests/integration/test_switch.py index 0533d0e..284d840 100644 --- a/tests/integration/test_switch.py +++ b/tests/integration/test_switch.py @@ -6,12 +6,18 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from homeassistant.util import dt as dt_util -from pytest_homeassistant_custom_component.common import async_fire_time_changed, async_mock_service +from pytest_homeassistant_custom_component.common import ( + async_capture_events, + async_fire_time_changed, + async_mock_service, +) from custom_components.advanced_device.const import DOMAIN from custom_components.advanced_device.core.model import Status from custom_components.advanced_device.core.profiles import get_profile +from .cycle_helpers import set_power + SWITCH = "switch.plug" POWER = "sensor.plug_power" @@ -135,3 +141,40 @@ async def test_custom_icon_overrides_profile(hass, entry): main = _eid(hass, entry, "switch", "main") assert hass.states.get(main).attributes["icon"] == "mdi:rocket" + + +async def test_failed_switch_off_aborts_shutdown(hass, freezer, entry_protected): + entry = entry_protected + hass.config_entries.async_update_entry(entry, options={**entry.options, "delay_s": 30}) + hass.states.async_set(SWITCH, "on") + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + events = async_capture_events(hass, f"{DOMAIN}_shutdown_aborted") + await set_power(hass, freezer, 0.5, 90) + assert entry.runtime_data.machine.status == Status.STANDBY + + async def _fail(call): + raise HomeAssistantError("switch unreachable") + + hass.services.async_register("switch", "turn_off", _fail) + await entry.runtime_data.async_turn_off() + assert entry.runtime_data.machine.status == Status.SHUTTING_DOWN + await set_power(hass, freezer, 0.5, 40) + + assert entry.runtime_data.machine.status == Status.STANDBY + assert events and events[-1].data["reason"] == "switch_failed" + + +async def test_main_switch_unavailable_with_plug(hass, entry, plug_device): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + main = _eid(hass, entry, "switch", "main") + assert hass.states.get(main).state != "unavailable" + + hass.states.async_set(SWITCH, "unavailable") + await hass.async_block_till_done() + assert hass.states.get(main).state == "unavailable" + + hass.states.async_set(SWITCH, "on") + await hass.async_block_till_done() + assert hass.states.get(main).state != "unavailable" diff --git a/tests/integration/test_washdata.py b/tests/integration/test_washdata.py index 252f237..733695a 100644 --- a/tests/integration/test_washdata.py +++ b/tests/integration/test_washdata.py @@ -27,6 +27,14 @@ WD_KEYS = ("washer_state", "washer_program", "time_remaining", "cycle_progress") +def _loaded_washdata(hass): + """A WashData entry in state LOADED; the link follows only loaded entries.""" + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + washdata.mock_state(hass, ConfigEntryState.LOADED) + return washdata + + def _options(**overrides): options = { "profile": "generic", @@ -105,8 +113,7 @@ async def test_field_hidden_without_washdata(hass): async def test_cycles_follow_washdata_events(hass, freezer, plug_device): - washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") - washdata.add_to_hass(hass) + washdata = _loaded_washdata(hass) _wd_entities(hass, washdata) entry = _entry(hass, washdata) await _setup(hass, entry) @@ -129,8 +136,7 @@ async def test_cycles_follow_washdata_events(hass, freezer, plug_device): async def test_release_only_on_finished(hass, freezer, plug_device, service_calls): - washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") - washdata.add_to_hass(hass) + washdata = _loaded_washdata(hass) wd = _wd_entities(hass, washdata) entry = _entry(hass, washdata, protection=True) hass.states.async_set(SWITCH, "on") @@ -152,8 +158,7 @@ async def test_release_only_on_finished(hass, freezer, plug_device, service_call async def test_external_off_tolerated_when_paused(hass, freezer, plug_device, service_calls): - washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") - washdata.add_to_hass(hass) + washdata = _loaded_washdata(hass) wd = _wd_entities(hass, washdata) entry = _entry(hass, washdata, protection=True, reenable=True) hass.states.async_set(SWITCH, "on") @@ -178,8 +183,7 @@ async def test_external_off_tolerated_when_paused(hass, freezer, plug_device, se async def test_mirror_sensors(hass, plug_device): - washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") - washdata.add_to_hass(hass) + washdata = _loaded_washdata(hass) wd = _wd_entities(hass, washdata) hass.states.async_set(wd["washer_program"], "cotton") hass.states.async_set( @@ -228,3 +232,50 @@ async def test_missing_washdata_creates_repair_and_falls_back(hass, freezer, plu await run_cycle(hass, freezer) assert len(started) == 1 assert len(finished) == 1 + + +async def test_persistence_with_washdata_linked(hass, freezer, plug_device): + washdata = _loaded_washdata(hass) + _wd_entities(hass, washdata) + entry = _entry(hass, washdata) + await _setup(hass, entry) + + hass.bus.async_fire("ha_washdata_cycle_started", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + freezer.tick(timedelta(seconds=120)) + hass.bus.async_fire("ha_washdata_cycle_ended", {"entry_id": washdata.entry_id}) + await hass.async_block_till_done() + await entry.runtime_data.async_lock_once(600) + assert entry.runtime_data.machine.cycles_total == 1 + + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert entry.runtime_data.machine.cycles_total == 1 + assert entry.runtime_data.machine.lock_active + + +async def test_washdata_not_loaded_falls_back(hass, plug_device): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) # added but never set up: NOT_LOADED + _wd_entities(hass, washdata) + entry = _entry(hass, washdata) + await _setup(hass, entry) + + assert entry.runtime_data.washdata is None + issue = ir.async_get(hass).async_get_issue(DOMAIN, f"washdata_missing_{entry.entry_id}") + assert issue is not None + + +async def test_remove_entry_deletes_washdata_issue(hass, plug_device): + washdata = MockConfigEntry(domain=WASHDATA, title="Washer WD") + washdata.add_to_hass(hass) + entry = _entry(hass, washdata) + await hass.config_entries.async_remove(washdata.entry_id) + await hass.async_block_till_done() + await _setup(hass, entry) + issue_id = f"washdata_missing_{entry.entry_id}" + assert ir.async_get(hass).async_get_issue(DOMAIN, issue_id) is not None + + assert await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + assert ir.async_get(hass).async_get_issue(DOMAIN, issue_id) is None From fdd279154875eb8f8cbd11542aa42fb88728a677 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 23:04:38 +0100 Subject: [PATCH 5/8] docs: align with final behaviour Co-Authored-By: Claude Sonnet 5.5 --- README.md | 12 ++++++----- .../advanced_device/strings.json | 6 +++--- .../advanced_device/translations/de.json | 6 +++--- .../advanced_device/translations/en.json | 6 +++--- docs/integration.md | 20 +++++++++++++------ docs/migration-from-blueprint.md | 4 ++-- 6 files changed, 32 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index d74afdd..4d9d44d 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ The focus is on **control, status and protection**. It is not a program recognit - **Status from power.** `off`, `starting`, `on`, `standby`, `idle`, `running`, `shutting_down` and `unavailable`, derived from smoothed power with configurable thresholds and durations. - **Shutdown lock.** A switch-off waits until the appliance is in standby. An optional action runs first (for example a script that enables the appliance's own shutdown), and a delay and maximum wait can be set. -- **Re-enable after external off.** If the plug is switched off by something other than this integration while the device is running, it is switched back on, up to three times. +- **Re-enable after external off.** If the plug is switched off by something other than this integration while the device is running, it is switched back on, up to three times. This needs the shutdown lock to be on and the option **Switch back on after external off** to be enabled. - **One-time lock.** Blocks the next switch-off once, with an optional expiry. Useful for a nightly "everything off" automation. - **Cycles and statistics.** Start and end of each run, with duration, energy and cost (when a price sensor is set). - **Auto-off.** Switches the plug off after a configurable time in standby. @@ -50,14 +50,16 @@ Profiles set starting values. All values can be changed afterwards. | Profile | Standby (W / s) | Idle (s) | Running (W / s) | Smoothing (s) | Min. cycle | Shutdown lock | Auto-off | |---|---|---|---|---|---|---|---| | Generic | 1.0 / 60 | 120 | 10.0 / 30 | 10 | 1 min | no | off | -| Washing machine | 2.5 / 300 | 600 | 15.0 / 60 | 30 | 10 min | yes | 60 min | -| Dryer | 1.5 / 300 | 300 | 100.0 / 60 | 30 | 10 min | yes | 60 min | -| Dishwasher | 1.0 / 300 | 300 | 30.0 / 60 | 30 | 15 min | yes | 60 min | +| Washing machine | 2.5 / 300 | 600 | 15.0 / 60 | 30 | 10 min | yes | off | +| Dryer | 1.5 / 300 | 300 | 100.0 / 60 | 30 | 10 min | yes | off | +| Dishwasher | 1.0 / 300 | 300 | 30.0 / 60 | 30 | 15 min | yes | off | | PC | 5.0 / 60 | 600 | 40.0 / 30 | 20 | 1 min | no | off | | TV | 3.0 / 60 | 300 | 80.0 / 60 | 30 | 5 min | no | off | | Printer | 1.0 / 120 | 300 | 20.0 / 10 | 5 | 30 s | no | 15 min | | Coffee machine | 0.5 / 60 | 180 | 800.0 / 30 | 10 | 1 min | no | 30 min | +Washing machine, dryer and dishwasher have auto-off off by default, because a delayed start looks like standby and would be cut off. + The values are starting points based on typical consumption, not measurements. Measurements from real devices are welcome through the "Device profile" issue template. ## WashData @@ -70,7 +72,7 @@ The values are starting points based on typical consumption, not measurements. M **Recommendation:** in WashData, use the **original plug switch** (the one this integration hides) as the pause/resume switch, not the Advanced Device switch. Pausing turns the plug off from outside this integration. While WashData reports a pause, the integration tolerates that off and does not switch the plug back on. -If the linked WashData device is removed, the coupling is inactive, a repair issue is shown, and the integration uses its own logic. Setup does not fail. +If the linked WashData device is removed or not loaded, the coupling is inactive, a repair issue is shown, and the integration uses its own logic. Setup does not fail. After WashData is loaded again, reload the Advanced Device entry or restart Home Assistant. **Program detection?** Use WashData. This integration does not recognise programs. diff --git a/custom_components/advanced_device/strings.json b/custom_components/advanced_device/strings.json index caa7412..d027ee3 100644 --- a/custom_components/advanced_device/strings.json +++ b/custom_components/advanced_device/strings.json @@ -43,12 +43,12 @@ "delay_s": "Delay from standby to off (s)", "max_wait_s": "Maximum wait (s, 0 = unlimited)", "reenable": "Switch back on after external off", - "lock_default_min": "Default expiry of one-time lock (min, 0 = only by consumption)" + "lock_default_min": "Default expiry of one-time lock (min, 0 = no expiry)" }, "data_description": { "pre_action": "Script, button or input button that runs before the device is switched off.", "max_wait_s": "Longest time a switch-off waits for standby. 0 waits indefinitely.", - "lock_default_min": "Default duration of a one-time lock. 0 means it only ends when the device consumes power again." + "lock_default_min": "Default duration of a one-time lock. 0 means no expiry: the lock ends only when a switch-off uses it up, or when it is turned off manually." } }, "extras": { @@ -142,7 +142,7 @@ "delay_s": "Delay from standby to off (s)", "max_wait_s": "Maximum wait (s, 0 = unlimited)", "reenable": "Switch back on after external off", - "lock_default_min": "Default expiry of one-time lock (min, 0 = only by consumption)" + "lock_default_min": "Default expiry of one-time lock (min, 0 = no expiry)" } }, "extras": { diff --git a/custom_components/advanced_device/translations/de.json b/custom_components/advanced_device/translations/de.json index 7aaaafa..0b4a869 100644 --- a/custom_components/advanced_device/translations/de.json +++ b/custom_components/advanced_device/translations/de.json @@ -43,12 +43,12 @@ "delay_s": "Verzögerung Standby bis Aus (s)", "max_wait_s": "Maximale Wartezeit (s, 0 = unbegrenzt)", "reenable": "Bei externem Abschalten wieder einschalten", - "lock_default_min": "Standard-Ablaufzeit der Einmal-Sperre (min, 0 = nur durch Verbrauch)" + "lock_default_min": "Standard-Ablaufzeit der Einmal-Sperre (min, 0 = kein Ablauf)" }, "data_description": { "pre_action": "Skript, Button oder Input-Button, der vor dem Ausschalten läuft.", "max_wait_s": "Wie lange ein Ausschaltbefehl höchstens auf Standby wartet. 0 wartet unbegrenzt.", - "lock_default_min": "Standarddauer einer Einmal-Sperre. 0 bedeutet, sie endet erst, wenn das Gerät wieder Strom verbraucht." + "lock_default_min": "Standarddauer einer Einmal-Sperre. 0 bedeutet keinen Ablauf: Die Sperre endet nur, wenn ein Ausschalten sie verbraucht oder sie manuell ausgeschaltet wird." } }, "extras": { @@ -142,7 +142,7 @@ "delay_s": "Verzögerung Standby bis Aus (s)", "max_wait_s": "Maximale Wartezeit (s, 0 = unbegrenzt)", "reenable": "Bei externem Abschalten wieder einschalten", - "lock_default_min": "Standard-Ablaufzeit der Einmal-Sperre (min, 0 = nur durch Verbrauch)" + "lock_default_min": "Standard-Ablaufzeit der Einmal-Sperre (min, 0 = kein Ablauf)" } }, "extras": { diff --git a/custom_components/advanced_device/translations/en.json b/custom_components/advanced_device/translations/en.json index caa7412..d027ee3 100644 --- a/custom_components/advanced_device/translations/en.json +++ b/custom_components/advanced_device/translations/en.json @@ -43,12 +43,12 @@ "delay_s": "Delay from standby to off (s)", "max_wait_s": "Maximum wait (s, 0 = unlimited)", "reenable": "Switch back on after external off", - "lock_default_min": "Default expiry of one-time lock (min, 0 = only by consumption)" + "lock_default_min": "Default expiry of one-time lock (min, 0 = no expiry)" }, "data_description": { "pre_action": "Script, button or input button that runs before the device is switched off.", "max_wait_s": "Longest time a switch-off waits for standby. 0 waits indefinitely.", - "lock_default_min": "Default duration of a one-time lock. 0 means it only ends when the device consumes power again." + "lock_default_min": "Default duration of a one-time lock. 0 means no expiry: the lock ends only when a switch-off uses it up, or when it is turned off manually." } }, "extras": { @@ -142,7 +142,7 @@ "delay_s": "Delay from standby to off (s)", "max_wait_s": "Maximum wait (s, 0 = unlimited)", "reenable": "Switch back on after external off", - "lock_default_min": "Default expiry of one-time lock (min, 0 = only by consumption)" + "lock_default_min": "Default expiry of one-time lock (min, 0 = no expiry)" } }, "extras": { diff --git a/docs/integration.md b/docs/integration.md index 9bb7c8a..9020ded 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -40,7 +40,7 @@ Validation: the standby threshold must not be above the running threshold. | Delay from standby to off | s | 0 | Extra wait after standby is reached. | | Maximum wait | s | 0 | Longest time a switch-off waits for standby. 0 waits without limit. | | Switch back on after external off | | off | See [Re-enable after external off](#re-enable-after-external-off). | -| Default expiry of one-time lock | min | 60 | Default duration of a one-time lock. 0 means the lock ends only when the device consumes power again. | +| Default expiry of one-time lock | min | 60 | Default duration of a one-time lock. 0 means no expiry: the lock ends only when a switch-off uses it up, or when it is turned off manually. | Validation: the shutdown lock needs a standby threshold above 0 W. @@ -49,7 +49,7 @@ Validation: the shutdown lock needs a standby threshold above 0 W. | Field | Unit | Default | Meaning | |---|---|---|---| | Electricity price sensor | | none | Optional `sensor` or `input_number` with the price per kWh. Enables the last cycle cost sensor. | -| Auto-off after standby | min | from profile | Switches the plug off after this long in uninterrupted standby. 0 disables it. | +| Auto-off after standby | min | from profile | Switches the plug off after this long in uninterrupted standby. 0 disables it. The washing machine, dryer and dishwasher profiles default to 0, because these appliances can wait in standby during a delayed start. | | Maximum cycle duration | min | 0 | A longer cycle sets the problem sensor. 0 disables it. | | Maintenance interval | operating hours | 0 | Reminder interval. 0 disables the reminder. | | WashData device | | none | Only shown if `ha_washdata` is installed. See the README. | @@ -107,7 +107,9 @@ The `status` sensor reports one of these states. | `shutting_down` | A switch-off was requested and is waiting for standby, the delay, or the pre-action. | | `unavailable` | The plug switch is unavailable. | -If the power sensor becomes unavailable, the status keeps its last value and the problem sensor reports `power_missing`. The integration does not switch the plug off in this case. +If the power sensor becomes unavailable, the status keeps its last value and the problem sensor reports `power_missing`. The integration does not switch the plug off on its own in this case: auto-off does not fire, and a pending shutdown is not completed until power data returns. A switch-off you request still follows the shutdown lock. If the lock is on, it waits for power data. + +If the plug switch becomes unavailable, the status is `unavailable`, but a running cycle is kept. When the plug is on again, the status comes from the power data. Switching the plug off ends the cycle, unless WashData owns the cycle. ## Events @@ -126,7 +128,7 @@ Additional fields per event: | `advanced_device_cycle_started` | none | A cycle starts (transition to `running`). | | `advanced_device_cycle_finished` | `duration_s`, `energy_kwh`, `cost` | A cycle ends. `cost` is empty without a price sensor. Cycles shorter than the profile's minimum duration are not counted. | | `advanced_device_shutdown_blocked` | `reason`: `one_time_lock` or `external_off` | A switch-off was blocked by the one-time lock, or an external off was reversed. | -| `advanced_device_shutdown_aborted` | none | A switch-off was cancelled because the maximum wait was exceeded. The plug stays on. | +| `advanced_device_shutdown_aborted` | `reason`: `switch_failed` when the switch-off command failed; no `reason` field when the maximum wait was exceeded | A switch-off was cancelled. The plug stays on. | Example automation trigger: @@ -171,14 +173,16 @@ Device triggers are available under the device's **Automations** tab. ### Switch-off sequence -A switch-off from the main switch, the `force_off` button or the auto-off is handled in this order: +A switch-off from the main switch or the auto-off is handled in this order: -1. **One-time lock active:** the switch-off is discarded and the lock is used up. The plug stays on, and `advanced_device_shutdown_blocked` fires with `reason: one_time_lock`. The **Force off** button and the `force_off` action skip this check and also remove an active lock. +1. **One-time lock active:** the switch-off is discarded and the lock is used up. The plug stays on, and `advanced_device_shutdown_blocked` fires with `reason: one_time_lock`. 2. **Shutdown lock off:** the plug switches off immediately. 3. **Shutdown lock on and status `standby`:** the plug switches off after the delay. 4. **Shutdown lock on, any other status:** the status becomes `shutting_down`. The pre-action runs, and the integration waits for `standby`. Then it waits for the delay and switches off. - If the maximum wait is exceeded, the plug is **not** switched off. The shutdown is cancelled, the status returns to the value derived from the power, and `advanced_device_shutdown_aborted` fires. +The **Force off** button and the `force_off` action do not go through this sequence. They switch the plug off at once, ignore the one-time lock and the shutdown lock, and remove an active lock. + Switching the main switch on during `shutting_down` cancels the shutdown. ### Re-enable after external off @@ -213,6 +217,8 @@ The integration must not switch a device off unexpectedly. If the state is uncle Cycle counter, operating hours, maintenance counter, last cycle values and the one-time lock expiry are stored with Home Assistant's storage helper. They survive restarts. +A running cycle is stored too, with its start time and the energy up to the last update. After a restart the cycle continues with its original start and no new cycle starts. Energy from the last seconds before the restart may be missing. + ### Removing the entry When the config entry is removed, the original switch is shown again, but only if it is still hidden by this integration. A switch that you hid yourself stays hidden. @@ -224,3 +230,5 @@ See the [WashData section in the README](../README.md#washdata). In short: - Cycle events and cycle sensors come from WashData when a WashData device is linked. - The shutdown lock is released only in WashData states `finished`, `clean`, `off` and `idle`. - Use the original plug switch, not the Advanced Device switch, as WashData's pause/resume switch. +- A linked WashData entry that is not loaded when the device is set up is not used: the device uses its own cycle logic and shows a repair issue. After WashData is loaded, reload the Advanced Device entry or restart Home Assistant. +- To remove a stale link, open the options and save the **Extras** step. diff --git a/docs/migration-from-blueprint.md b/docs/migration-from-blueprint.md index a81ebe2..5625159 100644 --- a/docs/migration-from-blueprint.md +++ b/docs/migration-from-blueprint.md @@ -73,6 +73,6 @@ For event-based automations, see the events and device triggers in the [referenc - The blueprint's status for an unavailable plug was never set, because of a typo (`unavaiable`). The integration reports `unavailable` correctly. - The idle status used the running duration. The integration has its own idle duration. - **Maximum wait (new).** The blueprint has no maximum wait. In the integration, if the device does not reach standby within the maximum wait, the shutdown is cancelled and the plug stays on. The default is 0, which waits without limit. -- **Lock expiry (new).** A one-time lock expires after a set time, by default 60 minutes. Set the default to 0 for a lock that ends only when the device consumes power again. +- **Lock expiry (new).** A one-time lock expires after a set time, by default 60 minutes. Set the default to 0 for no expiry: the lock then ends only when a switch-off uses it up, or when it is turned off manually. - **Re-enable after external off (new).** Optional, and limited to three attempts. -- **Missing power data.** The integration keeps the plug on when the power sensor is unavailable or data is missing. +- **Missing power data.** The integration keeps the plug on when the power sensor is unavailable or data is missing. Auto-off does not fire, and a pending shutdown does not complete, until power data returns. From 3025aad224d417bbac9cba61f92d24d7bbed058c Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 23:07:56 +0100 Subject: [PATCH 6/8] fix: close off/on paths from plug blips and restored cycles Co-Authored-By: Claude Sonnet 5.5 --- .../advanced_device/core/state_machine.py | 12 +++--- docs/integration.md | 4 +- tests/core/test_state_lock.py | 41 ++++++++++++++++--- tests/core/test_state_restore.py | 25 +++++++++++ 4 files changed, 70 insertions(+), 12 deletions(-) diff --git a/custom_components/advanced_device/core/state_machine.py b/custom_components/advanced_device/core/state_machine.py index 2637404..4083729 100644 --- a/custom_components/advanced_device/core/state_machine.py +++ b/custom_components/advanced_device/core/state_machine.py @@ -108,9 +108,10 @@ def on_plug(self, ts: float, state: PlugState) -> list[Action]: return [] if state is not PlugState.ON: self._feed_gap(ts) + first_reading = self._plug is None self._plug = state self._sync_counting(ts) - if state is not PlugState.ON: + if state is PlugState.OFF: self._power_missing = False self._last_raw = None self._settle_until = None @@ -136,7 +137,7 @@ def on_plug(self, ts: float, state: PlugState) -> list[Action]: self._auto_off_fired = False self._set_status(ts, Status.UNAVAILABLE) return [] - if not self._expect_off and self._may_reenable(): + if not first_reading and not self._expect_off and self._may_reenable(): self._reenable_count += 1 self._reenabling = True return [ @@ -312,7 +313,7 @@ def snapshot(self) -> dict: "operating_s_total": self._counter.total_s, "operating_s_since_maintenance": self._counter.since_maintenance_s, "cycle": None - if not self._cycle.active or self._cycle.started_at is None + if self._cfg.washdata or not self._cycle.active or self._cycle.started_at is None else {"start": self._cycle.started_at, "energy_ws": self._cycle.energy_ws}, } @@ -332,7 +333,8 @@ def restore(self, data: dict, now: float) -> None: self._counter.since_maintenance_s = ( _as_float(data.get("operating_s_since_maintenance"), 0.0) or 0.0 ) - self._restore_cycle(data.get("cycle"), now) + if not self._cfg.washdata: + self._restore_cycle(data.get("cycle"), now) def _restore_cycle(self, value: object, now: float) -> None: if not isinstance(value, dict): @@ -554,7 +556,7 @@ def _confirmed_status(self) -> Status: def _set_status(self, ts: float, status: Status) -> None: if status is Status.STANDBY: - if self._standby_since is None: + if self._standby_since is None and not self._power_missing: self._standby_since = ts else: self._standby_since = None diff --git a/docs/integration.md b/docs/integration.md index 9020ded..c4212c3 100644 --- a/docs/integration.md +++ b/docs/integration.md @@ -217,7 +217,7 @@ The integration must not switch a device off unexpectedly. If the state is uncle Cycle counter, operating hours, maintenance counter, last cycle values and the one-time lock expiry are stored with Home Assistant's storage helper. They survive restarts. -A running cycle is stored too, with its start time and the energy up to the last update. After a restart the cycle continues with its original start and no new cycle starts. Energy from the last seconds before the restart may be missing. +Without WashData, a running cycle is stored too, with its start time and the energy up to the last update. After a restart the cycle continues with its original start, and no new cycle starts. The downtime counts towards the duration: if the cycle ends soon after the restart, `duration_s` is measured from the original start. Energy from the last seconds before the restart may be missing. With WashData linked, no cycle is stored, and the cycle state comes from WashData again after a restart. ### Removing the entry @@ -230,5 +230,5 @@ See the [WashData section in the README](../README.md#washdata). In short: - Cycle events and cycle sensors come from WashData when a WashData device is linked. - The shutdown lock is released only in WashData states `finished`, `clean`, `off` and `idle`. - Use the original plug switch, not the Advanced Device switch, as WashData's pause/resume switch. -- A linked WashData entry that is not loaded when the device is set up is not used: the device uses its own cycle logic and shows a repair issue. After WashData is loaded, reload the Advanced Device entry or restart Home Assistant. +- A linked WashData entry that is not loaded when the device is set up is not used: the device uses its own cycle logic and shows a repair issue. This includes a WashData entry that is still retrying its setup when Home Assistant starts. After WashData is loaded, reload the Advanced Device entry or restart Home Assistant. - To remove a stale link, open the options and save the **Extras** step. diff --git a/tests/core/test_state_lock.py b/tests/core/test_state_lock.py index 637cf79..1a4efdb 100644 --- a/tests/core/test_state_lock.py +++ b/tests/core/test_state_lock.py @@ -113,11 +113,25 @@ def test_external_off_counter_resets_after_give_up(m_running_reenable): def test_turn_on_clears_pending_reenable(m_running_reenable): - m_running_reenable.on_plug(30, PlugState.OFF) # re-enable pending - m_running_reenable.turn_on(31) - assert m_running_reenable.on_plug(32, PlugState.ON) == [] - # Zyklus lief weiter, das bestätigte Band bleibt RUNNING (kein STARTING mehr) - assert m_running_reenable.status is Status.RUNNING + m = m_running_reenable + reenable = [SwitchPlug(True), FireEvent("shutdown_blocked", {"reason": "external_off"})] + # Three external offs are re-enabled; the plug reports ON again after each one. + assert m.on_plug(30, PlugState.OFF) == reenable + assert m.on_plug(31, PlugState.ON) == [] + assert m.on_plug(40, PlugState.OFF) == reenable + assert m.on_plug(41, PlugState.ON) == [] + # Third re-enable still pending when the user turns on: turn_on resets the counter. + assert m.on_plug(50, PlugState.OFF) == reenable + assert m.turn_on(51) == [SwitchPlug(True)] + # The ON reading after turn_on is processed normally (not swallowed by the pending re-enable). + assert m.on_plug(52, PlugState.ON) == [] + assert m.status is Status.RUNNING + # A fourth external off is re-enabled again, so the counter was reset. + assert m.on_plug(60, PlugState.OFF) == reenable + assert m.on_plug(61, PlugState.ON) == [] + m.on_power(62, 1) + m.on_tick(122) + assert m.status is Status.STANDBY def test_auto_off_not_rearmed_by_abort(make): @@ -147,3 +161,20 @@ def test_auto_off_restarts_after_power_returns(m_standby_autooff): m.on_power(1000, 1) # neue Standby-Phase beginnt mit dem bestätigenden Messwert assert m.on_tick(1299) == [] assert m.on_tick(1300) == [SwitchPlug(False)] + + +def test_power_then_plug_unavailable_no_auto_off(make): + m = make(washdata=True, auto_off_s=300) + m.on_plug(0, PlugState.ON) + m.on_washdata_cycle(0, True) + m.on_power(0, 1) + m.on_tick(60) + assert m.status is Status.STANDBY + m.on_power(70, None) + m.on_plug(80, PlugState.UNAVAILABLE) + m.on_plug(90, PlugState.ON) + acts = [] + for ts in range(100, 1091, 10): + acts += m.on_tick(ts) + assert SwitchPlug(False) not in acts + assert "power_missing" in m.problems diff --git a/tests/core/test_state_restore.py b/tests/core/test_state_restore.py index 515d6f4..d37bdf8 100644 --- a/tests/core/test_state_restore.py +++ b/tests/core/test_state_restore.py @@ -114,3 +114,28 @@ def test_restore_invalid_cycle_ignored(make): m = make(min_cycle_s=0) m.restore({"version": 1, "cycle": {"start": "x", "energy_ws": 1}}, now=0) assert not m.cycle_active + + +def test_no_reenable_on_first_plug_reading_after_restore(make): + # WashData owns the cycle, so the plug reading starts the switch-off check. + m = make( + washdata=True, + protection=True, + delay_s=30, + max_wait_s=600, + has_pre_action=True, + reenable_on_external_off=True, + ) + m.on_washdata_cycle(0, True) + acts = m.on_plug(20, PlugState.OFF) + assert SwitchPlug(True) not in acts + + +def test_washdata_cycle_not_persisted(make): + m = make(washdata=True, min_cycle_s=0) + m.on_plug(0, PlugState.ON) + m.on_washdata_cycle(5, True) + assert m.snapshot()["cycle"] is None + m2 = make(washdata=True, min_cycle_s=0) + m2.restore({"version": 1, "cycle": {"start": 5, "energy_ws": 0.0}}, now=10) + assert not m2.cycle_active From 25526cafc9b5840168f5302eff51521752b544d7 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sat, 5 Dec 2026 23:38:00 +0100 Subject: [PATCH 7/8] docs: drop blueprint migration Remove the migration guide, the archived blueprint and the README link. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 1 - docs/blueprint-template.yaml | 455 ------------------------------- docs/migration-from-blueprint.md | 78 ------ 3 files changed, 534 deletions(-) delete mode 100644 docs/blueprint-template.yaml delete mode 100644 docs/migration-from-blueprint.md diff --git a/README.md b/README.md index 4d9d44d..fc6c60e 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,6 @@ If the linked WashData device is removed or not loaded, the coupling is inactive ## Documentation - [Reference: configuration, entities, events, actions and triggers](docs/integration.md) -- [Migrating from the blueprint](docs/migration-from-blueprint.md) ## Built with AI diff --git a/docs/blueprint-template.yaml b/docs/blueprint-template.yaml deleted file mode 100644 index 89c3e83..0000000 --- a/docs/blueprint-template.yaml +++ /dev/null @@ -1,455 +0,0 @@ -blueprint: - name: "🔝 Advanced devices" - author: DevSimon - homeassistant: - min_version: 2024.6.0 - description: - "🔝 Advance your devices by an operation state, shutdown protection, delays, etc...\n\n - - This blueprint enables you to enhance your local power plugs by interpreting its power consumption and additional inputs.\n\n - - This automation is based on the Pyhton script 'ps_hassio_entities'.\n - [![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=pmazz&repository=ps_hassio_entities&category=python_script)" - domain: automation - input: - device_section: - name: Device variables - icon: mdi:devices - collapsed: false - input: - input_switch_state: - name: "{} Status switch" - description: "`switch` `status` \n\n - Switch of the power plug to be controlled.\n - Its recommended to use an UI configured template switch, to avoid overwrites from e.g. an integration.\n" - selector: - entity: - filter: - - domain: switch - input_switch_action: - name: "0|1 Action switch" - description: "`switch` `action` \n\n - Switch that the switching commands should be forwarded to.\n - Only works if the state switch is a template switch fireing events like described in the blueprints description" - default: - selector: - entity: - filter: - - domain: switch - input_power_entity: - name: "🔌 Power sensor" - description: "`power` \n\n - Power sensor of the plug to be monitored.\n" - selector: - entity: - filter: - - device_class: power - power_section: - name: Power configuration - icon: mdi:flash-auto - collapsed: true - input: - input_power_standby_threshold: - name: "📴 Standby threshold" - default: 0 - selector: - number: - min: 0 - max: 1000 - step: 0.5 - mode: box - unit_of_measurement: "W" - input_power_standby_duration: - name: "📴 Standby duration" - default: 10 - selector: - number: - min: 0 - max: 60 - step: 1 - unit_of_measurement: "seconds" - input_power_running_threshold: - name: "🔄 Running threshold" - default: 0 - selector: - number: - min: 0 - max: 1000 - step: 0.5 - mode: box - unit_of_measurement: "W" - input_power_running_duration: - name: "🔄 Running duration" - default: 10 - selector: - number: - min: 0 - max: 60 - step: 1 - unit_of_measurement: "seconds" - icon_section: - name: Target icons - icon: mdi:image-edit - collapsed: true - input: - input_icon_on: - name: "🟢 Enabled icon" - default: mdi:toggle-switch-variant - selector: - icon: - placeholder: mdi:toggle-switch-variant - input_icon_off: - name: "🔴 Disabled icon" - default: mdi:toggle-switch-variant-off - selector: - icon: - placeholder: mdi:toggle-switch-variant-off - input_icon_running: - name: "🔵 Running icon" - default: mdi:sync-circle - selector: - icon: - placeholder: mdi:sync-circle - input_icon_unavailable: - name: "🟠 Unavailable icon" - default: mdi:alert-circle - selector: - icon: - placeholder: mdi:alert-circle - shutdown_protect_section: - name: Shutdown protection/delay - icon: mdi:flash-off - collapsed: true - input: - input_bool_protect_shutdown: - name: "🛡 Enable shutdown protection" - default: false - selector: - boolean: - input_action_before_shutdown: - name: "⚡ Action to enable shutdown" - default: - selector: - action: - input_delay_before_off: - name: "⏳ Delay between standby and shutdown" - default: 0 - selector: - number: - min: 0 - max: 120 - step: 1 - unit_of_measurement: "seconds" - input_switch_force_enabled: - name: "⏩ Switch force enabled" - default: - selector: - entity: - filter: - - domain: switch - attribute_section: - name: Attribute configuration - icon: mdi:list-status - collapsed: true - input: - input_name_status: - name: "🔂 Status attribute name" - default: "status" - selector: - text: - # multiple: true -trigger_variables: - input_switch_state: !input input_switch_state - input_power_standby_threshold: !input input_power_standby_threshold - input_delay_before_off: !input input_delay_before_off -trigger: -- platform: state - id: trig_on - entity_id: !input input_switch_state - to: "on" - from: "off" -- platform: state - id: trig_refresh - entity_id: !input input_switch_state - to: "on" - from: unavaiable -- platform: state - entity_id: !input input_switch_state - id: trig_off - to: "off" -- platform: state - id: trig_unavaiable - entity_id: !input input_switch_state - to: unavaiable -- platform: event - id: trig_event_targeted - event_type: advanced_device_event - event_data: - target: !input input_switch_state -- platform: template - id: trig_shutdown - # value_template: "{{ false if state_attr(input_switch_state, 'shutdown') == '' else as_datetime(state_attr(input_switch_state, 'shutdown')) >= now() }}" - # value_template: "{{ 0 if state_attr(input_switch_state, 'shutdown') == None or state_attr(input_switch_state, 'shutdown') == 'waiting for standby' else as_datetime(state_attr(input_switch_state, 'shutdown')) < now() }}" - value_template: "{{ state_attr(input_switch_state, 'shutdown') != None and state_attr(input_switch_state, 'shutdown') != 'waiting for standby' }}" - for: - seconds: "{{ input_delay_before_off }}" -- platform: numeric_state - id: trig_idle - entity_id: !input input_power_entity - for: - hours: 0 - minutes: 0 - seconds: !input input_power_running_duration - above: !input input_power_standby_threshold - below: !input input_power_running_threshold -- platform: numeric_state - id: trig_running - entity_id: !input input_power_entity - for: - hours: 0 - minutes: 0 - seconds: !input input_power_running_duration - above: !input input_power_running_threshold -- platform: numeric_state - id: trig_standby - entity_id: !input input_power_entity - for: - hours: 0 - minutes: 0 - seconds: !input input_power_standby_duration - below: !input input_power_standby_threshold -- platform: event - event_type: automation_reloaded -- platform: event - id: trig_ha_started - event_type: component_loaded - event_data: - component: automation -variables: - input_switch_state: !input input_switch_state - input_name_status: !input input_name_status - input_power_standby_threshold: !input input_power_standby_threshold - input_switch_force_enabled: !input input_switch_force_enabled - input_delay_before_off: !input input_delay_before_off - var_status_attributes: "{{ 'on' if input_power_standby_threshold == 0 else 'starting' }}" - attr_shutdown: 'shutdown' - attr_shutdown_state_waiting: 'waiting for standby' -action: -- choose: - - conditions: - - condition: trigger - id: - - trig_on - - trig_refresh - - trig_standby - - trig_running - - trig_idle - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - icon: !input input_icon_on - - choose: - - conditions: - - condition: trigger - id: - - trig_on - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ input_name_status }}': '{{ var_status_attributes }}' - - action: python_script.hass_entities - metadata: {} - data: - action: delete_attribute - entity_id: !input input_switch_state - attribute: shutdown - - conditions: - - condition: trigger - id: - - trig_standby - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ input_name_status }}': 'standby' - - if: - - condition: template - value_template: "{{ state_attr(input_switch_state, attr_shutdown) == attr_shutdown_state_waiting }}" - then: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ attr_shutdown }}': "{{ now() + timedelta(seconds=input_delay_before_off) }}" - # - if: - # - condition: template - # value_template: "{{ state_attr(input_switch_state, input_name_status) == 'shutdown' }}" - # then: - # - action: switch.turn_off - # metadata: {} - # data: {} - # target: - # entity_id: !input input_switch_action - # else: - - conditions: - - condition: trigger - id: - - trig_idle - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ input_name_status }}': 'idle' - - icon: !input input_icon_on - - conditions: - - condition: trigger - id: - - trig_running - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ input_name_status }}': 'running' - - icon: !input input_icon_running - - conditions: - - condition: trigger - id: - - trig_off - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - icon: !input input_icon_off - - '{{ input_name_status }}': "off" - - conditions: - - condition: trigger - id: - - trig_unavailable - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - icon: !input input_icon_unavailable - - '{{ input_name_status }}': unavailable - - conditions: - - condition: trigger - id: - - trig_event_targeted - sequence: - choose: - - conditions: - - condition: template - value_template: "{{ trigger.event.data.action == 'off' }}" - sequence: - - choose: - - conditions: - - condition: template - value_template: "{{ states(input_switch_force_enabled) == 'on' }}" - sequence: - - action: switch.turn_off - metadata: {} - data: {} - target: - entity_id: !input input_switch_force_enabled - - conditions: - - condition: template - value_template: !input input_bool_protect_shutdown - sequence: - - if: - - condition: template - value_template: "{{ state_attr(input_switch_state, input_name_status) == 'standby' }}" - then: - - action: switch.turn_off - metadata: {} - data: {} - target: - entity_id: !input input_switch_action - else: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - '{{ input_name_status }}': shutdown - - '{{ attr_shutdown }}': "{{ attr_shutdown_state_waiting }}" - - sequence: !input input_action_before_shutdown - default: - - action: switch.turn_off - metadata: {} - data: {} - target: - entity_id: !input input_switch_action - default: - - action: switch.turn_on - metadata: {} - data: {} - target: - entity_id: !input input_switch_action - - conditions: - - condition: trigger - id: trig_shutdown - sequence: - - action: switch.turn_off - metadata: {} - data: {} - target: - entity_id: !input input_switch_action - default: - - if: - - condition: trigger - id: trig_ha_started - then: - - delay: - hours: 0 - minutes: 0 - seconds: 15 - milliseconds: 0 - - choose: - - conditions: - - condition: state - entity_id: !input input_switch_state - state: "on" - sequence: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - icon: !input input_icon_on - default: - - action: python_script.hass_entities - metadata: {} - data: - action: set_attributes - entity_id: !input input_switch_state - attributes: - - icon: !input input_icon_off -mode: queued -max: 10 diff --git a/docs/migration-from-blueprint.md b/docs/migration-from-blueprint.md deleted file mode 100644 index 5625159..0000000 --- a/docs/migration-from-blueprint.md +++ /dev/null @@ -1,78 +0,0 @@ -# Migrating from the blueprint - -The Advanced Device integration replaces the blueprint "🔝 Advanced devices" (`template.yaml`, kept for reference as [`blueprint-template.yaml`](blueprint-template.yaml)). The blueprint wrote status and icons as attributes onto a template switch and relied on the `python_script` helper. The integration owns its entities, so none of that is needed. - -Set up the integration first, then remove the blueprint automation. - -## Input mapping - -Each blueprint input maps to a setting of the integration. The setting is in the step named in the last column. - -| Blueprint input | Advanced Device setting | Step | -|---|---|---| -| `input_switch_state` (Status switch) | Plug switch | Add device | -| `input_switch_action` (Action switch) | not needed; the integration switches the plug directly | | -| `input_power_entity` (Power sensor) | Power sensor | Add device | -| `input_power_standby_threshold` | Standby threshold (W) | Power thresholds | -| `input_power_standby_duration` | Standby duration (s) | Power thresholds | -| `input_power_running_threshold` | Running threshold (W) | Power thresholds | -| `input_power_running_duration` | Running duration (s) | Power thresholds | -| (uses the running duration) | Idle duration (s), new own field | Power thresholds | -| (not in the blueprint) | Smoothing window (s) | Power thresholds | -| `input_icon_on` | Icon: on | Extras | -| `input_icon_off` | Icon: off | Extras | -| `input_icon_running` | Icon: running | Extras | -| `input_icon_unavailable` | Icon: unavailable | Extras | -| `input_bool_protect_shutdown` | Enable shutdown lock | Shutdown lock | -| `input_action_before_shutdown` (Action to enable shutdown) | Action before switching off: a `script`, `button` or `input_button` entity | Shutdown lock | -| `input_delay_before_off` | Delay from standby to off (s) | Shutdown lock | -| `input_switch_force_enabled` (Switch force enabled) | One-time lock switch, or the `advanced_device.lock_shutdown` action | Entities / Actions | -| `input_name_status` (Status attribute name) | not needed; the status is a sensor entity | | - -Notes on the mapping: - -- **Action before switching off.** The blueprint accepted an inline action. The integration accepts only an entity from the domains `script`, `button` or `input_button`. If your action is inline, create a script with those actions and select the script. -- **Icons.** The blueprint set icons for four states. The integration has an icon for each of the eight statuses. Icons not set in the blueprint take the profile's value. -- **Thresholds.** Values are not copied automatically. Enter them again in the Power thresholds step. Choose the profile that matches the appliance first, because its values prefill that step. -- **Shutdown lock.** The integration requires a standby threshold above 0 W when the shutdown lock is on. - -## What is removed - -These parts of the blueprint setup are no longer needed. Delete them after the integration works. - -- **Template switch.** The integration's main switch replaces it. Remove the template switch and the automation that updated it. -- **The blueprint automation instance.** Delete it under **Settings → Automations & Scenes**. -- **The `python_script` helper** (`python_script.hass_entities`). The integration needs no `python_script` integration or script. -- **Status and icon attributes** on the template switch. - -## Update automations and dashboards - -The blueprint exposed the status as an attribute `status` on the template switch. The integration exposes it as the entity `sensor._status`, with the states `off`, `starting`, `on`, `standby`, `idle`, `running`, `shutting_down` and `unavailable`. - -Replace templates and conditions that read the attribute: - -```yaml -# Before -condition: state -entity_id: switch.washer_template -attribute: status -state: running - -# After -condition: state -entity_id: sensor.washer_status -state: running -``` - -Use the status sensor's entity ID in triggers, conditions and dashboard cards. The main switch of the device (`switch.`) replaces the template switch for turning the plug on and off. - -For event-based automations, see the events and device triggers in the [reference](integration.md#events). The blueprint's "switch force enabled" logic is replaced by the one-time lock, which expires; see [One-time lock](integration.md#one-time-lock). - -## Behaviour differences - -- The blueprint's status for an unavailable plug was never set, because of a typo (`unavaiable`). The integration reports `unavailable` correctly. -- The idle status used the running duration. The integration has its own idle duration. -- **Maximum wait (new).** The blueprint has no maximum wait. In the integration, if the device does not reach standby within the maximum wait, the shutdown is cancelled and the plug stays on. The default is 0, which waits without limit. -- **Lock expiry (new).** A one-time lock expires after a set time, by default 60 minutes. Set the default to 0 for no expiry: the lock then ends only when a switch-off uses it up, or when it is turned off manually. -- **Re-enable after external off (new).** Optional, and limited to three attempts. -- **Missing power data.** The integration keeps the plug on when the power sensor is unavailable or data is missing. Auto-off does not fire, and a pending shutdown does not complete, until power data returns. From 4e05de8e1faa8b9dbefbf6d08656fe4d65c60cf9 Mon Sep 17 00:00:00 2001 From: Developer-Simon Date: Sun, 6 Dec 2026 00:04:19 +0100 Subject: [PATCH 8/8] test: keep entry setup mocked through the options reload OptionsFlowWithReload schedules a reload after the flow; when it ran after the local patch ended, the real setup started and left a delayed Store write behind (flaky 'Lingering timer' at teardown). Patch setup/unload for the whole flow test modules and wait for pending tasks. Co-Authored-By: Claude Sonnet 5.5 --- tests/integration/conftest.py | 14 ++++++++++++++ tests/integration/test_config_flow.py | 3 +++ tests/integration/test_options_flow.py | 3 +++ 3 files changed, 20 insertions(+) diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index d5106b4..1264b99 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -1,5 +1,7 @@ """Shared fixtures for integration tests.""" +from unittest.mock import patch + import pytest from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -134,3 +136,15 @@ def _record(event): hass.bus.async_listen(EVENT_CALL_SERVICE, _record) return calls + + +@pytest.fixture +async def no_entry_setup(hass): + """Keep entry setup/unload mocked for the whole test, including the reload + that OptionsFlowWithReload schedules after the flow finishes.""" + with ( + patch("custom_components.advanced_device.async_setup_entry", return_value=True), + patch("custom_components.advanced_device.async_unload_entry", return_value=True), + ): + yield + await hass.async_block_till_done() diff --git a/tests/integration/test_config_flow.py b/tests/integration/test_config_flow.py index 986d53f..cdd7bc4 100644 --- a/tests/integration/test_config_flow.py +++ b/tests/integration/test_config_flow.py @@ -2,6 +2,7 @@ from unittest.mock import patch +import pytest import voluptuous as vol from homeassistant import config_entries from homeassistant.data_entry_flow import FlowResultType @@ -14,6 +15,8 @@ SWITCH = "switch.washer_plug" POWER = "sensor.washer_power" +pytestmark = pytest.mark.usefixtures("no_entry_setup") + def _user_input(**overrides): data = { diff --git a/tests/integration/test_options_flow.py b/tests/integration/test_options_flow.py index a252216..1b27bc0 100644 --- a/tests/integration/test_options_flow.py +++ b/tests/integration/test_options_flow.py @@ -2,6 +2,7 @@ from unittest.mock import patch +import pytest import voluptuous as vol from homeassistant import config_entries from homeassistant.data_entry_flow import FlowResultType @@ -15,6 +16,8 @@ SWITCH = "switch.washer_plug" POWER = "sensor.washer_power" +pytestmark = pytest.mark.usefixtures("no_entry_setup") + def _current_options(**overrides): options = {