Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Airthings BlE integration."""
2 
3 from __future__ import annotations
4 
5 import dataclasses
6 import logging
7 from typing import Any
8 
9 from airthings_ble import AirthingsBluetoothDeviceData, AirthingsDevice
10 from bleak import BleakError
11 import voluptuous as vol
12 
13 from homeassistant.components import bluetooth
15  BluetoothServiceInfo,
16  async_discovered_service_info,
17 )
18 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
19 from homeassistant.const import CONF_ADDRESS
20 
21 from .const import DOMAIN, MFCT_ID
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 SERVICE_UUIDS = [
26  "b42e1f6e-ade7-11e4-89d3-123b93f75cba",
27  "b42e4a8e-ade7-11e4-89d3-123b93f75cba",
28  "b42e1c08-ade7-11e4-89d3-123b93f75cba",
29  "b42e3882-ade7-11e4-89d3-123b93f75cba",
30 ]
31 
32 
33 @dataclasses.dataclass
34 class Discovery:
35  """A discovered bluetooth device."""
36 
37  name: str
38  discovery_info: BluetoothServiceInfo
39  device: AirthingsDevice
40 
41 
42 def get_name(device: AirthingsDevice) -> str:
43  """Generate name with model and identifier for device."""
44 
45  name = device.friendly_name()
46  if identifier := device.identifier:
47  name += f" ({identifier})"
48  return name
49 
50 
51 class AirthingsDeviceUpdateError(Exception):
52  """Custom error class for device updates."""
53 
54 
55 class AirthingsConfigFlow(ConfigFlow, domain=DOMAIN):
56  """Handle a config flow for Airthings BLE."""
57 
58  VERSION = 1
59 
60  def __init__(self) -> None:
61  """Initialize the config flow."""
62  self._discovered_device_discovered_device: Discovery | None = None
63  self._discovered_devices: dict[str, Discovery] = {}
64 
65  async def _get_device_data(
66  self, discovery_info: BluetoothServiceInfo
67  ) -> AirthingsDevice:
68  ble_device = bluetooth.async_ble_device_from_address(
69  self.hass, discovery_info.address
70  )
71  if ble_device is None:
72  _LOGGER.debug("no ble_device in _get_device_data")
73  raise AirthingsDeviceUpdateError("No ble_device")
74 
75  airthings = AirthingsBluetoothDeviceData(_LOGGER)
76 
77  try:
78  data = await airthings.update_device(ble_device)
79  except BleakError as err:
80  _LOGGER.error(
81  "Error connecting to and getting data from %s: %s",
82  discovery_info.address,
83  err,
84  )
85  raise AirthingsDeviceUpdateError("Failed getting device data") from err
86  except Exception as err:
87  _LOGGER.error(
88  "Unknown error occurred from %s: %s", discovery_info.address, err
89  )
90  raise
91  return data
92 
94  self, discovery_info: BluetoothServiceInfo
95  ) -> ConfigFlowResult:
96  """Handle the bluetooth discovery step."""
97  _LOGGER.debug("Discovered BT device: %s", discovery_info)
98  await self.async_set_unique_idasync_set_unique_id(discovery_info.address)
99  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
100 
101  try:
102  device = await self._get_device_data_get_device_data(discovery_info)
103  except AirthingsDeviceUpdateError:
104  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
105  except Exception: # noqa: BLE001
106  return self.async_abortasync_abortasync_abort(reason="unknown")
107 
108  name = get_name(device)
109  self.context["title_placeholders"] = {"name": name}
110  self._discovered_device_discovered_device = Discovery(name, discovery_info, device)
111 
112  return await self.async_step_bluetooth_confirmasync_step_bluetooth_confirm()
113 
115  self, user_input: dict[str, Any] | None = None
116  ) -> ConfigFlowResult:
117  """Confirm discovery."""
118  if user_input is not None:
119  return self.async_create_entryasync_create_entryasync_create_entry(
120  title=self.context["title_placeholders"]["name"], data={}
121  )
122 
123  self._set_confirm_only_set_confirm_only()
124  return self.async_show_formasync_show_formasync_show_form(
125  step_id="bluetooth_confirm",
126  description_placeholders=self.context["title_placeholders"],
127  )
128 
129  async def async_step_user(
130  self, user_input: dict[str, Any] | None = None
131  ) -> ConfigFlowResult:
132  """Handle the user step to pick discovered device."""
133  if user_input is not None:
134  address = user_input[CONF_ADDRESS]
135  await self.async_set_unique_idasync_set_unique_id(address, raise_on_progress=False)
136  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
137  discovery = self._discovered_devices[address]
138 
139  self.context["title_placeholders"] = {
140  "name": discovery.name,
141  }
142 
143  self._discovered_device_discovered_device = discovery
144 
145  return self.async_create_entryasync_create_entryasync_create_entry(title=discovery.name, data={})
146 
147  current_addresses = self._async_current_ids_async_current_ids()
148  for discovery_info in async_discovered_service_info(self.hass):
149  address = discovery_info.address
150  if address in current_addresses or address in self._discovered_devices:
151  continue
152 
153  if MFCT_ID not in discovery_info.manufacturer_data:
154  continue
155 
156  if not any(uuid in SERVICE_UUIDS for uuid in discovery_info.service_uuids):
157  continue
158 
159  try:
160  device = await self._get_device_data_get_device_data(discovery_info)
161  except AirthingsDeviceUpdateError:
162  return self.async_abortasync_abortasync_abort(reason="cannot_connect")
163  except Exception: # noqa: BLE001
164  return self.async_abortasync_abortasync_abort(reason="unknown")
165  name = get_name(device)
166  self._discovered_devices[address] = Discovery(name, discovery_info, device)
167 
168  if not self._discovered_devices:
169  return self.async_abortasync_abortasync_abort(reason="no_devices_found")
170 
171  titles = {
172  address: discovery.device.name
173  for (address, discovery) in self._discovered_devices.items()
174  }
175  return self.async_show_formasync_show_formasync_show_form(
176  step_id="user",
177  data_schema=vol.Schema(
178  {
179  vol.Required(CONF_ADDRESS): vol.In(titles),
180  },
181  ),
182  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:131
ConfigFlowResult async_step_bluetooth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:116
AirthingsDevice _get_device_data(self, BluetoothServiceInfo discovery_info)
Definition: config_flow.py:67
ConfigFlowResult async_step_bluetooth(self, BluetoothServiceInfo discovery_info)
Definition: config_flow.py:95
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_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