| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326 |
- """Modbus/TCP 服务端:把视觉结果暴露成寄存器块,供西门子 PLC 周期读取。
- 为什么不用 pymodbus?
- ---------------------
- 现场只用到 4 个功能码,自己实现 ~200 行即可,能避免 pymodbus 3.x 的 API 变动、
- asyncio 版本差异和"启动器/数据存储"概念带来的排障成本;同时寄存器映射逻辑
- (:mod:`portcv.schema`)与 :mod:`portcv.plc.modbus_pdu` 可以单元测试覆盖。
- 寄存器规划(地址 = 配置项 ``plc.modbus.input_addr`` / ``holding_addr`` + 偏移)
- ------------------------------------------------------------------------
- 输入寄存器(FC4,PLC 读,视觉写,12 个字)::
- 0 state 0=不在车上 1=车斗 2=平板车;V2 不再发布 255
- 1 confidence 千分比 0..1000
- 2 flags 状态位(见 schema.StatusBits)
- 3 seq_hi 结果序号高 16bit(状态每变化一次 +1)
- 4 seq_lo
- 5 ts_hi unix 秒高 16bit
- 6 ts_lo
- 7 heartbeat 心跳计数(每心跳周期 +1,PLC 用它判断视觉是否存活)
- 8 fps_x10 帧率 x10
- 9 latency_ms 单帧端到端耗时
- 10 reserved
- 11 crc16 CRC-16/MODBUS(前 11 个字,大端字节序)
- 保持寄存器(FC3/FC6/FC16,PLC 写,视觉读,4 个字)::
- 0 cmd 0=空闲 1=请求识别 2=复位 3=清统计
- 1 preset 相机/ROI 预设编号
- 2 min_conf 覆盖最小置信度(千分比,0=用配置)
- 3 reserved
- """
- from __future__ import annotations
- import socketserver
- import threading
- import time
- from typing import Callable, Dict, List, Optional, Sequence
- from ..logging_utils import get_logger
- from ..schema import PlcCommand, VisionSnapshot
- from .modbus_pdu import (
- EXCEPTION_CODES,
- FC_READ_HOLDING_REGISTERS,
- FC_READ_INPUT_REGISTERS,
- FC_WRITE_MULTIPLE_REGISTERS,
- FC_WRITE_SINGLE_REGISTER,
- MBAP_HEADER_LEN,
- build_exception_response,
- build_frame,
- bytes_to_u16s,
- parse_mbap,
- u16s_to_bytes,
- )
- __all__ = ["ModbusTcpServer"]
- LOGGER = get_logger("plc.modbus")
- class _Handler(socketserver.BaseRequestHandler):
- """一个 PLC 连接 = 一个线程,循环处理请求。"""
- server: "ModbusTcpServer" # type: ignore[assignment]
- def handle(self) -> None: # noqa: D102
- sock = self.request
- sock.settimeout(30.0)
- peer = "%s:%s" % self.client_address[:2]
- self.server.on_client_connected(peer)
- try:
- while not self.server.is_stopping():
- header = self._recv_exact(MBAP_HEADER_LEN)
- if header is None:
- break
- length = int.from_bytes(header[4:6], "big")
- # 与 C++ service_client 同口径:length 含 unit_id,最小 2、最大 254
- # (PDU 253)。非法长度直接断连,避免错位/恶意报文把连接线程
- # 吊在 30 s 超时上,或让服务端按 64 KB 去缓冲。
- if length < 2 or length > 254:
- break
- body = self._recv_exact(max(0, length - 1))
- if body is None:
- break
- response = self.server.handle_frame(header + body, peer)
- if response:
- sock.sendall(response)
- except (ConnectionResetError, OSError):
- pass
- finally:
- self.server.on_client_disconnected(peer)
- def _recv_exact(self, size: int) -> Optional[bytes]:
- chunks = b""
- while len(chunks) < size:
- try:
- piece = self.request.recv(size - len(chunks))
- except (ConnectionResetError, OSError):
- return None
- if not piece:
- return None
- chunks += piece
- return chunks
- class ModbusTcpServer(socketserver.ThreadingTCPServer):
- """线程化 Modbus/TCP 从站。
- ``on_command`` 会在 PLC 写入保持寄存器后回调 ``(registers, peer)``,
- 服务主循环据此响应"按需识别/复位"等命令。
- """
- allow_reuse_address = True
- daemon_threads = True
- #: 输入寄存器块大小(字)
- INPUT_SIZE = VisionSnapshot.register_count()
- #: 保持寄存器块大小(字)
- HOLDING_SIZE = PlcCommand.register_count()
- def __init__(
- self,
- host: str = "0.0.0.0",
- port: int = 1502,
- unit_id: int = 1,
- allow_unit_any: bool = True,
- input_addr: int = 0,
- holding_addr: int = 0,
- on_command: Optional[Callable[[List[int], str], None]] = None,
- ) -> None:
- self.host = host
- self.port = int(port)
- self.unit_id = int(unit_id)
- self.allow_unit_any = bool(allow_unit_any)
- self.input_addr = int(input_addr)
- self.holding_addr = int(holding_addr)
- self.on_command = on_command
- self._lock = threading.RLock()
- self._inputs: List[int] = [0] * self.INPUT_SIZE
- self._holdings: List[int] = [0] * self.HOLDING_SIZE
- self._stopping = False
- self._clients: Dict[str, float] = {}
- self.stats: Dict[str, int] = {"requests": 0, "reads": 0, "writes": 0, "errors": 0}
- self._publisher_thread: Optional[threading.Thread] = None
- super().__init__((host, int(port)), _Handler)
- LOGGER.info("Modbus/TCP 服务端已监听 %s:%d (unit=%d)", host, port, unit_id)
- # ------------------------------------------------------------ 生命周期
- def start(self) -> "ModbusTcpServer":
- self._stopping = False
- self._publisher_thread = threading.Thread(
- target=self.serve_forever, name="modbus-server", daemon=True
- )
- self._publisher_thread.start()
- return self
- def stop(self, timeout: float = 3.0) -> None:
- self._stopping = True
- try:
- self.shutdown()
- except Exception: # pragma: no cover
- pass
- self.server_close()
- if self._publisher_thread is not None:
- self._publisher_thread.join(timeout=timeout)
- self._publisher_thread = None
- def is_stopping(self) -> bool:
- return bool(self._stopping)
- # ------------------------------------------------------ 数据块访问接口
- def set_snapshot(self, snapshot: VisionSnapshot) -> List[int]:
- """把快照写入输入寄存器块,返回写入的字(便于自检/测试)。"""
- words = snapshot.to_registers()
- with self._lock:
- self._inputs = list(words)
- return words
- def input_registers(self) -> List[int]:
- with self._lock:
- return list(self._inputs)
- def holding_registers(self) -> List[int]:
- with self._lock:
- return list(self._holdings)
- def command(self) -> PlcCommand:
- with self._lock:
- return PlcCommand.from_registers(self._holdings)
- def set_holding_registers(self, values: Sequence[int], offset: int = 0) -> None:
- """测试/上位机预置指令用。"""
- with self._lock:
- for i, value in enumerate(values):
- index = int(offset) + i
- if 0 <= index < self.HOLDING_SIZE:
- self._holdings[index] = int(value) & 0xFFFF
- @property
- def client_count(self) -> int:
- with self._lock:
- return len(self._clients)
- def clients(self) -> Dict[str, float]:
- with self._lock:
- return dict(self._clients)
- def on_client_connected(self, peer: str) -> None:
- with self._lock:
- self._clients[peer] = time.time()
- LOGGER.info("PLC 已连接: %s", peer)
- def on_client_disconnected(self, peer: str) -> None:
- with self._lock:
- self._clients.pop(peer, None)
- LOGGER.info("PLC 断开: %s", peer)
- # ------------------------------------------------------------ 报文处理
- def handle_frame(self, frame: bytes, peer: str = "") -> bytes:
- """处理一个完整 MBAP 帧,返回响应字节(空字节 = 不响应)。"""
- try:
- tx_id, proto_id, _length, unit_id, pdu = parse_mbap(frame)
- except ValueError as exc:
- self.stats["errors"] += 1
- LOGGER.warning("报文解析失败(%s): %s", peer, exc)
- return b""
- if not self.allow_unit_any and unit_id != self.unit_id:
- return b""
- if proto_id != 0 or not pdu:
- self.stats["errors"] += 1
- return build_exception_response(tx_id, unit_id, pdu[0] if pdu else 0, 0x03)
- # 注意:allow_unit_any 只表示“接受任意站点号”,响应必须原样回显请求的
- # unit_id(Modbus/TCP 规范)。不能改成配置里的 self.unit_id,否则 PLC 用
- # 非 1 的站点号时会把响应当成别的从站而丢弃/超时。
- func = pdu[0]
- self.stats["requests"] += 1
- if func == FC_READ_INPUT_REGISTERS:
- self.stats["reads"] += 1
- return self._read_registers(tx_id, unit_id, func, pdu, self._inputs, self.input_addr)
- if func == FC_READ_HOLDING_REGISTERS:
- self.stats["reads"] += 1
- return self._read_registers(tx_id, unit_id, func, pdu, self._holdings, self.holding_addr)
- if func == FC_WRITE_SINGLE_REGISTER:
- self.stats["writes"] += 1
- return self._write_single(tx_id, unit_id, pdu, peer)
- if func == FC_WRITE_MULTIPLE_REGISTERS:
- self.stats["writes"] += 1
- return self._write_multiple(tx_id, unit_id, pdu, peer)
- self.stats["errors"] += 1
- LOGGER.debug("未支持的功能码 0x%02X(来自 %s)", func, peer)
- return build_exception_response(tx_id, unit_id, func, 0x01)
- def _read_registers(
- self, tx_id: int, unit_id: int, func: int, pdu: bytes, block: List[int], base_addr: int
- ) -> bytes:
- if len(pdu) < 5:
- return build_exception_response(tx_id, unit_id, func, 0x03)
- address = int.from_bytes(pdu[1:3], "big")
- quantity = int.from_bytes(pdu[3:5], "big")
- if quantity < 1 or quantity > 125:
- self.stats["errors"] += 1
- return build_exception_response(tx_id, unit_id, func, 0x03)
- offset = address - int(base_addr)
- if offset < 0 or offset + quantity > len(block):
- self.stats["errors"] += 1
- LOGGER.debug("非法地址: %d 数量 %d(块大小 %d)", address, quantity, len(block))
- return build_exception_response(tx_id, unit_id, func, 0x02)
- with self._lock:
- words = list(block[offset : offset + quantity])
- payload = bytes([len(words) * 2]) + u16s_to_bytes(words)
- return build_frame(tx_id, unit_id, bytes([func]) + payload)
- def _write_single(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
- if len(pdu) < 5:
- return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x03)
- address = int.from_bytes(pdu[1:3], "big")
- value = int.from_bytes(pdu[3:5], "big")
- offset = address - self.holding_addr
- if offset < 0 or offset >= len(self._holdings):
- self.stats["errors"] += 1
- return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x02)
- with self._lock:
- self._holdings[offset] = value & 0xFFFF
- registers = list(self._holdings)
- self._notify(registers, peer)
- return build_frame(tx_id, unit_id, pdu[:5])
- def _write_multiple(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
- if len(pdu) < 6:
- return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
- address = int.from_bytes(pdu[1:3], "big")
- quantity = int.from_bytes(pdu[3:5], "big")
- byte_count = pdu[5]
- if quantity < 1 or quantity > 123 or byte_count != quantity * 2:
- self.stats["errors"] += 1
- return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
- values = bytes_to_u16s(pdu[6 : 6 + byte_count])
- offset = address - self.holding_addr
- if offset < 0 or offset + quantity > len(self._holdings) or len(values) < quantity:
- self.stats["errors"] += 1
- return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x02)
- with self._lock:
- for i in range(quantity):
- self._holdings[offset + i] = values[i] & 0xFFFF
- registers = list(self._holdings)
- self._notify(registers, peer)
- return build_frame(
- tx_id, unit_id, bytes([FC_WRITE_MULTIPLE_REGISTERS]) + u16s_to_bytes([address, quantity])
- )
- def _notify(self, registers: List[int], peer: str) -> None:
- if self.on_command is None:
- return
- try:
- self.on_command(registers, peer)
- except Exception: # pragma: no cover - 回调异常不能影响 Modbus 通信
- LOGGER.exception("on_command 回调异常(来自 %s)", peer)
|