app_config.cpp 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. // 现场配置 → C++ 运行参数的实现(见 include/portcv/app_config.hpp)。
  2. //
  3. // 实现选择:**表驱动的显式绑定**,而不是"反射"或代码生成。
  4. // * 绑定表就是"配置键 ↔ C++ 字段"的**唯一权威清单**,一眼能看完,评审时无需跳文件;
  5. // * 生成器(scripts/gen_cpp_constants.py)负责的是**寄存器契约**(布局/CRC/flags/默认参数),
  6. // 它不认识 EdgeParams 这种纯 C++ 结构,所以参数绑定留在 C++ 侧更诚实;
  7. // * 类型错 / 缺元素 / 越界 → 一律返回 false(main 直接退出并打印错误行号),
  8. // 绝不"部分生效":现场宁可不启动,也不要带着半套参数去指挥吊装。
  9. #include "portcv/app_config.hpp"
  10. #include <cstdarg>
  11. #include <cstdint>
  12. #include <cstdio>
  13. #include <string>
  14. #include <utility>
  15. #include <vector>
  16. #include "portcv/json_lite.hpp"
  17. namespace portcv {
  18. namespace {
  19. /// 绑定类型(决定"该键在 JSON 里应该长什么样")。
  20. enum class Kind { Number, Integer, Flag, Text, U16, U8, NumberPair, TextList, Points };
  21. /// 一条"配置键 → C++ 字段"的绑定。用工厂函数构造(见下),避免一长串 nullptr。
  22. struct Binding {
  23. const char* key = nullptr;
  24. Kind kind = Kind::Number;
  25. double* num = nullptr; ///< Kind::Number
  26. double* num2 = nullptr; ///< Kind::Number 的联动目标
  27. int* integer = nullptr; ///< Kind::Integer
  28. bool* flag = nullptr; ///< Kind::Flag
  29. std::string* text = nullptr; ///< Kind::Text
  30. uint16_t* u16 = nullptr; ///< Kind::U16
  31. uint8_t* u8 = nullptr; ///< Kind::U8
  32. std::vector<double*>* pair = nullptr; ///< Kind::NumberPair(恰好 2 个元素)
  33. std::vector<std::string>* texts = nullptr; ///< Kind::TextList
  34. std::vector<Point>* points = nullptr; ///< Kind::Points
  35. };
  36. Binding num(const char* key, double* dst) {
  37. Binding b;
  38. b.key = key;
  39. b.kind = Kind::Number;
  40. b.num = dst;
  41. return b;
  42. }
  43. /// 数字绑定,但一个键写两个字段(`edge.grad_pct` → EdgeParams::grad_pct + LineParams::grad_pct)。
  44. Binding num2(const char* key, double* dst, double* mirror) {
  45. Binding b = num(key, dst);
  46. b.num2 = mirror;
  47. return b;
  48. }
  49. Binding integer(const char* key, int* dst) {
  50. Binding b;
  51. b.key = key;
  52. b.kind = Kind::Integer;
  53. b.integer = dst;
  54. return b;
  55. }
  56. Binding flag(const char* key, bool* dst) {
  57. Binding b;
  58. b.key = key;
  59. b.kind = Kind::Flag;
  60. b.flag = dst;
  61. return b;
  62. }
  63. Binding text(const char* key, std::string* dst) {
  64. Binding b;
  65. b.key = key;
  66. b.kind = Kind::Text;
  67. b.text = dst;
  68. return b;
  69. }
  70. Binding u16(const char* key, uint16_t* dst) {
  71. Binding b;
  72. b.key = key;
  73. b.kind = Kind::U16;
  74. b.u16 = dst;
  75. return b;
  76. }
  77. Binding u8(const char* key, uint8_t* dst) {
  78. Binding b;
  79. b.key = key;
  80. b.kind = Kind::U8;
  81. b.u8 = dst;
  82. return b;
  83. }
  84. Binding pair(const char* key, std::vector<double*>* dst) {
  85. Binding b;
  86. b.key = key;
  87. b.kind = Kind::NumberPair;
  88. b.pair = dst;
  89. return b;
  90. }
  91. Binding text_list(const char* key, std::vector<std::string>* dst) {
  92. Binding b;
  93. b.key = key;
  94. b.kind = Kind::TextList;
  95. b.texts = dst;
  96. return b;
  97. }
  98. Binding point_list(const char* key, std::vector<Point>* dst) {
  99. Binding b;
  100. b.key = key;
  101. b.kind = Kind::Points;
  102. b.points = dst;
  103. return b;
  104. }
  105. /// 统一的错误文案:把"哪一项 / 实际是什么类型"写清楚,现场照着改即可。
  106. bool type_error(std::string* error, const char* key, const json::Value& value, const char* want) {
  107. if (error != nullptr) {
  108. *error = std::string("配置项 ") + key + " 类型不对:需要 " + want + ",实际是 " +
  109. value.type_name();
  110. }
  111. return false;
  112. }
  113. /// 依次套用绑定:**只有键存在时才覆盖**(= Python 的深合并效果),其余保持结构体默认值。
  114. bool apply(const Config& cfg, const std::vector<Binding>& bindings, std::string* error) {
  115. for (const Binding& b : bindings) {
  116. if (b.key == nullptr || !cfg.has(b.key)) { continue; }
  117. const json::Value& v = cfg.get(b.key);
  118. switch (b.kind) {
  119. case Kind::Number: {
  120. if (!v.is_number()) { return type_error(error, b.key, v, "数字"); }
  121. *b.num = v.number;
  122. if (b.num2 != nullptr) { *b.num2 = v.number; }
  123. break;
  124. }
  125. case Kind::Integer: {
  126. if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
  127. const double x = v.number;
  128. *b.integer = static_cast<int>(x < 0.0 ? x - 0.5 : x + 0.5);
  129. break;
  130. }
  131. case Kind::Flag: {
  132. if (!v.is_bool() && !v.is_number()) {
  133. return type_error(error, b.key, v, "true / false");
  134. }
  135. *b.flag = v.is_bool() ? v.boolean : (v.number != 0.0);
  136. break;
  137. }
  138. case Kind::Text: {
  139. if (!v.is_string()) { return type_error(error, b.key, v, "字符串"); }
  140. *b.text = v.text;
  141. break;
  142. }
  143. case Kind::U16: {
  144. if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
  145. if (v.number < 0.0 || v.number > 65535.0) {
  146. if (error != nullptr) {
  147. *error = std::string("配置项 ") + b.key + " 超出 0~65535(Modbus 地址/端口)";
  148. }
  149. return false;
  150. }
  151. *b.u16 = static_cast<uint16_t>(v.number);
  152. break;
  153. }
  154. case Kind::U8: {
  155. if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
  156. if (v.number < 0.0 || v.number > 255.0) {
  157. if (error != nullptr) {
  158. *error = std::string("配置项 ") + b.key + " 超出 0~255(单元号)";
  159. }
  160. return false;
  161. }
  162. *b.u8 = static_cast<uint8_t>(v.number);
  163. break;
  164. }
  165. case Kind::NumberPair: {
  166. if (!v.is_array()) { return type_error(error, b.key, v, "[数字, 数字]"); }
  167. if (v.items.size() != b.pair->size()) {
  168. if (error != nullptr) {
  169. *error = std::string("配置项 ") + b.key + " 需要 " +
  170. std::to_string(b.pair->size()) + " 个数字,实际 " +
  171. std::to_string(v.items.size()) + " 个";
  172. }
  173. return false;
  174. }
  175. for (std::size_t i = 0; i < v.items.size(); ++i) {
  176. if (!v.items[i].is_number()) {
  177. return type_error(error, b.key, v.items[i], "数字");
  178. }
  179. *(*b.pair)[i] = v.items[i].number;
  180. }
  181. break;
  182. }
  183. case Kind::TextList: {
  184. if (!v.is_array()) { return type_error(error, b.key, v, "字符串数组"); }
  185. b.texts->clear();
  186. b.texts->reserve(v.items.size());
  187. for (const json::Value& item : v.items) {
  188. if (!item.is_string()) { return type_error(error, b.key, item, "字符串"); }
  189. b.texts->push_back(item.text);
  190. }
  191. break;
  192. }
  193. case Kind::Points: {
  194. if (!v.is_array()) { return type_error(error, b.key, v, "点列 [[x, y], ...]"); }
  195. b.points->clear();
  196. b.points->reserve(v.items.size());
  197. for (const json::Value& item : v.items) {
  198. const bool shaped = item.is_array() && item.items.size() >= 2 &&
  199. item.items[0].is_number() && item.items[1].is_number();
  200. if (!shaped) { return type_error(error, b.key, item, "[x, y] 形式的点"); }
  201. b.points->push_back(Point(item.items[0].number, item.items[1].number));
  202. }
  203. break;
  204. }
  205. }
  206. }
  207. return true;
  208. }
  209. // ---------------------------------------------------------------- 各段的绑定表
  210. // 说明:每个段的绑定表就是该段的"配置键清单";新增键时请同步
  211. // docs/deployment.md §2.5 的键表与 configs/edge-cpp.json 模板。
  212. bool apply_run(const Config& cfg, AppConfig* out, std::string* error) {
  213. const std::vector<Binding> bindings = {
  214. text("run.backend", &out->backend),
  215. num("run.max_fps", &out->max_fps),
  216. integer("run.warmup_frames", &out->warmup_frames),
  217. };
  218. return apply(cfg, bindings, error);
  219. }
  220. bool apply_plc(const Config& cfg, AppConfig* out, std::string* error) {
  221. int gating_timeout_ms = static_cast<int>(out->gating_timeout_s * 1000.0);
  222. const std::vector<Binding> bindings = {
  223. flag("plc.enabled", &out->plc_enabled),
  224. flag("plc.gating", &out->gating),
  225. integer("plc.gating_timeout_ms", &gating_timeout_ms),
  226. text("plc.modbus.host", &out->modbus.host),
  227. u16("plc.modbus.port", &out->modbus.port),
  228. u8("plc.modbus.unit_id", &out->modbus.unit_id),
  229. u16("plc.modbus.input_addr", &out->modbus.input_addr),
  230. u16("plc.modbus.holding_addr", &out->modbus.holding_addr),
  231. flag("plc.modbus.allow_unit_any", &out->modbus.allow_unit_any),
  232. };
  233. if (!apply(cfg, bindings, error)) { return false; }
  234. out->gating_timeout_s = std::max(0.05, gating_timeout_ms / 1000.0);
  235. return true;
  236. }
  237. /// 取流(`source.*`):键名与 Python `portcv/config.py` DEFAULTS 的 source 段**逐字相同**,
  238. /// 语义与 `portcv/io/capture.py` 的 FrameGrabber 一致 —— 现场只维护一份配置文件。
  239. /// 最后两项是 C++ 侧实现级补充键(Python 没有;只影响 synth 源)。
  240. bool apply_source(const Config& cfg, AppConfig* out, std::string* error) {
  241. SourceConfig* s = &out->source;
  242. int synth_seed = static_cast<int>(s->synth_seed);
  243. const std::vector<Binding> bindings = {
  244. text("source.type", &s->type),
  245. text("source.uri", &s->uri),
  246. integer("source.width", &s->width),
  247. integer("source.height", &s->height),
  248. integer("source.buffer_size", &s->buffer_size),
  249. num("source.reconnect_s", &s->reconnect_s),
  250. num("source.stale_frame_s", &s->stale_frame_s),
  251. flag("source.loop", &s->loop),
  252. num("source.synth_shift_px", &s->synth_shift_px),
  253. integer("source.synth_seed", &synth_seed),
  254. };
  255. if (!apply(cfg, bindings, error)) { return false; }
  256. s->synth_seed = static_cast<uint32_t>(synth_seed < 0 ? 0 : synth_seed);
  257. return true;
  258. }
  259. bool apply_scene(const Config& cfg, AppConfig* out, std::string* error) {
  260. SceneParams* s = &out->scene;
  261. const std::vector<Binding> bindings = {
  262. text("scene.mode", &s->mode),
  263. text_list("scene.classes.container", &s->container_names),
  264. text_list("scene.classes.bed", &s->bed_names),
  265. text_list("scene.classes.flatbed", &s->flatbed_names),
  266. text_list("scene.classes.ignore", &s->ignore_names),
  267. point_list("scene.roi", &s->roi),
  268. flag("scene.require_container", &s->require_container),
  269. num("scene.min_class_conf", &s->min_class_conf),
  270. num("scene.roi_min_ratio", &s->roi_min_ratio),
  271. num("scene.support_overlap", &s->support_overlap),
  272. num("scene.support_dy_ratio", &s->support_dy_ratio),
  273. num("scene.support_score_ratio", &s->support_score_ratio),
  274. flag("scene.unknown_on_no_detection", &s->unknown_on_no_detection),
  275. num("scene.no_container_conf", &s->no_container_conf),
  276. };
  277. if (!apply(cfg, bindings, error)) { return false; }
  278. // direct_map:`{类别名: 场景编码}`(与 Python 同名同义,形状特殊故单独处理)
  279. if (cfg.has("scene.direct_map")) {
  280. const json::Value& map = cfg.get("scene.direct_map");
  281. if (!map.is_object()) {
  282. return type_error(error, "scene.direct_map", map, "对象 {类别名: 编码}");
  283. }
  284. s->direct_map.clear();
  285. for (const auto& kv : map.members) {
  286. if (!kv.second.is_number()) {
  287. return type_error(error, "scene.direct_map", kv.second, "整数编码");
  288. }
  289. const double code = kv.second.number;
  290. s->direct_map[kv.first] = static_cast<int>(code < 0.0 ? code - 0.5 : code + 0.5);
  291. }
  292. }
  293. // scene.mode 缺省时用 run.mode 兜底(Python 侧这两个键也互为双保险)
  294. if (!cfg.has("scene.mode") && cfg.has("run.mode")) {
  295. const json::Value& v = cfg.get("run.mode");
  296. if (!v.is_string()) { return type_error(error, "run.mode", v, "字符串"); }
  297. s->mode = v.text;
  298. }
  299. return true;
  300. }
  301. bool apply_voter(const Config& cfg, AppConfig* out, std::string* error) {
  302. VoterParams* d = &out->voter;
  303. const std::vector<Binding> bindings = {
  304. integer("decision.window", &d->window),
  305. num("decision.window_s", &d->window_s),
  306. integer("decision.min_votes", &d->min_votes),
  307. num("decision.min_confidence", &d->min_confidence),
  308. num("decision.min_dwell_s", &d->min_dwell_s),
  309. num("decision.hold_s", &d->hold_s),
  310. num("decision.lost_timeout_s", &d->lost_timeout_s),
  311. // 发布侧用(投票器不读):实测 fps 低于它 → 置 flags.LOW_FPS(bit3)。
  312. // 键名与 Python 同;写了阈值才生效,不写就用默认 3.0。
  313. num("decision.low_fps_threshold", &out->low_fps_threshold),
  314. };
  315. return apply(cfg, bindings, error);
  316. }
  317. bool apply_edge(const Config& cfg, AppConfig* out, std::string* error) {
  318. EdgeParams* e = &out->edge;
  319. // 成对参数(§7 表里写作 `[下限, 上限]`):本地 vector 必须在 apply 调用期间存活
  320. std::vector<double*> band_high{&e->band_high_lo, &e->band_high_hi};
  321. std::vector<double*> band_low{&e->band_low_lo, &e->band_low_hi};
  322. std::vector<double*> gap_band{&e->gap_band_lo, &e->gap_band_hi};
  323. std::vector<double*> cross_ratio{&e->cross_ratio_lo, &e->cross_ratio_hi};
  324. std::vector<double*> texture_period{&e->texture_period_lo, &e->texture_period_hi};
  325. const std::vector<Binding> bindings = {
  326. // ---- docs/edge_evidence.md §7(现场只调这一组)----
  327. num("edge.box_height_m", &e->box_height_m),
  328. pair("edge.band_high", &band_high),
  329. pair("edge.band_low", &band_low),
  330. pair("edge.gap_band", &gap_band),
  331. pair("edge.cross_ratio", &cross_ratio),
  332. num("edge.line_angle_deg", &e->line_angle_deg),
  333. num("edge.min_len_track", &e->min_len_track),
  334. num("edge.min_len_cross_px", &e->min_len_cross_px),
  335. num("edge.min_out_ratio", &e->min_out_ratio),
  336. num2("edge.grad_pct", &e->grad_pct, &out->line.grad_pct),
  337. pair("edge.texture_period", &texture_period),
  338. num("edge.near_edge_px", &e->near_edge_px),
  339. num("edge.motion_hold_s", &e->motion_hold_s),
  340. flag("edge.allow_state2", &e->allow_state2),
  341. // ---- 实现级补充键(§7 未列;现场整定后再并入 §7)----
  342. integer("edge.work_width", &e->work_width),
  343. flag("edge.use_clahe", &e->use_clahe),
  344. integer("edge.clahe_tiles", &e->clahe_tiles),
  345. num("edge.clahe_clip", &e->clahe_clip),
  346. flag("edge.box_is_on_left", &e->box_is_on_left),
  347. num("edge.strong_step_pct", &e->strong_step_pct),
  348. num("edge.wall_density_max", &e->wall_density_max),
  349. num("edge.ground_density_lo", &e->ground_density_lo),
  350. num("edge.ground_density_hi", &e->ground_density_hi),
  351. num("edge.ground_block_px", &e->ground_block_px),
  352. num("edge.c1_below_ground_max", &e->c1_below_ground_max),
  353. num("edge.c1_span_ratio_min", &e->c1_span_ratio_min),
  354. num("edge.c2_col_ratio_min", &e->c2_col_ratio_min),
  355. num("edge.c2_dark_k", &e->c2_dark_k),
  356. num("edge.p4_dark_ratio", &e->p4_dark_ratio),
  357. num("edge.contact_dark_k", &e->contact_dark_k),
  358. num("edge.motion_shift_max_px", &e->motion_shift_max_px),
  359. num("edge.motion_blur_ratio", &e->motion_blur_ratio),
  360. flag("edge.motion_gate", &e->motion_gate),
  361. num("edge.roi_left", &e->roi_left),
  362. num("edge.roi_right", &e->roi_right),
  363. num("edge.roi_top", &e->roi_top),
  364. num("edge.roi_bottom", &e->roi_bottom),
  365. };
  366. return apply(cfg, bindings, error);
  367. }
  368. /// 线段提取(L2)参数:不在 §7 表内,只有现场确实需要时才改。
  369. bool apply_line(const Config& cfg, AppConfig* out, std::string* error) {
  370. LineParams* l = &out->line;
  371. const std::vector<Binding> bindings = {
  372. num("edge.line.canny_lo_pct", &l->canny_lo_pct),
  373. num("edge.line.canny_hi_pct", &l->canny_hi_pct),
  374. integer("edge.line.min_points", &l->min_points),
  375. num("edge.line.fit_tol_px", &l->fit_tol_px),
  376. num("edge.line.dir_tol_deg", &l->dir_tol_deg),
  377. num("edge.line.thick_tol_px", &l->thick_tol_px),
  378. num("edge.line.min_inlier_ratio", &l->min_inlier_ratio),
  379. integer("edge.line.max_segments_per_blob", &l->max_segments_per_blob),
  380. num("edge.line.merge_gap_px", &l->merge_gap_px),
  381. num("edge.line.merge_angle_deg", &l->merge_angle_deg),
  382. num("edge.line.merge_offset_px", &l->merge_offset_px),
  383. num("edge.line.strength_off_px", &l->strength_off_px),
  384. num("edge.line.grad_pct", &l->grad_pct),
  385. };
  386. return apply(cfg, bindings, error);
  387. }
  388. bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
  389. EdgeV2Params* v = &out->evidence_v2;
  390. V2CommitParams* c = &out->evidence_commit;
  391. const std::vector<Binding> bindings = {
  392. text("evidence_v2.view", &v->view),
  393. integer("evidence_v2.work_width", &v->work_width),
  394. integer("evidence_v2.band_min_h", &v->band_min_h),
  395. num("evidence_v2.band_max_h_ratio", &v->band_max_h_ratio),
  396. num("evidence_v2.canny_lo_pct", &v->canny_lo_pct),
  397. num("evidence_v2.canny_hi_pct", &v->canny_hi_pct),
  398. num("evidence_v2.bed_search_ratio", &v->bed_search_ratio),
  399. num("evidence_v2.box_bottom_max_ratio", &v->box_bottom_max_ratio),
  400. num("evidence_v2.below_start_ratio", &v->below_start_ratio),
  401. num("evidence_v2.below_height_ratio", &v->below_height_ratio),
  402. integer("evidence_v2.below_min_height_px", &v->below_min_height_px),
  403. integer("evidence_v2.min_door_posts", &v->min_door_posts),
  404. integer("evidence_v2.max_door_posts", &v->max_door_posts),
  405. num("evidence_v2.max_bed_gap_px", &v->max_bed_gap_px),
  406. integer("evidence_v2.flat_max_door_posts", &v->flat_max_door_posts),
  407. num("evidence_v2.max_post_spacing_cv", &v->max_post_spacing_cv),
  408. num("evidence_v2.min_post_len_ratio", &v->min_post_len_ratio),
  409. num("evidence_v2.min_post_spacing_px", &v->min_post_spacing_px),
  410. integer("evidence_v2.min_diagonal_braces", &v->min_diagonal_braces),
  411. num("evidence_v2.min_post_span_ratio", &v->min_post_span_ratio),
  412. flag("evidence_v2.texture_top_enable", &v->texture_top_enable),
  413. num("evidence_v2.texture_grad_th", &v->texture_grad_th),
  414. integer("evidence_v2.texture_block_px", &v->texture_block_px),
  415. num("evidence_v2.texture_block_hit_ratio", &v->texture_block_hit_ratio),
  416. num("evidence_v2.texture_coverage_min", &v->texture_coverage_min),
  417. integer("evidence_v2.texture_run_rows", &v->texture_run_rows),
  418. integer("evidence_v2.texture_smooth_rows", &v->texture_smooth_rows),
  419. num("evidence_v2.texture_top_margin_ratio", &v->texture_top_margin_ratio),
  420. flag("evidence_v2.body_fallback_enable", &v->body_fallback_enable),
  421. num("evidence_v2.body_bottom_ratio", &v->body_bottom_ratio),
  422. num("evidence_v2.body_min_opacity", &v->body_min_opacity),
  423. integer("evidence_v2.body_min_roi_px", &v->body_min_roi_px),
  424. num("evidence_v2.body_canny_lo_pct", &v->body_canny_lo_pct),
  425. num("evidence_v2.body_canny_hi_pct", &v->body_canny_hi_pct),
  426. integer("evidence_v2.body_min_points", &v->body_min_points),
  427. num("evidence_v2.body_grad_pct", &v->body_grad_pct),
  428. num("evidence_v2.body_min_inlier_ratio", &v->body_min_inlier_ratio),
  429. num("evidence_v2.body_run_min_len_ratio", &v->body_run_min_len_ratio),
  430. num("evidence_v2.body_min_post_len_ratio", &v->body_min_post_len_ratio),
  431. num("evidence_v2.body_x_margin_ratio", &v->body_x_margin_ratio),
  432. integer("evidence_v2.body_min_posts", &v->body_min_posts),
  433. num("evidence_v2.vehicle_min_span_ratio", &v->vehicle_min_span_ratio),
  434. integer("evidence_v2.vehicle_max_posts", &v->vehicle_max_posts),
  435. flag("evidence_v2.empty_vehicle_enable", &v->empty_vehicle_enable),
  436. integer("evidence_v2.empty_min_posts", &v->empty_min_posts),
  437. num("evidence_v2.empty_min_span_ratio", &v->empty_min_span_ratio),
  438. num("evidence_v2.empty_min_opacity", &v->empty_min_opacity),
  439. num("evidence_v2.empty_min_wall_h_ratio", &v->empty_min_wall_h_ratio),
  440. num("evidence_v2.empty_min_post_len_ratio", &v->empty_min_post_len_ratio),
  441. integer("evidence_v2.empty_fallback_max_posts", &v->empty_fallback_max_posts),
  442. integer("evidence_v2.empty_min_diagonal_braces", &v->empty_min_diagonal_braces),
  443. flag("evidence_v2.empty_flatbed_enable", &v->empty_flatbed_enable),
  444. num("evidence_v2.empty_flatbed_min_gap_px", &v->empty_flatbed_min_gap_px),
  445. num("evidence_v2.empty_flatbed_max_plane_edge", &v->empty_flatbed_max_plane_edge),
  446. num("evidence_v2.empty_flatbed_max_gray_drop", &v->empty_flatbed_max_gray_drop),
  447. num("evidence_v2.empty_top_margin_ratio", &v->empty_top_margin_ratio),
  448. flag("evidence_v2.allow_state3", &v->allow_state3),
  449. num("evidence_v2.min_wall_opacity", &v->min_wall_opacity),
  450. num("evidence_v2.wall_edge_density_ref", &v->wall_edge_density_ref),
  451. num("evidence_v2.wall_edge_density_span", &v->wall_edge_density_span),
  452. integer("evidence_v2.ground_block_px", &v->ground_block_px),
  453. num("evidence_v2.ground_density_lo", &v->ground_density_lo),
  454. num("evidence_v2.ground_density_hi", &v->ground_density_hi),
  455. num("evidence_v2.min_zero_ground_ratio", &v->min_zero_ground_ratio),
  456. num("evidence_v2.deck_min_len_ratio", &v->deck_min_len_ratio),
  457. num("evidence_v2.contact_max_h_ratio", &v->contact_max_h_ratio),
  458. num("evidence_v2.under_deck_dark_delta", &v->under_deck_dark_delta),
  459. num("evidence_v2.under_deck_min_h_ratio", &v->under_deck_min_h_ratio),
  460. num("evidence_v2.under_deck_search_h_ratio", &v->under_deck_search_h_ratio),
  461. num("evidence_v2.max_flat_gap_px", &v->max_flat_gap_px),
  462. num("evidence_v2.box_height_m", &v->box_height_m),
  463. num("evidence_v2.px_per_m", &v->px_per_m),
  464. num("evidence_v2.min_scale_px", &v->min_scale_px),
  465. num("evidence_v2.motion_diff_max", &v->motion_diff_max),
  466. num("evidence_v2.motion_grad_ratio_min", &v->motion_grad_ratio_min),
  467. flag("evidence_v2.require_commit", &v->require_commit),
  468. flag("evidence_v2.allow_state2", &v->allow_state2),
  469. num("evidence_v2.structure_hits_min", &v->structure_hits_min),
  470. integer("evidence_v2.min_bed_roi_px", &v->min_bed_roi_px),
  471. // P0-0 图像侧安全门(键名与 Python `evidence_v2.*` 逐字相同)
  472. flag("evidence_v2.reject_hoist_high", &v->reject_hoist_high),
  473. integer("evidence_v2.hoist_dark_max", &v->hoist.dark_max),
  474. num("evidence_v2.hoist_band_frac", &v->hoist.band_frac),
  475. num("evidence_v2.hoist_line_ratio", &v->hoist.line_ratio),
  476. num("evidence_v2.hoist_dark_ratio", &v->hoist.dark_ratio),
  477. num("evidence_v2.hoist_bright_delta", &v->hoist.bright_delta),
  478. flag("evidence_v2.reject_spreader_contact", &v->reject_spreader_contact),
  479. integer("evidence_v2.spreader_dark_max", &v->spreader.dark_max),
  480. num("evidence_v2.spreader_dark_ratio", &v->spreader.dark_ratio),
  481. num("evidence_v2.commit.gap_m_max", &c->gap_m_max),
  482. num("evidence_v2.commit.gap_px_hard_max", &c->gap_px_hard_max),
  483. integer("evidence_v2.commit.stable_frames", &c->stable_frames),
  484. integer("evidence_v2.commit.structure_frames", &c->structure_frames),
  485. num("evidence_v2.commit.min_structure_hits", &c->min_structure_hits),
  486. num("evidence_v2.commit.max_gap_rise_m", &c->max_gap_rise_m),
  487. flag("evidence_v2.commit.allow_state1", &c->allow_state1),
  488. flag("evidence_v2.commit.allow_state2", &c->allow_state2),
  489. flag("evidence_v2.commit.allow_state3", &c->allow_state3),
  490. flag("evidence_v2.commit.require_motion_ok", &c->require_motion_ok),
  491. flag("evidence_v2.commit.require_view_known", &c->require_view_known),
  492. flag("evidence_v2.commit.use_plc_arrival", &c->use_plc_arrival),
  493. };
  494. if (!apply(cfg, bindings, error)) { return false; }
  495. // window 是 4 个归一化数字,Binding 只有 NumberPair,单独解析。
  496. if (cfg.has("evidence_v2.window")) {
  497. const json::Value& v4 = cfg.get("evidence_v2.window");
  498. if (!v4.is_array() || v4.items.size() != 4) {
  499. return type_error(error, "evidence_v2.window", v4, "4 个数字 [x0,y0,x1,y1]");
  500. }
  501. for (int i = 0; i < 4; ++i) {
  502. if (!v4.items[static_cast<std::size_t>(i)].is_number()) {
  503. return type_error(error, "evidence_v2.window", v4.items[static_cast<std::size_t>(i)], "数字");
  504. }
  505. v->window[i] = v4.items[static_cast<std::size_t>(i)].number;
  506. }
  507. }
  508. // 两个 allow_state2 开关**串联**(默认都 true):任一显式为 false 都会关闭 2 的提交。
  509. // 顶层键保留为模板可读性 / 旧模板兼容;这样现场只改一处也不会被另一处静默覆盖。
  510. c->allow_state2 = c->allow_state2 && v->allow_state2;
  511. v->allow_state2 = c->allow_state2;
  512. // P0-Q9:allow_state3(空车 3)同构串联。
  513. c->allow_state3 = c->allow_state3 && v->allow_state3;
  514. v->allow_state3 = c->allow_state3;
  515. return true;
  516. }
  517. // ---------------------------------------------------------------- 标定记录(P0-5)
  518. // 只解析"判定所需的四件事":记录路径 / 有效期 / 两个漂移容差 / 手工开关。
  519. // **不做文件存在性校验**:文件缺失不是"配置错",而是运行期 `CALIB_STALE`(现场
  520. // 拷贝漏了记录文件也要能起来、并在日志与 flags 上大声报警,而不是静默按默认值跑)。
  521. bool apply_calibration(const Config& cfg, AppConfig* out, std::string* error) {
  522. CalibrationConfig* c = &out->calibration;
  523. const std::vector<Binding> bindings = {
  524. flag("calibration.stale", &c->stale),
  525. text("calibration.record", &c->record),
  526. num("calibration.max_age_days", &c->max_age_days),
  527. num("calibration.px_per_m_tolerance", &c->px_per_m_tolerance),
  528. num("calibration.box_height_tolerance_m", &c->box_height_tolerance_m),
  529. // 新增键(C++/Python 同名同义):标定不可信时是否清 RESULT_VALID/STABLE
  530. flag("calibration.hold_on_stale", &c->hold_on_stale),
  531. };
  532. return apply(cfg, bindings, error);
  533. }
  534. // ---------------------------------------------------------------- 取值校验
  535. // 原则:**能判出来的错都在启动时判**。现场宁可"起不来 + 一行明确原因",
  536. // 也不要"起来了但参数是半套"——那会直接变成吊装动作的依据。
  537. bool validate(const AppConfig* cfg, std::string* error) {
  538. const auto bad = [error](const std::string& what) {
  539. if (error != nullptr) { *error = what; }
  540. return false;
  541. };
  542. if (cfg->backend.empty()) { return bad("run.backend 不能为空(mock / edge / edge-v2)"); }
  543. // 同上:`!(x > 0)` 才挡得住 NaN(JSON 字面量写不出 NaN,但 1e400 → inf 之类的
  544. // 溢出值会走到这里,防御性写法保持两条路径同口径)。
  545. if (!(cfg->max_fps > 0.0) || cfg->max_fps > 240.0) {
  546. return bad("run.max_fps 必须 ∈ (0, 240]");
  547. }
  548. if (cfg->warmup_frames < 0) { return bad("run.warmup_frames 不能为负"); }
  549. // ---- 取流(source.*):类型不认识 / 取值非法一律**启动即失败** ----
  550. // 注意:这里**只做语法层校验**(不认识 `gst/rtsp/file/usb` 是配置错误);
  551. // "本次构建有没有编进 GStreamer"属于**运行期能力**,放到 main 建源时报错 ——
  552. // 这样 `--check-config`(以及 configs/default.json 的加载)在纯算法机上也能跑。
  553. const SourceConfig& src = cfg->source;
  554. if (!source_type_known(src.type)) {
  555. return bad("source.type=\"" + src.type + "\" 不认识。\n" + source_type_help());
  556. }
  557. if (src.type != "none" && src.type != "synth" && src.uri.empty()) {
  558. return bad("source.type=" + src.type +
  559. " 必须给 source.uri(相机地址 / 视频文件 / PGM 目录 / 管线字符串)");
  560. }
  561. if (src.uri.find('"') != std::string::npos) {
  562. return bad("source.uri 不能包含双引号(会破坏 GStreamer 管线解析)");
  563. }
  564. if (src.type == "synth" && !synth_scene_known(src.uri)) {
  565. return bad("source.uri=\"" + src.uri +
  566. "\" 不是合成场景名;可用 gondola / flatbed / ground / empty(留空 = gondola)");
  567. }
  568. if (src.width < 0 || src.height < 0) { return bad("source.width / source.height 不能为负"); }
  569. if (src.buffer_size < 0) { return bad("source.buffer_size 不能为负(0 = 不设缓冲上限)"); }
  570. if (src.reconnect_s <= 0.0) { return bad("source.reconnect_s 必须 > 0"); }
  571. if (src.stale_frame_s <= 0.0) {
  572. return bad("source.stale_frame_s 必须 > 0(它是 FRAME_TIMEOUT 的判据)");
  573. }
  574. if (src.synth_shift_px < 0.0) { return bad("source.synth_shift_px 不能为负"); }
  575. const EdgeParams& e = cfg->edge;
  576. if (e.box_height_m <= 0.0) {
  577. return bad("edge.box_height_m 必须 > 0(自标尺基准:近端竖棱像素 / 箱高)");
  578. }
  579. if (e.band_high_lo > e.band_high_hi) { return bad("edge.band_high 需要 [下限, 上限]"); }
  580. if (e.band_low_lo > e.band_low_hi) { return bad("edge.band_low 需要 [下限, 上限]"); }
  581. if (e.gap_band_lo > e.gap_band_hi) { return bad("edge.gap_band 需要 [下限, 上限]"); }
  582. if (e.cross_ratio_lo > e.cross_ratio_hi) { return bad("edge.cross_ratio 需要 [下限, 上限]"); }
  583. if (e.texture_period_lo > e.texture_period_hi) {
  584. return bad("edge.texture_period 需要 [下限, 上限]");
  585. }
  586. if (e.near_edge_px < 0.0) { return bad("edge.near_edge_px 不能为负"); }
  587. if (e.motion_hold_s < 0.0) { return bad("edge.motion_hold_s 不能为负"); }
  588. if (e.work_width < 64) {
  589. return bad("edge.work_width 至少 64(证据阈值都是在 ~960 px 长边上整定的)");
  590. }
  591. if (e.clahe_tiles < 1) { return bad("edge.clahe_tiles 至少 1"); }
  592. if (cfg->line.min_points < 2) { return bad("edge.line.min_points 至少 2"); }
  593. if (cfg->line.max_segments_per_blob < 1) {
  594. return bad("edge.line.max_segments_per_blob 至少 1");
  595. }
  596. if (cfg->line.canny_lo_pct < 0.0 || cfg->line.canny_lo_pct > 1.0 ||
  597. cfg->line.canny_hi_pct < 0.0 || cfg->line.canny_hi_pct > 1.0) {
  598. return bad("edge.line.canny_*_pct 必须 ∈ [0, 1]");
  599. }
  600. if (cfg->line.canny_lo_pct > cfg->line.canny_hi_pct) {
  601. return bad("edge.line.canny_lo_pct 不能大于 canny_hi_pct");
  602. }
  603. const VoterParams& v = cfg->voter;
  604. if (v.window < 1) { return bad("decision.window 至少 1"); }
  605. if (v.min_votes < 1 || v.min_votes > v.window) {
  606. return bad("decision.min_votes 必须 ∈ [1, decision.window]");
  607. }
  608. if (v.window_s <= 0.0) { return bad("decision.window_s 必须 > 0"); }
  609. if (v.min_confidence < 0.0 || v.min_confidence > 1.0) {
  610. return bad("decision.min_confidence 必须 ∈ [0, 1]");
  611. }
  612. if (v.min_dwell_s < 0.0 || v.hold_s < 0.0 || v.lost_timeout_s < 0.0) {
  613. return bad("decision.min_dwell_s / hold_s / lost_timeout_s 不能为负");
  614. }
  615. if (v.hold_s > v.lost_timeout_s) {
  616. return bad("decision.hold_s 不应大于 lost_timeout_s(否则永远等到超时才置 255)");
  617. }
  618. const SceneParams& s = cfg->scene;
  619. if (s.mode != "composed" && s.mode != "direct") {
  620. return bad("scene.mode 只能是 composed / direct,实际是 \"" + s.mode + "\"");
  621. }
  622. if (s.min_class_conf < 0.0 || s.min_class_conf > 1.0) {
  623. return bad("scene.min_class_conf 必须 ∈ [0, 1]");
  624. }
  625. if (s.roi.size() < 3) { return bad("scene.roi 至少需要 3 个点(多边形)"); }
  626. if (s.container_names.empty()) { return bad("scene.classes.container 不能为空"); }
  627. if (s.bed_names.empty() || s.flatbed_names.empty()) {
  628. return bad("scene.classes.bed / scene.classes.flatbed 不能为空");
  629. }
  630. const EdgeV2Params& v2 = cfg->evidence_v2;
  631. if (v2.view != "front" && v2.view != "high" && v2.view != "unknown") {
  632. return bad("evidence_v2.view 只能是 front / high / unknown");
  633. }
  634. if (v2.work_width < 160) { return bad("evidence_v2.work_width 至少 160"); }
  635. if (v2.band_min_h < 1) { return bad("evidence_v2.band_min_h 至少 1"); }
  636. if (!(v2.band_max_h_ratio > 0.0 && v2.band_max_h_ratio <= 1.0)) {
  637. return bad("evidence_v2.band_max_h_ratio 必须 ∈ (0,1]");
  638. }
  639. if (v2.min_door_posts < 1 || v2.max_door_posts < v2.min_door_posts) {
  640. return bad("evidence_v2.min_door_posts / max_door_posts 非法");
  641. }
  642. if (v2.flat_max_door_posts < 1) {
  643. return bad("evidence_v2.flat_max_door_posts 至少 1");
  644. }
  645. if (v2.box_height_m <= 0.0) { return bad("evidence_v2.box_height_m 必须 > 0"); }
  646. if (v2.px_per_m < 0.0) { return bad("evidence_v2.px_per_m 不能为负(0=自标尺)"); }
  647. // P0-0 安全门参数:这些值只影响“命中多严”,不改变“命中即弃权”的语义;
  648. // 写错(例如 dark_max=0 或 band_frac=0)会让门永远不触发 —— 那比报错更危险,
  649. // 所以一律启动即失败。
  650. if (v2.hoist.dark_max <= 0 || v2.hoist.dark_max >= 255) {
  651. return bad("evidence_v2.hoist_dark_max 必须 ∈ (0, 255)");
  652. }
  653. if (!(v2.hoist.band_frac > 0.0 && v2.hoist.band_frac <= 0.5)) {
  654. return bad("evidence_v2.hoist_band_frac 必须 ∈ (0, 0.5]");
  655. }
  656. if (!(v2.hoist.line_ratio > 0.0 && v2.hoist.line_ratio <= 1.0)) {
  657. return bad("evidence_v2.hoist_line_ratio 必须 ∈ (0, 1]");
  658. }
  659. if (v2.hoist.dark_ratio < 0.0 || v2.hoist.dark_ratio > 1.0) {
  660. return bad("evidence_v2.hoist_dark_ratio 必须 ∈ [0, 1]");
  661. }
  662. if (v2.hoist.bright_delta < 0.0) {
  663. return bad("evidence_v2.hoist_bright_delta 不能为负");
  664. }
  665. if (v2.spreader.dark_max <= 0 || v2.spreader.dark_max >= 255) {
  666. return bad("evidence_v2.spreader_dark_max 必须 ∈ (0, 255)");
  667. }
  668. if (v2.spreader.dark_ratio < 0.0 || v2.spreader.dark_ratio > 1.0) {
  669. return bad("evidence_v2.spreader_dark_ratio 必须 ∈ [0, 1]");
  670. }
  671. if (v2.min_wall_opacity < 0.0 || v2.min_wall_opacity > 1.0) {
  672. return bad("evidence_v2.min_wall_opacity 必须 ∈ [0,1]");
  673. }
  674. if (v2.min_post_spacing_px < 0.0) {
  675. return bad("evidence_v2.min_post_spacing_px 不能为负(0=不启用该门)");
  676. }
  677. if (v2.min_diagonal_braces < 0) {
  678. return bad("evidence_v2.min_diagonal_braces 不能为负(0=不启用该门)");
  679. }
  680. if (v2.min_post_span_ratio < 0.0 || v2.min_post_span_ratio > 1.0) {
  681. return bad("evidence_v2.min_post_span_ratio 必须 ∈ [0,1](0=不启用该门)");
  682. }
  683. // P0-Q9:空车门参数(写错会让空车永远判不出或过度触发,启动即失败)。
  684. if (v2.empty_min_span_ratio < 0.0 || v2.empty_min_span_ratio > 1.0) {
  685. return bad("evidence_v2.empty_min_span_ratio 必须 ∈ [0,1]");
  686. }
  687. if (v2.empty_min_opacity < 0.0 || v2.empty_min_opacity > 1.0) {
  688. return bad("evidence_v2.empty_min_opacity 必须 ∈ [0,1]");
  689. }
  690. if (v2.empty_min_wall_h_ratio < 0.0 || v2.empty_min_wall_h_ratio > 1.0) {
  691. return bad("evidence_v2.empty_min_wall_h_ratio 必须 ∈ [0,1]");
  692. }
  693. if (v2.empty_min_post_len_ratio < 0.0 || v2.empty_min_post_len_ratio > 1.0) {
  694. return bad("evidence_v2.empty_min_post_len_ratio 必须 ∈ [0,1]");
  695. }
  696. if (v2.empty_top_margin_ratio < 0.0 || v2.empty_top_margin_ratio > 0.5) {
  697. return bad("evidence_v2.empty_top_margin_ratio 必须 ∈ [0,0.5](0=不设门槛)");
  698. }
  699. if (v2.empty_min_diagonal_braces < 0) {
  700. return bad("evidence_v2.empty_min_diagonal_braces 不能为负(0=不启用该门)");
  701. }
  702. if (v2.empty_flatbed_min_gap_px < 0.0) {
  703. return bad("evidence_v2.empty_flatbed_min_gap_px 不能为负");
  704. }
  705. if (v2.empty_flatbed_max_plane_edge < 0.0 || v2.empty_flatbed_max_plane_edge > 1.0) {
  706. return bad("evidence_v2.empty_flatbed_max_plane_edge 必须 ∈ [0,1]");
  707. }
  708. if (v2.empty_flatbed_max_gray_drop < 0.0) {
  709. return bad("evidence_v2.empty_flatbed_max_gray_drop 不能为负");
  710. }
  711. if (v2.empty_min_posts < 1) {
  712. return bad("evidence_v2.empty_min_posts 至少为 1");
  713. }
  714. if (v2.empty_fallback_max_posts < v2.empty_min_posts) {
  715. return bad("evidence_v2.empty_fallback_max_posts 不能小于 empty_min_posts");
  716. }
  717. if (!(v2.texture_grad_th > 0.0)) {
  718. return bad("evidence_v2.texture_grad_th 必须 > 0");
  719. }
  720. if (v2.texture_block_px < 4) {
  721. return bad("evidence_v2.texture_block_px 至少 4");
  722. }
  723. if (v2.texture_block_hit_ratio < 0.0 || v2.texture_block_hit_ratio > 1.0) {
  724. return bad("evidence_v2.texture_block_hit_ratio 必须 ∈ [0,1]");
  725. }
  726. if (v2.texture_coverage_min < 0.0 || v2.texture_coverage_min > 1.0) {
  727. return bad("evidence_v2.texture_coverage_min 必须 ∈ [0,1]");
  728. }
  729. if (v2.texture_run_rows < 1 || v2.texture_smooth_rows < 1) {
  730. return bad("evidence_v2.texture_run_rows / texture_smooth_rows 至少 1");
  731. }
  732. if (v2.texture_top_margin_ratio < 0.0 || v2.texture_top_margin_ratio > 0.5) {
  733. return bad("evidence_v2.texture_top_margin_ratio 必须 ∈ [0,0.5]");
  734. }
  735. if (!(v2.body_bottom_ratio > 0.0 && v2.body_bottom_ratio <= 1.0)) {
  736. return bad("evidence_v2.body_bottom_ratio 必须 ∈ (0,1]");
  737. }
  738. if (v2.body_min_opacity < 0.0 || v2.body_min_opacity > 1.0) {
  739. return bad("evidence_v2.body_min_opacity 必须 ∈ [0,1]");
  740. }
  741. if (v2.body_min_roi_px < 8) {
  742. return bad("evidence_v2.body_min_roi_px 至少 8");
  743. }
  744. if (!(v2.body_canny_lo_pct > 0.0 && v2.body_canny_lo_pct <= 1.0) ||
  745. !(v2.body_canny_hi_pct >= v2.body_canny_lo_pct && v2.body_canny_hi_pct <= 1.0)) {
  746. return bad("evidence_v2.body_canny_lo/hi_pct 必须满足 0 < lo <= hi <= 1");
  747. }
  748. if (v2.body_min_points < 4) {
  749. return bad("evidence_v2.body_min_points 至少 4");
  750. }
  751. if (v2.body_grad_pct < 0.0 || v2.body_grad_pct > 1.0 ||
  752. v2.body_min_inlier_ratio < 0.0 || v2.body_min_inlier_ratio > 1.0) {
  753. return bad("evidence_v2.body_grad_pct / body_min_inlier_ratio 必须 ∈ [0,1]");
  754. }
  755. if (!(v2.body_run_min_len_ratio > 0.0 && v2.body_run_min_len_ratio <= 1.0)) {
  756. return bad("evidence_v2.body_run_min_len_ratio 必须 ∈ (0,1]");
  757. }
  758. if (!(v2.body_min_post_len_ratio > 0.0 && v2.body_min_post_len_ratio <= 1.0)) {
  759. return bad("evidence_v2.body_min_post_len_ratio 必须 ∈ (0,1]");
  760. }
  761. if (v2.body_x_margin_ratio < 0.0 || v2.body_x_margin_ratio > 0.5) {
  762. return bad("evidence_v2.body_x_margin_ratio 必须 ∈ [0,0.5]");
  763. }
  764. if (v2.body_min_posts < 1) {
  765. return bad("evidence_v2.body_min_posts 至少 1");
  766. }
  767. // P0-Q6:没有箱底时的“只看车体”判据(罐箱箱底被车帮挡住时用)。
  768. if (!(v2.vehicle_min_span_ratio > 0.0 && v2.vehicle_min_span_ratio <= 1.0)) {
  769. return bad("evidence_v2.vehicle_min_span_ratio 必须 ∈ (0,1]");
  770. }
  771. if (v2.vehicle_max_posts < v2.body_min_posts) {
  772. return bad("evidence_v2.vehicle_max_posts 不能小于 body_min_posts");
  773. }
  774. // P0-Q3:2(平车)的贴合亮带厚度/车面下方暗带参数。写错会让门永不触发,
  775. // 比报错更危险(地面堆料会被判成平车),所以一律启动即失败。
  776. if (!(v2.contact_max_h_ratio > 0.0 && v2.contact_max_h_ratio <= 0.5)) {
  777. return bad("evidence_v2.contact_max_h_ratio 必须 ∈ (0, 0.5]");
  778. }
  779. if (v2.under_deck_dark_delta < 0.0) {
  780. return bad("evidence_v2.under_deck_dark_delta 不能为负");
  781. }
  782. if (!(v2.under_deck_min_h_ratio > 0.0 && v2.under_deck_min_h_ratio <= 0.1)) {
  783. return bad("evidence_v2.under_deck_min_h_ratio 必须 ∈ (0, 0.1]");
  784. }
  785. if (!(v2.under_deck_search_h_ratio > 0.0 && v2.under_deck_search_h_ratio <= 0.5)) {
  786. return bad("evidence_v2.under_deck_search_h_ratio 必须 ∈ (0, 0.5]");
  787. }
  788. // 太小会让"远距小箱"重新参与 1 的判定(B 片段实测误发布 1);太大则正常
  789. // 车距也判不出 1。A 实测 ROI≈201 px、B 误判帧 44~68 px,取 90 px 留出双向余量。
  790. if (v2.min_bed_roi_px < 24) { return bad("evidence_v2.min_bed_roi_px 至少 24"); }
  791. const V2CommitParams& c = cfg->evidence_commit;
  792. if (c.gap_m_max < 0.0 || c.gap_px_hard_max < 0.0) {
  793. return bad("evidence_v2.commit.gap_* 不能为负");
  794. }
  795. if (c.stable_frames < 1 || c.structure_frames < 1) {
  796. return bad("evidence_v2.commit.stable_frames / structure_frames 至少 1");
  797. }
  798. // ---- 标定(calibration.*):只挡"写错的数",不挡"记录文件缺失"(后者 → CALIB_STALE)----
  799. const CalibrationConfig& calib = cfg->calibration;
  800. if (!(calib.max_age_days >= 0.0)) {
  801. return bad("calibration.max_age_days 必须是 >= 0 的数字(0 = 不判过期)");
  802. }
  803. if (!(calib.px_per_m_tolerance >= 0.0) || calib.px_per_m_tolerance > 10.0) {
  804. return bad("calibration.px_per_m_tolerance 必须 ∈ [0, 10](相对容差,0.10 = 10%)");
  805. }
  806. if (!(calib.box_height_tolerance_m >= 0.0) || calib.box_height_tolerance_m > 5.0) {
  807. return bad("calibration.box_height_tolerance_m 必须 ∈ [0, 5] 米");
  808. }
  809. return true;
  810. }
  811. /// 把配置套用到一份**全新**的 AppConfig 上(重复调用幂等)。
  812. bool apply_config_into(const Config& cfg, AppConfig* out, std::string* error) {
  813. *out = AppConfig(); // 每次都从"结构体默认值"出发 —— 等价于 Python 的 DEFAULTS 深合并
  814. if (!apply_run(cfg, out, error)) { return false; }
  815. if (!apply_plc(cfg, out, error)) { return false; }
  816. if (!apply_source(cfg, out, error)) { return false; }
  817. if (!apply_scene(cfg, out, error)) { return false; }
  818. if (!apply_voter(cfg, out, error)) { return false; }
  819. // 顺序有讲究:先 edge.*(其中 edge.grad_pct 会联动 line.grad_pct),
  820. // 再 edge.line.*,这样现场既能用 §7 的键,也能显式覆盖联动值。
  821. if (!apply_edge(cfg, out, error)) { return false; }
  822. if (!apply_line(cfg, out, error)) { return false; }
  823. if (!apply_evidence_v2(cfg, out, error)) { return false; }
  824. if (!apply_calibration(cfg, out, error)) { return false; }
  825. return validate(out, error);
  826. }
  827. } // namespace
  828. // ---------------------------------------------------------------- 公开入口
  829. bool app_config_from_text(const std::string& text, AppConfig* out, std::string* error) {
  830. if (out == nullptr) {
  831. if (error != nullptr) { *error = "app_config_from_text: 输出参数为空指针"; }
  832. return false;
  833. }
  834. Config cfg;
  835. if (!Config::from_text(text, &cfg, error)) { return false; }
  836. return apply_config_into(cfg, out, error);
  837. }
  838. bool load_app_config(const std::string& path, AppConfig* out, std::string* error) {
  839. if (out == nullptr) {
  840. if (error != nullptr) { *error = "load_app_config: 输出参数为空指针"; }
  841. return false;
  842. }
  843. Config cfg; // 空配置 = 纯默认值(--config 不给时的行为)
  844. if (!path.empty() && !Config::from_file(path, &cfg, error)) { return false; }
  845. return apply_config_into(cfg, out, error);
  846. }
  847. bool check_backend(const AppConfig& cfg, std::string* error) {
  848. const auto fail = [error](const std::string& what) {
  849. if (error != nullptr) { *error = what; }
  850. return false;
  851. };
  852. const char* const backends[] = {"mock", "edge", "edge-v2", "evidence-v2"};
  853. bool known = false;
  854. for (const char* name : backends) {
  855. if (cfg.backend == name) { known = true; }
  856. }
  857. if (!known) {
  858. return fail("run.backend=\"" + cfg.backend +
  859. "\" 在 C++ 侧尚未实现(当前支持 mock / edge / edge-v2):\n"
  860. " * edge-v2 = P1b/P1c 前视 v2 结构证据 + commit 门(推荐;"
  861. "不需要 NPU / OpenCV / 模型权重);\n"
  862. " * edge = 二维边缘几何证据 v1(docs/edge_evidence.md,已冻结,仅回归对照);\n"
  863. " * mock = 脚本化检测框,用于「无相机无模型」把寄存器与指令握手联调通;\n"
  864. " * onnx / rknn / tensorrt 请用 Python 版:python -m portcv run -c <同一份配置>。");
  865. }
  866. const std::string& demo = cfg.edge_demo;
  867. if (demo != "none" && demo != "gondola" && demo != "flatbed" && demo != "ground") {
  868. return fail("--edge-demo 只能是 none / gondola / flatbed / ground,实际是 \"" + demo + "\"");
  869. }
  870. if (demo != "none" && cfg.backend != "edge") {
  871. return fail("--edge-demo 只在 --backend edge 下有意义(当前 backend=" + cfg.backend + ")");
  872. }
  873. if (error != nullptr) { error->clear(); }
  874. return true;
  875. }
  876. namespace {
  877. /// 追加一行格式化文本(配置文件很小、清单固定 13 行,超长即截断,不做动态分配)。
  878. #if defined(__GNUC__)
  879. __attribute__((format(printf, 2, 3)))
  880. #endif
  881. void append_line(std::string* out, const char* fmt, ...) {
  882. char buf[1024];
  883. va_list args;
  884. va_start(args, fmt);
  885. std::vsnprintf(buf, sizeof(buf), fmt, args);
  886. va_end(args);
  887. *out += buf;
  888. }
  889. } // namespace
  890. std::string describe_app_config(const AppConfig& cfg) {
  891. const SceneParams& s = cfg.scene;
  892. const VoterParams& v = cfg.voter;
  893. const EdgeParams& e = cfg.edge;
  894. const LineParams& l = cfg.line;
  895. std::string out;
  896. append_line(&out, "运行 : backend=%s max_fps=%.1f warmup_frames=%d plc=%s\n",
  897. cfg.backend.c_str(), cfg.max_fps, cfg.warmup_frames,
  898. cfg.plc_enabled ? "on" : "off");
  899. // 取流一行(口令掩掉):现场 `--check-config` 一眼能看到"到底接的是哪路画面"。
  900. append_line(&out,
  901. "取流 : source.type=%s uri=%s buffer_size=%d reconnect_s=%.1f stale_frame_s=%.2f "
  902. "loop=%d(%s;本构建%s GStreamer)\n",
  903. cfg.source.type.c_str(),
  904. cfg.source.uri.empty() ? "(未设置)" : redact_uri(cfg.source.uri).c_str(),
  905. cfg.source.buffer_size, cfg.source.reconnect_s, cfg.source.stale_frame_s,
  906. cfg.source.loop ? 1 : 0,
  907. cfg.source.type == "none"
  908. ? "不取流:Frame.gray = nullptr → 证据后端输出 255 安全值"
  909. : (cfg.source.type == "synth" ? "合成帧(台架/CI)" : "真机取流"),
  910. gst_available() ? "带" : "**不带**");
  911. if (cfg.source.type != "none" && cfg.source.type != "synth") {
  912. append_line(&out, " 管线=%s\n", redact_uri(gst_pipeline_for(cfg.source)).c_str());
  913. }
  914. append_line(&out,
  915. "PLC : %s:%u unit=%u input_addr=%u(%d字) holding_addr=%u(%d字) "
  916. "allow_unit_any=%d\n",
  917. cfg.modbus.host.c_str(), static_cast<unsigned>(cfg.modbus.port),
  918. static_cast<unsigned>(cfg.modbus.unit_id),
  919. static_cast<unsigned>(cfg.modbus.input_addr), VisionSnapshot::register_count(),
  920. static_cast<unsigned>(cfg.modbus.holding_addr), PlcCommand::register_count(),
  921. cfg.modbus.allow_unit_any ? 1 : 0);
  922. append_line(&out,
  923. "判定 : scene.mode=%s roi=%d点 min_class_conf=%.2f roi_min_ratio=%.2f "
  924. "support_overlap=%.2f support_dy_ratio=%.2f support_score_ratio=%.2f\n",
  925. s.mode.c_str(), static_cast<int>(s.roi.size()), s.min_class_conf, s.roi_min_ratio,
  926. s.support_overlap, s.support_dy_ratio, s.support_score_ratio);
  927. append_line(&out, " require_container=%d no_container_conf=%.2f unknown_on_no_detection=%d\n",
  928. s.require_container ? 1 : 0, s.no_container_conf, s.unknown_on_no_detection ? 1 : 0);
  929. append_line(&out,
  930. "时序 : decision.window=%d window_s=%.2f min_votes=%d min_confidence=%.2f "
  931. "min_dwell_s=%.2f hold_s=%.2f lost_timeout_s=%.2f low_fps_threshold=%.1f\n",
  932. v.window, v.window_s, v.min_votes, v.min_confidence, v.min_dwell_s, v.hold_s,
  933. v.lost_timeout_s, cfg.low_fps_threshold);
  934. append_line(&out,
  935. "边缘§7: edge.box_height_m=%.3f band_high=[%.2f, %.2f] band_low=[%.2f, %.2f] "
  936. "gap_band=[%.2f, %.2f]\n",
  937. e.box_height_m, e.band_high_lo, e.band_high_hi, e.band_low_lo, e.band_low_hi,
  938. e.gap_band_lo, e.gap_band_hi);
  939. append_line(&out,
  940. " edge.cross_ratio=[%.2f, %.2f] line_angle_deg=%.1f min_len_track=%.2f "
  941. "min_len_cross_px=%.1f min_out_ratio=%.2f\n",
  942. e.cross_ratio_lo, e.cross_ratio_hi, e.line_angle_deg, e.min_len_track,
  943. e.min_len_cross_px, e.min_out_ratio);
  944. append_line(&out,
  945. " edge.grad_pct=%.2f texture_period=[%.2f, %.2f] near_edge_px=%.0f "
  946. "motion_hold_s=%.1f allow_state2=%d\n",
  947. e.grad_pct, e.texture_period_lo, e.texture_period_hi, e.near_edge_px,
  948. e.motion_hold_s, e.allow_state2 ? 1 : 0);
  949. append_line(&out,
  950. "边缘补充: edge.work_width=%d use_clahe=%d clahe_tiles=%d clahe_clip=%.1f "
  951. "box_is_on_left=%d strong_step_pct=%.2f\n",
  952. e.work_width, e.use_clahe ? 1 : 0, e.clahe_tiles, e.clahe_clip,
  953. e.box_is_on_left ? 1 : 0, e.strong_step_pct);
  954. append_line(&out,
  955. " edge.wall_density_max=%.2f ground_density=[%.2f, %.2f] "
  956. "ground_block_px=%.0f c1_below_ground_max=%.2f c1_span_ratio_min=%.2f\n",
  957. e.wall_density_max, e.ground_density_lo, e.ground_density_hi, e.ground_block_px,
  958. e.c1_below_ground_max, e.c1_span_ratio_min);
  959. append_line(&out,
  960. " edge.c2_col_ratio_min=%.2f c2_dark_k=%.2f p4_dark_ratio=%.2f "
  961. "contact_dark_k=%.2f\n",
  962. e.c2_col_ratio_min, e.c2_dark_k, e.p4_dark_ratio, e.contact_dark_k);
  963. append_line(&out,
  964. " edge.motion_gate=%d motion_shift_max_px=%.1f motion_blur_ratio=%.2f "
  965. "roi=[%.2f, %.2f, %.2f, %.2f]\n",
  966. e.motion_gate ? 1 : 0, e.motion_shift_max_px, e.motion_blur_ratio, e.roi_left,
  967. e.roi_top, e.roi_right, e.roi_bottom);
  968. append_line(&out,
  969. "边缘线段: edge.line.canny=[%.2f, %.2f] min_points=%d fit_tol_px=%.1f "
  970. "dir_tol_deg=%.1f thick_tol_px=%.1f\n",
  971. l.canny_lo_pct, l.canny_hi_pct, l.min_points, l.fit_tol_px, l.dir_tol_deg,
  972. l.thick_tol_px);
  973. append_line(&out,
  974. " edge.line.min_inlier_ratio=%.2f max_segments_per_blob=%d "
  975. "merge=[%.0f, %.1f, %.1f] strength_off_px=%.1f grad_pct=%.2f\n",
  976. l.min_inlier_ratio, l.max_segments_per_blob, l.merge_gap_px, l.merge_angle_deg,
  977. l.merge_offset_px, l.strength_off_px, l.grad_pct);
  978. const EdgeV2Params& v2 = cfg.evidence_v2;
  979. const V2CommitParams& vc = cfg.evidence_commit;
  980. append_line(&out,
  981. "v2证据: view=%s work_width=%d posts=[%d, %d] wall_opacity>=%.2f "
  982. "ground=[%.2f, %.2f] 箱底ROI>=%dpx 门板间距>=%.0fpx 斜撑>=%d 跨度>=%.2f\n",
  983. v2.view.c_str(), v2.work_width, v2.min_door_posts, v2.max_door_posts,
  984. v2.min_wall_opacity, v2.ground_density_lo, v2.ground_density_hi,
  985. v2.min_bed_roi_px, v2.min_post_spacing_px, v2.min_diagonal_braces,
  986. v2.min_post_span_ratio);
  987. append_line(&out,
  988. "v2平车门: 贴合亮带<=%.2f×估箱高 车面下方暗带>=%.0f灰阶 "
  989. "probe=[%.3f, %.3f]×画幅(找不到暗带不判 2)\n",
  990. v2.contact_max_h_ratio, v2.under_deck_dark_delta,
  991. v2.under_deck_min_h_ratio, v2.under_deck_search_h_ratio);
  992. append_line(&out,
  993. "v2顶部门: enable=%d grad>=%.0f block=%d hit=%.2f cov>=%.2f "
  994. "run=%d smooth=%d margin=%.2f(车体顶以上亮/暗带剔除)\n",
  995. v2.texture_top_enable ? 1 : 0, v2.texture_grad_th, v2.texture_block_px,
  996. v2.texture_block_hit_ratio, v2.texture_coverage_min, v2.texture_run_rows,
  997. v2.texture_smooth_rows, v2.texture_top_margin_ratio);
  998. append_line(&out,
  999. "v2车体兜底: enable=%d bottom=%.2f x_margin=%.2f posts=[%d,%d] "
  1000. "opacity>=%.2f roi>=%dpx canny=[%.2f,%.2f] min_points=%d "
  1001. "grad>=%.2f run_len>=%.2f×ROI post_len>=%.2f×ROI\n",
  1002. v2.body_fallback_enable ? 1 : 0, v2.body_bottom_ratio,
  1003. v2.body_x_margin_ratio, v2.body_min_posts, v2.max_door_posts,
  1004. v2.body_min_opacity, v2.body_min_roi_px, v2.body_canny_lo_pct,
  1005. v2.body_canny_hi_pct, v2.body_min_points, v2.body_grad_pct,
  1006. v2.body_run_min_len_ratio, v2.body_min_post_len_ratio);
  1007. append_line(&out,
  1008. "v2无箱兜底: 只看车体(箱底被车帮挡住时)posts=[%d,%d] span>=%.2f "
  1009. "opacity>=%.2f diag>=%d(判不出仍 255,不会猜平车)\n",
  1010. v2.body_min_posts, v2.vehicle_max_posts,
  1011. v2.vehicle_min_span_ratio, v2.body_min_opacity,
  1012. v2.min_diagonal_braces);
  1013. append_line(&out,
  1014. "v2空车: enable=%d state3_submit=%d posts=[%d,%d] span>=%.2f "
  1015. "opacity>=%.2f wall_h>=%.2f post_len>=%.2f top_margin=%.2f"
  1016. "(完整空敞车侧墙 -> 3)\n",
  1017. v2.empty_vehicle_enable ? 1 : 0, v2.allow_state3 ? 1 : 0,
  1018. v2.empty_min_posts, v2.max_door_posts, v2.empty_min_span_ratio,
  1019. v2.empty_min_opacity, v2.empty_min_wall_h_ratio,
  1020. v2.empty_min_post_len_ratio, v2.empty_top_margin_ratio);
  1021. append_line(&out,
  1022. "v2空平车: enable=%d gap>=%.0fpx 车面边缘<=%.2f 灰度降<=%.0f"
  1023. "(薄边梁+车底透空+光滑亮车面 -> 3)\n",
  1024. v2.empty_flatbed_enable ? 1 : 0, v2.empty_flatbed_min_gap_px,
  1025. v2.empty_flatbed_max_plane_edge, v2.empty_flatbed_max_gray_drop);
  1026. append_line(&out,
  1027. "v2落位: require_commit=%d gap_m<=%.2f gap_px<=%.1f stable=%d structure=%d "
  1028. "allow_state2=%d allow_state3=%d use_plc_arrival=%s\n",
  1029. v2.require_commit ? 1 : 0, vc.gap_m_max, vc.gap_px_hard_max,
  1030. vc.stable_frames, vc.structure_frames, vc.allow_state2 ? 1 : 0,
  1031. vc.allow_state3 ? 1 : 0,
  1032. vc.use_plc_arrival ? "on(⚠无信号源,等价 off)" : "off");
  1033. if (vc.use_plc_arrival) {
  1034. // 说清楚"为什么配了也不生效":PLC 命令区目前没有"开始下放/到位/
  1035. // 吊具松开"位(docs/plc_interface.md §7 第 11 条待确认),运行时
  1036. // 也就没有来源把 plc_arrived 传给 EdgeV2::analyze()。
  1037. append_line(&out,
  1038. "⚠ evidence_v2.commit.use_plc_arrival=true,但 PLC 命令区尚无"
  1039. "到位/吊具松开信号(plc_interface §7 #11),本开关当前等价于 off;"
  1040. "commit 仍只看 gap_px/gap_m。\n");
  1041. }
  1042. append_line(&out,
  1043. "v2安全门: 吊具高悬=%s dark_max=%d band_frac=%.3f line_ratio=%.2f "
  1044. "dark_ratio=%.2f bright_delta=%.0f | 夹箱=%s dark_max=%d dark_ratio=%.2f"
  1045. "(命中即弃权且不累计 commit 窗口)\n",
  1046. v2.reject_hoist_high ? "on" : "off", v2.hoist.dark_max, v2.hoist.band_frac,
  1047. v2.hoist.line_ratio, v2.hoist.dark_ratio, v2.hoist.bright_delta,
  1048. v2.reject_spreader_contact ? "on" : "off", v2.spreader.dark_max,
  1049. v2.spreader.dark_ratio);
  1050. append_line(&out,
  1051. "标定配置: calibration.record=%s stale=%d max_age_days=%.0f px_per_m_tol=%.2f "
  1052. "box_height_tol=%.3fm hold_on_stale=%d(判定结果见下一行)\n",
  1053. cfg.calibration.record.empty() ? "(未配置)" : cfg.calibration.record.c_str(),
  1054. cfg.calibration.stale ? 1 : 0, cfg.calibration.max_age_days,
  1055. cfg.calibration.px_per_m_tolerance, cfg.calibration.box_height_tolerance_m,
  1056. cfg.calibration.hold_on_stale ? 1 : 0);
  1057. append_line(&out, "命令行: --edge-demo=%s publish_edge_flags=%s\n", cfg.edge_demo.c_str(),
  1058. cfg.publish_edge_flags ? "deprecated(诊断只写 reserved)" : "off(默认;bit8~12 为标准健康位)");
  1059. return out;
  1060. }
  1061. } // namespace portcv