feat(bms): add read-only diagnostics and guarded operating switch commands
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
"""Synthetic transport: no radio, real battery, or OS services are accessed."""
|
||||
|
||||
# ruff: noqa: E402
|
||||
import concurrent.futures
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from jkbms_test_runtime.operations import Operations
|
||||
from jkbms_test_runtime.settings import SWITCHES, decode_settings, switch_command, unchanged_except
|
||||
from test_bms import HEADER, Service, frame, telemetry
|
||||
|
||||
|
||||
def settings_frame(**switches):
|
||||
data = bytearray(300)
|
||||
data[:5] = HEADER + b"\x01"
|
||||
for offset, value in [(10, 2800), (18, 4250), (98, -50), (114, 13), (130, 120000)]:
|
||||
data[offset : offset + 4] = value.to_bytes(4, "little", signed=value < 0)
|
||||
for key, (_, offset) in SWITCHES.items():
|
||||
data[offset : offset + 4] = int(switches.get(key, True)).to_bytes(4, "little")
|
||||
data[-1] = sum(data[:-1]) & 255
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_encoder_cannot_address_numeric_settings_and_decoder_rejects_corruption():
|
||||
raw = settings_frame()
|
||||
value = decode_settings(raw)
|
||||
assert value["values"]["nominal_capacity_ah"] == 120
|
||||
assert value["values"]["charge_undertemp_c"] == -5
|
||||
for name, (register, _) in SWITCHES.items():
|
||||
for enabled in (True, False):
|
||||
encoded = switch_command(name, enabled)
|
||||
assert len(encoded) == 20 and encoded[:6] == bytes.fromhex("aa5590eb") + bytes(
|
||||
[register, 4]
|
||||
)
|
||||
assert int.from_bytes(encoded[6:10], "little") == int(enabled)
|
||||
assert encoded[-1] == sum(encoded[:-1]) & 255
|
||||
for bad in (1, 0, None, "true", [], {}):
|
||||
with pytest.raises(ValueError):
|
||||
switch_command(name, bad)
|
||||
for name in ("soc", "voltage", "capacity", "password", "firmware", "reset", 0x6E):
|
||||
with pytest.raises(ValueError):
|
||||
switch_command(name, True)
|
||||
for bad in (raw[:-1], raw[:70] + bytes([raw[70] ^ 1]) + raw[71:], frame()):
|
||||
with pytest.raises(ValueError):
|
||||
decode_settings(bad)
|
||||
assert unchanged_except(raw, settings_frame(charging=False), "charging", False)
|
||||
assert not unchanged_except(
|
||||
raw, settings_frame(charging=False, balancing=False), "charging", False
|
||||
)
|
||||
assert telemetry(frame())["effective_capacity_ah"] == 118
|
||||
assert telemetry(frame())["configured_capacity_ah"] is None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rig(tmp_path):
|
||||
service = Service(tmp_path)
|
||||
address = "AA:BB:CC:DD:EE:01"
|
||||
service.observe(address, "hci7", -50)
|
||||
service.identify(address, {"model": "JK_BD6A17S6P", "firmware": "11.47", "hardware": "11.XA"})
|
||||
sample = {**telemetry(frame()), "current_a": 0, "protection_mask": 1 << 19}
|
||||
service.sample(address, sample)
|
||||
service.settings(address, decode_settings(settings_frame()))
|
||||
reads, writes = [], []
|
||||
observer = SimpleNamespace(
|
||||
active={"address": address, "verified": True},
|
||||
write_read=reads.append,
|
||||
write_switch=lambda *args: writes.append(args),
|
||||
)
|
||||
operations = Operations(service, observer)
|
||||
service.operations = operations
|
||||
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def request(action, parameters=None):
|
||||
identifier = "op_" + uuid.uuid4().hex
|
||||
return dict(
|
||||
operation_id=identifier,
|
||||
idempotency_key=identifier,
|
||||
action_id=action,
|
||||
deadline_at=(datetime.now(UTC) + timedelta(seconds=20)).isoformat(),
|
||||
session={
|
||||
"device_id": service.devices[address]["id"],
|
||||
"session_id": service.devices[address]["session"],
|
||||
},
|
||||
parameters=parameters or {},
|
||||
)
|
||||
|
||||
def start(req):
|
||||
future = pool.submit(operations.execute, req)
|
||||
until = time.monotonic() + 1
|
||||
while not operations.job and not future.done() and time.monotonic() < until:
|
||||
time.sleep(0.001)
|
||||
operations.tick()
|
||||
return future
|
||||
|
||||
def receive(raw):
|
||||
value = decode_settings(raw)
|
||||
service.settings(address, value)
|
||||
operations.received(address, raw, value)
|
||||
|
||||
def write_ready():
|
||||
operations.job["query_at"] -= 2
|
||||
operations.tick()
|
||||
operations.job["read_after"] -= 1
|
||||
operations.tick()
|
||||
|
||||
yield SimpleNamespace(
|
||||
service=service,
|
||||
address=address,
|
||||
op=operations,
|
||||
reads=reads,
|
||||
writes=writes,
|
||||
request=request,
|
||||
start=start,
|
||||
receive=receive,
|
||||
write_ready=write_ready,
|
||||
)
|
||||
operations.finish("test teardown")
|
||||
pool.shutdown()
|
||||
|
||||
|
||||
def test_read_and_noop_set_never_mutate(rig):
|
||||
for action, params in [
|
||||
("bms.read", {}),
|
||||
(
|
||||
"bms.control.set",
|
||||
dict(
|
||||
switch="charging",
|
||||
enabled=True,
|
||||
fingerprint=decode_settings(settings_frame())["fingerprint"],
|
||||
link_generation=0,
|
||||
),
|
||||
),
|
||||
]:
|
||||
req = rig.request(action, params)
|
||||
f = rig.start(req)
|
||||
rig.receive(settings_frame())
|
||||
assert f.result(1)["state"] == "complete"
|
||||
assert rig.op.execute(req) == f.result() and not rig.writes
|
||||
|
||||
|
||||
def test_verify_writes_only_current_values_once_and_checks_entire_readback(rig):
|
||||
req = rig.request("bms.control.verify")
|
||||
f = rig.start(req)
|
||||
rig.receive(settings_frame())
|
||||
rig.op.tick()
|
||||
assert not rig.writes # query must settle first
|
||||
for name in SWITCHES:
|
||||
rig.write_ready()
|
||||
assert rig.writes[-1] == (name, True)
|
||||
rig.receive(settings_frame())
|
||||
assert f.result(1)["result"]["verification"] == "same-value-only"
|
||||
rig.op.execute(req)
|
||||
assert len(rig.writes) == 3
|
||||
|
||||
|
||||
def test_mutation_readback_and_idempotency(rig):
|
||||
params = dict(
|
||||
switch="balancing",
|
||||
enabled=False,
|
||||
fingerprint=decode_settings(settings_frame())["fingerprint"],
|
||||
link_generation=0,
|
||||
)
|
||||
req = rig.request("bms.control.set", params)
|
||||
f = rig.start(req)
|
||||
rig.receive(settings_frame())
|
||||
rig.write_ready()
|
||||
rig.receive(settings_frame(balancing=False))
|
||||
assert f.result(1)["state"] == "complete" and rig.writes == [("balancing", False)]
|
||||
assert rig.op.execute(req) == f.result()
|
||||
with pytest.raises(ValueError):
|
||||
rig.op.execute({**req, "parameters": {**params, "enabled": True}})
|
||||
|
||||
|
||||
def test_uncertain_disconnect_and_side_effect_block_future_writes(rig):
|
||||
f = rig.start(rig.request("bms.control.verify"))
|
||||
rig.receive(settings_frame())
|
||||
rig.write_ready()
|
||||
rig.receive(settings_frame(balancing=False))
|
||||
assert f.result(1)["state"] == "unknown"
|
||||
with pytest.raises(ValueError):
|
||||
rig.op.execute(rig.request("bms.control.verify"))
|
||||
f = rig.start(rig.request("bms.read"))
|
||||
rig.receive(settings_frame())
|
||||
assert f.result(1)["state"] == "complete" # reading remains possible
|
||||
|
||||
|
||||
def test_old_session_deadline_generation_fingerprint_and_fault_rejected(rig):
|
||||
base = rig.request("bms.read")
|
||||
for req in (
|
||||
{**base, "deadline_at": "2000-01-01T00:00:00Z"},
|
||||
{**base, "session": {**base["session"], "session_id": "old"}},
|
||||
{**base, "action_id": "bms.reset"},
|
||||
):
|
||||
with pytest.raises(ValueError):
|
||||
rig.op.execute(req)
|
||||
req = rig.request(
|
||||
"bms.control.set",
|
||||
dict(switch="charging", enabled=False, fingerprint="old", link_generation=0),
|
||||
)
|
||||
f = rig.start(req)
|
||||
rig.receive(settings_frame())
|
||||
assert f.result(1)["state"] == "error" and not rig.writes
|
||||
f = rig.start(rig.request("bms.control.verify"))
|
||||
rig.receive(settings_frame())
|
||||
rig.service.devices[rig.address]["sample"]["protection_mask"] = 2
|
||||
rig.op.job["query_at"] -= 2
|
||||
rig.op.tick()
|
||||
assert f.result(1)["state"] == "error" and not rig.writes
|
||||
|
||||
|
||||
def test_transport_loss_after_write_is_unknown_without_retry(rig):
|
||||
f = rig.start(rig.request("bms.control.verify"))
|
||||
rig.receive(settings_frame())
|
||||
rig.write_ready()
|
||||
rig.op.finish("connection lost")
|
||||
assert f.result(1)["state"] == "unknown" and len(rig.writes) == 1
|
||||
for _ in range(3):
|
||||
rig.op.tick()
|
||||
assert len(rig.writes) == 1
|
||||
Reference in New Issue
Block a user