|
| 1 | +"""Module to support ECO-WORTHY BMS.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections.abc import Callable |
| 5 | +from typing import Final |
| 6 | + |
| 7 | +from bleak.backends.characteristic import BleakGATTCharacteristic |
| 8 | +from bleak.backends.device import BLEDevice |
| 9 | +from bleak.uuids import normalize_uuid_str |
| 10 | + |
| 11 | +from custom_components.bms_ble.const import ( |
| 12 | + ATTR_BATTERY_CHARGING, |
| 13 | + ATTR_BATTERY_LEVEL, |
| 14 | + ATTR_CURRENT, |
| 15 | + ATTR_CYCLE_CAP, |
| 16 | + ATTR_CYCLE_CHRG, |
| 17 | + # ATTR_CYCLES, |
| 18 | + ATTR_DELTA_VOLTAGE, |
| 19 | + ATTR_POWER, |
| 20 | + ATTR_RUNTIME, |
| 21 | + ATTR_TEMPERATURE, |
| 22 | + ATTR_VOLTAGE, |
| 23 | + KEY_CELL_COUNT, |
| 24 | + KEY_CELL_VOLTAGE, |
| 25 | + KEY_DESIGN_CAP, |
| 26 | + KEY_PROBLEM, |
| 27 | + KEY_TEMP_SENS, |
| 28 | + KEY_TEMP_VALUE, |
| 29 | +) |
| 30 | + |
| 31 | +from .basebms import BaseBMS, BMSsample, crc_modbus |
| 32 | + |
| 33 | + |
| 34 | +class BMS(BaseBMS): |
| 35 | + """ECO-WORTHY battery class implementation.""" |
| 36 | + |
| 37 | + _HEAD: Final[list[int]] = [0xA1, 0xA2] |
| 38 | + _CELL_POS: Final[int] = 14 |
| 39 | + _TEMP_POS: Final[int] = 80 |
| 40 | + _FIELDS: Final[ |
| 41 | + list[tuple[str, int, int, int, bool, Callable[[int], int | float]]] |
| 42 | + ] = [ |
| 43 | + (ATTR_BATTERY_LEVEL, 0xA1, 16, 2, False, lambda x: x), |
| 44 | + (ATTR_VOLTAGE, 0xA1, 20, 2, False, lambda x: float(x / 100)), |
| 45 | + (ATTR_CURRENT, 0xA1, 22, 2, True, lambda x: float(x / 100)), |
| 46 | + (KEY_PROBLEM, 0xA1, 51, 2, False, lambda x: x), |
| 47 | + (KEY_DESIGN_CAP, 0xA1, 26, 2, False, lambda x: float(x / 100)), |
| 48 | + (KEY_CELL_COUNT, 0xA2, _CELL_POS, 2, False, lambda x: x), |
| 49 | + (KEY_TEMP_SENS, 0xA2, _TEMP_POS, 2, False, lambda x: x), |
| 50 | + # (ATTR_CYCLES, 0xA1, 8, 2, False, lambda x: x), |
| 51 | + ] |
| 52 | + _CMDS: Final[set[int]] = set({field[1] for field in _FIELDS}) |
| 53 | + |
| 54 | + def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None: |
| 55 | + """Initialize BMS.""" |
| 56 | + super().__init__(__name__, ble_device, reconnect) |
| 57 | + self._data_final: dict[int, bytearray] = {} |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def matcher_dict_list() -> list[dict]: |
| 61 | + """Provide BluetoothMatcher definition.""" |
| 62 | + return [ |
| 63 | + { |
| 64 | + "local_name": "ECO-WORTHY*", |
| 65 | + "manufacturer_id": 0xC2B4, |
| 66 | + "connectable": True, |
| 67 | + } |
| 68 | + ] |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def device_info() -> dict[str, str]: |
| 72 | + """Return device information for the battery management system.""" |
| 73 | + return {"manufacturer": "ECO-WORTHY", "model": "BW02"} |
| 74 | + |
| 75 | + @staticmethod |
| 76 | + def uuid_services() -> list[str]: |
| 77 | + """Return list of 128-bit UUIDs of services required by BMS.""" |
| 78 | + return [normalize_uuid_str("fff0")] |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def uuid_rx() -> str: |
| 82 | + """Return 16-bit UUID of characteristic that provides notification/read property.""" |
| 83 | + return "fff1" |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def uuid_tx() -> str: |
| 87 | + """Return 16-bit UUID of characteristic that provides write property.""" |
| 88 | + raise NotImplementedError |
| 89 | + |
| 90 | + @staticmethod |
| 91 | + def _calc_values() -> set[str]: |
| 92 | + return { |
| 93 | + ATTR_BATTERY_CHARGING, |
| 94 | + ATTR_CYCLE_CHRG, |
| 95 | + ATTR_CYCLE_CAP, |
| 96 | + ATTR_DELTA_VOLTAGE, |
| 97 | + ATTR_POWER, |
| 98 | + ATTR_RUNTIME, |
| 99 | + ATTR_TEMPERATURE, |
| 100 | + } # calculate further values from BMS provided set ones |
| 101 | + |
| 102 | + def _notification_handler( |
| 103 | + self, _sender: BleakGATTCharacteristic, data: bytearray |
| 104 | + ) -> None: |
| 105 | + """Handle the RX characteristics notify event (new data arrives).""" |
| 106 | + self._log.debug("RX BLE data: %s", data) |
| 107 | + |
| 108 | + if data[0] not in BMS._HEAD: |
| 109 | + self._log.debug("Invalid frame type: 0x%X", data[0]) |
| 110 | + return |
| 111 | + |
| 112 | + crc: Final[int] = crc_modbus(data[:-2]) |
| 113 | + if int.from_bytes(data[-2:], "little") != crc: |
| 114 | + self._log.debug( |
| 115 | + "invalid checksum 0x%X != 0x%X", |
| 116 | + int.from_bytes(data[-2:], "little"), |
| 117 | + crc, |
| 118 | + ) |
| 119 | + self._data = bytearray() |
| 120 | + return |
| 121 | + |
| 122 | + self._data_final[data[0]] = data.copy() |
| 123 | + if BMS._CMDS.issubset(self._data_final.keys()): |
| 124 | + self._data_event.set() |
| 125 | + |
| 126 | + @staticmethod |
| 127 | + def _decode_data(data: dict[int, bytearray]) -> dict[str, int | float]: |
| 128 | + return { |
| 129 | + key: func( |
| 130 | + int.from_bytes( |
| 131 | + data[cmd][idx : idx + size], byteorder="big", signed=sign |
| 132 | + ) |
| 133 | + ) |
| 134 | + for key, cmd, idx, size, sign, func in BMS._FIELDS |
| 135 | + } |
| 136 | + |
| 137 | + @staticmethod |
| 138 | + def _cell_voltages(data: bytearray, cells: int, offs: int) -> dict[str, float]: |
| 139 | + return {KEY_CELL_COUNT: cells} | { |
| 140 | + f"{KEY_CELL_VOLTAGE}{idx}": float( |
| 141 | + int.from_bytes( |
| 142 | + data[offs + idx * 2 : offs + idx * 2 + 2], |
| 143 | + byteorder="big", |
| 144 | + signed=False, |
| 145 | + ) |
| 146 | + ) |
| 147 | + / 1000 |
| 148 | + for idx in range(cells) |
| 149 | + } |
| 150 | + |
| 151 | + @staticmethod |
| 152 | + def _temp_sensors(data: bytearray, sensors: int, offs: int) -> dict[str, float]: |
| 153 | + return { |
| 154 | + f"{KEY_TEMP_VALUE}{idx}": ( |
| 155 | + int.from_bytes( |
| 156 | + data[offs + idx * 2 : offs + (idx + 1) * 2], |
| 157 | + byteorder="big", |
| 158 | + signed=True, |
| 159 | + ) |
| 160 | + ) |
| 161 | + / 10 |
| 162 | + for idx in range(sensors) |
| 163 | + } |
| 164 | + |
| 165 | + async def _async_update(self) -> BMSsample: |
| 166 | + """Update battery status information.""" |
| 167 | + |
| 168 | + self._data_final.clear() |
| 169 | + self._data_event.clear() # clear event to ensure new data is acquired |
| 170 | + await asyncio.wait_for(self._wait_event(), timeout=self.BAT_TIMEOUT) |
| 171 | + |
| 172 | + result: BMSsample = BMS._decode_data(self._data_final) |
| 173 | + |
| 174 | + result |= BMS._cell_voltages( |
| 175 | + self._data_final[0xA2], |
| 176 | + int(result.get(KEY_CELL_COUNT, 0)), |
| 177 | + BMS._CELL_POS + 2, |
| 178 | + ) |
| 179 | + result |= BMS._temp_sensors( |
| 180 | + self._data_final[0xA2], int(result.get(KEY_TEMP_SENS, 0)), BMS._TEMP_POS + 2 |
| 181 | + ) |
| 182 | + |
| 183 | + return result |
0 commit comments