Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Nexia integration."""
2 
3 import logging
4 from typing import Any
5 
6 import aiohttp
7 from nexia.const import BRAND_ASAIR, BRAND_NEXIA, BRAND_TRANE
8 from nexia.home import NexiaHome
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 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 
17 from .const import (
18  BRAND_ASAIR_NAME,
19  BRAND_NEXIA_NAME,
20  BRAND_TRANE_NAME,
21  CONF_BRAND,
22  DOMAIN,
23 )
24 from .util import is_invalid_auth_code
25 
26 _LOGGER = logging.getLogger(__name__)
27 
28 DATA_SCHEMA = vol.Schema(
29  {
30  vol.Required(CONF_USERNAME): str,
31  vol.Required(CONF_PASSWORD): str,
32  vol.Required(CONF_BRAND, default=BRAND_NEXIA): vol.In(
33  {
34  BRAND_NEXIA: BRAND_NEXIA_NAME,
35  BRAND_ASAIR: BRAND_ASAIR_NAME,
36  BRAND_TRANE: BRAND_TRANE_NAME,
37  }
38  ),
39  }
40 )
41 
42 
43 async def validate_input(hass: HomeAssistant, data):
44  """Validate the user input allows us to connect.
45 
46  Data has the keys from DATA_SCHEMA with values provided by the user.
47  """
48 
49  state_file = hass.config.path(
50  f"{data[CONF_BRAND]}_config_{data[CONF_USERNAME]}.conf"
51  )
52  session = async_get_clientsession(hass)
53  nexia_home = NexiaHome(
54  session,
55  username=data[CONF_USERNAME],
56  password=data[CONF_PASSWORD],
57  brand=data[CONF_BRAND],
58  device_name=hass.config.location_name,
59  state_file=state_file,
60  )
61  try:
62  await nexia_home.login()
63  except TimeoutError as ex:
64  _LOGGER.error("Unable to connect to Nexia service: %s", ex)
65  raise CannotConnect from ex
66  except aiohttp.ClientResponseError as http_ex:
67  _LOGGER.error("HTTP error from Nexia service: %s", http_ex)
68  if is_invalid_auth_code(http_ex.status):
69  raise InvalidAuth from http_ex
70  raise CannotConnect from http_ex
71 
72  if not nexia_home.get_name():
73  raise InvalidAuth
74 
75  info = {"title": nexia_home.get_name(), "house_id": nexia_home.house_id}
76  _LOGGER.debug("Setup ok with info: %s", info)
77  return info
78 
79 
80 class NexiaConfigFlow(ConfigFlow, domain=DOMAIN):
81  """Handle a config flow for Nexia."""
82 
83  VERSION = 1
84  MINOR_VERSION = 2
85 
86  async def async_step_user(
87  self, user_input: dict[str, Any] | None = None
88  ) -> ConfigFlowResult:
89  """Handle the initial step."""
90  errors = {}
91  if user_input is not None:
92  try:
93  info = await validate_input(self.hass, user_input)
94  except CannotConnect:
95  errors["base"] = "cannot_connect"
96  except InvalidAuth:
97  errors["base"] = "invalid_auth"
98  except Exception:
99  _LOGGER.exception("Unexpected exception")
100  errors["base"] = "unknown"
101 
102  if "base" not in errors:
103  await self.async_set_unique_idasync_set_unique_id(str(info["house_id"]))
104  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
105  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
106 
107  return self.async_show_formasync_show_formasync_show_form(
108  step_id="user", data_schema=DATA_SCHEMA, errors=errors
109  )
110 
111 
113  """Error to indicate we cannot connect."""
114 
115 
117  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:88
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)
str
_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:43
def is_invalid_auth_code(http_status_code)
Definition: util.py:6
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)