modbus_server.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. """Modbus/TCP 服务端:把视觉结果暴露成寄存器块,供西门子 PLC 周期读取。
  2. 为什么不用 pymodbus?
  3. ---------------------
  4. 现场只用到 4 个功能码,自己实现 ~200 行即可,能避免 pymodbus 3.x 的 API 变动、
  5. asyncio 版本差异和"启动器/数据存储"概念带来的排障成本;同时寄存器映射逻辑
  6. (:mod:`portcv.schema`)与 :mod:`portcv.plc.modbus_pdu` 可以单元测试覆盖。
  7. 寄存器规划(地址 = 配置项 ``plc.modbus.input_addr`` / ``holding_addr`` + 偏移)
  8. ------------------------------------------------------------------------
  9. 输入寄存器(FC4,PLC 读,视觉写,12 个字)::
  10. 0 state 0=不在车上 1=车斗 2=平板车;V2 不再发布 255
  11. 1 confidence 千分比 0..1000
  12. 2 flags 状态位(见 schema.StatusBits)
  13. 3 seq_hi 结果序号高 16bit(状态每变化一次 +1)
  14. 4 seq_lo
  15. 5 ts_hi unix 秒高 16bit
  16. 6 ts_lo
  17. 7 heartbeat 心跳计数(每心跳周期 +1,PLC 用它判断视觉是否存活)
  18. 8 fps_x10 帧率 x10
  19. 9 latency_ms 单帧端到端耗时
  20. 10 reserved
  21. 11 crc16 CRC-16/MODBUS(前 11 个字,大端字节序)
  22. 保持寄存器(FC3/FC6/FC16,PLC 写,视觉读,4 个字)::
  23. 0 cmd 0=空闲 1=请求识别 2=复位 3=清统计
  24. 1 preset 相机/ROI 预设编号
  25. 2 min_conf 覆盖最小置信度(千分比,0=用配置)
  26. 3 reserved
  27. """
  28. from __future__ import annotations
  29. import socketserver
  30. import threading
  31. import time
  32. from typing import Callable, Dict, List, Optional, Sequence
  33. from ..logging_utils import get_logger
  34. from ..schema import PlcCommand, VisionSnapshot
  35. from .modbus_pdu import (
  36. EXCEPTION_CODES,
  37. FC_READ_HOLDING_REGISTERS,
  38. FC_READ_INPUT_REGISTERS,
  39. FC_WRITE_MULTIPLE_REGISTERS,
  40. FC_WRITE_SINGLE_REGISTER,
  41. MBAP_HEADER_LEN,
  42. build_exception_response,
  43. build_frame,
  44. bytes_to_u16s,
  45. parse_mbap,
  46. u16s_to_bytes,
  47. )
  48. __all__ = ["ModbusTcpServer"]
  49. LOGGER = get_logger("plc.modbus")
  50. class _Handler(socketserver.BaseRequestHandler):
  51. """一个 PLC 连接 = 一个线程,循环处理请求。"""
  52. server: "ModbusTcpServer" # type: ignore[assignment]
  53. def handle(self) -> None: # noqa: D102
  54. sock = self.request
  55. sock.settimeout(30.0)
  56. peer = "%s:%s" % self.client_address[:2]
  57. self.server.on_client_connected(peer)
  58. try:
  59. while not self.server.is_stopping():
  60. header = self._recv_exact(MBAP_HEADER_LEN)
  61. if header is None:
  62. break
  63. length = int.from_bytes(header[4:6], "big")
  64. # 与 C++ service_client 同口径:length 含 unit_id,最小 2、最大 254
  65. # (PDU 253)。非法长度直接断连,避免错位/恶意报文把连接线程
  66. # 吊在 30 s 超时上,或让服务端按 64 KB 去缓冲。
  67. if length < 2 or length > 254:
  68. break
  69. body = self._recv_exact(max(0, length - 1))
  70. if body is None:
  71. break
  72. response = self.server.handle_frame(header + body, peer)
  73. if response:
  74. sock.sendall(response)
  75. except (ConnectionResetError, OSError):
  76. pass
  77. finally:
  78. self.server.on_client_disconnected(peer)
  79. def _recv_exact(self, size: int) -> Optional[bytes]:
  80. chunks = b""
  81. while len(chunks) < size:
  82. try:
  83. piece = self.request.recv(size - len(chunks))
  84. except (ConnectionResetError, OSError):
  85. return None
  86. if not piece:
  87. return None
  88. chunks += piece
  89. return chunks
  90. class ModbusTcpServer(socketserver.ThreadingTCPServer):
  91. """线程化 Modbus/TCP 从站。
  92. ``on_command`` 会在 PLC 写入保持寄存器后回调 ``(registers, peer)``,
  93. 服务主循环据此响应"按需识别/复位"等命令。
  94. """
  95. allow_reuse_address = True
  96. daemon_threads = True
  97. #: 输入寄存器块大小(字)
  98. INPUT_SIZE = VisionSnapshot.register_count()
  99. #: 保持寄存器块大小(字)
  100. HOLDING_SIZE = PlcCommand.register_count()
  101. def __init__(
  102. self,
  103. host: str = "0.0.0.0",
  104. port: int = 1502,
  105. unit_id: int = 1,
  106. allow_unit_any: bool = True,
  107. input_addr: int = 0,
  108. holding_addr: int = 0,
  109. on_command: Optional[Callable[[List[int], str], None]] = None,
  110. ) -> None:
  111. self.host = host
  112. self.port = int(port)
  113. self.unit_id = int(unit_id)
  114. self.allow_unit_any = bool(allow_unit_any)
  115. self.input_addr = int(input_addr)
  116. self.holding_addr = int(holding_addr)
  117. self.on_command = on_command
  118. self._lock = threading.RLock()
  119. self._inputs: List[int] = [0] * self.INPUT_SIZE
  120. self._holdings: List[int] = [0] * self.HOLDING_SIZE
  121. self._stopping = False
  122. self._clients: Dict[str, float] = {}
  123. self.stats: Dict[str, int] = {"requests": 0, "reads": 0, "writes": 0, "errors": 0}
  124. self._publisher_thread: Optional[threading.Thread] = None
  125. super().__init__((host, int(port)), _Handler)
  126. LOGGER.info("Modbus/TCP 服务端已监听 %s:%d (unit=%d)", host, port, unit_id)
  127. # ------------------------------------------------------------ 生命周期
  128. def start(self) -> "ModbusTcpServer":
  129. self._stopping = False
  130. self._publisher_thread = threading.Thread(
  131. target=self.serve_forever, name="modbus-server", daemon=True
  132. )
  133. self._publisher_thread.start()
  134. return self
  135. def stop(self, timeout: float = 3.0) -> None:
  136. self._stopping = True
  137. try:
  138. self.shutdown()
  139. except Exception: # pragma: no cover
  140. pass
  141. self.server_close()
  142. if self._publisher_thread is not None:
  143. self._publisher_thread.join(timeout=timeout)
  144. self._publisher_thread = None
  145. def is_stopping(self) -> bool:
  146. return bool(self._stopping)
  147. # ------------------------------------------------------ 数据块访问接口
  148. def set_snapshot(self, snapshot: VisionSnapshot) -> List[int]:
  149. """把快照写入输入寄存器块,返回写入的字(便于自检/测试)。"""
  150. words = snapshot.to_registers()
  151. with self._lock:
  152. self._inputs = list(words)
  153. return words
  154. def input_registers(self) -> List[int]:
  155. with self._lock:
  156. return list(self._inputs)
  157. def holding_registers(self) -> List[int]:
  158. with self._lock:
  159. return list(self._holdings)
  160. def command(self) -> PlcCommand:
  161. with self._lock:
  162. return PlcCommand.from_registers(self._holdings)
  163. def set_holding_registers(self, values: Sequence[int], offset: int = 0) -> None:
  164. """测试/上位机预置指令用。"""
  165. with self._lock:
  166. for i, value in enumerate(values):
  167. index = int(offset) + i
  168. if 0 <= index < self.HOLDING_SIZE:
  169. self._holdings[index] = int(value) & 0xFFFF
  170. @property
  171. def client_count(self) -> int:
  172. with self._lock:
  173. return len(self._clients)
  174. def clients(self) -> Dict[str, float]:
  175. with self._lock:
  176. return dict(self._clients)
  177. def on_client_connected(self, peer: str) -> None:
  178. with self._lock:
  179. self._clients[peer] = time.time()
  180. LOGGER.info("PLC 已连接: %s", peer)
  181. def on_client_disconnected(self, peer: str) -> None:
  182. with self._lock:
  183. self._clients.pop(peer, None)
  184. LOGGER.info("PLC 断开: %s", peer)
  185. # ------------------------------------------------------------ 报文处理
  186. def handle_frame(self, frame: bytes, peer: str = "") -> bytes:
  187. """处理一个完整 MBAP 帧,返回响应字节(空字节 = 不响应)。"""
  188. try:
  189. tx_id, proto_id, _length, unit_id, pdu = parse_mbap(frame)
  190. except ValueError as exc:
  191. self.stats["errors"] += 1
  192. LOGGER.warning("报文解析失败(%s): %s", peer, exc)
  193. return b""
  194. if not self.allow_unit_any and unit_id != self.unit_id:
  195. return b""
  196. if proto_id != 0 or not pdu:
  197. self.stats["errors"] += 1
  198. return build_exception_response(tx_id, unit_id, pdu[0] if pdu else 0, 0x03)
  199. # 注意:allow_unit_any 只表示“接受任意站点号”,响应必须原样回显请求的
  200. # unit_id(Modbus/TCP 规范)。不能改成配置里的 self.unit_id,否则 PLC 用
  201. # 非 1 的站点号时会把响应当成别的从站而丢弃/超时。
  202. func = pdu[0]
  203. self.stats["requests"] += 1
  204. if func == FC_READ_INPUT_REGISTERS:
  205. self.stats["reads"] += 1
  206. return self._read_registers(tx_id, unit_id, func, pdu, self._inputs, self.input_addr)
  207. if func == FC_READ_HOLDING_REGISTERS:
  208. self.stats["reads"] += 1
  209. return self._read_registers(tx_id, unit_id, func, pdu, self._holdings, self.holding_addr)
  210. if func == FC_WRITE_SINGLE_REGISTER:
  211. self.stats["writes"] += 1
  212. return self._write_single(tx_id, unit_id, pdu, peer)
  213. if func == FC_WRITE_MULTIPLE_REGISTERS:
  214. self.stats["writes"] += 1
  215. return self._write_multiple(tx_id, unit_id, pdu, peer)
  216. self.stats["errors"] += 1
  217. LOGGER.debug("未支持的功能码 0x%02X(来自 %s)", func, peer)
  218. return build_exception_response(tx_id, unit_id, func, 0x01)
  219. def _read_registers(
  220. self, tx_id: int, unit_id: int, func: int, pdu: bytes, block: List[int], base_addr: int
  221. ) -> bytes:
  222. if len(pdu) < 5:
  223. return build_exception_response(tx_id, unit_id, func, 0x03)
  224. address = int.from_bytes(pdu[1:3], "big")
  225. quantity = int.from_bytes(pdu[3:5], "big")
  226. if quantity < 1 or quantity > 125:
  227. self.stats["errors"] += 1
  228. return build_exception_response(tx_id, unit_id, func, 0x03)
  229. offset = address - int(base_addr)
  230. if offset < 0 or offset + quantity > len(block):
  231. self.stats["errors"] += 1
  232. LOGGER.debug("非法地址: %d 数量 %d(块大小 %d)", address, quantity, len(block))
  233. return build_exception_response(tx_id, unit_id, func, 0x02)
  234. with self._lock:
  235. words = list(block[offset : offset + quantity])
  236. payload = bytes([len(words) * 2]) + u16s_to_bytes(words)
  237. return build_frame(tx_id, unit_id, bytes([func]) + payload)
  238. def _write_single(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
  239. if len(pdu) < 5:
  240. return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x03)
  241. address = int.from_bytes(pdu[1:3], "big")
  242. value = int.from_bytes(pdu[3:5], "big")
  243. offset = address - self.holding_addr
  244. if offset < 0 or offset >= len(self._holdings):
  245. self.stats["errors"] += 1
  246. return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x02)
  247. with self._lock:
  248. self._holdings[offset] = value & 0xFFFF
  249. registers = list(self._holdings)
  250. self._notify(registers, peer)
  251. return build_frame(tx_id, unit_id, pdu[:5])
  252. def _write_multiple(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
  253. if len(pdu) < 6:
  254. return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
  255. address = int.from_bytes(pdu[1:3], "big")
  256. quantity = int.from_bytes(pdu[3:5], "big")
  257. byte_count = pdu[5]
  258. if quantity < 1 or quantity > 123 or byte_count != quantity * 2:
  259. self.stats["errors"] += 1
  260. return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
  261. values = bytes_to_u16s(pdu[6 : 6 + byte_count])
  262. offset = address - self.holding_addr
  263. if offset < 0 or offset + quantity > len(self._holdings) or len(values) < quantity:
  264. self.stats["errors"] += 1
  265. return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x02)
  266. with self._lock:
  267. for i in range(quantity):
  268. self._holdings[offset + i] = values[i] & 0xFFFF
  269. registers = list(self._holdings)
  270. self._notify(registers, peer)
  271. return build_frame(
  272. tx_id, unit_id, bytes([FC_WRITE_MULTIPLE_REGISTERS]) + u16s_to_bytes([address, quantity])
  273. )
  274. def _notify(self, registers: List[int], peer: str) -> None:
  275. if self.on_command is None:
  276. return
  277. try:
  278. self.on_command(registers, peer)
  279. except Exception: # pragma: no cover - 回调异常不能影响 Modbus 通信
  280. LOGGER.exception("on_command 回调异常(来自 %s)", peer)