现场调试版同步: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:
yangpengyu authored and trae-solo-agent committed 2026-11-19 10:59:27 +08:00
commit 9eaf87ab7d
43 files changed
+4514

No files matched your search

+244
View File
@@ -0,0 +1,244 @@
"""从 config.yaml 自动抽取完整寄存器映射表。
输出三部分:
表 A — 采集侧(蘑菇云电表)
表 B — 采集侧(希尔思 S331 气量)—— 气量地址为占位,标注
表 C — 输出侧(网关 RTU 从站,暴露给 S331 读取)
两种基址同时给出:协议地址(0 基,S4C/S331 填)、Modbus 4xxxx 显示地址(1 基,文档展示)。
"""
from __future__ import annotations
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))
from gateway.config import load_config # noqa: E402
def addr(zero_base: int) -> tuple[str, str]:
"""返回 (协议地址 0 基, 4xxxx 显示地址 1 基)。"""
return f"{zero_base}", f"4{zero_base + 1:04d}"
def fmt1(start: int, end: int) -> str:
"""一段寄存器的 4xxxx 显示地址区间。"""
return f"4{start + 1:04d}~4{end + 1:04d}"
def main() -> str:
cfg = load_config(ROOT / "config" / "config.yaml")
meter_devices = {name: d for name, d in cfg.devices.items() if name.startswith("mogo")}
s331_devices = {name: d for name, d in cfg.devices.items() if name.startswith("s331")}
# ------------------------- 表 A:蘑菇云电表 -------------------------
a_rows = []
for c in cfg.compressors:
meter = cfg.devices[c.meter]
row = {
"id": c.id,
"name": c.name,
"device": c.meter,
"host": meter.host,
"port": meter.port,
"slave": meter.slave_id,
}
for field, label in [("power_instant", "有功功率 kW"), ("energy_total", "有功电能 kWh")]:
p = getattr(c, field)
a_rows.append(
{
**row,
"signal": label,
"type": p.type,
"word_order": p.word_order,
"scale": str(p.scale),
"offset": str(p.offset),
"address_0": addr(p.address)[0],
"address_1": addr(p.address)[1],
"width": p.width,
}
)
# ------------------------- 表 B:S331 气量 -------------------------
b_rows = []
for c in cfg.compressors:
s331 = cfg.devices[c.s331]
for field, label in [("flow_instant", "瞬时流量 m³/min"), ("flow_total", "累计气量 m³")]:
p = getattr(c, field)
b_rows.append(
{
"id": c.id,
"name": c.name,
"device": c.s331,
"host": s331.host,
"port": s331.port,
"slave": s331.slave_id,
"signal": label,
"type": p.type,
"word_order": p.word_order,
"scale": str(p.scale),
"offset": str(p.offset),
"address_0": addr(p.address)[0],
"address_1": addr(p.address)[1],
"width": p.width,
}
)
# ------------------------- 表 C:RTU 从站输出 -------------------------
ratio_names = ["瞬时气电比", "小时气电比", "天气电比", "月气电比"]
c_rows = []
for c in cfg.compressors:
base = c.register_index * 8
for ratio_i, ratio_label in enumerate(ratio_names):
start = base + ratio_i * 2
end = start + 1
c_rows.append(
{
"id": c.id,
"name": c.name,
"ratio": ratio_label,
"register_index": c.register_index,
"device_s331": c.s331,
"address_0": addr(start)[0],
"address_0_range": f"{start}~{end}",
"address_1": addr(start)[1],
"address_1_range": fmt1(start, end),
"type": "Float32 (ABCD)",
"width": 2,
}
)
out = [
"# 边缘网关完整寄存器映射表(V3.2 蘑菇云 + S331)",
"",
"## 约定",
"- 协议地址(0 基)= S4C-Display / Modbus Poll 填写值,**不要勾 Base 1**",
"- 4xxxx 显示地址(1 基)= 文档展示,实际协议通信仍用 0 基",
"- Float32 占用 2 个保持寄存器(两个 16-bit word)",
"- 网关 RTU 从站:slave_id=10 接 /dev/ttyS1 给 S331 #1;slave_id=20 接 /dev/ttyS2 给 S331 #2",
f"- 网关 RTU 输出 Float 字序: {cfg.register_float_order}(ABCD = 高字在前)",
"",
"## 表 A — 采集侧:蘑菇云电表(Modbus TCP 10.50.253.165:1502 slave_id=1)",
"",
"| 空压机 | 信号 | 类型 | 字序 | scale | offset | 协议地址(0基) | 显示地址(4xxxx) |",
"|-------|------|------|------|-------|--------|--------------|----------------|",
]
for r in a_rows:
out.append(
f"| {r['id']:>2}# | {r['signal']} | {r['type']} | {r['word_order']} | "
f"×{r['scale']} | +{r['offset']} | **{r['address_0']}** | {r['address_1']} |"
)
out += [
"",
"## 表 B — 采集侧:希尔思 S331 气量(IP 待现场分配,当前为占位示例)",
"",
"⚠️ 重要:下表中 S331 的气量地址是**占位示例**,上线前必须用 probe.py 直连 S331 核对实际地址后替换 config.yaml。",
"",
"| 空压机 | 来源 | 信号 | 类型 | 字序 | 协议地址(0基) | 显示地址(4xxxx) |",
"|-------|------|------|------|------|--------------|----------------|",
]
for r in b_rows:
out.append(
f"| {r['id']:>2}# | {r['device']} ({r['host']}) | {r['signal']} | "
f"{r['type']} | {r['word_order']} | **{r['address_0']}** | {r['address_1']} |"
)
out += [
"",
"## 表 C — 输出侧:网关 RTU 从站(供 S331 通过 /dev/ttyS1 + /dev/ttyS2 读取)",
"",
"- RTU 从站 #1:slave_id=10,/dev/ttyS1 → S331 #1",
"- RTU 从站 #2:slave_id=20,/dev/ttyS2 → S331 #2",
"- 两个从站暴露**完全相同**的寄存器镜像(S331 可读到全部 9 台机器)",
"- 仅响应 FC03/FC04(读保持/输入寄存器),写请求一律拒绝",
"",
"| 空压机 | 寄存器索引 | 气电比 | 协议地址(0基) | 显示地址(4xxxx) | 数据类型 |",
"|-------|-----------|--------|--------------|----------------|----------|",
]
for r in c_rows:
out.append(
f"| {r['id']:>2}# | {r['register_index']} | {r['ratio']} | **{r['address_0_range']}** | "
f"{r['address_1_range']} | {r['type']} |"
)
# ------------------------- 附加:按 4xxxx 连续列出 -------------------------
out += [
"",
"## 表 C-展开:从 40001 起顺序列出全部寄存器",
"",
"| 显示地址 | 协议地址 | 空压机 | 气电比 | 数据类型 |",
"|----------|----------|-------|--------|----------|",
]
# 按协议地址排序
c_sorted = sorted(c_rows, key=lambda r: int(r["address_0"]))
for r in c_sorted:
out.append(
f"| {r['address_1_range']} | {r['address_0_range']} | "
f"{r['id']:>2}# | {r['ratio']} | {r['type']} |"
)
out += [
"",
"## 按设备的连续采集块规划(减少 TCP 请求次数)",
"",
"### 蘑菇云电表 — 网关一次请求覆盖全部点位:",
]
# 找出蘑菇云所有点位的 span
mogo_points = []
for c in cfg.compressors:
if c.meter == "mogo_meter":
for field in ("power_instant", "energy_total"):
p = getattr(c, field)
mogo_points.append((p.address, p.address + p.width, c.id, field))
mogo_points.sort()
span_start = mogo_points[0][0]
span_end = max(e for _, e, _, _ in mogo_points)
out.append(
f"- 蘑菇云电表:地址 {span_start} ~ {span_end - 1} 共 {span_end - span_start} 个寄存器,"
f"一次 Read Holding Registers 即可读完 9 台机器的功率+电能(仅约 0.2s)"
)
out += [""]
for s331_name in ("s331_1", "s331_2"):
s331_points = []
for c in cfg.compressors:
if c.s331 == s331_name:
for field in ("flow_instant", "flow_total"):
p = getattr(c, field)
s331_points.append((p.address, p.address + p.width, c.id, field))
if not s331_points:
continue
s331_points.sort()
sp = s331_points[0][0]
ep = max(e for _, e, _, _ in s331_points)
out.append(
f"### {s331_name} 气量 — 地址 {sp} ~ {ep - 1} 共 {ep - sp} 个寄存器,一次请求可读完"
)
out += [
"",
"## S4C-Display 侧配置要点(给现场工程师)",
"- 新增设备:Modbus RTU,地址 10 接 /dev/ttyS1 链路 → 读取网关",
"- 新增设备:Modbus RTU,地址 20 接 /dev/ttyS2 链路 → 读取网关",
"- 值地址填协议地址 0 基(0、2、4、6…),**千万不要勾 Base 1**",
"- 数据类型选 FLOAT",
"",
"---",
f"自动生成自 config/config.yaml(compressors={len(cfg.compressors)}, slaves={len(cfg.slaves)})",
]
return "\n".join(out)
if __name__ == "__main__":
text = main()
print(text)
out_path = ROOT / "docs" / "register_map.md"
out_path.parent.mkdir(exist_ok=True)
out_path.write_text(text, encoding="utf-8")
print(f"\n已写入: {out_path}")
+262
View File
@@ -0,0 +1,262 @@
"""生成 Modbus Poll / MBS Slave 可直接填写的测试数据表。
输出 3 份 CSV + 1 份 Markdown 汇总表:
- data_mogo_meter.csv (电表,slave=1, port=1502)
- data_s331_1.csv (S331 #1 气量, slave=10, port=502)
- data_s331_2.csv (S331 #2 气量, slave=20, port=503)
- test_data_summary.md (寄存器地址完整对照表)
CSV 列含义:
s4c_addr — Modbus Poll / MBS Slave 里的 S4C 地址(40001 基)
proto_addr — Modbus 协议地址(0 基,即 config.yaml 里的 address)
reg_lo — ABCD 字序的低字寄存器值(16-bit,十进制)
reg_hi — ABCD 字序的高字寄存器值(16-bit,十进制)
hex_lo — reg_lo 的 16 进制
hex_hi — reg_hi 的 16 进制
type — float32 / uint32
scale — 工程值 = 原始值 × scale
raw_value — 原始值(写入 Modbus 的值)
eng_value — 工程值(实际物理量)
unit — 单位
note — 说明
用法:在 Modbus Poll 的 Connection → Setup → Define 里新建 Connection,
Slave 地址按 slave_id 填,然后在 Setup → Read/Write Definition
里按 CSV 的 s4c_addr 和数量建窗口;数据填入 Holding Register。
"""
from __future__ import annotations
import csv
import os
import struct
from pathlib import Path
# ---------- 数据编码 ----------
def enc_float32_abcd(raw: float) -> tuple[int, int]:
"""float32 按 ABCD 字序拆成两个 16-bit 寄存器(高字在前)。"""
hi, lo = struct.unpack(">HH", struct.pack(">f", raw))
return hi, lo # ABCD = [hi, lo] 即 40001=hi, 40002=lo
def enc_uint32_abcd(raw: int) -> tuple[int, int]:
"""uint32 按 ABCD 字序拆成两个 16-bit 寄存器。"""
if raw < 0 or raw >= 2**32:
raise ValueError(f"uint32 溢出: {raw}")
hi, lo = struct.unpack(">HH", struct.pack(">I", raw))
return hi, lo # ABCD = [hi, lo]
# ---------- 点表定义(与 config.yaml 完全对齐)----------
# 蘑菇云电表 slave_id=1
# 功率: float32 ABCD, scale=0.001 → raw = eng / 0.001 = eng * 1000
# 电能: float32 ABCD, scale=0.1 → raw = eng / 0.1 = eng * 10
mogo_points = [
# (comp_id, point_name, proto_addr, type, scale, eng_value, unit)
(3, "功率", 149, "float32", 0.001, 15.5, "kW"),
(3, "电能", 151, "float32", 0.1, 12345.67,"kWh"),
(4, "功率", 157, "float32", 0.001, 12.3, "kW"),
(4, "电能", 159, "float32", 0.1, 9876.54, "kWh"),
(5, "功率", 165, "float32", 0.001, 18.0, "kW"),
(5, "电能", 167, "float32", 0.1, 15000.00, "kWh"),
(6, "功率", 173, "float32", 0.001, 9.8, "kW"),
(6, "电能", 175, "float32", 0.1, 7654.32, "kWh"),
(7, "功率", 181, "float32", 0.001, 20.1, "kW"),
(7, "电能", 183, "float32", 0.1, 18765.43, "kWh"),
(8, "功率", 189, "float32", 0.001, 11.2, "kW"),
(8, "电能", 191, "float32", 0.1, 8765.10, "kWh"),
(9, "功率", 213, "float32", 0.001, 16.7, "kW"),
(9, "电能", 215, "float32", 0.1, 13210.20, "kWh"),
(10, "功率", 205, "float32", 0.001, 13.4, "kW"),
(10, "电能", 207, "float32", 0.1, 10890.55, "kWh"),
(11, "功率", 197, "float32", 0.001, 14.8, "kW"),
(11, "电能", 199, "float32", 0.1, 11555.88, "kWh"),
]
# S331 #1 slave_id=10 负责 3/4/5/11
# 瞬时流量: float32 ABCD, scale=1 → raw = eng
# 累计气量: uint32 ABCD, scale=1 → raw = eng
s331_1_points = [
(3, "瞬时流量", 112, "float32", 1, 80.5, "m³/h"),
(3, "累计气量", 114, "uint32", 1, 1234567, "m³"),
(4, "瞬时流量", 122, "float32", 1, 95.2, "m³/h"),
(4, "累计气量", 124, "uint32", 1, 1089000, "m³"),
(5, "瞬时流量", 132, "float32", 1, 70.8, "m³/h"),
(5, "累计气量", 134, "uint32", 1, 1567800, "m³"),
(11, "瞬时流量", 142, "float32", 1, 88.1, "m³/h"),
(11, "累计气量", 144, "uint32", 1, 987654, "m³"),
]
# S331 #2 slave_id=20 负责 6/7/8/9/10
s331_2_points = [
(6, "瞬时流量", 118, "float32", 1, 65.0, "m³/h"),
(6, "累计气量", 120, "uint32", 1, 1678900, "m³"),
(7, "瞬时流量", 128, "float32", 1, 92.3, "m³/h"),
(7, "累计气量", 130, "uint32", 1, 1345600, "m³"),
(8, "瞬时流量", 138, "float32", 1, 78.4, "m³/h"),
(8, "累计气量", 140, "uint32", 1, 1200000, "m³"),
(9, "瞬时流量", 148, "float32", 1, 100.0, "m³/h"),
(9, "累计气量", 150, "uint32", 1, 1800000, "m³"),
(10, "瞬时流量", 158, "float32", 1, 85.6, "m³/h"),
(10, "累计气量", 160, "uint32", 1, 1450000, "m³"),
]
# ---------- 编码 & 导出 ----------
def build_rows(points: list) -> list[dict]:
rows = []
for comp_id, name, proto_addr, dtype, scale, eng_value, unit in points:
raw_value = eng_value / scale if scale != 0 else eng_value
if dtype == "float32":
hi, lo = enc_float32_abcd(float(raw_value))
elif dtype == "uint32":
hi, lo = enc_uint32_abcd(int(raw_value))
else:
raise ValueError(f"unknown type: {dtype}")
s4c_addr = proto_addr + 40001 # S4C 显示地址(协议地址 0 → 40001)
rows.append({
"comp_id": comp_id,
"name": f"{comp_id}#{name}",
"s4c_addr": s4c_addr,
"proto_addr": proto_addr,
"reg_hi": hi,
"reg_lo": lo,
"hex_hi": f"0x{hi:04X}",
"hex_lo": f"0x{lo:04X}",
"type": dtype,
"scale": scale,
"raw_value": raw_value,
"eng_value": eng_value,
"unit": unit,
"note": f"工程值={eng_value}{unit}, scale={scale}, 原始值={raw_value}",
})
return rows
def write_csv(path: str, rows: list[dict]) -> None:
fields = ["comp_id", "name", "s4c_addr", "proto_addr",
"reg_hi", "reg_lo", "hex_hi", "hex_lo",
"type", "scale", "raw_value", "eng_value", "unit", "note"]
with open(path, "w", newline="", encoding="utf-8-sig") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in rows:
w.writerow(r)
def write_markdown(path: str,
mogo: list[dict],
s331_1: list[dict],
s331_2: list[dict]) -> None:
with open(path, "w", encoding="utf-8") as f:
f.write("# Modbus Poll / MBS Slave 测试数据对照表\n\n")
f.write("生成时间:2026-11-17 \n")
f.write("**重要**:表格中的 `reg_hi` / `reg_lo` 和 `hex_hi` / `hex_lo` 是**原始值**,\n")
f.write("直接填入 Modbus Poll / MBS Slave 的 Holding Register 即可。\n")
f.write("`scale` 表示:网关内部工程值 = 原始值 × scale。\n\n")
# ---------- 设备 1:蘑菇云电表 ----------
f.write("---\n\n")
f.write("## 设备 1:蘑菇云电表 Modbus TCP Server\n\n")
f.write("| 项目 | 值 |\n|---|---|\n")
f.write("| Connection | Modbus TCP |\n")
f.write("| Host | 192.168.1.253(测试)/ 10.50.253.165(现场) |\n")
f.write("| Port | 1502 |\n")
f.write("| Slave ID | 1 |\n")
f.write("| Function Code | 03 (Read Holding Registers) |\n")
f.write("| 寄存器窗口 | 40149 ~ 40216(连续一段) |\n\n")
f.write("### 数据值\n\n")
f.write("| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |\n")
f.write("|---|---|---|---|---|---|---|---|---|---|---|---|\n")
for r in mogo:
f.write(f"| {r['comp_id']}# | {r['name'].split('#',1)[1]} | {r['proto_addr']} | {r['s4c_addr']} | "
f"{r['reg_hi']} | {r['reg_lo']} | {r['hex_hi']} | {r['hex_lo']} | "
f"{r['type']} | {r['scale']} | {r['eng_value']} | {r['unit']} |\n")
# ---------- 设备 2:S331 #1 ----------
f.write("\n---\n\n")
f.write("## 设备 2:希尔思 S331 #1 Modbus TCP Server(负责 3/4/5/11)\n\n")
f.write("| 项目 | 值 |\n|---|---|\n")
f.write("| Connection | Modbus TCP |\n")
f.write("| Host | 192.168.1.253(测试)/ 10.50.253.181(现场) |\n")
f.write("| Port | 502 |\n")
f.write("| Slave ID | 10 |\n")
f.write("| Function Code | 03 |\n")
f.write("| 寄存器窗口 | 40113 ~ 40145(连续一段) |\n\n")
f.write("### 数据值\n\n")
f.write("| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |\n")
f.write("|---|---|---|---|---|---|---|---|---|---|---|---|\n")
for r in s331_1:
f.write(f"| {r['comp_id']}# | {r['name'].split('#',1)[1]} | {r['proto_addr']} | {r['s4c_addr']} | "
f"{r['reg_hi']} | {r['reg_lo']} | {r['hex_hi']} | {r['hex_lo']} | "
f"{r['type']} | {r['scale']} | {r['eng_value']} | {r['unit']} |\n")
# ---------- 设备 3:S331 #2 ----------
f.write("\n---\n\n")
f.write("## 设备 3:希尔思 S331 #2 Modbus TCP Server(负责 6/7/8/9/10)\n\n")
f.write("| 项目 | 值 |\n|---|---|\n")
f.write("| Connection | Modbus TCP |\n")
f.write("| Host | 192.168.1.253(测试)/ 10.50.253.182(现场) |\n")
f.write("| Port | 503(测试)/ 502(现场) |\n")
f.write("| Slave ID | 20 |\n")
f.write("| Function Code | 03 |\n")
f.write("| 寄存器窗口 | 40119 ~ 40161(连续一段) |\n\n")
f.write("### 数据值\n\n")
f.write("| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |\n")
f.write("|---|---|---|---|---|---|---|---|---|---|---|---|\n")
for r in s331_2:
f.write(f"| {r['comp_id']}# | {r['name'].split('#',1)[1]} | {r['proto_addr']} | {r['s4c_addr']} | "
f"{r['reg_hi']} | {r['reg_lo']} | {r['hex_hi']} | {r['hex_lo']} | "
f"{r['type']} | {r['scale']} | {r['eng_value']} | {r['unit']} |\n")
# ---------- 快速校验 ----------
f.write("\n---\n\n")
f.write("## 快速校验样例\n\n")
f.write("如果网关采集正常,`journalctl -u hx-gateway -n 30` 应该看到类似:\n\n")
f.write("```\n")
f.write("状态 3#空压机 瞬时=0.1925 时=0.0000 日=0.0000 月=0.0000 | 瞬时流量=80.5 累计气量=1234567.0 瞬时功率=15.5 累计电量=12345.7 | 数据延迟=1s\n")
f.write("```\n\n")
f.write("气电比计算:\n\n")
f.write("```\n")
f.write("瞬时气电比 = 功率(kW) / 流量(m³/h)\n")
f.write("3#: 15.5 / 80.5 = 0.1925\n")
f.write("```\n")
def main():
out = Path(r"c:\Users\admin\Desktop\海信视像数采\chengxu\tools\test_data")
out.mkdir(parents=True, exist_ok=True)
mogo = build_rows(mogo_points)
s331_1 = build_rows(s331_1_points)
s331_2 = build_rows(s331_2_points)
write_csv(str(out / "data_mogo_meter.csv"), mogo)
write_csv(str(out / "data_s331_1.csv"), s331_1)
write_csv(str(out / "data_s331_2.csv"), s331_2)
write_markdown(str(out / "test_data_summary.md"), mogo, s331_1, s331_2)
print("✅ 已生成:")
print(f" {out / 'data_mogo_meter.csv'} (电表 slave=1)")
print(f" {out / 'data_s331_1.csv'} (S331 #1 slave=10)")
print(f" {out / 'data_s331_2.csv'} (S331 #2 slave=20)")
print(f" {out / 'test_data_summary.md'} (完整对照表)")
print()
# 终端预览
for title, rows in [("蘑菇云电表", mogo), ("S331 #1", s331_1), ("S331 #2", s331_2)]:
print(f"=== {title} ===")
print(f"{'点':<10} {'S4C':>6} {'proto':>5} {'type':<8} {'scale':>5} "
f"{'raw':>12} {'eng':>10} {'unit':<6} hex=[hi,lo]")
for r in rows:
print(f"{r['name']:<10} {r['s4c_addr']:>6} {r['proto_addr']:>5} {r['type']:<8} "
f"{r['scale']:>5} {str(r['raw_value']):>12} {r['eng_value']:>10} {r['unit']:<6} "
f"[{r['hex_hi']}, {r['hex_lo']}]")
print()
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
"""Mock Modbus TCP 服务器集群(单进程 asyncio 并发)。
启动后同时跑 3 个 Modbus TCP Server,完全模拟 V3.3 的蘑菇云 + 2 台 S331:
- mogo_meter : 0.0.0.0:1502 slave_id=1 (电表,9 台机器功率+电能)
- s331_1 : 0.0.0.0:502 slave_id=10 (气量,3/4/5/11 瞬时+累计)
- s331_2 : 0.0.0.0:503 slave_id=20 (气量,6/7/8/9/10 瞬时+累计)
Windows / Linux / Mac 通吃,不需要 multiprocessing。
"""
from __future__ import annotations
import argparse
import asyncio
import struct
import time
try:
from pymodbus.datastore import ModbusServerContext, ModbusSlaveContext, ModbusSequentialDataBlock
from pymodbus.server import StartAsyncTcpServer
except ImportError as e:
raise SystemExit(f"pymodbus 导入失败:{e}\n请先:pip install pymodbus")
# ------------------------- 编码 -------------------------
def _enc_float32(value: float) -> list[int]:
return list(struct.unpack(">HH", struct.pack(">f", value)))
def _enc_uint32(value: int) -> list[int]:
if not (0 <= value < 2**32):
raise ValueError(f"uint32 溢出: {value}")
return list(struct.unpack(">HH", struct.pack(">I", value)))
def _make_ctx(regs: dict[int, list[int]], slave_id: int) -> ModbusServerContext:
"""构造 pymodbus 3.x 的 TCP Server Context。
重要:pymodbus 3.x ModbusSlaveContext 内部有两个行为需要适配:
a) 必须同时传 di/co/ir/hr 四个 block(di=None 会导致其他 store 被重置)
b) getValues 内部做了 address += 1 偏移
→ 协议地址 N 的数据必须写入 block index N+1
→ 构造 block 时让起始地址 = 0,但写入时统一 addr+1
"""
# 留足够空间(协议地址最大 215 + 8 → block index 224)
capacity = max(1024, max(regs.keys()) + 16)
data = [0] * capacity # index 0 永远空着(供 address+=1 对齐)
for addr, words in regs.items():
# 协议地址 addr → 写入 block index addr+1(适配内部 address += 1)
idx = addr + 1
if idx + len(words) > capacity:
raise ValueError(f"寄存器 {addr} 越界")
data[idx : idx + len(words)] = words
# 4 种 store 都指向同一个 block(满足 di!=None 的要求)
block = ModbusSequentialDataBlock(0, data)
slave = ModbusSlaveContext(di=block, co=block, ir=block, hr=block)
return ModbusServerContext(slaves={slave_id: slave}, single=False)
# ------------------------- 构造数据 -------------------------
def build_mogo_regs() -> dict[int, list[int]]:
points = [(3, 149, 151, 15.5, 12345.67),
(4, 157, 159, 12.3, 9876.54),
(5, 165, 167, 18.0, 15000.00),
(6, 173, 175, 9.8, 7654.32),
(7, 181, 183, 20.1, 18765.43),
(8, 189, 191, 11.2, 8765.10),
(9, 213, 215, 16.7, 13210.20),
(10, 205, 207, 13.4, 10890.55),
(11, 197, 199, 14.8, 11555.88)]
regs: dict[int, list[int]] = {}
for _id, pa, ea, pw, en in points:
# 点表使用工程值;mock 按 config.yaml 的 scale 反算为电表原始值。
regs[pa] = _enc_float32(pw * 1000)
regs[ea] = _enc_float32(en * 10)
return regs
def build_s331_1_regs() -> dict[int, list[int]]:
points = [(3, 112, 114, 80.5, 1_234_567),
(4, 122, 124, 95.2, 1_089_000),
(5, 132, 134, 70.8, 1_567_800),
(11, 142, 144, 88.1, 987_654)]
regs: dict[int, list[int]] = {}
for _id, fa, ta, fl, tt in points:
regs[fa] = _enc_float32(fl)
regs[ta] = _enc_uint32(tt)
return regs
def build_s331_2_regs() -> dict[int, list[int]]:
points = [(6, 118, 120, 65.0, 1_678_900),
(7, 128, 130, 92.3, 1_345_600),
(8, 138, 140, 78.4, 1_200_000),
(9, 148, 150, 100.0, 1_800_000),
(10, 158, 160, 85.6, 1_450_000)]
regs: dict[int, list[int]] = {}
for _id, fa, ta, fl, tt in points:
regs[fa] = _enc_float32(fl)
regs[ta] = _enc_uint32(tt)
return regs
# ------------------------- 主入口 -------------------------
async def _serve_one(host: str, port: int, slave_id: int, regs: dict[int, list[int]], label: str):
ctx = _make_ctx(regs, slave_id)
print(f" [{label}] TCP Server -> {host}:{port} slave_id={slave_id} "
f"(regs {min(regs.keys())}~{max(regs.keys())+1})", flush=True)
await StartAsyncTcpServer(ctx, address=(host, port))
async def _serve_all(host: str, ports: dict[str, int]):
jobs = [
_serve_one(host, ports["mogo"], 1, build_mogo_regs(), "mogo_meter"),
_serve_one(host, ports["s331_1"], 10, build_s331_1_regs(), "s331_1"),
_serve_one(host, ports["s331_2"], 20, build_s331_2_regs(), "s331_2"),
]
await asyncio.gather(*jobs)
def main():
parser = argparse.ArgumentParser(description="V3.3 Mock TCP 数据源集群")
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--mogo-port", type=int, default=1502)
parser.add_argument("--s331-1-port", type=int, default=502)
parser.add_argument("--s331-2-port", type=int, default=503)
args = parser.parse_args()
print("=" * 62)
print(" V3.3 Mock TCP 数据源集群")
print("=" * 62)
print(f" mogo_meter : {args.host}:{args.mogo_port} slave=1 (9台电表)")
print(f" s331_1 : {args.host}:{args.s331_1_port} slave=10 (3/4/5/11)")
print(f" s331_2 : {args.host}:{args.s331_2_port} slave=20 (6/7/8/9/10)")
print("=" * 62, flush=True)
try:
asyncio.run(_serve_all(args.host, {
"mogo": args.mogo_port,
"s331_1": args.s331_1_port,
"s331_2": args.s331_2_port,
}))
except KeyboardInterrupt:
print("\n已停止。")
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
"""在 COM4 上用不同帧格式探测从站 10,定位 Modbus Poll 参数差异。
对角线实验:N/E/O 校验 × 1/2 停止位。"""
from pymodbus.client import ModbusSerialClient
for parity, stopbits in (("N", 1), ("E", 1), ("O", 1), ("N", 2)):
client = ModbusSerialClient(
port="COM4", baudrate=19200, bytesize=8, parity=parity, stopbits=stopbits, timeout=0.8,
)
try:
ok = client.connect()
if not ok:
print(f"8-{parity}-1 stop{stopbits}: 打开失败")
continue
rr = client.read_holding_registers(0, count=8, slave=10)
if rr.isError():
print(f"8-{parity}-{stopbits}: 异常响应")
else:
print(f"8-{parity}-{stopbits}: OK 寄存器0~7={rr.registers[:4]}...")
except Exception as e: # noqa: BLE001
print(f"8-{parity}-{stopbits}: 无响应 ({type(e).__name__})")
finally:
client.close()
+25
View File
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""从 PC 侧用 RTU 主站探测两个 USB-485 口,确定哪只适配器接到了网关。"""
import sys
from pymodbus.client import ModbusSerialClient
for port in ("COM4", "COM5"):
client = ModbusSerialClient(port=port, baudrate=19200, bytesize=8, parity="N", stopbits=1, timeout=1.0)
try:
if not client.connect():
print(f"{port}: 打开失败(可能被其他程序占用)")
continue
for slave in (10, 20):
try:
rr = client.read_holding_registers(0, count=8, slave=slave)
if rr.isError():
print(f"{port} slave={slave}: 异常响应 {rr}")
else:
regs = rr.registers
print(f"{port} slave={slave}: OK 寄存器0~7={regs}")
except Exception as e: # noqa: BLE001
print(f"{port} slave={slave}: 超时/无响应 ({type(e).__name__})")
client.close()
except Exception as e: # noqa: BLE001
print(f"{port}: 串口错误 {e}")
+128
View File
@@ -0,0 +1,128 @@
"""RTU 主站测试:连网关 RS-485 串口读寄存器,验证 V3.3 寄存器映射。
用法示例(PC 端,Windows/Mac/Linux 都可):
# 读 slave_id=10(/dev/ttyS1 链路),全部 9 台机器
python tools/rtu_client_test.py --port COM3 --slave 10
# 同时读两个从站,验证并发
python tools/rtu_client_test.py --port COM3 --slave 10,20
需要先装:pip install pymodbus pyserial
"""
from __future__ import annotations
import argparse
import struct
import sys
import time
from typing import Sequence
try:
from pymodbus.client import ModbusSerialClient
except ImportError as e:
raise SystemExit(f"请先安装依赖:pip install pymodbus pyserial\n原始错误:{e}")
def _decode_float32_two_registers(words: list[int], order: str = "ABCD") -> float:
"""两个 16-bit 寄存器 -> float32,ABCD 高字在前(即 order='big')。"""
if order.upper() == "ABCD":
packed = struct.pack(">HH", words[0], words[1])
elif order.upper() == "CDAB":
packed = struct.pack(">HH", words[1], words[0])
else:
raise ValueError(f"不支持的字序: {order}")
return struct.unpack(">f", packed)[0]
def _ratio_label(ratio_offset: int) -> str:
return ["瞬时气电比", "小时气电比", "天气电比", "月气电比"][ratio_offset // 2]
def test_slave(client: ModbusSerialClient, slave_id: int):
"""读 40001~40072 全部 72 个寄存器,解析并展示。"""
compressor_ids = [3, 4, 5, 6, 7, 8, 9, 10, 11]
start_time = time.time()
try:
resp = client.read_holding_registers(address=0, count=72, slave=slave_id)
except Exception as e:
print(f" ✗ slave {slave_id}: 通信异常 — {e}")
return
elapsed_ms = (time.time() - start_time) * 1000
if resp.isError():
print(f" ✗ slave {slave_id}: Modbus 错误 — {resp}")
return
words = list(resp.registers)
print(f"\n slave_id={slave_id} 读 72 个寄存器 耗时 {elapsed_ms:.1f} ms {'✓' if elapsed_ms < 50 else '⚠️ >50ms'}")
print(f" {'空压机':<4} {'瞬时气电比':>12} {'小时气电比':>12} {'天气电比':>12} {'月气电比':>12} {'寄存器范围':<16}")
print(" " + "-" * 70)
ok_count = 0
fail_count = 0
for idx, cid in enumerate(compressor_ids):
base = idx * 8
vals = []
for ratio_i in range(4): # 4 种气电比
offset = base + ratio_i * 2
try:
v = _decode_float32_two_registers(words[offset : offset + 2], "ABCD")
vals.append(v)
except Exception as e:
vals.append(None)
fail_count += 1
range_str = f"40001+{base}~40001+{base+7}"
print(f" {cid:>2}# {vals[0]:>12.4f} {vals[1]:>12.4f} {vals[2]:>12.4f} {vals[3]:>12.4f} {range_str}")
# 只要不是全 0(初始状态)就算正常
if any(v is not None and v > 0 for v in vals):
ok_count += 1
print(f"\n 有效数据机器数: {ok_count}/{len(compressor_ids)} 解析失败: {fail_count}")
print(f" 注: 若全部为 0,说明网关还没采集到数据,先启动 mock TCP 服务器让网关跑起来。")
def main():
parser = argparse.ArgumentParser(description="RTU 主站测试网关从站寄存器")
parser.add_argument("--port", required=True, help="串口号,如 COM3 或 /dev/ttyUSB0")
parser.add_argument("--slave", default="10", help="从站 ID,可逗号分隔多值如 10,20")
parser.add_argument("--baud", type=int, default=9600)
parser.add_argument("--parity", default="N", choices=["N", "E", "O"])
parser.add_argument("--timeout", type=float, default=1.0)
parser.add_argument("--interval", type=float, default=1.0, help="轮询间隔秒,0 则只测一次")
args = parser.parse_args()
slave_ids = [int(s.strip()) for s in args.slave.split(",")]
client = ModbusSerialClient(
port=args.port,
baudrate=args.baud,
bytesize=8,
parity=args.parity,
stopbits=1,
timeout=args.timeout,
)
if not client.connect():
print(f"无法打开串口 {args.port},波特率 {args.baud}-8-{args.parity}-1")
sys.exit(1)
print(f"已连接 {args.port},轮询从站 {slave_ids}")
try:
while True:
for sid in slave_ids:
test_slave(client, sid)
if args.interval > 0:
time.sleep(0.3)
if args.interval <= 0:
break
print("\n" + "=" * 60)
time.sleep(args.interval)
except KeyboardInterrupt:
print("\n已停止轮询。")
finally:
client.close()
if __name__ == "__main__":
main()
+19
View File
@@ -0,0 +1,19 @@
comp_id,name,s4c_addr,proto_addr,reg_hi,reg_lo,hex_hi,hex_lo,type,scale,raw_value,eng_value,unit,note
3,3#功率,40150,149,18034,12288,0x4672,0x3000,float32,0.001,15500.0,15.5,kW,"工程值=15.5kW, scale=0.001, 原始值=15500.0"
3,3#电能,40152,151,18417,8282,0x47F1,0x205A,float32,0.1,123456.7,12345.67,kWh,"工程值=12345.67kWh, scale=0.1, 原始值=123456.7"
4,4#功率,40158,157,17984,12288,0x4640,0x3000,float32,0.001,12300.0,12.3,kW,"工程值=12.3kW, scale=0.001, 原始值=12300.0"
4,4#电能,40160,159,18368,59059,0x47C0,0xE6B3,float32,0.1,98765.40000000001,9876.54,kWh,"工程值=9876.54kWh, scale=0.1, 原始值=98765.40000000001"
5,5#功率,40166,165,18060,40960,0x468C,0xA000,float32,0.001,18000.0,18.0,kW,"工程值=18.0kW, scale=0.001, 原始值=18000.0"
5,5#电能,40168,167,18450,31744,0x4812,0x7C00,float32,0.1,150000.0,15000.0,kWh,"工程值=15000.0kWh, scale=0.1, 原始值=150000.0"
6,6#功率,40174,173,17945,8192,0x4619,0x2000,float32,0.001,9800.0,9.8,kW,"工程值=9.8kW, scale=0.001, 原始值=9800.0"
6,6#电能,40176,175,18325,32666,0x4795,0x7F9A,float32,0.1,76543.2,7654.32,kWh,"工程值=7654.32kWh, scale=0.1, 原始值=76543.2"
7,7#功率,40182,181,18077,2048,0x469D,0x0800,float32,0.001,20100.0,20.1,kW,"工程值=20.1kW, scale=0.001, 原始值=20100.0"
7,7#电能,40184,183,18487,16787,0x4837,0x4193,float32,0.1,187654.3,18765.43,kWh,"工程值=18765.43kWh, scale=0.1, 原始值=187654.3"
8,8#功率,40190,189,17967,0,0x462F,0x0000,float32,0.001,11199.999999999998,11.2,kW,"工程值=11.2kW, scale=0.001, 原始值=11199.999999999998"
8,8#电能,40192,191,18347,12672,0x47AB,0x3180,float32,0.1,87651.0,8765.1,kWh,"工程值=8765.1kWh, scale=0.1, 原始值=87651.0"
9,9#功率,40214,213,18050,30720,0x4682,0x7800,float32,0.001,16700.0,16.7,kW,"工程值=16.7kW, scale=0.001, 原始值=16700.0"
9,9#电能,40216,215,18433,384,0x4801,0x0180,float32,0.1,132102.0,13210.2,kWh,"工程值=13210.2kWh, scale=0.1, 原始值=132102.0"
10,10#功率,40206,205,18001,24576,0x4651,0x6000,float32,0.001,13400.0,13.4,kW,"工程值=13.4kW, scale=0.001, 原始值=13400.0"
10,10#电能,40208,207,18388,46272,0x47D4,0xB4C0,float32,0.1,108905.49999999999,10890.55,kWh,"工程值=10890.55kWh, scale=0.1, 原始值=108905.49999999999"
11,11#功率,40198,197,18023,16384,0x4667,0x4000,float32,0.001,14800.0,14.8,kW,"工程值=14.8kW, scale=0.001, 原始值=14800.0"
11,11#电能,40200,199,18401,45926,0x47E1,0xB366,float32,0.1,115558.79999999999,11555.88,kWh,"工程值=11555.88kWh, scale=0.1, 原始值=115558.79999999999"
1 comp_id name s4c_addr proto_addr reg_hi reg_lo hex_hi hex_lo type scale raw_value eng_value unit note
2 3 3#功率 40150 149 18034 12288 0x4672 0x3000 float32 0.001 15500.0 15.5 kW 工程值=15.5kW, scale=0.001, 原始值=15500.0
3 3 3#电能 40152 151 18417 8282 0x47F1 0x205A float32 0.1 123456.7 12345.67 kWh 工程值=12345.67kWh, scale=0.1, 原始值=123456.7
4 4 4#功率 40158 157 17984 12288 0x4640 0x3000 float32 0.001 12300.0 12.3 kW 工程值=12.3kW, scale=0.001, 原始值=12300.0
5 4 4#电能 40160 159 18368 59059 0x47C0 0xE6B3 float32 0.1 98765.40000000001 9876.54 kWh 工程值=9876.54kWh, scale=0.1, 原始值=98765.40000000001
6 5 5#功率 40166 165 18060 40960 0x468C 0xA000 float32 0.001 18000.0 18.0 kW 工程值=18.0kW, scale=0.001, 原始值=18000.0
7 5 5#电能 40168 167 18450 31744 0x4812 0x7C00 float32 0.1 150000.0 15000.0 kWh 工程值=15000.0kWh, scale=0.1, 原始值=150000.0
8 6 6#功率 40174 173 17945 8192 0x4619 0x2000 float32 0.001 9800.0 9.8 kW 工程值=9.8kW, scale=0.001, 原始值=9800.0
9 6 6#电能 40176 175 18325 32666 0x4795 0x7F9A float32 0.1 76543.2 7654.32 kWh 工程值=7654.32kWh, scale=0.1, 原始值=76543.2
10 7 7#功率 40182 181 18077 2048 0x469D 0x0800 float32 0.001 20100.0 20.1 kW 工程值=20.1kW, scale=0.001, 原始值=20100.0
11 7 7#电能 40184 183 18487 16787 0x4837 0x4193 float32 0.1 187654.3 18765.43 kWh 工程值=18765.43kWh, scale=0.1, 原始值=187654.3
12 8 8#功率 40190 189 17967 0 0x462F 0x0000 float32 0.001 11199.999999999998 11.2 kW 工程值=11.2kW, scale=0.001, 原始值=11199.999999999998
13 8 8#电能 40192 191 18347 12672 0x47AB 0x3180 float32 0.1 87651.0 8765.1 kWh 工程值=8765.1kWh, scale=0.1, 原始值=87651.0
14 9 9#功率 40214 213 18050 30720 0x4682 0x7800 float32 0.001 16700.0 16.7 kW 工程值=16.7kW, scale=0.001, 原始值=16700.0
15 9 9#电能 40216 215 18433 384 0x4801 0x0180 float32 0.1 132102.0 13210.2 kWh 工程值=13210.2kWh, scale=0.1, 原始值=132102.0
16 10 10#功率 40206 205 18001 24576 0x4651 0x6000 float32 0.001 13400.0 13.4 kW 工程值=13.4kW, scale=0.001, 原始值=13400.0
17 10 10#电能 40208 207 18388 46272 0x47D4 0xB4C0 float32 0.1 108905.49999999999 10890.55 kWh 工程值=10890.55kWh, scale=0.1, 原始值=108905.49999999999
18 11 11#功率 40198 197 18023 16384 0x4667 0x4000 float32 0.001 14800.0 14.8 kW 工程值=14.8kW, scale=0.001, 原始值=14800.0
19 11 11#电能 40200 199 18401 45926 0x47E1 0xB366 float32 0.1 115558.79999999999 11555.88 kWh 工程值=11555.88kWh, scale=0.1, 原始值=115558.79999999999
+9
View File
@@ -0,0 +1,9 @@
comp_id,name,s4c_addr,proto_addr,reg_hi,reg_lo,hex_hi,hex_lo,type,scale,raw_value,eng_value,unit,note
3,3#瞬时流量,40113,112,17057,0,0x42A1,0x0000,float32,1,80.5,80.5,m³/h,"工程值=80.5m³/h, scale=1, 原始值=80.5"
3,3#累计气量,40115,114,18,54919,0x0012,0xD687,uint32,1,1234567.0,1234567,m³,"工程值=1234567m³, scale=1, 原始值=1234567.0"
4,4#瞬时流量,40123,122,17086,26214,0x42BE,0x6666,float32,1,95.2,95.2,m³/h,"工程值=95.2m³/h, scale=1, 原始值=95.2"
4,4#累计气量,40125,124,16,40424,0x0010,0x9DE8,uint32,1,1089000.0,1089000,m³,"工程值=1089000m³, scale=1, 原始值=1089000.0"
5,5#瞬时流量,40133,132,17037,39322,0x428D,0x999A,float32,1,70.8,70.8,m³/h,"工程值=70.8m³/h, scale=1, 原始值=70.8"
5,5#累计气量,40135,134,23,60472,0x0017,0xEC38,uint32,1,1567800.0,1567800,m³,"工程值=1567800m³, scale=1, 原始值=1567800.0"
11,11#瞬时流量,40143,142,17072,13107,0x42B0,0x3333,float32,1,88.1,88.1,m³/h,"工程值=88.1m³/h, scale=1, 原始值=88.1"
11,11#累计气量,40145,144,15,4614,0x000F,0x1206,uint32,1,987654.0,987654,m³,"工程值=987654m³, scale=1, 原始值=987654.0"
1 comp_id name s4c_addr proto_addr reg_hi reg_lo hex_hi hex_lo type scale raw_value eng_value unit note
2 3 3#瞬时流量 40113 112 17057 0 0x42A1 0x0000 float32 1 80.5 80.5 m³/h 工程值=80.5m³/h, scale=1, 原始值=80.5
3 3 3#累计气量 40115 114 18 54919 0x0012 0xD687 uint32 1 1234567.0 1234567 m³ 工程值=1234567m³, scale=1, 原始值=1234567.0
4 4 4#瞬时流量 40123 122 17086 26214 0x42BE 0x6666 float32 1 95.2 95.2 m³/h 工程值=95.2m³/h, scale=1, 原始值=95.2
5 4 4#累计气量 40125 124 16 40424 0x0010 0x9DE8 uint32 1 1089000.0 1089000 m³ 工程值=1089000m³, scale=1, 原始值=1089000.0
6 5 5#瞬时流量 40133 132 17037 39322 0x428D 0x999A float32 1 70.8 70.8 m³/h 工程值=70.8m³/h, scale=1, 原始值=70.8
7 5 5#累计气量 40135 134 23 60472 0x0017 0xEC38 uint32 1 1567800.0 1567800 m³ 工程值=1567800m³, scale=1, 原始值=1567800.0
8 11 11#瞬时流量 40143 142 17072 13107 0x42B0 0x3333 float32 1 88.1 88.1 m³/h 工程值=88.1m³/h, scale=1, 原始值=88.1
9 11 11#累计气量 40145 144 15 4614 0x000F 0x1206 uint32 1 987654.0 987654 m³ 工程值=987654m³, scale=1, 原始值=987654.0
+11
View File
@@ -0,0 +1,11 @@
comp_id,name,s4c_addr,proto_addr,reg_hi,reg_lo,hex_hi,hex_lo,type,scale,raw_value,eng_value,unit,note
6,6#瞬时流量,40119,118,17026,0,0x4282,0x0000,float32,1,65.0,65.0,m³/h,"工程值=65.0m³/h, scale=1, 原始值=65.0"
6,6#累计气量,40121,120,25,40500,0x0019,0x9E34,uint32,1,1678900.0,1678900,m³,"工程值=1678900m³, scale=1, 原始值=1678900.0"
7,7#瞬时流量,40129,128,17080,39322,0x42B8,0x999A,float32,1,92.3,92.3,m³/h,"工程值=92.3m³/h, scale=1, 原始值=92.3"
7,7#累计气量,40131,130,20,34880,0x0014,0x8840,uint32,1,1345600.0,1345600,m³,"工程值=1345600m³, scale=1, 原始值=1345600.0"
8,8#瞬时流量,40139,138,17052,52429,0x429C,0xCCCD,float32,1,78.4,78.4,m³/h,"工程值=78.4m³/h, scale=1, 原始值=78.4"
8,8#累计气量,40141,140,18,20352,0x0012,0x4F80,uint32,1,1200000.0,1200000,m³,"工程值=1200000m³, scale=1, 原始值=1200000.0"
9,9#瞬时流量,40149,148,17096,0,0x42C8,0x0000,float32,1,100.0,100.0,m³/h,"工程值=100.0m³/h, scale=1, 原始值=100.0"
9,9#累计气量,40151,150,27,30528,0x001B,0x7740,uint32,1,1800000.0,1800000,m³,"工程值=1800000m³, scale=1, 原始值=1800000.0"
10,10#瞬时流量,40159,158,17067,13107,0x42AB,0x3333,float32,1,85.6,85.6,m³/h,"工程值=85.6m³/h, scale=1, 原始值=85.6"
10,10#累计气量,40161,160,22,8208,0x0016,0x2010,uint32,1,1450000.0,1450000,m³,"工程值=1450000m³, scale=1, 原始值=1450000.0"
1 comp_id name s4c_addr proto_addr reg_hi reg_lo hex_hi hex_lo type scale raw_value eng_value unit note
2 6 6#瞬时流量 40119 118 17026 0 0x4282 0x0000 float32 1 65.0 65.0 m³/h 工程值=65.0m³/h, scale=1, 原始值=65.0
3 6 6#累计气量 40121 120 25 40500 0x0019 0x9E34 uint32 1 1678900.0 1678900 m³ 工程值=1678900m³, scale=1, 原始值=1678900.0
4 7 7#瞬时流量 40129 128 17080 39322 0x42B8 0x999A float32 1 92.3 92.3 m³/h 工程值=92.3m³/h, scale=1, 原始值=92.3
5 7 7#累计气量 40131 130 20 34880 0x0014 0x8840 uint32 1 1345600.0 1345600 m³ 工程值=1345600m³, scale=1, 原始值=1345600.0
6 8 8#瞬时流量 40139 138 17052 52429 0x429C 0xCCCD float32 1 78.4 78.4 m³/h 工程值=78.4m³/h, scale=1, 原始值=78.4
7 8 8#累计气量 40141 140 18 20352 0x0012 0x4F80 uint32 1 1200000.0 1200000 m³ 工程值=1200000m³, scale=1, 原始值=1200000.0
8 9 9#瞬时流量 40149 148 17096 0 0x42C8 0x0000 float32 1 100.0 100.0 m³/h 工程值=100.0m³/h, scale=1, 原始值=100.0
9 9 9#累计气量 40151 150 27 30528 0x001B 0x7740 uint32 1 1800000.0 1800000 m³ 工程值=1800000m³, scale=1, 原始值=1800000.0
10 10 10#瞬时流量 40159 158 17067 13107 0x42AB 0x3333 float32 1 85.6 85.6 m³/h 工程值=85.6m³/h, scale=1, 原始值=85.6
11 10 10#累计气量 40161 160 22 8208 0x0016 0x2010 uint32 1 1450000.0 1450000 m³ 工程值=1450000m³, scale=1, 原始值=1450000.0
+113
View File
@@ -0,0 +1,113 @@
# Modbus Poll / MBS Slave 测试数据对照表
生成时间:2026-11-17
**重要**:表格中的 `reg_hi` / `reg_lo` 和 `hex_hi` / `hex_lo` 是**原始值**,
直接填入 Modbus Poll / MBS Slave 的 Holding Register 即可。
`scale` 表示:网关内部工程值 = 原始值 × scale。
---
## 设备 1:蘑菇云电表 Modbus TCP Server
| 项目 | 值 |
|---|---|
| Connection | Modbus TCP |
| Host | 192.168.1.253(测试)/ 10.50.253.165(现场) |
| Port | 1502 |
| Slave ID | 1 |
| Function Code | 03 (Read Holding Registers) |
| 寄存器窗口 | 40149 ~ 40216(连续一段) |
### 数据值
| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 3# | 功率 | 149 | 40150 | 18034 | 12288 | 0x4672 | 0x3000 | float32 | 0.001 | 15.5 | kW |
| 3# | 电能 | 151 | 40152 | 18417 | 8282 | 0x47F1 | 0x205A | float32 | 0.1 | 12345.67 | kWh |
| 4# | 功率 | 157 | 40158 | 17984 | 12288 | 0x4640 | 0x3000 | float32 | 0.001 | 12.3 | kW |
| 4# | 电能 | 159 | 40160 | 18368 | 59059 | 0x47C0 | 0xE6B3 | float32 | 0.1 | 9876.54 | kWh |
| 5# | 功率 | 165 | 40166 | 18060 | 40960 | 0x468C | 0xA000 | float32 | 0.001 | 18.0 | kW |
| 5# | 电能 | 167 | 40168 | 18450 | 31744 | 0x4812 | 0x7C00 | float32 | 0.1 | 15000.0 | kWh |
| 6# | 功率 | 173 | 40174 | 17945 | 8192 | 0x4619 | 0x2000 | float32 | 0.001 | 9.8 | kW |
| 6# | 电能 | 175 | 40176 | 18325 | 32666 | 0x4795 | 0x7F9A | float32 | 0.1 | 7654.32 | kWh |
| 7# | 功率 | 181 | 40182 | 18077 | 2048 | 0x469D | 0x0800 | float32 | 0.001 | 20.1 | kW |
| 7# | 电能 | 183 | 40184 | 18487 | 16787 | 0x4837 | 0x4193 | float32 | 0.1 | 18765.43 | kWh |
| 8# | 功率 | 189 | 40190 | 17967 | 0 | 0x462F | 0x0000 | float32 | 0.001 | 11.2 | kW |
| 8# | 电能 | 191 | 40192 | 18347 | 12672 | 0x47AB | 0x3180 | float32 | 0.1 | 8765.1 | kWh |
| 9# | 功率 | 213 | 40214 | 18050 | 30720 | 0x4682 | 0x7800 | float32 | 0.001 | 16.7 | kW |
| 9# | 电能 | 215 | 40216 | 18433 | 384 | 0x4801 | 0x0180 | float32 | 0.1 | 13210.2 | kWh |
| 10# | 功率 | 205 | 40206 | 18001 | 24576 | 0x4651 | 0x6000 | float32 | 0.001 | 13.4 | kW |
| 10# | 电能 | 207 | 40208 | 18388 | 46272 | 0x47D4 | 0xB4C0 | float32 | 0.1 | 10890.55 | kWh |
| 11# | 功率 | 197 | 40198 | 18023 | 16384 | 0x4667 | 0x4000 | float32 | 0.001 | 14.8 | kW |
| 11# | 电能 | 199 | 40200 | 18401 | 45926 | 0x47E1 | 0xB366 | float32 | 0.1 | 11555.88 | kWh |
---
## 设备 2:希尔思 S331 #1 Modbus TCP Server(负责 3/4/5/11)
| 项目 | 值 |
|---|---|
| Connection | Modbus TCP |
| Host | 192.168.1.253(测试)/ 10.50.253.181(现场) |
| Port | 502 |
| Slave ID | 10 |
| Function Code | 03 |
| 寄存器窗口 | 40113 ~ 40145(连续一段) |
### 数据值
| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 3# | 瞬时流量 | 112 | 40113 | 17057 | 0 | 0x42A1 | 0x0000 | float32 | 1 | 80.5 | m³/h |
| 3# | 累计气量 | 114 | 40115 | 18 | 54919 | 0x0012 | 0xD687 | uint32 | 1 | 1234567 | m³ |
| 4# | 瞬时流量 | 122 | 40123 | 17086 | 26214 | 0x42BE | 0x6666 | float32 | 1 | 95.2 | m³/h |
| 4# | 累计气量 | 124 | 40125 | 16 | 40424 | 0x0010 | 0x9DE8 | uint32 | 1 | 1089000 | m³ |
| 5# | 瞬时流量 | 132 | 40133 | 17037 | 39322 | 0x428D | 0x999A | float32 | 1 | 70.8 | m³/h |
| 5# | 累计气量 | 134 | 40135 | 23 | 60472 | 0x0017 | 0xEC38 | uint32 | 1 | 1567800 | m³ |
| 11# | 瞬时流量 | 142 | 40143 | 17072 | 13107 | 0x42B0 | 0x3333 | float32 | 1 | 88.1 | m³/h |
| 11# | 累计气量 | 144 | 40145 | 15 | 4614 | 0x000F | 0x1206 | uint32 | 1 | 987654 | m³ |
---
## 设备 3:希尔思 S331 #2 Modbus TCP Server(负责 6/7/8/9/10)
| 项目 | 值 |
|---|---|
| Connection | Modbus TCP |
| Host | 192.168.1.253(测试)/ 10.50.253.182(现场) |
| Port | 503(测试)/ 502(现场) |
| Slave ID | 20 |
| Function Code | 03 |
| 寄存器窗口 | 40119 ~ 40161(连续一段) |
### 数据值
| 空压机 | 点 | 协议地址(0基) | S4C地址 | reg_hi | reg_lo | hex_hi | hex_lo | 类型 | scale | 工程值 | 单位 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 6# | 瞬时流量 | 118 | 40119 | 17026 | 0 | 0x4282 | 0x0000 | float32 | 1 | 65.0 | m³/h |
| 6# | 累计气量 | 120 | 40121 | 25 | 40500 | 0x0019 | 0x9E34 | uint32 | 1 | 1678900 | m³ |
| 7# | 瞬时流量 | 128 | 40129 | 17080 | 39322 | 0x42B8 | 0x999A | float32 | 1 | 92.3 | m³/h |
| 7# | 累计气量 | 130 | 40131 | 20 | 34880 | 0x0014 | 0x8840 | uint32 | 1 | 1345600 | m³ |
| 8# | 瞬时流量 | 138 | 40139 | 17052 | 52429 | 0x429C | 0xCCCD | float32 | 1 | 78.4 | m³/h |
| 8# | 累计气量 | 140 | 40141 | 18 | 20352 | 0x0012 | 0x4F80 | uint32 | 1 | 1200000 | m³ |
| 9# | 瞬时流量 | 148 | 40149 | 17096 | 0 | 0x42C8 | 0x0000 | float32 | 1 | 100.0 | m³/h |
| 9# | 累计气量 | 150 | 40151 | 27 | 30528 | 0x001B | 0x7740 | uint32 | 1 | 1800000 | m³ |
| 10# | 瞬时流量 | 158 | 40159 | 17067 | 13107 | 0x42AB | 0x3333 | float32 | 1 | 85.6 | m³/h |
| 10# | 累计气量 | 160 | 40161 | 22 | 8208 | 0x0016 | 0x2010 | uint32 | 1 | 1450000 | m³ |
---
## 快速校验样例
如果网关采集正常,`journalctl -u hx-gateway -n 30` 应该看到类似:
```
状态 3#空压机 瞬时=0.1925 时=0.0000 日=0.0000 月=0.0000 | 瞬时流量=80.5 累计气量=1234567.0 瞬时功率=15.5 累计电量=12345.7 | 数据延迟=1s
```
气电比计算:
```
瞬时气电比 = 功率(kW) / 流量(m³/h)
3#: 15.5 / 80.5 = 0.1925
```
+71
View File
@@ -0,0 +1,71 @@
"""V3.3 精确点表对齐校验脚本"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from gateway.config import load_config
cfg = load_config(Path("config/config.yaml"))
# V3.3 第 5 节期望值
EXPECT = {
"s331_1": {"slave_id": 10, "host": "10.50.253.181", "compressors": {
3: (112, 114), 4: (122, 124), 5: (132, 134), 11: (142, 144)}},
"s331_2": {"slave_id": 20, "host": "10.50.253.182", "compressors": {
6: (118, 120), 7: (128, 130), 8: (138, 140), 9: (148, 150), 10: (158, 160)}},
}
# V3.3 第 4 节蘑菇云电表功率地址
METER_EXP = {3: 149, 4: 157, 5: 165, 6: 173, 7: 181, 8: 189, 9: 213, 10: 205, 11: 197}
errors = []
# 1) S331 TCP Server 参数
for dev_name, exp in EXPECT.items():
dev = cfg.devices[dev_name]
if dev.slave_id != exp["slave_id"]:
errors.append(f"{dev_name} slave_id {dev.slave_id} != {exp['slave_id']}")
if dev.host != exp["host"]:
errors.append(f"{dev_name} host {dev.host} != {exp['host']}")
# 2) S331 气量地址 + 类型
for c in cfg.compressors:
exp = EXPECT[c.s331]["compressors"].get(c.id)
if exp:
got = (c.flow_instant.address, c.flow_total.address)
if got != exp:
errors.append(f"{c.id}# flow_addr {got} != {exp}")
if c.flow_total.type != "uint32":
errors.append(f"{c.id}# flow_total type {c.flow_total.type} != uint32")
if c.flow_instant.type != "float32":
errors.append(f"{c.id}# flow_instant type {c.flow_instant.type} != float32")
# 3) 蘑菇云电表功率地址
for c in cfg.compressors:
if c.power_instant.address != METER_EXP[c.id]:
errors.append(f"{c.id}# power_addr {c.power_instant.address} != {METER_EXP[c.id]}")
if errors:
print("V3.3 ALIGNMENT FAILED:")
for e in errors:
print(f" - {e}")
sys.exit(1)
print("ALL V3.3 CHECKS PASS")
print()
print("=== Final config summary ===")
print(f"mogo_meter : {cfg.devices['mogo_meter'].host}:{cfg.devices['mogo_meter'].port} slave={cfg.devices['mogo_meter'].slave_id}")
for name in ("s331_1", "s331_2"):
dev = cfg.devices[name]
print(f"{name}: {dev.host}:{dev.port} slave={dev.slave_id}")
print()
for c in cfg.compressors:
print(f" {c.id:>2}# s331={c.s331} idx={c.register_index} "
f"flow_inst={c.flow_instant.address}({c.flow_instant.type}) "
f"flow_tot={c.flow_total.address}({c.flow_total.type}) "
f"pow={c.power_instant.address}({c.power_instant.type}) "
f"energy={c.energy_total.address}({c.energy_total.type})")
print()
print("RTU slaves:")
for s in cfg.slaves:
print(f" {s.name}: {s.port} slave_id={s.slave_id}")
+171
View File
@@ -0,0 +1,171 @@
# -*- 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())