Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Read Your Meter Pro integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from pyrympro import CannotConnectError, RymPro, UnauthorizedError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, CONF_TOKEN, CONF_UNIQUE_ID
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 
17 from .const import DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 STEP_USER_DATA_SCHEMA = vol.Schema(
22  {
23  vol.Required(CONF_EMAIL): str,
24  vol.Required(CONF_PASSWORD): str,
25  }
26 )
27 
28 
29 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
30  """Validate the user input allows us to connect.
31 
32  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
33  """
34 
35  rympro = RymPro(async_get_clientsession(hass))
36 
37  token = await rympro.login(data[CONF_EMAIL], data[CONF_PASSWORD], "ha")
38 
39  info = await rympro.account_info()
40 
41  return {CONF_TOKEN: token, CONF_UNIQUE_ID: info["accountNumber"]}
42 
43 
44 class RymproConfigFlow(ConfigFlow, domain=DOMAIN):
45  """Handle a config flow for Read Your Meter Pro."""
46 
47  VERSION = 1
48 
49  async def async_step_user(
50  self, user_input: dict[str, Any] | None = None
51  ) -> ConfigFlowResult:
52  """Handle the initial step."""
53  if user_input is None:
54  return self.async_show_formasync_show_formasync_show_form(
55  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
56  )
57 
58  errors = {}
59 
60  try:
61  info = await validate_input(self.hass, user_input)
62  except CannotConnectError:
63  errors["base"] = "cannot_connect"
64  except UnauthorizedError:
65  errors["base"] = "invalid_auth"
66  except Exception:
67  _LOGGER.exception("Unexpected exception")
68  errors["base"] = "unknown"
69  else:
70  title = user_input[CONF_EMAIL]
71  data = {**user_input, **info}
72 
73  if self.sourcesourcesource != SOURCE_REAUTH:
74  await self.async_set_unique_idasync_set_unique_id(info[CONF_UNIQUE_ID])
75  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
76  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=data)
77 
78  return self.async_update_reload_and_abortasync_update_reload_and_abort(
79  self._get_reauth_entry_get_reauth_entry(),
80  title=title,
81  data=data,
82  unique_id=info[CONF_UNIQUE_ID],
83  )
84 
85  return self.async_show_formasync_show_formasync_show_form(
86  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
87  )
88 
89  async def async_step_reauth(
90  self, entry_data: Mapping[str, Any]
91  ) -> ConfigFlowResult:
92  """Handle configuration by re-auth."""
93  return await self.async_step_userasync_step_userasync_step_user()
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:91
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:51
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)
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)
str|None source(self)
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:29
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)