"""S7 (S7comm / python-snap7) 发布端:视觉侧主动把快照写进 PLC 的 DB 块。 适用场景 -------- * PLC 侧不方便做 Modbus 客户端(例如用 1500 的 PUT/GET 或已有 S7 通信栈); * 需要视觉侧按节拍推送、PLC 侧只读 DB 的架构; * 与 Modbus 通道并行做冗余。 依赖:``pip install python-snap7``(Jetson/RK 上直接 pip 装即可,无需 snap7-server 组件—— 客户端模式下库自带实现)。未安装时本发布器会**降级为不可用**并给出明确提示, 不影响 Modbus 通道运行。 写入的 DB 布局与 :meth:`VisionSnapshot.to_db_bytes` 完全一致(12 字 = 24 字节,大端): =========================== ================== 偏移(字节) 含义 =========================== ================== 0..1 state (0/1/2/255) 2..3 confidence 千分比 4..5 flags 位域 6..9 seq (32bit) 10..13 ts_s (32bit) 14..15 heartbeat 16..17 fps_x10 18..19 latency_ms 20..21 reserved 22..23 CRC-16/MODBUS =========================== ================== """ from __future__ import annotations import threading import time from typing import Dict, Optional from ..config import Config from ..logging_utils import get_logger from ..schema import PlcCommand, VisionSnapshot from .publisher import PlcPublisher __all__ = ["Snap7Publisher"] LOGGER = get_logger("plc.snap7") MISSING_HINT = ( "未安装 python-snap7,S7 推送通道不可用。请执行 `pip install python-snap7`," "或把配置改为 plc.push=\"modbus_server\" 走 Modbus/TCP 通道。" ) class Snap7Publisher(PlcPublisher): """按需重连的 S7 DB 写入器。""" name = "snap7" def __init__(self, cfg: Config) -> None: snap = cfg.get_path("plc.snap7", {}) or {} self.host = str(snap.get("host", "192.168.0.10")) self.rack = int(snap.get("rack", 0)) self.slot = int(snap.get("slot", 1)) self.tcp_port = int(snap.get("tcp_port", 102)) self.db_number = int(snap.get("db_number", 100)) self.db_start = int(snap.get("db_start", 0)) self.reconnect_s = float(snap.get("reconnect_s", 3.0)) #: >0 时同时从该 DB 读回 PLC 指令(可选) self.cmd_db_number = int(snap.get("cmd_db_number", 0)) self.cmd_db_start = int(snap.get("cmd_db_start", 0)) self._lock = threading.Lock() self._client = None self._snap7 = None self._available = True self._last_attempt = 0.0 self._last_error = "" self._writes = 0 self._errors = 0 self._command = PlcCommand() self._generation = 0 self._consumed = 0 # ------------------------------------------------------------ 生命周期 def start(self) -> None: self._connect(force=True) def stop(self) -> None: with self._lock: client = self._client self._client = None if client is not None: try: client.disconnect() except Exception: # pragma: no cover pass try: client.destroy() except Exception: # pragma: no cover pass LOGGER.info("S7 发布器已关闭") # ------------------------------------------------------------ 连接管理 def _connect(self, force: bool = False) -> bool: with self._lock: if self._client is not None: return True if not self._available: return False now = time.time() if not force and (now - self._last_attempt) < self.reconnect_s: return False self._last_attempt = now try: import snap7 # type: ignore except ImportError: with self._lock: self._available = False self._last_error = "缺少 python-snap7" LOGGER.error(MISSING_HINT) return False client = None try: client = snap7.client.Client() client.connect(self.host, self.rack, self.slot, self.tcp_port) if not client.get_connected(): raise RuntimeError("connect() 返回但未建立连接") except Exception as exc: self._last_error = str(exc) with self._lock: self._errors += 1 LOGGER.warning("连接 S7 %s rack=%d slot=%d 失败: %s", self.host, self.rack, self.slot, exc) try: if client is not None: client.destroy() except Exception: # pragma: no cover pass return False with self._lock: self._client = client self._snap7 = snap7 self._last_error = "" LOGGER.info( "S7 已连接 %s rack=%d slot=%d(DB%d,偏移 %d,端口 %d)", self.host, self.rack, self.slot, self.db_number, self.db_start, self.tcp_port, ) return True def _current_client(self): with self._lock: client = self._client if client is None: return None try: if client.get_connected(): return client except Exception: # pragma: no cover - 连接已断 pass with self._lock: self._client = None return None # ---------------------------------------------------------- 写入快照 def publish(self, snapshot: VisionSnapshot) -> bool: """把快照写入 DB;失败时标记断线,下个周期再重连(不阻塞主循环)。""" payload = snapshot.to_db_bytes() client = self._current_client() or (self._connect() and self._current_client()) if client is None: with self._lock: self._errors += 1 return False try: client.db_write(self.db_number, self.db_start, bytearray(payload)) except Exception as exc: with self._lock: self._errors += 1 self._last_error = str(exc) self._client = None LOGGER.warning("S7 写 DB%d 失败,将自动重连: %s", self.db_number, exc) return False with self._lock: self._writes += 1 return True # ---------------------------------------------------------- 读取指令 def _poll_command(self) -> None: if self.cmd_db_number <= 0: return client = self._current_client() if client is None: return size = PlcCommand.register_count() * 2 try: raw = bytes(client.db_read(self.cmd_db_number, self.cmd_db_start, size)) except Exception as exc: # pragma: no cover - 现场网络异常 LOGGER.debug("S7 读取指令 DB 失败: %s", exc) return words = [int.from_bytes(raw[i : i + 2], "big") for i in range(0, len(raw) - 1, 2)] command = PlcCommand.from_registers(words) with self._lock: if command.to_registers() != self._command.to_registers(): self._command = command self._generation += 1 LOGGER.info("S7 收到 PLC 指令 cmd=%d preset=%d", command.cmd, command.preset) def command(self) -> PlcCommand: self._poll_command() with self._lock: return self._command def take_command(self) -> Optional[PlcCommand]: self._poll_command() with self._lock: if self._generation <= self._consumed: return None self._consumed = self._generation return self._command # ---------------------------------------------------------- 状态 @property def ok(self) -> bool: return self._current_client() is not None @property def last_error(self) -> str: with self._lock: return self._last_error def status(self) -> Dict[str, object]: with self._lock: return { "publisher": self.name, "host": "%s rack=%d slot=%d" % (self.host, self.rack, self.slot), "db": self.db_number, "connected": self._client is not None, "available": self._available, "writes": self._writes, "errors": self._errors, "last_error": self._last_error, }