Files
yangpengyu 9eaf87ab7d 现场调试版同步: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
2026-11-19 10:59:27 +08:00

172 lines
6.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""把测试数据一次性写入 Modbus Slave (MBSlave) 的寄存器。
原理:MBSlave 是 Modbus TCP 服务端,接受 FC16 (Write Multiple Registers) 写入,
脚本作为主站把寄存器值写进去,MBSlave 窗口立即刷新,无需手动逐格输入。
用法:
python tools/write_mbslave.py
写入全部 3 台设备的所有点位(会先清零窗口范围,再写入点位值,
同时自动修正之前填错的单元格)
python tools/write_mbslave.py --device s331_2 --addr 130 --value 1345600 --type uint32
单点修改(用于模拟累计气量/电量增长,测试小时/天/月气电比)
前提:MBSlave 各窗口已 Connection -> Connect,监听端口:
ID=1 -> 1502 (mogo_meter 电表)
ID=10 -> 502 (s331_1)
ID=20 -> 503 (s331_2)
"""
from __future__ import annotations
import argparse
import struct
import sys
from pymodbus.client import ModbusTcpClient
HOST = "127.0.0.1"
# (地址, 类型, 原始值) —— 原始值 = 电表工程值/scale,与 gen_test_data.py 完全一致
# 电表: 功率 raw=eng*1000 (scale 0.001), 电能 raw=eng*10 (scale 0.1)
DEVICES = {
"mogo_meter": {
"port": 1502, "slave": 1,
"zero": (149, 218), # 清零范围,覆盖全部点位和误填的 217/218
"points": [
(149, "float32", 15500.0), # 3# 功率 15.5 kW
(151, "float32", 123456.7), # 3# 电能 12345.67 kWh
(157, "float32", 12300.0), # 4# 功率 12.3 kW
(159, "float32", 98765.4), # 4# 电能 9876.54 kWh
(165, "float32", 18000.0), # 5# 功率 18.0 kW
(167, "float32", 150000.0), # 5# 电能 15000.0 kWh
(173, "float32", 9800.0), # 6# 功率 9.8 kW
(175, "float32", 76543.2), # 6# 电能 7654.32 kWh
(181, "float32", 20100.0), # 7# 功率 20.1 kW
(183, "float32", 187654.3), # 7# 电能 18765.43 kWh
(189, "float32", 11200.0), # 8# 功率 11.2 kW
(191, "float32", 87651.0), # 8# 电能 8765.1 kWh
(213, "float32", 16700.0), # 9# 功率 16.7 kW
(215, "float32", 132102.0), # 9# 电能 13210.2 kWh
(205, "float32", 13400.0), # 10# 功率 13.4 kW
(207, "float32", 108905.5), # 10# 电能 10890.55 kWh
(197, "float32", 14800.0), # 11# 功率 14.8 kW
(199, "float32", 115558.8), # 11# 电能 11555.88 kWh
],
},
"s331_1": {
"port": 502, "slave": 10,
"zero": (110, 146),
"points": [
(112, "float32", 80.5), # 3# 瞬时流量 m³/h
(114, "uint32", 1234567), # 3# 累计气量 m³
(122, "float32", 95.2), # 4#
(124, "uint32", 1089000),
(132, "float32", 70.8), # 5#
(134, "uint32", 1567800),
(142, "float32", 88.1), # 11#
(144, "uint32", 987654),
],
},
"s331_2": {
"port": 503, "slave": 20,
"zero": (110, 162),
"points": [
(118, "float32", 65.0), # 6#
(120, "uint32", 1678900),
(128, "float32", 92.3), # 7#(含之前填错的 129/131,此处自动修正)
(130, "uint32", 1345600),
(138, "float32", 78.4), # 8#
(140, "uint32", 1200000),
(148, "float32", 100.0), # 9#
(150, "uint32", 1800000),
(158, "float32", 85.6), # 10#
(160, "uint32", 1450000),
],
},
}
def encode(value: float, dtype: str) -> list[int]:
"""按 ABCD 字序(高字在前)编码为 2 个 16 位寄存器。"""
if dtype == "float32":
hi, lo = struct.unpack(">HH", struct.pack(">f", float(value)))
elif dtype == "uint32":
iv = int(value)
if not 0 <= iv < 2**32:
raise ValueError(f"uint32 溢出: {iv}")
hi, lo = struct.unpack(">HH", struct.pack(">I", iv))
else:
raise ValueError(f"未知类型: {dtype}")
return [hi, lo]
def write_full() -> int:
failed = 0
for name, dev in DEVICES.items():
client = ModbusTcpClient(HOST, port=dev["port"], timeout=3)
if not client.connect():
print(f"[{name}] ❌ 连不上 127.0.0.1:{dev['port']},请确认 MBSlave 该窗口已 Connection -> Connect 且端口为 {dev['port']}")
failed += 1
continue
try:
z0, z1 = dev["zero"]
span = z1 - z0 + 1
rr = client.write_registers(z0, [0] * span, slave=dev["slave"])
if rr.isError():
print(f"[{name}] ❌ 清零 {z0}~{z1} 失败: {rr}")
failed += 1
continue
ok = 0
for addr, dtype, value in dev["points"]:
rr = client.write_registers(addr, encode(value, dtype), slave=dev["slave"])
if rr.isError():
print(f"[{name}] ❌ 写 {addr} 失败: {rr}")
failed += 1
else:
ok += 1
print(f"[{name}] ✅ 端口 {dev['port']} slave {dev['slave']}:清零 {z0}~{z1},写入 {ok}/{len(dev['points'])} 个点位")
finally:
client.close()
return failed
def write_single(device: str, addr: int, value: float, dtype: str) -> int:
dev = DEVICES[device]
client = ModbusTcpClient(HOST, port=dev["port"], timeout=3)
if not client.connect():
print(f"❌ 连不上 127.0.0.1:{dev['port']},请确认 MBSlave 已 Connect")
return 1
try:
regs = encode(value, dtype)
rr = client.write_registers(addr, regs, slave=dev["slave"])
if rr.isError():
print(f"❌ 写入失败: {rr}")
return 1
back = client.read_holding_registers(addr, count=2, slave=dev["slave"])
print(f"[{device}] ✅ 地址 {addr} <- {value} ({dtype}) 寄存器=[{regs[0]}, {regs[1]}]"
f" hex=[0x{regs[0]:04X}, 0x{regs[1]:04X}],回读={back.registers}")
return 0
finally:
client.close()
def main() -> int:
ap = argparse.ArgumentParser(description="向 MBSlave 写入测试数据")
ap.add_argument("--device", choices=list(DEVICES), help="只写指定设备")
ap.add_argument("--addr", type=int, help="单点写入的起始地址")
ap.add_argument("--value", type=float, help="单点写入的原始值")
ap.add_argument("--type", choices=("float32", "uint32"), default="float32", help="单点数据类型")
args = ap.parse_args()
if args.device and args.addr is not None and args.value is not None:
return write_single(args.device, args.addr, args.value, args.type)
if args.device or args.addr is not None or args.value is not None:
ap.error("单点模式需要同时给出 --device --addr --value(--type 可选);全量模式不带任何参数")
return write_full()
if __name__ == "__main__":
sys.exit(main())