Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the BLE Tracker."""
2 
3 from __future__ import annotations
4 
5 import base64
6 import binascii
7 import logging
8 
9 import voluptuous as vol
10 
11 from homeassistant.components import bluetooth
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 
14 from .const import DOMAIN
15 from .coordinator import async_last_service_info
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 CONF_IRK = "irk"
20 
21 
22 def _parse_irk(irk: str) -> bytes | None:
23  if irk.startswith("irk:"):
24  irk = irk[4:]
25 
26  if irk.endswith("="):
27  try:
28  irk_bytes = bytes(reversed(base64.b64decode(irk)))
29  except binascii.Error:
30  # IRK is not valid base64
31  return None
32  else:
33  try:
34  irk_bytes = binascii.unhexlify(irk)
35  except binascii.Error:
36  # IRK is not correctly hex encoded
37  return None
38 
39  if len(irk_bytes) != 16:
40  # IRK must be 16 bytes when decoded
41  return None
42 
43  return irk_bytes
44 
45 
46 class BLEDeviceTrackerConfigFlow(ConfigFlow, domain=DOMAIN):
47  """Handle a config flow for BLE Device Tracker."""
48 
49  VERSION = 1
50 
51  async def async_step_user(
52  self, user_input: dict[str, str] | None = None
53  ) -> ConfigFlowResult:
54  """Set up by user."""
55  errors: dict[str, str] = {}
56 
57  if not bluetooth.async_scanner_count(self.hass, connectable=False):
58  return self.async_abortasync_abortasync_abort(reason="bluetooth_not_available")
59 
60  if user_input is not None:
61  irk = user_input[CONF_IRK]
62 
63  if not (irk_bytes := _parse_irk(irk)):
64  errors[CONF_IRK] = "irk_not_valid"
65  elif not (service_info := async_last_service_info(self.hass, irk_bytes)):
66  errors[CONF_IRK] = "irk_not_found"
67  else:
68  await self.async_set_unique_idasync_set_unique_id(irk_bytes.hex())
69  return self.async_create_entryasync_create_entryasync_create_entry(
70  title=service_info.name or "BLE Device Tracker",
71  data={CONF_IRK: irk_bytes.hex()},
72  )
73 
74  data_schema = vol.Schema({CONF_IRK: str})
75  return self.async_show_formasync_show_formasync_show_form(
76  step_id="user", data_schema=data_schema, errors=errors
77  )
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:53
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)
BluetoothServiceInfoBleak|None async_last_service_info(HomeAssistant hass, str address, bool connectable=True)
Definition: api.py:80