Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for devolo Home Network 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 devolo_plc_api.device import Device
10 from devolo_plc_api.exceptions.device import DeviceNotFound
11 import voluptuous as vol
12 
13 from homeassistant.components import zeroconf
14 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_IP_ADDRESS, CONF_NAME, CONF_PASSWORD
16 from homeassistant.core import HomeAssistant
17 from homeassistant.helpers.httpx_client import get_async_client
18 
19 from . import DevoloHomeNetworkConfigEntry
20 from .const import DOMAIN, PRODUCT, SERIAL_NUMBER, TITLE
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_IP_ADDRESS): str})
25 STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Optional(CONF_PASSWORD): str})
26 
27 
28 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, str]:
29  """Validate the user input allows us to connect.
30 
31  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
32  """
33  zeroconf_instance = await zeroconf.async_get_instance(hass)
34  async_client = get_async_client(hass)
35 
36  device = Device(data[CONF_IP_ADDRESS], zeroconf_instance=zeroconf_instance)
37 
38  await device.async_connect(session_instance=async_client)
39  await device.async_disconnect()
40 
41  return {
42  SERIAL_NUMBER: str(device.serial_number),
43  TITLE: device.hostname.split(".", maxsplit=1)[0],
44  }
45 
46 
48  """Handle a config flow for devolo Home Network."""
49 
50  VERSION = 1
51 
52  host: str
53  _reauth_entry: DevoloHomeNetworkConfigEntry
54 
55  async def async_step_user(
56  self, user_input: dict[str, Any] | None = None
57  ) -> ConfigFlowResult:
58  """Handle the initial step."""
59  errors: dict = {}
60 
61  if user_input is None:
62  return self.async_show_formasync_show_formasync_show_form(
63  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
64  )
65 
66  try:
67  info = await validate_input(self.hass, user_input)
68  except DeviceNotFound:
69  errors["base"] = "cannot_connect"
70  except Exception:
71  _LOGGER.exception("Unexpected exception")
72  errors["base"] = "unknown"
73  else:
74  await self.async_set_unique_idasync_set_unique_id(info[SERIAL_NUMBER], raise_on_progress=False)
75  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
76  user_input[CONF_PASSWORD] = ""
77  return self.async_create_entryasync_create_entryasync_create_entry(title=info[TITLE], data=user_input)
78 
79  return self.async_show_formasync_show_formasync_show_form(
80  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
81  )
82 
84  self, discovery_info: zeroconf.ZeroconfServiceInfo
85  ) -> ConfigFlowResult:
86  """Handle zeroconf discovery."""
87  if discovery_info.properties["MT"] in ["2600", "2601"]:
88  return self.async_abortasync_abortasync_abort(reason="home_control")
89 
90  await self.async_set_unique_idasync_set_unique_id(discovery_info.properties["SN"])
91  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
92  updates={CONF_IP_ADDRESS: discovery_info.host}
93  )
94 
95  self.hosthost = discovery_info.host
96  self.context["title_placeholders"] = {
97  PRODUCT: discovery_info.properties["Product"],
98  CONF_NAME: discovery_info.hostname.split(".")[0],
99  }
100 
101  return await self.async_step_zeroconf_confirmasync_step_zeroconf_confirm()
102 
104  self, user_input: dict[str, Any] | None = None
105  ) -> ConfigFlowResult:
106  """Handle a flow initiated by zeroconf."""
107  title = self.context["title_placeholders"][CONF_NAME]
108  if user_input is not None:
109  data = {
110  CONF_IP_ADDRESS: self.hosthost,
111  CONF_PASSWORD: "",
112  }
113  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=data)
114  return self.async_show_formasync_show_formasync_show_form(
115  step_id="zeroconf_confirm",
116  description_placeholders={"host_name": title},
117  )
118 
119  async def async_step_reauth(
120  self, entry_data: Mapping[str, Any]
121  ) -> ConfigFlowResult:
122  """Handle reauthentication."""
123  self._reauth_entry_reauth_entry = self._get_reauth_entry_get_reauth_entry()
124  self.hosthost = entry_data[CONF_IP_ADDRESS]
125  placeholders = {
126  **self.context["title_placeholders"],
127  PRODUCT: self._reauth_entry_reauth_entry.runtime_data.device.product,
128  }
129  self.context["title_placeholders"] = placeholders
130  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
131 
133  self, user_input: dict[str, Any] | None = None
134  ) -> ConfigFlowResult:
135  """Handle a flow initiated by reauthentication."""
136  if user_input is None:
137  return self.async_show_formasync_show_formasync_show_form(
138  step_id="reauth_confirm",
139  data_schema=STEP_REAUTH_DATA_SCHEMA,
140  )
141 
142  data = {
143  CONF_IP_ADDRESS: self.hosthost,
144  CONF_PASSWORD: user_input[CONF_PASSWORD],
145  }
146  return self.async_update_reload_and_abortasync_update_reload_and_abort(self._reauth_entry_reauth_entry, data=data)
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:121
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:85
ConfigFlowResult async_step_zeroconf_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:105
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:57
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:134
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_abort(self, *str reason, Mapping[str, str]|None description_placeholders=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)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
dict[str, str] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:28
httpx.AsyncClient get_async_client(HomeAssistant hass, bool verify_ssl=True)
Definition: httpx_client.py:41