Refactor BLE layer for 24/7 reliability
- Replace raw BleakClient with establish_connection from bleak-retry-connector (retries, GATT service cache, proxy-aware) - Replace fragile asyncio.Event with asyncio.Queue for response frames, drain stale data on each connection to prevent cross-cycle leakage - Register BLE advertisement callback to keep BLEDevice reference fresh across ESPHome proxy path changes - Remove asyncio.sleep(2) device lookup hack - Increase poll timeout floor from 10s to 20s - Increase failure tolerance from 3 to 5 consecutive misses - Bump default poll interval to 30s, min to 15s (halves connection churn) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,15 @@
|
||||
"""Xiaoxiang Smart BMS — Home Assistant integration."""
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.components.bluetooth import (
|
||||
BluetoothChange,
|
||||
BluetoothScanningMode,
|
||||
BluetoothServiceInfoBleak,
|
||||
async_register_callback,
|
||||
)
|
||||
from homeassistant.components.bluetooth.match import ADDRESS, BluetoothCallbackMatcher
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
|
||||
from .const import CONF_ADDRESS, CONF_POLL_INTERVAL, DEFAULT_POLL_INTERVAL, DOMAIN
|
||||
from .coordinator import BmsCoordinator
|
||||
@@ -16,13 +23,31 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
poll_interval = entry.options.get(CONF_POLL_INTERVAL, DEFAULT_POLL_INTERVAL)
|
||||
|
||||
coordinator = BmsCoordinator(hass, address, poll_interval, name=entry.title)
|
||||
|
||||
# Keep the coordinator's BLE device reference fresh via advertisement callback.
|
||||
# This avoids stale transport paths when ESPHome proxies cycle.
|
||||
@callback
|
||||
def _async_update_ble(
|
||||
service_info: BluetoothServiceInfoBleak,
|
||||
change: BluetoothChange,
|
||||
) -> None:
|
||||
coordinator._ble_device = service_info.device
|
||||
|
||||
entry.async_on_unload(
|
||||
async_register_callback(
|
||||
hass,
|
||||
_async_update_ble,
|
||||
BluetoothCallbackMatcher({ADDRESS: address}),
|
||||
BluetoothScanningMode.PASSIVE,
|
||||
)
|
||||
)
|
||||
|
||||
await coordinator.async_setup()
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
# Reload the entry when options (e.g. poll interval) change
|
||||
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
|
||||
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user