蓝牙 API
订阅蓝牙发现
某些集成可能需要立即知道设备何时被发现。蓝牙集成提供了一个注册 API,它可以在发现匹配特定键值的新设备时接收回调。用于匹配的格式与 manifest.json
中的 bluetooth
相同。除了在 manifest.json
中使用的匹配器外,address
也可以作为匹配器使用。
提供了 bluetooth.async_register_callback
函数来实现此功能。该函数返回一个回调,用于在调用时取消注册。
以下示例演示了如何注册以获取 Switchbot 设备附近时的回调。
from homeassistant.components import bluetooth
...
@callback
def _async_discovered_device(service_info: bluetooth.BluetoothServiceInfoBleak, change: bluetooth.BluetoothChange) -> None:
"""订阅蓝牙变化。"""
_LOGGER.warning("新 service_info: %s", service_info)
entry.async_on_unload(
bluetooth.async_register_callback(
hass, _async_discovered_device, {"service_uuid": "cba20d00-224d-11e6-9fb8-0002a5d5c51b", "connectable": False}, bluetooth.BluetoothScanningMode.ACTIVE
)
)
以下示例演示了如何注册以获取 HomeKit 设备的回调。
from homeassistant.components import bluetooth
...
entry.async_on_unload(
bluetooth.async_register_callback(
hass, _async_discovered_homekit_device, {"manufacturer_id": 76, "manufacturer_data_first_byte": 6}, bluetooth.BluetoothScanningMode.ACTIVE
)
)
以下示例演示了如何注册以获取 Nespresso Prodigio 的回调。
from homeassistant.components import bluetooth
...
entry.async_on_unload(
bluetooth.async_register_callback(
hass, _async_nespresso_found, {"local_name": "Prodigio_*")}, bluetooth.BluetoothScanningMode.ACTIVE
)
)
以下示例演示了如何注册以获取地址为 44:33:11:22:33:22
的设备的回调。
from homeassistant.components import bluetooth
...
entry.async_on_unload(
bluetooth.async_register_callback(
hass, _async_specific_device_found, {"address": "44:33:11:22:33:22")}, bluetooth.BluetoothScanningMode.ACTIVE
)
)
获取共享的 BleakScanner 实例
需要 BleakScanner
实例的集成应调用 bluetooth.async_get_scanner
API。该 API 返回一个围绕单个 BleakScanner
的包装器,使集成能够共享而不造成系统过负荷。
from homeassistant.components import bluetooth
scanner = bluetooth.async_get_scanner(hass)
确定扫描器是否在运行
蓝牙集成可能已经设置,但没有可连接的适配器或遥控器。可以使用 bluetooth.async_scanner_count
API 来确定是否有正在运行的扫描器,该扫描器能够接收广告或生成可用于连接设备的 BLEDevice
。如果没有能够生成可连接 BLEDevice
对象的扫描器,集成可能希望在设置期间引发更加有用的错误。
from homeassistant.components import bluetooth
count = bluetooth.async_scanner_count(hass, connectable=True)
订阅不可用的回调
要在蓝牙堆栈无法再看到设备时获取回调,请调用 bluetooth.async_track_unavailable
API。出于性能原因,一旦设备不再被看到,获取回调可能需要长达五分钟的时间。
如果将 connectable
参数设置为 True
,则如果任何可连接的控制器可以达到设备,则设备将被视为可用。如果只有不可连接的控制器可以达到设备,则设备将被视为不可用。如果参数设置为 False
,则如果任何控制器可以看到设备,则设备将被视为可用。
from homeassistant.components import bluetooth
def _unavailable_callback(info: bluetooth.BluetoothServiceInfoBleak) -> None:
_LOGGER.debug("%s 不再被看到", info.address)
cancel = bluetooth.async_track_unavailable(hass, _unavailable_callback, "44:44:33:11:23:42", connectable=True)