Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the Nuki integration."""
2 
3 from collections.abc import Mapping
4 import logging
5 from typing import Any
6 
7 from pynuki import NukiBridge
8 from pynuki.bridge import InvalidCredentialsException
9 from requests.exceptions import RequestException
10 import voluptuous as vol
11 
12 from homeassistant.components import dhcp
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
15 from homeassistant.core import HomeAssistant
16 
17 from .const import CONF_ENCRYPT_TOKEN, DEFAULT_PORT, DEFAULT_TIMEOUT, DOMAIN
18 from .helpers import CannotConnect, InvalidAuth, parse_id
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 USER_SCHEMA = vol.Schema(
23  {
24  vol.Required(CONF_HOST): str,
25  vol.Optional(CONF_PORT, default=DEFAULT_PORT): vol.Coerce(int),
26  vol.Required(CONF_TOKEN): str,
27  }
28 )
29 
30 REAUTH_SCHEMA = vol.Schema(
31  {
32  vol.Required(CONF_TOKEN): str,
33  vol.Optional(CONF_ENCRYPT_TOKEN, default=True): bool,
34  }
35 )
36 
37 
38 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
39  """Validate the user input allows us to connect.
40 
41  Data has the keys from USER_SCHEMA with values provided by the user.
42  """
43 
44  try:
45  bridge = await hass.async_add_executor_job(
46  NukiBridge,
47  data[CONF_HOST],
48  data[CONF_TOKEN],
49  data[CONF_PORT],
50  data.get(CONF_ENCRYPT_TOKEN, True),
51  DEFAULT_TIMEOUT,
52  )
53 
54  info = await hass.async_add_executor_job(bridge.info)
55  except InvalidCredentialsException as err:
56  raise InvalidAuth from err
57  except RequestException as err:
58  raise CannotConnect from err
59 
60  return info
61 
62 
63 class NukiConfigFlow(ConfigFlow, domain=DOMAIN):
64  """Nuki config flow."""
65 
66  def __init__(self) -> None:
67  """Initialize the Nuki config flow."""
68  self.discovery_schemadiscovery_schema: vol.Schema | None = None
69  self._data_data: Mapping[str, Any] = {}
70 
71  async def async_step_user(
72  self, user_input: dict[str, Any] | None = None
73  ) -> ConfigFlowResult:
74  """Handle a flow initiated by the user."""
75  return await self.async_step_validateasync_step_validate(user_input)
76 
77  async def async_step_dhcp(
78  self, discovery_info: dhcp.DhcpServiceInfo
79  ) -> ConfigFlowResult:
80  """Prepare configuration for a DHCP discovered Nuki bridge."""
81  await self.async_set_unique_idasync_set_unique_id(discovery_info.hostname[12:].upper())
82 
83  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
84 
85  self.discovery_schemadiscovery_schema = vol.Schema(
86  {
87  vol.Required(CONF_HOST, default=discovery_info.ip): str,
88  vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
89  vol.Required(CONF_TOKEN): str,
90  }
91  )
92 
93  return await self.async_step_validateasync_step_validate()
94 
95  async def async_step_reauth(
96  self, entry_data: Mapping[str, Any]
97  ) -> ConfigFlowResult:
98  """Perform reauth upon an API authentication error."""
99  self._data_data = entry_data
100 
101  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
102 
104  self, user_input: dict[str, Any] | None = None
105  ) -> ConfigFlowResult:
106  """Dialog that inform the user that reauth is required."""
107  errors = {}
108  if user_input is None:
109  return self.async_show_formasync_show_formasync_show_form(
110  step_id="reauth_confirm", data_schema=REAUTH_SCHEMA
111  )
112 
113  conf = {
114  CONF_HOST: self._data_data[CONF_HOST],
115  CONF_PORT: self._data_data[CONF_PORT],
116  CONF_TOKEN: user_input[CONF_TOKEN],
117  CONF_ENCRYPT_TOKEN: user_input[CONF_ENCRYPT_TOKEN],
118  }
119 
120  try:
121  info = await validate_input(self.hass, conf)
122  except CannotConnect:
123  errors["base"] = "cannot_connect"
124  except InvalidAuth:
125  errors["base"] = "invalid_auth"
126  except Exception:
127  _LOGGER.exception("Unexpected exception")
128  errors["base"] = "unknown"
129 
130  if not errors:
131  existing_entry = await self.async_set_unique_idasync_set_unique_id(
132  parse_id(info["ids"]["hardwareId"])
133  )
134  if existing_entry:
135  self.hass.config_entries.async_update_entry(existing_entry, data=conf)
136  self.hass.async_create_task(
137  self.hass.config_entries.async_reload(existing_entry.entry_id)
138  )
139  return self.async_abortasync_abortasync_abort(reason="reauth_successful")
140  errors["base"] = "unknown"
141 
142  return self.async_show_formasync_show_formasync_show_form(
143  step_id="reauth_confirm", data_schema=REAUTH_SCHEMA, errors=errors
144  )
145 
147  self, user_input: dict[str, Any] | None = None
148  ) -> ConfigFlowResult:
149  """Handle init step of a flow."""
150 
151  data_schema = self.discovery_schemadiscovery_schema or USER_SCHEMA
152 
153  errors = {}
154  if user_input is not None:
155  data_schema = USER_SCHEMA.extend(
156  {
157  vol.Optional(CONF_ENCRYPT_TOKEN, default=True): bool,
158  }
159  )
160  try:
161  info = await validate_input(self.hass, user_input)
162  except CannotConnect:
163  errors["base"] = "cannot_connect"
164  except InvalidAuth:
165  errors["base"] = "invalid_auth"
166  except Exception:
167  _LOGGER.exception("Unexpected exception")
168  errors["base"] = "unknown"
169 
170  if "base" not in errors:
171  bridge_id = parse_id(info["ids"]["hardwareId"])
172  await self.async_set_unique_idasync_set_unique_id(bridge_id)
173  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
174  return self.async_create_entryasync_create_entryasync_create_entry(title=bridge_id, data=user_input)
175 
176  return self.async_show_formasync_show_formasync_show_form(
177  step_id="user",
178  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(data_schema, user_input),
179  errors=errors,
180  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:97
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:79
ConfigFlowResult async_step_validate(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:105
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:73
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_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)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:38