runner.py 26 KB

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