Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for baf."""
2 
3 from __future__ import annotations
4 
5 from asyncio import timeout
6 import logging
7 from typing import Any
8 
9 from aiobafi6 import Device, Service
10 from aiobafi6.discovery import PORT
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
16 
17 from .const import DOMAIN, RUN_TIMEOUT
18 from .models import BAFDiscovery
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
23 async def async_try_connect(ip_address: str) -> Device:
24  """Validate we can connect to a device."""
25  device = Device(Service(ip_addresses=[ip_address], port=PORT))
26  run_future = device.async_run()
27  try:
28  async with timeout(RUN_TIMEOUT):
29  await device.async_wait_available()
30  except TimeoutError as ex:
31  raise CannotConnect from ex
32  finally:
33  run_future.cancel()
34  return device
35 
36 
37 class BAFFlowHandler(ConfigFlow, domain=DOMAIN):
38  """Handle BAF discovery config flow."""
39 
40  VERSION = 1
41 
42  def __init__(self) -> None:
43  """Initialize the BAF config flow."""
44  self.discoverydiscovery: BAFDiscovery | None = None
45 
47  self, discovery_info: zeroconf.ZeroconfServiceInfo
48  ) -> ConfigFlowResult:
49  """Handle zeroconf discovery."""
50  if discovery_info.ip_address.version == 6:
51  return self.async_abortasync_abortasync_abort(reason="ipv6_not_supported")
52  properties = discovery_info.properties
53  ip_address = discovery_info.host
54  uuid = properties["uuid"]
55  model = properties["model"]
56  name = properties["name"]
57  await self.async_set_unique_idasync_set_unique_id(uuid)
58  self._abort_if_unique_id_configured_abort_if_unique_id_configured(updates={CONF_IP_ADDRESS: ip_address})
59  self.discoverydiscovery = BAFDiscovery(ip_address, name, uuid, model)
60  return await self.async_step_discovery_confirmasync_step_discovery_confirm()
61 
63  self, user_input: dict[str, Any] | None = None
64  ) -> ConfigFlowResult:
65  """Confirm discovery."""
66  assert self.discoverydiscovery is not None
67  discovery = self.discoverydiscovery
68  if user_input is not None:
69  return self.async_create_entryasync_create_entryasync_create_entry(
70  title=discovery.name,
71  data={CONF_IP_ADDRESS: discovery.ip_address},
72  )
73  placeholders = {
74  "name": discovery.name,
75  "model": discovery.model,
76  "ip_address": discovery.ip_address,
77  }
78  self.context["title_placeholders"] = placeholders
79  self._set_confirm_only_set_confirm_only()
80  return self.async_show_formasync_show_formasync_show_form(
81  step_id="discovery_confirm", description_placeholders=placeholders
82  )
83 
84  async def async_step_user(
85  self, user_input: dict[str, Any] | None = None
86  ) -> ConfigFlowResult:
87  """Handle the initial step."""
88  errors = {}
89  ip_address = (user_input or {}).get(CONF_IP_ADDRESS, "")
90  if user_input is not None:
91  try:
92  device = await async_try_connect(ip_address)
93  except CannotConnect:
94  errors[CONF_IP_ADDRESS] = "cannot_connect"
95  except Exception:
96  _LOGGER.exception(
97  "Unknown exception during connection test to %s", ip_address
98  )
99  errors["base"] = "unknown"
100  else:
101  await self.async_set_unique_idasync_set_unique_id(
102  device.dns_sd_uuid, raise_on_progress=False
103  )
104  self._abort_if_unique_id_configured_abort_if_unique_id_configured(
105  updates={CONF_IP_ADDRESS: ip_address}
106  )
107  return self.async_create_entryasync_create_entryasync_create_entry(
108  title=device.name,
109  data={CONF_IP_ADDRESS: ip_address},
110  )
111 
112  return self.async_show_formasync_show_formasync_show_form(
113  step_id="user",
114  data_schema=vol.Schema(
115  {vol.Required(CONF_IP_ADDRESS, default=ip_address): str}
116  ),
117  errors=errors,
118  )
119 
120 
121 class CannotConnect(Exception):
122  """Exception to raise when we cannot connect."""
ConfigFlowResult async_step_discovery_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:64
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:86
ConfigFlowResult async_step_zeroconf(self, zeroconf.ZeroconfServiceInfo discovery_info)
Definition: config_flow.py:48
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_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)
Device async_try_connect(str ip_address)
Definition: config_flow.py:23
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88