Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Steamist integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any, Self
7 
8 from aiosteamist import Steamist
9 from discovery30303 import Device30303, normalize_mac
10 import voluptuous as vol
11 
12 from homeassistant.components import dhcp
13 from homeassistant.config_entries import ConfigEntryState, ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_DEVICE, CONF_HOST, CONF_MODEL, CONF_NAME
15 from homeassistant.core import callback
16 from homeassistant.helpers import device_registry as dr
17 from homeassistant.helpers.aiohttp_client import async_get_clientsession
18 from homeassistant.helpers.typing import DiscoveryInfoType
19 
20 from .const import CONNECTION_EXCEPTIONS, DISCOVER_SCAN_TIMEOUT, DOMAIN
21 from .discovery import (
22  async_discover_device,
23  async_discover_devices,
24  async_is_steamist_device,
25  async_update_entry_from_discovery,
26 )
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 
31 class SteamistConfigFlow(ConfigFlow, domain=DOMAIN):
32  """Handle a config flow for Steamist."""
33 
34  VERSION = 1
35 
36  host: str | None = None
37 
38  def __init__(self) -> None:
39  """Initialize the config flow."""
40  self._discovered_devices_discovered_devices: dict[str, Device30303] = {}
41  self._discovered_device_discovered_device: Device30303 | None = None
42 
43  async def async_step_dhcp(
44  self, discovery_info: dhcp.DhcpServiceInfo
45  ) -> ConfigFlowResult:
46  """Handle discovery via dhcp."""
47  self._discovered_device_discovered_device = Device30303(
48  ipaddress=discovery_info.ip,
49  name="",
50  mac=normalize_mac(discovery_info.macaddress),
51  hostname=discovery_info.hostname,
52  )
53  return await self._async_handle_discovery_async_handle_discovery()
54 
56  self, discovery_info: DiscoveryInfoType
57  ) -> ConfigFlowResult:
58  """Handle integration discovery."""
59  self._discovered_device_discovered_device = Device30303(
60  ipaddress=discovery_info["ipaddress"],
61  name=discovery_info["name"],
62  mac=discovery_info["mac"],
63  hostname=discovery_info["hostname"],
64  )
65  return await self._async_handle_discovery_async_handle_discovery()
66 
67  async def _async_handle_discovery(self) -> ConfigFlowResult:
68  """Handle any discovery."""
69  device = self._discovered_device_discovered_device
70  assert device is not None
71  mac_address = device.mac
72  mac = dr.format_mac(mac_address)
73  host = device.ipaddress
74  await self.async_set_unique_idasync_set_unique_id(mac)
75  for entry in self._async_current_entries_async_current_entries(include_ignore=False):
76  if entry.unique_id == mac or entry.data[CONF_HOST] == host:
77  if (
78  async_update_entry_from_discovery(self.hass, entry, device)
79  and entry.state is not ConfigEntryState.SETUP_IN_PROGRESS
80  ):
81  self.hass.config_entries.async_schedule_reload(entry.entry_id)
82  return self.async_abortasync_abortasync_abort(reason="already_configured")
83  self.hosthost = host
84  if self.hass.config_entries.flow.async_has_matching_flow(self):
85  return self.async_abortasync_abortasync_abort(reason="already_in_progress")
86  if not device.name:
87  discovery = await async_discover_device(self.hass, device.ipaddress)
88  if not discovery:
89  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
90  self._discovered_device_discovered_device = discovery
91  assert self._discovered_device_discovered_device is not None
92  if not async_is_steamist_device(self._discovered_device_discovered_device):
93  return self.async_abortasync_abortasync_abort(reason="not_steamist_device")
94  return await self.async_step_discovery_confirmasync_step_discovery_confirm()
95 
96  def is_matching(self, other_flow: Self) -> bool:
97  """Return True if other_flow is matching this flow."""
98  return other_flow.host == self.hosthost
99 
101  self, user_input: dict[str, Any] | None = None
102  ) -> ConfigFlowResult:
103  """Confirm discovery."""
104  assert self._discovered_device_discovered_device is not None
105  device = self._discovered_device_discovered_device
106  if user_input is not None:
107  return self._async_create_entry_from_device_async_create_entry_from_device(self._discovered_device_discovered_device)
108  self._set_confirm_only_set_confirm_only()
109  placeholders = {
110  "name": device.name,
111  "ipaddress": device.ipaddress,
112  }
113  self.context["title_placeholders"] = placeholders
114  return self.async_show_formasync_show_formasync_show_form(
115  step_id="discovery_confirm", description_placeholders=placeholders
116  )
117 
118  @callback
119  def _async_create_entry_from_device(self, device: Device30303) -> ConfigFlowResult:
120  """Create a config entry from a device."""
121  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: device.ipaddress})
122  data = {CONF_HOST: device.ipaddress, CONF_NAME: device.name}
123  if device.hostname:
124  data[CONF_MODEL] = device.hostname.split("-", maxsplit=1)[0]
125  return self.async_create_entryasync_create_entryasync_create_entry(
126  title=device.name,
127  data=data,
128  )
129 
131  self, user_input: dict[str, Any] | None = None
132  ) -> ConfigFlowResult:
133  """Handle the step to pick discovered device."""
134  if user_input is not None:
135  mac = user_input[CONF_DEVICE]
136  await self.async_set_unique_idasync_set_unique_id(mac, raise_on_progress=False)
137  device = self._discovered_devices_discovered_devices[mac]
138  return self._async_create_entry_from_device_async_create_entry_from_device(device)
139 
140  current_unique_ids = self._async_current_ids_async_current_ids()
141  current_hosts = {
142  entry.data[CONF_HOST]
143  for entry in self._async_current_entries_async_current_entries(include_ignore=False)
144  }
145  self._discovered_devices_discovered_devices = {
146  dr.format_mac(device.mac): device
147  for device in await async_discover_devices(self.hass, DISCOVER_SCAN_TIMEOUT)
148  }
149  devices_name = {
150  mac: f"{device.name} ({device.ipaddress})"
151  for mac, device in self._discovered_devices_discovered_devices.items()
152  if mac not in current_unique_ids and device.ipaddress not in current_hosts
153  }
154  # Check if there is at least one device
155  if not devices_name:
156  return self.async_abortasync_abortasync_abort(reason="no_devices_found")
157  return self.async_show_formasync_show_formasync_show_form(
158  step_id="pick_device",
159  data_schema=vol.Schema({vol.Required(CONF_DEVICE): vol.In(devices_name)}),
160  )
161 
162  async def async_step_user(
163  self, user_input: dict[str, Any] | None = None
164  ) -> ConfigFlowResult:
165  """Handle the initial step."""
166  errors = {}
167 
168  if user_input is not None:
169  if not (host := user_input[CONF_HOST]):
170  return await self.async_step_pick_deviceasync_step_pick_device()
171  websession = async_get_clientsession(self.hass)
172  try:
173  await Steamist(host, websession).async_get_status()
174  except CONNECTION_EXCEPTIONS:
175  errors["base"] = "cannot_connect"
176  except Exception:
177  _LOGGER.exception("Unexpected exception")
178  errors["base"] = "unknown"
179  else:
180  if discovery := await async_discover_device(self.hass, host):
181  await self.async_set_unique_idasync_set_unique_id(
182  dr.format_mac(discovery.mac), raise_on_progress=False
183  )
184  return self._async_create_entry_from_device_async_create_entry_from_device(discovery)
185  self._async_abort_entries_match_async_abort_entries_match({CONF_HOST: host})
186  return self.async_create_entryasync_create_entryasync_create_entry(title=host, data=user_input)
187 
188  return self.async_show_formasync_show_formasync_show_form(
189  step_id="user",
190  data_schema=vol.Schema({vol.Optional(CONF_HOST, default=""): str}),
191  errors=errors,
192  )
ConfigFlowResult async_step_dhcp(self, dhcp.DhcpServiceInfo discovery_info)
Definition: config_flow.py:45
ConfigFlowResult async_step_discovery_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:102
ConfigFlowResult async_step_pick_device(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:132
ConfigFlowResult _async_create_entry_from_device(self, Device30303 device)
Definition: config_flow.py:119
ConfigFlowResult async_step_integration_discovery(self, DiscoveryInfoType discovery_info)
Definition: config_flow.py:57
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:164
set[str|None] _async_current_ids(self, bool include_ignore=True)
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)
list[ConfigEntry] _async_current_entries(self, bool|None include_ignore=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)
_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)
ElkSystem|None async_discover_device(HomeAssistant hass, str host)
Definition: discovery.py:78
list[ElkSystem] async_discover_devices(HomeAssistant hass, int timeout, str|None address=None)
Definition: discovery.py:43
bool async_update_entry_from_discovery(HomeAssistant hass, config_entries.ConfigEntry entry, ElkSystem device)
Definition: discovery.py:30
bool async_is_steamist_device(Device30303 device)
Definition: discovery.py:28
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)