Switch to persistent BLE connection model

The connect/disconnect-every-cycle approach caused ~50% failure rate
over 48h — each of the ~2880 daily connection attempts per device had
a significant chance of failure through ESPHome proxies.

New model (same as the user's Android app):
- Connect once, keep the connection alive across poll cycles
- _ensure_connected() reconnects automatically if the link drops
- _on_disconnect() callback detects unexpected disconnections
- On timeout, force-disconnect so next cycle gets a clean reconnect
- Polls now only send commands (no connection overhead) — expected
  completion in <1s instead of 10-25s

Connection lifecycle:
  startup → first poll → _ensure_connected() → persistent
  drop detected → next poll → _ensure_connected() → reconnected
  shutdown → async_teardown() → disconnect()

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-13 17:46:20 +02:00
parent dcc528b96a
commit b8bee14839
2 changed files with 133 additions and 108 deletions
+42 -32
View File
@@ -5,6 +5,7 @@ import asyncio
import logging
from datetime import timedelta
from bleak import BleakError
from bleak.backends.device import BLEDevice
from homeassistant.components.bluetooth import async_ble_device_from_address
from homeassistant.core import HomeAssistant
@@ -18,21 +19,19 @@ from .const import CMD_CELL, CMD_GENERAL, CMD_VERSION, DOMAIN
_LOGGER = logging.getLogger(__name__)
# Only mark sensors unavailable after this many *consecutive* failed polls.
# Transient BLE misses (device not in cache, ESPHome proxy busy, etc.) return
# the last known data instead so the UI doesn't oscillate.
_FAILURES_BEFORE_UNAVAILABLE = 5
# Hard ceiling on the BLE poll operation (connect + commands + disconnect).
# With the global lock preventing contention, connections should be fast —
# 15 s is generous for 2 commands over a local proxy.
# Hard ceiling on a single poll (commands only — no connection overhead
# when already connected). Reconnection adds ~5 s on top.
_POLL_TIMEOUT = 15
class BmsCoordinator(DataUpdateCoordinator[dict]):
"""Polls the BMS over BLE and distributes data to all sensor entities.
Uses a connect -> read -> disconnect pattern on every poll so the BMS's
single BLE connection slot is free between updates (mobile app access).
Holds a **persistent** BLE connection per device. The connection is
established on the first poll and kept alive across cycles. If it
drops, the next poll automatically reconnects.
"""
def __init__(
@@ -56,12 +55,12 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
self._consecutive_failures = 0
# Kept fresh by the BLE advertisement callback registered in __init__.py
self._ble_device: BLEDevice | None = None
# Shared across all BMS coordinator instances so only one BMS connects
# at a time — prevents ESPHome proxy connection slot exhaustion.
# Shared across all BMS coordinator instances — serialises BLE
# operations so multiple devices don't fight for proxy slots.
self._ble_lock = ble_lock or asyncio.Lock()
# ------------------------------------------------------------------
# Device info — shared by sensor, binary_sensor, number platforms
# Device info
# ------------------------------------------------------------------
@property
@@ -78,10 +77,11 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
# ------------------------------------------------------------------
async def async_setup(self) -> None:
"""No-op — no persistent connection to establish."""
"""No-op — connection is established lazily on first poll."""
async def async_teardown(self) -> None:
"""No-op — each poll disconnects itself."""
"""Disconnect the persistent BLE connection."""
await self._handler.disconnect()
async def async_write_mos(self, value: int) -> None:
"""Send a MOS control command to the BMS, then refresh sensor state."""
@@ -91,10 +91,13 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
f"BMS ({self.address}) not reachable — cannot send MOS command"
)
async with self._ble_lock:
success = await self._handler.write_mos(
device, value,
ble_device_callback=self._get_ble_device,
)
try:
success = await self._handler.write_mos(
device, value,
ble_device_callback=self._get_ble_device,
)
except (BleakError, asyncio.TimeoutError) as exc:
raise HomeAssistantError(f"MOS command failed: {exc}") from exc
if not success:
raise HomeAssistantError("BMS did not acknowledge the MOS command")
await self.async_request_refresh()
@@ -104,25 +107,22 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
# ------------------------------------------------------------------
def _get_ble_device(self) -> BLEDevice | None:
"""Return the freshest available BLEDevice reference.
Prefers the advertisement-callback reference (_ble_device) because it
tracks proxy transport path changes. Falls back to the scanner cache.
"""
return self._ble_device or async_ble_device_from_address(
"""Return the freshest available BLEDevice reference."""
if self._ble_device is not None:
return self._ble_device
device = async_ble_device_from_address(
self.hass, self.address, connectable=True
)
if device is not None:
_LOGGER.debug("BMS %s found via scanner cache", self.address)
return device
# ------------------------------------------------------------------
# Poll
# ------------------------------------------------------------------
def _handle_failure(self, reason: str) -> dict:
"""On a transient failure, return cached data up to the threshold.
Only raises UpdateFailed (-> sensors go unavailable) after
_FAILURES_BEFORE_UNAVAILABLE consecutive misses.
"""
"""Return cached data up to the threshold, then go unavailable."""
self._consecutive_failures += 1
if self._consecutive_failures <= _FAILURES_BEFORE_UNAVAILABLE and self.data:
_LOGGER.debug(
@@ -135,9 +135,17 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
raise UpdateFailed(reason)
async def _async_update_data(self) -> dict:
"""Connect to the BMS, fetch all data, disconnect."""
"""Poll the BMS over the persistent connection."""
device = self._get_ble_device()
if device is None:
# Wait up to 5 s for an advertisement (after HA restart / proxy reconnect)
_LOGGER.debug("BMS %s not discovered yet, waiting…", self.address)
for _ in range(5):
await asyncio.sleep(1.0)
device = self._get_ble_device()
if device is not None:
break
if device is None:
return self._handle_failure(
f"BMS ({self.address}) not reachable — check Bluetooth adapter / proxy"
@@ -147,8 +155,7 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
if self.hw_version is None:
commands.append(CMD_VERSION)
# Only one BMS polls at a time — prevents proxy connection slot contention.
# The timeout wraps only the actual BLE operation, not the lock wait.
# Serialise BLE operations across all BMS instances.
async with self._ble_lock:
try:
responses = await asyncio.wait_for(
@@ -160,10 +167,12 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
timeout=_POLL_TIMEOUT,
)
except asyncio.TimeoutError:
# Connection might be dead — force reconnect next cycle
await self._handler.disconnect()
return self._handle_failure(
f"BMS poll timed out after {_POLL_TIMEOUT}s"
)
except Exception as exc:
except (BleakError, Exception) as exc:
return self._handle_failure(f"BMS poll failed: {exc}")
general_frame, cell_frame = responses[0], responses[1]
@@ -194,9 +203,10 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
data["cell_delta"] = None
_LOGGER.debug(
"BMS data: %.2fV %.2fA %d%% %.2fAh %.3fkWh %d cells",
"BMS data: %.2fV %.2fA %d%% %.2fAh %.3fkWh %d cells (connected: %s)",
data["voltage"], data["current"], data["state_of_charge"],
data["residual_capacity"], data["energy_stored"],
len(data["cell_voltages"]),
self._handler.is_connected,
)
return data