Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Vodafone Station integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from aiovodafone import VodafoneStationSercommApi, exceptions as aiovodafone_exceptions
9 import voluptuous as vol
10 
12  CONF_CONSIDER_HOME,
13  DEFAULT_CONSIDER_HOME,
14 )
15 from homeassistant.config_entries import (
16  ConfigEntry,
17  ConfigFlow,
18  ConfigFlowResult,
19  OptionsFlow,
20 )
21 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
22 from homeassistant.core import HomeAssistant, callback
23 
24 from .const import _LOGGER, DEFAULT_HOST, DEFAULT_USERNAME, DOMAIN
25 
26 
27 def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema:
28  """Return user form schema."""
29  user_input = user_input or {}
30  return vol.Schema(
31  {
32  vol.Optional(CONF_HOST, default=DEFAULT_HOST): str,
33  vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): str,
34  vol.Required(CONF_PASSWORD): str,
35  }
36  )
37 
38 
39 STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Required(CONF_PASSWORD): str})
40 
41 
42 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
43  """Validate the user input allows us to connect."""
44 
45  api = VodafoneStationSercommApi(
46  data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD]
47  )
48 
49  try:
50  await api.login()
51  finally:
52  await api.logout()
53  await api.close()
54 
55  return {"title": data[CONF_HOST]}
56 
57 
58 class VodafoneStationConfigFlow(ConfigFlow, domain=DOMAIN):
59  """Handle a config flow for Vodafone Station."""
60 
61  VERSION = 1
62 
63  @staticmethod
64  @callback
66  config_entry: ConfigEntry,
67  ) -> VodafoneStationOptionsFlowHandler:
68  """Get the options flow for this handler."""
70 
71  async def async_step_user(
72  self, user_input: dict[str, Any] | None = None
73  ) -> ConfigFlowResult:
74  """Handle the initial step."""
75  if user_input is None:
76  return self.async_show_formasync_show_formasync_show_form(
77  step_id="user", data_schema=user_form_schema(user_input)
78  )
79 
80  # Use host because no serial number or mac is available to use for a unique id
81  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]})
82 
83  errors = {}
84 
85  try:
86  info = await validate_input(self.hass, user_input)
87  except aiovodafone_exceptions.AlreadyLogged:
88  errors["base"] = "already_logged"
89  except aiovodafone_exceptions.CannotConnect:
90  errors["base"] = "cannot_connect"
91  except aiovodafone_exceptions.CannotAuthenticate:
92  errors["base"] = "invalid_auth"
93  except aiovodafone_exceptions.ModelNotSupported:
94  errors["base"] = "model_not_supported"
95  except Exception: # noqa: BLE001
96  _LOGGER.exception("Unexpected exception")
97  errors["base"] = "unknown"
98  else:
99  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
100 
101  return self.async_show_formasync_show_formasync_show_form(
102  step_id="user", data_schema=user_form_schema(user_input), errors=errors
103  )
104 
105  async def async_step_reauth(
106  self, entry_data: Mapping[str, Any]
107  ) -> ConfigFlowResult:
108  """Handle reauth flow."""
109  self.context["title_placeholders"] = {"host": entry_data[CONF_HOST]}
110  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
111 
113  self, user_input: dict[str, Any] | None = None
114  ) -> ConfigFlowResult:
115  """Handle reauth confirm."""
116  errors = {}
117 
118  reauth_entry = self._get_reauth_entry_get_reauth_entry()
119  if user_input is not None:
120  try:
121  await validate_input(self.hass, {**reauth_entry.data, **user_input})
122  except aiovodafone_exceptions.AlreadyLogged:
123  errors["base"] = "already_logged"
124  except aiovodafone_exceptions.CannotConnect:
125  errors["base"] = "cannot_connect"
126  except aiovodafone_exceptions.CannotAuthenticate:
127  errors["base"] = "invalid_auth"
128  except Exception: # noqa: BLE001
129  _LOGGER.exception("Unexpected exception")
130  errors["base"] = "unknown"
131  else:
132  return self.async_update_reload_and_abortasync_update_reload_and_abort(
133  reauth_entry,
134  data_updates={
135  CONF_PASSWORD: user_input[CONF_PASSWORD],
136  },
137  )
138 
139  return self.async_show_formasync_show_formasync_show_form(
140  step_id="reauth_confirm",
141  description_placeholders={CONF_HOST: reauth_entry.data[CONF_HOST]},
142  data_schema=STEP_REAUTH_DATA_SCHEMA,
143  errors=errors,
144  )
145 
146 
148  """Handle a option flow."""
149 
150  async def async_step_init(
151  self, user_input: dict[str, Any] | None = None
152  ) -> ConfigFlowResult:
153  """Handle options flow."""
154 
155  if user_input is not None:
156  return self.async_create_entryasync_create_entry(title="", data=user_input)
157 
158  data_schema = vol.Schema(
159  {
160  vol.Optional(
161  CONF_CONSIDER_HOME,
162  default=self.config_entryconfig_entryconfig_entry.options.get(
163  CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME.total_seconds()
164  ),
165  ): vol.All(vol.Coerce(int), vol.Clamp(min=0, max=900))
166  }
167  )
168  return self.async_show_formasync_show_form(step_id="init", data_schema=data_schema)
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:107
VodafoneStationOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:67
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:114
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:73
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:152
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)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
None config_entry(self, ConfigEntry value)
_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, Any] data)
Definition: config_flow.py:42
vol.Schema user_form_schema(dict[str, Any]|None user_input)
Definition: config_flow.py:27