Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Whirlpool Appliances 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 aiohttp import ClientError
10 import voluptuous as vol
11 from whirlpool.appliancesmanager import AppliancesManager
12 from whirlpool.auth import Auth
13 from whirlpool.backendselector import BackendSelector
14 
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_USERNAME
17 from homeassistant.core import HomeAssistant
18 from homeassistant.exceptions import HomeAssistantError
19 from homeassistant.helpers.aiohttp_client import async_get_clientsession
20 
21 from .const import CONF_BRAND, CONF_BRANDS_MAP, CONF_REGIONS_MAP, DOMAIN
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 
26 STEP_USER_DATA_SCHEMA = vol.Schema(
27  {
28  vol.Required(CONF_USERNAME): str,
29  vol.Required(CONF_PASSWORD): str,
30  vol.Required(CONF_REGION): vol.In(list(CONF_REGIONS_MAP)),
31  vol.Required(CONF_BRAND): vol.In(list(CONF_BRANDS_MAP)),
32  }
33 )
34 
35 REAUTH_SCHEMA = vol.Schema(
36  {
37  vol.Required(CONF_PASSWORD): str,
38  vol.Required(CONF_BRAND): vol.In(list(CONF_BRANDS_MAP)),
39  }
40 )
41 
42 
43 async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str, str]:
44  """Validate the user input allows us to connect.
45 
46  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
47  """
48  session = async_get_clientsession(hass)
49  region = CONF_REGIONS_MAP[data[CONF_REGION]]
50  brand = CONF_BRANDS_MAP[data[CONF_BRAND]]
51  backend_selector = BackendSelector(brand, region)
52  auth = Auth(backend_selector, data[CONF_USERNAME], data[CONF_PASSWORD], session)
53  try:
54  await auth.do_auth()
55  except (TimeoutError, ClientError) as exc:
56  raise CannotConnect from exc
57 
58  if not auth.is_access_token_valid():
59  raise InvalidAuth
60 
61  appliances_manager = AppliancesManager(backend_selector, auth, session)
62  await appliances_manager.fetch_appliances()
63 
64  if not appliances_manager.aircons and not appliances_manager.washer_dryers:
65  raise NoAppliances
66 
67  return {"title": data[CONF_USERNAME]}
68 
69 
70 class WhirlpoolConfigFlow(ConfigFlow, domain=DOMAIN):
71  """Handle a config flow for Whirlpool Sixth Sense."""
72 
73  VERSION = 1
74 
75  async def async_step_reauth(
76  self, entry_data: Mapping[str, Any]
77  ) -> ConfigFlowResult:
78  """Handle re-authentication with Whirlpool Sixth Sense."""
79  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
80 
82  self, user_input: dict[str, Any] | None = None
83  ) -> ConfigFlowResult:
84  """Confirm re-authentication with Whirlpool Sixth Sense."""
85  errors: dict[str, str] = {}
86 
87  if user_input:
88  reauth_entry = self._get_reauth_entry_get_reauth_entry()
89  password = user_input[CONF_PASSWORD]
90  brand = user_input[CONF_BRAND]
91  data = {**reauth_entry.data, CONF_PASSWORD: password, CONF_BRAND: brand}
92 
93  try:
94  await validate_input(self.hass, data)
95  except InvalidAuth:
96  errors["base"] = "invalid_auth"
97  except (CannotConnect, TimeoutError):
98  errors["base"] = "cannot_connect"
99  else:
100  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=data)
101 
102  return self.async_show_formasync_show_formasync_show_form(
103  step_id="reauth_confirm",
104  data_schema=REAUTH_SCHEMA,
105  errors=errors,
106  description_placeholders={"name": "Whirlpool"},
107  )
108 
109  async def async_step_user(self, user_input=None) -> ConfigFlowResult:
110  """Handle the initial step."""
111  if user_input is None:
112  return self.async_show_formasync_show_formasync_show_form(
113  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
114  )
115 
116  errors = {}
117 
118  try:
119  info = await validate_input(self.hass, user_input)
120  except CannotConnect:
121  errors["base"] = "cannot_connect"
122  except InvalidAuth:
123  errors["base"] = "invalid_auth"
124  except NoAppliances:
125  errors["base"] = "no_appliances"
126  except Exception:
127  _LOGGER.exception("Unexpected exception")
128  errors["base"] = "unknown"
129  else:
130  await self.async_set_unique_idasync_set_unique_id(
131  user_input[CONF_USERNAME].lower(), raise_on_progress=False
132  )
133  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
134  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
135 
136  return self.async_show_formasync_show_formasync_show_form(
137  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
138  )
139 
140 
142  """Error to indicate we cannot connect."""
143 
144 
145 class InvalidAuth(HomeAssistantError):
146  """Error to indicate there is invalid auth."""
147 
148 
150  """Error to indicate no supported appliances in the user account."""
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:77
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:83
ConfigFlowResult async_step_user(self, user_input=None)
Definition: config_flow.py:109
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)
_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)
dict[str, str] validate_input(HomeAssistant hass, dict[str, str] data)
Definition: config_flow.py:43
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)