Coverage for custom_components/appliance_autonotify/config_flow.py: 99%
209 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"""Config flow for Appliance Auto Notify, one config entry per appliance"""
3from __future__ import annotations
5from typing import Any
7from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlowWithReload
8from homeassistant.const import CONF_DEVICE_ID, CONF_NAME, CONF_TYPE, UnitOfPower, UnitOfTime
9from homeassistant.core import HomeAssistant, callback
10from homeassistant.data_entry_flow import section
11from homeassistant.helpers.selector import (
12 BooleanSelector,
13 EntitySelector,
14 EntitySelectorConfig,
15 NumberSelector,
16 NumberSelectorConfig,
17 NumberSelectorMode,
18 SelectOptionDict,
19 SelectSelector,
20 SelectSelectorConfig,
21 SelectSelectorMode,
22 TargetSelector,
23 TextSelector,
24 TextSelectorConfig,
25)
27from .compat import vol
28from .const import (
29 BETA_FOUND,
30 BETA_NOTICE,
31 CONF_AUTO_DISCOVER,
32 CONF_CUSTOM_TARGET,
33 CONF_DASHBOARD,
34 CONF_DELIVERIES,
35 CONF_END_MESSAGE,
36 CONF_END_TITLE,
37 CONF_GRACE_PERIOD,
38 CONF_LIVE_SHOW,
39 CONF_LIVE_TIMER,
40 CONF_MAINTENANCE,
41 CONF_MAINTENANCE_PREFIX,
42 CONF_MIN_DURATION,
43 CONF_NOTIFY_END,
44 CONF_NOTIFY_PHASE,
45 CONF_NOTIFY_PROGRESS,
46 CONF_NOTIFY_START,
47 CONF_OFFLINE_AFTER,
48 CONF_POWER_ENTITY,
49 CONF_REMINDER,
50 CONF_REMINDER_REPEATS,
51 CONF_START_MESSAGE,
52 CONF_START_TITLE,
53 CONF_SWITCH_ENTITY,
54 CONF_SWITCH_OFF_BUTTON,
55 CONF_TARGET,
56 CONF_TARGETS,
57 CONF_THRESHOLD,
58 COST_PLACEHOLDER,
59 DEFAULT_GRACE_PERIOD,
60 DEFAULT_MIN_DURATION,
61 DEFAULT_REMINDER_REPEATS,
62 DEFAULT_THRESHOLD,
63 DEFAULT_TITLE,
64 DISCOVERY_TITLE,
65 DOMAIN,
66 DURATION_PLACEHOLDER,
67 ENERGY_PLACEHOLDER,
68 LIVE_DEFAULTS,
69 LIVE_SHOWS,
70 MAINTENANCE_ITEMS,
71 NAME_PLACEHOLDER,
72 NOTIFICATION_TEXTS,
73 PROGRAM_PLACEHOLDER,
74 START_TIME_PLACEHOLDER,
75 SUPERNOTIFY_MISSING,
76 SUPERNOTIFY_PRESENT,
77 TEXT_END,
78 TEXT_START,
79 TYPE_DISCOVERY,
80 TYPE_POWER,
81 TYPE_VACUUM,
82 VACUUM_SETTLE,
83)
84from .dashboards import dashboards
85from .discovery import appliance_beta, appliance_profile, find_appliances, integration_name, plug_switch
86from .maintenance import translated
87from .platforms import profile_for
88from .supernotify_api import deliveries_by_transport, supernotify_available
89from .words import DATA_WORDS, async_load_words
91STEP_POWER = "power"
92STEP_DISCOVERY = "discovery"
93STEP_SETTINGS = "settings"
94SECTION_START = "start"
95SECTION_END = "end"
96SECTION_NOTIFY = "notify"
97SECTION_MAINTENANCE = "maintenance_items"
99# a switch or a choice left as it comes isn't a setting either
100DEFAULT_CHOICES: dict[str, Any] = {
101 CONF_NOTIFY_START: False,
102 CONF_NOTIFY_END: True,
103 CONF_NOTIFY_PROGRESS: False,
104 **LIVE_DEFAULTS,
105}
108def default_texts(hass: HomeAssistant) -> dict[str, str]:
109 """The texts as they come, in the language of Home Assistant"""
110 texts = translated(hass, NOTIFICATION_TEXTS)
111 return {
112 CONF_START_TITLE: DEFAULT_TITLE,
113 CONF_START_MESSAGE: texts[TEXT_START],
114 CONF_END_TITLE: DEFAULT_TITLE,
115 CONF_END_MESSAGE: texts[TEXT_END],
116 }
119def supernotify_status(hass: HomeAssistant) -> str:
120 return SUPERNOTIFY_PRESENT if supernotify_available(hass) else SUPERNOTIFY_MISSING
123def beta_notice(hass: HomeAssistant, device_id: str | None) -> str:
124 """A word that the appliance's integration is yet to be tried on a real appliance, where it is"""
125 if not device_id:
126 return ""
127 profile = appliance_profile(hass, device_id)
128 if not appliance_beta(hass, device_id, profile):
129 return ""
130 return BETA_NOTICE.format(integration=integration_name(hass, profile.platform))
133def discovery_schema(auto_discover: bool = True) -> vol.Schema:
134 return vol.Schema({vol.Required(CONF_AUTO_DISCOVER, default=auto_discover): BooleanSelector()})
137async def settings_schema(
138 hass: HomeAssistant,
139 progress: bool = True,
140 phase: bool | None = None,
141 settle: bool = False,
142 live: bool = True,
143 vacuum: bool = False,
144 maintenance: dict[str, int] | None = None,
145) -> vol.Schema:
146 """The settings of an appliance, with maintenance for one with something to maintain, and the cycles between each
147 of the items for its type, as `maintenance` has them"""
148 fields: dict[vol.Marker, Any] = {
149 vol.Required(CONF_NOTIFY_START, default=False): BooleanSelector(),
150 vol.Required(CONF_NOTIFY_END, default=True): BooleanSelector(),
151 }
152 if maintenance is not None:
153 fields[vol.Required(CONF_MAINTENANCE, default=False)] = BooleanSelector()
154 if phase is not None:
155 # only for an appliance with phases, and on or off to begin with by how much they matter for its type
156 fields[vol.Required(CONF_NOTIFY_PHASE, default=phase)] = BooleanSelector()
157 if progress:
158 fields[vol.Required(CONF_NOTIFY_PROGRESS, default=False)] = BooleanSelector()
159 # none unless chosen, since an appliance switched off at the wall is unavailable too
160 fields[vol.Required(CONF_OFFLINE_AFTER, default=0)] = NumberSelector(
161 NumberSelectorConfig(min=0, max=1440, step=1, mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfTime.MINUTES)
162 )
163 if live and supernotify_available(hass):
164 # only a Live Activity shows what the appliance is doing as the cycle goes on, and has a timer, which a
165 # vacuum hasn't
166 if not vacuum:
167 fields[vol.Required(CONF_LIVE_TIMER, default=LIVE_DEFAULTS[CONF_LIVE_TIMER])] = BooleanSelector()
168 fields[vol.Required(CONF_LIVE_SHOW, default=LIVE_DEFAULTS[CONF_LIVE_SHOW])] = SelectSelector(
169 SelectSelectorConfig(
170 options=list(LIVE_SHOWS), multiple=True, mode=SelectSelectorMode.LIST, translation_key=CONF_LIVE_SHOW
171 )
172 )
173 notify: dict[vol.Marker, Any] = {}
174 end: dict[vol.Marker, Any] = {
175 vol.Optional(CONF_END_TITLE): TextSelector(),
176 vol.Optional(CONF_END_MESSAGE): TextSelector(TextSelectorConfig(multiline=True)),
177 }
178 if supernotify_available(hass):
179 # a choice of what's there, and not a box to type in, so a notification can't be made to open anything else
180 choices = [SelectOptionDict(value=path, label=title) for path, title in dashboards(hass).items()]
181 if choices:
182 fields[vol.Optional(CONF_DASHBOARD)] = SelectSelector(
183 SelectSelectorConfig(options=choices, mode=SelectSelectorMode.DROPDOWN)
184 )
185 # the same pair of target fields as supernotify.notify itself
186 notify[vol.Optional(CONF_TARGET)] = TargetSelector()
187 notify[vol.Optional(CONF_CUSTOM_TARGET)] = TextSelector(TextSelectorConfig(multiple=True))
188 deliveries = sorted({name for names in (await deliveries_by_transport(hass)).values() for name in names})
189 notify[vol.Optional(CONF_DELIVERIES)] = SelectSelector(SelectSelectorConfig(options=deliveries, multiple=True))
190 # buttons and reminders go with the end notification, which only Supernotify can give buttons
191 end[vol.Optional(CONF_REMINDER)] = NumberSelector(
192 NumberSelectorConfig(min=0, max=720, step=1, mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfTime.MINUTES)
193 )
194 end[vol.Required(CONF_REMINDER_REPEATS, default=DEFAULT_REMINDER_REPEATS)] = NumberSelector(
195 NumberSelectorConfig(min=1, max=20, step=1, mode=NumberSelectorMode.BOX)
196 )
197 else:
198 notify[vol.Optional(CONF_TARGETS)] = EntitySelector(EntitySelectorConfig(domain="notify", multiple=True))
199 if settle:
200 # a robot vacuum's wait on its dock before its cleaning is over, where its own progress doesn't say
201 end[vol.Required(CONF_GRACE_PERIOD, default=VACUUM_SETTLE)] = NumberSelector(
202 NumberSelectorConfig(min=1, max=3600, step=1, mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfTime.SECONDS)
203 )
204 sections: dict[str, dict[vol.Marker, Any]] = {
205 SECTION_START: {
206 vol.Optional(CONF_START_TITLE): TextSelector(),
207 vol.Optional(CONF_START_MESSAGE): TextSelector(TextSelectorConfig(multiline=True)),
208 },
209 SECTION_END: end,
210 SECTION_NOTIFY: notify,
211 }
212 if maintenance:
213 # 0 for an item not to be tracked
214 sections[SECTION_MAINTENANCE] = {
215 vol.Required(f"{CONF_MAINTENANCE_PREFIX}{key}", default=every): NumberSelector(
216 NumberSelectorConfig(min=0, max=1000, step=1, mode=NumberSelectorMode.BOX)
217 )
218 for key, every in maintenance.items()
219 }
220 # all tuning, so out of the way until it's wanted
221 # the maintenance items as they come unless changed, so the section needn't be sent
222 fields.update({
223 (vol.Optional if name == SECTION_MAINTENANCE else vol.Required)(name): section(
224 vol.Schema(contents), {"collapsed": True}
225 )
226 for name, contents in sections.items()
227 })
228 return vol.Schema(fields)
231def sectioned(schema: vol.Schema, values: dict[str, Any]) -> dict[str, Any]:
232 """Settings are stored flat, the sections are only for display"""
233 shown: dict[str, Any] = {}
234 for name, field in schema.schema.items():
235 if isinstance(field, section):
236 shown[str(name)] = {str(key): values[key] for key in field.schema.schema if key in values}
237 elif name in values:
238 shown[str(name)] = values[name]
239 return shown
242def flattened(user_input: dict[str, Any]) -> dict[str, Any]:
243 """The settings of a form, with those in sections alongside the rest"""
244 settings: dict[str, Any] = {}
245 for name, value in user_input.items():
246 settings.update(value if isinstance(value, dict) else {name: value})
247 return settings
250def power_schema(with_name: bool) -> vol.Schema:
251 fields: dict[vol.Marker, Any] = {}
252 if with_name:
253 fields[vol.Required(CONF_NAME)] = TextSelector()
254 fields[vol.Required(CONF_POWER_ENTITY)] = EntitySelector(EntitySelectorConfig(domain="sensor", device_class="power"))
255 fields[vol.Required(CONF_THRESHOLD, default=DEFAULT_THRESHOLD)] = NumberSelector(
256 NumberSelectorConfig(min=0, step="any", mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfPower.WATT)
257 )
258 fields[vol.Required(CONF_GRACE_PERIOD, default=DEFAULT_GRACE_PERIOD)] = NumberSelector(
259 NumberSelectorConfig(min=0, max=3600, step=1, mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfTime.SECONDS)
260 )
261 fields[vol.Required(CONF_MIN_DURATION, default=DEFAULT_MIN_DURATION)] = NumberSelector(
262 NumberSelectorConfig(min=0, max=3600, step=1, mode=NumberSelectorMode.BOX, unit_of_measurement=UnitOfTime.SECONDS)
263 )
264 fields[vol.Optional(CONF_SWITCH_ENTITY)] = EntitySelector(EntitySelectorConfig(domain="switch"))
265 fields[vol.Required(CONF_SWITCH_OFF_BUTTON, default=True)] = BooleanSelector()
266 return vol.Schema(fields)
269class AppliancesConfigFlow(ConfigFlow, domain=DOMAIN):
270 VERSION = 1
271 # 2 has the choice of what the title of a Live Activity names in place of the switch for the program in it
272 # 3 has a dashboard looked for as an appliance is first set up
273 MINOR_VERSION = 4
275 def __init__(self) -> None:
276 self._device_id: str | None = None
277 self._name: str = ""
278 # how the cycle of the appliance found is told, where it isn't by a vendor platform
279 self._type: dict[str, str] = {}
280 # a power monitor found by its name, to be filled in on the form for a look before it's set up
281 self._power: dict[str, Any] = {}
283 @staticmethod
284 @callback
285 def async_get_options_flow(config_entry: ConfigEntry) -> AppliancesOptionsFlow:
286 return AppliancesOptionsFlow()
288 async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
289 """Automatic discovery the first time, and from then on an appliance to describe by hand"""
290 if any(entry.data.get(CONF_TYPE) == TYPE_DISCOVERY for entry in self._async_current_entries()):
291 return await self.async_step_power()
292 if user_input is not None:
293 await self.async_set_unique_id(TYPE_DISCOVERY)
294 self._abort_if_unique_id_configured()
295 # the appliances themselves are set up as this entry is, each as its own entry to change or disable
296 return self.async_create_entry(title=DISCOVERY_TITLE, data={CONF_TYPE: TYPE_DISCOVERY}, options=user_input)
297 if DATA_WORDS not in self.hass.data:
298 # before the integration is first set up, to know the type of an appliance by its model
299 await async_load_words(self.hass)
300 configured = self._async_current_ids()
301 found = [
302 a.name + (BETA_FOUND if appliance_beta(self.hass, a.device_id, profile_for(a.platform)) else "")
303 for a in find_appliances(self.hass)
304 if a.device_id not in configured
305 ]
306 if found:
307 found_text = "Appliances found:\n\n" + "\n".join(f"- {name}" for name in found)
308 else:
309 found_text = "No appliances could be automatically installed."
310 return self.async_show_form(
311 step_id="user",
312 data_schema=discovery_schema(),
313 description_placeholders={"found": found_text, "supernotify": supernotify_status(self.hass)},
314 )
316 async def async_step_power(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
317 """An appliance not found by itself, with a power monitor to tell when it's running"""
318 if user_input is not None:
319 await self.async_set_unique_id(user_input[CONF_POWER_ENTITY])
320 self._abort_if_unique_id_configured()
321 return self.async_create_entry(
322 title=user_input[CONF_NAME],
323 data={CONF_TYPE: TYPE_POWER},
324 options={k: v for k, v in user_input.items() if k != CONF_NAME},
325 )
326 if self._power:
327 # looked for only now, since a plug's switch can be added after its sensor
328 switch = plug_switch(self.hass, self._power[CONF_POWER_ENTITY])
329 suggested = self._power | ({CONF_SWITCH_ENTITY: switch} if switch else {})
330 return self.async_show_form(
331 step_id=STEP_POWER,
332 data_schema=self.add_suggested_values_to_schema(power_schema(with_name=True), suggested),
333 )
334 return self.async_show_form(step_id=STEP_POWER, data_schema=power_schema(with_name=True))
336 async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
337 """An appliance found with automatic discovery on, so set up without asking"""
338 # a discovery of the same appliance may be waiting, and goes once this entry exists
339 await self.async_set_unique_id(import_data[CONF_DEVICE_ID], raise_on_progress=False)
340 self._abort_if_unique_id_configured()
341 data = {k: v for k, v in import_data.items() if k in (CONF_DEVICE_ID, CONF_TYPE)}
342 return self.async_create_entry(title=import_data[CONF_NAME], data=data)
344 async def async_step_integration_discovery(self, discovery_info: dict[str, Any]) -> ConfigFlowResult:
345 """An appliance found with automatic discovery off, or a power monitor named for one, so offered to be added"""
346 if CONF_POWER_ENTITY in discovery_info:
347 self._power = dict(discovery_info)
348 await self.async_set_unique_id(discovery_info[CONF_POWER_ENTITY])
349 self._abort_if_unique_id_configured()
350 self.context["title_placeholders"] = {"name": discovery_info[CONF_NAME]}
351 return await self.async_step_power()
352 self._device_id = discovery_info[CONF_DEVICE_ID]
353 self._name = discovery_info[CONF_NAME]
354 self._type = {CONF_TYPE: discovery_info[CONF_TYPE]} if CONF_TYPE in discovery_info else {}
355 await self.async_set_unique_id(self._device_id)
356 self._abort_if_unique_id_configured()
357 self.context["title_placeholders"] = {"name": self._name}
358 return await self.async_step_confirm()
360 async def async_step_confirm(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
361 if user_input is not None:
362 return self.async_create_entry(title=self._name, data={CONF_DEVICE_ID: self._device_id} | self._type)
363 return self.async_show_form(
364 step_id="confirm",
365 description_placeholders={
366 "name": self._name,
367 "supernotify": supernotify_status(self.hass),
368 "beta": beta_notice(self.hass, self._device_id),
369 },
370 )
373class AppliancesOptionsFlow(OptionsFlowWithReload):
374 def __init__(self) -> None:
375 self._settings: dict[str, Any] = {}
377 def _name(self) -> str:
378 # the name notifications are sent with, which follows the device rather than the entry's title
379 watcher = getattr(self.config_entry, "runtime_data", None)
380 return watcher.name if watcher is not None else self.config_entry.title
382 def _phase_default(self) -> bool | None:
383 return getattr(getattr(self.config_entry, "runtime_data", None), "phase_default", None)
385 def _maintenance(self) -> dict[str, int] | None:
386 """The items for the type of appliance, with their usual cycles apart, or None for an appliance with nothing
387 to maintain, whose settings have no maintenance"""
388 watcher = getattr(self.config_entry, "runtime_data", None)
389 if watcher is None:
390 # not running, so with nothing known of it to go by
391 return None
392 usual = dict(MAINTENANCE_ITEMS.get(watcher.appliance_type or "", {}))
393 # by the type, so taking every item out still leaves them there to put back
394 if usual or watcher.maintenance_items or self.config_entry.options.get(CONF_MAINTENANCE) is not None:
395 return usual
396 return None
398 async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
399 if self.config_entry.data.get(CONF_TYPE) == TYPE_DISCOVERY:
400 return await self.async_step_discovery()
401 return await self.async_step_settings()
403 async def async_step_discovery(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
404 if user_input is not None:
405 return self.async_create_entry(data=user_input)
406 return self.async_show_form(
407 step_id=STEP_DISCOVERY,
408 data_schema=discovery_schema(self.config_entry.options.get(CONF_AUTO_DISCOVER, True)),
409 )
411 async def async_step_settings(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
412 name = self._name()
413 kind = self.config_entry.data.get(CONF_TYPE)
414 vacuum = kind == TYPE_VACUUM
415 # as they'll be sent, so there's the real text to edit rather than a template or an empty box
416 defaults = {key: text.replace(NAME_PLACEHOLDER, name) for key, text in default_texts(self.hass).items()}
417 if user_input is not None:
418 # text left as the default isn't a setting, so it goes on following the name of the appliance
419 usual = {f"{CONF_MAINTENANCE_PREFIX}{key}": every for key, every in (self._maintenance() or {}).items()}
420 unset = (
421 defaults
422 | DEFAULT_CHOICES
423 | usual
424 | {
425 CONF_NOTIFY_PHASE: self._phase_default(),
426 CONF_REMINDER_REPEATS: DEFAULT_REMINDER_REPEATS,
427 CONF_GRACE_PERIOD: VACUUM_SETTLE,
428 }
429 )
430 # maintenance left off is only turned down once it had been on, so it's still offered to anyone who
431 # hasn't been asked
432 if self.config_entry.options.get(CONF_MAINTENANCE) is None:
433 unset[CONF_MAINTENANCE] = False
434 chosen = flattened(user_input)
435 if CONF_LIVE_SHOW in chosen:
436 # in the order they're shown, so as ticked is the same whatever order they were ticked in
437 chosen[CONF_LIVE_SHOW] = [show for show in LIVE_SHOWS if show in chosen[CONF_LIVE_SHOW]]
438 settings = {
439 key: value
440 for key, value in chosen.items()
441 # an item at 0 is one left out, not one left as it comes, and nothing ticked is nothing shown
442 if (value or value is False or (key == CONF_LIVE_SHOW and value == []) or (key in usual and value == 0))
443 and value != unset.get(key)
444 }
445 if self._maintenance() is None:
446 # not on the form, so kept as it was
447 settings = {
448 key: value for key, value in self.config_entry.options.items() if key.startswith(CONF_MAINTENANCE)
449 } | settings
450 if self.config_entry.data.get(CONF_TYPE) == TYPE_POWER:
451 self._settings = settings
452 return await self.async_step_power()
453 return self.async_create_entry(data=settings)
454 # a power monitored appliance has no progress to report, nor program for a Live Activity, and a robot vacuum's
455 # progress, where it has one, is only for the bar
456 schema = await settings_schema(
457 self.hass,
458 progress=kind not in (TYPE_POWER, TYPE_VACUUM),
459 phase=self._phase_default(),
460 settle=vacuum,
461 live=kind != TYPE_POWER,
462 vacuum=vacuum,
463 maintenance=self._maintenance(),
464 )
465 shown = dict(self.config_entry.options)
466 if shown.get(CONF_DASHBOARD) not in dashboards(self.hass):
467 # removed since it was chosen
468 shown.pop(CONF_DASHBOARD, None)
469 for key, text in defaults.items():
470 shown[key] = str(shown.get(key) or text).replace(NAME_PLACEHOLDER, name)
471 return self.async_show_form(
472 step_id=STEP_SETTINGS,
473 data_schema=self.add_suggested_values_to_schema(schema, sectioned(schema, shown)),
474 description_placeholders={
475 "name": name,
476 "supernotify": supernotify_status(self.hass),
477 # as it's to be typed, which a translation can't say for itself
478 "program_placeholder": PROGRAM_PLACEHOLDER,
479 "start_time_placeholder": START_TIME_PLACEHOLDER,
480 "totals_placeholders": f"{DURATION_PLACEHOLDER}, {ENERGY_PLACEHOLDER}, {COST_PLACEHOLDER}",
481 },
482 )
484 async def async_step_power(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
485 if user_input is not None:
486 return self.async_create_entry(data=self._settings | user_input)
487 return self.async_show_form(
488 step_id=STEP_POWER,
489 data_schema=self.add_suggested_values_to_schema(power_schema(with_name=False), self.config_entry.options),
490 description_placeholders={"name": self.config_entry.title},
491 )