Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Adds config flow for Nettigo Air Monitor."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from dataclasses import dataclass
7 import logging
8 from typing import Any
9 
10 from aiohttp.client_exceptions import ClientConnectorError
11 from nettigo_air_monitor import (
12  ApiError,
13  AuthFailedError,
14  CannotGetMacError,
15  ConnectionOptions,
16  NettigoAirMonitor,
17 )
18 import voluptuous as vol
19 
20 from homeassistant.components import zeroconf
21 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
22 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
23 from homeassistant.core import HomeAssistant
24 from homeassistant.helpers.aiohttp_client import async_get_clientsession
25 from homeassistant.helpers.device_registry import format_mac
26 
27 from .const import DOMAIN
28 
29 
30 @dataclass
31 class NamConfig:
32  """NAM device configuration class."""
33 
34  mac_address: str
35  auth_enabled: bool
36 
37 
38 _LOGGER = logging.getLogger(__name__)
39 
40 AUTH_SCHEMA = vol.Schema(
41  {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
42 )
43 
44 
45 async def async_get_config(hass: HomeAssistant, host: str) -> NamConfig:
46  """Get device MAC address and auth_enabled property."""
47  websession = async_get_clientsession(hass)
48 
49  options = ConnectionOptions(host)
50  nam = await NettigoAirMonitor.create(websession, options)
51 
52  mac = await nam.async_get_mac_address()
53 
54  return NamConfig(mac, nam.auth_enabled)
55 
56 
58  hass: HomeAssistant, host: str, data: dict[str, Any]
59 ) -> None:
60  """Check if credentials are valid."""
61  websession = async_get_clientsession(hass)
62 
63  options = ConnectionOptions(host, data.get(CONF_USERNAME), data.get(CONF_PASSWORD))
64 
65  nam = await NettigoAirMonitor.create(websession, options)
66 
67  await nam.async_check_credentials()
68 
69 
70 class NAMFlowHandler(ConfigFlow, domain=DOMAIN):
71  """Config flow for Nettigo Air Monitor."""
72 
73  VERSION = 1
74 
75  _config: NamConfig
76  host: str
77 
78  async def async_step_user(
79  self, user_input: dict[str, Any] | None = None
80  ) -> ConfigFlowResult:
81  """Handle a flow initialized by the user."""
82  errors: dict[str, str] = {}
83 
84  if user_input is not None:
85  self.hosthost = user_input[CONF_HOST]
86 
87  try:
88  config = await async_get_config(self.hass, self.hosthost)
89  except (ApiError, ClientConnectorError, TimeoutError):
90  errors["base"] = "cannot_connect"
91  except CannotGetMacError:
92  return self.async_abortasync_abortasync_abort(reason="device_unsupported")
93  except Exception:
94  _LOGGER.exception("Unexpected exception")
95  errors["base"] = "unknown"
96  else:
97  await self.async_set_unique_idasync_set_unique_id(format_mac(config.mac_address))
98  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.hosthost})
99 
100  if config.auth_enabled is True:
101  return await self.async_step_credentialsasync_step_credentials()
102 
103  return self.async_create_entryasync_create_entryasync_create_entry(
104  title=self.hosthost,
105  data=user_input,
106  )
107 
108  return self.async_show_formasync_show_formasync_show_form(
109  step_id="user",
110  data_schema=vol.Schema({vol.Required(CONF_HOST): str}),
111  errors=errors,
112  )
113 
115  self, user_input: dict[str, Any] | None = None
116  ) -> ConfigFlowResult:
117  """Handle the credentials step."""
118  errors: dict[str, str] = {}
119 
120  if user_input is not None:
121  try:
122  await async_check_credentials(self.hass, self.hosthost, user_input)
123  except AuthFailedError:
124  errors["base"] = "invalid_auth"
125  except (ApiError, ClientConnectorError, TimeoutError):
126  errors["base"] = "cannot_connect"
127  except Exception:
128  _LOGGER.exception("Unexpected exception")
129  errors["base"] = "unknown"
130  else:
131  return self.async_create_entryasync_create_entryasync_create_entry(
132  title=self.hosthost,
133  data={**user_input, CONF_HOST: self.hosthost},
134  )
135 
136  return self.async_show_formasync_show_formasync_show_form(
137  step_id="credentials", data_schema=AUTH_SCHEMA, errors=errors
138  )
139 
141  self, discovery_info: zeroconf.ZeroconfServiceInfo
142  ) -> ConfigFlowResult:
143  """Handle zeroconf discovery."""
144  self.hosthost = discovery_info.host
145  self.context["title_placeholders"] = {"host": self.hosthost}
146 
147  # Do not probe the device if the host is already configured
148  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: self.hosthost})
149 
150  try:
151  self._config_config = await async_get_config(self.hass, self.hosthost)
152  except (ApiError, ClientConnectorError, TimeoutError):
153  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
154  except CannotGetMacError:
155  return self.async_abortasync_abortasync_abort(reason="device_unsupported")
156 
157  await self.async_set_unique_idasync_set_unique_id(format_mac(self._config_config.mac_address))
158  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_HOST: self.hosthost})
159 
160  return await self.async_step_confirm_discoveryasync_step_confirm_discovery()
161 
163  self, user_input: dict[str, Any] | None = None
164  ) -> ConfigFlowResult:
165  """Handle discovery confirm."""
166  errors: dict[str, str] = {}
167 
168  if user_input is not None:
169  return self.async_create_entryasync_create_entryasync_create_entry(
170  title=self.hosthost,
171  data={CONF_HOST: self.hosthost},
172  )
173 
174  if self._config_config.auth_enabled is True:
175  return await self.async_step_credentialsasync_step_credentials()
176 
177  self._set_confirm_only_set_confirm_only()
178 
179  return self.async_show_formasync_show_formasync_show_form(
180  step_id="confirm_discovery",
181  description_placeholders={"host": self.hosthost},
182  errors=errors,
183  )
184 
185  async def async_step_reauth(
186  self, entry_data: Mapping[str, Any]
187  ) -> ConfigFlowResult:
188  """Handle configuration by re-auth."""
189  self.hosthost = entry_data[CONF_HOST]
190  self.context["title_placeholders"] = {"host": self.hosthost}
191  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
192 
194  self, user_input: dict[str, Any] | None = None
195  ) -> ConfigFlowResult:
196  """Dialog that informs the user that reauth is required."""
197  errors: dict[str, str] = {}
198 
199  if user_input is not None:
200  try:
201  await async_check_credentials(self.hass, self.hosthost, user_input)
202  except (
203  ApiError,
204  AuthFailedError,
205  ClientConnectorError,
206  TimeoutError,
207  ):
208  return self.async_abortasync_abortasync_abort(reason="reauth_unsuccessful")
209 
210  return self.async_update_reload_and_abortasync_update_reload_and_abort(
211  self._get_reauth_entry_get_reauth_entry(), data={**user_input, CONF_HOST: self.hosthost}
212  )
213 
214  return self.async_show_formasync_show_formasync_show_form(
215  step_id="reauth_confirm",
216  description_placeholders={"host": self.hosthost},
217  data_schema=AUTH_SCHEMA,
218  errors=errors,
219  )
220 
222  self, user_input: dict[str, Any] | None = None
223  ) -> ConfigFlowResult:
224  """Handle a reconfiguration flow initialized by the user."""
225  errors = {}
226  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
227  self.hosthost = reconfigure_entry.data[CONF_HOST]
228 
229  if user_input is not None:
230  try:
231  config = await async_get_config(self.hass, user_input[CONF_HOST])
232  except (ApiError, ClientConnectorError, TimeoutError):
233  errors["base"] = "cannot_connect"
234  else:
235  await self.async_set_unique_idasync_set_unique_id(format_mac(config.mac_address))
236  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="another_device")
237 
238  return self.async_update_reload_and_abortasync_update_reload_and_abort(
239  reconfigure_entry, data_updates={CONF_HOST: user_input[CONF_HOST]}
240  )
241 
242  return self.async_show_formasync_show_formasync_show_form(
243  step_id="reconfigure",
244  data_schema=vol.Schema(
245  {
246  vol.Required(CONF_HOST, default=self.hosthost): str,
247  }
248  ),
249  description_placeholders={"device_name": reconfigure_entry.title},
250  errors=errors,
251  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:187
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:195
ConfigFlowResult async_step_credentials(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:116
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:80
ConfigFlowResult async_step_confirm_discovery(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:164
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:142
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:223
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)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=None)
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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
NamConfig async_get_config(HomeAssistant hass, str host)
Definition: config_flow.py:45
None async_check_credentials(HomeAssistant hass, str host, dict[str, Any] data)
Definition: config_flow.py:59
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)