"""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[97:103] = 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