Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for WMS WebControl pro API integration."""
2 
3 from __future__ import annotations
4 
5 import ipaddress
6 import logging
7 from typing import Any
8 
9 import aiohttp
10 import voluptuous as vol
11 from wmspro.webcontrol import WebControlPro
12 
13 from homeassistant.components import dhcp
14 from homeassistant.components.dhcp import DhcpServiceInfo
15 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_HOST
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 from homeassistant.helpers.device_registry import format_mac
19 
20 from .const import DOMAIN, SUGGESTED_HOST
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 STEP_USER_DATA_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_HOST): str,
27  }
28 )
29 
30 
31 class WebControlProConfigFlow(ConfigFlow, domain=DOMAIN):
32  """Handle a config flow for wmspro."""
33 
34  VERSION = 1
35 
36  async def async_step_dhcp(
37  self, discovery_info: dhcp.DhcpServiceInfo
38  ) -> ConfigFlowResult:
39  """Handle the DHCP discovery step."""
40  unique_id = format_mac(discovery_info.macaddress)
41  await self.async_set_unique_idasync_set_unique_id(unique_id)
42 
43  entry = self.hass.config_entries.async_entry_for_domain_unique_id(
44  DOMAIN, unique_id
45  )
46  if entry:
47  try: # Check if current host is a valid IP address
48  ipaddress.ip_address(entry.data[CONF_HOST])
49  except ValueError: # Do not touch name-based host
50  return self.async_abortasync_abortasync_abort(reason="already_configured")
51  else: # Update existing host with new IP address
52  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
53  updates={CONF_HOST: discovery_info.ip}
54  )
55 
56  for entry in self.hass.config_entries.async_entries(DOMAIN):
57  if not entry.unique_id and entry.data[CONF_HOST] in (
58  discovery_info.hostname,
59  discovery_info.ip,
60  ):
61  self.hass.config_entries.async_update_entry(entry, unique_id=unique_id)
62  return self.async_abortasync_abortasync_abort(reason="already_configured")
63 
64  return await self.async_step_userasync_step_userasync_step_user()
65 
66  async def async_step_user(
67  self, user_input: dict[str, Any] | None = None
68  ) -> ConfigFlowResult:
69  """Handle the user-based step."""
70  errors: dict[str, str] = {}
71  if user_input is not None:
72  self._async_abort_entries_match_async_abort_entries_match(user_input)
73  host = user_input[CONF_HOST]
74  session = async_get_clientsession(self.hass)
75  hub = WebControlPro(host, session)
76  try:
77  pong = await hub.ping()
78  except aiohttp.ClientError:
79  errors["base"] = "cannot_connect"
80  except Exception:
81  _LOGGER.exception("Unexpected exception")
82  errors["base"] = "unknown"
83  else:
84  if not pong:
85  errors["base"] = "cannot_connect"
86  else:
87  await hub.refresh()
88  rooms = set(hub.rooms.keys())
89  for entry in self.hass.config_entries.async_loaded_entries(DOMAIN):
90  if (
91  entry.runtime_data
92  and entry.runtime_data.rooms
93  and set(entry.runtime_data.rooms.keys()) == rooms
94  ):
95  return self.async_abortasync_abortasync_abort(reason="already_configured")
96  return self.async_create_entryasync_create_entryasync_create_entry(title=host, data=user_input)
97 
98  if self.sourcesourcesourcesource == dhcp.DOMAIN:
99  discovery_info: DhcpServiceInfo = self.init_data
100  data_values = {CONF_HOST: discovery_info.ip}
101  else:
102  data_values = {CONF_HOST: SUGGESTED_HOST}
103 
104  self.context["title_placeholders"] = data_values
105  data_schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
106  STEP_USER_DATA_SCHEMA, data_values
107  )
108 
109  return self.async_show_formasync_show_formasync_show_form(
110  step_id="user", data_schema=data_schema, errors=errors
111  )
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:38
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:68
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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
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)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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|None source(self)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)