Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Linear Garage Door integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Collection, Mapping, Sequence
6 import logging
7 from typing import Any
8 import uuid
9 
10 from linear_garage_door import Linear
11 from linear_garage_door.errors import InvalidLoginError
12 import voluptuous as vol
13 
14 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
16 from homeassistant.core import HomeAssistant
17 from homeassistant.exceptions import HomeAssistantError
18 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 
20 from .const import DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = {
25  vol.Required(CONF_EMAIL): str,
26  vol.Required(CONF_PASSWORD): str,
27 }
28 
29 
30 async def validate_input(
31  hass: HomeAssistant,
32  data: dict[str, str],
33 ) -> dict[str, Sequence[Collection[str]]]:
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 
39  hub = Linear()
40 
41  device_id = str(uuid.uuid4())
42  try:
43  await hub.login(
44  data["email"],
45  data["password"],
46  device_id=device_id,
47  client_session=async_get_clientsession(hass),
48  )
49 
50  sites = await hub.get_sites()
51  except InvalidLoginError as err:
52  raise InvalidAuth from err
53  finally:
54  await hub.close()
55 
56  return {
57  "email": data["email"],
58  "password": data["password"],
59  "sites": sites,
60  "device_id": device_id,
61  }
62 
63 
64 class LinearGarageDoorConfigFlow(ConfigFlow, domain=DOMAIN):
65  """Handle a config flow for Linear Garage Door."""
66 
67  VERSION = 1
68 
69  def __init__(self) -> None:
70  """Initialize the config flow."""
71  self.datadata: dict[str, Sequence[Collection[str]]] = {}
72 
73  async def async_step_user(
74  self, user_input: dict[str, Any] | None = None
75  ) -> ConfigFlowResult:
76  """Handle the initial step."""
77  data_schema = vol.Schema(STEP_USER_DATA_SCHEMA)
78 
79  if user_input is None:
80  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=data_schema)
81 
82  errors = {}
83 
84  try:
85  info = await validate_input(self.hass, user_input)
86  except InvalidAuth:
87  errors["base"] = "invalid_auth"
88  except Exception:
89  _LOGGER.exception("Unexpected exception")
90  errors["base"] = "unknown"
91  else:
92  self.datadata = info
93 
94  # Check if we are reauthenticating
95  if self.sourcesourcesourcesource == SOURCE_REAUTH:
96  return self.async_update_reload_and_abortasync_update_reload_and_abort(
97  self._get_reauth_entry_get_reauth_entry(),
98  data_updates={
99  CONF_EMAIL: self.datadata["email"],
100  CONF_PASSWORD: self.datadata["password"],
101  },
102  )
103 
104  return await self.async_step_siteasync_step_site()
105 
106  return self.async_show_formasync_show_formasync_show_form(
107  step_id="user", data_schema=data_schema, errors=errors
108  )
109 
110  async def async_step_site(
111  self,
112  user_input: dict[str, Any] | None = None,
113  ) -> ConfigFlowResult:
114  """Handle the site step."""
115 
116  if isinstance(self.datadata["sites"], list):
117  sites: list[dict[str, str]] = self.datadata["sites"]
118 
119  if not user_input:
120  return self.async_show_formasync_show_formasync_show_form(
121  step_id="site",
122  data_schema=vol.Schema(
123  {
124  vol.Required("site"): vol.In(
125  {site["id"]: site["name"] for site in sites}
126  )
127  }
128  ),
129  )
130 
131  site_id = user_input["site"]
132 
133  site_name = next(site["name"] for site in sites if site["id"] == site_id)
134 
135  await self.async_set_unique_idasync_set_unique_id(site_id)
136  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
137 
138  return self.async_create_entryasync_create_entryasync_create_entry(
139  title=site_name,
140  data={
141  "site_id": site_id,
142  "email": self.datadata["email"],
143  "password": self.datadata["password"],
144  "device_id": self.datadata["device_id"],
145  },
146  )
147 
148  async def async_step_reauth(
149  self, entry_data: Mapping[str, Any]
150  ) -> ConfigFlowResult:
151  """Reauth in case of a password change or other error."""
152  return await self.async_step_userasync_step_userasync_step_user()
153 
154 
156  """Error to indicate there is invalid auth."""
157 
158 
159 class InvalidDeviceID(HomeAssistantError):
160  """Error to indicate there is invalid device ID."""
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:150
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:75
ConfigFlowResult async_step_site(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:113
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_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=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)
str|None source(self)
dict[str, Sequence[Collection[str]]] validate_input(HomeAssistant hass, dict[str, str] 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)