config_lite.hpp 2.7 KB

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