Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Sense integration."""
2 
3 from collections.abc import Mapping
4 from functools import partial
5 import logging
6 from typing import Any
7 
8 from sense_energy import (
9  ASyncSenseable,
10  SenseAuthenticationException,
11  SenseMFARequiredException,
12 )
13 import voluptuous as vol
14 
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_CODE, CONF_EMAIL, CONF_PASSWORD, CONF_TIMEOUT
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 
19 from .const import ACTIVE_UPDATE_RATE, DEFAULT_TIMEOUT, DOMAIN, SENSE_CONNECT_EXCEPTIONS
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 DATA_SCHEMA = vol.Schema(
24  {
25  vol.Required(CONF_EMAIL): str,
26  vol.Required(CONF_PASSWORD): str,
27  vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.Coerce(int),
28  }
29 )
30 
31 
32 class SenseConfigFlow(ConfigFlow, domain=DOMAIN):
33  """Handle a config flow for Sense."""
34 
35  VERSION = 1
36 
37  _gateway: ASyncSenseable
38 
39  def __init__(self) -> None:
40  """Init Config ."""
41  self._auth_data_auth_data: dict[str, Any] = {}
42 
43  async def validate_input(self, data: Mapping[str, Any]) -> None:
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  self._auth_data_auth_data.update(dict(data))
49  timeout = self._auth_data_auth_data[CONF_TIMEOUT]
50  client_session = async_get_clientsession(self.hass)
51 
52  # Creating the AsyncSenseable object loads
53  # ssl certificates which does blocking IO
54  self._gateway_gateway = await self.hass.async_add_executor_job(
55  partial(
56  ASyncSenseable,
57  api_timeout=timeout,
58  wss_timeout=timeout,
59  client_session=client_session,
60  )
61  )
62  self._gateway_gateway.rate_limit = ACTIVE_UPDATE_RATE
63  await self._gateway_gateway.authenticate(
64  self._auth_data_auth_data[CONF_EMAIL], self._auth_data_auth_data[CONF_PASSWORD]
65  )
66 
67  async def create_entry_from_data(self) -> ConfigFlowResult:
68  """Create the entry from the config data."""
69  self._auth_data_auth_data["access_token"] = self._gateway_gateway.sense_access_token
70  self._auth_data_auth_data["user_id"] = self._gateway_gateway.sense_user_id
71  self._auth_data_auth_data["device_id"] = self._gateway_gateway.device_id
72  self._auth_data_auth_data["refresh_token"] = self._gateway_gateway.refresh_token
73  self._auth_data_auth_data["monitor_id"] = self._gateway_gateway.sense_monitor_id
74  existing_entry = await self.async_set_unique_idasync_set_unique_id(self._auth_data_auth_data[CONF_EMAIL])
75  if not existing_entry:
76  return self.async_create_entryasync_create_entryasync_create_entry(
77  title=self._auth_data_auth_data[CONF_EMAIL], data=self._auth_data_auth_data
78  )
79 
80  return self.async_update_reload_and_abortasync_update_reload_and_abort(existing_entry, data=self._auth_data_auth_data)
81 
83  self, user_input: Mapping[str, Any], errors: dict[str, str]
84  ) -> ConfigFlowResult | None:
85  """Validate the input and create the entry from the data."""
86  try:
87  await self.validate_inputvalidate_input(user_input)
88  except SenseMFARequiredException:
89  return await self.async_step_validationasync_step_validation()
90  except SENSE_CONNECT_EXCEPTIONS:
91  errors["base"] = "cannot_connect"
92  except SenseAuthenticationException:
93  errors["base"] = "invalid_auth"
94  except Exception:
95  _LOGGER.exception("Unexpected exception")
96  errors["base"] = "unknown"
97  else:
98  return await self.create_entry_from_datacreate_entry_from_data()
99  return None
100 
102  self, user_input: dict[str, str] | None = None
103  ) -> ConfigFlowResult:
104  """Handle validation (2fa) step."""
105  errors = {}
106  if user_input:
107  try:
108  await self._gateway_gateway.validate_mfa(user_input[CONF_CODE])
109  except SENSE_CONNECT_EXCEPTIONS:
110  errors["base"] = "cannot_connect"
111  except SenseAuthenticationException:
112  errors["base"] = "invalid_auth"
113  except Exception:
114  _LOGGER.exception("Unexpected exception")
115  errors["base"] = "unknown"
116  else:
117  return await self.create_entry_from_datacreate_entry_from_data()
118 
119  return self.async_show_formasync_show_formasync_show_form(
120  step_id="validation",
121  data_schema=vol.Schema({vol.Required(CONF_CODE): vol.All(str, vol.Strip)}),
122  errors=errors,
123  )
124 
125  async def async_step_user(
126  self, user_input: dict[str, Any] | None = None
127  ) -> ConfigFlowResult:
128  """Handle the initial step."""
129  errors: dict[str, str] = {}
130  if user_input is not None:
131  if result := await self.validate_input_and_create_entryvalidate_input_and_create_entry(user_input, errors):
132  return result
133 
134  return self.async_show_formasync_show_formasync_show_form(
135  step_id="user", data_schema=DATA_SCHEMA, errors=errors
136  )
137 
138  async def async_step_reauth(
139  self, entry_data: Mapping[str, Any]
140  ) -> ConfigFlowResult:
141  """Handle configuration by re-auth."""
142  self._auth_data_auth_data = dict(entry_data)
143  return await self.async_step_reauth_validateasync_step_reauth_validate(entry_data)
144 
146  self, user_input: Mapping[str, Any]
147  ) -> ConfigFlowResult:
148  """Handle reauth and validation."""
149  errors: dict[str, str] = {}
150  if user_input is not None:
151  if result := await self.validate_input_and_create_entryvalidate_input_and_create_entry(user_input, errors):
152  return result
153 
154  return self.async_show_formasync_show_formasync_show_form(
155  step_id="reauth_validate",
156  data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
157  errors=errors,
158  description_placeholders={
159  CONF_EMAIL: self._auth_data_auth_data[CONF_EMAIL],
160  },
161  )
ConfigFlowResult async_step_reauth_validate(self, Mapping[str, Any] user_input)
Definition: config_flow.py:147
ConfigFlowResult async_step_validation(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:103
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:140
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:127
ConfigFlowResult|None validate_input_and_create_entry(self, Mapping[str, Any] user_input, dict[str, str] errors)
Definition: config_flow.py:84
None validate_input(self, Mapping[str, Any] data)
Definition: config_flow.py:43
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_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)
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
dict[str, str|bool] authenticate(HomeAssistant hass, str host, str security_code)
Definition: config_flow.py:132
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)