Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for OpenGarage integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import aiohttp
9 import opengarage
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_HOST, CONF_PORT, CONF_VERIFY_SSL
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
17 from homeassistant.helpers.device_registry import format_mac
18 
19 from .const import CONF_DEVICE_KEY, DEFAULT_PORT, DOMAIN
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 STEP_USER_DATA_SCHEMA = vol.Schema(
24  {
25  vol.Required(CONF_DEVICE_KEY): str,
26  vol.Required(CONF_HOST, default="http://"): str,
27  vol.Optional(CONF_PORT, default=DEFAULT_PORT): int,
28  vol.Optional(CONF_VERIFY_SSL, default=False): bool,
29  }
30 )
31 
32 
33 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
34  """Validate the user input allows us to connect.
35 
36  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
37  """
38  open_garage = opengarage.OpenGarage(
39  f"{data[CONF_HOST]}:{data[CONF_PORT]}",
40  data[CONF_DEVICE_KEY],
41  data[CONF_VERIFY_SSL],
43  )
44 
45  try:
46  status = await open_garage.update_state()
47  except aiohttp.ClientError as exp:
48  raise CannotConnect from exp
49 
50  if status is None:
51  raise InvalidAuth
52 
53  return {"title": status.get("name"), "unique_id": format_mac(status["mac"])}
54 
55 
56 class OpenGarageConfigFlow(ConfigFlow, domain=DOMAIN):
57  """Handle a config flow for OpenGarage."""
58 
59  VERSION = 1
60 
61  async def async_step_user(
62  self, user_input: dict[str, Any] | None = None
63  ) -> ConfigFlowResult:
64  """Handle the initial step."""
65  if user_input is None:
66  return self.async_show_formasync_show_formasync_show_form(
67  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
68  )
69 
70  errors = {}
71 
72  try:
73  info = await validate_input(self.hass, user_input)
74  except CannotConnect:
75  errors["base"] = "cannot_connect"
76  except InvalidAuth:
77  errors["base"] = "invalid_auth"
78  except Exception:
79  _LOGGER.exception("Unexpected exception")
80  errors["base"] = "unknown"
81  else:
82  await self.async_set_unique_idasync_set_unique_id(info["unique_id"])
83  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
84 
85  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
86 
87  return self.async_show_formasync_show_formasync_show_form(
88  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
89  )
90 
91 
93  """Error to indicate we cannot connect."""
94 
95 
97  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:63
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)
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, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:33
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)