Coverage for custom_components/appliance_autonotify/__init__.py: 99%
128 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-28 12:19 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-28 12:19 +0000
1"""Appliance Auto Notify - automatic notifications for household appliance cycles"""
3from __future__ import annotations
5from typing import TYPE_CHECKING, Any
7from homeassistant.const import CONF_TYPE, EVENT_HOMEASSISTANT_STOP, Platform
8from homeassistant.core import ServiceCall, callback
9from homeassistant.exceptions import ConfigEntryNotReady, ServiceValidationError
10from homeassistant.helpers import config_validation as cv
11from homeassistant.helpers.storage import Store
13from .compat import vol
14from .const import (
15 CONF_DASHBOARD,
16 CONF_DASHBOARD_FOUND,
17 CONF_LIVE_DETAIL,
18 CONF_LIVE_SHOW,
19 CONF_LIVE_TIMER,
20 CONF_LIVE_TITLE,
21 CONF_PROGRAM_IN_TITLE,
22 CYCLE_STORE,
23 CYCLE_STORE_VERSION,
24 DOMAIN,
25 LIVE_SHOW_PHASE,
26 LIVE_SHOW_PROGRAM,
27 LIVE_SHOW_STATE,
28 MAINTENANCE_SNOOZE_DAYS,
29 TYPE_DISCOVERY,
30 TYPE_POWER,
31 TYPE_VACUUM,
32)
33from .dashboards import matching_dashboard
34from .device import async_register_device
35from .discovery import async_discover, async_start_discovery
36from .maintenance import DATA_MAINTENANCE, MaintenanceTracker
37from .repairs import (
38 appliance_gone,
39 appliance_registered,
40 async_forget_removed,
41 async_report_removed,
42 async_watch_removals,
43)
44from .trace import TRACE_STORE, TRACE_STORE_VERSION, async_forget_feedback
45from .watcher import ApplianceWatcher, HomeConnectWatcher, PowerWatcher, VacuumWatcher
46from .words import async_load_words
48if TYPE_CHECKING:
49 from collections.abc import Mapping
51 from homeassistant.config_entries import ConfigEntry
52 from homeassistant.core import HomeAssistant
53 from homeassistant.helpers import device_registry as dr
54 from homeassistant.helpers.typing import ConfigType
56CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
57# the maintenance list is held by the entry for automatic discovery, there being one for every appliance
58DISCOVERY_PLATFORMS: list[Platform] = [Platform.TODO]
60ATTR_CONFIG_ENTRY_ID = "config_entry_id"
61ATTR_ITEM = "item"
62ATTR_CYCLES = "cycles"
63ATTR_DAYS = "days"
64SERVICE_RESET_MAINTENANCE = "reset_maintenance"
65SERVICE_SNOOZE_MAINTENANCE = "snooze_maintenance"
66RESET_SCHEMA = vol.Schema({
67 vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
68 vol.Optional(ATTR_ITEM): cv.string,
69 vol.Optional(ATTR_CYCLES, default=0): vol.All(vol.Coerce(int), vol.Range(min=0)),
70})
71SNOOZE_SCHEMA = vol.Schema({
72 vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
73 vol.Optional(ATTR_ITEM): cv.string,
74 vol.Optional(ATTR_DAYS, default=MAINTENANCE_SNOOZE_DAYS): vol.All(vol.Coerce(float), vol.Range(min=0)),
75})
77type AppliancesConfigEntry = ConfigEntry[ApplianceWatcher]
80async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
81 await async_load_words(hass)
82 tracker = MaintenanceTracker(hass)
83 await tracker.async_load()
84 hass.data[DATA_MAINTENANCE] = tracker
85 hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, tracker.async_stop)
86 _register_services(hass, tracker)
87 async_start_discovery(hass)
88 async_watch_removals(hass)
89 return True
92@callback
93def _register_services(hass: HomeAssistant, tracker: MaintenanceTracker) -> None:
94 """Maintenance done, or put off, without the notification, for one item of an appliance or all it has"""
96 def tracked(call: ServiceCall) -> tuple[str, str | None]:
97 entry_id: str = call.data[ATTR_CONFIG_ENTRY_ID]
98 key: str | None = call.data.get(ATTR_ITEM)
99 if not tracker.tracked(entry_id):
100 raise ServiceValidationError(
101 translation_domain=DOMAIN, translation_key="not_tracked", translation_placeholders={"entry_id": entry_id}
102 )
103 if key is not None and tracker.item(entry_id, key) is None:
104 raise ServiceValidationError(
105 translation_domain=DOMAIN,
106 translation_key="no_item",
107 translation_placeholders={"item": key, "entry_id": entry_id},
108 )
109 return entry_id, key
111 async def reset(call: ServiceCall) -> None:
112 entry_id, key = tracked(call)
113 if call.data[ATTR_CYCLES] and key is not None and (item := tracker.item(entry_id, key)) and item.every is None:
114 raise ServiceValidationError(
115 translation_domain=DOMAIN, translation_key="part_life_read", translation_placeholders={"item": key}
116 )
117 if call.data[ATTR_CYCLES]:
118 tracker.async_set_cycles(entry_id, key, call.data[ATTR_CYCLES])
119 else:
120 await tracker.async_done(entry_id, key, call.context)
122 async def snooze(call: ServiceCall) -> None:
123 entry_id, key = tracked(call)
124 tracker.async_snooze(entry_id, key, call.data[ATTR_DAYS])
126 hass.services.async_register(DOMAIN, SERVICE_RESET_MAINTENANCE, reset, schema=RESET_SCHEMA)
127 hass.services.async_register(DOMAIN, SERVICE_SNOOZE_MAINTENANCE, snooze, schema=SNOOZE_SCHEMA)
130async def async_migrate_entry(hass: HomeAssistant, entry: AppliancesConfigEntry) -> bool:
131 if entry.version > 1:
132 # from a later version, so not to be guessed at
133 return False
134 if entry.minor_version < 2:
135 options = dict(entry.options)
136 # the program left out of the title is the name alone, and left in it is the choice as it comes
137 if options.pop(CONF_PROGRAM_IN_TITLE, True) is False:
138 options[CONF_LIVE_TITLE] = "name"
139 hass.config_entries.async_update_entry(entry, options=options, minor_version=2)
140 if entry.minor_version < 3:
141 # set up before a dashboard was looked for, so left with whatever was chosen
142 hass.config_entries.async_update_entry(entry, data=entry.data | {CONF_DASHBOARD_FOUND: True}, minor_version=3)
143 if entry.minor_version < 4:
144 hass.config_entries.async_update_entry(entry, options=live_options(entry.options), minor_version=4)
145 return True
148def live_options(options: Mapping[str, Any]) -> dict[str, Any]:
149 """What a Live Activity shows, from the title and the detail once chosen, as near as ticking what's shown comes
150 to them, and left to the usual choice where they were"""
151 options = dict(options)
152 title, detail = options.pop(CONF_LIVE_TITLE, None), options.pop(CONF_LIVE_DETAIL, None)
153 if detail in (LIVE_SHOW_PROGRAM, "status", "program_status"):
154 # chosen in place of the time left, which a vacuum never had
155 options[CONF_LIVE_TIMER] = False
156 if detail == LIVE_SHOW_PROGRAM:
157 options[CONF_LIVE_SHOW] = [LIVE_SHOW_PROGRAM, LIVE_SHOW_STATE]
158 elif detail == "status":
159 options[CONF_LIVE_SHOW] = [LIVE_SHOW_PHASE, LIVE_SHOW_STATE]
160 elif title == "name" and detail in (None, "time_remaining"):
161 # the name alone over the time left
162 options[CONF_LIVE_SHOW] = []
163 return options
166async def async_setup_entry(hass: HomeAssistant, entry: AppliancesConfigEntry) -> bool:
167 if entry.data.get(CONF_TYPE) == TYPE_DISCOVERY:
168 # nothing to watch, only to look again now that automatic discovery may have been switched
169 async_discover(hass)
170 await hass.config_entries.async_forward_entry_setups(entry, DISCOVERY_PLATFORMS)
171 return True
172 if appliance_registered(hass, entry):
173 async_forget_removed(hass, entry.entry_id)
174 elif entry.data.get(CONF_TYPE) != TYPE_POWER:
175 # removed while Home Assistant was off, so kept retrying only in case it's added back, with a repair to say so
176 async_report_removed(hass, entry)
177 raise ConfigEntryNotReady(
178 translation_domain=DOMAIN, translation_key="appliance_removed", translation_placeholders={"name": entry.title}
179 )
180 watchers: dict[str | None, type[ApplianceWatcher]] = {TYPE_POWER: PowerWatcher, TYPE_VACUUM: VacuumWatcher}
181 watcher = watchers.get(entry.data.get(CONF_TYPE), HomeConnectWatcher)(hass, entry)
182 # a cycle under way before Home Assistant restarted, to carry on with as it starts
183 await watcher.async_load()
184 watcher.async_start()
185 watcher.async_watch_health()
186 await watcher.async_start_trace()
187 if not watcher.beta:
188 # its type of appliance has since been seen to work through its integration, so there's nothing more to ask
189 async_forget_feedback(hass, entry.entry_id)
190 watcher.async_listen_for_actions()
191 watcher.async_start_maintenance()
192 entry.runtime_data = watcher
193 async_register_device(hass, entry, watcher.name)
194 if not entry.data.get(CONF_DASHBOARD_FOUND):
195 _choose_dashboard(hass, entry, watcher)
196 return True
199def _choose_dashboard(hass: HomeAssistant, entry: AppliancesConfigEntry, watcher: ApplianceWatcher) -> None:
200 """A dashboard named for the appliance or its type, chosen as it's first set up, once its type is known, to be
201 changed or cleared in its settings like one chosen by hand"""
202 options = dict(entry.options)
203 if not options.get(CONF_DASHBOARD) and (match := matching_dashboard(hass, watcher.name, watcher.appliance_type)):
204 options[CONF_DASHBOARD] = match
205 hass.config_entries.async_update_entry(entry, data=entry.data | {CONF_DASHBOARD_FOUND: True}, options=options)
208async def async_unload_entry(hass: HomeAssistant, entry: AppliancesConfigEntry) -> bool:
209 if entry.data.get(CONF_TYPE) == TYPE_DISCOVERY:
210 return await hass.config_entries.async_unload_platforms(entry, DISCOVERY_PLATFORMS)
211 # the watcher's listeners are removed by the entry's own unload callbacks
212 return True
215async def async_remove_entry(hass: HomeAssistant, entry: AppliancesConfigEntry) -> None:
216 # whatever was kept of its cycle through a restart
217 await Store(hass, CYCLE_STORE_VERSION, CYCLE_STORE.format(entry_id=entry.entry_id)).async_remove()
218 # and of its first cycles, with the question of how they went
219 await Store(hass, TRACE_STORE_VERSION, TRACE_STORE.format(entry_id=entry.entry_id)).async_remove()
220 async_forget_feedback(hass, entry.entry_id)
221 async_forget_removed(hass, entry.entry_id)
222 # what was counted goes with the appliance
223 if (tracker := hass.data.get(DATA_MAINTENANCE)) is not None:
224 tracker.async_forget(entry.entry_id)
227async def async_remove_config_entry_device(
228 hass: HomeAssistant, entry: AppliancesConfigEntry, device_entry: dr.AnyDeviceEntry
229) -> bool:
230 """An appliance's device can be deleted by hand once the appliance is gone from Home Assistant, and not before,
231 since it would only be made again"""
232 return appliance_gone(hass, entry)