1 #include "buildjson/buildjson.hpp"
2 
3 #include "errors/exception.hpp"
4 
5 #include <nlohmann/json.hpp>
6 
7 #include <fstream>
8 
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 }
66