| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117 |
- // 现场配置 → C++ 运行参数的实现(见 include/portcv/app_config.hpp)。
- //
- // 实现选择:**表驱动的显式绑定**,而不是"反射"或代码生成。
- // * 绑定表就是"配置键 ↔ C++ 字段"的**唯一权威清单**,一眼能看完,评审时无需跳文件;
- // * 生成器(scripts/gen_cpp_constants.py)负责的是**寄存器契约**(布局/CRC/flags/默认参数),
- // 它不认识 EdgeParams 这种纯 C++ 结构,所以参数绑定留在 C++ 侧更诚实;
- // * 类型错 / 缺元素 / 越界 → 一律返回 false(main 直接退出并打印错误行号),
- // 绝不"部分生效":现场宁可不启动,也不要带着半套参数去指挥吊装。
- #include "portcv/app_config.hpp"
- #include <cstdarg>
- #include <cstdint>
- #include <cstdio>
- #include <string>
- #include <utility>
- #include <vector>
- #include "portcv/json_lite.hpp"
- namespace portcv {
- namespace {
- /// 绑定类型(决定"该键在 JSON 里应该长什么样")。
- enum class Kind { Number, Integer, Flag, Text, U16, U8, NumberPair, TextList, Points };
- /// 一条"配置键 → C++ 字段"的绑定。用工厂函数构造(见下),避免一长串 nullptr。
- struct Binding {
- const char* key = nullptr;
- Kind kind = Kind::Number;
- double* num = nullptr; ///< Kind::Number
- double* num2 = nullptr; ///< Kind::Number 的联动目标
- int* integer = nullptr; ///< Kind::Integer
- bool* flag = nullptr; ///< Kind::Flag
- std::string* text = nullptr; ///< Kind::Text
- uint16_t* u16 = nullptr; ///< Kind::U16
- uint8_t* u8 = nullptr; ///< Kind::U8
- std::vector<double*>* pair = nullptr; ///< Kind::NumberPair(恰好 2 个元素)
- std::vector<std::string>* texts = nullptr; ///< Kind::TextList
- std::vector<Point>* points = nullptr; ///< Kind::Points
- };
- Binding num(const char* key, double* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::Number;
- b.num = dst;
- return b;
- }
- /// 数字绑定,但一个键写两个字段(`edge.grad_pct` → EdgeParams::grad_pct + LineParams::grad_pct)。
- Binding num2(const char* key, double* dst, double* mirror) {
- Binding b = num(key, dst);
- b.num2 = mirror;
- return b;
- }
- Binding integer(const char* key, int* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::Integer;
- b.integer = dst;
- return b;
- }
- Binding flag(const char* key, bool* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::Flag;
- b.flag = dst;
- return b;
- }
- Binding text(const char* key, std::string* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::Text;
- b.text = dst;
- return b;
- }
- Binding u16(const char* key, uint16_t* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::U16;
- b.u16 = dst;
- return b;
- }
- Binding u8(const char* key, uint8_t* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::U8;
- b.u8 = dst;
- return b;
- }
- Binding pair(const char* key, std::vector<double*>* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::NumberPair;
- b.pair = dst;
- return b;
- }
- Binding text_list(const char* key, std::vector<std::string>* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::TextList;
- b.texts = dst;
- return b;
- }
- Binding point_list(const char* key, std::vector<Point>* dst) {
- Binding b;
- b.key = key;
- b.kind = Kind::Points;
- b.points = dst;
- return b;
- }
- /// 统一的错误文案:把"哪一项 / 实际是什么类型"写清楚,现场照着改即可。
- bool type_error(std::string* error, const char* key, const json::Value& value, const char* want) {
- if (error != nullptr) {
- *error = std::string("配置项 ") + key + " 类型不对:需要 " + want + ",实际是 " +
- value.type_name();
- }
- return false;
- }
- /// 依次套用绑定:**只有键存在时才覆盖**(= Python 的深合并效果),其余保持结构体默认值。
- bool apply(const Config& cfg, const std::vector<Binding>& bindings, std::string* error) {
- for (const Binding& b : bindings) {
- if (b.key == nullptr || !cfg.has(b.key)) { continue; }
- const json::Value& v = cfg.get(b.key);
- switch (b.kind) {
- case Kind::Number: {
- if (!v.is_number()) { return type_error(error, b.key, v, "数字"); }
- *b.num = v.number;
- if (b.num2 != nullptr) { *b.num2 = v.number; }
- break;
- }
- case Kind::Integer: {
- if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
- const double x = v.number;
- *b.integer = static_cast<int>(x < 0.0 ? x - 0.5 : x + 0.5);
- break;
- }
- case Kind::Flag: {
- if (!v.is_bool() && !v.is_number()) {
- return type_error(error, b.key, v, "true / false");
- }
- *b.flag = v.is_bool() ? v.boolean : (v.number != 0.0);
- break;
- }
- case Kind::Text: {
- if (!v.is_string()) { return type_error(error, b.key, v, "字符串"); }
- *b.text = v.text;
- break;
- }
- case Kind::U16: {
- if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
- if (v.number < 0.0 || v.number > 65535.0) {
- if (error != nullptr) {
- *error = std::string("配置项 ") + b.key + " 超出 0~65535(Modbus 地址/端口)";
- }
- return false;
- }
- *b.u16 = static_cast<uint16_t>(v.number);
- break;
- }
- case Kind::U8: {
- if (!v.is_number()) { return type_error(error, b.key, v, "整数"); }
- if (v.number < 0.0 || v.number > 255.0) {
- if (error != nullptr) {
- *error = std::string("配置项 ") + b.key + " 超出 0~255(单元号)";
- }
- return false;
- }
- *b.u8 = static_cast<uint8_t>(v.number);
- break;
- }
- case Kind::NumberPair: {
- if (!v.is_array()) { return type_error(error, b.key, v, "[数字, 数字]"); }
- if (v.items.size() != b.pair->size()) {
- if (error != nullptr) {
- *error = std::string("配置项 ") + b.key + " 需要 " +
- std::to_string(b.pair->size()) + " 个数字,实际 " +
- std::to_string(v.items.size()) + " 个";
- }
- return false;
- }
- for (std::size_t i = 0; i < v.items.size(); ++i) {
- if (!v.items[i].is_number()) {
- return type_error(error, b.key, v.items[i], "数字");
- }
- *(*b.pair)[i] = v.items[i].number;
- }
- break;
- }
- case Kind::TextList: {
- if (!v.is_array()) { return type_error(error, b.key, v, "字符串数组"); }
- b.texts->clear();
- b.texts->reserve(v.items.size());
- for (const json::Value& item : v.items) {
- if (!item.is_string()) { return type_error(error, b.key, item, "字符串"); }
- b.texts->push_back(item.text);
- }
- break;
- }
- case Kind::Points: {
- if (!v.is_array()) { return type_error(error, b.key, v, "点列 [[x, y], ...]"); }
- b.points->clear();
- b.points->reserve(v.items.size());
- for (const json::Value& item : v.items) {
- const bool shaped = item.is_array() && item.items.size() >= 2 &&
- item.items[0].is_number() && item.items[1].is_number();
- if (!shaped) { return type_error(error, b.key, item, "[x, y] 形式的点"); }
- b.points->push_back(Point(item.items[0].number, item.items[1].number));
- }
- break;
- }
- }
- }
- return true;
- }
- // ---------------------------------------------------------------- 各段的绑定表
- // 说明:每个段的绑定表就是该段的"配置键清单";新增键时请同步
- // docs/deployment.md §2.5 的键表与 configs/edge-cpp.json 模板。
- bool apply_run(const Config& cfg, AppConfig* out, std::string* error) {
- const std::vector<Binding> bindings = {
- text("run.backend", &out->backend),
- num("run.max_fps", &out->max_fps),
- integer("run.warmup_frames", &out->warmup_frames),
- };
- return apply(cfg, bindings, error);
- }
- bool apply_plc(const Config& cfg, AppConfig* out, std::string* error) {
- int gating_timeout_ms = static_cast<int>(out->gating_timeout_s * 1000.0);
- const std::vector<Binding> bindings = {
- flag("plc.enabled", &out->plc_enabled),
- flag("plc.gating", &out->gating),
- integer("plc.gating_timeout_ms", &gating_timeout_ms),
- text("plc.modbus.host", &out->modbus.host),
- u16("plc.modbus.port", &out->modbus.port),
- u8("plc.modbus.unit_id", &out->modbus.unit_id),
- u16("plc.modbus.input_addr", &out->modbus.input_addr),
- u16("plc.modbus.holding_addr", &out->modbus.holding_addr),
- flag("plc.modbus.allow_unit_any", &out->modbus.allow_unit_any),
- };
- if (!apply(cfg, bindings, error)) { return false; }
- out->gating_timeout_s = std::max(0.05, gating_timeout_ms / 1000.0);
- return true;
- }
- /// 取流(`source.*`):键名与 Python `portcv/config.py` DEFAULTS 的 source 段**逐字相同**,
- /// 语义与 `portcv/io/capture.py` 的 FrameGrabber 一致 —— 现场只维护一份配置文件。
- /// 最后两项是 C++ 侧实现级补充键(Python 没有;只影响 synth 源)。
- bool apply_source(const Config& cfg, AppConfig* out, std::string* error) {
- SourceConfig* s = &out->source;
- int synth_seed = static_cast<int>(s->synth_seed);
- const std::vector<Binding> bindings = {
- text("source.type", &s->type),
- text("source.uri", &s->uri),
- integer("source.width", &s->width),
- integer("source.height", &s->height),
- integer("source.buffer_size", &s->buffer_size),
- num("source.reconnect_s", &s->reconnect_s),
- num("source.stale_frame_s", &s->stale_frame_s),
- flag("source.loop", &s->loop),
- num("source.synth_shift_px", &s->synth_shift_px),
- integer("source.synth_seed", &synth_seed),
- };
- if (!apply(cfg, bindings, error)) { return false; }
- s->synth_seed = static_cast<uint32_t>(synth_seed < 0 ? 0 : synth_seed);
- return true;
- }
- bool apply_scene(const Config& cfg, AppConfig* out, std::string* error) {
- SceneParams* s = &out->scene;
- const std::vector<Binding> bindings = {
- text("scene.mode", &s->mode),
- text_list("scene.classes.container", &s->container_names),
- text_list("scene.classes.bed", &s->bed_names),
- text_list("scene.classes.flatbed", &s->flatbed_names),
- text_list("scene.classes.ignore", &s->ignore_names),
- point_list("scene.roi", &s->roi),
- flag("scene.require_container", &s->require_container),
- num("scene.min_class_conf", &s->min_class_conf),
- num("scene.roi_min_ratio", &s->roi_min_ratio),
- num("scene.support_overlap", &s->support_overlap),
- num("scene.support_dy_ratio", &s->support_dy_ratio),
- num("scene.support_score_ratio", &s->support_score_ratio),
- flag("scene.unknown_on_no_detection", &s->unknown_on_no_detection),
- num("scene.no_container_conf", &s->no_container_conf),
- };
- if (!apply(cfg, bindings, error)) { return false; }
- // direct_map:`{类别名: 场景编码}`(与 Python 同名同义,形状特殊故单独处理)
- if (cfg.has("scene.direct_map")) {
- const json::Value& map = cfg.get("scene.direct_map");
- if (!map.is_object()) {
- return type_error(error, "scene.direct_map", map, "对象 {类别名: 编码}");
- }
- s->direct_map.clear();
- for (const auto& kv : map.members) {
- if (!kv.second.is_number()) {
- return type_error(error, "scene.direct_map", kv.second, "整数编码");
- }
- const double code = kv.second.number;
- s->direct_map[kv.first] = static_cast<int>(code < 0.0 ? code - 0.5 : code + 0.5);
- }
- }
- // scene.mode 缺省时用 run.mode 兜底(Python 侧这两个键也互为双保险)
- if (!cfg.has("scene.mode") && cfg.has("run.mode")) {
- const json::Value& v = cfg.get("run.mode");
- if (!v.is_string()) { return type_error(error, "run.mode", v, "字符串"); }
- s->mode = v.text;
- }
- return true;
- }
- bool apply_voter(const Config& cfg, AppConfig* out, std::string* error) {
- VoterParams* d = &out->voter;
- const std::vector<Binding> bindings = {
- integer("decision.window", &d->window),
- num("decision.window_s", &d->window_s),
- integer("decision.min_votes", &d->min_votes),
- num("decision.min_confidence", &d->min_confidence),
- num("decision.min_dwell_s", &d->min_dwell_s),
- num("decision.hold_s", &d->hold_s),
- num("decision.lost_timeout_s", &d->lost_timeout_s),
- // 发布侧用(投票器不读):实测 fps 低于它 → 置 flags.LOW_FPS(bit3)。
- // 键名与 Python 同;写了阈值才生效,不写就用默认 3.0。
- num("decision.low_fps_threshold", &out->low_fps_threshold),
- };
- return apply(cfg, bindings, error);
- }
- bool apply_edge(const Config& cfg, AppConfig* out, std::string* error) {
- EdgeParams* e = &out->edge;
- // 成对参数(§7 表里写作 `[下限, 上限]`):本地 vector 必须在 apply 调用期间存活
- std::vector<double*> band_high{&e->band_high_lo, &e->band_high_hi};
- std::vector<double*> band_low{&e->band_low_lo, &e->band_low_hi};
- std::vector<double*> gap_band{&e->gap_band_lo, &e->gap_band_hi};
- std::vector<double*> cross_ratio{&e->cross_ratio_lo, &e->cross_ratio_hi};
- std::vector<double*> texture_period{&e->texture_period_lo, &e->texture_period_hi};
- const std::vector<Binding> bindings = {
- // ---- docs/edge_evidence.md §7(现场只调这一组)----
- num("edge.box_height_m", &e->box_height_m),
- pair("edge.band_high", &band_high),
- pair("edge.band_low", &band_low),
- pair("edge.gap_band", &gap_band),
- pair("edge.cross_ratio", &cross_ratio),
- num("edge.line_angle_deg", &e->line_angle_deg),
- num("edge.min_len_track", &e->min_len_track),
- num("edge.min_len_cross_px", &e->min_len_cross_px),
- num("edge.min_out_ratio", &e->min_out_ratio),
- num2("edge.grad_pct", &e->grad_pct, &out->line.grad_pct),
- pair("edge.texture_period", &texture_period),
- num("edge.near_edge_px", &e->near_edge_px),
- num("edge.motion_hold_s", &e->motion_hold_s),
- flag("edge.allow_state2", &e->allow_state2),
- // ---- 实现级补充键(§7 未列;现场整定后再并入 §7)----
- integer("edge.work_width", &e->work_width),
- flag("edge.use_clahe", &e->use_clahe),
- integer("edge.clahe_tiles", &e->clahe_tiles),
- num("edge.clahe_clip", &e->clahe_clip),
- flag("edge.box_is_on_left", &e->box_is_on_left),
- num("edge.strong_step_pct", &e->strong_step_pct),
- num("edge.wall_density_max", &e->wall_density_max),
- num("edge.ground_density_lo", &e->ground_density_lo),
- num("edge.ground_density_hi", &e->ground_density_hi),
- num("edge.ground_block_px", &e->ground_block_px),
- num("edge.c1_below_ground_max", &e->c1_below_ground_max),
- num("edge.c1_span_ratio_min", &e->c1_span_ratio_min),
- num("edge.c2_col_ratio_min", &e->c2_col_ratio_min),
- num("edge.c2_dark_k", &e->c2_dark_k),
- num("edge.p4_dark_ratio", &e->p4_dark_ratio),
- num("edge.contact_dark_k", &e->contact_dark_k),
- num("edge.motion_shift_max_px", &e->motion_shift_max_px),
- num("edge.motion_blur_ratio", &e->motion_blur_ratio),
- flag("edge.motion_gate", &e->motion_gate),
- num("edge.roi_left", &e->roi_left),
- num("edge.roi_right", &e->roi_right),
- num("edge.roi_top", &e->roi_top),
- num("edge.roi_bottom", &e->roi_bottom),
- };
- return apply(cfg, bindings, error);
- }
- /// 线段提取(L2)参数:不在 §7 表内,只有现场确实需要时才改。
- bool apply_line(const Config& cfg, AppConfig* out, std::string* error) {
- LineParams* l = &out->line;
- const std::vector<Binding> bindings = {
- num("edge.line.canny_lo_pct", &l->canny_lo_pct),
- num("edge.line.canny_hi_pct", &l->canny_hi_pct),
- integer("edge.line.min_points", &l->min_points),
- num("edge.line.fit_tol_px", &l->fit_tol_px),
- num("edge.line.dir_tol_deg", &l->dir_tol_deg),
- num("edge.line.thick_tol_px", &l->thick_tol_px),
- num("edge.line.min_inlier_ratio", &l->min_inlier_ratio),
- integer("edge.line.max_segments_per_blob", &l->max_segments_per_blob),
- num("edge.line.merge_gap_px", &l->merge_gap_px),
- num("edge.line.merge_angle_deg", &l->merge_angle_deg),
- num("edge.line.merge_offset_px", &l->merge_offset_px),
- num("edge.line.strength_off_px", &l->strength_off_px),
- num("edge.line.grad_pct", &l->grad_pct),
- };
- return apply(cfg, bindings, error);
- }
- bool apply_evidence_v2(const Config& cfg, AppConfig* out, std::string* error) {
- EdgeV2Params* v = &out->evidence_v2;
- V2CommitParams* c = &out->evidence_commit;
- const std::vector<Binding> bindings = {
- text("evidence_v2.view", &v->view),
- integer("evidence_v2.work_width", &v->work_width),
- integer("evidence_v2.band_min_h", &v->band_min_h),
- num("evidence_v2.band_max_h_ratio", &v->band_max_h_ratio),
- num("evidence_v2.canny_lo_pct", &v->canny_lo_pct),
- num("evidence_v2.canny_hi_pct", &v->canny_hi_pct),
- num("evidence_v2.bed_search_ratio", &v->bed_search_ratio),
- num("evidence_v2.box_bottom_max_ratio", &v->box_bottom_max_ratio),
- num("evidence_v2.below_start_ratio", &v->below_start_ratio),
- num("evidence_v2.below_height_ratio", &v->below_height_ratio),
- integer("evidence_v2.below_min_height_px", &v->below_min_height_px),
- integer("evidence_v2.min_door_posts", &v->min_door_posts),
- integer("evidence_v2.max_door_posts", &v->max_door_posts),
- num("evidence_v2.max_bed_gap_px", &v->max_bed_gap_px),
- integer("evidence_v2.flat_max_door_posts", &v->flat_max_door_posts),
- num("evidence_v2.max_post_spacing_cv", &v->max_post_spacing_cv),
- num("evidence_v2.min_post_len_ratio", &v->min_post_len_ratio),
- num("evidence_v2.min_post_spacing_px", &v->min_post_spacing_px),
- integer("evidence_v2.min_diagonal_braces", &v->min_diagonal_braces),
- num("evidence_v2.min_post_span_ratio", &v->min_post_span_ratio),
- flag("evidence_v2.texture_top_enable", &v->texture_top_enable),
- num("evidence_v2.texture_grad_th", &v->texture_grad_th),
- integer("evidence_v2.texture_block_px", &v->texture_block_px),
- num("evidence_v2.texture_block_hit_ratio", &v->texture_block_hit_ratio),
- num("evidence_v2.texture_coverage_min", &v->texture_coverage_min),
- integer("evidence_v2.texture_run_rows", &v->texture_run_rows),
- integer("evidence_v2.texture_smooth_rows", &v->texture_smooth_rows),
- num("evidence_v2.texture_top_margin_ratio", &v->texture_top_margin_ratio),
- flag("evidence_v2.body_fallback_enable", &v->body_fallback_enable),
- num("evidence_v2.body_bottom_ratio", &v->body_bottom_ratio),
- num("evidence_v2.body_min_opacity", &v->body_min_opacity),
- integer("evidence_v2.body_min_roi_px", &v->body_min_roi_px),
- num("evidence_v2.body_canny_lo_pct", &v->body_canny_lo_pct),
- num("evidence_v2.body_canny_hi_pct", &v->body_canny_hi_pct),
- integer("evidence_v2.body_min_points", &v->body_min_points),
- num("evidence_v2.body_grad_pct", &v->body_grad_pct),
- num("evidence_v2.body_min_inlier_ratio", &v->body_min_inlier_ratio),
- num("evidence_v2.body_run_min_len_ratio", &v->body_run_min_len_ratio),
- num("evidence_v2.body_min_post_len_ratio", &v->body_min_post_len_ratio),
- num("evidence_v2.body_x_margin_ratio", &v->body_x_margin_ratio),
- integer("evidence_v2.body_min_posts", &v->body_min_posts),
- num("evidence_v2.vehicle_min_span_ratio", &v->vehicle_min_span_ratio),
- integer("evidence_v2.vehicle_max_posts", &v->vehicle_max_posts),
- flag("evidence_v2.empty_vehicle_enable", &v->empty_vehicle_enable),
- integer("evidence_v2.empty_min_posts", &v->empty_min_posts),
- num("evidence_v2.empty_min_span_ratio", &v->empty_min_span_ratio),
- num("evidence_v2.empty_min_opacity", &v->empty_min_opacity),
- num("evidence_v2.empty_min_wall_h_ratio", &v->empty_min_wall_h_ratio),
- num("evidence_v2.empty_min_post_len_ratio", &v->empty_min_post_len_ratio),
- integer("evidence_v2.empty_fallback_max_posts", &v->empty_fallback_max_posts),
- integer("evidence_v2.empty_min_diagonal_braces", &v->empty_min_diagonal_braces),
- flag("evidence_v2.empty_flatbed_enable", &v->empty_flatbed_enable),
- num("evidence_v2.empty_flatbed_min_gap_px", &v->empty_flatbed_min_gap_px),
- num("evidence_v2.empty_flatbed_max_plane_edge", &v->empty_flatbed_max_plane_edge),
- num("evidence_v2.empty_flatbed_max_gray_drop", &v->empty_flatbed_max_gray_drop),
- num("evidence_v2.empty_top_margin_ratio", &v->empty_top_margin_ratio),
- flag("evidence_v2.allow_state3", &v->allow_state3),
- num("evidence_v2.min_wall_opacity", &v->min_wall_opacity),
- num("evidence_v2.wall_edge_density_ref", &v->wall_edge_density_ref),
- num("evidence_v2.wall_edge_density_span", &v->wall_edge_density_span),
- integer("evidence_v2.ground_block_px", &v->ground_block_px),
- num("evidence_v2.ground_density_lo", &v->ground_density_lo),
- num("evidence_v2.ground_density_hi", &v->ground_density_hi),
- num("evidence_v2.min_zero_ground_ratio", &v->min_zero_ground_ratio),
- num("evidence_v2.deck_min_len_ratio", &v->deck_min_len_ratio),
- num("evidence_v2.contact_max_h_ratio", &v->contact_max_h_ratio),
- num("evidence_v2.under_deck_dark_delta", &v->under_deck_dark_delta),
- num("evidence_v2.under_deck_min_h_ratio", &v->under_deck_min_h_ratio),
- num("evidence_v2.under_deck_search_h_ratio", &v->under_deck_search_h_ratio),
- num("evidence_v2.max_flat_gap_px", &v->max_flat_gap_px),
- num("evidence_v2.box_height_m", &v->box_height_m),
- num("evidence_v2.px_per_m", &v->px_per_m),
- num("evidence_v2.min_scale_px", &v->min_scale_px),
- num("evidence_v2.motion_diff_max", &v->motion_diff_max),
- num("evidence_v2.motion_grad_ratio_min", &v->motion_grad_ratio_min),
- flag("evidence_v2.require_commit", &v->require_commit),
- flag("evidence_v2.allow_state2", &v->allow_state2),
- num("evidence_v2.structure_hits_min", &v->structure_hits_min),
- integer("evidence_v2.min_bed_roi_px", &v->min_bed_roi_px),
- // P0-0 图像侧安全门(键名与 Python `evidence_v2.*` 逐字相同)
- flag("evidence_v2.reject_hoist_high", &v->reject_hoist_high),
- integer("evidence_v2.hoist_dark_max", &v->hoist.dark_max),
- num("evidence_v2.hoist_band_frac", &v->hoist.band_frac),
- num("evidence_v2.hoist_line_ratio", &v->hoist.line_ratio),
- num("evidence_v2.hoist_dark_ratio", &v->hoist.dark_ratio),
- num("evidence_v2.hoist_bright_delta", &v->hoist.bright_delta),
- flag("evidence_v2.reject_spreader_contact", &v->reject_spreader_contact),
- integer("evidence_v2.spreader_dark_max", &v->spreader.dark_max),
- num("evidence_v2.spreader_dark_ratio", &v->spreader.dark_ratio),
- num("evidence_v2.commit.gap_m_max", &c->gap_m_max),
- num("evidence_v2.commit.gap_px_hard_max", &c->gap_px_hard_max),
- integer("evidence_v2.commit.stable_frames", &c->stable_frames),
- integer("evidence_v2.commit.structure_frames", &c->structure_frames),
- num("evidence_v2.commit.min_structure_hits", &c->min_structure_hits),
- num("evidence_v2.commit.max_gap_rise_m", &c->max_gap_rise_m),
- flag("evidence_v2.commit.allow_state1", &c->allow_state1),
- flag("evidence_v2.commit.allow_state2", &c->allow_state2),
- flag("evidence_v2.commit.allow_state3", &c->allow_state3),
- flag("evidence_v2.commit.require_motion_ok", &c->require_motion_ok),
- flag("evidence_v2.commit.require_view_known", &c->require_view_known),
- flag("evidence_v2.commit.use_plc_arrival", &c->use_plc_arrival),
- };
- if (!apply(cfg, bindings, error)) { return false; }
- // window 是 4 个归一化数字,Binding 只有 NumberPair,单独解析。
- if (cfg.has("evidence_v2.window")) {
- const json::Value& v4 = cfg.get("evidence_v2.window");
- if (!v4.is_array() || v4.items.size() != 4) {
- return type_error(error, "evidence_v2.window", v4, "4 个数字 [x0,y0,x1,y1]");
- }
- for (int i = 0; i < 4; ++i) {
- if (!v4.items[static_cast<std::size_t>(i)].is_number()) {
- return type_error(error, "evidence_v2.window", v4.items[static_cast<std::size_t>(i)], "数字");
- }
- v->window[i] = v4.items[static_cast<std::size_t>(i)].number;
- }
- }
- // 两个 allow_state2 开关**串联**(默认都 true):任一显式为 false 都会关闭 2 的提交。
- // 顶层键保留为模板可读性 / 旧模板兼容;这样现场只改一处也不会被另一处静默覆盖。
- c->allow_state2 = c->allow_state2 && v->allow_state2;
- v->allow_state2 = c->allow_state2;
- // P0-Q9:allow_state3(空车 3)同构串联。
- c->allow_state3 = c->allow_state3 && v->allow_state3;
- v->allow_state3 = c->allow_state3;
- return true;
- }
- // ---------------------------------------------------------------- 标定记录(P0-5)
- // 只解析"判定所需的四件事":记录路径 / 有效期 / 两个漂移容差 / 手工开关。
- // **不做文件存在性校验**:文件缺失不是"配置错",而是运行期 `CALIB_STALE`(现场
- // 拷贝漏了记录文件也要能起来、并在日志与 flags 上大声报警,而不是静默按默认值跑)。
- bool apply_calibration(const Config& cfg, AppConfig* out, std::string* error) {
- CalibrationConfig* c = &out->calibration;
- const std::vector<Binding> bindings = {
- flag("calibration.stale", &c->stale),
- text("calibration.record", &c->record),
- num("calibration.max_age_days", &c->max_age_days),
- num("calibration.px_per_m_tolerance", &c->px_per_m_tolerance),
- num("calibration.box_height_tolerance_m", &c->box_height_tolerance_m),
- // 新增键(C++/Python 同名同义):标定不可信时是否清 RESULT_VALID/STABLE
- flag("calibration.hold_on_stale", &c->hold_on_stale),
- };
- return apply(cfg, bindings, error);
- }
- // ---------------------------------------------------------------- 取值校验
- // 原则:**能判出来的错都在启动时判**。现场宁可"起不来 + 一行明确原因",
- // 也不要"起来了但参数是半套"——那会直接变成吊装动作的依据。
- bool validate(const AppConfig* cfg, std::string* error) {
- const auto bad = [error](const std::string& what) {
- if (error != nullptr) { *error = what; }
- return false;
- };
- if (cfg->backend.empty()) { return bad("run.backend 不能为空(mock / edge / edge-v2)"); }
- // 同上:`!(x > 0)` 才挡得住 NaN(JSON 字面量写不出 NaN,但 1e400 → inf 之类的
- // 溢出值会走到这里,防御性写法保持两条路径同口径)。
- if (!(cfg->max_fps > 0.0) || cfg->max_fps > 240.0) {
- return bad("run.max_fps 必须 ∈ (0, 240]");
- }
- if (cfg->warmup_frames < 0) { return bad("run.warmup_frames 不能为负"); }
- // ---- 取流(source.*):类型不认识 / 取值非法一律**启动即失败** ----
- // 注意:这里**只做语法层校验**(不认识 `gst/rtsp/file/usb` 是配置错误);
- // "本次构建有没有编进 GStreamer"属于**运行期能力**,放到 main 建源时报错 ——
- // 这样 `--check-config`(以及 configs/default.json 的加载)在纯算法机上也能跑。
- const SourceConfig& src = cfg->source;
- if (!source_type_known(src.type)) {
- return bad("source.type=\"" + src.type + "\" 不认识。\n" + source_type_help());
- }
- if (src.type != "none" && src.type != "synth" && src.uri.empty()) {
- return bad("source.type=" + src.type +
- " 必须给 source.uri(相机地址 / 视频文件 / PGM 目录 / 管线字符串)");
- }
- if (src.uri.find('"') != std::string::npos) {
- return bad("source.uri 不能包含双引号(会破坏 GStreamer 管线解析)");
- }
- if (src.type == "synth" && !synth_scene_known(src.uri)) {
- return bad("source.uri=\"" + src.uri +
- "\" 不是合成场景名;可用 gondola / flatbed / ground / empty(留空 = gondola)");
- }
- if (src.width < 0 || src.height < 0) { return bad("source.width / source.height 不能为负"); }
- if (src.buffer_size < 0) { return bad("source.buffer_size 不能为负(0 = 不设缓冲上限)"); }
- if (src.reconnect_s <= 0.0) { return bad("source.reconnect_s 必须 > 0"); }
- if (src.stale_frame_s <= 0.0) {
- return bad("source.stale_frame_s 必须 > 0(它是 FRAME_TIMEOUT 的判据)");
- }
- if (src.synth_shift_px < 0.0) { return bad("source.synth_shift_px 不能为负"); }
- const EdgeParams& e = cfg->edge;
- if (e.box_height_m <= 0.0) {
- return bad("edge.box_height_m 必须 > 0(自标尺基准:近端竖棱像素 / 箱高)");
- }
- if (e.band_high_lo > e.band_high_hi) { return bad("edge.band_high 需要 [下限, 上限]"); }
- if (e.band_low_lo > e.band_low_hi) { return bad("edge.band_low 需要 [下限, 上限]"); }
- if (e.gap_band_lo > e.gap_band_hi) { return bad("edge.gap_band 需要 [下限, 上限]"); }
- if (e.cross_ratio_lo > e.cross_ratio_hi) { return bad("edge.cross_ratio 需要 [下限, 上限]"); }
- if (e.texture_period_lo > e.texture_period_hi) {
- return bad("edge.texture_period 需要 [下限, 上限]");
- }
- if (e.near_edge_px < 0.0) { return bad("edge.near_edge_px 不能为负"); }
- if (e.motion_hold_s < 0.0) { return bad("edge.motion_hold_s 不能为负"); }
- if (e.work_width < 64) {
- return bad("edge.work_width 至少 64(证据阈值都是在 ~960 px 长边上整定的)");
- }
- if (e.clahe_tiles < 1) { return bad("edge.clahe_tiles 至少 1"); }
- if (cfg->line.min_points < 2) { return bad("edge.line.min_points 至少 2"); }
- if (cfg->line.max_segments_per_blob < 1) {
- return bad("edge.line.max_segments_per_blob 至少 1");
- }
- if (cfg->line.canny_lo_pct < 0.0 || cfg->line.canny_lo_pct > 1.0 ||
- cfg->line.canny_hi_pct < 0.0 || cfg->line.canny_hi_pct > 1.0) {
- return bad("edge.line.canny_*_pct 必须 ∈ [0, 1]");
- }
- if (cfg->line.canny_lo_pct > cfg->line.canny_hi_pct) {
- return bad("edge.line.canny_lo_pct 不能大于 canny_hi_pct");
- }
- const VoterParams& v = cfg->voter;
- if (v.window < 1) { return bad("decision.window 至少 1"); }
- if (v.min_votes < 1 || v.min_votes > v.window) {
- return bad("decision.min_votes 必须 ∈ [1, decision.window]");
- }
- if (v.window_s <= 0.0) { return bad("decision.window_s 必须 > 0"); }
- if (v.min_confidence < 0.0 || v.min_confidence > 1.0) {
- return bad("decision.min_confidence 必须 ∈ [0, 1]");
- }
- if (v.min_dwell_s < 0.0 || v.hold_s < 0.0 || v.lost_timeout_s < 0.0) {
- return bad("decision.min_dwell_s / hold_s / lost_timeout_s 不能为负");
- }
- if (v.hold_s > v.lost_timeout_s) {
- return bad("decision.hold_s 不应大于 lost_timeout_s(否则永远等到超时才置 255)");
- }
- const SceneParams& s = cfg->scene;
- if (s.mode != "composed" && s.mode != "direct") {
- return bad("scene.mode 只能是 composed / direct,实际是 \"" + s.mode + "\"");
- }
- if (s.min_class_conf < 0.0 || s.min_class_conf > 1.0) {
- return bad("scene.min_class_conf 必须 ∈ [0, 1]");
- }
- if (s.roi.size() < 3) { return bad("scene.roi 至少需要 3 个点(多边形)"); }
- if (s.container_names.empty()) { return bad("scene.classes.container 不能为空"); }
- if (s.bed_names.empty() || s.flatbed_names.empty()) {
- return bad("scene.classes.bed / scene.classes.flatbed 不能为空");
- }
- const EdgeV2Params& v2 = cfg->evidence_v2;
- if (v2.view != "front" && v2.view != "high" && v2.view != "unknown") {
- return bad("evidence_v2.view 只能是 front / high / unknown");
- }
- if (v2.work_width < 160) { return bad("evidence_v2.work_width 至少 160"); }
- if (v2.band_min_h < 1) { return bad("evidence_v2.band_min_h 至少 1"); }
- if (!(v2.band_max_h_ratio > 0.0 && v2.band_max_h_ratio <= 1.0)) {
- return bad("evidence_v2.band_max_h_ratio 必须 ∈ (0,1]");
- }
- if (v2.min_door_posts < 1 || v2.max_door_posts < v2.min_door_posts) {
- return bad("evidence_v2.min_door_posts / max_door_posts 非法");
- }
- if (v2.flat_max_door_posts < 1) {
- return bad("evidence_v2.flat_max_door_posts 至少 1");
- }
- if (v2.box_height_m <= 0.0) { return bad("evidence_v2.box_height_m 必须 > 0"); }
- if (v2.px_per_m < 0.0) { return bad("evidence_v2.px_per_m 不能为负(0=自标尺)"); }
- // P0-0 安全门参数:这些值只影响“命中多严”,不改变“命中即弃权”的语义;
- // 写错(例如 dark_max=0 或 band_frac=0)会让门永远不触发 —— 那比报错更危险,
- // 所以一律启动即失败。
- if (v2.hoist.dark_max <= 0 || v2.hoist.dark_max >= 255) {
- return bad("evidence_v2.hoist_dark_max 必须 ∈ (0, 255)");
- }
- if (!(v2.hoist.band_frac > 0.0 && v2.hoist.band_frac <= 0.5)) {
- return bad("evidence_v2.hoist_band_frac 必须 ∈ (0, 0.5]");
- }
- if (!(v2.hoist.line_ratio > 0.0 && v2.hoist.line_ratio <= 1.0)) {
- return bad("evidence_v2.hoist_line_ratio 必须 ∈ (0, 1]");
- }
- if (v2.hoist.dark_ratio < 0.0 || v2.hoist.dark_ratio > 1.0) {
- return bad("evidence_v2.hoist_dark_ratio 必须 ∈ [0, 1]");
- }
- if (v2.hoist.bright_delta < 0.0) {
- return bad("evidence_v2.hoist_bright_delta 不能为负");
- }
- if (v2.spreader.dark_max <= 0 || v2.spreader.dark_max >= 255) {
- return bad("evidence_v2.spreader_dark_max 必须 ∈ (0, 255)");
- }
- if (v2.spreader.dark_ratio < 0.0 || v2.spreader.dark_ratio > 1.0) {
- return bad("evidence_v2.spreader_dark_ratio 必须 ∈ [0, 1]");
- }
- if (v2.min_wall_opacity < 0.0 || v2.min_wall_opacity > 1.0) {
- return bad("evidence_v2.min_wall_opacity 必须 ∈ [0,1]");
- }
- if (v2.min_post_spacing_px < 0.0) {
- return bad("evidence_v2.min_post_spacing_px 不能为负(0=不启用该门)");
- }
- if (v2.min_diagonal_braces < 0) {
- return bad("evidence_v2.min_diagonal_braces 不能为负(0=不启用该门)");
- }
- if (v2.min_post_span_ratio < 0.0 || v2.min_post_span_ratio > 1.0) {
- return bad("evidence_v2.min_post_span_ratio 必须 ∈ [0,1](0=不启用该门)");
- }
- // P0-Q9:空车门参数(写错会让空车永远判不出或过度触发,启动即失败)。
- if (v2.empty_min_span_ratio < 0.0 || v2.empty_min_span_ratio > 1.0) {
- return bad("evidence_v2.empty_min_span_ratio 必须 ∈ [0,1]");
- }
- if (v2.empty_min_opacity < 0.0 || v2.empty_min_opacity > 1.0) {
- return bad("evidence_v2.empty_min_opacity 必须 ∈ [0,1]");
- }
- if (v2.empty_min_wall_h_ratio < 0.0 || v2.empty_min_wall_h_ratio > 1.0) {
- return bad("evidence_v2.empty_min_wall_h_ratio 必须 ∈ [0,1]");
- }
- if (v2.empty_min_post_len_ratio < 0.0 || v2.empty_min_post_len_ratio > 1.0) {
- return bad("evidence_v2.empty_min_post_len_ratio 必须 ∈ [0,1]");
- }
- if (v2.empty_top_margin_ratio < 0.0 || v2.empty_top_margin_ratio > 0.5) {
- return bad("evidence_v2.empty_top_margin_ratio 必须 ∈ [0,0.5](0=不设门槛)");
- }
- if (v2.empty_min_diagonal_braces < 0) {
- return bad("evidence_v2.empty_min_diagonal_braces 不能为负(0=不启用该门)");
- }
- if (v2.empty_flatbed_min_gap_px < 0.0) {
- return bad("evidence_v2.empty_flatbed_min_gap_px 不能为负");
- }
- if (v2.empty_flatbed_max_plane_edge < 0.0 || v2.empty_flatbed_max_plane_edge > 1.0) {
- return bad("evidence_v2.empty_flatbed_max_plane_edge 必须 ∈ [0,1]");
- }
- if (v2.empty_flatbed_max_gray_drop < 0.0) {
- return bad("evidence_v2.empty_flatbed_max_gray_drop 不能为负");
- }
- if (v2.empty_min_posts < 1) {
- return bad("evidence_v2.empty_min_posts 至少为 1");
- }
- if (v2.empty_fallback_max_posts < v2.empty_min_posts) {
- return bad("evidence_v2.empty_fallback_max_posts 不能小于 empty_min_posts");
- }
- if (!(v2.texture_grad_th > 0.0)) {
- return bad("evidence_v2.texture_grad_th 必须 > 0");
- }
- if (v2.texture_block_px < 4) {
- return bad("evidence_v2.texture_block_px 至少 4");
- }
- if (v2.texture_block_hit_ratio < 0.0 || v2.texture_block_hit_ratio > 1.0) {
- return bad("evidence_v2.texture_block_hit_ratio 必须 ∈ [0,1]");
- }
- if (v2.texture_coverage_min < 0.0 || v2.texture_coverage_min > 1.0) {
- return bad("evidence_v2.texture_coverage_min 必须 ∈ [0,1]");
- }
- if (v2.texture_run_rows < 1 || v2.texture_smooth_rows < 1) {
- return bad("evidence_v2.texture_run_rows / texture_smooth_rows 至少 1");
- }
- if (v2.texture_top_margin_ratio < 0.0 || v2.texture_top_margin_ratio > 0.5) {
- return bad("evidence_v2.texture_top_margin_ratio 必须 ∈ [0,0.5]");
- }
- if (!(v2.body_bottom_ratio > 0.0 && v2.body_bottom_ratio <= 1.0)) {
- return bad("evidence_v2.body_bottom_ratio 必须 ∈ (0,1]");
- }
- if (v2.body_min_opacity < 0.0 || v2.body_min_opacity > 1.0) {
- return bad("evidence_v2.body_min_opacity 必须 ∈ [0,1]");
- }
- if (v2.body_min_roi_px < 8) {
- return bad("evidence_v2.body_min_roi_px 至少 8");
- }
- if (!(v2.body_canny_lo_pct > 0.0 && v2.body_canny_lo_pct <= 1.0) ||
- !(v2.body_canny_hi_pct >= v2.body_canny_lo_pct && v2.body_canny_hi_pct <= 1.0)) {
- return bad("evidence_v2.body_canny_lo/hi_pct 必须满足 0 < lo <= hi <= 1");
- }
- if (v2.body_min_points < 4) {
- return bad("evidence_v2.body_min_points 至少 4");
- }
- if (v2.body_grad_pct < 0.0 || v2.body_grad_pct > 1.0 ||
- v2.body_min_inlier_ratio < 0.0 || v2.body_min_inlier_ratio > 1.0) {
- return bad("evidence_v2.body_grad_pct / body_min_inlier_ratio 必须 ∈ [0,1]");
- }
- if (!(v2.body_run_min_len_ratio > 0.0 && v2.body_run_min_len_ratio <= 1.0)) {
- return bad("evidence_v2.body_run_min_len_ratio 必须 ∈ (0,1]");
- }
- if (!(v2.body_min_post_len_ratio > 0.0 && v2.body_min_post_len_ratio <= 1.0)) {
- return bad("evidence_v2.body_min_post_len_ratio 必须 ∈ (0,1]");
- }
- if (v2.body_x_margin_ratio < 0.0 || v2.body_x_margin_ratio > 0.5) {
- return bad("evidence_v2.body_x_margin_ratio 必须 ∈ [0,0.5]");
- }
- if (v2.body_min_posts < 1) {
- return bad("evidence_v2.body_min_posts 至少 1");
- }
- // P0-Q6:没有箱底时的“只看车体”判据(罐箱箱底被车帮挡住时用)。
- if (!(v2.vehicle_min_span_ratio > 0.0 && v2.vehicle_min_span_ratio <= 1.0)) {
- return bad("evidence_v2.vehicle_min_span_ratio 必须 ∈ (0,1]");
- }
- if (v2.vehicle_max_posts < v2.body_min_posts) {
- return bad("evidence_v2.vehicle_max_posts 不能小于 body_min_posts");
- }
- // P0-Q3:2(平车)的贴合亮带厚度/车面下方暗带参数。写错会让门永不触发,
- // 比报错更危险(地面堆料会被判成平车),所以一律启动即失败。
- if (!(v2.contact_max_h_ratio > 0.0 && v2.contact_max_h_ratio <= 0.5)) {
- return bad("evidence_v2.contact_max_h_ratio 必须 ∈ (0, 0.5]");
- }
- if (v2.under_deck_dark_delta < 0.0) {
- return bad("evidence_v2.under_deck_dark_delta 不能为负");
- }
- if (!(v2.under_deck_min_h_ratio > 0.0 && v2.under_deck_min_h_ratio <= 0.1)) {
- return bad("evidence_v2.under_deck_min_h_ratio 必须 ∈ (0, 0.1]");
- }
- if (!(v2.under_deck_search_h_ratio > 0.0 && v2.under_deck_search_h_ratio <= 0.5)) {
- return bad("evidence_v2.under_deck_search_h_ratio 必须 ∈ (0, 0.5]");
- }
- // 太小会让"远距小箱"重新参与 1 的判定(B 片段实测误发布 1);太大则正常
- // 车距也判不出 1。A 实测 ROI≈201 px、B 误判帧 44~68 px,取 90 px 留出双向余量。
- if (v2.min_bed_roi_px < 24) { return bad("evidence_v2.min_bed_roi_px 至少 24"); }
- const V2CommitParams& c = cfg->evidence_commit;
- if (c.gap_m_max < 0.0 || c.gap_px_hard_max < 0.0) {
- return bad("evidence_v2.commit.gap_* 不能为负");
- }
- if (c.stable_frames < 1 || c.structure_frames < 1) {
- return bad("evidence_v2.commit.stable_frames / structure_frames 至少 1");
- }
- // ---- 标定(calibration.*):只挡"写错的数",不挡"记录文件缺失"(后者 → CALIB_STALE)----
- const CalibrationConfig& calib = cfg->calibration;
- if (!(calib.max_age_days >= 0.0)) {
- return bad("calibration.max_age_days 必须是 >= 0 的数字(0 = 不判过期)");
- }
- if (!(calib.px_per_m_tolerance >= 0.0) || calib.px_per_m_tolerance > 10.0) {
- return bad("calibration.px_per_m_tolerance 必须 ∈ [0, 10](相对容差,0.10 = 10%)");
- }
- if (!(calib.box_height_tolerance_m >= 0.0) || calib.box_height_tolerance_m > 5.0) {
- return bad("calibration.box_height_tolerance_m 必须 ∈ [0, 5] 米");
- }
- return true;
- }
- /// 把配置套用到一份**全新**的 AppConfig 上(重复调用幂等)。
- bool apply_config_into(const Config& cfg, AppConfig* out, std::string* error) {
- *out = AppConfig(); // 每次都从"结构体默认值"出发 —— 等价于 Python 的 DEFAULTS 深合并
- if (!apply_run(cfg, out, error)) { return false; }
- if (!apply_plc(cfg, out, error)) { return false; }
- if (!apply_source(cfg, out, error)) { return false; }
- if (!apply_scene(cfg, out, error)) { return false; }
- if (!apply_voter(cfg, out, error)) { return false; }
- // 顺序有讲究:先 edge.*(其中 edge.grad_pct 会联动 line.grad_pct),
- // 再 edge.line.*,这样现场既能用 §7 的键,也能显式覆盖联动值。
- if (!apply_edge(cfg, out, error)) { return false; }
- if (!apply_line(cfg, out, error)) { return false; }
- if (!apply_evidence_v2(cfg, out, error)) { return false; }
- if (!apply_calibration(cfg, out, error)) { return false; }
- return validate(out, error);
- }
- } // namespace
- // ---------------------------------------------------------------- 公开入口
- bool app_config_from_text(const std::string& text, AppConfig* out, std::string* error) {
- if (out == nullptr) {
- if (error != nullptr) { *error = "app_config_from_text: 输出参数为空指针"; }
- return false;
- }
- Config cfg;
- if (!Config::from_text(text, &cfg, error)) { return false; }
- return apply_config_into(cfg, out, error);
- }
- bool load_app_config(const std::string& path, AppConfig* out, std::string* error) {
- if (out == nullptr) {
- if (error != nullptr) { *error = "load_app_config: 输出参数为空指针"; }
- return false;
- }
- Config cfg; // 空配置 = 纯默认值(--config 不给时的行为)
- if (!path.empty() && !Config::from_file(path, &cfg, error)) { return false; }
- return apply_config_into(cfg, out, error);
- }
- bool check_backend(const AppConfig& cfg, std::string* error) {
- const auto fail = [error](const std::string& what) {
- if (error != nullptr) { *error = what; }
- return false;
- };
- const char* const backends[] = {"mock", "edge", "edge-v2", "evidence-v2"};
- bool known = false;
- for (const char* name : backends) {
- if (cfg.backend == name) { known = true; }
- }
- if (!known) {
- return fail("run.backend=\"" + cfg.backend +
- "\" 在 C++ 侧尚未实现(当前支持 mock / edge / edge-v2):\n"
- " * edge-v2 = P1b/P1c 前视 v2 结构证据 + commit 门(推荐;"
- "不需要 NPU / OpenCV / 模型权重);\n"
- " * edge = 二维边缘几何证据 v1(docs/edge_evidence.md,已冻结,仅回归对照);\n"
- " * mock = 脚本化检测框,用于「无相机无模型」把寄存器与指令握手联调通;\n"
- " * onnx / rknn / tensorrt 请用 Python 版:python -m portcv run -c <同一份配置>。");
- }
- const std::string& demo = cfg.edge_demo;
- if (demo != "none" && demo != "gondola" && demo != "flatbed" && demo != "ground") {
- return fail("--edge-demo 只能是 none / gondola / flatbed / ground,实际是 \"" + demo + "\"");
- }
- if (demo != "none" && cfg.backend != "edge") {
- return fail("--edge-demo 只在 --backend edge 下有意义(当前 backend=" + cfg.backend + ")");
- }
- if (error != nullptr) { error->clear(); }
- return true;
- }
- namespace {
- /// 追加一行格式化文本(配置文件很小、清单固定 13 行,超长即截断,不做动态分配)。
- #if defined(__GNUC__)
- __attribute__((format(printf, 2, 3)))
- #endif
- void append_line(std::string* out, const char* fmt, ...) {
- char buf[1024];
- va_list args;
- va_start(args, fmt);
- std::vsnprintf(buf, sizeof(buf), fmt, args);
- va_end(args);
- *out += buf;
- }
- } // namespace
- std::string describe_app_config(const AppConfig& cfg) {
- const SceneParams& s = cfg.scene;
- const VoterParams& v = cfg.voter;
- const EdgeParams& e = cfg.edge;
- const LineParams& l = cfg.line;
- std::string out;
- append_line(&out, "运行 : backend=%s max_fps=%.1f warmup_frames=%d plc=%s\n",
- cfg.backend.c_str(), cfg.max_fps, cfg.warmup_frames,
- cfg.plc_enabled ? "on" : "off");
- // 取流一行(口令掩掉):现场 `--check-config` 一眼能看到"到底接的是哪路画面"。
- append_line(&out,
- "取流 : source.type=%s uri=%s buffer_size=%d reconnect_s=%.1f stale_frame_s=%.2f "
- "loop=%d(%s;本构建%s GStreamer)\n",
- cfg.source.type.c_str(),
- cfg.source.uri.empty() ? "(未设置)" : redact_uri(cfg.source.uri).c_str(),
- cfg.source.buffer_size, cfg.source.reconnect_s, cfg.source.stale_frame_s,
- cfg.source.loop ? 1 : 0,
- cfg.source.type == "none"
- ? "不取流:Frame.gray = nullptr → 证据后端输出 255 安全值"
- : (cfg.source.type == "synth" ? "合成帧(台架/CI)" : "真机取流"),
- gst_available() ? "带" : "**不带**");
- if (cfg.source.type != "none" && cfg.source.type != "synth") {
- append_line(&out, " 管线=%s\n", redact_uri(gst_pipeline_for(cfg.source)).c_str());
- }
- append_line(&out,
- "PLC : %s:%u unit=%u input_addr=%u(%d字) holding_addr=%u(%d字) "
- "allow_unit_any=%d\n",
- cfg.modbus.host.c_str(), static_cast<unsigned>(cfg.modbus.port),
- static_cast<unsigned>(cfg.modbus.unit_id),
- static_cast<unsigned>(cfg.modbus.input_addr), VisionSnapshot::register_count(),
- static_cast<unsigned>(cfg.modbus.holding_addr), PlcCommand::register_count(),
- cfg.modbus.allow_unit_any ? 1 : 0);
- append_line(&out,
- "判定 : scene.mode=%s roi=%d点 min_class_conf=%.2f roi_min_ratio=%.2f "
- "support_overlap=%.2f support_dy_ratio=%.2f support_score_ratio=%.2f\n",
- s.mode.c_str(), static_cast<int>(s.roi.size()), s.min_class_conf, s.roi_min_ratio,
- s.support_overlap, s.support_dy_ratio, s.support_score_ratio);
- append_line(&out, " require_container=%d no_container_conf=%.2f unknown_on_no_detection=%d\n",
- s.require_container ? 1 : 0, s.no_container_conf, s.unknown_on_no_detection ? 1 : 0);
- append_line(&out,
- "时序 : decision.window=%d window_s=%.2f min_votes=%d min_confidence=%.2f "
- "min_dwell_s=%.2f hold_s=%.2f lost_timeout_s=%.2f low_fps_threshold=%.1f\n",
- v.window, v.window_s, v.min_votes, v.min_confidence, v.min_dwell_s, v.hold_s,
- v.lost_timeout_s, cfg.low_fps_threshold);
- append_line(&out,
- "边缘§7: edge.box_height_m=%.3f band_high=[%.2f, %.2f] band_low=[%.2f, %.2f] "
- "gap_band=[%.2f, %.2f]\n",
- e.box_height_m, e.band_high_lo, e.band_high_hi, e.band_low_lo, e.band_low_hi,
- e.gap_band_lo, e.gap_band_hi);
- append_line(&out,
- " edge.cross_ratio=[%.2f, %.2f] line_angle_deg=%.1f min_len_track=%.2f "
- "min_len_cross_px=%.1f min_out_ratio=%.2f\n",
- e.cross_ratio_lo, e.cross_ratio_hi, e.line_angle_deg, e.min_len_track,
- e.min_len_cross_px, e.min_out_ratio);
- append_line(&out,
- " edge.grad_pct=%.2f texture_period=[%.2f, %.2f] near_edge_px=%.0f "
- "motion_hold_s=%.1f allow_state2=%d\n",
- e.grad_pct, e.texture_period_lo, e.texture_period_hi, e.near_edge_px,
- e.motion_hold_s, e.allow_state2 ? 1 : 0);
- append_line(&out,
- "边缘补充: edge.work_width=%d use_clahe=%d clahe_tiles=%d clahe_clip=%.1f "
- "box_is_on_left=%d strong_step_pct=%.2f\n",
- e.work_width, e.use_clahe ? 1 : 0, e.clahe_tiles, e.clahe_clip,
- e.box_is_on_left ? 1 : 0, e.strong_step_pct);
- append_line(&out,
- " edge.wall_density_max=%.2f ground_density=[%.2f, %.2f] "
- "ground_block_px=%.0f c1_below_ground_max=%.2f c1_span_ratio_min=%.2f\n",
- e.wall_density_max, e.ground_density_lo, e.ground_density_hi, e.ground_block_px,
- e.c1_below_ground_max, e.c1_span_ratio_min);
- append_line(&out,
- " edge.c2_col_ratio_min=%.2f c2_dark_k=%.2f p4_dark_ratio=%.2f "
- "contact_dark_k=%.2f\n",
- e.c2_col_ratio_min, e.c2_dark_k, e.p4_dark_ratio, e.contact_dark_k);
- append_line(&out,
- " edge.motion_gate=%d motion_shift_max_px=%.1f motion_blur_ratio=%.2f "
- "roi=[%.2f, %.2f, %.2f, %.2f]\n",
- e.motion_gate ? 1 : 0, e.motion_shift_max_px, e.motion_blur_ratio, e.roi_left,
- e.roi_top, e.roi_right, e.roi_bottom);
- append_line(&out,
- "边缘线段: edge.line.canny=[%.2f, %.2f] min_points=%d fit_tol_px=%.1f "
- "dir_tol_deg=%.1f thick_tol_px=%.1f\n",
- l.canny_lo_pct, l.canny_hi_pct, l.min_points, l.fit_tol_px, l.dir_tol_deg,
- l.thick_tol_px);
- append_line(&out,
- " edge.line.min_inlier_ratio=%.2f max_segments_per_blob=%d "
- "merge=[%.0f, %.1f, %.1f] strength_off_px=%.1f grad_pct=%.2f\n",
- l.min_inlier_ratio, l.max_segments_per_blob, l.merge_gap_px, l.merge_angle_deg,
- l.merge_offset_px, l.strength_off_px, l.grad_pct);
- const EdgeV2Params& v2 = cfg.evidence_v2;
- const V2CommitParams& vc = cfg.evidence_commit;
- append_line(&out,
- "v2证据: view=%s work_width=%d posts=[%d, %d] wall_opacity>=%.2f "
- "ground=[%.2f, %.2f] 箱底ROI>=%dpx 门板间距>=%.0fpx 斜撑>=%d 跨度>=%.2f\n",
- v2.view.c_str(), v2.work_width, v2.min_door_posts, v2.max_door_posts,
- v2.min_wall_opacity, v2.ground_density_lo, v2.ground_density_hi,
- v2.min_bed_roi_px, v2.min_post_spacing_px, v2.min_diagonal_braces,
- v2.min_post_span_ratio);
- append_line(&out,
- "v2平车门: 贴合亮带<=%.2f×估箱高 车面下方暗带>=%.0f灰阶 "
- "probe=[%.3f, %.3f]×画幅(找不到暗带不判 2)\n",
- v2.contact_max_h_ratio, v2.under_deck_dark_delta,
- v2.under_deck_min_h_ratio, v2.under_deck_search_h_ratio);
- append_line(&out,
- "v2顶部门: enable=%d grad>=%.0f block=%d hit=%.2f cov>=%.2f "
- "run=%d smooth=%d margin=%.2f(车体顶以上亮/暗带剔除)\n",
- v2.texture_top_enable ? 1 : 0, v2.texture_grad_th, v2.texture_block_px,
- v2.texture_block_hit_ratio, v2.texture_coverage_min, v2.texture_run_rows,
- v2.texture_smooth_rows, v2.texture_top_margin_ratio);
- append_line(&out,
- "v2车体兜底: enable=%d bottom=%.2f x_margin=%.2f posts=[%d,%d] "
- "opacity>=%.2f roi>=%dpx canny=[%.2f,%.2f] min_points=%d "
- "grad>=%.2f run_len>=%.2f×ROI post_len>=%.2f×ROI\n",
- v2.body_fallback_enable ? 1 : 0, v2.body_bottom_ratio,
- v2.body_x_margin_ratio, v2.body_min_posts, v2.max_door_posts,
- v2.body_min_opacity, v2.body_min_roi_px, v2.body_canny_lo_pct,
- v2.body_canny_hi_pct, v2.body_min_points, v2.body_grad_pct,
- v2.body_run_min_len_ratio, v2.body_min_post_len_ratio);
- append_line(&out,
- "v2无箱兜底: 只看车体(箱底被车帮挡住时)posts=[%d,%d] span>=%.2f "
- "opacity>=%.2f diag>=%d(判不出仍 255,不会猜平车)\n",
- v2.body_min_posts, v2.vehicle_max_posts,
- v2.vehicle_min_span_ratio, v2.body_min_opacity,
- v2.min_diagonal_braces);
- append_line(&out,
- "v2空车: enable=%d state3_submit=%d posts=[%d,%d] span>=%.2f "
- "opacity>=%.2f wall_h>=%.2f post_len>=%.2f top_margin=%.2f"
- "(完整空敞车侧墙 -> 3)\n",
- v2.empty_vehicle_enable ? 1 : 0, v2.allow_state3 ? 1 : 0,
- v2.empty_min_posts, v2.max_door_posts, v2.empty_min_span_ratio,
- v2.empty_min_opacity, v2.empty_min_wall_h_ratio,
- v2.empty_min_post_len_ratio, v2.empty_top_margin_ratio);
- append_line(&out,
- "v2空平车: enable=%d gap>=%.0fpx 车面边缘<=%.2f 灰度降<=%.0f"
- "(薄边梁+车底透空+光滑亮车面 -> 3)\n",
- v2.empty_flatbed_enable ? 1 : 0, v2.empty_flatbed_min_gap_px,
- v2.empty_flatbed_max_plane_edge, v2.empty_flatbed_max_gray_drop);
- append_line(&out,
- "v2落位: require_commit=%d gap_m<=%.2f gap_px<=%.1f stable=%d structure=%d "
- "allow_state2=%d allow_state3=%d use_plc_arrival=%s\n",
- v2.require_commit ? 1 : 0, vc.gap_m_max, vc.gap_px_hard_max,
- vc.stable_frames, vc.structure_frames, vc.allow_state2 ? 1 : 0,
- vc.allow_state3 ? 1 : 0,
- vc.use_plc_arrival ? "on(⚠无信号源,等价 off)" : "off");
- if (vc.use_plc_arrival) {
- // 说清楚"为什么配了也不生效":PLC 命令区目前没有"开始下放/到位/
- // 吊具松开"位(docs/plc_interface.md §7 第 11 条待确认),运行时
- // 也就没有来源把 plc_arrived 传给 EdgeV2::analyze()。
- append_line(&out,
- "⚠ evidence_v2.commit.use_plc_arrival=true,但 PLC 命令区尚无"
- "到位/吊具松开信号(plc_interface §7 #11),本开关当前等价于 off;"
- "commit 仍只看 gap_px/gap_m。\n");
- }
- append_line(&out,
- "v2安全门: 吊具高悬=%s dark_max=%d band_frac=%.3f line_ratio=%.2f "
- "dark_ratio=%.2f bright_delta=%.0f | 夹箱=%s dark_max=%d dark_ratio=%.2f"
- "(命中即弃权且不累计 commit 窗口)\n",
- v2.reject_hoist_high ? "on" : "off", v2.hoist.dark_max, v2.hoist.band_frac,
- v2.hoist.line_ratio, v2.hoist.dark_ratio, v2.hoist.bright_delta,
- v2.reject_spreader_contact ? "on" : "off", v2.spreader.dark_max,
- v2.spreader.dark_ratio);
- append_line(&out,
- "标定配置: calibration.record=%s stale=%d max_age_days=%.0f px_per_m_tol=%.2f "
- "box_height_tol=%.3fm hold_on_stale=%d(判定结果见下一行)\n",
- cfg.calibration.record.empty() ? "(未配置)" : cfg.calibration.record.c_str(),
- cfg.calibration.stale ? 1 : 0, cfg.calibration.max_age_days,
- cfg.calibration.px_per_m_tolerance, cfg.calibration.box_height_tolerance_m,
- cfg.calibration.hold_on_stale ? 1 : 0);
- append_line(&out, "命令行: --edge-demo=%s publish_edge_flags=%s\n", cfg.edge_demo.c_str(),
- cfg.publish_edge_flags ? "deprecated(诊断只写 reserved)" : "off(默认;bit8~12 为标准健康位)");
- return out;
- }
- } // namespace portcv
|