diff --git a/custom_components/xiaoxiang_bms/bluetooth_handler.py b/custom_components/xiaoxiang_bms/bluetooth_handler.py index a148e4f..daf00a9 100644 --- a/custom_components/xiaoxiang_bms/bluetooth_handler.py +++ b/custom_components/xiaoxiang_bms/bluetooth_handler.py @@ -52,14 +52,25 @@ class BmsBluetoothHandler: if self.is_connected: return _LOGGER.debug("Connecting to BMS at %s (via %s)", self._address, ble_device.name) - self._client = BleakClient( + client = BleakClient( ble_device, disconnected_callback=self._on_disconnect, ) - await self._client.connect() - await self._client.start_notify(RX_CHAR_UUID, self._on_notify) + 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 + 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)