Add global BLE lock + faster timeouts for multi-device reliability

Root cause: 3 BMS devices fighting for 3 ESPHome proxy connection slots
simultaneously, causing 80% timeout failures and 22s+ poll times.

Fixes:
- Add shared asyncio.Lock so only one BMS polls at a time — eliminates
  proxy slot contention entirely
- Pass ble_device_callback to establish_connection so retry attempts
  get a fresh BLEDevice (handles proxy path changes)
- Reduce command timeout 5s -> 3s, retries 3 -> 2 (BMS responds in
  <200ms when connection is clean)
- Reduce establish_connection max_attempts 3 -> 2 (fail fast, retry
  next cycle instead of blocking 25s)
- Fixed poll timeout to 15s (was poll_interval-5=25s)

Expected: polls complete in 2-5s instead of 22s, ~95%+ success rate.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-12 10:05:54 +02:00
parent 1520ed3c0f
commit dcc528b96a
3 changed files with 65 additions and 23 deletions
+16 -2
View File
@@ -1,6 +1,8 @@
"""Xiaoxiang Smart BMS — Home Assistant integration."""
from __future__ import annotations
import asyncio
from homeassistant.components.bluetooth import (
BluetoothChange,
BluetoothScanningMode,
@@ -22,7 +24,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
address = entry.data[CONF_ADDRESS]
poll_interval = entry.options.get(CONF_POLL_INTERVAL, DEFAULT_POLL_INTERVAL)
coordinator = BmsCoordinator(hass, address, poll_interval, name=entry.title)
hass.data.setdefault(DOMAIN, {})
# Shared BLE lock — only one BMS connects at a time to avoid
# ESPHome proxy connection slot exhaustion with multiple devices.
if "_ble_lock" not in hass.data[DOMAIN]:
hass.data[DOMAIN]["_ble_lock"] = asyncio.Lock()
ble_lock = hass.data[DOMAIN]["_ble_lock"]
coordinator = BmsCoordinator(
hass, address, poll_interval,
name=entry.title,
ble_lock=ble_lock,
)
# Keep the coordinator's BLE device reference fresh via advertisement callback.
# This avoids stale transport paths when ESPHome proxies cycle.
@@ -45,7 +59,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
await coordinator.async_setup()
await coordinator.async_config_entry_first_refresh()
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
hass.data[DOMAIN][entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(_async_update_listener))