| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738 |
- """常驻服务:取帧 → 推理 → 判定 → 发布,并把心跳/指令/统计一并管起来。
- 线程模型
- --------
- * **抓帧线程**::class:`~portcv.io.capture.FrameGrabber` 内部线程,只保留最新帧;
- * **主线程**:本模块的循环,做推理与判定(按 ``run.max_fps`` 限速);
- * **Modbus 线程**:由 :class:`~portcv.plc.modbus_server.ModbusTcpServer` 派生,
- 负责应答 PLC 的读写,并把指令投递给主循环(``take_command``);
- * **存图线程**:仅当 ``run.save_on_change=true`` 时启动,只做 JPEG 编码与写盘。
- 队列满就丢图并计数(``stats.saves_dropped``),**绝不阻塞推理**——1080p 编码
- 实测 3~15 ms,是这条链路上最容易漏算的一笔。
- 因此发布动作是**非阻塞**的:Modbus 模式下写的是内存寄存器块,S7 模式下写入失败
- 只会标记断线并在下个周期重连,不会拖慢节拍。
- 安全语义(重要)
- ----------------
- V2:PLC 结果区的 ``state`` 只写 0/1/2(``255`` 只存在于内部 ``Decision``)。
- 只要出现下列任一情况,都由 :class:`~portcv.service.publish_gate.PublishGate`
- **保持上一稳定值**(无历史则 0),并清掉 ``STABLE`` / ``RESULT_VALID``:
- * 长时间拿不到新帧(``FRAME_TIMEOUT``);
- * 内部状态 255、置信度不足或状态尚未稳定。
- 这样 HMI 仍能看到"视觉认为是 1 但我不敢确认"(state=1、flags=0/0),
- PLC 则以标志位为准——比直接翻成 0/1/2 更安全。
- """
- from __future__ import annotations
- import os
- import queue
- import threading
- import time
- from typing import Any, Dict, Optional, Tuple
- from ..calibration import evaluate as evaluate_calibration
- from ..config import Config
- from ..detect.rknn_backend import model_chain_ratio
- from ..health import FrameHealthMonitor, HealthReport
- from ..io import build_grabber
- from ..io.capture import Frame, FrameGrabber
- from ..logging_utils import get_logger
- from ..plc import PlcPublisher, build_publisher
- from ..schema import Decision, Observation, PlcCommand, SceneState, StatusBits, VisionSnapshot
- from ..storage import EvidenceStore
- from .pipeline import VisionPipeline
- from .publish_gate import PublishGate, PublishResult
- __all__ = ["RunService"]
- LOGGER = get_logger("service")
- class _SaveWorker:
- """状态变化存图的落盘线程:主线程只画框 + 投递,JPEG 编码与写盘在后台。
- 为什么值得单独开一个线程:``cv2.imwrite`` 对 1080p 是 **3~15 ms**(x86 / aarch64),
- 而且它发生在状态刚变化的那一帧——正是 PLC 最在意节拍的时刻。画框必须留在主线程
- (要跟当前帧同步),编码与写盘完全可以异步。
- 队列有界(默认 8):现场磁盘变慢时宁可**丢难例**也不要拖慢推理,
- 丢弃数量记在 :attr:`dropped`,由 ``stats.saves_dropped`` 上报。
- """
- def __init__(self, maxsize: int = 8) -> None:
- self._queue: "queue.Queue[Tuple[Any, str]]" = queue.Queue(maxsize=max(1, int(maxsize)))
- self._stop = threading.Event()
- self._thread: Optional[threading.Thread] = None
- self.saved = 0
- self.dropped = 0
- self.errors = 0
- # ------------------------------------------------------------ 生命周期
- def start(self) -> "_SaveWorker":
- if self._thread is None:
- self._thread = threading.Thread(target=self._loop, name="save-worker", daemon=True)
- self._thread.start()
- return self
- def stop(self, timeout: float = 3.0) -> None:
- """停止并**尽量排空**队列(已入队的图会写完),超时则丢下剩余部分。"""
- self._stop.set()
- thread = self._thread
- if thread is not None:
- thread.join(timeout=timeout)
- self._thread = None
- # ------------------------------------------------------------ 投递
- def submit(self, image: Any, path: str) -> bool:
- """投递一张待写图;队列满返回 ``False``(调用方计数,不要重试)。"""
- try:
- self._queue.put_nowait((image, path))
- return True
- except queue.Full:
- self.dropped += 1
- return False
- # ------------------------------------------------------------ 线程体
- def _loop(self) -> None:
- try:
- import cv2 # 延迟导入:无 OpenCV 时线程直接退出,不影响主链路
- except ImportError: # pragma: no cover
- LOGGER.warning("未安装 opencv-python,存图线程不启动")
- return
- while not self._stop.is_set() or not self._queue.empty():
- try:
- image, path = self._queue.get(timeout=0.2)
- except queue.Empty:
- continue
- try:
- if cv2.imwrite(path, image):
- self.saved += 1
- else:
- self.errors += 1
- except Exception: # pragma: no cover - 磁盘满/权限问题
- self.errors += 1
- LOGGER.exception("后台存图失败:%s", path)
- finally:
- self._queue.task_done()
- class RunService:
- """把流水线、发布器、抓帧器组装成一个可长时间运行的服务。"""
- def __init__(
- self,
- cfg: Config,
- pipeline: Optional[VisionPipeline] = None,
- publisher: Optional[PlcPublisher] = None,
- grabber: Optional[FrameGrabber] = None,
- ) -> None:
- self.cfg = cfg
- self.pipeline = pipeline or VisionPipeline(cfg)
- self.publisher = publisher or build_publisher(cfg)
- self.grabber = grabber or build_grabber(cfg)
- run = cfg.section("run")
- plc = cfg.section("plc")
- self.max_fps = float(run.get("max_fps", 15.0) or 0.0)
- self.save_on_change = bool(run.get("save_on_change", False))
- self.output_dir = str(run.get("output_dir", "runs") or "runs")
- self.preview = bool(run.get("preview", False))
- self.gating = bool(plc.get("gating", False))
- self.gating_timeout_s = max(0.0, float(plc.get("gating_timeout_ms", 800)) / 1000.0)
- self.heartbeat_s = max(0.05, float(plc.get("heartbeat_ms", 500)) / 1000.0)
- self.min_publish_interval_s = max(
- 0.0, float(plc.get("min_publish_interval_ms", 50)) / 1000.0
- )
- self.confidence_scale = int(plc.get("confidence_scale", 1000) or 1000)
- self.min_confidence = float(cfg.get_path("decision.min_confidence", 0.45))
- self.low_fps = float(cfg.get_path("decision.low_fps_threshold", 3.0))
- self.mrc_on_uncertain = bool(cfg.get_path("decision.mrc_on_uncertain", True))
- self.health = FrameHealthMonitor.from_config(cfg)
- self._last_health = HealthReport()
- self._health_logged: Optional[str] = None
- self._calib_status = evaluate_calibration(cfg)
- self._calib_stale = bool(self._calib_status.stale)
- self._calib_hold = bool(getattr(self._calib_status, "hold", True))
- self.evidence = (
- EvidenceStore.from_config(cfg)
- if bool(cfg.get_path("evidence.enabled", False))
- else None
- )
- self._last_purge_ts = 0.0
- self._evidence_commit_latch = False
- # V2:PLC 结果区只写 0/1/2;内部 255/低分/未稳定/超时都由 PublishGate 保持。
- self._publish_gate = PublishGate(self.min_confidence)
- self._stop = threading.Event()
- self._heartbeat = 0
- self._last_frame_id = -1
- self._last_publish_ts = 0.0
- self._last_snapshot: Optional[VisionSnapshot] = None
- self._last_decision = Decision()
- self._last_publish_result: Optional[PublishResult] = None
- self._last_observation: Optional[Observation] = None
- self._on_demand_until = 0.0
- self._min_conf_override = 0
- self._start_ts = 0.0
- self._latency_ema = 0.0
- self._saved = 0
- self._saver: Optional[_SaveWorker] = None
- self._publish_ok = True
- self._timeout_latched = False
- self._reset_publish_pending = False
- self.stats: Dict[str, object] = {
- "frames": 0,
- "published": 0,
- "changes": 0,
- "errors": 0,
- "saves_dropped": 0,
- "state_counts": {},
- }
- # ------------------------------------------------------------ 生命周期
- def start(self) -> "RunService":
- """加载模型 → 预热 → 启动抓帧与发布通道。"""
- LOGGER.info("启动 portcv 服务:backend=%s mode=%s", self.pipeline.detector.name, self.cfg.get_path("run.mode"))
- if self._calib_stale:
- LOGGER.warning(
- "标定不可用(CALIB_STALE):%s;record=%s",
- ",".join(self._calib_status.reasons) or "unknown",
- self._calib_status.path or "(empty)",
- )
- if self._calib_hold:
- LOGGER.warning(
- "标定不可信 → 清 RESULT_VALID/STABLE(calibration.hold_on_stale=true);"
- "PLC 不得据此自动动作。请现场重标 + 复核后重新封存记录。"
- )
- else:
- LOGGER.warning(
- "仅告警(calibration.hold_on_stale=false):是否继续自动运行由 PLC 联锁/现场规程决定。"
- )
- elif self._calib_status.record is not None:
- LOGGER.info(
- "标定记录:%s %s(%s,复核 %s,%.1f 天)",
- self._calib_status.record.site,
- self._calib_status.record.camera_id,
- self._calib_status.record.method,
- self._calib_status.record.reviewer,
- self._calib_status.age_days or 0.0,
- )
- self.pipeline.load()
- warmed = self.pipeline.warmup()
- if warmed:
- LOGGER.info("推理预热完成(%d 帧,%.1f ms/帧)", warmed, self.pipeline.detector.infer_ms)
- self.publisher.start()
- self.grabber.start()
- if self.save_on_change and self._saver is None:
- self._saver = _SaveWorker().start()
- if self.evidence is not None:
- try:
- self.evidence.open()
- self._last_purge_ts = time.time()
- LOGGER.info("证据链已启用:%s", self.evidence.directory)
- except Exception: # pragma: no cover - 磁盘/权限问题不应拖垮服务
- LOGGER.exception("证据链打开失败,已禁用(服务继续运行)")
- self.evidence = None
- self._start_ts = time.time()
- return self
- def stop(self) -> None:
- self._stop.set()
- try:
- self.grabber.stop()
- except Exception: # pragma: no cover
- pass
- if self._saver is not None:
- # 先停抓帧再排空存图队列:已入队的难例会尽量写完,超时就丢
- self._saver.stop()
- self.stats["saves_dropped"] = int(self._saver.dropped)
- LOGGER.info(
- "存图线程已退出:写入 %d 张,丢弃 %d 张,失败 %d 次",
- int(self._saver.saved),
- int(self._saver.dropped),
- int(self._saver.errors),
- )
- self._saver = None
- try:
- self.publisher.stop()
- except Exception: # pragma: no cover
- pass
- if self.evidence is not None:
- try:
- self.evidence.close()
- except Exception: # pragma: no cover
- pass
- self.pipeline.close()
- LOGGER.info("服务已停止:%s", self.status_line())
- # ------------------------------------------------------------ 命令处理
- def handle_command(self) -> Optional[PlcCommand]:
- """处理 PLC 指令;返回本次取到的指令(没有则 ``None``)。"""
- command = self.publisher.take_command()
- if command is None:
- return None
- if int(command.min_conf) > 0:
- self._min_conf_override = int(command.min_conf)
- if command.is_request():
- self._on_demand_until = time.time() + self.gating_timeout_s
- LOGGER.info("PLC 请求识别:按需窗口 %.0f ms", self.gating_timeout_s * 1000)
- elif int(command.cmd) == 2:
- self.pipeline.reset()
- self._publish_gate.reset()
- self._last_decision = Decision()
- self._last_publish_result = None
- self._reset_publish_pending = True
- self._last_frame_id = -1
- self._on_demand_until = 0.0
- self._min_conf_override = 0
- self._evidence_commit_latch = False
- LOGGER.info("PLC 复位:投票窗口、PublishGate 与保持状态已清零")
- elif int(command.cmd) == 3:
- self._start_ts = time.time()
- self.stats["changes"] = 0
- self.stats["errors"] = 0
- self.stats["state_counts"] = {}
- LOGGER.info("PLC 清统计")
- return command
- # ------------------------------------------------------------ 主循环
- def run(
- self,
- max_seconds: Optional[float] = None,
- max_frames: Optional[int] = None,
- log_interval_s: float = 5.0,
- ) -> Dict[str, object]:
- """阻塞运行主循环;``max_seconds`` / ``max_frames`` 只用于自检与测试。"""
- self._stop.clear()
- self.start()
- next_log = time.time() + max(1.0, float(log_interval_s))
- last_frame_start = 0.0
- try:
- while not self._stop.is_set():
- now = time.time()
- if max_seconds is not None and (now - self._start_ts) >= float(max_seconds):
- LOGGER.info("达到 max_seconds=%.1f,正常退出", float(max_seconds))
- break
- if max_frames is not None and int(self.stats["frames"]) >= int(max_frames):
- LOGGER.info("达到 max_frames=%d,正常退出", int(max_frames))
- break
- self.handle_command()
- if self.gating and now >= self._on_demand_until:
- # 按需模式空档期:只刷心跳,不做推理
- self._publish_heartbeat(now)
- self._idle_sleep()
- continue
- frame = self.grabber.latest
- if frame is None or frame.frame_id == self._last_frame_id:
- self._publish_timeout_if_needed(now)
- self._publish_heartbeat(now)
- self._idle_sleep()
- continue
- last_frame_start = time.time()
- self._last_frame_id = frame.frame_id
- self._process(frame)
- self._publish_heartbeat(now)
- if now >= next_log:
- next_log = now + max(1.0, float(log_interval_s))
- LOGGER.info(self.status_line())
- if self.max_fps > 0:
- budget = 1.0 / self.max_fps
- used = time.time() - last_frame_start
- if used < budget:
- self._stop.wait(budget - used)
- except KeyboardInterrupt: # pragma: no cover - 现场 Ctrl+C
- LOGGER.info("收到中断信号,正在退出…")
- finally:
- self.stop()
- return self.stats
- # ------------------------------------------------------------ 单帧处理
- def _process(self, frame: Frame) -> Tuple[Observation, Decision]:
- start = time.perf_counter()
- if self._timeout_latched:
- self._timeout_latched = False
- LOGGER.info("取流已恢复(帧 #%d)", frame.frame_id)
- observation, decision = self.pipeline.step(frame)
- health = self.health.observe(frame.image, frame.ts)
- self._last_health = health
- self._log_health_change(health)
- latency_ms = (time.perf_counter() - start) * 1000.0
- self._latency_ema = (
- latency_ms if self._latency_ema <= 0 else 0.8 * self._latency_ema + 0.2 * latency_ms
- )
- self._last_observation = observation
- self._last_decision = decision
- self.stats["frames"] = int(self.stats["frames"]) + 1
- if decision.changed:
- self.stats["changes"] = int(self.stats["changes"]) + 1
- counts = dict(self.stats["state_counts"]) # type: ignore[arg-type]
- key = str(int(decision.state))
- counts[key] = int(counts.get(key, 0)) + 1
- self.stats["state_counts"] = counts
- LOGGER.info(
- "状态变化 → %d(%s) conf=%.2f seq=%d 原因=%s",
- int(decision.state),
- decision.label,
- decision.confidence,
- int(decision.seq),
- decision.reason,
- )
- self._save_on_change(frame, observation, decision)
- self._publish(frame, decision, latency_ms)
- self._record_evidence(frame, observation, decision)
- if self.preview:
- self._show_preview(frame, observation, decision)
- return observation, decision
- def _record_evidence(
- self, frame: Frame, observation: Observation, decision: Decision
- ) -> None:
- """P0-4:逐帧证据 + 状态变化事件环缓;失败只告警,不影响发布。"""
- if self.evidence is None:
- return
- try:
- evidence_v2 = getattr(self.pipeline, "evidence_v2", None)
- evidence_result = evidence_v2.last if evidence_v2 is not None else None
- committed = bool(getattr(evidence_result, "committed", False))
- event = bool(decision.changed) or (committed and not self._evidence_commit_latch)
- self._evidence_commit_latch = committed
- self.evidence.record(
- frame,
- observation,
- decision,
- snapshot=self._last_snapshot,
- evidence=evidence_result,
- health=self._last_health,
- event=event,
- )
- now = time.time()
- if (now - self._last_purge_ts) >= 3600.0:
- self._last_purge_ts = now
- removed = self.evidence.purge()
- if removed:
- LOGGER.info("证据链清理过期文件 %d 个", len(removed))
- except Exception: # pragma: no cover - 磁盘满/权限问题不影响主链路
- LOGGER.exception("证据落盘失败(本帧跳过)")
- # ------------------------------------------------------------ 自监测
- def _log_health_change(self, health: HealthReport) -> None:
- """健康状态变化时打一条结构化 warning;正常时不刷日志。"""
- key = "%s|%s" % (int(health.sensor_degraded), ",".join(health.reasons))
- if key == self._health_logged:
- return
- self._health_logged = key
- if health.sensor_degraded:
- LOGGER.warning(
- "视觉健康降级:%s(blur=%.1f dark=%.2f bright=%.2f low_tex=%.2f)",
- ",".join(health.reasons) or "degraded",
- health.blur_var,
- health.dark_clip_ratio,
- health.bright_clip_ratio,
- health.low_texture_ratio,
- )
- else:
- LOGGER.info("视觉健康恢复:blur=%.1f low_tex=%.2f", health.blur_var,
- health.low_texture_ratio)
- # ------------------------------------------------------------ 快照发布
- def _effective_min_conf(self) -> float:
- """PLC 覆盖值(千分比)优先;否则用 ``decision.min_confidence``。"""
- if self._min_conf_override > 0:
- scale = float(self.confidence_scale or 1000)
- if scale > 0.0:
- return float(self._min_conf_override) / scale
- return self.min_confidence
- def build_snapshot(
- self,
- decision: Decision,
- latency_ms: float = 0.0,
- extra_flags: int = 0,
- *,
- frame_timeout: Optional[bool] = None,
- reset: bool = False,
- health: Optional[HealthReport] = None,
- ) -> VisionSnapshot:
- """按当前状态组装 :class:`VisionSnapshot`(含所有状态位)。
- V2:发给 PLC 的 ``state`` / ``confidence`` / ``STABLE`` /
- ``RESULT_VALID`` 一律由 :class:`PublishGate` 决定;内部 ``255``
- 不会写进结果区。P0-2/P0-3:健康退化或任何“保持”都置
- ``PERCEPTION_UNCERTAIN``,并按配置请求 ``MRC``。
- """
- now = time.time()
- fps = self.grabber.fps
- fresh = self.grabber.fresh
- timeout = (not fresh) if frame_timeout is None else bool(frame_timeout)
- reset_now = bool(reset or self._reset_publish_pending)
- report = health or self._last_health
- uncertain = bool(report.perception_uncertain) and not reset_now
- published = self._publish_gate.apply(
- decision,
- frame_timeout=timeout,
- reset=reset_now,
- min_conf=self._effective_min_conf(),
- perception_uncertain=uncertain,
- )
- self._last_publish_result = published
- if reset_now:
- self._reset_publish_pending = False
- flags = 0
- if self.pipeline.ready:
- flags |= int(StatusBits.READY)
- if fresh and not timeout:
- flags |= int(StatusBits.FRAME_OK)
- else:
- flags |= int(StatusBits.FRAME_TIMEOUT)
- flags |= int(StatusBits.DATA_LOSS)
- if published.stable:
- flags |= int(StatusBits.STABLE)
- if published.result_valid:
- flags |= int(StatusBits.RESULT_VALID)
- if 0.0 < fps < self.low_fps:
- flags |= int(StatusBits.LOW_FPS)
- if self.gating and now < self._on_demand_until:
- flags |= int(StatusBits.ON_DEMAND)
- if self._publish_ok:
- flags |= int(StatusBits.PUBLISH_OK)
- if published.perception_uncertain:
- flags |= int(StatusBits.PERCEPTION_UNCERTAIN)
- if self.mrc_on_uncertain:
- flags |= int(StatusBits.MRC_REQUEST)
- if report.sensor_degraded:
- flags |= int(StatusBits.SENSOR_DEGRADED)
- if self._calib_stale:
- flags |= int(StatusBits.CALIB_STALE)
- # hold_on_stale=True(默认):标定不可信就不给"可执行结果" ——
- # state 照常发布(PLC 仍能看到当前判读),但 RESULT_VALID/STABLE 必须为 0,
- # 防止 PLC 据此自动落箱。与 C++ `main.cpp` 的落位同一不变量。
- if self._calib_hold:
- flags &= ~int(StatusBits.RESULT_VALID)
- flags &= ~int(StatusBits.STABLE)
- flags |= int(extra_flags)
- # 安全不变量:PERCEPTION_UNCERTAIN 时绝不能同时给 RESULT_VALID/STABLE,
- # 也不能把上一帧置信度带出去。即使 extra_flags 误置也在这里兜底。
- if flags & int(StatusBits.PERCEPTION_UNCERTAIN):
- flags &= ~int(StatusBits.RESULT_VALID)
- flags &= ~int(StatusBits.STABLE)
- confidence = 0
- else:
- confidence = int(published.confidence)
- return VisionSnapshot(
- state=int(published.state),
- confidence=confidence,
- flags=flags,
- seq=int(decision.seq),
- ts_s=int(now),
- heartbeat=int(self._heartbeat),
- fps_x10=int(round(fps * 10.0)),
- latency_ms=int(round(max(0.0, latency_ms))),
- reserved=0,
- )
- def _publish_snapshot(self, snapshot: VisionSnapshot) -> bool:
- ok = False
- try:
- ok = bool(self.publisher.publish(snapshot))
- except Exception:
- self.stats["errors"] = int(self.stats["errors"]) + 1
- LOGGER.exception("发布快照失败")
- self._publish_ok = ok
- if ok:
- self.stats["published"] = int(self.stats["published"]) + 1
- else:
- self.stats["errors"] = int(self.stats["errors"]) + 1
- self._last_snapshot = snapshot
- self._last_publish_ts = time.time()
- return ok
- def _publish(self, frame: Optional[Frame], decision: Decision, latency_ms: float) -> VisionSnapshot:
- snapshot = self.build_snapshot(decision, latency_ms)
- self._publish_snapshot(snapshot)
- return snapshot
- def _publish_heartbeat(self, now: float) -> None:
- """即使没有新帧/判决,也按 ``plc.heartbeat_ms`` 刷新一次,让 PLC 看到设备存活。"""
- if (now - self._last_publish_ts) < self.heartbeat_s:
- return
- self._heartbeat = (self._heartbeat + 1) & 0xFFFF
- self._publish_snapshot(self.build_snapshot(self._last_decision, self._latency_ema))
- def _publish_timeout_if_needed(self, now: float) -> None:
- """相机/网络断了:V2 保持上一稳定值,并清 STABLE/RESULT_VALID。"""
- if self.grabber.fresh:
- return
- if (now - self._last_publish_ts) < self.heartbeat_s:
- return
- if not self._timeout_latched:
- self._timeout_latched = True
- LOGGER.warning(
- "超过 %.2fs 未收到新帧 → 保持上一稳定值,清 RESULT_VALID/STABLE(FRAME_TIMEOUT)",
- self.grabber.stale_frame_s,
- )
- timeout_decision = Decision(
- state=int(SceneState.UNKNOWN),
- confidence=0.0,
- stable=False,
- seq=int(self.pipeline.voter.seq),
- since_ts=now,
- reason="frame_timeout",
- )
- self._last_decision = timeout_decision
- self._heartbeat = (self._heartbeat + 1) & 0xFFFF
- self._publish_snapshot(
- self.build_snapshot(timeout_decision, self._latency_ema, frame_timeout=True)
- )
- def _idle_sleep(self) -> None:
- """没有新帧时的等待:短睡,保证 PLC 指令响应及时。"""
- self._stop.wait(0.005)
- # ------------------------------------------------------------ 存图/预览
- def _save_on_change(self, frame: Frame, observation: Observation, decision: Decision) -> None:
- """状态变化时存一张带框的图,用于复盘与挖难例(``run.save_on_change``)。
- 画框必须在主线程(要跟当前帧同步,且旧行为是原地画在 ``frame.image`` 上,
- 证据链随后用的是同一张图);**JPEG 编码 + 写盘交给 :class:`_SaveWorker`**,
- 否则状态刚变化的那一帧会被 ``cv2.imwrite`` 吃掉 3~15 ms。
- """
- if not self.save_on_change:
- return
- try:
- import cv2 # noqa: F401 延迟导入,无 OpenCV 时静默跳过
- except ImportError: # pragma: no cover
- return
- try:
- stamp = time.strftime("%Y-%m-%d_%H%M%S", time.localtime(decision.since_ts or time.time()))
- msec = int((decision.since_ts or time.time()) * 1000) % 1000
- folder = os.path.join(self.output_dir, time.strftime("%Y-%m-%d", time.localtime()))
- os.makedirs(folder, exist_ok=True)
- name = "state%d_seq%d_%s_%03d.jpg" % (
- int(decision.state),
- int(decision.seq),
- stamp,
- msec,
- )
- image = self.pipeline.annotate(frame, observation, decision)
- path = os.path.join(folder, name)
- saver = self._saver
- if saver is None:
- # 没起后台线程(单测/回放里直接调本方法):退回同步写,行为与旧版一致
- cv2.imwrite(path, image)
- self._saved += 1
- elif saver.submit(image, path):
- self._saved += 1
- else:
- self.stats["saves_dropped"] = int(self.stats["saves_dropped"]) + 1
- except Exception: # pragma: no cover - 存图失败不能影响主循环
- self.stats["errors"] = int(self.stats["errors"]) + 1
- LOGGER.exception("保存状态变化图失败")
- def _show_preview(self, frame: Frame, observation: Observation, decision: Decision) -> None:
- """本地联调预览窗口(``run.preview``,板子上通常关掉)。"""
- try:
- import cv2
- except ImportError: # pragma: no cover
- return
- try:
- image = self.pipeline.annotate(frame, observation, decision)
- cv2.imshow("portcv", image)
- cv2.waitKey(1)
- except Exception: # pragma: no cover - 无显示环境
- self.preview = False
- # ------------------------------------------------------------ 状态查询
- @property
- def last_snapshot(self) -> Optional[VisionSnapshot]:
- return self._last_snapshot
- @property
- def last_decision(self) -> Decision:
- return self._last_decision
- def status(self) -> Dict[str, object]:
- uptime = time.time() - self._start_ts if self._start_ts else 0.0
- frames = int(self.stats["frames"])
- npu_ratio = model_chain_ratio(getattr(self.pipeline.detector, "stage_ms", None))
- payload: Dict[str, object] = {
- "uptime_s": round(uptime, 1),
- "mode": str(self.cfg.get_path("run.mode", "composed")),
- "backend": self.pipeline.detector.name,
- "frames": frames,
- "published": int(self.stats["published"]),
- "changes": int(self.stats["changes"]),
- "errors": int(self.stats["errors"]),
- "state_counts": dict(self.stats["state_counts"]), # type: ignore[arg-type]
- "fps": round(self.grabber.fps, 2),
- "latency_ms": round(self._latency_ema, 1),
- "heartbeat": int(self._heartbeat),
- "saved_images": int(self._saved),
- "saves_dropped": int(self.stats["saves_dropped"]),
- # 口径 B(模型链)实时占比;口径 A(含解码/等帧/存图)只能由
- # scripts/rknpu_ratio.py 出数,别拿这个数去对 70% 的门禁。
- "npu_ratio": None if npu_ratio is None else round(npu_ratio, 4),
- "npu_ratio_scope": "model_chain",
- "gating": self.gating,
- "on_demand": bool(self.gating and time.time() < self._on_demand_until),
- "decision": self._last_decision.to_dict(),
- "health": self._last_health.to_dict(),
- "calibration": self._calib_status.to_dict(),
- "snapshot": self._last_snapshot.to_dict() if self._last_snapshot else None,
- "grabber": self.grabber.describe(),
- "publisher": self.publisher.status(),
- }
- return payload
- def status_line(self) -> str:
- """单行摘要,便于日志滚动查看。"""
- decision = self._last_decision
- ratio = model_chain_ratio(getattr(self.pipeline.detector, "stage_ms", None))
- # npr = 口径 B(模型链 NPU 占比);mock/edge/evidence-v2 没有 stage_ms,打 n/a 而不是 0%
- npr = "n/a" if ratio is None else "%.0f%%" % (ratio * 100.0)
- return "state=%d(%s,%.2f) seq=%d fps=%.1f lat=%.0fms npr=%s frames=%d pub=%d chg=%d err=%d" % (
- int(decision.state),
- decision.label,
- decision.confidence,
- int(decision.seq),
- self.grabber.fps,
- self._latency_ema,
- npr,
- int(self.stats["frames"]),
- int(self.stats["published"]),
- int(self.stats["changes"]),
- int(self.stats["errors"]),
- )
|