Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Overkiz integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any, cast
7 
8 from aiohttp import ClientConnectorCertificateError, ClientError
9 from pyoverkiz.client import OverkizClient
10 from pyoverkiz.const import SERVERS_WITH_LOCAL_API, SUPPORTED_SERVERS
11 from pyoverkiz.enums import APIType, Server
12 from pyoverkiz.exceptions import (
13  BadCredentialsException,
14  CozyTouchBadCredentialsException,
15  MaintenanceException,
16  NotSuchTokenException,
17  TooManyAttemptsBannedException,
18  TooManyRequestsException,
19  UnknownUserException,
20 )
21 from pyoverkiz.models import OverkizServer
22 from pyoverkiz.obfuscate import obfuscate_id
23 from pyoverkiz.utils import generate_local_server, is_overkiz_gateway
24 import voluptuous as vol
25 
26 from homeassistant.components import dhcp, zeroconf
27 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
28 from homeassistant.const import (
29  CONF_HOST,
30  CONF_PASSWORD,
31  CONF_TOKEN,
32  CONF_USERNAME,
33  CONF_VERIFY_SSL,
34 )
35 from homeassistant.exceptions import HomeAssistantError
36 from homeassistant.helpers.aiohttp_client import async_create_clientsession
37 
38 from .const import CONF_API_TYPE, CONF_HUB, DEFAULT_SERVER, DOMAIN, LOGGER
39 
40 
42  """Error to indicate Somfy Developer Mode is disabled."""
43 
44 
45 class OverkizConfigFlow(ConfigFlow, domain=DOMAIN):
46  """Handle a config flow for Overkiz (by Somfy)."""
47 
48  VERSION = 1
49 
50  _api_type: APIType = APIType.CLOUD
51  _user: str | None = None
52  _server: str = DEFAULT_SERVER
53  _host: str = "gateway-xxxx-xxxx-xxxx.local:8443"
54 
55  async def async_validate_input(self, user_input: dict[str, Any]) -> dict[str, Any]:
56  """Validate user credentials."""
57  user_input[CONF_API_TYPE] = self._api_type_api_type
58 
59  client = self._create_cloud_client(
60  username=user_input[CONF_USERNAME],
61  password=user_input[CONF_PASSWORD],
62  server=SUPPORTED_SERVERS[user_input[CONF_HUB]],
63  )
64  await client.login(register_event_listener=False)
65 
66  # For Local API, we create and activate a local token
67  if self._api_type_api_type == APIType.LOCAL:
68  user_input[CONF_TOKEN] = await self._create_local_api_token(
69  cloud_client=client,
70  host=user_input[CONF_HOST],
71  verify_ssl=user_input[CONF_VERIFY_SSL],
72  )
73 
74  # Set main gateway id as unique id
75  if gateways := await client.get_gateways():
76  for gateway in gateways:
77  if is_overkiz_gateway(gateway.id):
78  gateway_id = gateway.id
79  await self.async_set_unique_idasync_set_unique_id(gateway_id)
80 
81  return user_input
82 
83  async def async_step_user(
84  self, user_input: dict[str, Any] | None = None
85  ) -> ConfigFlowResult:
86  """Handle the initial step via config flow."""
87  if user_input:
88  self._server_server = user_input[CONF_HUB]
89 
90  # Some Overkiz hubs do support a local API
91  # Users can choose between local or cloud API.
92  if self._server_server in SERVERS_WITH_LOCAL_API:
93  return await self.async_step_local_or_cloud()
94 
95  return await self.async_step_cloud()
96 
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="user",
99  data_schema=vol.Schema(
100  {
101  vol.Required(CONF_HUB, default=self._server_server): vol.In(
102  {key: hub.name for key, hub in SUPPORTED_SERVERS.items()}
103  ),
104  }
105  ),
106  )
107 
108  async def async_step_local_or_cloud(
109  self, user_input: dict[str, Any] | None = None
110  ) -> ConfigFlowResult:
111  """Users can choose between local API or cloud API via config flow."""
112  if user_input:
113  self._api_type_api_type = user_input[CONF_API_TYPE]
114 
115  if self._api_type_api_type == APIType.LOCAL:
116  return await self.async_step_local()
117 
118  return await self.async_step_cloud()
119 
120  return self.async_show_formasync_show_formasync_show_form(
121  step_id="local_or_cloud",
122  data_schema=vol.Schema(
123  {
124  vol.Required(CONF_API_TYPE): vol.In(
125  {
126  APIType.LOCAL: "Local API",
127  APIType.CLOUD: "Cloud API",
128  }
129  ),
130  }
131  ),
132  )
133 
134  async def async_step_cloud(
135  self, user_input: dict[str, Any] | None = None
136  ) -> ConfigFlowResult:
137  """Handle the cloud authentication step via config flow."""
138  errors: dict[str, str] = {}
139  description_placeholders = {}
140 
141  if user_input:
142  self._user_user = user_input[CONF_USERNAME]
143 
144  # inherit the server from previous step
145  user_input[CONF_HUB] = self._server_server
146 
147  try:
148  await self.async_validate_inputasync_validate_input(user_input)
149  except TooManyRequestsException:
150  errors["base"] = "too_many_requests"
151  except BadCredentialsException as exception:
152  # If authentication with CozyTouch auth server is valid, but token is invalid
153  # for Overkiz API server, the hardware is not supported.
154  if user_input[CONF_HUB] == Server.ATLANTIC_COZYTOUCH and not isinstance(
155  exception, CozyTouchBadCredentialsException
156  ):
157  description_placeholders["unsupported_device"] = "CozyTouch"
158  errors["base"] = "unsupported_hardware"
159  else:
160  errors["base"] = "invalid_auth"
161  except (TimeoutError, ClientError):
162  errors["base"] = "cannot_connect"
163  except MaintenanceException:
164  errors["base"] = "server_in_maintenance"
165  except TooManyAttemptsBannedException:
166  errors["base"] = "too_many_attempts"
167  except UnknownUserException:
168  # Somfy Protect accounts are not supported since they don't use
169  # the Overkiz API server. Login will return unknown user.
170  description_placeholders["unsupported_device"] = "Somfy Protect"
171  errors["base"] = "unsupported_hardware"
172  except Exception: # noqa: BLE001
173  errors["base"] = "unknown"
174  LOGGER.exception("Unknown error")
175  else:
176  if self.sourcesourcesourcesource == SOURCE_REAUTH:
177  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="reauth_wrong_account")
178 
179  return self.async_update_reload_and_abortasync_update_reload_and_abort(
180  self._get_reauth_entry_get_reauth_entry(), data_updates=user_input
181  )
182 
183  # Create new entry
184  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
185 
186  return self.async_create_entryasync_create_entryasync_create_entry(
187  title=user_input[CONF_USERNAME], data=user_input
188  )
189 
190  return self.async_show_formasync_show_formasync_show_form(
191  step_id="cloud",
192  data_schema=vol.Schema(
193  {
194  vol.Required(CONF_USERNAME, default=self._user_user): str,
195  vol.Required(CONF_PASSWORD): str,
196  }
197  ),
198  description_placeholders=description_placeholders,
199  errors=errors,
200  )
201 
202  async def async_step_local(
203  self, user_input: dict[str, Any] | None = None
204  ) -> ConfigFlowResult:
205  """Handle the local authentication step via config flow."""
206  errors = {}
207  description_placeholders = {}
208 
209  if user_input:
210  self._host_host = user_input[CONF_HOST]
211  self._user_user = user_input[CONF_USERNAME]
212 
213  # inherit the server from previous step
214  user_input[CONF_HUB] = self._server_server
215 
216  try:
217  user_input = await self.async_validate_inputasync_validate_input(user_input)
218  except TooManyRequestsException:
219  errors["base"] = "too_many_requests"
220  except BadCredentialsException:
221  errors["base"] = "invalid_auth"
222  except ClientConnectorCertificateError as exception:
223  errors["base"] = "certificate_verify_failed"
224  LOGGER.debug(exception)
225  except (TimeoutError, ClientError) as exception:
226  errors["base"] = "cannot_connect"
227  LOGGER.debug(exception)
228  except MaintenanceException:
229  errors["base"] = "server_in_maintenance"
230  except TooManyAttemptsBannedException:
231  errors["base"] = "too_many_attempts"
232  except NotSuchTokenException:
233  errors["base"] = "no_such_token"
234  except DeveloperModeDisabled:
235  errors["base"] = "developer_mode_disabled"
236  except UnknownUserException:
237  # Somfy Protect accounts are not supported since they don't use
238  # the Overkiz API server. Login will return unknown user.
239  description_placeholders["unsupported_device"] = "Somfy Protect"
240  errors["base"] = "unsupported_hardware"
241  except Exception: # noqa: BLE001
242  errors["base"] = "unknown"
243  LOGGER.exception("Unknown error")
244  else:
245  if self.sourcesourcesourcesource == SOURCE_REAUTH:
246  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="reauth_wrong_account")
247 
248  return self.async_update_reload_and_abortasync_update_reload_and_abort(
249  self._get_reauth_entry_get_reauth_entry(), data_updates=user_input
250  )
251 
252  # Create new entry
253  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
254 
255  return self.async_create_entryasync_create_entryasync_create_entry(
256  title=user_input[CONF_HOST], data=user_input
257  )
258 
259  return self.async_show_formasync_show_formasync_show_form(
260  step_id="local",
261  data_schema=vol.Schema(
262  {
263  vol.Required(CONF_HOST, default=self._host_host): str,
264  vol.Required(CONF_USERNAME, default=self._user_user): str,
265  vol.Required(CONF_PASSWORD): str,
266  vol.Required(CONF_VERIFY_SSL, default=True): bool,
267  }
268  ),
269  description_placeholders=description_placeholders,
270  errors=errors,
271  )
272 
273  async def async_step_dhcp(
274  self, discovery_info: dhcp.DhcpServiceInfo
275  ) -> ConfigFlowResult:
276  """Handle DHCP discovery."""
277  hostname = discovery_info.hostname
278  gateway_id = hostname[8:22]
279  self._host_host = f"gateway-{gateway_id}.local:8443"
280 
281  LOGGER.debug("DHCP discovery detected gateway %s", obfuscate_id(gateway_id))
282  return await self._process_discovery(gateway_id)
283 
284  async def async_step_zeroconf(
285  self, discovery_info: zeroconf.ZeroconfServiceInfo
286  ) -> ConfigFlowResult:
287  """Handle ZeroConf discovery."""
288  properties = discovery_info.properties
289  gateway_id = properties["gateway_pin"]
290  hostname = discovery_info.hostname
291 
292  LOGGER.debug(
293  "ZeroConf discovery detected gateway %s on %s (%s)",
294  obfuscate_id(gateway_id),
295  hostname,
296  discovery_info.type,
297  )
298 
299  if discovery_info.type == "_kizbox._tcp.local.":
300  self._host_host = f"gateway-{gateway_id}.local:8443"
301 
302  if discovery_info.type == "_kizboxdev._tcp.local.":
303  self._host_host = f"{discovery_info.hostname[:-1]}:{discovery_info.port}"
304  self._api_type_api_type = APIType.LOCAL
305 
306  return await self._process_discovery(gateway_id)
307 
308  async def _process_discovery(self, gateway_id: str) -> ConfigFlowResult:
309  """Handle discovery of a gateway."""
310  await self.async_set_unique_idasync_set_unique_id(gateway_id)
311  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
312  self.context["title_placeholders"] = {"gateway_id": gateway_id}
313 
314  return await self.async_step_userasync_step_user()
315 
316  async def async_step_reauth(
317  self, entry_data: Mapping[str, Any]
318  ) -> ConfigFlowResult:
319  """Handle reauth."""
320  # overkiz entries always have unique IDs
321  self.context["title_placeholders"] = {"gateway_id": cast(str, self.unique_idunique_id)}
322 
323  self._user_user = entry_data[CONF_USERNAME]
324  self._server_server = entry_data[CONF_HUB]
325  self._api_type_api_type = entry_data.get(CONF_API_TYPE, APIType.CLOUD)
326 
327  if self._api_type_api_type == APIType.LOCAL:
328  self._host_host = entry_data[CONF_HOST]
329 
330  return await self.async_step_userasync_step_user(dict(entry_data))
331 
332  def _create_cloud_client(
333  self, username: str, password: str, server: OverkizServer
334  ) -> OverkizClient:
335  session = async_create_clientsession(self.hass)
336  return OverkizClient(
337  username=username, password=password, server=server, session=session
338  )
339 
340  async def _create_local_api_token(
341  self, cloud_client: OverkizClient, host: str, verify_ssl: bool
342  ) -> str:
343  """Create local API token."""
344  # Create session on Somfy cloud server to generate an access token for local API
345  gateways = await cloud_client.get_gateways()
346 
347  gateway_id = ""
348  for gateway in gateways:
349  # Overkiz can return multiple gateways, but we only can generate a token
350  # for the main gateway.
351  if is_overkiz_gateway(gateway.id):
352  gateway_id = gateway.id
353 
354  developer_mode = await cloud_client.get_setup_option(
355  f"developerMode-{gateway_id}"
356  )
357 
358  if developer_mode is None:
359  raise DeveloperModeDisabled
360 
361  token = await cloud_client.generate_local_token(gateway_id)
362  await cloud_client.activate_local_token(
363  gateway_id=gateway_id, token=token, label="Home Assistant/local"
364  )
365 
366  session = async_create_clientsession(self.hass, verify_ssl=verify_ssl)
367 
368  # Local API
369  local_client = OverkizClient(
370  username="",
371  password="",
372  token=token,
373  session=session,
374  server=generate_local_server(host=host),
375  verify_ssl=verify_ssl,
376  )
377 
378  await local_client.login()
379 
380  return token
dict[str, Any] async_validate_input(self, dict[str, Any] user_input)
Definition: config_flow.py:55
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigFlowResult async_step_dhcp(self, DhcpServiceInfo discovery_info)
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_step_zeroconf(self, ZeroconfServiceInfo discovery_info)
None _abort_if_unique_id_mismatch(self, *str reason="unique_id_mismatch", Mapping[str, str]|None description_placeholders=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)
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51