Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 87 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,89 @@
<img src="https://raw.githubusercontent.com/Developer-Simon/ha-advanced-device/main/custom_components/advanced_device/brand/icon.png" alt="Advanced Device icon" width="88" align="right">

# 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. 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.
- **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 | 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

[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 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.

## Documentation

- [Reference: configuration, entities, events, actions and triggers](docs/integration.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).
2 changes: 2 additions & 0 deletions custom_components/advanced_device/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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()


Expand Down
83 changes: 75 additions & 8 deletions custom_components/advanced_device/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
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 import entity_registry as er
from homeassistant.helpers.selector import (
BooleanSelector,
EntitySelector,
Expand Down Expand Up @@ -46,11 +47,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:
Expand Down Expand Up @@ -147,7 +152,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[
Expand All @@ -158,6 +176,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])] = (
Expand All @@ -166,8 +196,32 @@ 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 _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],
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:
Expand All @@ -176,6 +230,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 = (
Expand Down Expand Up @@ -303,21 +362,23 @@ 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])
defaults = {
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:
Expand All @@ -335,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]
Expand Down Expand Up @@ -460,19 +524,22 @@ 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)
_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)

profile = get_profile(self._options[CONF_PROFILE])
defaults = {
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),
)
5 changes: 4 additions & 1 deletion custom_components/advanced_device/config_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"))
Expand Down Expand Up @@ -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)),
)
2 changes: 1 addition & 1 deletion custom_components/advanced_device/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions custom_components/advanced_device/core/cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions custom_components/advanced_device/core/power.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions custom_components/advanced_device/core/profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down
Loading
Loading