Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """The yalexs_ble integration models."""
2 
3 from __future__ import annotations
4 
5 import platform
6 
7 from yalexs_ble import local_name_is_unique
8 
10  BluetoothServiceInfoBleak,
11  async_discovered_service_info,
12 )
14  ADDRESS,
15  LOCAL_NAME,
16  BluetoothCallbackMatcher,
17 )
18 from homeassistant.core import HomeAssistant, callback
19 
20 
22  local_name: str, address: str
23 ) -> BluetoothCallbackMatcher:
24  """Return a BluetoothCallbackMatcher for the given local_name and address."""
25  # On MacOS, coreblueooth uses UUIDs for addresses so we must
26  # have a unique local_name to match since the system
27  # hides the address from us.
28  if local_name_is_unique(local_name) and platform.system() == "Darwin":
29  return BluetoothCallbackMatcher({LOCAL_NAME: local_name})
30  # On every other platform we actually get the mac address
31  # which is needed for the older August locks that use the
32  # older version of the underlying protocol.
33  return BluetoothCallbackMatcher({ADDRESS: address})
34 
35 
36 @callback
38  hass: HomeAssistant, local_name: str, address: str
39 ) -> BluetoothServiceInfoBleak | None:
40  """Return the service info for the given local_name and address."""
41  has_unique_local_name = local_name_is_unique(local_name)
42  for service_info in async_discovered_service_info(hass):
43  device = service_info.device
44  if (
45  has_unique_local_name and device.name == local_name
46  ) or device.address == address:
47  return service_info
48  return None
49 
50 
51 def short_address(address: str) -> str:
52  """Convert a Bluetooth address to a short address."""
53  split_address = address.replace("-", ":").split(":")
54  return f"{split_address[-2].upper()}{split_address[-1].upper()}"[-4:]
55 
56 
57 def human_readable_name(name: str | None, local_name: str, address: str) -> str:
58  """Return a human readable name for the given name, local_name, and address."""
59  return f"{name or local_name} ({short_address(address)})"
Iterable[BluetoothServiceInfoBleak] async_discovered_service_info(HomeAssistant hass, bool connectable=True)
Definition: api.py:72
BluetoothServiceInfoBleak|None async_find_existing_service_info(HomeAssistant hass, str local_name, str address)
Definition: util.py:39
str human_readable_name(str|None name, str local_name, str address)
Definition: util.py:57
BluetoothCallbackMatcher bluetooth_callback_matcher(str local_name, str address)
Definition: util.py:23