Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Prosegur Alarm integration."""
2 
3 from collections.abc import Mapping
4 import logging
5 from typing import Any
6 
7 from pyprosegur.auth import COUNTRY, Auth
8 from pyprosegur.installation import Installation
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_COUNTRY, CONF_PASSWORD, CONF_USERNAME
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 from homeassistant.helpers import aiohttp_client, selector
16 
17 from .const import CONF_CONTRACT, DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 STEP_USER_DATA_SCHEMA = vol.Schema(
22  {
23  vol.Required(CONF_USERNAME): str,
24  vol.Required(CONF_PASSWORD): str,
25  vol.Required(CONF_COUNTRY): selector.CountrySelector(
26  selector.CountrySelectorConfig(countries=list(COUNTRY))
27  ),
28  }
29 )
30 
31 
32 async def validate_input(hass: HomeAssistant, data):
33  """Validate the user input allows us to connect."""
34  session = aiohttp_client.async_get_clientsession(hass)
35  auth = Auth(session, data[CONF_USERNAME], data[CONF_PASSWORD], data[CONF_COUNTRY])
36  try:
37  contracts = await Installation.list(auth)
38  except ConnectionRefusedError:
39  raise InvalidAuth from ConnectionRefusedError
40  except ConnectionError:
41  raise CannotConnect from ConnectionError
42  return auth, contracts
43 
44 
45 class ProsegurConfigFlow(ConfigFlow, domain=DOMAIN):
46  """Handle a config flow for Prosegur Alarm."""
47 
48  VERSION = 1
49  auth: Auth
50  user_input: dict
51  contracts: list[dict[str, str]]
52 
53  async def async_step_user(
54  self, user_input: dict[str, Any] | None = None
55  ) -> ConfigFlowResult:
56  """Handle the initial step."""
57  errors = {}
58 
59  if user_input:
60  try:
61  self.auth, self.contractscontracts = await validate_input(self.hass, user_input)
62  except CannotConnect:
63  errors["base"] = "cannot_connect"
64  except InvalidAuth:
65  errors["base"] = "invalid_auth"
66  except Exception:
67  _LOGGER.exception("Unexpected exception")
68  errors["base"] = "unknown"
69  else:
70  self.user_inputuser_input = user_input
71  return await self.async_step_choose_contractasync_step_choose_contract()
72 
73  return self.async_show_formasync_show_formasync_show_form(
74  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
75  )
76 
78  self, user_input: Any | None = None
79  ) -> ConfigFlowResult:
80  """Let user decide which contract is being setup."""
81 
82  if user_input:
83  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_CONTRACT])
84  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
85 
86  self.user_inputuser_input[CONF_CONTRACT] = user_input[CONF_CONTRACT]
87 
88  return self.async_create_entryasync_create_entryasync_create_entry(
89  title=f"Contract {user_input[CONF_CONTRACT]}", data=self.user_inputuser_input
90  )
91 
92  contract_options = [
93  selector.SelectOptionDict(value=c["contractId"], label=c["description"])
94  for c in self.contractscontracts
95  ]
96 
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="choose_contract",
99  data_schema=vol.Schema(
100  {
101  vol.Required(CONF_CONTRACT): selector.SelectSelector(
102  selector.SelectSelectorConfig(options=contract_options)
103  ),
104  }
105  ),
106  )
107 
108  async def async_step_reauth(
109  self, entry_data: Mapping[str, Any]
110  ) -> ConfigFlowResult:
111  """Handle initiation of re-authentication with Prosegur."""
112  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
113 
115  self, user_input: dict[str, str] | None = None
116  ) -> ConfigFlowResult:
117  """Handle re-authentication with Prosegur."""
118  errors: dict[str, str] = {}
119 
120  reauth_entry = self._get_reauth_entry_get_reauth_entry()
121  if user_input:
122  try:
123  user_input[CONF_COUNTRY] = reauth_entry.data[CONF_COUNTRY]
124  self.auth, self.contractscontracts = await validate_input(self.hass, user_input)
125 
126  except CannotConnect:
127  errors["base"] = "cannot_connect"
128  except InvalidAuth:
129  errors["base"] = "invalid_auth"
130  except Exception:
131  _LOGGER.exception("Unexpected exception")
132  errors["base"] = "unknown"
133  else:
134  return self.async_update_reload_and_abortasync_update_reload_and_abort(
135  reauth_entry,
136  data_updates={
137  CONF_USERNAME: user_input[CONF_USERNAME],
138  CONF_PASSWORD: user_input[CONF_PASSWORD],
139  },
140  )
141 
142  return self.async_show_formasync_show_formasync_show_form(
143  step_id="reauth_confirm",
144  data_schema=vol.Schema(
145  {
146  vol.Required(
147  CONF_USERNAME, default=reauth_entry.data[CONF_USERNAME]
148  ): str,
149  vol.Required(CONF_PASSWORD): str,
150  }
151  ),
152  errors=errors,
153  )
154 
155 
157  """Error to indicate we cannot connect."""
158 
159 
161  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:55
ConfigFlowResult async_step_reauth_confirm(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:116
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:110
ConfigFlowResult async_step_choose_contract(self, Any|None user_input=None)
Definition: config_flow.py:79
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)
def validate_input(HomeAssistant hass, data)
Definition: config_flow.py:32