Coverage for custom_components/appliance_autonotify/discovery.py: 99%
198 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"""Find appliances with an identifiable cycle, and set each up or offer it as a discovered config entry"""
3from __future__ import annotations
5from dataclasses import dataclass
6from typing import TYPE_CHECKING
8from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_INTEGRATION_DISCOVERY
9from homeassistant.const import CONF_DEVICE_ID, CONF_NAME, CONF_TYPE, UnitOfPower
10from homeassistant.core import Event, HomeAssistant, callback
11from homeassistant.helpers import device_registry as dr
12from homeassistant.helpers import discovery_flow
13from homeassistant.helpers import entity_registry as er
14from homeassistant.loader import IntegrationNotLoaded, async_get_loaded_integration
16from .const import (
17 CONF_AUTO_DISCOVER,
18 CONF_POWER_ENTITY,
19 CYCLE_KEY,
20 CYCLE_TYPES,
21 DERIVED_POWER_PLATFORMS,
22 DOMAIN,
23 ENTITY_DOMAINS,
24 PROGRAM_KEYS,
25 STATES_RUN,
26 TYPE_DISCOVERY,
27 TYPE_VACUUM,
28)
29from .platforms import PlatformProfile, profile_for
30from .words import name_type
32if TYPE_CHECKING:
33 from homeassistant.helpers.device_registry import EventDeviceRegistryUpdatedData
34 from homeassistant.helpers.entity_registry import EventEntityRegistryUpdatedData
36POWER_DEVICE_CLASS = "power"
37SENSOR_DOMAIN = "sensor"
38SWITCH_DOMAIN = "switch"
41@dataclass(frozen=True)
42class Appliance:
43 device_id: str
44 name: str
45 # how its cycle is told, None for an appliance of a vendor platform
46 type: str | None = None
47 # the integration it comes through
48 platform: str | None = None
51@dataclass(frozen=True)
52class PowerMonitor:
53 """A power sensor whose name says it's on an appliance that runs in cycles"""
55 entity_id: str
56 name: str
59def role_key(entity: er.RegistryEntry) -> str | None:
60 """What an entity does, as the translation key Home Connect gives an entity that does the same, by the names of
61 its own integration before those of every integration"""
62 return profile_for(entity.platform).role_key(entity.translation_key)
65def is_cycle_entity(entity: er.RegistryEntry) -> bool:
66 """A sensor of the state of an appliance's cycle, of whichever integration, whose states include one of a cycle
67 under way, so not a sensor of something else that happens to have the same name"""
68 if entity.disabled or entity.device_id is None or entity.domain != SENSOR_DOMAIN or role_key(entity) != CYCLE_KEY:
69 return False
70 options = (entity.capabilities or {}).get("options") or []
71 profile = profile_for(entity.platform)
72 return any(profile.cycle_state(option) in STATES_RUN for option in options)
75@callback
76def cycle_entities(hass: HomeAssistant) -> dict[str, er.RegistryEntry]:
77 """The cycle state entity of every device that has one, by device"""
78 registry = er.async_get(hass)
79 found: dict[str, er.RegistryEntry] = {}
80 for entity in registry.entities.values():
81 if is_cycle_entity(entity) and entity.device_id is not None and _has_needs(registry, entity):
82 found.setdefault(entity.device_id, entity)
83 return found
86def _has_needs(registry: er.EntityRegistry, cycle: er.RegistryEntry) -> bool:
87 """Whether the device of a cycle state entity has whatever else its integration needs it to, to be an appliance"""
88 needs = profile_for(cycle.platform).cycle_needs
89 if not needs:
90 return True
91 roles = {role_key(e) for e in er.async_entries_for_device(registry, cycle.device_id or "") if not e.disabled}
92 return all(need in roles for need in needs)
95@callback
96def companions(hass: HomeAssistant, device_id: str, cycles: dict[str, er.RegistryEntry] | None = None) -> list[str]:
97 """Other devices with a cycle that are the same appliance through another integration, by an id they have in
98 common, as a Samsung appliance's own id is to both SmartThings and LocalThings"""
99 cycles = cycle_entities(hass) if cycles is None else cycles
100 device_registry = dr.async_get(hass)
101 device = device_registry.async_get(device_id)
102 if device is None:
103 return []
104 domains = {domain for domain, _ in device.identifiers}
105 ids = {value for _, value in device.identifiers}
106 found: list[str] = []
107 for other_id in cycles:
108 other = device_registry.async_get(other_id) if other_id != device_id else None
109 if other is not None and any(value in ids and domain not in domains for domain, value in other.identifiers):
110 found.append(other_id)
111 return found
114@callback
115def preference(hass: HomeAssistant, cycle: er.RegistryEntry) -> tuple[bool, int, str]:
116 """How much an appliance's device is preferred to another for the same appliance: one its integration reaches on
117 the local network over one reached through the vendor's cloud, then the one that tells more of its cycle"""
118 try:
119 iot_class = async_get_loaded_integration(hass, cycle.platform).iot_class or ""
120 except IntegrationNotLoaded:
121 iot_class = ""
122 entities = er.async_entries_for_device(er.async_get(hass), cycle.device_id or "")
123 roles = {key for entity in entities if not entity.disabled and (key := role_key(entity)) in ENTITY_DOMAINS}
124 # and of two alike, always the same one
125 return iot_class.startswith("local"), len(roles), cycle.device_id or ""
128@callback
129def _chosen_devices(hass: HomeAssistant) -> tuple[dict[str, er.RegistryEntry], set[str]]:
130 """The cycle state entity of each appliance to offer, by device, and the devices passed over for another one
131 of the same appliance"""
132 cycles = cycle_entities(hass)
133 configured = {entry.unique_id for entry in hass.config_entries.async_entries(DOMAIN, include_ignore=True)}
134 chosen: dict[str, er.RegistryEntry] = {}
135 passed_over: set[str] = set()
136 for device_id, cycle in cycles.items():
137 # the same appliance through two integrations is set up once, through the one preferred, unless it
138 # already is through the other
139 others = [] if device_id in configured else companions(hass, device_id, cycles)
140 if others and (
141 any(other in configured for other in others)
142 or max([device_id, *others], key=lambda d: preference(hass, cycles[d])) != device_id
143 ):
144 passed_over.add(device_id)
145 continue
146 chosen[device_id] = cycle
147 return chosen, passed_over
150@callback
151def find_appliances(hass: HomeAssistant) -> list[Appliance]:
152 """Devices with a cycle state entity, of whichever integration, one for each appliance, and robot vacuums of
153 any make"""
154 device_registry = dr.async_get(hass)
155 found: dict[str, Appliance] = {}
156 for device_id, cycle in _chosen_devices(hass)[0].items():
157 if (device := device_registry.async_get(device_id)) is not None:
158 found[device_id] = Appliance(
159 device_id, device.name_by_user or device.name or cycle.entity_id, platform=cycle.platform
160 )
161 for entity in er.async_get(hass).entities.values():
162 if entity.domain != TYPE_VACUUM or entity.device_id is None or entity.disabled:
163 continue
164 if (device := device_registry.async_get(entity.device_id)) is not None:
165 found[device.id] = Appliance(
166 device.id, device.name_by_user or device.name or entity.entity_id, TYPE_VACUUM, entity.platform
167 )
168 return list(found.values())
171@callback
172def appliance_profile(hass: HomeAssistant, device_id: str) -> PlatformProfile:
173 """The profile of the integration an appliance comes through, by its cycle state entity, or its vacuum"""
174 if (cycle := cycle_entities(hass).get(device_id)) is not None:
175 return profile_for(cycle.platform)
176 vacuum = next(
177 (
178 entity
179 for entity in er.async_entries_for_device(er.async_get(hass), device_id)
180 if entity.domain == TYPE_VACUUM and not entity.disabled
181 ),
182 None,
183 )
184 return profile_for(vacuum.platform if vacuum is not None else None)
187@callback
188def device_type(hass: HomeAssistant, device_id: str, profile: PlatformProfile) -> str | None:
189 """The type of appliance a device is, as its integration names its programs, or failing that, for an integration
190 with several types, its entities, or failing that its model, None where none of them say"""
191 programs: list[str] = []
192 translation_keys: list[str] = []
193 for entity in er.async_entries_for_device(er.async_get(hass), device_id):
194 key = role_key(entity)
195 if key is None or entity.disabled:
196 continue
197 translation_keys.append(entity.translation_key or "")
198 if key in PROGRAM_KEYS and entity.domain in ENTITY_DOMAINS.get(key, ()):
199 programs.extend((entity.capabilities or {}).get("options") or [])
200 if kind := profile.appliance_type(programs, translation_keys):
201 return kind
202 device = dr.async_get(hass).async_get(device_id)
203 model = device.model if isinstance(device, dr.DeviceEntry) and device.model else ""
204 return name_type(hass, model.replace("_", " ")) if model else None
207@callback
208def appliance_beta(hass: HomeAssistant, device_id: str, profile: PlatformProfile | None = None) -> bool:
209 """Whether an appliance is of a type yet to be seen to work through its integration, by its own name where
210 nothing else says what it is"""
211 profile = profile or appliance_profile(hass, device_id)
212 if not profile.beta:
213 return False
214 kind = device_type(hass, device_id, profile)
215 if kind is None and (device := dr.async_get(hass).async_get(device_id)) is not None:
216 kind = name_type(hass, device.name_by_user or device.name or "")
217 return profile.beta_for(kind)
220@callback
221def integration_name(hass: HomeAssistant, platform: str | None) -> str:
222 """The name an integration goes by, or its domain where it isn't loaded"""
223 try:
224 return async_get_loaded_integration(hass, platform or "").name
225 except IntegrationNotLoaded:
226 return platform or ""
229def is_power_sensor(entity: er.RegistryEntry) -> bool:
230 """A power sensor in watts, measured by the device itself rather than estimated or worked out from others"""
231 return (
232 entity.domain == SENSOR_DOMAIN
233 and (entity.device_class or entity.original_device_class) == POWER_DEVICE_CLASS
234 and entity.unit_of_measurement == UnitOfPower.WATT
235 and entity.platform not in DERIVED_POWER_PLATFORMS
236 )
239def names_cycle_appliance(hass: HomeAssistant, name: str) -> bool:
240 """Whether a name is that of an appliance that runs in cycles, by the same words that choose its icon"""
241 return name_type(hass, name) in CYCLE_TYPES
244@callback
245def find_power_monitors(hass: HomeAssistant) -> list[PowerMonitor]:
246 """Power sensors named for an appliance, such as a "Washing machine" plug, one for each device"""
247 entity_registry = er.async_get(hass)
248 device_registry = dr.async_get(hass)
249 # a device already set up by its own integration has no need of its power too
250 configured = {entry.unique_id for entry in hass.config_entries.async_entries(DOMAIN, include_ignore=True)}
251 found: dict[str, PowerMonitor] = {}
252 for entity in sorted(entity_registry.entities.values(), key=lambda e: e.entity_id):
253 if entity.disabled or not is_power_sensor(entity):
254 continue
255 device = device_registry.async_get(entity.device_id) if entity.device_id else None
256 if device is not None and (device.id in configured or device.id in found):
257 continue
258 device_name = (device.name_by_user or device.name or "") if device is not None else ""
259 entity_name = entity.name or entity.original_name or ""
260 if not names_cycle_appliance(hass, f"{device_name} {entity_name}"):
261 continue
262 found[device.id if device is not None else entity.entity_id] = PowerMonitor(
263 entity.entity_id, device_name or entity_name or entity.entity_id
264 )
265 return list(found.values())
268@callback
269def plug_switch(hass: HomeAssistant, power_entity_id: str) -> str | None:
270 """The switch of the device a power sensor is on, where it has only the one, so the plug the appliance is on.
271 A setting, such as a dryer's own Wrinkle prevent, isn't a plug, so isn't counted"""
272 entity_registry = er.async_get(hass)
273 entity = entity_registry.async_get(power_entity_id)
274 if entity is None or entity.device_id is None:
275 return None
276 switches = [
277 switch.entity_id
278 for switch in er.async_entries_for_device(entity_registry, entity.device_id)
279 if switch.domain == SWITCH_DOMAIN and switch.entity_category is None
280 ]
281 return switches[0] if len(switches) == 1 else None
284@callback
285def auto_discovery(hass: HomeAssistant) -> bool:
286 """Whether appliances found are set up without asking, so not while the discovery entry is disabled or deleted"""
287 return any(
288 entry.data.get(CONF_TYPE) == TYPE_DISCOVERY and entry.options.get(CONF_AUTO_DISCOVER)
289 for entry in hass.config_entries.async_entries(DOMAIN, include_disabled=False)
290 )
293@callback
294def async_discover(hass: HomeAssistant) -> None:
295 """Set up every appliance found, or with automatic discovery off, offer each to be added"""
296 source = SOURCE_IMPORT if auto_discovery(hass) else SOURCE_INTEGRATION_DISCOVERY
297 # an appliance offered through one integration, and now found through another preferred to it, is offered
298 # through that one instead
299 passed_over = _chosen_devices(hass)[1]
300 for flow in hass.config_entries.flow.async_progress_by_handler(DOMAIN):
301 if flow["context"].get("unique_id") in passed_over:
302 hass.config_entries.flow.async_abort(flow["flow_id"])
303 for appliance in find_appliances(hass):
304 # appliances already configured, ignored or in progress are dropped by the flow's unique id, and one of an
305 # integration not yet tried on a real appliance is only ever offered, to be added knowing that
306 discovery_flow.async_create_flow(
307 hass,
308 DOMAIN,
309 context={
310 "source": SOURCE_INTEGRATION_DISCOVERY
311 if appliance_beta(hass, appliance.device_id, profile_for(appliance.platform))
312 else source
313 },
314 data={CONF_DEVICE_ID: appliance.device_id, CONF_NAME: appliance.name}
315 | ({CONF_TYPE: appliance.type} if appliance.type else {}),
316 )
317 for monitor in find_power_monitors(hass):
318 # only ever offered, since the name is a guess where a cycle state entity isn't, and the threshold is
319 # worth a look before it's set up
320 discovery_flow.async_create_flow(
321 hass,
322 DOMAIN,
323 context={"source": SOURCE_INTEGRATION_DISCOVERY},
324 data={CONF_POWER_ENTITY: monitor.entity_id, CONF_NAME: monitor.name},
325 )
328@callback
329def async_start_discovery(hass: HomeAssistant) -> None:
330 """Look for appliances now, and again whenever one may have been added or named"""
332 @callback
333 def entity_registry_updated(event: Event[EventEntityRegistryUpdatedData]) -> None:
334 if event.data["action"] not in ("create", "update"):
335 return
336 entity = er.async_get(hass).async_get(event.data["entity_id"])
337 if entity is None:
338 return
339 # any entity of an appliance, which may make one through another integration the one to prefer
340 appliance_entity = role_key(entity) == CYCLE_KEY or role_key(entity) in ENTITY_DOMAINS or entity.domain == TYPE_VACUUM
341 if (event.data["action"] == "create" and appliance_entity) or is_power_sensor(entity):
342 async_discover(hass)
344 @callback
345 def device_registry_updated(event: Event[EventDeviceRegistryUpdatedData]) -> None:
346 # a plug renamed after the appliance it's on
347 if event.data["action"] == "update" and {"name", "name_by_user"} & set(event.data["changes"]):
348 async_discover(hass)
350 hass.bus.async_listen(er.EVENT_ENTITY_REGISTRY_UPDATED, entity_registry_updated)
351 hass.bus.async_listen(dr.EVENT_DEVICE_REGISTRY_UPDATED, device_registry_updated)
352 async_discover(hass)