Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Balboa Spa Client integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pybalboa import SpaClient
9 from pybalboa.exceptions import SpaConnectionError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_HOST
14 from homeassistant.core import callback
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers.device_registry import format_mac
18  SchemaFlowFormStep,
19  SchemaOptionsFlowHandler,
20 )
21 
22 from .const import CONF_SYNC_TIME, DOMAIN
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
27 
28 OPTIONS_SCHEMA = vol.Schema(
29  {
30  vol.Required(CONF_SYNC_TIME, default=False): bool,
31  }
32 )
33 OPTIONS_FLOW = {
34  "init": SchemaFlowFormStep(OPTIONS_SCHEMA),
35 }
36 
37 
38 async def validate_input(data: dict[str, Any]) -> dict[str, str]:
39  """Validate the user input allows us to connect."""
40  _LOGGER.debug("Attempting to connect to %s", data[CONF_HOST])
41  try:
42  async with SpaClient(data[CONF_HOST]) as spa:
43  if not await spa.async_configuration_loaded():
44  raise CannotConnect
45  mac = format_mac(spa.mac_address)
46  model = spa.model
47  except SpaConnectionError as err:
48  raise CannotConnect from err
49 
50  return {"title": model, "formatted_mac": mac}
51 
52 
53 class BalboaSpaClientFlowHandler(ConfigFlow, domain=DOMAIN):
54  """Handle a Balboa Spa Client config flow."""
55 
56  VERSION = 1
57 
58  _host: str | None
59 
60  @staticmethod
61  @callback
62  def async_get_options_flow(config_entry: ConfigEntry) -> SchemaOptionsFlowHandler:
63  """Get the options flow for this handler."""
64  return SchemaOptionsFlowHandler(config_entry, OPTIONS_FLOW)
65 
66  async def async_step_user(
67  self, user_input: dict[str, Any] | None = None
68  ) -> ConfigFlowResult:
69  """Handle a flow initialized by the user."""
70  errors = {}
71  if user_input is not None:
72  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
73  try:
74  info = await validate_input(user_input)
75  except CannotConnect:
76  errors["base"] = "cannot_connect"
77  except Exception:
78  _LOGGER.exception("Unexpected exception")
79  errors["base"] = "unknown"
80  else:
81  await self.async_set_unique_idasync_set_unique_id(info["formatted_mac"])
82  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
83  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
84 
85  return self.async_show_formasync_show_formasync_show_form(
86  step_id="user", data_schema=DATA_SCHEMA, errors=errors
87  )
88 
89 
91  """Error to indicate we cannot connect."""
SchemaOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:62
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:68
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
dict[str, str] validate_input(dict[str, Any] data)
Definition: config_flow.py:38