Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Vilfo Router integration."""
2 
3 import logging
4 from typing import Any
5 
6 from vilfo import Client as VilfoClient
7 from vilfo.exceptions import (
8  AuthenticationException as VilfoAuthenticationException,
9  VilfoException,
10 )
11 import voluptuous as vol
12 
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, CONF_ID, CONF_MAC
15 from homeassistant.core import HomeAssistant
16 from homeassistant.exceptions import HomeAssistantError
17 from homeassistant.util.network import is_host_valid
18 
19 from .const import DOMAIN, ROUTER_DEFAULT_HOST
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 DATA_SCHEMA = vol.Schema(
24  {
25  vol.Required(CONF_HOST, default=ROUTER_DEFAULT_HOST): str,
26  vol.Required(CONF_ACCESS_TOKEN, default=""): str,
27  }
28 )
29 
30 RESULT_SUCCESS = "success"
31 RESULT_CANNOT_CONNECT = "cannot_connect"
32 RESULT_INVALID_AUTH = "invalid_auth"
33 
34 
36  """Attempt to connect and call the ping endpoint and, if successful, fetch basic information."""
37 
38  # Perform the ping. This doesn't validate authentication.
39  controller = VilfoClient(host=host, token=token)
40  result = {"type": None, "data": {}}
41 
42  try:
43  controller.ping()
44  except VilfoException:
45  result["type"] = RESULT_CANNOT_CONNECT
46  result["data"] = CannotConnect
47  return result
48 
49  # Perform a call that requires authentication.
50  try:
51  controller.get_board_information()
52  except VilfoAuthenticationException:
53  result["type"] = RESULT_INVALID_AUTH
54  result["data"] = InvalidAuth
55  return result
56 
57  if controller.mac:
58  result["data"][CONF_ID] = controller.mac
59  result["data"][CONF_MAC] = controller.mac
60  else:
61  result["data"][CONF_ID] = host
62  result["data"][CONF_MAC] = None
63 
64  result["type"] = RESULT_SUCCESS
65 
66  return result
67 
68 
69 async def validate_input(hass: HomeAssistant, data):
70  """Validate the user input allows us to connect.
71 
72  Data has the keys from DATA_SCHEMA with values provided by the user.
73  """
74 
75  # Validate the host before doing anything else.
76  if not is_host_valid(data[CONF_HOST]):
77  raise InvalidHost
78 
79  config = {}
80 
81  result = await hass.async_add_executor_job(
82  _try_connect_and_fetch_basic_info, data[CONF_HOST], data[CONF_ACCESS_TOKEN]
83  )
84 
85  if result["type"] != RESULT_SUCCESS:
86  raise result["data"]
87 
88  # Return some info we want to store in the config entry.
89  result_data = result["data"]
90  config["title"] = f"{data[CONF_HOST]}"
91  config[CONF_MAC] = result_data[CONF_MAC]
92  config[CONF_HOST] = data[CONF_HOST]
93  config[CONF_ID] = result_data[CONF_ID]
94 
95  return config
96 
97 
98 class DomainConfigFlow(ConfigFlow, domain=DOMAIN):
99  """Handle a config flow for Vilfo Router."""
100 
101  VERSION = 1
102 
103  async def async_step_user(
104  self, user_input: dict[str, Any] | None = None
105  ) -> ConfigFlowResult:
106  """Handle the initial step."""
107  errors = {}
108  if user_input is not None:
109  try:
110  info = await validate_input(self.hass, user_input)
111  except InvalidHost:
112  errors["base"] = "invalid_host"
113  except CannotConnect:
114  errors["base"] = "cannot_connect"
115  except InvalidAuth:
116  errors["base"] = "invalid_auth"
117  except Exception as err: # noqa: BLE001
118  _LOGGER.error("Unexpected exception: %s", err)
119  errors["base"] = "unknown"
120  else:
121  await self.async_set_unique_idasync_set_unique_id(info[CONF_ID])
122  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
123 
124  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
125 
126  return self.async_show_formasync_show_formasync_show_form(
127  step_id="user", data_schema=DATA_SCHEMA, errors=errors
128  )
129 
130 
132  """Error to indicate we cannot connect."""
133 
134 
135 class InvalidAuth(HomeAssistantError):
136  """Error to indicate there is invalid auth."""
137 
138 
140  """Error to indicate that hostname/IP address is invalid."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:105
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)
def validate_input(HomeAssistant hass, data)
Definition: config_flow.py:69
def _try_connect_and_fetch_basic_info(host, token)
Definition: config_flow.py:35
bool is_host_valid(str host)
Definition: network.py:93