Skip to content

Commit

Permalink
fixed exception handling of BMS/coordinator
Browse files Browse the repository at this point in the history
  • Loading branch information
patman15 committed Apr 3, 2024
1 parent 2076481 commit d945314
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 24 deletions.
9 changes: 1 addition & 8 deletions custom_components/bms_ble/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""The BLE Battery Management System integration."""

from asyncio import CancelledError

from homeassistant.components.bluetooth import async_ble_device_from_address
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
Expand Down Expand Up @@ -34,17 +32,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

# Query the device the first time, initialise coordinator.data
try:
entry.async_create_background_task(
hass=hass,
target=coordinator.async_config_entry_first_refresh(),
name="initialize",
)
# Insert the coordinator in the global registry
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
except CancelledError:
except:
del coordinator
return False

Expand Down
21 changes: 13 additions & 8 deletions custom_components/bms_ble/coordinator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Home Assistant coordinator for BLE Battery Management System integration."""

from asyncio import CancelledError
from datetime import timedelta

from bleak import BleakError
from bleak.backends.device import BLEDevice
from homeassistant.components import bluetooth
from homeassistant.components.bluetooth import DOMAIN as BLUETOOTH_DOMAIN
Expand Down Expand Up @@ -31,6 +31,7 @@ def __init__(
logger=LOGGER,
name=ble_device.name,
update_interval=timedelta(seconds=UPDATE_INTERVAL),
update_method=self.async_update_data,
# always_update=False, # only update when sensor value has changed
)
self._mac = ble_device.address
Expand Down Expand Up @@ -64,16 +65,20 @@ async def async_update_data(self) -> dict[str, float]:
"""Return the latest data from the device."""
LOGGER.debug(f"BMS {self.device_info.get(ATTR_NAME)} data update")

service_info = bluetooth.async_last_service_info(
self.hass, address=self._mac, connectable=True
)
battery_info: dict[str, float] = {}
try:
battery_info = await self._device.async_update()
except CancelledError:
return {}
except:
raise UpdateFailed("Device communicating error.")
except TimeoutError:
LOGGER.debug("Device communication timeout.")
raise
except BleakError as err:
raise UpdateFailed(
f"device communicating failed: {str(err)} ({type(err).__name__})"
) from err

service_info = bluetooth.async_last_service_info(
self.hass, address=self._mac, connectable=True
)
if service_info is not None:
battery_info.update({"rssi": service_info.rssi})

Expand Down
11 changes: 3 additions & 8 deletions custom_components/bms_ble/plugins/ogt_bms.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,21 +113,16 @@ def _sensor_conv(
async def async_update(self) -> dict[str, float]:
"""Update battery status information"""

try:
await self._connect()
except Exception as e:
LOGGER.debug(f"Failed to connect: {str(e)} ({type(e).__name__}).")
raise IOError
except asyncio.CancelledError:
return {}
await self._connect()

self._values.clear()
for key in list(self._OGT_REGISTERS):
await self._read(key)
try:
await asyncio.wait_for(self._wait_event(), timeout=BAT_TIMEOUT)
except TimeoutError:
LOGGER.debug(f"Reading {self._OGT_REGISTERS[key].name} timed out.")
LOGGER.debug(f"Reading {self._OGT_REGISTERS[key]['name']} timed out.")

# multiply with voltage with capacity to get Wh instead of Ah
self._values = self._sensor_conv(
self._values,
Expand Down

0 comments on commit d945314

Please sign in to comment.