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