Switch to connect→poll→disconnect per cycle (single-connection BMS fix)

The BMS only allows one simultaneous BLE connection. Keeping a persistent
connection blocked the mobile app from connecting at all.

Changes:
- BmsBluetoothHandler: replace connect()/disconnect()/request() public API
  with a single poll() method that owns the full connect→read→disconnect
  lifecycle. Connection is held only for the duration of one data fetch.
- Coordinator: gutted connection-state management — _async_update_data now
  just calls handler.poll() and processes results. No reconnect loop needed.
- Poll interval defaults: 15s default, 10s min, 300s max. The BLE connect
  overhead (~2s) makes sub-10s intervals impractical.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-04-11 20:09:43 +02:00
parent af608792da
commit 3fc25c083b
3 changed files with 79 additions and 114 deletions
@@ -25,67 +25,55 @@ _TRAILER_LEN = 3
class BmsBluetoothHandler:
"""Manages BLE connection and protocol framing for a Xiaoxiang BMS device."""
"""Protocol framing and parsing for a Xiaoxiang BMS device.
Designed for a connect → poll → disconnect pattern: the BMS only allows
one simultaneous BLE connection, so we hold it only for the duration of
a single data fetch and release it immediately after.
"""
def __init__(self, address: str) -> None:
self._address = address
self._client: BleakClient | None = None
self._buffer = bytearray()
self._response_event = asyncio.Event()
self._response_data: bytes | None = None
self._lock = asyncio.Lock()
# ------------------------------------------------------------------
# Connection management
# High-level poll — the only entry point the coordinator needs
# ------------------------------------------------------------------
@property
def is_connected(self) -> bool:
return self._client is not None and self._client.is_connected
async def poll(
self,
ble_device: BLEDevice,
commands: list[bytes],
timeout: float = 5.0,
retries: int = 3,
) -> list[bytes | None]:
"""Connect, send each command in sequence, disconnect.
async def connect(self, ble_device: BLEDevice) -> None:
"""Open BLE connection and start notifications.
Accepts a BLEDevice resolved by HA's Bluetooth subsystem so that
ESPHome BLE proxies are used transparently alongside local adapters.
The BMS only supports a single BLE connection at a time. By connecting
only during the active read window and disconnecting immediately after,
the mobile app (or any other client) can connect freely between polls.
"""
if self.is_connected:
return
_LOGGER.debug("Connecting to BMS at %s (via %s)", self._address, ble_device.name)
client = BleakClient(
ble_device,
disconnected_callback=self._on_disconnect,
)
_LOGGER.debug("Polling BMS at %s", self._address)
client = BleakClient(ble_device)
try:
await client.connect()
await client.start_notify(RX_CHAR_UUID, self._on_notify)
except Exception:
# Ensure a failed connect never leaves a broken client behind —
# next poll will start fresh
# Give the BMS a moment to register the subscription before
# we start sending commands
await asyncio.sleep(0.5)
return [
await self._request(client, cmd, timeout, retries)
for cmd in commands
]
finally:
try:
await client.disconnect()
except Exception:
pass
self._client = None
raise
# Give the BMS a moment to register the notification subscription
# before we start sending commands — avoids dropped first response
self._client = client
await asyncio.sleep(0.5)
_LOGGER.debug("Connected to BMS at %s", self._address)
async def disconnect(self) -> None:
"""Close the BLE connection cleanly."""
if self._client:
try:
await self._client.disconnect()
except Exception:
pass
self._client = None
def _on_disconnect(self, _client: BleakClient) -> None:
_LOGGER.debug("BMS at %s disconnected", self._address)
self._client = None
self._buffer.clear()
# ------------------------------------------------------------------
# Frame reception
@@ -131,36 +119,30 @@ class BmsBluetoothHandler:
self._response_event.set()
# ------------------------------------------------------------------
# Request / response
# Request / response (private — used inside poll())
# ------------------------------------------------------------------
async def request(
async def _request(
self,
client: BleakClient,
command: bytes,
timeout: float = 5.0,
retries: int = 3,
timeout: float,
retries: int,
) -> bytes | None:
"""Send a command frame and wait for the corresponding response frame.
"""Send one command and wait for the response frame, with retries.
Retries up to `retries` times with a short pause between attempts to
handle occasional BLE packet loss or a slow BMS response.
Tries Write With Response first; if that raises a GATT error the BMS
likely only supports Write Without Response, so we fall back silently.
Tries Write With Response first; falls back to Write Without Response
if the characteristic rejects it — covers both BMS firmware variants.
"""
async with self._lock:
for attempt in range(1, retries + 1):
self._response_event.clear()
self._response_data = None
try:
await self._client.write_gatt_char(
TX_CHAR_UUID, command, response=True
)
await client.write_gatt_char(TX_CHAR_UUID, command, response=True)
except BleakError:
# Characteristic may not support Write With Response — try without
try:
await self._client.write_gatt_char(
TX_CHAR_UUID, command, response=False
)
await client.write_gatt_char(TX_CHAR_UUID, command, response=False)
except BleakError as exc:
_LOGGER.error("BLE write failed (attempt %d/%d): %s",
attempt, retries, exc)
@@ -172,10 +154,8 @@ class BmsBluetoothHandler:
await asyncio.wait_for(self._response_event.wait(), timeout)
return self._response_data
except asyncio.TimeoutError:
_LOGGER.warning(
"BMS response timeout (cmd=0x%s, attempt %d/%d)",
command.hex(), attempt, retries,
)
_LOGGER.warning("BMS timeout (cmd=0x%s, attempt %d/%d)",
command.hex(), attempt, retries)
if attempt < retries:
await asyncio.sleep(0.5)