Coverage for custom_components/appliance_autonotify/trace.py: 100%
80 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"""What an appliance of an integration not yet tried on a real appliance does through its first cycles, every state
2of every entity made use of as it comes, kept to be downloaded with its diagnostics and looked over"""
4from __future__ import annotations
6from typing import TYPE_CHECKING, Any, Final
8from homeassistant.core import CALLBACK_TYPE, Event, EventStateChangedData, HomeAssistant, callback
9from homeassistant.helpers import issue_registry as ir
10from homeassistant.helpers.event import async_track_state_change_event
11from homeassistant.helpers.storage import Store
12from homeassistant.util import dt as dt_util
14from .const import DOMAIN
16if TYPE_CHECKING:
17 from collections.abc import Mapping
19TRACE_STORE: Final[str] = f"{DOMAIN}.trace.{{entry_id}}"
20TRACE_STORE_VERSION: Final[int] = 1
21# cycles traced, enough to see one start and end and one more to see it wasn't a fluke
22TRACE_CYCLES: Final[int] = 3
23# changes kept, the oldest going first, should an appliance chatter through a long cycle
24TRACE_LIMIT: Final[int] = 1000
25TRACE_SAVE_DELAY: Final[float] = 10
26# the role kept with the end of a cycle, as the watcher took it
27ENDED: Final[str] = "ended"
28FEEDBACK_ISSUE: Final[str] = "beta_feedback"
29# where to say how it went, for an integration with no issue of its own
30ISSUE_TRACKER: Final[str] = "https://github.com/rhizomatics/appliance_autonotify/issues"
33class CycleTrace:
34 def __init__(self, hass: HomeAssistant, entry_id: str) -> None:
35 self.hass = hass
36 self._store: Store[dict[str, Any]] = Store(hass, TRACE_STORE_VERSION, TRACE_STORE.format(entry_id=entry_id))
37 self.events: list[dict[str, Any]] = []
38 self.cycles_ended: int = 0
39 self.cycles_finished: int = 0
40 # the end of a cycle has just been kept, ahead of the change that ended it where the watcher heard of that
41 # first, as it does where its handler runs straight away, so that change goes before it
42 self._just_ended: bool = False
44 async def async_load(self) -> None:
45 kept = await self._store.async_load() or {}
46 self.events = list(kept.get("events") or [])
47 self.cycles_ended = int(kept.get("cycles_ended") or 0)
48 self.cycles_finished = int(kept.get("cycles_finished") or 0)
50 @property
51 def recording(self) -> bool:
52 return self.cycles_ended < TRACE_CYCLES
54 @callback
55 def async_start(self, roles: Mapping[str, str]) -> CALLBACK_TYPE | None:
56 """Keep every change of the entities given, by entity id with what each is made use of for"""
57 if not self.recording or not roles:
58 return None
60 @callback
61 def changed(event: Event[EventStateChangedData]) -> None:
62 if not self.recording and not self._just_ended:
63 return
64 old, new = event.data["old_state"], event.data["new_state"]
65 change = {
66 "at": dt_util.utcnow().isoformat(),
67 "role": roles.get(event.data["entity_id"], ""),
68 "entity_id": event.data["entity_id"],
69 "from": old.state if old is not None else None,
70 "to": new.state if new is not None else None,
71 }
72 if self._just_ended and self.events and self.events[-1]["role"] == ENDED:
73 self.events.insert(len(self.events) - 1, change)
74 self._kept()
75 else:
76 self._add(change)
78 return async_track_state_change_event(self.hass, list(roles), changed)
80 @callback
81 def async_cycle_ended(self, finished: bool) -> bool:
82 """The end of a cycle as the watcher took it, so it can be seen against what led up to it, saying whether
83 it's the first to have finished"""
84 if not self.recording:
85 return False
86 self.cycles_ended += 1
87 self.cycles_finished += finished
88 self._add({"role": ENDED, "finished": finished})
89 self._just_ended = True
90 self.hass.loop.call_soon(self._settled)
91 return finished and self.cycles_finished == 1
93 @callback
94 def _settled(self) -> None:
95 self._just_ended = False
97 @callback
98 def _add(self, event: dict[str, Any]) -> None:
99 self.events.append({"at": dt_util.utcnow().isoformat()} | event)
100 self._kept()
102 @callback
103 def _kept(self) -> None:
104 del self.events[:-TRACE_LIMIT]
105 self._store.async_delay_save(self.as_dict, TRACE_SAVE_DELAY)
107 def as_dict(self) -> dict[str, Any]:
108 return {"cycles_ended": self.cycles_ended, "cycles_finished": self.cycles_finished, "events": list(self.events)}
110 async def async_remove(self) -> None:
111 await self._store.async_remove()
114def feedback_issue_id(entry_id: str) -> str:
115 return f"{FEEDBACK_ISSUE}_{entry_id}"
118@callback
119def async_ask_feedback(hass: HomeAssistant, entry_id: str, name: str, integration: str, url: str | None) -> None:
120 """Ask how the first cycle went, as a repair, with where to say so"""
121 ir.async_create_issue(
122 hass,
123 DOMAIN,
124 feedback_issue_id(entry_id),
125 is_fixable=False,
126 is_persistent=True,
127 severity=ir.IssueSeverity.WARNING,
128 learn_more_url=url or ISSUE_TRACKER,
129 translation_key=FEEDBACK_ISSUE,
130 translation_placeholders={"name": name, "integration": integration},
131 )
134@callback
135def async_forget_feedback(hass: HomeAssistant, entry_id: str) -> None:
136 ir.async_delete_issue(hass, DOMAIN, feedback_issue_id(entry_id))