publisher.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. """PLC 发布层:把 :class:`VisionSnapshot` 送出去,并把 PLC 指令收进来。
  2. 三种模式(``plc.push``)
  3. -----------------------
  4. ``modbus_server``(默认,推荐)
  5. 视觉侧做 Modbus/TCP **从站**,PLC 做客户端周期读输入寄存器(FC4),
  6. 同时把指令写到保持寄存器(FC6/FC16)。西门子 PLC 用 ``MB_CLIENT`` 指令即可,
  7. 不需要额外库,联调最省事。
  8. ``snap7``
  9. PLC 做服务端,视觉侧用 S7comm(``python-snap7``)主动写 DB 块,
  10. 适合 PLC 侧不方便发起轮询、或要走 S7 通信(如 1500 的 PUT/GET)。
  11. ``both``
  12. 两条链路同时写,互为冗余(现场切换/过渡期常用)。
  13. """
  14. from __future__ import annotations
  15. import threading
  16. import time
  17. from typing import Dict, List, Optional
  18. from ..config import Config
  19. from ..logging_utils import get_logger
  20. from ..schema import PlcCommand, VisionSnapshot
  21. __all__ = [
  22. "MultiPublisher",
  23. "NullPublisher",
  24. "PlcPublisher",
  25. "ModbusServerPublisher",
  26. "build_publisher",
  27. ]
  28. LOGGER = get_logger("plc")
  29. class PlcPublisher:
  30. """发布接口。``publish`` 必须尽量快、非阻塞(现场节拍不允许被网络拖住)。"""
  31. name = "base"
  32. def start(self) -> None:
  33. """建立连接/开始监听。"""
  34. def publish(self, snapshot: VisionSnapshot) -> bool:
  35. raise NotImplementedError
  36. def command(self) -> PlcCommand:
  37. """当前 PLC 指令(未实现则返回空指令)。"""
  38. return PlcCommand()
  39. def take_command(self) -> Optional[PlcCommand]:
  40. """取走一条尚未处理的新指令(服务主循环轮询)。"""
  41. return None
  42. def stop(self) -> None:
  43. """释放资源。"""
  44. @property
  45. def ok(self) -> bool:
  46. return True
  47. def status(self) -> Dict[str, object]:
  48. return {"publisher": self.name, "ok": self.ok}
  49. class NullPublisher(PlcPublisher):
  50. """不连 PLC,只打日志(``plc.enabled=false`` 或纯离线调试用)。"""
  51. name = "none"
  52. def __init__(self) -> None:
  53. self._last: Optional[VisionSnapshot] = None
  54. def publish(self, snapshot: VisionSnapshot) -> bool:
  55. if self._last is None or int(self._last.state) != int(snapshot.state):
  56. LOGGER.info(
  57. "PLCoFF state=%d(%s) conf=%d seq=%d",
  58. int(snapshot.state),
  59. snapshot.to_dict()["state_label"],
  60. int(snapshot.confidence),
  61. int(snapshot.seq),
  62. )
  63. self._last = snapshot
  64. return True
  65. class ModbusServerPublisher(PlcPublisher):
  66. """Modbus/TCP 从站发布器(PLC 主动读)。"""
  67. name = "modbus_server"
  68. def __init__(self, cfg: Config) -> None:
  69. from .modbus_server import ModbusTcpServer
  70. modbus = cfg.get_path("plc.modbus", {}) or {}
  71. self._lock = threading.Lock()
  72. self._generation = 0
  73. self._consumed = 0
  74. self._command = PlcCommand()
  75. self._last_publish_ts = 0.0
  76. self._publish_count = 0
  77. self.server = ModbusTcpServer(
  78. host=str(modbus.get("host", "0.0.0.0")),
  79. port=int(modbus.get("port", 1502)),
  80. unit_id=int(modbus.get("unit_id", 1)),
  81. allow_unit_any=bool(modbus.get("allow_unit_any", True)),
  82. input_addr=int(modbus.get("input_addr", 0)),
  83. holding_addr=int(modbus.get("holding_addr", 0)),
  84. on_command=self._on_write,
  85. )
  86. # -- PlcPublisher 接口 -------------------------------------------------
  87. def start(self) -> None:
  88. self.server.start()
  89. LOGGER.info("Modbus 发布器就绪:%s:%d", self.server.host, self.server.port)
  90. def publish(self, snapshot: VisionSnapshot) -> bool:
  91. self.server.set_snapshot(snapshot)
  92. with self._lock:
  93. self._last_publish_ts = time.time()
  94. self._publish_count += 1
  95. return True
  96. def command(self) -> PlcCommand:
  97. with self._lock:
  98. return self._command
  99. def take_command(self) -> Optional[PlcCommand]:
  100. with self._lock:
  101. if self._generation <= self._consumed:
  102. return None
  103. self._consumed = self._generation
  104. return self._command
  105. def stop(self) -> None:
  106. try:
  107. self.server.stop()
  108. except Exception: # pragma: no cover
  109. pass
  110. # -- 内部 -------------------------------------------------------------
  111. def _on_write(self, registers: List[int], peer: str) -> None:
  112. command = PlcCommand.from_registers(registers)
  113. with self._lock:
  114. self._command = command
  115. self._generation += 1
  116. LOGGER.info(
  117. "收到 PLC 指令 cmd=%d preset=%d min_conf=%d (来自 %s)",
  118. command.cmd,
  119. command.preset,
  120. command.min_conf,
  121. peer,
  122. )
  123. @property
  124. def ok(self) -> bool:
  125. return bool(self.server.client_count > 0)
  126. def status(self) -> Dict[str, object]:
  127. with self._lock:
  128. return {
  129. "publisher": self.name,
  130. "listen": "%s:%d" % (self.server.host, self.server.port),
  131. "clients": self.server.client_count,
  132. "publish_count": self._publish_count,
  133. "generation": self._generation,
  134. "stats": dict(self.server.stats),
  135. }
  136. class MultiPublisher(PlcPublisher):
  137. """同时向多个发布器写入(任一失败不影响其它)。"""
  138. name = "multi"
  139. def __init__(self, publishers: List[PlcPublisher]) -> None:
  140. self.publishers = list(publishers)
  141. def start(self) -> None:
  142. for publisher in self.publishers:
  143. try:
  144. publisher.start()
  145. except Exception:
  146. LOGGER.exception("发布器 %s 启动失败", publisher.name)
  147. def publish(self, snapshot: VisionSnapshot) -> bool:
  148. ok = False
  149. for publisher in self.publishers:
  150. try:
  151. ok = publisher.publish(snapshot) or ok
  152. except Exception:
  153. LOGGER.exception("发布器 %s 写入失败", publisher.name)
  154. return ok
  155. def command(self) -> PlcCommand:
  156. for publisher in self.publishers:
  157. command = publisher.command()
  158. if int(command.cmd) != 0:
  159. return command
  160. return self.publishers[0].command() if self.publishers else PlcCommand()
  161. def take_command(self) -> Optional[PlcCommand]:
  162. for publisher in self.publishers:
  163. command = publisher.take_command()
  164. if command is not None:
  165. return command
  166. return None
  167. def stop(self) -> None:
  168. for publisher in self.publishers:
  169. try:
  170. publisher.stop()
  171. except Exception: # pragma: no cover
  172. pass
  173. @property
  174. def ok(self) -> bool:
  175. return any(p.ok for p in self.publishers)
  176. def status(self) -> Dict[str, object]:
  177. return {"publisher": self.name, "children": [p.status() for p in self.publishers]}
  178. def build_publisher(cfg: Config) -> PlcPublisher:
  179. """按 ``plc.enabled`` / ``plc.push`` 创建发布器。"""
  180. if not bool(cfg.get_path("plc.enabled", True)):
  181. return NullPublisher()
  182. mode = str(cfg.get_path("plc.push", "modbus_server")).lower()
  183. publishers: List[PlcPublisher] = []
  184. if mode in ("modbus_server", "modbus", "both"):
  185. publishers.append(ModbusServerPublisher(cfg))
  186. if mode in ("snap7", "s7", "both"):
  187. from .snap7_client import Snap7Publisher
  188. publishers.append(Snap7Publisher(cfg))
  189. if not publishers:
  190. LOGGER.warning("plc.push=%s 无法识别,退化为不连 PLC", mode)
  191. return NullPublisher()
  192. if len(publishers) == 1:
  193. return publishers[0]
  194. return MultiPublisher(publishers)