Harvey Wu | 3dcfd54 | 2022-10-31 17:11:02 +0800 | [diff] [blame^] | 1 | #include "buildjson/buildjson.hpp" |
Patrick Venture | 5426c34 | 2019-02-11 12:03:30 -0800 | [diff] [blame] | 2 | |
| 3 | #include "errors/exception.hpp" |
| 4 | |
Patrick Venture | 5426c34 | 2019-02-11 12:03:30 -0800 | [diff] [blame] | 5 | #include <nlohmann/json.hpp> |
| 6 | |
Patrick Venture | a83a3ec | 2020-08-04 09:52:05 -0700 | [diff] [blame] | 7 | #include <fstream> |
| 8 | |
Patrick Venture | 5426c34 | 2019-02-11 12:03:30 -0800 | [diff] [blame] | 9 | using json = nlohmann::json; |
| 10 | |
| 11 | void validateJson(const json& data) |
| 12 | { |
| 13 | if (data.count("sensors") != 1) |
| 14 | { |
| 15 | throw ConfigurationException( |
| 16 | "KeyError: 'sensors' not found (or found repeatedly)"); |
| 17 | } |
| 18 | |
| 19 | if (data["sensors"].size() == 0) |
| 20 | { |
| 21 | throw ConfigurationException( |
| 22 | "Invalid Configuration: At least one sensor required"); |
| 23 | } |
| 24 | |
| 25 | if (data.count("zones") != 1) |
| 26 | { |
| 27 | throw ConfigurationException( |
| 28 | "KeyError: 'zones' not found (or found repeatedly)"); |
| 29 | } |
| 30 | |
| 31 | for (const auto& zone : data["zones"]) |
| 32 | { |
| 33 | if (zone.count("pids") != 1) |
| 34 | { |
| 35 | throw ConfigurationException( |
| 36 | "KeyError: should only have one 'pids' key per zone."); |
| 37 | } |
| 38 | |
| 39 | if (zone["pids"].size() == 0) |
| 40 | { |
| 41 | throw ConfigurationException( |
| 42 | "Invalid Configuration: must be at least one pid per zone."); |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | json parseValidateJson(const std::string& path) |
| 48 | { |
| 49 | std::ifstream jsonFile(path); |
| 50 | if (!jsonFile.is_open()) |
| 51 | { |
| 52 | throw ConfigurationException("Unable to open json file"); |
| 53 | } |
| 54 | |
| 55 | auto data = json::parse(jsonFile, nullptr, false); |
| 56 | if (data.is_discarded()) |
| 57 | { |
| 58 | throw ConfigurationException("Invalid json - parse failed"); |
| 59 | } |
| 60 | |
| 61 | /* Check the data. */ |
| 62 | validateJson(data); |
| 63 | |
| 64 | return data; |
| 65 | } |