Coverage for custom_components/appliance_autonotify/repairs.py: 95%
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"""Repairs for what needs someone to act on it: an appliance removed from Home Assistant, whose entry would otherwise be
2left retrying for good, and notifications with nowhere to go"""
4from __future__ import annotations
6from typing import TYPE_CHECKING, Any, Final
8from homeassistant.components.repairs import ConfirmRepairFlow, RepairsFlow
9from homeassistant.const import CONF_DEVICE_ID, CONF_TYPE
10from homeassistant.core import Event, HomeAssistant, callback
11from homeassistant.helpers import device_registry as dr
12from homeassistant.helpers import entity_registry as er
13from homeassistant.helpers import issue_registry as ir
15from .const import CONF_POWER_ENTITY, DOMAIN, TYPE_DISCOVERY, TYPE_POWER
17if TYPE_CHECKING:
18 from homeassistant.components.repairs import RepairsFlowResult
19 from homeassistant.config_entries import ConfigEntry
20 from homeassistant.helpers.device_registry import EventDeviceRegistryUpdatedData
21 from homeassistant.helpers.entity_registry import EventEntityRegistryUpdatedData
23REMOVED_ISSUE: Final[str] = "appliance_removed"
24NO_TARGETS_ISSUE: Final[str] = "no_targets"
25TROUBLESHOOTING_URL: Final[str] = "https://appliance-autonotify.rhizomatics.org.uk/#nothing-sent"
28def removed_issue_id(entry_id: str) -> str:
29 return f"{REMOVED_ISSUE}_{entry_id}"
32@callback
33def appliance_gone(hass: HomeAssistant, entry: ConfigEntry) -> bool:
34 """Whether what the appliance is watched through has been removed from Home Assistant: its own device, or for one
35 known by its power, the power sensor, which may be one never registered, so is only gone with no state either"""
36 if entry.data.get(CONF_TYPE) == TYPE_DISCOVERY:
37 return False
38 if entry.data.get(CONF_TYPE) == TYPE_POWER:
39 power: str = entry.options.get(CONF_POWER_ENTITY, "")
40 return er.async_get(hass).async_get(power) is None and hass.states.get(power) is None
41 return dr.async_get(hass).async_get(entry.data.get(CONF_DEVICE_ID, "")) is None
44@callback
45def appliance_registered(hass: HomeAssistant, entry: ConfigEntry) -> bool:
46 """Whether what the appliance is watched through is in Home Assistant's registries, which is the one sure sign it's
47 there: the state of a power sensor removed lingers a moment after its registry entry goes"""
48 if entry.data.get(CONF_TYPE) == TYPE_POWER:
49 return er.async_get(hass).async_get(entry.options.get(CONF_POWER_ENTITY, "")) is not None
50 return not appliance_gone(hass, entry)
53@callback
54def async_report_removed(hass: HomeAssistant, entry: ConfigEntry) -> None:
55 ir.async_create_issue(
56 hass,
57 DOMAIN,
58 removed_issue_id(entry.entry_id),
59 is_fixable=True,
60 is_persistent=False,
61 severity=ir.IssueSeverity.WARNING,
62 translation_key=REMOVED_ISSUE,
63 translation_placeholders={"name": entry.title},
64 data={"entry_id": entry.entry_id},
65 )
68@callback
69def async_forget_removed(hass: HomeAssistant, entry_id: str) -> None:
70 ir.async_delete_issue(hass, DOMAIN, removed_issue_id(entry_id))
73@callback
74def async_watch_removals(hass: HomeAssistant) -> None:
75 """An appliance's device, or the power sensor of one known by its power, removed from Home Assistant, as when the
76 appliance is removed from its own integration, raises a repair offering to remove it here too, and its entry is
77 reloaded so it stops watching; added back, as a device restored by its integration is, it's watched again"""
79 @callback
80 def changed(entry: ConfigEntry, removed: bool) -> None:
81 if removed:
82 async_report_removed(hass, entry)
83 else:
84 async_forget_removed(hass, entry.entry_id)
85 # a power monitored appliance just has nothing more to hear from, where one with a device of its own retries
86 if entry.data.get(CONF_TYPE) != TYPE_POWER and not entry.disabled_by:
87 hass.config_entries.async_schedule_reload(entry.entry_id)
89 @callback
90 def device_updated(event: Event[EventDeviceRegistryUpdatedData]) -> None:
91 if event.data["action"] not in ("create", "remove"):
92 return
93 for entry in hass.config_entries.async_entries(DOMAIN):
94 if entry.data.get(CONF_TYPE) not in (TYPE_DISCOVERY, TYPE_POWER) and (
95 entry.data.get(CONF_DEVICE_ID) == event.data["device_id"]
96 ):
97 changed(entry, event.data["action"] == "remove")
99 @callback
100 def entity_updated(event: Event[EventEntityRegistryUpdatedData]) -> None:
101 if event.data["action"] not in ("create", "remove"):
102 return
103 for entry in hass.config_entries.async_entries(DOMAIN):
104 if entry.data.get(CONF_TYPE) == TYPE_POWER and entry.options.get(CONF_POWER_ENTITY) == event.data["entity_id"]:
105 changed(entry, event.data["action"] == "remove")
107 hass.bus.async_listen(dr.EVENT_DEVICE_REGISTRY_UPDATED, device_updated)
108 hass.bus.async_listen(er.EVENT_ENTITY_REGISTRY_UPDATED, entity_updated)
111@callback
112def async_report_no_targets(hass: HomeAssistant, name: str) -> None:
113 """Nowhere to send notifications, with no Supernotify, no targets chosen and no phone with the app, which is
114 otherwise only logged, where it may never be seen"""
115 ir.async_create_issue(
116 hass,
117 DOMAIN,
118 NO_TARGETS_ISSUE,
119 is_fixable=False,
120 is_persistent=False,
121 severity=ir.IssueSeverity.WARNING,
122 learn_more_url=TROUBLESHOOTING_URL,
123 translation_key=NO_TARGETS_ISSUE,
124 translation_placeholders={"name": name},
125 )
128@callback
129def async_forget_no_targets(hass: HomeAssistant) -> None:
130 ir.async_delete_issue(hass, DOMAIN, NO_TARGETS_ISSUE)
133class RemoveApplianceFlow(RepairsFlow):
134 """Remove the entry of an appliance that's gone from Home Assistant, with its device and all that was kept of it"""
136 def __init__(self, entry_id: str) -> None:
137 self.entry_id = entry_id
139 async def async_step_init(self, user_input: dict[str, Any] | None = None) -> RepairsFlowResult:
140 return await self.async_step_confirm()
142 async def async_step_confirm(self, user_input: dict[str, Any] | None = None) -> RepairsFlowResult:
143 entry = self.hass.config_entries.async_get_entry(self.entry_id)
144 if user_input is not None:
145 if entry is not None:
146 await self.hass.config_entries.async_remove(self.entry_id)
147 return self.async_create_entry(data={})
148 return self.async_show_form(
149 step_id="confirm", description_placeholders={"name": entry.title if entry is not None else ""}
150 )
153async def async_create_fix_flow(hass: HomeAssistant, issue_id: str, data: dict[str, Any] | None) -> RepairsFlow:
154 if issue_id.startswith(REMOVED_ISSUE) and data is not None:
155 return RemoveApplianceFlow(str(data["entry_id"]))
156 return ConfirmRepairFlow()