From a22a591cacef43075a7c6139ff2f1924367f4b98 Mon Sep 17 00:00:00 2001 From: Jc2k Date: Sun, 24 Sep 2023 09:45:41 +0100 Subject: [PATCH] Add new bluetooth APIs for working with unavailability timeout (#1935) Co-authored-by: J. Nick Koston --- docs/core/bluetooth/api.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/core/bluetooth/api.md b/docs/core/bluetooth/api.md index 22d2811f..ba6281be 100644 --- a/docs/core/bluetooth/api.md +++ b/docs/core/bluetooth/api.md @@ -105,6 +105,35 @@ def _unavailable_callback(info: bluetooth.BluetoothServiceInfoBleak) -> None: cancel = bluetooth.async_track_unavailable(hass, _unavailable_callback, "44:44:33:11:23:42", connectable=True) ``` +### Finding out the availability timeout + +Availability is based on the time since the device's last known broadcast. This timeout is learned automatically based on the device's regular broadcasting pattern. You can find out this with the `bluetooth.async_get_learned_advertising_interval` API. + +```python +from homeassistant.components import bluetooth + +learned_interval = bluetooth.async_get_learned_advertising_interval(hass, "44:44:33:11:23:42") +``` + +If the advertising interval is not yet known, this will return `None`. In that case, unavailability tracking will try the fallback interval for that address. The below example returns the interval that has been set manually by an integration: + +```python +from homeassistant.components import bluetooth + +bluetooth.async_set_fallback_availability_interval(hass, "44:44:33:11:23:42", 64.0) + +fallback_interval = bluetooth.async_get_fallback_availability_interval(hass, "44:44:33:11:23:42") +``` + +If there is no learned interval or fallback interval for the device, a hardcoded safe default interval is used: + +```python +from homeassistant.components import bluetooth + +default_fallback_interval = bluetooth.FALLBACK_MAXIMUM_STALE_ADVERTISEMENT_SECONDS +``` + + ### Fetching the bleak `BLEDevice` from the `address` Integrations should avoid the overhead of starting an additional scanner to resolve the address by calling the `bluetooth.async_ble_device_from_address` API, which returns a `BLEDevice` for the nearest configured `bluetooth` adapter that can reach the device. If no adapters can reach the device, the `bluetooth.async_ble_device_from_address` API, will return `None`.