| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913 |
- // portcv(C++)可执行入口:取帧 → 检测 / 边缘证据 → 时序滤波 → Modbus/TCP 服务端。
- //
- // 线程模型(docs/technical_route.md §5.2):
- // * 线程 A 取流(`source.type != none` 时才起):相机 → 灰度帧 → 帧槽(**只留最新一帧**);
- // * 线程 B 本函数主循环:从帧槽取最新帧 → 推理/证据 → 时序滤波 → PublishGate → 写快照
- // (+ 可选导出黄金语料);没有新帧时按 `source.stale_frame_s` 置 `flags.FRAME_TIMEOUT`,
- // 并由 PublishGate 保持上一稳定值(无历史则 0)、清 RESULT_VALID/STABLE
- // (与 Python `portcv/service/runner.py` 同口径)—— 相机断了 PLC 看到的是"不可信",
- // 而不是旧结果,也不会在结果区看到 255;
- // * 线程 C Modbus/TCP Server:只读快照,**永不因推理/取帧慢而阻塞**。
- //
- // 两种后端(配置文件 `run.backend`,命令行 `--backend` 可覆盖):
- // * mock:脚本化检测框 → SceneClassifier(composed / direct 规则)→ TemporalVoter。
- // 无相机、无模型也能把"寄存器刷新 + 指令握手"整条链路联调通(现场先对寄存器);
- // * edge:EdgeEvidenceDetector(docs/edge_evidence.md 的二维边缘几何证据,**C++ 唯一实现**)
- // → 硬门槛 / 弃权 / 运动门控结论 → TemporalVoter。
- // 现场部署用的就是它:不需要 NPU、不需要 OpenCV、不需要模型权重。
- //
- // 参数一律来自配置文件(现场改配置**不重编译**),命令行只做覆盖:
- // portcv_run -c configs/edge-cpp.json --backend edge
- // portcv_run -c configs/edge-cpp.json --check-config # 只打印生效参数后退出
- //
- // 部署纪律(与 Python 版"二选一",见 docs/deployment.md §2.5):
- // 同一台机器**只跑一个运行时**。两个进程抢同一个端口时后启动的一方会 bind 失败,
- // 所以换运行时务必 `systemctl stop portcv` 之后再 `systemctl start portcv-cpp`。
- #include <atomic>
- #include <chrono>
- #include <csignal>
- #include <cstdint>
- #include <cstdio>
- #include <cstdlib>
- #include <ctime>
- #include <memory>
- #include <mutex>
- #include <string>
- #include <thread>
- #include <utility>
- #include <vector>
- #include "portcv/app_config.hpp"
- #include "portcv/calibration.hpp"
- #include "portcv/capture.hpp"
- #include "portcv/decision.hpp"
- #include "portcv/detector.hpp"
- #include "portcv/edge_evidence.hpp"
- #include "portcv/edge_v2.hpp"
- #include "portcv/frame_dump.hpp"
- #include "portcv/modbus_server.hpp"
- #include "portcv/publish_gate.hpp"
- #include "portcv/rate_stats.hpp"
- #include "portcv/registers.hpp"
- #include "portcv/scene.hpp"
- #include "portcv/schema.hpp"
- #include "portcv/snapshot.hpp"
- namespace {
- std::atomic<bool> g_stop{false};
- void on_signal(int) { g_stop.store(true); }
- double now_seconds() {
- using namespace std::chrono;
- return duration_cast<duration<double>>(steady_clock::now().time_since_epoch()).count();
- }
- /// 演示脚本(mock 后端):空画面 → 平车无箱 → 平车落箱 → 敞车(车斗)落箱。
- std::vector<std::vector<portcv::Box>> demo_script() {
- using portcv::make_box;
- std::vector<std::vector<portcv::Box>> script;
- script.push_back({}); // 0) 空画面
- script.push_back({make_box("flatbed", 650, 690, 1150, 900, 0.88f, 2)}); // 1) 只有平车
- script.push_back({ // 2) 平车 + 箱
- make_box("flatbed", 650, 690, 1150, 900, 0.85f, 2),
- make_box("container", 700, 400, 1100, 700, 0.91f, 0)});
- script.push_back({ // 3) 平车 + 箱(箱已落位)
- make_box("flatbed", 650, 690, 1150, 900, 0.87f, 2),
- make_box("container", 700, 402, 1100, 699, 0.93f, 0)});
- for (int i = 0; i < 6; ++i) { script.push_back(script.back()); }
- script.push_back({ // 4) 换成敞车(车斗)
- make_box("bed", 640, 660, 1160, 900, 0.90f, 1),
- make_box("container", 700, 380, 1100, 662, 0.92f, 0)});
- for (int i = 0; i < 8; ++i) { script.push_back(script.back()); }
- return script;
- }
- /// 命令行参数(只记录"给了什么",最终取值 = 配置文件 → 命令行覆盖)。
- struct Cli {
- std::string config_path; ///< -c / --config:现场配置文件
- bool check_config = false; ///< --check-config:打印生效参数后退出
- bool no_plc = false; ///< --no-plc:不启动 Modbus/TCP 服务端
- bool publish_edge_flags = false; ///< --publish-edge-flags(§10 需 PLC 签字)
- long max_frames = 0; ///< --max-frames:跑够 N 帧自动退出(0 = 不限)
- bool has_backend = false;
- std::string backend;
- bool has_edge_demo = false;
- std::string edge_demo;
- bool has_host = false;
- std::string host;
- bool has_port = false;
- int port = 0;
- bool has_unit = false;
- int unit = 0;
- bool has_input_addr = false;
- int input_addr = 0;
- bool has_holding_addr = false;
- int holding_addr = 0;
- bool has_fps = false;
- double fps = 0.0;
- bool has_mode = false;
- std::string mode;
- // ---- 取流(覆盖 source.*;用法见 print_usage)----
- bool has_source_uri = false;
- std::string source_uri; ///< --source-uri:相机地址 / 文件 / 管线字符串
- bool has_source_type = false;
- std::string source_type; ///< --source-type:强制指定取流类型(默认按 uri 推断)
- // ---- 黄金语料导出(B-lite:现场整定 + 自动回归用;不改判决)----
- bool has_dump_path = false;
- std::string dump_path; ///< --dump-frames:JSONL 输出路径
- bool has_dump_dir = false;
- std::string dump_dir; ///< --dump-dir:PGM 输出目录(缺省 = JSONL 同级的 frames/)
- bool has_dump_every = false;
- int dump_every = 1; ///< --dump-every:每 N 帧导出一帧
- };
- void print_usage(const char* argv0) {
- std::printf(
- "用法: %s [-c configs/site.json] [--backend mock|edge]\n"
- " [--edge-demo none|gondola|flatbed|ground] [--check-config] [--max-frames N]\n"
- " [--source-uri rtsp://…|/dev/video0|out.mp4|runs/frames(PGM 目录)"
- "|'…!appsink name=portcv_sink…']\n"
- " [--source-type none|synth|images|gst|rtsp|file|usb]\n"
- " [--dump-frames runs/dump.jsonl] [--dump-dir runs/dump] [--dump-every N]\n"
- " [--host 0.0.0.0] [--port 1502] [--unit 1] [--input-addr 0] "
- "[--holding-addr 0]\n"
- " [--fps 15] [--mode composed|direct] [--no-plc] [--publish-edge-flags(已停用)]\n"
- "\n"
- "参数优先级:命令行 > 配置文件 > 内置默认值(= 各结构体默认值)。\n"
- "配置文件键与 Python 侧同名同义(plc.modbus.* / scene.* / decision.* / edge.* / source.*),\n"
- "只写要覆盖的字段;键名或类型写错会**直接报错退出**,不会静默取默认值。\n"
- "真机取流:source.type=rtsp|file|usb|gst(需 -DPORTCV_WITH_GSTREAMER=ON 构建);\n"
- "没有相机时用 --edge-demo(= source.type=synth)先把寄存器与握手对完;\n"
- "现场片段(mp4)离线复盘:source.type=images(--source-uri 指 PGM 目录,零依赖):\n"
- " python scripts/extract_frames.py --clip 现场.mp4 --out runs/frames\n"
- " portcv_run -c configs/edge-cpp.json --source-type images --source-uri runs/frames "
- "--no-plc\n",
- argv0);
- }
- bool parse_args(int argc, char** argv, Cli* cli) {
- for (int i = 1; i < argc; ++i) {
- const std::string key = argv[i];
- const char* value = nullptr;
- auto need_value = [&]() -> bool {
- if (i + 1 >= argc) { return false; }
- value = argv[++i];
- return true;
- };
- if ((key == "-c" || key == "--config") && need_value()) {
- cli->config_path = value;
- } else if (key == "--backend" && need_value()) {
- cli->has_backend = true;
- cli->backend = value;
- } else if (key == "--edge-demo" && need_value()) {
- cli->has_edge_demo = true;
- cli->edge_demo = value;
- } else if (key == "--host" && need_value()) {
- cli->has_host = true;
- cli->host = value;
- } else if (key == "--port" && need_value()) {
- cli->has_port = true;
- cli->port = std::atoi(value);
- } else if (key == "--unit" && need_value()) {
- cli->has_unit = true;
- cli->unit = std::atoi(value);
- } else if (key == "--input-addr" && need_value()) {
- cli->has_input_addr = true;
- cli->input_addr = std::atoi(value);
- } else if (key == "--holding-addr" && need_value()) {
- cli->has_holding_addr = true;
- cli->holding_addr = std::atoi(value);
- } else if (key == "--fps" && need_value()) {
- cli->has_fps = true;
- cli->fps = std::atof(value);
- } else if (key == "--mode" && need_value()) {
- cli->has_mode = true;
- cli->mode = value;
- } else if (key == "--max-frames" && need_value()) {
- cli->max_frames = std::atol(value);
- } else if (key == "--source-uri" && need_value()) {
- cli->has_source_uri = true;
- cli->source_uri = value;
- } else if (key == "--source-type" && need_value()) {
- cli->has_source_type = true;
- cli->source_type = value;
- } else if (key == "--dump-frames" && need_value()) {
- cli->has_dump_path = true;
- cli->dump_path = value;
- } else if (key == "--dump-dir" && need_value()) {
- cli->has_dump_dir = true;
- cli->dump_dir = value;
- } else if (key == "--dump-every" && need_value()) {
- cli->has_dump_every = true;
- cli->dump_every = std::atoi(value);
- } else if (key == "--check-config") {
- cli->check_config = true;
- } else if (key == "--no-plc") {
- cli->no_plc = true;
- } else if (key == "--publish-edge-flags") {
- cli->publish_edge_flags = true;
- } else if (key == "--help" || key == "-h") {
- print_usage(argv[0]);
- return false;
- } else {
- std::printf("未知参数: %s\n", key.c_str());
- print_usage(argv[0]);
- return false;
- }
- }
- return true;
- }
- /// 命令行覆盖配置文件(**只覆盖显式给出的项**),并做与配置文件同口径的范围检查。
- bool apply_cli(const Cli& cli, portcv::AppConfig* cfg, std::string* error) {
- const auto bad = [error](const std::string& what) {
- if (error != nullptr) { *error = what; }
- return false;
- };
- if (cli.has_host) { cfg->modbus.host = cli.host; }
- if (cli.has_port) {
- if (cli.port < 0 || cli.port > 65535) { return bad("--port 超出 0~65535"); }
- cfg->modbus.port = static_cast<uint16_t>(cli.port);
- }
- if (cli.has_unit) {
- if (cli.unit < 0 || cli.unit > 255) { return bad("--unit 超出 0~255"); }
- cfg->modbus.unit_id = static_cast<uint8_t>(cli.unit);
- }
- if (cli.has_input_addr) {
- if (cli.input_addr < 0 || cli.input_addr > 65535) { return bad("--input-addr 超出 0~65535"); }
- cfg->modbus.input_addr = static_cast<uint16_t>(cli.input_addr);
- }
- if (cli.has_holding_addr) {
- if (cli.holding_addr < 0 || cli.holding_addr > 65535) {
- return bad("--holding-addr 超出 0~65535");
- }
- cfg->modbus.holding_addr = static_cast<uint16_t>(cli.holding_addr);
- }
- if (cli.has_fps) {
- // 判据写成 `!(x > 0)` 而不是 `x <= 0`:NaN 与任何数比较都是 false,
- // 用后者会让 `--fps nan` 一路穿过校验,主循环 period=1/NaN → 全速空转
- // (fuzz 用例 fps_nan,见 docs/stability_soak.md §3.2)。
- if (!(cli.fps > 0.0) || cli.fps > 240.0) { return bad("--fps 必须 ∈ (0, 240]"); }
- cfg->max_fps = cli.fps;
- }
- if (cli.has_mode) {
- if (cli.mode != "composed" && cli.mode != "direct") {
- return bad("--mode 只能是 composed / direct");
- }
- cfg->scene.mode = cli.mode;
- }
- if (cli.has_backend) { cfg->backend = cli.backend; }
- // 取流:`--source-uri` 决定了类型(rtsp:// → rtsp,/dev/video* → usb,含 '!' → gst 管线,
- // 其余 → file),除非 `--source-type` 明确指定;`--source-type` 永远最后赢。
- if (cli.has_source_uri) {
- cfg->source.uri = cli.source_uri;
- if (!cli.has_source_type) {
- cfg->source.type = portcv::source_type_from_uri(cli.source_uri);
- }
- }
- if (cli.has_source_type) { cfg->source.type = cli.source_type; }
- if (cli.has_edge_demo) {
- cfg->edge_demo = cli.edge_demo;
- // 台架开关:切到合成帧源(**覆盖** source.*)——"没有相机也能把整条链路验完"。
- if (cli.edge_demo != "none") {
- cfg->source.type = "synth";
- cfg->source.uri = cli.edge_demo;
- }
- }
- if (cli.has_dump_every && cli.dump_every < 1) { return bad("--dump-every 至少 1"); }
- if (cli.no_plc) { cfg->plc_enabled = false; }
- if (cli.publish_edge_flags) { cfg->publish_edge_flags = true; }
- if (cli.max_frames < 0) { return bad("--max-frames 不能为负"); }
- if (error != nullptr) { error->clear(); }
- return true;
- }
- /// `--dump-dir` 缺省:JSONL 同级的 frames/(JSONL 没有目录 → ./frames)。
- std::string default_dump_dir(const std::string& jsonl_path) {
- const std::size_t pos = jsonl_path.find_last_of("/\\");
- if (pos == std::string::npos) { return "frames"; }
- return jsonl_path.substr(0, pos + 1) + "frames";
- }
- } // namespace
- int main(int argc, char** argv) {
- Cli cli;
- if (!parse_args(argc, argv, &cli)) { return 2; }
- std::string error;
- portcv::AppConfig config;
- if (!portcv::load_app_config(cli.config_path, &config, &error)) {
- std::printf("配置加载失败: %s\n", error.c_str());
- return 4;
- }
- if (!apply_cli(cli, &config, &error)) {
- std::printf("命令行参数不对: %s\n", error.c_str());
- return 2;
- }
- if (!portcv::check_backend(config, &error)) {
- std::printf("后端不可用: %s\n", error.c_str());
- return 3;
- }
- std::printf("portcv(C++) 配置文件: %s\n",
- cli.config_path.empty() ? "(未指定,全部用内置默认值)" : cli.config_path.c_str());
- std::printf("%s", portcv::describe_app_config(config).c_str());
- // P0-5:标定记录在启动时**判定一次**(与 Python `RunService.start()` 同口径)。
- // 结果写进 flags bit11 `CALIB_STALE`;是否需要"清 RESULT_VALID/STABLE"由
- // calibration.hold_on_stale 决定(默认 true —— 标定不可信就不给可执行结果)。
- const portcv::CalibrationStatus calib =
- portcv::evaluate_calibration(config.calibration, config.evidence_v2.px_per_m,
- config.evidence_v2.box_height_m, portcv::epoch_now());
- std::printf("%s", portcv::calibration_status_line(calib).c_str());
- if (calib.stale) {
- std::printf("[warn] 标定不可用(CALIB_STALE:%s)→ flags bit11=1%s\n",
- calib.reasons_text().c_str(),
- calib.hold ? ";并清 RESULT_VALID/STABLE(calibration.hold_on_stale=1,PLC 不得据此自动动作)"
- : ";仅告警(calibration.hold_on_stale=0,是否继续自动运行由 PLC 联锁决定)");
- std::printf(" 处理:现场重标 → 第二人复核 → 重新封存记录(scripts/calib_record.py create)\n");
- std::fflush(stdout);
- }
- std::fflush(stdout);
- if (cli.check_config) {
- std::printf("--check-config:参数有效;未启动服务、未取帧。\n");
- return 0;
- }
- if (config.publish_edge_flags) {
- std::printf(
- "警告:--publish-edge-flags 已停用(bit8~12 为 PERCEPTION_UNCERTAIN/MRC/"
- "SENSOR/CALIB/DATA_LOSS);\n"
- " edge 诊断只写入 word10(reserved),不会覆盖标准 flags。\n");
- }
- std::signal(SIGINT, on_signal);
- std::signal(SIGTERM, on_signal);
- // ---------------- 组件装配 ----------------
- portcv::LatestSnapshot snapshot;
- portcv::CommandSlot commands;
- portcv::SceneClassifier classifier(config.scene);
- portcv::TemporalVoter voter(config.voter);
- // V2:PLC 结果区只写 0/1/2;内部 255/低分/未稳定/超时在这里被保持。
- portcv::PublishGate gate(config.voter.min_confidence);
- // cmd=2 由 Modbus 线程置位、主循环消费:PublishGate 非线程安全,不能跨线程调用。
- std::atomic<bool> reset_pending{false};
- std::unique_ptr<portcv::MockDetector> mock;
- std::unique_ptr<portcv::EdgeEvidenceDetector> edge;
- std::unique_ptr<portcv::EdgeV2> edge_v2;
- if (config.backend == "edge") {
- edge.reset(new portcv::EdgeEvidenceDetector(config.edge, config.line));
- } else if (config.backend == "edge-v2" || config.backend == "evidence-v2") {
- edge_v2.reset(new portcv::EdgeV2(config.evidence_v2, config.evidence_commit));
- } else {
- mock.reset(new portcv::MockDetector(demo_script()));
- }
- portcv::Detector* detector = nullptr;
- if (edge) {
- detector = edge.get();
- } else {
- // edge-v2 自带逐帧判定;mock 只用于满足 Detector 接口的 warmup/名称打印。
- if (!mock) { mock.reset(new portcv::MockDetector(demo_script())); }
- detector = mock.get();
- }
- if (!detector->warmup(&error)) {
- std::printf("后端预热失败: %s\n", error.c_str());
- return 5;
- }
- // ---------------- 取流(线程 A:相机 → 灰度帧 → 帧槽)----------------
- // 配置 `source.*`(键名与 Python 同名同义)+ 命令行覆盖(--source-uri / --edge-demo)。
- // `source.type=none` → 不起线程,主循环保持旧行为(Frame.gray = nullptr,证据后端输出 255)。
- std::unique_ptr<portcv::FrameSource> source;
- portcv::FrameSlot slot;
- std::thread capture_thread;
- std::atomic<uint64_t> capture_failures{0};
- std::mutex capture_error_mu;
- std::string capture_last_error;
- if (!portcv::make_frame_source(config.source, &source, &error)) {
- std::printf("取流不可用: %s\n", error.c_str());
- return 6;
- }
- if (source) {
- std::printf("取流 : %s —— %s\n", source->name().c_str(), source->describe().c_str());
- } else if (edge || edge_v2) {
- std::printf(
- "[edge] 未配置取流(source.type=none):Frame.gray = nullptr → 证据后端输出 255"
- "(安全值,绝不误报 2);\n"
- " 台架用 `--edge-demo gondola|flatbed|ground`(合成帧),"
- "真机用 `--source-uri rtsp://…`。\n");
- }
- std::fflush(stdout);
- // ---------------- 黄金语料导出(B-lite;只读旁路,写失败只告警不影响判决)----------------
- portcv::FrameDumper dumper;
- if (cli.has_dump_path) {
- portcv::DumpConfig dump_cfg;
- dump_cfg.jsonl_path = cli.dump_path;
- dump_cfg.image_dir = cli.has_dump_dir ? cli.dump_dir : default_dump_dir(cli.dump_path);
- dump_cfg.every = cli.dump_every;
- if (!dumper.open(dump_cfg, &error)) {
- std::printf("导出初始化失败: %s\n", error.c_str());
- return 7;
- }
- std::printf(
- "导出 : %s(每 %d 帧一行 JSON;像素目录 %s)\n"
- " 回放断言:python scripts/replay_check.py %s [--baseline <基线.jsonl>]\n",
- dump_cfg.jsonl_path.c_str(), dump_cfg.every,
- dump_cfg.image_dir.empty() ? "(不存图)" : dump_cfg.image_dir.c_str(),
- dump_cfg.jsonl_path.c_str());
- std::fflush(stdout);
- }
- std::unique_ptr<portcv::ModbusServer> server;
- std::thread server_thread;
- if (config.plc_enabled) {
- server.reset(new portcv::ModbusServer(config.modbus, &snapshot));
- server->set_command_handler([&](const portcv::PlcCommand& command) {
- commands.set(command);
- std::printf("[plc] cmd=%u(%s) preset=%u min_conf=%u\n", command.cmd,
- portcv::cmd_label(command.cmd), command.preset, command.min_conf);
- std::fflush(stdout);
- // 不在服务线程里改状态:主循环用 commands.take() 消费并按 cmd 处理。
- });
- if (!server->start(&error)) {
- std::printf("Modbus/TCP 启动失败: %s\n", error.c_str());
- std::printf(
- "提示(部署纪律):同一台机器只跑一个运行时 —— 先 `systemctl stop portcv`"
- "(Python 版)再启动本程序;或临时用 `--no-plc` 只跑推理。\n");
- return 1;
- }
- std::printf("portcv(C++) detector=%s\n", detector->name().c_str());
- std::printf("Modbus/TCP 监听 %s\n",
- portcv::layout_summary(config.modbus.host, server->bound_port(),
- config.modbus.unit_id, config.modbus.input_addr,
- config.modbus.holding_addr)
- .c_str());
- std::printf("输入寄存器表(PLC 用 FC4 按地址读):\n");
- for (const portcv::LayoutRow& row : portcv::snapshot_rows(config.modbus.input_addr)) {
- std::printf(" %5u %-12s %s\n", row.address, row.field.c_str(), row.note.c_str());
- }
- std::fflush(stdout);
- server_thread = std::thread([&server]() { server->serve_forever(); });
- } else {
- std::printf("portcv(C++) detector=%s\n", detector->name().c_str());
- std::printf("[plc] 未启动 Modbus/TCP 服务端(plc.enabled=false 或 --no-plc):只推理 + 打日志\n");
- std::fflush(stdout);
- }
- // 先发布一张"未就绪"快照:V2 结果区只写 0/1/2(flags 0/0 = 未知/保持),
- // PLC 立刻就能读到合法数据,而不是 V1 的 255。
- {
- portcv::VisionSnapshot boot;
- boot.state = static_cast<uint16_t>(portcv::SceneState::NOT_ON_TRAIN);
- boot.confidence = 0;
- boot.flags = 0;
- snapshot.store(boot);
- }
- // ---------------- 取帧线程(线程 A)----------------
- // 为什么单独一线程:取帧/解码/重连是**阻塞**的(RTSP 抖动、U 盘式相机掉线都要等)。
- // 放在主循环里会让"没有画面"的那段时间连心跳和 FRAME_TIMEOUT 都发不出去。
- // 帧槽只留最新一帧 → 推理慢于取流时丢旧帧,而不是排队累积延迟。
- if (source) {
- capture_thread = std::thread([&]() {
- std::string next_error;
- uint64_t consecutive = 0;
- while (!g_stop.load()) {
- if (slot.has_new()) { // 消费者还没取走上一帧:先别取(省 CPU,也让帧更新)
- std::this_thread::sleep_for(std::chrono::milliseconds(2));
- continue;
- }
- portcv::CapturedFrame cap;
- if (!source->next(&cap, &next_error)) {
- ++consecutive;
- capture_failures.fetch_add(1);
- {
- std::lock_guard<std::mutex> lock(capture_error_mu);
- capture_last_error = next_error;
- }
- // 前 1 次 + 之后每 100 次打一行:现场日志要能看出"相机在反复掉线",
- // 又不至于把 journal 刷爆。
- if (consecutive == 1 || consecutive % 100 == 0) {
- std::printf("[warn] 取流失败(连续第 %llu 次):%s\n",
- static_cast<unsigned long long>(consecutive),
- next_error.c_str());
- std::fflush(stdout);
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- continue;
- }
- consecutive = 0;
- slot.publish(std::move(cap));
- }
- });
- std::printf("取帧线程已启动(线程 A);帧槽只保留最新一帧,取流失败按 "
- "source.reconnect_s=%.1fs 重连\n",
- config.source.reconnect_s);
- std::fflush(stdout);
- }
- // ---------------- 主循环:持续推理 + 持续发布 ----------------
- const double period = 1.0 / config.max_fps;
- // 断流时"隔多久重发一次超时快照"(与 Python `_publish_timeout_if_needed` 的 heartbeat_s 同量级)。
- const double kTimeoutPublishS = 0.5;
- portcv::Frame frame;
- uint16_t heartbeat = 0;
- double last_heartbeat = now_seconds();
- uint64_t frames = 0;
- uint64_t published = 0;
- double window_start = now_seconds();
- double latency_sum = 0.0;
- double max_latency = 0.0;
- // 断流兜底发布用的"上一拍"值(断流时没有新判决,沿用最近的 seq / 耗时)。
- uint32_t last_seq = 0;
- uint16_t last_latency_ms = 0;
- double last_timeout_publish = 0.0;
- bool timeout_latched = false;
- // cmd=2 后的下一个快照必须是 0 + flags 0/0(清 last stable),之后才允许重新建立。
- bool reset_publish_pending = false;
- double on_demand_until = 0.0;
- // 运行期观测(见 include/portcv/rate_stats.hpp):
- // * `measured_fps` = 最近 2 s 主循环真实节拍 → 填寄存器 `fps_x10` 并判 `flags.LOW_FPS`;
- // * `latency_window` = 最近 256 帧的单帧耗时分布 → 日志里的 p50/p95/p99(§6.4 验收看 P95/P99)。
- portcv::RateMeter rate(2.0);
- portcv::LatencyStats latency_window(256);
- double measured_fps = 0.0;
- bool low_fps_latched = false;
- while (!g_stop.load() && (!server || !server->stopped())) {
- const double loop_start = now_seconds();
- // PLC 指令在主线程消费(`take()` 读后清零 = 一次握手)。
- const portcv::PlcCommand command = commands.take();
- if (command.cmd == portcv::CMD_REQUEST) {
- on_demand_until = loop_start + config.gating_timeout_s;
- } else if (command.cmd == portcv::CMD_RESET) {
- reset_pending.store(true);
- } else if (command.cmd == portcv::CMD_CLEAR_STATS) {
- std::printf("[plc] 收到清统计命令(C++ 侧只清本轮显示计数,累计计数保留)\n");
- std::fflush(stdout);
- }
- if (command.min_conf > 0) {
- gate.set_min_conf(static_cast<double>(command.min_conf) / 1000.0);
- }
- // PLC 复位在**主线程**消费:TemporalVoter / PublishGate 都不是线程安全的。
- if (reset_pending.exchange(false)) {
- voter.reset();
- gate.reset();
- reset_publish_pending = true;
- timeout_latched = false;
- std::printf("[plc] 收到复位命令 → 时序滤波与 PublishGate 已清零\n");
- std::fflush(stdout);
- }
- // 取帧:① 配了取流源 → 从帧槽取最新一帧(线程 A 在填);
- // ② 没配(source.type=none)→ 旧行为:Frame.gray = nullptr,每拍都"有新帧"。
- portcv::CapturedFrame cap;
- if (source && !slot.take(&cap)) {
- // 没有新帧:心跳照走,并按 source.stale_frame_s 处置
- //(与 Python `runner.py::_publish_timeout_if_needed` 同口径):
- // 相机/网络断了必须让 PLC 看到"不可信",而不是继续拿旧结果去动作。
- const double now = now_seconds();
- if (now - last_heartbeat >= 0.5) {
- heartbeat = static_cast<uint16_t>(heartbeat + 1);
- last_heartbeat = now;
- }
- if (!slot.fresh(now, config.source.stale_frame_s) &&
- (now - last_timeout_publish) >= kTimeoutPublishS) {
- last_timeout_publish = now;
- const double fps_now = rate.fps();
- const bool reset_now = reset_publish_pending;
- reset_publish_pending = false;
- const portcv::PublishResult gate_result =
- gate.apply(portcv::Decision{}, true, reset_now);
- portcv::VisionSnapshot timeout_snap;
- timeout_snap.state = gate_result.state;
- timeout_snap.confidence = gate_result.confidence;
- timeout_snap.seq = last_seq;
- timeout_snap.ts_s = static_cast<uint32_t>(std::time(nullptr));
- timeout_snap.heartbeat = heartbeat;
- timeout_snap.fps_x10 = portcv::fps_to_x10(fps_now);
- timeout_snap.latency_ms = last_latency_ms;
- timeout_snap.set_flag(portcv::StatusBits::READY,
- frames >= static_cast<uint64_t>(config.warmup_frames));
- timeout_snap.set_flag(portcv::StatusBits::FRAME_OK, false);
- timeout_snap.set_flag(portcv::StatusBits::FRAME_TIMEOUT, true);
- timeout_snap.set_flag(portcv::StatusBits::STABLE, gate_result.stable);
- timeout_snap.set_flag(portcv::StatusBits::RESULT_VALID,
- gate_result.result_valid);
- timeout_snap.set_flag(portcv::StatusBits::LOW_FPS,
- portcv::low_fps_flag(fps_now, config.low_fps_threshold));
- timeout_snap.set_flag(portcv::StatusBits::PUBLISH_OK, true);
- timeout_snap.set_flag(portcv::StatusBits::DATA_LOSS, true);
- if (gate_result.perception_uncertain) {
- timeout_snap.set_flag(portcv::StatusBits::PERCEPTION_UNCERTAIN, true);
- timeout_snap.set_flag(portcv::StatusBits::MRC_REQUEST, true);
- }
- // P0-5:标定不可信 → bit11(断流快照也必须带,健康位与帧无关)。
- timeout_snap.set_flag(portcv::StatusBits::CALIB_STALE, calib.stale);
- if (calib.stale && calib.hold) {
- timeout_snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
- timeout_snap.set_flag(portcv::StatusBits::STABLE, false);
- }
- snapshot.store(timeout_snap);
- ++published;
- if (!timeout_latched) { // 从"有结果"跳到"断流"时打一行(不刷屏)
- timeout_latched = true;
- std::printf(
- "[warn] 超过 %.2fs 未收到新帧 → 保持 state=%u,清 RESULT_VALID/STABLE"
- "(FRAME_TIMEOUT);取流失败累计 %llu 次\n",
- config.source.stale_frame_s, gate_result.state,
- static_cast<unsigned long long>(capture_failures.load()));
- std::lock_guard<std::mutex> lock(capture_error_mu);
- if (!capture_last_error.empty()) {
- std::printf(" 最后一次取流错误:%s\n", capture_last_error.c_str());
- }
- std::fflush(stdout);
- }
- }
- std::this_thread::sleep_for(std::chrono::milliseconds(5));
- continue;
- }
- // 有新帧(或本就没配取流)→ 正常推理
- if (source) {
- frame.index = cap.index;
- frame.ts = cap.ts;
- frame.width = cap.gray.width;
- frame.height = cap.gray.height;
- frame.gray = &cap.gray;
- if (timeout_latched) {
- timeout_latched = false;
- std::printf("[run] 取流已恢复(帧 #%ld)\n", cap.index);
- std::fflush(stdout);
- }
- } else {
- frame.index += 1;
- frame.ts = loop_start;
- frame.gray = nullptr;
- }
- // 判决:edge 后端用"硬门槛 + 弃权 + 运动门控"的结论(composed 几何规则表达不了它);
- // mock 后端仍走几何关联规则(与 Python scene.py 同参数同行为)。
- portcv::Observation obs;
- if (edge_v2) {
- // P1b/P1c:动态 ROI + 箱底以下结构证据 + commit 门。
- if (frame.gray != nullptr) {
- edge_v2->analyze(*frame.gray, frame.ts);
- } else {
- const portcv::GrayImage empty;
- edge_v2->analyze(empty, frame.ts);
- }
- obs = edge_v2->last().to_observation(frame.ts, frame.index,
- config.evidence_v2.require_commit);
- } else if (edge) {
- edge->infer(frame); // 结论在 last_result() 里(含证据摘要)
- obs = edge->last_result().to_observation(frame.ts, frame.index);
- } else {
- const std::vector<portcv::Box> boxes = detector->infer(frame);
- obs = classifier.classify(boxes, frame.width, frame.height, frame.ts, frame.index);
- }
- const portcv::Decision decision = voter.update(obs);
- if (now_seconds() - last_heartbeat >= 0.5) { // 心跳:PLC 靠它判断视觉是否存活
- heartbeat = static_cast<uint16_t>(heartbeat + 1);
- last_heartbeat = now_seconds();
- }
- // 帧新鲜度(bit1/bit4):判据与 Python `build_snapshot` 的 `fresh` 同口径 ——
- // 拿不到新帧时 FRAME_OK=0 **且** FRAME_TIMEOUT=1,PLC 侧不应采信。
- const bool frame_fresh =
- source ? slot.fresh(now_seconds(), config.source.stale_frame_s) : true;
- const bool reset_now = reset_publish_pending;
- reset_publish_pending = false;
- // V2:内部 255/低分/未稳定/超时都不会写进结果区。
- const portcv::PublishResult gate_result =
- gate.apply(decision, !frame_fresh, reset_now);
- portcv::VisionSnapshot snap;
- snap.state = gate_result.state;
- snap.confidence = gate_result.confidence;
- snap.seq = decision.seq;
- snap.ts_s = static_cast<uint32_t>(std::time(nullptr));
- snap.heartbeat = heartbeat;
- // `fps_x10` 发**实测值**(不是 run.max_fps):板子跑不动时目标值会骗人,
- // PLC 侧据此判断"视觉是否跟得上"。首帧尚无测量值 → 0(= 未就绪,与 Python 侧同义)。
- rate.tick(loop_start);
- measured_fps = rate.fps();
- snap.fps_x10 = portcv::fps_to_x10(measured_fps);
- const double latency_ms = (now_seconds() - loop_start) * 1000.0;
- snap.latency_ms = static_cast<uint16_t>(latency_ms > 65535.0 ? 65535.0 : latency_ms);
- latency_window.add(latency_ms);
- snap.flags = 0;
- snap.set_flag(portcv::StatusBits::READY, frames >= static_cast<uint64_t>(config.warmup_frames));
- snap.set_flag(portcv::StatusBits::FRAME_OK, frame_fresh);
- snap.set_flag(portcv::StatusBits::FRAME_TIMEOUT, !frame_fresh);
- snap.set_flag(portcv::StatusBits::STABLE, gate_result.stable);
- // 低帧率位(bit3):判据与 Python `0.0 < fps < decision.low_fps_threshold` 逐字同义。
- // 边沿处打一行日志 —— 现场"帧率掉下来"要能在日志里一眼看到,而不是去解析 flags。
- const bool low_fps = portcv::low_fps_flag(measured_fps, config.low_fps_threshold);
- snap.set_flag(portcv::StatusBits::LOW_FPS, low_fps);
- if (low_fps != low_fps_latched) {
- low_fps_latched = low_fps;
- std::printf(low_fps ? "[warn] 实测帧率 %.2f fps < 下限 %.2f → flags.LOW_FPS=1(PLC 应拒绝采信)\n"
- : "[warn] 实测帧率 %.2f fps 已回到下限 %.2f 之上 → flags.LOW_FPS=0\n",
- measured_fps, config.low_fps_threshold);
- std::fflush(stdout);
- }
- snap.set_flag(portcv::StatusBits::RESULT_VALID, gate_result.result_valid);
- snap.set_flag(portcv::StatusBits::ON_DEMAND, loop_start < on_demand_until);
- snap.set_flag(portcv::StatusBits::PUBLISH_OK, true);
- if (!frame_fresh) {
- snap.set_flag(portcv::StatusBits::DATA_LOSS, true);
- }
- if (gate_result.perception_uncertain) {
- // P0-2 安全不变量:不确定时清 RESULT_VALID/STABLE,并请求 MRC。
- snap.set_flag(portcv::StatusBits::PERCEPTION_UNCERTAIN, true);
- snap.set_flag(portcv::StatusBits::MRC_REQUEST, true);
- snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
- snap.set_flag(portcv::StatusBits::STABLE, false);
- snap.confidence = 0;
- }
- // P0-5:标定不可信 → bit11;hold_on_stale=1 时再清 RESULT_VALID/STABLE。
- // 放在 PERCEPTION_UNCERTAIN **之后**:这里是最后改写这两位的代码,
- // 保证"标定过期"不会被上面的分支重新置回 1(顺序即不变量)。
- snap.set_flag(portcv::StatusBits::CALIB_STALE, calib.stale);
- if (calib.stale && calib.hold) {
- snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
- snap.set_flag(portcv::StatusBits::STABLE, false);
- }
- if (edge && config.publish_edge_flags) { // P0-2:bit8~12 已划给标准健康位
- const portcv::Evidence& ev = edge->last_result().ev;
- static bool warned_edges = false;
- if (!warned_edges) {
- warned_edges = true;
- std::printf("[warn] --publish-edge-flags 已停用:bit8~12 属于 "
- "PERCEPTION_UNCERTAIN/MRC/SENSOR/CALIB/DATA_LOSS;"
- "edge 诊断仅写入 reserved。\n");
- std::fflush(stdout);
- }
- snap.reserved = static_cast<uint16_t>(ev.diag);
- }
- snapshot.store(snap);
- ++published;
- last_seq = snap.seq;
- last_latency_ms = snap.latency_ms;
- // 黄金语料导出(B-lite):逐帧灰度图 + 逐项证据 + 结论 → 回放脚本可断言(scripts/replay_check.py)。
- // 只读旁路:写失败只告警一次(FrameDumper 内部已置 failed_),绝不影响判决与发布。
- if (dumper.enabled()) {
- portcv::DumpFrame dump_frame;
- dump_frame.index = frame.index;
- dump_frame.ts = frame.ts;
- dump_frame.gray = frame.gray;
- dump_frame.snap = &snap;
- // 本帧证据结论 vs 投票结论 vs 寄存器口径:`snap.state` 可能是 PublishGate 的保持值,
- // 导出必须把三者都给,否则回放断言会把"保持"误读成"弃权却不输出 255"。
- dump_frame.edge_state = obs.state;
- dump_frame.edge_conf = obs.confidence;
- dump_frame.vote_state = decision.state;
- if (edge_v2) {
- dump_frame.summary = edge_v2->last().evidence_summary();
- } else if (edge) {
- dump_frame.evidence = &edge->last_result().ev;
- dump_frame.summary = edge->last_result().evidence_summary();
- }
- dump_frame.reason = decision.reason;
- std::string dump_error;
- if (!dumper.write(dump_frame, &dump_error)) {
- std::printf("[warn] 导出失败(后续不再重试):%s\n", dump_error.c_str());
- std::fflush(stdout);
- }
- }
- if (decision.changed) {
- std::printf(
- "[%6llu] 内部状态变化 → state=%u(%s) 发布 state=%u flags=0x%04X "
- "seq=%u conf=%.2f reason=%s\n",
- static_cast<unsigned long long>(frames), decision.state, decision.label(),
- snap.state, snap.flags, decision.seq, decision.confidence,
- decision.reason.c_str());
- std::fflush(stdout);
- }
- latency_sum += latency_ms;
- if (latency_ms > max_latency) { max_latency = latency_ms; }
- ++frames;
- if (frames % 50 == 0) {
- const double elapsed = now_seconds() - window_start;
- if (elapsed > 0.0) {
- std::printf(
- "[stat] 已发布 %llu 帧,本轮 %.1f fps(滑窗 %.1f fps),单帧 全程均 %.2f / "
- "近 %llu 帧 p50 %.2f p95 %.2f p99 %.2f / 最大 %.2f ms",
- static_cast<unsigned long long>(published), 50.0 / elapsed, measured_fps,
- latency_sum / static_cast<double>(frames),
- static_cast<unsigned long long>(latency_window.size()),
- latency_window.quantile(0.50), latency_window.quantile(0.95),
- latency_window.quantile(0.99), max_latency);
- if (server) {
- std::printf(" 已响应 PLC 请求=%llu",
- static_cast<unsigned long long>(server->served_requests()));
- }
- std::printf("\n");
- if (edge) { // 现场整定用:逐项证据摘要(§9.3 的量化口径)
- std::printf("[edge] %s\n", edge->last_result().evidence_summary().c_str());
- }
- std::fflush(stdout);
- }
- window_start = now_seconds();
- }
- if (cli.max_frames > 0 && frames >= static_cast<uint64_t>(cli.max_frames)) {
- std::printf("[run] 已跑满 --max-frames=%ld,主动退出(台架验收用)\n", cli.max_frames);
- g_stop.store(true);
- }
- const double spent = now_seconds() - loop_start;
- if (spent < period) {
- std::this_thread::sleep_for(std::chrono::duration<double>(period - spent));
- }
- }
- // ---------------- 收尾 ----------------
- if (server) { server->stop(); }
- if (server_thread.joinable()) { server_thread.join(); }
- // 停取帧线程:先置停止标志再 join(`next()` 内部超时 ≤200 ms,不会久等),最后关源。
- g_stop.store(true);
- if (capture_thread.joinable()) { capture_thread.join(); }
- if (source) { source->close(); }
- const uint64_t captured = slot.version();
- const uint64_t dropped = captured > frames ? captured - frames : 0;
- if (dumper.enabled() || dumper.written() > 0) {
- dumper.close();
- std::printf("导出统计: %llu 帧已落盘(每 %d 帧一行;写失败=%s)\n",
- static_cast<unsigned long long>(dumper.written()), cli.dump_every,
- dumper.failed() ? dumper.last_error().c_str() : "无");
- }
- std::printf(
- "取流统计: 取到帧=%llu 已推理=%llu 丢帧(推理没跟上)=%llu 取流失败=%llu%s\n",
- static_cast<unsigned long long>(captured), static_cast<unsigned long long>(frames),
- static_cast<unsigned long long>(dropped),
- static_cast<unsigned long long>(capture_failures.load()),
- capture_last_error.empty() ? "" : "(最后一次错误见下方)");
- if (!capture_last_error.empty()) {
- std::printf(" 最后一次取流错误:%s\n", capture_last_error.c_str());
- }
- const std::vector<uint16_t> words = snapshot.load();
- const portcv::VisionSnapshot final_snap = portcv::VisionSnapshot::from_registers(words, true);
- std::printf("\n=== 退出统计 ===\n");
- std::printf("发布帧数=%llu 平均耗时=%.2f ms 最大=%.2f ms 已响应 PLC 请求=%llu\n",
- static_cast<unsigned long long>(published),
- frames ? latency_sum / static_cast<double>(frames) : 0.0, max_latency,
- static_cast<unsigned long long>(server ? server->served_requests() : 0));
- std::printf("单帧耗时: 全程均 %.2f ms 近 %llu 帧 p50=%.2f p95=%.2f p99=%.2f 最大=%.2f ms\n",
- frames ? latency_sum / static_cast<double>(frames) : 0.0,
- static_cast<unsigned long long>(latency_window.size()),
- latency_window.quantile(0.50), latency_window.quantile(0.95),
- latency_window.quantile(0.99), max_latency);
- std::printf("实测帧率: 滑窗 %.1f fps(%llu 个采样 / %.1f s 窗口) 发布 fps_x10=%u LOW_FPS 下限=%.1f\n",
- measured_fps, static_cast<unsigned long long>(rate.samples()), rate.window_s(),
- static_cast<unsigned>(portcv::fps_to_x10(measured_fps)),
- config.low_fps_threshold);
- // 验收口径(docs/technical_route.md §6.4):T2-T0 ≤ 1 s(P99),目标 P95 ≤ 300 ms。
- // 这里只把**实测帧率**折算成"帧数预算",不含取流 / 网络 / PLC 扫描周期 —— 它是打点前的自检,
- // 不是承诺值;现场仍按 §6.4 用双向日志对账。
- if (measured_fps > 0.0) {
- const double vote_s = static_cast<double>(config.voter.min_votes) / measured_fps;
- const double resync_s = 3.0 / measured_fps; // 运动后重同步固定 +3 帧(edge_evidence)
- std::printf(
- "[预算] 按实测 %.1f fps 折算:停稳→出结果 ≈ %d 帧(min_votes)=%.2f s + 驻留 %.2f s = %.2f s;\n"
- " 首次判断 / cmd=2 复位后(kUnknown 跳过驻留)≈ %d 帧=%.2f s;运动后重同步固定 +3 帧 ≈ +%.2f s。\n"
- " 跑 `--max-frames 200` 看上面的 p95/p99 与 flags.LOW_FPS,再对照 §6.4 判断是否达标。\n",
- measured_fps, config.voter.min_votes, vote_s, config.voter.min_dwell_s,
- vote_s + config.voter.min_dwell_s, config.voter.min_votes, vote_s, resync_s);
- } else {
- std::printf("[预算] 帧率样本不足 2 个,无法折算换向时延;把 --max-frames 调大(≥100)再跑。\n");
- }
- std::printf("最终快照: state=%u(%s) conf=%u seq=%u heartbeat=%u flags=0x%04X crc=0x%04X\n",
- final_snap.state, portcv::scene_state_label(final_snap.state), final_snap.confidence,
- final_snap.seq, final_snap.heartbeat, final_snap.flags, words.back());
- if (edge_v2) {
- std::printf("最终 v2 证据: %s\n", edge_v2->last().evidence_summary().c_str());
- } else if (edge) {
- std::printf("最终边缘证据: %s\n", edge->last_result().evidence_summary().c_str());
- }
- std::printf("状态提交次数:");
- for (const auto& kv : voter.commit_counts()) {
- std::printf(" %s=%d", kv.first.c_str(), kv.second);
- }
- std::printf("\n");
- return 0;
- }
|