现场调试版同步: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,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()
|
||||
Reference in new issue
Block a user