Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Switchbot."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from switchbot import (
9  SwitchbotAccountConnectionError,
10  SwitchBotAdvertisement,
11  SwitchbotApiError,
12  SwitchbotAuthenticationError,
13  SwitchbotLock,
14  parse_advertisement_data,
15 )
16 import voluptuous as vol
17 
19  BluetoothServiceInfoBleak,
20  async_discovered_service_info,
21 )
22 from homeassistant.config_entries import (
23  ConfigEntry,
24  ConfigFlow,
25  ConfigFlowResult,
26  OptionsFlow,
27 )
28 from homeassistant.const import (
29  CONF_ADDRESS,
30  CONF_PASSWORD,
31  CONF_SENSOR_TYPE,
32  CONF_USERNAME,
33 )
34 from homeassistant.core import callback
35 from homeassistant.data_entry_flow import AbortFlow
36 from homeassistant.helpers.aiohttp_client import async_get_clientsession
37 
38 from .const import (
39  CONF_ENCRYPTION_KEY,
40  CONF_KEY_ID,
41  CONF_LOCK_NIGHTLATCH,
42  CONF_RETRY_COUNT,
43  CONNECTABLE_SUPPORTED_MODEL_TYPES,
44  DEFAULT_LOCK_NIGHTLATCH,
45  DEFAULT_RETRY_COUNT,
46  DOMAIN,
47  NON_CONNECTABLE_SUPPORTED_MODEL_TYPES,
48  SUPPORTED_LOCK_MODELS,
49  SUPPORTED_MODEL_TYPES,
50  SupportedModels,
51 )
52 
53 _LOGGER = logging.getLogger(__name__)
54 
55 
56 def format_unique_id(address: str) -> str:
57  """Format the unique ID for a switchbot."""
58  return address.replace(":", "").lower()
59 
60 
61 def short_address(address: str) -> str:
62  """Convert a Bluetooth address to a short address."""
63  results = address.replace("-", ":").split(":")
64  return f"{results[-2].upper()}{results[-1].upper()}"[-4:]
65 
66 
67 def name_from_discovery(discovery: SwitchBotAdvertisement) -> str:
68  """Get the name from a discovery."""
69  return f'{discovery.data["modelFriendlyName"]} {short_address(discovery.address)}'
70 
71 
72 class SwitchbotConfigFlow(ConfigFlow, domain=DOMAIN):
73  """Handle a config flow for Switchbot."""
74 
75  VERSION = 1
76 
77  @staticmethod
78  @callback
80  config_entry: ConfigEntry,
81  ) -> SwitchbotOptionsFlowHandler:
82  """Get the options flow for this handler."""
84 
85  def __init__(self) -> None:
86  """Initialize the config flow."""
87  self._discovered_adv_discovered_adv: SwitchBotAdvertisement | None = None
88  self._discovered_advs: dict[str, SwitchBotAdvertisement] = {}
89 
91  self, discovery_info: BluetoothServiceInfoBleak
92  ) -> ConfigFlowResult:
93  """Handle the bluetooth discovery step."""
94  _LOGGER.debug("Discovered bluetooth device: %s", discovery_info.as_dict())
95  await self.async_set_unique_idasync_set_unique_id(format_unique_id(discovery_info.address))
96  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
97  parsed = parse_advertisement_data(
98  discovery_info.device, discovery_info.advertisement
99  )
100  if not parsed or parsed.data.get("modelName") not in SUPPORTED_MODEL_TYPES:
101  return self.async_abortasync_abortasync_abort(reason="not_supported")
102  model_name = parsed.data.get("modelName")
103  if (
104  not discovery_info.connectable
105  and model_name in CONNECTABLE_SUPPORTED_MODEL_TYPES
106  ):
107  # Source is not connectable but the model is connectable
108  return self.async_abortasync_abortasync_abort(reason="not_supported")
109  self._discovered_adv_discovered_adv = parsed
110  data = parsed.data
111  self.context["title_placeholders"] = {
112  "name": data["modelFriendlyName"],
113  "address": short_address(discovery_info.address),
114  }
115  if model_name in SUPPORTED_LOCK_MODELS:
116  return await self.async_step_lock_choose_methodasync_step_lock_choose_method()
117  if self._discovered_adv_discovered_adv.data["isEncrypted"]:
118  return await self.async_step_passwordasync_step_password()
119  return await self.async_step_confirmasync_step_confirm()
120 
122  self, user_input: dict[str, Any]
123  ) -> ConfigFlowResult:
124  """Create an entry from a discovery."""
125  assert self._discovered_adv_discovered_adv is not None
126  discovery = self._discovered_adv_discovered_adv
127  name = name_from_discovery(discovery)
128  model_name = discovery.data["modelName"]
129  return self.async_create_entryasync_create_entryasync_create_entry(
130  title=name,
131  data={
132  **user_input,
133  CONF_ADDRESS: discovery.address,
134  CONF_SENSOR_TYPE: str(SUPPORTED_MODEL_TYPES[model_name]),
135  },
136  )
137 
139  self, user_input: dict[str, Any] | None = None
140  ) -> ConfigFlowResult:
141  """Confirm a single device."""
142  assert self._discovered_adv_discovered_adv is not None
143  if user_input is not None:
144  return await self._async_create_entry_from_discovery_async_create_entry_from_discovery(user_input)
145 
146  self._set_confirm_only_set_confirm_only()
147  return self.async_show_formasync_show_formasync_show_form(
148  step_id="confirm",
149  data_schema=vol.Schema({}),
150  description_placeholders={
151  "name": name_from_discovery(self._discovered_adv_discovered_adv)
152  },
153  )
154 
156  self, user_input: dict[str, Any] | None = None
157  ) -> ConfigFlowResult:
158  """Handle the password step."""
159  assert self._discovered_adv_discovered_adv is not None
160  if user_input is not None:
161  # There is currently no api to validate the password
162  # that does not operate the device so we have
163  # to accept it as-is
164  return await self._async_create_entry_from_discovery_async_create_entry_from_discovery(user_input)
165 
166  return self.async_show_formasync_show_formasync_show_form(
167  step_id="password",
168  data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
169  description_placeholders={
170  "name": name_from_discovery(self._discovered_adv_discovered_adv)
171  },
172  )
173 
175  self, user_input: dict[str, Any] | None = None
176  ) -> ConfigFlowResult:
177  """Handle the SwitchBot API auth step."""
178  errors = {}
179  assert self._discovered_adv_discovered_adv is not None
180  description_placeholders = {}
181  if user_input is not None:
182  try:
183  key_details = await SwitchbotLock.async_retrieve_encryption_key(
184  async_get_clientsession(self.hass),
185  self._discovered_adv_discovered_adv.address,
186  user_input[CONF_USERNAME],
187  user_input[CONF_PASSWORD],
188  )
189  except (SwitchbotApiError, SwitchbotAccountConnectionError) as ex:
190  _LOGGER.debug(
191  "Failed to connect to SwitchBot API: %s", ex, exc_info=True
192  )
193  raise AbortFlow(
194  "api_error", description_placeholders={"error_detail": str(ex)}
195  ) from ex
196  except SwitchbotAuthenticationError as ex:
197  _LOGGER.debug("Authentication failed: %s", ex, exc_info=True)
198  errors = {"base": "auth_failed"}
199  description_placeholders = {"error_detail": str(ex)}
200  else:
201  return await self.async_step_lock_keyasync_step_lock_key(key_details)
202 
203  user_input = user_input or {}
204  return self.async_show_formasync_show_formasync_show_form(
205  step_id="lock_auth",
206  errors=errors,
207  data_schema=vol.Schema(
208  {
209  vol.Required(
210  CONF_USERNAME, default=user_input.get(CONF_USERNAME)
211  ): str,
212  vol.Required(CONF_PASSWORD): str,
213  }
214  ),
215  description_placeholders={
216  "name": name_from_discovery(self._discovered_adv_discovered_adv),
217  **description_placeholders,
218  },
219  )
220 
222  self, user_input: dict[str, Any] | None = None
223  ) -> ConfigFlowResult:
224  """Handle the SwitchBot API chose method step."""
225  assert self._discovered_adv_discovered_adv is not None
226 
227  return self.async_show_menuasync_show_menu(
228  step_id="lock_choose_method",
229  menu_options=["lock_auth", "lock_key"],
230  description_placeholders={
231  "name": name_from_discovery(self._discovered_adv_discovered_adv),
232  },
233  )
234 
236  self, user_input: dict[str, Any] | None = None
237  ) -> ConfigFlowResult:
238  """Handle the encryption key step."""
239  errors = {}
240  assert self._discovered_adv_discovered_adv is not None
241  if user_input is not None:
242  if not await SwitchbotLock.verify_encryption_key(
243  self._discovered_adv_discovered_adv.device,
244  user_input[CONF_KEY_ID],
245  user_input[CONF_ENCRYPTION_KEY],
246  model=self._discovered_adv_discovered_adv.data["modelName"],
247  ):
248  errors = {
249  "base": "encryption_key_invalid",
250  }
251  else:
252  return await self._async_create_entry_from_discovery_async_create_entry_from_discovery(user_input)
253 
254  return self.async_show_formasync_show_formasync_show_form(
255  step_id="lock_key",
256  errors=errors,
257  data_schema=vol.Schema(
258  {
259  vol.Required(CONF_KEY_ID): str,
260  vol.Required(CONF_ENCRYPTION_KEY): str,
261  }
262  ),
263  description_placeholders={
264  "name": name_from_discovery(self._discovered_adv_discovered_adv),
265  },
266  )
267 
268  @callback
269  def _async_discover_devices(self) -> None:
270  current_addresses = self._async_current_ids_async_current_ids()
271  for connectable in (True, False):
272  for discovery_info in async_discovered_service_info(self.hass, connectable):
273  address = discovery_info.address
274  if (
275  format_unique_id(address) in current_addresses
276  or address in self._discovered_advs
277  ):
278  continue
279  parsed = parse_advertisement_data(
280  discovery_info.device, discovery_info.advertisement
281  )
282  if not parsed:
283  continue
284  model_name = parsed.data.get("modelName")
285  if (
286  discovery_info.connectable
287  and model_name in CONNECTABLE_SUPPORTED_MODEL_TYPES
288  ) or model_name in NON_CONNECTABLE_SUPPORTED_MODEL_TYPES:
289  self._discovered_advs[address] = parsed
290 
291  if not self._discovered_advs:
292  raise AbortFlow("no_devices_found")
293 
294  async def _async_set_device(self, discovery: SwitchBotAdvertisement) -> None:
295  """Set the device to work with."""
296  self._discovered_adv_discovered_adv = discovery
297  address = discovery.address
298  await self.async_set_unique_idasync_set_unique_id(
299  format_unique_id(address), raise_on_progress=False
300  )
301  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
302 
303  async def async_step_user(
304  self, user_input: dict[str, Any] | None = None
305  ) -> ConfigFlowResult:
306  """Handle the user step to pick discovered device."""
307  errors: dict[str, str] = {}
308  device_adv: SwitchBotAdvertisement | None = None
309  if user_input is not None:
310  device_adv = self._discovered_advs[user_input[CONF_ADDRESS]]
311  await self._async_set_device_async_set_device(device_adv)
312  if device_adv.data.get("modelName") in SUPPORTED_LOCK_MODELS:
313  return await self.async_step_lock_choose_methodasync_step_lock_choose_method()
314  if device_adv.data["isEncrypted"]:
315  return await self.async_step_passwordasync_step_password()
316  return await self._async_create_entry_from_discovery_async_create_entry_from_discovery(user_input)
317 
318  self._async_discover_devices_async_discover_devices()
319  if len(self._discovered_advs) == 1:
320  # If there is only one device we can ask for a password
321  # or simply confirm it
322  device_adv = list(self._discovered_advs.values())[0]
323  await self._async_set_device_async_set_device(device_adv)
324  if device_adv.data.get("modelName") in SUPPORTED_LOCK_MODELS:
325  return await self.async_step_lock_choose_methodasync_step_lock_choose_method()
326  if device_adv.data["isEncrypted"]:
327  return await self.async_step_passwordasync_step_password()
328  return await self.async_step_confirmasync_step_confirm()
329 
330  return self.async_show_formasync_show_formasync_show_form(
331  step_id="user",
332  data_schema=vol.Schema(
333  {
334  vol.Required(CONF_ADDRESS): vol.In(
335  {
336  address: name_from_discovery(parsed)
337  for address, parsed in self._discovered_advs.items()
338  }
339  ),
340  }
341  ),
342  errors=errors,
343  )
344 
345 
347  """Handle Switchbot options."""
348 
349  async def async_step_init(
350  self, user_input: dict[str, Any] | None = None
351  ) -> ConfigFlowResult:
352  """Manage Switchbot options."""
353  if user_input is not None:
354  # Update common entity options for all other entities.
355  return self.async_create_entryasync_create_entry(title="", data=user_input)
356 
357  options: dict[vol.Optional, Any] = {
358  vol.Optional(
359  CONF_RETRY_COUNT,
360  default=self.config_entryconfig_entryconfig_entry.options.get(
361  CONF_RETRY_COUNT, DEFAULT_RETRY_COUNT
362  ),
363  ): int
364  }
365  if self.config_entryconfig_entryconfig_entry.data.get(CONF_SENSOR_TYPE) == SupportedModels.LOCK_PRO:
366  options.update(
367  {
368  vol.Optional(
369  CONF_LOCK_NIGHTLATCH,
370  default=self.config_entryconfig_entryconfig_entry.options.get(
371  CONF_LOCK_NIGHTLATCH, DEFAULT_LOCK_NIGHTLATCH
372  ),
373  ): bool
374  }
375  )
376 
377  return self.async_show_formasync_show_form(step_id="init", data_schema=vol.Schema(options))
ConfigFlowResult async_step_lock_auth(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:176
SwitchbotOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:81
ConfigFlowResult _async_create_entry_from_discovery(self, dict[str, Any] user_input)
Definition: config_flow.py:123
ConfigFlowResult async_step_password(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:157
ConfigFlowResult async_step_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:140
ConfigFlowResult async_step_lock_key(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:237
ConfigFlowResult async_step_lock_choose_method(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:223
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:305
None _async_set_device(self, SwitchBotAdvertisement discovery)
Definition: config_flow.py:294
ConfigFlowResult async_step_bluetooth(self, BluetoothServiceInfoBleak discovery_info)
Definition: config_flow.py:92
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:351
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
set[str|None] _async_current_ids(self, bool include_ignore=True)
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_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)
None config_entry(self, ConfigEntry value)
str
_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_show_menu(self, *str|None step_id=None, Container[str] menu_options, Mapping[str, str]|None description_placeholders=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)
Iterable[BluetoothServiceInfoBleak] async_discovered_service_info(HomeAssistant hass, bool connectable=True)
Definition: api.py:72
str name_from_discovery(SwitchBotAdvertisement discovery)
Definition: config_flow.py:67
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)