import struct from decimal import Decimal import pytest from gateway.config import Point from gateway.registers import Block, decode_point, encode_float32, extract_values, locate, plan_blocks def _regs(*values: int) -> list[int]: return list(values) def test_encode_decode_float32_abcd(): words = encode_float32(3.5, "ABCD") assert decode_point(words, Point(address=0, type="float32")) == Decimal("3.5") hi, lo = words assert struct.unpack(">f", struct.pack(">HH", hi, lo))[0] == 3.5 def test_decode_float32_cdab(): words = encode_float32(-12.75, "CDAB") point = Point(address=0, type="float32", word_order="CDAB") assert decode_point(words, point) == Decimal("-12.75") def test_decode_int32_with_scale(): # 410S 常见:32 位整数,0.001 分辨率 words = [(123456 >> 16) & 0xFFFF, 123456 & 0xFFFF] point = Point(address=0, type="uint32", scale=Decimal("0.001")) assert decode_point(words, point) == Decimal("123.456") def test_decode_int16_and_scale_offset(): point = Point(address=0, type="int16", scale=Decimal("0.1"), offset=Decimal("-5")) assert decode_point([0xFFF6], point) == Decimal("-6") def test_decode_short_words_raises(): with pytest.raises(ValueError): decode_point([0x0000], Point(address=0, type="float32")) def test_plan_blocks_merges_adjacent_points(): spans = [(0, 2), (2, 2), (4, 2), (20, 2)] blocks = plan_blocks(spans, max_registers=60, max_gap=4) assert blocks[0] == Block(0, 6) assert blocks[1] == Block(20, 2) def test_plan_blocks_respects_max_registers(): spans = [(0, 2), (4, 2)] blocks = plan_blocks(spans, max_registers=4, max_gap=4) assert blocks == [Block(0, 2), Block(4, 2)] def test_locate_and_extract(): points = { "instant": Point(address=2, type="float32"), "total": Point(address=20, type="uint32", scale=Decimal("0.1")), } blocks = plan_blocks([(p.address, p.width) for p in points.values()], max_gap=4) block_values = { 2: encode_float32(3.5), 20: _regs(0, 100), # 10.0 } values = extract_values(blocks, block_values, points) assert values["instant"] == Decimal("3.5") assert values["total"] == Decimal("10.0") assert locate(blocks, 20, 2)[0] == 20 def test_locate_missing_raises(): with pytest.raises(LookupError): locate([Block(0, 4)], 10, 2)