Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for ista EcoTrend integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import TYPE_CHECKING, Any
8 
9 from pyecotrend_ista import KeycloakError, LoginError, PyEcotrendIsta, ServerError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_EMAIL, CONF_NAME, CONF_PASSWORD
15  TextSelector,
16  TextSelectorConfig,
17  TextSelectorType,
18 )
19 
20 from .const import DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_EMAIL): TextSelector(
28  type=TextSelectorType.EMAIL,
29  autocomplete="email",
30  )
31  ),
32  vol.Required(CONF_PASSWORD): TextSelector(
34  type=TextSelectorType.PASSWORD,
35  autocomplete="current-password",
36  )
37  ),
38  }
39 )
40 
41 
42 class IstaConfigFlow(ConfigFlow, domain=DOMAIN):
43  """Handle a config flow for ista EcoTrend."""
44 
45  async def async_step_user(
46  self, user_input: dict[str, Any] | None = None
47  ) -> ConfigFlowResult:
48  """Handle the initial step."""
49  errors: dict[str, str] = {}
50  if user_input is not None:
51  ista = PyEcotrendIsta(
52  user_input[CONF_EMAIL],
53  user_input[CONF_PASSWORD],
54  _LOGGER,
55  )
56  try:
57  await self.hass.async_add_executor_job(ista.login)
58  info = ista.get_account()
59  except ServerError:
60  errors["base"] = "cannot_connect"
61  except (LoginError, KeycloakError):
62  errors["base"] = "invalid_auth"
63  except Exception:
64  _LOGGER.exception("Unexpected exception")
65  errors["base"] = "unknown"
66  else:
67  if TYPE_CHECKING:
68  assert info
69  title = f"{info["firstName"]} {info["lastName"]}".strip()
70  await self.async_set_unique_idasync_set_unique_id(info["activeConsumptionUnit"])
71  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
72  return self.async_create_entryasync_create_entryasync_create_entry(
73  title=title or "ista EcoTrend", data=user_input
74  )
75 
76  return self.async_show_formasync_show_formasync_show_form(
77  step_id="user",
78  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
79  data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input
80  ),
81  errors=errors,
82  )
83 
84  async def async_step_reauth(
85  self, entry_data: Mapping[str, Any]
86  ) -> ConfigFlowResult:
87  """Perform reauth upon an API authentication error."""
88  return await self.async_step_reauth_confirm()
89 
90  async def async_step_reauth_confirm(
91  self, user_input: dict[str, Any] | None = None
92  ) -> ConfigFlowResult:
93  """Dialog that informs the user that reauth is required."""
94  errors: dict[str, str] = {}
95 
96  reauth_entry = self._get_reauth_entry_get_reauth_entry()
97  if user_input is not None:
98  ista = PyEcotrendIsta(
99  user_input[CONF_EMAIL],
100  user_input[CONF_PASSWORD],
101  _LOGGER,
102  )
103  try:
104  await self.hass.async_add_executor_job(ista.login)
105  except ServerError:
106  errors["base"] = "cannot_connect"
107  except (LoginError, KeycloakError):
108  errors["base"] = "invalid_auth"
109  except Exception:
110  _LOGGER.exception("Unexpected exception")
111  errors["base"] = "unknown"
112  else:
113  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=user_input)
114 
115  return self.async_show_formasync_show_formasync_show_form(
116  step_id="reauth_confirm",
117  data_schema=self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
118  data_schema=STEP_USER_DATA_SCHEMA,
119  suggested_values={
120  CONF_EMAIL: user_input[CONF_EMAIL]
121  if user_input is not None
122  else reauth_entry.data[CONF_EMAIL]
123  },
124  ),
125  description_placeholders={
126  CONF_NAME: reauth_entry.title,
127  CONF_EMAIL: reauth_entry.data[CONF_EMAIL],
128  },
129  errors=errors,
130  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:47
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_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)