现场调试版同步:S331 点表修正(CDAB/scale 60/int32) + SafeRTUFramer 多点485 + 哨兵过滤
- config.yaml: 恢复现场 IP(10.50.253.165/.181/.182)、s331_2 端口 502 - config.yaml: S331 全部 32 位量 word_order 改 CDAB,瞬时流量 scale=60 (m3/min -> m3/h) - config.yaml: 11# 电表功率/电能类型改 int32;第二路 RTU 从站 slave_id 改 10 - poller.py: 过滤 S331 无数据哨兵 -9999 与非有限值,避免污染周期基准 - rtu.py: 新增 SafeRTUFramer 支持多点半总线,忽略其它从站请求 - 新增 config.debug.yaml、README.md、wheelhouse 离线依赖 - tests: 适配新配置(ttyS7/address_offset);新增 pytest.ini 限定 testpaths
This commit is contained in:
commit
9eaf87ab7d
43 files changed
+4514
No files matched your search
@@ -0,0 +1,6 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
@@ -0,0 +1,60 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from gateway.config import ConfigError, load_config
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_load_shipped_config():
|
||||
cfg = load_config(ROOT / "config" / "config.yaml")
|
||||
assert len(cfg.compressors) == 9
|
||||
assert len(cfg.slaves) == 2
|
||||
assert cfg.slaves[0].port != cfg.slaves[1].port
|
||||
assert sorted(c.register_index for c in cfg.compressors) == list(range(9))
|
||||
assert cfg.register_float_order == "ABCD"
|
||||
assert {c.s331 for c in cfg.compressors} == {"s331_1", "s331_2"}
|
||||
|
||||
|
||||
def test_device_address_offset_is_applied(tmp_path):
|
||||
# 先加载原配置拿原始值
|
||||
cfg_orig = load_config(ROOT / "config" / "config.yaml")
|
||||
first_orig = next(c for c in cfg_orig.compressors if c.id == 3)
|
||||
orig_power_addr = first_orig.power_instant.address
|
||||
orig_flow_addr = first_orig.flow_instant.address
|
||||
orig_device_count = len(cfg_orig.devices)
|
||||
|
||||
source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8")
|
||||
# 给蘑菇云电表加 10 个寄存器整体偏移(devices 首个配置块即 mogo_meter)
|
||||
source = source.replace(" address_offset: 0", " address_offset: 10", 1)
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(source, encoding="utf-8")
|
||||
|
||||
cfg = load_config(config_file)
|
||||
assert len(cfg.devices) == orig_device_count
|
||||
meter = cfg.devices["mogo_meter"]
|
||||
assert meter.address_offset == 10
|
||||
# 电表点位整体后移 10 个寄存器
|
||||
first = next(c for c in cfg.compressors if c.id == 3)
|
||||
assert first.power_instant.address == orig_power_addr + 10
|
||||
# S331 点位不受 meter 偏移影响
|
||||
assert first.flow_instant.address == orig_flow_addr
|
||||
|
||||
|
||||
def test_duplicate_register_index_rejected(tmp_path):
|
||||
source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8")
|
||||
source = source.replace("register_index: 1\n", "register_index: 0\n", 1)
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(source, encoding="utf-8")
|
||||
with pytest.raises(ConfigError):
|
||||
load_config(config_file)
|
||||
|
||||
|
||||
def test_duplicate_slave_port_rejected(tmp_path):
|
||||
source = (ROOT / "config" / "config.yaml").read_text(encoding="utf-8")
|
||||
source = source.replace("/dev/ttyS7", "/dev/ttyS1")
|
||||
config_file = tmp_path / "config.yaml"
|
||||
config_file.write_text(source, encoding="utf-8")
|
||||
with pytest.raises(ConfigError):
|
||||
load_config(config_file)
|
||||
@@ -0,0 +1,155 @@
|
||||
"""端到端验证:真实 Modbus TCP 服务端 + 网关从站数据源。
|
||||
|
||||
串口无法在开发机上跑,这里用同一套 SnapshotDeviceContext 通过 TCP 暴露寄存器,
|
||||
验证地址从 0 开始(40001)、Float 编码、越界返回异常码、读取耗时。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
from pymodbus.server import ModbusTcpServer
|
||||
|
||||
from gateway.config import CompressorCfg, Point
|
||||
from gateway.registers import decode_point
|
||||
from gateway.rtu import build_context
|
||||
from gateway.store import StateStore
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def _cfg() -> CompressorCfg:
|
||||
point = Point(address=0)
|
||||
return CompressorCfg(
|
||||
id=3,
|
||||
name="3#空压机",
|
||||
s331="s331_1",
|
||||
meter="meter_410s",
|
||||
register_index=2,
|
||||
flow_instant=point,
|
||||
flow_total=point,
|
||||
power_instant=point,
|
||||
energy_total=point,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store() -> StateStore:
|
||||
store = StateStore([_cfg()], float_order="ABCD")
|
||||
store.update(
|
||||
{
|
||||
3: {
|
||||
"instant_flow": Decimal("10"),
|
||||
"instant_power": Decimal("35"),
|
||||
"total_flow": Decimal("100"),
|
||||
"total_energy": Decimal("300"),
|
||||
}
|
||||
},
|
||||
now=datetime(2026, 1, 1, 10, 0, 0),
|
||||
)
|
||||
store.update(
|
||||
{3: {"total_flow": Decimal("110"), "total_energy": Decimal("330")}},
|
||||
now=datetime(2026, 1, 1, 10, 30, 0),
|
||||
)
|
||||
return store
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server_port(store: StateStore):
|
||||
loop = asyncio.new_event_loop()
|
||||
thread = threading.Thread(target=loop.run_forever, daemon=True)
|
||||
thread.start()
|
||||
port = _free_port()
|
||||
holder: dict = {}
|
||||
ready = threading.Event()
|
||||
|
||||
async def serve() -> None:
|
||||
server = ModbusTcpServer(build_context(store, 10), address=("127.0.0.1", port))
|
||||
holder["server"] = server
|
||||
ready.set()
|
||||
await server.serve_forever()
|
||||
|
||||
future = asyncio.run_coroutine_threadsafe(serve(), loop)
|
||||
assert ready.wait(5), "Modbus TCP 测试服务未能创建"
|
||||
|
||||
deadline = time.time() + 5
|
||||
while not holder["server"].is_active and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
assert holder["server"].is_active, "Modbus TCP 测试服务未能监听端口"
|
||||
|
||||
yield port
|
||||
|
||||
future.cancel()
|
||||
loop.call_soon_threadsafe(loop.stop)
|
||||
thread.join(timeout=5)
|
||||
|
||||
|
||||
def _open(port: int) -> ModbusTcpClient:
|
||||
client = ModbusTcpClient("127.0.0.1", port=port, timeout=2, retries=1)
|
||||
assert client.connect()
|
||||
return client
|
||||
|
||||
|
||||
def test_registers_start_at_40001(server_port: int, store: StateStore):
|
||||
client = _open(server_port)
|
||||
try:
|
||||
response = client.read_holding_registers(16, count=8, slave=10)
|
||||
finally:
|
||||
client.close()
|
||||
assert response is not None and not response.isError()
|
||||
|
||||
point = Point(address=0, type="float32")
|
||||
values = [decode_point(response.registers[i : i + 2], point) for i in range(0, 8, 2)]
|
||||
# register_index=2 -> 基址 16 (40017),与 S331 读取 40017~40024 一致
|
||||
assert values[0] == Decimal("3.5")
|
||||
assert values[1] == Decimal("3")
|
||||
assert values[2] == Decimal("3")
|
||||
assert values[3] == Decimal("3")
|
||||
|
||||
|
||||
def test_unmapped_address_returns_exception(server_port: int):
|
||||
client = _open(server_port)
|
||||
try:
|
||||
response = client.read_holding_registers(1000, count=2, slave=10)
|
||||
finally:
|
||||
client.close()
|
||||
assert response is None or response.isError()
|
||||
|
||||
|
||||
def test_unknown_slave_id_gets_no_answer(server_port: int):
|
||||
client = ModbusTcpClient("127.0.0.1", port=server_port, timeout=0.5, retries=1)
|
||||
assert client.connect()
|
||||
try:
|
||||
try:
|
||||
response = client.read_holding_registers(0, count=2, slave=99)
|
||||
except Exception: # noqa: BLE001 - pymodbus 对未知从站会直接抛异常
|
||||
response = None
|
||||
finally:
|
||||
client.close()
|
||||
assert response is None or response.isError()
|
||||
|
||||
|
||||
def test_read_latency(server_port: int):
|
||||
client = _open(server_port)
|
||||
try:
|
||||
elapsed = []
|
||||
for _ in range(20):
|
||||
started = time.perf_counter()
|
||||
response = client.read_holding_registers(16, count=8, slave=10)
|
||||
elapsed.append(time.perf_counter() - started)
|
||||
assert response is not None and not response.isError()
|
||||
finally:
|
||||
client.close()
|
||||
# 局域网 TCP 往返,串口版还受波特率限制(9600 下 8 个寄存器约 20~30ms)
|
||||
assert max(elapsed) < 1.0
|
||||
@@ -0,0 +1,124 @@
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from gateway.model import MachineState
|
||||
|
||||
|
||||
def _machine() -> MachineState:
|
||||
return MachineState(1, "1#空压机", 0)
|
||||
|
||||
|
||||
def test_instant_ratio():
|
||||
m = _machine()
|
||||
t = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t, instant_flow=Decimal("10"), total_flow=Decimal("1000"))
|
||||
m.apply(t, instant_power=Decimal("50"), total_energy=Decimal("5000"))
|
||||
|
||||
assert m.ratios["instant"] == Decimal("5")
|
||||
# 周期基准刚建立,小时/天/月比值应为 0
|
||||
assert m.ratios["hour"] == 0
|
||||
assert m.ratios["day"] == 0
|
||||
assert m.ratios["month"] == 0
|
||||
|
||||
|
||||
def test_instant_ratio_zero_flow_is_safe():
|
||||
m = _machine()
|
||||
t = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t, instant_flow=Decimal("0"), instant_power=Decimal("50"))
|
||||
assert m.ratios["instant"] == 0
|
||||
|
||||
|
||||
def test_hour_ratio_and_hour_rollover():
|
||||
m = _machine()
|
||||
t0 = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t0, total_flow=Decimal("1000"), total_energy=Decimal("5000"))
|
||||
|
||||
m.apply(t0 + timedelta(minutes=30), total_flow=Decimal("1100"), total_energy=Decimal("5500"))
|
||||
assert m.ratios["hour"] == Decimal("5")
|
||||
assert m.ratios["day"] == Decimal("5")
|
||||
|
||||
# 11:00:01 整点清零:之前累计值成为新基准
|
||||
t1 = datetime(2026, 1, 1, 11, 0, 1)
|
||||
m.apply(t1, total_flow=Decimal("1120"), total_energy=Decimal("5600"))
|
||||
assert m.ratios["hour"] == 0
|
||||
# 天累计不受整点影响:600/120 = 5
|
||||
assert m.ratios["day"] == Decimal("5")
|
||||
|
||||
# 本小时内有新产出后才开始累计
|
||||
m.apply(t1 + timedelta(minutes=10), total_flow=Decimal("1170"), total_energy=Decimal("5850"))
|
||||
assert m.ratios["hour"] == Decimal("5")
|
||||
|
||||
|
||||
def test_day_and_month_rollover():
|
||||
m = _machine()
|
||||
start = datetime(2026, 1, 31, 23, 50, 0)
|
||||
m.apply(start, total_flow=Decimal("1000"), total_energy=Decimal("3000"))
|
||||
m.apply(start + timedelta(minutes=5), total_flow=Decimal("1100"), total_energy=Decimal("3300"))
|
||||
assert m.ratios["day"] == Decimal("3")
|
||||
assert m.ratios["month"] == Decimal("3")
|
||||
|
||||
# 跨零点、跨月
|
||||
m.apply(datetime(2026, 2, 1, 0, 0, 5), total_flow=Decimal("1110"), total_energy=Decimal("3330"))
|
||||
assert m.ratios["day"] == 0
|
||||
assert m.ratios["month"] == 0
|
||||
assert m.ratios["hour"] == 0
|
||||
|
||||
m.apply(datetime(2026, 2, 1, 0, 0, 35), total_flow=Decimal("1130"), total_energy=Decimal("3390"))
|
||||
assert m.ratios["day"] == Decimal("3")
|
||||
assert m.ratios["month"] == Decimal("3")
|
||||
|
||||
|
||||
def test_zero_consumption_in_period_is_zero():
|
||||
m = _machine()
|
||||
t = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t, total_flow=Decimal("1000"), total_energy=Decimal("5000"))
|
||||
m.apply(t + timedelta(minutes=5), total_flow=Decimal("1000"), total_energy=Decimal("5000"))
|
||||
assert m.ratios["hour"] == 0
|
||||
|
||||
|
||||
def test_restore_same_period_keeps_accumulation():
|
||||
m = _machine()
|
||||
t0 = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t0, total_flow=Decimal("1000"), total_energy=Decimal("5000"))
|
||||
m.apply(t0 + timedelta(minutes=10), total_flow=Decimal("1100"), total_energy=Decimal("5500"))
|
||||
|
||||
payload = m.to_payload()
|
||||
restored = MachineState(1, "1#空压机", 0)
|
||||
restored.restore(payload, t0 + timedelta(minutes=20))
|
||||
|
||||
assert restored.ratios["day"] == Decimal("5")
|
||||
# 恢复后再累加,仍以原始基准计算:700/140 = 5
|
||||
restored.apply(t0 + timedelta(minutes=30), total_flow=Decimal("1140"), total_energy=Decimal("5700"))
|
||||
assert restored.ratios["day"] == Decimal("5")
|
||||
|
||||
|
||||
def test_restore_after_period_change_uses_last_totals():
|
||||
m = _machine()
|
||||
t0 = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t0, total_flow=Decimal("1000"), total_energy=Decimal("5000"))
|
||||
m.apply(t0 + timedelta(minutes=10), total_flow=Decimal("1100"), total_energy=Decimal("5500"))
|
||||
payload = m.to_payload()
|
||||
|
||||
restored = MachineState(1, "1#空压机", 0)
|
||||
restored.restore(payload, datetime(2026, 1, 2, 8, 0, 0))
|
||||
assert restored.ratios["day"] == 0
|
||||
# 仍在同一个月内,月累计保持连续
|
||||
assert restored.ratios["month"] == Decimal("5")
|
||||
|
||||
# 恢复后的新数据以“最后一次累计值”为起点
|
||||
restored.apply(datetime(2026, 1, 2, 8, 1, 0), total_flow=Decimal("1110"), total_energy=Decimal("5530"))
|
||||
assert restored.ratios["day"] == Decimal("3")
|
||||
|
||||
|
||||
def test_restore_payload_roundtrip_of_ratios():
|
||||
m = _machine()
|
||||
t0 = datetime(2026, 1, 1, 10, 0, 0)
|
||||
m.apply(t0, instant_flow=Decimal("10"), total_flow=Decimal("1000"))
|
||||
m.apply(t0, instant_power=Decimal("25"), total_energy=Decimal("5000"))
|
||||
m.apply(t0 + timedelta(minutes=1), total_flow=Decimal("1010"), total_energy=Decimal("5050"))
|
||||
|
||||
payload = m.to_payload()
|
||||
restored = MachineState(1, "1#空压机", 0)
|
||||
restored.restore(payload, t0 + timedelta(minutes=2))
|
||||
for key in ("instant", "hour", "day", "month"):
|
||||
assert restored.ratios[key] == m.ratios[key]
|
||||
@@ -0,0 +1,145 @@
|
||||
"""采集线程验证:批量读取解码 + 断线后指数退避重连并自动恢复。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusServerContext, ModbusSlaveContext
|
||||
from pymodbus.server import ModbusTcpServer
|
||||
|
||||
from gateway.config import DeviceCfg, Point
|
||||
from gateway.poller import PointBinding, TcpPoller
|
||||
from gateway.registers import encode_float32
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def _context() -> ModbusServerContext:
|
||||
registers = [0] * 64
|
||||
for address, value in ((0, 3.5), (2, 1000.0), (4, 42.0), (6, 4200.0)):
|
||||
registers[address : address + 2] = encode_float32(value)
|
||||
# pymodbus 内置从站上下文内部有 +1 偏移,块起始地址设为 1 才能对应协议地址 0;
|
||||
# 注意 pymodbus 3.9.2 的 ModbusSlaveContext 只在 di 不为空时才采用传入的 hr 块,
|
||||
# 因此这里四个数据区都传入同一个块(仅测试用模拟服务端,生产从站使用自定义上下文)。
|
||||
block = ModbusSequentialDataBlock(1, registers)
|
||||
context = ModbusSlaveContext(di=block, co=block, ir=block, hr=block)
|
||||
return ModbusServerContext(slaves={1: context}, single=False)
|
||||
|
||||
|
||||
class _Server:
|
||||
def __init__(self, port: int) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
self._thread = threading.Thread(target=self._loop.run_forever, daemon=True)
|
||||
self._holder: dict = {}
|
||||
self._ready = threading.Event()
|
||||
self._port = port
|
||||
self._future = None
|
||||
|
||||
def start(self) -> "_Server":
|
||||
self._thread.start()
|
||||
|
||||
async def serve() -> None:
|
||||
server = ModbusTcpServer(_context(), address=("127.0.0.1", self._port))
|
||||
self._holder["server"] = server
|
||||
self._ready.set()
|
||||
await server.serve_forever()
|
||||
|
||||
self._future = asyncio.run_coroutine_threadsafe(serve(), self._loop)
|
||||
assert self._ready.wait(5)
|
||||
deadline = time.time() + 5
|
||||
while not self._holder["server"].is_active and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
assert self._holder["server"].is_active
|
||||
return self
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._future is not None:
|
||||
self._future.cancel()
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._thread.join(timeout=5)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server():
|
||||
server = _Server(_free_port()).start()
|
||||
yield server
|
||||
server.stop()
|
||||
|
||||
|
||||
def _bindings() -> list[PointBinding]:
|
||||
return [
|
||||
PointBinding(1, "instant_flow", Point(address=0, type="float32")),
|
||||
PointBinding(1, "total_flow", Point(address=2, type="float32")),
|
||||
PointBinding(1, "instant_power", Point(address=4, type="float32")),
|
||||
PointBinding(1, "total_energy", Point(address=6, type="float32")),
|
||||
]
|
||||
|
||||
|
||||
def _poller(port: int, stop: threading.Event, on_values) -> TcpPoller:
|
||||
cfg = DeviceCfg(
|
||||
name="s331_test",
|
||||
host="127.0.0.1",
|
||||
port=port,
|
||||
poll_interval_s=0.05,
|
||||
timeout_s=0.5,
|
||||
reconnect_min_s=0.1,
|
||||
reconnect_max_s=0.4,
|
||||
)
|
||||
return TcpPoller(cfg, _bindings(), on_values, stop)
|
||||
|
||||
|
||||
def _wait_for(predicate, timeout: float) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if predicate():
|
||||
return True
|
||||
time.sleep(0.02)
|
||||
return False
|
||||
|
||||
|
||||
def test_poller_reads_and_decodes(server: _Server):
|
||||
samples: list[dict] = []
|
||||
stop = threading.Event()
|
||||
poller = _poller(server._port, stop, samples.append)
|
||||
poller.start()
|
||||
try:
|
||||
assert _wait_for(lambda: len(samples) >= 2, 5)
|
||||
finally:
|
||||
stop.set()
|
||||
poller.join(timeout=2)
|
||||
|
||||
values = samples[-1]
|
||||
assert values[(1, "instant_flow")] == Decimal("3.5")
|
||||
assert values[(1, "total_flow")] == Decimal("1000")
|
||||
assert values[(1, "instant_power")] == Decimal("42")
|
||||
assert values[(1, "total_energy")] == Decimal("4200")
|
||||
assert poller.status()["ok_cycles"] >= 2
|
||||
|
||||
|
||||
def test_poller_reconnects_after_device_comes_back():
|
||||
port = _free_port()
|
||||
samples: list[dict] = []
|
||||
stop = threading.Event()
|
||||
poller = _poller(port, stop, samples.append)
|
||||
poller.start()
|
||||
time.sleep(0.8) # 设备不在线:线程必须存活并进入退避重连
|
||||
assert poller.is_alive()
|
||||
assert poller.status()["fail_cycles"] > 0
|
||||
|
||||
server = _Server(port).start()
|
||||
try:
|
||||
assert _wait_for(lambda: len(samples) >= 1, 10)
|
||||
assert poller.status()["ok_cycles"] >= 1
|
||||
finally:
|
||||
stop.set()
|
||||
poller.join(timeout=2)
|
||||
server.stop()
|
||||
@@ -0,0 +1,75 @@
|
||||
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)
|
||||
@@ -0,0 +1,113 @@
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from gateway.config import CompressorCfg, Point
|
||||
from gateway.registers import decode_point
|
||||
from gateway.store import StateStore
|
||||
|
||||
|
||||
def _cfg(machine_id: int, register_index: int) -> CompressorCfg:
|
||||
point = Point(address=0)
|
||||
return CompressorCfg(
|
||||
id=machine_id,
|
||||
name=f"{machine_id}#空压机",
|
||||
s331="s331_1",
|
||||
meter="meter_410s",
|
||||
register_index=register_index,
|
||||
flow_instant=point,
|
||||
flow_total=point,
|
||||
power_instant=point,
|
||||
energy_total=point,
|
||||
)
|
||||
|
||||
|
||||
def _ratio_words(store: StateStore, base: int) -> list[Decimal]:
|
||||
point = Point(address=0, type="float32")
|
||||
words = store.read_registers(base, 8)
|
||||
assert words is not None
|
||||
return [decode_point(words[i : i + 2], point) for i in range(0, 8, 2)]
|
||||
|
||||
|
||||
def test_register_image_layout():
|
||||
store = StateStore([_cfg(1, 0), _cfg(2, 1)])
|
||||
assert store.register_count == 16
|
||||
|
||||
now = datetime(2026, 1, 1, 10, 0, 0)
|
||||
store.update(
|
||||
{2: {"instant_flow": Decimal("10"), "instant_power": Decimal("30")}},
|
||||
now=now,
|
||||
)
|
||||
machine1 = _ratio_words(store, 0)
|
||||
machine2 = _ratio_words(store, 8)
|
||||
assert machine1 == [Decimal(0)] * 4
|
||||
assert machine2[0] == Decimal("3")
|
||||
|
||||
|
||||
def test_read_out_of_range_returns_none():
|
||||
store = StateStore([_cfg(1, 0)])
|
||||
assert store.read_registers(0, 8) is not None
|
||||
assert store.read_registers(4, 8) is None
|
||||
assert store.read_registers(-1, 2) is None
|
||||
|
||||
|
||||
def test_concurrent_updates_never_tear_registers():
|
||||
"""写线程成组更新 4 个比值,读线程必须始终读到同一代数据。"""
|
||||
import threading
|
||||
|
||||
store = StateStore([_cfg(1, 0)])
|
||||
now = datetime(2026, 1, 1, 10, 0, 0)
|
||||
# 建立 (0, 0) 基准,使四种比值完全由后续累计值决定
|
||||
store.update({1: {"total_flow": Decimal(0), "total_energy": Decimal(0)}}, now=now)
|
||||
|
||||
stop = threading.Event()
|
||||
read_count = 0
|
||||
bad_reads: list[list[Decimal]] = []
|
||||
|
||||
def writer() -> None:
|
||||
for index in range(1, 4001):
|
||||
factor = 3 if index % 2 == 0 else 6
|
||||
store.update(
|
||||
{
|
||||
1: {
|
||||
"instant_flow": Decimal(10),
|
||||
"instant_power": Decimal(10 * factor),
|
||||
"total_flow": Decimal(100),
|
||||
"total_energy": Decimal(100 * factor),
|
||||
}
|
||||
},
|
||||
now=now,
|
||||
)
|
||||
stop.set()
|
||||
|
||||
thread = threading.Thread(target=writer, daemon=True)
|
||||
thread.start()
|
||||
while not stop.is_set():
|
||||
values = _ratio_words(store, 0)
|
||||
read_count += 1
|
||||
if len(set(values)) != 1:
|
||||
bad_reads.append(values)
|
||||
thread.join()
|
||||
|
||||
assert read_count > 100
|
||||
assert bad_reads == []
|
||||
|
||||
|
||||
def test_persist_and_restore_roundtrip():
|
||||
store = StateStore([_cfg(1, 0)])
|
||||
now = datetime(2026, 1, 1, 10, 0, 0)
|
||||
store.update(
|
||||
{
|
||||
1: {
|
||||
"instant_flow": Decimal("10"),
|
||||
"instant_power": Decimal("30"),
|
||||
"total_flow": Decimal("1000"),
|
||||
"total_energy": Decimal("3000"),
|
||||
}
|
||||
},
|
||||
now=now,
|
||||
)
|
||||
payload = store.persist_payloads()
|
||||
|
||||
fresh = StateStore([_cfg(1, 0)])
|
||||
assert fresh.restore(payload, now=now) == 1
|
||||
assert _ratio_words(fresh, 0)[0] == Decimal("3")
|
||||
Reference in new issue
Block a user