Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Airzone."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from aioairzone.const import DEFAULT_PORT, DEFAULT_SYSTEM_ID
9 from aioairzone.exceptions import AirzoneError, InvalidSystem
10 from aioairzone.localapi import AirzoneLocalApi, ConnectionOptions
11 import voluptuous as vol
12 
13 from homeassistant.components import dhcp
14 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_HOST, CONF_ID, CONF_PORT
16 from homeassistant.data_entry_flow import AbortFlow
17 from homeassistant.helpers import aiohttp_client
18 from homeassistant.helpers.device_registry import format_mac
19 
20 from .const import DOMAIN
21 
22 _LOGGER = logging.getLogger(__name__)
23 
24 CONFIG_SCHEMA = vol.Schema(
25  {
26  vol.Required(CONF_HOST): str,
27  vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
28  }
29 )
30 SYSTEM_ID_SCHEMA = CONFIG_SCHEMA.extend(
31  {
32  vol.Required(CONF_ID, default=1): int,
33  }
34 )
35 
36 
37 def short_mac(addr: str) -> str:
38  """Convert MAC address to short address."""
39  return addr.replace(":", "")[-4:].upper()
40 
41 
42 class AirZoneConfigFlow(ConfigFlow, domain=DOMAIN):
43  """Handle config flow for an Airzone device."""
44 
45  _discovered_ip: str | None = None
46  _discovered_mac: str | None = None
47 
48  async def async_step_user(
49  self, user_input: dict[str, Any] | None = None
50  ) -> ConfigFlowResult:
51  """Handle the initial step."""
52  data_schema = CONFIG_SCHEMA
53  errors = {}
54 
55  if user_input is not None:
56  self._async_abort_entries_match_async_abort_entries_match(user_input)
57 
58  airzone = AirzoneLocalApi(
59  aiohttp_client.async_get_clientsession(self.hass),
60  ConnectionOptions(
61  user_input[CONF_HOST],
62  user_input[CONF_PORT],
63  user_input.get(CONF_ID, DEFAULT_SYSTEM_ID),
64  ),
65  )
66 
67  try:
68  mac = await airzone.validate()
69  except InvalidSystem:
70  data_schema = SYSTEM_ID_SCHEMA
71  errors[CONF_ID] = "invalid_system_id"
72  except AirzoneError:
73  errors["base"] = "cannot_connect"
74  else:
75  if mac:
76  await self.async_set_unique_idasync_set_unique_id(
77  format_mac(mac), raise_on_progress=False
78  )
79  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
80  updates={
81  CONF_HOST: user_input[CONF_HOST],
82  CONF_PORT: user_input[CONF_PORT],
83  }
84  )
85 
86  title = f"Airzone {user_input[CONF_HOST]}:{user_input[CONF_PORT]}"
87  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
88 
89  return self.async_show_formasync_show_formasync_show_form(
90  step_id="user",
91  data_schema=data_schema,
92  errors=errors,
93  )
94 
95  async def async_step_dhcp(
96  self, discovery_info: dhcp.DhcpServiceInfo
97  ) -> ConfigFlowResult:
98  """Handle DHCP discovery."""
99  self._discovered_ip_discovered_ip = discovery_info.ip
100  self._discovered_mac_discovered_mac = discovery_info.macaddress
101 
102  _LOGGER.debug(
103  "DHCP discovery detected Airzone WebServer: %s", self._discovered_mac_discovered_mac
104  )
105 
106  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: self._discovered_ip_discovered_ip})
107 
108  await self.async_set_unique_idasync_set_unique_id(format_mac(self._discovered_mac_discovered_mac))
109  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
110 
111  options = ConnectionOptions(self._discovered_ip_discovered_ip)
112  airzone = AirzoneLocalApi(
113  aiohttp_client.async_get_clientsession(self.hass), options
114  )
115  try:
116  await airzone.get_version()
117  except (AirzoneError, TimeoutError) as err:
118  raise AbortFlow("cannot_connect") from err
119 
120  return await self.async_step_discovered_connection()
121 
122  async def async_step_discovered_connection(
123  self, user_input: dict[str, Any] | None = None
124  ) -> ConfigFlowResult:
125  """Confirm discovery."""
126  assert self._discovered_ip_discovered_ip is not None
127  assert self._discovered_mac_discovered_mac is not None
128 
129  errors = {}
130  base_schema = {vol.Required(CONF_PORT, default=DEFAULT_PORT): int}
131 
132  if user_input is not None:
133  airzone = AirzoneLocalApi(
134  aiohttp_client.async_get_clientsession(self.hass),
135  ConnectionOptions(
136  self._discovered_ip_discovered_ip,
137  user_input[CONF_PORT],
138  user_input.get(CONF_ID, DEFAULT_SYSTEM_ID),
139  ),
140  )
141 
142  try:
143  mac = await airzone.validate()
144  except InvalidSystem:
145  base_schema[vol.Required(CONF_ID, default=1)] = int
146  errors[CONF_ID] = "invalid_system_id"
147  except AirzoneError:
148  errors["base"] = "cannot_connect"
149  else:
150  user_input[CONF_HOST] = self._discovered_ip_discovered_ip
151 
152  if mac is None:
153  mac = self._discovered_mac_discovered_mac
154 
155  await self.async_set_unique_idasync_set_unique_id(format_mac(mac))
156  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
157  updates={
158  CONF_HOST: user_input[CONF_HOST],
159  CONF_PORT: user_input[CONF_PORT],
160  }
161  )
162 
163  title = f"Airzone {short_mac(mac)}"
164  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=user_input)
165 
166  return self.async_show_formasync_show_formasync_show_form(
167  step_id="discovered_connection",
168  data_schema=vol.Schema(base_schema),
169  errors=errors,
170  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:50
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigFlowResult async_step_dhcp(self, DhcpServiceInfo discovery_info)
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)
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)