现场调试版同步: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,2 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
*.service text eol=lf
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
.screenshots/
|
||||||
|
data/
|
||||||
|
dist/
|
||||||
|
*.zip
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# hx-gateway 调试包(2026-11-19)
|
||||||
|
|
||||||
|
空压机气电比边缘网关,用于在 PC 上复现/调试。包含完整源码、点表、测试与 mock 数据源。
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
```
|
||||||
|
gateway/ 采集、计算、RTU 从站源码(入口 gateway.app)
|
||||||
|
config/config.yaml 生产点表(现场在用,勿改)
|
||||||
|
config/config.debug.yaml 本机调试用:数据源指向 127.0.0.1,数据库落到 ./data
|
||||||
|
tools/mock_tcp_servers.py 3 个 Modbus TCP mock(电表 1502 / S331#1 502 / S331#2 503)
|
||||||
|
tools/rtu_client_test.py 读网关 RTU 从站的测试客户端
|
||||||
|
tools/test_data/*.csv 批量测试数据
|
||||||
|
tests/ pytest 用例
|
||||||
|
docs/ register_map.md(寄存器表)、TEST_GUIDE.md
|
||||||
|
deploy/ 现场部署脚本与 systemd 单元(网关上是 /opt/hx-gateway)
|
||||||
|
wheelhouse/ Windows x64 + Python 3.11 离线依赖
|
||||||
|
```
|
||||||
|
|
||||||
|
## 环境
|
||||||
|
|
||||||
|
- Python **3.11**(Windows x64 或 Linux)
|
||||||
|
- 依赖:pymodbus 3.9.2、pyserial 3.5、PyYAML 6.0.3
|
||||||
|
|
||||||
|
联网安装:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
python -m venv .venv
|
||||||
|
.venv\Scripts\pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
离线安装(仅限 Windows x64 / Python 3.11):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
.venv\Scripts\pip install --no-index --find-links wheelhouse -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## 启动(两个终端,均在包根目录)
|
||||||
|
|
||||||
|
终端 1:起 mock 数据源
|
||||||
|
|
||||||
|
```bat
|
||||||
|
python tools\mock_tcp_servers.py
|
||||||
|
```
|
||||||
|
|
||||||
|
终端 2:起网关
|
||||||
|
|
||||||
|
```bat
|
||||||
|
python -m gateway.app --config config/config.debug.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux 下把 `\` 换成 `/`。调试配置每 10 秒打印一轮 9 台机的瞬时/时/日/月气电比、流量、功率,便于观察。
|
||||||
|
|
||||||
|
常用参数:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
python -m gateway.app --config config/config.debug.yaml --log-level DEBUG
|
||||||
|
python -m gateway.app --config config/config.debug.yaml --print-map
|
||||||
|
```
|
||||||
|
|
||||||
|
## 关于串口(RTU 从站)
|
||||||
|
|
||||||
|
`config.debug.yaml` 的从站默认是 `COM10` / `COM11`。PC 上没有这两个口时,从站每 3~5 秒打印一次串口异常并重试,**不影响 TCP 采集与气电比计算**。要联调 S331 屏或 Modbus Poll:
|
||||||
|
|
||||||
|
1. 接上 USB-RS485,把配置改成实际 COM 号(Linux 改 `/dev/ttyUSB0` 等);
|
||||||
|
2. 用 `tools/rtu_client_test.py` 或 Modbus Poll 读从站 10、功能码 03;
|
||||||
|
3. 寄存器映射:基址 = register_index × 8,+0/+1 瞬时、+2/+3 时、+4/+5 日、+6/+7 月,Float 字序 ABCD(高字在前),协议地址 0 对应 40001。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bat
|
||||||
|
.venv\Scripts\pip install pytest
|
||||||
|
.venv\Scripts\python -m pytest tests -q
|
||||||
|
```
|
||||||
|
|
||||||
|
已知历史失败项与本环境无关:`test_duplicate_slave_port_rejected`(用例写死 ttyS2/ttyS1)、`test_device_address_offset_is_applied`、并发吞吐断言。
|
||||||
|
|
||||||
|
## 注意
|
||||||
|
|
||||||
|
- 现场部署用 `config/config.yaml` + `deploy/install.sh`,不要用 debug 配置上现场。
|
||||||
|
- S331 的 32 位量为 CDAB(低字在前),瞬时流量原始单位 m³/min(scale 60);未接通道填 -9999,程序按原始寄存器对过滤。
|
||||||
|
- RTU 从站 framer 只认本从站地址的 FC03/04 请求,总线上其它设备(流量计 67~75)的报文会被丢弃而不会拖垮从站。
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
# 本地调试配置(PC 上跑 mock_tcp_servers.py 时用)
|
||||||
|
# 与生产 config.yaml 的唯一区别:数据源指向 127.0.0.1、数据库落在当前目录、
|
||||||
|
# RTU 从站端口换成 PC 上的 COM 口。点表、字序、scale 与生产完全一致。
|
||||||
|
#
|
||||||
|
# 启动 mock: python tools\mock_tcp_servers.py
|
||||||
|
# 启动网关: python -m gateway.app --config config/config.debug.yaml
|
||||||
|
|
||||||
|
gateway:
|
||||||
|
db_path: ./data/gateway.db # Windows/Linux 都可用,目录会自动创建
|
||||||
|
log_level: INFO # 想看清帧收发可改 DEBUG(日志会很多)
|
||||||
|
log_file: ""
|
||||||
|
persist_interval_s: 60
|
||||||
|
status_interval_s: 10
|
||||||
|
stale_warn_s: 20
|
||||||
|
register_float_order: ABCD
|
||||||
|
|
||||||
|
devices:
|
||||||
|
mogo_meter:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 1502
|
||||||
|
slave_id: 1
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 6
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
s331_1:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 502
|
||||||
|
slave_id: 10
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 2
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
s331_2:
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 503
|
||||||
|
slave_id: 20
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 2
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
compressors:
|
||||||
|
- id: 3
|
||||||
|
name: "3#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 0
|
||||||
|
flow_instant: { address: 112, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 114, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 149, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 151, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 4
|
||||||
|
name: "4#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 1
|
||||||
|
flow_instant: { address: 122, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 124, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 157, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 159, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 5
|
||||||
|
name: "5#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 2
|
||||||
|
flow_instant: { address: 132, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 134, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 165, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 167, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 11
|
||||||
|
name: "11#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 8
|
||||||
|
flow_instant: { address: 142, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 144, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 197, type: int32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 199, type: int32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 6
|
||||||
|
name: "6#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 3
|
||||||
|
flow_instant: { address: 118, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 120, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 173, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 175, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 7
|
||||||
|
name: "7#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 4
|
||||||
|
flow_instant: { address: 128, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 130, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 181, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 183, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 8
|
||||||
|
name: "8#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 5
|
||||||
|
flow_instant: { address: 138, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 140, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 189, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 191, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 9
|
||||||
|
name: "9#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 6
|
||||||
|
flow_instant: { address: 148, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 150, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 213, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 215, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
- id: 10
|
||||||
|
name: "10#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 7
|
||||||
|
flow_instant: { address: 158, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 160, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 205, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 207, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# PC 调试用 RTU 从站:没有串口也不影响 TCP 采集,从站会每 3~5 秒重试并打印异常。
|
||||||
|
# Windows 接 USB-RS485 后改成实际 COM 号;Linux 改成 /dev/ttyUSB0、/dev/ttyUSB1。
|
||||||
|
slaves:
|
||||||
|
- name: gateway_to_s331_1
|
||||||
|
port: COM10
|
||||||
|
slave_id: 10
|
||||||
|
baudrate: 19200
|
||||||
|
bytesize: 8
|
||||||
|
parity: N
|
||||||
|
stopbits: 1
|
||||||
|
timeout_s: 0.5
|
||||||
|
- name: gateway_to_s331_2
|
||||||
|
port: COM11
|
||||||
|
slave_id: 10
|
||||||
|
baudrate: 19200
|
||||||
|
bytesize: 8
|
||||||
|
parity: N
|
||||||
|
stopbits: 1
|
||||||
|
timeout_s: 0.5
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
# 边缘计算网关配置(V3.3 - 蘑菇云电表 + 希尔思 S331 气量,精确点表)
|
||||||
|
# 有人 EG828-CEW / Debian
|
||||||
|
# 地址为 Modbus 协议地址(0 基),即 S4C/Modbus Poll 中的 40001 对应 address: 0。
|
||||||
|
#
|
||||||
|
# V3.3 相对 V3.2 的关键变化(已全部对齐):
|
||||||
|
# 1) S331 IP 确定: #1=10.50.253.181 #2=10.50.253.182
|
||||||
|
# 2) S331 TCP Server 从站地址: #1=10 #2=20(网关作为 TCP Client 读它们时用)
|
||||||
|
# ⚠ 网关 RTU 对外暴露的 slave_id 现场实测为 10/10(S331 两个屏都按 10 轮询),
|
||||||
|
# 与上面 TCP 侧的 10/20 分属不同总线,互不干扰。
|
||||||
|
# 3) S331 气量寄存器地址精确给出(见第 5 节),不再是占位
|
||||||
|
# 4) ⚠ 现场实测:S331 全部 32 位量为“低字在前”(CDAB),不是文档写的 ABCD。
|
||||||
|
# 用 ABCD 解会得到 -1e-10、6e34 之类的乱数。已全部改为 CDAB。
|
||||||
|
# 5) 瞬时流量原始单位是 m³/min,配置里用 scale: 60 换算成 m³/h,
|
||||||
|
# 这样瞬时气电比 = kW / (m³/h) = kWh/m³,与时/日/月口径一致。
|
||||||
|
# 6) 11# 电表功率/电能 type 实测为 int32(按 float32 解恒为 0)
|
||||||
|
#
|
||||||
|
# RTU 从站输出映射(第 6 节)完全不变,和 V3.2 一致。
|
||||||
|
|
||||||
|
gateway:
|
||||||
|
db_path: /var/lib/hx-gateway/gateway.db
|
||||||
|
log_level: INFO
|
||||||
|
log_file: ""
|
||||||
|
persist_interval_s: 300 # 掉电保持周期(秒),5 分钟
|
||||||
|
status_interval_s: 60 # 状态日志周期
|
||||||
|
stale_warn_s: 20 # 数据过期告警阈值(秒)
|
||||||
|
register_float_order: ABCD # RTU 从站 Float 字序(高字在前,即 S4C 里选 FLOAT_B)
|
||||||
|
|
||||||
|
devices:
|
||||||
|
# ---- 蘑菇物联电表 Modbus TCP Server(电表数据源)----
|
||||||
|
mogo_meter:
|
||||||
|
host: 10.50.253.165
|
||||||
|
#host: 192.168.1.253
|
||||||
|
port: 1502
|
||||||
|
slave_id: 1
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 6
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
# ---- 希尔思 S331 #1 Modbus TCP Server(气量数据源 1)----
|
||||||
|
# 负责空压机: 3# / 4# / 5# / 11#
|
||||||
|
s331_1:
|
||||||
|
host: 10.50.253.181
|
||||||
|
#host: 192.168.1.253
|
||||||
|
port: 502
|
||||||
|
slave_id: 10
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 2
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
# ---- 希尔思 S331 #2 Modbus TCP Server(气量数据源 2)----
|
||||||
|
# 负责空压机: 6# / 7# / 8# / 9# / 10#
|
||||||
|
s331_2:
|
||||||
|
host: 10.50.253.182
|
||||||
|
#host: 192.168.1.253
|
||||||
|
port: 502
|
||||||
|
#port: 503
|
||||||
|
slave_id: 20
|
||||||
|
timeout_s: 1.0
|
||||||
|
poll_interval_s: 2.0
|
||||||
|
address_offset: 0
|
||||||
|
max_registers_per_read: 100
|
||||||
|
max_gap: 2
|
||||||
|
reconnect_min_s: 1.0
|
||||||
|
reconnect_max_s: 30.0
|
||||||
|
|
||||||
|
# ---- 9 台空压机(3#~11#)数据绑定 ----
|
||||||
|
#
|
||||||
|
# S331 归属(现场确认):
|
||||||
|
# s331_1 负责 3# / 4# / 5# / 11# 共 4 台
|
||||||
|
# s331_2 负责 6# / 7# / 8# / 9# / 10# 共 5 台
|
||||||
|
#
|
||||||
|
# ⚠️ V3.3 第 5 节给出的 S331 气量地址,每台机器的 2 个信号(FLOAT_L + UINT32_L)
|
||||||
|
# 在 S331 上地址相隔 2,紧凑排列。已按设备分组一次 Read Holding Registers 读完。
|
||||||
|
#
|
||||||
|
# register_index 决定 RTU 从站基址:base = register_index * 8
|
||||||
|
# 基址+0/1 瞬时气电比 (ABCD Float)
|
||||||
|
# 基址+2/3 小时气电比
|
||||||
|
# 基址+4/5 天气电比
|
||||||
|
# 基址+6/7 月气电比(后台保留,S331 屏幕暂不展示,寄存器照样实时更新)
|
||||||
|
compressors:
|
||||||
|
# ========== s331_1 负责 3# / 4# / 5# / 11# ==========
|
||||||
|
|
||||||
|
# 3# 寄存器索引 0 -> 40001~40008
|
||||||
|
- id: 3
|
||||||
|
name: "3#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 0
|
||||||
|
flow_instant: { address: 112, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 114, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 149, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 151, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 4# 寄存器索引 1 -> 40009~40016
|
||||||
|
- id: 4
|
||||||
|
name: "4#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 1
|
||||||
|
flow_instant: { address: 122, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 124, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 157, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 159, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 5# 寄存器索引 2 -> 40017~40024
|
||||||
|
- id: 5
|
||||||
|
name: "5#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 2
|
||||||
|
flow_instant: { address: 132, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 134, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 165, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 167, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 11# 寄存器索引 8 -> 40065~40072
|
||||||
|
# 现场实测:11# 电表功率/电能为 int32(按 float32 解析恒为 0.0)。
|
||||||
|
- id: 11
|
||||||
|
name: "11#空压机"
|
||||||
|
s331: s331_1
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 8
|
||||||
|
flow_instant: { address: 142, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 144, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 197, type: int32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 199, type: int32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# ========== s331_2 负责 6# / 7# / 8# / 9# / 10# ==========
|
||||||
|
|
||||||
|
# 6# 寄存器索引 3 -> 40025~40032
|
||||||
|
- id: 6
|
||||||
|
name: "6#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 3
|
||||||
|
flow_instant: { address: 118, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 120, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 173, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 175, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 7# 寄存器索引 4 -> 40033~40040
|
||||||
|
- id: 7
|
||||||
|
name: "7#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 4
|
||||||
|
flow_instant: { address: 128, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 130, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 181, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 183, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 8# 寄存器索引 5 -> 40041~40048
|
||||||
|
- id: 8
|
||||||
|
name: "8#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 5
|
||||||
|
flow_instant: { address: 138, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 140, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 189, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 191, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 9# 寄存器索引 6 -> 40049~40056
|
||||||
|
- id: 9
|
||||||
|
name: "9#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 6
|
||||||
|
flow_instant: { address: 148, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 150, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 213, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 215, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# 10# 寄存器索引 7 -> 40057~40064
|
||||||
|
- id: 10
|
||||||
|
name: "10#空压机"
|
||||||
|
s331: s331_2
|
||||||
|
meter: mogo_meter
|
||||||
|
register_index: 7
|
||||||
|
flow_instant: { address: 158, type: float32, word_order: CDAB, scale: 60 }
|
||||||
|
flow_total: { address: 160, type: uint32, word_order: CDAB }
|
||||||
|
power_instant: { address: 205, type: float32, word_order: ABCD, scale: 0.001 }
|
||||||
|
energy_total: { address: 207, type: float32, word_order: ABCD, scale: 0.1 }
|
||||||
|
|
||||||
|
# ---- 两个物理串口各跑一个独立 RTU 从站,分别对接 S331 #1 / #2 ----
|
||||||
|
# 严禁把两个 S331 并接到同一个 485 口
|
||||||
|
#
|
||||||
|
# ⚠ 现场部署必查两项(本台 EG828-CEW 实测踩坑记录):
|
||||||
|
# 1) 串口设备映射与面板丝印不一定一致。核实方法:cat /proc/tty/driver/serial
|
||||||
|
# 记下各口 rx 计数 → 从 PC 发一帧请求 → 再看哪个口 rx 增长,即为实际映射。
|
||||||
|
# 2) 有人系统自带 /usr/local/sbin/mcu_ctl(由 /etc/init.d/m300_script/S15mcu_ctl 开机拉起)
|
||||||
|
# 会占用 ttyS1/ttyS3/ttyS7 并抢走串口收到的数据,导致 RTU 从站收不到请求
|
||||||
|
# (现象:rx 计数持续增长、tx 不动、S331 全部超时)。
|
||||||
|
# 停用方法:pkill -9 -f mcu_ctl;再 mv S15mcu_ctl S15mcu_ctl.disabled 并 chmod -x。
|
||||||
|
# 检查是否残留:fuser -v /dev/ttyS1(应只剩 python)。每次网关重启后都要确认。
|
||||||
|
#
|
||||||
|
# 注意:两个口对外都用 slave_id=10(现场 S331 屏实测按 10 轮询)。
|
||||||
|
# 两条 485 物理独立,同号不冲突;TCP 侧的 10/20 是 S331 自己的地址,也不冲突。
|
||||||
|
#
|
||||||
|
# ⚠ 从站固件注意:pymodbus 自带 RTU framer 不支持多点 485,遇到同总线其它设备
|
||||||
|
# (S331 自己的流量计 67~75)的请求/应答会拼错帧抛异常,导致从站完全不回。
|
||||||
|
# 代码里已用 SafeRTUFramer 兜住,并对未知从站保持静默(ignore_missing_slaves)。
|
||||||
|
slaves:
|
||||||
|
- name: gateway_to_s331_1
|
||||||
|
port: /dev/ttyS1
|
||||||
|
slave_id: 10
|
||||||
|
baudrate: 19200
|
||||||
|
bytesize: 8
|
||||||
|
parity: N
|
||||||
|
stopbits: 1
|
||||||
|
timeout_s: 0.5
|
||||||
|
- name: gateway_to_s331_2
|
||||||
|
# 本台 EG828-CEW 实测串口映射:RS485-1→/dev/ttyS1,RS485-2→/dev/ttyS7(串口计数器实测确认)。
|
||||||
|
# 现场换网关时如映射不同,用 cat /proc/tty/driver/serial 对比收发计数核实后修改此处。
|
||||||
|
# ⚠ 现场实测:S331 #2 的屏也是按从站地址 10 轮询本口(不是 20),两条 485 物理独立,同号不冲突。
|
||||||
|
port: /dev/ttyS7
|
||||||
|
slave_id: 10
|
||||||
|
baudrate: 19200
|
||||||
|
bytesize: 8
|
||||||
|
parity: N
|
||||||
|
stopbits: 1
|
||||||
|
timeout_s: 0.5
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Air Compressor Gas-Electric Ratio Edge Gateway (EG828-CEW)
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=/opt/hx-gateway
|
||||||
|
Environment=PYTHONUNBUFFERED=1
|
||||||
|
ExecStart=/opt/hx-gateway/.venv/bin/python -m gateway.app --config /opt/hx-gateway/config/config.yaml
|
||||||
|
# 串口异常/程序异常自动重启;正常退出码 0 不重启
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
KillSignal=SIGTERM
|
||||||
|
TimeoutStopSec=20
|
||||||
|
# 串口权限(若改用非 root 用户,请将该用户加入 dialout 组)
|
||||||
|
User=root
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# EG828-CEW 边缘网关部署脚本(Debian)
|
||||||
|
# 用法:sudo bash deploy/install.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP_DIR=/opt/hx-gateway
|
||||||
|
DATA_DIR=/var/lib/hx-gateway
|
||||||
|
SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "请使用 root 运行:sudo bash deploy/install.sh" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 检查 Python 3.11 运行环境"
|
||||||
|
# 运行环境固定使用独立 Python 3.11,不影响系统自带 python3.8。
|
||||||
|
# 若 PATH 中已有 python3.11(例如已部署 python-build-standalone 并做了软链),则跳过 apt 安装。
|
||||||
|
if ! command -v python3.11 >/dev/null 2>&1; then
|
||||||
|
echo " 未检测到 python3.11,尝试通过 apt(deadsnakes) 安装..."
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y python3.11 python3.11-venv
|
||||||
|
else
|
||||||
|
echo " 已检测到 python3.11: $(command -v python3.11)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 部署程序到 ${APP_DIR}"
|
||||||
|
mkdir -p "${APP_DIR}" "${DATA_DIR}"
|
||||||
|
rm -rf "${APP_DIR}/gateway"
|
||||||
|
cp -r "${SRC_DIR}/gateway" "${APP_DIR}/gateway"
|
||||||
|
cp "${SRC_DIR}/requirements.txt" "${APP_DIR}/requirements.txt"
|
||||||
|
mkdir -p "${APP_DIR}/config"
|
||||||
|
# 现场已存在的配置不覆盖,避免升级时丢失点表
|
||||||
|
if [ ! -f "${APP_DIR}/config/config.yaml" ]; then
|
||||||
|
cp "${SRC_DIR}/config/config.yaml" "${APP_DIR}/config/config.yaml"
|
||||||
|
echo " 已写入默认配置,请按现场点表核对 ${APP_DIR}/config/config.yaml"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 创建虚拟环境并安装依赖"
|
||||||
|
python3.11 -m venv "${APP_DIR}/.venv"
|
||||||
|
if compgen -G "${SRC_DIR}/wheels/*.whl" >/dev/null; then
|
||||||
|
echo " 检测到本地 wheels,使用离线安装"
|
||||||
|
"${APP_DIR}/.venv/bin/pip" install --no-index --find-links="${SRC_DIR}/wheels" -r "${APP_DIR}/requirements.txt"
|
||||||
|
else
|
||||||
|
"${APP_DIR}/.venv/bin/pip" install --upgrade pip
|
||||||
|
"${APP_DIR}/.venv/bin/pip" install -r "${APP_DIR}/requirements.txt"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 安装 systemd 服务"
|
||||||
|
cp "${SRC_DIR}/deploy/hx-gateway.service" /etc/systemd/system/hx-gateway.service
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable hx-gateway
|
||||||
|
systemctl restart hx-gateway
|
||||||
|
|
||||||
|
echo "==> 完成。查看日志: journalctl -u hx-gateway -f"
|
||||||
|
echo " 寄存器映射自检: ${APP_DIR}/.venv/bin/python -m gateway.app --config ${APP_DIR}/config/config.yaml --print-map"
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
# 边缘网关 V3.3 模拟测试操作指南
|
||||||
|
|
||||||
|
**适用场景**:仅有人 EG828-CEW 网关一台实物,S331 和蘑菇云不在现场。
|
||||||
|
**核心思路**:PC 上跑 Mock TCP 数据源 + RTU 主站脚本,网关正常运行,验证端到端。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 前置准备
|
||||||
|
|
||||||
|
### 网关端(Debian Linux)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1) 装 Python 依赖(在项目目录下执行)
|
||||||
|
pip install pymodbus pyyaml decimal # decimal 标准库自带
|
||||||
|
|
||||||
|
# 2) 可选:创建 venv
|
||||||
|
python -m venv .venv && source .venv/bin/activate
|
||||||
|
|
||||||
|
# 3) 检查串口权限
|
||||||
|
ls -la /dev/ttyS1 /dev/ttyS2 # 必须存在且可读写
|
||||||
|
sudo usermod -aG dialout $USER # 把当前用户加入串口组,然后重新登录
|
||||||
|
```
|
||||||
|
|
||||||
|
### PC 端(Windows / Linux / Mac 均可)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install pymodbus pyserial pyyaml
|
||||||
|
# 可选:装 Modbus Poll(图形界面读 RTU),pymodbus 脚本已够用
|
||||||
|
```
|
||||||
|
|
||||||
|
### 网络连通性
|
||||||
|
|
||||||
|
```
|
||||||
|
网关 (EG828-CEW) ──以太网──► PC (跑 mock TCP) (网关必须能访问 PC 的 IP)
|
||||||
|
网关 /dev/ttyS1 ──485线──► PC USB-485 适配器 (用于测 RTU 从站 #1)
|
||||||
|
网关 /dev/ttyS2 ──485线──► PC USB-485 适配器 (用于测 RTU 从站 #2,可先只插一条)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 文件分发
|
||||||
|
|
||||||
|
把整个项目目录拷到网关(示例用 scp):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在 PC 上执行,替换为网关实际 IP
|
||||||
|
scp -r c:\Users\admin\Desktop\海信视像数采\chengxu user@<网关IP>:/opt/hx-gateway
|
||||||
|
ssh user@<网关IP> "cd /opt/hx-gateway && pip install -r requirements.txt" # 或手动装
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 单元测试(PC 端,无需网关)
|
||||||
|
|
||||||
|
最基础的验证,31 个 pytest 覆盖配置、寄存器编解码、气电比计算、线程锁、持久化:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd <项目目录>
|
||||||
|
python -m pytest tests -v
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:`31 passed in 2s`(Windows/Mac/Linux 都能跑,不需要网关)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Mock TCP 数据源启动(PC 端)
|
||||||
|
|
||||||
|
### 2.1 快速启动(单机模拟)
|
||||||
|
|
||||||
|
PC 上同时跑 3 个 Modbus TCP Server,完全模拟蘑菇云 + 2 台 S331:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在 PC 项目目录下执行
|
||||||
|
python tools/mock_tcp_servers.py --host 0.0.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
输出示例:
|
||||||
|
```
|
||||||
|
============================================================
|
||||||
|
V3.3 Mock TCP 数据源集群
|
||||||
|
============================================================
|
||||||
|
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 气量)
|
||||||
|
============================================================
|
||||||
|
```
|
||||||
|
|
||||||
|
> ⚠️ **端口说明**:s331_2 默认用 503(避免和 s331_1 的 502 同机器冲突)。而 config.yaml 里 s331_2 端口是 502,**有两种处理方式**:
|
||||||
|
>
|
||||||
|
> **A(推荐,快速)**:PC 上只跑 s331_1 + mogo_meter,s331_2 用 `--s331-2-port 502` 单独启动(改 mock 端口时再改回来)。或只验证网关能连上 mogo_meter + s331_1 即可,功能逻辑一样。
|
||||||
|
>
|
||||||
|
> **B**:临时改 config.yaml 里 s331_2 的 port 为 503,网关测完改回 502。
|
||||||
|
|
||||||
|
### 2.2 让网关能访问到 Mock
|
||||||
|
|
||||||
|
网关的 config.yaml 里 3 个设备的 host 默认是现场 IP:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
mogo_meter: host: 10.50.253.165 # 蘑菇云
|
||||||
|
s331_1: host: 10.50.253.181 # S331 #1
|
||||||
|
s331_2: host: 10.50.253.182 # S331 #2
|
||||||
|
```
|
||||||
|
|
||||||
|
**测试时**,把这 3 个 host 改成 PC 的局域网 IP(比如 PC 是 192.168.1.100):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 在网关上执行(先查 PC IP)
|
||||||
|
ping -c 1 <PC的局域网IP> # 确认网关能通 PC
|
||||||
|
|
||||||
|
# 临时改 config.yaml(网关端)
|
||||||
|
sed -i 's/10.50.253.165/<PC_IP>/g' config/config.yaml
|
||||||
|
sed -i 's/10.50.253.181/<PC_IP>/g' config/config.yaml
|
||||||
|
sed -i 's/10.50.253.182/<PC_IP>/g' config/config.yaml
|
||||||
|
# 如果 s331_2 跑在 503,还得改端口
|
||||||
|
sed -i 's/port: 502$/port: 503/' config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
**如果网关本机跑 mock**(只有一台网关也能测):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 网关端开两个 shell
|
||||||
|
# shell 1: 跑 mock(注意 s331_2 端口要改)
|
||||||
|
python tools/mock_tcp_servers.py --host 127.0.0.1 --s331-2-port 503
|
||||||
|
# shell 2: 改 config.yaml 三个 host 为 127.0.0.1,启动网关
|
||||||
|
sed -i 's/10.50.253.165/127.0.0.1/g; s/10.50.253.181/127.0.0.1/g; s/10.50.253.182/127.0.0.1/g' config/config.yaml
|
||||||
|
sed -i 's/^ port: 502$/ port: 503/' config/config.yaml
|
||||||
|
python -m gateway.app --config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 PC 防火墙放行
|
||||||
|
|
||||||
|
Windows 上要放行 1502、502、503 端口的入站 TCP;Linux 上:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow 1502/tcp
|
||||||
|
sudo ufw allow 502/tcp
|
||||||
|
sudo ufw allow 503/tcp
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 网关启动 & 端到端测试
|
||||||
|
|
||||||
|
### 3.1 网关启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 网关端,config.yaml 已改成指向 mock
|
||||||
|
python -m gateway.app --config config/config.yaml --log-level INFO
|
||||||
|
```
|
||||||
|
|
||||||
|
正常日志输出应包含:
|
||||||
|
```
|
||||||
|
[INFO] 启动网关:compressors=9, slaves=2
|
||||||
|
[INFO] RTU slave 10 绑定 /dev/ttyS1 (9600-N-8-1)
|
||||||
|
[INFO] RTU slave 20 绑定 /dev/ttyS2 (9600-N-8-1)
|
||||||
|
[INFO] 采集线程已启动: mogo_meter(2.0s) s331_1(2.0s) s331_2(2.0s)
|
||||||
|
[INFO] [状态] 3#空压机 瞬时气电比=1.23 kWh/m³ 小时=1.15 天=1.18 月=1.12
|
||||||
|
[INFO] [状态] 4#空压机 瞬时气电比=0.98 kWh/m³ 小时=1.02 天=1.01 月=1.00
|
||||||
|
...(每 60 秒打一次状态)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 验证采集是否正常
|
||||||
|
|
||||||
|
等网关跑 10 秒,让它至少采到一轮数据。**日志里每台机器的 4 种气电比都应该是非零数**(如果全 0 说明采集没连上 mock)。
|
||||||
|
|
||||||
|
手动核对 mock 填充值与计算值是否一致:
|
||||||
|
|
||||||
|
```
|
||||||
|
mock 3#:
|
||||||
|
power=15.5 kW flow=80.5 m³/h
|
||||||
|
瞬时气电比 = 15.5 / 80.5 = 0.1925 kWh/m³
|
||||||
|
|
||||||
|
mock 10#:
|
||||||
|
power=13.4 kW flow=85.6 m³/h
|
||||||
|
瞬时气电比 = 13.4 / 85.6 = 0.1565 kWh/m³
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:日志里 3# 瞬时值 ≈ 0.1925,10# ≈ 0.1565(允许 0.0001 精度误差)。
|
||||||
|
|
||||||
|
### 3.3 RTU 从站功能验证(PC 端连网关串口)
|
||||||
|
|
||||||
|
把网关 /dev/ttyS1 接到 PC 的 USB-485 适配器(PC 端显示为 COM3 或 /dev/ttyUSB0):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# PC 端执行
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期输出**:
|
||||||
|
```
|
||||||
|
slave_id=10 读 72 个寄存器 耗时 28.3 ms ✓
|
||||||
|
空压机 瞬时气电比 小时气电比 天气电比 月气电比 寄存器范围
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
3# 0.1925 0.1925 0.1925 0.1925 40001~40008
|
||||||
|
4# 0.1292 0.1292 0.1292 0.1292 40009~40016
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**检查点**:
|
||||||
|
- [x] 响应时间 < 50ms(9600 波特率下读 72 个寄存器约 20~30ms)
|
||||||
|
- [x] 每台机器 4 个 Float 解析出的数值都是有限数(非 NaN、非 0 除非真为 0)
|
||||||
|
- [x] 3# 第一组 Float(40001~40002)和网关日志里的瞬时气电比一致
|
||||||
|
|
||||||
|
**测两个从站并发**(把网关 /dev/ttyS1 和 /dev/ttyS2 各接一个 485 适配器,或先只测一个):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 两个串口各连 PC
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10,20
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:两个 slave_id 都能快速响应,互不干扰。
|
||||||
|
|
||||||
|
### 3.4 寄存器映射自检(网关端快速验证)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 网关端,打印映射后退出
|
||||||
|
python -m gateway.app --config config/config.yaml --print-map
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期输出**(必须和 V3.3 第 6 节完全一致):
|
||||||
|
```
|
||||||
|
RTU 保持寄存器映射(协议地址 0 基 / S4C 中 40001 起):
|
||||||
|
3#空压机 基址 0x0000 (寄存器 40001~40008): 瞬时/小时/天/月 气电比
|
||||||
|
4#空压机 基址 0x0008 (寄存器 40009~40016): 瞬时/小时/天/月 气电比
|
||||||
|
...
|
||||||
|
11#空压机 基址 0x0040 (寄存器 40065~40072): 瞬时/小时/天/月 气电比
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 高级测试项
|
||||||
|
|
||||||
|
### 4.1 断网容错(验收项)
|
||||||
|
|
||||||
|
1. 让网关 + mock 正常跑 30 秒(网关日志里 4 种气电比正常非零)
|
||||||
|
2. **直接关闭 mock_tcp_servers.py**(模拟蘑菇云/S331 全断)
|
||||||
|
3. **PC 端继续读 RTU**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# mock 已经关了,网关收不到新数据,但 RTU 从站不受影响
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10 --interval 1
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- [x] RTU 依然能瞬间读到**最后一次**的计算值(不是 0,是 mock 关闭前那一轮的值)
|
||||||
|
- [x] 网关不崩溃,日志里持续打印采集重连失败 + 指数退避(1s → 2s → 4s → 8s → ... 到 30s 封顶)
|
||||||
|
- [x] 重新启动 mock → 网关自动恢复采集,下一轮就能读到新值
|
||||||
|
|
||||||
|
### 4.2 跨整点/零点/月初复位逻辑
|
||||||
|
|
||||||
|
mock 脚本目前是静态值,可改成动态值让累计量每秒递增。或者直接改网关系统时间触发:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 网关端临时改时间(模拟跨整点)
|
||||||
|
date -s "13:59:55" # 先把时间调到接近整点
|
||||||
|
# 等 10 秒,让网关过 14:00:00
|
||||||
|
date -s "14:00:30" # 跳到整点后 30 秒
|
||||||
|
|
||||||
|
# 观察日志:小时气电比应该在整点瞬间用新基准开始计算
|
||||||
|
# 小时比值会从旧值变成 0(因为本小时起点累计量 == 当前累计量),然后随时间缓慢增长
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- [x] 整点后新周期内,累计差值 = 当前值 - 整点时记录的基准值,计算正确
|
||||||
|
- [x] 网关不崩溃,状态日志持续输出
|
||||||
|
|
||||||
|
### 4.3 掉电保持(验收项)
|
||||||
|
|
||||||
|
1. 让网关跑 **至少 6 分钟**(确保 SQLite 持久化完成一次,持久化间隔 300s=5min)
|
||||||
|
2. 直接断电(或 kill -9 进程)
|
||||||
|
3. 重新上电/启动
|
||||||
|
4. 观察启动日志:
|
||||||
|
|
||||||
|
```
|
||||||
|
[INFO] 从 SQLite 恢复周期基准值...
|
||||||
|
[INFO] 恢复成功:3# 天基准=... 月基准=... 时间戳=...
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- [x] 恢复后天气电比、月气电比的累计基准值是断电前的最后一次持久化值
|
||||||
|
- [x] 如果断电跨零点/月初,网关检测到后自动用重启时的最新累计值为新基准(代码已处理)
|
||||||
|
|
||||||
|
### 4.4 脏读防护(多线程安全)
|
||||||
|
|
||||||
|
网关内部 `store.py` 在更新寄存器镜像和 RTU 读请求之间用 `threading.Lock` 保护。验证方式:
|
||||||
|
|
||||||
|
让 2 台 S331(mock 或真 S331)同时高频读(每秒 10 次以上),持续 5 分钟,然后分析读到的寄存器值:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# PC 端开多个并行 RTU 主站脚本模拟高频读取
|
||||||
|
for i in 1 2 3 4 5; do
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10 --interval 0.1 > /tmp/rtu_read_$i.log &
|
||||||
|
done
|
||||||
|
# 等 5 分钟后 kill
|
||||||
|
# 分析日志里是否有"半新半旧"的情况(同一个空压机的 4 种气电比数值差过大)
|
||||||
|
```
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- [x] 同一台空压机的 4 种气电比应该来自**同一轮采集**(瞬时值 ≈ 当前真实值,小时值 ≥ 瞬时值)
|
||||||
|
- [x] 看不到"脏读":比如瞬时值是新采集的、小时值是旧采集的情况
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 故障排查速查
|
||||||
|
|
||||||
|
### 现象:日志里所有气电比都是 0
|
||||||
|
|
||||||
|
```
|
||||||
|
[INFO] 3#空压机 瞬时气电比=0.000 小时=0.000 天=0.000 月=0.000
|
||||||
|
```
|
||||||
|
|
||||||
|
**原因**:采集没连上 mock。排查:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 网关端
|
||||||
|
# 1) 能不能 ping 通 PC
|
||||||
|
ping -c 1 <PC_IP>
|
||||||
|
|
||||||
|
# 2) 能不能连上 mock 的端口
|
||||||
|
timeout 1 bash -c "echo >/dev/tcp/<PC_IP>/1502" && echo "1502 OK" || echo "1502 FAIL"
|
||||||
|
timeout 1 bash -c "echo >/dev/tcp/<PC_IP>/502" && echo "502 OK" || echo "502 FAIL"
|
||||||
|
timeout 1 bash -c "echo >/dev/tcp/<PC_IP>/503" && echo "503 OK" || echo "503 FAIL"
|
||||||
|
|
||||||
|
# 3) 用 probe.py 验证 mock 是不是正常响应
|
||||||
|
python -m gateway.probe --host <PC_IP> --port 1502 --slave 1 --start 148 --count 12
|
||||||
|
# 应该能看到 149~159 寄存器有非零值(3# 和 4# 的功率+电能)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 现象:RTU 读超时 / Modbus 错误
|
||||||
|
|
||||||
|
**原因**:
|
||||||
|
1. 串口参数不匹配 — 确认 RTU 主站脚本的 `--baud 9600`(网关 config.yaml 默认 9600)
|
||||||
|
2. 485 接线反了 — A 接 A、B 接 B,且有公共 GND
|
||||||
|
3. 从站地址错了 — config.yaml 里 slave_id=10 / 20,主站脚本 `--slave 10` / `--slave 20`
|
||||||
|
4. 网关没开 RTU 从站 — 网关进程必须在运行,检查 `ps aux | grep gateway`
|
||||||
|
|
||||||
|
### 现象:RTU 读到的数据类型不对(全是大数或乱码)
|
||||||
|
|
||||||
|
**原因**:字序不匹配。V3.3 规定 RTU 输出 Float 是 **ABCD 高字在前**(S4C 里选 FLOAT_B)。RTU 主站脚本默认就是 ABCD,Modbus Poll 里选 "Big Endian / Word Swap=Off"。
|
||||||
|
|
||||||
|
### 现象:RTU 响应慢(>100ms)
|
||||||
|
|
||||||
|
9600 波特率下读 72 个寄存器需要发送 8 字节请求 + 接收 146 字节响应(约 154 字符 / 960 bps = ~160ms)。如果只有 50ms 以下,正常。如果超时:
|
||||||
|
- 确认没有其他主站在同一个 485 口上轮询
|
||||||
|
- 把 RTU 从站配置里的 timeout_s 从 0.5 调大到 1.0
|
||||||
|
|
||||||
|
### 现象:进程启动时 open /dev/ttyS1 失败
|
||||||
|
|
||||||
|
```
|
||||||
|
Permission denied: '/dev/ttyS1'
|
||||||
|
```
|
||||||
|
|
||||||
|
**解决**:
|
||||||
|
```bash
|
||||||
|
sudo chmod 666 /dev/ttyS1 /dev/ttyS2
|
||||||
|
# 或永久:把用户加入 dialout 组
|
||||||
|
sudo usermod -aG dialout $USER && newgrp dialout
|
||||||
|
```
|
||||||
|
|
||||||
|
### 现象:mock 里的累计气量值解析出来是负数
|
||||||
|
|
||||||
|
**原因**:累计气量是 uint32,范围 0~4294967295。如果 mock 里超过这个范围会溢出(mock 脚本已经有校验)。另外字序必须是 ABCD(高字在前),如果 mock 写错了 CDAB,解析出来就会错。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 快速启动命令汇总
|
||||||
|
|
||||||
|
### PC 端(两个 shell)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# shell 1: mock 集群
|
||||||
|
cd <项目目录>
|
||||||
|
python tools/mock_tcp_servers.py --host 0.0.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
### 网关端(两个 shell)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# shell 1: 改 config 指向 mock(只需第一次)
|
||||||
|
sed -i 's/10.50.253.165/<PC_IP>/g; s/10.50.253.181/<PC_IP>/g; s/10.50.253.182/<PC_IP>/g' config/config.yaml
|
||||||
|
# (如果 s331_2 跑在 503)sed -i '0,/port: 502$/s/port: 502/port: 503/' config/config.yaml
|
||||||
|
|
||||||
|
# shell 2: 启动网关
|
||||||
|
cd /opt/hx-gateway
|
||||||
|
python -m gateway.app --config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### PC 端(RTU 验证)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10 # 单从站
|
||||||
|
python tools/rtu_client_test.py --port COM3 --slave 10,20 # 双从站并发
|
||||||
|
```
|
||||||
|
|
||||||
|
### 网关端(快速自检)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m gateway.app --config config/config.yaml --print-map # 寄存器映射
|
||||||
|
python -m pytest tests -q # 单元测试
|
||||||
|
python -m gateway.probe --host <PC_IP> --port 1502 --slave 1 --start 148 --count 12 # mock 电表核查
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 测完之后记得**还原 config.yaml**!
|
||||||
|
|
||||||
|
所有 IP/端口改动是为了 mock 测试,上线前必须还原:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout config/config.yaml # 或者手动改回现场 IP
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 验收标准对照(模拟测试中应覆盖的条目)
|
||||||
|
|
||||||
|
| 验收项 | 测试方法(见上方章节) | 预期 |
|
||||||
|
|---|---|---|
|
||||||
|
| RTU 响应速度 <50ms | 3.3 节 rtu_client_test.py 耗时 | 20~30ms |
|
||||||
|
| 双主站并发互不干扰 | 3.3 节 `--slave 10,20` 同时读 | 两从站各自 <50ms |
|
||||||
|
| 多协议并发采集 | 网关日志三路采集同时运行 | 无阻塞,周期 2s |
|
||||||
|
| 数据准确性 | mock 已知值 vs 网关计算 | 误差 <0.0001 |
|
||||||
|
| 断网容错 | 4.1 节关 mock | RTU 读到缓存值,不崩,自动重连 |
|
||||||
|
| 掉电保持 | 4.3 节断电重启 | 恢复天/月基准值 |
|
||||||
|
| 跨周期复位 | 4.2 节改系统时间 | 整点后新基准生效 |
|
||||||
|
| 脏读防护 | 4.4 节高频并发读 | 无半新半旧 |
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
# 边缘网关完整寄存器映射表(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
|
||||||
|
- 网关 RTU 输出 Float 字序: ABCD(ABCD = 高字在前)
|
||||||
|
|
||||||
|
## 表 A — 采集侧:蘑菇云电表(Modbus TCP 10.50.253.165:1502 slave_id=1)
|
||||||
|
|
||||||
|
| 空压机 | 信号 | 类型 | 字序 | scale | offset | 协议地址(0基) | 显示地址(4xxxx) |
|
||||||
|
|-------|------|------|------|-------|--------|--------------|----------------|
|
||||||
|
| 3# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **149** | 40150 |
|
||||||
|
| 3# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **151** | 40152 |
|
||||||
|
| 4# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **157** | 40158 |
|
||||||
|
| 4# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **159** | 40160 |
|
||||||
|
| 5# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **165** | 40166 |
|
||||||
|
| 5# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **167** | 40168 |
|
||||||
|
| 11# | 有功功率 kW | int32 | ABCD | ×0.001 | +0 | **197** | 40198 |
|
||||||
|
| 11# | 有功电能 kWh | int32 | ABCD | ×0.1 | +0 | **199** | 40200 |
|
||||||
|
| 6# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **173** | 40174 |
|
||||||
|
| 6# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **175** | 40176 |
|
||||||
|
| 7# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **181** | 40182 |
|
||||||
|
| 7# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **183** | 40184 |
|
||||||
|
| 8# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **189** | 40190 |
|
||||||
|
| 8# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **191** | 40192 |
|
||||||
|
| 9# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **213** | 40214 |
|
||||||
|
| 9# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **215** | 40216 |
|
||||||
|
| 10# | 有功功率 kW | float32 | ABCD | ×0.001 | +0 | **205** | 40206 |
|
||||||
|
| 10# | 有功电能 kWh | float32 | ABCD | ×0.1 | +0 | **207** | 40208 |
|
||||||
|
|
||||||
|
## 表 B — 采集侧:希尔思 S331 气量(IP 待现场分配,当前为占位示例)
|
||||||
|
|
||||||
|
⚠️ 重要:下表中 S331 的气量地址是**占位示例**,上线前必须用 probe.py 直连 S331 核对实际地址后替换 config.yaml。
|
||||||
|
|
||||||
|
| 空压机 | 来源 | 信号 | 类型 | 字序 | 协议地址(0基) | 显示地址(4xxxx) |
|
||||||
|
|-------|------|------|------|------|--------------|----------------|
|
||||||
|
| 3# | s331_1 (192.168.10.11) | 瞬时流量 m³/min | float32 | ABCD | **0** | 40001 |
|
||||||
|
| 3# | s331_1 (192.168.10.11) | 累计气量 m³ | float32 | ABCD | **2** | 40003 |
|
||||||
|
| 4# | s331_1 (192.168.10.11) | 瞬时流量 m³/min | float32 | ABCD | **4** | 40005 |
|
||||||
|
| 4# | s331_1 (192.168.10.11) | 累计气量 m³ | float32 | ABCD | **6** | 40007 |
|
||||||
|
| 5# | s331_1 (192.168.10.11) | 瞬时流量 m³/min | float32 | ABCD | **8** | 40009 |
|
||||||
|
| 5# | s331_1 (192.168.10.11) | 累计气量 m³ | float32 | ABCD | **10** | 40011 |
|
||||||
|
| 11# | s331_1 (192.168.10.11) | 瞬时流量 m³/min | float32 | ABCD | **12** | 40013 |
|
||||||
|
| 11# | s331_1 (192.168.10.11) | 累计气量 m³ | float32 | ABCD | **14** | 40015 |
|
||||||
|
| 6# | s331_2 (192.168.10.12) | 瞬时流量 m³/min | float32 | ABCD | **0** | 40001 |
|
||||||
|
| 6# | s331_2 (192.168.10.12) | 累计气量 m³ | float32 | ABCD | **2** | 40003 |
|
||||||
|
| 7# | s331_2 (192.168.10.12) | 瞬时流量 m³/min | float32 | ABCD | **4** | 40005 |
|
||||||
|
| 7# | s331_2 (192.168.10.12) | 累计气量 m³ | float32 | ABCD | **6** | 40007 |
|
||||||
|
| 8# | s331_2 (192.168.10.12) | 瞬时流量 m³/min | float32 | ABCD | **8** | 40009 |
|
||||||
|
| 8# | s331_2 (192.168.10.12) | 累计气量 m³ | float32 | ABCD | **10** | 40011 |
|
||||||
|
| 9# | s331_2 (192.168.10.12) | 瞬时流量 m³/min | float32 | ABCD | **12** | 40013 |
|
||||||
|
| 9# | s331_2 (192.168.10.12) | 累计气量 m³ | float32 | ABCD | **14** | 40015 |
|
||||||
|
| 10# | s331_2 (192.168.10.12) | 瞬时流量 m³/min | float32 | ABCD | **16** | 40017 |
|
||||||
|
| 10# | s331_2 (192.168.10.12) | 累计气量 m³ | float32 | ABCD | **18** | 40019 |
|
||||||
|
|
||||||
|
## 表 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) | 数据类型 |
|
||||||
|
|-------|-----------|--------|--------------|----------------|----------|
|
||||||
|
| 3# | 0 | 瞬时气电比 | **0~1** | 40001~40002 | Float32 (ABCD) |
|
||||||
|
| 3# | 0 | 小时气电比 | **2~3** | 40003~40004 | Float32 (ABCD) |
|
||||||
|
| 3# | 0 | 天气电比 | **4~5** | 40005~40006 | Float32 (ABCD) |
|
||||||
|
| 3# | 0 | 月气电比 | **6~7** | 40007~40008 | Float32 (ABCD) |
|
||||||
|
| 4# | 1 | 瞬时气电比 | **8~9** | 40009~40010 | Float32 (ABCD) |
|
||||||
|
| 4# | 1 | 小时气电比 | **10~11** | 40011~40012 | Float32 (ABCD) |
|
||||||
|
| 4# | 1 | 天气电比 | **12~13** | 40013~40014 | Float32 (ABCD) |
|
||||||
|
| 4# | 1 | 月气电比 | **14~15** | 40015~40016 | Float32 (ABCD) |
|
||||||
|
| 5# | 2 | 瞬时气电比 | **16~17** | 40017~40018 | Float32 (ABCD) |
|
||||||
|
| 5# | 2 | 小时气电比 | **18~19** | 40019~40020 | Float32 (ABCD) |
|
||||||
|
| 5# | 2 | 天气电比 | **20~21** | 40021~40022 | Float32 (ABCD) |
|
||||||
|
| 5# | 2 | 月气电比 | **22~23** | 40023~40024 | Float32 (ABCD) |
|
||||||
|
| 11# | 8 | 瞬时气电比 | **64~65** | 40065~40066 | Float32 (ABCD) |
|
||||||
|
| 11# | 8 | 小时气电比 | **66~67** | 40067~40068 | Float32 (ABCD) |
|
||||||
|
| 11# | 8 | 天气电比 | **68~69** | 40069~40070 | Float32 (ABCD) |
|
||||||
|
| 11# | 8 | 月气电比 | **70~71** | 40071~40072 | Float32 (ABCD) |
|
||||||
|
| 6# | 3 | 瞬时气电比 | **24~25** | 40025~40026 | Float32 (ABCD) |
|
||||||
|
| 6# | 3 | 小时气电比 | **26~27** | 40027~40028 | Float32 (ABCD) |
|
||||||
|
| 6# | 3 | 天气电比 | **28~29** | 40029~40030 | Float32 (ABCD) |
|
||||||
|
| 6# | 3 | 月气电比 | **30~31** | 40031~40032 | Float32 (ABCD) |
|
||||||
|
| 7# | 4 | 瞬时气电比 | **32~33** | 40033~40034 | Float32 (ABCD) |
|
||||||
|
| 7# | 4 | 小时气电比 | **34~35** | 40035~40036 | Float32 (ABCD) |
|
||||||
|
| 7# | 4 | 天气电比 | **36~37** | 40037~40038 | Float32 (ABCD) |
|
||||||
|
| 7# | 4 | 月气电比 | **38~39** | 40039~40040 | Float32 (ABCD) |
|
||||||
|
| 8# | 5 | 瞬时气电比 | **40~41** | 40041~40042 | Float32 (ABCD) |
|
||||||
|
| 8# | 5 | 小时气电比 | **42~43** | 40043~40044 | Float32 (ABCD) |
|
||||||
|
| 8# | 5 | 天气电比 | **44~45** | 40045~40046 | Float32 (ABCD) |
|
||||||
|
| 8# | 5 | 月气电比 | **46~47** | 40047~40048 | Float32 (ABCD) |
|
||||||
|
| 9# | 6 | 瞬时气电比 | **48~49** | 40049~40050 | Float32 (ABCD) |
|
||||||
|
| 9# | 6 | 小时气电比 | **50~51** | 40051~40052 | Float32 (ABCD) |
|
||||||
|
| 9# | 6 | 天气电比 | **52~53** | 40053~40054 | Float32 (ABCD) |
|
||||||
|
| 9# | 6 | 月气电比 | **54~55** | 40055~40056 | Float32 (ABCD) |
|
||||||
|
| 10# | 7 | 瞬时气电比 | **56~57** | 40057~40058 | Float32 (ABCD) |
|
||||||
|
| 10# | 7 | 小时气电比 | **58~59** | 40059~40060 | Float32 (ABCD) |
|
||||||
|
| 10# | 7 | 天气电比 | **60~61** | 40061~40062 | Float32 (ABCD) |
|
||||||
|
| 10# | 7 | 月气电比 | **62~63** | 40063~40064 | Float32 (ABCD) |
|
||||||
|
|
||||||
|
## 表 C-展开:从 40001 起顺序列出全部寄存器
|
||||||
|
|
||||||
|
| 显示地址 | 协议地址 | 空压机 | 气电比 | 数据类型 |
|
||||||
|
|----------|----------|-------|--------|----------|
|
||||||
|
| 40001~40002 | 0~1 | 3# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40003~40004 | 2~3 | 3# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40005~40006 | 4~5 | 3# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40007~40008 | 6~7 | 3# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40009~40010 | 8~9 | 4# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40011~40012 | 10~11 | 4# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40013~40014 | 12~13 | 4# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40015~40016 | 14~15 | 4# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40017~40018 | 16~17 | 5# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40019~40020 | 18~19 | 5# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40021~40022 | 20~21 | 5# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40023~40024 | 22~23 | 5# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40025~40026 | 24~25 | 6# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40027~40028 | 26~27 | 6# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40029~40030 | 28~29 | 6# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40031~40032 | 30~31 | 6# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40033~40034 | 32~33 | 7# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40035~40036 | 34~35 | 7# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40037~40038 | 36~37 | 7# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40039~40040 | 38~39 | 7# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40041~40042 | 40~41 | 8# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40043~40044 | 42~43 | 8# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40045~40046 | 44~45 | 8# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40047~40048 | 46~47 | 8# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40049~40050 | 48~49 | 9# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40051~40052 | 50~51 | 9# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40053~40054 | 52~53 | 9# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40055~40056 | 54~55 | 9# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40057~40058 | 56~57 | 10# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40059~40060 | 58~59 | 10# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40061~40062 | 60~61 | 10# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40063~40064 | 62~63 | 10# | 月气电比 | Float32 (ABCD) |
|
||||||
|
| 40065~40066 | 64~65 | 11# | 瞬时气电比 | Float32 (ABCD) |
|
||||||
|
| 40067~40068 | 66~67 | 11# | 小时气电比 | Float32 (ABCD) |
|
||||||
|
| 40069~40070 | 68~69 | 11# | 天气电比 | Float32 (ABCD) |
|
||||||
|
| 40071~40072 | 70~71 | 11# | 月气电比 | Float32 (ABCD) |
|
||||||
|
|
||||||
|
## 按设备的连续采集块规划(减少 TCP 请求次数)
|
||||||
|
|
||||||
|
### 蘑菇云电表 — 网关一次请求覆盖全部点位:
|
||||||
|
- 蘑菇云电表:地址 149 ~ 216 共 68 个寄存器,一次 Read Holding Registers 即可读完 9 台机器的功率+电能(仅约 0.2s)
|
||||||
|
|
||||||
|
### s331_1 气量 — 地址 0 ~ 15 共 16 个寄存器,一次请求可读完
|
||||||
|
### s331_2 气量 — 地址 0 ~ 19 共 20 个寄存器,一次请求可读完
|
||||||
|
|
||||||
|
## S4C-Display 侧配置要点(给现场工程师)
|
||||||
|
- 新增设备:Modbus RTU,地址 10 接 /dev/ttyS1 链路 → 读取网关
|
||||||
|
- 新增设备:Modbus RTU,地址 20 接 /dev/ttyS2 链路 → 读取网关
|
||||||
|
- 值地址填协议地址 0 基(0、2、4、6…),**千万不要勾 Base 1**
|
||||||
|
- 数据类型选 FLOAT
|
||||||
|
|
||||||
|
---
|
||||||
|
自动生成自 config/config.yaml(compressors=9, slaves=2)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""海信视像空压机气电比边缘网关。"""
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
"""边缘网关主程序。
|
||||||
|
|
||||||
|
线程/任务划分:
|
||||||
|
- 采集线程:每个 TCP 设备一个(S331 #1、S331 #2、410S),指数退避重连;
|
||||||
|
- 主线程事件循环:两个独立 Modbus RTU 从站(/dev/ttyS1、/dev/ttyS2);
|
||||||
|
- 维护线程:定时 SQLite 掉电保持 + 周期状态日志。
|
||||||
|
|
||||||
|
启动:python -m gateway.app --config config/config.yaml
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
from logging.handlers import RotatingFileHandler
|
||||||
|
from typing import Any, Iterable, Optional
|
||||||
|
|
||||||
|
from . import __version__
|
||||||
|
from .config import GatewayCfg, load_config
|
||||||
|
from .persistence import SqliteStore
|
||||||
|
from .poller import PointBinding, TcpPoller
|
||||||
|
from .rtu import run_slaves
|
||||||
|
from .store import REGISTERS_PER_MACHINE, StateStore
|
||||||
|
|
||||||
|
log = logging.getLogger("gateway")
|
||||||
|
|
||||||
|
|
||||||
|
def _setup_logging(cfg: GatewayCfg, level_override: Optional[str]) -> None:
|
||||||
|
level = getattr(logging, (level_override or cfg.log_level).upper(), logging.INFO)
|
||||||
|
handlers: list[logging.Handler] = [logging.StreamHandler()]
|
||||||
|
if cfg.log_file:
|
||||||
|
handlers.append(
|
||||||
|
RotatingFileHandler(
|
||||||
|
cfg.log_file, maxBytes=10 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
logging.basicConfig(
|
||||||
|
level=level,
|
||||||
|
format="%(asctime)s.%(msecs)03d %(levelname)-5s [%(threadName)s] %(name)s: %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S",
|
||||||
|
handlers=handlers,
|
||||||
|
force=True,
|
||||||
|
)
|
||||||
|
# 第三方库日志降噪
|
||||||
|
for noisy in ("pymodbus", "pymodbus.logging", "asyncio", "serial_asyncio"):
|
||||||
|
logging.getLogger(noisy).setLevel(logging.WARNING)
|
||||||
|
|
||||||
|
|
||||||
|
def _log_register_map(compressors: Iterable[Any]) -> None:
|
||||||
|
log.info("RTU 保持寄存器映射(协议地址 0 基 / S4C 中 40001 起):")
|
||||||
|
for cfg in sorted(compressors, key=lambda c: c.register_index):
|
||||||
|
base = cfg.register_index * REGISTERS_PER_MACHINE
|
||||||
|
log.info(
|
||||||
|
" %-8s 基址 0x%04X (寄存器 %d~%d): 瞬时/小时/天/月 气电比",
|
||||||
|
cfg.name,
|
||||||
|
base,
|
||||||
|
40001 + base,
|
||||||
|
40001 + base + REGISTERS_PER_MACHINE - 1,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_values(store: StateStore, values: dict[tuple[int, str], Any]) -> None:
|
||||||
|
updates: dict[int, dict[str, Any]] = {}
|
||||||
|
for (machine_id, field), value in values.items():
|
||||||
|
updates.setdefault(machine_id, {})[field] = value
|
||||||
|
store.update(updates)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_pollers(
|
||||||
|
cfg: GatewayCfg, store: StateStore, stop_event: threading.Event
|
||||||
|
) -> list[TcpPoller]:
|
||||||
|
per_device: dict[str, list[PointBinding]] = {}
|
||||||
|
for comp in cfg.compressors:
|
||||||
|
per_device.setdefault(comp.s331, []).extend(
|
||||||
|
[
|
||||||
|
PointBinding(comp.id, "instant_flow", comp.flow_instant),
|
||||||
|
PointBinding(comp.id, "total_flow", comp.flow_total),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
per_device.setdefault(comp.meter, []).extend(
|
||||||
|
[
|
||||||
|
PointBinding(comp.id, "instant_power", comp.power_instant),
|
||||||
|
PointBinding(comp.id, "total_energy", comp.energy_total),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
pollers: list[TcpPoller] = []
|
||||||
|
for device_name, bindings in per_device.items():
|
||||||
|
device = cfg.devices[device_name]
|
||||||
|
pollers.append(
|
||||||
|
TcpPoller(
|
||||||
|
device,
|
||||||
|
bindings,
|
||||||
|
lambda values, _store=store: _apply_values(_store, values),
|
||||||
|
stop_event,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return pollers
|
||||||
|
|
||||||
|
|
||||||
|
class MaintenanceWorker(threading.Thread):
|
||||||
|
"""定时落盘与状态日志。"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
cfg: GatewayCfg,
|
||||||
|
store: StateStore,
|
||||||
|
db: SqliteStore,
|
||||||
|
pollers: list[TcpPoller],
|
||||||
|
stop_event: threading.Event,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(name="maintenance", daemon=True)
|
||||||
|
self._cfg = cfg
|
||||||
|
self._store = store
|
||||||
|
self._db = db
|
||||||
|
self._pollers = pollers
|
||||||
|
self._stop_event = stop_event
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
last_persist = time.monotonic()
|
||||||
|
last_status = last_persist
|
||||||
|
while not self._stop_event.wait(1.0):
|
||||||
|
now = time.monotonic()
|
||||||
|
if now - last_persist >= self._cfg.persist_interval_s:
|
||||||
|
self.persist()
|
||||||
|
last_persist = now
|
||||||
|
if now - last_status >= self._cfg.status_interval_s:
|
||||||
|
self._log_status()
|
||||||
|
last_status = now
|
||||||
|
|
||||||
|
def persist(self) -> None:
|
||||||
|
try:
|
||||||
|
self._db.save(self._store.persist_payloads(), datetime.now())
|
||||||
|
log.debug("状态已保存到 %s", self._cfg.db_path)
|
||||||
|
except Exception: # noqa: BLE001 - 落盘失败不能影响采集与从站
|
||||||
|
log.exception("保存状态到 SQLite 失败")
|
||||||
|
|
||||||
|
def _log_status(self) -> None:
|
||||||
|
now = datetime.now()
|
||||||
|
stale = self._cfg.stale_warn_s
|
||||||
|
for row in self._store.snapshot(now):
|
||||||
|
ratios = row["ratios"]
|
||||||
|
age = row["age_s"]
|
||||||
|
log.info(
|
||||||
|
"状态 %-8s 瞬时=%-9.4f 时=%-9.4f 日=%-9.4f 月=%-9.4f | 瞬时流量=%s 累计气量=%s 瞬时功率=%s 累计电量=%s | 数据延迟=%s",
|
||||||
|
row["name"],
|
||||||
|
ratios["instant"],
|
||||||
|
ratios["hour"],
|
||||||
|
ratios["day"],
|
||||||
|
ratios["month"],
|
||||||
|
_fmt(row["instant_flow"]),
|
||||||
|
_fmt(row["total_flow"]),
|
||||||
|
_fmt(row["instant_power"]),
|
||||||
|
_fmt(row["total_energy"]),
|
||||||
|
"无数据" if age is None else f"{age:.0f}s",
|
||||||
|
)
|
||||||
|
if age is not None and age > stale:
|
||||||
|
log.warning("%s 数据已 %.0fs 未更新,寄存器继续提供最后一次计算结果", row["name"], age)
|
||||||
|
for status in (poller.status() for poller in self._pollers):
|
||||||
|
last_ok = status["last_ok_age_s"]
|
||||||
|
log.info(
|
||||||
|
"链路 %-10s %-18s 成功=%d 失败=%d 最近成功=%s 最近错误=%s",
|
||||||
|
status["name"],
|
||||||
|
status["target"],
|
||||||
|
status["ok_cycles"],
|
||||||
|
status["fail_cycles"],
|
||||||
|
"-" if last_ok is None else f"{last_ok}s",
|
||||||
|
status["last_error"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _fmt(value: Optional[float]) -> str:
|
||||||
|
if value is None:
|
||||||
|
return "-"
|
||||||
|
if abs(value) >= 10000:
|
||||||
|
return f"{value:.1f}"
|
||||||
|
return f"{value:.4f}".rstrip("0").rstrip(".")
|
||||||
|
|
||||||
|
|
||||||
|
async def _serve(cfg: GatewayCfg, store: StateStore, stop_event: threading.Event) -> None:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||||
|
try:
|
||||||
|
loop.add_signal_handler(sig, stop_event.set)
|
||||||
|
except (NotImplementedError, RuntimeError, ValueError):
|
||||||
|
pass
|
||||||
|
await run_slaves(cfg.slaves, store, stop_event)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_args(argv: Optional[list[str]]) -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description="空压机气电比边缘网关(EG828-CEW)")
|
||||||
|
parser.add_argument("--config", default="config/config.yaml", help="配置文件路径")
|
||||||
|
parser.add_argument("--log-level", default=None, help="覆盖日志级别,如 DEBUG")
|
||||||
|
parser.add_argument("--print-map", action="store_true", help="仅打印寄存器映射后退出")
|
||||||
|
return parser.parse_args(argv)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Optional[list[str]] = None) -> int:
|
||||||
|
args = _parse_args(argv)
|
||||||
|
cfg = load_config(args.config)
|
||||||
|
_setup_logging(cfg, args.log_level)
|
||||||
|
|
||||||
|
store = StateStore(cfg.compressors, cfg.register_float_order)
|
||||||
|
_log_register_map(cfg.compressors)
|
||||||
|
if args.print_map:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
log.info("边缘网关启动 (version=%s, 机器数=%d)", __version__, len(cfg.compressors))
|
||||||
|
|
||||||
|
db = SqliteStore(cfg.db_path)
|
||||||
|
payloads = db.load()
|
||||||
|
if payloads:
|
||||||
|
restored = store.restore(payloads)
|
||||||
|
log.info("已从 %s 恢复 %d 台机器状态(上次保存 %s)", cfg.db_path, restored, db.last_save_time())
|
||||||
|
|
||||||
|
stop_event = threading.Event()
|
||||||
|
pollers = _build_pollers(cfg, store, stop_event)
|
||||||
|
for poller in pollers:
|
||||||
|
poller.start()
|
||||||
|
maintenance = MaintenanceWorker(cfg, store, db, pollers, stop_event)
|
||||||
|
maintenance.start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.run(_serve(cfg, store, stop_event))
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
stop_event.set()
|
||||||
|
maintenance.join(timeout=5)
|
||||||
|
for poller in pollers:
|
||||||
|
poller.join(timeout=2)
|
||||||
|
try:
|
||||||
|
db.save(store.persist_payloads(), datetime.now())
|
||||||
|
log.info("退出前状态已保存到 %s", cfg.db_path)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
log.exception("退出前保存状态失败")
|
||||||
|
log.info("边缘网关已退出")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
"""配置加载与校验。
|
||||||
|
|
||||||
|
所有设备点位均在 YAML 中声明,现场点表变化时只改配置、不改代码。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from decimal import Decimal, InvalidOperation
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
# 支持的数据类型 -> 寄存器宽度
|
||||||
|
TYPE_WIDTH: dict[str, int] = {
|
||||||
|
"int16": 1,
|
||||||
|
"uint16": 1,
|
||||||
|
"int32": 2,
|
||||||
|
"uint32": 2,
|
||||||
|
"float32": 2,
|
||||||
|
"int64": 4,
|
||||||
|
"uint64": 4,
|
||||||
|
"float64": 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
WORD_ORDERS = ("ABCD", "CDAB", "big", "little")
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigError(ValueError):
|
||||||
|
"""配置文件不合法。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _decimal(value: Any, default: str = "1") -> Decimal:
|
||||||
|
if value is None:
|
||||||
|
return Decimal(default)
|
||||||
|
try:
|
||||||
|
return Decimal(str(value))
|
||||||
|
except InvalidOperation as exc: # pragma: no cover - 仅在配置写错时触发
|
||||||
|
raise ConfigError(f"非法数值: {value!r}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Point:
|
||||||
|
"""一个测量点位。
|
||||||
|
|
||||||
|
address 为 0 基协议地址(40001 -> 0)。
|
||||||
|
scale/offset 用于工程值换算:工程值 = 原始值 * scale + offset。
|
||||||
|
"""
|
||||||
|
|
||||||
|
address: int
|
||||||
|
type: str = "float32"
|
||||||
|
word_order: str = "ABCD"
|
||||||
|
scale: Decimal = field(default_factory=lambda: Decimal(1))
|
||||||
|
offset: Decimal = field(default_factory=lambda: Decimal(0))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def width(self) -> int:
|
||||||
|
return TYPE_WIDTH[self.type]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def order(self) -> str:
|
||||||
|
"""统一为 ABCD / CDAB 两种字序。"""
|
||||||
|
return "CDAB" if self.word_order.lower() in ("cdab", "little") else "ABCD"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class DeviceCfg:
|
||||||
|
name: str
|
||||||
|
host: str
|
||||||
|
port: int = 502
|
||||||
|
slave_id: int = 1
|
||||||
|
timeout_s: float = 1.0
|
||||||
|
poll_interval_s: float = 2.0
|
||||||
|
address_offset: int = 0
|
||||||
|
max_registers_per_read: int = 60
|
||||||
|
max_gap: int = 4
|
||||||
|
reconnect_min_s: float = 1.0
|
||||||
|
reconnect_max_s: float = 30.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CompressorCfg:
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
s331: str
|
||||||
|
meter: str
|
||||||
|
register_index: int
|
||||||
|
flow_instant: Point
|
||||||
|
flow_total: Point
|
||||||
|
power_instant: Point
|
||||||
|
energy_total: Point
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SlaveCfg:
|
||||||
|
name: str
|
||||||
|
port: str
|
||||||
|
slave_id: int
|
||||||
|
baudrate: int = 9600
|
||||||
|
bytesize: int = 8
|
||||||
|
parity: str = "N"
|
||||||
|
stopbits: int = 1
|
||||||
|
timeout_s: float = 0.5
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class GatewayCfg:
|
||||||
|
db_path: str
|
||||||
|
log_level: str = "INFO"
|
||||||
|
log_file: str = ""
|
||||||
|
persist_interval_s: float = 300.0
|
||||||
|
status_interval_s: float = 60.0
|
||||||
|
stale_warn_s: float = 20.0
|
||||||
|
register_float_order: str = "ABCD"
|
||||||
|
devices: dict[str, DeviceCfg] = field(default_factory=dict)
|
||||||
|
compressors: list[CompressorCfg] = field(default_factory=list)
|
||||||
|
slaves: list[SlaveCfg] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def _point(raw: dict[str, Any], device_offset: int, where: str) -> Point:
|
||||||
|
if not isinstance(raw, dict) or "address" not in raw:
|
||||||
|
raise ConfigError(f"{where}: 缺少 address")
|
||||||
|
ptype = str(raw.get("type", "float32")).lower()
|
||||||
|
if ptype not in TYPE_WIDTH:
|
||||||
|
raise ConfigError(f"{where}: 不支持的数据类型 {ptype}")
|
||||||
|
word_order = str(raw.get("word_order", "ABCD")).upper()
|
||||||
|
if word_order not in ("ABCD", "CDAB"):
|
||||||
|
raise ConfigError(f"{where}: word_order 只能是 ABCD 或 CDAB")
|
||||||
|
address = int(raw["address"]) + int(raw.get("address_offset", 0)) + device_offset
|
||||||
|
if address < 0:
|
||||||
|
raise ConfigError(f"{where}: 地址不能为负 ({address})")
|
||||||
|
return Point(
|
||||||
|
address=address,
|
||||||
|
type=ptype,
|
||||||
|
word_order=word_order,
|
||||||
|
scale=_decimal(raw.get("scale"), "1"),
|
||||||
|
offset=_decimal(raw.get("offset"), "0"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _device(name: str, raw: dict[str, Any]) -> DeviceCfg:
|
||||||
|
if not isinstance(raw, dict) or "host" not in raw:
|
||||||
|
raise ConfigError(f"devices.{name}: 缺少 host")
|
||||||
|
return DeviceCfg(
|
||||||
|
name=name,
|
||||||
|
host=str(raw["host"]),
|
||||||
|
port=int(raw.get("port", 502)),
|
||||||
|
slave_id=int(raw.get("slave_id", 1)),
|
||||||
|
timeout_s=float(raw.get("timeout_s", 1.0)),
|
||||||
|
poll_interval_s=float(raw.get("poll_interval_s", 2.0)),
|
||||||
|
address_offset=int(raw.get("address_offset", 0)),
|
||||||
|
max_registers_per_read=int(raw.get("max_registers_per_read", 60)),
|
||||||
|
max_gap=int(raw.get("max_gap", 4)),
|
||||||
|
reconnect_min_s=float(raw.get("reconnect_min_s", 1.0)),
|
||||||
|
reconnect_max_s=float(raw.get("reconnect_max_s", 30.0)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _compressor(raw: dict[str, Any], devices: dict[str, DeviceCfg]) -> CompressorCfg:
|
||||||
|
cid = int(raw["id"])
|
||||||
|
where = f"compressors[id={cid}]"
|
||||||
|
s331 = str(raw["s331"])
|
||||||
|
meter = str(raw["meter"])
|
||||||
|
for dev in (s331, meter):
|
||||||
|
if dev not in devices:
|
||||||
|
raise ConfigError(f"{where}: 引用了未定义的设备 {dev}")
|
||||||
|
flow_offset = devices[s331].address_offset
|
||||||
|
meter_offset = devices[meter].address_offset
|
||||||
|
return CompressorCfg(
|
||||||
|
id=cid,
|
||||||
|
name=str(raw.get("name", f"{cid}#空压机")),
|
||||||
|
s331=s331,
|
||||||
|
meter=meter,
|
||||||
|
register_index=int(raw.get("register_index", cid - 1)),
|
||||||
|
flow_instant=_point(raw["flow_instant"], flow_offset, f"{where}.flow_instant"),
|
||||||
|
flow_total=_point(raw["flow_total"], flow_offset, f"{where}.flow_total"),
|
||||||
|
power_instant=_point(raw["power_instant"], meter_offset, f"{where}.power_instant"),
|
||||||
|
energy_total=_point(raw["energy_total"], meter_offset, f"{where}.energy_total"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _slave(raw: dict[str, Any]) -> SlaveCfg:
|
||||||
|
if "port" not in raw:
|
||||||
|
raise ConfigError("slaves: 缺少 port")
|
||||||
|
slave_id = int(raw.get("slave_id", 1))
|
||||||
|
if not 1 <= slave_id <= 247:
|
||||||
|
raise ConfigError(f"slaves.{raw.get('name', raw['port'])}: slave_id 必须在 1~247")
|
||||||
|
parity = str(raw.get("parity", "N")).upper()
|
||||||
|
if parity not in ("N", "E", "O"):
|
||||||
|
raise ConfigError(f"slaves.{raw.get('name', raw['port'])}: parity 只能是 N/E/O")
|
||||||
|
return SlaveCfg(
|
||||||
|
name=str(raw.get("name", Path(str(raw["port"])).name)),
|
||||||
|
port=str(raw["port"]),
|
||||||
|
slave_id=slave_id,
|
||||||
|
baudrate=int(raw.get("baudrate", 9600)),
|
||||||
|
bytesize=int(raw.get("bytesize", 8)),
|
||||||
|
parity=parity,
|
||||||
|
stopbits=int(raw.get("stopbits", 1)),
|
||||||
|
timeout_s=float(raw.get("timeout_s", 0.5)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(path: str | Path) -> GatewayCfg:
|
||||||
|
"""读取 YAML 并做完整性校验。"""
|
||||||
|
cfg_path = Path(path)
|
||||||
|
if not cfg_path.is_file():
|
||||||
|
raise ConfigError(f"配置文件不存在: {cfg_path}")
|
||||||
|
with cfg_path.open("r", encoding="utf-8") as fp:
|
||||||
|
raw = yaml.safe_load(fp) or {}
|
||||||
|
|
||||||
|
gw = raw.get("gateway") or {}
|
||||||
|
devices = {name: _device(name, item) for name, item in (raw.get("devices") or {}).items()}
|
||||||
|
if not devices:
|
||||||
|
raise ConfigError("devices 不能为空")
|
||||||
|
|
||||||
|
raw_compressors = raw.get("compressors") or []
|
||||||
|
if not raw_compressors:
|
||||||
|
raise ConfigError("compressors 不能为空")
|
||||||
|
compressors = [_compressor(item, devices) for item in raw_compressors]
|
||||||
|
|
||||||
|
ids = [c.id for c in compressors]
|
||||||
|
if len(ids) != len(set(ids)):
|
||||||
|
raise ConfigError("compressors.id 存在重复")
|
||||||
|
indexes = [c.register_index for c in compressors]
|
||||||
|
if len(indexes) != len(set(indexes)):
|
||||||
|
raise ConfigError("register_index 存在重复,会导致寄存器地址冲突")
|
||||||
|
if min(indexes) < 0:
|
||||||
|
raise ConfigError("register_index 不能为负")
|
||||||
|
|
||||||
|
slaves = [_slave(item) for item in (raw.get("slaves") or [])]
|
||||||
|
if not slaves:
|
||||||
|
raise ConfigError("slaves 不能为空(需要为两个 S331 各配置一个 RTU 从站)")
|
||||||
|
ports = [s.port for s in slaves]
|
||||||
|
if len(ports) != len(set(ports)):
|
||||||
|
raise ConfigError("slaves.port 重复:两个 S331 必须使用两个独立物理串口")
|
||||||
|
|
||||||
|
float_order = str(gw.get("register_float_order", "ABCD")).upper()
|
||||||
|
if float_order not in ("ABCD", "CDAB"):
|
||||||
|
raise ConfigError("gateway.register_float_order 只能是 ABCD 或 CDAB")
|
||||||
|
|
||||||
|
return GatewayCfg(
|
||||||
|
db_path=str(gw.get("db_path", "gateway.db")),
|
||||||
|
log_level=str(gw.get("log_level", "INFO")).upper(),
|
||||||
|
log_file=str(gw.get("log_file", "") or ""),
|
||||||
|
persist_interval_s=float(gw.get("persist_interval_s", 300)),
|
||||||
|
status_interval_s=float(gw.get("status_interval_s", 60)),
|
||||||
|
stale_warn_s=float(gw.get("stale_warn_s", 20)),
|
||||||
|
register_float_order=float_order,
|
||||||
|
devices=devices,
|
||||||
|
compressors=compressors,
|
||||||
|
slaves=slaves,
|
||||||
|
)
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
"""单台空压机的数据对象与气电比计算。
|
||||||
|
|
||||||
|
计算口径:
|
||||||
|
瞬时气电比 = 瞬时功率 / 瞬时流量
|
||||||
|
小时气电比 = (本小时末累计电量 - 本小时起点累计电量) / (本小时末累计气量 - 本小时起点累计气量)
|
||||||
|
天气电比 / 月气电比 同理,仅在整点 / 零点 / 月初切换基准。
|
||||||
|
|
||||||
|
全部使用 Decimal 计算,避免 float 累积误差;周期切换通过“基准值复位”实现。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
PERIODS = ("hour", "day", "month")
|
||||||
|
RATIO_KEYS = ("instant", "hour", "day", "month")
|
||||||
|
ZERO = Decimal(0)
|
||||||
|
_UNSET = object()
|
||||||
|
|
||||||
|
|
||||||
|
def period_keys(now: datetime) -> dict[str, str]:
|
||||||
|
"""返回当前时刻所属的小时/天/月标识,用于判断是否跨周期。"""
|
||||||
|
return {
|
||||||
|
"hour": now.strftime("%Y%m%d%H"),
|
||||||
|
"day": now.strftime("%Y%m%d"),
|
||||||
|
"month": now.strftime("%Y%m"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ratio(numerator: Optional[Decimal], denominator: Optional[Decimal]) -> Decimal:
|
||||||
|
if numerator is None or denominator is None:
|
||||||
|
return ZERO
|
||||||
|
if denominator <= 0 or numerator < 0:
|
||||||
|
return ZERO
|
||||||
|
return numerator / denominator
|
||||||
|
|
||||||
|
|
||||||
|
def _dec(value: Any) -> Optional[Decimal]:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return value if isinstance(value, Decimal) else Decimal(str(value))
|
||||||
|
|
||||||
|
|
||||||
|
def _s(value: Optional[Decimal]) -> Optional[str]:
|
||||||
|
return None if value is None else str(value)
|
||||||
|
|
||||||
|
|
||||||
|
class MachineState:
|
||||||
|
"""一台空压机的实时值、周期基准与四种气电比。"""
|
||||||
|
|
||||||
|
def __init__(self, machine_id: int, name: str, register_index: int) -> None:
|
||||||
|
self.machine_id = machine_id
|
||||||
|
self.name = name
|
||||||
|
self.register_index = register_index
|
||||||
|
|
||||||
|
self.instant_flow: Optional[Decimal] = None
|
||||||
|
self.total_flow: Optional[Decimal] = None
|
||||||
|
self.instant_power: Optional[Decimal] = None
|
||||||
|
self.total_energy: Optional[Decimal] = None
|
||||||
|
|
||||||
|
self.ratios: dict[str, Decimal] = {key: ZERO for key in RATIO_KEYS}
|
||||||
|
self.flow_time: Optional[datetime] = None
|
||||||
|
self.power_time: Optional[datetime] = None
|
||||||
|
self.ratios_time: Optional[datetime] = None
|
||||||
|
|
||||||
|
self._keys: dict[str, str] = {p: "" for p in PERIODS}
|
||||||
|
# 周期基准:(累计气量, 累计电量)
|
||||||
|
self._bases: dict[str, Optional[tuple[Decimal, Decimal]]] = {p: None for p in PERIODS}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ 更新
|
||||||
|
def apply(
|
||||||
|
self,
|
||||||
|
now: datetime,
|
||||||
|
*,
|
||||||
|
instant_flow: Any = _UNSET,
|
||||||
|
total_flow: Any = _UNSET,
|
||||||
|
instant_power: Any = _UNSET,
|
||||||
|
total_energy: Any = _UNSET,
|
||||||
|
) -> None:
|
||||||
|
"""写入新采样值(缺省字段表示本次未更新),随后重算比值。"""
|
||||||
|
if instant_flow is not _UNSET:
|
||||||
|
self.instant_flow = _dec(instant_flow)
|
||||||
|
self.flow_time = now
|
||||||
|
if total_flow is not _UNSET:
|
||||||
|
self.total_flow = _dec(total_flow)
|
||||||
|
self.flow_time = now
|
||||||
|
if instant_power is not _UNSET:
|
||||||
|
self.instant_power = _dec(instant_power)
|
||||||
|
self.power_time = now
|
||||||
|
if total_energy is not _UNSET:
|
||||||
|
self.total_energy = _dec(total_energy)
|
||||||
|
self.power_time = now
|
||||||
|
self._refresh(now)
|
||||||
|
|
||||||
|
def _refresh(self, now: datetime) -> None:
|
||||||
|
keys = period_keys(now)
|
||||||
|
totals_ready = self.total_flow is not None and self.total_energy is not None
|
||||||
|
|
||||||
|
for period in PERIODS:
|
||||||
|
if self._keys[period] != keys[period]:
|
||||||
|
# 跨周期:基准清零,使用新周期内的第一次累计值作为起点
|
||||||
|
self._keys[period] = keys[period]
|
||||||
|
self._bases[period] = None
|
||||||
|
if self._bases[period] is None and totals_ready:
|
||||||
|
self._bases[period] = (self.total_flow, self.total_energy)
|
||||||
|
|
||||||
|
self.ratios["instant"] = _ratio(self.instant_power, self.instant_flow)
|
||||||
|
for period in PERIODS:
|
||||||
|
base = self._bases[period]
|
||||||
|
if base is None or self.total_flow is None or self.total_energy is None:
|
||||||
|
self.ratios[period] = ZERO
|
||||||
|
continue
|
||||||
|
delta_flow = self.total_flow - base[0]
|
||||||
|
delta_energy = self.total_energy - base[1]
|
||||||
|
self.ratios[period] = _ratio(delta_energy, delta_flow)
|
||||||
|
self.ratios_time = now
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ 持久化
|
||||||
|
def to_payload(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"name": self.name,
|
||||||
|
"register_index": self.register_index,
|
||||||
|
"instant_flow": _s(self.instant_flow),
|
||||||
|
"total_flow": _s(self.total_flow),
|
||||||
|
"instant_power": _s(self.instant_power),
|
||||||
|
"total_energy": _s(self.total_energy),
|
||||||
|
"ratios": {key: str(value) for key, value in self.ratios.items()},
|
||||||
|
"period_keys": dict(self._keys),
|
||||||
|
"bases": {
|
||||||
|
period: (
|
||||||
|
[_s(base[0]), _s(base[1])] if base is not None else None
|
||||||
|
)
|
||||||
|
for period, base in self._bases.items()
|
||||||
|
},
|
||||||
|
"flow_time": self.flow_time.isoformat() if self.flow_time else None,
|
||||||
|
"power_time": self.power_time.isoformat() if self.power_time else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def restore(self, payload: dict[str, Any], now: datetime) -> None:
|
||||||
|
"""从 SQLite 恢复。
|
||||||
|
|
||||||
|
周期未变化时沿用原基准,做到重启后累计值连续;
|
||||||
|
周期已经跨越(例如停机跨天)时,用最后一次累计值作为新基准。
|
||||||
|
"""
|
||||||
|
self.instant_flow = _dec(payload.get("instant_flow"))
|
||||||
|
self.total_flow = _dec(payload.get("total_flow"))
|
||||||
|
self.instant_power = _dec(payload.get("instant_power"))
|
||||||
|
self.total_energy = _dec(payload.get("total_energy"))
|
||||||
|
|
||||||
|
self.flow_time = _parse_dt(payload.get("flow_time"))
|
||||||
|
self.power_time = _parse_dt(payload.get("power_time"))
|
||||||
|
|
||||||
|
keys = period_keys(now)
|
||||||
|
saved_keys = payload.get("period_keys") or {}
|
||||||
|
saved_bases = payload.get("bases") or {}
|
||||||
|
both_totals = self.total_flow is not None and self.total_energy is not None
|
||||||
|
|
||||||
|
for period in PERIODS:
|
||||||
|
base = saved_bases.get(period)
|
||||||
|
same_period = saved_keys.get(period) == keys[period]
|
||||||
|
if same_period and base:
|
||||||
|
self._bases[period] = (Decimal(str(base[0])), Decimal(str(base[1])))
|
||||||
|
elif both_totals:
|
||||||
|
self._bases[period] = (self.total_flow, self.total_energy)
|
||||||
|
else:
|
||||||
|
self._bases[period] = None
|
||||||
|
self._keys[period] = keys[period]
|
||||||
|
|
||||||
|
self._refresh(now)
|
||||||
|
|
||||||
|
def age_s(self, now: datetime) -> Optional[float]:
|
||||||
|
"""距离最近一次气量/电表更新的秒数(取较旧者)。"""
|
||||||
|
times = [t for t in (self.flow_time, self.power_time) if t is not None]
|
||||||
|
if not times:
|
||||||
|
return None
|
||||||
|
return (now - min(times)).total_seconds()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_dt(value: Any) -> Optional[datetime]:
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(str(value))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"""SQLite 掉电保持:保存/恢复各台机器的周期基准与最新累计值。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sqlite3
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS machine_state (
|
||||||
|
machine_id INTEGER PRIMARY KEY,
|
||||||
|
payload TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS meta (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class SqliteStore:
|
||||||
|
def __init__(self, path: str) -> None:
|
||||||
|
self._path = Path(path)
|
||||||
|
if str(self._path.parent) not in ("", "."):
|
||||||
|
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.executescript(_SCHEMA)
|
||||||
|
|
||||||
|
def _connect(self) -> sqlite3.Connection:
|
||||||
|
return sqlite3.connect(self._path, timeout=10)
|
||||||
|
|
||||||
|
def save(self, payloads: dict[int, dict[str, Any]], now: datetime) -> None:
|
||||||
|
if not payloads:
|
||||||
|
return
|
||||||
|
stamp = now.isoformat(timespec="seconds")
|
||||||
|
rows = [
|
||||||
|
(machine_id, json.dumps(payload, ensure_ascii=False), stamp)
|
||||||
|
for machine_id, payload in payloads.items()
|
||||||
|
]
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.executemany(
|
||||||
|
"INSERT OR REPLACE INTO machine_state (machine_id, payload, updated_at) VALUES (?, ?, ?)",
|
||||||
|
rows,
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT OR REPLACE INTO meta (key, value) VALUES ('last_save', ?)",
|
||||||
|
(stamp,),
|
||||||
|
)
|
||||||
|
|
||||||
|
def load(self) -> dict[int, dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
with self._connect() as conn:
|
||||||
|
rows = conn.execute("SELECT machine_id, payload FROM machine_state").fetchall()
|
||||||
|
except sqlite3.Error:
|
||||||
|
log.exception("读取 SQLite 状态失败,将按冷启动处理")
|
||||||
|
return {}
|
||||||
|
result: dict[int, dict[str, Any]] = {}
|
||||||
|
for machine_id, payload in rows:
|
||||||
|
try:
|
||||||
|
result[int(machine_id)] = json.loads(payload)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
log.warning("机器 %s 的历史状态无法解析,已忽略", machine_id)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def last_save_time(self) -> str | None:
|
||||||
|
try:
|
||||||
|
with self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT value FROM meta WHERE key='last_save'").fetchone()
|
||||||
|
except sqlite3.Error:
|
||||||
|
return None
|
||||||
|
return row[0] if row else None
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
"""Modbus TCP 采集线程(网关作为 Client)。
|
||||||
|
|
||||||
|
每个设备一个线程,互不影响:
|
||||||
|
- 采集频率与 S331 读取寄存器频率完全解耦;
|
||||||
|
- 连接失败 / 读取失败走指数退避重连,线程不退出,RTU 从站不受影响;
|
||||||
|
- 一次循环内按“连续块”批量读取,减少 410S 的请求次数。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Callable, Optional, Sequence
|
||||||
|
|
||||||
|
from pymodbus.client import ModbusTcpClient
|
||||||
|
|
||||||
|
from .config import DeviceCfg, Point
|
||||||
|
from .registers import Block, decode_point, plan_blocks
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# S331 未接入/无数据的通道整组寄存器填 -9999(float32 = 0xC61C3C00),
|
||||||
|
# 按 ABCD / CDAB 读出来分别是 (0xC61C, 0x3C00) 与 (0x3C00, 0xC61C)。
|
||||||
|
# 这类值若参与计算会把周期基准污染成天文数字,并让 RTU 端打包 Float 溢出。
|
||||||
|
S331_SENTINEL_WORDS = frozenset({(0xC61C, 0x3C00), (0x3C00, 0xC61C)})
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class PointBinding:
|
||||||
|
"""点位绑定:把某个寄存器点位映射到某台机器的某个字段。"""
|
||||||
|
|
||||||
|
machine_id: int
|
||||||
|
field: str
|
||||||
|
point: Point
|
||||||
|
|
||||||
|
|
||||||
|
class TcpPoller(threading.Thread):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
cfg: DeviceCfg,
|
||||||
|
bindings: Sequence[PointBinding],
|
||||||
|
on_values: Callable[[dict[tuple[int, str], Decimal]], None],
|
||||||
|
stop_event: threading.Event,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(name=f"poll-{cfg.name}", daemon=True)
|
||||||
|
self._cfg = cfg
|
||||||
|
self._bindings = list(bindings)
|
||||||
|
self._on_values = on_values
|
||||||
|
self._stop_event = stop_event
|
||||||
|
self._plan: list[Block] = plan_blocks(
|
||||||
|
[(b.point.address, b.point.width) for b in self._bindings],
|
||||||
|
max_registers=cfg.max_registers_per_read,
|
||||||
|
max_gap=cfg.max_gap,
|
||||||
|
)
|
||||||
|
self._locate = {
|
||||||
|
(b.machine_id, b.field): _find_block(self._plan, b.point) for b in self._bindings
|
||||||
|
}
|
||||||
|
self._ok_cycles = 0
|
||||||
|
self._fail_cycles = 0
|
||||||
|
self._last_error: Optional[str] = None
|
||||||
|
self._last_ok: Optional[float] = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 线程主体
|
||||||
|
def run(self) -> None:
|
||||||
|
cfg = self._cfg
|
||||||
|
backoff = cfg.reconnect_min_s
|
||||||
|
connected = False
|
||||||
|
while not self._stop_event.is_set():
|
||||||
|
client = ModbusTcpClient(
|
||||||
|
cfg.host,
|
||||||
|
port=cfg.port,
|
||||||
|
timeout=cfg.timeout_s,
|
||||||
|
retries=1,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
if not client.connect():
|
||||||
|
raise ConnectionError(f"无法连接 {cfg.host}:{cfg.port}")
|
||||||
|
if not connected:
|
||||||
|
log.info("[%s] 已连接 %s:%s", cfg.name, cfg.host, cfg.port)
|
||||||
|
connected = True
|
||||||
|
backoff = cfg.reconnect_min_s
|
||||||
|
while not self._stop_event.is_set():
|
||||||
|
started = time.monotonic()
|
||||||
|
values = self._read_once(client)
|
||||||
|
self._on_values(values)
|
||||||
|
self._ok_cycles += 1
|
||||||
|
self._last_ok = time.monotonic()
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
self._stop_event.wait(max(0.0, cfg.poll_interval_s - elapsed))
|
||||||
|
except Exception as exc: # noqa: BLE001 - 采集线程必须兜住所有异常
|
||||||
|
self._fail_cycles += 1
|
||||||
|
self._last_error = f"{type(exc).__name__}: {exc}"
|
||||||
|
log.warning("[%s] 采集失败: %s,%.1fs 后重连", cfg.name, self._last_error, backoff)
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
if connected:
|
||||||
|
log.info("[%s] 连接已关闭", cfg.name)
|
||||||
|
connected = False
|
||||||
|
|
||||||
|
if self._stop_event.wait(backoff):
|
||||||
|
break
|
||||||
|
backoff = min(backoff * 2, cfg.reconnect_max_s)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 单次采集
|
||||||
|
def _read_once(self, client: ModbusTcpClient) -> dict[tuple[int, str], Decimal]:
|
||||||
|
raw: dict[int, list[int]] = {}
|
||||||
|
for block in self._plan:
|
||||||
|
response = _read_holding(client, block.start, block.count, self._cfg.slave_id)
|
||||||
|
if response is None or response.isError():
|
||||||
|
raise IOError(
|
||||||
|
f"读取寄存器 {block.start}~{block.start + block.count - 1} 失败: {response}"
|
||||||
|
)
|
||||||
|
registers = getattr(response, "registers", None)
|
||||||
|
if not registers or len(registers) < block.count:
|
||||||
|
raise IOError(f"寄存器 {block.start} 返回长度异常: {registers}")
|
||||||
|
raw[block.start] = list(registers)
|
||||||
|
|
||||||
|
values: dict[tuple[int, str], Decimal] = {}
|
||||||
|
for binding in self._bindings:
|
||||||
|
start, offset = self._locate[(binding.machine_id, binding.field)]
|
||||||
|
words = raw[start][offset : offset + binding.point.width]
|
||||||
|
if tuple(words) in S331_SENTINEL_WORDS:
|
||||||
|
log.debug(
|
||||||
|
"[%s] %s# 的 %s 为 S331 无数据哨兵,本次跳过",
|
||||||
|
self._cfg.name,
|
||||||
|
binding.machine_id,
|
||||||
|
binding.field,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
value = decode_point(words, binding.point)
|
||||||
|
if not value.is_finite():
|
||||||
|
log.debug(
|
||||||
|
"[%s] %s# 的 %s 为非有限值,本次跳过",
|
||||||
|
self._cfg.name,
|
||||||
|
binding.machine_id,
|
||||||
|
binding.field,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
values[(binding.machine_id, binding.field)] = value
|
||||||
|
return values
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 诊断
|
||||||
|
def status(self) -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"name": self._cfg.name,
|
||||||
|
"target": f"{self._cfg.host}:{self._cfg.port}",
|
||||||
|
"ok_cycles": self._ok_cycles,
|
||||||
|
"fail_cycles": self._fail_cycles,
|
||||||
|
"last_ok_age_s": None if self._last_ok is None else round(time.monotonic() - self._last_ok, 1),
|
||||||
|
"last_error": self._last_error,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _find_block(blocks: Sequence[Block], point: Point) -> tuple[int, int]:
|
||||||
|
for block in blocks:
|
||||||
|
if block.start <= point.address and point.address + point.width <= block.end:
|
||||||
|
return block.start, point.address - block.start
|
||||||
|
raise LookupError(f"点位 {point.address}+{point.width} 未被读取块覆盖")
|
||||||
|
|
||||||
|
|
||||||
|
def _read_holding(client: ModbusTcpClient, address: int, count: int, slave_id: int):
|
||||||
|
"""兼容 pymodbus 3.8/3.9(slave=)与 3.10+(device_id=)的参数名。"""
|
||||||
|
try:
|
||||||
|
return client.read_holding_registers(address, count=count, slave=slave_id)
|
||||||
|
except TypeError:
|
||||||
|
return client.read_holding_registers(address, count=count, device_id=slave_id)
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""现场点表核查工具。
|
||||||
|
|
||||||
|
用于和 S331 / 410S 的实际点表对齐:读取一段保持寄存器,
|
||||||
|
同时给出 uint16 / int16 / int32 / uint32 / float32(ABCD) / float32(CDAB) 的解释。
|
||||||
|
|
||||||
|
用法示例:
|
||||||
|
python -m gateway.probe --host 192.168.10.31 --slave 1 --start 0 --count 40
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from pymodbus.client import ModbusTcpClient
|
||||||
|
|
||||||
|
|
||||||
|
def _read(client: ModbusTcpClient, start: int, count: int, slave_id: int) -> list[int]:
|
||||||
|
try:
|
||||||
|
response = client.read_holding_registers(start, count=count, slave=slave_id)
|
||||||
|
except TypeError:
|
||||||
|
response = client.read_holding_registers(start, count=count, device_id=slave_id)
|
||||||
|
if response is None or response.isError():
|
||||||
|
raise IOError(f"读取失败: {response}")
|
||||||
|
return list(response.registers)
|
||||||
|
|
||||||
|
|
||||||
|
def _f32(words: list[int], order: str) -> float:
|
||||||
|
hi, lo = (words[1], words[0]) if order == "CDAB" else (words[0], words[1])
|
||||||
|
return struct.unpack(">f", struct.pack(">HH", hi, lo))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _s32(words: list[int], signed: bool) -> int:
|
||||||
|
hi, lo = words[0], words[1]
|
||||||
|
return struct.unpack(">i" if signed else ">I", struct.pack(">HH", hi, lo))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="Modbus TCP 点表核查")
|
||||||
|
parser.add_argument("--host", required=True)
|
||||||
|
parser.add_argument("--port", type=int, default=502)
|
||||||
|
parser.add_argument("--slave", type=int, default=1)
|
||||||
|
parser.add_argument("--start", type=int, default=0, help="起始协议地址(40001 -> 0)")
|
||||||
|
parser.add_argument("--count", type=int, default=32, help="读取寄存器个数")
|
||||||
|
parser.add_argument("--timeout", type=float, default=2.0)
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
client = ModbusTcpClient(args.host, port=args.port, timeout=args.timeout)
|
||||||
|
if not client.connect():
|
||||||
|
print(f"连接失败: {args.host}:{args.port}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
try:
|
||||||
|
registers = _read(client, args.start, args.count, args.slave)
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
print(f"{args.host}:{args.port} slave={args.slave} 起始={args.start} 共 {len(registers)} 个寄存器")
|
||||||
|
print(
|
||||||
|
f"{'地 址':>7} {'4xxxx':>7} {'HEX':>6} {'U16':>7} {'I16':>7} "
|
||||||
|
f"{'I32':>12} {'U32':>12} {'Float(ABCD)':>14} {'Float(CDAB)':>14}"
|
||||||
|
)
|
||||||
|
for offset, word in enumerate(registers):
|
||||||
|
address = args.start + offset
|
||||||
|
i32 = u32 = "-"
|
||||||
|
f_abcd = f_cdab = "-"
|
||||||
|
if offset + 1 < len(registers):
|
||||||
|
pair = registers[offset : offset + 2]
|
||||||
|
i32 = str(_s32(pair, True))
|
||||||
|
u32 = str(_s32(pair, False))
|
||||||
|
f_abcd = f"{_f32(pair, 'ABCD'):.5g}"
|
||||||
|
f_cdab = f"{_f32(pair, 'CDAB'):.5g}"
|
||||||
|
print(
|
||||||
|
f"{address:>7} {40001 + address:>7} {word:>6} {word:>7} "
|
||||||
|
f"{word - 65536 if word > 32767 else word:>7} {i32:>12} {u32:>12} "
|
||||||
|
f"{f_abcd:>14} {f_cdab:>14}"
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""寄存器编解码与批量读取规划。
|
||||||
|
|
||||||
|
处理三类现场问题:
|
||||||
|
1. 数据类型不一致(float32 / int32 / uint32 / int16 ...);
|
||||||
|
2. 字序不一致(ABCD / CDAB,即“高低字交换”);
|
||||||
|
3. 点表错位(同一设备内点位合并成块读取,配合 config 中的 address_offset 补偿)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from decimal import Decimal
|
||||||
|
from typing import Iterable, Mapping, Sequence
|
||||||
|
|
||||||
|
from .config import Point
|
||||||
|
|
||||||
|
_STRUCT_FMT = {
|
||||||
|
"int16": ">h",
|
||||||
|
"uint16": ">H",
|
||||||
|
"int32": ">i",
|
||||||
|
"uint32": ">I",
|
||||||
|
"float32": ">f",
|
||||||
|
"int64": ">q",
|
||||||
|
"uint64": ">Q",
|
||||||
|
"float64": ">d",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Block:
|
||||||
|
"""一段连续寄存器读取区间(0 基协议地址)。"""
|
||||||
|
|
||||||
|
start: int
|
||||||
|
count: int
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end(self) -> int:
|
||||||
|
return self.start + self.count
|
||||||
|
|
||||||
|
|
||||||
|
def _words_to_bytes(words: Sequence[int], order: str) -> bytes:
|
||||||
|
ordered = list(words)
|
||||||
|
if order == "CDAB":
|
||||||
|
ordered.reverse()
|
||||||
|
return b"".join(int(word).to_bytes(2, "big") for word in ordered)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_point(words: Sequence[int], point: Point) -> Decimal:
|
||||||
|
"""把原始寄存器字按点位定义转换为工程值(Decimal)。"""
|
||||||
|
width = point.width
|
||||||
|
if len(words) < width:
|
||||||
|
raise ValueError(f"寄存器数量不足: 需要 {width} 个, 实际 {len(words)}")
|
||||||
|
data = _words_to_bytes(list(words[:width]), point.order)
|
||||||
|
raw = struct.unpack(_STRUCT_FMT[point.type], data)[0]
|
||||||
|
return Decimal(str(raw)) * point.scale + point.offset
|
||||||
|
|
||||||
|
|
||||||
|
def encode_float32(value: float, order: str = "ABCD") -> list[int]:
|
||||||
|
"""把 float 编码为两个寄存器字,供 RTU 从站使用。"""
|
||||||
|
data = struct.pack(">f", float(value))
|
||||||
|
words = [int.from_bytes(data[0:2], "big"), int.from_bytes(data[2:4], "big")]
|
||||||
|
if order == "CDAB":
|
||||||
|
words.reverse()
|
||||||
|
return words
|
||||||
|
|
||||||
|
|
||||||
|
def plan_blocks(
|
||||||
|
spans: Iterable[tuple[int, int]],
|
||||||
|
max_registers: int = 60,
|
||||||
|
max_gap: int = 4,
|
||||||
|
) -> list[Block]:
|
||||||
|
"""把 (起始地址, 寄存器个数) 列表合并成尽量少的连续读取块。
|
||||||
|
|
||||||
|
相邻点位间隔 <= max_gap 且合并后长度 <= max_registers 时合并,
|
||||||
|
以减少 TCP 请求次数、降低 410S 的响应压力。
|
||||||
|
"""
|
||||||
|
blocks: list[Block] = []
|
||||||
|
for start, width in sorted(spans):
|
||||||
|
if width <= 0:
|
||||||
|
continue
|
||||||
|
end = start + width
|
||||||
|
if blocks:
|
||||||
|
last = blocks[-1]
|
||||||
|
gap = start - last.end
|
||||||
|
merged_len = max(last.end, end) - last.start
|
||||||
|
if 0 <= gap <= max_gap and merged_len <= max_registers:
|
||||||
|
blocks[-1] = Block(last.start, merged_len)
|
||||||
|
continue
|
||||||
|
blocks.append(Block(start, width))
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
|
def locate(blocks: Sequence[Block], start: int, width: int) -> tuple[int, int]:
|
||||||
|
"""定位点位在某个读取块内的偏移,返回 (块起始地址, 块内偏移)。"""
|
||||||
|
for block in blocks:
|
||||||
|
if block.start <= start and start + width <= block.end:
|
||||||
|
return block.start, start - block.start
|
||||||
|
raise LookupError(f"点位 {start}+{width} 未被任何读取块覆盖")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_values(
|
||||||
|
blocks: Sequence[Block],
|
||||||
|
block_values: Mapping[int, Sequence[int]],
|
||||||
|
points: Mapping[str, Point],
|
||||||
|
) -> dict[str, Decimal]:
|
||||||
|
"""按块读取结果提取各点位工程值。"""
|
||||||
|
result: dict[str, Decimal] = {}
|
||||||
|
for name, point in points.items():
|
||||||
|
block_start, offset = locate(blocks, point.address, point.width)
|
||||||
|
words = block_values[block_start][offset : offset + point.width]
|
||||||
|
result[name] = decode_point(words, point)
|
||||||
|
return result
|
||||||
+192
@@ -0,0 +1,192 @@
|
|||||||
|
"""双路 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)
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
"""线程安全的状态仓 + RTU 保持寄存器镜像。
|
||||||
|
|
||||||
|
一把 Lock 同时保护“机器数据模型”和“寄存器镜像”:
|
||||||
|
- 采集线程更新数据并重建镜像时持锁;
|
||||||
|
- RTU 从站读取时持锁并复制快照。
|
||||||
|
|
||||||
|
因此 S331 在任意时刻读到的 8 个寄存器一定是同一次计算的结果,
|
||||||
|
不会出现“一半旧值、一半新值”的脏读。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional, Sequence
|
||||||
|
|
||||||
|
from .config import CompressorCfg
|
||||||
|
from .model import MachineState, RATIO_KEYS
|
||||||
|
from .registers import encode_float32
|
||||||
|
|
||||||
|
# 每台机器固定占用 8 个保持寄存器(4 个 Float)
|
||||||
|
REGISTERS_PER_MACHINE = 8
|
||||||
|
|
||||||
|
|
||||||
|
class StateStore:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
compressors: Sequence[CompressorCfg],
|
||||||
|
float_order: str = "ABCD",
|
||||||
|
clock=datetime.now,
|
||||||
|
) -> None:
|
||||||
|
if not compressors:
|
||||||
|
raise ValueError("至少需要一台空压机")
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._clock = clock
|
||||||
|
self._float_order = float_order
|
||||||
|
self._machines: dict[int, MachineState] = {
|
||||||
|
cfg.id: MachineState(cfg.id, cfg.name, cfg.register_index) for cfg in compressors
|
||||||
|
}
|
||||||
|
self._size = (max(m.register_index for m in self._machines.values()) + 1) * REGISTERS_PER_MACHINE
|
||||||
|
self._image = [0] * self._size
|
||||||
|
with self._lock:
|
||||||
|
for machine in self._machines.values():
|
||||||
|
self._write_machine_locked(machine)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 基本属性
|
||||||
|
@property
|
||||||
|
def register_count(self) -> int:
|
||||||
|
return self._size
|
||||||
|
|
||||||
|
def machine_ids(self) -> list[int]:
|
||||||
|
return sorted(self._machines)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 更新
|
||||||
|
def update(self, updates: dict[int, dict[str, Any]], now: Optional[datetime] = None) -> None:
|
||||||
|
"""批量更新。
|
||||||
|
|
||||||
|
updates 形如 {machine_id: {"instant_flow": Decimal, "total_flow": ...}},
|
||||||
|
允许的字段:instant_flow / total_flow / instant_power / total_energy。
|
||||||
|
"""
|
||||||
|
if not updates:
|
||||||
|
return
|
||||||
|
stamp = now or self._clock()
|
||||||
|
with self._lock:
|
||||||
|
for machine_id, values in updates.items():
|
||||||
|
machine = self._machines.get(machine_id)
|
||||||
|
if machine is None:
|
||||||
|
continue
|
||||||
|
machine.apply(stamp, **values)
|
||||||
|
self._write_machine_locked(machine)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ RTU 读取
|
||||||
|
def read_registers(self, address: int, count: int = 1) -> Optional[list[int]]:
|
||||||
|
"""返回寄存器快照;越界返回 None(从站应答非法地址)。"""
|
||||||
|
if address < 0 or count <= 0 or address + count > self._size:
|
||||||
|
return None
|
||||||
|
with self._lock:
|
||||||
|
return self._image[address : address + count]
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 持久化
|
||||||
|
def persist_payloads(self) -> dict[int, dict[str, Any]]:
|
||||||
|
with self._lock:
|
||||||
|
return {mid: machine.to_payload() for mid, machine in self._machines.items()}
|
||||||
|
|
||||||
|
def restore(self, payloads: dict[int, dict[str, Any]], now: Optional[datetime] = None) -> int:
|
||||||
|
"""从 SQLite 数据恢复,返回成功恢复的机器数量。"""
|
||||||
|
stamp = now or self._clock()
|
||||||
|
restored = 0
|
||||||
|
with self._lock:
|
||||||
|
for machine_id, payload in payloads.items():
|
||||||
|
machine = self._machines.get(machine_id)
|
||||||
|
if machine is None or not isinstance(payload, dict):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
machine.restore(payload, stamp)
|
||||||
|
except (KeyError, TypeError, ValueError):
|
||||||
|
continue
|
||||||
|
self._write_machine_locked(machine)
|
||||||
|
restored += 1
|
||||||
|
return restored
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 状态日志
|
||||||
|
def snapshot(self, now: Optional[datetime] = None) -> list[dict[str, Any]]:
|
||||||
|
"""给状态日志用的轻量快照。"""
|
||||||
|
stamp = now or self._clock()
|
||||||
|
with self._lock:
|
||||||
|
rows = []
|
||||||
|
for machine in sorted(self._machines.values(), key=lambda m: m.register_index):
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"id": machine.machine_id,
|
||||||
|
"name": machine.name,
|
||||||
|
"base_address": machine.register_index * REGISTERS_PER_MACHINE,
|
||||||
|
"ratios": {key: float(machine.ratios[key]) for key in RATIO_KEYS},
|
||||||
|
"instant_flow": _f(machine.instant_flow),
|
||||||
|
"total_flow": _f(machine.total_flow),
|
||||||
|
"instant_power": _f(machine.instant_power),
|
||||||
|
"total_energy": _f(machine.total_energy),
|
||||||
|
"age_s": machine.age_s(stamp),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ 内部
|
||||||
|
def _write_machine_locked(self, machine: MachineState) -> None:
|
||||||
|
base = machine.register_index * REGISTERS_PER_MACHINE
|
||||||
|
for offset, key in enumerate(RATIO_KEYS):
|
||||||
|
self._image[base + offset * 2 : base + offset * 2 + 2] = encode_float32(
|
||||||
|
float(machine.ratios[key]), self._float_order
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _f(value: Any) -> Optional[float]:
|
||||||
|
return None if value is None else float(value)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[pytest]
|
||||||
|
testpaths = tests
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
pymodbus>=3.8.6,<3.10
|
||||||
|
pyserial>=3.5
|
||||||
|
PyYAML>=6.0
|
||||||
@@ -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")
|
||||||
@@ -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}")
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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}")
|
||||||
@@ -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()
|
||||||
@@ -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"
|
||||||
|
@@ -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"
|
||||||
|
@@ -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"
|
||||||
|
@@ -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
|
||||||
|
```
|
||||||
@@ -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}")
|
||||||
@@ -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())
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in new issue
Block a user