Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for NuHeat integration."""
2 
3 from http import HTTPStatus
4 import logging
5 from typing import Any
6 
7 import nuheat
8 import requests.exceptions
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 
16 from .const import CONF_SERIAL_NUMBER, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 DATA_SCHEMA = vol.Schema(
21  {
22  vol.Required(CONF_USERNAME): str,
23  vol.Required(CONF_PASSWORD): str,
24  vol.Required(CONF_SERIAL_NUMBER): str,
25  }
26 )
27 
28 
29 async def validate_input(hass: HomeAssistant, data):
30  """Validate the user input allows us to connect.
31 
32  Data has the keys from DATA_SCHEMA with values provided by the user.
33  """
34  api = nuheat.NuHeat(data[CONF_USERNAME], data[CONF_PASSWORD])
35 
36  try:
37  await hass.async_add_executor_job(api.authenticate)
38  except requests.exceptions.Timeout as ex:
39  raise CannotConnect from ex
40  except requests.exceptions.HTTPError as ex:
41  if (
42  ex.response.status_code > HTTPStatus.BAD_REQUEST
43  and ex.response.status_code < HTTPStatus.INTERNAL_SERVER_ERROR
44  ):
45  raise InvalidAuth from ex
46  raise CannotConnect from ex
47  #
48  # The underlying module throws a generic exception on login failure
49  #
50  except Exception as ex:
51  raise InvalidAuth from ex
52 
53  try:
54  thermostat = await hass.async_add_executor_job(
55  api.get_thermostat, data[CONF_SERIAL_NUMBER]
56  )
57  except requests.exceptions.HTTPError as ex:
58  raise InvalidThermostat from ex
59 
60  return {"title": thermostat.room, "serial_number": thermostat.serial_number}
61 
62 
63 class NuHeatConfigFlow(ConfigFlow, domain=DOMAIN):
64  """Handle a config flow for NuHeat."""
65 
66  VERSION = 1
67 
68  async def async_step_user(
69  self, user_input: dict[str, Any] | None = None
70  ) -> ConfigFlowResult:
71  """Handle the initial step."""
72  errors = {}
73  if user_input is not None:
74  try:
75  info = await validate_input(self.hass, user_input)
76  except CannotConnect:
77  errors["base"] = "cannot_connect"
78  except InvalidAuth:
79  errors["base"] = "invalid_auth"
80  except InvalidThermostat:
81  errors["base"] = "invalid_thermostat"
82  except Exception:
83  _LOGGER.exception("Unexpected exception")
84  errors["base"] = "unknown"
85 
86  if "base" not in errors:
87  await self.async_set_unique_idasync_set_unique_id(info["serial_number"])
88  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
89  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
90 
91  return self.async_show_formasync_show_formasync_show_form(
92  step_id="user", data_schema=DATA_SCHEMA, errors=errors
93  )
94 
95 
97  """Error to indicate we cannot connect."""
98 
99 
101  """Error to indicate there is invalid auth."""
102 
103 
105  """Error to indicate there is invalid thermostat."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:70
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)
def validate_input(HomeAssistant hass, data)
Definition: config_flow.py:29