blob: 12adad275d5e35e3427db1f9e39d118e9942eeae [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/";
Rashmica Guptae7efe132021-07-27 19:42:11 +100016static constexpr auto entityManagerBusName =
17 "xyz.openbmc_project.EntityManager";
18static constexpr auto vsThresholdsIfaceSuffix = ".Thresholds";
19static constexpr std::array<const char*, 0> calculationIfaces = {};
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070020
21using namespace phosphor::logging;
22
Vijay Khemka51f898e2020-09-09 22:24:18 -070023int handleDbusSignal(sd_bus_message* msg, void* usrData, sd_bus_error*)
24{
25 if (usrData == nullptr)
26 {
27 throw std::runtime_error("Invalid match");
28 }
29
30 auto sdbpMsg = sdbusplus::message::message(msg);
31 std::string msgIfce;
32 std::map<std::string, std::variant<int64_t, double, bool>> msgData;
33
34 sdbpMsg.read(msgIfce, msgData);
35
36 if (msgData.find("Value") != msgData.end())
37 {
38 using namespace phosphor::virtualSensor;
39 VirtualSensor* obj = static_cast<VirtualSensor*>(usrData);
40 // TODO(openbmc/phosphor-virtual-sensor#1): updateVirtualSensor should
41 // be changed to take the information we got from the signal, to avoid
42 // having to do numerous dbus queries.
43 obj->updateVirtualSensor();
44 }
45 return 0;
46}
47
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070048namespace phosphor
49{
50namespace virtualSensor
51{
52
53void printParams(const VirtualSensor::ParamMap& paramMap)
54{
55 for (const auto& p : paramMap)
56 {
57 const auto& p1 = p.first;
58 const auto& p2 = p.second;
59 auto val = p2->getParamValue();
60 std::cout << p1 << " = " << val << "\n";
61 }
62}
63
64double SensorParam::getParamValue()
65{
66 switch (paramType)
67 {
68 case constParam:
69 return value;
70 break;
Vijay Khemka7452a862020-08-11 16:01:23 -070071 case dbusParam:
72 return dbusSensor->getSensorValue();
73 break;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -070074 default:
75 throw std::invalid_argument("param type not supported");
76 }
77}
78
Lei YU0fcf0e12021-06-04 11:14:17 +080079using AssociationList =
80 std::vector<std::tuple<std::string, std::string, std::string>>;
81
82AssociationList getAssociationsFromJson(const Json& j)
83{
84 AssociationList assocs{};
85 try
86 {
87 j.get_to(assocs);
88 }
89 catch (const std::exception& ex)
90 {
91 log<level::ERR>("Failed to parse association",
92 entry("EX=%s", ex.what()));
93 }
94 return assocs;
95}
96
Rashmica Guptae7efe132021-07-27 19:42:11 +100097template <typename U>
98struct VariantToNumber
99{
100 template <typename T>
101 U operator()(const T& t) const
102 {
103 if constexpr (std::is_convertible<T, U>::value)
104 {
105 return static_cast<U>(t);
106 }
107 throw std::invalid_argument("Invalid number type in config\n");
108 }
109};
110
111template <typename U>
112U getNumberFromConfig(const PropertyMap& map, const std::string& name,
113 bool required)
114{
115 if (auto itr = map.find(name); itr != map.end())
116 {
117 return std::visit(VariantToNumber<U>(), itr->second);
118 }
119 else if (required)
120 {
121 log<level::ERR>("Required field missing in config",
122 entry("NAME=%s", name.c_str()));
123 throw std::invalid_argument("Required field missing in config");
124 }
125 return std::numeric_limits<U>::quiet_NaN();
126}
127
128bool isCalculationType(const std::string& interface)
129{
130 auto itr = std::find(calculationIfaces.begin(), calculationIfaces.end(),
131 interface);
132 if (itr != calculationIfaces.end())
133 {
134 return true;
135 }
136 return false;
137}
138
139const std::string getThresholdType(const std::string& direction,
140 uint64_t severity)
141{
142 std::string threshold;
143 std::string suffix;
144 static const std::array thresholdTypes{"Warning", "Critical",
145 "PerformanceLoss", "SoftShutdown",
146 "HardShutdown"};
147
148 if (severity >= thresholdTypes.size())
149 {
150 throw std::invalid_argument(
151 "Invalid threshold severity specified in entity manager");
152 }
153 threshold = thresholdTypes[severity];
154
155 if (direction == "less than")
156 {
157 suffix = "Low";
158 }
159 else if (direction == "greater than")
160 {
161 suffix = "High";
162 }
163 else
164 {
165 throw std::invalid_argument(
166 "Invalid threshold direction specified in entity manager");
167 }
168 return threshold + suffix;
169}
170
171void parseThresholds(Json& thresholds, const PropertyMap& propertyMap)
172{
173 std::string direction;
174
175 auto severity =
176 getNumberFromConfig<uint64_t>(propertyMap, "Severity", true);
177 auto value = getNumberFromConfig<double>(propertyMap, "Value", true);
178
179 auto itr = propertyMap.find("Direction");
180 if (itr != propertyMap.end())
181 {
182 direction = std::get<std::string>(itr->second);
183 }
184
185 auto threshold = getThresholdType(direction, severity);
186 thresholds[threshold] = value;
187}
188
189void VirtualSensor::parseConfigInterface(const PropertyMap& propertyMap,
190 const std::string& sensorType,
191 const std::string& interface)
192{
193 /* Parse sensors / DBus params */
194 if (auto itr = propertyMap.find("Sensors"); itr != propertyMap.end())
195 {
196 auto sensors = std::get<std::vector<std::string>>(itr->second);
197 for (auto sensor : sensors)
198 {
199 std::replace(sensor.begin(), sensor.end(), ' ', '_');
200 auto sensorObjPath = sensorDbusPath + sensorType + "/" + sensor;
201
202 auto paramPtr =
203 std::make_unique<SensorParam>(bus, sensorObjPath, this);
204 symbols.create_variable(sensor);
205 paramMap.emplace(std::move(sensor), std::move(paramPtr));
206 }
207 }
208 /* Get expression string */
209 if (!isCalculationType(interface))
210 {
211 throw std::invalid_argument("Invalid expression in interface");
212 }
213 exprStr = interface;
214
215 /* Get optional min and max input and output values */
216 ValueIface::maxValue(
217 getNumberFromConfig<double>(propertyMap, "MaxValue", false));
218 ValueIface::minValue(
219 getNumberFromConfig<double>(propertyMap, "MinValue", false));
220 maxValidInput =
221 getNumberFromConfig<double>(propertyMap, "MaxValidInput", false);
222 minValidInput =
223 getNumberFromConfig<double>(propertyMap, "MinValidInput", false);
224}
225
Matt Spinlerce675222021-01-14 16:38:09 -0600226void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
227 const std::string& objPath)
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700228{
229
230 static const Json empty{};
231
232 /* Get threshold values if defined in config */
233 auto threshold = sensorConfig.value("Threshold", empty);
Matt Spinlerf15189e2021-01-15 10:13:28 -0600234
Rashmica Gupta3e999192021-06-09 16:17:04 +1000235 createThresholds(threshold, objPath);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700236
Harvey Wuf6443742021-04-09 16:47:36 +0800237 /* Get MaxValue, MinValue setting if defined in config */
238 auto confDesc = sensorConfig.value("Desc", empty);
239 if (auto maxConf = confDesc.find("MaxValue");
240 maxConf != confDesc.end() && maxConf->is_number())
241 {
242 ValueIface::maxValue(maxConf->get<double>());
243 }
244 if (auto minConf = confDesc.find("MinValue");
245 minConf != confDesc.end() && minConf->is_number())
246 {
247 ValueIface::minValue(minConf->get<double>());
248 }
249
Lei YU0fcf0e12021-06-04 11:14:17 +0800250 /* Get optional association */
251 auto assocJson = sensorConfig.value("Associations", empty);
252 if (!assocJson.empty())
253 {
254 auto assocs = getAssociationsFromJson(assocJson);
255 if (!assocs.empty())
256 {
257 associationIface =
258 std::make_unique<AssociationObject>(bus, objPath.c_str());
259 associationIface->associations(assocs);
260 }
261 }
262
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700263 /* Get expression string */
264 exprStr = sensorConfig.value("Expression", "");
265
266 /* Get all the parameter listed in configuration */
267 auto params = sensorConfig.value("Params", empty);
268
269 /* Check for constant parameter */
270 const auto& consParams = params.value("ConstParam", empty);
271 if (!consParams.empty())
272 {
273 for (auto& j : consParams)
274 {
275 if (j.find("ParamName") != j.end())
276 {
277 auto paramPtr = std::make_unique<SensorParam>(j["Value"]);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700278 std::string name = j["ParamName"];
279 symbols.create_variable(name);
280 paramMap.emplace(std::move(name), std::move(paramPtr));
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700281 }
282 else
283 {
284 /* Invalid configuration */
285 throw std::invalid_argument(
286 "ParamName not found in configuration");
287 }
288 }
289 }
290
Vijay Khemka7452a862020-08-11 16:01:23 -0700291 /* Check for dbus parameter */
292 auto dbusParams = params.value("DbusParam", empty);
293 if (!dbusParams.empty())
294 {
295 for (auto& j : dbusParams)
296 {
297 /* Get parameter dbus sensor descriptor */
298 auto desc = j.value("Desc", empty);
299 if ((!desc.empty()) && (j.find("ParamName") != j.end()))
300 {
301 std::string sensorType = desc.value("SensorType", "");
302 std::string name = desc.value("Name", "");
303
304 if (!sensorType.empty() && !name.empty())
305 {
306 std::string objPath(sensorDbusPath);
307 objPath += sensorType + "/" + name;
308
Vijay Khemka51f898e2020-09-09 22:24:18 -0700309 auto paramPtr =
310 std::make_unique<SensorParam>(bus, objPath, this);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700311 std::string name = j["ParamName"];
312 symbols.create_variable(name);
313 paramMap.emplace(std::move(name), std::move(paramPtr));
Vijay Khemka7452a862020-08-11 16:01:23 -0700314 }
315 }
316 }
317 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700318
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700319 symbols.add_constants();
Matt Spinler9f1ef4f2020-11-09 15:59:11 -0600320 symbols.add_package(vecopsPackage);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700321 expression.register_symbol_table(symbols);
322
323 /* parser from exprtk */
324 exprtk::parser<double> parser{};
Matt Spinlerddc6dcd2020-11-09 11:16:31 -0600325 if (!parser.compile(exprStr, expression))
326 {
327 log<level::ERR>("Expression compilation failed");
328
329 for (std::size_t i = 0; i < parser.error_count(); ++i)
330 {
331 auto error = parser.get_error(i);
332
333 log<level::ERR>(
334 fmt::format(
335 "Position: {} Type: {} Message: {}", error.token.position,
336 exprtk::parser_error::to_str(error.mode), error.diagnostic)
337 .c_str());
338 }
339 throw std::runtime_error("Expression compilation failed");
340 }
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700341
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700342 /* Print all parameters for debug purpose only */
343 if (DEBUG)
344 printParams(paramMap);
345}
346
Rashmica Guptae7efe132021-07-27 19:42:11 +1000347void VirtualSensor::initVirtualSensor(const InterfaceMap& interfaceMap,
348 const std::string& objPath,
349 const std::string& sensorType,
350 const std::string& calculationIface)
351{
352 Json thresholds;
353 const std::string vsThresholdsIntf =
354 calculationIface + vsThresholdsIfaceSuffix;
355
356 for (const auto& [interface, propertyMap] : interfaceMap)
357 {
358 /* Each threshold is on it's own interface with a number as a suffix
359 * eg xyz.openbmc_project.Configuration.ModifiedMedian.Thresholds1 */
360 if (interface.find(vsThresholdsIntf) != std::string::npos)
361 {
362 parseThresholds(thresholds, propertyMap);
363 }
364 else if (interface == calculationIface)
365 {
366 parseConfigInterface(propertyMap, sensorType, interface);
367 }
368 }
369
370 createThresholds(thresholds, objPath);
371 symbols.add_constants();
372 symbols.add_package(vecopsPackage);
373 expression.register_symbol_table(symbols);
374
375 /* Print all parameters for debug purpose only */
376 if (DEBUG)
377 {
378 printParams(paramMap);
379 }
380}
381
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700382void VirtualSensor::setSensorValue(double value)
383{
Patrick Williams543bf662021-04-29 09:03:53 -0500384 value = std::clamp(value, ValueIface::minValue(), ValueIface::maxValue());
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700385 ValueIface::value(value);
386}
387
Rashmica Guptae7efe132021-07-27 19:42:11 +1000388double VirtualSensor::calculateValue()
389{
390 // Placeholder until calculation types are added
391 return std::numeric_limits<double>::quiet_NaN();
392}
393
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700394void VirtualSensor::updateVirtualSensor()
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700395{
396 for (auto& param : paramMap)
397 {
398 auto& name = param.first;
399 auto& data = param.second;
400 if (auto var = symbols.get_variable(name))
401 {
402 var->ref() = data->getParamValue();
403 }
404 else
405 {
406 /* Invalid parameter */
407 throw std::invalid_argument("ParamName not found in symbols");
408 }
409 }
Rashmica Guptae7efe132021-07-27 19:42:11 +1000410 auto itr =
411 std::find(calculationIfaces.begin(), calculationIfaces.end(), exprStr);
412 auto val = (itr == calculationIfaces.end()) ? expression.value()
413 : calculateValue();
Vijay Khemka32a71562020-09-10 15:29:18 -0700414
415 /* Set sensor value to dbus interface */
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700416 setSensorValue(val);
Vijay Khemka32a71562020-09-10 15:29:18 -0700417
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700418 if (DEBUG)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000419 {
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700420 std::cout << "Sensor value is " << val << "\n";
Rashmica Guptae7efe132021-07-27 19:42:11 +1000421 }
Vijay Khemka32a71562020-09-10 15:29:18 -0700422
Matt Spinler8f5e6112021-01-15 10:44:32 -0600423 /* Check sensor thresholds and log required message */
Matt Spinlerb306b032021-02-01 10:05:46 -0600424 checkThresholds(val, perfLossIface);
Patrick Williamsfdb826d2021-01-20 14:37:53 -0600425 checkThresholds(val, warningIface);
426 checkThresholds(val, criticalIface);
427 checkThresholds(val, softShutdownIface);
428 checkThresholds(val, hardShutdownIface);
Vijay Khemka3ed9a512020-08-21 16:13:05 -0700429}
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700430
Rashmica Gupta3e999192021-06-09 16:17:04 +1000431void VirtualSensor::createThresholds(const Json& threshold,
432 const std::string& objPath)
433{
434 if (threshold.empty())
435 {
436 return;
437 }
438 // Only create the threshold interfaces if
439 // at least one of their values is present.
440 if (threshold.contains("CriticalHigh") || threshold.contains("CriticalLow"))
441 {
442 criticalIface =
443 std::make_unique<Threshold<CriticalObject>>(bus, objPath.c_str());
444
445 criticalIface->criticalHigh(threshold.value(
446 "CriticalHigh", std::numeric_limits<double>::quiet_NaN()));
447 criticalIface->criticalLow(threshold.value(
448 "CriticalLow", std::numeric_limits<double>::quiet_NaN()));
449 }
450
451 if (threshold.contains("WarningHigh") || threshold.contains("WarningLow"))
452 {
453 warningIface =
454 std::make_unique<Threshold<WarningObject>>(bus, objPath.c_str());
455
456 warningIface->warningHigh(threshold.value(
457 "WarningHigh", std::numeric_limits<double>::quiet_NaN()));
458 warningIface->warningLow(threshold.value(
459 "WarningLow", std::numeric_limits<double>::quiet_NaN()));
460 }
461
462 if (threshold.contains("HardShutdownHigh") ||
463 threshold.contains("HardShutdownLow"))
464 {
465 hardShutdownIface = std::make_unique<Threshold<HardShutdownObject>>(
466 bus, objPath.c_str());
467
468 hardShutdownIface->hardShutdownHigh(threshold.value(
469 "HardShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
470 hardShutdownIface->hardShutdownLow(threshold.value(
471 "HardShutdownLow", std::numeric_limits<double>::quiet_NaN()));
472 }
473
474 if (threshold.contains("SoftShutdownHigh") ||
475 threshold.contains("SoftShutdownLow"))
476 {
477 softShutdownIface = std::make_unique<Threshold<SoftShutdownObject>>(
478 bus, objPath.c_str());
479
480 softShutdownIface->softShutdownHigh(threshold.value(
481 "SoftShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
482 softShutdownIface->softShutdownLow(threshold.value(
483 "SoftShutdownLow", std::numeric_limits<double>::quiet_NaN()));
484 }
485
486 if (threshold.contains("PerformanceLossHigh") ||
487 threshold.contains("PerformanceLossLow"))
488 {
489 perfLossIface = std::make_unique<Threshold<PerformanceLossObject>>(
490 bus, objPath.c_str());
491
492 perfLossIface->performanceLossHigh(threshold.value(
493 "PerformanceLossHigh", std::numeric_limits<double>::quiet_NaN()));
494 perfLossIface->performanceLossLow(threshold.value(
495 "PerformanceLossLow", std::numeric_limits<double>::quiet_NaN()));
496 }
497}
498
Rashmica Guptae7efe132021-07-27 19:42:11 +1000499ManagedObjectType VirtualSensors::getObjectsFromDBus()
500{
501 ManagedObjectType objects;
502
503 try
504 {
505 auto method = bus.new_method_call(entityManagerBusName, "/",
506 "org.freedesktop.DBus.ObjectManager",
507 "GetManagedObjects");
508 auto reply = bus.call(method);
509 reply.read(objects);
510 }
511 catch (const sdbusplus::exception::SdBusError& ex)
512 {
513 // If entity manager isn't running yet, keep going.
514 if (std::string("org.freedesktop.DBus.Error.ServiceUnknown") !=
515 ex.name())
516 {
517 throw ex.name();
518 }
519 }
520
521 return objects;
522}
523
524void VirtualSensors::propertiesChanged(sdbusplus::message::message& msg)
525{
526 std::string path;
527 PropertyMap properties;
528
529 msg.read(path, properties);
530
531 /* We get multiple callbacks for one sensor. 'Type' is a required field and
532 * is a unique label so use to to only proceed once per sensor */
533 if (properties.contains("Type"))
534 {
535 if (isCalculationType(path))
536 {
537 createVirtualSensorsFromDBus(path);
538 }
539 }
540}
541
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700542/** @brief Parsing Virtual Sensor config JSON file */
543Json VirtualSensors::parseConfigFile(const std::string configFile)
544{
545 std::ifstream jsonFile(configFile);
546 if (!jsonFile.is_open())
547 {
548 log<level::ERR>("config JSON file not found",
Patrick Williams1846d822021-06-23 14:44:07 -0500549 entry("FILENAME=%s", configFile.c_str()));
Rashmica Guptae7efe132021-07-27 19:42:11 +1000550 return {};
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700551 }
552
553 auto data = Json::parse(jsonFile, nullptr, false);
554 if (data.is_discarded())
555 {
556 log<level::ERR>("config readings JSON parser failure",
Patrick Williams1846d822021-06-23 14:44:07 -0500557 entry("FILENAME=%s", configFile.c_str()));
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700558 throw std::exception{};
559 }
560
561 return data;
562}
563
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700564std::map<std::string, ValueIface::Unit> unitMap = {
565 {"temperature", ValueIface::Unit::DegreesC},
566 {"fan_tach", ValueIface::Unit::RPMS},
567 {"voltage", ValueIface::Unit::Volts},
568 {"altitude", ValueIface::Unit::Meters},
569 {"current", ValueIface::Unit::Amperes},
570 {"power", ValueIface::Unit::Watts},
571 {"energy", ValueIface::Unit::Joules},
Kumar Thangavel2b56ddb2021-01-13 20:16:11 +0530572 {"utilization", ValueIface::Unit::Percent},
Rashmica Gupta4ac7a7f2021-07-08 12:30:50 +1000573 {"airflow", ValueIface::Unit::CFM},
574 {"pressure", ValueIface::Unit::Pascals}};
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700575
Rashmica Guptae7efe132021-07-27 19:42:11 +1000576const std::string getSensorTypeFromUnit(const std::string& unit)
577{
578 std::string unitPrefix = "xyz.openbmc_project.Sensor.Value.Unit.";
579 for (auto [type, unitObj] : unitMap)
580 {
581 auto unitPath = ValueIface::convertUnitToString(unitObj);
582 if (unitPath == (unitPrefix + unit))
583 {
584 return type;
585 }
586 }
587 return "";
588}
589
590void VirtualSensors::setupMatches()
591{
592 /* Already setup */
593 if (!this->matches.empty())
594 {
595 return;
596 }
597
598 /* Setup matches */
599 auto eventHandler = [this](sdbusplus::message::message& message) {
600 if (message.is_method_error())
601 {
602 log<level::ERR>("Callback method error");
603 return;
604 }
605 this->propertiesChanged(message);
606 };
607
608 for (const char* iface : calculationIfaces)
609 {
610 auto match = std::make_unique<sdbusplus::bus::match::match>(
611 bus,
612 sdbusplus::bus::match::rules::propertiesChangedNamespace(
613 "/xyz/openbmc_project/inventory", iface),
614 eventHandler);
615 this->matches.emplace_back(std::move(match));
616 }
617}
618
619void VirtualSensors::createVirtualSensorsFromDBus(
620 const std::string& calculationIface)
621{
622 if (calculationIface.empty())
623 {
624 log<level::ERR>("No calculation type supplied");
625 return;
626 }
627 auto objects = getObjectsFromDBus();
628
629 /* Get virtual sensors config data */
630 for (const auto& [path, interfaceMap] : objects)
631 {
632 auto objpath = static_cast<std::string>(path);
633 std::string name = path.filename();
634 std::string sensorType, sensorUnit;
635
636 /* Find Virtual Sensor interfaces */
637 if (!interfaceMap.contains(calculationIface))
638 {
639 continue;
640 }
641 if (name.empty())
642 {
643 log<level::ERR>(
644 "Virtual Sensor name not found in entity manager config");
645 continue;
646 }
647 if (virtualSensorsMap.contains(name))
648 {
649 log<level::ERR>("A virtual sensor with this name already exists",
650 entry("NAME=%s", name.c_str()));
651 continue;
652 }
653
654 /* Extract the virtual sensor type as we need this to initialize the
655 * sensor */
656 for (const auto& [interface, propertyMap] : interfaceMap)
657 {
658 if (interface != calculationIface)
659 {
660 continue;
661 }
662 auto itr = propertyMap.find("Units");
663 if (itr != propertyMap.end())
664 {
665 sensorUnit = std::get<std::string>(itr->second);
666 break;
667 }
668 }
669 sensorType = getSensorTypeFromUnit(sensorUnit);
670 if (sensorType.empty())
671 {
672 log<level::ERR>("Sensor unit is not supported",
673 entry("TYPE=%s", sensorUnit.c_str()));
674 continue;
675 }
676
677 try
678 {
679 auto virtObjPath = sensorDbusPath + sensorType + "/" + name;
680
681 auto virtualSensorPtr = std::make_unique<VirtualSensor>(
682 bus, virtObjPath.c_str(), interfaceMap, name, sensorType,
683 calculationIface);
684 log<level::INFO>("Added a new virtual sensor",
685 entry("NAME=%s", name.c_str()));
686 virtualSensorPtr->updateVirtualSensor();
687
688 /* Initialize unit value for virtual sensor */
689 virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
690 virtualSensorPtr->emit_object_added();
691
692 virtualSensorsMap.emplace(name, std::move(virtualSensorPtr));
693
694 /* Setup match for interfaces removed */
695 auto intfRemoved = [this, objpath,
696 name](sdbusplus::message::message& message) {
697 if (!virtualSensorsMap.contains(name))
698 {
699 return;
700 }
701 sdbusplus::message::object_path path;
702 message.read(path);
703 if (static_cast<const std::string&>(path) == objpath)
704 {
705 log<level::INFO>("Removed a virtual sensor",
706 entry("NAME=%s", name.c_str()));
707 virtualSensorsMap.erase(name);
708 }
709 };
710 auto matchOnRemove = std::make_unique<sdbusplus::bus::match::match>(
711 bus,
712 sdbusplus::bus::match::rules::interfacesRemoved() +
713 sdbusplus::bus::match::rules::argNpath(0, objpath),
714 intfRemoved);
715 /* TODO: slight race condition here. Check that the config still
716 * exists */
717 this->matches.emplace_back(std::move(matchOnRemove));
718 }
719 catch (std::invalid_argument& ia)
720 {
721 log<level::ERR>("Failed to set up virtual sensor",
722 entry("Error=%s", ia.what()));
723 }
724 }
725}
726
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700727void VirtualSensors::createVirtualSensors()
728{
729 static const Json empty{};
730
731 auto data = parseConfigFile(VIRTUAL_SENSOR_CONFIG_FILE);
Rashmica Guptae7efe132021-07-27 19:42:11 +1000732
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700733 // print values
734 if (DEBUG)
Rashmica Guptae7efe132021-07-27 19:42:11 +1000735 {
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700736 std::cout << "Config json data:\n" << data << "\n\n";
Rashmica Guptae7efe132021-07-27 19:42:11 +1000737 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700738
739 /* Get virtual sensors config data */
740 for (const auto& j : data)
741 {
742 auto desc = j.value("Desc", empty);
743 if (!desc.empty())
744 {
Rashmica Guptae7efe132021-07-27 19:42:11 +1000745 if (desc.value("Config", "") == "D-Bus")
746 {
747 /* Look on D-Bus for a virtual sensor config. Set up matches
748 * first because the configs may not be on D-Bus yet and we
749 * don't want to miss them */
750 setupMatches();
751
752 if (desc.contains("Type"))
753 {
754 auto path = "xyz.openbmc_project.Configuration." +
755 desc.value("Type", "");
756 if (!isCalculationType(path))
757 {
758 log<level::ERR>(
759 "Invalid calculation type supplied\n",
760 entry("TYPE=%s", desc.value("Type", "").c_str()));
761 continue;
762 }
763 createVirtualSensorsFromDBus(path);
764 }
765 continue;
766 }
767
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700768 std::string sensorType = desc.value("SensorType", "");
769 std::string name = desc.value("Name", "");
Rashmica Gupta665a0a22021-06-30 11:35:28 +1000770 std::replace(name.begin(), name.end(), ' ', '_');
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700771
772 if (!name.empty() && !sensorType.empty())
773 {
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700774 if (unitMap.find(sensorType) == unitMap.end())
775 {
776 log<level::ERR>("Sensor type is not supported",
Patrick Williams1846d822021-06-23 14:44:07 -0500777 entry("TYPE=%s", sensorType.c_str()));
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700778 }
779 else
780 {
Rashmica Gupta67d8b9d2021-06-30 11:41:14 +1000781 if (virtualSensorsMap.find(name) != virtualSensorsMap.end())
782 {
783 log<level::ERR>(
784 "A virtual sensor with this name already exists",
785 entry("TYPE=%s", name.c_str()));
786 continue;
787 }
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700788 std::string objPath(sensorDbusPath);
789 objPath += sensorType + "/" + name;
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700790
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700791 auto virtualSensorPtr = std::make_unique<VirtualSensor>(
792 bus, objPath.c_str(), j, name);
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700793
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700794 log<level::INFO>("Added a new virtual sensor",
Patrick Williams1846d822021-06-23 14:44:07 -0500795 entry("NAME=%s", name.c_str()));
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700796 virtualSensorPtr->updateVirtualSensor();
797
798 /* Initialize unit value for virtual sensor */
799 virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
Rashmica Guptaa2fa63a2021-08-06 12:21:13 +1000800 virtualSensorPtr->emit_object_added();
Vijay Khemkae0d371e2020-09-21 18:35:52 -0700801
802 virtualSensorsMap.emplace(std::move(name),
803 std::move(virtualSensorPtr));
804 }
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700805 }
806 else
807 {
808 log<level::ERR>("Sensor type or name not found in config file");
809 }
810 }
811 else
812 {
813 log<level::ERR>(
814 "Descriptor for new virtual sensor not found in config file");
815 }
816 }
817}
818
819} // namespace virtualSensor
820} // namespace phosphor
821
822/**
823 * @brief Main
824 */
825int main()
826{
827
828 // Get a default event loop
829 auto event = sdeventplus::Event::get_default();
830
831 // Get a handle to system dbus
832 auto bus = sdbusplus::bus::new_default();
833
Matt Spinler6c19e7d2021-01-12 16:26:45 -0600834 // Add the ObjectManager interface
835 sdbusplus::server::manager::manager objManager(bus, "/");
836
Vijay Khemkaabcc94f2020-08-11 15:27:44 -0700837 // Create an virtual sensors object
838 phosphor::virtualSensor::VirtualSensors virtualSensors(bus);
839
840 // Request service bus name
841 bus.request_name(busName);
842
843 // Attach the bus to sd_event to service user requests
844 bus.attach_event(event.get(), SD_EVENT_PRIORITY_NORMAL);
845 event.loop();
846
847 return 0;
848}