aiobmsble
Asynchronous library to query battery management systems (BMS) via Bluetooth LE.
This library is intended to query data from battery management systems that use Bluetooth LE. Stand-alone usage is possible in any Python environment (with necessary dependencies installed).
Warning: BMS readings are telemetry only. Do not use them to control actions that are safety relevant, e.g. prevent battery damage, overheating, or fire.
Quick start
import asyncio
from bleak import BleakScanner
from aiobmsble import BMSError, BMSSample
from aiobmsble.utils import identify
async def main() -> None:
for device, adv in (await BleakScanner.discover(return_adv=True)).values():
if not (bms_classes := await identify(adv, device.address)):
continue
try:
async with bms_classes[0](ble_device=device) as bms:
print(await bms.device_info())
data: BMSSample = await bms.update()
print(data)
except BMSError as exc:
print(f"{device.address}: query failed: {exc}")
asyncio.run(main())
If the BMS type is known, import its class directly, e.g.
from aiobmsble.bms.dummy_bms import BMS.
Continuous polling
Create one BMS instance and call aiobmsble.basebms.BaseBMS.update() periodically.
With the default BMSConfig(keep_alive=True) the connection stays open between calls
and is re-established automatically after it was lost.
import asyncio
from bleak import BleakScanner
from aiobmsble import BMSError, BMSSample
from aiobmsble.bms.dummy_bms import BMS # use the class for your device
ADDRESS = "00:11:22:33:44:55" # Bluetooth address of your BMS
INTERVAL = 30 # [s] between queries
async def poll() -> None:
if (device := await BleakScanner.find_device_by_address(ADDRESS)) is None:
raise SystemExit(f"{ADDRESS} not found")
bms = BMS(ble_device=device)
try:
while True:
try:
data: BMSSample = await bms.update()
print(data.get("voltage"), data.get("current"), data.get("battery_level"))
except BMSError as exc:
if not exc.retryable: # e.g. wrong secret or unsupported device
print(f"stop polling: {exc}")
break
print(f"query failed, retrying at next interval: {exc}")
await asyncio.sleep(INTERVAL)
finally:
await bms.disconnect()
asyncio.run(poll())
Retries are already done inside update(), so do not retry immediately after an error.
The quick start uses async with, which connects when the block is entered and raises
if the device is not reachable at that moment. That suits a one-off query. The polling
example deliberately uses try/finally instead: the first connection is only made by
update(), so a device that is unreachable at startup is just a failed poll that is
retried at the next interval. Once connected, both variants behave the same.
Modules
aiobmsble: data types returned by a BMS (BMSSample,BMSInfo,BMSLimits, ...) and the connection configurationBMSConfig.aiobmsble.basebms:aiobmsble.basebms.BaseBMS, the interface all BMS classes implement.aiobmsble.exceptions: errors raised by BMS operations, also exported here.aiobmsble.utils: helpers to find the BMS class for a device (identify(),get_bms(),available_bms(),load_bms_plugins()), convert advertisement dictionaries (adv_dict_to_advdata()), and summarize problems (problem_levels()).aiobmsble.bms: the BMS plugin modules, one per supported protocol.aiobmsble.test_data: recorded advertisements for integration tests.aiobmsble.plugin: types for plugin authors.
Project: aiobmsble, https://pypi.org/p/aiobmsble/ License: Apache-2.0, http://www.apache.org/licenses/
1"""Asynchronous library to query battery management systems (BMS) via Bluetooth LE. 2 3This library is intended to query data from battery management systems 4that use Bluetooth LE. Stand-alone usage is possible in any Python environment 5(with necessary dependencies installed). 6 7**Warning:** BMS readings are telemetry only. Do not use them to control actions that 8are safety relevant, e.g. prevent battery damage, overheating, or fire. 9 10.. include:: ../docs/quickstart.md 11 12## Modules 13 14- `aiobmsble`: data types returned by a BMS (`BMSSample`, `BMSInfo`, `BMSLimits`, ...) 15 and the connection configuration `BMSConfig`. 16- `aiobmsble.basebms`: `aiobmsble.basebms.BaseBMS`, the interface all BMS classes implement. 17- `aiobmsble.exceptions`: errors raised by BMS operations, also exported here. 18- `aiobmsble.utils`: helpers to find the BMS class for a device (`identify()`, 19 `get_bms()`, `available_bms()`, `load_bms_plugins()`), convert advertisement 20 dictionaries (`adv_dict_to_advdata()`), and summarize problems (`problem_levels()`). 21- `aiobmsble.bms`: the BMS plugin modules, one per supported protocol. 22- `aiobmsble.test_data`: recorded advertisements for integration tests. 23- `aiobmsble.plugin`: types for plugin authors. 24 25Project: aiobmsble, https://pypi.org/p/aiobmsble/ 26License: Apache-2.0, http://www.apache.org/licenses/ 27""" 28 29from collections.abc import Mapping 30from contextlib import suppress 31from dataclasses import dataclass 32from enum import IntEnum, StrEnum, auto, unique 33from importlib.metadata import PackageNotFoundError, version 34from types import MappingProxyType 35from typing import Final, NamedTuple, Self, TypedDict 36 37from aiobmsble.exceptions import ( 38 BMSAuthError, 39 BMSCommandRejectedError, 40 BMSConfigError, 41 BMSConnectionError, 42 BMSDataError, 43 BMSError, 44 BMSTimeoutError, 45 BMSUnsupportedError, 46) 47 48__all__: list[str] = [ 49 "PROBLEM_DEFAULTS", 50 "BMSAuthError", 51 "BMSCommandRejectedError", 52 "BMSConfig", 53 "BMSConfigError", 54 "BMSConnectionError", 55 "BMSDataError", 56 "BMSError", 57 "BMSInfo", 58 "BMSLimits", 59 "BMSMode", 60 "BMSProblem", 61 "BMSSample", 62 "BMSTimeoutError", 63 "BMSUnsupportedError", 64 "BatterySample", 65 "Limit", 66 "PackSample", 67 "PrbDefault", 68 "PrbType", 69 "Severity", 70 "TSKind", 71 "TempSensor", 72 "Threshold", 73 "__version__", 74] 75 76__version__: str = "0.0.0.dev0" 77with suppress(PackageNotFoundError): 78 __version__ = version("aiobmsble") 79 80 81@unique 82class BMSMode(IntEnum): 83 """Enumeration of BMS modes.""" 84 85 UNKNOWN = -1 86 BULK = 0x00 87 ABSORPTION = 0x01 88 FLOAT = 0x02 89 90 91@unique 92class TSKind(IntEnum): 93 """Enumeration of temperature sensor source types.""" 94 95 GENERIC = 0x0 96 CELL = auto() 97 CELL_MAX = auto() 98 CELL_MIN = auto() 99 MOSFET = auto() 100 PCB = auto() 101 HEATER = auto() 102 BALANCER = auto() 103 AMBIENT = auto() 104 105 106@dataclass(frozen=True, slots=True) 107class TempSensor: 108 """Represents a temperature sensor reading from the BMS. 109 110 Instances compare equal to plain numbers by value, but to other `TempSensor` 111 instances by value and type. Ordering (`<`, `max()`, ...) uses the value only. 112 Conversion (`float()`, `int()`, `round()`) operates on the value and returns 113 plain numbers 114 115 Note: equality is not transitive. For example, `TempSensor(1, CELL) == 1` and 116 `1 == TempSensor(1, GENERIC)` are both `True`, yet 117 `TempSensor(1, CELL) != TempSensor(1, GENERIC)`. Do not rely on transitivity 118 when comparing mixed sensor types and plain numbers. Hashing uses the value only, 119 so sensors of different types with equal values may share a hash bucket. 120 """ 121 122 value: float 123 kind: TSKind = TSKind.GENERIC 124 125 def __eq__(self: Self, other: object) -> bool: 126 """Compare against other TempSensor including type or int, float.""" 127 128 if isinstance(other, TempSensor): 129 return (self.kind, self.value) == (other.kind, other.value) 130 if isinstance(other, (int, float)) and not isinstance(other, bool): 131 return self.value == other 132 return NotImplemented 133 134 def __float__(self) -> float: 135 """Return the temperature value as a float.""" 136 return float(self.value) 137 138 def __int__(self) -> int: 139 """Return the temperature value truncated to an int.""" 140 return int(self.value) 141 142 def __round__(self, ndigits: int | None = None) -> int | float: 143 """Round the temperature value, as `round()` does for numbers.""" 144 if ndigits is None: 145 return round(self.value) 146 return round(self.value, ndigits) 147 148 def __format__(self, format_spec: str) -> str: 149 """Format the temperature value, delegating to the underlying number.""" 150 return format(self.value, format_spec) 151 152 @staticmethod 153 def _cmp_value(other: object) -> float | None: 154 if isinstance(other, TempSensor): 155 return other.value 156 if isinstance(other, (int, float)) and not isinstance(other, bool): 157 return other 158 return None 159 160 def __lt__(self, other: object) -> bool: 161 """Compare temperature value.""" 162 if (val := self._cmp_value(other)) is None: 163 return NotImplemented 164 return self.value < val 165 166 def __le__(self, other: object) -> bool: 167 """Compare temperature value.""" 168 if (val := self._cmp_value(other)) is None: 169 return NotImplemented 170 return self.value <= val 171 172 def __gt__(self, other: object) -> bool: 173 """Compare temperature value.""" 174 if (val := self._cmp_value(other)) is None: 175 return NotImplemented 176 return self.value > val 177 178 def __ge__(self, other: object) -> bool: 179 """Compare temperature value.""" 180 if (val := self._cmp_value(other)) is None: 181 return NotImplemented 182 return self.value >= val 183 184 def __hash__(self) -> int: 185 """Hash the TempSensor based on its value (consistent with equality to numbers).""" 186 return hash(self.value) 187 188 def __repr__(self) -> str: 189 """Return the string representation of the sensor value/type.""" 190 return f"{self.__class__.__name__}({self.value!r}, {self.kind!r})" 191 192 193@unique 194class Severity(IntEnum): 195 """Problem severity, ordered so that max() yields the worst level.""" 196 197 OK = 0 198 INFO = 1 # operating state notice, no limit violated 199 WARN = 2 # limit approached, BMS still operational 200 PROTECT = 3 # protection tripped, charging and/or discharging inhibited 201 FAULT = 4 # hardware/internal failure 202 203 204@unique 205class PrbType(StrEnum): 206 """Generic problem categories (value = stable key).""" 207 208 CELL_OV = auto() 209 CELL_UV = auto() 210 PACK_OV = auto() 211 PACK_UV = auto() 212 CELL_IMBALANCE = auto() 213 CHARGE_OC = auto() 214 DISCHARGE_OC = auto() 215 SHORT_CIRCUIT = auto() 216 CHARGE_OT = auto() 217 CHARGE_UT = auto() 218 DISCHARGE_OT = auto() 219 DISCHARGE_UT = auto() 220 FET_OT = auto() 221 FET_UT = auto() 222 SYSTEM_OT = auto() 223 SYSTEM_UT = auto() 224 LOW_SOC = auto() 225 FET_LOCKED = auto() 226 FET_FAILURE = auto() 227 AFE_FAILURE = auto() 228 CELL_FAILURE = auto() 229 SENSOR_FAILURE = auto() 230 COMM_FAILURE = auto() 231 FUSE_BLOWN = auto() 232 OTHER = auto() # vendor specific, requires BMSPrbDef.text 233 UNKNOWN = auto() # bit set but not described by the plugin 234 235 236class PrbDefault(NamedTuple): 237 """Default severity and human readable description of a problem type.""" 238 239 level: Severity 240 text: str 241 242 243PROBLEM_DEFAULTS: Final[Mapping[PrbType, PrbDefault]] = MappingProxyType( 244 { 245 PrbType.CELL_OV: PrbDefault(Severity.PROTECT, "Cell overvoltage"), 246 PrbType.CELL_UV: PrbDefault(Severity.PROTECT, "Cell undervoltage"), 247 PrbType.PACK_OV: PrbDefault(Severity.PROTECT, "Pack overvoltage"), 248 PrbType.PACK_UV: PrbDefault(Severity.PROTECT, "Pack undervoltage"), 249 PrbType.CELL_IMBALANCE: PrbDefault(Severity.WARN, "Cell voltage imbalance"), 250 PrbType.CHARGE_OC: PrbDefault(Severity.PROTECT, "Charge overcurrent"), 251 PrbType.DISCHARGE_OC: PrbDefault(Severity.PROTECT, "Discharge overcurrent"), 252 PrbType.SHORT_CIRCUIT: PrbDefault(Severity.PROTECT, "Short circuit"), 253 PrbType.CHARGE_OT: PrbDefault(Severity.PROTECT, "Charge overtemperature"), 254 PrbType.CHARGE_UT: PrbDefault(Severity.PROTECT, "Charge undertemperature"), 255 PrbType.DISCHARGE_OT: PrbDefault(Severity.PROTECT, "Discharge overtemperature"), 256 PrbType.DISCHARGE_UT: PrbDefault(Severity.PROTECT, "Discharge undertemperature"), 257 PrbType.FET_OT: PrbDefault(Severity.PROTECT, "MOSFET overtemperature"), 258 PrbType.FET_UT: PrbDefault(Severity.PROTECT, "MOSFET undertemperature"), 259 # examples for SYSTEM_*: ambient, PCB, board, battery temperature. NOT: MOSFET temperature 260 PrbType.SYSTEM_OT: PrbDefault(Severity.PROTECT, "System overtemperature"), 261 PrbType.SYSTEM_UT: PrbDefault(Severity.PROTECT, "System undertemperature"), 262 PrbType.LOW_SOC: PrbDefault(Severity.WARN, "Low state of charge"), 263 PrbType.FET_LOCKED: PrbDefault(Severity.INFO, "MOSFET locked"), 264 PrbType.FET_FAILURE: PrbDefault(Severity.FAULT, "MOSFET"), 265 PrbType.AFE_FAILURE: PrbDefault(Severity.FAULT, "Analog front-end"), 266 PrbType.CELL_FAILURE: PrbDefault(Severity.FAULT, "Cell"), 267 PrbType.SENSOR_FAILURE: PrbDefault(Severity.FAULT, "Sensor"), 268 PrbType.COMM_FAILURE: PrbDefault(Severity.FAULT, "Internal communication"), 269 PrbType.FUSE_BLOWN: PrbDefault(Severity.FAULT, "Fuse blown"), 270 PrbType.OTHER: PrbDefault(Severity.WARN, "Other problem"), 271 PrbType.UNKNOWN: PrbDefault(Severity.WARN, "Unknown problem"), 272 } 273) 274"""Default severity and description per problem type (read-only).""" 275 276 277@dataclass(frozen=True, slots=True, init=False) 278class BMSProblem: 279 """Decoded problem reported by the BMS.""" 280 281 kind: PrbType 282 """Generic problem category.""" 283 level: Severity 284 """Severity of the problem.""" 285 text: str 286 """Human readable (vendor specific) description.""" 287 288 def __init__(self, kind: PrbType, level: Severity | None = None, text: str = "") -> None: 289 """Create a problem, omitted level and text default to those of the problem kind.""" 290 default: Final[PrbDefault] = PROBLEM_DEFAULTS[kind] 291 object.__setattr__(self, "kind", kind) 292 object.__setattr__(self, "level", default.level if level is None else level) 293 object.__setattr__(self, "text", text or default.text) 294 295 def __str__(self) -> str: 296 """Return human readable representation.""" 297 return f"{self.text} ({self.level.name.lower()})" 298 299 def __repr__(self) -> str: 300 """Return compact representation for logging.""" 301 return f"{self.__class__.__name__}({self.kind.name}, {self.level.name}, {self.text!r})" 302 303 304class BatterySample(TypedDict, total=False): 305 """Common fields for battery samples. 306 307 Units: voltage [V], current [A], charge [Ah], energy [Wh], power [W], temperature [°C], 308 level/health [%]. Current and power are positive while charging. 309 Only fields that the BMS provides (or that can be derived) are present. 310 """ 311 312 battery_level: float | int # [%] 313 battery_health: float | int # [%] 314 cell_count: int # [#] 315 cell_voltages: list[float] # [V] 316 current: float # [A] (positive: charging) 317 cycles: int # [#] 318 cycle_charge: float | int # [Ah] 319 cycle_energy: float | int # [Wh] 320 delta_cell_voltage: float # [V] 321 design_capacity: int # [Ah] 322 power: float # [W] (positive: charging) 323 temp_count: int # [#] 324 temperature: list[TempSensor] # [°C] 325 voltage: float # [V] 326 327 328class PackSample(BatterySample, total=False): 329 """Dictionary representing a sample of a battery sub-system.""" 330 331 # check pace_bms.py before adding items 332 333 334class BMSSample(BatterySample, total=False): 335 """Dictionary representing a sample of battery management system (BMS) data.""" 336 337 # BMS-specific fields 338 battery_charging: bool # True: battery charging 339 battery_mode: BMSMode # BMS charging mode 340 problem: bool # True: problem detected 341 runtime: int # [s] 342 343 # detailed information 344 balancer: bool | int # False: off, True: active or bit mask, 1: enabled/active 345 balance_current: float # [A] 346 heater_current: float # [A] 347 total_charge: int # [Ah], charge discharged over lifetime 348 pack_count: int # [#] 349 problem_code: int # BMS specific code, 0 no problem 350 problems: list[BMSProblem] # decoded problem_code and failed value sanity checks 351 352 # BMS switches 353 chrg_mosfet: bool # True: enabled 354 dischrg_mosfet: bool # True: enabled 355 heater: bool # True: enabled/heating 356 357 # battery pack data 358 packs: list[PackSample] # data from battery sub-systems 359 360 361@dataclass(slots=True, frozen=True) 362class BMSConfig: 363 """Configuration for the BMS (connection).""" 364 365 keep_alive: bool = True 366 """Keep the connection open between calls (faster, more stable).""" 367 secret: str = "" 368 """Application level secret/PIN, only used if the BMS class sets `ACCEPT_SECRET`.""" 369 370 def __repr__(self) -> str: 371 """Represent the config without exposing the secret value.""" 372 return f"BMSConfig(keep_alive={self.keep_alive}, secret_set={self.secret != ''})" 373 374 375class BMSInfo(TypedDict, total=False): 376 """Human readable information about the BMS device.""" 377 378 fw_version: str 379 manufacturer: str 380 model: str 381 model_id: str 382 name: str 383 serial_number: str 384 sw_version: str 385 hw_version: str 386 387 388@unique 389class Limit(StrEnum): 390 """Protection functions a BMS may implement (value = stable key).""" 391 392 # cell voltage 393 CELL_OVP = auto() 394 CELL_UVP = auto() 395 # pack voltage 396 PACK_OVP = auto() 397 PACK_UVP = auto() 398 # current 399 CHARGE_OCP = auto() 400 DISCHARGE_OCP = auto() 401 # temperature 402 CHARGE_OTP = auto() 403 CHARGE_UTP = auto() 404 DISCHARGE_OTP = auto() 405 DISCHARGE_UTP = auto() 406 FET_OTP = auto() 407 FET_UTP = auto() 408 409 410@dataclass(frozen=True, slots=True, kw_only=True) 411class Threshold: 412 """A single protection threshold as configured in the BMS. 413 414 Trip/release points at which the BMS activates/releases a protection. 415 They are not the operating envelope of the battery and must not be used as 416 charger/inverter set points. 417 """ 418 419 trip: float 420 """Trip point [V, A, °C].""" 421 release: float | None = None 422 """Recovery point, if reported.""" 423 delay: float | None = None 424 """Trip delay [s], if reported.""" 425 426 427type BMSLimits = dict[Limit, Threshold] 428"""Thresholds configured in the BMS, returned by `aiobmsble.basebms.BaseBMS.limits()`."""
Default severity and description per problem type (read-only).
114class BMSAuthError(BMSError, PermissionError): 115 """Secret/PIN missing or rejected by the device. 116 117 Provide a valid `aiobmsble.BMSConfig.secret` before trying again. 118 """ 119 120 retryable = False 121 default_msg = "Authentication failed."
Secret/PIN missing or rejected by the device.
Provide a valid aiobmsble.BMSConfig.secret before trying again.
145class BMSCommandRejectedError(BMSError): 146 """Device actively refused a command (error reply).""" 147 148 retryable = False 149 default_msg = "Command rejected by BMS."
Device actively refused a command (error reply).
362@dataclass(slots=True, frozen=True) 363class BMSConfig: 364 """Configuration for the BMS (connection).""" 365 366 keep_alive: bool = True 367 """Keep the connection open between calls (faster, more stable).""" 368 secret: str = "" 369 """Application level secret/PIN, only used if the BMS class sets `ACCEPT_SECRET`.""" 370 371 def __repr__(self) -> str: 372 """Represent the config without exposing the secret value.""" 373 return f"BMSConfig(keep_alive={self.keep_alive}, secret_set={self.secret != ''})"
Configuration for the BMS (connection).
124class BMSConfigError(BMSError, ValueError): 125 """Invalid `aiobmsble.BMSConfig` or API usage. 126 127 Examples: a badly formatted secret, `async with` without `keep_alive=True`, or 128 malformed advertisement data passed to `aiobmsble.utils.adv_dict_to_advdata()`. 129 """ 130 131 retryable = False 132 default_msg = "Invalid configuration."
Invalid aiobmsble.BMSConfig or API usage.
Examples: a badly formatted secret, async with without keep_alive=True, or
malformed advertisement data passed to aiobmsble.utils.adv_dict_to_advdata().
87class BMSConnectionError(BMSError, ConnectionError): 88 """BLE link could not be established or was lost. 89 90 Typical causes: device out of range, switched off, or connected to another client. 91 """ 92 93 default_msg = "BLE connection failed."
BLE link could not be established or was lost.
Typical causes: device out of range, switched off, or connected to another client.
105class BMSDataError(BMSError, ValueError): 106 """Reply received but incomplete or inconsistent. 107 108 With `aiobmsble.BMSConfig.keep_alive` enabled the connection is kept for the next poll. 109 """ 110 111 default_msg = "BMS data incomplete."
Reply received but incomplete or inconsistent.
With aiobmsble.BMSConfig.keep_alive enabled the connection is kept for the next poll.
57class BMSError(Exception): 58 """Base class for all aiobmsble errors. 59 60 Catch this class to handle every error raised by the library. 61 """ 62 63 retryable: bool = True 64 """`True` if the failure is temporary and the call may be repeated at the next poll.""" 65 66 default_msg: str = "BMS operation failed." 67 """Message used if the exception is raised without one.""" 68 69 def __init__( 70 self, msg: str = "", *, bms_type: str | None = None, address: str | None = None 71 ) -> None: 72 """Initialize an aiobmsble error with optional device context. 73 74 Args: 75 msg: error description; `default_msg` is used if empty 76 bms_type: BMS type (plugin module name, e.g. `dummy_bms`), set by the library if omitted 77 address: Bluetooth address of the device, set by the library if omitted 78 79 """ 80 super().__init__(msg or self.default_msg) 81 self.bms_type: str | None = bms_type 82 """BMS type (plugin module name, e.g. `dummy_bms`) that raised the error.""" 83 self.address: str | None = address 84 """Bluetooth address of the device that raised the error."""
Base class for all aiobmsble errors.
Catch this class to handle every error raised by the library.
69 def __init__( 70 self, msg: str = "", *, bms_type: str | None = None, address: str | None = None 71 ) -> None: 72 """Initialize an aiobmsble error with optional device context. 73 74 Args: 75 msg: error description; `default_msg` is used if empty 76 bms_type: BMS type (plugin module name, e.g. `dummy_bms`), set by the library if omitted 77 address: Bluetooth address of the device, set by the library if omitted 78 79 """ 80 super().__init__(msg or self.default_msg) 81 self.bms_type: str | None = bms_type 82 """BMS type (plugin module name, e.g. `dummy_bms`) that raised the error.""" 83 self.address: str | None = address 84 """Bluetooth address of the device that raised the error."""
Initialize an aiobmsble error with optional device context.
Arguments:
- msg: error description;
default_msgis used if empty - bms_type: BMS type (plugin module name, e.g.
dummy_bms), set by the library if omitted - address: Bluetooth address of the device, set by the library if omitted
376class BMSInfo(TypedDict, total=False): 377 """Human readable information about the BMS device.""" 378 379 fw_version: str 380 manufacturer: str 381 model: str 382 model_id: str 383 name: str 384 serial_number: str 385 sw_version: str 386 hw_version: str
Human readable information about the BMS device.
Thresholds configured in the BMS, returned by aiobmsble.basebms.BaseBMS.limits().
82@unique 83class BMSMode(IntEnum): 84 """Enumeration of BMS modes.""" 85 86 UNKNOWN = -1 87 BULK = 0x00 88 ABSORPTION = 0x01 89 FLOAT = 0x02
Enumeration of BMS modes.
278@dataclass(frozen=True, slots=True, init=False) 279class BMSProblem: 280 """Decoded problem reported by the BMS.""" 281 282 kind: PrbType 283 """Generic problem category.""" 284 level: Severity 285 """Severity of the problem.""" 286 text: str 287 """Human readable (vendor specific) description.""" 288 289 def __init__(self, kind: PrbType, level: Severity | None = None, text: str = "") -> None: 290 """Create a problem, omitted level and text default to those of the problem kind.""" 291 default: Final[PrbDefault] = PROBLEM_DEFAULTS[kind] 292 object.__setattr__(self, "kind", kind) 293 object.__setattr__(self, "level", default.level if level is None else level) 294 object.__setattr__(self, "text", text or default.text) 295 296 def __str__(self) -> str: 297 """Return human readable representation.""" 298 return f"{self.text} ({self.level.name.lower()})" 299 300 def __repr__(self) -> str: 301 """Return compact representation for logging.""" 302 return f"{self.__class__.__name__}({self.kind.name}, {self.level.name}, {self.text!r})"
Decoded problem reported by the BMS.
289 def __init__(self, kind: PrbType, level: Severity | None = None, text: str = "") -> None: 290 """Create a problem, omitted level and text default to those of the problem kind.""" 291 default: Final[PrbDefault] = PROBLEM_DEFAULTS[kind] 292 object.__setattr__(self, "kind", kind) 293 object.__setattr__(self, "level", default.level if level is None else level) 294 object.__setattr__(self, "text", text or default.text)
Create a problem, omitted level and text default to those of the problem kind.
335class BMSSample(BatterySample, total=False): 336 """Dictionary representing a sample of battery management system (BMS) data.""" 337 338 # BMS-specific fields 339 battery_charging: bool # True: battery charging 340 battery_mode: BMSMode # BMS charging mode 341 problem: bool # True: problem detected 342 runtime: int # [s] 343 344 # detailed information 345 balancer: bool | int # False: off, True: active or bit mask, 1: enabled/active 346 balance_current: float # [A] 347 heater_current: float # [A] 348 total_charge: int # [Ah], charge discharged over lifetime 349 pack_count: int # [#] 350 problem_code: int # BMS specific code, 0 no problem 351 problems: list[BMSProblem] # decoded problem_code and failed value sanity checks 352 353 # BMS switches 354 chrg_mosfet: bool # True: enabled 355 dischrg_mosfet: bool # True: enabled 356 heater: bool # True: enabled/heating 357 358 # battery pack data 359 packs: list[PackSample] # data from battery sub-systems
Dictionary representing a sample of battery management system (BMS) data.
96class BMSTimeoutError(BMSError, TimeoutError): 97 """Device connected but did not send a valid reply in time. 98 99 Raised after the internal retries are used up. 100 """ 101 102 default_msg = "BMS did not send a valid reply in time."
Device connected but did not send a valid reply in time.
Raised after the internal retries are used up.
135class BMSUnsupportedError(BMSError, ConnectionError): 136 """Device lacks a required GATT service or characteristic. 137 138 Usually the wrong BMS plugin was selected or the firmware is not supported. 139 """ 140 141 retryable = False 142 default_msg = "Required GATT service or characteristic not found."
Device lacks a required GATT service or characteristic.
Usually the wrong BMS plugin was selected or the firmware is not supported.
305class BatterySample(TypedDict, total=False): 306 """Common fields for battery samples. 307 308 Units: voltage [V], current [A], charge [Ah], energy [Wh], power [W], temperature [°C], 309 level/health [%]. Current and power are positive while charging. 310 Only fields that the BMS provides (or that can be derived) are present. 311 """ 312 313 battery_level: float | int # [%] 314 battery_health: float | int # [%] 315 cell_count: int # [#] 316 cell_voltages: list[float] # [V] 317 current: float # [A] (positive: charging) 318 cycles: int # [#] 319 cycle_charge: float | int # [Ah] 320 cycle_energy: float | int # [Wh] 321 delta_cell_voltage: float # [V] 322 design_capacity: int # [Ah] 323 power: float # [W] (positive: charging) 324 temp_count: int # [#] 325 temperature: list[TempSensor] # [°C] 326 voltage: float # [V]
Common fields for battery samples.
Units: voltage [V], current [A], charge [Ah], energy [Wh], power [W], temperature [°C], level/health [%]. Current and power are positive while charging. Only fields that the BMS provides (or that can be derived) are present.
389@unique 390class Limit(StrEnum): 391 """Protection functions a BMS may implement (value = stable key).""" 392 393 # cell voltage 394 CELL_OVP = auto() 395 CELL_UVP = auto() 396 # pack voltage 397 PACK_OVP = auto() 398 PACK_UVP = auto() 399 # current 400 CHARGE_OCP = auto() 401 DISCHARGE_OCP = auto() 402 # temperature 403 CHARGE_OTP = auto() 404 CHARGE_UTP = auto() 405 DISCHARGE_OTP = auto() 406 DISCHARGE_UTP = auto() 407 FET_OTP = auto() 408 FET_UTP = auto()
Protection functions a BMS may implement (value = stable key).
329class PackSample(BatterySample, total=False): 330 """Dictionary representing a sample of a battery sub-system.""" 331 332 # check pace_bms.py before adding items
Dictionary representing a sample of a battery sub-system.
237class PrbDefault(NamedTuple): 238 """Default severity and human readable description of a problem type.""" 239 240 level: Severity 241 text: str
Default severity and human readable description of a problem type.
205@unique 206class PrbType(StrEnum): 207 """Generic problem categories (value = stable key).""" 208 209 CELL_OV = auto() 210 CELL_UV = auto() 211 PACK_OV = auto() 212 PACK_UV = auto() 213 CELL_IMBALANCE = auto() 214 CHARGE_OC = auto() 215 DISCHARGE_OC = auto() 216 SHORT_CIRCUIT = auto() 217 CHARGE_OT = auto() 218 CHARGE_UT = auto() 219 DISCHARGE_OT = auto() 220 DISCHARGE_UT = auto() 221 FET_OT = auto() 222 FET_UT = auto() 223 SYSTEM_OT = auto() 224 SYSTEM_UT = auto() 225 LOW_SOC = auto() 226 FET_LOCKED = auto() 227 FET_FAILURE = auto() 228 AFE_FAILURE = auto() 229 CELL_FAILURE = auto() 230 SENSOR_FAILURE = auto() 231 COMM_FAILURE = auto() 232 FUSE_BLOWN = auto() 233 OTHER = auto() # vendor specific, requires BMSPrbDef.text 234 UNKNOWN = auto() # bit set but not described by the plugin
Generic problem categories (value = stable key).
194@unique 195class Severity(IntEnum): 196 """Problem severity, ordered so that max() yields the worst level.""" 197 198 OK = 0 199 INFO = 1 # operating state notice, no limit violated 200 WARN = 2 # limit approached, BMS still operational 201 PROTECT = 3 # protection tripped, charging and/or discharging inhibited 202 FAULT = 4 # hardware/internal failure
Problem severity, ordered so that max() yields the worst level.
92@unique 93class TSKind(IntEnum): 94 """Enumeration of temperature sensor source types.""" 95 96 GENERIC = 0x0 97 CELL = auto() 98 CELL_MAX = auto() 99 CELL_MIN = auto() 100 MOSFET = auto() 101 PCB = auto() 102 HEATER = auto() 103 BALANCER = auto() 104 AMBIENT = auto()
Enumeration of temperature sensor source types.
107@dataclass(frozen=True, slots=True) 108class TempSensor: 109 """Represents a temperature sensor reading from the BMS. 110 111 Instances compare equal to plain numbers by value, but to other `TempSensor` 112 instances by value and type. Ordering (`<`, `max()`, ...) uses the value only. 113 Conversion (`float()`, `int()`, `round()`) operates on the value and returns 114 plain numbers 115 116 Note: equality is not transitive. For example, `TempSensor(1, CELL) == 1` and 117 `1 == TempSensor(1, GENERIC)` are both `True`, yet 118 `TempSensor(1, CELL) != TempSensor(1, GENERIC)`. Do not rely on transitivity 119 when comparing mixed sensor types and plain numbers. Hashing uses the value only, 120 so sensors of different types with equal values may share a hash bucket. 121 """ 122 123 value: float 124 kind: TSKind = TSKind.GENERIC 125 126 def __eq__(self: Self, other: object) -> bool: 127 """Compare against other TempSensor including type or int, float.""" 128 129 if isinstance(other, TempSensor): 130 return (self.kind, self.value) == (other.kind, other.value) 131 if isinstance(other, (int, float)) and not isinstance(other, bool): 132 return self.value == other 133 return NotImplemented 134 135 def __float__(self) -> float: 136 """Return the temperature value as a float.""" 137 return float(self.value) 138 139 def __int__(self) -> int: 140 """Return the temperature value truncated to an int.""" 141 return int(self.value) 142 143 def __round__(self, ndigits: int | None = None) -> int | float: 144 """Round the temperature value, as `round()` does for numbers.""" 145 if ndigits is None: 146 return round(self.value) 147 return round(self.value, ndigits) 148 149 def __format__(self, format_spec: str) -> str: 150 """Format the temperature value, delegating to the underlying number.""" 151 return format(self.value, format_spec) 152 153 @staticmethod 154 def _cmp_value(other: object) -> float | None: 155 if isinstance(other, TempSensor): 156 return other.value 157 if isinstance(other, (int, float)) and not isinstance(other, bool): 158 return other 159 return None 160 161 def __lt__(self, other: object) -> bool: 162 """Compare temperature value.""" 163 if (val := self._cmp_value(other)) is None: 164 return NotImplemented 165 return self.value < val 166 167 def __le__(self, other: object) -> bool: 168 """Compare temperature value.""" 169 if (val := self._cmp_value(other)) is None: 170 return NotImplemented 171 return self.value <= val 172 173 def __gt__(self, other: object) -> bool: 174 """Compare temperature value.""" 175 if (val := self._cmp_value(other)) is None: 176 return NotImplemented 177 return self.value > val 178 179 def __ge__(self, other: object) -> bool: 180 """Compare temperature value.""" 181 if (val := self._cmp_value(other)) is None: 182 return NotImplemented 183 return self.value >= val 184 185 def __hash__(self) -> int: 186 """Hash the TempSensor based on its value (consistent with equality to numbers).""" 187 return hash(self.value) 188 189 def __repr__(self) -> str: 190 """Return the string representation of the sensor value/type.""" 191 return f"{self.__class__.__name__}({self.value!r}, {self.kind!r})"
Represents a temperature sensor reading from the BMS.
Instances compare equal to plain numbers by value, but to other TempSensor
instances by value and type. Ordering (<, max(), ...) uses the value only.
Conversion (float(), int(), round()) operates on the value and returns
plain numbers
Note: equality is not transitive. For example, TempSensor(1, CELL) == 1 and
1 == TempSensor(1, GENERIC) are both True, yet
TempSensor(1, CELL) != TempSensor(1, GENERIC). Do not rely on transitivity
when comparing mixed sensor types and plain numbers. Hashing uses the value only,
so sensors of different types with equal values may share a hash bucket.
411@dataclass(frozen=True, slots=True, kw_only=True) 412class Threshold: 413 """A single protection threshold as configured in the BMS. 414 415 Trip/release points at which the BMS activates/releases a protection. 416 They are not the operating envelope of the battery and must not be used as 417 charger/inverter set points. 418 """ 419 420 trip: float 421 """Trip point [V, A, °C].""" 422 release: float | None = None 423 """Recovery point, if reported.""" 424 delay: float | None = None 425 """Trip delay [s], if reported."""
A single protection threshold as configured in the BMS.
Trip/release points at which the BMS activates/releases a protection. They are not the operating envelope of the battery and must not be used as charger/inverter set points.