"""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()