blob: 4a60f4da57af13b3f79288c370596ba7b165cb15 [file] [log] [blame]
Vijay Khemkaabcc94f2020-08-11 15:27:44 -07001#include "virtualSensor.hpp"
2
3#include "config.hpp"
4
Patrick Williams82b39c62021-07-28 16:22:27 -05005#include <phosphor-logging/lg2.hpp>
Vijay Khemkaabcc94f2020-08-11 15:27:44 -07006#include <sdeventplus/event.hpp>
7
8#include <fstream>
Vijay Khemkaabcc94f2020-08-11 15:27:44 -07009
10static constexpr bool DEBUG = false;
11static constexpr auto busName = "xyz.openbmc_project.VirtualSensor";
12static constexpr auto sensorDbusPath = "/xyz/openbmc_project/sensors/";
Rashmica Guptae7efe132021-07-27 19:42:11 +100013static constexpr auto entityManagerBusName =
14 "xyz.openbmc_project.EntityManager";
15static constexpr auto vsThresholdsIfaceSuffix = ".Thresholds";
Rashmica Gupta304fd0e2021-08-10 16:50:44 +100016static constexpr std::array<const char*, 1> calculationIfaces = {
17 "xyz.openbmc_project.Configuration.ModifiedMedian"};
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +100018static constexpr auto defaultHysteresis = 0;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070019
Patrick Williams82b39c62021-07-28 16:22:27 -050020PHOSPHOR_LOG2_USING_WITH_FLAGS;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070021
Vijay Khemka51f898e2020-09-09 22:24:18 -070022int handleDbusSignal(sd_bus_message* msg, void* usrData, sd_bus_error*)
23{
24 if (usrData == nullptr)
25 {
26 throw std::runtime_error("Invalid match");
27 }
28
29 auto sdbpMsg = sdbusplus::message::message(msg);
30 std::string msgIfce;
31 std::map<std::string, std::variant<int64_t, double, bool>> msgData;
32
33 sdbpMsg.read(msgIfce, msgData);
34
35 if (msgData.find("Value") != msgData.end())
36 {
37 using namespace phosphor::virtualSensor;
38 VirtualSensor* obj = static_cast<VirtualSensor*>(usrData);
39 // TODO(openbmc/phosphor-virtual-sensor#1): updateVirtualSensor should
40 // be changed to take the information we got from the signal, to avoid
41 // having to do numerous dbus queries.
42 obj->updateVirtualSensor();
43 }
44 return 0;
45}
46
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070047namespace phosphor
48{
49namespace virtualSensor
50{
51
52void printParams(const VirtualSensor::ParamMap& paramMap)
53{
54 for (const auto& p : paramMap)
55 {
56 const auto& p1 = p.first;
57 const auto& p2 = p.second;
58 auto val = p2->getParamValue();
Patrick Williamsfbd71452021-08-30 06:59:46 -050059 debug("Parameter: {PARAM} = {VALUE}", "PARAM", p1, "VALUE", val);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070060 }
61}
62
63double SensorParam::getParamValue()
64{
65 switch (paramType)
66 {
67 case constParam:
68 return value;
69 break;
Vijay Khemka7452a862020-08-11 16:01:23 -070070 case dbusParam:
71 return dbusSensor->getSensorValue();
72 break;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070073 default:
74 throw std::invalid_argument("param type not supported");
75 }
76}
77
Lei YU0fcf0e12021-06-04 11:14:17 +080078using AssociationList =
79 std::vector<std::tuple<std::string, std::string, std::string>>;
80
81AssociationList getAssociationsFromJson(const Json& j)
82{
83 AssociationList assocs{};
84 try
85 {
86 j.get_to(assocs);
87 }
88 catch (const std::exception& ex)
89 {
Patrick Williams82b39c62021-07-28 16:22:27 -050090 error("Failed to parse association: {ERROR}", "ERROR", ex);
Lei YU0fcf0e12021-06-04 11:14:17 +080091 }
92 return assocs;
93}
94
Rashmica Guptae7efe132021-07-27 19:42:11 +100095template <typename U>
96struct VariantToNumber
97{
98 template <typename T>
99 U operator()(const T& t) const
100 {
101 if constexpr (std::is_convertible<T, U>::value)
102 {
103 return static_cast<U>(t);
104 }
105 throw std::invalid_argument("Invalid number type in config\n");
106 }
107};
108
109template <typename U>
110U getNumberFromConfig(const PropertyMap& map, const std::string& name,
Jiaqing Zhao190f6d02022-05-21 23:26:15 +0800111 bool required,
112 U defaultValue = std::numeric_limits<U>::quiet_NaN())
Rashmica Guptae7efe132021-07-27 19:42:11 +1000113{
114 if (auto itr = map.find(name); itr != map.end())
115 {
116 return std::visit(VariantToNumber<U>(), itr->second);
117 }
118 else if (required)
119 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500120 error("Required field {NAME} missing in config", "NAME", name);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000121 throw std::invalid_argument("Required field missing in config");
122 }
Jiaqing Zhao190f6d02022-05-21 23:26:15 +0800123 return defaultValue;
Rashmica Guptae7efe132021-07-27 19:42:11 +1000124}
125
126bool isCalculationType(const std::string& interface)
127{
128 auto itr = std::find(calculationIfaces.begin(), calculationIfaces.end(),
129 interface);
130 if (itr != calculationIfaces.end())
131 {
132 return true;
133 }
134 return false;
135}
136
137const std::string getThresholdType(const std::string& direction,
Rashmica Gupta05b1d412021-11-03 12:01:36 +1100138 const std::string& severity)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000139{
Rashmica Guptae7efe132021-07-27 19:42:11 +1000140 std::string suffix;
Rashmica Guptae7efe132021-07-27 19:42:11 +1000141
142 if (direction == "less than")
143 {
144 suffix = "Low";
145 }
146 else if (direction == "greater than")
147 {
148 suffix = "High";
149 }
150 else
151 {
152 throw std::invalid_argument(
153 "Invalid threshold direction specified in entity manager");
154 }
Rashmica Gupta05b1d412021-11-03 12:01:36 +1100155 return severity + suffix;
156}
157
158std::string getSeverityField(const PropertyMap& propertyMap)
159{
160 static const std::array thresholdTypes{"Warning", "Critical",
161 "PerformanceLoss", "SoftShutdown",
162 "HardShutdown"};
163
164 std::string severity;
165 if (auto itr = propertyMap.find("Severity"); itr != propertyMap.end())
166 {
167 /* Severity should be a string, but can be an unsigned int */
168 if (std::holds_alternative<std::string>(itr->second))
169 {
170 severity = std::get<std::string>(itr->second);
171 if (0 == std::ranges::count(thresholdTypes, severity))
172 {
173 throw std::invalid_argument(
174 "Invalid threshold severity specified in entity manager");
175 }
176 }
177 else
178 {
179 auto sev =
180 getNumberFromConfig<uint64_t>(propertyMap, "Severity", true);
181 /* Checking bounds ourselves so we throw invalid argument on
182 * invalid user input */
183 if (sev >= thresholdTypes.size())
184 {
185 throw std::invalid_argument(
186 "Invalid threshold severity specified in entity manager");
187 }
188 severity = thresholdTypes.at(sev);
189 }
190 }
191 return severity;
Rashmica Guptae7efe132021-07-27 19:42:11 +1000192}
193
194void parseThresholds(Json& thresholds, const PropertyMap& propertyMap)
195{
196 std::string direction;
197
Rashmica Guptae7efe132021-07-27 19:42:11 +1000198 auto value = getNumberFromConfig<double>(propertyMap, "Value", true);
199
Rashmica Gupta05b1d412021-11-03 12:01:36 +1100200 auto severity = getSeverityField(propertyMap);
201
202 if (auto itr = propertyMap.find("Direction"); itr != propertyMap.end())
Rashmica Guptae7efe132021-07-27 19:42:11 +1000203 {
204 direction = std::get<std::string>(itr->second);
205 }
206
207 auto threshold = getThresholdType(direction, severity);
208 thresholds[threshold] = value;
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000209
210 auto hysteresis =
211 getNumberFromConfig<double>(propertyMap, "Hysteresis", false);
212 if (hysteresis != std::numeric_limits<double>::quiet_NaN())
213 {
214 thresholds[threshold + "Hysteresis"] = hysteresis;
215 }
Rashmica Guptae7efe132021-07-27 19:42:11 +1000216}
217
218void VirtualSensor::parseConfigInterface(const PropertyMap& propertyMap,
219 const std::string& sensorType,
220 const std::string& interface)
221{
222 /* Parse sensors / DBus params */
223 if (auto itr = propertyMap.find("Sensors"); itr != propertyMap.end())
224 {
225 auto sensors = std::get<std::vector<std::string>>(itr->second);
226 for (auto sensor : sensors)
227 {
228 std::replace(sensor.begin(), sensor.end(), ' ', '_');
229 auto sensorObjPath = sensorDbusPath + sensorType + "/" + sensor;
230
231 auto paramPtr =
232 std::make_unique<SensorParam>(bus, sensorObjPath, this);
233 symbols.create_variable(sensor);
234 paramMap.emplace(std::move(sensor), std::move(paramPtr));
235 }
236 }
237 /* Get expression string */
238 if (!isCalculationType(interface))
239 {
240 throw std::invalid_argument("Invalid expression in interface");
241 }
242 exprStr = interface;
243
244 /* Get optional min and max input and output values */
245 ValueIface::maxValue(
246 getNumberFromConfig<double>(propertyMap, "MaxValue", false));
247 ValueIface::minValue(
248 getNumberFromConfig<double>(propertyMap, "MinValue", false));
249 maxValidInput =
Jiaqing Zhao190f6d02022-05-21 23:26:15 +0800250 getNumberFromConfig<double>(propertyMap, "MaxValidInput", false,
251 std::numeric_limits<double>::infinity());
Rashmica Guptae7efe132021-07-27 19:42:11 +1000252 minValidInput =
Jiaqing Zhao190f6d02022-05-21 23:26:15 +0800253 getNumberFromConfig<double>(propertyMap, "MinValidInput", false,
254 -std::numeric_limits<double>::infinity());
Rashmica Guptae7efe132021-07-27 19:42:11 +1000255}
256
Matt Spinlerce675222021-01-14 16:38:09 -0600257void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
258 const std::string& objPath)
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700259{
260
261 static const Json empty{};
262
263 /* Get threshold values if defined in config */
264 auto threshold = sensorConfig.value("Threshold", empty);
Matt Spinlerf15189e2021-01-15 10:13:28 -0600265
Rashmica Gupta3e999192021-06-09 16:17:04 +1000266 createThresholds(threshold, objPath);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700267
Harvey Wuf6443742021-04-09 16:47:36 +0800268 /* Get MaxValue, MinValue setting if defined in config */
269 auto confDesc = sensorConfig.value("Desc", empty);
270 if (auto maxConf = confDesc.find("MaxValue");
271 maxConf != confDesc.end() && maxConf->is_number())
272 {
273 ValueIface::maxValue(maxConf->get<double>());
274 }
275 if (auto minConf = confDesc.find("MinValue");
276 minConf != confDesc.end() && minConf->is_number())
277 {
278 ValueIface::minValue(minConf->get<double>());
279 }
280
Lei YU0fcf0e12021-06-04 11:14:17 +0800281 /* Get optional association */
282 auto assocJson = sensorConfig.value("Associations", empty);
283 if (!assocJson.empty())
284 {
285 auto assocs = getAssociationsFromJson(assocJson);
286 if (!assocs.empty())
287 {
288 associationIface =
289 std::make_unique<AssociationObject>(bus, objPath.c_str());
290 associationIface->associations(assocs);
291 }
292 }
293
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700294 /* Get expression string */
Patrick Williams03c4c8e2022-04-14 22:19:44 -0500295 static constexpr auto exprKey = "Expression";
296 if (sensorConfig.contains(exprKey))
297 {
Patrick Williamsa9596782022-04-15 10:20:07 -0500298 auto& ref = sensorConfig.at(exprKey);
Patrick Williams03c4c8e2022-04-14 22:19:44 -0500299 if (ref.is_array())
300 {
301 exprStr = std::string{};
302 for (auto& s : ref)
303 {
304 exprStr += s;
305 }
306 }
307 else if (ref.is_string())
308 {
309 exprStr = std::string{ref};
310 }
311 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700312
313 /* Get all the parameter listed in configuration */
314 auto params = sensorConfig.value("Params", empty);
315
316 /* Check for constant parameter */
317 const auto& consParams = params.value("ConstParam", empty);
318 if (!consParams.empty())
319 {
320 for (auto& j : consParams)
321 {
322 if (j.find("ParamName") != j.end())
323 {
324 auto paramPtr = std::make_unique<SensorParam>(j["Value"]);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700325 std::string name = j["ParamName"];
326 symbols.create_variable(name);
327 paramMap.emplace(std::move(name), std::move(paramPtr));
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700328 }
329 else
330 {
331 /* Invalid configuration */
332 throw std::invalid_argument(
333 "ParamName not found in configuration");
334 }
335 }
336 }
337
Vijay Khemka7452a862020-08-11 16:01:23 -0700338 /* Check for dbus parameter */
339 auto dbusParams = params.value("DbusParam", empty);
340 if (!dbusParams.empty())
341 {
342 for (auto& j : dbusParams)
343 {
344 /* Get parameter dbus sensor descriptor */
345 auto desc = j.value("Desc", empty);
346 if ((!desc.empty()) && (j.find("ParamName") != j.end()))
347 {
348 std::string sensorType = desc.value("SensorType", "");
349 std::string name = desc.value("Name", "");
350
351 if (!sensorType.empty() && !name.empty())
352 {
George Liu1204b432021-12-29 17:24:48 +0800353 auto path = sensorDbusPath + sensorType + "/" + name;
Vijay Khemka7452a862020-08-11 16:01:23 -0700354
Vijay Khemka51f898e2020-09-09 22:24:18 -0700355 auto paramPtr =
George Liu1204b432021-12-29 17:24:48 +0800356 std::make_unique<SensorParam>(bus, path, this);
357 std::string paramName = j["ParamName"];
358 symbols.create_variable(paramName);
359 paramMap.emplace(std::move(paramName), std::move(paramPtr));
Vijay Khemka7452a862020-08-11 16:01:23 -0700360 }
361 }
362 }
363 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700364
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700365 symbols.add_constants();
Matt Spinler9f1ef4f2020-11-09 15:59:11 -0600366 symbols.add_package(vecopsPackage);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700367 expression.register_symbol_table(symbols);
368
369 /* parser from exprtk */
370 exprtk::parser<double> parser{};
Matt Spinlerddc6dcd2020-11-09 11:16:31 -0600371 if (!parser.compile(exprStr, expression))
372 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500373 error("Expression compilation failed");
Matt Spinlerddc6dcd2020-11-09 11:16:31 -0600374
375 for (std::size_t i = 0; i < parser.error_count(); ++i)
376 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500377 auto err = parser.get_error(i);
378 error("Error parsing token at {POSITION}: {ERROR}", "POSITION",
379 err.token.position, "TYPE",
380 exprtk::parser_error::to_str(err.mode), "ERROR",
381 err.diagnostic);
Matt Spinlerddc6dcd2020-11-09 11:16:31 -0600382 }
383 throw std::runtime_error("Expression compilation failed");
384 }
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700385
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700386 /* Print all parameters for debug purpose only */
387 if (DEBUG)
388 printParams(paramMap);
389}
390
Rashmica Guptae7efe132021-07-27 19:42:11 +1000391void VirtualSensor::initVirtualSensor(const InterfaceMap& interfaceMap,
392 const std::string& objPath,
393 const std::string& sensorType,
394 const std::string& calculationIface)
395{
396 Json thresholds;
397 const std::string vsThresholdsIntf =
398 calculationIface + vsThresholdsIfaceSuffix;
399
400 for (const auto& [interface, propertyMap] : interfaceMap)
401 {
402 /* Each threshold is on it's own interface with a number as a suffix
403 * eg xyz.openbmc_project.Configuration.ModifiedMedian.Thresholds1 */
404 if (interface.find(vsThresholdsIntf) != std::string::npos)
405 {
406 parseThresholds(thresholds, propertyMap);
407 }
408 else if (interface == calculationIface)
409 {
410 parseConfigInterface(propertyMap, sensorType, interface);
411 }
412 }
413
414 createThresholds(thresholds, objPath);
415 symbols.add_constants();
416 symbols.add_package(vecopsPackage);
417 expression.register_symbol_table(symbols);
418
419 /* Print all parameters for debug purpose only */
420 if (DEBUG)
421 {
422 printParams(paramMap);
423 }
424}
425
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700426void VirtualSensor::setSensorValue(double value)
427{
Patrick Williams543bf662021-04-29 09:03:53 -0500428 value = std::clamp(value, ValueIface::minValue(), ValueIface::maxValue());
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700429 ValueIface::value(value);
430}
431
Rashmica Gupta304fd0e2021-08-10 16:50:44 +1000432double VirtualSensor::calculateValue(const std::string& calculation,
433 const VirtualSensor::ParamMap& paramMap)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000434{
Rashmica Gupta304fd0e2021-08-10 16:50:44 +1000435 auto itr = std::find(calculationIfaces.begin(), calculationIfaces.end(),
436 calculation);
437 if (itr == calculationIfaces.end())
438 {
439 return std::numeric_limits<double>::quiet_NaN();
440 }
441 else if (calculation == "xyz.openbmc_project.Configuration.ModifiedMedian")
442 {
443 return calculateModifiedMedianValue(paramMap);
444 }
Rashmica Guptae7efe132021-07-27 19:42:11 +1000445 return std::numeric_limits<double>::quiet_NaN();
446}
447
Rashmica Gupta304fd0e2021-08-10 16:50:44 +1000448bool VirtualSensor::sensorInRange(double value)
449{
450 if (value <= this->maxValidInput && value >= this->minValidInput)
451 {
452 return true;
453 }
454 return false;
455}
456
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700457void VirtualSensor::updateVirtualSensor()
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700458{
459 for (auto& param : paramMap)
460 {
461 auto& name = param.first;
462 auto& data = param.second;
463 if (auto var = symbols.get_variable(name))
464 {
465 var->ref() = data->getParamValue();
466 }
467 else
468 {
469 /* Invalid parameter */
470 throw std::invalid_argument("ParamName not found in symbols");
471 }
472 }
Rashmica Guptae7efe132021-07-27 19:42:11 +1000473 auto itr =
474 std::find(calculationIfaces.begin(), calculationIfaces.end(), exprStr);
Rashmica Gupta304fd0e2021-08-10 16:50:44 +1000475 auto val = (itr == calculationIfaces.end())
476 ? expression.value()
477 : calculateValue(exprStr, paramMap);
Vijay Khemka32a71562020-09-10 15:29:18 -0700478
479 /* Set sensor value to dbus interface */
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700480 setSensorValue(val);
Vijay Khemka32a71562020-09-10 15:29:18 -0700481
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700482 if (DEBUG)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000483 {
Patrick Williamsfbd71452021-08-30 06:59:46 -0500484 debug("Sensor {NAME} = {VALUE}", "NAME", this->name, "VALUE", val);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000485 }
Vijay Khemka32a71562020-09-10 15:29:18 -0700486
Matt Spinler8f5e6112021-01-15 10:44:32 -0600487 /* Check sensor thresholds and log required message */
Matt Spinlerb306b032021-02-01 10:05:46 -0600488 checkThresholds(val, perfLossIface);
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600489 checkThresholds(val, warningIface);
490 checkThresholds(val, criticalIface);
491 checkThresholds(val, softShutdownIface);
492 checkThresholds(val, hardShutdownIface);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700493}
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700494
Rashmica Gupta304fd0e2021-08-10 16:50:44 +1000495double VirtualSensor::calculateModifiedMedianValue(
496 const VirtualSensor::ParamMap& paramMap)
497{
498 std::vector<double> values;
499
500 for (auto& param : paramMap)
501 {
502 auto& name = param.first;
503 if (auto var = symbols.get_variable(name))
504 {
505 if (!sensorInRange(var->ref()))
506 {
507 continue;
508 }
509 values.push_back(var->ref());
510 }
511 }
512
513 size_t size = values.size();
514 std::sort(values.begin(), values.end());
515 switch (size)
516 {
517 case 2:
518 /* Choose biggest value */
519 return values.at(1);
520 case 0:
521 return std::numeric_limits<double>::quiet_NaN();
522 default:
523 /* Choose median value */
524 if (size % 2 == 0)
525 {
526 // Average of the two middle values
527 return (values.at(size / 2) + values.at(size / 2 - 1)) / 2;
528 }
529 else
530 {
531 return values.at((size - 1) / 2);
532 }
533 }
534}
535
Rashmica Gupta3e999192021-06-09 16:17:04 +1000536void VirtualSensor::createThresholds(const Json& threshold,
537 const std::string& objPath)
538{
539 if (threshold.empty())
540 {
541 return;
542 }
543 // Only create the threshold interfaces if
544 // at least one of their values is present.
545 if (threshold.contains("CriticalHigh") || threshold.contains("CriticalLow"))
546 {
547 criticalIface =
548 std::make_unique<Threshold<CriticalObject>>(bus, objPath.c_str());
549
550 criticalIface->criticalHigh(threshold.value(
551 "CriticalHigh", std::numeric_limits<double>::quiet_NaN()));
552 criticalIface->criticalLow(threshold.value(
553 "CriticalLow", std::numeric_limits<double>::quiet_NaN()));
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000554 criticalIface->setHighHysteresis(
555 threshold.value("CriticalHighHysteresis", defaultHysteresis));
556 criticalIface->setLowHysteresis(
557 threshold.value("CriticalLowHysteresis", defaultHysteresis));
Rashmica Gupta3e999192021-06-09 16:17:04 +1000558 }
559
560 if (threshold.contains("WarningHigh") || threshold.contains("WarningLow"))
561 {
562 warningIface =
563 std::make_unique<Threshold<WarningObject>>(bus, objPath.c_str());
564
565 warningIface->warningHigh(threshold.value(
566 "WarningHigh", std::numeric_limits<double>::quiet_NaN()));
567 warningIface->warningLow(threshold.value(
568 "WarningLow", std::numeric_limits<double>::quiet_NaN()));
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000569 warningIface->setHighHysteresis(
570 threshold.value("WarningHighHysteresis", defaultHysteresis));
571 warningIface->setLowHysteresis(
572 threshold.value("WarningLowHysteresis", defaultHysteresis));
Rashmica Gupta3e999192021-06-09 16:17:04 +1000573 }
574
575 if (threshold.contains("HardShutdownHigh") ||
576 threshold.contains("HardShutdownLow"))
577 {
578 hardShutdownIface = std::make_unique<Threshold<HardShutdownObject>>(
579 bus, objPath.c_str());
580
581 hardShutdownIface->hardShutdownHigh(threshold.value(
582 "HardShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
583 hardShutdownIface->hardShutdownLow(threshold.value(
584 "HardShutdownLow", std::numeric_limits<double>::quiet_NaN()));
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000585 hardShutdownIface->setHighHysteresis(
586 threshold.value("HardShutdownHighHysteresis", defaultHysteresis));
587 hardShutdownIface->setLowHysteresis(
588 threshold.value("HardShutdownLowHysteresis", defaultHysteresis));
Rashmica Gupta3e999192021-06-09 16:17:04 +1000589 }
590
591 if (threshold.contains("SoftShutdownHigh") ||
592 threshold.contains("SoftShutdownLow"))
593 {
594 softShutdownIface = std::make_unique<Threshold<SoftShutdownObject>>(
595 bus, objPath.c_str());
596
597 softShutdownIface->softShutdownHigh(threshold.value(
598 "SoftShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
599 softShutdownIface->softShutdownLow(threshold.value(
600 "SoftShutdownLow", std::numeric_limits<double>::quiet_NaN()));
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000601 softShutdownIface->setHighHysteresis(
602 threshold.value("SoftShutdownHighHysteresis", defaultHysteresis));
603 softShutdownIface->setLowHysteresis(
604 threshold.value("SoftShutdownLowHysteresis", defaultHysteresis));
Rashmica Gupta3e999192021-06-09 16:17:04 +1000605 }
606
607 if (threshold.contains("PerformanceLossHigh") ||
608 threshold.contains("PerformanceLossLow"))
609 {
610 perfLossIface = std::make_unique<Threshold<PerformanceLossObject>>(
611 bus, objPath.c_str());
612
613 perfLossIface->performanceLossHigh(threshold.value(
614 "PerformanceLossHigh", std::numeric_limits<double>::quiet_NaN()));
615 perfLossIface->performanceLossLow(threshold.value(
616 "PerformanceLossLow", std::numeric_limits<double>::quiet_NaN()));
Rashmica Gupta1dff7dc2021-07-27 19:43:31 +1000617 perfLossIface->setHighHysteresis(threshold.value(
618 "PerformanceLossHighHysteresis", defaultHysteresis));
619 perfLossIface->setLowHysteresis(
620 threshold.value("PerformanceLossLowHysteresis", defaultHysteresis));
Rashmica Gupta3e999192021-06-09 16:17:04 +1000621 }
622}
623
Rashmica Guptae7efe132021-07-27 19:42:11 +1000624ManagedObjectType VirtualSensors::getObjectsFromDBus()
625{
626 ManagedObjectType objects;
627
628 try
629 {
630 auto method = bus.new_method_call(entityManagerBusName, "/",
631 "org.freedesktop.DBus.ObjectManager",
632 "GetManagedObjects");
633 auto reply = bus.call(method);
634 reply.read(objects);
635 }
Patrick Williams74c1e7d2021-09-02 09:50:55 -0500636 catch (const sdbusplus::exception::exception& ex)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000637 {
638 // If entity manager isn't running yet, keep going.
639 if (std::string("org.freedesktop.DBus.Error.ServiceUnknown") !=
640 ex.name())
641 {
642 throw ex.name();
643 }
644 }
645
646 return objects;
647}
648
649void VirtualSensors::propertiesChanged(sdbusplus::message::message& msg)
650{
651 std::string path;
652 PropertyMap properties;
653
654 msg.read(path, properties);
655
656 /* We get multiple callbacks for one sensor. 'Type' is a required field and
657 * is a unique label so use to to only proceed once per sensor */
658 if (properties.contains("Type"))
659 {
660 if (isCalculationType(path))
661 {
662 createVirtualSensorsFromDBus(path);
663 }
664 }
665}
666
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700667/** @brief Parsing Virtual Sensor config JSON file */
George Liu1204b432021-12-29 17:24:48 +0800668Json VirtualSensors::parseConfigFile(const std::string& configFile)
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700669{
670 std::ifstream jsonFile(configFile);
671 if (!jsonFile.is_open())
672 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500673 error("config JSON file {FILENAME} not found", "FILENAME", configFile);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000674 return {};
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700675 }
676
677 auto data = Json::parse(jsonFile, nullptr, false);
678 if (data.is_discarded())
679 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500680 error("config readings JSON parser failure with {FILENAME}", "FILENAME",
681 configFile);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700682 throw std::exception{};
683 }
684
685 return data;
686}
687
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700688std::map<std::string, ValueIface::Unit> unitMap = {
689 {"temperature", ValueIface::Unit::DegreesC},
690 {"fan_tach", ValueIface::Unit::RPMS},
691 {"voltage", ValueIface::Unit::Volts},
692 {"altitude", ValueIface::Unit::Meters},
693 {"current", ValueIface::Unit::Amperes},
694 {"power", ValueIface::Unit::Watts},
695 {"energy", ValueIface::Unit::Joules},
Kumar Thangavel2b56ddb2021-01-13 20:16:11 +0530696 {"utilization", ValueIface::Unit::Percent},
Rashmica Gupta4ac7a7f2021-07-08 12:30:50 +1000697 {"airflow", ValueIface::Unit::CFM},
698 {"pressure", ValueIface::Unit::Pascals}};
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700699
Rashmica Guptae7efe132021-07-27 19:42:11 +1000700const std::string getSensorTypeFromUnit(const std::string& unit)
701{
702 std::string unitPrefix = "xyz.openbmc_project.Sensor.Value.Unit.";
703 for (auto [type, unitObj] : unitMap)
704 {
705 auto unitPath = ValueIface::convertUnitToString(unitObj);
706 if (unitPath == (unitPrefix + unit))
707 {
708 return type;
709 }
710 }
711 return "";
712}
713
714void VirtualSensors::setupMatches()
715{
716 /* Already setup */
717 if (!this->matches.empty())
718 {
719 return;
720 }
721
722 /* Setup matches */
723 auto eventHandler = [this](sdbusplus::message::message& message) {
724 if (message.is_method_error())
725 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500726 error("Callback method error");
Rashmica Guptae7efe132021-07-27 19:42:11 +1000727 return;
728 }
729 this->propertiesChanged(message);
730 };
731
732 for (const char* iface : calculationIfaces)
733 {
734 auto match = std::make_unique<sdbusplus::bus::match::match>(
735 bus,
736 sdbusplus::bus::match::rules::propertiesChangedNamespace(
737 "/xyz/openbmc_project/inventory", iface),
738 eventHandler);
739 this->matches.emplace_back(std::move(match));
740 }
741}
742
743void VirtualSensors::createVirtualSensorsFromDBus(
744 const std::string& calculationIface)
745{
746 if (calculationIface.empty())
747 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500748 error("No calculation type supplied");
Rashmica Guptae7efe132021-07-27 19:42:11 +1000749 return;
750 }
751 auto objects = getObjectsFromDBus();
752
753 /* Get virtual sensors config data */
754 for (const auto& [path, interfaceMap] : objects)
755 {
756 auto objpath = static_cast<std::string>(path);
757 std::string name = path.filename();
758 std::string sensorType, sensorUnit;
759
760 /* Find Virtual Sensor interfaces */
761 if (!interfaceMap.contains(calculationIface))
762 {
763 continue;
764 }
765 if (name.empty())
766 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500767 error("Virtual Sensor name not found in entity manager config");
Rashmica Guptae7efe132021-07-27 19:42:11 +1000768 continue;
769 }
770 if (virtualSensorsMap.contains(name))
771 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500772 error("A virtual sensor named {NAME} already exists", "NAME", name);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000773 continue;
774 }
775
776 /* Extract the virtual sensor type as we need this to initialize the
777 * sensor */
778 for (const auto& [interface, propertyMap] : interfaceMap)
779 {
780 if (interface != calculationIface)
781 {
782 continue;
783 }
784 auto itr = propertyMap.find("Units");
785 if (itr != propertyMap.end())
786 {
787 sensorUnit = std::get<std::string>(itr->second);
788 break;
789 }
790 }
791 sensorType = getSensorTypeFromUnit(sensorUnit);
792 if (sensorType.empty())
793 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500794 error("Sensor unit type {TYPE} is not supported", "TYPE",
795 sensorUnit);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000796 continue;
797 }
798
799 try
800 {
801 auto virtObjPath = sensorDbusPath + sensorType + "/" + name;
802
803 auto virtualSensorPtr = std::make_unique<VirtualSensor>(
804 bus, virtObjPath.c_str(), interfaceMap, name, sensorType,
805 calculationIface);
Patrick Williams82b39c62021-07-28 16:22:27 -0500806 info("Added a new virtual sensor: {NAME} {TYPE}", "NAME", name,
807 "TYPE", sensorType);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000808 virtualSensorPtr->updateVirtualSensor();
809
810 /* Initialize unit value for virtual sensor */
811 virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
812 virtualSensorPtr->emit_object_added();
813
814 virtualSensorsMap.emplace(name, std::move(virtualSensorPtr));
815
816 /* Setup match for interfaces removed */
817 auto intfRemoved = [this, objpath,
818 name](sdbusplus::message::message& message) {
819 if (!virtualSensorsMap.contains(name))
820 {
821 return;
822 }
823 sdbusplus::message::object_path path;
824 message.read(path);
825 if (static_cast<const std::string&>(path) == objpath)
826 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500827 info("Removed a virtual sensor: {NAME}", "NAME", name);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000828 virtualSensorsMap.erase(name);
829 }
830 };
831 auto matchOnRemove = std::make_unique<sdbusplus::bus::match::match>(
832 bus,
833 sdbusplus::bus::match::rules::interfacesRemoved() +
834 sdbusplus::bus::match::rules::argNpath(0, objpath),
835 intfRemoved);
836 /* TODO: slight race condition here. Check that the config still
837 * exists */
838 this->matches.emplace_back(std::move(matchOnRemove));
839 }
Patrick Williamsdac26632021-10-06 14:38:47 -0500840 catch (const std::invalid_argument& ia)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000841 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500842 error("Failed to set up virtual sensor: {ERROR}", "ERROR", ia);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000843 }
844 }
845}
846
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700847void VirtualSensors::createVirtualSensors()
848{
849 static const Json empty{};
850
851 auto data = parseConfigFile(VIRTUAL_SENSOR_CONFIG_FILE);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000852
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700853 // print values
854 if (DEBUG)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000855 {
Patrick Williamsfbd71452021-08-30 06:59:46 -0500856 debug("JSON: {JSON}", "JSON", data.dump());
Rashmica Guptae7efe132021-07-27 19:42:11 +1000857 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700858
859 /* Get virtual sensors config data */
860 for (const auto& j : data)
861 {
862 auto desc = j.value("Desc", empty);
863 if (!desc.empty())
864 {
Rashmica Guptae7efe132021-07-27 19:42:11 +1000865 if (desc.value("Config", "") == "D-Bus")
866 {
867 /* Look on D-Bus for a virtual sensor config. Set up matches
868 * first because the configs may not be on D-Bus yet and we
869 * don't want to miss them */
870 setupMatches();
871
872 if (desc.contains("Type"))
873 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500874 auto type = desc.value("Type", "");
875 auto path = "xyz.openbmc_project.Configuration." + type;
876
Rashmica Guptae7efe132021-07-27 19:42:11 +1000877 if (!isCalculationType(path))
878 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500879 error("Invalid calculation type {TYPE} supplied.",
880 "TYPE", type);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000881 continue;
882 }
883 createVirtualSensorsFromDBus(path);
884 }
885 continue;
886 }
887
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700888 std::string sensorType = desc.value("SensorType", "");
889 std::string name = desc.value("Name", "");
Rashmica Gupta665a0a22021-06-30 11:35:28 +1000890 std::replace(name.begin(), name.end(), ' ', '_');
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700891
892 if (!name.empty() && !sensorType.empty())
893 {
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700894 if (unitMap.find(sensorType) == unitMap.end())
895 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500896 error("Sensor type {TYPE} is not supported", "TYPE",
897 sensorType);
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700898 }
899 else
900 {
Rashmica Gupta67d8b9d2021-06-30 11:41:14 +1000901 if (virtualSensorsMap.find(name) != virtualSensorsMap.end())
902 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500903 error("A virtual sensor named {NAME} already exists",
904 "NAME", name);
Rashmica Gupta67d8b9d2021-06-30 11:41:14 +1000905 continue;
906 }
Rashmica Gupta862c3d12021-08-06 12:19:31 +1000907 auto objPath = sensorDbusPath + sensorType + "/" + name;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700908
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700909 auto virtualSensorPtr = std::make_unique<VirtualSensor>(
910 bus, objPath.c_str(), j, name);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700911
Patrick Williams82b39c62021-07-28 16:22:27 -0500912 info("Added a new virtual sensor: {NAME}", "NAME", name);
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700913 virtualSensorPtr->updateVirtualSensor();
914
915 /* Initialize unit value for virtual sensor */
916 virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
Rashmica Guptaa2fa63a2021-08-06 12:21:13 +1000917 virtualSensorPtr->emit_object_added();
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700918
919 virtualSensorsMap.emplace(std::move(name),
920 std::move(virtualSensorPtr));
921 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700922 }
923 else
924 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500925 error(
926 "Sensor type ({TYPE}) or name ({NAME}) not found in config file",
927 "NAME", name, "TYPE", sensorType);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700928 }
929 }
930 else
931 {
Patrick Williams82b39c62021-07-28 16:22:27 -0500932 error("Descriptor for new virtual sensor not found in config file");
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700933 }
934 }
935}
936
937} // namespace virtualSensor
938} // namespace phosphor
939
940/**
941 * @brief Main
942 */
943int main()
944{
945
946 // Get a default event loop
947 auto event = sdeventplus::Event::get_default();
948
949 // Get a handle to system dbus
950 auto bus = sdbusplus::bus::new_default();
951
Matt Spinler6c19e7d2021-01-12 16:26:45 -0600952 // Add the ObjectManager interface
953 sdbusplus::server::manager::manager objManager(bus, "/");
954
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700955 // Create an virtual sensors object
956 phosphor::virtualSensor::VirtualSensors virtualSensors(bus);
957
958 // Request service bus name
959 bus.request_name(busName);
960
961 // Attach the bus to sd_event to service user requests
962 bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
963 event.loop();
964
965 return 0;
966}