1 /**
2  * Copyright 2019 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "sensors/buildjson.hpp"
18 
19 #include "conf.hpp"
20 #include "sensors/sensor.hpp"
21 
22 #include <cstdio>
23 #include <nlohmann/json.hpp>
24 
25 using json = nlohmann::json;
26 
27 namespace conf
28 {
29 void from_json(const json& j, conf::SensorConfig& s)
30 {
31     j.at("type").get_to(s.type);
32     j.at("readPath").get_to(s.readPath);
33 
34     /* The writePath field is optional in a configuration */
35     auto writePath = j.find("writePath");
36     if (writePath == j.end())
37     {
38         s.writePath = "";
39     }
40     else
41     {
42         j.at("writePath").get_to(s.writePath);
43     }
44 
45     s.min = 0;
46     s.max = 0;
47 
48     /* The min field is optional in a configuration. */
49     auto min = j.find("min");
50     if (min != j.end())
51     {
52         if (s.type == "fan")
53         {
54             j.at("min").get_to(s.min);
55         }
56         else
57         {
58             std::fprintf(stderr, "Non-fan types ignore min value specified\n");
59         }
60     }
61 
62     /* The max field is optional in a configuration. */
63     auto max = j.find("max");
64     if (max != j.end())
65     {
66         if (s.type == "fan")
67         {
68             j.at("max").get_to(s.max);
69         }
70         else
71         {
72             std::fprintf(stderr, "Non-fan types ignore max value specified\n");
73         }
74     }
75 
76     /* The timeout field is optional in a configuration. */
77     auto timeout = j.find("timeout");
78     if (timeout == j.end())
79     {
80         s.timeout = Sensor::getDefaultTimeout(s.type);
81     }
82     else
83     {
84         j.at("timeout").get_to(s.timeout);
85     }
86 }
87 } // namespace conf
88 
89 std::map<std::string, struct conf::SensorConfig>
90     buildSensorsFromJson(const json& data)
91 {
92     std::map<std::string, struct conf::SensorConfig> config;
93     auto sensors = data["sensors"];
94 
95     /* TODO: If no sensors, this is invalid, and we should except here or during
96      * parsing.
97      */
98     for (const auto& sensor : sensors)
99     {
100         config[sensor["name"]] = sensor.get<struct conf::SensorConfig>();
101     }
102 
103     return config;
104 }
105