snap7_client.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. """S7 (S7comm / python-snap7) 发布端:视觉侧主动把快照写进 PLC 的 DB 块。
  2. 适用场景
  3. --------
  4. * PLC 侧不方便做 Modbus 客户端(例如用 1500 的 PUT/GET 或已有 S7 通信栈);
  5. * 需要视觉侧按节拍推送、PLC 侧只读 DB 的架构;
  6. * 与 Modbus 通道并行做冗余。
  7. 依赖:``pip install python-snap7``(Jetson/RK 上直接 pip 装即可,无需 snap7-server 组件——
  8. 客户端模式下库自带实现)。未安装时本发布器会**降级为不可用**并给出明确提示,
  9. 不影响 Modbus 通道运行。
  10. 写入的 DB 布局与 :meth:`VisionSnapshot.to_db_bytes` 完全一致(12 字 = 24 字节,大端):
  11. =========================== ==================
  12. 偏移(字节) 含义
  13. =========================== ==================
  14. 0..1 state (0/1/2/255)
  15. 2..3 confidence 千分比
  16. 4..5 flags 位域
  17. 6..9 seq (32bit)
  18. 10..13 ts_s (32bit)
  19. 14..15 heartbeat
  20. 16..17 fps_x10
  21. 18..19 latency_ms
  22. 20..21 reserved
  23. 22..23 CRC-16/MODBUS
  24. =========================== ==================
  25. """
  26. from __future__ import annotations
  27. import threading
  28. import time
  29. from typing import Dict, Optional
  30. from ..config import Config
  31. from ..logging_utils import get_logger
  32. from ..schema import PlcCommand, VisionSnapshot
  33. from .publisher import PlcPublisher
  34. __all__ = ["Snap7Publisher"]
  35. LOGGER = get_logger("plc.snap7")
  36. MISSING_HINT = (
  37. "未安装 python-snap7,S7 推送通道不可用。请执行 `pip install python-snap7`,"
  38. "或把配置改为 plc.push=\"modbus_server\" 走 Modbus/TCP 通道。"
  39. )
  40. class Snap7Publisher(PlcPublisher):
  41. """按需重连的 S7 DB 写入器。"""
  42. name = "snap7"
  43. def __init__(self, cfg: Config) -> None:
  44. snap = cfg.get_path("plc.snap7", {}) or {}
  45. self.host = str(snap.get("host", "192.168.0.10"))
  46. self.rack = int(snap.get("rack", 0))
  47. self.slot = int(snap.get("slot", 1))
  48. self.tcp_port = int(snap.get("tcp_port", 102))
  49. self.db_number = int(snap.get("db_number", 100))
  50. self.db_start = int(snap.get("db_start", 0))
  51. self.reconnect_s = float(snap.get("reconnect_s", 3.0))
  52. #: >0 时同时从该 DB 读回 PLC 指令(可选)
  53. self.cmd_db_number = int(snap.get("cmd_db_number", 0))
  54. self.cmd_db_start = int(snap.get("cmd_db_start", 0))
  55. self._lock = threading.Lock()
  56. self._client = None
  57. self._snap7 = None
  58. self._available = True
  59. self._last_attempt = 0.0
  60. self._last_error = ""
  61. self._writes = 0
  62. self._errors = 0
  63. self._command = PlcCommand()
  64. self._generation = 0
  65. self._consumed = 0
  66. # ------------------------------------------------------------ 生命周期
  67. def start(self) -> None:
  68. self._connect(force=True)
  69. def stop(self) -> None:
  70. with self._lock:
  71. client = self._client
  72. self._client = None
  73. if client is not None:
  74. try:
  75. client.disconnect()
  76. except Exception: # pragma: no cover
  77. pass
  78. try:
  79. client.destroy()
  80. except Exception: # pragma: no cover
  81. pass
  82. LOGGER.info("S7 发布器已关闭")
  83. # ------------------------------------------------------------ 连接管理
  84. def _connect(self, force: bool = False) -> bool:
  85. with self._lock:
  86. if self._client is not None:
  87. return True
  88. if not self._available:
  89. return False
  90. now = time.time()
  91. if not force and (now - self._last_attempt) < self.reconnect_s:
  92. return False
  93. self._last_attempt = now
  94. try:
  95. import snap7 # type: ignore
  96. except ImportError:
  97. with self._lock:
  98. self._available = False
  99. self._last_error = "缺少 python-snap7"
  100. LOGGER.error(MISSING_HINT)
  101. return False
  102. client = None
  103. try:
  104. client = snap7.client.Client()
  105. client.connect(self.host, self.rack, self.slot, self.tcp_port)
  106. if not client.get_connected():
  107. raise RuntimeError("connect() 返回但未建立连接")
  108. except Exception as exc:
  109. self._last_error = str(exc)
  110. with self._lock:
  111. self._errors += 1
  112. LOGGER.warning("连接 S7 %s rack=%d slot=%d 失败: %s", self.host, self.rack, self.slot, exc)
  113. try:
  114. if client is not None:
  115. client.destroy()
  116. except Exception: # pragma: no cover
  117. pass
  118. return False
  119. with self._lock:
  120. self._client = client
  121. self._snap7 = snap7
  122. self._last_error = ""
  123. LOGGER.info(
  124. "S7 已连接 %s rack=%d slot=%d(DB%d,偏移 %d,端口 %d)",
  125. self.host,
  126. self.rack,
  127. self.slot,
  128. self.db_number,
  129. self.db_start,
  130. self.tcp_port,
  131. )
  132. return True
  133. def _current_client(self):
  134. with self._lock:
  135. client = self._client
  136. if client is None:
  137. return None
  138. try:
  139. if client.get_connected():
  140. return client
  141. except Exception: # pragma: no cover - 连接已断
  142. pass
  143. with self._lock:
  144. self._client = None
  145. return None
  146. # ---------------------------------------------------------- 写入快照
  147. def publish(self, snapshot: VisionSnapshot) -> bool:
  148. """把快照写入 DB;失败时标记断线,下个周期再重连(不阻塞主循环)。"""
  149. payload = snapshot.to_db_bytes()
  150. client = self._current_client() or (self._connect() and self._current_client())
  151. if client is None:
  152. with self._lock:
  153. self._errors += 1
  154. return False
  155. try:
  156. client.db_write(self.db_number, self.db_start, bytearray(payload))
  157. except Exception as exc:
  158. with self._lock:
  159. self._errors += 1
  160. self._last_error = str(exc)
  161. self._client = None
  162. LOGGER.warning("S7 写 DB%d 失败,将自动重连: %s", self.db_number, exc)
  163. return False
  164. with self._lock:
  165. self._writes += 1
  166. return True
  167. # ---------------------------------------------------------- 读取指令
  168. def _poll_command(self) -> None:
  169. if self.cmd_db_number <= 0:
  170. return
  171. client = self._current_client()
  172. if client is None:
  173. return
  174. size = PlcCommand.register_count() * 2
  175. try:
  176. raw = bytes(client.db_read(self.cmd_db_number, self.cmd_db_start, size))
  177. except Exception as exc: # pragma: no cover - 现场网络异常
  178. LOGGER.debug("S7 读取指令 DB 失败: %s", exc)
  179. return
  180. words = [int.from_bytes(raw[i : i + 2], "big") for i in range(0, len(raw) - 1, 2)]
  181. command = PlcCommand.from_registers(words)
  182. with self._lock:
  183. if command.to_registers() != self._command.to_registers():
  184. self._command = command
  185. self._generation += 1
  186. LOGGER.info("S7 收到 PLC 指令 cmd=%d preset=%d", command.cmd, command.preset)
  187. def command(self) -> PlcCommand:
  188. self._poll_command()
  189. with self._lock:
  190. return self._command
  191. def take_command(self) -> Optional[PlcCommand]:
  192. self._poll_command()
  193. with self._lock:
  194. if self._generation <= self._consumed:
  195. return None
  196. self._consumed = self._generation
  197. return self._command
  198. # ---------------------------------------------------------- 状态
  199. @property
  200. def ok(self) -> bool:
  201. return self._current_client() is not None
  202. @property
  203. def last_error(self) -> str:
  204. with self._lock:
  205. return self._last_error
  206. def status(self) -> Dict[str, object]:
  207. with self._lock:
  208. return {
  209. "publisher": self.name,
  210. "host": "%s rack=%d slot=%d" % (self.host, self.rack, self.slot),
  211. "db": self.db_number,
  212. "connected": self._client is not None,
  213. "available": self._available,
  214. "writes": self._writes,
  215. "errors": self._errors,
  216. "last_error": self._last_error,
  217. }