Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Tado integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import PyTado
9 from PyTado.interface import Tado
10 import requests.exceptions
11 import voluptuous as vol
12 
13 from homeassistant.components import zeroconf
14 from homeassistant.config_entries import (
15  ConfigEntry,
16  ConfigFlow,
17  ConfigFlowResult,
18  OptionsFlow,
19 )
20 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
21 from homeassistant.core import HomeAssistant, callback
22 from homeassistant.exceptions import HomeAssistantError
23 
24 from .const import (
25  CONF_FALLBACK,
26  CONST_OVERLAY_TADO_DEFAULT,
27  CONST_OVERLAY_TADO_OPTIONS,
28  DOMAIN,
29  UNIQUE_ID,
30 )
31 
32 _LOGGER = logging.getLogger(__name__)
33 
34 DATA_SCHEMA = vol.Schema(
35  {
36  vol.Required(CONF_USERNAME): str,
37  vol.Required(CONF_PASSWORD): str,
38  }
39 )
40 
41 
42 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
43  """Validate the user input allows us to connect.
44 
45  Data has the keys from DATA_SCHEMA with values provided by the user.
46  """
47 
48  try:
49  tado = await hass.async_add_executor_job(
50  Tado, data[CONF_USERNAME], data[CONF_PASSWORD]
51  )
52  tado_me = await hass.async_add_executor_job(tado.getMe)
53  except KeyError as ex:
54  raise InvalidAuth from ex
55  except RuntimeError as ex:
56  raise CannotConnect from ex
57  except requests.exceptions.HTTPError as ex:
58  if ex.response.status_code > 400 and ex.response.status_code < 500:
59  raise InvalidAuth from ex
60  raise CannotConnect from ex
61 
62  if "homes" not in tado_me or len(tado_me["homes"]) == 0:
63  raise NoHomes
64 
65  home = tado_me["homes"][0]
66  unique_id = str(home["id"])
67  name = home["name"]
68 
69  return {"title": name, UNIQUE_ID: unique_id}
70 
71 
72 class TadoConfigFlow(ConfigFlow, domain=DOMAIN):
73  """Handle a config flow for Tado."""
74 
75  VERSION = 1
76 
77  async def async_step_user(
78  self, user_input: dict[str, Any] | None = None
79  ) -> ConfigFlowResult:
80  """Handle the initial step."""
81  errors = {}
82  if user_input is not None:
83  try:
84  validated = await validate_input(self.hass, user_input)
85  except CannotConnect:
86  errors["base"] = "cannot_connect"
87  except InvalidAuth:
88  errors["base"] = "invalid_auth"
89  except NoHomes:
90  errors["base"] = "no_homes"
91  except Exception:
92  _LOGGER.exception("Unexpected exception")
93  errors["base"] = "unknown"
94 
95  if "base" not in errors:
96  await self.async_set_unique_idasync_set_unique_id(validated[UNIQUE_ID])
97  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
98  return self.async_create_entryasync_create_entryasync_create_entry(
99  title=validated["title"], data=user_input
100  )
101 
102  return self.async_show_formasync_show_formasync_show_form(
103  step_id="user", data_schema=DATA_SCHEMA, errors=errors
104  )
105 
107  self, discovery_info: zeroconf.ZeroconfServiceInfo
108  ) -> ConfigFlowResult:
109  """Handle HomeKit discovery."""
110  self._async_abort_entries_match_async_abort_entries_match()
111  properties = {
112  key.lower(): value for (key, value) in discovery_info.properties.items()
113  }
114  await self.async_set_unique_idasync_set_unique_id(properties[zeroconf.ATTR_PROPERTIES_ID])
115  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
116  return await self.async_step_userasync_step_userasync_step_user()
117 
119  self, user_input: dict[str, Any] | None = None
120  ) -> ConfigFlowResult:
121  """Handle a reconfiguration flow initialized by the user."""
122  errors: dict[str, str] = {}
123  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
124 
125  if user_input is not None:
126  user_input[CONF_USERNAME] = reconfigure_entry.data[CONF_USERNAME]
127  try:
128  await validate_input(self.hass, user_input)
129  except CannotConnect:
130  errors["base"] = "cannot_connect"
131  except PyTado.exceptions.TadoWrongCredentialsException:
132  errors["base"] = "invalid_auth"
133  except NoHomes:
134  errors["base"] = "no_homes"
135  except Exception: # pylint: disable=broad-except
136  _LOGGER.exception("Unexpected exception")
137  errors["base"] = "unknown"
138 
139  if not errors:
140  return self.async_update_reload_and_abortasync_update_reload_and_abort(
141  reconfigure_entry, data_updates=user_input
142  )
143 
144  return self.async_show_formasync_show_formasync_show_form(
145  step_id="reconfigure",
146  data_schema=vol.Schema(
147  {
148  vol.Required(CONF_PASSWORD): str,
149  }
150  ),
151  errors=errors,
152  description_placeholders={
153  CONF_USERNAME: reconfigure_entry.data[CONF_USERNAME]
154  },
155  )
156 
157  @staticmethod
158  @callback
160  config_entry: ConfigEntry,
161  ) -> OptionsFlowHandler:
162  """Get the options flow for this handler."""
163  return OptionsFlowHandler()
164 
165 
167  """Handle an option flow for Tado."""
168 
169  async def async_step_init(
170  self, user_input: dict[str, Any] | None = None
171  ) -> ConfigFlowResult:
172  """Handle options flow."""
173  if user_input is not None:
174  return self.async_create_entryasync_create_entry(data=user_input)
175 
176  data_schema = vol.Schema(
177  {
178  vol.Optional(
179  CONF_FALLBACK,
180  default=self.config_entryconfig_entryconfig_entry.options.get(
181  CONF_FALLBACK, CONST_OVERLAY_TADO_DEFAULT
182  ),
183  ): vol.In(CONST_OVERLAY_TADO_OPTIONS),
184  }
185  )
186  return self.async_show_formasync_show_form(step_id="init", data_schema=data_schema)
187 
188 
190  """Error to indicate we cannot connect."""
191 
192 
193 class InvalidAuth(HomeAssistantError):
194  """Error to indicate there is invalid auth."""
195 
196 
198  """Error to indicate the account has no homes."""
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:171
OptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:161
ConfigFlowResult async_step_homekit(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:108
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:120
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:79
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_step_user(self, dict[str, Any]|None user_input=None)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
_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)
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:42