- 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
193 lines
7.4 KiB
Python
193 lines
7.4 KiB
Python
"""双路 Modbus RTU 从站。
|
|
|
|
为 S331 #1 与 S331 #2 各启动一个独立的 ModbusSerialServer 实例,
|
|
分别绑定 /dev/ttyS1 与 /dev/ttyS2,物理隔离,互不干扰。
|
|
|
|
从站仅提供只读保持寄存器(FC03/FC04),数据源为 StateStore 中的寄存器快照。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import threading
|
|
from typing import Sequence
|
|
|
|
from pymodbus import FramerType
|
|
from pymodbus.datastore import ModbusServerContext
|
|
from pymodbus.framer import FramerRTU
|
|
from pymodbus.server import ModbusSerialServer
|
|
|
|
from .config import SlaveCfg
|
|
from .store import StateStore
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
# 功能码 -> 数据区(只读,写操作一律拒绝)
|
|
_FX_MAPPER = {1: "c", 2: "d", 3: "h", 4: "i", 5: "c", 6: "h", 15: "c", 16: "h", 22: "h", 23: "h"}
|
|
|
|
ILLEGAL_DATA_ADDRESS = 2
|
|
ILLEGAL_FUNCTION = 1
|
|
|
|
|
|
class SafeRTUFramer(FramerRTU):
|
|
"""只认“发往本从站地址”的 RTU 从站 framer。
|
|
|
|
pymodbus 自带的 FramerRTU 默认 485 上只有自己一个从站,按顺序逐帧解析收到的
|
|
字节。现场这条 485 上 S331 屏是主站,它同时轮询 67~75 号流量计,实测一次读进来
|
|
的数据能粘成 772 字节的一大批;批里只要有一帧解不出来,异常就冒到 asyncio
|
|
回调里,整批字节被丢弃——包括夹在中间的 `0a 03 ...` 请求,屏上的气电比因此
|
|
会短暂变空、过一会儿才恢复。
|
|
这里改成只在缓冲区里扫描“地址=本从站、FC03/04、CRC 正确”的 8 字节请求,
|
|
其余字节直接丢弃,我方请求不会被别的设备的流量带走。
|
|
"""
|
|
|
|
SLAVE_ID = 10 # 由 _serve_one 按配置设置
|
|
REQUESTS = (3, 4) # S331 屏只用 FC03/FC04 读保持/输入寄存器
|
|
|
|
def processIncomingFrame(self, data):
|
|
size = len(data)
|
|
for offset in range(max(0, size - 7)):
|
|
if data[offset] != self.SLAVE_ID or data[offset + 1] not in self.REQUESTS:
|
|
continue
|
|
frame = data[offset : offset + 8]
|
|
crc = (frame[6] << 8) | frame[7]
|
|
if not self.check_CRC(frame[:6], crc):
|
|
continue
|
|
try:
|
|
pdu = self.decoder.decode(frame[1:6])
|
|
except Exception: # noqa: BLE001 - 偶发坏帧跳过即可
|
|
continue
|
|
if pdu is None:
|
|
continue
|
|
pdu.dev_id = self.SLAVE_ID
|
|
pdu.transaction_id = 0
|
|
log.debug("RTU 收到请求 dev=%s func=%s", pdu.dev_id, pdu.function_code)
|
|
return offset + 8, pdu
|
|
# 没找到完整请求:丢掉除末尾 7 字节外的数据(末尾可能是一帧的半截)
|
|
return max(0, size - 7), None
|
|
|
|
def encode(self, pdu: bytes, dev_id: int, tid: int) -> bytes:
|
|
frame = super().encode(pdu, dev_id, tid)
|
|
log.debug("RTU 发送应答 dev=%s func=%s len=%d", dev_id, pdu[0] if pdu else -1, len(frame))
|
|
return frame
|
|
|
|
|
|
class SnapshotDeviceContext:
|
|
"""把 StateStore 的寄存器镜像暴露成 pymodbus 设备上下文。
|
|
|
|
与 pymodbus 内置 ModbusSlaveContext 的区别:
|
|
- 不额外做 +1 地址偏移,协议地址 0 直接对应 40001;
|
|
- getValues 一次性加锁复制快照,避免 S331 读到半新半旧的数据。
|
|
"""
|
|
|
|
def __init__(self, store: StateStore, slave_id: int) -> None:
|
|
self._store = store
|
|
self._slave_id = slave_id
|
|
|
|
def decode(self, function_code: int) -> str:
|
|
return _FX_MAPPER.get(function_code, "h")
|
|
|
|
def validate(self, function_code: int, address: int, count: int = 1) -> bool:
|
|
if function_code not in (3, 4, 23):
|
|
return False
|
|
return 0 <= address and count > 0 and address + count <= self._store.register_count
|
|
|
|
def getValues(self, function_code: int, address: int, count: int = 1):
|
|
if function_code not in (3, 4, 23):
|
|
return ILLEGAL_FUNCTION
|
|
values = self._store.read_registers(address, count)
|
|
if values is None:
|
|
return ILLEGAL_DATA_ADDRESS
|
|
return values
|
|
|
|
async def async_getValues(self, function_code: int, address: int, count: int = 1):
|
|
return self.getValues(function_code, address, count)
|
|
|
|
def setValues(self, function_code: int, address: int, values) -> None:
|
|
# 网关数据由采集线程维护,S331 不允许写入
|
|
log.warning(
|
|
"从站 %s 收到写寄存器请求 (功能码=%s 地址=%s),已忽略",
|
|
self._slave_id,
|
|
function_code,
|
|
address,
|
|
)
|
|
return None
|
|
|
|
async def async_setValues(self, function_code: int, address: int, values) -> None:
|
|
self.setValues(function_code, address, values)
|
|
|
|
def reset(self) -> None:
|
|
return None
|
|
|
|
|
|
def build_context(store: StateStore, slave_id: int) -> ModbusServerContext:
|
|
return ModbusServerContext(
|
|
slaves={slave_id: SnapshotDeviceContext(store, slave_id)},
|
|
single=False,
|
|
)
|
|
|
|
|
|
async def run_slaves(
|
|
slaves: Sequence[SlaveCfg],
|
|
store: StateStore,
|
|
stop_event: threading.Event,
|
|
) -> None:
|
|
"""并发启动全部 RTU 从站,直到 stop_event 被置位。"""
|
|
tasks = [asyncio.create_task(_serve_one(cfg, store, stop_event), name=f"rtu-{cfg.name}") for cfg in slaves]
|
|
try:
|
|
while not stop_event.is_set():
|
|
await asyncio.sleep(0.2)
|
|
finally:
|
|
for task in tasks:
|
|
task.cancel()
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
log.info("全部 RTU 从站已停止")
|
|
|
|
|
|
async def _serve_one(cfg: SlaveCfg, store: StateStore, stop_event: threading.Event) -> None:
|
|
"""单个串口的从站循环;串口异常时自动重启,不影响另一个串口。"""
|
|
while not stop_event.is_set():
|
|
server = ModbusSerialServer(
|
|
build_context(store, cfg.slave_id),
|
|
framer=FramerType.RTU,
|
|
port=cfg.port,
|
|
baudrate=cfg.baudrate,
|
|
bytesize=cfg.bytesize,
|
|
parity=cfg.parity,
|
|
stopbits=cfg.stopbits,
|
|
timeout=cfg.timeout_s,
|
|
# 同一条 485 上还有别的从站(S331 自己的流量计 67~75),
|
|
# 对别人的请求必须保持静默,否则会和生产从站抢着应答,撞坏总线
|
|
ignore_missing_slaves=True,
|
|
)
|
|
# 必须在 serve_forever 之前换掉,串口打开时才会用这个类实例化 framer
|
|
SafeRTUFramer.SLAVE_ID = cfg.slave_id
|
|
server.framer = SafeRTUFramer
|
|
try:
|
|
log.info(
|
|
"RTU 从站启动: %s -> %s (slave_id=%s, %s-%s-%s-%s)",
|
|
cfg.name,
|
|
cfg.port,
|
|
cfg.slave_id,
|
|
cfg.baudrate,
|
|
cfg.bytesize,
|
|
cfg.parity,
|
|
cfg.stopbits,
|
|
)
|
|
await server.serve_forever()
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception: # noqa: BLE001 - 串口异常不能拖垮主程序
|
|
log.exception("[%s] 串口 %s 异常,3 秒后重新启动从站", cfg.name, cfg.port)
|
|
await asyncio.sleep(3)
|
|
finally:
|
|
try:
|
|
# 关闭串口传输;pymodbus 内部会自动重连,这里仅在退出时释放资源
|
|
server.close()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
if not stop_event.is_set():
|
|
# serve_forever 正常返回(非退出场景)时稍作等待,避免空转
|
|
await asyncio.sleep(2)
|