Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for TRIGGERcmd integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import jwt
9 from triggercmd import TRIGGERcmdConnectionError, client
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.core import HomeAssistant
14 from homeassistant.exceptions import HomeAssistantError
15 
16 from .const import CONF_TOKEN, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 DATA_SCHEMA = vol.Schema({(CONF_TOKEN): str})
21 
22 
23 async def validate_input(hass: HomeAssistant, data: dict) -> str:
24  """Validate the user input allows us to connect.
25 
26  Data has the keys from DATA_SCHEMA with values provided by the user.
27  """
28  if len(data[CONF_TOKEN]) < 100:
29  raise InvalidToken
30 
31  token_data = jwt.decode(data[CONF_TOKEN], options={"verify_signature": False})
32  if not token_data["id"]:
33  raise InvalidToken
34 
35  try:
36  await client.async_connection_test(data[CONF_TOKEN])
37  except Exception as e:
38  raise TRIGGERcmdConnectionError from e
39  else:
40  return token_data["id"]
41 
42 
43 class TriggerCMDConfigFlow(ConfigFlow, domain=DOMAIN):
44  """Handle a config flow."""
45 
46  VERSION = 1
47 
48  async def async_step_user(
49  self, user_input: dict[str, Any] | None = None
50  ) -> ConfigFlowResult:
51  """Handle the initial step."""
52  errors = {}
53  if user_input is not None:
54  try:
55  identifier = await validate_input(self.hass, user_input)
56  except InvalidToken:
57  errors[CONF_TOKEN] = "invalid_token"
58  except TRIGGERcmdConnectionError:
59  errors["base"] = "cannot_connect"
60  except Exception: # pylint: disable=broad-except
61  _LOGGER.exception("Unexpected exception")
62  errors["base"] = "unknown"
63  else:
64  await self.async_set_unique_idasync_set_unique_id(identifier)
65  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
66 
67  return self.async_create_entryasync_create_entryasync_create_entry(title="TRIGGERcmd Hub", data=user_input)
68 
69  return self.async_show_formasync_show_formasync_show_form(
70  step_id="user", data_schema=DATA_SCHEMA, errors=errors
71  )
72 
73 
75  """Invalid token."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:50
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_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 validate_input(HomeAssistant hass, dict data)
Definition: config_flow.py:23