Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for LEDBLE integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from bluetooth_data_tools import human_readable_name
9 from led_ble import BLEAK_EXCEPTIONS, LEDBLE
10 import voluptuous as vol
11 
13  BluetoothServiceInfoBleak,
14  async_discovered_service_info,
15 )
16 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
17 from homeassistant.const import CONF_ADDRESS
18 
19 from .const import DOMAIN, LOCAL_NAMES, UNSUPPORTED_SUB_MODEL
20 
21 _LOGGER = logging.getLogger(__name__)
22 
23 
24 class LedBleConfigFlow(ConfigFlow, domain=DOMAIN):
25  """Handle a config flow for Yale Access Bluetooth."""
26 
27  VERSION = 1
28 
29  def __init__(self) -> None:
30  """Initialize the config flow."""
31  self._discovery_info_discovery_info: BluetoothServiceInfoBleak | None = None
32  self._discovered_devices: dict[str, BluetoothServiceInfoBleak] = {}
33 
35  self, discovery_info: BluetoothServiceInfoBleak
36  ) -> ConfigFlowResult:
37  """Handle the bluetooth discovery step."""
38  if discovery_info.name.startswith(UNSUPPORTED_SUB_MODEL):
39  # These versions speak a different protocol
40  # that we do not support yet.
41  return self.async_abortasync_abortasync_abort(reason="not_supported")
42  await self.async_set_unique_idasync_set_unique_id(discovery_info.address)
43  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
44  self._discovery_info_discovery_info = discovery_info
45  self.context["title_placeholders"] = {
46  "name": human_readable_name(
47  None, discovery_info.name, discovery_info.address
48  )
49  }
50  return await self.async_step_userasync_step_userasync_step_user()
51 
52  async def async_step_user(
53  self, user_input: dict[str, Any] | None = None
54  ) -> ConfigFlowResult:
55  """Handle the user step to pick discovered device."""
56  errors: dict[str, str] = {}
57 
58  if user_input is not None:
59  address = user_input[CONF_ADDRESS]
60  discovery_info = self._discovered_devices[address]
61  local_name = discovery_info.name
62  await self.async_set_unique_idasync_set_unique_id(
63  discovery_info.address, raise_on_progress=False
64  )
65  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
66  led_ble = LEDBLE(discovery_info.device)
67  try:
68  await led_ble.update()
69  except BLEAK_EXCEPTIONS:
70  errors["base"] = "cannot_connect"
71  except Exception:
72  _LOGGER.exception("Unexpected error")
73  errors["base"] = "unknown"
74  else:
75  await led_ble.stop()
76  return self.async_create_entryasync_create_entryasync_create_entry(
77  title=local_name,
78  data={
79  CONF_ADDRESS: discovery_info.address,
80  },
81  )
82 
83  if discovery := self._discovery_info_discovery_info:
84  self._discovered_devices[discovery.address] = discovery
85  else:
86  current_addresses = self._async_current_ids_async_current_ids()
87  for discovery in async_discovered_service_info(self.hass):
88  if (
89  discovery.address in current_addresses
90  or discovery.address in self._discovered_devices
91  or not any(
92  discovery.name.startswith(local_name)
93  and not discovery.name.startswith(UNSUPPORTED_SUB_MODEL)
94  for local_name in LOCAL_NAMES
95  )
96  ):
97  continue
98  self._discovered_devices[discovery.address] = discovery
99 
100  if not self._discovered_devices:
101  return self.async_abortasync_abortasync_abort(reason="no_devices_found")
102 
103  data_schema = vol.Schema(
104  {
105  vol.Required(CONF_ADDRESS): vol.In(
106  {
107  service_info.address: (
108  f"{service_info.name} ({service_info.address})"
109  )
110  for service_info in self._discovered_devices.values()
111  }
112  ),
113  }
114  )
115  return self.async_show_formasync_show_formasync_show_form(
116  step_id="user",
117  data_schema=data_schema,
118  errors=errors,
119  )
ConfigFlowResult async_step_bluetooth(self, BluetoothServiceInfoBleak discovery_info)
Definition: config_flow.py:36
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:54
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
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)
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)
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)
Iterable[BluetoothServiceInfoBleak] async_discovered_service_info(HomeAssistant hass, bool connectable=True)
Definition: api.py:72
str human_readable_name(str hostname, str vendor, str mac_address)
Definition: __init__.py:50