|
| 1 | +"""Module to support Dummy BMS.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import logging |
| 5 | +from typing import Any, Callable, Final |
| 6 | + |
| 7 | +from bleak.backends.device import BLEDevice |
| 8 | +from bleak.uuids import normalize_uuid_str |
| 9 | + |
| 10 | +from custom_components.bms_ble.const import ( |
| 11 | + ATTR_BATTERY_CHARGING, |
| 12 | + ATTR_BATTERY_LEVEL, |
| 13 | + ATTR_CURRENT, |
| 14 | + ATTR_CYCLE_CAP, |
| 15 | + ATTR_CYCLE_CHRG, |
| 16 | + ATTR_CYCLES, |
| 17 | + ATTR_DELTA_VOLTAGE, |
| 18 | + ATTR_POWER, |
| 19 | + ATTR_RUNTIME, |
| 20 | + ATTR_TEMPERATURE, |
| 21 | + ATTR_VOLTAGE, |
| 22 | + KEY_CELL_VOLTAGE, |
| 23 | +) |
| 24 | + |
| 25 | +from .basebms import BaseBMS, BMSsample |
| 26 | + |
| 27 | +LOGGER = logging.getLogger(__name__) |
| 28 | +BAT_TIMEOUT = 10 |
| 29 | + |
| 30 | + |
| 31 | +class BMS(BaseBMS): |
| 32 | + """Dummy battery class implementation.""" |
| 33 | + |
| 34 | + CRC_POS: Final = -1 # last byte |
| 35 | + HEAD_LEN: Final = 3 |
| 36 | + MAX_CELLS: Final = 16 |
| 37 | + |
| 38 | + def __init__(self, ble_device: BLEDevice, reconnect: bool = False) -> None: |
| 39 | + """Initialize BMS.""" |
| 40 | + LOGGER.debug("%s init(), BT address: %s", self.device_id(), ble_device.address) |
| 41 | + super().__init__(LOGGER, self._notification_handler, ble_device, reconnect) |
| 42 | + |
| 43 | + self._data: bytearray = bytearray() |
| 44 | + self._FIELDS: Final[ |
| 45 | + list[tuple[str, int, int, bool, Callable[[int], int | float]]] |
| 46 | + ] = [ |
| 47 | + (ATTR_VOLTAGE, 12, 2, False, lambda x: float(x / 1000)), |
| 48 | + (ATTR_CURRENT, 48, 4, True, lambda x: float(x / 1000)), |
| 49 | + (ATTR_TEMPERATURE, 56, 2, False, lambda x: x), |
| 50 | + (ATTR_BATTERY_LEVEL, 90, 2, False, lambda x: x), |
| 51 | + (ATTR_CYCLE_CHRG, 62, 2, False, lambda x: float(x / 100)), |
| 52 | + (ATTR_CYCLES, 96, 4, False, lambda x: x), |
| 53 | + ] |
| 54 | + |
| 55 | + @staticmethod |
| 56 | + def matcher_dict_list() -> list[dict[str, Any]]: |
| 57 | + """Provide BluetoothMatcher definition.""" |
| 58 | + return [ |
| 59 | + { |
| 60 | + "service_uuid": BMS.uuid_services()[0], |
| 61 | + "manufacturer_id": 0x585A, |
| 62 | + "connectable": True, |
| 63 | + } |
| 64 | + ] |
| 65 | + |
| 66 | + @staticmethod |
| 67 | + def device_info() -> dict[str, str]: |
| 68 | + """Return device information for the battery management system.""" |
| 69 | + return {"manufacturer": "Redodo", "model": "Bluetooth battery"} |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def uuid_services() -> list[str]: |
| 73 | + """Return list of 128-bit UUIDs of services required by BMS.""" |
| 74 | + return [normalize_uuid_str("ffe0")] # change service UUID here! |
| 75 | + |
| 76 | + @staticmethod |
| 77 | + def uuid_rx() -> str: |
| 78 | + """Return 16-bit UUID of characteristic that provides notification/read property.""" |
| 79 | + return "ffe1" |
| 80 | + |
| 81 | + @staticmethod |
| 82 | + def uuid_tx() -> str: |
| 83 | + """Return 16-bit UUID of characteristic that provides write property.""" |
| 84 | + return "ffe2" |
| 85 | + |
| 86 | + @staticmethod |
| 87 | + def _calc_values() -> set[str]: |
| 88 | + return { |
| 89 | + ATTR_BATTERY_CHARGING, |
| 90 | + ATTR_DELTA_VOLTAGE, |
| 91 | + ATTR_CYCLE_CAP, |
| 92 | + ATTR_POWER, |
| 93 | + ATTR_RUNTIME, |
| 94 | + } # calculate further values from BMS provided set ones |
| 95 | + |
| 96 | + def _notification_handler(self, _sender, data: bytearray) -> None: |
| 97 | + """Handle the RX characteristics notify event (new data arrives).""" |
| 98 | + LOGGER.debug("%s: Received BLE data: %s", self.name, data.hex(" ")) |
| 99 | + |
| 100 | + if len(data) < 3 or not data.startswith(b"\x00\x00"): |
| 101 | + LOGGER.debug("%s: incorrect SOF.") |
| 102 | + return |
| 103 | + |
| 104 | + if len(data) != data[2] + self.HEAD_LEN + 1: # add header length and CRC |
| 105 | + LOGGER.debug("(%s) incorrect frame length (%i)", self.name, len(data)) |
| 106 | + return |
| 107 | + |
| 108 | + crc = self._crc(data[: self.CRC_POS]) |
| 109 | + if crc != data[self.CRC_POS]: |
| 110 | + LOGGER.debug( |
| 111 | + "(%s) Rx data CRC is invalid: 0x%x != 0x%x", |
| 112 | + self.name, |
| 113 | + data[len(data) + self.CRC_POS], |
| 114 | + crc, |
| 115 | + ) |
| 116 | + return |
| 117 | + |
| 118 | + self._data = data |
| 119 | + self._data_event.set() |
| 120 | + |
| 121 | + def _crc(self, frame: bytes) -> int: |
| 122 | + """Calculate frame CRC.""" |
| 123 | + return sum(frame) & 0xFF |
| 124 | + |
| 125 | + def _cell_voltages(self, data: bytearray, cells: int) -> dict[str, float]: |
| 126 | + """Return cell voltages from status message.""" |
| 127 | + return { |
| 128 | + f"{KEY_CELL_VOLTAGE}{idx}": int.from_bytes( |
| 129 | + data[16 + 2 * idx : 16 + 2 * idx + 2], |
| 130 | + byteorder="little", |
| 131 | + signed=False, |
| 132 | + ) |
| 133 | + / 1000 |
| 134 | + for idx in range(cells) |
| 135 | + if int.from_bytes(data[16 + 2 * idx : 16 + 2 * idx + 2], byteorder="little") |
| 136 | + } |
| 137 | + |
| 138 | + async def _async_update(self) -> BMSsample: |
| 139 | + """Update battery status information.""" |
| 140 | + await self._client.write_gatt_char( |
| 141 | + BMS.uuid_tx(), data=b"\x00\x00\x04\x01\x13\x55\xaa\x17" |
| 142 | + ) |
| 143 | + await asyncio.wait_for(self._wait_event(), timeout=BAT_TIMEOUT) |
| 144 | + |
| 145 | + return { |
| 146 | + key: func( |
| 147 | + int.from_bytes( |
| 148 | + self._data[idx : idx + size], byteorder="little", signed=sign |
| 149 | + ) |
| 150 | + ) |
| 151 | + for key, idx, size, sign, func in self._FIELDS |
| 152 | + } | self._cell_voltages(self._data, self.MAX_CELLS) |
0 commit comments