Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for SwitchBee Smart Home integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from switchbee.api.central_unit import SwitchBeeError
9 from switchbee.api.polling import CentralUnitPolling
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 from homeassistant.helpers.device_registry import format_mac
19 
20 from .const import DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_HOST): cv.string,
27  vol.Required(CONF_USERNAME): cv.string,
28  vol.Required(CONF_PASSWORD): cv.string,
29  }
30 )
31 
32 
33 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> str:
34  """Validate the user input allows us to connect."""
35 
36  websession = async_get_clientsession(hass, verify_ssl=False)
37  api = CentralUnitPolling(
38  data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD], websession
39  )
40  try:
41  await api.connect()
42  except SwitchBeeError as exp:
43  _LOGGER.error(exp)
44  if "LOGIN_FAILED" in str(exp):
45  raise InvalidAuth from exp
46 
47  raise CannotConnect from exp
48 
49  if api.unique_id:
50  return api.unique_id
51 
52  assert api.mac is not None
53  return format_mac(api.mac)
54 
55 
56 class SwitchBeeConfigFlow(ConfigFlow, domain=DOMAIN):
57  """Handle a config flow for SwitchBee Smart Home."""
58 
59  VERSION = 2
60 
61  async def async_step_user(
62  self, user_input: dict[str, Any] | None = None
63  ) -> ConfigFlowResult:
64  """Show the setup form to the user."""
65  errors: dict[str, str] = {}
66 
67  if user_input is None:
68  return self.async_show_formasync_show_formasync_show_form(
69  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
70  )
71 
72  try:
73  unique_id = 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 
82  else:
83  await self.async_set_unique_idasync_set_unique_id(unique_id)
84  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
85  return self.async_create_entryasync_create_entryasync_create_entry(title=user_input[CONF_HOST], 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)
str 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)