Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Fibaro 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 slugify import slugify
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_URL, CONF_USERNAME
14 from homeassistant.core import HomeAssistant
15 
16 from . import FibaroAuthFailed, FibaroConnectFailed, init_controller
17 from .const import CONF_IMPORT_PLUGINS, DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 STEP_USER_DATA_SCHEMA = vol.Schema(
22  {
23  vol.Required(CONF_URL): str,
24  vol.Required(CONF_USERNAME): str,
25  vol.Required(CONF_PASSWORD): str,
26  vol.Optional(CONF_IMPORT_PLUGINS, default=False): bool,
27  }
28 )
29 
30 
31 async def _validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
32  """Validate the user input allows us to connect.
33 
34  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
35  """
36  controller = await hass.async_add_executor_job(init_controller, data)
37 
38  _LOGGER.debug(
39  "Successfully connected to fibaro home center %s with name %s",
40  controller.hub_serial,
41  controller.hub_name,
42  )
43  return {
44  "serial_number": slugify(controller.hub_serial),
45  "name": controller.hub_name,
46  }
47 
48 
49 def _normalize_url(url: str) -> str:
50  """Try to fix errors in the entered url.
51 
52  We know that the url should be in the format http://<HOST>/api/
53  """
54  if url.endswith("/api"):
55  return f"{url}/"
56  if not url.endswith("/api/"):
57  return f"{url}api/" if url.endswith("/") else f"{url}/api/"
58  return url
59 
60 
61 class FibaroConfigFlow(ConfigFlow, domain=DOMAIN):
62  """Handle a config flow for Fibaro."""
63 
64  VERSION = 1
65 
66  async def async_step_user(
67  self, user_input: dict[str, Any] | None = None
68  ) -> ConfigFlowResult:
69  """Handle the initial step."""
70  errors = {}
71 
72  if user_input is not None:
73  try:
74  user_input[CONF_URL] = _normalize_url(user_input[CONF_URL])
75  info = await _validate_input(self.hass, user_input)
76  except FibaroConnectFailed:
77  errors["base"] = "cannot_connect"
78  except FibaroAuthFailed:
79  errors["base"] = "invalid_auth"
80  else:
81  await self.async_set_unique_idasync_set_unique_id(info["serial_number"])
82  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates=user_input)
83  return self.async_create_entryasync_create_entryasync_create_entry(title=info["name"], data=user_input)
84 
85  return self.async_show_formasync_show_formasync_show_form(
86  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
87  )
88 
89  async def async_step_reauth(
90  self, entry_data: Mapping[str, Any]
91  ) -> ConfigFlowResult:
92  """Handle reauthentication."""
93  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
94 
96  self, user_input: dict[str, Any] | None = None
97  ) -> ConfigFlowResult:
98  """Handle a flow initiated by reauthentication."""
99  errors = {}
100 
101  reauth_entry = self._get_reauth_entry_get_reauth_entry()
102 
103  if user_input is not None:
104  new_data = reauth_entry.data | user_input
105  try:
106  await _validate_input(self.hass, new_data)
107  except FibaroConnectFailed:
108  errors["base"] = "cannot_connect"
109  except FibaroAuthFailed:
110  errors["base"] = "invalid_auth"
111  else:
112  return self.async_update_reload_and_abortasync_update_reload_and_abort(
113  reauth_entry, data_updates=user_input
114  )
115 
116  return self.async_show_formasync_show_formasync_show_form(
117  step_id="reauth_confirm",
118  data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
119  errors=errors,
120  description_placeholders={
121  CONF_USERNAME: reauth_entry.data[CONF_USERNAME],
122  CONF_NAME: reauth_entry.title,
123  },
124  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:91
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:68
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:97
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)
dict[str, Any] _validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:31