Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for LaCrosse View 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 lacrosse_view import LaCrosse, Location, LoginError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 from homeassistant.helpers.aiohttp_client import async_get_clientsession
16 
17 from .const import DOMAIN
18 
19 STEP_USER_DATA_SCHEMA = vol.Schema(
20  {
21  vol.Required("username"): str,
22  vol.Required("password"): str,
23  }
24 )
25 _LOGGER = logging.getLogger(__name__)
26 
27 
28 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> list[Location]:
29  """Validate the user input allows us to connect."""
30 
31  api = LaCrosse(async_get_clientsession(hass))
32 
33  try:
34  if await api.login(data["username"], data["password"]):
35  _LOGGER.debug("Successfully logged in")
36 
37  locations = await api.get_locations()
38  _LOGGER.debug(locations)
39  except LoginError as error:
40  raise InvalidAuth from error
41 
42  if not locations:
43  raise NoLocations(f'No locations found for account {data["username"]}')
44 
45  return locations
46 
47 
48 class LaCrosseViewConfigFlow(ConfigFlow, domain=DOMAIN):
49  """Handle a config flow for LaCrosse View."""
50 
51  VERSION = 1
52 
53  def __init__(self) -> None:
54  """Initialize the config flow."""
55  self.datadata: dict[str, str] = {}
56  self.locationslocations: list[Location] = []
57 
58  async def async_step_user(
59  self, user_input: dict[str, Any] | None = None
60  ) -> ConfigFlowResult:
61  """Handle the initial step."""
62  if user_input is None:
63  _LOGGER.debug("Showing initial form")
64  return self.async_show_formasync_show_formasync_show_form(
65  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
66  )
67 
68  errors = {}
69 
70  try:
71  info = await validate_input(self.hass, user_input)
72  except InvalidAuth:
73  _LOGGER.exception("Could not login")
74  errors["base"] = "invalid_auth"
75  except NoLocations:
76  errors["base"] = "no_locations"
77  except Exception:
78  _LOGGER.exception("Unexpected exception")
79  errors["base"] = "unknown"
80  else:
81  self.datadata = user_input
82  self.locationslocations = info
83 
84  # Check if we are reauthenticating
85  if self.sourcesourcesourcesource == SOURCE_REAUTH:
86  return self.async_update_reload_and_abortasync_update_reload_and_abort(
87  self._get_reauth_entry_get_reauth_entry(), data_updates=self.datadata
88  )
89 
90  _LOGGER.debug("Moving on to location step")
91  return await self.async_step_locationasync_step_location()
92 
93  _LOGGER.debug("Showing errors")
94  return self.async_show_formasync_show_formasync_show_form(
95  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
96  )
97 
99  self, user_input: dict[str, Any] | None = None
100  ) -> ConfigFlowResult:
101  """Handle the location step."""
102 
103  if not user_input:
104  _LOGGER.debug("Showing initial location selection")
105  return self.async_show_formasync_show_formasync_show_form(
106  step_id="location",
107  data_schema=vol.Schema(
108  {
109  vol.Required("location"): vol.In(
110  {location.id: location.name for location in self.locationslocations}
111  )
112  }
113  ),
114  )
115 
116  location_id = user_input["location"]
117 
118  location_name = next(
119  location.name for location in self.locationslocations if location.id == location_id
120  )
121 
122  await self.async_set_unique_idasync_set_unique_id(location_id)
123  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
124 
125  return self.async_create_entryasync_create_entryasync_create_entry(
126  title=location_name,
127  data={
128  "id": location_id,
129  "name": location_name,
130  "username": self.datadata["username"],
131  "password": self.datadata["password"],
132  },
133  )
134 
135  async def async_step_reauth(
136  self, entry_data: Mapping[str, Any]
137  ) -> ConfigFlowResult:
138  """Reauth in case of a password change or other error."""
139  return await self.async_step_userasync_step_userasync_step_user()
140 
141 
143  """Error to indicate there is invalid auth."""
144 
145 
146 class NoLocations(HomeAssistantError):
147  """Error to indicate there are no locations."""
148 
149 
151  """Error to indicate that the entry does not exist when it should."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:60
ConfigFlowResult async_step_location(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:100
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:137
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)
list[Location] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:28
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)