Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helper functions for the Broadlink integration."""
2 
3 from base64 import b64decode
4 
5 from homeassistant import config_entries
6 from homeassistant.const import CONF_HOST
7 from homeassistant.helpers import config_validation as cv
8 
9 from .const import DOMAIN
10 
11 
12 def data_packet(value):
13  """Decode a data packet given for a Broadlink remote."""
14  value = cv.string(value)
15  extra = len(value) % 4
16  if extra > 0:
17  value = value + ("=" * (4 - extra))
18  return b64decode(value)
19 
20 
21 def mac_address(mac):
22  """Validate and convert a MAC address to bytes."""
23  mac = cv.string(mac)
24  if len(mac) == 17:
25  mac = "".join(mac[i : i + 2] for i in range(0, 17, 3))
26  elif len(mac) == 14:
27  mac = "".join(mac[i : i + 4] for i in range(0, 14, 5))
28  elif len(mac) != 12:
29  raise ValueError("Invalid MAC address")
30  return bytes.fromhex(mac)
31 
32 
33 def format_mac(mac):
34  """Format a MAC address."""
35  return ":".join([format(octet, "02x") for octet in mac])
36 
37 
38 def import_device(hass, host):
39  """Create a config flow for a device."""
40  configured_hosts = {
41  entry.data.get(CONF_HOST) for entry in hass.config_entries.async_entries(DOMAIN)
42  }
43 
44  if host not in configured_hosts:
45  task = hass.config_entries.flow.async_init(
46  DOMAIN,
47  context={"source": config_entries.SOURCE_IMPORT},
48  data={CONF_HOST: host},
49  )
50  hass.async_create_task(task)