main.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. // portcv(C++)可执行入口:取帧 → 检测 / 边缘证据 → 时序滤波 → Modbus/TCP 服务端。
  2. //
  3. // 线程模型(docs/technical_route.md §5.2):
  4. // * 线程 A 取流(`source.type != none` 时才起):相机 → 灰度帧 → 帧槽(**只留最新一帧**);
  5. // * 线程 B 本函数主循环:从帧槽取最新帧 → 推理/证据 → 时序滤波 → PublishGate → 写快照
  6. // (+ 可选导出黄金语料);没有新帧时按 `source.stale_frame_s` 置 `flags.FRAME_TIMEOUT`,
  7. // 并由 PublishGate 保持上一稳定值(无历史则 0)、清 RESULT_VALID/STABLE
  8. // (与 Python `portcv/service/runner.py` 同口径)—— 相机断了 PLC 看到的是"不可信",
  9. // 而不是旧结果,也不会在结果区看到 255;
  10. // * 线程 C Modbus/TCP Server:只读快照,**永不因推理/取帧慢而阻塞**。
  11. //
  12. // 两种后端(配置文件 `run.backend`,命令行 `--backend` 可覆盖):
  13. // * mock:脚本化检测框 → SceneClassifier(composed / direct 规则)→ TemporalVoter。
  14. // 无相机、无模型也能把"寄存器刷新 + 指令握手"整条链路联调通(现场先对寄存器);
  15. // * edge:EdgeEvidenceDetector(docs/edge_evidence.md 的二维边缘几何证据,**C++ 唯一实现**)
  16. // → 硬门槛 / 弃权 / 运动门控结论 → TemporalVoter。
  17. // 现场部署用的就是它:不需要 NPU、不需要 OpenCV、不需要模型权重。
  18. //
  19. // 参数一律来自配置文件(现场改配置**不重编译**),命令行只做覆盖:
  20. // portcv_run -c configs/edge-cpp.json --backend edge
  21. // portcv_run -c configs/edge-cpp.json --check-config # 只打印生效参数后退出
  22. //
  23. // 部署纪律(与 Python 版"二选一",见 docs/deployment.md §2.5):
  24. // 同一台机器**只跑一个运行时**。两个进程抢同一个端口时后启动的一方会 bind 失败,
  25. // 所以换运行时务必 `systemctl stop portcv` 之后再 `systemctl start portcv-cpp`。
  26. #include <atomic>
  27. #include <chrono>
  28. #include <csignal>
  29. #include <cstdint>
  30. #include <cstdio>
  31. #include <cstdlib>
  32. #include <ctime>
  33. #include <memory>
  34. #include <mutex>
  35. #include <string>
  36. #include <thread>
  37. #include <utility>
  38. #include <vector>
  39. #include "portcv/app_config.hpp"
  40. #include "portcv/calibration.hpp"
  41. #include "portcv/capture.hpp"
  42. #include "portcv/decision.hpp"
  43. #include "portcv/detector.hpp"
  44. #include "portcv/edge_evidence.hpp"
  45. #include "portcv/edge_v2.hpp"
  46. #include "portcv/frame_dump.hpp"
  47. #include "portcv/modbus_server.hpp"
  48. #include "portcv/publish_gate.hpp"
  49. #include "portcv/rate_stats.hpp"
  50. #include "portcv/registers.hpp"
  51. #include "portcv/scene.hpp"
  52. #include "portcv/schema.hpp"
  53. #include "portcv/snapshot.hpp"
  54. namespace {
  55. std::atomic<bool> g_stop{false};
  56. void on_signal(int) { g_stop.store(true); }
  57. double now_seconds() {
  58. using namespace std::chrono;
  59. return duration_cast<duration<double>>(steady_clock::now().time_since_epoch()).count();
  60. }
  61. /// 演示脚本(mock 后端):空画面 → 平车无箱 → 平车落箱 → 敞车(车斗)落箱。
  62. std::vector<std::vector<portcv::Box>> demo_script() {
  63. using portcv::make_box;
  64. std::vector<std::vector<portcv::Box>> script;
  65. script.push_back({}); // 0) 空画面
  66. script.push_back({make_box("flatbed", 650, 690, 1150, 900, 0.88f, 2)}); // 1) 只有平车
  67. script.push_back({ // 2) 平车 + 箱
  68. make_box("flatbed", 650, 690, 1150, 900, 0.85f, 2),
  69. make_box("container", 700, 400, 1100, 700, 0.91f, 0)});
  70. script.push_back({ // 3) 平车 + 箱(箱已落位)
  71. make_box("flatbed", 650, 690, 1150, 900, 0.87f, 2),
  72. make_box("container", 700, 402, 1100, 699, 0.93f, 0)});
  73. for (int i = 0; i < 6; ++i) { script.push_back(script.back()); }
  74. script.push_back({ // 4) 换成敞车(车斗)
  75. make_box("bed", 640, 660, 1160, 900, 0.90f, 1),
  76. make_box("container", 700, 380, 1100, 662, 0.92f, 0)});
  77. for (int i = 0; i < 8; ++i) { script.push_back(script.back()); }
  78. return script;
  79. }
  80. /// 命令行参数(只记录"给了什么",最终取值 = 配置文件 → 命令行覆盖)。
  81. struct Cli {
  82. std::string config_path; ///< -c / --config:现场配置文件
  83. bool check_config = false; ///< --check-config:打印生效参数后退出
  84. bool no_plc = false; ///< --no-plc:不启动 Modbus/TCP 服务端
  85. bool publish_edge_flags = false; ///< --publish-edge-flags(§10 需 PLC 签字)
  86. long max_frames = 0; ///< --max-frames:跑够 N 帧自动退出(0 = 不限)
  87. bool has_backend = false;
  88. std::string backend;
  89. bool has_edge_demo = false;
  90. std::string edge_demo;
  91. bool has_host = false;
  92. std::string host;
  93. bool has_port = false;
  94. int port = 0;
  95. bool has_unit = false;
  96. int unit = 0;
  97. bool has_input_addr = false;
  98. int input_addr = 0;
  99. bool has_holding_addr = false;
  100. int holding_addr = 0;
  101. bool has_fps = false;
  102. double fps = 0.0;
  103. bool has_mode = false;
  104. std::string mode;
  105. // ---- 取流(覆盖 source.*;用法见 print_usage)----
  106. bool has_source_uri = false;
  107. std::string source_uri; ///< --source-uri:相机地址 / 文件 / 管线字符串
  108. bool has_source_type = false;
  109. std::string source_type; ///< --source-type:强制指定取流类型(默认按 uri 推断)
  110. // ---- 黄金语料导出(B-lite:现场整定 + 自动回归用;不改判决)----
  111. bool has_dump_path = false;
  112. std::string dump_path; ///< --dump-frames:JSONL 输出路径
  113. bool has_dump_dir = false;
  114. std::string dump_dir; ///< --dump-dir:PGM 输出目录(缺省 = JSONL 同级的 frames/)
  115. bool has_dump_every = false;
  116. int dump_every = 1; ///< --dump-every:每 N 帧导出一帧
  117. };
  118. void print_usage(const char* argv0) {
  119. std::printf(
  120. "用法: %s [-c configs/site.json] [--backend mock|edge]\n"
  121. " [--edge-demo none|gondola|flatbed|ground] [--check-config] [--max-frames N]\n"
  122. " [--source-uri rtsp://…|/dev/video0|out.mp4|runs/frames(PGM 目录)"
  123. "|'…!appsink name=portcv_sink…']\n"
  124. " [--source-type none|synth|images|gst|rtsp|file|usb]\n"
  125. " [--dump-frames runs/dump.jsonl] [--dump-dir runs/dump] [--dump-every N]\n"
  126. " [--host 0.0.0.0] [--port 1502] [--unit 1] [--input-addr 0] "
  127. "[--holding-addr 0]\n"
  128. " [--fps 15] [--mode composed|direct] [--no-plc] [--publish-edge-flags(已停用)]\n"
  129. "\n"
  130. "参数优先级:命令行 > 配置文件 > 内置默认值(= 各结构体默认值)。\n"
  131. "配置文件键与 Python 侧同名同义(plc.modbus.* / scene.* / decision.* / edge.* / source.*),\n"
  132. "只写要覆盖的字段;键名或类型写错会**直接报错退出**,不会静默取默认值。\n"
  133. "真机取流:source.type=rtsp|file|usb|gst(需 -DPORTCV_WITH_GSTREAMER=ON 构建);\n"
  134. "没有相机时用 --edge-demo(= source.type=synth)先把寄存器与握手对完;\n"
  135. "现场片段(mp4)离线复盘:source.type=images(--source-uri 指 PGM 目录,零依赖):\n"
  136. " python scripts/extract_frames.py --clip 现场.mp4 --out runs/frames\n"
  137. " portcv_run -c configs/edge-cpp.json --source-type images --source-uri runs/frames "
  138. "--no-plc\n",
  139. argv0);
  140. }
  141. bool parse_args(int argc, char** argv, Cli* cli) {
  142. for (int i = 1; i < argc; ++i) {
  143. const std::string key = argv[i];
  144. const char* value = nullptr;
  145. auto need_value = [&]() -> bool {
  146. if (i + 1 >= argc) { return false; }
  147. value = argv[++i];
  148. return true;
  149. };
  150. if ((key == "-c" || key == "--config") && need_value()) {
  151. cli->config_path = value;
  152. } else if (key == "--backend" && need_value()) {
  153. cli->has_backend = true;
  154. cli->backend = value;
  155. } else if (key == "--edge-demo" && need_value()) {
  156. cli->has_edge_demo = true;
  157. cli->edge_demo = value;
  158. } else if (key == "--host" && need_value()) {
  159. cli->has_host = true;
  160. cli->host = value;
  161. } else if (key == "--port" && need_value()) {
  162. cli->has_port = true;
  163. cli->port = std::atoi(value);
  164. } else if (key == "--unit" && need_value()) {
  165. cli->has_unit = true;
  166. cli->unit = std::atoi(value);
  167. } else if (key == "--input-addr" && need_value()) {
  168. cli->has_input_addr = true;
  169. cli->input_addr = std::atoi(value);
  170. } else if (key == "--holding-addr" && need_value()) {
  171. cli->has_holding_addr = true;
  172. cli->holding_addr = std::atoi(value);
  173. } else if (key == "--fps" && need_value()) {
  174. cli->has_fps = true;
  175. cli->fps = std::atof(value);
  176. } else if (key == "--mode" && need_value()) {
  177. cli->has_mode = true;
  178. cli->mode = value;
  179. } else if (key == "--max-frames" && need_value()) {
  180. cli->max_frames = std::atol(value);
  181. } else if (key == "--source-uri" && need_value()) {
  182. cli->has_source_uri = true;
  183. cli->source_uri = value;
  184. } else if (key == "--source-type" && need_value()) {
  185. cli->has_source_type = true;
  186. cli->source_type = value;
  187. } else if (key == "--dump-frames" && need_value()) {
  188. cli->has_dump_path = true;
  189. cli->dump_path = value;
  190. } else if (key == "--dump-dir" && need_value()) {
  191. cli->has_dump_dir = true;
  192. cli->dump_dir = value;
  193. } else if (key == "--dump-every" && need_value()) {
  194. cli->has_dump_every = true;
  195. cli->dump_every = std::atoi(value);
  196. } else if (key == "--check-config") {
  197. cli->check_config = true;
  198. } else if (key == "--no-plc") {
  199. cli->no_plc = true;
  200. } else if (key == "--publish-edge-flags") {
  201. cli->publish_edge_flags = true;
  202. } else if (key == "--help" || key == "-h") {
  203. print_usage(argv[0]);
  204. return false;
  205. } else {
  206. std::printf("未知参数: %s\n", key.c_str());
  207. print_usage(argv[0]);
  208. return false;
  209. }
  210. }
  211. return true;
  212. }
  213. /// 命令行覆盖配置文件(**只覆盖显式给出的项**),并做与配置文件同口径的范围检查。
  214. bool apply_cli(const Cli& cli, portcv::AppConfig* cfg, std::string* error) {
  215. const auto bad = [error](const std::string& what) {
  216. if (error != nullptr) { *error = what; }
  217. return false;
  218. };
  219. if (cli.has_host) { cfg->modbus.host = cli.host; }
  220. if (cli.has_port) {
  221. if (cli.port < 0 || cli.port > 65535) { return bad("--port 超出 0~65535"); }
  222. cfg->modbus.port = static_cast<uint16_t>(cli.port);
  223. }
  224. if (cli.has_unit) {
  225. if (cli.unit < 0 || cli.unit > 255) { return bad("--unit 超出 0~255"); }
  226. cfg->modbus.unit_id = static_cast<uint8_t>(cli.unit);
  227. }
  228. if (cli.has_input_addr) {
  229. if (cli.input_addr < 0 || cli.input_addr > 65535) { return bad("--input-addr 超出 0~65535"); }
  230. cfg->modbus.input_addr = static_cast<uint16_t>(cli.input_addr);
  231. }
  232. if (cli.has_holding_addr) {
  233. if (cli.holding_addr < 0 || cli.holding_addr > 65535) {
  234. return bad("--holding-addr 超出 0~65535");
  235. }
  236. cfg->modbus.holding_addr = static_cast<uint16_t>(cli.holding_addr);
  237. }
  238. if (cli.has_fps) {
  239. // 判据写成 `!(x > 0)` 而不是 `x <= 0`:NaN 与任何数比较都是 false,
  240. // 用后者会让 `--fps nan` 一路穿过校验,主循环 period=1/NaN → 全速空转
  241. // (fuzz 用例 fps_nan,见 docs/stability_soak.md §3.2)。
  242. if (!(cli.fps > 0.0) || cli.fps > 240.0) { return bad("--fps 必须 ∈ (0, 240]"); }
  243. cfg->max_fps = cli.fps;
  244. }
  245. if (cli.has_mode) {
  246. if (cli.mode != "composed" && cli.mode != "direct") {
  247. return bad("--mode 只能是 composed / direct");
  248. }
  249. cfg->scene.mode = cli.mode;
  250. }
  251. if (cli.has_backend) { cfg->backend = cli.backend; }
  252. // 取流:`--source-uri` 决定了类型(rtsp:// → rtsp,/dev/video* → usb,含 '!' → gst 管线,
  253. // 其余 → file),除非 `--source-type` 明确指定;`--source-type` 永远最后赢。
  254. if (cli.has_source_uri) {
  255. cfg->source.uri = cli.source_uri;
  256. if (!cli.has_source_type) {
  257. cfg->source.type = portcv::source_type_from_uri(cli.source_uri);
  258. }
  259. }
  260. if (cli.has_source_type) { cfg->source.type = cli.source_type; }
  261. if (cli.has_edge_demo) {
  262. cfg->edge_demo = cli.edge_demo;
  263. // 台架开关:切到合成帧源(**覆盖** source.*)——"没有相机也能把整条链路验完"。
  264. if (cli.edge_demo != "none") {
  265. cfg->source.type = "synth";
  266. cfg->source.uri = cli.edge_demo;
  267. }
  268. }
  269. if (cli.has_dump_every && cli.dump_every < 1) { return bad("--dump-every 至少 1"); }
  270. if (cli.no_plc) { cfg->plc_enabled = false; }
  271. if (cli.publish_edge_flags) { cfg->publish_edge_flags = true; }
  272. if (cli.max_frames < 0) { return bad("--max-frames 不能为负"); }
  273. if (error != nullptr) { error->clear(); }
  274. return true;
  275. }
  276. /// `--dump-dir` 缺省:JSONL 同级的 frames/(JSONL 没有目录 → ./frames)。
  277. std::string default_dump_dir(const std::string& jsonl_path) {
  278. const std::size_t pos = jsonl_path.find_last_of("/\\");
  279. if (pos == std::string::npos) { return "frames"; }
  280. return jsonl_path.substr(0, pos + 1) + "frames";
  281. }
  282. } // namespace
  283. int main(int argc, char** argv) {
  284. Cli cli;
  285. if (!parse_args(argc, argv, &cli)) { return 2; }
  286. std::string error;
  287. portcv::AppConfig config;
  288. if (!portcv::load_app_config(cli.config_path, &config, &error)) {
  289. std::printf("配置加载失败: %s\n", error.c_str());
  290. return 4;
  291. }
  292. if (!apply_cli(cli, &config, &error)) {
  293. std::printf("命令行参数不对: %s\n", error.c_str());
  294. return 2;
  295. }
  296. if (!portcv::check_backend(config, &error)) {
  297. std::printf("后端不可用: %s\n", error.c_str());
  298. return 3;
  299. }
  300. std::printf("portcv(C++) 配置文件: %s\n",
  301. cli.config_path.empty() ? "(未指定,全部用内置默认值)" : cli.config_path.c_str());
  302. std::printf("%s", portcv::describe_app_config(config).c_str());
  303. // P0-5:标定记录在启动时**判定一次**(与 Python `RunService.start()` 同口径)。
  304. // 结果写进 flags bit11 `CALIB_STALE`;是否需要"清 RESULT_VALID/STABLE"由
  305. // calibration.hold_on_stale 决定(默认 true —— 标定不可信就不给可执行结果)。
  306. const portcv::CalibrationStatus calib =
  307. portcv::evaluate_calibration(config.calibration, config.evidence_v2.px_per_m,
  308. config.evidence_v2.box_height_m, portcv::epoch_now());
  309. std::printf("%s", portcv::calibration_status_line(calib).c_str());
  310. if (calib.stale) {
  311. std::printf("[warn] 标定不可用(CALIB_STALE:%s)→ flags bit11=1%s\n",
  312. calib.reasons_text().c_str(),
  313. calib.hold ? ";并清 RESULT_VALID/STABLE(calibration.hold_on_stale=1,PLC 不得据此自动动作)"
  314. : ";仅告警(calibration.hold_on_stale=0,是否继续自动运行由 PLC 联锁决定)");
  315. std::printf(" 处理:现场重标 → 第二人复核 → 重新封存记录(scripts/calib_record.py create)\n");
  316. std::fflush(stdout);
  317. }
  318. std::fflush(stdout);
  319. if (cli.check_config) {
  320. std::printf("--check-config:参数有效;未启动服务、未取帧。\n");
  321. return 0;
  322. }
  323. if (config.publish_edge_flags) {
  324. std::printf(
  325. "警告:--publish-edge-flags 已停用(bit8~12 为 PERCEPTION_UNCERTAIN/MRC/"
  326. "SENSOR/CALIB/DATA_LOSS);\n"
  327. " edge 诊断只写入 word10(reserved),不会覆盖标准 flags。\n");
  328. }
  329. std::signal(SIGINT, on_signal);
  330. std::signal(SIGTERM, on_signal);
  331. // ---------------- 组件装配 ----------------
  332. portcv::LatestSnapshot snapshot;
  333. portcv::CommandSlot commands;
  334. portcv::SceneClassifier classifier(config.scene);
  335. portcv::TemporalVoter voter(config.voter);
  336. // V2:PLC 结果区只写 0/1/2;内部 255/低分/未稳定/超时在这里被保持。
  337. portcv::PublishGate gate(config.voter.min_confidence);
  338. // cmd=2 由 Modbus 线程置位、主循环消费:PublishGate 非线程安全,不能跨线程调用。
  339. std::atomic<bool> reset_pending{false};
  340. std::unique_ptr<portcv::MockDetector> mock;
  341. std::unique_ptr<portcv::EdgeEvidenceDetector> edge;
  342. std::unique_ptr<portcv::EdgeV2> edge_v2;
  343. if (config.backend == "edge") {
  344. edge.reset(new portcv::EdgeEvidenceDetector(config.edge, config.line));
  345. } else if (config.backend == "edge-v2" || config.backend == "evidence-v2") {
  346. edge_v2.reset(new portcv::EdgeV2(config.evidence_v2, config.evidence_commit));
  347. } else {
  348. mock.reset(new portcv::MockDetector(demo_script()));
  349. }
  350. portcv::Detector* detector = nullptr;
  351. if (edge) {
  352. detector = edge.get();
  353. } else {
  354. // edge-v2 自带逐帧判定;mock 只用于满足 Detector 接口的 warmup/名称打印。
  355. if (!mock) { mock.reset(new portcv::MockDetector(demo_script())); }
  356. detector = mock.get();
  357. }
  358. if (!detector->warmup(&error)) {
  359. std::printf("后端预热失败: %s\n", error.c_str());
  360. return 5;
  361. }
  362. // ---------------- 取流(线程 A:相机 → 灰度帧 → 帧槽)----------------
  363. // 配置 `source.*`(键名与 Python 同名同义)+ 命令行覆盖(--source-uri / --edge-demo)。
  364. // `source.type=none` → 不起线程,主循环保持旧行为(Frame.gray = nullptr,证据后端输出 255)。
  365. std::unique_ptr<portcv::FrameSource> source;
  366. portcv::FrameSlot slot;
  367. std::thread capture_thread;
  368. std::atomic<uint64_t> capture_failures{0};
  369. std::mutex capture_error_mu;
  370. std::string capture_last_error;
  371. if (!portcv::make_frame_source(config.source, &source, &error)) {
  372. std::printf("取流不可用: %s\n", error.c_str());
  373. return 6;
  374. }
  375. if (source) {
  376. std::printf("取流 : %s —— %s\n", source->name().c_str(), source->describe().c_str());
  377. } else if (edge || edge_v2) {
  378. std::printf(
  379. "[edge] 未配置取流(source.type=none):Frame.gray = nullptr → 证据后端输出 255"
  380. "(安全值,绝不误报 2);\n"
  381. " 台架用 `--edge-demo gondola|flatbed|ground`(合成帧),"
  382. "真机用 `--source-uri rtsp://…`。\n");
  383. }
  384. std::fflush(stdout);
  385. // ---------------- 黄金语料导出(B-lite;只读旁路,写失败只告警不影响判决)----------------
  386. portcv::FrameDumper dumper;
  387. if (cli.has_dump_path) {
  388. portcv::DumpConfig dump_cfg;
  389. dump_cfg.jsonl_path = cli.dump_path;
  390. dump_cfg.image_dir = cli.has_dump_dir ? cli.dump_dir : default_dump_dir(cli.dump_path);
  391. dump_cfg.every = cli.dump_every;
  392. if (!dumper.open(dump_cfg, &error)) {
  393. std::printf("导出初始化失败: %s\n", error.c_str());
  394. return 7;
  395. }
  396. std::printf(
  397. "导出 : %s(每 %d 帧一行 JSON;像素目录 %s)\n"
  398. " 回放断言:python scripts/replay_check.py %s [--baseline <基线.jsonl>]\n",
  399. dump_cfg.jsonl_path.c_str(), dump_cfg.every,
  400. dump_cfg.image_dir.empty() ? "(不存图)" : dump_cfg.image_dir.c_str(),
  401. dump_cfg.jsonl_path.c_str());
  402. std::fflush(stdout);
  403. }
  404. std::unique_ptr<portcv::ModbusServer> server;
  405. std::thread server_thread;
  406. if (config.plc_enabled) {
  407. server.reset(new portcv::ModbusServer(config.modbus, &snapshot));
  408. server->set_command_handler([&](const portcv::PlcCommand& command) {
  409. commands.set(command);
  410. std::printf("[plc] cmd=%u(%s) preset=%u min_conf=%u\n", command.cmd,
  411. portcv::cmd_label(command.cmd), command.preset, command.min_conf);
  412. std::fflush(stdout);
  413. // 不在服务线程里改状态:主循环用 commands.take() 消费并按 cmd 处理。
  414. });
  415. if (!server->start(&error)) {
  416. std::printf("Modbus/TCP 启动失败: %s\n", error.c_str());
  417. std::printf(
  418. "提示(部署纪律):同一台机器只跑一个运行时 —— 先 `systemctl stop portcv`"
  419. "(Python 版)再启动本程序;或临时用 `--no-plc` 只跑推理。\n");
  420. return 1;
  421. }
  422. std::printf("portcv(C++) detector=%s\n", detector->name().c_str());
  423. std::printf("Modbus/TCP 监听 %s\n",
  424. portcv::layout_summary(config.modbus.host, server->bound_port(),
  425. config.modbus.unit_id, config.modbus.input_addr,
  426. config.modbus.holding_addr)
  427. .c_str());
  428. std::printf("输入寄存器表(PLC 用 FC4 按地址读):\n");
  429. for (const portcv::LayoutRow& row : portcv::snapshot_rows(config.modbus.input_addr)) {
  430. std::printf(" %5u %-12s %s\n", row.address, row.field.c_str(), row.note.c_str());
  431. }
  432. std::fflush(stdout);
  433. server_thread = std::thread([&server]() { server->serve_forever(); });
  434. } else {
  435. std::printf("portcv(C++) detector=%s\n", detector->name().c_str());
  436. std::printf("[plc] 未启动 Modbus/TCP 服务端(plc.enabled=false 或 --no-plc):只推理 + 打日志\n");
  437. std::fflush(stdout);
  438. }
  439. // 先发布一张"未就绪"快照:V2 结果区只写 0/1/2(flags 0/0 = 未知/保持),
  440. // PLC 立刻就能读到合法数据,而不是 V1 的 255。
  441. {
  442. portcv::VisionSnapshot boot;
  443. boot.state = static_cast<uint16_t>(portcv::SceneState::NOT_ON_TRAIN);
  444. boot.confidence = 0;
  445. boot.flags = 0;
  446. snapshot.store(boot);
  447. }
  448. // ---------------- 取帧线程(线程 A)----------------
  449. // 为什么单独一线程:取帧/解码/重连是**阻塞**的(RTSP 抖动、U 盘式相机掉线都要等)。
  450. // 放在主循环里会让"没有画面"的那段时间连心跳和 FRAME_TIMEOUT 都发不出去。
  451. // 帧槽只留最新一帧 → 推理慢于取流时丢旧帧,而不是排队累积延迟。
  452. if (source) {
  453. capture_thread = std::thread([&]() {
  454. std::string next_error;
  455. uint64_t consecutive = 0;
  456. while (!g_stop.load()) {
  457. if (slot.has_new()) { // 消费者还没取走上一帧:先别取(省 CPU,也让帧更新)
  458. std::this_thread::sleep_for(std::chrono::milliseconds(2));
  459. continue;
  460. }
  461. portcv::CapturedFrame cap;
  462. if (!source->next(&cap, &next_error)) {
  463. ++consecutive;
  464. capture_failures.fetch_add(1);
  465. {
  466. std::lock_guard<std::mutex> lock(capture_error_mu);
  467. capture_last_error = next_error;
  468. }
  469. // 前 1 次 + 之后每 100 次打一行:现场日志要能看出"相机在反复掉线",
  470. // 又不至于把 journal 刷爆。
  471. if (consecutive == 1 || consecutive % 100 == 0) {
  472. std::printf("[warn] 取流失败(连续第 %llu 次):%s\n",
  473. static_cast<unsigned long long>(consecutive),
  474. next_error.c_str());
  475. std::fflush(stdout);
  476. }
  477. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  478. continue;
  479. }
  480. consecutive = 0;
  481. slot.publish(std::move(cap));
  482. }
  483. });
  484. std::printf("取帧线程已启动(线程 A);帧槽只保留最新一帧,取流失败按 "
  485. "source.reconnect_s=%.1fs 重连\n",
  486. config.source.reconnect_s);
  487. std::fflush(stdout);
  488. }
  489. // ---------------- 主循环:持续推理 + 持续发布 ----------------
  490. const double period = 1.0 / config.max_fps;
  491. // 断流时"隔多久重发一次超时快照"(与 Python `_publish_timeout_if_needed` 的 heartbeat_s 同量级)。
  492. const double kTimeoutPublishS = 0.5;
  493. portcv::Frame frame;
  494. uint16_t heartbeat = 0;
  495. double last_heartbeat = now_seconds();
  496. uint64_t frames = 0;
  497. uint64_t published = 0;
  498. double window_start = now_seconds();
  499. double latency_sum = 0.0;
  500. double max_latency = 0.0;
  501. // 断流兜底发布用的"上一拍"值(断流时没有新判决,沿用最近的 seq / 耗时)。
  502. uint32_t last_seq = 0;
  503. uint16_t last_latency_ms = 0;
  504. double last_timeout_publish = 0.0;
  505. bool timeout_latched = false;
  506. // cmd=2 后的下一个快照必须是 0 + flags 0/0(清 last stable),之后才允许重新建立。
  507. bool reset_publish_pending = false;
  508. double on_demand_until = 0.0;
  509. // 运行期观测(见 include/portcv/rate_stats.hpp):
  510. // * `measured_fps` = 最近 2 s 主循环真实节拍 → 填寄存器 `fps_x10` 并判 `flags.LOW_FPS`;
  511. // * `latency_window` = 最近 256 帧的单帧耗时分布 → 日志里的 p50/p95/p99(§6.4 验收看 P95/P99)。
  512. portcv::RateMeter rate(2.0);
  513. portcv::LatencyStats latency_window(256);
  514. double measured_fps = 0.0;
  515. bool low_fps_latched = false;
  516. while (!g_stop.load() && (!server || !server->stopped())) {
  517. const double loop_start = now_seconds();
  518. // PLC 指令在主线程消费(`take()` 读后清零 = 一次握手)。
  519. const portcv::PlcCommand command = commands.take();
  520. if (command.cmd == portcv::CMD_REQUEST) {
  521. on_demand_until = loop_start + config.gating_timeout_s;
  522. } else if (command.cmd == portcv::CMD_RESET) {
  523. reset_pending.store(true);
  524. } else if (command.cmd == portcv::CMD_CLEAR_STATS) {
  525. std::printf("[plc] 收到清统计命令(C++ 侧只清本轮显示计数,累计计数保留)\n");
  526. std::fflush(stdout);
  527. }
  528. if (command.min_conf > 0) {
  529. gate.set_min_conf(static_cast<double>(command.min_conf) / 1000.0);
  530. }
  531. // PLC 复位在**主线程**消费:TemporalVoter / PublishGate 都不是线程安全的。
  532. if (reset_pending.exchange(false)) {
  533. voter.reset();
  534. gate.reset();
  535. reset_publish_pending = true;
  536. timeout_latched = false;
  537. std::printf("[plc] 收到复位命令 → 时序滤波与 PublishGate 已清零\n");
  538. std::fflush(stdout);
  539. }
  540. // 取帧:① 配了取流源 → 从帧槽取最新一帧(线程 A 在填);
  541. // ② 没配(source.type=none)→ 旧行为:Frame.gray = nullptr,每拍都"有新帧"。
  542. portcv::CapturedFrame cap;
  543. if (source && !slot.take(&cap)) {
  544. // 没有新帧:心跳照走,并按 source.stale_frame_s 处置
  545. //(与 Python `runner.py::_publish_timeout_if_needed` 同口径):
  546. // 相机/网络断了必须让 PLC 看到"不可信",而不是继续拿旧结果去动作。
  547. const double now = now_seconds();
  548. if (now - last_heartbeat >= 0.5) {
  549. heartbeat = static_cast<uint16_t>(heartbeat + 1);
  550. last_heartbeat = now;
  551. }
  552. if (!slot.fresh(now, config.source.stale_frame_s) &&
  553. (now - last_timeout_publish) >= kTimeoutPublishS) {
  554. last_timeout_publish = now;
  555. const double fps_now = rate.fps();
  556. const bool reset_now = reset_publish_pending;
  557. reset_publish_pending = false;
  558. const portcv::PublishResult gate_result =
  559. gate.apply(portcv::Decision{}, true, reset_now);
  560. portcv::VisionSnapshot timeout_snap;
  561. timeout_snap.state = gate_result.state;
  562. timeout_snap.confidence = gate_result.confidence;
  563. timeout_snap.seq = last_seq;
  564. timeout_snap.ts_s = static_cast<uint32_t>(std::time(nullptr));
  565. timeout_snap.heartbeat = heartbeat;
  566. timeout_snap.fps_x10 = portcv::fps_to_x10(fps_now);
  567. timeout_snap.latency_ms = last_latency_ms;
  568. timeout_snap.set_flag(portcv::StatusBits::READY,
  569. frames >= static_cast<uint64_t>(config.warmup_frames));
  570. timeout_snap.set_flag(portcv::StatusBits::FRAME_OK, false);
  571. timeout_snap.set_flag(portcv::StatusBits::FRAME_TIMEOUT, true);
  572. timeout_snap.set_flag(portcv::StatusBits::STABLE, gate_result.stable);
  573. timeout_snap.set_flag(portcv::StatusBits::RESULT_VALID,
  574. gate_result.result_valid);
  575. timeout_snap.set_flag(portcv::StatusBits::LOW_FPS,
  576. portcv::low_fps_flag(fps_now, config.low_fps_threshold));
  577. timeout_snap.set_flag(portcv::StatusBits::PUBLISH_OK, true);
  578. timeout_snap.set_flag(portcv::StatusBits::DATA_LOSS, true);
  579. if (gate_result.perception_uncertain) {
  580. timeout_snap.set_flag(portcv::StatusBits::PERCEPTION_UNCERTAIN, true);
  581. timeout_snap.set_flag(portcv::StatusBits::MRC_REQUEST, true);
  582. }
  583. // P0-5:标定不可信 → bit11(断流快照也必须带,健康位与帧无关)。
  584. timeout_snap.set_flag(portcv::StatusBits::CALIB_STALE, calib.stale);
  585. if (calib.stale && calib.hold) {
  586. timeout_snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
  587. timeout_snap.set_flag(portcv::StatusBits::STABLE, false);
  588. }
  589. snapshot.store(timeout_snap);
  590. ++published;
  591. if (!timeout_latched) { // 从"有结果"跳到"断流"时打一行(不刷屏)
  592. timeout_latched = true;
  593. std::printf(
  594. "[warn] 超过 %.2fs 未收到新帧 → 保持 state=%u,清 RESULT_VALID/STABLE"
  595. "(FRAME_TIMEOUT);取流失败累计 %llu 次\n",
  596. config.source.stale_frame_s, gate_result.state,
  597. static_cast<unsigned long long>(capture_failures.load()));
  598. std::lock_guard<std::mutex> lock(capture_error_mu);
  599. if (!capture_last_error.empty()) {
  600. std::printf(" 最后一次取流错误:%s\n", capture_last_error.c_str());
  601. }
  602. std::fflush(stdout);
  603. }
  604. }
  605. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  606. continue;
  607. }
  608. // 有新帧(或本就没配取流)→ 正常推理
  609. if (source) {
  610. frame.index = cap.index;
  611. frame.ts = cap.ts;
  612. frame.width = cap.gray.width;
  613. frame.height = cap.gray.height;
  614. frame.gray = &cap.gray;
  615. if (timeout_latched) {
  616. timeout_latched = false;
  617. std::printf("[run] 取流已恢复(帧 #%ld)\n", cap.index);
  618. std::fflush(stdout);
  619. }
  620. } else {
  621. frame.index += 1;
  622. frame.ts = loop_start;
  623. frame.gray = nullptr;
  624. }
  625. // 判决:edge 后端用"硬门槛 + 弃权 + 运动门控"的结论(composed 几何规则表达不了它);
  626. // mock 后端仍走几何关联规则(与 Python scene.py 同参数同行为)。
  627. portcv::Observation obs;
  628. if (edge_v2) {
  629. // P1b/P1c:动态 ROI + 箱底以下结构证据 + commit 门。
  630. if (frame.gray != nullptr) {
  631. edge_v2->analyze(*frame.gray, frame.ts);
  632. } else {
  633. const portcv::GrayImage empty;
  634. edge_v2->analyze(empty, frame.ts);
  635. }
  636. obs = edge_v2->last().to_observation(frame.ts, frame.index,
  637. config.evidence_v2.require_commit);
  638. } else if (edge) {
  639. edge->infer(frame); // 结论在 last_result() 里(含证据摘要)
  640. obs = edge->last_result().to_observation(frame.ts, frame.index);
  641. } else {
  642. const std::vector<portcv::Box> boxes = detector->infer(frame);
  643. obs = classifier.classify(boxes, frame.width, frame.height, frame.ts, frame.index);
  644. }
  645. const portcv::Decision decision = voter.update(obs);
  646. if (now_seconds() - last_heartbeat >= 0.5) { // 心跳:PLC 靠它判断视觉是否存活
  647. heartbeat = static_cast<uint16_t>(heartbeat + 1);
  648. last_heartbeat = now_seconds();
  649. }
  650. // 帧新鲜度(bit1/bit4):判据与 Python `build_snapshot` 的 `fresh` 同口径 ——
  651. // 拿不到新帧时 FRAME_OK=0 **且** FRAME_TIMEOUT=1,PLC 侧不应采信。
  652. const bool frame_fresh =
  653. source ? slot.fresh(now_seconds(), config.source.stale_frame_s) : true;
  654. const bool reset_now = reset_publish_pending;
  655. reset_publish_pending = false;
  656. // V2:内部 255/低分/未稳定/超时都不会写进结果区。
  657. const portcv::PublishResult gate_result =
  658. gate.apply(decision, !frame_fresh, reset_now);
  659. portcv::VisionSnapshot snap;
  660. snap.state = gate_result.state;
  661. snap.confidence = gate_result.confidence;
  662. snap.seq = decision.seq;
  663. snap.ts_s = static_cast<uint32_t>(std::time(nullptr));
  664. snap.heartbeat = heartbeat;
  665. // `fps_x10` 发**实测值**(不是 run.max_fps):板子跑不动时目标值会骗人,
  666. // PLC 侧据此判断"视觉是否跟得上"。首帧尚无测量值 → 0(= 未就绪,与 Python 侧同义)。
  667. rate.tick(loop_start);
  668. measured_fps = rate.fps();
  669. snap.fps_x10 = portcv::fps_to_x10(measured_fps);
  670. const double latency_ms = (now_seconds() - loop_start) * 1000.0;
  671. snap.latency_ms = static_cast<uint16_t>(latency_ms > 65535.0 ? 65535.0 : latency_ms);
  672. latency_window.add(latency_ms);
  673. snap.flags = 0;
  674. snap.set_flag(portcv::StatusBits::READY, frames >= static_cast<uint64_t>(config.warmup_frames));
  675. snap.set_flag(portcv::StatusBits::FRAME_OK, frame_fresh);
  676. snap.set_flag(portcv::StatusBits::FRAME_TIMEOUT, !frame_fresh);
  677. snap.set_flag(portcv::StatusBits::STABLE, gate_result.stable);
  678. // 低帧率位(bit3):判据与 Python `0.0 < fps < decision.low_fps_threshold` 逐字同义。
  679. // 边沿处打一行日志 —— 现场"帧率掉下来"要能在日志里一眼看到,而不是去解析 flags。
  680. const bool low_fps = portcv::low_fps_flag(measured_fps, config.low_fps_threshold);
  681. snap.set_flag(portcv::StatusBits::LOW_FPS, low_fps);
  682. if (low_fps != low_fps_latched) {
  683. low_fps_latched = low_fps;
  684. std::printf(low_fps ? "[warn] 实测帧率 %.2f fps < 下限 %.2f → flags.LOW_FPS=1(PLC 应拒绝采信)\n"
  685. : "[warn] 实测帧率 %.2f fps 已回到下限 %.2f 之上 → flags.LOW_FPS=0\n",
  686. measured_fps, config.low_fps_threshold);
  687. std::fflush(stdout);
  688. }
  689. snap.set_flag(portcv::StatusBits::RESULT_VALID, gate_result.result_valid);
  690. snap.set_flag(portcv::StatusBits::ON_DEMAND, loop_start < on_demand_until);
  691. snap.set_flag(portcv::StatusBits::PUBLISH_OK, true);
  692. if (!frame_fresh) {
  693. snap.set_flag(portcv::StatusBits::DATA_LOSS, true);
  694. }
  695. if (gate_result.perception_uncertain) {
  696. // P0-2 安全不变量:不确定时清 RESULT_VALID/STABLE,并请求 MRC。
  697. snap.set_flag(portcv::StatusBits::PERCEPTION_UNCERTAIN, true);
  698. snap.set_flag(portcv::StatusBits::MRC_REQUEST, true);
  699. snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
  700. snap.set_flag(portcv::StatusBits::STABLE, false);
  701. snap.confidence = 0;
  702. }
  703. // P0-5:标定不可信 → bit11;hold_on_stale=1 时再清 RESULT_VALID/STABLE。
  704. // 放在 PERCEPTION_UNCERTAIN **之后**:这里是最后改写这两位的代码,
  705. // 保证"标定过期"不会被上面的分支重新置回 1(顺序即不变量)。
  706. snap.set_flag(portcv::StatusBits::CALIB_STALE, calib.stale);
  707. if (calib.stale && calib.hold) {
  708. snap.set_flag(portcv::StatusBits::RESULT_VALID, false);
  709. snap.set_flag(portcv::StatusBits::STABLE, false);
  710. }
  711. if (edge && config.publish_edge_flags) { // P0-2:bit8~12 已划给标准健康位
  712. const portcv::Evidence& ev = edge->last_result().ev;
  713. static bool warned_edges = false;
  714. if (!warned_edges) {
  715. warned_edges = true;
  716. std::printf("[warn] --publish-edge-flags 已停用:bit8~12 属于 "
  717. "PERCEPTION_UNCERTAIN/MRC/SENSOR/CALIB/DATA_LOSS;"
  718. "edge 诊断仅写入 reserved。\n");
  719. std::fflush(stdout);
  720. }
  721. snap.reserved = static_cast<uint16_t>(ev.diag);
  722. }
  723. snapshot.store(snap);
  724. ++published;
  725. last_seq = snap.seq;
  726. last_latency_ms = snap.latency_ms;
  727. // 黄金语料导出(B-lite):逐帧灰度图 + 逐项证据 + 结论 → 回放脚本可断言(scripts/replay_check.py)。
  728. // 只读旁路:写失败只告警一次(FrameDumper 内部已置 failed_),绝不影响判决与发布。
  729. if (dumper.enabled()) {
  730. portcv::DumpFrame dump_frame;
  731. dump_frame.index = frame.index;
  732. dump_frame.ts = frame.ts;
  733. dump_frame.gray = frame.gray;
  734. dump_frame.snap = &snap;
  735. // 本帧证据结论 vs 投票结论 vs 寄存器口径:`snap.state` 可能是 PublishGate 的保持值,
  736. // 导出必须把三者都给,否则回放断言会把"保持"误读成"弃权却不输出 255"。
  737. dump_frame.edge_state = obs.state;
  738. dump_frame.edge_conf = obs.confidence;
  739. dump_frame.vote_state = decision.state;
  740. if (edge_v2) {
  741. dump_frame.summary = edge_v2->last().evidence_summary();
  742. } else if (edge) {
  743. dump_frame.evidence = &edge->last_result().ev;
  744. dump_frame.summary = edge->last_result().evidence_summary();
  745. }
  746. dump_frame.reason = decision.reason;
  747. std::string dump_error;
  748. if (!dumper.write(dump_frame, &dump_error)) {
  749. std::printf("[warn] 导出失败(后续不再重试):%s\n", dump_error.c_str());
  750. std::fflush(stdout);
  751. }
  752. }
  753. if (decision.changed) {
  754. std::printf(
  755. "[%6llu] 内部状态变化 → state=%u(%s) 发布 state=%u flags=0x%04X "
  756. "seq=%u conf=%.2f reason=%s\n",
  757. static_cast<unsigned long long>(frames), decision.state, decision.label(),
  758. snap.state, snap.flags, decision.seq, decision.confidence,
  759. decision.reason.c_str());
  760. std::fflush(stdout);
  761. }
  762. latency_sum += latency_ms;
  763. if (latency_ms > max_latency) { max_latency = latency_ms; }
  764. ++frames;
  765. if (frames % 50 == 0) {
  766. const double elapsed = now_seconds() - window_start;
  767. if (elapsed > 0.0) {
  768. std::printf(
  769. "[stat] 已发布 %llu 帧,本轮 %.1f fps(滑窗 %.1f fps),单帧 全程均 %.2f / "
  770. "近 %llu 帧 p50 %.2f p95 %.2f p99 %.2f / 最大 %.2f ms",
  771. static_cast<unsigned long long>(published), 50.0 / elapsed, measured_fps,
  772. latency_sum / static_cast<double>(frames),
  773. static_cast<unsigned long long>(latency_window.size()),
  774. latency_window.quantile(0.50), latency_window.quantile(0.95),
  775. latency_window.quantile(0.99), max_latency);
  776. if (server) {
  777. std::printf(" 已响应 PLC 请求=%llu",
  778. static_cast<unsigned long long>(server->served_requests()));
  779. }
  780. std::printf("\n");
  781. if (edge) { // 现场整定用:逐项证据摘要(§9.3 的量化口径)
  782. std::printf("[edge] %s\n", edge->last_result().evidence_summary().c_str());
  783. }
  784. std::fflush(stdout);
  785. }
  786. window_start = now_seconds();
  787. }
  788. if (cli.max_frames > 0 && frames >= static_cast<uint64_t>(cli.max_frames)) {
  789. std::printf("[run] 已跑满 --max-frames=%ld,主动退出(台架验收用)\n", cli.max_frames);
  790. g_stop.store(true);
  791. }
  792. const double spent = now_seconds() - loop_start;
  793. if (spent < period) {
  794. std::this_thread::sleep_for(std::chrono::duration<double>(period - spent));
  795. }
  796. }
  797. // ---------------- 收尾 ----------------
  798. if (server) { server->stop(); }
  799. if (server_thread.joinable()) { server_thread.join(); }
  800. // 停取帧线程:先置停止标志再 join(`next()` 内部超时 ≤200 ms,不会久等),最后关源。
  801. g_stop.store(true);
  802. if (capture_thread.joinable()) { capture_thread.join(); }
  803. if (source) { source->close(); }
  804. const uint64_t captured = slot.version();
  805. const uint64_t dropped = captured > frames ? captured - frames : 0;
  806. if (dumper.enabled() || dumper.written() > 0) {
  807. dumper.close();
  808. std::printf("导出统计: %llu 帧已落盘(每 %d 帧一行;写失败=%s)\n",
  809. static_cast<unsigned long long>(dumper.written()), cli.dump_every,
  810. dumper.failed() ? dumper.last_error().c_str() : "无");
  811. }
  812. std::printf(
  813. "取流统计: 取到帧=%llu 已推理=%llu 丢帧(推理没跟上)=%llu 取流失败=%llu%s\n",
  814. static_cast<unsigned long long>(captured), static_cast<unsigned long long>(frames),
  815. static_cast<unsigned long long>(dropped),
  816. static_cast<unsigned long long>(capture_failures.load()),
  817. capture_last_error.empty() ? "" : "(最后一次错误见下方)");
  818. if (!capture_last_error.empty()) {
  819. std::printf(" 最后一次取流错误:%s\n", capture_last_error.c_str());
  820. }
  821. const std::vector<uint16_t> words = snapshot.load();
  822. const portcv::VisionSnapshot final_snap = portcv::VisionSnapshot::from_registers(words, true);
  823. std::printf("\n=== 退出统计 ===\n");
  824. std::printf("发布帧数=%llu 平均耗时=%.2f ms 最大=%.2f ms 已响应 PLC 请求=%llu\n",
  825. static_cast<unsigned long long>(published),
  826. frames ? latency_sum / static_cast<double>(frames) : 0.0, max_latency,
  827. static_cast<unsigned long long>(server ? server->served_requests() : 0));
  828. std::printf("单帧耗时: 全程均 %.2f ms 近 %llu 帧 p50=%.2f p95=%.2f p99=%.2f 最大=%.2f ms\n",
  829. frames ? latency_sum / static_cast<double>(frames) : 0.0,
  830. static_cast<unsigned long long>(latency_window.size()),
  831. latency_window.quantile(0.50), latency_window.quantile(0.95),
  832. latency_window.quantile(0.99), max_latency);
  833. std::printf("实测帧率: 滑窗 %.1f fps(%llu 个采样 / %.1f s 窗口) 发布 fps_x10=%u LOW_FPS 下限=%.1f\n",
  834. measured_fps, static_cast<unsigned long long>(rate.samples()), rate.window_s(),
  835. static_cast<unsigned>(portcv::fps_to_x10(measured_fps)),
  836. config.low_fps_threshold);
  837. // 验收口径(docs/technical_route.md §6.4):T2-T0 ≤ 1 s(P99),目标 P95 ≤ 300 ms。
  838. // 这里只把**实测帧率**折算成"帧数预算",不含取流 / 网络 / PLC 扫描周期 —— 它是打点前的自检,
  839. // 不是承诺值;现场仍按 §6.4 用双向日志对账。
  840. if (measured_fps > 0.0) {
  841. const double vote_s = static_cast<double>(config.voter.min_votes) / measured_fps;
  842. const double resync_s = 3.0 / measured_fps; // 运动后重同步固定 +3 帧(edge_evidence)
  843. std::printf(
  844. "[预算] 按实测 %.1f fps 折算:停稳→出结果 ≈ %d 帧(min_votes)=%.2f s + 驻留 %.2f s = %.2f s;\n"
  845. " 首次判断 / cmd=2 复位后(kUnknown 跳过驻留)≈ %d 帧=%.2f s;运动后重同步固定 +3 帧 ≈ +%.2f s。\n"
  846. " 跑 `--max-frames 200` 看上面的 p95/p99 与 flags.LOW_FPS,再对照 §6.4 判断是否达标。\n",
  847. measured_fps, config.voter.min_votes, vote_s, config.voter.min_dwell_s,
  848. vote_s + config.voter.min_dwell_s, config.voter.min_votes, vote_s, resync_s);
  849. } else {
  850. std::printf("[预算] 帧率样本不足 2 个,无法折算换向时延;把 --max-frames 调大(≥100)再跑。\n");
  851. }
  852. std::printf("最终快照: state=%u(%s) conf=%u seq=%u heartbeat=%u flags=0x%04X crc=0x%04X\n",
  853. final_snap.state, portcv::scene_state_label(final_snap.state), final_snap.confidence,
  854. final_snap.seq, final_snap.heartbeat, final_snap.flags, words.back());
  855. if (edge_v2) {
  856. std::printf("最终 v2 证据: %s\n", edge_v2->last().evidence_summary().c_str());
  857. } else if (edge) {
  858. std::printf("最终边缘证据: %s\n", edge->last_result().evidence_summary().c_str());
  859. }
  860. std::printf("状态提交次数:");
  861. for (const auto& kv : voter.commit_counts()) {
  862. std::printf(" %s=%d", kv.first.c_str(), kv.second);
  863. }
  864. std::printf("\n");
  865. return 0;
  866. }