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:
@@ -16,7 +16,11 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BmsCoordinator(DataUpdateCoordinator[dict]):
|
||||
"""Polls the BMS over BLE and distributes data to all sensor entities."""
|
||||
"""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).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -32,10 +36,10 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
|
||||
)
|
||||
self.address = address
|
||||
self._handler = BmsBluetoothHandler(address)
|
||||
self.hw_version: str | None = None # populated on first successful poll
|
||||
self.hw_version: str | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Device info — centralised so sensor + binary_sensor share it
|
||||
# Device info — shared by sensor, binary_sensor, number platforms
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@property
|
||||
@@ -51,60 +55,44 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
|
||||
# Lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _get_ble_device(self):
|
||||
"""Resolve the best available BLE device via HA's Bluetooth subsystem.
|
||||
|
||||
Automatically uses ESPHome BLE proxies if they can reach the BMS.
|
||||
"""
|
||||
device = async_ble_device_from_address(self.hass, self.address, connectable=True)
|
||||
if device is None:
|
||||
raise UpdateFailed(
|
||||
f"BMS ({self.address}) not reachable by any Bluetooth adapter or proxy"
|
||||
)
|
||||
return device
|
||||
|
||||
async def async_setup(self) -> None:
|
||||
"""No-op — connection is established lazily on the first poll."""
|
||||
"""No-op — no persistent connection to establish."""
|
||||
|
||||
async def async_teardown(self) -> None:
|
||||
"""Disconnect cleanly. Called on entry unload."""
|
||||
await self._handler.disconnect()
|
||||
"""No-op — each poll disconnects itself."""
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Poll
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
async def _async_update_data(self) -> dict:
|
||||
"""Fetch data from the BMS. Reconnects automatically if disconnected."""
|
||||
if not self._handler.is_connected:
|
||||
_LOGGER.debug("BMS not connected, attempting reconnect…")
|
||||
try:
|
||||
await self._handler.connect(self._get_ble_device())
|
||||
except UpdateFailed:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise UpdateFailed(f"BMS reconnect failed: {exc}") from exc
|
||||
"""Connect to the BMS, fetch all data, disconnect."""
|
||||
device = async_ble_device_from_address(self.hass, self.address, connectable=True)
|
||||
if device is None:
|
||||
raise UpdateFailed(
|
||||
f"BMS ({self.address}) not reachable — check Bluetooth adapter / proxy"
|
||||
)
|
||||
|
||||
# Fetch hardware version once; skip on subsequent polls
|
||||
commands = [CMD_GENERAL, CMD_CELL]
|
||||
if self.hw_version is None:
|
||||
commands.append(CMD_VERSION)
|
||||
|
||||
try:
|
||||
general_frame = await self._handler.request(CMD_GENERAL)
|
||||
if general_frame is None:
|
||||
raise UpdateFailed("No response to general info request (0x03)")
|
||||
|
||||
cell_frame = await self._handler.request(CMD_CELL)
|
||||
if cell_frame is None:
|
||||
raise UpdateFailed("No response to cell info request (0x04)")
|
||||
|
||||
# Fetch hardware version string once — used in DeviceInfo model field
|
||||
if self.hw_version is None:
|
||||
version_frame = await self._handler.request(CMD_VERSION)
|
||||
if version_frame:
|
||||
self.hw_version = BmsBluetoothHandler.parse_version(version_frame)
|
||||
_LOGGER.debug("BMS hardware version: %s", self.hw_version)
|
||||
|
||||
except UpdateFailed:
|
||||
raise
|
||||
responses = await self._handler.poll(device, commands)
|
||||
except Exception as exc:
|
||||
raise UpdateFailed(f"BLE communication error: {exc}") from exc
|
||||
raise UpdateFailed(f"BMS poll failed: {exc}") from exc
|
||||
|
||||
general_frame, cell_frame = responses[0], responses[1]
|
||||
|
||||
if general_frame is None:
|
||||
raise UpdateFailed("No response to general info request (0x03)")
|
||||
if cell_frame is None:
|
||||
raise UpdateFailed("No response to cell info request (0x04)")
|
||||
|
||||
if self.hw_version is None and len(responses) > 2 and responses[2]:
|
||||
self.hw_version = BmsBluetoothHandler.parse_version(responses[2])
|
||||
_LOGGER.debug("BMS hardware version: %s", self.hw_version)
|
||||
|
||||
data = BmsBluetoothHandler.parse_general_info(general_frame)
|
||||
data.update(BmsBluetoothHandler.parse_cell_info(cell_frame))
|
||||
@@ -122,11 +110,8 @@ class BmsCoordinator(DataUpdateCoordinator[dict]):
|
||||
|
||||
_LOGGER.debug(
|
||||
"BMS data: %.2fV %.2fA %d%% %.2fAh %.3fkWh %d cells",
|
||||
data["voltage"],
|
||||
data["current"],
|
||||
data["state_of_charge"],
|
||||
data["residual_capacity"],
|
||||
data["energy_stored"],
|
||||
data["voltage"], data["current"], data["state_of_charge"],
|
||||
data["residual_capacity"], data["energy_stored"],
|
||||
len(data["cell_voltages"]),
|
||||
)
|
||||
return data
|
||||
|
||||
Reference in New Issue
Block a user