feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
"""Exercise the actual observer against synthetic D-Bus objects, without BLE."""
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import types
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def observer(monkeypatch, tmp_path):
|
||||
package = "jk_observer_test_" + uuid.uuid4().hex
|
||||
root = Path(__file__).resolve().parents[1] / "runtime"
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
package, root / "__init__.py", submodule_search_locations=[str(root)]
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, module)
|
||||
spec.loader.exec_module(module)
|
||||
calls, objects = [], {}
|
||||
|
||||
class Proxy:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
|
||||
def __getattr__(self, name):
|
||||
def call(*args, **kwargs):
|
||||
calls.append((self.path, name, args))
|
||||
if name == "GetManagedObjects":
|
||||
return objects
|
||||
if name == "GetAll":
|
||||
return objects[self.path][args[0]]
|
||||
|
||||
return call
|
||||
|
||||
class Bus:
|
||||
def get_object(self, destination, path, **kwargs):
|
||||
assert destination == "org.bluez" and kwargs.get("introspect") is False
|
||||
return Proxy(path)
|
||||
|
||||
def add_signal_receiver(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
dbus = types.ModuleType("dbus")
|
||||
dbus.DBusException = type("DBusException", (Exception,), {})
|
||||
dbus.SystemBus = Bus
|
||||
dbus.Interface = lambda obj, interface: obj
|
||||
dbus.Array = lambda value, **kwargs: value
|
||||
dbus.Dictionary = lambda value, **kwargs: value
|
||||
dbus.Boolean, dbus.String = bool, str
|
||||
monkeypatch.setitem(sys.modules, "dbus", dbus)
|
||||
monkeypatch.setitem(sys.modules, "dbus.mainloop", types.ModuleType("dbus.mainloop"))
|
||||
glib = types.ModuleType("dbus.mainloop.glib")
|
||||
glib.DBusGMainLoop = lambda **kwargs: None
|
||||
monkeypatch.setitem(sys.modules, "dbus.mainloop.glib", glib)
|
||||
runtime = importlib.import_module(package + ".bluez")
|
||||
service = importlib.import_module(package + ".service").Service(tmp_path)
|
||||
now = [100.0]
|
||||
monkeypatch.setattr(runtime.time, "monotonic", lambda: now[0])
|
||||
obj = runtime.Observer(service)
|
||||
adapter, peer = "/org/bluez/hci5", "/org/bluez/hci5/dev_AA_BB_CC_DD_EE_01"
|
||||
props = {
|
||||
"Name": "JK_synthetic",
|
||||
"Address": "AA:BB:CC:DD:EE:01",
|
||||
"AddressType": "public",
|
||||
"ManufacturerData": {0x0B65: bytes.fromhex("88a0aabbccddee01")},
|
||||
"Adapter": adapter,
|
||||
"RSSI": -65,
|
||||
}
|
||||
objects[adapter] = {runtime.ADAPTER: {"Powered": True}}
|
||||
objects[peer] = {runtime.DEVICE: props}
|
||||
objects[peer + "/service"] = {"org.bluez.GattService1": {"UUID": runtime.SERVICE}}
|
||||
objects[peer + "/char"] = {
|
||||
runtime.GATT: {
|
||||
"Service": peer + "/service",
|
||||
"UUID": runtime.CHARACTERISTIC,
|
||||
"Flags": ["notify", "write-without-response"],
|
||||
}
|
||||
}
|
||||
return obj, runtime, objects, props, calls, now, peer
|
||||
|
||||
|
||||
def start(observer):
|
||||
obj, runtime, objects, props, calls, now, peer = observer
|
||||
obj.tick()
|
||||
obj.added(peer, {runtime.DEVICE: props})
|
||||
now[0] = 113
|
||||
obj.tick()
|
||||
props.update(Connected=True, ServicesResolved=True)
|
||||
obj.tick()
|
||||
|
||||
|
||||
def info(version):
|
||||
data = bytearray(300)
|
||||
data[:5] = bytes.fromhex("55aaeb9003")
|
||||
data[6:18] = b"JK_BD6A17S6P"
|
||||
data[30:35] = version
|
||||
data[-1] = sum(data[:-1]) & 255
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_verification_precedes_telemetry_request(observer):
|
||||
start(observer)
|
||||
obj, runtime, objects, props, calls, now, peer = observer
|
||||
def writes():
|
||||
return [args[0][4] for _, name, args in calls if name == "WriteValue"]
|
||||
assert writes() == [0x97]
|
||||
obj.changed(runtime.GATT, {"Value": info(b"11.47")}, [], path=peer + "/char")
|
||||
obj.tick()
|
||||
assert writes() == [0x97, 0x96]
|
||||
props["Connected"] = False
|
||||
obj.tick()
|
||||
assert obj.active is None
|
||||
assert any(name == "StopNotify" for _, name, _ in calls)
|
||||
assert writes() == [0x97, 0x96]
|
||||
|
||||
|
||||
def test_unsupported_firmware_never_requests_telemetry(observer):
|
||||
start(observer)
|
||||
obj, runtime, objects, props, calls, now, peer = observer
|
||||
obj.changed(runtime.GATT, {"Value": info(b"14.00")}, [], path=peer + "/char")
|
||||
assert obj.active is None
|
||||
assert [args[0][4] for _, name, args in calls if name == "WriteValue"] == [0x97]
|
||||
assert (
|
||||
obj.service.inventory("synthetic")["items"][0]["bms_status"]["state"]
|
||||
== "unsupported_firmware"
|
||||
)
|
||||
|
||||
|
||||
def test_foreign_connection_is_never_taken_over(observer):
|
||||
obj, runtime, objects, props, calls, now, peer = observer
|
||||
props["Connected"] = True
|
||||
obj.tick()
|
||||
obj.added(peer, {runtime.DEVICE: props})
|
||||
now[0] = 113
|
||||
obj.tick()
|
||||
assert obj.active is None
|
||||
assert not any(
|
||||
name in {"Connect", "Disconnect", "WriteValue", "StartNotify"} for _, name, _ in calls
|
||||
)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Synthetic protocol and inventory checks; never opens a radio."""
|
||||
|
||||
# ruff: noqa: E402
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from missioncore_plugin_sdk.v0alpha2 import DeviceSessionSnapshot
|
||||
|
||||
root = Path(__file__).resolve().parents[1] / "runtime"
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"jkbms_test_runtime", root / "__init__.py", submodule_search_locations=[str(root)]
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
from jkbms_test_runtime.protocol import (
|
||||
HEADER,
|
||||
Frames,
|
||||
candidate,
|
||||
device_id,
|
||||
identity,
|
||||
query,
|
||||
supported,
|
||||
telemetry,
|
||||
)
|
||||
from jkbms_test_runtime.service import Service
|
||||
|
||||
|
||||
def frame():
|
||||
data = bytearray(300)
|
||||
data[:5] = HEADER + b"\x02"
|
||||
|
||||
def put(offset, value, size=4, signed=False):
|
||||
data[offset : offset + size] = value.to_bytes(size, "little", signed=signed)
|
||||
|
||||
for n in range(13):
|
||||
put(6 + n * 2, 4100, 2)
|
||||
put(70, (1 << 13) - 1)
|
||||
put(150, 53300)
|
||||
put(158, -2000, signed=True)
|
||||
put(173, 80, 1)
|
||||
put(174, 94400)
|
||||
put(178, 118000)
|
||||
put(182, 170)
|
||||
put(214, 3, 1)
|
||||
put(144, 251, 2)
|
||||
put(162, 270, 2)
|
||||
put(164, 1000, 2)
|
||||
data[-1] = sum(data[:-1]) & 255
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_fragmentation_resync_checksum_and_bounded_buffer():
|
||||
raw = frame()
|
||||
for split in range(1, 300):
|
||||
parser = Frames()
|
||||
assert parser.feed(b"noise" + raw[:split]) == []
|
||||
assert parser.feed(raw[split:]) == [raw]
|
||||
parser = Frames()
|
||||
damaged = raw[:90] + bytes([raw[90] ^ 1]) + raw[91:]
|
||||
assert parser.feed(damaged) == []
|
||||
assert parser.feed(raw) == [raw]
|
||||
assert parser.rejected == 1
|
||||
parser.feed(b"x" * 100000)
|
||||
assert len(parser.buffer) < 300
|
||||
|
||||
|
||||
def test_only_reviewed_requests_and_temperature_presence():
|
||||
assert query(0x97).hex() == "aa5590eb97000000000000000000000000000011"
|
||||
assert query(0x96).hex() == "aa5590eb96000000000000000000000000000010"
|
||||
for value in (0, 1, 0x98, True, "0x97"):
|
||||
with pytest.raises(ValueError):
|
||||
query(value)
|
||||
sample = telemetry(frame())
|
||||
assert sample["cell_count"] == 13 and sample["voltage_v"] == 53.3
|
||||
assert sample["current_a"] == -2 and sample["power_w"] == -106.6
|
||||
assert sample["temperature_mos_c"] == 25.1 and sample["temperature_2_c"] is None
|
||||
bad = bytearray(frame())
|
||||
bad[173] = 101
|
||||
with pytest.raises(ValueError):
|
||||
telemetry(bad)
|
||||
bad = bytearray(frame())
|
||||
bad[70:74] = b"\x05\x00\x00\x00"
|
||||
with pytest.raises(ValueError):
|
||||
telemetry(bad)
|
||||
|
||||
|
||||
def test_identity_allowlist_and_candidate_are_not_compatibility():
|
||||
data = bytearray(300)
|
||||
data[:5] = HEADER + b"\x03"
|
||||
data[6:18] = b"JK_BD6A17S6P"
|
||||
data[30:35] = b"11.47"
|
||||
data[90:96] = b"SECRET"
|
||||
info = identity(data)
|
||||
assert supported(info) and "SECRET" not in json.dumps(info)
|
||||
assert not supported({**info, "firmware": "14.00"})
|
||||
props = {
|
||||
"Name": "JK_synthetic",
|
||||
"Address": "AA:BB:CC:DD:EE:01",
|
||||
"AddressType": "public",
|
||||
"ManufacturerData": {0x0B65: bytes.fromhex("88a0aabbccddee01")},
|
||||
}
|
||||
assert candidate(props)
|
||||
for change in (
|
||||
{"Name": "other"},
|
||||
{"ManufacturerData": {}},
|
||||
{"AddressType": "random"},
|
||||
{"Address": "AA:BB:CC:DD:EE:02"},
|
||||
):
|
||||
assert not candidate({**props, **change})
|
||||
|
||||
|
||||
def test_multiple_instances_restart_stale_and_no_disk_measurements(tmp_path):
|
||||
now = [10]
|
||||
service = Service(tmp_path, clock=lambda: now[0])
|
||||
address = "AA:BB:CC:DD:EE:01"
|
||||
service.observe(address, "hci7", -70)
|
||||
service.identify(address, {"model": "JK_BD6A17S6P", "firmware": "11.47"})
|
||||
service.sample(address, telemetry(frame()))
|
||||
first = service.inventory("synthetic-node")["items"][0]
|
||||
DeviceSessionSnapshot.model_validate(first["snapshot"])
|
||||
assert first["online"]
|
||||
service.state(address, "disconnected")
|
||||
service.observe(address, "hci9", -75)
|
||||
second = service.inventory("synthetic-node")["items"][0]
|
||||
assert (
|
||||
second["id"] == first["id"]
|
||||
and second["snapshot"]["context"] == first["snapshot"]["context"]
|
||||
)
|
||||
assert second["bms_status"]["sample"] and not second["online"]
|
||||
for index in range(2, 11):
|
||||
service.observe(f"AA:BB:CC:DD:EE:{index:02X}", "hci9", -65)
|
||||
assert len(service.inventory("synthetic-node")["items"]) == 8
|
||||
assert device_id(address) != device_id("AA:BB:CC:DD:EE:02")
|
||||
raw = next(tmp_path.glob("*.json")).read_text()
|
||||
assert "sample" not in raw and "voltage" not in raw and "53300" not in raw
|
||||
restored = Service(tmp_path).inventory("synthetic-node")["items"][0]
|
||||
assert restored["id"] == first["id"] and restored["bms_status"]["sample"] is None
|
||||
now[0] = 311
|
||||
assert service.inventory("synthetic-node")["items"][0]["bms_status"]["sample"] is None
|
||||
Reference in New Issue
Block a user