"""PLC 发布层:把 :class:`VisionSnapshot` 送出去,并把 PLC 指令收进来。 三种模式(``plc.push``) ----------------------- ``modbus_server``(默认,推荐) 视觉侧做 Modbus/TCP **从站**,PLC 做客户端周期读输入寄存器(FC4), 同时把指令写到保持寄存器(FC6/FC16)。西门子 PLC 用 ``MB_CLIENT`` 指令即可, 不需要额外库,联调最省事。 ``snap7`` PLC 做服务端,视觉侧用 S7comm(``python-snap7``)主动写 DB 块, 适合 PLC 侧不方便发起轮询、或要走 S7 通信(如 1500 的 PUT/GET)。 ``both`` 两条链路同时写,互为冗余(现场切换/过渡期常用)。 """ from __future__ import annotations import threading import time from typing import Dict, List, Optional from ..config import Config from ..logging_utils import get_logger from ..schema import PlcCommand, VisionSnapshot __all__ = [ "MultiPublisher", "NullPublisher", "PlcPublisher", "ModbusServerPublisher", "build_publisher", ] LOGGER = get_logger("plc") class PlcPublisher: """发布接口。``publish`` 必须尽量快、非阻塞(现场节拍不允许被网络拖住)。""" name = "base" def start(self) -> None: """建立连接/开始监听。""" def publish(self, snapshot: VisionSnapshot) -> bool: raise NotImplementedError def command(self) -> PlcCommand: """当前 PLC 指令(未实现则返回空指令)。""" return PlcCommand() def take_command(self) -> Optional[PlcCommand]: """取走一条尚未处理的新指令(服务主循环轮询)。""" return None def stop(self) -> None: """释放资源。""" @property def ok(self) -> bool: return True def status(self) -> Dict[str, object]: return {"publisher": self.name, "ok": self.ok} class NullPublisher(PlcPublisher): """不连 PLC,只打日志(``plc.enabled=false`` 或纯离线调试用)。""" name = "none" def __init__(self) -> None: self._last: Optional[VisionSnapshot] = None def publish(self, snapshot: VisionSnapshot) -> bool: if self._last is None or int(self._last.state) != int(snapshot.state): LOGGER.info( "PLCoFF state=%d(%s) conf=%d seq=%d", int(snapshot.state), snapshot.to_dict()["state_label"], int(snapshot.confidence), int(snapshot.seq), ) self._last = snapshot return True class ModbusServerPublisher(PlcPublisher): """Modbus/TCP 从站发布器(PLC 主动读)。""" name = "modbus_server" def __init__(self, cfg: Config) -> None: from .modbus_server import ModbusTcpServer modbus = cfg.get_path("plc.modbus", {}) or {} self._lock = threading.Lock() self._generation = 0 self._consumed = 0 self._command = PlcCommand() self._last_publish_ts = 0.0 self._publish_count = 0 self.server = ModbusTcpServer( host=str(modbus.get("host", "0.0.0.0")), port=int(modbus.get("port", 1502)), unit_id=int(modbus.get("unit_id", 1)), allow_unit_any=bool(modbus.get("allow_unit_any", True)), input_addr=int(modbus.get("input_addr", 0)), holding_addr=int(modbus.get("holding_addr", 0)), on_command=self._on_write, ) # -- PlcPublisher 接口 ------------------------------------------------- def start(self) -> None: self.server.start() LOGGER.info("Modbus 发布器就绪:%s:%d", self.server.host, self.server.port) def publish(self, snapshot: VisionSnapshot) -> bool: self.server.set_snapshot(snapshot) with self._lock: self._last_publish_ts = time.time() self._publish_count += 1 return True def command(self) -> PlcCommand: with self._lock: return self._command def take_command(self) -> Optional[PlcCommand]: with self._lock: if self._generation <= self._consumed: return None self._consumed = self._generation return self._command def stop(self) -> None: try: self.server.stop() except Exception: # pragma: no cover pass # -- 内部 ------------------------------------------------------------- def _on_write(self, registers: List[int], peer: str) -> None: command = PlcCommand.from_registers(registers) with self._lock: self._command = command self._generation += 1 LOGGER.info( "收到 PLC 指令 cmd=%d preset=%d min_conf=%d (来自 %s)", command.cmd, command.preset, command.min_conf, peer, ) @property def ok(self) -> bool: return bool(self.server.client_count > 0) def status(self) -> Dict[str, object]: with self._lock: return { "publisher": self.name, "listen": "%s:%d" % (self.server.host, self.server.port), "clients": self.server.client_count, "publish_count": self._publish_count, "generation": self._generation, "stats": dict(self.server.stats), } class MultiPublisher(PlcPublisher): """同时向多个发布器写入(任一失败不影响其它)。""" name = "multi" def __init__(self, publishers: List[PlcPublisher]) -> None: self.publishers = list(publishers) def start(self) -> None: for publisher in self.publishers: try: publisher.start() except Exception: LOGGER.exception("发布器 %s 启动失败", publisher.name) def publish(self, snapshot: VisionSnapshot) -> bool: ok = False for publisher in self.publishers: try: ok = publisher.publish(snapshot) or ok except Exception: LOGGER.exception("发布器 %s 写入失败", publisher.name) return ok def command(self) -> PlcCommand: for publisher in self.publishers: command = publisher.command() if int(command.cmd) != 0: return command return self.publishers[0].command() if self.publishers else PlcCommand() def take_command(self) -> Optional[PlcCommand]: for publisher in self.publishers: command = publisher.take_command() if command is not None: return command return None def stop(self) -> None: for publisher in self.publishers: try: publisher.stop() except Exception: # pragma: no cover pass @property def ok(self) -> bool: return any(p.ok for p in self.publishers) def status(self) -> Dict[str, object]: return {"publisher": self.name, "children": [p.status() for p in self.publishers]} def build_publisher(cfg: Config) -> PlcPublisher: """按 ``plc.enabled`` / ``plc.push`` 创建发布器。""" if not bool(cfg.get_path("plc.enabled", True)): return NullPublisher() mode = str(cfg.get_path("plc.push", "modbus_server")).lower() publishers: List[PlcPublisher] = [] if mode in ("modbus_server", "modbus", "both"): publishers.append(ModbusServerPublisher(cfg)) if mode in ("snap7", "s7", "both"): from .snap7_client import Snap7Publisher publishers.append(Snap7Publisher(cfg)) if not publishers: LOGGER.warning("plc.push=%s 无法识别,退化为不连 PLC", mode) return NullPublisher() if len(publishers) == 1: return publishers[0] return MultiPublisher(publishers)