blob: a67077b06e942afdec0542f4e299aa4f1e13293a [file] [log] [blame]
Vijay Khemkaabcc94f2020-08-11 15:27:44 -07001#include "virtualSensor.hpp"
2
3#include "config.hpp"
4
Matt Spinlerddc6dcd2020-11-09 11:16:31 -06005#include <fmt/format.h>
6
Vijay Khemkaabcc94f2020-08-11 15:27:44 -07007#include <phosphor-logging/log.hpp>
8#include <sdeventplus/event.hpp>
9
10#include <fstream>
11#include <iostream>
12
13static constexpr bool DEBUG = false;
14static constexpr auto busName = "xyz.openbmc_project.VirtualSensor";
15static constexpr auto sensorDbusPath = "/xyz/openbmc_project/sensors/";
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070016
17using namespace phosphor::logging;
18
Vijay Khemka51f898e2020-09-09 22:24:18 -070019int handleDbusSignal(sd_bus_message* msg, void* usrData, sd_bus_error*)
20{
21 if (usrData == nullptr)
22 {
23 throw std::runtime_error("Invalid match");
24 }
25
26 auto sdbpMsg = sdbusplus::message::message(msg);
27 std::string msgIfce;
28 std::map<std::string, std::variant<int64_t, double, bool>> msgData;
29
30 sdbpMsg.read(msgIfce, msgData);
31
32 if (msgData.find("Value") != msgData.end())
33 {
34 using namespace phosphor::virtualSensor;
35 VirtualSensor* obj = static_cast<VirtualSensor*>(usrData);
36 // TODO(openbmc/phosphor-virtual-sensor#1): updateVirtualSensor should
37 // be changed to take the information we got from the signal, to avoid
38 // having to do numerous dbus queries.
39 obj->updateVirtualSensor();
40 }
41 return 0;
42}
43
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070044namespace phosphor
45{
46namespace virtualSensor
47{
48
49void printParams(const VirtualSensor::ParamMap& paramMap)
50{
51 for (const auto& p : paramMap)
52 {
53 const auto& p1 = p.first;
54 const auto& p2 = p.second;
55 auto val = p2->getParamValue();
56 std::cout << p1 << " = " << val << "\n";
57 }
58}
59
60double SensorParam::getParamValue()
61{
62 switch (paramType)
63 {
64 case constParam:
65 return value;
66 break;
Vijay Khemka7452a862020-08-11 16:01:23 -070067 case dbusParam:
68 return dbusSensor->getSensorValue();
69 break;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070070 default:
71 throw std::invalid_argument("param type not supported");
72 }
73}
74
Matt Spinlerce675222021-01-14 16:38:09 -060075void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
76 const std::string& objPath)
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070077{
78
79 static const Json empty{};
80
81 /* Get threshold values if defined in config */
82 auto threshold = sensorConfig.value("Threshold", empty);
83 if (!threshold.empty())
84 {
Matt Spinlerf15189e2021-01-15 10:13:28 -060085 // Only create the threshold interfaces if
Matt Spinlerce675222021-01-14 16:38:09 -060086 // at least one of their values is present.
Matt Spinlerf15189e2021-01-15 10:13:28 -060087
88 if (threshold.contains("CriticalHigh") ||
89 threshold.contains("CriticalLow"))
90 {
Patrick Williamsfdb826d2021-01-20 14:37:53 -060091 criticalIface = std::make_unique<Threshold<CriticalObject>>(
92 bus, objPath.c_str());
Matt Spinlerf15189e2021-01-15 10:13:28 -060093
94 criticalIface->criticalHigh(threshold.value(
95 "CriticalHigh", std::numeric_limits<double>::quiet_NaN()));
96 criticalIface->criticalLow(threshold.value(
97 "CriticalLow", std::numeric_limits<double>::quiet_NaN()));
98 }
99
100 if (threshold.contains("WarningHigh") ||
101 threshold.contains("WarningLow"))
102 {
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600103 warningIface = std::make_unique<Threshold<WarningObject>>(
104 bus, objPath.c_str());
Matt Spinlerf15189e2021-01-15 10:13:28 -0600105
106 warningIface->warningHigh(threshold.value(
107 "WarningHigh", std::numeric_limits<double>::quiet_NaN()));
108 warningIface->warningLow(threshold.value(
109 "WarningLow", std::numeric_limits<double>::quiet_NaN()));
110 }
111
Matt Spinlerce675222021-01-14 16:38:09 -0600112 if (threshold.contains("HardShutdownHigh") ||
113 threshold.contains("HardShutdownLow"))
114 {
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600115 hardShutdownIface = std::make_unique<Threshold<HardShutdownObject>>(
116 bus, objPath.c_str());
Matt Spinlerce675222021-01-14 16:38:09 -0600117
118 hardShutdownIface->hardShutdownHigh(threshold.value(
119 "HardShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
120 hardShutdownIface->hardShutdownLow(threshold.value(
121 "HardShutdownLow", std::numeric_limits<double>::quiet_NaN()));
122 }
123
124 if (threshold.contains("SoftShutdownHigh") ||
125 threshold.contains("SoftShutdownLow"))
126 {
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600127 softShutdownIface = std::make_unique<Threshold<SoftShutdownObject>>(
128 bus, objPath.c_str());
Matt Spinlerce675222021-01-14 16:38:09 -0600129
130 softShutdownIface->softShutdownHigh(threshold.value(
131 "SoftShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
132 softShutdownIface->softShutdownLow(threshold.value(
133 "SoftShutdownLow", std::numeric_limits<double>::quiet_NaN()));
134 }
Vijay Khemkac62a5542020-09-10 14:45:49 -0700135 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700136
137 /* Get expression string */
138 exprStr = sensorConfig.value("Expression", "");
139
140 /* Get all the parameter listed in configuration */
141 auto params = sensorConfig.value("Params", empty);
142
143 /* Check for constant parameter */
144 const auto& consParams = params.value("ConstParam", empty);
145 if (!consParams.empty())
146 {
147 for (auto& j : consParams)
148 {
149 if (j.find("ParamName") != j.end())
150 {
151 auto paramPtr = std::make_unique<SensorParam>(j["Value"]);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700152 std::string name = j["ParamName"];
153 symbols.create_variable(name);
154 paramMap.emplace(std::move(name), std::move(paramPtr));
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700155 }
156 else
157 {
158 /* Invalid configuration */
159 throw std::invalid_argument(
160 "ParamName not found in configuration");
161 }
162 }
163 }
164
Vijay Khemka7452a862020-08-11 16:01:23 -0700165 /* Check for dbus parameter */
166 auto dbusParams = params.value("DbusParam", empty);
167 if (!dbusParams.empty())
168 {
169 for (auto& j : dbusParams)
170 {
171 /* Get parameter dbus sensor descriptor */
172 auto desc = j.value("Desc", empty);
173 if ((!desc.empty()) && (j.find("ParamName") != j.end()))
174 {
175 std::string sensorType = desc.value("SensorType", "");
176 std::string name = desc.value("Name", "");
177
178 if (!sensorType.empty() && !name.empty())
179 {
180 std::string objPath(sensorDbusPath);
181 objPath += sensorType + "/" + name;
182
Vijay Khemka51f898e2020-09-09 22:24:18 -0700183 auto paramPtr =
184 std::make_unique<SensorParam>(bus, objPath, this);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700185 std::string name = j["ParamName"];
186 symbols.create_variable(name);
187 paramMap.emplace(std::move(name), std::move(paramPtr));
Vijay Khemka7452a862020-08-11 16:01:23 -0700188 }
189 }
190 }
191 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700192
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700193 symbols.add_constants();
Matt Spinler9f1ef4f2020-11-09 15:59:11 -0600194 symbols.add_package(vecopsPackage);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700195 expression.register_symbol_table(symbols);
196
197 /* parser from exprtk */
198 exprtk::parser<double> parser{};
Matt Spinlerddc6dcd2020-11-09 11:16:31 -0600199 if (!parser.compile(exprStr, expression))
200 {
201 log<level::ERR>("Expression compilation failed");
202
203 for (std::size_t i = 0; i < parser.error_count(); ++i)
204 {
205 auto error = parser.get_error(i);
206
207 log<level::ERR>(
208 fmt::format(
209 "Position: {} Type: {} Message: {}", error.token.position,
210 exprtk::parser_error::to_str(error.mode), error.diagnostic)
211 .c_str());
212 }
213 throw std::runtime_error("Expression compilation failed");
214 }
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700215
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700216 /* Print all parameters for debug purpose only */
217 if (DEBUG)
218 printParams(paramMap);
219}
220
221void VirtualSensor::setSensorValue(double value)
222{
223 ValueIface::value(value);
224}
225
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700226void VirtualSensor::updateVirtualSensor()
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700227{
228 for (auto& param : paramMap)
229 {
230 auto& name = param.first;
231 auto& data = param.second;
232 if (auto var = symbols.get_variable(name))
233 {
234 var->ref() = data->getParamValue();
235 }
236 else
237 {
238 /* Invalid parameter */
239 throw std::invalid_argument("ParamName not found in symbols");
240 }
241 }
242 double val = expression.value();
Vijay Khemka32a71562020-09-10 15:29:18 -0700243
244 /* Set sensor value to dbus interface */
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700245 setSensorValue(val);
Vijay Khemka32a71562020-09-10 15:29:18 -0700246
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700247 if (DEBUG)
248 std::cout << "Sensor value is " << val << "\n";
Vijay Khemka32a71562020-09-10 15:29:18 -0700249
Matt Spinler8f5e6112021-01-15 10:44:32 -0600250 /* Check sensor thresholds and log required message */
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600251 checkThresholds(val, warningIface);
252 checkThresholds(val, criticalIface);
253 checkThresholds(val, softShutdownIface);
254 checkThresholds(val, hardShutdownIface);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700255}
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700256
257/** @brief Parsing Virtual Sensor config JSON file */
258Json VirtualSensors::parseConfigFile(const std::string configFile)
259{
260 std::ifstream jsonFile(configFile);
261 if (!jsonFile.is_open())
262 {
263 log<level::ERR>("config JSON file not found",
264 entry("FILENAME = %s", configFile.c_str()));
265 throw std::exception{};
266 }
267
268 auto data = Json::parse(jsonFile, nullptr, false);
269 if (data.is_discarded())
270 {
271 log<level::ERR>("config readings JSON parser failure",
272 entry("FILENAME = %s", configFile.c_str()));
273 throw std::exception{};
274 }
275
276 return data;
277}
278
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700279std::map<std::string, ValueIface::Unit> unitMap = {
280 {"temperature", ValueIface::Unit::DegreesC},
281 {"fan_tach", ValueIface::Unit::RPMS},
282 {"voltage", ValueIface::Unit::Volts},
283 {"altitude", ValueIface::Unit::Meters},
284 {"current", ValueIface::Unit::Amperes},
285 {"power", ValueIface::Unit::Watts},
286 {"energy", ValueIface::Unit::Joules},
287 {"utilization", ValueIface::Unit::Percent}};
288
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700289void VirtualSensors::createVirtualSensors()
290{
291 static const Json empty{};
292
293 auto data = parseConfigFile(VIRTUAL_SENSOR_CONFIG_FILE);
294 // print values
295 if (DEBUG)
296 std::cout << "Config json data:\n" << data << "\n\n";
297
298 /* Get virtual sensors config data */
299 for (const auto& j : data)
300 {
301 auto desc = j.value("Desc", empty);
302 if (!desc.empty())
303 {
304 std::string sensorType = desc.value("SensorType", "");
305 std::string name = desc.value("Name", "");
306
307 if (!name.empty() && !sensorType.empty())
308 {
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700309 if (unitMap.find(sensorType) == unitMap.end())
310 {
311 log<level::ERR>("Sensor type is not supported",
312 entry("TYPE = %s", sensorType.c_str()));
313 }
314 else
315 {
316 std::string objPath(sensorDbusPath);
317 objPath += sensorType + "/" + name;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700318
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700319 auto virtualSensorPtr = std::make_unique<VirtualSensor>(
320 bus, objPath.c_str(), j, name);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700321
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700322 log<level::INFO>("Added a new virtual sensor",
323 entry("NAME = %s", name.c_str()));
324 virtualSensorPtr->updateVirtualSensor();
325
326 /* Initialize unit value for virtual sensor */
327 virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
328
329 virtualSensorsMap.emplace(std::move(name),
330 std::move(virtualSensorPtr));
331 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700332 }
333 else
334 {
335 log<level::ERR>("Sensor type or name not found in config file");
336 }
337 }
338 else
339 {
340 log<level::ERR>(
341 "Descriptor for new virtual sensor not found in config file");
342 }
343 }
344}
345
346} // namespace virtualSensor
347} // namespace phosphor
348
349/**
350 * @brief Main
351 */
352int main()
353{
354
355 // Get a default event loop
356 auto event = sdeventplus::Event::get_default();
357
358 // Get a handle to system dbus
359 auto bus = sdbusplus::bus::new_default();
360
Matt Spinler6c19e7d2021-01-12 16:26:45 -0600361 // Add the ObjectManager interface
362 sdbusplus::server::manager::manager objManager(bus, "/");
363
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700364 // Create an virtual sensors object
365 phosphor::virtualSensor::VirtualSensors virtualSensors(bus);
366
367 // Request service bus name
368 bus.request_name(busName);
369
370 // Attach the bus to sd_event to service user requests
371 bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
372 event.loop();
373
374 return 0;
375}