Browse Source

feat(portcv): 入库 Python 参考实现、配置体系与依赖清单

为什么改:
工程此前只有本地目录,没有版本基线;本次把可用状态整体入库为 v0.1.0 基线的一层。

改了什么:
- portcv/:采集(V4L2 / RTSP / 图像序列 / 可选 GStreamer)、三套推理后端
  (onnxruntime / tensorrt / rknn,mock 兜底)、几何 + 场景分类 + 时序投票与防抖状态机、
  Modbus/TCP 服务端(FC3/4/6/16)与 snap7 客户端、寄存器与 CRC、
  逐帧 JSONL 与事件视频环缓、标定记录与健康检查、CLI(run/selftest/doctor/bench/registers/probe)
- configs/:default.json、edge-v2-front.json 及现场变体
- pyproject.toml、requirements*.txt:硬依赖仅 numpy + opencv-python,其余按后端可选

验证:
python -m portcv selftest → 5/5 通过(交付目录内复跑同样 5/5)
python -m unittest discover -s tests -q → 229 项 OK(测试文件随后一提交入库)

关联:docs/route_v2.md
Administrator 2 weeks ago
parent
commit
d82ac9a26a
50 changed files with 9579 additions and 0 deletions
  1. 120 0
      configs/README.md
  2. 45 0
      configs/calib/README.md
  3. 235 0
      configs/default.json
  4. 89 0
      configs/edge-cpp.json
  5. 142 0
      configs/edge-v2-front.json
  6. 50 0
      configs/jetson-rtsp.json
  7. 43 0
      configs/rk3588-rtsp.json
  8. 35 0
      portcv/__init__.py
  9. 10 0
      portcv/__main__.py
  10. 230 0
      portcv/calibration.py
  11. 943 0
      portcv/cli.py
  12. 301 0
      portcv/config.py
  13. 95 0
      portcv/detect/__init__.py
  14. 99 0
      portcv/detect/base.py
  15. 84 0
      portcv/detect/mock.py
  16. 87 0
      portcv/detect/onnx_backend.py
  17. 204 0
      portcv/detect/postproc.py
  18. 90 0
      portcv/detect/preproc.py
  19. 105 0
      portcv/detect/rknn_backend.py
  20. 170 0
      portcv/detect/trt_backend.py
  21. 229 0
      portcv/health.py
  22. 20 0
      portcv/io/__init__.py
  23. 268 0
      portcv/io/capture.py
  24. 149 0
      portcv/io/synthetic.py
  25. 85 0
      portcv/logging_utils.py
  26. 29 0
      portcv/logic/__init__.py
  27. 360 0
      portcv/logic/commit.py
  28. 230 0
      portcv/logic/decision.py
  29. 1216 0
      portcv/logic/evidence_v2.py
  30. 124 0
      portcv/logic/geometry.py
  31. 281 0
      portcv/logic/scene.py
  32. 67 0
      portcv/plc/__init__.py
  33. 126 0
      portcv/plc/modbus_pdu.py
  34. 326 0
      portcv/plc/modbus_server.py
  35. 247 0
      portcv/plc/publisher.py
  36. 277 0
      portcv/plc/registers.py
  37. 245 0
      portcv/plc/snap7_client.py
  38. 0 0
      portcv/py.typed
  39. 234 0
      portcv/recognition.py
  40. 452 0
      portcv/schema.py
  41. 13 0
      portcv/service/__init__.py
  42. 150 0
      portcv/service/pipeline.py
  43. 209 0
      portcv/service/publish_gate.py
  44. 624 0
      portcv/service/runner.py
  45. 364 0
      portcv/storage.py
  46. 40 0
      pyproject.toml
  47. 12 0
      requirements-dev.txt
  48. 10 0
      requirements-jetson.txt
  49. 9 0
      requirements-rknn.txt
  50. 6 0
      requirements.txt

+ 120 - 0
configs/README.md

@@ -0,0 +1,120 @@
+# 配置模板
+
+`configs/` 下的文件都是**给现场改的模板**,加载时与 `portcv/config.py` 里的
+`DEFAULTS` 做深合并:只写要覆盖的字段,其余自动取默认值。
+
+| 文件 | 用途 |
+| --- | --- |
+| `default.json` | 全量默认值,**由脚本生成**,用于对照/评审(README 与代码不会漂移) |
+| `jetson-rtsp.json` | Jetson(Orin/Xavier) + RTSP + TensorRT |
+| `rk3588-rtsp.json` | **现场机型(WXD-A576 / 主板 DC-A576 / RK3576)** + RTSP + RKNN(INT8) + 按需识别(gating);**RK3576 单 NPU core → `model.rknn_core` 只能 `auto`** |
+| `edge-cpp.json` | **C++ 版(`portcv_run`)专用**:`run.backend=edge`(二维边缘几何证据,不需要 NPU/OpenCV/模型)+ `edge.*` 参数模板。键名与 Python 同名同义,但 `backend=edge` 只有 C++ 版认识 —— Python 侧请继续用上面的模板 |
+
+现场事实(2026-10-10 确认,直接影响配置):
+
+* 主机**只有 1 个千兆 RJ45** → 相机(RTSP)与 PLC(Modbus/TCP)**必须接同一交换机或可路由**;
+* 相机 = 海康 IPC **固定在车身左前方**(不在吊臂上、画面固定)→ `scene.roi` 按**固定光轴标定一次**;
+* 箱型只有两种:**20 尺(≈6.06 m)与 40 尺(≈12.19 m)标准箱**(2026-10-10 确认;现场口语说成"4 尺 / 8 尺")→ 自标尺按**箱高 2.591 m** 固定、现场不必整定;**40 尺近满车**时判据可能给 `255`,属设计内(见 docs/edge_evidence.md §5 / §12.8);
+* 仅 **1 台相机**(`plc.modbus.holding_addr` 的 `preset` 预留多机位 / 多工位,寄存器布局不变)。
+
+## 改默认值
+
+1. 改 `portcv/config.py` 的 `DEFAULTS`;
+2. 重新生成模板:`python scripts/dump_default_config.py`;
+3. `git diff configs/default.json` 确认差异只在预期字段;
+4. **同步 C++ 侧常量**(生产实现也要一致):`python scripts/gen_cpp_constants.py`
+   并跑一次 `python scripts/gen_cpp_constants.py --check`(CI 拦漂移)。
+
+## 新建现场配置
+
+从最接近的模板复制,只保留需要覆盖的段落即可(JSON 原生支持,无需 pyyaml):
+
+```bash
+cp configs/rk3588-rtsp.json configs/site-A.json
+python scripts/check_configs.py                       # 结构/契约自检(CI 可跑)
+python -m portcv doctor -c configs/site-A.json --deep   # 环境+模型+相机+PLC 自检
+python -m portcv run -c configs/site-A.json
+```
+
+**C++ 版(`portcv_run`)**从 `configs/edge-cpp.json` 复制,改完先核对参数再起服务:
+
+```bash
+cp configs/edge-cpp.json configs/site-cpp.json
+/opt/portcv/bin/portcv_run -c configs/site-cpp.json --check-config   # 打印生效参数;有错会指出键名
+/opt/portcv/bin/portcv_run -c configs/site-cpp.json                  # 起服务(键表见 cpp/README.md §3)
+```
+
+> 注意:配置里的 `_note` 字段是写给人看的注释,程序会原样带在 `cfg.data` 里、不参与逻辑。
+
+## `source.*`(取流,2026-10-10 落地)
+
+同一批键 Python 与 C++ 两侧都读(Python:`portcv/io/capture.py` 的 `FrameGrabber`;
+C++:`cpp/include/portcv/capture.hpp`),默认值与语义一致:
+
+| 键 | 默认 | 说明 |
+| --- | --- | --- |
+| `source.type` | `none` | `none` 不取流 / `synth` 合成帧 / `gst` 自写管线 / `rtsp` / `file` / `usb` |
+| `source.uri` | `""` | 相机地址、文件路径或 GStreamer 管线串;`synth` 时取场景名(`gondola`/`flatbed`/`ground`/`empty`) |
+| `source.width` / `source.height` | `0` | 0 = 用源分辨率 |
+| `source.buffer_size` | `2` | 解码缓冲帧数(越小延迟越低);`0` = 不设上限 |
+| `source.reconnect_s` | `2.0` | 断流后重连间隔(秒) |
+| `source.stale_frame_s` | `0.6` | 超过它没新帧 → `flags.FRAME_TIMEOUT`(bit4)+ 状态 `255` |
+| `source.loop` | `false` | `file` 源读到尾部是否重开(离线复盘循环) |
+| `source.synth_shift_px` / `source.synth_seed` | `0.0` / `20261010` | 合成源专用:制造运动 / 固定 seed 保证逐像素可复现 |
+
+现场注意:
+
+* **C++ 版**用 `rtsp|usb|file|gst` 时必须用 `-DPORTCV_WITH_GSTREAMER=ON` 构建;否则启动即报错(不静默降级);
+* 口令写在 uri 里没有问题(日志与启动摘要都会掩成 `***`),但**配置文件权限要收紧**(`chmod 600`);
+* 没有相机时用 `source.type=synth` 就能把整条链路验完(台架/验收),需要"看真图"时再切 `file` 放视频文件;
+* 改完先 `portcv_run -c <site>.json --check-config`(坏值会指出键名与原因),再重启服务。
+
+## `calibration.*`(P0-5 标定记录)
+
+| 键 | 默认 | 说明 |
+| --- | --- | --- |
+| `calibration.record` | `""` | `configs/calib/*.json`;空 = 不自动判定 |
+| `calibration.stale` | `false` | 手工置 `CALIB_STALE`(覆盖自动判定) |
+| `calibration.max_age_days` | `180` | 超过则 `expired` |
+| `calibration.px_per_m_tolerance` | `0.10` | 与 `evidence_v2.px_per_m` 的相对偏差上限 |
+| `calibration.box_height_tolerance_m` | `0.02` | 与 `evidence_v2.box_height_m` 的绝对偏差上限 |
+
+生成/校验命令与记录格式见 `configs/calib/README.md`、`docs/calibration.md`。
+
+## `evidence.*`(P0-4 证据链,默认关)
+
+| 键 | 默认 | 说明 |
+| --- | --- | --- |
+| `evidence.enabled` | `false` | 打开逐帧 JSONL + 事件视频环缓 |
+| `evidence.dir` | `""` | 空 = `<run.output_dir>/evidence` |
+| `evidence.retention_days` | `90` | 证据保留天数,启动/每小时清理 |
+| `evidence.segment_mb` | `50` | 单个 JSONL 段上限 |
+| `evidence.ring_frames` | `300` | 环缓帧数(15 fps ≈ 20 s;10~30 s 可设 150~450) |
+| `evidence.fps` | `15` | 事件视频帧率 |
+| `evidence.jpeg_quality` | `85` | 环缓 JPEG 质量 |
+| `evidence.max_side` | `960` | 事件视频最长边 |
+
+逐帧 JSONL 按 15 fps 约 **1~2 GB/天**,90 天需 90~170 GB;容量不够时先降采样/
+缩短保留期,不要关事件环缓。恢复演练脚本:`scripts/evidence_drill.py`,详见
+`docs/data_retention.md`。
+
+日志按天轮转由 `run.log_dir`(非空时写 `portcv.log`)与
+`run.log_retention_days`(默认 90)控制。
+
+
+
+| 键 | 默认 | 说明 |
+| --- | --- | --- |
+| `health.enabled` | `true` | 关闭后零开销,不产生 `SENSOR_DEGRADED` |
+| `health.work_width` | `320` | 分析前缩放宽;越小越省算力 |
+| `health.blur_var_min` | `18.0` | Laplacian 方差低于它且低纹理 → 模糊 |
+| `health.dark_clip_ratio_max` | `0.97` | 近黑像素占比上限(欠曝/遮挡) |
+| `health.bright_clip_ratio_max` | `0.55` | 近白像素占比上限(过曝) |
+| `health.low_texture_ratio_max` | `0.88` | 低纹理块占比上限(镜头脏污/遮挡) |
+| `health.degrade_persist_s` | `0.8` | 连续异常多久才报退化(迟滞) |
+| `health.recover_persist_s` | `1.5` | 连续正常多久才恢复(迟滞) |
+
+退化时 `runner` 置 `SENSOR_DEGRADED`(bit10)+ `PERCEPTION_UNCERTAIN`(bit8)
++ `MRC_REQUEST`(bit9),并按 `PublishGate` 清 `RESULT_VALID/STABLE`;阈值需按
+现场雨/雾/夜间光照复核,不得直接照搬。
+

+ 45 - 0
configs/calib/README.md

@@ -0,0 +1,45 @@
+# 标定记录(P0-5)
+
+每台相机、每个机位一份记录,文件名建议 `<站点>-<机位>.json`:
+
+```
+configs/calib/ct01-front.json
+```
+
+**不要手改已封存记录**:`sha256` 覆盖除自身外全部字段,改一个数就校验失败
+(`CALIB_STALE`)。需要改就重新生成并复核。
+
+## 必填/建议字段
+
+| 字段 | 必填 | 说明 |
+| --- | --- | --- |
+| `site` | 是 | 站点/堆场编号 |
+| `camera_id` | 是 | 相机或机位名(front/high/...) |
+| `calibrated_at` | 是 | ISO-8601,带时区,如 `2026-10-26T10:00:00+08:00` |
+| `reviewer` | 建议 | 复核人;为空 → `CALIB_STALE` |
+| `method` | 建议 | `box_vertical_scale` / `fisheye` / `total_station` |
+| `px_per_m` | 建议 | 与运行配置 `evidence_v2.px_per_m` 对照,偏差 >10% → 漂移 |
+| `box_height_m` | 建议 | 与 `evidence_v2.box_height_m` 对照,偏差 >0.02 m → 漂移 |
+| `intrinsics` | 建议 | `fx/fy/cx/cy/dist` |
+| `extrinsics` | 建议 | 安装高度/俯仰/偏航 |
+| `roi` | 可选 | 归一化多边形 |
+| `sha256` | 自动 | 由脚本写入 |
+
+## 生成/校验
+
+```powershell
+# 生成(当前时间,自动 sha256)
+python scripts/calib_record.py create --site CT01 --camera front `
+  --reviewer "张工" --method box_vertical_scale `
+  --px-per-m 115.6 --box-height 2.591 `
+  --out configs/calib/ct01-front.json
+
+# 校验(过期/哈希/复核/漂移;退出码 1 = CALIB_STALE)
+python scripts/calib_record.py check configs/calib/ct01-front.json `
+  --max-age-days 180 --px-per-m 115.6 --box-height 2.591
+```
+
+运行配置里指定记录后,`runner` / `portcv_run` 启动时自动评估;不通过则 flags bit11
+`CALIB_STALE=1`,并在启动日志(以及 `--check-config` 输出)给出原因串。默认
+`calibration.hold_on_stale=true`:标定不可信时同时清 `RESULT_VALID`/`STABLE`。
+详见 `docs/calibration.md`。

+ 235 - 0
configs/default.json

@@ -0,0 +1,235 @@
+{
+  "run": {
+    "mode": "composed",
+    "backend": "mock",
+    "max_fps": 15.0,
+    "warmup_frames": 3,
+    "log_level": "INFO",
+    "log_json": false,
+    "save_on_change": false,
+    "output_dir": "runs",
+    "preview": false,
+    "log_dir": "",
+    "log_retention_days": 90
+  },
+  "evidence": {
+    "enabled": false,
+    "dir": "",
+    "retention_days": 90,
+    "segment_mb": 50,
+    "ring_frames": 300,
+    "fps": 15.0,
+    "jpeg_quality": 85,
+    "max_side": 960
+  },
+  "health": {
+    "enabled": true,
+    "work_width": 320,
+    "blur_var_min": 18.0,
+    "dark_clip_ratio_max": 0.97,
+    "bright_clip_ratio_max": 0.55,
+    "low_texture_ratio_max": 0.88,
+    "degrade_persist_s": 0.8,
+    "recover_persist_s": 1.5
+  },
+  "source": {
+    "type": "file",
+    "uri": "samples/demo.mp4",
+    "width": 0,
+    "height": 0,
+    "buffer_size": 2,
+    "use_gst": false,
+    "reconnect_s": 2.0,
+    "stale_frame_s": 0.6
+  },
+  "model": {
+    "path": "weights/model.onnx",
+    "engine_path": "weights/model.plan",
+    "rknn_path": "weights/model.rknn",
+    "labels": [
+      "container",
+      "bed",
+      "flatbed",
+      "not_on_train"
+    ],
+    "input_size": [
+      640,
+      640
+    ],
+    "input_format": "rgb_float",
+    "conf": 0.35,
+    "iou": 0.5,
+    "max_det": 60,
+    "nms_free": false,
+    "quantized": false,
+    "rknn_core": "auto",
+    "onnx_providers": [
+      "CUDAExecutionProvider",
+      "CPUExecutionProvider"
+    ],
+    "num_threads": 2
+  },
+  "scene": {
+    "mode": "composed",
+    "classes": {
+      "container": [
+        "container",
+        "container_full",
+        "container_empty",
+        "container_20ft",
+        "container_40ft"
+      ],
+      "bed": [
+        "bed",
+        "wagon_bed",
+        "hopper_wagon",
+        "gondola"
+      ],
+      "flatbed": [
+        "flatbed",
+        "flat_wagon",
+        "platform_wagon"
+      ],
+      "ignore": [
+        "person",
+        "people",
+        "crane",
+        "spreader",
+        "truck",
+        "wheel",
+        "rail"
+      ]
+    },
+    "direct_map": {
+      "not_on_train": 0,
+      "bed": 1,
+      "flatbed": 2
+    },
+    "roi": [
+      [
+        0.03,
+        0.1
+      ],
+      [
+        0.97,
+        0.1
+      ],
+      [
+        0.97,
+        0.99
+      ],
+      [
+        0.03,
+        0.99
+      ]
+    ],
+    "require_container": true,
+    "min_class_conf": 0.3,
+    "roi_min_ratio": 0.3,
+    "support_overlap": 0.3,
+    "support_dy_ratio": 0.45,
+    "support_score_ratio": 0.6,
+    "unknown_on_no_detection": true,
+    "no_container_conf": 0.6
+  },
+  "evidence_v2": {
+    "enabled": false,
+    "view": "front",
+    "work_width": 960,
+    "window": [
+      0.24,
+      0.02,
+      0.78,
+      0.95
+    ],
+    "band_min_h": 3,
+    "band_max_h_ratio": 0.15,
+    "bed_search_ratio": 0.4,
+    "box_bottom_max_ratio": 0.78,
+    "below_start_ratio": 0.07,
+    "below_height_ratio": 0.55,
+    "below_min_height_px": 24,
+    "min_door_posts": 5,
+    "max_door_posts": 16,
+    "max_bed_gap_px": 40.0,
+    "flat_max_door_posts": 4,
+    "max_post_spacing_cv": 6.0,
+    "min_post_len_ratio": 0.3,
+    "min_wall_opacity": 0.35,
+    "max_flat_gap_px": 40.0,
+    "wall_edge_density_ref": 0.14,
+    "wall_edge_density_span": 0.04,
+    "ground_block_px": 32,
+    "ground_density_lo": 0.02,
+    "ground_density_hi": 0.35,
+    "min_flat_ground_ratio": 0.4,
+    "min_zero_ground_ratio": 0.65,
+    "deck_min_len_ratio": 0.3,
+    "box_height_m": 2.591,
+    "px_per_m": 0.0,
+    "min_scale_px": 60.0,
+    "motion_diff_max": 12.0,
+    "motion_grad_ratio_min": 0.72,
+    "require_commit": true,
+    "allow_state2": true,
+    "structure_hits_min": 0.6,
+    "commit": {
+      "gap_m_max": 0.1,
+      "gap_px_hard_max": 8.0,
+      "stable_frames": 5,
+      "structure_frames": 5,
+      "min_structure_hits": 0.6,
+      "max_gap_rise_m": 0.01,
+      "allow_state1": true,
+      "allow_state2": true,
+      "require_motion_ok": true,
+      "require_view_known": true,
+      "use_plc_arrival": true
+    }
+  },
+  "decision": {
+    "window": 9,
+    "window_s": 1.0,
+    "min_votes": 4,
+    "min_confidence": 0.45,
+    "min_dwell_s": 0.2,
+    "hold_s": 0.6,
+    "lost_timeout_s": 1.5,
+    "low_fps_threshold": 3.0,
+    "mrc_on_uncertain": true
+  },
+  "calibration": {
+    "stale": false,
+    "record": "",
+    "max_age_days": 180,
+    "px_per_m_tolerance": 0.1,
+    "box_height_tolerance_m": 0.02,
+    "hold_on_stale": true
+  },
+  "plc": {
+    "enabled": true,
+    "push": "modbus_server",
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0,
+      "allow_unit_any": true
+    },
+    "snap7": {
+      "host": "192.168.0.10",
+      "rack": 0,
+      "slot": 1,
+      "db_number": 100,
+      "db_start": 0,
+      "reconnect_s": 3.0,
+      "tcp_port": 102
+    },
+    "gating": false,
+    "gating_timeout_ms": 800,
+    "heartbeat_ms": 500,
+    "confidence_scale": 1000,
+    "min_publish_interval_ms": 50
+  }
+}

+ 89 - 0
configs/edge-cpp.json

@@ -0,0 +1,89 @@
+{
+  "_note": [
+    "现场模板(**C++ 版专用**):二维边缘几何证据后端(docs/edge_evidence.md),不需要 NPU / OpenCV / 模型权重。",
+    "用法:/opt/portcv/bin/portcv_run -c /opt/portcv/configs/edge-cpp.json",
+    "先自检参数:portcv_run -c configs/edge-cpp.json --check-config(只打印生效参数后退出)",
+    "键名与 Python 侧同名同义;本文件的 run.backend=edge 只有 C++ 版认识,Python 侧请继续用 configs/rk3588-rtsp.json。",
+    "edge.* 分两组:§7 表(现场整定用,docs/edge_evidence.md §7)与实现级补充键(§8 采样回来后并入 §7)。",
+    "edge.allow_state2 按 §11 第 10 条:首次上线先置 false(只输出 1 / 0 / 255),验收通过后再改 true。",
+    "plc.modbus.port 要与 PLC 侧 MB_CLIENT 目标端口一致;标准 502 在 Linux 需要特权(见 deploy/README.md)。",
+    "source.* 是取流开关(2026-10-10 落地):type=none 不取流(默认,Frame.gray=nullptr→输出 255 安全值);",
+    "  真机把 type 改成 rtsp|usb|file(或 gst 自写管线)并填 uri,且构建要开 -DPORTCV_WITH_GSTREAMER=ON;",
+    "  没有相机时用 type=synth(uri=gondola|flatbed|ground|empty,零依赖、同 seed 逐像素可复现)。",
+    "  取流层的校验在启动时做:类型不认识/缺 uri/未编译进来 一律报错退出,不静默降级。",
+    "  整定与回归:--dump-frames <jsonl> --dump-dir <dir> 出黄金语料,再用 scripts/replay_check.py 对拍(见 docs/runtime_route_decision.md §4)。"
+  ],
+  "source": {
+    "type": "none",
+    "uri": "",
+    "_comment": "真机示例:type=rtsp + uri=rtsp://user:pass@192.168.1.64:554/Streaming/Channels/101(日志会掩掉口令)"
+  },
+  "run": {
+    "backend": "edge",
+    "max_fps": 15.0,
+    "warmup_frames": 3
+  },
+  "plc": {
+    "enabled": true,
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0,
+      "allow_unit_any": true
+    }
+  },
+  "decision": {
+    "window": 9,
+    "window_s": 1.0,
+    "min_votes": 4,
+    "min_confidence": 0.45,
+    "min_dwell_s": 0.2,
+    "hold_s": 0.6,
+    "lost_timeout_s": 1.5,
+    "low_fps_threshold": 3.0
+  },
+  "calibration": {
+    "_comment": "P0-5 标定记录:填 configs/calib/<站点>-<机位>.json;留空则不做判定。hold_on_stale=true 时标定不可信会清 RESULT_VALID/STABLE(PLC 不得据此自动动作)。",
+    "stale": false,
+    "record": "",
+    "max_age_days": 180,
+    "px_per_m_tolerance": 0.1,
+    "box_height_tolerance_m": 0.02,
+    "hold_on_stale": true
+  },
+  "scene": {
+    "mode": "composed",
+    "roi": [
+      [0.03, 0.1],
+      [0.97, 0.1],
+      [0.97, 0.99],
+      [0.03, 0.99]
+    ]
+  },
+  "edge": {
+    "box_height_m": 2.591,
+    "band_high": [0.55, 0.85],
+    "band_low": [0.0, 0.1],
+    "gap_band": [0.1, 0.45],
+    "cross_ratio": [0.1, 0.35],
+    "line_angle_deg": 8.0,
+    "min_len_track": 0.3,
+    "min_len_cross_px": 20.0,
+    "min_out_ratio": 0.3,
+    "grad_pct": 0.9,
+    "texture_period": [0.03, 0.2],
+    "near_edge_px": 60.0,
+    "motion_hold_s": 1.5,
+    "allow_state2": false,
+    "work_width": 960,
+    "use_clahe": true,
+    "clahe_tiles": 8,
+    "clahe_clip": 3.0,
+    "box_is_on_left": true,
+    "motion_gate": true,
+    "motion_shift_max_px": 6.0,
+    "motion_blur_ratio": 0.75
+  }
+}

+ 142 - 0
configs/edge-v2-front.json

@@ -0,0 +1,142 @@
+{
+  "_note": [
+    "P1b/P1c 前视 v2 模板:箱底以下结构证据 + commit 落位门。",
+    "Python: python -m portcv run -c configs/edge-v2-front.json --no-plc",
+    "C++   : portcv_run -c configs/edge-v2-front.json --backend edge-v2 --no-plc",
+    "source.type=images 是 A/B 回放模板;真机改成 rtsp 并填 uri。",
+    "require_commit=true:commit 不成立时内部输出 255,PublishGate 保持上一稳定值。",
+    "allow_state2=true:平车 2 已打开提交;顶层与 commit 两个开关串联,任一 false 都会回退为只识别、不提交。",
+    "px_per_m=0 表示用箱体竖棱自标尺;现场若已标定可填固定值(A/B 实测约 115.6)。"
+  ],
+  "run": {
+    "mode": "composed",
+    "backend": "evidence-v2",
+    "max_fps": 15.0,
+    "warmup_frames": 3,
+    "log_level": "INFO",
+    "log_json": false,
+    "save_on_change": true,
+    "output_dir": "runs/edge_v2",
+    "preview": false
+  },
+  "health": {
+    "enabled": true,
+    "work_width": 320,
+    "blur_var_min": 18.0,
+    "dark_clip_ratio_max": 0.97,
+    "bright_clip_ratio_max": 0.55,
+    "low_texture_ratio_max": 0.88,
+    "degrade_persist_s": 0.8,
+    "recover_persist_s": 1.5
+  },
+  "source": {
+    "type": "images",
+    "uri": "runs/frames_A1",
+    "width": 0,
+    "height": 0,
+    "buffer_size": 2,
+    "use_gst": false,
+    "reconnect_s": 2.0,
+    "stale_frame_s": 0.6
+  },
+  "calibration": {
+    "_comment": "P0-5 标定记录:填 configs/calib/<站点>-<机位>.json;留空则不做判定(只受 stale 开关控制)。hold_on_stale=true 时标定不可信会清 RESULT_VALID/STABLE。",
+    "stale": false,
+    "record": "",
+    "max_age_days": 180,
+    "px_per_m_tolerance": 0.1,
+    "box_height_tolerance_m": 0.02,
+    "hold_on_stale": true
+  },
+  "scene": {
+    "mode": "composed",
+    "roi": [[0.03, 0.1], [0.97, 0.1], [0.97, 0.99], [0.03, 0.99]]
+  },
+  "evidence_v2": {
+    "enabled": true,
+    "view": "front",
+    "work_width": 960,
+    "window": [0.24, 0.02, 0.78, 0.95],
+    "band_min_h": 3,
+    "band_max_h_ratio": 0.15,
+    "bed_search_ratio": 0.4,
+    "box_bottom_max_ratio": 0.78,
+    "below_start_ratio": 0.07,
+    "below_height_ratio": 0.55,
+    "below_min_height_px": 24,
+    "min_door_posts": 5,
+    "max_door_posts": 16,
+    "max_bed_gap_px": 40.0,
+    "flat_max_door_posts": 4,
+    "max_post_spacing_cv": 6.0,
+    "min_post_len_ratio": 0.3,
+    "min_wall_opacity": 0.35,
+    "wall_edge_density_ref": 0.14,
+    "wall_edge_density_span": 0.04,
+    "ground_block_px": 32,
+    "ground_density_lo": 0.02,
+    "ground_density_hi": 0.35,
+    "min_flat_ground_ratio": 0.4,
+    "min_zero_ground_ratio": 0.65,
+    "deck_min_len_ratio": 0.3,
+    "max_flat_gap_px": 40.0,
+    "box_height_m": 2.591,
+    "px_per_m": 0.0,
+    "min_scale_px": 60.0,
+    "motion_diff_max": 12.0,
+    "motion_grad_ratio_min": 0.72,
+    "require_commit": true,
+    "allow_state2": true,
+    "structure_hits_min": 0.6,
+    "min_bed_roi_px": 90,
+    "reject_hoist_high": true,
+    "hoist_dark_max": 75,
+    "hoist_band_frac": 0.035,
+    "hoist_line_ratio": 0.2,
+    "hoist_dark_ratio": 0.55,
+    "hoist_bright_delta": 12.0,
+    "reject_spreader_contact": true,
+    "spreader_dark_max": 110,
+    "spreader_dark_ratio": 0.55,
+    "commit": {
+      "gap_m_max": 0.1,
+      "gap_px_hard_max": 8.0,
+      "stable_frames": 5,
+      "structure_frames": 5,
+      "min_structure_hits": 0.6,
+      "max_gap_rise_m": 0.01,
+      "allow_state1": true,
+      "allow_state2": true,
+      "require_motion_ok": true,
+      "require_view_known": true,
+      "use_plc_arrival": true
+    }
+  },
+  "decision": {
+    "window": 9,
+    "window_s": 1.0,
+    "min_votes": 4,
+    "min_confidence": 0.45,
+    "min_dwell_s": 0.2,
+    "hold_s": 0.6,
+    "lost_timeout_s": 1.5,
+    "low_fps_threshold": 3.0
+  },
+  "plc": {
+    "enabled": true,
+    "push": "modbus_server",
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0,
+      "allow_unit_any": true
+    },
+    "gating": false,
+    "gating_timeout_ms": 800,
+    "heartbeat_ms": 500,
+    "confidence_scale": 1000,
+    "min_publish_interval_ms": 50
+  }
+}

+ 50 - 0
configs/jetson-rtsp.json

@@ -0,0 +1,50 @@
+{
+  "_note": [
+    "现场模板:Jetson(Orin/Xavier)+ RTSP 相机 + TensorRT 后端。",
+    "用户配置只需要写要覆盖的字段,其余自动取 portcv/config.py 的 DEFAULTS。",
+    "用法:python -m portcv run -c configs/jetson-rtsp.json",
+    "上线前置检查:python -m portcv doctor -c configs/jetson-rtsp.json --deep"
+  ],
+  "run": {
+    "backend": "tensorrt",
+    "max_fps": 25.0,
+    "warmup_frames": 5,
+    "save_on_change": true,
+    "log_json": true
+  },
+  "source": {
+    "type": "rtsp",
+    "uri": "rtsp://admin:passwd@192.168.1.64:554/Streaming/Channels/101",
+    "buffer_size": 1,
+    "reconnect_s": 2.0,
+    "stale_frame_s": 0.6
+  },
+  "model": {
+    "engine_path": "weights/model.plan",
+    "input_size": [640, 640],
+    "input_format": "rgb_float",
+    "conf": 0.35,
+    "nms_free": false,
+    "quantized": false
+  },
+  "plc": {
+    "enabled": true,
+    "push": "modbus_server",
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0
+    },
+    "snap7": {
+      "host": "192.168.0.10",
+      "rack": 0,
+      "slot": 1,
+      "db_number": 100,
+      "db_start": 0
+    },
+    "gating": false,
+    "heartbeat_ms": 500
+  }
+}

+ 43 - 0
configs/rk3588-rtsp.json

@@ -0,0 +1,43 @@
+{
+  "_note": [
+    "现场模板:RK3576(现场主机 WXD-A576 / 主板 DC-A576;RKNN INT8,单 NPU core)+ RTSP 相机,走按需识别(gating)省算力。",
+    "RK3576 单 NPU core → model.rknn_core 只能 auto;INT8 模型由 scripts/onnx_to_rknn.py --target rk3576 在 x86 开发机生成,见 docs/deployment.md §1.3。",
+    "相机 = 海康 IPC 固定在车身左前方(不在吊臂上),画面固定 → scene.roi 按固定光轴标定一次;RTSP 主码流给算法、子码流给监看。",
+    "用法:cp configs/rk3588-rtsp.json configs/site.json && python -m portcv run -c configs/site.json"
+  ],
+  "run": {
+    "backend": "rknn",
+    "max_fps": 15.0,
+    "warmup_frames": 3,
+    "save_on_change": true,
+    "log_json": true
+  },
+  "source": {
+    "type": "rtsp",
+    "uri": "rtsp://admin:passwd@192.168.1.64:554/Streaming/Channels/101",
+    "buffer_size": 2,
+    "reconnect_s": 3.0
+  },
+  "model": {
+    "rknn_path": "weights/model.rknn",
+    "input_size": [640, 640],
+    "input_format": "rgb_uint8",
+    "rknn_core": "auto",
+    "quantized": true,
+    "num_threads": 3
+  },
+  "plc": {
+    "enabled": true,
+    "push": "modbus_server",
+    "modbus": {
+      "host": "0.0.0.0",
+      "port": 1502,
+      "unit_id": 1,
+      "input_addr": 0,
+      "holding_addr": 0
+    },
+    "gating": true,
+    "gating_timeout_ms": 800,
+    "heartbeat_ms": 500
+  }
+}

+ 35 - 0
portcv/__init__.py

@@ -0,0 +1,35 @@
+"""portcv —— 港口车斗/平板车集装箱吊装视觉识别。
+
+对外核心契约(务必固定,PLC 侧按此编码解析)::
+
+    0 = 集装箱不在车上(未识别到集装箱,或集装箱底下不是车斗/平板车)
+    1 = 车斗(带斗车厢)
+    2 = 平板车(无车斗)
+  255 = 视觉未就绪 / 结果不可信(PLC 应保持或回退到安全状态)
+
+主要子模块::
+
+    portcv.schema       公共数据结构(Box / Observation / Decision / VisionSnapshot)
+    portcv.config       配置加载(json 原生,yaml 可选)
+    portcv.detect       YOLO 各推理后端(mock / onnxruntime / rknn / tensorrt)
+    portcv.logic        几何 + 场景判定 + 时序防抖状态机
+    portcv.plc          Modbus/TCP 服务端、S7(snap7) 推送端、寄存器映射
+    portcv.service      主服务循环(取帧 → 推理 → 判定 → 发布)
+    portcv.cli          命令行入口
+"""
+
+from .recognition import ObjectType, RecognitionResult, results_from_observation
+from .schema import Box, Decision, Observation, SceneState, VisionSnapshot
+
+__all__ = [
+    "Box",
+    "Decision",
+    "ObjectType",
+    "Observation",
+    "RecognitionResult",
+    "SceneState",
+    "VisionSnapshot",
+    "results_from_observation",
+]
+
+__version__ = "0.1.0"

+ 10 - 0
portcv/__main__.py

@@ -0,0 +1,10 @@
+"""``python -m portcv`` 入口:直接调用 ``portcv.cli.main``。"""
+
+from __future__ import annotations
+
+import sys
+
+from .cli import main
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 230 - 0
portcv/calibration.py

@@ -0,0 +1,230 @@
+"""P0-5 标定记录:内参/外参/ROI/比例尺/箱高的入库、哈希校验与过期判定。
+
+为什么需要
+----------
+现场一旦换机位、调焦、换镜头或重装支架,所有基于像素的阈值(箱高、间隙、
+门板间距)都会漂移;如果只把标定值散落在配置里,没人能回答“这份结果是用
+哪次标定算的”。本模块把标定做成**可复核的记录**:
+
+* 记录文件 ``configs/calib/<site>.json``,字段含标定人/复核人/日期/方法;
+* ``sha256`` 覆盖除自身外的所有字段,现场改一个数就会校验失败;
+* 超过 ``max_age_days``、无复核人、运行期比例尺/箱高与记录不一致 → ``CALIB_STALE``;
+* 记录的 ``px_per_m`` / ``box_height_m`` 可直接对照 ``evidence_v2.*``,用于漂移检查。
+
+注意:本模块只做“记录与判定”,不自动改配置;发现 ``CALIB_STALE`` 必须现场
+重标并复核,不能靠调阈值掩盖。
+"""
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import hmac
+import json
+import os
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional
+
+from .config import Config
+
+__all__ = [
+    "CalibrationRecord",
+    "CalibrationStatus",
+    "compute_hash",
+    "evaluate",
+    "load_record",
+    "seal",
+    "verify",
+]
+
+_REQUIRED = ("site", "camera_id", "calibrated_at")
+
+
+def _canonical(record: Dict[str, Any]) -> bytes:
+    payload = {key: value for key, value in record.items() if key != "sha256"}
+    return json.dumps(
+        payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str
+    ).encode("utf-8")
+
+
+def compute_hash(record: Dict[str, Any]) -> str:
+    """记录内容的 sha256(不含 ``sha256`` 字段本身)。"""
+
+    return hashlib.sha256(_canonical(record)).hexdigest()
+
+
+def seal(record: Dict[str, Any]) -> Dict[str, Any]:
+    """写入/刷新 ``sha256``,返回同一个 dict。"""
+
+    record = copy.deepcopy(record)
+    record["sha256"] = compute_hash(record)
+    return record
+
+
+def verify(record: Dict[str, Any]) -> bool:
+    expected = str(record.get("sha256", ""))
+    return bool(expected) and hmac.compare_digest(expected, compute_hash(record))
+
+
+def _parse_time(value: object) -> Optional[datetime]:
+    text = str(value or "").strip()
+    if not text:
+        return None
+    if text.endswith("Z"):
+        text = text[:-1] + "+00:00"
+    try:
+        parsed = datetime.fromisoformat(text)
+    except ValueError:
+        return None
+    return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
+
+
+@dataclass
+class CalibrationRecord:
+    site: str
+    camera_id: str
+    calibrated_at: datetime
+    reviewer: str
+    method: str = ""
+    px_per_m: float = 0.0
+    box_height_m: float = 0.0
+    intrinsics: Dict[str, object] = field(default_factory=dict)
+    extrinsics: Dict[str, object] = field(default_factory=dict)
+    roi: List[List[float]] = field(default_factory=list)
+    raw: Dict[str, object] = field(default_factory=dict)
+
+    @classmethod
+    def from_dict(cls, data: Dict[str, Any]) -> "CalibrationRecord":
+        missing = [key for key in _REQUIRED if not str(data.get(key, "")).strip()]
+        if missing:
+            raise ValueError("标定记录缺少字段: %s" % ", ".join(missing))
+        ts = _parse_time(data.get("calibrated_at"))
+        if ts is None:
+            raise ValueError("calibrated_at 不是 ISO-8601 时间: %r" % data.get("calibrated_at"))
+        return cls(
+            site=str(data["site"]),
+            camera_id=str(data["camera_id"]),
+            calibrated_at=ts,
+            reviewer=str(data.get("reviewer", "") or ""),
+            method=str(data.get("method", "")),
+            px_per_m=float(data.get("px_per_m", 0.0) or 0.0),
+            box_height_m=float(data.get("box_height_m", 0.0) or 0.0),
+            intrinsics=dict(data.get("intrinsics") or {}),
+            extrinsics=dict(data.get("extrinsics") or {}),
+            roi=[list(map(float, point)) for point in data.get("roi") or []],
+            raw=dict(data),
+        )
+
+    def to_dict(self) -> Dict[str, object]:
+        return copy.deepcopy(self.raw)
+
+
+@dataclass
+class CalibrationStatus:
+    stale: bool = False
+    reasons: List[str] = field(default_factory=list)
+    age_days: Optional[float] = None
+    hash_ok: bool = False
+    record: Optional[CalibrationRecord] = None
+    path: str = ""
+    # calibration.hold_on_stale:标定不可信时是否清 RESULT_VALID/STABLE(默认 True)。
+    # 与 C++ 侧 `portcv::CalibrationStatus::hold` **同名同义**(cpp/include/portcv/calibration.hpp)。
+    hold: bool = True
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "stale": bool(self.stale),
+            "reasons": list(self.reasons),
+            "age_days": None if self.age_days is None else round(float(self.age_days), 1),
+            "hash_ok": bool(self.hash_ok),
+            "hold": bool(self.hold),
+            "path": self.path,
+            "site": self.record.site if self.record is not None else "",
+            "camera_id": self.record.camera_id if self.record is not None else "",
+            "reviewer": self.record.reviewer if self.record is not None else "",
+            "calibrated_at": (
+                self.record.calibrated_at.isoformat() if self.record is not None else ""
+            ),
+        }
+
+
+def load_record(path: str) -> CalibrationRecord:
+    with open(path, "r", encoding="utf-8") as fh:
+        data = json.load(fh)
+    if not isinstance(data, dict):
+        raise ValueError("标定记录必须是 JSON 对象")
+    return CalibrationRecord.from_dict(data)
+
+
+def evaluate(
+    cfg: Config,
+    *,
+    now: Optional[datetime] = None,
+    record_path: Optional[str] = None,
+) -> CalibrationStatus:
+    """按配置评估标定记录;``calibration.record`` 为空时不做判定(保持兼容)。"""
+
+    override = bool(cfg.get_path("calibration.stale", False))
+    hold = bool(cfg.get_path("calibration.hold_on_stale", True))
+    path = str(
+        cfg.get_path("calibration.record", "") if record_path is None else record_path
+    ).strip()
+    if not path:
+        return CalibrationStatus(
+            stale=override, reasons=["manual_stale"] if override else [], hold=hold
+        )
+
+    status = CalibrationStatus(path=path, hold=hold)
+    if not os.path.isfile(path):
+        status.stale = True
+        status.reasons.append("missing")
+        return status
+
+    now_dt = now or datetime.now(timezone.utc)
+    if now_dt.tzinfo is None:
+        now_dt = now_dt.replace(tzinfo=timezone.utc)
+    try:
+        with open(path, "r", encoding="utf-8") as fh:
+            data = json.load(fh)
+        if not isinstance(data, dict):
+            raise ValueError("not an object")
+        status.hash_ok = verify(data)
+        if not status.hash_ok:
+            status.reasons.append("hash_mismatch")
+        record = CalibrationRecord.from_dict(data)
+        status.record = record
+    except Exception as exc:  # 记录损坏/字段缺失都按 stale 处理
+        status.stale = True
+        status.reasons.append("invalid:%s" % type(exc).__name__)
+        return status
+
+    age_days = (
+        now_dt - record.calibrated_at.astimezone(timezone.utc)
+    ).total_seconds() / 86400.0
+    status.age_days = age_days
+    max_age = float(cfg.get_path("calibration.max_age_days", 180) or 180)
+    if max_age > 0 and age_days > max_age:
+        status.reasons.append("expired")
+    if not record.reviewer.strip():
+        status.reasons.append("unreviewed")
+
+    run_px = float(cfg.get_path("evidence_v2.px_per_m", 0.0) or 0.0)
+    if record.px_per_m > 0 and run_px > 0:
+        tol = max(1e-6, float(cfg.get_path("calibration.px_per_m_tolerance", 0.10) or 0.10))
+        if abs(run_px - record.px_per_m) / record.px_per_m > tol:
+            status.reasons.append("px_per_m_drift")
+    run_box_h = float(cfg.get_path("evidence_v2.box_height_m", 0.0) or 0.0)
+    if record.box_height_m > 0 and run_box_h > 0:
+        tol_m = max(
+            1e-6, float(cfg.get_path("calibration.box_height_tolerance_m", 0.02) or 0.02)
+        )
+        if abs(run_box_h - record.box_height_m) > tol_m:
+            status.reasons.append("box_height_drift")
+
+    if override:
+        status.reasons.append("manual_stale")
+    status.stale = bool(status.reasons)
+    return status
+
+

+ 943 - 0
portcv/cli.py

@@ -0,0 +1,943 @@
+"""命令行入口:``python -m portcv <子命令>``。
+
+子命令一览
+----------
+``run``        常驻服务:取帧 → 推理 → 判定 → 发布(现场部署就用它)
+``selftest``   零硬件端到端自检:合成帧 + mock 模型 + Modbus 回环校验,CI 里也能跑
+``doctor``     环境体检:依赖、模型文件、相机、PLC 端口、平台识别(Jetson/RK)
+``bench``      性能压测:单帧推理耗时与端到端节拍
+``registers``  打印寄存器映射,并可输出 PLC 侧 SCL 片段(给电气/PLC 工程师)
+``probe``      用最小 Modbus/TCP 客户端读(或写)PLC 寄存器,验证联调结果
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import platform
+import socket
+import statistics
+import sys
+import threading
+import time
+from typing import Dict, List, Optional, Sequence, Tuple
+
+from . import __version__
+from .config import Config, load_config
+from .logging_utils import get_logger, setup_logging
+from .plc.modbus_pdu import (
+    EXCEPTION_CODES,
+    FC_READ_HOLDING_REGISTERS,
+    FC_READ_INPUT_REGISTERS,
+    FC_WRITE_MULTIPLE_REGISTERS,
+    FC_WRITE_SINGLE_REGISTER,
+    build_request,
+    parse_mbap,
+    parse_read_response,
+)
+from .plc.registers import (
+    COMMAND_FIELD_NOTES,  # noqa: F401 - 保留旧名字,方便脚本/文档 import
+    SCL_SNIPPET,
+    SNAPSHOT_FIELD_NOTES,  # noqa: F401
+    addresses as modbus_addresses,
+    command_rows,
+    describe as describe_registers,
+    flag_bits,
+    snapshot_rows,
+)
+from .schema import STATE_LABELS, Decision, PlcCommand, SceneState, VisionSnapshot
+
+__all__ = ["main", "build_parser"]
+
+LOGGER = get_logger("cli")
+
+#: 给 PLC 工程师的 SCL 参考代码、寄存器字段说明、地址展开与编解码都在
+#: :mod:`portcv.plc.registers`(唯一事实来源),本模块只做命令行排版。
+
+
+# ---------------------------------------------------------------- 工具函数
+def parse_source(spec: str) -> Dict[str, object]:
+    """把命令行里的 ``type:uri`` 解析成 ``source`` 配置片段。
+
+    支持 ``rtsp://...``、``usb:0``、``file:C:/a.mp4``、``images:./dir``、
+    ``synthetic``(合成帧,无相机自检/演示)以及裸路径/裸序号。
+    """
+
+    text = str(spec).strip()
+    if not text:
+        raise ValueError("source 不能为空")
+    head = text.split(":", 1)[0].lower()
+    if head in ("synthetic", "fake", "demo"):
+        return {"type": "synthetic", "uri": text.split(":", 1)[1] if ":" in text else ""}
+    if ":" in text and text[1:2] != ":" and head in ("file", "rtsp", "usb", "gst", "images"):
+        kind, uri = text.split(":", 1)
+        return {"type": kind.lower(), "uri": uri}
+    if text.lower().startswith("rtsp://"):
+        return {"type": "rtsp", "uri": text}
+    if text.isdigit():
+        return {"type": "usb", "uri": text}
+    if os.path.isdir(text):
+        return {"type": "images", "uri": text}
+    return {"type": "file", "uri": text}
+
+
+def build_config(args: argparse.Namespace) -> Config:
+    """加载配置文件并叠加命令行覆盖项(覆盖优先级:默认值 < 配置文件 < 命令行)。"""
+
+    overrides: Dict[str, object] = {}
+
+    def put(section: str, key: str, value: object) -> None:
+        node = overrides.setdefault(section, {})
+        if isinstance(node, dict):
+            node[key] = value
+
+    if getattr(args, "backend", None):
+        put("run", "backend", args.backend)
+    if getattr(args, "mode", None):
+        put("run", "mode", args.mode)
+        put("scene", "mode", args.mode)
+    if getattr(args, "max_fps", None):
+        put("run", "max_fps", args.max_fps)
+    if getattr(args, "save", False):
+        put("run", "save_on_change", True)
+    if getattr(args, "preview", False):
+        put("run", "preview", True)
+    if getattr(args, "no_plc", False):
+        put("plc", "enabled", False)
+    if getattr(args, "gating", False):
+        put("plc", "gating", True)
+    if getattr(args, "modbus_port", None):
+        put("plc", "modbus", {"port": int(args.modbus_port)})
+    if getattr(args, "source", None):
+        overrides["source"] = dict(parse_source(args.source))
+
+    return load_config(getattr(args, "config", None), overrides)  # type: ignore[arg-type]
+
+
+def free_port(preferred: int = 0) -> int:
+    """挑一个可用端口(自检用,避免和现场已运行的实例撞端口)。"""
+
+    if preferred:
+        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+            try:
+                probe.bind(("127.0.0.1", int(preferred)))
+                return int(preferred)
+            except OSError:
+                pass
+    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+        probe.bind(("127.0.0.1", 0))
+        return int(probe.getsockname()[1])
+
+
+# ---------------------------------------------------------------- 子命令:run
+def cmd_run(args: argparse.Namespace) -> int:
+    from .service import RunService
+
+    cfg = build_config(args)
+    setup_logging(
+        args.log_level or str(cfg.get_path("run.log_level", "INFO")),
+        json_mode=bool(args.json_logs or cfg.get_path("run.log_json", False)),
+        log_dir=str(cfg.get_path("run.log_dir", "") or "") or None,
+        retention_days=int(cfg.get_path("run.log_retention_days", 90) or 90),
+    )
+    LOGGER.info("portcv %s 启动(Python %s, %s)", __version__, platform.python_version(), sys.platform)
+    LOGGER.info(
+        "配置:backend=%s mode=%s source=%s:%s plc=%s",
+        cfg.get_path("run.backend"),
+        cfg.get_path("run.mode"),
+        cfg.get_path("source.type"),
+        cfg.get_path("source.uri"),
+        cfg.get_path("plc.push") if cfg.get_path("plc.enabled") else "off",
+    )
+
+    service = RunService(cfg)
+    try:
+        service.run(max_seconds=args.max_seconds, max_frames=args.max_frames)
+    except KeyboardInterrupt:  # pragma: no cover - 现场 Ctrl+C
+        service.stop()
+    if args.report:
+        print(json.dumps(service.status(), ensure_ascii=False, indent=2, default=str))
+    return 0
+
+
+# ------------------------------------------------- 最小 Modbus/TCP 客户端工具
+def _modbus_request(
+    host: str,
+    port: int,
+    frame: bytes,
+    unit_id: int,
+    timeout: float = 2.0,
+) -> bytes:
+    """发一个请求帧并读回响应 PDU(自带 MBAP 长度切分)。"""
+
+    with socket.create_connection((host, int(port)), timeout=timeout) as sock:
+        sock.settimeout(timeout)
+        sock.sendall(frame)
+        header = b""
+        while len(header) < 7:
+            chunk = sock.recv(7 - len(header))
+            if not chunk:
+                raise RuntimeError("连接被对端关闭(无响应)")
+            header += chunk
+        length = int.from_bytes(header[4:6], "big")
+        body = b""
+        while len(body) < max(0, length - 1):
+            chunk = sock.recv(length - 1 - len(body))
+            if not chunk:
+                raise RuntimeError("响应不完整")
+            body += chunk
+    _tx, _proto, _len, _unit, pdu = parse_mbap(header + body)
+    return pdu
+
+
+def modbus_read(
+    host: str,
+    port: int,
+    address: int,
+    quantity: int,
+    unit_id: int = 1,
+    timeout: float = 2.0,
+    function: int = FC_READ_INPUT_REGISTERS,
+) -> List[int]:
+    """读寄存器。``function`` 支持 ``3``(保持寄存器)与 ``4``(输入寄存器)。"""
+
+    request = build_request(0x0001, unit_id, int(function), address, quantity=quantity)
+    pdu = _modbus_request(host, port, request, unit_id, timeout)
+    return parse_read_response(pdu)
+
+
+def modbus_write_single(
+    host: str,
+    port: int,
+    address: int,
+    value: int,
+    unit_id: int = 1,
+    timeout: float = 2.0,
+) -> int:
+    """写单个保持寄存器(FC6),返回写入值。"""
+
+    request = build_request(0x0002, unit_id, FC_WRITE_SINGLE_REGISTER, address, single_value=value)
+    pdu = _modbus_request(host, port, request, unit_id, timeout)
+    if pdu and (pdu[0] & 0x80):
+        code = pdu[1] if len(pdu) > 1 else 0
+        raise RuntimeError("Modbus 异常响应: 0x%02X %s" % (code, EXCEPTION_CODES.get(code, "未知")))
+    return int(value)
+
+
+def modbus_write_multiple(
+    host: str,
+    port: int,
+    address: int,
+    values: Sequence[int],
+    unit_id: int = 1,
+    timeout: float = 2.0,
+) -> List[int]:
+    """写多个保持寄存器(FC16),返回写入值列表。"""
+
+    request = build_request(
+        0x0003, unit_id, FC_WRITE_MULTIPLE_REGISTERS, address, values=list(values)
+    )
+    pdu = _modbus_request(host, port, request, unit_id, timeout)
+    if pdu and (pdu[0] & 0x80):
+        code = pdu[1] if len(pdu) > 1 else 0
+        raise RuntimeError("Modbus 异常响应: 0x%02X %s" % (code, EXCEPTION_CODES.get(code, "未知")))
+    return [int(v) for v in values]
+
+
+# ------------------------------------------------------------ 子命令:selftest
+def cmd_selftest(args: argparse.Namespace) -> int:
+    """零硬件自检:合成帧 + mock 检测器走通『检测 → 判定 → 寄存器 → Modbus 回环』。"""
+
+    import numpy as np
+
+    from .detect.mock import MockDetector, build_demo_script
+    from .io.capture import Frame
+    from .io.synthetic import SyntheticGrabber
+    from .service import RunService, VisionPipeline
+
+    cfg = load_config(
+        args.config,
+        {
+            "run": {"backend": "mock", "max_fps": 0.0, "warmup_frames": 1, "save_on_change": False},
+            "plc": {"enabled": False},
+        },
+    )
+    if args.mode:
+        cfg.data["run"]["mode"] = args.mode
+        cfg.data["scene"]["mode"] = args.mode
+    setup_logging(args.log_level or "WARNING")
+
+    failures: List[str] = []
+    notes: List[str] = []
+
+    # --- 阶段 1:确定性流水线(每个场景保持若干帧,模拟真实视频) -----------------
+    # 每个剧本场景保持 SCRIPT_HOLD 帧;末尾再补 EMPTY_TAIL 帧空场景。
+    # 空场景的观测是 UNKNOWN(unknown_on_no_detection=true)→ 投票器会先“保持”上一状态,
+    # 超过 lost_timeout_s(默认 1.5s ≈ 45 帧@30fps) 才回落 UNKNOWN,所以尾巴要给够帧数。
+    script_hold = 20
+    empty_tail = 90
+    script = [item for item in build_demo_script() for _ in range(script_hold)]
+    script += [[] for _ in range(empty_tail)]
+    detector = MockDetector(cfg, script=script)
+    pipeline = VisionPipeline(cfg, detector=detector)
+    pipeline.load()
+
+    image = np.zeros((720, 1280, 3), dtype=np.uint8)
+    dt = 1.0 / 30.0
+    ts = time.time()
+    seen: List[int] = []
+    holds = 0  # 空场景期间“保持上一状态但 stable=False”的帧数
+    for index in range(len(script)):
+        ts += dt
+        _obs, decision = pipeline.step(Frame(image=image, ts=ts, frame_id=index + 1))
+        if not seen or seen[-1] != int(decision.state):
+            seen.append(int(decision.state))
+        if index >= script_hold * 3 and int(decision.state) == int(SceneState.NOT_ON_TRAIN) and not decision.stable:
+            holds += 1
+
+    for expect in (int(SceneState.BED), int(SceneState.FLATBED), int(SceneState.NOT_ON_TRAIN), int(SceneState.UNKNOWN)):
+        if expect not in seen:
+            failures.append(
+                "阶段 1:未产生状态 %d(%s),实际序列 %s"
+                % (expect, STATE_LABELS.get(expect, "?"), seen)
+            )
+    try:
+        idx1 = seen.index(int(SceneState.BED))
+        idx2 = seen.index(int(SceneState.FLATBED))
+        idx0 = seen.index(int(SceneState.NOT_ON_TRAIN))
+        idx255 = len(seen) - 1 - seen[::-1].index(int(SceneState.UNKNOWN))
+        ordered = idx1 < idx2 < idx0 < idx255
+    except ValueError:
+        ordered = False
+    if not ordered:
+        failures.append(
+            "阶段 1:状态先后顺序不符合预期(允许初始 255;应为 车斗→平板车→不在车上→UNKNOWN),实际 %s"
+            % seen
+        )
+    if holds <= 0:
+        failures.append("阶段 1:空场景期间没有出现“保持上一状态 + stable=False”的过渡帧")
+    notes.append(
+        "阶段 1 状态序列 %s(%d 帧,其中“保持但未稳定”%d 帧)"
+        % (" → ".join(str(s) for s in seen), len(script), holds)
+    )
+
+    # --- 阶段 2:完整服务 + Modbus 通道 ----------------------------------------
+    port = free_port(int(args.modbus_port or 1502))
+    cfg.data["plc"] = {
+        "enabled": True,
+        "push": "modbus_server",
+        "modbus": {"host": "127.0.0.1", "port": port, "unit_id": 1, "allow_unit_any": True},
+        "heartbeat_ms": 100,
+        "min_publish_interval_ms": 0,
+        "confidence_scale": 1000,
+    }
+    cfg.data["run"].update({"max_fps": 20.0, "warmup_frames": 1})
+    service = RunService(cfg, grabber=SyntheticGrabber(fps=20.0, size=(1280, 720)))
+    service.gating = False
+    stats = service.stats
+    # 服务跑在后台线程里,"主线程"扮演 PLC:先等它产出结果,再经 TCP 回读寄存器
+    runner = threading.Thread(
+        target=service.run,
+        kwargs={"max_seconds": 60.0, "max_frames": 1000000, "log_interval_s": 600.0},
+        name="portcv-selftest",
+        daemon=True,
+    )
+    runner.start()
+    deadline = time.time() + 10.0
+    while time.time() < deadline:
+        if int(stats["frames"]) >= 10 and service.last_snapshot is not None:
+            break
+        time.sleep(0.05)
+    if int(stats["frames"]) < 10:
+        failures.append("阶段 2:处理帧数过少(%s),主循环可能没跑起来" % stats["frames"])
+    if int(stats["published"]) <= 0:
+        failures.append("阶段 2:未发布任何快照")
+    snapshot = service.last_snapshot
+    if snapshot is None:
+        failures.append("阶段 2:没有快照产生")
+    else:
+        notes.append(
+            "阶段 2 最后快照 state=%d conf=%d flags=0x%04X heartbeat=%d latency=%dms"
+            % (
+                int(snapshot.state),
+                int(snapshot.confidence),
+                int(snapshot.flags),
+                int(snapshot.heartbeat),
+                int(snapshot.latency_ms),
+            )
+        )
+
+    # --- 阶段 3:真的经 TCP 读一次输入寄存器,校验 CRC --------------------------
+    try:
+        words = modbus_read("127.0.0.1", port, 0, VisionSnapshot.register_count(), timeout=2.0)
+        restored = VisionSnapshot.from_registers(words, verify=True)
+        if int(restored.state) not in (0, 1, 2, 255):
+            failures.append("阶段 3:寄存器里的状态码非法:%d" % int(restored.state))
+        else:
+            notes.append(
+                "阶段 3 Modbus 回读 CRC 校验通过:state=%d seq=%d flags=0x%04X"
+                % (int(restored.state), int(restored.seq), int(restored.flags))
+            )
+    except Exception as exc:  # noqa: BLE001 - 自检要把任何异常都变成可读结论
+        failures.append("阶段 3:Modbus 回读失败:%s" % exc)
+
+    # --- 阶段 4:写保持寄存器(PLC → 视觉指令) --------------------------------
+    try:
+        modbus_write_single("127.0.0.1", port, 0, 1, timeout=2.0)
+        holdings = modbus_read(
+            "127.0.0.1",
+            port,
+            0,
+            PlcCommand.register_count(),
+            timeout=2.0,
+            function=FC_READ_HOLDING_REGISTERS,
+        )
+        command = PlcCommand.from_registers(holdings)
+        if not command.is_request():
+            failures.append("阶段 4:写入的识别请求未生效(holding=%s)" % holdings)
+        else:
+            notes.append("阶段 4 PLC 指令回读正常:cmd=%d" % int(command.cmd))
+    except Exception as exc:  # noqa: BLE001
+        failures.append("阶段 4:写保持寄存器失败:%s" % exc)
+
+    # 收尾:停掉后台服务线程,避免自检结束后仍有线程/端口残留
+    service.stop()
+    runner.join(timeout=5.0)
+    if runner.is_alive():
+        failures.append("阶段 2:服务线程未能在 5s 内退出")
+    if int(stats["published"]) > 0:
+        notes.append("阶段 2 已发布 %d 帧快照(frames=%d)" % (int(stats["published"]), int(stats["frames"])))
+
+    print("portcv selftest(离线自检,不依赖相机/PLC)")
+    for note in notes:
+        print("  [OK]   %s" % note)
+    for item in failures:
+        print("  [FAIL] %s" % item)
+    print(
+        "结果:%s(%d 项通过,%d 项失败)"
+        % ("通过" if not failures else "失败", len(notes), len(failures))
+    )
+    return 0 if not failures else 1
+
+
+# ------------------------------------------------------------- 子命令:doctor
+def _module_available(name: str) -> bool:
+    """判断模块是否可导入(不真的导入,避免加载慢/副作用)。"""
+
+    import importlib.util
+
+    try:
+        return importlib.util.find_spec(name) is not None
+    except (ImportError, ValueError):  # pragma: no cover - 安装损坏
+        return False
+
+
+def _platform_summary() -> str:
+    """识别 Jetson / Rockchip 等目标平台,便于现场确认板型。"""
+
+    hints: List[str] = []
+    try:
+        if os.path.exists("/etc/nv_tegra_release"):
+            hints.append("Jetson(L4T)")
+        for dev in ("/proc/device-tree/compatible", "/proc/device-tree/model"):
+            if not os.path.exists(dev):
+                continue
+            with open(dev, "rb") as fh:
+                text = fh.read(200).decode("utf-8", "ignore").split("\x00")[0].strip()
+            lowered = text.lower()
+            if not text:
+                continue
+            if "rockchip" in lowered or "rk3" in lowered:
+                hints.append("Rockchip(%s)" % text[:48])
+            elif "nvidia" in lowered or "jetson" in lowered:
+                hints.append("Jetson(%s)" % text[:48])
+    except OSError:  # pragma: no cover
+        pass
+    suffix = " / " + ", ".join(hints) if hints else ""
+    return "%s %s%s" % (platform.system(), platform.machine(), suffix)
+
+
+def _backend_requirement(cfg: Config) -> Tuple[str, str, str]:
+    """返回 ``(后端名, 必需依赖, 模型文件路径)``。"""
+
+    backend = str(cfg.get_path("run.backend", "mock")).lower()
+    if backend == "onnx":
+        return "onnx", "onnxruntime", str(cfg.get_path("model.path", "") or "")
+    if backend == "rknn":
+        return "rknn", "rknnlite", str(cfg.get_path("model.rknn_path", "") or "")
+    if backend in ("tensorrt", "trt", "plan"):
+        return "tensorrt", "tensorrt", str(cfg.get_path("model.engine_path", "") or "")
+    return "mock", "", ""
+
+
+def _tcp_reachable(host: str, port: int, timeout: float = 1.0) -> bool:
+    if not host:
+        return False
+    try:
+        socket.create_connection((host, int(port)), timeout=timeout).close()
+        return True
+    except OSError:
+        return False
+
+
+def _print_rows(rows: Sequence[Tuple[str, str, str]]) -> None:
+    width = max([len(name) for name, _status, _detail in rows] or [8])
+    print("portcv doctor")
+    for name, status, detail in rows:
+        mark = {"OK": " OK ", "WARN": "WARN", "FAIL": "FAIL"}.get(status, status)
+        print("  [%s] %-*s  %s" % (mark, width, name, detail))
+
+
+def cmd_doctor(args: argparse.Namespace) -> int:
+    """环境体检:依赖、模型、相机、PLC 端口、目标平台。"""
+
+    rows: List[Tuple[str, str, str]] = []
+
+    def add(name: str, status: str, detail: str) -> None:
+        rows.append((name, status, detail))
+
+    add("Python", "OK" if sys.version_info >= (3, 8) else "FAIL", "%d.%d.%d" % sys.version_info[:3])
+    add("平台", "OK", _platform_summary())
+
+    for module, note in (
+        ("numpy", "数值计算(必需)"),
+        ("cv2", "opencv-python:解码/预览/存图(必需)"),
+        ("onnxruntime", "onnx 后端"),
+        ("rknnlite", "RK3588/RK3568 NPU 后端"),
+        ("tensorrt", "Jetson 高性能后端"),
+        ("pycuda", "TensorRT 零拷贝内存(可选)"),
+        ("snap7", "S7 推送(不装也能跑 Modbus 模式)"),
+        ("yaml", "支持 .yaml 配置文件(可选)"),
+    ):
+        exists = _module_available(module)
+        add("依赖 %s" % module, "OK" if exists else "WARN", note if exists else "未安装:%s" % note)
+
+    try:
+        cfg = build_config(args)
+    except Exception as exc:  # noqa: BLE001 - 配置错就是最该先修的问题
+        add("配置", "FAIL", str(exc))
+        _print_rows(rows)
+        return 1
+    add(
+        "配置",
+        "OK",
+        "backend=%s mode=%s plc=%s"
+        % (
+            cfg.get_path("run.backend"),
+            cfg.get_path("run.mode"),
+            cfg.get_path("plc.push") if cfg.get_path("plc.enabled") else "off",
+        ),
+    )
+
+    backend, module, model_path = _backend_requirement(cfg)
+    if backend == "mock":
+        add("推理后端", "OK", "mock(无需模型,用于联调/自检)")
+    else:
+        add("推理后端 %s" % backend, "OK" if _module_available(module) else "FAIL", "依赖包 %s" % module)
+        if model_path:
+            exists = os.path.isfile(model_path)
+            add("模型文件", "OK" if exists else "FAIL", model_path if exists else "%s 不存在" % model_path)
+        else:
+            add("模型文件", "FAIL", "配置里未指定模型路径")
+
+    output_dir = str(cfg.get_path("run.output_dir", "runs") or "runs")
+    try:
+        os.makedirs(output_dir, exist_ok=True)
+        probe_path = os.path.join(output_dir, ".portcv_write_test")
+        with open(probe_path, "w", encoding="utf-8") as fh:
+            fh.write("ok")
+        os.remove(probe_path)
+        add("输出目录", "OK", os.path.abspath(output_dir))
+    except OSError as exc:
+        add("输出目录", "FAIL", "%s(%s)" % (output_dir, exc))
+
+    if bool(cfg.get_path("plc.enabled", False)):
+        mode = str(cfg.get_path("plc.push", "modbus_server")).lower()
+        if mode in ("modbus_server", "modbus", "both"):
+            host = str(cfg.get_path("plc.modbus.host", "0.0.0.0"))
+            port = int(cfg.get_path("plc.modbus.port", 1502))
+            try:
+                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+                    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+                    sock.bind((host, port))
+                detail = "%s:%d 可绑定" % (host, port)
+                if port < 1024 and os.name != "nt":
+                    detail += "(<1024 需 root,现场建议 1502 等高端口)"
+                add("Modbus 端口", "OK", detail)
+            except OSError as exc:
+                add("Modbus 端口", "FAIL", "%s:%d 无法绑定:%s" % (host, port, exc))
+        if mode in ("snap7", "s7", "both"):
+            host = str(cfg.get_path("plc.snap7.host", ""))
+            port = int(cfg.get_path("plc.snap7.tcp_port", 102))
+            reachable = _tcp_reachable(host, port, timeout=1.0)
+            add(
+                "S7 连通性",
+                "OK" if reachable else "WARN",
+                "%s:%d %s" % (host, port, "可连接" if reachable else "暂时连不上(检查网线/机架槽号)"),
+            )
+    else:
+        add("PLC 通道", "WARN", "plc.enabled=false,当前只做本地判定")
+
+    if args.deep:
+        try:
+            from .io.capture import FrameGrabber
+
+            grabber = FrameGrabber(cfg)
+            grabber.start()
+            frame = grabber.read(timeout=3.0)
+            if frame is None:
+                add("视频源", "FAIL", "3s 内没有取到帧:%s:%s" % (cfg.get_path("source.type"), cfg.get_path("source.uri")))
+            else:
+                add(
+                    "视频源",
+                    "OK",
+                    "%s:%s → %dx%d fps=%.1f frame_id=%s"
+                    % (
+                        cfg.get_path("source.type"),
+                        cfg.get_path("source.uri"),
+                        frame.image.shape[1],
+                        frame.image.shape[0],
+                        grabber.fps,
+                        frame.frame_id,
+                    ),
+                )
+            grabber.stop()
+        except Exception as exc:  # noqa: BLE001
+            add("视频源", "FAIL", str(exc))
+
+    _print_rows(rows)
+    failed = [row for row in rows if row[1] == "FAIL"]
+    print("\n结论:%s" % ("可以上机运行" if not failed else "有 %d 项必须先修" % len(failed)))
+    return 0 if not failed else 1
+
+
+# -------------------------------------------------------------- 子命令:bench
+def _latency_stats(values: Sequence[float]) -> Dict[str, float]:
+    """返回 mean/p50/p95/max 与等效帧率(毫秒输入)。"""
+
+    ordered = sorted(float(v) for v in values)
+    count = len(ordered)
+    mean = statistics.fmean(ordered) if count else 0.0
+    return {
+        "mean": mean,
+        "p50": ordered[count // 2] if count else 0.0,
+        "p95": ordered[min(count - 1, int(round(0.95 * (count - 1))))] if count else 0.0,
+        "max": ordered[-1] if count else 0.0,
+        "fps": (1000.0 / mean) if mean > 0 else 0.0,
+    }
+
+
+def cmd_bench(args: argparse.Namespace) -> int:
+    """压测纯推理耗时与整链节拍(先在 PC 上用 mock 跑,板上换 --backend 即可对比)。"""
+
+    import numpy as np
+
+    from .io.capture import Frame
+    from .service import VisionPipeline
+
+    cfg = build_config(args)
+    setup_logging(args.log_level or "WARNING")
+    pipeline = VisionPipeline(cfg)
+    pipeline.load()
+    pipeline.warmup(2)
+
+    width = int(args.width)
+    height = int(args.height)
+    count = max(5, int(args.frames))
+    rng = np.random.default_rng(20240501)
+    image = rng.integers(0, 255, (height, width, 3)).astype(np.uint8)
+
+    infer_ms: List[float] = []
+    for _ in range(count):
+        pipeline.detector.timed_infer(image)  # 纯推理:不含判定/投票
+        infer_ms.append(float(pipeline.detector.infer_ms))
+
+    full_ms: List[float] = []
+    ts = time.time()
+    for index in range(count):
+        ts += 1.0 / 30.0
+        start = time.perf_counter()
+        pipeline.step(Frame(image=image, ts=ts, frame_id=index + 1))
+        full_ms.append((time.perf_counter() - start) * 1000.0)
+
+    infer = _latency_stats(infer_ms)
+    full = _latency_stats(full_ms)
+    print(
+        "portcv bench(backend=%s mode=%s,%d 帧,%dx%d)"
+        % (pipeline.detector.name, pipeline.classifier.mode, count, width, height)
+    )
+    for label, item in (("纯推理", infer), ("整链 推理+判定+防抖", full)):
+        print(
+            "  %-20s mean=%7.2fms p50=%7.2fms p95=%7.2fms max=%7.2fms → %5.1f fps"
+            % (label, item["mean"], item["p50"], item["p95"], item["max"], item["fps"])
+        )
+
+    target = float(args.target_fps or 0.0)
+    if target > 0:
+        if full["fps"] >= target:
+            print("  目标 %.0f fps:达标(余量 %.0f%%)" % (target, (full["fps"] / target - 1.0) * 100.0))
+        else:
+            print(
+                "  目标 %.0f fps:未达标 → 降低输入分辨率/换 TensorRT(RKNN) 后端/开 FP16 或 INT8"
+                % target
+            )
+    if args.json:
+        print(
+            json.dumps(
+                {"backend": pipeline.detector.name, "mode": pipeline.classifier.mode, "infer": infer, "full": full},
+                ensure_ascii=False,
+            )
+        )
+    pipeline.close()
+    return 0
+
+
+# ---------------------------------------------------------- 子命令:registers
+#: 字段说明与地址展开的唯一事实来源在 :mod:`portcv.plc.registers`。
+
+
+def cmd_registers(args: argparse.Namespace) -> int:
+    """打印寄存器映射(现场联调时把这张表给 PLC 侧即可)。
+
+    布局表来自 :mod:`portcv.plc.registers`,这里只负责排版与 SCL 片段输出。
+    """
+
+    cfg = load_config(args.config)
+    info = modbus_addresses(cfg)
+    unit_id = int(info["unit_id"])
+    input_addr = int(info["input_addr"])
+    holding_addr = int(info["holding_addr"])
+
+    if args.json:
+        payload = describe_registers(input_addr, holding_addr, unit_id)
+        payload["listen"] = "%s:%d" % (info["host"], info["port"])
+        print(json.dumps(payload, ensure_ascii=False, indent=2))
+        return 0
+
+    print(
+        "portcv 寄存器映射(Modbus/TCP,unit_id=%d,监听 %s:%d)"
+        % (unit_id, info["host"], info["port"])
+    )
+    print(
+        "\n[输入寄存器] PLC 用 FC4 读,起始地址 %d,共 %d 个字(视觉 → PLC)"
+        % (input_addr, int(info["input_count"]))
+    )
+    for address, field, width, note in snapshot_rows(input_addr):
+        print("  %4d  %-12s %d字   %s" % (address, field, width, note))
+    print(
+        "\n[保持寄存器] PLC 用 FC3 读 / FC6·FC16 写,起始地址 %d,共 %d 个字(PLC → 视觉)"
+        % (holding_addr, int(info["holding_count"]))
+    )
+    for address, field, width, note in command_rows(holding_addr):
+        print("  %4d  %-12s %d字   %s" % (address, field, width, note))
+    print("\n[flags 位定义]")
+    for name, mask, note in flag_bits():
+        print("  bit%-2d %-14s 0x%04X  %s" % (mask.bit_length() - 1, name, mask, note))
+    if args.scl:
+        print("\n[PLC 侧 SCL 参考代码]\n")
+        print(SCL_SNIPPET)
+    else:
+        print("\n提示:加 --scl 输出西门子 SCL 片段,加 --json 输出机器可读的映射。")
+    return 0
+
+
+# -------------------------------------------------------------- 子命令:probe
+def _format_words(words: Sequence[int]) -> str:
+    return " ".join("%d/0x%04X" % (int(w) & 0xFFFF, int(w) & 0xFFFF) for w in words)
+
+
+def cmd_probe(args: argparse.Namespace) -> int:
+    """最小 Modbus/TCP 客户端:读/写寄存器验证联调,不依赖 pymodbus。"""
+
+    host = str(args.host)
+    port = int(args.port)
+    unit = int(args.unit)
+    address = int(args.address)
+
+    if args.write_cmd is not None:
+        try:
+            modbus_write_single(host, port, address, int(args.write_cmd), unit_id=unit, timeout=args.timeout)
+            print("已写入保持寄存器 %d = %d(FC6,unit=%d)" % (address, int(args.write_cmd), unit))
+        except Exception as exc:  # noqa: BLE001
+            print("写寄存器失败:%s" % exc, file=sys.stderr)
+            return 2
+
+    failures = 0
+    for index in range(max(1, int(args.repeat))):
+        if index and float(args.interval) > 0:
+            time.sleep(float(args.interval))
+        stamp = time.strftime("%H:%M:%S")
+        try:
+            words = modbus_read(
+                host, port, address, int(args.count), unit_id=unit, timeout=args.timeout, function=int(args.fc)
+            )
+        except Exception as exc:  # noqa: BLE001
+            failures += 1
+            print("[%s] 第 %d 次读取失败:%s" % (stamp, index + 1, exc), file=sys.stderr)
+            continue
+
+        if int(args.fc) == FC_READ_INPUT_REGISTERS and len(words) >= VisionSnapshot.register_count():
+            try:
+                snapshot = VisionSnapshot.from_registers(words, verify=True)
+                print(
+                    "[%s] state=%d(%-11s) conf=%4d flags=0x%04X seq=%d hb=%d fps=%.1f lat=%dms crc=OK"
+                    % (
+                        stamp,
+                        int(snapshot.state),
+                        STATE_LABELS.get(int(snapshot.state), "?"),
+                        int(snapshot.confidence),
+                        int(snapshot.flags),
+                        int(snapshot.seq),
+                        int(snapshot.heartbeat),
+                        int(snapshot.fps_x10) / 10.0,
+                        int(snapshot.latency_ms),
+                    )
+                )
+            except ValueError as exc:
+                failures += 1
+                print("[%s] 读到数据但解码失败:%s" % (stamp, exc), file=sys.stderr)
+        elif int(args.fc) == FC_READ_HOLDING_REGISTERS:
+            command = PlcCommand.from_registers(words)
+            print(
+                "[%s] cmd=%d preset=%d min_conf=%d reserved=%d"
+                % (stamp, int(command.cmd), int(command.preset), int(command.min_conf), int(command.reserved))
+            )
+        else:
+            print("[%s] %d 个字:%s" % (stamp, len(words), _format_words(words)))
+        if args.raw:
+            print("       原始:%s" % _format_words(words))
+    return 1 if failures else 0
+
+
+# ------------------------------------------------------------ 参数解析与入口
+def _add_common(parser: argparse.ArgumentParser, with_log: bool = True) -> None:
+    parser.add_argument("-c", "--config", default=None, help="配置文件(.json;装了 pyyaml 也可 .yaml)")
+    if with_log:
+        parser.add_argument("--log-level", default=None, help="日志级别:DEBUG/INFO/WARNING/ERROR")
+        parser.add_argument("--json-logs", action="store_true", help="日志输出为 JSON Lines")
+
+
+def build_parser() -> argparse.ArgumentParser:
+    """构造命令行解析器(供 ``python -m portcv`` 与测试复用)。"""
+
+    parser = argparse.ArgumentParser(
+        prog="portcv",
+        description="集装箱落位识别(车斗 / 平板车 / 不在车上)→ 西门子 PLC",
+        epilog=(
+            "示例:\n"
+            "  python -m portcv selftest                  # 零硬件自检(建议先跑)\n"
+            "  python -m portcv doctor --deep             # 上机前体检(含相机/端口)\n"
+            "  python -m portcv registers --scl           # 寄存器映射 + SCL 片段\n"
+            "  python -m portcv run -c configs/default.json --source rtsp://192.168.0.50/live\n"
+            "  python -m portcv probe --repeat 10 --raw   # 周期读寄存器,验证联调\n"
+        ),
+        formatter_class=argparse.RawDescriptionHelpFormatter,
+    )
+    parser.add_argument("--version", action="version", version="portcv %s" % __version__)
+    subparsers = parser.add_subparsers(dest="command", metavar="<命令>")
+
+    run = subparsers.add_parser("run", help="常驻服务:取帧→推理→判定→发布")
+    _add_common(run)
+    run.add_argument("--backend", default=None, help="mock | onnx | rknn | tensorrt")
+    run.add_argument("--mode", default=None, choices=["composed", "direct"], help="判定模式")
+    run.add_argument("--source", default=None, help="视频源:rtsp://... | usb:0 | file:a.mp4 | images:dir")
+    run.add_argument("--max-fps", dest="max_fps", type=float, default=None, help="主循环限速(0=不限)")
+    run.add_argument("--max-seconds", dest="max_seconds", type=float, default=None, help="跑多少秒后退出(调试)")
+    run.add_argument("--max-frames", dest="max_frames", type=int, default=None, help="处理多少帧后退出(调试)")
+    run.add_argument("--save", action="store_true", help="状态变化时存图(挖难例)")
+    run.add_argument("--preview", action="store_true", help="弹本地预览窗口")
+    run.add_argument("--no-plc", dest="no_plc", action="store_true", help="不连 PLC,仅本地判定")
+    run.add_argument("--gating", action="store_true", help="只有 PLC 请求时才推理(省算力)")
+    run.add_argument("--modbus-port", dest="modbus_port", type=int, default=None, help="Modbus 监听端口")
+    run.add_argument("--report", action="store_true", help="退出时打印统计 JSON")
+    run.set_defaults(func=cmd_run)
+
+    selftest = subparsers.add_parser("selftest", help="零硬件自检:合成帧 + mock + Modbus 回环")
+    _add_common(selftest)
+    selftest.add_argument("--mode", default=None, choices=["composed", "direct"], help="判定模式")
+    selftest.add_argument("--modbus-port", dest="modbus_port", type=int, default=None,
+                          help="自检端口(默认 1502,被占用会自动换)")
+    selftest.set_defaults(func=cmd_selftest)
+
+    doctor = subparsers.add_parser("doctor", help="环境体检:依赖/模型/相机/PLC 端口")
+    _add_common(doctor)
+    doctor.add_argument("--backend", default=None, help="按指定后端检查依赖与模型")
+    doctor.add_argument("--source", default=None, help="指定视频源")
+    doctor.add_argument("--deep", action="store_true", help="额外真实打开一次视频源")
+    doctor.set_defaults(func=cmd_doctor)
+
+    bench = subparsers.add_parser("bench", help="推理/整链耗时压测")
+    _add_common(bench)
+    bench.add_argument("--backend", default=None, help="mock | onnx | rknn | tensorrt")
+    bench.add_argument("--mode", default=None, choices=["composed", "direct"])
+    bench.add_argument("--frames", type=int, default=50, help="测试帧数")
+    bench.add_argument("--width", type=int, default=1280)
+    bench.add_argument("--height", type=int, default=720)
+    bench.add_argument("--target-fps", dest="target_fps", type=float, default=0.0, help="达标帧率,用于给结论")
+    bench.add_argument("--json", action="store_true", help="额外输出 JSON")
+    bench.set_defaults(func=cmd_bench)
+
+    registers = subparsers.add_parser("registers", help="打印寄存器映射(可输出 SCL)")
+    _add_common(registers, with_log=False)
+    registers.add_argument("--scl", action="store_true", help="输出西门子 SCL 参考代码")
+    registers.add_argument("--json", action="store_true", help="输出 JSON 映射")
+    registers.set_defaults(func=cmd_registers)
+
+    probe = subparsers.add_parser("probe", help="最小 Modbus/TCP 客户端,读/写寄存器验证联调")
+    _add_common(probe, with_log=False)
+    probe.add_argument("--host", default="127.0.0.1", help="视觉盒子 IP(或 Modbus 从站 IP)")
+    probe.add_argument("--port", type=int, default=1502, help="Modbus 端口")
+    probe.add_argument("--unit", type=int, default=1, help="从站号")
+    probe.add_argument("--address", type=int, default=0, help="起始地址")
+    probe.add_argument("--count", type=int, default=12, help="读取字数")
+    probe.add_argument(
+        "--fc",
+        type=int,
+        default=FC_READ_INPUT_REGISTERS,
+        choices=[FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS],
+        help="4=读输入寄存器(视觉结果) 3=读保持寄存器(PLC 指令)",
+    )
+    probe.add_argument("--write-cmd", dest="write_cmd", type=int, default=None,
+                       help="先写一个保持寄存器(FC6),如 --write-cmd 1 触发按需识别")
+    probe.add_argument("--repeat", type=int, default=1, help="读取次数")
+    probe.add_argument("--interval", type=float, default=0.5, help="每次读取间隔(秒)")
+    probe.add_argument("--timeout", type=float, default=2.0, help="单次请求超时(秒)")
+    probe.add_argument("--raw", action="store_true", help="额外打印原始字(十进制/十六进制)")
+    probe.set_defaults(func=cmd_probe)
+
+    return parser
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+    """命令行入口。返回进程退出码(0 = 成功)。"""
+
+    parser = build_parser()
+    args = parser.parse_args(list(argv) if argv is not None else None)
+    if not getattr(args, "command", None):
+        parser.print_help()
+        return 2
+    try:
+        return int(args.func(args))
+    except FileNotFoundError as exc:
+        print("错误:%s" % exc, file=sys.stderr)
+        return 2
+    except KeyboardInterrupt:  # pragma: no cover - 现场 Ctrl+C
+        print("\n已中断", file=sys.stderr)
+        return 130
+    except (ValueError, RuntimeError, OSError) as exc:
+        print("错误:%s" % exc, file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":  # pragma: no cover
+    sys.exit(main())
+
+
+
+
+
+
+
+
+

+ 301 - 0
portcv/config.py

@@ -0,0 +1,301 @@
+"""配置加载与默认值。
+
+* 原生支持 ``.json``(标准库,现场零依赖)。
+* 若安装了 ``pyyaml``,``.yaml`` / ``.yml`` 同样可用;未安装时给出明确提示。
+* :data:`DEFAULTS` 是唯一的默认值来源,用户配置只需写要覆盖的字段(深合并)。
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import os
+from typing import Any, Dict, List, Optional, Tuple
+
+__all__ = ["Config", "DEFAULTS", "load_config", "deep_update"]
+
+#: 默认配置。与 ``configs/default.json`` 保持一致(后者是给现场改的模板)。
+DEFAULTS: Dict[str, Any] = {
+    "run": {
+        "mode": "composed",       # composed=检测+规则 | direct=模型直接输出三分类
+        "backend": "mock",        # mock | onnx | rknn | tensorrt
+        "max_fps": 15.0,
+        "warmup_frames": 3,
+        "log_level": "INFO",
+        "log_json": False,
+        "save_on_change": False,  # 状态变化时存图,便于复盘/挖难例
+        "output_dir": "runs",
+        "preview": False,
+        "log_dir": "",              # 非空时另写按天轮转文件(P0-4)
+        "log_retention_days": 90,   # 按天备份保留天数
+    },
+    "evidence": {
+        "enabled": False,           # 现场确认磁盘/权限后再开
+        "dir": "",                  # 空 = <run.output_dir>/evidence
+        "retention_days": 90,
+        "segment_mb": 50,
+        "ring_frames": 300,         # 事件视频环缓帧数(15 fps ≈ 20 s)
+        "fps": 15.0,
+        "jpeg_quality": 85,
+        "max_side": 960,
+    },
+    "health": {
+        "enabled": True,
+        "work_width": 320,
+        "blur_var_min": 18.0,
+        "dark_clip_ratio_max": 0.97,
+        "bright_clip_ratio_max": 0.55,
+        "low_texture_ratio_max": 0.88,
+        "degrade_persist_s": 0.8,
+        "recover_persist_s": 1.5,
+    },
+    "source": {
+        "type": "file",           # file | rtsp | usb | gst | images
+        "uri": "samples/demo.mp4",
+        "width": 0,               # 0 = 用源分辨率
+        "height": 0,
+        "buffer_size": 2,
+        "use_gst": False,
+        "reconnect_s": 2.0,
+        "stale_frame_s": 0.6,     # 超过该时间没新帧 → FRAME_TIMEOUT
+    },
+    "model": {
+        "path": "weights/model.onnx",
+        "engine_path": "weights/model.plan",   # tensorrt
+        "rknn_path": "weights/model.rknn",     # rockchip
+        "labels": ["container", "bed", "flatbed", "not_on_train"],
+        "input_size": [640, 640],
+        "input_format": "rgb_float",  # rgb_float | bgr_uint8 | rgb_uint8
+        "conf": 0.35,
+        "iou": 0.5,
+        "max_det": 60,
+        "nms_free": False,            # True: 模型已内置 NMS(输出 Nx6)
+        "quantized": False,           # rknn int8
+        "rknn_core": "auto",          # auto | 0 | 1 | 2 | 0_1_2
+        "onnx_providers": ["CUDAExecutionProvider", "CPUExecutionProvider"],
+        "num_threads": 2,
+    },
+    "scene": {
+        "mode": "composed",           # 与 run.mode 同步,留作双保险
+        "classes": {
+            "container": ["container", "container_full", "container_empty", "container_20ft", "container_40ft"],
+            "bed": ["bed", "wagon_bed", "hopper_wagon", "gondola"],
+            "flatbed": ["flatbed", "flat_wagon", "platform_wagon"],
+            "ignore": ["person", "people", "crane", "spreader", "truck", "wheel", "rail"],
+        },
+        # direct 模式下模型类别名 → 场景编码
+        "direct_map": {"not_on_train": 0, "bed": 1, "flatbed": 2},
+        # 归一化 ROI(图像占比),限定在目标车厢区域,抑制远处干扰
+        "roi": [[0.03, 0.10], [0.97, 0.10], [0.97, 0.99], [0.03, 0.99]],
+        "require_container": True,    # 必须看到集装箱才算"在车上"
+        "min_class_conf": 0.30,
+        "roi_min_ratio": 0.30,        # 框与 ROI 的重叠比例下限
+        "support_overlap": 0.30,      # 集装箱与车厢框的横向交叠下限
+        "support_dy_ratio": 0.45,     # |车厢顶边 - 箱底边| / 箱高 的容差
+        "support_score_ratio": 0.60,  # 车厢分数 / 集装箱分数的下限
+        "unknown_on_no_detection": True,  # 完全无检测 → UNKNOWN(否则判 0)
+        "no_container_conf": 0.60,    # "没看到集装箱" 时的基础置信度
+    },
+    "evidence_v2": {
+        # P1b/P1c:默认关闭;启用后 VisionPipeline 不再走 SceneClassifier。
+        "enabled": False,
+        "view": "front",              # front | high
+        "work_width": 960,
+        "window": [0.24, 0.02, 0.78, 0.95],  # 归一化水平带搜索窗
+        "band_min_h": 3,
+        "band_max_h_ratio": 0.15,
+        "bed_search_ratio": 0.40,     # 车体上缘搜索窗 / 估计箱高
+        "box_bottom_max_ratio": 0.78,
+        "below_start_ratio": 0.07,    # 动态 ROI 起点 = 箱底 + 7% 箱高(避开下侧梁)
+        "below_height_ratio": 0.55,   # 箱底以下动态 ROI 高 / 估计箱高
+        "below_min_height_px": 24,
+        "min_door_posts": 5,          # 1 的门板立柱下限(A: 8–14, B: 0–4)
+        "max_door_posts": 16,         # 超过 → 箱体波纹/背景误检,弃权
+        "max_bed_gap_px": 40.0,       # 箱体高悬(>0.35m)时不做 1 分类
+        "flat_max_door_posts": 4,
+        "max_post_spacing_cv": 6.0,
+        "min_post_len_ratio": 0.30,
+        "min_wall_opacity": 0.35,
+        "max_flat_gap_px": 40.0,
+        "wall_edge_density_ref": 0.14,
+        "wall_edge_density_span": 0.04,
+        "ground_block_px": 32,
+        "ground_density_lo": 0.02,
+        "ground_density_hi": 0.35,
+        "min_flat_ground_ratio": 0.40,
+        "min_zero_ground_ratio": 0.65,
+        "deck_min_len_ratio": 0.30,
+        "box_height_m": 2.591,
+        "px_per_m": 0.0,              # 0 = 用箱体竖棱自标尺
+        "min_scale_px": 60.0,
+        "motion_diff_max": 12.0,
+        "motion_grad_ratio_min": 0.72,
+        "require_commit": True,       # True: commit 不成立时内部输出 255
+        "allow_state2": True,         # 平车 2 已打开提交;与 commit.allow_state2 串联
+        "structure_hits_min": 0.60,
+        "commit": {
+            "gap_m_max": 0.10,
+            "gap_px_hard_max": 8.0,   # 前视箱底 ±5 px 的安全硬门
+            "stable_frames": 5,
+            "structure_frames": 5,
+            "min_structure_hits": 0.60,
+            "max_gap_rise_m": 0.01,
+            "allow_state1": True,
+            "allow_state2": True,
+            "require_motion_ok": True,
+            "require_view_known": True,
+            "use_plc_arrival": True,
+        },
+    },
+    "decision": {
+        "window": 9,             # 滑窗帧数
+        "window_s": 1.0,         # 滑窗时间窗(秒),两者取小
+        "min_votes": 4,          # 窗内同状态最少票数
+        "min_confidence": 0.45,
+        "min_dwell_s": 0.20,     # 新状态需持续该时长才提交(防抖)
+        "hold_s": 0.60,          # 短暂无有效观测时保持上一状态
+        "lost_timeout_s": 1.50,  # 超时后置 UNKNOWN,让 PLC 回安全态
+        "low_fps_threshold": 3.0,
+        "mrc_on_uncertain": True,  # 感知不确定时置 MRC_REQUEST(整机 MRC 由 PLC 执行)
+    },
+    "calibration": {
+        "stale": False,            # 手工标记过期/漂移(覆盖自动判定)
+        "record": "",              # configs/calib/*.json 路径(P0-5)
+        "max_age_days": 180,       # 超过则 CALIB_STALE
+        "px_per_m_tolerance": 0.10,
+        "box_height_tolerance_m": 0.02,
+        # 标定不可信时是否清 RESULT_VALID/STABLE(默认 True:不给可执行结果)。
+        # C++ 侧同名同义(cpp/src/calibration.cpp);置 False = 只告警,由 PLC 联锁决定。
+        "hold_on_stale": True,
+    },
+    "plc": {
+        "enabled": True,
+        "push": "modbus_server",   # modbus_server | snap7 | both | none
+        "modbus": {
+            "host": "0.0.0.0",
+            "port": 1502,          # 标准 502 在 Linux 需 root,现场按 PLC 侧要求改
+            "unit_id": 1,
+            "input_addr": 0,       # 输入寄存器(视觉 → PLC)起始地址
+            "holding_addr": 0,     # 保持寄存器(PLC → 视觉)起始地址
+            "allow_unit_any": True,
+        },
+        "snap7": {
+            "host": "192.168.0.10",
+            "rack": 0,
+            "slot": 1,
+            "db_number": 100,
+            "db_start": 0,
+            "reconnect_s": 3.0,
+            "tcp_port": 102,
+        },
+        "gating": False,           # True: 只有 PLC 请求时才推理(省算力)
+        "gating_timeout_ms": 800,
+        "heartbeat_ms": 500,
+        "confidence_scale": 1000,
+        "min_publish_interval_ms": 50,
+    },
+}
+
+
+def _load_yaml(path: str) -> Dict[str, Any]:
+    try:
+        import yaml  # type: ignore
+    except ImportError as exc:  # pragma: no cover - 取决于环境
+        raise RuntimeError(
+            "读取 %s 需要 pyyaml,请 `pip install pyyaml`,或改用 .json 配置文件" % path
+        ) from exc
+    with open(path, "r", encoding="utf-8") as fh:
+        return yaml.safe_load(fh) or {}
+
+
+def deep_update(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
+    """把 ``override`` 递归合并进 ``base``(原地修改并返回 base)。"""
+
+    for key, value in override.items():
+        if isinstance(value, dict) and isinstance(base.get(key), dict):
+            deep_update(base[key], value)
+        else:
+            base[key] = copy.deepcopy(value)
+    return base
+
+
+class Config:
+    """轻量配置访问器:``cfg.get_path("plc.modbus.port", 502)``。"""
+
+    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
+        self.data: Dict[str, Any] = copy.deepcopy(DEFAULTS)
+        if data:
+            deep_update(self.data, data)
+
+    # -- 读写 -------------------------------------------------------------
+    def get_path(self, path: str, default: Any = None) -> Any:
+        node: Any = self.data
+        for part in path.split("."):
+            if not isinstance(node, dict) or part not in node:
+                return default
+            node = node[part]
+        return node
+
+    def set_path(self, path: str, value: Any) -> None:
+        parts = path.split(".")
+        node = self.data
+        for part in parts[:-1]:
+            node = node.setdefault(part, {})
+        node[parts[-1]] = value
+
+    def section(self, name: str) -> Dict[str, Any]:
+        value = self.data.get(name, {})
+        return copy.deepcopy(value) if isinstance(value, dict) else {}
+
+    def to_dict(self) -> Dict[str, Any]:
+        return copy.deepcopy(self.data)
+
+    def dump(self, path: str) -> None:
+        """把当前配置写回文件(json),便于现场固化参数。"""
+
+        folder = os.path.dirname(os.path.abspath(path))
+        if folder:
+            os.makedirs(folder, exist_ok=True)
+        with open(path, "w", encoding="utf-8") as fh:
+            json.dump(self.data, fh, ensure_ascii=False, indent=2)
+
+    def __getitem__(self, key: str) -> Any:
+        return self.data[key]
+
+    def __contains__(self, key: str) -> bool:
+        return key in self.data
+
+    # -- 便捷属性 ---------------------------------------------------------
+    @property
+    def labels(self) -> List[str]:
+        return list(self.get_path("model.labels", []) or [])
+
+    @property
+    def input_size(self) -> Tuple[int, int]:
+        size = self.get_path("model.input_size", [640, 640])
+        return (int(size[0]), int(size[1]))
+
+    @property
+    def roi(self) -> List[Tuple[float, float]]:
+        return [tuple(map(float, p)) for p in (self.get_path("scene.roi") or [])]
+
+
+def load_config(path: Optional[str] = None, overrides: Optional[Dict[str, Any]] = None) -> Config:
+    """加载配置文件(可为 None → 纯默认值),再套用 ``overrides``。"""
+
+    data: Dict[str, Any] = {}
+    if path:
+        if not os.path.isfile(path):
+            raise FileNotFoundError("配置文件不存在: %s" % path)
+        ext = os.path.splitext(path)[1].lower()
+        if ext in (".yaml", ".yml"):
+            data = _load_yaml(path)
+        elif ext == ".json":
+            with open(path, "r", encoding="utf-8") as fh:
+                data = json.load(fh) or {}
+        else:
+            raise ValueError("不支持的配置文件格式: %s(请用 .json / .yaml)" % ext)
+    cfg = Config(data)
+    if overrides:
+        cfg.data = deep_update(cfg.data, overrides)
+    return cfg

+ 95 - 0
portcv/detect/__init__.py

@@ -0,0 +1,95 @@
+"""检测后端注册表:按配置创建检测器,重依赖全部懒加载。
+
+``run.backend`` 可选:``mock`` / ``onnx`` / ``rknn`` / ``tensorrt`` / ``auto``。
+
+``auto`` 的优先级:``rknn``(RK 板子)→ ``tensorrt``(Jetson)→ ``onnx`` → ``mock``,
+方便同一份配置在工控机/板子上都能直接跑起来。
+"""
+
+from __future__ import annotations
+
+import importlib.util
+from typing import Dict, Type
+
+from ..config import Config
+from .base import Detector
+from .mock import MockDetector
+from .postproc import decode_yolo_output, draw_boxes
+from .preproc import letterbox, to_blob
+
+__all__ = [
+    "Detector",
+    "MockDetector",
+    "build_detector",
+    "decode_yolo_output",
+    "draw_boxes",
+    "letterbox",
+    "to_blob",
+]
+
+_ALIASES: Dict[str, str] = {
+    "mock": "mock",
+    "sim": "mock",
+    "none": "mock",
+    # P1b:evidence_v2 自己完成逐帧判定,不需要模型;用 mock 占位以复用服务链路。
+    "evidence_v2": "mock",
+    "evidence-v2": "mock",
+    "edge-v2": "mock",
+    "onnx": "onnx",
+    "onnxruntime": "onnx",
+    "ort": "onnx",
+    "rknn": "rknn",
+    "rockchip": "rknn",
+    "npu": "rknn",
+    "trt": "tensorrt",
+    "tensorrt": "tensorrt",
+    "jetson": "tensorrt",
+    "auto": "auto",
+}
+
+
+def _module_available(name: str) -> bool:
+    try:
+        return importlib.util.find_spec(name) is not None
+    except (ImportError, ValueError):  # pragma: no cover
+        return False
+
+
+def resolve_backend(name: str) -> str:
+    """把别名/auto 解析成真实后端名。"""
+
+    key = _ALIASES.get(str(name or "").strip().lower(), "")
+    if not key:
+        raise ValueError(
+            "未知推理后端: %r(可选 mock / onnx / rknn / tensorrt / auto)" % name
+        )
+    if key != "auto":
+        return key
+    if _module_available("rknnlite"):
+        return "rknn"
+    if _module_available("tensorrt") and _module_available("pycuda"):
+        return "tensorrt"
+    if _module_available("onnxruntime"):
+        return "onnx"
+    return "mock"
+
+
+def build_detector(cfg: Config, backend: str = "") -> Detector:
+    """按配置创建检测器实例(不加载权重,由 service 决定何时 load/warmup)。"""
+
+    name = resolve_backend(backend or cfg.get_path("run.backend", "mock"))
+    if name == "mock":
+        return MockDetector(cfg)
+    if name == "onnx":
+        from .onnx_backend import OnnxDetector
+
+        return OnnxDetector(cfg)
+    if name == "rknn":
+        from .rknn_backend import RknnDetector
+
+        return RknnDetector(cfg)
+    if name == "tensorrt":
+        from .trt_backend import TensorRtDetector
+
+        return TensorRtDetector(cfg)
+    raise ValueError("未实现的后端: %s" % name)

+ 99 - 0
portcv/detect/base.py

@@ -0,0 +1,99 @@
+"""检测器抽象基类。
+
+所有后端(mock / onnxruntime / rknn / tensorrt / deepstream)都实现同一接口,
+上层 :mod:`portcv.service` 因此与硬件无关:换板子只换 ``run.backend``。
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Dict, List, Optional, Sequence
+
+import numpy as np
+
+from ..config import Config
+from ..schema import Box
+
+__all__ = ["Detector"]
+
+
+class Detector:
+    """检测器接口。``infer`` 必须返回原图坐标系下的 :class:`Box` 列表。"""
+
+    name = "base"
+
+    def __init__(self, cfg: Config) -> None:
+        self.cfg = cfg
+        self.labels: List[str] = cfg.labels
+        self.input_size = cfg.input_size
+        self.input_format: str = str(cfg.get_path("model.input_format", "rgb_float"))
+        self.conf: float = float(cfg.get_path("model.conf", 0.35))
+        self.iou: float = float(cfg.get_path("model.iou", 0.5))
+        self.max_det: int = int(cfg.get_path("model.max_det", 60))
+        self.nms_free: bool = bool(cfg.get_path("model.nms_free", False))
+        self.quantized: bool = bool(cfg.get_path("model.quantized", False))
+        self._infer_ms: float = 0.0
+
+    # -- 子类实现 ---------------------------------------------------------
+    def infer(self, frame: np.ndarray) -> List[Box]:
+        raise NotImplementedError
+
+    def load(self) -> None:
+        """加载模型/引擎(幂等)。"""
+
+    def close(self) -> None:
+        """释放资源。"""
+
+    # -- 通用 -------------------------------------------------------------
+    def warmup(self, frames: int = 3) -> None:
+        """预热:触发一次图/引擎构建,避免首帧耗时影响节拍。"""
+
+        width, height = self.input_size
+        dummy = np.zeros((height, width, 3), dtype=np.uint8)
+        for _ in range(max(1, int(frames))):
+            self.infer(dummy)
+
+    @property
+    def infer_ms(self) -> float:
+        return self._infer_ms
+
+    def timed_infer(self, frame: np.ndarray) -> List[Box]:
+        """带计时的推理。"""
+
+        start = time.perf_counter()
+        boxes = self.infer(frame)
+        self._infer_ms = (time.perf_counter() - start) * 1000.0
+        return boxes
+
+    def describe(self) -> Dict[str, object]:
+        return {
+            "backend": self.name,
+            "labels": list(self.labels),
+            "input_size": list(self.input_size),
+            "input_format": self.input_format,
+            "conf": self.conf,
+            "iou": self.iou,
+            "nms_free": self.nms_free,
+            "quantized": self.quantized,
+        }
+
+    # -- 工具 -------------------------------------------------------------
+    def pick_output(self, outputs: Sequence[np.ndarray]) -> Optional[np.ndarray]:
+        """从多个输出里挑出检测头张量(兼容导出时附带的多路输出)。"""
+
+        nc = len(self.labels)
+        candidates = []
+        for out in outputs:
+            arr = np.asarray(out)
+            while arr.ndim > 3:
+                arr = arr[0]
+            if arr.ndim < 2:
+                continue
+            for axis in (1, 0):
+                if axis < arr.ndim and int(arr.shape[axis]) in (4 + nc, 5 + nc, 6):
+                    candidates.append(arr)
+                    break
+        if not candidates:
+            return None
+        # 取元素最多的那个(通常是真实检测头)
+        return max(candidates, key=lambda a: int(a.size))

+ 84 - 0
portcv/detect/mock.py

@@ -0,0 +1,84 @@
+"""Mock 检测器:无模型也能跑通全链路(联调 PLC、验证状态机、跑回归测试)。
+
+脚本用 **归一化坐标**(0..1)描述,``infer`` 时按实际帧尺寸展开,因此与分辨率无关。
+默认脚本按"车斗 → 平板车 → 只有箱(不在车上)→ 空场景"循环,方便现场演示三种反馈值。
+"""
+
+from __future__ import annotations
+
+from typing import Dict, List, Optional, Sequence, Tuple
+
+import numpy as np
+
+from ..config import Config
+from ..schema import Box
+from .base import Detector
+
+__all__ = ["MockDetector", "build_demo_script"]
+
+#: 每个剧本元素:(类别名, 归一化 x1, y1, x2, y2, 分数)
+ScriptFrame = List[Tuple[str, float, float, float, float, float]]
+
+
+def build_demo_script() -> List[ScriptFrame]:
+    """默认演示剧本,覆盖 1 / 2 / 0 / UNKNOWN 四种情况。"""
+
+    return [
+        # 车斗:集装箱坐在带斗车厢上
+        [
+            ("container", 0.30, 0.28, 0.72, 0.62, 0.91),
+            ("bed", 0.27, 0.62, 0.75, 0.88, 0.86),
+        ],
+        # 平板车:集装箱坐在平板车上
+        [
+            ("container", 0.32, 0.30, 0.70, 0.60, 0.89),
+            ("flatbed", 0.28, 0.60, 0.74, 0.84, 0.83),
+        ],
+        # 只有集装箱(被吊起/在卡车上)→ 0
+        [
+            ("container", 0.34, 0.22, 0.68, 0.50, 0.88),
+        ],
+        # 空场景 → UNKNOWN(可配置成 0)
+        [],
+    ]
+
+
+class MockDetector(Detector):
+    """按剧本循环输出检测框,用于自检与演示。"""
+
+    name = "mock"
+
+    def __init__(self, cfg: Config, script: Optional[Sequence[ScriptFrame]] = None) -> None:
+        super().__init__(cfg)
+        self.script: List[ScriptFrame] = [list(frame) for frame in (script or build_demo_script())]
+        if not self.script:
+            self.script = [[]]
+        self._cursor = 0
+
+    def infer(self, frame: np.ndarray) -> List[Box]:
+        height, width = frame.shape[:2]
+        raw = self.script[self._cursor % len(self.script)]
+        self._cursor += 1
+        boxes: List[Box] = []
+        for name, x1, y1, x2, y2, score in raw:
+            class_id = self.labels.index(name) if name in self.labels else -1
+            boxes.append(
+                Box(
+                    x1 * width,
+                    y1 * height,
+                    x2 * width,
+                    y2 * height,
+                    score=float(score),
+                    class_id=class_id,
+                    class_name=str(name),
+                )
+            )
+        return boxes
+
+    def reset(self) -> None:
+        self._cursor = 0
+
+    def describe(self) -> Dict[str, object]:
+        info = super().describe()
+        info["script_frames"] = len(self.script)
+        return info

+ 87 - 0
portcv/detect/onnx_backend.py

@@ -0,0 +1,87 @@
+"""ONNX Runtime 后端(PC 联调 / Jetson CPU 兜底 / x86 工控机部署)。
+
+Jetson 上生产环境优先用 :mod:`.trt_backend` 或 DeepStream(见 ``deploy/deepstream``),
+ONNX Runtime 主要用来:
+* 在开发机上验证模型与后处理是否对得上;
+* 与 ONNX 转换流程做逐帧对比(同输入同输出)。
+"""
+
+from __future__ import annotations
+
+from typing import Dict, List, Optional
+
+import numpy as np
+
+from ..config import Config
+from ..schema import Box
+from .base import Detector
+from .postproc import decode_yolo_output
+from .preproc import letterbox, to_blob
+
+__all__ = ["OnnxDetector"]
+
+
+class OnnxDetector(Detector):
+    name = "onnx"
+
+    def __init__(self, cfg: Config) -> None:
+        super().__init__(cfg)
+        self.model_path: str = str(cfg.get_path("model.path", ""))
+        self.providers = list(cfg.get_path("model.onnx_providers", []) or [])
+        self.num_threads = int(cfg.get_path("model.num_threads", 0) or 0)
+        self.session = None
+        self.input_name: Optional[str] = None
+
+    def load(self) -> None:
+        if self.session is not None:
+            return
+        try:
+            import onnxruntime as ort  # type: ignore
+        except ImportError as exc:  # pragma: no cover
+            raise RuntimeError(
+                "使用 onnx 后端需要 onnxruntime:pip install onnxruntime "
+                "(Jetson/ARM 请装官方对应 wheel 或改用 tensorrt/rknn 后端)"
+            ) from exc
+        available = ort.get_available_providers()
+        providers = [p for p in self.providers if p in available] or None
+        options = ort.SessionOptions()
+        if self.num_threads > 0:
+            options.intra_op_num_threads = self.num_threads
+            options.inter_op_num_threads = 1
+        options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
+        self.session = ort.InferenceSession(self.model_path, options, providers=providers)
+        self.input_name = self.session.get_inputs()[0].name
+        shape = self.session.get_inputs()[0].shape
+        if len(shape) == 4 and isinstance(shape[2], int) and isinstance(shape[3], int):
+            self.input_size = (int(shape[3]), int(shape[2]))
+
+    def infer(self, frame: np.ndarray) -> List[Box]:
+        if self.session is None:
+            self.load()
+        assert self.session is not None and self.input_name is not None
+        height, width = frame.shape[:2]
+        padded, ratio, pad = letterbox(frame, self.input_size)
+        blob = to_blob(padded, self.input_format)
+        outputs = self.session.run(None, {self.input_name: blob})
+        raw = self.pick_output(outputs)
+        if raw is None:
+            return []
+        return decode_yolo_output(
+            raw,
+            labels=self.labels,
+            conf_thres=self.conf,
+            iou_thres=self.iou,
+            max_det=self.max_det,
+            nms_free=self.nms_free,
+            ratio=ratio,
+            pad=pad,
+            image_size=(width, height),
+        )
+
+    def close(self) -> None:
+        self.session = None
+
+    def describe(self) -> Dict[str, object]:
+        info = super().describe()
+        info.update({"model_path": self.model_path, "providers": self.providers})
+        return info

+ 204 - 0
portcv/detect/postproc.py

@@ -0,0 +1,204 @@
+"""推理后处理:解析 YOLO 输出 → :class:`~portcv.schema.Box` 列表。
+
+兼容三种常见导出形态
+--------------------
+* ``(1, 4+nc, N)`` / ``(1, N, 4+nc)``:YOLOv8/v11 系列 xywh + 类别分数;
+* ``(1, 5+nc, N)`` / ``(1, N, 5+nc)``:YOLOv5 系列 xywh + obj + 类别分数;
+* ``(1, N, 6)``(``nms_free=True``):``x1,y1,x2,y2,score,class_id`` 端到端输出。
+
+坐标系约定:输入张量坐标是 **letterbox 后的输入尺寸**,本模块负责还原到原图。
+"""
+
+from __future__ import annotations
+
+from typing import List, Optional, Sequence, Tuple
+
+import numpy as np
+
+from ..schema import Box
+from .preproc import unletterbox_box
+
+__all__ = ["decode_yolo_output", "draw_boxes"]
+
+try:  # pragma: no cover
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+
+def _as_2d(raw: np.ndarray, nc: int, nms_free: bool) -> np.ndarray:
+    """把输出统一成 ``(N, C)``(C = 4+nc / 5+nc / 6)。"""
+
+    arr = np.asarray(raw, dtype=np.float32)
+    while arr.ndim > 2:
+        arr = arr[0]
+    if arr.ndim == 1:
+        arr = arr[None]
+    cols = int(arr.shape[1])
+    expected = 6 if nms_free else (4 + nc)
+    expected_obj = 5 + nc
+    if cols not in (expected, expected_obj, 6) and arr.shape[0] in (expected, expected_obj, 6):
+        arr = arr.T
+    return np.ascontiguousarray(arr)
+
+
+def _label_at(index: int, labels: Sequence[str]) -> str:
+    if 0 <= int(index) < len(labels):
+        return str(labels[int(index)])
+    return "cls_%d" % index
+
+
+def decode_yolo_output(
+    raw: np.ndarray,
+    labels: Sequence[str],
+    conf_thres: float = 0.35,
+    iou_thres: float = 0.5,
+    max_det: int = 60,
+    nms_free: bool = False,
+    ratio: float = 1.0,
+    pad: Tuple[float, float] = (0.0, 0.0),
+    image_size: Tuple[int, int] = (640, 640),
+    apply_nms: bool = True,
+) -> List[Box]:
+    """解析模型输出。``image_size`` 为原图 ``(width, height)``。"""
+
+    nc = len(labels)
+    arr = _as_2d(raw, nc, nms_free)
+    if arr.size == 0:
+        return []
+    cols = int(arr.shape[1])
+
+    if cols == 6 and nms_free:
+        boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
+    elif cols in (4 + nc, 5 + nc):
+        boxes = _decode_xywh(
+            arr, labels, conf_thres, ratio, pad, image_size, use_obj=(cols == 5 + nc)
+        )
+    elif cols == 6:
+        boxes = _decode_nms_free(arr, labels, conf_thres, ratio, pad, image_size)
+    else:
+        return []
+
+    if len(boxes) > max_det:
+        boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
+    if apply_nms and boxes and not nms_free:
+        from ..logic.geometry import nms as _nms
+
+        boxes = _nms(boxes, iou_thres, per_class=True)
+        if len(boxes) > max_det:
+            boxes = sorted(boxes, key=lambda b: b.score, reverse=True)[:max_det]
+    return boxes
+
+
+def _decode_nms_free(
+    arr: np.ndarray,
+    labels: Sequence[str],
+    conf_thres: float,
+    ratio: float,
+    pad: Tuple[float, float],
+    image_size: Tuple[int, int],
+) -> List[Box]:
+    """``N x 6``:``x1, y1, x2, y2, score, class_id``。"""
+
+    boxes: List[Box] = []
+    for row in arr:
+        score = float(row[4])
+        if score < conf_thres:
+            continue
+        cls_id = int(round(float(row[5])))
+        x1, y1, x2, y2 = unletterbox_box(
+            float(row[0]), float(row[1]), float(row[2]), float(row[3]), ratio, pad, image_size
+        )
+        if x2 - x1 < 1 or y2 - y1 < 1:
+            continue
+        boxes.append(
+            Box(x1, y1, x2, y2, score=score, class_id=cls_id, class_name=_label_at(cls_id, labels))
+        )
+    return boxes
+
+
+def _decode_xywh(
+    arr: np.ndarray,
+    labels: Sequence[str],
+    conf_thres: float,
+    ratio: float,
+    pad: Tuple[float, float],
+    image_size: Tuple[int, int],
+    use_obj: bool,
+) -> List[Box]:
+    """``N x (4+nc)`` 或 ``N x (5+nc)``:cxcywh(+obj)+类别分数。"""
+
+    nc = len(labels)
+    cx, cy, w, h = arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3]
+    if use_obj:
+        obj = arr[:, 4]
+        cls_scores = arr[:, 5 : 5 + nc]
+        cls_ids = np.argmax(cls_scores, axis=1)
+        scores = obj * cls_scores[np.arange(len(obj)), cls_ids]
+    else:
+        cls_scores = arr[:, 4 : 4 + nc]
+        cls_ids = np.argmax(cls_scores, axis=1)
+        scores = cls_scores[np.arange(len(cls_ids)), cls_ids]
+
+    keep = scores >= conf_thres
+    if not np.any(keep):
+        return []
+    x1 = cx[keep] - w[keep] / 2.0
+    y1 = cy[keep] - h[keep] / 2.0
+    x2 = cx[keep] + w[keep] / 2.0
+    y2 = cy[keep] + h[keep] / 2.0
+    scores = scores[keep]
+    cls_ids = cls_ids[keep]
+
+    boxes: List[Box] = []
+    for i in range(len(scores)):
+        rx1, ry1, rx2, ry2 = unletterbox_box(
+            float(x1[i]), float(y1[i]), float(x2[i]), float(y2[i]), ratio, pad, image_size
+        )
+        if rx2 - rx1 < 1 or ry2 - ry1 < 1:
+            continue
+        boxes.append(
+            Box(
+                rx1,
+                ry1,
+                rx2,
+                ry2,
+                score=float(scores[i]),
+                class_id=int(cls_ids[i]),
+                class_name=_label_at(int(cls_ids[i]), labels),
+            )
+        )
+    return boxes
+
+
+def draw_boxes(
+    image: np.ndarray,
+    boxes: Sequence[Box],
+    roi: Optional[Sequence[Tuple[float, float]]] = None,
+    texts: Optional[Sequence[str]] = None,
+) -> np.ndarray:
+    """画框 + ROI + 文本,用于联调预览与难例复盘(原地绘制并返回同一张图)。"""
+
+    if cv2 is None:
+        return image
+    colors = {
+        "container": (0, 215, 255),
+        "bed": (0, 255, 0),
+        "flatbed": (255, 128, 0),
+    }
+    for box in boxes:
+        color = colors.get(box.class_name, (0, 0, 255))
+        x1, y1, x2, y2 = [int(v) for v in box.as_xyxy()]
+        cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
+        tag = "%s %.2f" % (box.class_name, box.score)
+        cv2.putText(image, tag, (x1, max(12, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
+    if roi:
+        pts = np.array([[int(x), int(y)] for x, y in roi], dtype=np.int32)
+        cv2.polylines(image, [pts], True, (0, 255, 255), 2)
+    if texts:
+        for i, line in enumerate(texts):
+            cv2.putText(
+                image, str(line), (10, 24 + i * 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2
+            )
+    return image
+

+ 90 - 0
portcv/detect/preproc.py

@@ -0,0 +1,90 @@
+"""推理预处理:letterbox 缩放 + NCHW/NHWC blob 组装。
+
+``letterbox`` 与 :mod:`portcv.detect.postproc` 中的还原逻辑严格配对:
+训练/导出用的预处理必须与这里一致,否则框会整体偏移(尤其宽高比差异大的画面)。
+"""
+
+from __future__ import annotations
+
+from typing import Tuple
+
+import numpy as np
+
+__all__ = ["letterbox", "to_blob", "unletterbox_box"]
+
+try:  # pragma: no cover - 取决于环境
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+
+def letterbox(
+    image: np.ndarray,
+    new_shape: Tuple[int, int] = (640, 640),
+    color: Tuple[int, int, int] = (114, 114, 114),
+) -> Tuple[np.ndarray, float, Tuple[float, float]]:
+    """等比缩放到 ``new_shape`` 并居中填充。
+
+    返回 ``(图像, 缩放比例, (pad_x, pad_y))``。
+    """
+
+    if cv2 is None:
+        raise RuntimeError("需要 opencv-python: pip install opencv-python")
+    height, width = image.shape[:2]
+    new_w, new_h = int(new_shape[0]), int(new_shape[1])
+    ratio = min(new_w / float(width), new_h / float(height))
+    unpad_w, unpad_h = int(round(width * ratio)), int(round(height * ratio))
+    resized = cv2.resize(image, (unpad_w, unpad_h), interpolation=cv2.INTER_LINEAR)
+    dw = (new_w - unpad_w) / 2.0
+    dh = (new_h - unpad_h) / 2.0
+    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
+    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
+    padded = cv2.copyMakeBorder(
+        resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
+    )
+    return padded, float(ratio), (float(left), float(top))
+
+
+def to_blob(image: np.ndarray, input_format: str = "rgb_float") -> np.ndarray:
+    """按要求组装成模型输入 blob(batch=1)。
+
+    * ``rgb_float``:NCHW float32 / 255(ONNX、TensorRT 常用);
+    * ``rgb_uint8`` / ``bgr_uint8``:NHWC uint8(RKNN 量化模型与部分 ONNX 常用)。
+    """
+
+    fmt = str(input_format).lower()
+    if fmt == "rgb_float":
+        rgb = image[:, :, ::-1]
+        tensor = np.ascontiguousarray(rgb.transpose(2, 0, 1)[None].astype(np.float32) / 255.0)
+        return tensor
+    if fmt == "rgb_uint8":
+        rgb = np.ascontiguousarray(image[:, :, ::-1])
+        return rgb[None]
+    if fmt == "bgr_uint8":
+        return np.ascontiguousarray(image)[None]
+    raise ValueError("未知 input_format: %s(可选 rgb_float / rgb_uint8 / bgr_uint8)" % input_format)
+
+
+def unletterbox_box(
+    x1: float,
+    y1: float,
+    x2: float,
+    y2: float,
+    ratio: float,
+    pad: Tuple[float, float],
+    image_size: Tuple[int, int],
+) -> Tuple[float, float, float, float]:
+    """把 letterbox 坐标系下的框还原到原图坐标,并裁剪到图像范围。"""
+
+    pad_x, pad_y = float(pad[0]), float(pad[1])
+    ratio = float(ratio) if ratio > 0 else 1.0
+    x1 = (x1 - pad_x) / ratio
+    x2 = (x2 - pad_x) / ratio
+    y1 = (y1 - pad_y) / ratio
+    y2 = (y2 - pad_y) / ratio
+    width, height = float(image_size[0]), float(image_size[1])
+    x1 = min(max(x1, 0.0), width)
+    x2 = min(max(x2, 0.0), width)
+    y1 = min(max(y1, 0.0), height)
+    y2 = min(max(y2, 0.0), height)
+    return x1, y1, x2, y2

+ 105 - 0
portcv/detect/rknn_backend.py

@@ -0,0 +1,105 @@
+"""瑞芯微 RK 系列后端(RK3588 / RK3576 / RK3568,rknn-toolkit2 转换 + rknnlite 推理)。
+
+部署要点
+--------
+* 转换脚本:``scripts/onnx_to_rknn.py``(INT8 量化需要量化校准图集 txt);
+* RK3588 有 3 个 NPU core,可按 ``model.rknn_core`` 指定(``auto`` / ``0`` / ``1`` / ``2`` /
+  ``0_1_2``),多路相机时可把不同流绑到不同 core;
+* INT8 模型输入一般是 **NHWC uint8**,因此 ``model.input_format`` 用 ``rgb_uint8``;
+  若在转换时用了 ``mean_values``/``std_values`` 归一化,就不要再手工 /255。
+
+该后端只能在 RK 板子上导入(``rknnlite`` 仅提供 aarch64 Linux wheel),
+在本机(x86 Windows)会给出明确的安装提示而不是崩溃。
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Dict, List, Optional
+
+import numpy as np
+
+from ..config import Config
+from ..schema import Box
+from .base import Detector
+from .postproc import decode_yolo_output
+from .preproc import letterbox, to_blob
+
+__all__ = ["RknnDetector"]
+
+#: rknnlite 的 core_mask 常量(不同版本常量名一致,这里用数值兜底)
+_CORE_MASKS = {
+    "auto": 0,
+    "0": 1,
+    "1": 2,
+    "2": 4,
+    "0_1": 3,
+    "0_2": 5,
+    "1_2": 6,
+    "0_1_2": 7,
+}
+
+
+class RknnDetector(Detector):
+    name = "rknn"
+
+    def __init__(self, cfg: Config) -> None:
+        super().__init__(cfg)
+        self.model_path: str = str(cfg.get_path("model.rknn_path", ""))
+        self.core: str = str(cfg.get_path("model.rknn_core", "auto")).lower()
+        self.rknn = None
+
+    def load(self) -> None:
+        if self.rknn is not None:
+            return
+        if not os.path.isfile(self.model_path):
+            raise FileNotFoundError("RKNN 模型不存在: %s(先用 scripts/onnx_to_rknn.py 转换)" % self.model_path)
+        try:
+            from rknnlite.api import RKNNLite  # type: ignore
+        except ImportError as exc:  # pragma: no cover - 仅在 RK 板子上可导入
+            raise RuntimeError(
+                "使用 rknn 后端需要在 Rockchip 板子上安装 rknn-toolkit2 的 rknnlite 运行时,"
+                "并把 librknnrt.so 放到 LD_LIBRARY_PATH;详见 docs/04-deploy-rockchip.md"
+            ) from exc
+        rknn = RKNNLite(verbose=False)
+        if rknn.load_rknn(self.model_path) != 0:
+            raise RuntimeError("load_rknn 失败: %s" % self.model_path)
+        mask = _CORE_MASKS.get(self.core, 0)
+        if rknn.init_runtime(core_mask=mask) != 0:
+            raise RuntimeError("init_runtime 失败(core=%s)" % self.core)
+        self.rknn = rknn
+
+    def infer(self, frame: np.ndarray) -> List[Box]:
+        if self.rknn is None:
+            self.load()
+        assert self.rknn is not None
+        height, width = frame.shape[:2]
+        padded, ratio, pad = letterbox(frame, self.input_size)
+        blob = to_blob(padded, self.input_format)
+        outputs = self.rknn.inference(inputs=[blob])
+        raw = self.pick_output(list(outputs))
+        if raw is None:
+            return []
+        return decode_yolo_output(
+            raw,
+            labels=self.labels,
+            conf_thres=self.conf,
+            iou_thres=self.iou,
+            max_det=self.max_det,
+            nms_free=self.nms_free,
+            ratio=ratio,
+            pad=pad,
+            image_size=(width, height),
+        )
+
+    def close(self) -> None:
+        if self.rknn is not None:
+            try:
+                self.rknn.release()
+            finally:
+                self.rknn = None
+
+    def describe(self) -> Dict[str, object]:
+        info = super().describe()
+        info.update({"model_path": self.model_path, "core": self.core})
+        return info

+ 170 - 0
portcv/detect/trt_backend.py

@@ -0,0 +1,170 @@
+"""Jetson TensorRT 后端(pycuda 直跑 .plan 引擎)。
+
+* 生产环境更推荐 DeepStream(``deploy/deepstream``),它自带零拷贝、多路解码和
+  nvinfer 批处理;
+* 这个后端适合"单路相机 + 自己做状态机"的简洁部署,也用于和 DeepStream 对比精度;
+* 兼容 TensorRT 8(``get_binding_*``)与 TensorRT 10(``get_tensor_*`` / ``execute_async_v3``)。
+
+引擎构建请用 ``scripts/build_trt.py``(在 Jetson 上执行,必须与设备版本一致)。
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Dict, List, Optional
+
+import numpy as np
+
+from ..config import Config
+from ..schema import Box
+from .base import Detector
+from .postproc import decode_yolo_output
+from .preproc import letterbox, to_blob
+
+__all__ = ["TensorRtDetector"]
+
+
+class TensorRtDetector(Detector):
+    name = "tensorrt"
+
+    def __init__(self, cfg: Config) -> None:
+        super().__init__(cfg)
+        self.engine_path: str = str(cfg.get_path("model.engine_path", ""))
+        self.engine = None
+        self.context = None
+        self.stream = None
+        self._cuda = None
+        self._trt = None
+        self._tensors: List[Dict[str, object]] = []
+
+    # ------------------------------------------------------------ 加载
+    def load(self) -> None:
+        if self.context is not None:
+            return
+        if not os.path.isfile(self.engine_path):
+            raise FileNotFoundError(
+                "TensorRT 引擎不存在: %s(先在 Jetson 上执行 scripts/build_trt.py)" % self.engine_path
+            )
+        try:
+            import tensorrt as trt  # type: ignore
+            import pycuda.driver as cuda  # type: ignore
+        except ImportError as exc:  # pragma: no cover
+            raise RuntimeError(
+                "使用 tensorrt 后端需要 JetPack 自带的 tensorrt 与 pip 安装的 pycuda;"
+                "若不想管理这些依赖,请改用 DeepStream 或 onnx 后端"
+            ) from exc
+        cuda.init()
+        self._cuda = cuda
+        self._trt = trt
+        self.stream = cuda.Stream()
+        with open(self.engine_path, "rb") as fh:
+            runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
+            self.engine = runtime.deserialize_cuda_engine(fh.read())
+        if self.engine is None:
+            raise RuntimeError("反序列化 TensorRT 引擎失败(引擎与当前 TensorRT 版本不匹配?)")
+        self.context = self.engine.create_execution_context()
+        self._allocate()
+
+    def _allocate(self) -> None:
+        cuda = self._cuda
+        trt = self._trt
+        assert cuda is not None and trt is not None and self.engine is not None
+        modern = hasattr(self.engine, "num_io_tensors")  # TRT >= 10
+        count = self.engine.num_io_tensors if modern else self.engine.num_bindings
+        for index in range(count):
+            if modern:
+                name = self.engine.get_tensor_name(index)
+                is_input = str(self.engine.get_tensor_mode(name)) == "TensorIOMode.INPUT"
+                shape = tuple(int(v) for v in self.engine.get_tensor_shape(name))
+                dtype = trt.nptype(self.engine.get_tensor_dtype(name))
+            else:
+                name = self.engine.get_binding_name(index)
+                is_input = bool(self.engine.binding_is_input(index))
+                shape = tuple(int(v) for v in self.engine.get_binding_shape(index))
+                dtype = trt.nptype(self.engine.get_binding_dtype(index))
+            if is_input:
+                # 网络输入通常是 NCHW,H/W 可能为 -1(动态 shape),这里按配置固定
+                height, width = self.input_size[1], self.input_size[0]
+                shape = (1, 3, height, width)
+                if modern:
+                    self.context.set_input_shape(name, shape)
+                else:
+                    self.context.set_binding_shape(index, shape)
+            size = int(np.prod(shape))
+            host = cuda.pagelocked_empty(size, dtype)
+            device = cuda.mem_alloc(host.nbytes)
+            self._tensors.append(
+                {
+                    "name": name,
+                    "is_input": is_input,
+                    "shape": shape,
+                    "dtype": dtype,
+                    "host": host,
+                    "device": device,
+                    "index": index,
+                }
+            )
+
+    # ------------------------------------------------------------ 推理
+    def infer(self, frame: np.ndarray) -> List[Box]:
+        if self.context is None:
+            self.load()
+        cuda = self._cuda
+        assert cuda is not None and self.context is not None and self.stream is not None
+        height, width = frame.shape[:2]
+        padded, ratio, pad = letterbox(frame, self.input_size)
+        blob = to_blob(padded, self.input_format).astype(np.float32, copy=False)
+
+        for item in self._tensors:
+            if item["is_input"]:
+                host = item["host"]
+                np.copyto(host, blob.reshape(-1))
+                cuda.memcpy_htod_async(item["device"], host, self.stream)
+        if hasattr(self.context, "execute_async_v3"):
+            for item in self._tensors:
+                self.context.set_tensor_address(item["name"], int(item["device"]))
+            self.context.execute_async_v3(stream_handle=self.stream.handle)
+        else:  # TensorRT 8
+            bindings = [int(item["device"]) for item in self._tensors]
+            self.context.execute_async_v2(bindings=bindings, stream_handle=self.stream.handle)
+        for item in self._tensors:
+            if not item["is_input"]:
+                cuda.memcpy_dtoh_async(item["host"], item["device"], self.stream)
+        self.stream.synchronize()
+
+        outputs: List[np.ndarray] = []
+        for item in self._tensors:
+            if not item["is_input"]:
+                outputs.append(np.array(item["host"]).reshape(tuple(item["shape"])))
+        raw = self.pick_output(outputs)
+        if raw is None:
+            return []
+        return decode_yolo_output(
+            raw,
+            labels=self.labels,
+            conf_thres=self.conf,
+            iou_thres=self.iou,
+            max_det=self.max_det,
+            nms_free=self.nms_free,
+            ratio=ratio,
+            pad=pad,
+            image_size=(width, height),
+        )
+
+    # ------------------------------------------------------------ 释放
+    def close(self) -> None:
+        for item in self._tensors:
+            try:
+                item["device"].free()
+            except Exception:  # pragma: no cover - 释放失败不影响退出
+                pass
+        self._tensors = []
+        self.context = None
+        self.engine = None
+        self.stream = None
+
+    def describe(self) -> Dict[str, object]:
+        info = super().describe()
+        info.update({"engine_path": self.engine_path})
+        return info
+

+ 229 - 0
portcv/health.py

@@ -0,0 +1,229 @@
+"""P0-3 视觉自监测:图像质量 / 传感器退化 / 数据链健康。
+
+现场最容易出现的“算法看起来在跑、其实输入已经不可用”的情况:
+
+* 镜头结露、雨滴、油污 → 画面整体模糊或局部低纹理;
+* 逆光/夜间补光过曝 → 大面积削顶;
+* 镜头被遮挡/贴纸 → 画面近乎均匀,Laplacian 方差趋零;
+* 取流断链 → 由 ``runner`` 的 ``FRAME_TIMEOUT`` 处理。
+
+本模块**不改变**分类结果,只输出可解释的健康报告;``runner`` 把
+``sensor_degraded`` / ``perception_uncertain`` 映射到 flags bit10/bit8,
+并按 GB/T 45163.5 5.1.4 请求 MRC(bit9)。
+"""
+
+from __future__ import annotations
+
+import math
+import time
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional
+
+import numpy as np
+
+try:  # pragma: no cover - 与 evidence_v2 同一策略
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+from .config import Config
+
+__all__ = ["FrameHealthMonitor", "HealthParams", "HealthReport"]
+
+
+@dataclass(frozen=True)
+class HealthParams:
+    """``health.*`` 配置(阈值现场可整定)。"""
+
+    enabled: bool = True
+    work_width: int = 320
+    blur_var_min: float = 18.0
+    dark_clip_ratio_max: float = 0.97
+    bright_clip_ratio_max: float = 0.55
+    low_texture_ratio_max: float = 0.88
+    degrade_persist_s: float = 0.8
+    recover_persist_s: float = 1.5
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "HealthParams":
+        raw = cfg.section("health")
+        return cls(
+            enabled=bool(raw.get("enabled", True)),
+            work_width=max(64, int(raw.get("work_width", 320))),
+            blur_var_min=max(0.0, float(raw.get("blur_var_min", 18.0))),
+            dark_clip_ratio_max=float(raw.get("dark_clip_ratio_max", 0.97)),
+            bright_clip_ratio_max=float(raw.get("bright_clip_ratio_max", 0.55)),
+            low_texture_ratio_max=float(raw.get("low_texture_ratio_max", 0.88)),
+            degrade_persist_s=max(0.0, float(raw.get("degrade_persist_s", 0.8))),
+            recover_persist_s=max(0.0, float(raw.get("recover_persist_s", 1.5))),
+        )
+
+
+@dataclass
+class HealthReport:
+    """一帧的健康结论;字段可直接写 JSONL。"""
+
+    ts: float = 0.0
+    sensor_degraded: bool = False
+    perception_uncertain: bool = False
+    blur_var: float = 0.0
+    dark_clip_ratio: float = 0.0
+    bright_clip_ratio: float = 0.0
+    low_texture_ratio: float = 0.0
+    motion_diff: float = 0.0
+    reasons: List[str] = field(default_factory=list)
+
+    @property
+    def ok(self) -> bool:
+        return not self.sensor_degraded and not self.perception_uncertain
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "ts": round(float(self.ts), 6),
+            "ok": bool(self.ok),
+            "sensor_degraded": bool(self.sensor_degraded),
+            "perception_uncertain": bool(self.perception_uncertain),
+            "blur_var": round(float(self.blur_var), 3),
+            "dark_clip_ratio": round(float(self.dark_clip_ratio), 4),
+            "bright_clip_ratio": round(float(self.bright_clip_ratio), 4),
+            "low_texture_ratio": round(float(self.low_texture_ratio), 4),
+            "motion_diff": round(float(self.motion_diff), 4),
+            "reasons": list(self.reasons),
+        }
+
+
+class FrameHealthMonitor:
+    """逐帧图像健康监测(线程内使用,非线程安全)。"""
+
+    def __init__(self, params: Optional[HealthParams] = None) -> None:
+        self.p = params or HealthParams()
+        self._degraded = False
+        self._bad_since: Optional[float] = None
+        self._good_since: Optional[float] = None
+        self._prev_thumb: Optional[np.ndarray] = None
+        self._last = HealthReport()
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "FrameHealthMonitor":
+        return cls(HealthParams.from_config(cfg))
+
+    @property
+    def last(self) -> HealthReport:
+        return self._last
+
+    def reset(self) -> None:
+        self._degraded = False
+        self._bad_since = None
+        self._good_since = None
+        self._prev_thumb = None
+        self._last = HealthReport()
+
+    def observe(self, image: np.ndarray, ts: Optional[float] = None) -> HealthReport:
+        """分析一帧;``enabled=False`` 时只返回空报告(零开销)。"""
+
+        ts_value = float(time.time() if ts is None else ts)
+        if not self.p.enabled:
+            self._last = HealthReport(ts=ts_value)
+            return self._last
+
+        if image is None or getattr(image, "size", 0) == 0:
+            self._last = HealthReport(
+                ts=ts_value,
+                sensor_degraded=True,
+                perception_uncertain=True,
+                reasons=["no_image"],
+            )
+            return self._last
+
+        gray = image
+        if gray.ndim == 3:
+            if cv2 is not None:
+                gray = cv2.cvtColor(gray, cv2.COLOR_BGR2GRAY)
+            else:  # pragma: no cover - 无 OpenCV 时退化为亮度均值
+                gray = gray[..., :3].mean(axis=2).astype(np.uint8)
+        h, w = gray.shape[:2]
+        scale = min(1.0, float(self.p.work_width) / float(max(1, w)))
+        if cv2 is not None and scale < 1.0:
+            gray = cv2.resize(
+                gray, (int(round(w * scale)), int(round(h * scale))),
+                interpolation=cv2.INTER_AREA,
+            )
+
+        blur_var = 0.0
+        if cv2 is not None:
+            blur_var = float(cv2.Laplacian(gray, cv2.CV_64F).var())
+        total = float(max(1, gray.size))
+        dark = float(np.count_nonzero(gray <= 5)) / total
+        bright = float(np.count_nonzero(gray >= 250)) / total
+        low_texture = self._low_texture_ratio(gray)
+        motion_diff = self._motion_diff(gray)
+
+        reasons: List[str] = []
+        blur_bad = blur_var < self.p.blur_var_min and low_texture >= 0.65
+        dark_bad = dark >= self.p.dark_clip_ratio_max and low_texture >= 0.80
+        bright_bad = bright >= self.p.bright_clip_ratio_max and low_texture >= 0.80
+        flat_bad = low_texture >= self.p.low_texture_ratio_max
+        if blur_bad:
+            reasons.append("blur")
+        if dark_bad:
+            reasons.append("dark_clip")
+        if bright_bad:
+            reasons.append("bright_clip")
+        if flat_bad:
+            reasons.append("low_texture")
+        raw_bad = blur_bad or dark_bad or bright_bad or flat_bad
+
+        # 迟滞:连续 raw_bad 超过 degrade_persist_s 才报退化;恢复也要
+        # 连续正常 recover_persist_s,避免雨滴/飞虫造成逐帧抖动。
+        if raw_bad:
+            if self._bad_since is None:
+                self._bad_since = ts_value
+            self._good_since = None
+            if ts_value - self._bad_since >= self.p.degrade_persist_s:
+                self._degraded = True
+        else:
+            self._bad_since = None
+            if self._good_since is None:
+                self._good_since = ts_value
+            if ts_value - self._good_since >= self.p.recover_persist_s:
+                self._degraded = False
+
+        self._last = HealthReport(
+            ts=ts_value,
+            sensor_degraded=bool(self._degraded),
+            perception_uncertain=bool(self._degraded),
+            blur_var=blur_var,
+            dark_clip_ratio=dark,
+            bright_clip_ratio=bright,
+            low_texture_ratio=low_texture,
+            motion_diff=motion_diff,
+            reasons=reasons if self._degraded else [],
+        )
+        return self._last
+
+    # ---------------------------------------------------------------- 内部
+    @staticmethod
+    def _low_texture_ratio(gray: np.ndarray) -> float:
+        h, w = gray.shape[:2]
+        block = 16
+        if h < block or w < block:
+            return 1.0 if float(np.std(gray)) < 3.5 else 0.0
+        hh = (h // block) * block
+        ww = (w // block) * block
+        blocks = gray[:hh, :ww].reshape(hh // block, block, ww // block, block)
+        stds = blocks.std(axis=(1, 3))
+        return float(np.mean(stds < 3.5))
+
+    def _motion_diff(self, gray: np.ndarray) -> float:
+        thumb = gray
+        if cv2 is not None:
+            thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA)
+        if self._prev_thumb is None or self._prev_thumb.shape != thumb.shape:
+            self._prev_thumb = thumb.astype(np.uint8, copy=True)
+            return 0.0
+        diff = float(
+            np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean()
+        )
+        self._prev_thumb = thumb.astype(np.uint8, copy=True)
+        return diff if math.isfinite(diff) else 0.0
+

+ 20 - 0
portcv/io/__init__.py

@@ -0,0 +1,20 @@
+"""输入输出层:取帧与帧缓冲。"""
+
+from .capture import Frame, FrameGrabber, ImageSequence, open_capture
+from .synthetic import SyntheticGrabber
+
+__all__ = ["Frame", "FrameGrabber", "ImageSequence", "SyntheticGrabber", "build_grabber", "open_capture"]
+
+
+def build_grabber(cfg):
+    """按 ``source.type`` 造抓帧器:``synthetic`` 用合成帧,其余走 :class:`FrameGrabber`。
+
+    有了这个工厂,``python -m portcv run --source synthetic`` 就能在没有相机/视频的
+    机器上演示整条链路(含 PLC 发布),配置文件里只要把 ``source.type`` 改成 ``synthetic``。
+    """
+
+    source_type = str(cfg.get_path("source.type", "file")).lower()
+    if source_type == "synthetic":
+        return SyntheticGrabber(cfg, fps=float(cfg.get_path("source.fps", 25.0) or 25.0))
+    return FrameGrabber(cfg)
+

+ 268 - 0
portcv/io/capture.py

@@ -0,0 +1,268 @@
+"""取帧模块:相机/视频/RTSP 统一入口 + "只保留最新帧"的抓帧线程。
+
+为什么要单独做抓帧线程?
+------------------------
+``cv2.VideoCapture.read()`` 会按 GOP 依次吐帧,如果主循环(推理)比取帧慢,
+缓冲区会累积到几秒延迟——对吊装这种"要快"的场景是不可接受的。
+:class:`FrameGrabber` 在后台线程里持续读帧并**只保留最后一帧**,主循环永远拿到
+最新画面,延迟被限制在一次推理耗时内。
+
+支持 ``file`` / ``images`` / ``usb`` / ``rtsp`` / ``gst`` 五种源,
+Jetson 与 RK 上都可以直接用 GStreamer 硬件解码管线(``source.use_gst`` 或 ``type=gst``)。
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+import time
+from dataclasses import dataclass
+from glob import glob
+from typing import List, Optional, Tuple
+
+import numpy as np
+
+from ..config import Config
+
+__all__ = ["Frame", "FrameGrabber", "ImageSequence", "imread_any", "open_capture"]
+
+try:  # pragma: no cover
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+
+@dataclass
+class Frame:
+    """一帧画面及其时间戳。``frame_id`` 单调递增,便于丢帧统计。"""
+
+    image: np.ndarray
+    ts: float
+    frame_id: int
+
+    @property
+    def size(self) -> Tuple[int, int]:
+        height, width = self.image.shape[:2]
+        return (int(width), int(height))
+
+
+def imread_any(path: str, flags: Optional[int] = None) -> Optional[np.ndarray]:
+    """读一张图片,**支持非 ASCII 路径**。
+
+    ``cv2.imread`` 在 Windows 上把路径当 ANSI 解释:目录名只要含中文(例如交付目录
+    ``正面吊``)就会静默返回 ``None``,表现为「素材明明在、却读不到帧」。
+    这里改成先按字节读文件、再 ``imdecode``,语义与 ``imread`` 等价且与路径编码无关;
+    Linux 上同样适用(无副作用)。
+    """
+
+    if cv2 is None:
+        raise RuntimeError("需要 opencv-python: pip install opencv-python")
+    try:
+        buf = np.fromfile(path, dtype=np.uint8)
+    except OSError:
+        return None
+    if buf.size == 0:
+        return None
+    flag = cv2.IMREAD_COLOR if flags is None else int(flags)
+    return cv2.imdecode(buf, flag)
+
+
+def open_capture(uri: str, use_gst: bool = False, buffer_size: int = 2):
+    """打开视频源。``uri`` 可以是文件路径、``rtsp://...``、GStreamer 管线或相机序号。"""
+
+    if cv2 is None:
+        raise RuntimeError("需要 opencv-python: pip install opencv-python")
+    backend = cv2.CAP_ANY
+    target: object = uri
+    if isinstance(uri, str) and uri.isdigit():
+        target = int(uri)
+    if use_gst:
+        try:
+            backend = cv2.CAP_GSTREAMER
+        except AttributeError:  # pragma: no cover
+            backend = cv2.CAP_ANY
+    cap = cv2.VideoCapture(target, backend)
+    if buffer_size and hasattr(cv2, "CAP_PROP_BUFFERSIZE"):
+        cap.set(cv2.CAP_PROP_BUFFERSIZE, int(buffer_size))
+    return cap
+
+
+class ImageSequence:
+    """把图片文件夹当作视频源(现场离线复盘常用)。"""
+
+    def __init__(self, folder: str, pattern: str = "*.jpg") -> None:
+        files: List[str] = []
+        for ext in (pattern, "*.png", "*.jpeg", "*.bmp"):
+            files.extend(glob(os.path.join(folder, ext)))
+        self.files = sorted(set(files))
+        self._cursor = 0
+
+    def __len__(self) -> int:
+        return len(self.files)
+
+    def read(self) -> Optional[np.ndarray]:
+        if not self.files:
+            return None
+        if cv2 is None:
+            raise RuntimeError("需要 opencv-python: pip install opencv-python")
+        path = self.files[self._cursor % len(self.files)]
+        self._cursor += 1
+        image = imread_any(path)
+        return image
+
+
+class FrameGrabber:
+    """后台抓帧线程:永远只保留最新一帧,附时间戳与自增 ``frame_id``。"""
+
+    def __init__(self, cfg: Config) -> None:
+        self.cfg = cfg
+        source = cfg.section("source")
+        self.source_type = str(source.get("type", "file")).lower()
+        self.uri = str(source.get("uri", ""))
+        self.use_gst = bool(source.get("use_gst", False))
+        self.buffer_size = int(source.get("buffer_size", 2) or 0)
+        self.reconnect_s = float(source.get("reconnect_s", 2.0))
+        self.width = int(source.get("width", 0) or 0)
+        self.height = int(source.get("height", 0) or 0)
+        self.stale_frame_s = float(source.get("stale_frame_s", 0.6))
+
+        self._lock = threading.Lock()
+        self._stop = threading.Event()
+        self._thread: Optional[threading.Thread] = None
+        self._frame: Optional[Frame] = None
+        self._cap = None
+        self._sequence: Optional[ImageSequence] = None
+        self._frame_id = 0
+        self._fps = 0.0
+        self._failures = 0
+        self._opened = False
+        self._last_grab_ts = 0.0
+
+    # ------------------------------------------------------------ 生命周期
+    def start(self) -> "FrameGrabber":
+        if self._thread is not None:
+            return self
+        self._open()
+        self._thread = threading.Thread(target=self._loop, name="frame-grabber", daemon=True)
+        self._thread.start()
+        return self
+
+    def stop(self, timeout: float = 2.0) -> None:
+        self._stop.set()
+        if self._thread is not None:
+            self._thread.join(timeout=timeout)
+            self._thread = None
+        self._release()
+
+    # ------------------------------------------------------------ 打开/释放
+    def _open(self) -> bool:
+        self._release()
+        if self.source_type == "images":
+            self._sequence = ImageSequence(self.uri)
+            self._opened = bool(len(self._sequence))
+            return self._opened
+        if self.source_type in ("rtsp", "file", "usb", "gst") or self.uri:
+            gst = self.use_gst or self.source_type == "gst"
+            self._cap = open_capture(self.uri, use_gst=gst, buffer_size=self.buffer_size)
+            self._opened = bool(self._cap is not None and self._cap.isOpened())
+            if self._opened and self.width and self.height:
+                self._cap.set(cv2.CAP_PROP_FRAME_WIDTH, float(self.width))
+                self._cap.set(cv2.CAP_PROP_FRAME_HEIGHT, float(self.height))
+            return self._opened
+        return False
+
+    def _release(self) -> None:
+        if self._cap is not None:
+            try:
+                self._cap.release()
+            except Exception:  # pragma: no cover
+                pass
+            self._cap = None
+        self._opened = False
+
+    # ------------------------------------------------------------ 抓帧循环
+    def _loop(self) -> None:
+        while not self._stop.is_set():
+            if not self._opened:
+                if self._stop.wait(max(self.reconnect_s, 0.2)):
+                    break
+                self._open()
+                continue
+            grabbed = False
+            if self._sequence is not None:
+                image = self._sequence.read()
+                grabbed = image is not None
+            elif self._cap is not None:
+                ok, image = self._cap.read()
+                grabbed = bool(ok) and image is not None
+            else:
+                image = None
+            if grabbed:
+                self._frame_id += 1
+                self._failures = 0
+                now = time.time()
+                delta = now - self._last_grab_ts if self._last_grab_ts else 0.0
+                if delta > 0:
+                    inst = 1.0 / delta
+                    self._fps = inst if self._fps <= 0 else (0.8 * self._fps + 0.2 * inst)
+                self._last_grab_ts = now
+                with self._lock:
+                    self._frame = Frame(image=image, ts=now, frame_id=self._frame_id)
+            else:
+                self._failures += 1
+                if self.source_type in ("file", "images") and self._failures > 120:
+                    # 离线文件读到尾:短暂等待后重开,便于循环演示
+                    self._stop.wait(self.reconnect_s)
+                    self._open()
+                else:
+                    self._stop.wait(0.01)
+
+    # ------------------------------------------------------------ 读取
+    def read(self, timeout: float = 1.0) -> Optional[Frame]:
+        """取最新帧(非阻塞拷贝引用)。到 ``timeout`` 还没有帧则返回 ``None``。"""
+
+        deadline = time.time() + max(0.0, timeout)
+        while True:
+            with self._lock:
+                frame = self._frame
+            if frame is not None:
+                return frame
+            if time.time() >= deadline or self._stop.is_set():
+                return None
+            time.sleep(0.005)
+
+    @property
+    def latest(self) -> Optional[Frame]:
+        with self._lock:
+            return self._frame
+
+    @property
+    def fresh(self) -> bool:
+        """最近一帧是否足够新(用于 FRAME_TIMEOUT 判断)。"""
+
+        frame = self.latest
+        if frame is None:
+            return False
+        return (time.time() - frame.ts) <= self.stale_frame_s
+
+    @property
+    def fps(self) -> float:
+        return float(self._fps)
+
+    @property
+    def frame_id(self) -> int:
+        return int(self._frame_id)
+
+    @property
+    def opened(self) -> bool:
+        return bool(self._opened)
+
+    def describe(self) -> dict:
+        return {
+            "source_type": self.source_type,
+            "uri": self.uri,
+            "use_gst": self.use_gst,
+            "opened": self.opened,
+            "fps": round(self.fps, 2),
+        }
+

+ 149 - 0
portcv/io/synthetic.py

@@ -0,0 +1,149 @@
+"""合成帧源:没有相机/视频也能跑通整条链路(CI、自检、演示、PLC 联调)。
+
+接口与 :class:`~portcv.io.capture.FrameGrabber` 保持一致(``start/stop/latest/fresh/fps/
+frame_id/describe``),因此可以直接注入 :class:`~portcv.service.runner.RunService`
+替换真实抓帧器——这也是 ``portcv selftest`` 与单元测试能"零硬件"跑全链路的原因。
+
+画面里会画一个来回移动的矩形,配合 ``run.preview`` 一眼就能看出服务是否在跑。
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Dict, Optional, Tuple
+
+import numpy as np
+
+from ..config import Config
+from .capture import Frame
+
+__all__ = ["SyntheticGrabber"]
+
+
+class SyntheticGrabber:
+    """按固定帧率生成假画面的抓帧器(后台线程 + 只保留最新帧)。"""
+
+    def __init__(
+        self,
+        cfg: Optional[Config] = None,
+        fps: float = 25.0,
+        size: Tuple[int, int] = (1280, 720),
+        stale_frame_s: float = 0.6,
+        image: Optional[np.ndarray] = None,
+    ) -> None:
+        source = cfg.section("source") if cfg is not None else {}
+        self.fps_target = max(0.5, float(fps))
+        if cfg is not None and source.get("width") and source.get("height"):
+            size = (int(source["width"]), int(source["height"]))
+        self.size = (int(size[0]), int(size[1]))
+        self.stale_frame_s = float(
+            stale_frame_s if cfg is None else source.get("stale_frame_s", stale_frame_s)
+        )
+        self.use_fixed_image = image is not None
+
+        self._image = image if image is not None else self._make_background()
+        self._lock = threading.Lock()
+        self._stop = threading.Event()
+        self._thread: Optional[threading.Thread] = None
+        self._frame: Optional[Frame] = None
+        self._frame_id = 0
+        self._fps = 0.0
+        self._last_ts = 0.0
+        self._phase = 0.0
+
+    # ------------------------------------------------------------ 画面生成
+    def _make_background(self) -> np.ndarray:
+        width, height = self.size
+        rows = np.linspace(40, 200, height, dtype=np.uint8).reshape(height, 1)
+        cols = np.linspace(40, 120, width, dtype=np.uint8).reshape(1, width)
+        base = np.clip(rows.astype(np.int16) + cols.astype(np.int16), 0, 255).astype(np.uint8)
+        return np.dstack([base, base, base]).copy()
+
+    def _render(self) -> np.ndarray:
+        if self.use_fixed_image:
+            return self._image
+        image = self._image.copy()
+        height, width = image.shape[:2]
+        band_y = int(height * 0.62)
+        image[band_y:, :] = 90  # 车厢/地面
+        self._phase = (self._phase + 0.04) % 1.0
+        cx = int(width * (0.2 + 0.6 * self._phase))
+        half = int(width * 0.16)
+        half_h = int(height * 0.14)
+        cy = band_y - half_h
+        x1, x2 = max(0, cx - half), min(width - 1, cx + half)
+        y1, y2 = max(0, cy - half_h), min(height - 1, cy + half_h)
+        image[y1:y2, x1:x2] = (60, 140, 200)  # 集装箱
+        return image
+
+    # ------------------------------------------------------------ 生命周期
+    def start(self) -> "SyntheticGrabber":
+        if self._thread is not None:
+            return self
+        self._thread = threading.Thread(target=self._loop, name="synthetic-grabber", daemon=True)
+        self._thread.start()
+        return self
+
+    def stop(self, timeout: float = 2.0) -> None:
+        self._stop.set()
+        if self._thread is not None:
+            self._thread.join(timeout=timeout)
+            self._thread = None
+
+    def _loop(self) -> None:
+        period = 1.0 / self.fps_target
+        while not self._stop.is_set():
+            started = time.time()
+            image = self._render()
+            now = time.time()
+            self._frame_id += 1
+            delta = now - self._last_ts if self._last_ts else period
+            self._last_ts = now
+            inst = 1.0 / delta if delta > 0 else self.fps_target
+            self._fps = inst if self._fps <= 0 else 0.8 * self._fps + 0.2 * inst
+            with self._lock:
+                self._frame = Frame(image=image, ts=now, frame_id=self._frame_id)
+            self._stop.wait(max(0.0, period - (time.time() - started)))
+
+    # ------------------------------------------------------------ 兼容接口
+    @property
+    def latest(self) -> Optional[Frame]:
+        with self._lock:
+            return self._frame
+
+    @property
+    def fresh(self) -> bool:
+        frame = self.latest
+        return frame is not None and (time.time() - frame.ts) <= self.stale_frame_s
+
+    def read(self, timeout: float = 1.0) -> Optional[Frame]:
+        deadline = time.time() + max(0.0, timeout)
+        while True:
+            frame = self.latest
+            if frame is not None:
+                return frame
+            if time.time() >= deadline:
+                return None
+            time.sleep(0.005)
+
+    @property
+    def fps(self) -> float:
+        return float(self._fps)
+
+    @property
+    def frame_id(self) -> int:
+        return int(self._frame_id)
+
+    @property
+    def opened(self) -> bool:
+        return True
+
+    def describe(self) -> Dict[str, object]:
+        return {
+            "source_type": "synthetic",
+            "size": list(self.size),
+            "target_fps": self.fps_target,
+            "fps": round(self.fps, 2),
+            "frame_id": self.frame_id,
+        }

+ 85 - 0
portcv/logging_utils.py

@@ -0,0 +1,85 @@
+"""日志配置:现场调试看文本,上位机/日志采集看 JSON Lines。"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import sys
+import time
+from logging.handlers import TimedRotatingFileHandler
+from typing import Optional
+
+__all__ = ["setup_logging", "get_logger"]
+
+_CONFIGURED = False
+
+
+class _JsonFormatter(logging.Formatter):
+    """单行 JSON,方便现场把日志丢给 ELK/Loki 或 grep 状态变化。"""
+
+    def format(self, record: logging.LogRecord) -> str:  # noqa: D102
+        payload = {
+            "ts": round(record.created, 3),
+            "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created)),
+            "level": record.levelname,
+            "logger": record.name,
+            "msg": record.getMessage(),
+        }
+        extra = getattr(record, "extra_fields", None)
+        if isinstance(extra, dict):
+            payload.update(extra)
+        if record.exc_info:
+            payload["exc"] = self.formatException(record.exc_info)
+        return json.dumps(payload, ensure_ascii=False)
+
+
+def setup_logging(
+    level: str = "INFO",
+    json_mode: bool = False,
+    name: str = "portcv",
+    log_dir: Optional[str] = None,
+    retention_days: int = 90,
+) -> logging.Logger:
+    """初始化根 logger(幂等)。
+
+    ``log_dir`` 非空时,除 stdout 外再写 **按天轮转** 的 ``portcv.log``,
+    最多保留 ``retention_days`` 个备份(P0-4 的 90 天要求)。
+    """
+
+    global _CONFIGURED
+    logger = logging.getLogger(name)
+    formatter: logging.Formatter
+    if json_mode:
+        formatter = _JsonFormatter()
+    else:
+        formatter = logging.Formatter(
+            "%(asctime)s | %(levelname)-5s | %(name)s | %(message)s",
+            datefmt="%H:%M:%S",
+        )
+    if not _CONFIGURED:
+        handlers: list = [logging.StreamHandler(sys.stdout)]
+        if log_dir:
+            os.makedirs(log_dir, exist_ok=True)
+            file_handler = TimedRotatingFileHandler(
+                os.path.join(log_dir, "portcv.log"),
+                when="midnight",
+                backupCount=max(1, int(retention_days)),
+                encoding="utf-8",
+                delay=True,
+            )
+            file_handler.suffix = "%Y-%m-%d"
+            handlers.append(file_handler)
+        for handler in handlers:
+            handler.setFormatter(formatter)
+        root = logging.getLogger()
+        root.handlers = handlers
+        root.setLevel(getattr(logging, str(level).upper(), logging.INFO))
+        _CONFIGURED = True
+    else:
+        logging.getLogger().setLevel(getattr(logging, str(level).upper(), logging.INFO))
+    return logger
+
+
+def get_logger(suffix: Optional[str] = None) -> logging.Logger:
+    return logging.getLogger("portcv" if not suffix else "portcv.%s" % suffix)

+ 29 - 0
portcv/logic/__init__.py

@@ -0,0 +1,29 @@
+"""判定逻辑:几何、场景规则、时序防抖。"""
+
+from .commit import CommitParams, CommitState, CommitTracker
+from .decision import TemporalVoter
+from .evidence_v2 import EvidenceV2, EvidenceV2Params, EvidenceV2Result
+from .geometry import (
+    box_in_polygon_ratio,
+    nms,
+    normalized_to_pixel_polygon,
+    point_in_polygon,
+    polygon_area,
+)
+from .scene import SceneClassifier
+
+__all__ = [
+    "CommitParams",
+    "CommitState",
+    "CommitTracker",
+    "EvidenceV2",
+    "EvidenceV2Params",
+    "EvidenceV2Result",
+    "SceneClassifier",
+    "TemporalVoter",
+    "box_in_polygon_ratio",
+    "nms",
+    "normalized_to_pixel_polygon",
+    "point_in_polygon",
+    "polygon_area",
+]

+ 360 - 0
portcv/logic/commit.py

@@ -0,0 +1,360 @@
+"""P1c:落位(commit)相位判定。
+
+为什么需要单独的 commit 门
+---------------------------
+``evidence_v2`` 回答的是“这一帧看起来像 1 还是 2”;PLC 真正需要的是
+“**箱已经落到位,可以按这个车型执行落箱工艺**”。两者不能混为一谈:
+
+* A 片段(C70 敞车 + 罐箱)在 clip 结束时仍差 ≈0.2 m,但单帧间隙只有
+  9–12 px,按 0.10 m 的单一阈值可能误命中;
+* B 片段(X70 平车)落位帧间隙只有 3 px,必须允许提交。
+
+因此本模块用**组合条件**而不是单一阈值:
+
+1. ``gap_m <= gap_m_max``(默认 0.10 m);
+2. **安全硬门** ``gap_px <= gap_px_hard_max``(默认 8 px)——前视模式箱底
+   像素本身有 ±5 px 不确定度,0.10 m 在 115 px/m 下约 11.5 px;加这条
+   可以确保 A 的 9–12 px 不会提交,同时 B 的 3 px 仍能通过;
+3. 最近 ``stable_frames`` 帧状态一致、结构证据持续成立;
+4. 运动门控通过,间隙没有明显回升;
+5. 可选 PLC “到位 / 吊具松开”信号可**替代**间隙门(但仍需结构与稳定帧)。
+
+``allow_state2`` 默认 **True**(现场验收后已打开):平车 `2` 与 `1` 一样进入
+commit;置 false 可回退为“只识别、不提交”。顶层 ``evidence_v2.allow_state2``
+与 ``evidence_v2.commit.allow_state2`` 串联,任一 false 都会关闭提交。
+
+本模块不依赖 OpenCV / numpy,只做状态机;图像特征由
+:mod:`portcv.logic.evidence_v2` 提供。
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from dataclasses import dataclass
+from typing import Deque, Optional, Tuple
+
+from ..config import Config
+
+__all__ = [
+    "CommitParams",
+    "CommitState",
+    "CommitTracker",
+    "DEFAULT_GAP_M_MAX",
+    "DEFAULT_GAP_PX_HARD_MAX",
+]
+
+#: 路线文档锁定的间隙门(米)。
+DEFAULT_GAP_M_MAX = 0.10
+#: 前视箱底像素不确定度对应的安全硬门(≈0.07 m @ 115 px/m)。
+DEFAULT_GAP_PX_HARD_MAX = 8.0
+#: 箱底与车面直接贴合(flat_contact 归零)的容差;该分支不要求 px_per_m。
+CONTACT_GAP_PX = 1.0
+
+
+@dataclass(frozen=True)
+class CommitParams:
+    """commit 门参数(对应配置段 ``evidence_v2.commit.*``)。"""
+
+    gap_m_max: float = DEFAULT_GAP_M_MAX
+    gap_px_hard_max: float = DEFAULT_GAP_PX_HARD_MAX
+    stable_frames: int = 5
+    structure_frames: int = 5
+    min_structure_hits: float = 0.60
+    max_gap_rise_m: float = 0.01
+    allow_state1: bool = True
+    allow_state2: bool = True
+    require_motion_ok: bool = True
+    require_view_known: bool = True
+    use_plc_arrival: bool = True
+
+    def __post_init__(self) -> None:
+        if self.gap_m_max < 0.0:
+            raise ValueError("gap_m_max 不能为负")
+        if self.gap_px_hard_max < 0.0:
+            raise ValueError("gap_px_hard_max 不能为负")
+        if self.stable_frames < 1:
+            raise ValueError("stable_frames 至少为 1")
+        if self.structure_frames < 1:
+            raise ValueError("structure_frames 至少为 1")
+        if not 0.0 <= self.min_structure_hits <= 1.0:
+            raise ValueError("min_structure_hits 必须在 0..1")
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "CommitParams":
+        section = cfg.section("evidence_v2")
+        raw = section.get("commit") or {}
+        # 与 C++ `apply_evidence_v2` 同口径:顶层与 commit 两个开关串联,任一 false 即关闭。
+        allow_state2 = bool(raw.get("allow_state2", True)) and bool(
+            section.get("allow_state2", True)
+        )
+        return cls(
+            gap_m_max=float(raw.get("gap_m_max", DEFAULT_GAP_M_MAX)),
+            gap_px_hard_max=float(raw.get("gap_px_hard_max", DEFAULT_GAP_PX_HARD_MAX)),
+            stable_frames=int(raw.get("stable_frames", 5)),
+            structure_frames=int(raw.get("structure_frames", 5)),
+            min_structure_hits=float(raw.get("min_structure_hits", 0.60)),
+            max_gap_rise_m=float(raw.get("max_gap_rise_m", 0.01)),
+            allow_state1=bool(raw.get("allow_state1", True)),
+            allow_state2=allow_state2,
+            require_motion_ok=bool(raw.get("require_motion_ok", True)),
+            require_view_known=bool(raw.get("require_view_known", True)),
+            use_plc_arrival=bool(raw.get("use_plc_arrival", True)),
+        )
+
+
+@dataclass(frozen=True)
+class CommitState:
+    """``CommitTracker.update()`` 的输出(可直接写进 evidence 诊断)。"""
+
+    committed: bool
+    phase: str                 # T1 / T2 / T3
+    reason: str
+    gap_m: Optional[float] = None
+    gap_px: Optional[float] = None
+    stable_frames: int = 0
+    structure_frames: int = 0
+    gap_slope_m_per_s: Optional[float] = None
+    plc_arrival: bool = False
+    hoist_high: bool = False
+
+    def to_dict(self) -> dict:
+        return {
+            "committed": bool(self.committed),
+            "phase": self.phase,
+            "reason": self.reason,
+            "gap_m": None if self.gap_m is None else round(float(self.gap_m), 4),
+            "gap_px": None if self.gap_px is None else round(float(self.gap_px), 2),
+            "stable_frames": int(self.stable_frames),
+            "structure_frames": int(self.structure_frames),
+            "gap_slope_m_per_s": (
+                None if self.gap_slope_m_per_s is None
+                else round(float(self.gap_slope_m_per_s), 4)
+            ),
+            "plc_arrival": bool(self.plc_arrival),
+            "hoist_high": bool(self.hoist_high),
+        }
+
+
+@dataclass
+class _Sample:
+    ts: float
+    state: int
+    gap_m: Optional[float]
+    gap_px: Optional[float]
+    structure_ok: bool
+    motion_ok: bool
+
+
+class CommitTracker:
+    """有状态的 commit 判定器(线程内使用、非线程安全)。"""
+
+    def __init__(self, params: Optional[CommitParams] = None) -> None:
+        self.p = params or CommitParams()
+        self._samples: Deque[_Sample] = deque(maxlen=256)
+        self._last_ts = 0.0
+        self._last = CommitState(False, "T1", "init")
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "CommitTracker":
+        return cls(CommitParams.from_config(cfg))
+
+    @property
+    def params(self) -> CommitParams:
+        return self.p
+
+    @property
+    def last(self) -> CommitState:
+        return self._last
+
+    def reset(self) -> None:
+        self._samples.clear()
+        self._last_ts = 0.0
+        self._last = CommitState(False, "T1", "reset")
+
+    # ---------------------------------------------------------------- 主入口
+    def update(
+        self,
+        ts: float,
+        *,
+        state: int,
+        gap_m: Optional[float],
+        gap_px: Optional[float],
+        structure_hits: float = 1.0,
+        motion_ok: bool = True,
+        view_known: bool = True,
+        plc_arrived: bool = False,
+        plc_spreader_released: bool = False,
+        hoist_high: bool = False,
+    ) -> CommitState:
+        """喂入一帧证据,返回是否允许提交。
+
+        ``state`` 是 ``evidence_v2`` 的**单帧分类结果**(0/1/2/255);
+        ``structure_hits`` 是该帧结构证据强度(0..1),不是像素计数。
+        ``hoist_high`` 表示画面出现吊具/钢缆/臂架高悬特征:箱体尚未落位,
+        无论间隙看起来多小都不得提交(安全门优先于所有几何门)。
+        """
+
+        now = float(ts)
+        if now < self._last_ts:
+            now = self._last_ts
+        self._last_ts = now
+
+        state = int(state)
+        structure_ok = float(structure_hits) >= self.p.min_structure_hits
+        arrival = bool(
+            self.p.use_plc_arrival and (plc_arrived or plc_spreader_released)
+        )
+
+        # 安全门:吊具/钢缆/臂架仍在画面上方,说明箱体未落位。即使视觉
+        # 把箱侧壁误当成车斗门板、算出“零间隙”,也不得累计 commit 帧。
+        # 这一分支不写 _samples,避免高悬消失后立刻复用之前的窗口。
+        if hoist_high:
+            self._last = CommitState(
+                False, "T3", "hoist_high", gap_m, gap_px, 0, 0, None, arrival, True
+            )
+            return self._last
+
+        if state not in (0, 1, 2):
+            self._last = CommitState(
+                False, "T3" if not motion_ok else "T1", "state_unknown",
+                gap_m, gap_px, 0, 0, None, arrival,
+            )
+            return self._last
+
+        if state == 1 and not self.p.allow_state1:
+            self._last = CommitState(False, "T1", "state1_disabled",
+                                     gap_m, gap_px, 0, 0, None, arrival)
+            return self._last
+        if state == 2 and not self.p.allow_state2:
+            # 平车在 PLC 签字前只识别、不提交;仍记录窗口,便于诊断。
+            self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
+            self._last = CommitState(False, "T1", "state2_disabled",
+                                     gap_m, gap_px, 0, 0, None, arrival)
+            return self._last
+
+        self._append(now, state, gap_m, gap_px, structure_ok, motion_ok)
+
+        if not motion_ok and self.p.require_motion_ok:
+            self._last = CommitState(False, "T3", "motion", gap_m, gap_px,
+                                     0, 0, None, arrival)
+            return self._last
+        if not view_known and self.p.require_view_known:
+            self._last = CommitState(False, "T1", "view_unknown", gap_m, gap_px,
+                                     0, 0, None, arrival)
+            return self._last
+
+        # 0 是“其他/不在车上”,不需要间隙门;仍需稳定帧与正面证据。
+        gap_ok = True
+        if state in (1, 2):
+            if arrival:
+                gap_ok = True
+            else:
+                contact = gap_px is not None and float(gap_px) <= CONTACT_GAP_PX
+                gap_ok = (
+                    gap_px is not None
+                    and float(gap_px) <= self.p.gap_px_hard_max
+                    and (
+                        contact
+                        or (
+                            gap_m is not None
+                            and float(gap_m) <= self.p.gap_m_max
+                        )
+                    )
+                )
+
+        window = self._window(max(self.p.stable_frames, self.p.structure_frames))
+        stable_n = self._same_state_run(state)
+        structure_n = sum(1 for s in window if s.structure_ok)
+        gap_n = sum(1 for s in window if self._gap_ok(s, arrival))
+        slope = self._gap_slope(window)
+
+        stable_enough = stable_n >= self.p.stable_frames
+        structure_enough = structure_n >= self.p.structure_frames
+        gap_enough = gap_n >= self.p.stable_frames
+        not_rising = slope is None or slope <= self.p.max_gap_rise_m
+
+        phase = "T2" if gap_ok else "T1"
+        committed = bool(
+            gap_ok and stable_enough and structure_enough and gap_enough and not_rising
+        )
+
+        reason_parts = []
+        if not gap_ok:
+            reason_parts.append("gap")
+        if not stable_enough:
+            reason_parts.append("stable=%d/%d" % (stable_n, self.p.stable_frames))
+        if not structure_enough:
+            reason_parts.append("structure=%d/%d" % (structure_n, self.p.structure_frames))
+        if not gap_enough:
+            reason_parts.append("gap_window=%d/%d" % (gap_n, self.p.stable_frames))
+        if not not_rising:
+            reason_parts.append("gap_rising")
+        reason = "commit" if committed else (
+            "wait:" + ",".join(reason_parts) if reason_parts else "wait"
+        )
+        if arrival and committed:
+            reason = "commit:plc_arrival"
+
+        self._last = CommitState(
+            committed=committed,
+            phase=phase,
+            reason=reason,
+            gap_m=gap_m,
+            gap_px=gap_px,
+            stable_frames=int(stable_n),
+            structure_frames=int(structure_n),
+            gap_slope_m_per_s=slope,
+            plc_arrival=arrival,
+        )
+        return self._last
+
+    # ---------------------------------------------------------------- 内部
+    def _append(
+        self,
+        ts: float,
+        state: int,
+        gap_m: Optional[float],
+        gap_px: Optional[float],
+        structure_ok: bool,
+        motion_ok: bool,
+    ) -> None:
+        self._samples.append(
+            _Sample(ts, int(state), gap_m, gap_px, bool(structure_ok), bool(motion_ok))
+        )
+
+    def _window(self, n: int) -> Tuple[_Sample, ...]:
+        if n <= 0:
+            return tuple()
+        return tuple(list(self._samples)[-n:])
+
+    def _same_state_run(self, state: int) -> int:
+        count = 0
+        for sample in reversed(self._samples):
+            if sample.state != int(state):
+                break
+            count += 1
+        return count
+
+    def _gap_ok(self, sample: _Sample, arrival: bool) -> bool:
+        if sample.state == 0 or arrival:
+            return True
+        if sample.gap_px is None or float(sample.gap_px) > self.p.gap_px_hard_max:
+            return False
+        # 零间隙 = 已直接接触:没有 px_per_m 时 gap_m 为空,不能因此拒绝。
+        if float(sample.gap_px) <= CONTACT_GAP_PX:
+            return True
+        return bool(
+            sample.gap_m is not None
+            and float(sample.gap_m) <= self.p.gap_m_max
+        )
+
+    def _gap_slope(self, window: Tuple[_Sample, ...]) -> Optional[float]:
+        points = [(s.ts, s.gap_m) for s in window if s.gap_m is not None]
+        if len(points) < 2:
+            return None
+        t0, g0 = points[0]
+        t1, g1 = points[-1]
+        dt = float(t1) - float(t0)
+        if dt <= 1e-6:
+            return None
+        return (float(g1) - float(g0)) / dt

+ 230 - 0
portcv/logic/decision.py

@@ -0,0 +1,230 @@
+"""时序防抖:把逐帧观测稳定成可直接下发给 PLC 的判决。
+
+现场难点
+--------
+* 吊具/箱子在动,单帧结果会跳(尤其"车斗/平板车"边界模糊时);
+* 起重机振动、逆光、雨雾会造成偶发漏检;
+* PLC 需要的是"稳定、可联锁"的结果,而不是每帧都变的状态码。
+
+因此这里做三件事:
+
+1. **滑窗投票**:最近 ``window`` 帧(或 ``window_s`` 秒)内同一状态票数达到
+   ``min_votes`` 且平均置信度达到 ``min_confidence`` 才算候选;
+2. **最小驻留**:候选状态要连续保持 ``min_dwell_s`` 才真正提交,避免毛刺。
+   **冷启动的 UNKNOWN 也走同一套门限**:首帧、复位后的第一帧都不得直接 commit,
+   必须等票数与驻留同时满足;否则跟踪器一上电就可能把单帧误检当成结果送给 PLC。
+3. **保持/丢失**:短暂没有有效观测时先保持上一状态(``hold_s``,此时 ``stable=False``
+   提示 PLC "别动作"),超过 ``lost_timeout_s`` 才置 ``UNKNOWN``(PLC 应回安全逻辑)。
+
+状态每次提交变化时 ``seq + 1``,PLC 用它判断"是否有新结果"。
+"""
+
+from __future__ import annotations
+
+import time
+from collections import deque
+from typing import Deque, Dict, List, Optional, Tuple
+
+from ..config import Config
+from ..schema import Decision, Observation, SceneState, STATE_LABELS
+
+__all__ = ["TemporalVoter"]
+
+
+class TemporalVoter:
+    """滑窗投票 + 最小驻留 + 保持/丢失超时。"""
+
+    def __init__(
+        self,
+        window: int = 9,
+        window_s: float = 1.0,
+        min_votes: int = 4,
+        min_confidence: float = 0.45,
+        min_dwell_s: float = 0.20,
+        hold_s: float = 0.60,
+        lost_timeout_s: float = 1.50,
+    ) -> None:
+        self.window = max(1, int(window))
+        self.window_s = max(0.0, float(window_s))
+        self.min_votes = max(1, int(min_votes))
+        self.min_confidence = float(min_confidence)
+        self.min_dwell_s = max(0.0, float(min_dwell_s))
+        self.hold_s = max(0.0, float(hold_s))
+        self.lost_timeout_s = max(self.hold_s, float(lost_timeout_s))
+
+        self._obs: Deque[Tuple[float, int, float]] = deque(maxlen=self.window)
+        self._state: int = int(SceneState.UNKNOWN)
+        self._conf: float = 0.0
+        self._since: float = 0.0
+        self._seq: int = 0
+        self._reason: str = "init"
+        self._last_ts: float = 0.0
+        self._last_valid_ts: float = 0.0
+        self._pending: Optional[int] = None
+        self._pending_since: float = 0.0
+        self._commits: Dict[int, int] = {}
+
+    # ------------------------------------------------------------- 构造
+    @classmethod
+    def from_config(cls, cfg: Config) -> "TemporalVoter":
+        d = cfg.section("decision")
+        return cls(
+            window=d.get("window", 9),
+            window_s=d.get("window_s", 1.0),
+            min_votes=d.get("min_votes", 4),
+            min_confidence=d.get("min_confidence", 0.45),
+            min_dwell_s=d.get("min_dwell_s", 0.20),
+            hold_s=d.get("hold_s", 0.60),
+            lost_timeout_s=d.get("lost_timeout_s", 1.50),
+        )
+
+    # ------------------------------------------------------------- 属性
+    @property
+    def state(self) -> int:
+        return self._state
+
+    @property
+    def seq(self) -> int:
+        return self._seq
+
+    @property
+    def commit_counts(self) -> Dict[int, int]:
+        return {STATE_LABELS.get(k, str(k)): v for k, v in self._commits.items()}
+
+    def reset(self) -> None:
+        """复位到初始状态(PLC 下复位命令或重连时调用)。"""
+
+        self._obs.clear()
+        self._state = int(SceneState.UNKNOWN)
+        self._conf = 0.0
+        self._since = 0.0
+        self._reason = "reset"
+        self._pending = None
+        self._pending_since = 0.0
+
+    # ------------------------------------------------------------- 主入口
+    def update(self, obs: Observation) -> Decision:
+        """喂入一帧观测,返回当前判决。"""
+
+        ts = float(obs.ts)
+        if ts < self._last_ts:  # 时钟回拨/乱序,夹紧保证单调
+            ts = self._last_ts
+        self._last_ts = ts
+
+        valid = obs.is_valid and float(obs.confidence) >= self.min_confidence
+        if valid:
+            self._obs.append((ts, int(obs.state), float(obs.confidence)))
+            self._last_valid_ts = ts
+        self._prune(ts)
+
+        candidate, cand_conf = self._vote()
+        changed = False
+        reason = obs.reason
+
+        if candidate is None:
+            # 没有可信候选:先保持,再超时置 UNKNOWN
+            gap = ts - self._last_valid_ts if self._last_valid_ts > 0 else ts
+            if self._state != int(SceneState.UNKNOWN) and gap > self.lost_timeout_s:
+                changed = self._commit(int(SceneState.UNKNOWN), 0.0, ts, "lost_timeout")
+            elif self._state != int(SceneState.UNKNOWN) and gap > self.hold_s:
+                self._reason = "hold(lost=%.2fs)" % gap
+            else:
+                self._reason = obs.reason or "no_candidate"
+        elif candidate == self._state:
+            self._pending = None
+            self._conf = cand_conf
+            if obs.reason:
+                self._reason = obs.reason
+        else:
+            # 候选与当前状态不同:需要连续驻留 min_dwell_s。
+            # 注意:这里**不再**给 UNKNOWN 开绿灯。冷启动/复位后的第一帧可能
+            # 只有一个观测,单帧误检(如箱侧壁被当成车斗门板)必须在驻留门
+            # 之前就被挡住,不能直接 commit 给 PLC。
+            if self._pending != candidate:
+                self._pending = candidate
+                self._pending_since = self._candidate_since(candidate, ts)
+            if (
+                ts - self._pending_since >= self.min_dwell_s
+                and ts > self._pending_since
+                and len(self._obs) >= 2
+            ):
+                changed = self._commit(candidate, cand_conf, ts, obs.reason or "vote")
+
+        stable = (
+            self._state != int(SceneState.UNKNOWN)
+            and (ts - self._since) >= self.min_dwell_s
+            and (ts - self._last_valid_ts) <= self.hold_s
+        )
+        return Decision(
+            state=int(self._state),
+            confidence=float(self._conf),
+            stable=bool(stable),
+            seq=int(self._seq),
+            since_ts=float(self._since),
+            reason=self._reason,
+            changed=bool(changed),
+        )
+
+    # ------------------------------------------------------------- 内部
+    def _prune(self, now: float) -> None:
+        if self.window_s <= 0:
+            return
+        while self._obs and (now - self._obs[0][0]) > self.window_s:
+            self._obs.popleft()
+
+    def _vote(self) -> Tuple[Optional[int], float]:
+        """滑窗投票。返回 ``(状态, 平均置信度)``;票数不足返回 ``(None, 0)``。"""
+
+        if not self._obs:
+            return None, 0.0
+        stats: Dict[int, List[float]] = {}
+        for _ts, state, conf in self._obs:
+            stats.setdefault(int(state), []).append(float(conf))
+        best_state = max(stats.keys(), key=lambda s: (len(stats[s]), sum(stats[s])))
+        confs = stats[best_state]
+        required = min(self.min_votes, len(self._obs))
+        if len(confs) < required:
+            return None, 0.0
+        return int(best_state), float(sum(confs) / len(confs))
+
+    def _candidate_since(self, candidate: int, now: float) -> float:
+        """候选状态在窗口内连续出现的最早时间戳(没有则用 now)。"""
+
+        since = now
+        for ts, state, _conf in reversed(self._obs):
+            if int(state) != int(candidate):
+                break
+            since = ts
+        return since
+
+    def _commit(self, state: int, conf: float, ts: float, reason: str) -> bool:
+        changed = int(state) != int(self._state)
+        if changed:
+            self._state = int(state)
+            self._since = ts
+            self._seq += 1
+            self._commits[int(state)] = self._commits.get(int(state), 0) + 1
+        self._conf = float(conf)
+        self._reason = reason or self._reason
+        self._pending = None
+        return changed
+
+    def current(self) -> Decision:
+        """不喂新观测,取当前判决(用于心跳发布)。"""
+
+        now = self._last_ts or time.time()
+        stable = (
+            self._state != int(SceneState.UNKNOWN)
+            and (now - self._since) >= self.min_dwell_s
+            and (now - self._last_valid_ts) <= self.hold_s
+        )
+        return Decision(
+            state=int(self._state),
+            confidence=float(self._conf),
+            stable=bool(stable),
+            seq=int(self._seq),
+            since_ts=float(self._since),
+            reason=self._reason,
+            changed=False,
+        )
+

+ 1216 - 0
portcv/logic/evidence_v2.py

@@ -0,0 +1,1216 @@
+"""P1b:前视 v2 结构证据(箱底以下的门板 / 边梁 / 地面)。
+
+设计依据
+--------
+``docs/route_v2.md`` §2–§4 与 P0 实测(``docs/evidence/p0_v2``):
+
+* **1(敞车)**:箱底以下是一整面不透明侧墙,门板立柱 ``8–14`` 根、
+  立柱间距有规律,斜撑/矩形门可作加分;
+* **2(平车)**:箱底以下只有薄车面边梁,下方透空,能看到地面/植被;
+  门板立柱 ``0–4`` 根;
+* **0(其他)**:只有连续地面,既无门板阵列也无可信车面边梁。
+
+与 v1 的区别
+-------------
+v1 用固定高位带(箱底以上 0.55–0.85 箱高)找围挡,方向是错的;本模块
+**只在箱底以下**取证,ROI 的 y 起点跟随每帧箱底下沿,不再使用
+``y=475..619`` 的固定带。单帧输出只是“候选”,是否允许提交给 PLC 由
+:mod:`portcv.logic.commit` 的 T2 门决定。
+
+工程约束
+--------
+* 运行期依赖 ``numpy`` + ``opencv-python``(取流层本来就需要 OpenCV);
+* 所有几何量用**原图像素**输出,内部按 ``work_width`` 缩放;
+* 单帧确定性:不使用随机数,Hough 参数固定;
+* 看不清一律内部 255,绝不硬判 2。
+"""
+
+from __future__ import annotations
+
+import math
+import statistics
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Sequence, Tuple
+
+import numpy as np
+
+try:  # pragma: no cover - 无 OpenCV 时给出明确错误,而不是静默降级
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+from ..config import Config
+from ..schema import Box, CommitPhase, Observation, SceneState, ViewMode
+from .commit import CommitState, CommitTracker
+
+__all__ = [
+    "Band",
+    "EvidenceV2",
+    "EvidenceV2Params",
+    "EvidenceV2Result",
+    "detect_hoist_high",
+    "detect_spreader_contact",
+    "detect_structure_v2",
+    "ground_like_ratio",
+    "horizontal_bands",
+    "pick_box_and_bed",
+]
+
+Point = Tuple[float, float]
+
+
+@dataclass(frozen=True)
+class Band:
+    """水平亮带/暗带(原图像素坐标)。"""
+
+    y0: float
+    y1: float
+    strength: float
+
+    @property
+    def height(self) -> float:
+        return max(0.0, self.y1 - self.y0)
+
+
+@dataclass(frozen=True)
+class EvidenceV2Params:
+    """``evidence_v2.*`` 配置(与 ``configs/edge-v2-front.json`` 同名同义)。"""
+
+    enabled: bool = False
+    view: ViewMode = ViewMode.FRONT
+    work_width: int = 960
+    window: Tuple[float, float, float, float] = (0.24, 0.02, 0.78, 0.95)
+    band_min_h: int = 3
+    band_max_h_ratio: float = 0.15
+    bed_search_ratio: float = 0.40
+    box_bottom_max_ratio: float = 0.78
+    below_start_ratio: float = 0.07
+    below_height_ratio: float = 0.55
+    below_min_height_px: int = 24
+    min_door_posts: int = 5
+    max_door_posts: int = 16
+    max_bed_gap_px: float = 40.0
+    flat_max_door_posts: int = 4
+    max_post_spacing_cv: float = 6.0
+    min_post_len_ratio: float = 0.30
+    min_wall_opacity: float = 0.35
+    max_flat_gap_px: float = 40.0
+    wall_edge_density_ref: float = 0.14
+    wall_edge_density_span: float = 0.04
+    ground_block_px: int = 32
+    ground_density_lo: float = 0.02
+    ground_density_hi: float = 0.35
+    min_flat_ground_ratio: float = 0.40
+    min_zero_ground_ratio: float = 0.65
+    deck_min_len_ratio: float = 0.30
+    box_height_m: float = 2.591
+    px_per_m: float = 0.0
+    min_scale_px: float = 60.0
+    motion_diff_max: float = 12.0
+    motion_grad_ratio_min: float = 0.72
+    require_commit: bool = True
+    allow_state2: bool = True
+    structure_hits_min: float = 0.60
+    # P0-0:吊具/钢缆/臂架高悬安全门(默认开)。只在箱体上方区域找
+    # “长横线 + 上方暗带 + 下方更亮”的组合;宁可弃权,不可把悬空箱
+    # 当成已落位。
+    reject_hoist_high: bool = True
+    hoist_dark_max: int = 75
+    hoist_band_frac: float = 0.035
+    hoist_line_ratio: float = 0.20
+    hoist_dark_ratio: float = 0.55
+    hoist_bright_delta: float = 12.0
+
+    def __post_init__(self) -> None:
+        if self.work_width < 160:
+            raise ValueError("work_width 至少 160")
+        if self.band_min_h < 1:
+            raise ValueError("band_min_h 至少 1")
+        if not 0.0 < self.band_max_h_ratio <= 1.0:
+            raise ValueError("band_max_h_ratio 必须在 (0,1]")
+        if self.bed_search_ratio <= 0.0:
+            raise ValueError("bed_search_ratio 必须为正")
+        if self.below_height_ratio <= 0.0:
+            raise ValueError("below_height_ratio 必须为正")
+        if self.min_door_posts < 1:
+            raise ValueError("min_door_posts 至少 1")
+        if self.box_height_m <= 0.0:
+            raise ValueError("box_height_m 必须为正")
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "EvidenceV2Params":
+        raw = cfg.section("evidence_v2")
+        window = raw.get("window") or [0.24, 0.02, 0.78, 0.95]
+        if len(window) != 4:
+            raise ValueError("evidence_v2.window 需要 4 个数字")
+        return cls(
+            enabled=bool(raw.get("enabled", False)),
+            view=ViewMode.parse(raw.get("view", "front")),
+            work_width=int(raw.get("work_width", 960)),
+            window=tuple(float(v) for v in window),  # type: ignore[arg-type]
+            band_min_h=int(raw.get("band_min_h", 3)),
+            band_max_h_ratio=float(raw.get("band_max_h_ratio", 0.15)),
+            bed_search_ratio=float(raw.get("bed_search_ratio", 0.40)),
+            box_bottom_max_ratio=float(raw.get("box_bottom_max_ratio", 0.78)),
+            below_start_ratio=float(raw.get("below_start_ratio", 0.07)),
+            below_height_ratio=float(raw.get("below_height_ratio", 0.55)),
+            below_min_height_px=int(raw.get("below_min_height_px", 24)),
+            min_door_posts=int(raw.get("min_door_posts", 5)),
+            max_door_posts=int(raw.get("max_door_posts", 16)),
+            max_bed_gap_px=float(raw.get("max_bed_gap_px", 40.0)),
+            flat_max_door_posts=int(raw.get("flat_max_door_posts", 4)),
+            max_post_spacing_cv=float(raw.get("max_post_spacing_cv", 6.0)),
+            min_post_len_ratio=float(raw.get("min_post_len_ratio", 0.30)),
+            min_wall_opacity=float(raw.get("min_wall_opacity", 0.35)),
+            max_flat_gap_px=float(raw.get("max_flat_gap_px", 40.0)),
+            wall_edge_density_ref=float(raw.get("wall_edge_density_ref", 0.14)),
+            wall_edge_density_span=float(raw.get("wall_edge_density_span", 0.04)),
+            ground_block_px=int(raw.get("ground_block_px", 32)),
+            ground_density_lo=float(raw.get("ground_density_lo", 0.02)),
+            ground_density_hi=float(raw.get("ground_density_hi", 0.35)),
+            min_flat_ground_ratio=float(raw.get("min_flat_ground_ratio", 0.40)),
+            min_zero_ground_ratio=float(raw.get("min_zero_ground_ratio", 0.65)),
+            deck_min_len_ratio=float(raw.get("deck_min_len_ratio", 0.30)),
+            box_height_m=float(raw.get("box_height_m", 2.591)),
+            px_per_m=float(raw.get("px_per_m", 0.0)),
+            min_scale_px=float(raw.get("min_scale_px", 60.0)),
+            motion_diff_max=float(raw.get("motion_diff_max", 12.0)),
+            motion_grad_ratio_min=float(raw.get("motion_grad_ratio_min", 0.72)),
+            require_commit=bool(raw.get("require_commit", True)),
+            allow_state2=bool(raw.get("allow_state2", True)),
+            structure_hits_min=float(raw.get("structure_hits_min", 0.60)),
+            reject_hoist_high=bool(raw.get("reject_hoist_high", True)),
+            hoist_dark_max=int(raw.get("hoist_dark_max", 75)),
+            hoist_band_frac=float(raw.get("hoist_band_frac", 0.035)),
+            hoist_line_ratio=float(raw.get("hoist_line_ratio", 0.20)),
+            hoist_dark_ratio=float(raw.get("hoist_dark_ratio", 0.55)),
+            hoist_bright_delta=float(raw.get("hoist_bright_delta", 12.0)),
+        )
+
+
+@dataclass
+class EvidenceV2Result:
+    """单帧 v2 证据与分类结果(所有坐标均为原图像素)。"""
+
+    state: int = int(SceneState.UNKNOWN)
+    confidence: float = 0.0
+    view: ViewMode = ViewMode.UNKNOWN
+    box_bottom_y: Optional[float] = None
+    box_top_y: Optional[float] = None
+    box_h_px: Optional[float] = None
+    px_per_m: Optional[float] = None
+    scale_ok: bool = False
+    bed_top_y: Optional[float] = None
+    gap_px: Optional[float] = None
+    gap_m: Optional[float] = None
+    door_posts: int = 0
+    post_spacing_px: Optional[float] = None
+    post_spacing_cv: Optional[float] = None
+    rect_doors: int = 0
+    diagonal_braces: int = 0
+    wall_opacity: float = 0.0
+    deck_edge: bool = False
+    wheel_count: int = 0
+    ground_ratio: float = 0.0
+    phase: CommitPhase = CommitPhase.T1
+    committed: bool = False
+    commit_reason: str = "init"
+    stable_frames: int = 0
+    structure_frames: int = 0
+    motion_ok: bool = True
+    hoist_high: bool = False
+    abstain_reason: str = ""
+    below_roi: Tuple[int, int, int, int] = (0, 0, 0, 0)
+    diagnostics: Dict[str, object] = field(default_factory=dict)
+
+    @property
+    def candidate_state(self) -> int:
+        """分类候选(未经 commit 门);诊断/回放用。"""
+
+        return int(self.state)
+
+    def publishable(self, require_commit: bool = True) -> bool:
+        if int(self.state) not in (0, 1, 2):
+            return False
+        if not require_commit:
+            return True
+        return bool(self.committed)
+
+    def to_observation(
+        self,
+        ts: float = 0.0,
+        frame_id: int = 0,
+        detections: Optional[Sequence[object]] = None,
+        *,
+        require_commit: bool = True,
+    ) -> Observation:
+        """转成现有 ``TemporalVoter`` 可消费的 ``Observation``。
+
+        commit 不成立时输出内部 255(不是 0),并保留分类候选在 reason 里。
+        """
+
+        ok = self.publishable(require_commit)
+        state = int(self.state) if ok else int(SceneState.UNKNOWN)
+        conf = float(self.confidence) if ok else 0.0
+        reason = "v2:%s view=%s posts=%d opacity=%.2f gap=%s commit=%s hoist=%d" % (
+            "ok" if ok else "abstain",
+            self.view.value,
+            int(self.door_posts),
+            float(self.wall_opacity),
+            "n/a" if self.gap_px is None else "%.0fpx" % self.gap_px,
+            self.commit_reason,
+            int(bool(self.hoist_high)),
+        )
+        if not ok and self.abstain_reason:
+            reason += " reason=%s" % self.abstain_reason
+        return Observation(
+            ts=float(ts),
+            state=state,
+            confidence=conf,
+            detections=list(detections or []),
+            reason=reason,
+            frame_id=int(frame_id),
+        )
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "state": int(self.state),
+            "confidence": round(float(self.confidence), 4),
+            "view": self.view.value,
+            "box_bottom_y": _round_opt(self.box_bottom_y),
+            "box_top_y": _round_opt(self.box_top_y),
+            "box_h_px": _round_opt(self.box_h_px),
+            "px_per_m": _round_opt(self.px_per_m),
+            "scale_ok": bool(self.scale_ok),
+            "bed_top_y": _round_opt(self.bed_top_y),
+            "gap_px": _round_opt(self.gap_px),
+            "gap_m": _round_opt(self.gap_m, 4),
+            "door_posts": int(self.door_posts),
+            "post_spacing_px": _round_opt(self.post_spacing_px),
+            "post_spacing_cv": _round_opt(self.post_spacing_cv, 3),
+            "rect_doors": int(self.rect_doors),
+            "diagonal_braces": int(self.diagonal_braces),
+            "wall_opacity": round(float(self.wall_opacity), 3),
+            "deck_edge": bool(self.deck_edge),
+            "wheel_count": int(self.wheel_count),
+            "ground_ratio": round(float(self.ground_ratio), 3),
+            "phase": self.phase.value,
+            "committed": bool(self.committed),
+            "commit_reason": self.commit_reason,
+            "stable_frames": int(self.stable_frames),
+            "structure_frames": int(self.structure_frames),
+            "motion_ok": bool(self.motion_ok),
+            "hoist_high": bool(self.hoist_high),
+            "abstain_reason": self.abstain_reason,
+            "below_roi": [int(v) for v in self.below_roi],
+            "diagnostics": dict(self.diagnostics),
+        }
+
+
+def _round_opt(value: Optional[float], digits: int = 2) -> Optional[float]:
+    if value is None:
+        return None
+    return round(float(value), digits)
+
+
+def _to_gray(image: np.ndarray) -> np.ndarray:
+    if image is None:
+        return np.zeros((0, 0), dtype=np.uint8)
+    if image.ndim == 2:
+        return image.astype(np.uint8, copy=False)
+    if cv2 is None:  # pragma: no cover
+        raise RuntimeError("需要 opencv-python 进行彩色转换")
+    if image.shape[2] == 4:
+        return cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
+    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
+
+
+def horizontal_bands(
+    gray: np.ndarray,
+    roi: Tuple[int, int, int, int],
+    min_h: int = 3,
+    max_h: int = 90,
+    topn: int = 12,
+) -> Tuple[List[Band], List[Band]]:
+    """行均值纵向 Sobel 找水平亮带/暗带(P0 算法的生产化版本)。
+
+    返回 ``(bright, dark)``;``y0/y1`` 是原图坐标。亮带 = 中间比上下亮,
+    暗带 = 中间比上下暗。算法只用行均值,因此在箱体移动/局部纹理下比
+    全画面霍夫更稳定。
+    """
+
+    if cv2 is None:  # pragma: no cover
+        raise RuntimeError("evidence_v2 需要 opencv-python")
+    x0, y0, x1, y1 = [int(v) for v in roi]
+    x0 = max(0, x0)
+    y0 = max(0, y0)
+    x1 = min(int(gray.shape[1]), x1)
+    y1 = min(int(gray.shape[0]), y1)
+    if x1 <= x0 or y1 <= y0:
+        return [], []
+    crop = gray[y0:y1, x0:x1].astype(np.float32)
+    if crop.size == 0:
+        return [], []
+    crop = cv2.GaussianBlur(crop, (3, 3), 0)
+    gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3).mean(axis=1)
+    mag = np.abs(gy)
+    if mag.size == 0:
+        return [], []
+    if mag.size < 3:
+        return [], []
+    limit = float(mag.mean() + 0.9 * mag.std())
+    # 峰值抑制:同一道边缘常在相邻 1~2 行出现两个极值(例如箱底 3 px
+    # 暗带:y=167 负峰、y=168 负峰、y=170 正峰)。旧实现要求 ±2 行内
+    # 严格最大:167 会压掉 168,168 又压掉 170,最终只剩一个负峰,
+    # 暗带无法配对,整帧直接 no_box。这里先取 ±1 行局部极大,再按幅值
+    # 贪心抑制 3 px 内的重复峰,既保留 3 px 薄带,又不拆散同一道边缘。
+    min_sep = max(2, int(round(min_h)))
+    candidates = [
+        i for i in range(1, len(mag) - 1)
+        if mag[i] >= limit and mag[i] >= mag[i - 1] and mag[i] >= mag[i + 1]
+    ]
+    picked: List[int] = []
+    for i in sorted(candidates, key=lambda j: mag[j], reverse=True):
+        if all(abs(i - j) >= min_sep for j in picked):
+            picked.append(i)
+    picked.sort()
+    events: List[Tuple[int, float]] = [(i, float(gy[i])) for i in picked]
+
+    bright: List[Band] = []
+    dark: List[Band] = []
+    for j in range(len(events) - 1):
+        i1, v1 = events[j]
+        i2, v2 = events[j + 1]
+        height = i2 - i1
+        if height < min_h or height > max_h:
+            continue
+        strength = min(abs(v1), abs(v2))
+        if strength <= 0.0:
+            continue
+        if v1 > 0.0 > v2:
+            bright.append(Band(float(y0 + i1), float(y0 + i2), strength))
+        elif v1 < 0.0 < v2:
+            dark.append(Band(float(y0 + i1), float(y0 + i2), strength))
+    bright.sort(key=lambda b: b.strength, reverse=True)
+    dark.sort(key=lambda b: b.strength, reverse=True)
+    return bright[:topn], dark[:topn]
+
+
+def pick_box_and_bed(
+    bright: Sequence[Band],
+    dark: Sequence[Band],
+    frame_h: int,
+    *,
+    box_bottom_max_ratio: float = 0.78,
+    bed_search_px: float = 120.0,
+) -> Tuple[Optional[Band], Optional[Band]]:
+    """选箱底暗带与它下方最近的车体上缘亮带(与 P0 同口径)。"""
+
+    upper = [
+        b for b in dark
+        if b.y1 <= box_bottom_max_ratio * frame_h and b.y0 >= 0.02 * frame_h
+    ]
+    if not upper:
+        return None, None
+    strongest = max(b.strength for b in upper)
+    strong = [b for b in upper if b.strength >= 0.45 * strongest]
+    box = min(strong, key=lambda b: b.y0)
+    below = [b for b in bright if b.y0 >= box.y1 - 1.0 and b.y0 <= box.y1 + bed_search_px]
+    bed = min(below, key=lambda b: b.y0) if below else None
+    return box, bed
+
+
+def ground_like_ratio(
+    gray: np.ndarray,
+    roi: Tuple[int, int, int, int],
+    segments: Sequence[Dict[str, float]],
+    *,
+    block_px: int = 32,
+    density_lo: float = 0.02,
+    density_hi: float = 0.35,
+) -> Tuple[float, int]:
+    """分块“地面样”比例:纹理密度在区间内且块内无长直线。
+
+    与 v1 ``edge_evidence.cpp::region_stats`` 的 ``ground_like`` 同口径;
+    门板立柱是**竖线**、门板横梁/车面边梁是**横线**,两者都算结构面。
+    """
+
+    if cv2 is None:  # pragma: no cover
+        return 0.0, 0
+    x0, y0, x1, y1 = [int(v) for v in roi]
+    crop = gray[y0:y1, x0:x1]
+    if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
+        return 0.0, 0
+    gx = cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3)
+    gy = cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3)
+    mag = np.sqrt(gx * gx + gy * gy)
+    ref = float(np.percentile(mag, 60.0))
+    hot = mag > ref
+    b = max(6, int(block_px))
+    total = 0
+    ground = 0
+    for by in range(0, crop.shape[0], b):
+        for bx in range(0, crop.shape[1], b):
+            ex = min(crop.shape[1], bx + b)
+            ey = min(crop.shape[0], by + b)
+            block = hot[by:ey, bx:ex]
+            if block.size == 0:
+                continue
+            density = float(block.mean())
+            long_line = any(
+                float(seg["length"]) >= 0.6 * b
+                and bx + x0 <= (float(seg["x0"]) + float(seg["x1"])) * 0.5 <= ex + x0
+                and by + y0 <= (float(seg["y0"]) + float(seg["y1"])) * 0.5 <= ey + y0
+                for seg in segments
+                if "x0" in seg and "x1" in seg and "y0" in seg and "y1" in seg
+            )
+            total += 1
+            if not long_line and density_lo <= density <= density_hi:
+                ground += 1
+    return (float(ground) / float(total) if total else 0.0), total
+
+
+def _cluster_positions(values: Sequence[float], gap_px: float) -> List[float]:
+    ordered = sorted(float(v) for v in values)
+    if not ordered:
+        return []
+    clusters: List[List[float]] = [[ordered[0]]]
+    for value in ordered[1:]:
+        if value - clusters[-1][-1] <= gap_px:
+            clusters[-1].append(value)
+        else:
+            clusters.append([value])
+    return [float(statistics.median(c)) for c in clusters]
+
+
+def detect_structure_v2(
+    gray: np.ndarray,
+    roi: Tuple[int, int, int, int],
+    *,
+    min_post_len_ratio: float = 0.30,
+    cluster_gap_px: float = 9.0,
+    scale: float = 1.0,
+) -> Dict[str, object]:
+    """箱底以下 ROI 的门板立柱 / 斜撑 / 矩形门 / 水平边梁。
+
+    只做**证据计数**,不做分类;返回的坐标相对 ROI(线段另带
+    ``y`` 原图坐标,供 deck_edge 使用)。
+    """
+
+    if cv2 is None:  # pragma: no cover
+        raise RuntimeError("evidence_v2 需要 opencv-python")
+    x0, y0, x1, y1 = [int(v) for v in roi]
+    crop = gray[y0:y1, x0:x1]
+    empty = {
+        "vertical_lines": 0, "diagonal_lines": 0, "horizontal_lines": 0,
+        "rect_doors": 0, "post_count": 0, "post_spacing_median": None,
+        "post_spacing_cv": None, "edge_density": 0.0,
+        "horizontal": [], "lines": [],
+    }
+    if crop.size == 0 or crop.shape[0] < 8 or crop.shape[1] < 8:
+        return empty
+
+    crop = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop)
+    edges = cv2.Canny(crop, 50, 150)
+    roi_h = max(1, crop.shape[0])
+    roi_area = float(crop.shape[0] * crop.shape[1])
+
+    lines = cv2.HoughLinesP(
+        edges, 1, math.pi / 180.0, threshold=24,
+        minLineLength=max(12, int(round(20 * scale))), maxLineGap=max(4, int(round(8 * scale))),
+    )
+    vertical: List[Tuple[float, float, float]] = []
+    horizontal: List[Dict[str, float]] = []
+    all_lines: List[Dict[str, float]] = []
+    diagonal = 0
+    if lines is not None:
+        flat = np.asarray(lines).reshape(-1, 4)
+        for raw in flat:
+            xa, ya, xb, yb = (float(v) for v in raw)
+            dx, dy = xb - xa, yb - ya
+            length = math.hypot(dx, dy)
+            if length < max(12.0, 20.0 * scale):
+                continue
+            all_lines.append({
+                "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
+                "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
+                "length": length,
+            })
+            if abs(dy) >= 1.8 * abs(dx):
+                vertical.append(((xa + xb) * 0.5, min(ya, yb), max(ya, yb)))
+            elif abs(dx) >= 1.8 * abs(dy):
+                horizontal.append({
+                    "x0": x0 + min(xa, xb), "x1": x0 + max(xa, xb),
+                    "y": y0 + (ya + yb) * 0.5, "length": length,
+                    "y0": y0 + min(ya, yb), "y1": y0 + max(ya, yb),
+                })
+            else:
+                diagonal += 1
+
+    posts = [v for v in vertical if (v[2] - v[1]) >= min_post_len_ratio * roi_h]
+    post_x = _cluster_positions([v[0] for v in posts], max(3.0, cluster_gap_px * scale))
+    spacings = [post_x[i + 1] - post_x[i] for i in range(len(post_x) - 1)]
+    spacing_median = float(statistics.median(spacings)) if spacings else None
+    spacing_cv = None
+    if len(spacings) >= 2 and spacing_median:
+        spacing_cv = float(statistics.pstdev(spacings) / spacing_median)
+
+    contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
+    rect_doors = 0
+    for contour in contours:
+        area = cv2.contourArea(contour)
+        if area < 180.0 or area > 0.20 * roi_area:
+            continue
+        peri = cv2.arcLength(contour, True)
+        if peri <= 0.0:
+            continue
+        approx = cv2.approxPolyDP(contour, 0.04 * peri, True)
+        if not (4 <= len(approx) <= 6):
+            continue
+        _, _, bw, bh = cv2.boundingRect(approx)
+        if bh <= 0:
+            continue
+        aspect = bw / float(bh)
+        if 0.30 <= aspect <= 3.2:
+            rect_doors += 1
+
+    return {
+        "vertical_lines": len(posts),
+        "diagonal_lines": int(diagonal),
+        "horizontal_lines": len(horizontal),
+        "rect_doors": int(rect_doors),
+        "post_count": len(post_x),
+        "post_spacing_median": spacing_median,
+        "post_spacing_cv": spacing_cv,
+        "edge_density": float(edges.mean() / 255.0),
+        "horizontal": horizontal,
+        "lines": all_lines,
+    }
+
+
+def detect_spreader_contact(
+    gray: np.ndarray,
+    container_bbox: Tuple[float, float, float, float],
+    *,
+    dark_max: int = 110,
+    dark_ratio: float = 0.55,
+) -> Tuple[bool, Dict[str, object]]:
+    """检测集装箱上沿紧邻的吊具横梁(吊具仍夹着箱)。
+
+    负样本里最典型的误判是:算法把**箱侧壁瓦楞**当成车斗门板,箱底
+    又恰好贴到画面上某个横向结构,于是 5 帧后 commit。真正落位时,
+    箱顶上方不应存在一条“紧贴箱顶、横跨箱宽、明显更暗”的横梁;吊具
+    未松开时这条横梁必然存在。
+
+    只使用检测器给出的 container 框(不是 ``box_top`` 自标尺),因此
+    不受箱高估计误差影响。返回值第二项为诊断。
+    """
+
+    empty = {"spreader_contact": False, "dark_run_px": 0, "band_delta": 0.0}
+    if gray is None or gray.size == 0:
+        return False, empty
+    h, w = gray.shape[:2]
+    x1, y1, x2, y2 = [int(round(v)) for v in container_bbox]
+    x1, x2 = max(0, min(x1, x2)), min(w, max(x1, x2))
+    y1, y2 = max(0, min(y1, y2)), min(h, max(y1, y2))
+    box_h = y2 - y1
+    box_w = x2 - x1
+    if box_h < 20 or box_w < 20:
+        return False, empty
+
+    probe = max(4, int(0.30 * box_h))
+    y0 = max(0, y1 - probe)
+    roi = gray[y0:y1, x1:x2]
+    if roi.shape[0] < 3:
+        return False, empty
+    dark = roi < int(dark_max)
+    frac = dark.mean(axis=1)
+    min_run = max(3, int(0.02 * box_h))
+    runs = []
+    run_start = None
+    for row, value in enumerate(frac):
+        if value >= dark_ratio:
+            if run_start is None:
+                run_start = row
+        elif run_start is not None:
+            if (row - run_start) >= min_run:
+                runs.append((run_start, row - 1))
+            run_start = None
+    if run_start is not None and (len(frac) - run_start) >= min_run:
+        runs.append((run_start, len(frac) - 1))
+    if not runs:
+        return False, empty
+    # 优先选离箱顶最近的一条暗横梁:吊具夹着箱时它紧贴箱顶;更长的
+    # 远处吊臂不能替代它,否则会把“远处横梁”误当成“已落位”。
+    best_start, best_end = min(runs, key=lambda item: (len(frac) - 1 - item[1], item[0] - item[1]))
+    if (len(frac) - 1 - best_end) > max(2, int(0.08 * box_h)):
+        return False, empty
+    band = roi[best_start:best_end + 1, :]
+    below = gray[y1:min(h, y1 + max(6, int(0.06 * box_h))), x1:x2]
+    if band.size == 0 or below.size == 0:
+        return False, empty
+    band_mean = float(band.mean())
+    below_mean = float(below.mean())
+    if below_mean < band_mean + 10.0:
+        return False, empty
+    return True, {
+        "spreader_contact": True,
+        "dark_run_px": int(best_end - best_start + 1),
+        "band_delta": round(below_mean - band_mean, 2),
+    }
+
+
+def detect_hoist_high(
+    gray: np.ndarray,
+    box_top_y: float,
+    *,
+    dark_max: int = 75,
+    band_frac: float = 0.035,
+    line_ratio: float = 0.30,
+    dark_ratio: float = 0.55,
+    bright_delta: float = 12.0,
+) -> Tuple[bool, Dict[str, object]]:
+    """检测箱体上方的吊具/臂架/钢缆高悬特征。
+
+    只看**候选箱体上沿以上**的区域,要求同时满足:
+
+    * 至少一条横跨画面中央的长横线(Hough);
+    * 横线上方是一条暗带(吊具/臂架本体);
+    * 暗带下方明显更亮(天空、箱顶或车体),说明暗带是遮挡物而不是
+      箱体本身的暗边。
+
+    这三个条件是为了避开集装箱侧壁的竖向瓦楞和车体横梁:A/B 正样本的
+    箱顶通常已被画幅裁掉(``box_top_y`` 很小),不会进入该区域;负样本
+    (屏幕录制)上方有明显黑色吊臂/吊具,会被拦下。返回值第二项只用于
+    诊断,不参与安全判定。
+    """
+
+    empty = {"hoist_high": False, "horizontal_lines": 0, "cables": 0}
+    if cv2 is None or gray is None or gray.size == 0:
+        return False, empty
+    h, w = gray.shape[:2]
+    limit = int(min(max(8.0, float(box_top_y) - 2.0), 0.45 * h))
+    if limit < max(12, int(0.06 * h)) or w < 32:
+        return False, empty
+
+    scale = min(1.0, 480.0 / float(w))
+    if scale < 1.0:
+        work = cv2.resize(
+            gray, (int(round(w * scale)), int(round(h * scale))),
+            interpolation=cv2.INTER_AREA,
+        )
+    else:
+        work = gray
+    hh, ww = work.shape[:2]
+    limit_w = min(hh, max(1, int(round(limit * scale))))
+    roi = work[:limit_w, :]
+    if roi.shape[0] < 12 or roi.shape[1] < 32:
+        return False, empty
+
+    blur = cv2.GaussianBlur(roi, (5, 5), 0)
+    edges = cv2.Canny(blur, 50, 150)
+    lines = cv2.HoughLinesP(
+        edges,
+        1,
+        math.pi / 180.0,
+        threshold=15,
+        minLineLength=max(10, int(line_ratio * ww)),
+        maxLineGap=max(4, int(0.03 * ww)),
+    )
+
+    horizontal_hits = 0
+    cables = 0
+    x0 = int(0.10 * ww)
+    x1 = max(x0 + 8, int(0.90 * ww))
+    band_h = max(3, int(band_frac * hh))
+    if lines is not None:
+        for raw in np.asarray(lines).reshape(-1, 4):
+            xa, ya, xb, yb = (float(v) for v in raw)
+            dx, dy = abs(xb - xa), abs(yb - ya)
+            if dx < line_ratio * ww * 0.8:
+                continue
+            # 近水平线:吊具横梁/臂架下缘
+            if dy <= max(3.0, 0.04 * dx):
+                y = int(round((ya + yb) * 0.5))
+                if y - band_h < 0 or y + 2 >= limit_w:
+                    continue
+                band = blur[y - band_h:y, x0:x1]
+                below = blur[y + 2:min(limit_w, y + 2 + 2 * band_h), x0:x1]
+                if band.size == 0 or below.size == 0:
+                    continue
+                dark = float(np.mean(band < int(dark_max)))
+                if dark >= dark_ratio and float(below.mean()) >= float(band.mean()) + bright_delta:
+                    horizontal_hits += 1
+            # 近竖直线:钢缆/油管(只作诊断与辅助确认)
+            elif dy >= max(6.0, 4.0 * dx) and dy >= 0.12 * hh:
+                xs = np.linspace(xa, xb, num=12)
+                ys = np.linspace(ya, yb, num=12)
+                samples = [
+                    blur[int(round(yv)), int(round(xv))]
+                    for xv, yv in zip(xs, ys)
+                    if 0 <= int(round(yv)) < limit_w and 0 <= int(round(xv)) < ww
+                ]
+                if samples and float(np.mean(samples)) <= float(dark_max) + 25.0:
+                    cables += 1
+
+    hoist = horizontal_hits >= 1
+    return hoist, {
+        "hoist_high": bool(hoist),
+        "horizontal_lines": int(horizontal_hits),
+        "cables": int(cables),
+    }
+
+
+class EvidenceV2:
+    """前视 v2 证据提取 + 分类 + commit 门(线程内使用)。"""
+
+    def __init__(self, params: Optional[EvidenceV2Params] = None,
+                 tracker: Optional[CommitTracker] = None) -> None:
+        self.p = params or EvidenceV2Params()
+        self.tracker = tracker or CommitTracker()
+        self._last = EvidenceV2Result(view=self.p.view)
+        self._prev_thumb: Optional[np.ndarray] = None
+        self._prev_mag = 0.0
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "EvidenceV2":
+        return cls(EvidenceV2Params.from_config(cfg), CommitTracker.from_config(cfg))
+
+    @property
+    def last(self) -> EvidenceV2Result:
+        return self._last
+
+    def reset(self) -> None:
+        self.tracker.reset()
+        self._prev_thumb = None
+        self._prev_mag = 0.0
+        self._last = EvidenceV2Result(view=self.p.view)
+
+    # ------------------------------------------------------------ 运动门控
+    def _motion(self, gray: np.ndarray) -> Tuple[bool, float, float]:
+        if cv2 is None:  # pragma: no cover
+            return True, 0.0, 1.0
+        thumb = cv2.resize(gray, (160, 90), interpolation=cv2.INTER_AREA)
+        lap = cv2.Laplacian(thumb, cv2.CV_32F)
+        mag = float(np.abs(lap).mean())
+        if self._prev_thumb is None:
+            self._prev_thumb = thumb
+            self._prev_mag = mag
+            return True, 0.0, 1.0
+        diff = float(np.abs(thumb.astype(np.float32) - self._prev_thumb.astype(np.float32)).mean())
+        ratio = (mag / self._prev_mag) if self._prev_mag > 1e-6 else 1.0
+        ok = diff <= self.p.motion_diff_max and ratio >= self.p.motion_grad_ratio_min
+        self._prev_thumb = thumb
+        self._prev_mag = 0.8 * self._prev_mag + 0.2 * mag if self._prev_mag > 0 else mag
+        return ok, diff, ratio
+
+    # ------------------------------------------------------------ 自标尺
+    def _scale_from_vertical(
+        self,
+        gray: np.ndarray,
+        box: Band,
+        window: Tuple[int, int, int, int],
+        scale: float,
+    ) -> Tuple[Optional[float], Optional[float]]:
+        """用箱体近端竖棱估 ``px_per_m``;失败返回 ``(None, None)``。"""
+
+        if cv2 is None:  # pragma: no cover
+            return None, None
+        if self.p.px_per_m > 0.0:
+            px_per_m = float(self.p.px_per_m)
+            return px_per_m, None
+        x0, y0, x1, _ = [int(v) for v in window]
+        y1 = max(1, int(box.y0))
+        crop = gray[max(0, y0):y1, max(0, x0):min(gray.shape[1], x1)]
+        if crop.size == 0:
+            return None, None
+        edges = cv2.Canny(cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(crop), 50, 150)
+        lines = cv2.HoughLinesP(
+            edges, 1, math.pi / 180.0, threshold=24,
+            minLineLength=max(12, int(self.p.min_scale_px * scale)),
+            maxLineGap=max(4, int(10 * scale)),
+        )
+        best = 0.0
+        if lines is not None:
+            for raw in np.asarray(lines).reshape(-1, 4):
+                xa, ya, xb, yb = (float(v) for v in raw)
+                dx, dy = abs(xb - xa), abs(yb - ya)
+                if dy >= 2.0 * dx and dy > best:
+                    best = dy
+        if best < self.p.min_scale_px * scale:
+            return None, None
+        px_per_m_work = best / self.p.box_height_m
+        return px_per_m_work / max(scale, 1e-6), best
+
+    # ------------------------------------------------------------ 分类
+    def _classify(
+        self,
+        *,
+        posts: int,
+        spacing_cv: Optional[float],
+        opacity: float,
+        ground: float,
+        deck: bool,
+        wheels: int,
+        gap_px: Optional[float],
+        motion_ok: bool,
+        view: ViewMode,
+    ) -> Tuple[int, float, float, str]:
+        """返回 ``(state, confidence, structure_hits, reason)``。"""
+
+        if view == ViewMode.UNKNOWN:
+            return int(SceneState.UNKNOWN), 0.0, 0.0, "view_unknown"
+        if not motion_ok:
+            return int(SceneState.UNKNOWN), 0.0, 0.0, "motion"
+
+        bed_strong = (
+            self.p.min_door_posts <= posts <= self.p.max_door_posts
+            and opacity >= self.p.min_wall_opacity
+            and (gap_px is None or gap_px <= self.p.max_bed_gap_px)
+            and (spacing_cv is None or spacing_cv <= self.p.max_post_spacing_cv)
+        )
+        # 平车:没有门板阵列 + 箱底下有可见车面边梁。地面比例只作置信度加分:
+        # B 的落位帧里车面本身占满动态 ROI,分块“地面样”会偏低。
+        flat_strong = (
+            posts <= self.p.flat_max_door_posts
+            and deck
+            and (gap_px is None or gap_px <= self.p.max_flat_gap_px)
+        )
+
+        if bed_strong and flat_strong:
+            return int(SceneState.UNKNOWN), 0.0, 0.0, "conflict_1_2"
+
+        if bed_strong:
+            conf = 0.55 + 0.25 * min(1.0, posts / 8.0) + 0.15 * opacity
+            hits = min(1.0, 0.40 + 0.05 * posts + 0.20 * opacity)
+            return int(SceneState.BED), min(1.0, conf), hits, "wall_posts"
+
+        if flat_strong:
+            conf = 0.60 + 0.20 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0)
+            hits = min(1.0, 0.55 + 0.15 * ground + 0.10 * max(0.0, 1.0 - posts / 4.0))
+            return int(SceneState.FLATBED), min(1.0, conf), hits, "deck_edge"
+
+        if posts <= 1 and ground >= self.p.min_zero_ground_ratio and not deck:
+            conf = 0.55 + 0.30 * ground
+            hits = min(1.0, 0.50 + 0.40 * ground)
+            return int(SceneState.NOT_ON_TRAIN), min(1.0, conf), hits, "ground_only"
+
+        return int(SceneState.UNKNOWN), 0.0, 0.0, "weak_evidence"
+
+    # ------------------------------------------------------------ 车轮(辅助)
+    @staticmethod
+    def _wheel_count(gray: np.ndarray, roi: Tuple[int, int, int, int], scale: float) -> int:
+        if cv2 is None:  # pragma: no cover
+            return 0
+        x0, y0, x1, y1 = roi
+        crop = gray[y0:y1, x0:x1]
+        if crop.size == 0 or min(crop.shape[:2]) < 40:
+            return 0
+        crop = cv2.medianBlur(crop, 5)
+        try:
+            circles = cv2.HoughCircles(
+                crop, cv2.HOUGH_GRADIENT, dp=1.2,
+                minDist=max(20, int(36 * scale)),
+                param1=100, param2=26,
+                minRadius=max(7, int(12 * scale)), maxRadius=max(20, int(60 * scale)),
+            )
+        except cv2.error:  # pragma: no cover - 某些精简版 OpenCV
+            return 0
+        if circles is None:
+            return 0
+        return int(len(np.asarray(circles).reshape(-1, 3)))
+
+    # ------------------------------------------------------------ 主入口
+    def analyze(
+        self,
+        image: np.ndarray,
+        ts: float = 0.0,
+        frame_id: int = 0,
+        *,
+        plc_arrived: bool = False,
+        plc_spreader_released: bool = False,
+        detections: Optional[Sequence[Box]] = None,
+        hoist_high: Optional[bool] = None,
+    ) -> EvidenceV2Result:
+        """提取一帧证据并更新 commit 状态。
+
+        ``image`` 可以是灰度或 BGR;坐标一律按**原图**返回。
+        ``detections`` 是检测器本帧输出(可选);有 container 框时,用
+        箱顶正上方的暗横梁判断吊具是否仍夹着箱。``hoist_high`` 仅用于
+        离线回放/单测注入;生产路径由图像 + 检测框自动判定。
+        """
+
+        gray0 = _to_gray(image)
+        if gray0.size == 0:
+            self._last = EvidenceV2Result(
+                view=self.p.view, abstain_reason="no_image",
+                commit_reason="no_image", phase=CommitPhase.T1,
+            )
+            return self._last
+
+        h, w = gray0.shape[:2]
+        scale = min(1.0, float(self.p.work_width) / float(w))
+        if scale < 1.0:
+            gray = cv2.resize(gray0, (int(round(w * scale)), int(round(h * scale))),
+                              interpolation=cv2.INTER_AREA)
+        else:
+            gray = gray0
+
+        motion_ok, motion_diff, motion_ratio = self._motion(gray)
+        wh, ww = gray.shape[:2]
+        window = (
+            int(self.p.window[0] * ww), int(self.p.window[1] * wh),
+            int(self.p.window[2] * ww), int(self.p.window[3] * wh),
+        )
+        max_h = max(6, int(self.p.band_max_h_ratio * wh))
+        bright, dark = horizontal_bands(
+            gray, window, min_h=max(1, int(self.p.band_min_h * scale)), max_h=max_h
+        )
+        # 先估一个箱高,用于“车体上缘搜索窗”(P0 固定 120 px 的等价物)。
+        box_hint = max(80.0, 0.40 * wh)
+        box, bed = pick_box_and_bed(
+            bright, dark, wh,
+            box_bottom_max_ratio=self.p.box_bottom_max_ratio,
+            bed_search_px=max(24.0, self.p.bed_search_ratio * box_hint),
+        )
+        if box is None and dark:
+            # 兜底:取上半幅最强的暗带(仍要求离顶部有一点距离)。
+            candidates = [b for b in dark if b.y0 >= 0.03 * wh and b.y1 <= 0.90 * wh]
+            box = max(candidates, key=lambda b: b.strength) if candidates else None
+        if box is None:
+            self._last = EvidenceV2Result(
+                view=self.p.view, motion_ok=motion_ok, abstain_reason="no_box",
+                commit_reason="no_box", phase=CommitPhase.T3 if not motion_ok else CommitPhase.T1,
+                diagnostics={"motion_diff": round(motion_diff, 2),
+                             "motion_ratio": round(motion_ratio, 3)},
+            )
+            return self._last
+        if bed is None and bright:
+            below = [b for b in bright if b.y0 >= box.y1 - 1.0]
+            bed = min(below, key=lambda b: b.y0) if below else None
+
+        px_per_m, vertical_run = self._scale_from_vertical(gray, box, window, scale)
+        box_h_px = None
+        if px_per_m is not None:
+            box_h_px = px_per_m * self.p.box_height_m
+        elif vertical_run is not None:
+            box_h_px = vertical_run / max(scale, 1e-6)
+        box_top = None
+        if box_h_px is not None:
+            box_top = max(0.0, box.y1 / max(scale, 1e-6) - box_h_px)
+
+        # P0-0 安全门:看箱体上沿以上有没有吊具/臂架/钢缆。没有可靠箱高时
+        # 用“箱底暗带往上 0.35 画幅”保守估计,宁可多弃权。
+        hoist_flag = False
+        hoist_cues: Dict[str, object] = {
+            "hoist_high": False, "horizontal_lines": 0, "cables": 0,
+        }
+        if hoist_high is not None:
+            hoist_flag = bool(hoist_high)
+            hoist_cues = {
+                "hoist_high": bool(hoist_flag),
+                "horizontal_lines": 0,
+                "cables": 0,
+                "injected": True,
+            }
+        elif self.p.reject_hoist_high:
+            # 首选:检测器 container 框 + 箱顶正上方的暗横梁。它比
+            # “用箱高猜箱顶”稳,因为负样本里箱高估计会被前景集装箱
+            # 侧壁带偏(i=668 估到 136 px,真实箱顶在 ~208 px)。
+            container = None
+            for det in detections or []:
+                name = str(getattr(det, "class_name", "") or "").lower()
+                if "container" not in name:
+                    continue
+                if container is None or getattr(det, "area", 0.0) > getattr(container, "area", 0.0):
+                    container = det
+            if container is not None:
+                contact_flag, contact_cues = detect_spreader_contact(
+                    gray0,
+                    (container.x1, container.y1, container.x2, container.y2),
+                )
+                line_flag, line_cues = detect_hoist_high(
+                    gray0,
+                    float(container.y1),
+                    dark_max=self.p.hoist_dark_max,
+                    band_frac=self.p.hoist_band_frac,
+                    line_ratio=self.p.hoist_line_ratio,
+                    dark_ratio=self.p.hoist_dark_ratio,
+                    bright_delta=self.p.hoist_bright_delta,
+                )
+                hoist_flag = bool(contact_flag or line_flag)
+                hoist_cues = dict(contact_cues)
+                hoist_cues.update({
+                    "source": "detector_box",
+                    "spreader_contact": bool(contact_flag),
+                    "horizontal_lines": int(line_cues.get("horizontal_lines", 0)),
+                    "cables": int(line_cues.get("cables", 0)),
+                })
+            else:
+                probe_top = (
+                    float(box_top)
+                    if box_top is not None
+                    else max(0.0, box.y0 / max(scale, 1e-6) - 0.35 * h)
+                )
+                hoist_flag, hoist_cues = detect_hoist_high(
+                    gray0,
+                    probe_top,
+                    dark_max=self.p.hoist_dark_max,
+                    band_frac=self.p.hoist_band_frac,
+                    line_ratio=self.p.hoist_line_ratio,
+                    dark_ratio=self.p.hoist_dark_ratio,
+                    bright_delta=self.p.hoist_bright_delta,
+                )
+                hoist_cues = dict(hoist_cues)
+                hoist_cues["source"] = "image_rows"
+
+        # 动态 ROI:y 从本帧箱底下沿开始,绝不复用 P0 固定 y=475..619。
+        est_h = max(60.0, box.y0 - 0.05 * wh)
+        # 起点要越过箱体下侧梁/车体上缘的强横线:从箱底下方约 7% 箱高开始。
+        # 但若箱底已经贴近画面底边,剩余高度不足以再跳过 7%,就只留 2 px
+        # 保护带。否则整段动态 ROI 会落到画面外,平车的车面边梁/地板线
+        # 完全看不到(本帧 25 px 车面 → deck=False、gap=None → 不能提交 2)。
+        start = max(2.0, self.p.below_start_ratio * est_h)
+        min_below_h = self.p.below_min_height_px * max(scale, 1e-6)
+        if (wh - 1) - box.y1 <= start + min_below_h:
+            start = 2.0
+        y0w = min(
+            wh - 2,
+            int(math.ceil(box.y1 + start)),
+        )
+        below_h = max(
+            min_below_h,
+            min(self.p.below_height_ratio * est_h, 0.30 * wh),
+        )
+        y1w = min(wh - 1, max(y0w + below_h, box.y1 + 0.10 * est_h))
+        x0w = max(0, int(0.05 * ww))
+        x1w = min(ww - 1, int(0.95 * ww))
+        below_work = (x0w, y0w, x1w, max(y0w + 8, int(y1w)))
+
+        structure = detect_structure_v2(
+            gray, below_work,
+            min_post_len_ratio=self.p.min_post_len_ratio,
+            cluster_gap_px=9.0, scale=scale,
+        )
+        posts = int(structure["post_count"])
+        spacing_median = structure["post_spacing_median"]
+        spacing_cv = structure["post_spacing_cv"]
+        edge_density = float(structure["edge_density"])
+        ground, ground_blocks = ground_like_ratio(
+            gray, below_work, structure.get("lines", []),  # type: ignore[arg-type]
+            block_px=self.p.ground_block_px,
+            density_lo=self.p.ground_density_lo,
+            density_hi=self.p.ground_density_hi,
+        )
+        if ground_blocks > 0:
+            opacity = max(0.0, min(1.0, 1.0 - ground))
+        else:
+            span = max(1e-6, float(self.p.wall_edge_density_span))
+            opacity = max(0.0, min(1.0, (self.p.wall_edge_density_ref - edge_density) / span))
+            ground = max(0.0, min(1.0, 1.0 - opacity))
+
+        below_h_work = max(1.0, below_work[3] - below_work[1])
+        deck_min_len = max(20.0, self.p.deck_min_len_ratio * 0.55 * ww)
+        deck_edge = any(
+            box.y1 - 2.0 <= float(seg["y"]) <= box.y1 + 0.35 * below_h_work
+            and float(seg["length"]) >= deck_min_len
+            for seg in structure.get("horizontal", [])  # type: ignore[union-attr]
+        )
+        wheels = self._wheel_count(gray, below_work, scale)
+        gap_px = None
+        if bed is not None:
+            gap_px = max(0.0, (bed.y0 - box.y1) / max(scale, 1e-6))
+
+        state, conf, hits, reason = self._classify(
+            posts=posts,
+            spacing_cv=spacing_cv,
+            opacity=opacity,
+            ground=ground,
+            deck=deck_edge,
+            wheels=wheels,
+            gap_px=gap_px,
+            motion_ok=motion_ok,
+            view=self.p.view,
+        )
+        gap_m = (
+            None if gap_px is None or px_per_m is None or px_per_m <= 0.0
+            else gap_px / px_per_m
+        )
+        commit = self.tracker.update(
+            ts,
+            state=state,
+            gap_m=gap_m,
+            gap_px=gap_px,
+            structure_hits=hits,
+            motion_ok=motion_ok,
+            view_known=self.p.view != ViewMode.UNKNOWN,
+            plc_arrived=plc_arrived,
+            plc_spreader_released=plc_spreader_released,
+            hoist_high=hoist_flag,
+        )
+        phase = CommitPhase.T3 if not motion_ok else CommitPhase(commit.phase)
+
+        result = EvidenceV2Result(
+            state=int(state),
+            confidence=float(conf),
+            view=self.p.view,
+            box_bottom_y=box.y1 / max(scale, 1e-6),
+            box_top_y=box_top,
+            box_h_px=box_h_px,
+            px_per_m=px_per_m,
+            scale_ok=px_per_m is not None,
+            bed_top_y=None if bed is None else bed.y0 / max(scale, 1e-6),
+            gap_px=gap_px,
+            gap_m=gap_m,
+            door_posts=posts,
+            post_spacing_px=(
+                None if spacing_median is None else float(spacing_median) / max(scale, 1e-6)
+            ),
+            post_spacing_cv=None if spacing_cv is None else float(spacing_cv),
+            rect_doors=int(structure["rect_doors"]),
+            diagonal_braces=int(structure["diagonal_lines"]),
+            wall_opacity=opacity,
+            deck_edge=bool(deck_edge),
+            wheel_count=int(wheels),
+            ground_ratio=ground,
+            phase=phase,
+            committed=bool(commit.committed),
+            commit_reason=commit.reason,
+            stable_frames=int(commit.stable_frames),
+            structure_frames=int(commit.structure_frames),
+            motion_ok=bool(motion_ok),
+            hoist_high=bool(hoist_flag),
+            abstain_reason=(
+                "hoist_high" if hoist_flag and state in (0, 1, 2)
+                else ("" if state in (0, 1, 2) else reason)
+            ),
+            below_roi=(
+                int(round(below_work[0] / scale)), int(round(below_work[1] / scale)),
+                int(round(below_work[2] / scale)), int(round(below_work[3] / scale)),
+            ),
+            diagnostics={
+                "class_reason": reason,
+                "box_band": [round(box.y0 / scale, 2), round(box.y1 / scale, 2)],
+                "bed_band": None if bed is None else [round(bed.y0 / scale, 2), round(bed.y1 / scale, 2)],
+                "vertical_run_px": None if vertical_run is None else round(vertical_run / scale, 2),
+                "motion_diff": round(motion_diff, 2),
+                "motion_ratio": round(motion_ratio, 3),
+                "edge_density": round(edge_density, 4),
+                "ground_blocks": int(ground_blocks),
+                "vertical_lines": int(structure["vertical_lines"]),
+                "horizontal_lines": int(structure["horizontal_lines"]),
+                "hoist_cues": dict(hoist_cues),
+                "scale": round(scale, 4),
+            },
+        )
+        self._last = result
+        return result
+
+    def classify(self, image: np.ndarray, ts: float = 0.0, frame_id: int = 0,
+                 **kwargs) -> Observation:
+        """``analyze`` + ``to_observation`` 的便捷入口(pipeline 使用)。"""
+
+        result = self.analyze(image, ts=ts, frame_id=frame_id, **kwargs)
+        return result.to_observation(
+            ts=ts, frame_id=frame_id, require_commit=self.p.require_commit
+        )

+ 124 - 0
portcv/logic/geometry.py

@@ -0,0 +1,124 @@
+"""几何工具:NMS、点/框与多边形 ROI 的关系。
+
+只依赖标准库 + 纯 Python 计算(numpy 可选加速),保证在 RK/Jetson 上都能跑。
+所有坐标均为像素坐标;ROI 在配置里是**归一化**坐标,使用时用
+:func:`normalized_to_pixel_polygon` 转成像素。
+"""
+
+from __future__ import annotations
+
+from typing import List, Sequence, Tuple
+
+from ..schema import Box
+
+Point = Tuple[float, float]
+Polygon = Sequence[Point]
+
+__all__ = [
+    "box_in_polygon_ratio",
+    "clip_polygon",
+    "nms",
+    "normalized_to_pixel_polygon",
+    "point_in_polygon",
+    "polygon_area",
+]
+
+
+def normalized_to_pixel_polygon(polygon: Polygon, width: float, height: float) -> List[Point]:
+    """归一化多边形 → 像素多边形。"""
+
+    if not polygon:
+        return [(0.0, 0.0), (width, 0.0), (width, height), (0.0, height)]
+    return [(float(x) * width, float(y) * height) for x, y in polygon]
+
+
+def clip_polygon(polygon: Polygon, width: float, height: float) -> List[Point]:
+    """把多边形顶点夹到图像范围内。"""
+
+    return [
+        (min(max(float(x), 0.0), width), min(max(float(y), 0.0), height))
+        for x, y in polygon
+    ]
+
+
+def polygon_area(polygon: Polygon) -> float:
+    """鞋带公式,返回绝对值面积。"""
+
+    if len(polygon) < 3:
+        return 0.0
+    total = 0.0
+    for i in range(len(polygon)):
+        x1, y1 = polygon[i]
+        x2, y2 = polygon[(i + 1) % len(polygon)]
+        total += x1 * y2 - x2 * y1
+    return abs(total) / 2.0
+
+
+def point_in_polygon(point: Point, polygon: Polygon) -> bool:
+    """射线法判断点是否在多边形内(含边界近似)。"""
+
+    if len(polygon) < 3:
+        return False
+    x, y = float(point[0]), float(point[1])
+    inside = False
+    n = len(polygon)
+    for i in range(n):
+        x1, y1 = polygon[i]
+        x2, y2 = polygon[(i + 1) % n]
+        if (y1 > y) != (y2 > y):
+            x_cross = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
+            if x < x_cross:
+                inside = not inside
+    return inside
+
+
+def box_in_polygon_ratio(
+    box: Box,
+    polygon: Polygon,
+    samples_x: int = 7,
+    samples_y: int = 7,
+) -> float:
+    """用网格采样估计"框落在 ROI 内的面积比例"(0..1)。
+
+    比精确多边形裁剪简单得多,且对现场 ROI 精度完全够用;采样点先取中心,
+    保证目标很小时也能被识别到。
+    """
+
+    if len(polygon) < 3 or box.area <= 0:
+        return 0.0
+    sx = max(1, int(samples_x))
+    sy = max(1, int(samples_y))
+    hits = 0
+    total = 0
+    for ix in range(sx):
+        fx = (ix + 0.5) / sx
+        x = box.x1 + fx * box.width
+        for iy in range(sy):
+            fy = (iy + 0.5) / sy
+            y = box.y1 + fy * box.height
+            total += 1
+            if point_in_polygon((x, y), polygon):
+                hits += 1
+    if total == 0:
+        return 0.0
+    return float(hits) / float(total)
+
+
+def nms(boxes: List[Box], iou_threshold: float = 0.5, per_class: bool = True) -> List[Box]:
+    """非极大值抑制。``per_class=True`` 时按类别分别抑制(YOLO 常见做法)。"""
+
+    if not boxes:
+        return []
+    order = sorted(boxes, key=lambda b: b.score, reverse=True)
+    keep: List[Box] = []
+    for box in order:
+        suppressed = False
+        for kept in keep:
+            if per_class and kept.class_id != box.class_id:
+                continue
+            if box.iou(kept) > iou_threshold:
+                suppressed = True
+                break
+        if not suppressed:
+            keep.append(box)
+    return keep

+ 281 - 0
portcv/logic/scene.py

@@ -0,0 +1,281 @@
+"""场景规则判定:把 YOLO 检测框映射成 ``0 / 1 / 2`` 场景编码。
+
+两种工作模式
+------------
+``composed``(默认,推荐)
+    模型检测 ``container / bed / flatbed`` 等目标,本模块用**几何关系**判断集装箱
+    是否落在某种车厢上:
+
+    * 集装箱必须有足够面积落在 ROI 内(``roi_min_ratio``);
+    * 车厢框与集装箱框在横向要有交叠(``support_overlap``);
+    * 车厢顶边要贴近集装箱底边(``support_dy_ratio``,单位是箱高的比例);
+    * 车厢置信度不能明显低于集装箱(``support_score_ratio``)。
+
+    这样做可解释、可现场调参,也便于以后新增 ``person`` 等安全类而不影响既有编码。
+
+``direct``
+    模型直接输出 3 类场景(``not_on_train / bed / flatbed``),本模块只做 ROI 过滤
+    与 argmax。
+
+输出始终是 :class:`~portcv.schema.Observation`,编码含义::
+
+    0 = 集装箱不在车上(没看到箱,或箱底下不是车斗/平板车)
+    1 = 车斗
+    2 = 平板车
+  255 = UNKNOWN(无任何观测 / 未就绪),由上层时序滤波决定是否下发给 PLC
+"""
+
+from __future__ import annotations
+
+import math
+import time
+from typing import Dict, List, Optional, Sequence, Tuple
+
+from ..config import Config
+from ..schema import Box, Observation, SceneState
+from .geometry import box_in_polygon_ratio, normalized_to_pixel_polygon
+
+__all__ = ["SceneClassifier", "GROUP_CONTAINER", "GROUP_BED", "GROUP_FLATBED", "GROUP_IGNORE"]
+
+GROUP_CONTAINER = "container"
+GROUP_BED = "bed"
+GROUP_FLATBED = "flatbed"
+GROUP_IGNORE = "ignore"
+GROUP_UNKNOWN = "unknown"
+
+
+class SceneClassifier:
+    """检测框 → 场景编码。线程内使用,非线程安全。"""
+
+    def __init__(self, cfg: Config) -> None:
+        self.cfg = cfg
+        scene = cfg.section("scene")
+        self.mode = str(scene.get("mode") or cfg.get_path("run.mode", "composed")).lower()
+
+        classes = scene.get("classes") or {}
+        self._groups: Dict[str, set] = {}
+        for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE):
+            self._groups[group] = {self.normalize(n) for n in (classes.get(group) or []) if n}
+
+        # direct 模式:类别名 → 场景编码
+        self._direct_map: Dict[str, int] = {}
+        for name, code in (scene.get("direct_map") or {}).items():
+            self._direct_map[self.normalize(name)] = int(code)
+        for label, code in ((0, 0), (1, 1), (2, 2)):
+            self._direct_map.setdefault(
+                self.normalize(["not_on_train", "bed", "flatbed"][label]), code
+            )
+
+        self.require_container = bool(scene.get("require_container", True))
+        self.min_class_conf = float(scene.get("min_class_conf", 0.30))
+        self.roi_min_ratio = float(scene.get("roi_min_ratio", 0.30))
+        self.support_overlap = float(scene.get("support_overlap", 0.30))
+        self.support_dy_ratio = float(scene.get("support_dy_ratio", 0.45))
+        self.support_score_ratio = float(scene.get("support_score_ratio", 0.60))
+        self.unknown_on_no_detection = bool(scene.get("unknown_on_no_detection", True))
+        self.no_container_conf = float(scene.get("no_container_conf", 0.60))
+
+        self._roi_norm: List[Tuple[float, float]] = cfg.roi
+        self._roi_cache: Dict[Tuple[int, int], List[Tuple[float, float]]] = {}
+
+    # ---------------------------------------------------------------- 工具
+    @staticmethod
+    def normalize(name: str) -> str:
+        return str(name or "").strip().lower().replace("-", "_").replace(" ", "_")
+
+    def group_of(self, class_name: str) -> str:
+        """类别名 → 语义分组。"""
+
+        name = self.normalize(class_name)
+        for group in (GROUP_CONTAINER, GROUP_BED, GROUP_FLATBED, GROUP_IGNORE):
+            if name in self._groups[group]:
+                return group
+        return GROUP_UNKNOWN
+
+    def roi_polygon(self, width: int, height: int) -> List[Tuple[float, float]]:
+        key = (int(width), int(height))
+        if key not in self._roi_cache:
+            self._roi_cache[key] = normalized_to_pixel_polygon(self._roi_norm, width, height)
+        return self._roi_cache[key]
+
+    # ------------------------------------------------------------ 主入口
+    def classify(
+        self,
+        detections: Sequence[Box],
+        frame_size: Tuple[int, int],
+        ts: Optional[float] = None,
+        frame_id: int = 0,
+    ) -> Observation:
+        """``frame_size`` 为 ``(width, height)``。"""
+
+        ts = float(ts if ts is not None else time.time())
+        width, height = int(frame_size[0]), int(frame_size[1])
+        boxes = [b for b in detections if float(b.score) >= self.min_class_conf]
+        if self.mode == "direct":
+            return self._classify_direct(boxes, width, height, ts, frame_id)
+        return self._classify_composed(boxes, width, height, ts, frame_id)
+
+    # --------------------------------------------------------- direct 模式
+    def _classify_direct(
+        self,
+        boxes: List[Box],
+        width: int,
+        height: int,
+        ts: float,
+        frame_id: int,
+    ) -> Observation:
+        poly = self.roi_polygon(width, height)
+        best: Optional[Tuple[Box, int, float]] = None  # (box, state, score)
+        for box in boxes:
+            name = self.normalize(box.class_name)
+            if name not in self._direct_map:
+                continue
+            ratio = box_in_polygon_ratio(box, poly)
+            if ratio < self.roi_min_ratio:
+                continue
+            score = float(box.score) * (0.5 + 0.5 * ratio)
+            if best is None or score > best[2]:
+                best = (box, int(self._direct_map[name]), score)
+        if best is None:
+            if self.unknown_on_no_detection:
+                return Observation(ts, int(SceneState.UNKNOWN), 0.0, list(boxes), "no_direct_hit", frame_id)
+            return Observation(
+                ts, int(SceneState.NOT_ON_TRAIN), self.no_container_conf, list(boxes), "no_direct_hit", frame_id
+            )
+        box, state, score = best
+        return Observation(
+            ts,
+            state,
+            min(1.0, float(box.score)),
+            list(boxes),
+            "direct:%s=%.2f" % (box.class_name, box.score),
+            frame_id,
+        )
+
+    # ------------------------------------------------------- composed 模式
+    @staticmethod
+    def _overlap_x1d(a1: float, a2: float, b1: float, b2: float) -> float:
+        """一维交叠长度占较短区间长度的比例(0..1)。"""
+
+        inter = min(a2, b2) - max(a1, b1)
+        if inter <= 0:
+            return 0.0
+        shorter = min(a2 - a1, b2 - b1)
+        return float(inter / shorter) if shorter > 0 else 0.0
+
+    def _support_quality(self, container: Box, wagon: Box) -> Optional[Tuple[float, float]]:
+        """判断车厢是否"托着"集装箱,返回 ``(横向交叠, 匹配质量)``,不匹配则 None。"""
+
+        if container.height <= 0:
+            return None
+        if wagon.score < self.support_score_ratio * container.score:
+            return None
+        # 车厢顶边不应明显高于集装箱顶边(否则多半是别的车厢/背景)
+        if wagon.top < container.top - 0.05 * container.height:
+            return None
+        ov_x = self._overlap_x1d(container.x1, container.x2, wagon.x1, wagon.x2)
+        if ov_x < self.support_overlap:
+            return None
+        dy_ratio = abs(wagon.top - container.bottom) / container.height
+        if dy_ratio > self.support_dy_ratio:
+            return None
+        tol = max(self.support_dy_ratio, 1e-6)
+        quality = ov_x * max(0.2, 1.0 - 0.5 * (dy_ratio / tol))
+        return ov_x, quality
+
+    def _best_support(
+        self, container: Box, wagons: List[Tuple[Box, float]]
+    ) -> Optional[Tuple[Box, float, float, float]]:
+        """返回 ``(车厢框, 匹配分数, 横向交叠, 车厢ROI比例)``,取分数最高者。"""
+
+        best: Optional[Tuple[Box, float, float, float]] = None
+        for wagon, roi_ratio in wagons:
+            matched = self._support_quality(container, wagon)
+            if matched is None:
+                continue
+            ov_x, quality = matched
+            score = float(wagon.score) * quality
+            if best is None or score > best[1]:
+                best = (wagon, score, ov_x, roi_ratio)
+        return best
+
+    def _classify_composed(
+        self,
+        boxes: List[Box],
+        width: int,
+        height: int,
+        ts: float,
+        frame_id: int,
+    ) -> Observation:
+        if not boxes:
+            if self.unknown_on_no_detection:
+                return Observation(
+                    ts, int(SceneState.UNKNOWN), 0.0, [], "no_detection", frame_id
+                )
+            return Observation(
+                ts,
+                int(SceneState.NOT_ON_TRAIN),
+                self.no_container_conf,
+                [],
+                "no_detection",
+                frame_id,
+            )
+
+        poly = self.roi_polygon(width, height)
+        containers: List[Tuple[Box, float]] = []
+        beds: List[Tuple[Box, float]] = []
+        flats: List[Tuple[Box, float]] = []
+        for box in boxes:
+            group = self.group_of(box.class_name)
+            if group == GROUP_IGNORE or group == GROUP_UNKNOWN:
+                continue
+            ratio = box_in_polygon_ratio(box, poly)
+            if ratio < self.roi_min_ratio:
+                continue
+            if group == GROUP_CONTAINER:
+                containers.append((box, ratio))
+            elif group == GROUP_BED:
+                beds.append((box, ratio))
+            elif group == GROUP_FLATBED:
+                flats.append((box, ratio))
+
+        if not containers:
+            # ROI 内没有集装箱 → "集装箱不在车上"
+            wagon_score = max([b.score for b, _ in beds] + [b.score for b, _ in flats] + [0.0])
+            conf = min(1.0, 0.55 + 0.35 * wagon_score)
+            reason = "no_container" + ("_wagon_seen=%.2f" % wagon_score if wagon_score else "")
+            return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id)
+
+        container = max(containers, key=lambda item: item[0].score * (0.5 + 0.5 * item[1]))[0]
+        bed_hit = self._best_support(container, beds)
+        flat_hit = self._best_support(container, flats)
+
+        if bed_hit is None and flat_hit is None:
+            # 有箱,但底下既不是车斗也不是平板车(吊起来/在卡车上/堆场)
+            conf = min(0.75, 0.40 + 0.25 * container.score)
+            reason = "container_without_wagon(c=%.2f)" % container.score
+            return Observation(ts, int(SceneState.NOT_ON_TRAIN), conf, list(boxes), reason, frame_id)
+
+        candidates = []
+        if bed_hit is not None:
+            candidates.append((int(SceneState.BED), bed_hit, "bed"))
+        if flat_hit is not None:
+            candidates.append((int(SceneState.FLATBED), flat_hit, "flatbed"))
+        state, hit, tag = max(candidates, key=lambda item: item[1][1])
+        wagon, sup_score, ov_x, _wagon_ratio = hit
+        conf = (container.score * wagon.score) ** 0.5 * (0.55 + 0.45 * ov_x)
+        ambiguous = len(candidates) > 1 and max(c[1][1] for c in candidates) < 1.10 * min(
+            c[1][1] for c in candidates
+        )
+        if ambiguous:
+            conf *= 0.85  # 两种车厢都像 → 降权,交给时序滤波去稳定
+        reason = "c=%.2f %s=%.2f ov=%.2f%s" % (
+            container.score,
+            tag,
+            wagon.score,
+            ov_x,
+            " ambiguous" if ambiguous else "",
+        )
+        return Observation(ts, int(state), min(1.0, conf), list(boxes), reason, frame_id)
+
+

+ 67 - 0
portcv/plc/__init__.py

@@ -0,0 +1,67 @@
+"""PLC 通信层。
+
+对外只暴露三样东西:
+
+* :func:`build_publisher` —— 按配置创建发布器(Modbus 从站 / S7 推送 / 两者);
+* :class:`~portcv.plc.publisher.PlcPublisher` —— 发布器接口;
+* :class:`~portcv.plc.modbus_server.ModbusTcpServer` —— 需要自己做探测/自检时直接用。
+
+寄存器映射与 PLC 侧约定详见 :mod:`portcv.schema`(数据来源)与
+:mod:`portcv.plc.modbus_server`(地址规划)。
+"""
+
+from .modbus_server import ModbusTcpServer
+from .publisher import (
+    ModbusServerPublisher,
+    MultiPublisher,
+    NullPublisher,
+    PlcPublisher,
+    build_publisher,
+)
+from .registers import (
+    CMD_CLEAR_STATS,
+    CMD_IDLE,
+    CMD_LABELS,
+    CMD_REQUEST,
+    CMD_RESET,
+    COMMAND_FIELD_NOTES,
+    SCL_SNIPPET,
+    SNAPSHOT_FIELD_NOTES,
+    addresses,
+    command_rows,
+    decode_command,
+    decode_snapshot,
+    encode_command,
+    encode_snapshot,
+    flag_bits,
+    holding_offsets,
+    input_offsets,
+    snapshot_rows,
+)
+
+__all__ = [
+    "CMD_CLEAR_STATS",
+    "CMD_IDLE",
+    "CMD_LABELS",
+    "CMD_REQUEST",
+    "CMD_RESET",
+    "COMMAND_FIELD_NOTES",
+    "ModbusServerPublisher",
+    "ModbusTcpServer",
+    "MultiPublisher",
+    "NullPublisher",
+    "PlcPublisher",
+    "SCL_SNIPPET",
+    "SNAPSHOT_FIELD_NOTES",
+    "addresses",
+    "build_publisher",
+    "command_rows",
+    "decode_command",
+    "decode_snapshot",
+    "encode_command",
+    "encode_snapshot",
+    "flag_bits",
+    "holding_offsets",
+    "input_offsets",
+    "snapshot_rows",
+]

+ 126 - 0
portcv/plc/modbus_pdu.py

@@ -0,0 +1,126 @@
+"""Modbus/TCP 报文编解码(纯函数,便于单元测试与命令行探测工具复用)。
+
+支持的 PDU 功能码
+-----------------
+* ``0x03`` 读保持寄存器(PLC → 视觉的指令区)
+* ``0x04`` 读输入寄存器(视觉 → PLC 的结果区,本项目的核心数据)
+* ``0x06`` 写单个保持寄存器
+* ``0x10`` 写多个保持寄存器
+
+MBAP 头:``事务号(2) 协议号(2)=0 长度(2) 单元号(1)``。
+"""
+
+from __future__ import annotations
+
+import struct
+from typing import List, Optional, Sequence, Tuple
+
+__all__ = [
+    "FC_READ_COILS",
+    "FC_READ_DISCRETE_INPUTS",
+    "FC_READ_HOLDING_REGISTERS",
+    "FC_READ_INPUT_REGISTERS",
+    "FC_WRITE_MULTIPLE_REGISTERS",
+    "FC_WRITE_SINGLE_COIL",
+    "FC_WRITE_SINGLE_REGISTER",
+    "EXCEPTION_CODES",
+    "MBAP_HEADER_LEN",
+    "build_exception_response",
+    "build_request",
+    "bytes_to_u16s",
+    "parse_mbap",
+    "parse_read_response",
+    "u16s_to_bytes",
+]
+
+MBAP_HEADER_LEN = 7
+
+FC_READ_COILS = 0x01
+FC_READ_DISCRETE_INPUTS = 0x02
+FC_READ_HOLDING_REGISTERS = 0x03
+FC_READ_INPUT_REGISTERS = 0x04
+FC_WRITE_SINGLE_COIL = 0x05
+FC_WRITE_SINGLE_REGISTER = 0x06
+FC_WRITE_MULTIPLE_REGISTERS = 0x10
+
+EXCEPTION_CODES = {
+    0x01: "非法功能码",
+    0x02: "非法数据地址",
+    0x03: "非法数据值",
+    0x04: "从站设备故障",
+    0x05: "确认(正在处理)",
+    0x06: "设备忙",
+}
+
+
+def parse_mbap(data: bytes) -> Tuple[int, int, int, int, bytes]:
+    """解析 MBAP + PDU,返回 ``(事务号, 协议号, 长度, 单元号, pdu)``。"""
+
+    if len(data) < MBAP_HEADER_LEN:
+        raise ValueError("报文长度不足: %d" % len(data))
+    tx_id, proto_id, length, unit_id = struct.unpack(">HHHB", data[:MBAP_HEADER_LEN])
+    pdu = bytes(data[MBAP_HEADER_LEN:])
+    if len(pdu) != length - 1:
+        # 允许 PDU 多带字节(部分网关如此),取 length-1
+        pdu = pdu[: max(0, length - 1)]
+    return int(tx_id), int(proto_id), int(length), int(unit_id), pdu
+
+
+def build_frame(tx_id: int, unit_id: int, pdu: bytes) -> bytes:
+    """MBAP 封装。``length`` 包含单元号 + PDU。"""
+
+    header = struct.pack(">HHHB", int(tx_id) & 0xFFFF, 0, len(pdu) + 1, int(unit_id) & 0xFF)
+    return header + pdu
+
+
+def build_request(
+    tx_id: int,
+    unit_id: int,
+    function: int,
+    address: int,
+    quantity: Optional[int] = None,
+    values: Optional[Sequence[int]] = None,
+    single_value: Optional[int] = None,
+) -> bytes:
+    """构造客户端请求(本项目的探测工具与测试用)。"""
+
+    func = int(function)
+    if func in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS, FC_READ_COILS, FC_READ_DISCRETE_INPUTS):
+        pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(quantity or 1) & 0xFFFF)
+    elif func == FC_WRITE_SINGLE_REGISTER:
+        pdu = struct.pack(">BHH", func, int(address) & 0xFFFF, int(single_value or 0) & 0xFFFF)
+    elif func == FC_WRITE_MULTIPLE_REGISTERS:
+        words = list(values or [])
+        payload = struct.pack(">HHB", int(address) & 0xFFFF, len(words), len(words) * 2)
+        pdu = struct.pack(">B", func) + payload + u16s_to_bytes(words)
+    else:
+        raise ValueError("未支持的请求功能码: 0x%02X" % func)
+    return build_frame(tx_id, unit_id, pdu)
+
+
+def build_exception_response(tx_id: int, unit_id: int, function: int, code: int) -> bytes:
+    pdu = struct.pack(">BB", (int(function) | 0x80) & 0xFF, int(code) & 0xFF)
+    return build_frame(tx_id, unit_id, pdu)
+
+
+def u16s_to_bytes(words: Sequence[int]) -> bytes:
+    return b"".join(struct.pack(">H", int(w) & 0xFFFF) for w in words)
+
+
+def bytes_to_u16s(data: bytes) -> List[int]:
+    return [int(v) for v in struct.unpack(">%dH" % (len(data) // 2), data[: (len(data) // 2) * 2])]
+
+
+def parse_read_response(pdu: bytes) -> List[int]:
+    """解析 ``0x03/0x04`` 响应 PDU → 寄存器列表;异常响应当 :class:`RuntimeError` 抛出。"""
+
+    if not pdu:
+        raise ValueError("空 PDU")
+    func = pdu[0]
+    if func & 0x80:
+        code = pdu[1] if len(pdu) > 1 else 0
+        raise RuntimeError("Modbus 异常响应: 0x%02X %s" % (code, EXCEPTION_CODES.get(code, "未知")))
+    if func not in (FC_READ_HOLDING_REGISTERS, FC_READ_INPUT_REGISTERS):
+        raise ValueError("不是读寄存器响应: 0x%02X" % func)
+    byte_count = pdu[1]
+    return bytes_to_u16s(pdu[2 : 2 + byte_count])

+ 326 - 0
portcv/plc/modbus_server.py

@@ -0,0 +1,326 @@
+"""Modbus/TCP 服务端:把视觉结果暴露成寄存器块,供西门子 PLC 周期读取。
+
+为什么不用 pymodbus?
+---------------------
+现场只用到 4 个功能码,自己实现 ~200 行即可,能避免 pymodbus 3.x 的 API 变动、
+asyncio 版本差异和"启动器/数据存储"概念带来的排障成本;同时寄存器映射逻辑
+(:mod:`portcv.schema`)与 :mod:`portcv.plc.modbus_pdu` 可以单元测试覆盖。
+
+寄存器规划(地址 = 配置项 ``plc.modbus.input_addr`` / ``holding_addr`` + 偏移)
+------------------------------------------------------------------------
+输入寄存器(FC4,PLC 读,视觉写,12 个字)::
+
+    0   state            0=不在车上 1=车斗 2=平板车;V2 不再发布 255
+    1   confidence       千分比 0..1000
+    2   flags            状态位(见 schema.StatusBits)
+    3   seq_hi           结果序号高 16bit(状态每变化一次 +1)
+    4   seq_lo
+    5   ts_hi            unix 秒高 16bit
+    6   ts_lo
+    7   heartbeat        心跳计数(每心跳周期 +1,PLC 用它判断视觉是否存活)
+    8   fps_x10          帧率 x10
+    9   latency_ms       单帧端到端耗时
+    10  reserved
+    11  crc16            CRC-16/MODBUS(前 11 个字,大端字节序)
+
+保持寄存器(FC3/FC6/FC16,PLC 写,视觉读,4 个字)::
+
+    0   cmd              0=空闲 1=请求识别 2=复位 3=清统计
+    1   preset           相机/ROI 预设编号
+    2   min_conf         覆盖最小置信度(千分比,0=用配置)
+    3   reserved
+"""
+
+from __future__ import annotations
+
+import socketserver
+import threading
+import time
+from typing import Callable, Dict, List, Optional, Sequence
+
+from ..logging_utils import get_logger
+from ..schema import PlcCommand, VisionSnapshot
+from .modbus_pdu import (
+    EXCEPTION_CODES,
+    FC_READ_HOLDING_REGISTERS,
+    FC_READ_INPUT_REGISTERS,
+    FC_WRITE_MULTIPLE_REGISTERS,
+    FC_WRITE_SINGLE_REGISTER,
+    MBAP_HEADER_LEN,
+    build_exception_response,
+    build_frame,
+    bytes_to_u16s,
+    parse_mbap,
+    u16s_to_bytes,
+)
+
+__all__ = ["ModbusTcpServer"]
+
+LOGGER = get_logger("plc.modbus")
+
+
+class _Handler(socketserver.BaseRequestHandler):
+    """一个 PLC 连接 = 一个线程,循环处理请求。"""
+
+    server: "ModbusTcpServer"  # type: ignore[assignment]
+
+    def handle(self) -> None:  # noqa: D102
+        sock = self.request
+        sock.settimeout(30.0)
+        peer = "%s:%s" % self.client_address[:2]
+        self.server.on_client_connected(peer)
+        try:
+            while not self.server.is_stopping():
+                header = self._recv_exact(MBAP_HEADER_LEN)
+                if header is None:
+                    break
+                length = int.from_bytes(header[4:6], "big")
+                # 与 C++ service_client 同口径:length 含 unit_id,最小 2、最大 254
+                # (PDU 253)。非法长度直接断连,避免错位/恶意报文把连接线程
+                # 吊在 30 s 超时上,或让服务端按 64 KB 去缓冲。
+                if length < 2 or length > 254:
+                    break
+                body = self._recv_exact(max(0, length - 1))
+                if body is None:
+                    break
+                response = self.server.handle_frame(header + body, peer)
+                if response:
+                    sock.sendall(response)
+        except (ConnectionResetError, OSError):
+            pass
+        finally:
+            self.server.on_client_disconnected(peer)
+
+    def _recv_exact(self, size: int) -> Optional[bytes]:
+        chunks = b""
+        while len(chunks) < size:
+            try:
+                piece = self.request.recv(size - len(chunks))
+            except (ConnectionResetError, OSError):
+                return None
+            if not piece:
+                return None
+            chunks += piece
+        return chunks
+
+
+class ModbusTcpServer(socketserver.ThreadingTCPServer):
+    """线程化 Modbus/TCP 从站。
+
+    ``on_command`` 会在 PLC 写入保持寄存器后回调 ``(registers, peer)``,
+    服务主循环据此响应"按需识别/复位"等命令。
+    """
+
+    allow_reuse_address = True
+    daemon_threads = True
+
+    #: 输入寄存器块大小(字)
+    INPUT_SIZE = VisionSnapshot.register_count()
+    #: 保持寄存器块大小(字)
+    HOLDING_SIZE = PlcCommand.register_count()
+
+    def __init__(
+        self,
+        host: str = "0.0.0.0",
+        port: int = 1502,
+        unit_id: int = 1,
+        allow_unit_any: bool = True,
+        input_addr: int = 0,
+        holding_addr: int = 0,
+        on_command: Optional[Callable[[List[int], str], None]] = None,
+    ) -> None:
+        self.host = host
+        self.port = int(port)
+        self.unit_id = int(unit_id)
+        self.allow_unit_any = bool(allow_unit_any)
+        self.input_addr = int(input_addr)
+        self.holding_addr = int(holding_addr)
+        self.on_command = on_command
+
+        self._lock = threading.RLock()
+        self._inputs: List[int] = [0] * self.INPUT_SIZE
+        self._holdings: List[int] = [0] * self.HOLDING_SIZE
+        self._stopping = False
+        self._clients: Dict[str, float] = {}
+        self.stats: Dict[str, int] = {"requests": 0, "reads": 0, "writes": 0, "errors": 0}
+        self._publisher_thread: Optional[threading.Thread] = None
+
+        super().__init__((host, int(port)), _Handler)
+        LOGGER.info("Modbus/TCP 服务端已监听 %s:%d (unit=%d)", host, port, unit_id)
+
+    # ------------------------------------------------------------ 生命周期
+    def start(self) -> "ModbusTcpServer":
+        self._stopping = False
+        self._publisher_thread = threading.Thread(
+            target=self.serve_forever, name="modbus-server", daemon=True
+        )
+        self._publisher_thread.start()
+        return self
+
+    def stop(self, timeout: float = 3.0) -> None:
+        self._stopping = True
+        try:
+            self.shutdown()
+        except Exception:  # pragma: no cover
+            pass
+        self.server_close()
+        if self._publisher_thread is not None:
+            self._publisher_thread.join(timeout=timeout)
+            self._publisher_thread = None
+
+    def is_stopping(self) -> bool:
+        return bool(self._stopping)
+
+    # ------------------------------------------------------ 数据块访问接口
+    def set_snapshot(self, snapshot: VisionSnapshot) -> List[int]:
+        """把快照写入输入寄存器块,返回写入的字(便于自检/测试)。"""
+
+        words = snapshot.to_registers()
+        with self._lock:
+            self._inputs = list(words)
+        return words
+
+    def input_registers(self) -> List[int]:
+        with self._lock:
+            return list(self._inputs)
+
+    def holding_registers(self) -> List[int]:
+        with self._lock:
+            return list(self._holdings)
+
+    def command(self) -> PlcCommand:
+        with self._lock:
+            return PlcCommand.from_registers(self._holdings)
+
+    def set_holding_registers(self, values: Sequence[int], offset: int = 0) -> None:
+        """测试/上位机预置指令用。"""
+
+        with self._lock:
+            for i, value in enumerate(values):
+                index = int(offset) + i
+                if 0 <= index < self.HOLDING_SIZE:
+                    self._holdings[index] = int(value) & 0xFFFF
+
+    @property
+    def client_count(self) -> int:
+        with self._lock:
+            return len(self._clients)
+
+    def clients(self) -> Dict[str, float]:
+        with self._lock:
+            return dict(self._clients)
+
+    def on_client_connected(self, peer: str) -> None:
+        with self._lock:
+            self._clients[peer] = time.time()
+        LOGGER.info("PLC 已连接: %s", peer)
+
+    def on_client_disconnected(self, peer: str) -> None:
+        with self._lock:
+            self._clients.pop(peer, None)
+        LOGGER.info("PLC 断开: %s", peer)
+
+    # ------------------------------------------------------------ 报文处理
+    def handle_frame(self, frame: bytes, peer: str = "") -> bytes:
+        """处理一个完整 MBAP 帧,返回响应字节(空字节 = 不响应)。"""
+
+        try:
+            tx_id, proto_id, _length, unit_id, pdu = parse_mbap(frame)
+        except ValueError as exc:
+            self.stats["errors"] += 1
+            LOGGER.warning("报文解析失败(%s): %s", peer, exc)
+            return b""
+        if not self.allow_unit_any and unit_id != self.unit_id:
+            return b""
+        if proto_id != 0 or not pdu:
+            self.stats["errors"] += 1
+            return build_exception_response(tx_id, unit_id, pdu[0] if pdu else 0, 0x03)
+        # 注意:allow_unit_any 只表示“接受任意站点号”,响应必须原样回显请求的
+        # unit_id(Modbus/TCP 规范)。不能改成配置里的 self.unit_id,否则 PLC 用
+        # 非 1 的站点号时会把响应当成别的从站而丢弃/超时。
+
+        func = pdu[0]
+        self.stats["requests"] += 1
+        if func == FC_READ_INPUT_REGISTERS:
+            self.stats["reads"] += 1
+            return self._read_registers(tx_id, unit_id, func, pdu, self._inputs, self.input_addr)
+        if func == FC_READ_HOLDING_REGISTERS:
+            self.stats["reads"] += 1
+            return self._read_registers(tx_id, unit_id, func, pdu, self._holdings, self.holding_addr)
+        if func == FC_WRITE_SINGLE_REGISTER:
+            self.stats["writes"] += 1
+            return self._write_single(tx_id, unit_id, pdu, peer)
+        if func == FC_WRITE_MULTIPLE_REGISTERS:
+            self.stats["writes"] += 1
+            return self._write_multiple(tx_id, unit_id, pdu, peer)
+        self.stats["errors"] += 1
+        LOGGER.debug("未支持的功能码 0x%02X(来自 %s)", func, peer)
+        return build_exception_response(tx_id, unit_id, func, 0x01)
+
+    def _read_registers(
+        self, tx_id: int, unit_id: int, func: int, pdu: bytes, block: List[int], base_addr: int
+    ) -> bytes:
+        if len(pdu) < 5:
+            return build_exception_response(tx_id, unit_id, func, 0x03)
+        address = int.from_bytes(pdu[1:3], "big")
+        quantity = int.from_bytes(pdu[3:5], "big")
+        if quantity < 1 or quantity > 125:
+            self.stats["errors"] += 1
+            return build_exception_response(tx_id, unit_id, func, 0x03)
+        offset = address - int(base_addr)
+        if offset < 0 or offset + quantity > len(block):
+            self.stats["errors"] += 1
+            LOGGER.debug("非法地址: %d 数量 %d(块大小 %d)", address, quantity, len(block))
+            return build_exception_response(tx_id, unit_id, func, 0x02)
+        with self._lock:
+            words = list(block[offset : offset + quantity])
+        payload = bytes([len(words) * 2]) + u16s_to_bytes(words)
+        return build_frame(tx_id, unit_id, bytes([func]) + payload)
+
+    def _write_single(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
+        if len(pdu) < 5:
+            return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x03)
+        address = int.from_bytes(pdu[1:3], "big")
+        value = int.from_bytes(pdu[3:5], "big")
+        offset = address - self.holding_addr
+        if offset < 0 or offset >= len(self._holdings):
+            self.stats["errors"] += 1
+            return build_exception_response(tx_id, unit_id, FC_WRITE_SINGLE_REGISTER, 0x02)
+        with self._lock:
+            self._holdings[offset] = value & 0xFFFF
+            registers = list(self._holdings)
+        self._notify(registers, peer)
+        return build_frame(tx_id, unit_id, pdu[:5])
+
+    def _write_multiple(self, tx_id: int, unit_id: int, pdu: bytes, peer: str) -> bytes:
+        if len(pdu) < 6:
+            return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
+        address = int.from_bytes(pdu[1:3], "big")
+        quantity = int.from_bytes(pdu[3:5], "big")
+        byte_count = pdu[5]
+        if quantity < 1 or quantity > 123 or byte_count != quantity * 2:
+            self.stats["errors"] += 1
+            return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x03)
+        values = bytes_to_u16s(pdu[6 : 6 + byte_count])
+        offset = address - self.holding_addr
+        if offset < 0 or offset + quantity > len(self._holdings) or len(values) < quantity:
+            self.stats["errors"] += 1
+            return build_exception_response(tx_id, unit_id, FC_WRITE_MULTIPLE_REGISTERS, 0x02)
+        with self._lock:
+            for i in range(quantity):
+                self._holdings[offset + i] = values[i] & 0xFFFF
+            registers = list(self._holdings)
+        self._notify(registers, peer)
+        return build_frame(
+            tx_id, unit_id, bytes([FC_WRITE_MULTIPLE_REGISTERS]) + u16s_to_bytes([address, quantity])
+        )
+
+    def _notify(self, registers: List[int], peer: str) -> None:
+        if self.on_command is None:
+            return
+        try:
+            self.on_command(registers, peer)
+        except Exception:  # pragma: no cover - 回调异常不能影响 Modbus 通信
+            LOGGER.exception("on_command 回调异常(来自 %s)", peer)
+
+

+ 247 - 0
portcv/plc/publisher.py

@@ -0,0 +1,247 @@
+"""PLC 发布层:把 :class:`VisionSnapshot` 送出去,并把 PLC 指令收进来。
+
+三种模式(``plc.push``)
+-----------------------
+``modbus_server``(默认,推荐)
+    视觉侧做 Modbus/TCP **从站**,PLC 做客户端周期读输入寄存器(FC4),
+    同时把指令写到保持寄存器(FC6/FC16)。西门子 PLC 用 ``MB_CLIENT`` 指令即可,
+    不需要额外库,联调最省事。
+``snap7``
+    PLC 做服务端,视觉侧用 S7comm(``python-snap7``)主动写 DB 块,
+    适合 PLC 侧不方便发起轮询、或要走 S7 通信(如 1500 的 PUT/GET)。
+``both``
+    两条链路同时写,互为冗余(现场切换/过渡期常用)。
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Dict, List, Optional
+
+from ..config import Config
+from ..logging_utils import get_logger
+from ..schema import PlcCommand, VisionSnapshot
+
+__all__ = [
+    "MultiPublisher",
+    "NullPublisher",
+    "PlcPublisher",
+    "ModbusServerPublisher",
+    "build_publisher",
+]
+
+LOGGER = get_logger("plc")
+
+
+class PlcPublisher:
+    """发布接口。``publish`` 必须尽量快、非阻塞(现场节拍不允许被网络拖住)。"""
+
+    name = "base"
+
+    def start(self) -> None:
+        """建立连接/开始监听。"""
+
+    def publish(self, snapshot: VisionSnapshot) -> bool:
+        raise NotImplementedError
+
+    def command(self) -> PlcCommand:
+        """当前 PLC 指令(未实现则返回空指令)。"""
+
+        return PlcCommand()
+
+    def take_command(self) -> Optional[PlcCommand]:
+        """取走一条尚未处理的新指令(服务主循环轮询)。"""
+
+        return None
+
+    def stop(self) -> None:
+        """释放资源。"""
+
+    @property
+    def ok(self) -> bool:
+        return True
+
+    def status(self) -> Dict[str, object]:
+        return {"publisher": self.name, "ok": self.ok}
+
+
+class NullPublisher(PlcPublisher):
+    """不连 PLC,只打日志(``plc.enabled=false`` 或纯离线调试用)。"""
+
+    name = "none"
+
+    def __init__(self) -> None:
+        self._last: Optional[VisionSnapshot] = None
+
+    def publish(self, snapshot: VisionSnapshot) -> bool:
+        if self._last is None or int(self._last.state) != int(snapshot.state):
+            LOGGER.info(
+                "PLCoFF state=%d(%s) conf=%d seq=%d",
+                int(snapshot.state),
+                snapshot.to_dict()["state_label"],
+                int(snapshot.confidence),
+                int(snapshot.seq),
+            )
+        self._last = snapshot
+        return True
+
+
+class ModbusServerPublisher(PlcPublisher):
+    """Modbus/TCP 从站发布器(PLC 主动读)。"""
+
+    name = "modbus_server"
+
+    def __init__(self, cfg: Config) -> None:
+        from .modbus_server import ModbusTcpServer
+
+        modbus = cfg.get_path("plc.modbus", {}) or {}
+        self._lock = threading.Lock()
+        self._generation = 0
+        self._consumed = 0
+        self._command = PlcCommand()
+        self._last_publish_ts = 0.0
+        self._publish_count = 0
+        self.server = ModbusTcpServer(
+            host=str(modbus.get("host", "0.0.0.0")),
+            port=int(modbus.get("port", 1502)),
+            unit_id=int(modbus.get("unit_id", 1)),
+            allow_unit_any=bool(modbus.get("allow_unit_any", True)),
+            input_addr=int(modbus.get("input_addr", 0)),
+            holding_addr=int(modbus.get("holding_addr", 0)),
+            on_command=self._on_write,
+        )
+
+    # -- PlcPublisher 接口 -------------------------------------------------
+    def start(self) -> None:
+        self.server.start()
+        LOGGER.info("Modbus 发布器就绪:%s:%d", self.server.host, self.server.port)
+
+    def publish(self, snapshot: VisionSnapshot) -> bool:
+        self.server.set_snapshot(snapshot)
+        with self._lock:
+            self._last_publish_ts = time.time()
+            self._publish_count += 1
+        return True
+
+    def command(self) -> PlcCommand:
+        with self._lock:
+            return self._command
+
+    def take_command(self) -> Optional[PlcCommand]:
+        with self._lock:
+            if self._generation <= self._consumed:
+                return None
+            self._consumed = self._generation
+            return self._command
+
+    def stop(self) -> None:
+        try:
+            self.server.stop()
+        except Exception:  # pragma: no cover
+            pass
+
+    # -- 内部 -------------------------------------------------------------
+    def _on_write(self, registers: List[int], peer: str) -> None:
+        command = PlcCommand.from_registers(registers)
+        with self._lock:
+            self._command = command
+            self._generation += 1
+        LOGGER.info(
+            "收到 PLC 指令 cmd=%d preset=%d min_conf=%d (来自 %s)",
+            command.cmd,
+            command.preset,
+            command.min_conf,
+            peer,
+        )
+
+    @property
+    def ok(self) -> bool:
+        return bool(self.server.client_count > 0)
+
+    def status(self) -> Dict[str, object]:
+        with self._lock:
+            return {
+                "publisher": self.name,
+                "listen": "%s:%d" % (self.server.host, self.server.port),
+                "clients": self.server.client_count,
+                "publish_count": self._publish_count,
+                "generation": self._generation,
+                "stats": dict(self.server.stats),
+            }
+
+
+class MultiPublisher(PlcPublisher):
+    """同时向多个发布器写入(任一失败不影响其它)。"""
+
+    name = "multi"
+
+    def __init__(self, publishers: List[PlcPublisher]) -> None:
+        self.publishers = list(publishers)
+
+    def start(self) -> None:
+        for publisher in self.publishers:
+            try:
+                publisher.start()
+            except Exception:
+                LOGGER.exception("发布器 %s 启动失败", publisher.name)
+
+    def publish(self, snapshot: VisionSnapshot) -> bool:
+        ok = False
+        for publisher in self.publishers:
+            try:
+                ok = publisher.publish(snapshot) or ok
+            except Exception:
+                LOGGER.exception("发布器 %s 写入失败", publisher.name)
+        return ok
+
+    def command(self) -> PlcCommand:
+        for publisher in self.publishers:
+            command = publisher.command()
+            if int(command.cmd) != 0:
+                return command
+        return self.publishers[0].command() if self.publishers else PlcCommand()
+
+    def take_command(self) -> Optional[PlcCommand]:
+        for publisher in self.publishers:
+            command = publisher.take_command()
+            if command is not None:
+                return command
+        return None
+
+    def stop(self) -> None:
+        for publisher in self.publishers:
+            try:
+                publisher.stop()
+            except Exception:  # pragma: no cover
+                pass
+
+    @property
+    def ok(self) -> bool:
+        return any(p.ok for p in self.publishers)
+
+    def status(self) -> Dict[str, object]:
+        return {"publisher": self.name, "children": [p.status() for p in self.publishers]}
+
+
+def build_publisher(cfg: Config) -> PlcPublisher:
+    """按 ``plc.enabled`` / ``plc.push`` 创建发布器。"""
+
+    if not bool(cfg.get_path("plc.enabled", True)):
+        return NullPublisher()
+    mode = str(cfg.get_path("plc.push", "modbus_server")).lower()
+    publishers: List[PlcPublisher] = []
+    if mode in ("modbus_server", "modbus", "both"):
+        publishers.append(ModbusServerPublisher(cfg))
+    if mode in ("snap7", "s7", "both"):
+        from .snap7_client import Snap7Publisher
+
+        publishers.append(Snap7Publisher(cfg))
+    if not publishers:
+        LOGGER.warning("plc.push=%s 无法识别,退化为不连 PLC", mode)
+        return NullPublisher()
+    if len(publishers) == 1:
+        return publishers[0]
+    return MultiPublisher(publishers)
+
+

+ 277 - 0
portcv/plc/registers.py

@@ -0,0 +1,277 @@
+"""寄存器映射的**唯一事实来源**(现场联调清单 / PLC 侧对照表)。
+
+为什么单独一个模块?
+--------------------
+寄存器布局此前散落在三处(:mod:`portcv.schema` 的编解码、:mod:`portcv.plc.modbus_server`
+的地址块、``cli registers`` 的打印文本),改一个字宽就要改三遍。现在统一到这里:
+
+* 布局表 :data:`VisionSnapshot.REGISTER_LAYOUT` / :data:`PlcCommand.REGISTER_LAYOUT`
+  (在 :mod:`portcv.schema`,因为编解码要用);
+* 字段含义 :data:`SNAPSHOT_FIELD_NOTES` / :data:`COMMAND_FIELD_NOTES`;
+* 地址展开 :func:`snapshot_rows` / :func:`command_rows`;
+* 编解码 :func:`encode_snapshot` / :func:`decode_snapshot` / :func:`encode_command` /
+  :func:`decode_command`;
+* PLC 侧 SCL 参考代码 :data:`SCL_SNIPPET`。
+
+``cli registers``、单元测试、模拟 PLC 的脚本都从这里取数据,保证三者永远一致。
+
+地址约定
+--------
+地址 = 配置项 ``plc.modbus.input_addr`` / ``plc.modbus.holding_addr`` + 表内偏移。
+西门子侧 MB_MASTER 的 ``MB_DATA_ADDR`` 填起始地址,``MB_DATA_LEN`` 填字数。
+"""
+
+from __future__ import annotations
+
+from typing import Dict, List, Sequence, Tuple
+
+from ..config import Config
+from ..schema import PlcCommand, StatusBits, VisionSnapshot
+
+__all__ = [
+    "CMD_IDLE",
+    "CMD_REQUEST",
+    "CMD_RESET",
+    "CMD_CLEAR_STATS",
+    "CMD_LABELS",
+    "CRC_FIELD",
+    "SNAPSHOT_FIELD_NOTES",
+    "COMMAND_FIELD_NOTES",
+    "SCL_SNIPPET",
+    "addresses",
+    "command_rows",
+    "decode_command",
+    "decode_snapshot",
+    "describe",
+    "encode_command",
+    "encode_snapshot",
+    "field_offsets",
+    "flag_bits",
+    "holding_offsets",
+    "input_offsets",
+    "layout_rows",
+    "snapshot_rows",
+]
+
+#: 保持寄存器 ``cmd`` 字段取值(PLC → 视觉)
+CMD_IDLE = 0
+CMD_REQUEST = 1
+CMD_RESET = 2
+CMD_CLEAR_STATS = 3
+
+CMD_LABELS: Dict[int, str] = {
+    CMD_IDLE: "空闲",
+    CMD_REQUEST: "请求识别(按需)",
+    CMD_RESET: "复位(清状态/投票)",
+    CMD_CLEAR_STATS: "清统计",
+}
+
+#: 快照末尾 CRC 字段名(不在 ``REGISTER_LAYOUT`` 里,因为它由 ``to_registers`` 追加)
+CRC_FIELD = "crc16"
+
+#: 输入寄存器字段含义(打印给 PLC 工程师看)
+SNAPSHOT_FIELD_NOTES: Dict[str, str] = {
+    "state": "0=不在车上(仅 flags 有效时已确认) 1=车斗 2=平板车;V2 不再发布 255(仅内部)",
+    "confidence": "千分比 0..1000",
+    "flags": "bit0 就绪 bit1 帧有效 bit2 稳定 bit3 帧率低 bit4 取帧超时 bit5 按需识别 bit6 结果有效 bit7 发布正常 bit8 感知不确定 bit9 MRC 请求 bit10 传感器退化 bit11 标定过期 bit12 数据链中断",
+    "seq": "结果序号(32bit,状态每变化一次 +1,PLC 用它判断“有新结果”)",
+    "ts_s": "unix 秒(32bit)",
+    "heartbeat": "心跳计数:持续变化=视觉存活;停滞=离线",
+    "fps_x10": "帧率 x10",
+    "latency_ms": "单帧端到端耗时(毫秒)",
+    "reserved": "预留(未使用,恒 0)",
+    CRC_FIELD: "CRC-16/MODBUS(前 11 个字按大端字节序的校验值)",
+}
+
+COMMAND_FIELD_NOTES: Dict[str, str] = {
+    "cmd": "0=空闲 1=请求识别(按需) 2=复位(清状态/投票) 3=清统计",
+    "preset": "相机/ROI 预设编号(0=默认)",
+    "min_conf": "覆盖最小置信度(千分比,0=用配置文件里的值)",
+    "reserved": "预留(未使用)",
+}
+
+#: 给 PLC 工程师的 SCL 参考代码(旧平台 MB_MASTER;S7-1200/1500 用 MB_CLIENT)
+SCL_SNIPPET = """\
+// ---------------------------------------------------------------
+// 视觉结果 DB(12 个字,1 Word = 16bit,大端)
+// ---------------------------------------------------------------
+// DATA_BLOCK "VisionDB"
+// { S7_Optimized_Access := 'FALSE' }   // 必须关掉优化访问,MB_CLIENT/MB_MASTER 要按绝对地址
+// VERSION : 0.1
+//    STRUCT
+//       state      : Word;   // 0=不在车上 1=车斗 2=平板车;V2 不发布 255
+//       confidence : Word;   // 千分比 0..1000
+//       flags      : Word;   // bit0 就绪 bit2 稳定 bit6 结果有效 bit8 感知不确定 bit9 MRC ...
+//       seq_hi     : Word;   // 结果序号(高 16bit)
+//       seq_lo     : Word;   // 结果序号(低 16bit)
+//       ts_hi      : Word;   // unix 秒(高 16bit)
+//       ts_lo      : Word;   // unix 秒(低 16bit)
+//       heartbeat  : Word;   // 心跳,持续变化说明视觉在线
+//       fps_x10    : Word;   // 帧率 x10
+//       latency_ms : Word;   // 单帧耗时
+//       reserved   : Word;
+//       crc16      : Word;   // CRC-16/MODBUS(前 11 个字的按大端字节序校验)
+//    END_STRUCT;
+// END_DATA_BLOCK
+
+// 循环任务里每 200~500ms 读一次(MODE=4 → FC4 读输入寄存器)
+"MB_MASTER_DB"(
+    REQ       := "VisionReqPulse",        // 周期脉冲,或与上一帧错开
+    MB_ADDR   := 1,                       // 视觉侧 unit_id
+    MB_MODE   := 4,                       // 4 = 读输入寄存器
+    MB_DATA_ADDR := 0,                    // 配置里的 plc.modbus.input_addr
+    MB_DATA_LEN  := 12,
+    MB_DATA_PTR  := "VisionDB",
+    DONE      => "VisionReadDone",
+    ERROR     => "VisionReadError",
+    STATUS    => "VisionReadStatus");
+
+// 使用建议(安全逻辑)
+// IF "VisionDB".flags.%X6 AND "VisionDB".state = 1 THEN ...  // 结果有效 + 车斗
+// IF NOT "VisionDB".flags.%X2 THEN ...                        // 未稳定:不要自动落箱
+// IF "VisionDB".heartbeat 连续 3s 不变 THEN ...               // 视觉离线:报警
+"""
+
+#: ``flags`` 位说明:(名称, 掩码, 含义)
+_FLAG_NOTES: Tuple[Tuple[str, int, str], ...] = (
+    ("READY", int(StatusBits.READY), "模型已加载且完成预热"),
+    ("FRAME_OK", int(StatusBits.FRAME_OK), "最近一帧是新的(未超过 stale 时限)"),
+    ("STABLE", int(StatusBits.STABLE), "状态稳定,可用于联锁/自动落箱"),
+    ("LOW_FPS", int(StatusBits.LOW_FPS), "帧率低于下限"),
+    ("FRAME_TIMEOUT", int(StatusBits.FRAME_TIMEOUT), "长时间拿不到帧(相机/网络异常)"),
+    ("ON_DEMAND", int(StatusBits.ON_DEMAND), "当前处于 PLC 请求触发的按需识别"),
+    ("RESULT_VALID", int(StatusBits.RESULT_VALID), "置信度达到阈值,结果有效"),
+    ("PUBLISH_OK", int(StatusBits.PUBLISH_OK), "最近一次向 PLC 发布成功"),
+    ("PERCEPTION_UNCERTAIN", int(StatusBits.PERCEPTION_UNCERTAIN),
+     "感知不确定(低置信度/证据不足/图像模糊等);与 RESULT_VALID 互斥"),
+    ("MRC_REQUEST", int(StatusBits.MRC_REQUEST),
+     "请求 PLC 进入最小风险状态(MRC,整机侧执行)"),
+    ("SENSOR_DEGRADED", int(StatusBits.SENSOR_DEGRADED),
+     "图像质量/传感器退化(模糊、过曝、遮挡)"),
+    ("CALIB_STALE", int(StatusBits.CALIB_STALE), "标定过期或漂移"),
+    ("DATA_LOSS", int(StatusBits.DATA_LOSS), "数据链中断(取帧超时/丢流)"),
+)
+
+
+# ----------------------------------------------------------------- 地址展开
+def layout_rows(
+    layout: Sequence[Tuple[str, int]], notes: Dict[str, str], base: int = 0
+) -> List[Tuple[int, str, int, str]]:
+    """把字段宽度表展开成 ``(地址, 字段, 宽度, 说明)`` 行。"""
+
+    rows: List[Tuple[int, str, int, str]] = []
+    offset = int(base)
+    for field, width in layout:
+        rows.append((offset, str(field), int(width), notes.get(str(field), "")))
+        offset += int(width)
+    return rows
+
+
+def field_offsets(layout: Sequence[Tuple[str, int]]) -> Dict[str, int]:
+    """字段 → 相对起始地址的偏移(字)。"""
+
+    offsets: Dict[str, int] = {}
+    offset = 0
+    for field, width in layout:
+        offsets[str(field)] = offset
+        offset += int(width)
+    return offsets
+
+
+def input_offsets() -> Dict[str, int]:
+    """输入寄存器字段偏移(含末尾 ``crc16``)。"""
+
+    offsets = field_offsets(VisionSnapshot.REGISTER_LAYOUT)
+    offsets[CRC_FIELD] = VisionSnapshot.register_count() - 1
+    return offsets
+
+
+def holding_offsets() -> Dict[str, int]:
+    """保持寄存器字段偏移。"""
+
+    return field_offsets(PlcCommand.REGISTER_LAYOUT)
+
+
+def snapshot_rows(base: int = 0) -> List[Tuple[int, str, int, str]]:
+    """输入寄存器全表(含 CRC 行),用于打印/文档/测试。"""
+
+    rows = layout_rows(VisionSnapshot.REGISTER_LAYOUT, SNAPSHOT_FIELD_NOTES, base)
+    rows.append(
+        (
+            int(base) + VisionSnapshot.register_count() - 1,
+            CRC_FIELD,
+            1,
+            SNAPSHOT_FIELD_NOTES[CRC_FIELD],
+        )
+    )
+    return rows
+
+
+def command_rows(base: int = 0) -> List[Tuple[int, str, int, str]]:
+    """保持寄存器全表。"""
+
+    return layout_rows(PlcCommand.REGISTER_LAYOUT, COMMAND_FIELD_NOTES, base)
+
+
+def flag_bits() -> List[Tuple[str, int, str]]:
+    """``flags`` 的位定义 ``(名称, 掩码, 含义)``。"""
+
+    return list(_FLAG_NOTES)
+
+
+# ----------------------------------------------------------------- 编解码
+def encode_snapshot(snapshot: VisionSnapshot) -> List[int]:
+    """快照 → 输入寄存器字数组(末字为 CRC)。"""
+
+    return list(snapshot.to_registers())
+
+
+def decode_snapshot(words: Sequence[int], verify: bool = True) -> VisionSnapshot:
+    """输入寄存器字数组 → 快照(默认校验 CRC,失败抛 ``ValueError``)。"""
+
+    return VisionSnapshot.from_registers(words, verify=bool(verify))
+
+
+def encode_command(command: PlcCommand) -> List[int]:
+    """指令 → 保持寄存器字数组。"""
+
+    return list(command.to_registers())
+
+
+def decode_command(words: Sequence[int]) -> PlcCommand:
+    """保持寄存器字数组 → 指令(不足补 0)。"""
+
+    return PlcCommand.from_registers(words)
+
+
+# ----------------------------------------------------------------- 汇总
+def addresses(cfg: Config) -> Dict[str, object]:
+    """从配置里取 Modbus 连接/地址参数(供打印与客户端复用)。"""
+
+    return {
+        "host": str(cfg.get_path("plc.modbus.host", "0.0.0.0")),
+        "port": int(cfg.get_path("plc.modbus.port", 1502)),
+        "unit_id": int(cfg.get_path("plc.modbus.unit_id", 1)),
+        "input_addr": int(cfg.get_path("plc.modbus.input_addr", 0)),
+        "holding_addr": int(cfg.get_path("plc.modbus.holding_addr", 0)),
+        "input_count": VisionSnapshot.register_count(),
+        "holding_count": PlcCommand.register_count(),
+    }
+
+
+def describe(base_input: int = 0, base_holding: int = 0, unit_id: int = 1) -> Dict[str, object]:
+    """机器可读的映射表(``cli registers --json`` 与文档生成共用)。"""
+
+    def _rows(items: List[Tuple[int, str, int, str]]) -> List[Dict[str, object]]:
+        return [
+            {"address": int(a), "field": f, "width": int(w), "note": n} for a, f, w, n in items
+        ]
+
+    return {
+        "unit_id": int(unit_id),
+        "crc": "CRC-16/MODBUS",
+        "input": _rows(snapshot_rows(base_input)),
+        "holding": _rows(command_rows(base_holding)),
+        "flags": [{"name": n, "mask": int(m), "note": t} for n, m, t in flag_bits()],
+        "cmd_labels": {str(k): v for k, v in CMD_LABELS.items()},
+    }

+ 245 - 0
portcv/plc/snap7_client.py

@@ -0,0 +1,245 @@
+"""S7 (S7comm / python-snap7) 发布端:视觉侧主动把快照写进 PLC 的 DB 块。
+
+适用场景
+--------
+* PLC 侧不方便做 Modbus 客户端(例如用 1500 的 PUT/GET 或已有 S7 通信栈);
+* 需要视觉侧按节拍推送、PLC 侧只读 DB 的架构;
+* 与 Modbus 通道并行做冗余。
+
+依赖:``pip install python-snap7``(Jetson/RK 上直接 pip 装即可,无需 snap7-server 组件——
+客户端模式下库自带实现)。未安装时本发布器会**降级为不可用**并给出明确提示,
+不影响 Modbus 通道运行。
+
+写入的 DB 布局与 :meth:`VisionSnapshot.to_db_bytes` 完全一致(12 字 = 24 字节,大端):
+
+===========================  ==================
+偏移(字节)                    含义
+===========================  ==================
+0..1                         state (0/1/2/255)
+2..3                         confidence 千分比
+4..5                         flags 位域
+6..9                         seq (32bit)
+10..13                       ts_s (32bit)
+14..15                       heartbeat
+16..17                       fps_x10
+18..19                       latency_ms
+20..21                       reserved
+22..23                       CRC-16/MODBUS
+===========================  ==================
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Dict, Optional
+
+from ..config import Config
+from ..logging_utils import get_logger
+from ..schema import PlcCommand, VisionSnapshot
+from .publisher import PlcPublisher
+
+__all__ = ["Snap7Publisher"]
+
+LOGGER = get_logger("plc.snap7")
+
+MISSING_HINT = (
+    "未安装 python-snap7,S7 推送通道不可用。请执行 `pip install python-snap7`,"
+    "或把配置改为 plc.push=\"modbus_server\" 走 Modbus/TCP 通道。"
+)
+
+
+class Snap7Publisher(PlcPublisher):
+    """按需重连的 S7 DB 写入器。"""
+
+    name = "snap7"
+
+    def __init__(self, cfg: Config) -> None:
+        snap = cfg.get_path("plc.snap7", {}) or {}
+        self.host = str(snap.get("host", "192.168.0.10"))
+        self.rack = int(snap.get("rack", 0))
+        self.slot = int(snap.get("slot", 1))
+        self.tcp_port = int(snap.get("tcp_port", 102))
+        self.db_number = int(snap.get("db_number", 100))
+        self.db_start = int(snap.get("db_start", 0))
+        self.reconnect_s = float(snap.get("reconnect_s", 3.0))
+        #: >0 时同时从该 DB 读回 PLC 指令(可选)
+        self.cmd_db_number = int(snap.get("cmd_db_number", 0))
+        self.cmd_db_start = int(snap.get("cmd_db_start", 0))
+
+        self._lock = threading.Lock()
+        self._client = None
+        self._snap7 = None
+        self._available = True
+        self._last_attempt = 0.0
+        self._last_error = ""
+        self._writes = 0
+        self._errors = 0
+        self._command = PlcCommand()
+        self._generation = 0
+        self._consumed = 0
+
+    # ------------------------------------------------------------ 生命周期
+    def start(self) -> None:
+        self._connect(force=True)
+
+    def stop(self) -> None:
+        with self._lock:
+            client = self._client
+            self._client = None
+        if client is not None:
+            try:
+                client.disconnect()
+            except Exception:  # pragma: no cover
+                pass
+            try:
+                client.destroy()
+            except Exception:  # pragma: no cover
+                pass
+        LOGGER.info("S7 发布器已关闭")
+
+    # ------------------------------------------------------------ 连接管理
+    def _connect(self, force: bool = False) -> bool:
+        with self._lock:
+            if self._client is not None:
+                return True
+            if not self._available:
+                return False
+            now = time.time()
+            if not force and (now - self._last_attempt) < self.reconnect_s:
+                return False
+            self._last_attempt = now
+        try:
+            import snap7  # type: ignore
+        except ImportError:
+            with self._lock:
+                self._available = False
+                self._last_error = "缺少 python-snap7"
+            LOGGER.error(MISSING_HINT)
+            return False
+        client = None
+        try:
+            client = snap7.client.Client()
+            client.connect(self.host, self.rack, self.slot, self.tcp_port)
+            if not client.get_connected():
+                raise RuntimeError("connect() 返回但未建立连接")
+        except Exception as exc:
+            self._last_error = str(exc)
+            with self._lock:
+                self._errors += 1
+            LOGGER.warning("连接 S7 %s rack=%d slot=%d 失败: %s", self.host, self.rack, self.slot, exc)
+            try:
+                if client is not None:
+                    client.destroy()
+            except Exception:  # pragma: no cover
+                pass
+            return False
+        with self._lock:
+            self._client = client
+            self._snap7 = snap7
+            self._last_error = ""
+        LOGGER.info(
+            "S7 已连接 %s rack=%d slot=%d(DB%d,偏移 %d,端口 %d)",
+            self.host,
+            self.rack,
+            self.slot,
+            self.db_number,
+            self.db_start,
+            self.tcp_port,
+        )
+        return True
+
+    def _current_client(self):
+        with self._lock:
+            client = self._client
+        if client is None:
+            return None
+        try:
+            if client.get_connected():
+                return client
+        except Exception:  # pragma: no cover - 连接已断
+            pass
+        with self._lock:
+            self._client = None
+        return None
+
+    # ---------------------------------------------------------- 写入快照
+    def publish(self, snapshot: VisionSnapshot) -> bool:
+        """把快照写入 DB;失败时标记断线,下个周期再重连(不阻塞主循环)。"""
+
+        payload = snapshot.to_db_bytes()
+        client = self._current_client() or (self._connect() and self._current_client())
+        if client is None:
+            with self._lock:
+                self._errors += 1
+            return False
+        try:
+            client.db_write(self.db_number, self.db_start, bytearray(payload))
+        except Exception as exc:
+            with self._lock:
+                self._errors += 1
+                self._last_error = str(exc)
+                self._client = None
+            LOGGER.warning("S7 写 DB%d 失败,将自动重连: %s", self.db_number, exc)
+            return False
+        with self._lock:
+            self._writes += 1
+        return True
+
+    # ---------------------------------------------------------- 读取指令
+    def _poll_command(self) -> None:
+        if self.cmd_db_number <= 0:
+            return
+        client = self._current_client()
+        if client is None:
+            return
+        size = PlcCommand.register_count() * 2
+        try:
+            raw = bytes(client.db_read(self.cmd_db_number, self.cmd_db_start, size))
+        except Exception as exc:  # pragma: no cover - 现场网络异常
+            LOGGER.debug("S7 读取指令 DB 失败: %s", exc)
+            return
+        words = [int.from_bytes(raw[i : i + 2], "big") for i in range(0, len(raw) - 1, 2)]
+        command = PlcCommand.from_registers(words)
+        with self._lock:
+            if command.to_registers() != self._command.to_registers():
+                self._command = command
+                self._generation += 1
+                LOGGER.info("S7 收到 PLC 指令 cmd=%d preset=%d", command.cmd, command.preset)
+
+    def command(self) -> PlcCommand:
+        self._poll_command()
+        with self._lock:
+            return self._command
+
+    def take_command(self) -> Optional[PlcCommand]:
+        self._poll_command()
+        with self._lock:
+            if self._generation <= self._consumed:
+                return None
+            self._consumed = self._generation
+            return self._command
+
+    # ---------------------------------------------------------- 状态
+    @property
+    def ok(self) -> bool:
+        return self._current_client() is not None
+
+    @property
+    def last_error(self) -> str:
+        with self._lock:
+            return self._last_error
+
+    def status(self) -> Dict[str, object]:
+        with self._lock:
+            return {
+                "publisher": self.name,
+                "host": "%s rack=%d slot=%d" % (self.host, self.rack, self.slot),
+                "db": self.db_number,
+                "connected": self._client is not None,
+                "available": self._available,
+                "writes": self._writes,
+                "errors": self._errors,
+                "last_error": self._last_error,
+            }
+

+ 0 - 0
portcv/py.typed


+ 234 - 0
portcv/recognition.py

@@ -0,0 +1,234 @@
+"""GB/T 45163.5 识别结果对象模型(P0-1)。
+
+标准要求识别系统按**对象**给出结果,而不是只给一个场景码:被吊物、
+抓取特征、装卸位置、装卸对象信息、环境。本模块提供与现有
+``Observation`` / ``Decision`` 解耦的稳定数据契约:
+
+* 训练/推理侧新增对象时只扩展 :class:`ObjectType` 与字段,不动 PLC 的
+  0/1/2 语义;
+* ``bbox_px`` 使用原图像素坐标,``position_mm`` 使用设计文件规定的
+  坐标原点与单位;
+* ``evidence_id`` 把结果与日志/图片/视频证据关联,``reason`` 保留
+  分类器的可解释原因,便于按标准 6.x 做追溯;
+* :meth:`RecognitionResult.to_dict` 只输出 JSON 原生类型,可直接写
+  JSONL,不依赖 numpy / OpenCV。
+
+本模块**不改变**现有 ``Observation`` / ``Decision``,旧路径行为不变。
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from enum import Enum
+from typing import Dict, List, Optional, Tuple
+
+from .schema import Box, Observation
+
+__all__ = [
+    "ObjectType",
+    "RecognitionResult",
+    "results_from_observation",
+]
+
+BBoxPx = Tuple[float, float, float, float]
+PositionMm = Tuple[float, float, float]
+
+
+class ObjectType(str, Enum):
+    """标准 5.2 b) 的五类识别对象。"""
+
+    LIFTED_OBJECT = "lifted_object"          # 被吊物(集装箱/罐箱等)
+    GRIP_FEATURE = "grip_feature"            # 抓取特征(角件/旋锁等)
+    LOAD_POSITION = "load_position"          # 装卸位置(车斗/平板车/工位)
+    LOAD_OBJECT_INFO = "load_object_info"    # 装卸对象信息(车号/车牌/工位)
+    ENVIRONMENT = "environment"              # 环境(人/车/障碍物)
+
+    @classmethod
+    def parse(cls, value: object) -> "ObjectType":
+        if isinstance(value, cls):
+            return value
+        text = str(value or "").strip().lower()
+        for item in cls:
+            if item.value == text:
+                return item
+        raise ValueError("未知识别对象类型: %r" % (value,))
+
+
+def _finite(value: float, name: str) -> float:
+    number = float(value)
+    if not math.isfinite(number):
+        raise ValueError("%s 必须是有限数值,实际 %r" % (name, value))
+    return number
+
+@dataclass(frozen=True)
+class RecognitionResult:
+    """一条可追溯的识别结果。
+
+    字段顺序与标准 5.2 b) 对齐;``object_type`` / ``label`` 是最小语义,
+    其余字段为可选证据。对象类型与标签分开的原因:同一 ``lifted_object``
+    可以是 20ft/40ft 箱或罐箱,同一 ``load_position`` 可以是 1/2/0。
+    """
+
+    object_type: ObjectType
+    label: str
+    bbox_px: BBoxPx
+    confidence: float
+    ts: float
+    frame_id: int
+    sensor_id: str = ""
+    position_mm: Optional[PositionMm] = None
+    odd_id: str = ""
+    evidence_id: str = ""
+    reason: str = ""
+
+    def __post_init__(self) -> None:
+        object.__setattr__(self, "object_type", ObjectType.parse(self.object_type))
+        label = str(self.label or "").strip()
+        if not label:
+            raise ValueError("RecognitionResult.label 不能为空")
+        object.__setattr__(self, "label", label)
+
+        if len(self.bbox_px) != 4:
+            raise ValueError("bbox_px 需要 (x1, y1, x2, y2)")
+        x1, y1, x2, y2 = (_finite(v, "bbox_px") for v in self.bbox_px)
+        if x2 < x1 or y2 < y1:
+            raise ValueError("bbox_px 必须满足 x2 >= x1 且 y2 >= y1")
+        object.__setattr__(self, "bbox_px", (x1, y1, x2, y2))
+
+        conf = _finite(self.confidence, "confidence")
+        if not 0.0 <= conf <= 1.0:
+            raise ValueError("confidence 必须在 0..1,实际 %r" % (self.confidence,))
+        object.__setattr__(self, "confidence", conf)
+
+        ts = _finite(self.ts, "ts")
+        if ts < 0.0:
+            raise ValueError("ts 不能为负")
+        object.__setattr__(self, "ts", ts)
+        object.__setattr__(self, "frame_id", int(self.frame_id))
+
+        if self.position_mm is not None:
+            if len(self.position_mm) != 3:
+                raise ValueError("position_mm 需要 (x, y, z)")
+            object.__setattr__(
+                self, "position_mm", tuple(_finite(v, "position_mm") for v in self.position_mm)
+            )
+
+        object.__setattr__(self, "sensor_id", str(self.sensor_id or ""))
+        object.__setattr__(self, "odd_id", str(self.odd_id or ""))
+        object.__setattr__(self, "evidence_id", str(self.evidence_id or ""))
+
+    def to_dict(self) -> Dict[str, object]:
+        """JSON 原生字典(不包含 numpy/枚举实例)。"""
+
+        return {
+            "object_type": self.object_type.value,
+            "label": self.label,
+            "bbox_px": [round(float(v), 3) for v in self.bbox_px],
+            "confidence": round(float(self.confidence), 6),
+            "ts": round(float(self.ts), 6),
+            "frame_id": int(self.frame_id),
+            "sensor_id": self.sensor_id,
+            "position_mm": (
+                None if self.position_mm is None
+                else [round(float(v), 3) for v in self.position_mm]
+            ),
+            "odd_id": self.odd_id,
+            "evidence_id": self.evidence_id,
+            "reason": self.reason,
+        }
+
+    @classmethod
+    def from_dict(cls, data: Dict[str, object]) -> "RecognitionResult":
+        position = data.get("position_mm")
+        bbox = data.get("bbox_px") or (0.0, 0.0, 0.0, 0.0)
+        return cls(
+            object_type=ObjectType.parse(data.get("object_type")),
+            label=str(data.get("label", "")),
+            bbox_px=tuple(float(v) for v in bbox),  # type: ignore[arg-type]
+            confidence=float(data.get("confidence", 0.0)),
+            ts=float(data.get("ts", 0.0)),
+            frame_id=int(data.get("frame_id", 0) or 0),
+            sensor_id=str(data.get("sensor_id", "")),
+            position_mm=(
+                None if position is None
+                else tuple(float(v) for v in position)  # type: ignore[arg-type]
+            ),
+            odd_id=str(data.get("odd_id", "")),
+            evidence_id=str(data.get("evidence_id", "")),
+            reason=str(data.get("reason", "")),
+        )
+
+    @classmethod
+    def from_box(
+        cls,
+        box: Box,
+        *,
+        object_type: ObjectType = ObjectType.LIFTED_OBJECT,
+        ts: float = 0.0,
+        frame_id: int = 0,
+        sensor_id: str = "",
+        position_mm: Optional[PositionMm] = None,
+        odd_id: str = "",
+        evidence_id: str = "",
+        reason: str = "",
+    ) -> "RecognitionResult":
+        return cls(
+            object_type=object_type,
+            label=box.class_name or "object",
+            bbox_px=(box.x1, box.y1, box.x2, box.y2),
+            confidence=float(box.score),
+            ts=ts,
+            frame_id=frame_id,
+            sensor_id=sensor_id,
+            position_mm=position_mm,
+            odd_id=odd_id,
+            evidence_id=evidence_id,
+            reason=reason,
+        )
+
+
+def results_from_observation(
+    observation: Observation,
+    *,
+    sensor_id: str = "",
+    odd_id: str = "",
+    include_environment: bool = False,
+) -> List[RecognitionResult]:
+    """把旧 ``Observation.detections`` 映射成标准对象结果。
+
+    这是**兼容层**:旧分类器只输出检测框,没有抓取特征/位置 mm 等
+    字段;本函数只做可解释的粗映射,不伪造毫米级位置。新模型应直接
+    构造 :class:`RecognitionResult`。
+    """
+
+    loading_labels = {
+        "bed", "wagon_bed", "hopper_wagon", "gondola",
+        "flatbed", "flat_wagon", "platform_wagon",
+    }
+    env_labels = {"person", "people", "crane", "spreader", "truck", "wheel", "rail"}
+    results: List[RecognitionResult] = []
+    for index, box in enumerate(observation.detections):
+        name = str(box.class_name or "").strip().lower()
+        if name in loading_labels:
+            object_type = ObjectType.LOAD_POSITION
+        elif name in env_labels:
+            if not include_environment:
+                continue
+            object_type = ObjectType.ENVIRONMENT
+        else:
+            object_type = ObjectType.LIFTED_OBJECT
+        results.append(
+            RecognitionResult.from_box(
+                box,
+                object_type=object_type,
+                ts=observation.ts,
+                frame_id=observation.frame_id,
+                sensor_id=sensor_id,
+                odd_id=odd_id,
+                evidence_id="%d:%d" % (int(observation.frame_id), int(index)),
+                reason=observation.reason,
+            )
+        )
+    return results
+

+ 452 - 0
portcv/schema.py

@@ -0,0 +1,452 @@
+"""公共数据结构:检测框、单帧观测、时序判决、PLC 快照。
+
+约定
+----
+* 检测框一律使用 **像素坐标**,原点在图像左上角,``y`` 向下增大。
+* :class:`SceneState` 的枚举值就是最终反馈给西门子 PLC 的编码,改动前先确认 PLC 侧。
+* :class:`VisionSnapshot` 是"视觉 → PLC"的唯一数据载体,Modbus/TCP 服务端与 S7 推送端
+  都必须通过它来编码,保证两条链路语义一致。
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from enum import Enum, IntEnum
+from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple
+
+if TYPE_CHECKING:  # pragma: no cover - 仅类型检查,避免 schema ↔ recognition 循环导入
+    from .recognition import RecognitionResult
+
+__all__ = [
+    "Box",
+    "CommitPhase",
+    "Decision",
+    "Observation",
+    "PlcCommand",
+    "SceneState",
+    "STATE_LABELS",
+    "STATE_NAME_TO_CODE",
+    "StatusBits",
+    "ViewMode",
+    "VisionSnapshot",
+    "crc16_modbus",
+    "recognition_results",
+]
+
+
+class SceneState(IntEnum):
+    """反馈给 PLC 的场景编码。"""
+
+    NOT_ON_TRAIN = 0  # 集装箱不在车上
+    BED = 1           # 车斗
+    FLATBED = 2       # 平板车
+    UNKNOWN = 255     # 视觉未就绪 / 结果不可信
+
+    @property
+    def label(self) -> str:
+        return STATE_LABELS.get(int(self), "unknown")
+
+
+STATE_LABELS: Dict[int, str] = {
+    0: "not_on_train",
+    1: "bed",
+    2: "flatbed",
+    255: "unknown",
+}
+
+STATE_NAME_TO_CODE: Dict[str, int] = {v: k for k, v in STATE_LABELS.items()}
+
+
+class ViewMode(str, Enum):
+    """P1 双视角模式(``docs/route_v2.md`` §3)。"""
+
+    FRONT = "front"
+    HIGH = "high"
+    UNKNOWN = "unknown"
+
+    @classmethod
+    def parse(cls, value: object) -> "ViewMode":
+        text = str(value or "").strip().lower()
+        for item in cls:
+            if item.value == text:
+                return item
+        return cls.UNKNOWN
+
+
+class CommitPhase(str, Enum):
+    """落位相位:T1 可判窗口、T2 已落位、T3 吊装中。"""
+
+    T1 = "T1"
+    T2 = "T2"
+    T3 = "T3"
+
+
+class StatusBits(IntEnum):
+    """``VisionSnapshot.flags`` 的位定义(同时写入 Modbus 寄存器与 S7 DB)。"""
+
+    READY = 1 << 0          # 模型已加载且完成预热
+    FRAME_OK = 1 << 1       # 最近一帧是新的(未超过 stale 时限)
+    STABLE = 1 << 2         # 状态稳定,可用于联锁/自动落箱
+    LOW_FPS = 1 << 3        # 帧率低于下限
+    FRAME_TIMEOUT = 1 << 4  # 长时间拿不到帧(相机/网络异常)
+    ON_DEMAND = 1 << 5      # 当前处于 PLC 请求触发的按需识别
+    RESULT_VALID = 1 << 6   # 置信度达到阈值,结果有效
+    PUBLISH_OK = 1 << 7     # 最近一次向 PLC 发布成功(服务端模式恒为 1)
+    # P0-2:GB/T 45163.5 5.1.3/5.1.4 的感知健康位(bit8~12)。
+    # 约束:PERCEPTION_UNCERTAIN=1 时 RESULT_VALID 必须为 0。
+    PERCEPTION_UNCERTAIN = 1 << 8   # 感知不确定(低置信度/证据不足/模糊等)
+    MRC_REQUEST = 1 << 9            # 请求 PLC 进入最小风险状态(MRC)
+    SENSOR_DEGRADED = 1 << 10       # 图像质量/传感器退化(模糊、过曝、遮挡)
+    CALIB_STALE = 1 << 11           # 标定过期或漂移
+    DATA_LOSS = 1 << 12             # 数据链中断(取帧超时/丢流)
+
+
+def crc16_modbus(data: bytes) -> int:
+    """CRC-16/MODBUS,用于快照校验,便于 PLC 侧判断数据是否完整/刷新。"""
+
+    crc = 0xFFFF
+    for byte in data:
+        crc ^= byte
+        for _ in range(8):
+            if crc & 0x0001:
+                crc = (crc >> 1) ^ 0xA001
+            else:
+                crc >>= 1
+    return crc & 0xFFFF
+
+
+@dataclass
+class Box:
+    """一个检测框。``class_id`` 为模型输出索引,``class_name`` 为标签名。"""
+
+    x1: float
+    y1: float
+    x2: float
+    y2: float
+    score: float = 0.0
+    class_id: int = -1
+    class_name: str = ""
+
+    def __post_init__(self) -> None:
+        if self.x2 < self.x1:
+            self.x1, self.x2 = self.x2, self.x1
+        if self.y2 < self.y1:
+            self.y1, self.y2 = self.y2, self.y1
+
+    # -- 几何属性 ---------------------------------------------------------
+    @property
+    def width(self) -> float:
+        return max(0.0, self.x2 - self.x1)
+
+    @property
+    def height(self) -> float:
+        return max(0.0, self.y2 - self.y1)
+
+    @property
+    def area(self) -> float:
+        return self.width * self.height
+
+    @property
+    def cx(self) -> float:
+        return (self.x1 + self.x2) / 2.0
+
+    @property
+    def cy(self) -> float:
+        return (self.y1 + self.y2) / 2.0
+
+    @property
+    def top(self) -> float:
+        return min(self.y1, self.y2)
+
+    @property
+    def bottom(self) -> float:
+        return max(self.y1, self.y2)
+
+    def as_xyxy(self) -> Tuple[float, float, float, float]:
+        return (self.x1, self.y1, self.x2, self.y2)
+
+    def as_list(self) -> List[float]:
+        return [float(self.x1), float(self.y1), float(self.x2), float(self.y2)]
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "box": [round(v, 1) for v in self.as_list()],
+            "score": round(float(self.score), 4),
+            "class_id": int(self.class_id),
+            "class_name": self.class_name,
+        }
+
+    # -- 构造 / 变换 ------------------------------------------------------
+    @classmethod
+    def from_xywh(
+        cls,
+        cx: float,
+        cy: float,
+        w: float,
+        h: float,
+        score: float = 0.0,
+        class_id: int = -1,
+        class_name: str = "",
+    ) -> "Box":
+        return cls(
+            cx - w / 2.0,
+            cy - h / 2.0,
+            cx + w / 2.0,
+            cy + h / 2.0,
+            score=score,
+            class_id=class_id,
+            class_name=class_name,
+        )
+
+    def clip(self, width: float, height: float) -> "Box":
+        """裁剪到图像范围内。"""
+
+        return Box(
+            min(max(self.x1, 0.0), width),
+            min(max(self.y1, 0.0), height),
+            min(max(self.x2, 0.0), width),
+            min(max(self.y2, 0.0), height),
+            score=self.score,
+            class_id=self.class_id,
+            class_name=self.class_name,
+        )
+
+    # -- 关系运算 ---------------------------------------------------------
+    def intersection(self, other: "Box") -> float:
+        ix1 = max(self.x1, other.x1)
+        iy1 = max(self.y1, other.y1)
+        ix2 = min(self.x2, other.x2)
+        iy2 = min(self.y2, other.y2)
+        if ix2 <= ix1 or iy2 <= iy1:
+            return 0.0
+        return float((ix2 - ix1) * (iy2 - iy1))
+
+    def iou(self, other: "Box") -> float:
+        inter = self.intersection(other)
+        if inter <= 0.0:
+            return 0.0
+        union = self.area + other.area - inter
+        return float(inter / union) if union > 0 else 0.0
+
+    def overlap_ratio(self, other: "Box") -> float:
+        """交叠面积占两者**较小**面积的比例(小框被大框包含时为 1)。"""
+
+        inter = self.intersection(other)
+        if inter <= 0.0:
+            return 0.0
+        denom = min(self.area, other.area)
+        return float(inter / denom) if denom > 0 else 0.0
+
+    def contains_point(self, x: float, y: float) -> bool:
+        return self.x1 <= x <= self.x2 and self.y1 <= y <= self.y2
+
+
+@dataclass
+class Observation:
+    """单帧的场景判定结果(未经时序滤波)。"""
+
+    ts: float = 0.0
+    state: int = int(SceneState.UNKNOWN)
+    confidence: float = 0.0
+    detections: List[Box] = field(default_factory=list)
+    reason: str = ""
+    frame_id: int = 0
+
+    @property
+    def is_valid(self) -> bool:
+        return int(self.state) != int(SceneState.UNKNOWN)
+
+
+@dataclass
+class Decision:
+    """时序滤波后的判决,可直接发布给 PLC。"""
+
+    state: int = int(SceneState.UNKNOWN)
+    confidence: float = 0.0
+    stable: bool = False
+    seq: int = 0           # 状态每提交一次变化 +1,PLC 用它判断"有新结果"
+    since_ts: float = 0.0  # 当前状态起始时间(秒,time.time())
+    reason: str = "init"
+    changed: bool = False  # 本次 update 是否发生了状态变化
+
+    @property
+    def label(self) -> str:
+        return STATE_LABELS.get(int(self.state), "unknown")
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "state": int(self.state),
+            "label": self.label,
+            "confidence": round(float(self.confidence), 4),
+            "stable": bool(self.stable),
+            "seq": int(self.seq),
+            "reason": self.reason,
+        }
+
+
+@dataclass
+class VisionSnapshot:
+    """视觉侧写入 PLC 的一张"结果快照"。
+
+    Modbus/TCP 服务端把它铺到输入寄存器(FC4 只读),S7 推送端把它打成 DB 字节数组。
+    字段宽度之和 = 11 个 16bit 字,第 12 个字是 CRC-16/MODBUS。
+    """
+
+    state: int = int(SceneState.UNKNOWN)
+    confidence: int = 0     # 千分比 0..1000
+    flags: int = 0
+    seq: int = 0            # 32bit,状态变化计数
+    ts_s: int = 0           # unix 秒(32bit)
+    heartbeat: int = 0      # 0..65535,每个心跳周期 +1
+    fps_x10: int = 0        # 帧率 x10
+    latency_ms: int = 0     # 单帧端到端耗时
+    reserved: int = 0
+
+    #: 寄存器布局:字段 → 16bit 字宽度
+    REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
+        ("state", 1),
+        ("confidence", 1),
+        ("flags", 1),
+        ("seq", 2),
+        ("ts_s", 2),
+        ("heartbeat", 1),
+        ("fps_x10", 1),
+        ("latency_ms", 1),
+        ("reserved", 1),
+    )
+
+    @staticmethod
+    def register_count() -> int:
+        return int(sum(width for _, width in VisionSnapshot.REGISTER_LAYOUT)) + 1  # +1 = CRC
+
+    def to_registers(self) -> List[int]:
+        """铺成 16bit 寄存器数组(大端),最后一个字为 CRC-16/MODBUS 校验。"""
+
+        words = [
+            int(self.state) & 0xFFFF,
+            int(self.confidence) & 0xFFFF,
+            int(self.flags) & 0xFFFF,
+            (int(self.seq) >> 16) & 0xFFFF,
+            int(self.seq) & 0xFFFF,
+            (int(self.ts_s) >> 16) & 0xFFFF,
+            int(self.ts_s) & 0xFFFF,
+            int(self.heartbeat) & 0xFFFF,
+            int(self.fps_x10) & 0xFFFF,
+            int(self.latency_ms) & 0xFFFF,
+            int(self.reserved) & 0xFFFF,
+        ]
+        payload = b"".join(int(w).to_bytes(2, "big") for w in words)
+        words.append(crc16_modbus(payload))
+        return words
+
+    @classmethod
+    def from_registers(cls, words: Sequence[int], verify: bool = False) -> "VisionSnapshot":
+        values = [int(w) & 0xFFFF for w in words]
+        if len(values) < cls.register_count():
+            raise ValueError(
+                "寄存器数量不足: 需要 %d,实际 %d" % (cls.register_count(), len(values))
+            )
+        if verify:
+            payload = b"".join(int(w).to_bytes(2, "big") for w in values[:-1])
+            if crc16_modbus(payload) != values[-1]:
+                raise ValueError("CRC 校验失败,数据可能不完整")
+        return cls(
+            state=values[0],
+            confidence=values[1],
+            flags=values[2],
+            seq=(values[3] << 16) | values[4],
+            ts_s=(values[5] << 16) | values[6],
+            heartbeat=values[7],
+            fps_x10=values[8],
+            latency_ms=values[9],
+            reserved=values[10],
+        )
+
+    def to_db_bytes(self) -> bytes:
+        """S7 DB 字节块(每字大端),布局与 :meth:`to_registers` 一致。"""
+
+        return b"".join(int(w).to_bytes(2, "big") for w in self.to_registers())
+
+    def has_flag(self, bit: StatusBits) -> bool:
+        return bool(int(self.flags) & int(bit))
+
+    def to_dict(self) -> Dict[str, object]:
+        return {
+            "state": int(self.state),
+            "state_label": STATE_LABELS.get(int(self.state), "unknown"),
+            "confidence": int(self.confidence),
+            "flags": int(self.flags),
+            "seq": int(self.seq),
+            "ts_s": int(self.ts_s),
+            "heartbeat": int(self.heartbeat),
+            "fps_x10": int(self.fps_x10),
+            "latency_ms": int(self.latency_ms),
+        }
+
+
+@dataclass
+class PlcCommand:
+    """PLC → 视觉的指令块(保持寄存器 FC3/FC6/FC16)。"""
+
+    cmd: int = 0        # 0=空闲, 1=请求识别(按需), 2=复位, 3=清统计
+    preset: int = 0     # ROI / 相机预设编号
+    min_conf: int = 0   # 覆盖最小置信度(千分比,0=用配置值)
+    reserved: int = 0
+
+    #: 保持寄存器布局:字段 → 16bit 字宽度
+    REGISTER_LAYOUT: Tuple[Tuple[str, int], ...] = (
+        ("cmd", 1),
+        ("preset", 1),
+        ("min_conf", 1),
+        ("reserved", 1),
+    )
+
+    @staticmethod
+    def register_count() -> int:
+        return int(sum(width for _, width in PlcCommand.REGISTER_LAYOUT))
+
+    def to_registers(self) -> List[int]:
+        return [
+            int(self.cmd) & 0xFFFF,
+            int(self.preset) & 0xFFFF,
+            int(self.min_conf) & 0xFFFF,
+            int(self.reserved) & 0xFFFF,
+        ]
+
+    @classmethod
+    def from_registers(cls, words: Sequence[int]) -> "PlcCommand":
+        values = [int(w) & 0xFFFF for w in words]
+        while len(values) < cls.register_count():
+            values.append(0)
+        return cls(cmd=values[0], preset=values[1], min_conf=values[2], reserved=values[3])
+
+    def is_request(self) -> bool:
+        return int(self.cmd) == 1
+
+    def is_reset(self) -> bool:
+        return int(self.cmd) == 2
+
+
+def recognition_results(
+    observation: Observation,
+    *,
+    sensor_id: str = "",
+    odd_id: str = "",
+    include_environment: bool = False,
+) -> List["RecognitionResult"]:
+    """兼容入口:旧 ``Observation`` → 标准识别对象结果(P0-1)。
+
+    实现放在 :mod:`portcv.recognition`;这里只做延迟导入,保持
+    ``Observation`` / ``Decision`` 字段与旧行为完全不变。
+    """
+
+    from .recognition import results_from_observation
+
+    return results_from_observation(
+        observation,
+        sensor_id=sensor_id,
+        odd_id=odd_id,
+        include_environment=include_environment,
+    )
+
+

+ 13 - 0
portcv/service/__init__.py

@@ -0,0 +1,13 @@
+"""服务层:把检测、判定、发布组装成常驻进程。"""
+
+from .pipeline import VisionPipeline
+from .publish_gate import PublishGate, PublishResult, evaluate_publish_gate
+from .runner import RunService
+
+__all__ = [
+    "PublishGate",
+    "PublishResult",
+    "RunService",
+    "VisionPipeline",
+    "evaluate_publish_gate",
+]

+ 150 - 0
portcv/service/pipeline.py

@@ -0,0 +1,150 @@
+"""单帧处理流水线:推理 → 场景判定 → 时序防抖。
+
+把这三步封在一起的好处:**同一份逻辑**既能被常驻服务使用,也能被自检/回放工具
+逐帧调用(:mod:`portcv.cli` 的 ``selftest`` / ``replay``),测试里也只需要构造一个
+:class:`VisionPipeline` 就能覆盖全链路。
+"""
+
+from __future__ import annotations
+
+from typing import Dict, Optional, Tuple
+
+from ..config import Config
+from ..detect import Detector, build_detector
+from ..detect.postproc import draw_boxes
+from ..io.capture import Frame
+from ..logic import SceneClassifier, TemporalVoter
+from ..logic.evidence_v2 import EvidenceV2
+from ..schema import Decision, Observation
+
+__all__ = ["VisionPipeline"]
+
+
+class VisionPipeline:
+    """推理 + 判定流水线(线程内使用,非线程安全)。"""
+
+    def __init__(self, cfg: Config, detector: Optional[Detector] = None) -> None:
+        self.cfg = cfg
+        self.detector: Detector = detector or build_detector(cfg)
+        self.classifier = SceneClassifier(cfg)
+        self.voter = TemporalVoter.from_config(cfg)
+        # P1b/P1c:显式启用后才替换逐帧判定链路;默认保持既有行为。
+        self.evidence_v2 = (
+            EvidenceV2.from_config(cfg)
+            if bool(cfg.get_path("evidence_v2.enabled", False))
+            else None
+        )
+        self._plc_arrival_pending = False
+        self._loaded = False
+        self._warmup_frames = 0
+        self.frames = 0
+        self.last_ms = 0.0
+
+    # ------------------------------------------------------------ 生命周期
+    def load(self) -> None:
+        if self._loaded:
+            return
+        self.detector.load()
+        self._loaded = True
+
+    def warmup(self, frames: Optional[int] = None) -> int:
+        """预热推理后端;返回实际预热帧数。``run.warmup_frames=0`` 表示跳过。"""
+
+        count = int(frames if frames is not None else self.cfg.get_path("run.warmup_frames", 3))
+        if count <= 0:
+            return 0
+        self.load()
+        self.detector.warmup(count)
+        self._warmup_frames = count
+        return count
+
+    def close(self) -> None:
+        try:
+            self.detector.close()
+        except Exception:  # pragma: no cover - 释放失败不影响退出
+            pass
+        self._loaded = False
+
+    # ------------------------------------------------------------ 主入口
+    def step(self, frame: Frame) -> Tuple[Observation, Decision]:
+        """处理一帧,返回 ``(单帧观测, 时序判决)``。"""
+
+        boxes = self.detector.timed_infer(frame.image)
+        if self.evidence_v2 is not None:
+            observation = self.evidence_v2.classify(
+                frame.image,
+                ts=frame.ts,
+                frame_id=frame.frame_id,
+                plc_arrived=self._plc_arrival_pending,
+                detections=boxes,
+            )
+            self._plc_arrival_pending = False
+        else:
+            observation = self.classifier.classify(
+                boxes,
+                frame.size,
+                ts=frame.ts,
+                frame_id=frame.frame_id,
+            )
+        decision = self.voter.update(observation)
+        self.frames += 1
+        self.last_ms = float(self.detector.infer_ms)
+        return observation, decision
+
+    def current(self) -> Decision:
+        """不喂新帧,取当前判决(用于心跳/按需识别之间的空档期)。"""
+
+        return self.voter.current()
+
+    def reset(self) -> None:
+        """PLC 复位命令:清空投票窗口与当前状态。"""
+
+        self.voter.reset()
+        if self.evidence_v2 is not None:
+            self.evidence_v2.reset()
+        self._plc_arrival_pending = False
+
+    def note_plc_arrival(self, arrived: bool = True) -> None:
+        """可选 PLC “到位/吊具松开”信号:下一帧 commit 门可用它替代间隙门。"""
+
+        self._plc_arrival_pending = bool(arrived)
+
+    def annotate(self, frame: Frame, observation: Optional[Observation] = None, decision: Optional[Decision] = None):
+        """在帧上画框/ROI/状态,返回同一张图(联调预览与难例存档用)。"""
+
+        boxes = observation.detections if observation is not None else []
+        roi = self.classifier.roi_polygon(*frame.size)
+        texts = []
+        if decision is not None:
+            texts.append("state=%d %s conf=%.2f seq=%d" % (
+                int(decision.state), decision.label, decision.confidence, int(decision.seq)
+            ))
+        return draw_boxes(frame.image, boxes, roi, texts)
+
+    # ------------------------------------------------------------ 属性
+    @property
+    def ready(self) -> bool:
+        return bool(self._loaded and self._warmup_frames > 0)
+
+    @property
+    def warmup_frames(self) -> int:
+        return int(self._warmup_frames)
+
+    def describe(self) -> Dict[str, object]:
+        info: Dict[str, object] = dict(self.detector.describe())
+        info.update(
+            {
+                "scene_mode": (
+                    "evidence_v2" if self.evidence_v2 is not None else self.classifier.mode
+                ),
+                "roi": [[round(x, 4), round(y, 4)] for x, y in self.cfg.roi],
+                "evidence_v2": (
+                    self.evidence_v2.last.to_dict() if self.evidence_v2 is not None else None
+                ),
+                "decision": dict(self.cfg.section("decision")),
+                "loaded": self._loaded,
+                "warmup_frames": self._warmup_frames,
+                "frames": self.frames,
+            }
+        )
+        return info

+ 209 - 0
portcv/service/publish_gate.py

@@ -0,0 +1,209 @@
+"""V2 PublishGate:把内部 ``Decision`` 映射成 PLC 可以安全消费的结果。
+
+背景
+----
+V1 在不确定时直接把 ``state=255`` 写进 PLC 寄存器;V2 的目标契约是
+**PLC 侧只看到 0/1/2**,255 只存在于视觉内部。做法:
+
+* 内部有效(0/1/2、稳定、置信度达标)→ 发布该状态,置
+  ``RESULT_VALID`` 与 ``STABLE``;
+* 内部 255 / 低置信度 / 未稳定 → **保持上一稳定值**,清两个标志;
+* 帧超时 → 同样保持上一稳定值(超时优先于有效结果);
+* PLC ``cmd=2`` 复位 → 回到 ``0 + flags 0/0``,并清掉 last stable;
+* 从未有过稳定值(冷启动)→ ``0 + flags 0/0``。
+
+``0 + flags 0/0`` 只表示“不知道/保持”,**不是**“已确认不在车上”;
+PLC 必须按 ``RESULT_VALID && STABLE`` 门控。
+
+本模块只做输出映射,不依赖检测/证据模块;P1a 先用合成 ``Decision``
+验证契约,P1b 再把它接进运行时。
+"""
+
+from __future__ import annotations
+
+import math
+from dataclasses import dataclass
+from typing import Optional, Tuple
+
+from ..schema import Decision
+
+__all__ = [
+    "DEFAULT_MIN_CONFIDENCE",
+    "PublishGate",
+    "PublishResult",
+    "evaluate_publish_gate",
+]
+
+#: 与 ``decision.min_confidence`` 的默认值一致(45%)。
+DEFAULT_MIN_CONFIDENCE = 0.45
+
+_VALID_STATES = (0, 1, 2)
+
+
+def _is_valid_state(state: int) -> bool:
+    return int(state) in _VALID_STATES
+
+
+def _confidence_milli(conf: float) -> int:
+    """把 0..1 的置信度换成 0..1000 的整数(half-up)。
+
+    不用 Python 内置 ``round`` / C++ ``std::lround`` 的原因:两者对
+    ``.5`` 的舍入规则不同(banker's vs away-from-zero),会造成
+    Python/C++ 同一输入得到不同千分比。这里固定为
+    ``floor(conf * 1000 + 0.5)``,两侧逐位一致。
+    """
+
+    if not math.isfinite(conf) or conf <= 0.0:
+        return 0
+    if conf >= 1.0:
+        return 1000
+    return int(math.floor(conf * 1000.0 + 0.5))
+
+
+@dataclass(frozen=True)
+class PublishResult:
+    """PublishGate 的输出;字段与 PLC 结果区的前三个字对应。"""
+
+    state: int
+    result_valid: bool
+    stable: bool
+    confidence: int
+    last_stable: Optional[int]
+    perception_uncertain: bool = False
+
+    def __post_init__(self) -> None:
+        if self.state not in _VALID_STATES:
+            raise ValueError("PublishGate.state 必须是 0/1/2,实际 %r" % (self.state,))
+        if self.result_valid and not self.stable:
+            raise ValueError("RESULT_VALID=1 时必须 STABLE=1")
+        if self.result_valid and self.perception_uncertain:
+            raise ValueError("PERCEPTION_UNCERTAIN=1 时不得置 RESULT_VALID")
+        if not 0 <= int(self.confidence) <= 1000:
+            raise ValueError("confidence 必须在 0..1000,实际 %r" % (self.confidence,))
+        if not self.result_valid and int(self.confidence) != 0:
+            raise ValueError("结果无效时 confidence 必须为 0")
+        if self.last_stable is not None and self.last_stable not in _VALID_STATES:
+            raise ValueError("last_stable 必须是 0/1/2 或 None")
+
+    def as_tuple(self) -> Tuple[int, int, int, int, Optional[int]]:
+        """返回契约测试用的五元组(1/0 而非 bool)。"""
+
+        return (
+            int(self.state),
+            int(bool(self.result_valid)),
+            int(bool(self.stable)),
+            int(self.confidence),
+            self.last_stable,
+        )
+
+
+def _hold(last_stable: Optional[int], perception_uncertain: bool = True) -> PublishResult:
+    """不确定时的安全输出:保持 last stable;没有历史则 0/None。
+
+    P0-2:只要走“保持”分支,就置 ``perception_uncertain``;调用方据此
+    置 ``PERCEPTION_UNCERTAIN``/``MRC_REQUEST``,且绝不会同时置
+    ``RESULT_VALID``。
+    """
+
+    if last_stable is not None and _is_valid_state(int(last_stable)):
+        last = int(last_stable)
+        return PublishResult(state=last, result_valid=False, stable=False,
+                             confidence=0, last_stable=last,
+                             perception_uncertain=bool(perception_uncertain))
+    return PublishResult(state=0, result_valid=False, stable=False,
+                         confidence=0, last_stable=None,
+                         perception_uncertain=bool(perception_uncertain))
+
+
+def evaluate_publish_gate(
+    decision: Decision,
+    *,
+    frame_timeout: bool = False,
+    reset: bool = False,
+    last_stable: Optional[int] = None,
+    min_conf: float = DEFAULT_MIN_CONFIDENCE,
+    perception_uncertain: bool = False,
+) -> PublishResult:
+    """纯函数版 PublishGate(便于单测/回放)。
+
+    优先级:``reset`` > ``frame_timeout`` > ``perception_uncertain`` >
+    有效结果 > 保持。``last_stable`` 是**上一稳定值**,不是本帧内部状态;
+    有效时才更新。
+    """
+
+    if reset:
+        return PublishResult(state=0, result_valid=False, stable=False,
+                             confidence=0, last_stable=None)
+
+    if frame_timeout:
+        return _hold(last_stable, True)
+
+    if perception_uncertain:
+        return _hold(last_stable, True)
+
+    threshold = float(min_conf)
+    if not math.isfinite(threshold):
+        threshold = DEFAULT_MIN_CONFIDENCE
+
+    conf = float(decision.confidence)
+    valid = (
+        _is_valid_state(int(decision.state))
+        and bool(decision.stable)
+        and math.isfinite(conf)
+        and conf >= threshold
+    )
+    if not valid:
+        return _hold(last_stable, True)
+
+    state = int(decision.state)
+    return PublishResult(state=state, result_valid=True, stable=True,
+                         confidence=_confidence_milli(conf), last_stable=state,
+                         perception_uncertain=False)
+
+
+class PublishGate:
+    """有状态的 PublishGate:在自己内部保存 last stable。
+
+    线程内使用、非线程安全;每个发布循环一个实例即可。
+    """
+
+    def __init__(self, min_conf: float = DEFAULT_MIN_CONFIDENCE) -> None:
+        threshold = float(min_conf)
+        self._min_conf = threshold if math.isfinite(threshold) else DEFAULT_MIN_CONFIDENCE
+        self._last_stable: Optional[int] = None
+
+    @property
+    def min_conf(self) -> float:
+        return self._min_conf
+
+    @property
+    def last_stable(self) -> Optional[int]:
+        return self._last_stable
+
+    def reset(self) -> None:
+        """PLC ``cmd=2``:清掉 last stable(下一次有效结果重新建立)。"""
+
+        self._last_stable = None
+
+    def apply(
+        self,
+        decision: Decision,
+        *,
+        frame_timeout: bool = False,
+        reset: bool = False,
+        min_conf: Optional[float] = None,
+        perception_uncertain: bool = False,
+    ) -> PublishResult:
+        """处理一个内部 Decision,更新并返回发布结果。"""
+
+        threshold = self._min_conf if min_conf is None else float(min_conf)
+        result = evaluate_publish_gate(
+            decision,
+            frame_timeout=frame_timeout,
+            reset=reset,
+            last_stable=self._last_stable,
+            min_conf=threshold,
+            perception_uncertain=perception_uncertain,
+        )
+        self._last_stable = result.last_stable
+        return result

+ 624 - 0
portcv/service/runner.py

@@ -0,0 +1,624 @@
+"""常驻服务:取帧 → 推理 → 判定 → 发布,并把心跳/指令/统计一并管起来。
+
+线程模型
+--------
+* **抓帧线程**::class:`~portcv.io.capture.FrameGrabber` 内部线程,只保留最新帧;
+* **主线程**:本模块的循环,做推理与判定(按 ``run.max_fps`` 限速);
+* **Modbus 线程**:由 :class:`~portcv.plc.modbus_server.ModbusTcpServer` 派生,
+  负责应答 PLC 的读写,并把指令投递给主循环(``take_command``)。
+
+因此发布动作是**非阻塞**的: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 threading
+import time
+from typing import Dict, Optional, Tuple
+
+from ..calibration import evaluate as evaluate_calibration
+from ..config import Config
+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 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._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,
+            "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.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
+        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``)。"""
+
+        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)
+            cv2.imwrite(os.path.join(folder, name), image)
+            self._saved += 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"])
+        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),
+            "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
+        return "state=%d(%s,%.2f) seq=%d fps=%.1f lat=%.0fms frames=%d pub=%d chg=%d err=%d" % (
+            int(decision.state),
+            decision.label,
+            decision.confidence,
+            int(decision.seq),
+            self.grabber.fps,
+            self._latency_ema,
+            int(self.stats["frames"]),
+            int(self.stats["published"]),
+            int(self.stats["changes"]),
+            int(self.stats["errors"]),
+        )
+
+
+

+ 364 - 0
portcv/storage.py

@@ -0,0 +1,364 @@
+"""P0-4 数据证据链:逐帧 JSONL、事件视频环缓、50 MB 切分、保留期清理。
+
+现场验收要能回答三个问题:
+
+1. 某次误判/漏判发生时,**输入画面**是什么?→ 事件环缓 + 单帧 JSONL;
+2. 断电/重启后,证据是否**连续且可恢复**?→ 追加写、坏尾行修复、段文件;
+3. 硬盘会不会被写满?→ 50 MB 切分 + ``retention_days`` 清理。
+
+本模块只负责落盘,不改变判决。默认 ``evidence.enabled=false``,现场确认
+磁盘/权限后再开;开启后 ``runner`` 每帧写一行 JSONL,状态变化时把环缓里
+最近 N 帧导成 mp4(失败则退化为 JPG 序列)。
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from collections import deque
+from typing import Deque, Dict, List, Optional
+
+import numpy as np
+
+try:  # pragma: no cover - 与取流层同一依赖
+    import cv2
+except ImportError:  # pragma: no cover
+    cv2 = None  # type: ignore
+
+from .config import Config
+
+__all__ = [
+    "DEFAULT_SEGMENT_BYTES",
+    "EventRing",
+    "EvidenceStore",
+    "SegmentingJsonlWriter",
+    "purge_old_files",
+]
+
+DEFAULT_SEGMENT_BYTES = 50 * 1024 * 1024
+
+
+def _ensure_dir(path: str) -> str:
+    os.makedirs(path, exist_ok=True)
+    return path
+
+
+def purge_old_files(directory: str, retention_days: float, now: Optional[float] = None) -> List[str]:
+    """删除 ``directory`` 下超过保留期的普通文件;返回删除路径。"""
+
+    if not directory or not os.path.isdir(directory) or retention_days <= 0:
+        return []
+    cutoff = float(now if now is not None else time.time()) - float(retention_days) * 86400.0
+    removed: List[str] = []
+    for name in os.listdir(directory):
+        path = os.path.join(directory, name)
+        if not os.path.isfile(path):
+            continue
+        try:
+            if os.path.getmtime(path) < cutoff:
+                os.remove(path)
+                removed.append(path)
+        except OSError:
+            continue
+    return removed
+
+
+class SegmentingJsonlWriter:
+    """按大小切分的 JSONL 追加写;重启后继续写当前段,坏尾行自动补换行。"""
+
+    def __init__(
+        self,
+        directory: str,
+        max_bytes: int = DEFAULT_SEGMENT_BYTES,
+        retention_days: float = 90.0,
+        fsync_interval_s: float = 1.0,
+    ) -> None:
+        self.directory = _ensure_dir(directory)
+        self.max_bytes = max(64, int(max_bytes))
+        self.retention_days = float(retention_days)
+        self.fsync_interval_s = max(0.0, float(fsync_interval_s))
+        self.path = os.path.join(self.directory, "frames.jsonl")
+        self.records = 0
+        self.segments = 0
+        self.session = ""
+        self._fh = None  # type: ignore[assignment]
+        self._last_fsync = 0.0
+
+    # -- 生命周期 ---------------------------------------------------------
+    def open(self) -> "SegmentingJsonlWriter":
+        _ensure_dir(self.directory)
+        self.session = "%s-%d" % (time.strftime("%Y%m%d-%H%M%S"), os.getpid())
+        self._repair_tail()
+        self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
+        self.segments = len(self._segment_files())
+        purge_old_files(self.directory, self.retention_days)
+        return self
+
+    def close(self) -> None:
+        if self._fh is not None:
+            try:
+                self._fh.flush()
+                os.fsync(self._fh.fileno())
+            except OSError:
+                pass
+            self._fh.close()
+            self._fh = None
+
+    def _segment_files(self) -> List[str]:
+        return sorted(
+            os.path.join(self.directory, name)
+            for name in os.listdir(self.directory)
+            if name.startswith("frames-") and name.endswith(".jsonl")
+        )
+
+    def _repair_tail(self) -> None:
+        """断电时最后一行可能只写了一半;补换行,保留原始字节供排查。"""
+
+        if not os.path.isfile(self.path) or os.path.getsize(self.path) == 0:
+            return
+        with open(self.path, "rb+") as fh:
+            fh.seek(-1, os.SEEK_END)
+            if fh.read(1) != b"\n":
+                fh.write(b"\n")
+
+    def _rotate(self) -> None:
+        if self._fh is not None:
+            self._fh.close()
+            self._fh = None
+        stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
+        target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, self.segments + 1))
+        counter = 1
+        while os.path.exists(target):
+            counter += 1
+            target = os.path.join(self.directory, "frames-%s-%04d.jsonl" % (stamp, counter))
+        try:
+            os.replace(self.path, target)
+        except OSError:
+            pass
+        self.segments += 1
+        self._fh = open(self.path, "a", encoding="utf-8", newline="\n")
+
+    # -- 写入 -------------------------------------------------------------
+    def write(self, record: Dict[str, object]) -> str:
+        if self._fh is None:
+            self.open()
+        line = json.dumps(record, ensure_ascii=False, default=str, separators=(",", ":")) + "\n"
+        data = line.encode("utf-8")
+        try:
+            size = os.path.getsize(self.path)
+        except OSError:
+            size = 0
+        if size > 0 and size + len(data) > self.max_bytes:
+            self._rotate()
+        self._fh.write(line)  # type: ignore[union-attr]
+        self._fh.flush()  # type: ignore[union-attr]
+        self.records += 1
+        now = time.time()
+        if self.fsync_interval_s > 0 and (now - self._last_fsync) >= self.fsync_interval_s:
+            self._last_fsync = now
+            try:
+                os.fsync(self._fh.fileno())  # type: ignore[union-attr]
+            except OSError:
+                pass
+        return self.path
+
+
+class EventRing:
+    """最近 N 帧的 JPEG 环缓;状态变化时导出为 mp4(或 JPG 序列)。"""
+
+    def __init__(
+        self,
+        max_frames: int = 90,
+        jpeg_quality: int = 85,
+        max_side: int = 960,
+        fps: float = 15.0,
+    ) -> None:
+        self.max_frames = max(1, int(max_frames))
+        self.jpeg_quality = min(100, max(30, int(jpeg_quality)))
+        self.max_side = max(160, int(max_side))
+        self.fps = max(1.0, float(fps))
+        self._frames: Deque[Dict[str, object]] = deque(maxlen=self.max_frames)
+
+    def __len__(self) -> int:
+        return len(self._frames)
+
+    def clear(self) -> None:
+        self._frames.clear()
+
+    def append(self, image: np.ndarray, ts: float, frame_id: int) -> bool:
+        if cv2 is None or image is None or getattr(image, "size", 0) == 0:
+            return False
+        ok, buffer = cv2.imencode(
+            ".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), self.jpeg_quality]
+        )
+        if not ok:
+            return False
+        self._frames.append(
+            {"ts": float(ts), "frame_id": int(frame_id), "jpeg": buffer.tobytes()}
+        )
+        return True
+
+    def save(
+        self,
+        directory: str,
+        payload: Optional[Dict[str, object]] = None,
+        stem: Optional[str] = None,
+    ) -> Dict[str, object]:
+        """把环缓存盘;返回 ``{"clip":..., "frames":..., "meta":...}``。"""
+
+        _ensure_dir(directory)
+        stem = stem or ("event-%s" % time.strftime("%Y%m%d-%H%M%S"))
+        meta_path = os.path.join(directory, "%s.json" % stem)
+        with open(meta_path, "w", encoding="utf-8") as fh:
+            json.dump(payload or {}, fh, ensure_ascii=False, default=str, indent=2)
+        saved = {"clip": "", "frames": 0, "meta": meta_path, "mode": "none"}
+        if not self._frames:
+            return saved
+
+        first = cv2.imdecode(np.frombuffer(self._frames[0]["jpeg"], np.uint8), cv2.IMREAD_COLOR)  # type: ignore[arg-type]
+        if first is None:
+            return saved
+        height, width = first.shape[:2]
+        scale = min(1.0, float(self.max_side) / float(max(width, height)))
+        size = (max(2, int(round(width * scale))), max(2, int(round(height * scale))))
+
+        clip_path = os.path.join(directory, "%s.mp4" % stem)
+        writer = None
+        if cv2 is not None:
+            writer = cv2.VideoWriter(
+                clip_path, cv2.VideoWriter_fourcc(*"mp4v"), self.fps, size
+            )
+        if writer is not None and writer.isOpened():
+            for item in self._frames:
+                frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR)  # type: ignore[arg-type]
+                if frame is None:
+                    continue
+                if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
+                    frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
+                writer.write(frame)
+                saved["frames"] = int(saved["frames"]) + 1
+            writer.release()
+            saved["clip"] = clip_path
+            saved["mode"] = "mp4"
+        else:
+            if writer is not None:
+                writer.release()
+            frame_dir = _ensure_dir(os.path.join(directory, "%s_frames" % stem))
+            for index, item in enumerate(self._frames):
+                frame = cv2.imdecode(np.frombuffer(item["jpeg"], np.uint8), cv2.IMREAD_COLOR)  # type: ignore[arg-type]
+                if frame is None:
+                    continue
+                if frame.shape[1] != size[0] or frame.shape[0] != size[1]:
+                    frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
+                path = os.path.join(frame_dir, "%06d.jpg" % index)
+                cv2.imwrite(path, frame)
+                saved["frames"] = int(saved["frames"]) + 1
+            saved["clip"] = frame_dir
+            saved["mode"] = "jpg"
+        return saved
+
+
+class EvidenceStore:
+    """P0-4 证据落盘门面:逐帧 JSONL + 事件环缓 + 保留期清理。"""
+
+    def __init__(
+        self,
+        directory: str,
+        retention_days: float = 90.0,
+        segment_bytes: int = DEFAULT_SEGMENT_BYTES,
+        ring_frames: int = 300,
+        fps: float = 15.0,
+        jpeg_quality: int = 85,
+        max_side: int = 960,
+    ) -> None:
+        self.directory = _ensure_dir(directory)
+        self.retention_days = max(0.0, float(retention_days))
+        self.writer = SegmentingJsonlWriter(
+            self.directory, max_bytes=segment_bytes, retention_days=self.retention_days
+        )
+        self.ring = EventRing(
+            max_frames=ring_frames, jpeg_quality=jpeg_quality, max_side=max_side, fps=fps
+        )
+        self.events = 0
+        self.last_event: Dict[str, object] = {}
+
+    @classmethod
+    def from_config(cls, cfg: Config) -> "EvidenceStore":
+        run_dir = str(cfg.get_path("run.output_dir", "runs") or "runs")
+        directory = str(cfg.get_path("evidence.dir", "") or os.path.join(run_dir, "evidence"))
+        segment_mb = float(cfg.get_path("evidence.segment_mb", 50.0) or 50.0)
+        return cls(
+            directory=directory,
+            retention_days=float(cfg.get_path("evidence.retention_days", 90.0) or 90.0),
+            segment_bytes=int(segment_mb * 1024 * 1024),
+            ring_frames=int(cfg.get_path("evidence.ring_frames", 300) or 300),
+            fps=float(cfg.get_path("evidence.fps", 15.0) or 15.0),
+            jpeg_quality=int(cfg.get_path("evidence.jpeg_quality", 85) or 85),
+            max_side=int(cfg.get_path("evidence.max_side", 960) or 960),
+        )
+
+    def open(self) -> "EvidenceStore":
+        self.writer.open()
+        return self
+
+    def close(self) -> None:
+        self.writer.close()
+
+    def record(
+        self,
+        frame,
+        observation,
+        decision,
+        snapshot=None,
+        evidence=None,
+        health=None,
+        event: bool = False,
+    ) -> Dict[str, object]:
+        """写一行逐帧记录;``event=True`` 时同时导出环缓。"""
+
+        now = time.time()
+        if not self.writer.session:
+            self.writer.open()
+        payload: Dict[str, object] = {
+            "ts": round(now, 3),
+            "session": self.writer.session,
+            "frame_ts": round(float(getattr(frame, "ts", 0.0)), 3),
+            "frame_id": int(getattr(frame, "frame_id", 0)),
+            "state": int(getattr(decision, "state", 255)),
+            "label": str(getattr(decision, "label", "unknown")),
+            "confidence": round(float(getattr(decision, "confidence", 0.0)), 4),
+            "stable": bool(getattr(decision, "stable", False)),
+            "changed": bool(getattr(decision, "changed", False)),
+            "reason": str(getattr(decision, "reason", "")),
+            "observation": {
+                "state": int(getattr(observation, "state", 255)),
+                "confidence": round(float(getattr(observation, "confidence", 0.0)), 4),
+                "reason": str(getattr(observation, "reason", "")),
+                "detections": [
+                    box.to_dict() for box in getattr(observation, "detections", []) or []
+                ],
+            },
+        }
+        if snapshot is not None:
+            payload["snapshot"] = snapshot.to_dict()
+        if evidence is not None:
+            payload["evidence"] = evidence if isinstance(evidence, dict) else evidence.to_dict()
+        if health is not None:
+            payload["health"] = health if isinstance(health, dict) else health.to_dict()
+
+        self.writer.write(payload)
+        self.ring.append(getattr(frame, "image", None), payload["frame_ts"], payload["frame_id"])
+        if event:
+            self.events += 1
+            stem = "event-%s-%06d" % (time.strftime("%Y%m%d-%H%M%S"), self.events)
+            self.last_event = self.ring.save(self.directory, payload=payload, stem=stem)
+            self.last_event["stem"] = stem
+        return payload
+
+    def purge(self) -> List[str]:
+        """删除超过保留期的段/事件文件;返回删除路径。"""
+
+        return purge_old_files(self.directory, self.retention_days)
+
+

+ 40 - 0
pyproject.toml

@@ -0,0 +1,40 @@
+[build-system]
+requires = ["setuptools>=61"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "portcv"
+version = "0.1.0"
+description = "港口吊装视觉识别:判定集装箱在车斗 / 平板车 / 不在车上,并通过 Modbus-TCP 发布给 PLC"
+readme = "README.md"
+requires-python = ">=3.8"
+license = { text = "Proprietary" }
+authors = [{ name = "portcv team" }]
+keywords = ["vision", "yolo", "port", "modbus", "plc", "jetson", "rk3588"]
+classifiers = [
+    "Programming Language :: Python :: 3",
+    "Operating System :: POSIX :: Linux",
+    "Topic :: Scientific/Engineering :: Image Recognition",
+]
+# 只保留硬依赖:现场板子上的加速运行时(tensorrt / rknnlite)由系统/官方 wheel 提供
+dependencies = ["numpy>=1.21", "opencv-python>=4.5"]
+
+[project.optional-dependencies]
+dev = ["pyyaml>=6.0", "onnx>=1.14", "onnxruntime>=1.16", "ultralytics>=8.1"]
+onnx = ["onnxruntime>=1.16"]
+
+[project.scripts]
+portcv = "portcv.cli:main"
+
+[tool.setuptools]
+packages = [
+    "portcv",
+    "portcv.detect",
+    "portcv.io",
+    "portcv.logic",
+    "portcv.plc",
+    "portcv.service",
+]
+
+[tool.setuptools.package-data]
+portcv = ["py.typed"]

+ 12 - 0
requirements-dev.txt

@@ -0,0 +1,12 @@
+# 开发机依赖:训练/导出/联调(不需要装在现场板子上)
+-r requirements.txt
+
+pyyaml>=6.0            # 可选配置格式
+onnx>=1.14             # scripts/export_onnx.py --check、模型图检查
+onnxruntime>=1.16      # 无板子时跑 onnx 后端做端到端回归
+ultralytics>=8.1       # 训练 + 导出 YOLOv8/v11
+# rknn-toolkit2        # 仅 x86 Linux,转换 rknn 用(见 requirements-rknn.txt)
+# torch / torchvision  # ultralytics 会自动带;单独训练时按官方说明装 CUDA 版
+
+# 测试:全部基于标准库 unittest,无需 pytest:
+#   python -m unittest discover -s tests -t . -v

+ 10 - 0
requirements-jetson.txt

@@ -0,0 +1,10 @@
+# Jetson(Orin / Xavier / Nano):基础依赖 + 板载加速后端
+# 注意:tensorrt / cuda-python / pycuda 请用 JetPack 自带的,不要 pip 覆盖!
+-r requirements.txt
+
+# TensorRT 走 JetPack(python3 -c "import tensorrt; print(tensorrt.__version__)" 验证)
+# 若要用 onnxruntime 兜底对比精度:
+# onnxruntime-gpu>=1.16
+
+# 需要 DeepStream 多路相机时,用 SDK Manager 装 DeepStream,不要 pip:
+#   /opt/nvidia/deepstream/deepstream-6.4  (deploy/deepstream/ 下有配置模板)

+ 9 - 0
requirements-rknn.txt

@@ -0,0 +1,9 @@
+# Rockchip RK3588 / RK3576 / RK3568 板子上的推理依赖
+-r requirements.txt
+
+# rknn-toolkit-lite2:板子上的推理运行时(用官方 wheel,别 pip 乱装)
+# 例(Python 3.9,rk3588):
+#   pip install rknn_toolkit_lite2-2.0.0b0-cp39-cp39-linux_aarch64.whl
+#
+# 转换用的 rknn-toolkit2 只装在 x86 开发机(不在板子上):
+#   pip install rknn-toolkit2

+ 6 - 0
requirements.txt

@@ -0,0 +1,6 @@
+# portcv 基础依赖:只有这两个是硬依赖(现场镜像必须能装上)。
+numpy>=1.21
+opencv-python>=4.5
+
+# 可选:装了才能读 .yaml/.yml 配置(.json 是标准库原生支持)
+# pyyaml>=6.0