Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure SleepIQ component."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from asyncsleepiq import AsyncSleepIQ, SleepIQLoginException, SleepIQTimeoutException
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
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 
22 class SleepIQFlowHandler(ConfigFlow, domain=DOMAIN):
23  """Handle a SleepIQ config flow."""
24 
25  VERSION = 1
26 
27  async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
28  """Import a SleepIQ account as a config entry.
29 
30  This flow is triggered by 'async_setup' for configured accounts.
31  """
32  await self.async_set_unique_idasync_set_unique_id(import_data[CONF_USERNAME].lower())
33  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
34 
35  if error := await try_connection(self.hass, import_data):
36  _LOGGER.error("Could not authenticate with SleepIQ server: %s", error)
37  return self.async_abortasync_abortasync_abort(reason=error)
38 
39  return self.async_create_entryasync_create_entryasync_create_entry(
40  title=import_data[CONF_USERNAME], data=import_data
41  )
42 
43  async def async_step_user(
44  self, user_input: dict[str, Any] | None = None
45  ) -> ConfigFlowResult:
46  """Handle a flow initialized by the user."""
47  errors = {}
48 
49  if user_input is not None:
50  # Don't allow multiple instances with the same username
51  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_USERNAME].lower())
52  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
53 
54  if error := await try_connection(self.hass, user_input):
55  errors["base"] = error
56  else:
57  return self.async_create_entryasync_create_entryasync_create_entry(
58  title=user_input[CONF_USERNAME], data=user_input
59  )
60 
61  else:
62  user_input = {}
63 
64  return self.async_show_formasync_show_formasync_show_form(
65  step_id="user",
66  data_schema=vol.Schema(
67  {
68  vol.Required(
69  CONF_USERNAME,
70  default=user_input.get(CONF_USERNAME),
71  ): str,
72  vol.Required(CONF_PASSWORD): str,
73  }
74  ),
75  errors=errors,
76  last_step=True,
77  )
78 
79  async def async_step_reauth(
80  self, entry_data: Mapping[str, Any]
81  ) -> ConfigFlowResult:
82  """Perform reauth upon an API authentication error."""
83  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
84 
86  self, user_input: dict[str, Any] | None = None
87  ) -> ConfigFlowResult:
88  """Confirm reauth."""
89  errors: dict[str, str] = {}
90 
91  reauth_entry = self._get_reauth_entry_get_reauth_entry()
92  if user_input is not None:
93  data = {
94  CONF_USERNAME: reauth_entry.data[CONF_USERNAME],
95  CONF_PASSWORD: user_input[CONF_PASSWORD],
96  }
97 
98  if not (error := await try_connection(self.hass, data)):
99  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=data)
100  errors["base"] = error
101 
102  return self.async_show_formasync_show_formasync_show_form(
103  step_id="reauth_confirm",
104  data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
105  errors=errors,
106  description_placeholders={
107  CONF_USERNAME: reauth_entry.data[CONF_USERNAME],
108  },
109  )
110 
111 
112 async def try_connection(hass: HomeAssistant, user_input: dict[str, Any]) -> str | None:
113  """Test if the given credentials can successfully login to SleepIQ."""
114 
115  client_session = async_get_clientsession(hass)
116 
117  gateway = AsyncSleepIQ(client_session=client_session)
118  try:
119  await gateway.login(user_input[CONF_USERNAME], user_input[CONF_PASSWORD])
120  except SleepIQLoginException:
121  return "invalid_auth"
122  except SleepIQTimeoutException:
123  return "cannot_connect"
124 
125  return None
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:81
ConfigFlowResult async_step_import(self, dict[str, Any] import_data)
Definition: config_flow.py:27
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:45
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:87
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)
str|None try_connection(HomeAssistant hass, dict[str, Any] user_input)
Definition: config_flow.py:112
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)