runner.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. """常驻服务:取帧 → 推理 → 判定 → 发布,并把心跳/指令/统计一并管起来。
  2. 线程模型
  3. --------
  4. * **抓帧线程**::class:`~portcv.io.capture.FrameGrabber` 内部线程,只保留最新帧;
  5. * **主线程**:本模块的循环,做推理与判定(按 ``run.max_fps`` 限速);
  6. * **Modbus 线程**:由 :class:`~portcv.plc.modbus_server.ModbusTcpServer` 派生,
  7. 负责应答 PLC 的读写,并把指令投递给主循环(``take_command``);
  8. * **存图线程**:仅当 ``run.save_on_change=true`` 时启动,只做 JPEG 编码与写盘。
  9. 队列满就丢图并计数(``stats.saves_dropped``),**绝不阻塞推理**——1080p 编码
  10. 实测 3~15 ms,是这条链路上最容易漏算的一笔。
  11. 因此发布动作是**非阻塞**的:Modbus 模式下写的是内存寄存器块,S7 模式下写入失败
  12. 只会标记断线并在下个周期重连,不会拖慢节拍。
  13. 安全语义(重要)
  14. ----------------
  15. V2:PLC 结果区的 ``state`` 只写 0/1/2(``255`` 只存在于内部 ``Decision``)。
  16. 只要出现下列任一情况,都由 :class:`~portcv.service.publish_gate.PublishGate`
  17. **保持上一稳定值**(无历史则 0),并清掉 ``STABLE`` / ``RESULT_VALID``:
  18. * 长时间拿不到新帧(``FRAME_TIMEOUT``);
  19. * 内部状态 255、置信度不足或状态尚未稳定。
  20. 这样 HMI 仍能看到"视觉认为是 1 但我不敢确认"(state=1、flags=0/0),
  21. PLC 则以标志位为准——比直接翻成 0/1/2 更安全。
  22. """
  23. from __future__ import annotations
  24. import os
  25. import queue
  26. import threading
  27. import time
  28. from typing import Any, Dict, Optional, Tuple
  29. from ..calibration import evaluate as evaluate_calibration
  30. from ..config import Config
  31. from ..detect.rknn_backend import model_chain_ratio
  32. from ..health import FrameHealthMonitor, HealthReport
  33. from ..io import build_grabber
  34. from ..io.capture import Frame, FrameGrabber
  35. from ..logging_utils import get_logger
  36. from ..plc import PlcPublisher, build_publisher
  37. from ..schema import Decision, Observation, PlcCommand, SceneState, StatusBits, VisionSnapshot
  38. from ..storage import EvidenceStore
  39. from .pipeline import VisionPipeline
  40. from .publish_gate import PublishGate, PublishResult
  41. __all__ = ["RunService"]
  42. LOGGER = get_logger("service")
  43. class _SaveWorker:
  44. """状态变化存图的落盘线程:主线程只画框 + 投递,JPEG 编码与写盘在后台。
  45. 为什么值得单独开一个线程:``cv2.imwrite`` 对 1080p 是 **3~15 ms**(x86 / aarch64),
  46. 而且它发生在状态刚变化的那一帧——正是 PLC 最在意节拍的时刻。画框必须留在主线程
  47. (要跟当前帧同步),编码与写盘完全可以异步。
  48. 队列有界(默认 8):现场磁盘变慢时宁可**丢难例**也不要拖慢推理,
  49. 丢弃数量记在 :attr:`dropped`,由 ``stats.saves_dropped`` 上报。
  50. """
  51. def __init__(self, maxsize: int = 8) -> None:
  52. self._queue: "queue.Queue[Tuple[Any, str]]" = queue.Queue(maxsize=max(1, int(maxsize)))
  53. self._stop = threading.Event()
  54. self._thread: Optional[threading.Thread] = None
  55. self.saved = 0
  56. self.dropped = 0
  57. self.errors = 0
  58. # ------------------------------------------------------------ 生命周期
  59. def start(self) -> "_SaveWorker":
  60. if self._thread is None:
  61. self._thread = threading.Thread(target=self._loop, name="save-worker", daemon=True)
  62. self._thread.start()
  63. return self
  64. def stop(self, timeout: float = 3.0) -> None:
  65. """停止并**尽量排空**队列(已入队的图会写完),超时则丢下剩余部分。"""
  66. self._stop.set()
  67. thread = self._thread
  68. if thread is not None:
  69. thread.join(timeout=timeout)
  70. self._thread = None
  71. # ------------------------------------------------------------ 投递
  72. def submit(self, image: Any, path: str) -> bool:
  73. """投递一张待写图;队列满返回 ``False``(调用方计数,不要重试)。"""
  74. try:
  75. self._queue.put_nowait((image, path))
  76. return True
  77. except queue.Full:
  78. self.dropped += 1
  79. return False
  80. # ------------------------------------------------------------ 线程体
  81. def _loop(self) -> None:
  82. try:
  83. import cv2 # 延迟导入:无 OpenCV 时线程直接退出,不影响主链路
  84. except ImportError: # pragma: no cover
  85. LOGGER.warning("未安装 opencv-python,存图线程不启动")
  86. return
  87. while not self._stop.is_set() or not self._queue.empty():
  88. try:
  89. image, path = self._queue.get(timeout=0.2)
  90. except queue.Empty:
  91. continue
  92. try:
  93. if cv2.imwrite(path, image):
  94. self.saved += 1
  95. else:
  96. self.errors += 1
  97. except Exception: # pragma: no cover - 磁盘满/权限问题
  98. self.errors += 1
  99. LOGGER.exception("后台存图失败:%s", path)
  100. finally:
  101. self._queue.task_done()
  102. class RunService:
  103. """把流水线、发布器、抓帧器组装成一个可长时间运行的服务。"""
  104. def __init__(
  105. self,
  106. cfg: Config,
  107. pipeline: Optional[VisionPipeline] = None,
  108. publisher: Optional[PlcPublisher] = None,
  109. grabber: Optional[FrameGrabber] = None,
  110. ) -> None:
  111. self.cfg = cfg
  112. self.pipeline = pipeline or VisionPipeline(cfg)
  113. self.publisher = publisher or build_publisher(cfg)
  114. self.grabber = grabber or build_grabber(cfg)
  115. run = cfg.section("run")
  116. plc = cfg.section("plc")
  117. self.max_fps = float(run.get("max_fps", 15.0) or 0.0)
  118. self.save_on_change = bool(run.get("save_on_change", False))
  119. self.output_dir = str(run.get("output_dir", "runs") or "runs")
  120. self.preview = bool(run.get("preview", False))
  121. self.gating = bool(plc.get("gating", False))
  122. self.gating_timeout_s = max(0.0, float(plc.get("gating_timeout_ms", 800)) / 1000.0)
  123. self.heartbeat_s = max(0.05, float(plc.get("heartbeat_ms", 500)) / 1000.0)
  124. self.min_publish_interval_s = max(
  125. 0.0, float(plc.get("min_publish_interval_ms", 50)) / 1000.0
  126. )
  127. self.confidence_scale = int(plc.get("confidence_scale", 1000) or 1000)
  128. self.min_confidence = float(cfg.get_path("decision.min_confidence", 0.45))
  129. self.low_fps = float(cfg.get_path("decision.low_fps_threshold", 3.0))
  130. self.mrc_on_uncertain = bool(cfg.get_path("decision.mrc_on_uncertain", True))
  131. self.health = FrameHealthMonitor.from_config(cfg)
  132. self._last_health = HealthReport()
  133. self._health_logged: Optional[str] = None
  134. self._calib_status = evaluate_calibration(cfg)
  135. self._calib_stale = bool(self._calib_status.stale)
  136. self._calib_hold = bool(getattr(self._calib_status, "hold", True))
  137. self.evidence = (
  138. EvidenceStore.from_config(cfg)
  139. if bool(cfg.get_path("evidence.enabled", False))
  140. else None
  141. )
  142. self._last_purge_ts = 0.0
  143. self._evidence_commit_latch = False
  144. # V2:PLC 结果区只写 0/1/2;内部 255/低分/未稳定/超时都由 PublishGate 保持。
  145. self._publish_gate = PublishGate(self.min_confidence)
  146. self._stop = threading.Event()
  147. self._heartbeat = 0
  148. self._last_frame_id = -1
  149. self._last_publish_ts = 0.0
  150. self._last_snapshot: Optional[VisionSnapshot] = None
  151. self._last_decision = Decision()
  152. self._last_publish_result: Optional[PublishResult] = None
  153. self._last_observation: Optional[Observation] = None
  154. self._on_demand_until = 0.0
  155. self._min_conf_override = 0
  156. self._start_ts = 0.0
  157. self._latency_ema = 0.0
  158. self._saved = 0
  159. self._saver: Optional[_SaveWorker] = None
  160. self._publish_ok = True
  161. self._timeout_latched = False
  162. self._reset_publish_pending = False
  163. self.stats: Dict[str, object] = {
  164. "frames": 0,
  165. "published": 0,
  166. "changes": 0,
  167. "errors": 0,
  168. "saves_dropped": 0,
  169. "state_counts": {},
  170. }
  171. # ------------------------------------------------------------ 生命周期
  172. def start(self) -> "RunService":
  173. """加载模型 → 预热 → 启动抓帧与发布通道。"""
  174. LOGGER.info("启动 portcv 服务:backend=%s mode=%s", self.pipeline.detector.name, self.cfg.get_path("run.mode"))
  175. if self._calib_stale:
  176. LOGGER.warning(
  177. "标定不可用(CALIB_STALE):%s;record=%s",
  178. ",".join(self._calib_status.reasons) or "unknown",
  179. self._calib_status.path or "(empty)",
  180. )
  181. if self._calib_hold:
  182. LOGGER.warning(
  183. "标定不可信 → 清 RESULT_VALID/STABLE(calibration.hold_on_stale=true);"
  184. "PLC 不得据此自动动作。请现场重标 + 复核后重新封存记录。"
  185. )
  186. else:
  187. LOGGER.warning(
  188. "仅告警(calibration.hold_on_stale=false):是否继续自动运行由 PLC 联锁/现场规程决定。"
  189. )
  190. elif self._calib_status.record is not None:
  191. LOGGER.info(
  192. "标定记录:%s %s(%s,复核 %s,%.1f 天)",
  193. self._calib_status.record.site,
  194. self._calib_status.record.camera_id,
  195. self._calib_status.record.method,
  196. self._calib_status.record.reviewer,
  197. self._calib_status.age_days or 0.0,
  198. )
  199. self.pipeline.load()
  200. warmed = self.pipeline.warmup()
  201. if warmed:
  202. LOGGER.info("推理预热完成(%d 帧,%.1f ms/帧)", warmed, self.pipeline.detector.infer_ms)
  203. self.publisher.start()
  204. self.grabber.start()
  205. if self.save_on_change and self._saver is None:
  206. self._saver = _SaveWorker().start()
  207. if self.evidence is not None:
  208. try:
  209. self.evidence.open()
  210. self._last_purge_ts = time.time()
  211. LOGGER.info("证据链已启用:%s", self.evidence.directory)
  212. except Exception: # pragma: no cover - 磁盘/权限问题不应拖垮服务
  213. LOGGER.exception("证据链打开失败,已禁用(服务继续运行)")
  214. self.evidence = None
  215. self._start_ts = time.time()
  216. return self
  217. def stop(self) -> None:
  218. self._stop.set()
  219. try:
  220. self.grabber.stop()
  221. except Exception: # pragma: no cover
  222. pass
  223. if self._saver is not None:
  224. # 先停抓帧再排空存图队列:已入队的难例会尽量写完,超时就丢
  225. self._saver.stop()
  226. self.stats["saves_dropped"] = int(self._saver.dropped)
  227. LOGGER.info(
  228. "存图线程已退出:写入 %d 张,丢弃 %d 张,失败 %d 次",
  229. int(self._saver.saved),
  230. int(self._saver.dropped),
  231. int(self._saver.errors),
  232. )
  233. self._saver = None
  234. try:
  235. self.publisher.stop()
  236. except Exception: # pragma: no cover
  237. pass
  238. if self.evidence is not None:
  239. try:
  240. self.evidence.close()
  241. except Exception: # pragma: no cover
  242. pass
  243. self.pipeline.close()
  244. LOGGER.info("服务已停止:%s", self.status_line())
  245. # ------------------------------------------------------------ 命令处理
  246. def handle_command(self) -> Optional[PlcCommand]:
  247. """处理 PLC 指令;返回本次取到的指令(没有则 ``None``)。"""
  248. command = self.publisher.take_command()
  249. if command is None:
  250. return None
  251. if int(command.min_conf) > 0:
  252. self._min_conf_override = int(command.min_conf)
  253. if command.is_request():
  254. self._on_demand_until = time.time() + self.gating_timeout_s
  255. LOGGER.info("PLC 请求识别:按需窗口 %.0f ms", self.gating_timeout_s * 1000)
  256. elif int(command.cmd) == 2:
  257. self.pipeline.reset()
  258. self._publish_gate.reset()
  259. self._last_decision = Decision()
  260. self._last_publish_result = None
  261. self._reset_publish_pending = True
  262. self._last_frame_id = -1
  263. self._on_demand_until = 0.0
  264. self._min_conf_override = 0
  265. self._evidence_commit_latch = False
  266. LOGGER.info("PLC 复位:投票窗口、PublishGate 与保持状态已清零")
  267. elif int(command.cmd) == 3:
  268. self._start_ts = time.time()
  269. self.stats["changes"] = 0
  270. self.stats["errors"] = 0
  271. self.stats["state_counts"] = {}
  272. LOGGER.info("PLC 清统计")
  273. return command
  274. # ------------------------------------------------------------ 主循环
  275. def run(
  276. self,
  277. max_seconds: Optional[float] = None,
  278. max_frames: Optional[int] = None,
  279. log_interval_s: float = 5.0,
  280. ) -> Dict[str, object]:
  281. """阻塞运行主循环;``max_seconds`` / ``max_frames`` 只用于自检与测试。"""
  282. self._stop.clear()
  283. self.start()
  284. next_log = time.time() + max(1.0, float(log_interval_s))
  285. last_frame_start = 0.0
  286. try:
  287. while not self._stop.is_set():
  288. now = time.time()
  289. if max_seconds is not None and (now - self._start_ts) >= float(max_seconds):
  290. LOGGER.info("达到 max_seconds=%.1f,正常退出", float(max_seconds))
  291. break
  292. if max_frames is not None and int(self.stats["frames"]) >= int(max_frames):
  293. LOGGER.info("达到 max_frames=%d,正常退出", int(max_frames))
  294. break
  295. self.handle_command()
  296. if self.gating and now >= self._on_demand_until:
  297. # 按需模式空档期:只刷心跳,不做推理
  298. self._publish_heartbeat(now)
  299. self._idle_sleep()
  300. continue
  301. frame = self.grabber.latest
  302. if frame is None or frame.frame_id == self._last_frame_id:
  303. self._publish_timeout_if_needed(now)
  304. self._publish_heartbeat(now)
  305. self._idle_sleep()
  306. continue
  307. last_frame_start = time.time()
  308. self._last_frame_id = frame.frame_id
  309. self._process(frame)
  310. self._publish_heartbeat(now)
  311. if now >= next_log:
  312. next_log = now + max(1.0, float(log_interval_s))
  313. LOGGER.info(self.status_line())
  314. if self.max_fps > 0:
  315. budget = 1.0 / self.max_fps
  316. used = time.time() - last_frame_start
  317. if used < budget:
  318. self._stop.wait(budget - used)
  319. except KeyboardInterrupt: # pragma: no cover - 现场 Ctrl+C
  320. LOGGER.info("收到中断信号,正在退出…")
  321. finally:
  322. self.stop()
  323. return self.stats
  324. # ------------------------------------------------------------ 单帧处理
  325. def _process(self, frame: Frame) -> Tuple[Observation, Decision]:
  326. start = time.perf_counter()
  327. if self._timeout_latched:
  328. self._timeout_latched = False
  329. LOGGER.info("取流已恢复(帧 #%d)", frame.frame_id)
  330. observation, decision = self.pipeline.step(frame)
  331. health = self.health.observe(frame.image, frame.ts)
  332. self._last_health = health
  333. self._log_health_change(health)
  334. latency_ms = (time.perf_counter() - start) * 1000.0
  335. self._latency_ema = (
  336. latency_ms if self._latency_ema <= 0 else 0.8 * self._latency_ema + 0.2 * latency_ms
  337. )
  338. self._last_observation = observation
  339. self._last_decision = decision
  340. self.stats["frames"] = int(self.stats["frames"]) + 1
  341. if decision.changed:
  342. self.stats["changes"] = int(self.stats["changes"]) + 1
  343. counts = dict(self.stats["state_counts"]) # type: ignore[arg-type]
  344. key = str(int(decision.state))
  345. counts[key] = int(counts.get(key, 0)) + 1
  346. self.stats["state_counts"] = counts
  347. LOGGER.info(
  348. "状态变化 → %d(%s) conf=%.2f seq=%d 原因=%s",
  349. int(decision.state),
  350. decision.label,
  351. decision.confidence,
  352. int(decision.seq),
  353. decision.reason,
  354. )
  355. self._save_on_change(frame, observation, decision)
  356. self._publish(frame, decision, latency_ms)
  357. self._record_evidence(frame, observation, decision)
  358. if self.preview:
  359. self._show_preview(frame, observation, decision)
  360. return observation, decision
  361. def _record_evidence(
  362. self, frame: Frame, observation: Observation, decision: Decision
  363. ) -> None:
  364. """P0-4:逐帧证据 + 状态变化事件环缓;失败只告警,不影响发布。"""
  365. if self.evidence is None:
  366. return
  367. try:
  368. evidence_v2 = getattr(self.pipeline, "evidence_v2", None)
  369. evidence_result = evidence_v2.last if evidence_v2 is not None else None
  370. committed = bool(getattr(evidence_result, "committed", False))
  371. event = bool(decision.changed) or (committed and not self._evidence_commit_latch)
  372. self._evidence_commit_latch = committed
  373. self.evidence.record(
  374. frame,
  375. observation,
  376. decision,
  377. snapshot=self._last_snapshot,
  378. evidence=evidence_result,
  379. health=self._last_health,
  380. event=event,
  381. )
  382. now = time.time()
  383. if (now - self._last_purge_ts) >= 3600.0:
  384. self._last_purge_ts = now
  385. removed = self.evidence.purge()
  386. if removed:
  387. LOGGER.info("证据链清理过期文件 %d 个", len(removed))
  388. except Exception: # pragma: no cover - 磁盘满/权限问题不影响主链路
  389. LOGGER.exception("证据落盘失败(本帧跳过)")
  390. # ------------------------------------------------------------ 自监测
  391. def _log_health_change(self, health: HealthReport) -> None:
  392. """健康状态变化时打一条结构化 warning;正常时不刷日志。"""
  393. key = "%s|%s" % (int(health.sensor_degraded), ",".join(health.reasons))
  394. if key == self._health_logged:
  395. return
  396. self._health_logged = key
  397. if health.sensor_degraded:
  398. LOGGER.warning(
  399. "视觉健康降级:%s(blur=%.1f dark=%.2f bright=%.2f low_tex=%.2f)",
  400. ",".join(health.reasons) or "degraded",
  401. health.blur_var,
  402. health.dark_clip_ratio,
  403. health.bright_clip_ratio,
  404. health.low_texture_ratio,
  405. )
  406. else:
  407. LOGGER.info("视觉健康恢复:blur=%.1f low_tex=%.2f", health.blur_var,
  408. health.low_texture_ratio)
  409. # ------------------------------------------------------------ 快照发布
  410. def _effective_min_conf(self) -> float:
  411. """PLC 覆盖值(千分比)优先;否则用 ``decision.min_confidence``。"""
  412. if self._min_conf_override > 0:
  413. scale = float(self.confidence_scale or 1000)
  414. if scale > 0.0:
  415. return float(self._min_conf_override) / scale
  416. return self.min_confidence
  417. def build_snapshot(
  418. self,
  419. decision: Decision,
  420. latency_ms: float = 0.0,
  421. extra_flags: int = 0,
  422. *,
  423. frame_timeout: Optional[bool] = None,
  424. reset: bool = False,
  425. health: Optional[HealthReport] = None,
  426. ) -> VisionSnapshot:
  427. """按当前状态组装 :class:`VisionSnapshot`(含所有状态位)。
  428. V2:发给 PLC 的 ``state`` / ``confidence`` / ``STABLE`` /
  429. ``RESULT_VALID`` 一律由 :class:`PublishGate` 决定;内部 ``255``
  430. 不会写进结果区。P0-2/P0-3:健康退化或任何“保持”都置
  431. ``PERCEPTION_UNCERTAIN``,并按配置请求 ``MRC``。
  432. """
  433. now = time.time()
  434. fps = self.grabber.fps
  435. fresh = self.grabber.fresh
  436. timeout = (not fresh) if frame_timeout is None else bool(frame_timeout)
  437. reset_now = bool(reset or self._reset_publish_pending)
  438. report = health or self._last_health
  439. uncertain = bool(report.perception_uncertain) and not reset_now
  440. published = self._publish_gate.apply(
  441. decision,
  442. frame_timeout=timeout,
  443. reset=reset_now,
  444. min_conf=self._effective_min_conf(),
  445. perception_uncertain=uncertain,
  446. )
  447. self._last_publish_result = published
  448. if reset_now:
  449. self._reset_publish_pending = False
  450. flags = 0
  451. if self.pipeline.ready:
  452. flags |= int(StatusBits.READY)
  453. if fresh and not timeout:
  454. flags |= int(StatusBits.FRAME_OK)
  455. else:
  456. flags |= int(StatusBits.FRAME_TIMEOUT)
  457. flags |= int(StatusBits.DATA_LOSS)
  458. if published.stable:
  459. flags |= int(StatusBits.STABLE)
  460. if published.result_valid:
  461. flags |= int(StatusBits.RESULT_VALID)
  462. if 0.0 < fps < self.low_fps:
  463. flags |= int(StatusBits.LOW_FPS)
  464. if self.gating and now < self._on_demand_until:
  465. flags |= int(StatusBits.ON_DEMAND)
  466. if self._publish_ok:
  467. flags |= int(StatusBits.PUBLISH_OK)
  468. if published.perception_uncertain:
  469. flags |= int(StatusBits.PERCEPTION_UNCERTAIN)
  470. if self.mrc_on_uncertain:
  471. flags |= int(StatusBits.MRC_REQUEST)
  472. if report.sensor_degraded:
  473. flags |= int(StatusBits.SENSOR_DEGRADED)
  474. if self._calib_stale:
  475. flags |= int(StatusBits.CALIB_STALE)
  476. # hold_on_stale=True(默认):标定不可信就不给"可执行结果" ——
  477. # state 照常发布(PLC 仍能看到当前判读),但 RESULT_VALID/STABLE 必须为 0,
  478. # 防止 PLC 据此自动落箱。与 C++ `main.cpp` 的落位同一不变量。
  479. if self._calib_hold:
  480. flags &= ~int(StatusBits.RESULT_VALID)
  481. flags &= ~int(StatusBits.STABLE)
  482. flags |= int(extra_flags)
  483. # 安全不变量:PERCEPTION_UNCERTAIN 时绝不能同时给 RESULT_VALID/STABLE,
  484. # 也不能把上一帧置信度带出去。即使 extra_flags 误置也在这里兜底。
  485. if flags & int(StatusBits.PERCEPTION_UNCERTAIN):
  486. flags &= ~int(StatusBits.RESULT_VALID)
  487. flags &= ~int(StatusBits.STABLE)
  488. confidence = 0
  489. else:
  490. confidence = int(published.confidence)
  491. return VisionSnapshot(
  492. state=int(published.state),
  493. confidence=confidence,
  494. flags=flags,
  495. seq=int(decision.seq),
  496. ts_s=int(now),
  497. heartbeat=int(self._heartbeat),
  498. fps_x10=int(round(fps * 10.0)),
  499. latency_ms=int(round(max(0.0, latency_ms))),
  500. reserved=0,
  501. )
  502. def _publish_snapshot(self, snapshot: VisionSnapshot) -> bool:
  503. ok = False
  504. try:
  505. ok = bool(self.publisher.publish(snapshot))
  506. except Exception:
  507. self.stats["errors"] = int(self.stats["errors"]) + 1
  508. LOGGER.exception("发布快照失败")
  509. self._publish_ok = ok
  510. if ok:
  511. self.stats["published"] = int(self.stats["published"]) + 1
  512. else:
  513. self.stats["errors"] = int(self.stats["errors"]) + 1
  514. self._last_snapshot = snapshot
  515. self._last_publish_ts = time.time()
  516. return ok
  517. def _publish(self, frame: Optional[Frame], decision: Decision, latency_ms: float) -> VisionSnapshot:
  518. snapshot = self.build_snapshot(decision, latency_ms)
  519. self._publish_snapshot(snapshot)
  520. return snapshot
  521. def _publish_heartbeat(self, now: float) -> None:
  522. """即使没有新帧/判决,也按 ``plc.heartbeat_ms`` 刷新一次,让 PLC 看到设备存活。"""
  523. if (now - self._last_publish_ts) < self.heartbeat_s:
  524. return
  525. self._heartbeat = (self._heartbeat + 1) & 0xFFFF
  526. self._publish_snapshot(self.build_snapshot(self._last_decision, self._latency_ema))
  527. def _publish_timeout_if_needed(self, now: float) -> None:
  528. """相机/网络断了:V2 保持上一稳定值,并清 STABLE/RESULT_VALID。"""
  529. if self.grabber.fresh:
  530. return
  531. if (now - self._last_publish_ts) < self.heartbeat_s:
  532. return
  533. if not self._timeout_latched:
  534. self._timeout_latched = True
  535. LOGGER.warning(
  536. "超过 %.2fs 未收到新帧 → 保持上一稳定值,清 RESULT_VALID/STABLE(FRAME_TIMEOUT)",
  537. self.grabber.stale_frame_s,
  538. )
  539. timeout_decision = Decision(
  540. state=int(SceneState.UNKNOWN),
  541. confidence=0.0,
  542. stable=False,
  543. seq=int(self.pipeline.voter.seq),
  544. since_ts=now,
  545. reason="frame_timeout",
  546. )
  547. self._last_decision = timeout_decision
  548. self._heartbeat = (self._heartbeat + 1) & 0xFFFF
  549. self._publish_snapshot(
  550. self.build_snapshot(timeout_decision, self._latency_ema, frame_timeout=True)
  551. )
  552. def _idle_sleep(self) -> None:
  553. """没有新帧时的等待:短睡,保证 PLC 指令响应及时。"""
  554. self._stop.wait(0.005)
  555. # ------------------------------------------------------------ 存图/预览
  556. def _save_on_change(self, frame: Frame, observation: Observation, decision: Decision) -> None:
  557. """状态变化时存一张带框的图,用于复盘与挖难例(``run.save_on_change``)。
  558. 画框必须在主线程(要跟当前帧同步,且旧行为是原地画在 ``frame.image`` 上,
  559. 证据链随后用的是同一张图);**JPEG 编码 + 写盘交给 :class:`_SaveWorker`**,
  560. 否则状态刚变化的那一帧会被 ``cv2.imwrite`` 吃掉 3~15 ms。
  561. """
  562. if not self.save_on_change:
  563. return
  564. try:
  565. import cv2 # noqa: F401 延迟导入,无 OpenCV 时静默跳过
  566. except ImportError: # pragma: no cover
  567. return
  568. try:
  569. stamp = time.strftime("%Y-%m-%d_%H%M%S", time.localtime(decision.since_ts or time.time()))
  570. msec = int((decision.since_ts or time.time()) * 1000) % 1000
  571. folder = os.path.join(self.output_dir, time.strftime("%Y-%m-%d", time.localtime()))
  572. os.makedirs(folder, exist_ok=True)
  573. name = "state%d_seq%d_%s_%03d.jpg" % (
  574. int(decision.state),
  575. int(decision.seq),
  576. stamp,
  577. msec,
  578. )
  579. image = self.pipeline.annotate(frame, observation, decision)
  580. path = os.path.join(folder, name)
  581. saver = self._saver
  582. if saver is None:
  583. # 没起后台线程(单测/回放里直接调本方法):退回同步写,行为与旧版一致
  584. cv2.imwrite(path, image)
  585. self._saved += 1
  586. elif saver.submit(image, path):
  587. self._saved += 1
  588. else:
  589. self.stats["saves_dropped"] = int(self.stats["saves_dropped"]) + 1
  590. except Exception: # pragma: no cover - 存图失败不能影响主循环
  591. self.stats["errors"] = int(self.stats["errors"]) + 1
  592. LOGGER.exception("保存状态变化图失败")
  593. def _show_preview(self, frame: Frame, observation: Observation, decision: Decision) -> None:
  594. """本地联调预览窗口(``run.preview``,板子上通常关掉)。"""
  595. try:
  596. import cv2
  597. except ImportError: # pragma: no cover
  598. return
  599. try:
  600. image = self.pipeline.annotate(frame, observation, decision)
  601. cv2.imshow("portcv", image)
  602. cv2.waitKey(1)
  603. except Exception: # pragma: no cover - 无显示环境
  604. self.preview = False
  605. # ------------------------------------------------------------ 状态查询
  606. @property
  607. def last_snapshot(self) -> Optional[VisionSnapshot]:
  608. return self._last_snapshot
  609. @property
  610. def last_decision(self) -> Decision:
  611. return self._last_decision
  612. def status(self) -> Dict[str, object]:
  613. uptime = time.time() - self._start_ts if self._start_ts else 0.0
  614. frames = int(self.stats["frames"])
  615. npu_ratio = model_chain_ratio(getattr(self.pipeline.detector, "stage_ms", None))
  616. payload: Dict[str, object] = {
  617. "uptime_s": round(uptime, 1),
  618. "mode": str(self.cfg.get_path("run.mode", "composed")),
  619. "backend": self.pipeline.detector.name,
  620. "frames": frames,
  621. "published": int(self.stats["published"]),
  622. "changes": int(self.stats["changes"]),
  623. "errors": int(self.stats["errors"]),
  624. "state_counts": dict(self.stats["state_counts"]), # type: ignore[arg-type]
  625. "fps": round(self.grabber.fps, 2),
  626. "latency_ms": round(self._latency_ema, 1),
  627. "heartbeat": int(self._heartbeat),
  628. "saved_images": int(self._saved),
  629. "saves_dropped": int(self.stats["saves_dropped"]),
  630. # 口径 B(模型链)实时占比;口径 A(含解码/等帧/存图)只能由
  631. # scripts/rknpu_ratio.py 出数,别拿这个数去对 70% 的门禁。
  632. "npu_ratio": None if npu_ratio is None else round(npu_ratio, 4),
  633. "npu_ratio_scope": "model_chain",
  634. "gating": self.gating,
  635. "on_demand": bool(self.gating and time.time() < self._on_demand_until),
  636. "decision": self._last_decision.to_dict(),
  637. "health": self._last_health.to_dict(),
  638. "calibration": self._calib_status.to_dict(),
  639. "snapshot": self._last_snapshot.to_dict() if self._last_snapshot else None,
  640. "grabber": self.grabber.describe(),
  641. "publisher": self.publisher.status(),
  642. }
  643. return payload
  644. def status_line(self) -> str:
  645. """单行摘要,便于日志滚动查看。"""
  646. decision = self._last_decision
  647. ratio = model_chain_ratio(getattr(self.pipeline.detector, "stage_ms", None))
  648. # npr = 口径 B(模型链 NPU 占比);mock/edge/evidence-v2 没有 stage_ms,打 n/a 而不是 0%
  649. npr = "n/a" if ratio is None else "%.0f%%" % (ratio * 100.0)
  650. return "state=%d(%s,%.2f) seq=%d fps=%.1f lat=%.0fms npr=%s frames=%d pub=%d chg=%d err=%d" % (
  651. int(decision.state),
  652. decision.label,
  653. decision.confidence,
  654. int(decision.seq),
  655. self.grabber.fps,
  656. self._latency_ema,
  657. npr,
  658. int(self.stats["frames"]),
  659. int(self.stats["published"]),
  660. int(self.stats["changes"]),
  661. int(self.stats["errors"]),
  662. )