Coverage for custom_components/appliance_autonotify/maintenance.py: 98%
240 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"""Maintenance of appliances, counted in cycles, or read from how much life a part has left where the appliance's own
2integration says, with whatever is due kept on a to-do list and told of once as it falls due"""
4from __future__ import annotations
6import logging
7from dataclasses import dataclass
8from datetime import datetime, timedelta
9from typing import TYPE_CHECKING, Any
11from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, PERCENTAGE
12from homeassistant.core import CALLBACK_TYPE, Context, Event, EventStateChangedData, HomeAssistant, State, callback
13from homeassistant.exceptions import HomeAssistantError
14from homeassistant.helpers import entity_registry as er
15from homeassistant.helpers.event import async_track_point_in_utc_time, async_track_state_change_event
16from homeassistant.helpers.storage import Store
17from homeassistant.util import dt as dt_util
19from .const import (
20 CONF_MAINTENANCE_PREFIX,
21 DOMAIN,
22 LIFESPAN_DUE,
23 LIFESPAN_KEY,
24 LIFESPAN_RESET_PREFIX,
25 MAINTENANCE_ITEMS,
26 MAINTENANCE_MESSAGES,
27 MAINTENANCE_NAMES,
28 MAINTENANCE_SNOOZE_DAYS,
29)
31if TYPE_CHECKING:
32 from collections.abc import Callable, Mapping
34_LOGGER = logging.getLogger(__name__)
36DATA_MAINTENANCE = f"{DOMAIN}_maintenance"
37STORAGE_KEY = f"{DOMAIN}.maintenance"
38STORAGE_VERSION = 1
39# seconds to gather changes into one write
40SAVE_DELAY = 10
43@dataclass(frozen=True)
44class MaintenanceItem:
45 """An item of an appliance's maintenance, due every so many cycles, or once a part's life is down to little"""
47 key: str
48 name: str
49 every: int | None = None
50 entity_id: str | None = None
51 reset_entity_id: str | None = None
54def translated(hass: HomeAssistant, table: Mapping[str, Mapping[str, str]]) -> Mapping[str, str]:
55 """The texts in the language of Home Assistant, English for any other"""
56 return table.get(hass.config.language.split("-")[0], table["en"])
59@callback
60def maintenance_items(
61 hass: HomeAssistant, appliance_type: str | None, device_id: str | None, options: Mapping[str, Any]
62) -> list[MaintenanceItem]:
63 """The items an appliance starts with for its type, at the intervals chosen, and one for each part whose life its
64 own integration reports, such as a robot vacuum's brushes and filter"""
65 names = translated(hass, MAINTENANCE_NAMES)
66 items: list[MaintenanceItem] = []
67 for key, every in MAINTENANCE_ITEMS.get(appliance_type or "", {}).items():
68 cycles = int(options.get(f"{CONF_MAINTENANCE_PREFIX}{key}", every))
69 if cycles > 0:
70 items.append(MaintenanceItem(key, names.get(key, key), every=cycles))
71 if device_id is None:
72 return items
73 entities = er.async_entries_for_device(er.async_get(hass), device_id)
74 resets = {
75 entity.translation_key: entity.entity_id
76 for entity in entities
77 if entity.domain == "button" and entity.translation_key and not entity.disabled
78 }
79 for entity in entities:
80 key = entity.translation_key or ""
81 # only a percentage, there being no telling when a part counted any other way is due
82 if (
83 entity.domain == "sensor"
84 and not entity.disabled
85 and LIFESPAN_KEY in key
86 and entity.unit_of_measurement == PERCENTAGE
87 ):
88 # the name Home Assistant shows is used where there's a state, this for when there isn't
89 fallback = key.replace(LIFESPAN_KEY, "").strip("_").replace("_", " ").capitalize() or key
90 items.append(
91 MaintenanceItem(
92 entity.entity_id,
93 entity.name or entity.original_name or fallback,
94 entity_id=entity.entity_id,
95 reset_entity_id=resets.get(f"{LIFESPAN_RESET_PREFIX}{key}"),
96 )
97 )
98 return items
101class MaintenanceTracker:
102 """The maintenance of every appliance it's tracked for, kept across restarts"""
104 def __init__(self, hass: HomeAssistant) -> None:
105 self.hass = hass
106 self._store: Store[dict[str, Any]] = Store(hass, STORAGE_VERSION, STORAGE_KEY)
107 self._data: dict[str, Any] = {"entries": {}}
108 # the appliances tracked, by entry id, with their name and items
109 self._appliances: dict[str, tuple[str, list[MaintenanceItem]]] = {}
110 self._unsubscribe: dict[str, CALLBACK_TYPE] = {}
111 self._listeners: list[Callable[[], None]] = []
112 self._cancel_wake: CALLBACK_TYPE | None = None
114 async def async_load(self) -> None:
115 self._data = await self._store.async_load() or {"entries": {}}
117 @callback
118 def async_stop(self, *_: Any) -> None:
119 """Nothing left waiting as Home Assistant stops"""
120 if self._cancel_wake is not None:
121 self._cancel_wake()
122 self._cancel_wake = None
124 @callback
125 def async_add_listener(self, listener: Callable[[], None]) -> CALLBACK_TYPE:
126 """Told whenever what's due may have changed"""
127 self._listeners.append(listener)
129 @callback
130 def remove() -> None:
131 self._listeners.remove(listener)
133 return remove
135 def _entry(self, entry_id: str) -> dict[str, Any]:
136 return self._data["entries"].setdefault(entry_id, {"items": {}})
138 def _state(self, entry_id: str, key: str) -> dict[str, Any]:
139 return self._entry(entry_id)["items"].setdefault(key, {})
141 @callback
142 def _changed(self) -> None:
143 self._store.async_delay_save(lambda: self._data, SAVE_DELAY)
144 self._schedule_wake()
145 for listener in list(self._listeners):
146 listener()
148 @callback
149 def async_register(
150 self,
151 entry_id: str,
152 name: str,
153 items: list[MaintenanceItem],
154 on_due: Callable[[MaintenanceItem], None] | None = None,
155 ) -> None:
156 """An appliance whose maintenance is tracked, told through `on_due` of a part falling due as it does, and not
157 only as a cycle ends, since a vacuum may sit on its dock a long while"""
158 self.async_unregister(entry_id)
159 self._appliances[entry_id] = (name, items)
160 for item in items:
161 # replaced while it wasn't being watched
162 self._settle(entry_id, item)
163 if lifespans := [item.entity_id for item in items if item.entity_id]:
165 @callback
166 def lifespan_changed(event: Event[EventStateChangedData]) -> None:
167 new_state = event.data["new_state"]
168 for item in items:
169 if new_state is None or item.entity_id != event.data["entity_id"]:
170 continue
171 # by the reading in the event, since a later one may already be there
172 self._settle(entry_id, item, self._percentage(new_state))
173 state = self._state(entry_id, item.key)
174 if self.due(entry_id, item) and not state.get("told") and on_due is not None:
175 state["told"] = True
176 on_due(item)
177 self._changed()
179 self._unsubscribe[entry_id] = async_track_state_change_event(self.hass, lifespans, lifespan_changed)
180 self._changed()
182 @callback
183 def async_unregister(self, entry_id: str) -> None:
184 if (unsubscribe := self._unsubscribe.pop(entry_id, None)) is not None:
185 unsubscribe()
186 if self._appliances.pop(entry_id, None) is not None:
187 self._changed()
189 @callback
190 def async_forget(self, entry_id: str) -> None:
191 """An appliance removed, along with all it had counted"""
192 self.async_unregister(entry_id)
193 if self._data["entries"].pop(entry_id, None) is not None:
194 self._changed()
196 def tracked(self, entry_id: str) -> bool:
197 return entry_id in self._appliances
199 def offered(self, entry_id: str) -> bool:
200 """Whether tracking has been offered on an end notification, which it's offered on only once"""
201 return bool(self._data["entries"].get(entry_id, {}).get("offered"))
203 @callback
204 def async_mark_offered(self, entry_id: str) -> None:
205 self._entry(entry_id)["offered"] = True
206 # straight away, so it isn't offered again after a restart soon after
207 self._store.async_delay_save(lambda: self._data, 0)
209 def item(self, entry_id: str, key: str) -> MaintenanceItem | None:
210 return next((item for item in self._appliances.get(entry_id, ("", []))[1] if item.key == key), None)
212 def name(self, entry_id: str, item: MaintenanceItem) -> str:
213 """What the item is called, a part's as Home Assistant shows its entity, without the appliance's name"""
214 if item.entity_id is None or (state := self.hass.states.get(item.entity_id)) is None:
215 return item.name
216 appliance = self._appliances.get(entry_id, ("", []))[0]
217 name = str(state.attributes.get(ATTR_FRIENDLY_NAME) or item.name)
218 return name.removeprefix(appliance).strip() or name
220 def message(self, entry_id: str, item: MaintenanceItem) -> str:
221 """What's due, said in the notification and on the list"""
222 messages = translated(self.hass, MAINTENANCE_MESSAGES)
223 name = self.name(entry_id, item)
224 if item.every is None:
225 return messages["lifespan"].format(item=name, value=f"{self.lifespan(item) or 0:g}")
226 cycles = self.cycles(entry_id, item)
227 return messages["cycle" if cycles == 1 else "cycles"].format(item=name, cycles=cycles)
229 def lifespan(self, item: MaintenanceItem) -> float | None:
230 """The life left of a part, as a percentage"""
231 return self._percentage(self.hass.states.get(item.entity_id) if item.entity_id else None)
233 @staticmethod
234 def _percentage(state: State | None) -> float | None:
235 if state is None or state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) != PERCENTAGE:
236 return None
237 try:
238 return float(state.state)
239 except ValueError:
240 return None
242 def cycles(self, entry_id: str, item: MaintenanceItem) -> int:
243 return int(self._data["entries"].get(entry_id, {}).get("items", {}).get(item.key, {}).get("cycles", 0))
245 def _snoozed(self, state: Mapping[str, Any]) -> bool:
246 until = dt_util.parse_datetime(state["snoozed"]) if state.get("snoozed") else None
247 return until is not None and until > dt_util.utcnow()
249 def _settle(self, entry_id: str, item: MaintenanceItem, value: float | None = None) -> None:
250 """A part with plenty of life again has been replaced, however that was done, so is due again only once it
251 runs low once more, by the reading given or else the one there is now"""
252 value = self.lifespan(item) if value is None else value
253 if item.entity_id is not None and value is not None and value > LIFESPAN_DUE:
254 state = self._state(entry_id, item.key)
255 state.pop("acknowledged", None)
256 state.pop("told", None)
258 def due(self, entry_id: str, item: MaintenanceItem) -> bool:
259 state = self._data["entries"].get(entry_id, {}).get("items", {}).get(item.key, {})
260 if self._snoozed(state):
261 return False
262 if item.every is not None:
263 return self.cycles(entry_id, item) >= item.every
264 value = self.lifespan(item)
265 return value is not None and value <= LIFESPAN_DUE and not state.get("acknowledged")
267 def due_items(self) -> list[tuple[str, str, MaintenanceItem]]:
268 """Every item due, with the entry id and name of its appliance"""
269 due: list[tuple[str, str, MaintenanceItem]] = []
270 for entry_id, (name, items) in self._appliances.items():
271 for item in items:
272 if self.due(entry_id, item):
273 due.append((entry_id, name, item))
274 return due
276 @callback
277 def async_cycle_ended(self, entry_id: str) -> list[MaintenanceItem]:
278 """One more cycle counted, returning the items it has made due, which are told of only the once"""
279 items = self._appliances.get(entry_id, ("", []))[1]
280 newly_due: list[MaintenanceItem] = []
281 for item in items:
282 state = self._state(entry_id, item.key)
283 if item.every is not None:
284 state["cycles"] = self.cycles(entry_id, item) + 1
285 self._settle(entry_id, item)
286 if not self.due(entry_id, item):
287 # a count told again once it's due again, as after its cycles are changed, where a part is told
288 # again only once it has read as replaced, not whenever its reading drops out
289 if item.every is not None:
290 state.pop("told", None)
291 elif not state.get("told"):
292 state["told"] = True
293 newly_due.append(item)
294 if items:
295 self._changed()
296 return newly_due
298 def _keys(self, entry_id: str, key: str | None) -> list[str]:
299 return [item.key for item in self._appliances.get(entry_id, ("", []))[1] if key in (None, item.key)]
301 async def async_done(self, entry_id: str, key: str | None = None, context: Context | None = None) -> None:
302 """Maintenance done, the count starting again, and a part reset where its integration has a button for that,
303 or else left alone until it's replaced. For all of an appliance's items, only parts that are due, so the
304 life of the rest isn't thrown away"""
305 for item_key in self._keys(entry_id, key):
306 item = self.item(entry_id, item_key)
307 # by its reading, so one put off is reset along with the rest
308 low = item is not None and (value := self.lifespan(item)) is not None and value <= LIFESPAN_DUE
309 if key is None and item is not None and item.entity_id is not None and not low:
310 continue
311 state = self._state(entry_id, item_key)
312 state.pop("snoozed", None)
313 state.pop("told", None)
314 if item is not None and item.entity_id is None:
315 state["cycles"] = 0
316 continue
317 if item is not None and item.reset_entity_id and self.hass.states.get(item.reset_entity_id) is not None:
318 try:
319 await self.hass.services.async_call(
320 "button", "press", {ATTR_ENTITY_ID: item.reset_entity_id}, blocking=True, context=context
321 )
322 except HomeAssistantError:
323 _LOGGER.exception("APPLIANCES Resetting %s failed", item.reset_entity_id)
324 # until it reads as replaced, which a reset makes it do straight away
325 state["acknowledged"] = True
326 self._changed()
328 @callback
329 def async_snooze(self, entry_id: str, key: str | None = None, days: float = MAINTENANCE_SNOOZE_DAYS) -> None:
330 """Put off, for one item or all an appliance has, after which it's due, and told of, again"""
331 until = (dt_util.utcnow() + timedelta(days=days)).isoformat()
332 for item_key in self._keys(entry_id, key):
333 state = self._state(entry_id, item_key)
334 state["snoozed"] = until
335 state.pop("told", None)
336 self._changed()
338 @callback
339 def async_set_cycles(self, entry_id: str, key: str | None, cycles: int) -> None:
340 """The cycles since an item was last done, as known from before it was tracked here"""
341 for item_key in self._keys(entry_id, key):
342 item = self.item(entry_id, item_key)
343 if item is None or item.every is None:
344 continue
345 state = self._state(entry_id, item_key)
346 state["cycles"] = cycles
347 state.pop("told", None)
348 state.pop("snoozed", None)
349 self._changed()
351 @callback
352 def _schedule_wake(self) -> None:
353 """The list brought up to date as soon as something put off is due again"""
354 if self._cancel_wake is not None:
355 self._cancel_wake()
356 self._cancel_wake = None
357 now = dt_util.utcnow()
358 times = [
359 until
360 for entry in self._data["entries"].values()
361 for state in entry.get("items", {}).values()
362 if state.get("snoozed") and (until := dt_util.parse_datetime(state["snoozed"])) is not None and until > now
363 ]
364 if times:
365 self._cancel_wake = async_track_point_in_utc_time(self.hass, self._woken, min(times))
367 @callback
368 def _woken(self, now: datetime) -> None:
369 self._cancel_wake = None
370 self._changed()