blob: 14253e842075eee2a85238851d6d810f0f1b4f01 [file] [log] [blame]
Patrick Venture5426c342019-02-11 12:03:30 -08001#include "build/buildjson.hpp"
2
3#include "errors/exception.hpp"
4
Patrick Venture5426c342019-02-11 12:03:30 -08005#include <nlohmann/json.hpp>
6
Patrick Venturea83a3ec2020-08-04 09:52:05 -07007#include <fstream>
8
Patrick Venture5426c342019-02-11 12:03:30 -08009using json = nlohmann::json;
10
11void 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
47json 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}