Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Bosch Smart Home Controller integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from os import makedirs
8 from typing import Any, cast
9 
10 from boschshcpy import SHCRegisterClient, SHCSession
11 from boschshcpy.exceptions import (
12  SHCAuthenticationError,
13  SHCConnectionError,
14  SHCRegistrationError,
15  SHCSessionError,
16 )
17 import voluptuous as vol
18 
19 from homeassistant.components import zeroconf
20 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
21 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_TOKEN
22 from homeassistant.core import HomeAssistant
23 
24 from .const import (
25  CONF_HOSTNAME,
26  CONF_SHC_CERT,
27  CONF_SHC_KEY,
28  CONF_SSL_CERTIFICATE,
29  CONF_SSL_KEY,
30  DOMAIN,
31 )
32 
33 _LOGGER = logging.getLogger(__name__)
34 
35 HOST_SCHEMA = vol.Schema(
36  {
37  vol.Required(CONF_HOST): str,
38  }
39 )
40 
41 
43  hass: HomeAssistant, folder: str, filename: str, asset: bytes
44 ) -> None:
45  """Write the tls assets to disk."""
46  makedirs(hass.config.path(DOMAIN, folder), exist_ok=True)
47  with open(
48  hass.config.path(DOMAIN, folder, filename), "w", encoding="utf8"
49  ) as file_handle:
50  file_handle.write(asset.decode("utf-8"))
51 
52 
54  hass: HomeAssistant,
55  host: str,
56  unique_id: str,
57  user_input: dict[str, Any],
58  zeroconf_instance: zeroconf.HaZeroconf,
59 ) -> dict[str, Any] | None:
60  """Create and store credentials and validate session."""
61  helper = SHCRegisterClient(host, user_input[CONF_PASSWORD])
62  result = helper.register(host, "HomeAssistant")
63 
64  if result is not None:
65  # Save key/certificate pair for each registered host separately
66  # otherwise only the last registered host is accessible.
67  write_tls_asset(hass, unique_id, CONF_SHC_CERT, result["cert"])
68  write_tls_asset(hass, unique_id, CONF_SHC_KEY, result["key"])
69 
70  session = SHCSession(
71  host,
72  hass.config.path(DOMAIN, unique_id, CONF_SHC_CERT),
73  hass.config.path(DOMAIN, unique_id, CONF_SHC_KEY),
74  True,
75  zeroconf_instance,
76  )
77  session.authenticate()
78 
79  return result
80 
81 
83  hass: HomeAssistant, host: str, zeroconf_instance: zeroconf.HaZeroconf
84 ) -> dict[str, str | None]:
85  """Get information from host."""
86  session = SHCSession(
87  host,
88  "",
89  "",
90  True,
91  zeroconf_instance,
92  )
93  information = session.mdns_info()
94  return {"title": information.name, "unique_id": information.unique_id}
95 
96 
97 class BoschSHCConfigFlow(ConfigFlow, domain=DOMAIN):
98  """Handle a config flow for Bosch SHC."""
99 
100  VERSION = 1
101  info: dict[str, str | None]
102  host: str
103 
104  async def async_step_reauth(
105  self, entry_data: Mapping[str, Any]
106  ) -> ConfigFlowResult:
107  """Perform reauth upon an API authentication error."""
108  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
109 
111  self, user_input: dict[str, Any] | None = None
112  ) -> ConfigFlowResult:
113  """Dialog that informs the user that reauth is required."""
114  if user_input is None:
115  return self.async_show_formasync_show_formasync_show_form(
116  step_id="reauth_confirm",
117  data_schema=HOST_SCHEMA,
118  )
119  self.hosthost = user_input[CONF_HOST]
120  self.infoinfo = await self._get_info_get_info(self.hosthost)
121  return await self.async_step_credentialsasync_step_credentials()
122 
123  async def async_step_user(
124  self, user_input: dict[str, Any] | None = None
125  ) -> ConfigFlowResult:
126  """Handle the initial step."""
127  errors: dict[str, str] = {}
128  if user_input is not None:
129  self.hosthost = user_input[CONF_HOST]
130  try:
131  self.infoinfo = await self._get_info_get_info(self.hosthost)
132  except SHCConnectionError:
133  errors["base"] = "cannot_connect"
134  except Exception:
135  _LOGGER.exception("Unexpected exception")
136  errors["base"] = "unknown"
137  else:
138  await self.async_set_unique_idasync_set_unique_id(self.infoinfo["unique_id"])
139  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.hosthost})
140  return await self.async_step_credentialsasync_step_credentials()
141 
142  return self.async_show_formasync_show_formasync_show_form(
143  step_id="user", data_schema=HOST_SCHEMA, errors=errors
144  )
145 
147  self, user_input: dict[str, Any] | None = None
148  ) -> ConfigFlowResult:
149  """Handle the credentials step."""
150  errors: dict[str, str] = {}
151  if user_input is not None:
152  zeroconf_instance = await zeroconf.async_get_instance(self.hass)
153  # unique_id uniquely identifies the registered controller and is used
154  # to save the key/certificate pair for each controller separately
155  unique_id = self.infoinfo["unique_id"]
156  assert unique_id
157  try:
158  result = await self.hass.async_add_executor_job(
159  create_credentials_and_validate,
160  self.hass,
161  self.hosthost,
162  unique_id,
163  user_input,
164  zeroconf_instance,
165  )
166  except SHCAuthenticationError:
167  errors["base"] = "invalid_auth"
168  except SHCConnectionError:
169  errors["base"] = "cannot_connect"
170  except SHCSessionError as err:
171  _LOGGER.warning("Session error: %s", err.message)
172  errors["base"] = "session_error"
173  except SHCRegistrationError as err:
174  _LOGGER.warning("Registration error: %s", err.message)
175  errors["base"] = "pairing_failed"
176  except Exception:
177  _LOGGER.exception("Unexpected exception")
178  errors["base"] = "unknown"
179  else:
180  assert result
181  entry_data = {
182  # Each host has its own key/certificate pair
183  CONF_SSL_CERTIFICATE: self.hass.config.path(
184  DOMAIN, unique_id, CONF_SHC_CERT
185  ),
186  CONF_SSL_KEY: self.hass.config.path(
187  DOMAIN, unique_id, CONF_SHC_KEY
188  ),
189  CONF_HOST: self.hosthost,
190  CONF_TOKEN: result["token"],
191  CONF_HOSTNAME: result["token"].split(":", 1)[1],
192  }
193  existing_entry = await self.async_set_unique_idasync_set_unique_id(unique_id)
194  if existing_entry:
195  return self.async_update_reload_and_abortasync_update_reload_and_abort(
196  existing_entry,
197  data=entry_data,
198  )
199 
200  return self.async_create_entryasync_create_entryasync_create_entry(
201  title=cast(str, self.infoinfo["title"]),
202  data=entry_data,
203  )
204  else:
205  user_input = {}
206 
207  schema = vol.Schema(
208  {
209  vol.Required(
210  CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, "")
211  ): str,
212  }
213  )
214 
215  return self.async_show_formasync_show_formasync_show_form(
216  step_id="credentials", data_schema=schema, errors=errors
217  )
218 
220  self, discovery_info: zeroconf.ZeroconfServiceInfo
221  ) -> ConfigFlowResult:
222  """Handle zeroconf discovery."""
223  if not discovery_info.name.startswith("Bosch SHC"):
224  return self.async_abortasync_abortasync_abort(reason="not_bosch_shc")
225 
226  try:
227  self.infoinfo = await self._get_info_get_info(discovery_info.host)
228  except SHCConnectionError:
229  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
230  self.hosthost = discovery_info.host
231 
232  local_name = discovery_info.hostname[:-1]
233  node_name = local_name.removesuffix(".local")
234 
235  await self.async_set_unique_idasync_set_unique_id(self.infoinfo["unique_id"])
236  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.hosthost})
237  self.context["title_placeholders"] = {"name": node_name}
238  return await self.async_step_confirm_discoveryasync_step_confirm_discovery()
239 
241  self, user_input: dict[str, Any] | None = None
242  ) -> ConfigFlowResult:
243  """Handle discovery confirm."""
244  errors: dict[str, str] = {}
245  if user_input is not None:
246  return await self.async_step_credentialsasync_step_credentials()
247 
248  return self.async_show_formasync_show_formasync_show_form(
249  step_id="confirm_discovery",
250  description_placeholders={
251  "model": "Bosch SHC",
252  "host": self.hosthost,
253  },
254  errors=errors,
255  )
256 
257  async def _get_info(self, host: str) -> dict[str, str | None]:
258  """Get additional information."""
259  zeroconf_instance = await zeroconf.async_get_instance(self.hass)
260 
261  return await self.hass.async_add_executor_job(
262  get_info_from_host,
263  self.hass,
264  host,
265  zeroconf_instance,
266  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:125
ConfigFlowResult async_step_credentials(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:148
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:112
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:106
ConfigFlowResult async_step_confirm_discovery(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:242
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:221
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_abort(self, *str reason, 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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
dict[str, Any]|None create_credentials_and_validate(HomeAssistant hass, str host, str unique_id, dict[str, Any] user_input, zeroconf.HaZeroconf zeroconf_instance)
Definition: config_flow.py:59
dict[str, str|None] get_info_from_host(HomeAssistant hass, str host, zeroconf.HaZeroconf zeroconf_instance)
Definition: config_flow.py:84
None write_tls_asset(HomeAssistant hass, str folder, str filename, bytes asset)
Definition: config_flow.py:44
None open(self, **Any kwargs)
Definition: lock.py:86