Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Comelit integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from aiocomelit import (
9  ComeliteSerialBridgeApi,
10  ComelitVedoApi,
11  exceptions as aiocomelit_exceptions,
12 )
13 from aiocomelit.api import ComelitCommonApi
14 from aiocomelit.const import BRIDGE
15 import voluptuous as vol
16 
17 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
18 from homeassistant.const import CONF_HOST, CONF_PIN, CONF_PORT, CONF_TYPE
19 from homeassistant.core import HomeAssistant
20 from homeassistant.exceptions import HomeAssistantError
22 
23 from .const import _LOGGER, DEFAULT_PORT, DEVICE_TYPE_LIST, DOMAIN
24 
25 DEFAULT_HOST = "192.168.1.252"
26 DEFAULT_PIN = 111111
27 
28 
29 def user_form_schema(user_input: dict[str, Any] | None) -> vol.Schema:
30  """Return user form schema."""
31  user_input = user_input or {}
32  return vol.Schema(
33  {
34  vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
35  vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
36  vol.Optional(CONF_PIN, default=DEFAULT_PIN): cv.positive_int,
37  vol.Required(CONF_TYPE, default=BRIDGE): vol.In(DEVICE_TYPE_LIST),
38  }
39  )
40 
41 
42 STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Required(CONF_PIN): cv.positive_int})
43 
44 
45 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
46  """Validate the user input allows us to connect."""
47 
48  api: ComelitCommonApi
49  if data.get(CONF_TYPE, BRIDGE) == BRIDGE:
50  api = ComeliteSerialBridgeApi(data[CONF_HOST], data[CONF_PORT], data[CONF_PIN])
51  else:
52  api = ComelitVedoApi(data[CONF_HOST], data[CONF_PORT], data[CONF_PIN])
53 
54  try:
55  await api.login()
56  except aiocomelit_exceptions.CannotConnect as err:
57  raise CannotConnect from err
58  except aiocomelit_exceptions.CannotAuthenticate as err:
59  raise InvalidAuth from err
60  finally:
61  await api.logout()
62  await api.close()
63 
64  return {"title": data[CONF_HOST]}
65 
66 
67 class ComelitConfigFlow(ConfigFlow, domain=DOMAIN):
68  """Handle a config flow for Comelit."""
69 
70  VERSION = 1
71 
72  async def async_step_user(
73  self, user_input: dict[str, Any] | None = None
74  ) -> ConfigFlowResult:
75  """Handle the initial step."""
76  if user_input is None:
77  return self.async_show_formasync_show_formasync_show_form(
78  step_id="user", data_schema=user_form_schema(user_input)
79  )
80 
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 CannotConnect:
88  errors["base"] = "cannot_connect"
89  except InvalidAuth:
90  errors["base"] = "invalid_auth"
91  except Exception: # noqa: BLE001
92  _LOGGER.exception("Unexpected exception")
93  errors["base"] = "unknown"
94  else:
95  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
96 
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="user", data_schema=user_form_schema(user_input), errors=errors
99  )
100 
101  async def async_step_reauth(
102  self, entry_data: Mapping[str, Any]
103  ) -> ConfigFlowResult:
104  """Handle reauth flow."""
105  self.context["title_placeholders"] = {"host": entry_data[CONF_HOST]}
106  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
107 
109  self, user_input: dict[str, Any] | None = None
110  ) -> ConfigFlowResult:
111  """Handle reauth confirm."""
112  errors = {}
113 
114  reauth_entry = self._get_reauth_entry_get_reauth_entry()
115  entry_data = reauth_entry.data
116 
117  if user_input is not None:
118  try:
119  await validate_input(
120  self.hass,
121  {
122  CONF_HOST: entry_data[CONF_HOST],
123  CONF_PORT: entry_data.get(CONF_PORT, DEFAULT_PORT),
124  CONF_TYPE: entry_data.get(CONF_TYPE, BRIDGE),
125  }
126  | user_input,
127  )
128  except CannotConnect:
129  errors["base"] = "cannot_connect"
130  except InvalidAuth:
131  errors["base"] = "invalid_auth"
132  except Exception: # noqa: BLE001
133  _LOGGER.exception("Unexpected exception")
134  errors["base"] = "unknown"
135  else:
136  return self.async_update_reload_and_abortasync_update_reload_and_abort(
137  reauth_entry,
138  data={
139  CONF_HOST: entry_data[CONF_HOST],
140  CONF_PORT: entry_data.get(CONF_PORT, DEFAULT_PORT),
141  CONF_PIN: user_input[CONF_PIN],
142  CONF_TYPE: entry_data.get(CONF_TYPE, BRIDGE),
143  },
144  )
145 
146  return self.async_show_formasync_show_formasync_show_form(
147  step_id="reauth_confirm",
148  description_placeholders={CONF_HOST: entry_data[CONF_HOST]},
149  data_schema=STEP_REAUTH_DATA_SCHEMA,
150  errors=errors,
151  )
152 
153 
155  """Error to indicate we cannot connect."""
156 
157 
159  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:74
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:110
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:103
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)
_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)
vol.Schema user_form_schema(dict[str, Any]|None user_input)
Definition: config_flow.py:29
dict[str, str] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:45