| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- // 配置访问器(只读)—— 与 Python `portcv.config.Config` **同语义**:
- // Python: cfg.get_path("plc.modbus.port", 1502)
- // C++ : cfg.number("plc.modbus.port", 1502.0)
- //
- // 为什么要单独一层:
- // * main.cpp / 自检只应看到"路径 + 默认值",不该关心 JSON 细节;
- // * "深合并 + 默认值"的语义与 Python 保持一致 → 同一个 configs/*.json 交到两侧手里结论相同
- // (Python 用 DEFAULTS 深合并,C++ 用"结构体默认值 + 只在键存在时覆盖",见 app_config.hpp);
- // * 类型不符**不静默**:本层只回答"是什么类型/取什么值",严格校验统一在 app_config.cpp 里做,
- // 这样现场把 `"false"` 写成字符串时是**启动即报错**,而不是悄悄按默认值跑。
- #pragma once
- #include <string>
- #include <utility>
- #include <vector>
- #include "portcv/json_lite.hpp"
- namespace portcv {
- /// 只读配置(深路径访问 + 类型安全的取值)。
- class Config {
- public:
- Config() = default;
- /// 解析 JSON 文本(失败返回 false 并填写 error)。
- static bool from_text(const std::string& text, Config* out, std::string* error);
- /// 读文件并解析(失败返回 false 并填写 error)。
- static bool from_file(const std::string& path, Config* out, std::string* error);
- const json::Value& root() const { return root_; }
- /// 路径存在且值不是 null(`"x": null` 视为未配置)。
- bool has(const std::string& path) const;
- /// 取路径上的值;缺失返回 Null。
- const json::Value& get(const std::string& path) const;
- /// 取数字(非数字 → fallback);缺失 → fallback。
- double number(const std::string& path, double fallback) const;
- /// 取整数(非数字 → fallback;四舍五入到最近整数)。
- int integer(const std::string& path, int fallback) const;
- /// 取布尔(true/false;数字 0/非 0 也接受 —— 与 Python 的 bool(value) 口径一致)。
- bool boolean(const std::string& path, bool fallback) const;
- /// 取字符串(非字符串 → fallback)。
- std::string text(const std::string& path, const std::string& fallback) const;
- /// 取数字数组;非数组 → 空;非数字元素按 0 计入(严格校验由调用方负责)。
- std::vector<double> numbers(const std::string& path) const;
- /// 取字符串数组;非数组 → 空;非字符串元素跳过。
- std::vector<std::string> strings(const std::string& path) const;
- /// 取点列 `[[x, y], ...]`(归一化 ROI 用);形状不符的元素跳过。
- std::vector<std::pair<double, double>> points(const std::string& path) const;
- private:
- json::Value root_;
- };
- } // namespace portcv
|