Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for SMLIGHT Zigbee integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from pysmlight import Api2
9 from pysmlight.exceptions import SmlightAuthError, SmlightConnectionError
10 import voluptuous as vol
11 
12 from homeassistant.components import zeroconf
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
15 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 from homeassistant.helpers.device_registry import format_mac
17 
18 from .const import DOMAIN
19 
20 STEP_USER_DATA_SCHEMA = vol.Schema(
21  {
22  vol.Required(CONF_HOST): str,
23  }
24 )
25 
26 STEP_AUTH_DATA_SCHEMA = vol.Schema(
27  {
28  vol.Required(CONF_USERNAME): str,
29  vol.Required(CONF_PASSWORD): str,
30  }
31 )
32 
33 
34 class SmlightConfigFlow(ConfigFlow, domain=DOMAIN):
35  """Handle a config flow for SMLIGHT Zigbee."""
36 
37  host: str
38 
39  def __init__(self) -> None:
40  """Initialize the config flow."""
41  self.clientclient: Api2
42 
43  async def async_step_user(
44  self, user_input: dict[str, Any] | None = None
45  ) -> ConfigFlowResult:
46  """Handle the initial step."""
47  errors: dict[str, str] = {}
48 
49  if user_input is not None:
50  self.hosthost = user_input[CONF_HOST]
51  self.clientclient = Api2(self.hosthost, session=async_get_clientsession(self.hass))
52 
53  try:
54  if not await self._async_check_auth_required_async_check_auth_required(user_input):
55  return await self._async_complete_entry_async_complete_entry(user_input)
56  except SmlightConnectionError:
57  errors["base"] = "cannot_connect"
58  except SmlightAuthError:
59  return await self.async_step_authasync_step_auth()
60 
61  return self.async_show_formasync_show_formasync_show_form(
62  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
63  )
64 
65  async def async_step_auth(
66  self, user_input: dict[str, Any] | None = None
67  ) -> ConfigFlowResult:
68  """Handle authentication to SLZB-06 device."""
69  errors: dict[str, str] = {}
70 
71  if user_input is not None:
72  try:
73  if not await self._async_check_auth_required_async_check_auth_required(user_input):
74  return await self._async_complete_entry_async_complete_entry(user_input)
75  except SmlightConnectionError:
76  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
77  except SmlightAuthError:
78  errors["base"] = "invalid_auth"
79 
80  return self.async_show_formasync_show_formasync_show_form(
81  step_id="auth", data_schema=STEP_AUTH_DATA_SCHEMA, errors=errors
82  )
83 
85  self, discovery_info: zeroconf.ZeroconfServiceInfo
86  ) -> ConfigFlowResult:
87  """Handle a discovered Lan coordinator."""
88  local_name = discovery_info.hostname[:-1]
89  node_name = local_name.removesuffix(".local")
90 
91  self.hosthost = local_name
92  self.context["title_placeholders"] = {CONF_NAME: node_name}
93  self.clientclient = Api2(self.hosthost, session=async_get_clientsession(self.hass))
94 
95  mac = discovery_info.properties.get("mac")
96  # fallback for legacy firmware
97  if mac is None:
98  try:
99  info = await self.clientclient.get_info()
100  except SmlightConnectionError:
101  # User is likely running unsupported ESPHome firmware
102  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
103  mac = info.MAC
104 
105  await self.async_set_unique_idasync_set_unique_id(format_mac(mac))
106  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
107 
108  return await self.async_step_confirm_discoveryasync_step_confirm_discovery()
109 
111  self, user_input: dict[str, Any] | None = None
112  ) -> ConfigFlowResult:
113  """Handle discovery confirm."""
114  errors: dict[str, str] = {}
115 
116  if user_input is not None:
117  user_input[CONF_HOST] = self.hosthost
118  try:
119  if not await self._async_check_auth_required_async_check_auth_required(user_input):
120  return await self._async_complete_entry_async_complete_entry(user_input)
121 
122  except SmlightConnectionError:
123  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
124 
125  except SmlightAuthError:
126  return await self.async_step_authasync_step_auth()
127 
128  self._set_confirm_only_set_confirm_only()
129 
130  return self.async_show_formasync_show_formasync_show_form(
131  step_id="confirm_discovery",
132  description_placeholders={"host": self.hosthost},
133  errors=errors,
134  )
135 
136  async def async_step_reauth(
137  self, entry_data: Mapping[str, Any]
138  ) -> ConfigFlowResult:
139  """Handle reauth when API Authentication failed."""
140 
141  self.hosthost = entry_data[CONF_HOST]
142  self.clientclient = Api2(self.hosthost, session=async_get_clientsession(self.hass))
143 
144  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
145 
147  self, user_input: dict[str, Any] | None = None
148  ) -> ConfigFlowResult:
149  """Handle re-authentication of an existing config entry."""
150  errors = {}
151  if user_input is not None:
152  try:
153  await self.clientclient.authenticate(
154  user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
155  )
156  except SmlightAuthError:
157  errors["base"] = "invalid_auth"
158  except SmlightConnectionError:
159  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
160  else:
161  return self.async_update_reload_and_abortasync_update_reload_and_abort(
162  self._get_reauth_entry_get_reauth_entry(), data_updates=user_input
163  )
164 
165  return self.async_show_formasync_show_formasync_show_form(
166  step_id="reauth_confirm",
167  data_schema=STEP_AUTH_DATA_SCHEMA,
168  description_placeholders=self.context["title_placeholders"],
169  errors=errors,
170  )
171 
172  async def _async_check_auth_required(self, user_input: dict[str, Any]) -> bool:
173  """Check if auth required and attempt to authenticate."""
174  if await self.clientclient.check_auth_needed():
175  if user_input.get(CONF_USERNAME) and user_input.get(CONF_PASSWORD):
176  return not await self.clientclient.authenticate(
177  user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
178  )
179  raise SmlightAuthError
180  return False
181 
183  self, user_input: dict[str, Any]
184  ) -> ConfigFlowResult:
185  info = await self.clientclient.get_info()
186  await self.async_set_unique_idasync_set_unique_id(format_mac(info.MAC))
187  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
188 
189  if user_input.get(CONF_HOST) is None:
190  user_input[CONF_HOST] = self.hosthost
191 
192  assert info.model is not None
193  title = self.context.get("title_placeholders", {}).get(CONF_NAME) or info.model
194  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
bool _async_check_auth_required(self, dict[str, Any] user_input)
Definition: config_flow.py:172
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:86
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:138
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:148
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:45
ConfigFlowResult _async_complete_entry(self, dict[str, Any] user_input)
Definition: config_flow.py:184
ConfigFlowResult async_step_confirm_discovery(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:112
ConfigFlowResult async_step_auth(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:67
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)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
dict[str, Any]|None get_info(HomeAssistant hass)
Definition: coordinator.py:69
dict[str, str|bool] authenticate(HomeAssistant hass, str host, str security_code)
Definition: config_flow.py:132
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)