Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the MELCloud platform."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Mapping
7 from http import HTTPStatus
8 import logging
9 from typing import Any
10 
11 from aiohttp import ClientError, ClientResponseError
12 import pymelcloud
13 import voluptuous as vol
14 
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 
19 from .const import DOMAIN
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
24 class FlowHandler(ConfigFlow, domain=DOMAIN):
25  """Handle a config flow."""
26 
27  VERSION = 1
28 
29  async def _create_entry(self, username: str, token: str) -> ConfigFlowResult:
30  """Register new entry."""
31  await self.async_set_unique_idasync_set_unique_id(username)
32  self._abort_if_unique_id_configured_abort_if_unique_id_configured({CONF_TOKEN: token})
33  return self.async_create_entryasync_create_entryasync_create_entry(
34  title=username, data={CONF_USERNAME: username, CONF_TOKEN: token}
35  )
36 
37  async def _create_client(
38  self,
39  username: str,
40  *,
41  password: str | None = None,
42  token: str | None = None,
43  ) -> ConfigFlowResult:
44  """Create client."""
45  try:
46  async with asyncio.timeout(10):
47  if (acquired_token := token) is None:
48  acquired_token = await pymelcloud.login(
49  username,
50  password,
51  async_get_clientsession(self.hass),
52  )
53  await pymelcloud.get_devices(
54  acquired_token,
55  async_get_clientsession(self.hass),
56  )
57  except ClientResponseError as err:
58  if err.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN):
59  return self.async_abortasync_abortasync_abort(reason="invalid_auth")
60  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
61  except (TimeoutError, ClientError):
62  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
63 
64  return await self._create_entry_create_entry(username, acquired_token)
65 
66  async def async_step_user(
67  self, user_input: dict[str, Any] | None = None
68  ) -> ConfigFlowResult:
69  """User initiated config flow."""
70  if user_input is None:
71  return self.async_show_formasync_show_formasync_show_form(
72  step_id="user",
73  data_schema=vol.Schema(
74  {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
75  ),
76  )
77  username = user_input[CONF_USERNAME]
78  return await self._create_client_create_client(username, password=user_input[CONF_PASSWORD])
79 
80  async def async_step_reauth(
81  self, entry_data: Mapping[str, Any]
82  ) -> ConfigFlowResult:
83  """Handle initiation of re-authentication with MELCloud."""
84  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
85 
87  self, user_input: dict[str, Any] | None = None
88  ) -> ConfigFlowResult:
89  """Handle re-authentication with MELCloud."""
90  errors: dict[str, str] = {}
91 
92  if user_input is not None:
93  aquired_token, errors = await self.async_reauthenticate_clientasync_reauthenticate_client(user_input)
94 
95  if not errors:
96  return self.async_update_reload_and_abortasync_update_reload_and_abort(
97  self._get_reauth_entry_get_reauth_entry(), data={CONF_TOKEN: aquired_token}
98  )
99  return self.async_show_formasync_show_formasync_show_form(
100  step_id="reauth_confirm",
101  data_schema=vol.Schema(
102  {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
103  ),
104  errors=errors,
105  )
106 
108  self, user_input: dict[str, Any]
109  ) -> tuple[str | None, dict[str, str]]:
110  """Reauthenticate with MELCloud."""
111  errors: dict[str, str] = {}
112  acquired_token = None
113 
114  try:
115  async with asyncio.timeout(10):
116  acquired_token = await pymelcloud.login(
117  user_input[CONF_USERNAME],
118  user_input[CONF_PASSWORD],
119  async_get_clientsession(self.hass),
120  )
121  except (ClientResponseError, AttributeError) as err:
122  if (
123  isinstance(err, ClientResponseError)
124  and err.status
125  in (
126  HTTPStatus.UNAUTHORIZED,
127  HTTPStatus.FORBIDDEN,
128  )
129  or isinstance(err, AttributeError)
130  and err.name == "get"
131  ):
132  errors["base"] = "invalid_auth"
133  else:
134  errors["base"] = "cannot_connect"
135  except (
136  TimeoutError,
137  ClientError,
138  ):
139  errors["base"] = "cannot_connect"
140 
141  return acquired_token, errors
142 
144  self, user_input: dict[str, Any] | None = None
145  ) -> ConfigFlowResult:
146  """Handle a reconfiguration flow initialized by the user."""
147  errors: dict[str, str] = {}
148  acquired_token = None
149  reconfigure_entry = self._get_reconfigure_entry_get_reconfigure_entry()
150 
151  if user_input is not None:
152  user_input[CONF_USERNAME] = reconfigure_entry.data[CONF_USERNAME]
153  try:
154  async with asyncio.timeout(10):
155  acquired_token = await pymelcloud.login(
156  user_input[CONF_USERNAME],
157  user_input[CONF_PASSWORD],
158  async_get_clientsession(self.hass),
159  )
160  except (ClientResponseError, AttributeError) as err:
161  if (
162  isinstance(err, ClientResponseError)
163  and err.status
164  in (
165  HTTPStatus.UNAUTHORIZED,
166  HTTPStatus.FORBIDDEN,
167  )
168  or isinstance(err, AttributeError)
169  and err.name == "get"
170  ):
171  errors["base"] = "invalid_auth"
172  else:
173  errors["base"] = "cannot_connect"
174  except (
175  TimeoutError,
176  ClientError,
177  ):
178  errors["base"] = "cannot_connect"
179 
180  if not errors:
181  user_input[CONF_TOKEN] = acquired_token
182  return self.async_update_reload_and_abortasync_update_reload_and_abort(
183  reconfigure_entry, data_updates=user_input
184  )
185 
186  return self.async_show_formasync_show_formasync_show_form(
187  step_id="reconfigure",
188  data_schema=vol.Schema(
189  {
190  vol.Required(CONF_PASSWORD): str,
191  }
192  ),
193  errors=errors,
194  description_placeholders={
195  CONF_USERNAME: reconfigure_entry.data[CONF_USERNAME]
196  },
197  )
ConfigFlowResult _create_client(self, str username, *str|None password=None, str|None token=None)
Definition: config_flow.py:43
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:68
ConfigFlowResult _create_entry(self, str username, str token)
Definition: config_flow.py:29
ConfigFlowResult async_step_reconfigure(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:145
tuple[str|None, dict[str, str]] async_reauthenticate_client(self, dict[str, Any] user_input)
Definition: config_flow.py:109
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:82
ConfigFlowResult async_step_reauth_confirm(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_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_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
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)