1abcc94faSVijay Khemka #include "virtualSensor.hpp"
2abcc94faSVijay Khemka 
3abcc94faSVijay Khemka #include "config.hpp"
4abcc94faSVijay Khemka 
582b39c66SPatrick Williams #include <phosphor-logging/lg2.hpp>
6abcc94faSVijay Khemka 
7abcc94faSVijay Khemka #include <fstream>
8abcc94faSVijay Khemka 
9abcc94faSVijay Khemka static constexpr bool DEBUG = false;
10abcc94faSVijay Khemka static constexpr auto busName = "xyz.openbmc_project.VirtualSensor";
11abcc94faSVijay Khemka static constexpr auto sensorDbusPath = "/xyz/openbmc_project/sensors/";
12e7efe135SRashmica Gupta static constexpr auto entityManagerBusName =
13e7efe135SRashmica Gupta     "xyz.openbmc_project.EntityManager";
14e7efe135SRashmica Gupta static constexpr auto vsThresholdsIfaceSuffix = ".Thresholds";
15304fd0e4SRashmica Gupta static constexpr std::array<const char*, 1> calculationIfaces = {
16304fd0e4SRashmica Gupta     "xyz.openbmc_project.Configuration.ModifiedMedian"};
171dff7dceSRashmica Gupta static constexpr auto defaultHysteresis = 0;
18abcc94faSVijay Khemka 
1982b39c66SPatrick Williams PHOSPHOR_LOG2_USING_WITH_FLAGS;
20abcc94faSVijay Khemka 
2151f898e2SVijay Khemka int handleDbusSignal(sd_bus_message* msg, void* usrData, sd_bus_error*)
2251f898e2SVijay Khemka {
2351f898e2SVijay Khemka     if (usrData == nullptr)
2451f898e2SVijay Khemka     {
2551f898e2SVijay Khemka         throw std::runtime_error("Invalid match");
2651f898e2SVijay Khemka     }
2751f898e2SVijay Khemka 
288e11cccbSPatrick Williams     auto sdbpMsg = sdbusplus::message_t(msg);
2951f898e2SVijay Khemka     std::string msgIfce;
3051f898e2SVijay Khemka     std::map<std::string, std::variant<int64_t, double, bool>> msgData;
3151f898e2SVijay Khemka 
3251f898e2SVijay Khemka     sdbpMsg.read(msgIfce, msgData);
3351f898e2SVijay Khemka 
3451f898e2SVijay Khemka     if (msgData.find("Value") != msgData.end())
3551f898e2SVijay Khemka     {
3651f898e2SVijay Khemka         using namespace phosphor::virtualSensor;
3751f898e2SVijay Khemka         VirtualSensor* obj = static_cast<VirtualSensor*>(usrData);
3851f898e2SVijay Khemka         // TODO(openbmc/phosphor-virtual-sensor#1): updateVirtualSensor should
3951f898e2SVijay Khemka         // be changed to take the information we got from the signal, to avoid
4051f898e2SVijay Khemka         // having to do numerous dbus queries.
4151f898e2SVijay Khemka         obj->updateVirtualSensor();
4251f898e2SVijay Khemka     }
4351f898e2SVijay Khemka     return 0;
4451f898e2SVijay Khemka }
4551f898e2SVijay Khemka 
46abcc94faSVijay Khemka namespace phosphor
47abcc94faSVijay Khemka {
48abcc94faSVijay Khemka namespace virtualSensor
49abcc94faSVijay Khemka {
50abcc94faSVijay Khemka 
51abcc94faSVijay Khemka void printParams(const VirtualSensor::ParamMap& paramMap)
52abcc94faSVijay Khemka {
53abcc94faSVijay Khemka     for (const auto& p : paramMap)
54abcc94faSVijay Khemka     {
55abcc94faSVijay Khemka         const auto& p1 = p.first;
56abcc94faSVijay Khemka         const auto& p2 = p.second;
57abcc94faSVijay Khemka         auto val = p2->getParamValue();
58fbd7145eSPatrick Williams         debug("Parameter: {PARAM} = {VALUE}", "PARAM", p1, "VALUE", val);
59abcc94faSVijay Khemka     }
60abcc94faSVijay Khemka }
61abcc94faSVijay Khemka 
62abcc94faSVijay Khemka double SensorParam::getParamValue()
63abcc94faSVijay Khemka {
64abcc94faSVijay Khemka     switch (paramType)
65abcc94faSVijay Khemka     {
66abcc94faSVijay Khemka         case constParam:
67abcc94faSVijay Khemka             return value;
68abcc94faSVijay Khemka             break;
697452a867SVijay Khemka         case dbusParam:
707452a867SVijay Khemka             return dbusSensor->getSensorValue();
717452a867SVijay Khemka             break;
72abcc94faSVijay Khemka         default:
73abcc94faSVijay Khemka             throw std::invalid_argument("param type not supported");
74abcc94faSVijay Khemka     }
75abcc94faSVijay Khemka }
76abcc94faSVijay Khemka 
770fcf0e1cSLei YU using AssociationList =
780fcf0e1cSLei YU     std::vector<std::tuple<std::string, std::string, std::string>>;
790fcf0e1cSLei YU 
800fcf0e1cSLei YU AssociationList getAssociationsFromJson(const Json& j)
810fcf0e1cSLei YU {
820fcf0e1cSLei YU     AssociationList assocs{};
830fcf0e1cSLei YU     try
840fcf0e1cSLei YU     {
850fcf0e1cSLei YU         j.get_to(assocs);
860fcf0e1cSLei YU     }
870fcf0e1cSLei YU     catch (const std::exception& ex)
880fcf0e1cSLei YU     {
8982b39c66SPatrick Williams         error("Failed to parse association: {ERROR}", "ERROR", ex);
900fcf0e1cSLei YU     }
910fcf0e1cSLei YU     return assocs;
920fcf0e1cSLei YU }
930fcf0e1cSLei YU 
94e7efe135SRashmica Gupta template <typename U>
95e7efe135SRashmica Gupta struct VariantToNumber
96e7efe135SRashmica Gupta {
97e7efe135SRashmica Gupta     template <typename T>
98e7efe135SRashmica Gupta     U operator()(const T& t) const
99e7efe135SRashmica Gupta     {
100e7efe135SRashmica Gupta         if constexpr (std::is_convertible<T, U>::value)
101e7efe135SRashmica Gupta         {
102e7efe135SRashmica Gupta             return static_cast<U>(t);
103e7efe135SRashmica Gupta         }
104e7efe135SRashmica Gupta         throw std::invalid_argument("Invalid number type in config\n");
105e7efe135SRashmica Gupta     }
106e7efe135SRashmica Gupta };
107e7efe135SRashmica Gupta 
108e7efe135SRashmica Gupta template <typename U>
109e7efe135SRashmica Gupta U getNumberFromConfig(const PropertyMap& map, const std::string& name,
110190f6d06SJiaqing Zhao                       bool required,
111190f6d06SJiaqing Zhao                       U defaultValue = std::numeric_limits<U>::quiet_NaN())
112e7efe135SRashmica Gupta {
113e7efe135SRashmica Gupta     if (auto itr = map.find(name); itr != map.end())
114e7efe135SRashmica Gupta     {
115e7efe135SRashmica Gupta         return std::visit(VariantToNumber<U>(), itr->second);
116e7efe135SRashmica Gupta     }
117e7efe135SRashmica Gupta     else if (required)
118e7efe135SRashmica Gupta     {
11982b39c66SPatrick Williams         error("Required field {NAME} missing in config", "NAME", name);
120e7efe135SRashmica Gupta         throw std::invalid_argument("Required field missing in config");
121e7efe135SRashmica Gupta     }
122190f6d06SJiaqing Zhao     return defaultValue;
123e7efe135SRashmica Gupta }
124e7efe135SRashmica Gupta 
125e7efe135SRashmica Gupta bool isCalculationType(const std::string& interface)
126e7efe135SRashmica Gupta {
127e7efe135SRashmica Gupta     auto itr = std::find(calculationIfaces.begin(), calculationIfaces.end(),
128e7efe135SRashmica Gupta                          interface);
129e7efe135SRashmica Gupta     if (itr != calculationIfaces.end())
130e7efe135SRashmica Gupta     {
131e7efe135SRashmica Gupta         return true;
132e7efe135SRashmica Gupta     }
133e7efe135SRashmica Gupta     return false;
134e7efe135SRashmica Gupta }
135e7efe135SRashmica Gupta 
136e7efe135SRashmica Gupta const std::string getThresholdType(const std::string& direction,
13705b1d417SRashmica Gupta                                    const std::string& severity)
138e7efe135SRashmica Gupta {
139e7efe135SRashmica Gupta     std::string suffix;
140e7efe135SRashmica Gupta 
141e7efe135SRashmica Gupta     if (direction == "less than")
142e7efe135SRashmica Gupta     {
143e7efe135SRashmica Gupta         suffix = "Low";
144e7efe135SRashmica Gupta     }
145e7efe135SRashmica Gupta     else if (direction == "greater than")
146e7efe135SRashmica Gupta     {
147e7efe135SRashmica Gupta         suffix = "High";
148e7efe135SRashmica Gupta     }
149e7efe135SRashmica Gupta     else
150e7efe135SRashmica Gupta     {
151e7efe135SRashmica Gupta         throw std::invalid_argument(
152e7efe135SRashmica Gupta             "Invalid threshold direction specified in entity manager");
153e7efe135SRashmica Gupta     }
15405b1d417SRashmica Gupta     return severity + suffix;
15505b1d417SRashmica Gupta }
15605b1d417SRashmica Gupta 
15705b1d417SRashmica Gupta std::string getSeverityField(const PropertyMap& propertyMap)
15805b1d417SRashmica Gupta {
15905b1d417SRashmica Gupta     static const std::array thresholdTypes{"Warning", "Critical",
16005b1d417SRashmica Gupta                                            "PerformanceLoss", "SoftShutdown",
16105b1d417SRashmica Gupta                                            "HardShutdown"};
16205b1d417SRashmica Gupta 
16305b1d417SRashmica Gupta     std::string severity;
16405b1d417SRashmica Gupta     if (auto itr = propertyMap.find("Severity"); itr != propertyMap.end())
16505b1d417SRashmica Gupta     {
16605b1d417SRashmica Gupta         /* Severity should be a string, but can be an unsigned int */
16705b1d417SRashmica Gupta         if (std::holds_alternative<std::string>(itr->second))
16805b1d417SRashmica Gupta         {
16905b1d417SRashmica Gupta             severity = std::get<std::string>(itr->second);
17005b1d417SRashmica Gupta             if (0 == std::ranges::count(thresholdTypes, severity))
17105b1d417SRashmica Gupta             {
17205b1d417SRashmica Gupta                 throw std::invalid_argument(
17305b1d417SRashmica Gupta                     "Invalid threshold severity specified in entity manager");
17405b1d417SRashmica Gupta             }
17505b1d417SRashmica Gupta         }
17605b1d417SRashmica Gupta         else
17705b1d417SRashmica Gupta         {
17805b1d417SRashmica Gupta             auto sev =
17905b1d417SRashmica Gupta                 getNumberFromConfig<uint64_t>(propertyMap, "Severity", true);
18005b1d417SRashmica Gupta             /* Checking bounds ourselves so we throw invalid argument on
18105b1d417SRashmica Gupta              * invalid user input */
18205b1d417SRashmica Gupta             if (sev >= thresholdTypes.size())
18305b1d417SRashmica Gupta             {
18405b1d417SRashmica Gupta                 throw std::invalid_argument(
18505b1d417SRashmica Gupta                     "Invalid threshold severity specified in entity manager");
18605b1d417SRashmica Gupta             }
18705b1d417SRashmica Gupta             severity = thresholdTypes.at(sev);
18805b1d417SRashmica Gupta         }
18905b1d417SRashmica Gupta     }
19005b1d417SRashmica Gupta     return severity;
191e7efe135SRashmica Gupta }
192e7efe135SRashmica Gupta 
193e7efe135SRashmica Gupta void parseThresholds(Json& thresholds, const PropertyMap& propertyMap)
194e7efe135SRashmica Gupta {
195e7efe135SRashmica Gupta     std::string direction;
196e7efe135SRashmica Gupta 
197e7efe135SRashmica Gupta     auto value = getNumberFromConfig<double>(propertyMap, "Value", true);
198e7efe135SRashmica Gupta 
19905b1d417SRashmica Gupta     auto severity = getSeverityField(propertyMap);
20005b1d417SRashmica Gupta 
20105b1d417SRashmica Gupta     if (auto itr = propertyMap.find("Direction"); itr != propertyMap.end())
202e7efe135SRashmica Gupta     {
203e7efe135SRashmica Gupta         direction = std::get<std::string>(itr->second);
204e7efe135SRashmica Gupta     }
205e7efe135SRashmica Gupta 
206e7efe135SRashmica Gupta     auto threshold = getThresholdType(direction, severity);
207e7efe135SRashmica Gupta     thresholds[threshold] = value;
2081dff7dceSRashmica Gupta 
2091dff7dceSRashmica Gupta     auto hysteresis =
2101dff7dceSRashmica Gupta         getNumberFromConfig<double>(propertyMap, "Hysteresis", false);
2111dff7dceSRashmica Gupta     if (hysteresis != std::numeric_limits<double>::quiet_NaN())
2121dff7dceSRashmica Gupta     {
2131dff7dceSRashmica Gupta         thresholds[threshold + "Hysteresis"] = hysteresis;
2141dff7dceSRashmica Gupta     }
215e7efe135SRashmica Gupta }
216e7efe135SRashmica Gupta 
217e7efe135SRashmica Gupta void VirtualSensor::parseConfigInterface(const PropertyMap& propertyMap,
218e7efe135SRashmica Gupta                                          const std::string& sensorType,
219e7efe135SRashmica Gupta                                          const std::string& interface)
220e7efe135SRashmica Gupta {
221e7efe135SRashmica Gupta     /* Parse sensors / DBus params */
222e7efe135SRashmica Gupta     if (auto itr = propertyMap.find("Sensors"); itr != propertyMap.end())
223e7efe135SRashmica Gupta     {
224e7efe135SRashmica Gupta         auto sensors = std::get<std::vector<std::string>>(itr->second);
225e7efe135SRashmica Gupta         for (auto sensor : sensors)
226e7efe135SRashmica Gupta         {
227e7efe135SRashmica Gupta             std::replace(sensor.begin(), sensor.end(), ' ', '_');
228e7efe135SRashmica Gupta             auto sensorObjPath = sensorDbusPath + sensorType + "/" + sensor;
229e7efe135SRashmica Gupta 
230e7efe135SRashmica Gupta             auto paramPtr =
231e7efe135SRashmica Gupta                 std::make_unique<SensorParam>(bus, sensorObjPath, this);
232e7efe135SRashmica Gupta             symbols.create_variable(sensor);
233e7efe135SRashmica Gupta             paramMap.emplace(std::move(sensor), std::move(paramPtr));
234e7efe135SRashmica Gupta         }
235e7efe135SRashmica Gupta     }
236e7efe135SRashmica Gupta     /* Get expression string */
237e7efe135SRashmica Gupta     if (!isCalculationType(interface))
238e7efe135SRashmica Gupta     {
239e7efe135SRashmica Gupta         throw std::invalid_argument("Invalid expression in interface");
240e7efe135SRashmica Gupta     }
241e7efe135SRashmica Gupta     exprStr = interface;
242e7efe135SRashmica Gupta 
243e7efe135SRashmica Gupta     /* Get optional min and max input and output values */
244e7efe135SRashmica Gupta     ValueIface::maxValue(
245e7efe135SRashmica Gupta         getNumberFromConfig<double>(propertyMap, "MaxValue", false));
246e7efe135SRashmica Gupta     ValueIface::minValue(
247e7efe135SRashmica Gupta         getNumberFromConfig<double>(propertyMap, "MinValue", false));
248e7efe135SRashmica Gupta     maxValidInput =
249190f6d06SJiaqing Zhao         getNumberFromConfig<double>(propertyMap, "MaxValidInput", false,
250190f6d06SJiaqing Zhao                                     std::numeric_limits<double>::infinity());
251e7efe135SRashmica Gupta     minValidInput =
252190f6d06SJiaqing Zhao         getNumberFromConfig<double>(propertyMap, "MinValidInput", false,
253190f6d06SJiaqing Zhao                                     -std::numeric_limits<double>::infinity());
254e7efe135SRashmica Gupta }
255e7efe135SRashmica Gupta 
256ce675228SMatt Spinler void VirtualSensor::initVirtualSensor(const Json& sensorConfig,
257ce675228SMatt Spinler                                       const std::string& objPath)
258abcc94faSVijay Khemka {
259abcc94faSVijay Khemka     static const Json empty{};
260abcc94faSVijay Khemka 
261abcc94faSVijay Khemka     /* Get threshold values if defined in config */
262abcc94faSVijay Khemka     auto threshold = sensorConfig.value("Threshold", empty);
263f15189e3SMatt Spinler 
2643e99919bSRashmica Gupta     createThresholds(threshold, objPath);
265abcc94faSVijay Khemka 
266f6443742SHarvey Wu     /* Get MaxValue, MinValue setting if defined in config */
267f6443742SHarvey Wu     auto confDesc = sensorConfig.value("Desc", empty);
268f6443742SHarvey Wu     if (auto maxConf = confDesc.find("MaxValue");
269f6443742SHarvey Wu         maxConf != confDesc.end() && maxConf->is_number())
270f6443742SHarvey Wu     {
271f6443742SHarvey Wu         ValueIface::maxValue(maxConf->get<double>());
272f6443742SHarvey Wu     }
273f6443742SHarvey Wu     if (auto minConf = confDesc.find("MinValue");
274f6443742SHarvey Wu         minConf != confDesc.end() && minConf->is_number())
275f6443742SHarvey Wu     {
276f6443742SHarvey Wu         ValueIface::minValue(minConf->get<double>());
277f6443742SHarvey Wu     }
278f6443742SHarvey Wu 
2790fcf0e1cSLei YU     /* Get optional association */
2800fcf0e1cSLei YU     auto assocJson = sensorConfig.value("Associations", empty);
2810fcf0e1cSLei YU     if (!assocJson.empty())
2820fcf0e1cSLei YU     {
2830fcf0e1cSLei YU         auto assocs = getAssociationsFromJson(assocJson);
2840fcf0e1cSLei YU         if (!assocs.empty())
2850fcf0e1cSLei YU         {
2860fcf0e1cSLei YU             associationIface =
2870fcf0e1cSLei YU                 std::make_unique<AssociationObject>(bus, objPath.c_str());
2880fcf0e1cSLei YU             associationIface->associations(assocs);
2890fcf0e1cSLei YU         }
2900fcf0e1cSLei YU     }
2910fcf0e1cSLei YU 
292abcc94faSVijay Khemka     /* Get expression string */
29303c4c8e2SPatrick Williams     static constexpr auto exprKey = "Expression";
29403c4c8e2SPatrick Williams     if (sensorConfig.contains(exprKey))
29503c4c8e2SPatrick Williams     {
296a959678cSPatrick Williams         auto& ref = sensorConfig.at(exprKey);
29703c4c8e2SPatrick Williams         if (ref.is_array())
29803c4c8e2SPatrick Williams         {
29903c4c8e2SPatrick Williams             exprStr = std::string{};
30003c4c8e2SPatrick Williams             for (auto& s : ref)
30103c4c8e2SPatrick Williams             {
30203c4c8e2SPatrick Williams                 exprStr += s;
30303c4c8e2SPatrick Williams             }
30403c4c8e2SPatrick Williams         }
30503c4c8e2SPatrick Williams         else if (ref.is_string())
30603c4c8e2SPatrick Williams         {
30703c4c8e2SPatrick Williams             exprStr = std::string{ref};
30803c4c8e2SPatrick Williams         }
30903c4c8e2SPatrick Williams     }
310abcc94faSVijay Khemka 
311abcc94faSVijay Khemka     /* Get all the parameter listed in configuration */
312abcc94faSVijay Khemka     auto params = sensorConfig.value("Params", empty);
313abcc94faSVijay Khemka 
314abcc94faSVijay Khemka     /* Check for constant parameter */
315abcc94faSVijay Khemka     const auto& consParams = params.value("ConstParam", empty);
316abcc94faSVijay Khemka     if (!consParams.empty())
317abcc94faSVijay Khemka     {
318abcc94faSVijay Khemka         for (auto& j : consParams)
319abcc94faSVijay Khemka         {
320abcc94faSVijay Khemka             if (j.find("ParamName") != j.end())
321abcc94faSVijay Khemka             {
322abcc94faSVijay Khemka                 auto paramPtr = std::make_unique<SensorParam>(j["Value"]);
3233ed9a516SVijay Khemka                 std::string name = j["ParamName"];
3243ed9a516SVijay Khemka                 symbols.create_variable(name);
3253ed9a516SVijay Khemka                 paramMap.emplace(std::move(name), std::move(paramPtr));
326abcc94faSVijay Khemka             }
327abcc94faSVijay Khemka             else
328abcc94faSVijay Khemka             {
329abcc94faSVijay Khemka                 /* Invalid configuration */
330abcc94faSVijay Khemka                 throw std::invalid_argument(
331abcc94faSVijay Khemka                     "ParamName not found in configuration");
332abcc94faSVijay Khemka             }
333abcc94faSVijay Khemka         }
334abcc94faSVijay Khemka     }
335abcc94faSVijay Khemka 
3367452a867SVijay Khemka     /* Check for dbus parameter */
3377452a867SVijay Khemka     auto dbusParams = params.value("DbusParam", empty);
3387452a867SVijay Khemka     if (!dbusParams.empty())
3397452a867SVijay Khemka     {
3407452a867SVijay Khemka         for (auto& j : dbusParams)
3417452a867SVijay Khemka         {
3427452a867SVijay Khemka             /* Get parameter dbus sensor descriptor */
3437452a867SVijay Khemka             auto desc = j.value("Desc", empty);
3447452a867SVijay Khemka             if ((!desc.empty()) && (j.find("ParamName") != j.end()))
3457452a867SVijay Khemka             {
3467452a867SVijay Khemka                 std::string sensorType = desc.value("SensorType", "");
3477452a867SVijay Khemka                 std::string name = desc.value("Name", "");
3487452a867SVijay Khemka 
3497452a867SVijay Khemka                 if (!sensorType.empty() && !name.empty())
3507452a867SVijay Khemka                 {
3511204b433SGeorge Liu                     auto path = sensorDbusPath + sensorType + "/" + name;
3527452a867SVijay Khemka 
35351f898e2SVijay Khemka                     auto paramPtr =
3541204b433SGeorge Liu                         std::make_unique<SensorParam>(bus, path, this);
3551204b433SGeorge Liu                     std::string paramName = j["ParamName"];
3561204b433SGeorge Liu                     symbols.create_variable(paramName);
3571204b433SGeorge Liu                     paramMap.emplace(std::move(paramName), std::move(paramPtr));
3587452a867SVijay Khemka                 }
3597452a867SVijay Khemka             }
3607452a867SVijay Khemka         }
3617452a867SVijay Khemka     }
362abcc94faSVijay Khemka 
3633ed9a516SVijay Khemka     symbols.add_constants();
3649f1ef4f5SMatt Spinler     symbols.add_package(vecopsPackage);
3653ed9a516SVijay Khemka     expression.register_symbol_table(symbols);
3663ed9a516SVijay Khemka 
3673ed9a516SVijay Khemka     /* parser from exprtk */
3683ed9a516SVijay Khemka     exprtk::parser<double> parser{};
369ddc6dcd6SMatt Spinler     if (!parser.compile(exprStr, expression))
370ddc6dcd6SMatt Spinler     {
37182b39c66SPatrick Williams         error("Expression compilation failed");
372ddc6dcd6SMatt Spinler 
373ddc6dcd6SMatt Spinler         for (std::size_t i = 0; i < parser.error_count(); ++i)
374ddc6dcd6SMatt Spinler         {
37582b39c66SPatrick Williams             auto err = parser.get_error(i);
37682b39c66SPatrick Williams             error("Error parsing token at {POSITION}: {ERROR}", "POSITION",
37782b39c66SPatrick Williams                   err.token.position, "TYPE",
37882b39c66SPatrick Williams                   exprtk::parser_error::to_str(err.mode), "ERROR",
37982b39c66SPatrick Williams                   err.diagnostic);
380ddc6dcd6SMatt Spinler         }
381ddc6dcd6SMatt Spinler         throw std::runtime_error("Expression compilation failed");
382ddc6dcd6SMatt Spinler     }
3833ed9a516SVijay Khemka 
384abcc94faSVijay Khemka     /* Print all parameters for debug purpose only */
385abcc94faSVijay Khemka     if (DEBUG)
386abcc94faSVijay Khemka         printParams(paramMap);
387abcc94faSVijay Khemka }
388abcc94faSVijay Khemka 
389e7efe135SRashmica Gupta void VirtualSensor::initVirtualSensor(const InterfaceMap& interfaceMap,
390e7efe135SRashmica Gupta                                       const std::string& objPath,
391e7efe135SRashmica Gupta                                       const std::string& sensorType,
392e7efe135SRashmica Gupta                                       const std::string& calculationIface)
393e7efe135SRashmica Gupta {
394e7efe135SRashmica Gupta     Json thresholds;
395e7efe135SRashmica Gupta     const std::string vsThresholdsIntf =
396e7efe135SRashmica Gupta         calculationIface + vsThresholdsIfaceSuffix;
397e7efe135SRashmica Gupta 
398e7efe135SRashmica Gupta     for (const auto& [interface, propertyMap] : interfaceMap)
399e7efe135SRashmica Gupta     {
400e7efe135SRashmica Gupta         /* Each threshold is on it's own interface with a number as a suffix
401e7efe135SRashmica Gupta          * eg xyz.openbmc_project.Configuration.ModifiedMedian.Thresholds1 */
402e7efe135SRashmica Gupta         if (interface.find(vsThresholdsIntf) != std::string::npos)
403e7efe135SRashmica Gupta         {
404e7efe135SRashmica Gupta             parseThresholds(thresholds, propertyMap);
405e7efe135SRashmica Gupta         }
406e7efe135SRashmica Gupta         else if (interface == calculationIface)
407e7efe135SRashmica Gupta         {
408e7efe135SRashmica Gupta             parseConfigInterface(propertyMap, sensorType, interface);
409e7efe135SRashmica Gupta         }
410e7efe135SRashmica Gupta     }
411e7efe135SRashmica Gupta 
412e7efe135SRashmica Gupta     createThresholds(thresholds, objPath);
413e7efe135SRashmica Gupta     symbols.add_constants();
414e7efe135SRashmica Gupta     symbols.add_package(vecopsPackage);
415e7efe135SRashmica Gupta     expression.register_symbol_table(symbols);
416e7efe135SRashmica Gupta 
417e7efe135SRashmica Gupta     /* Print all parameters for debug purpose only */
418e7efe135SRashmica Gupta     if (DEBUG)
419e7efe135SRashmica Gupta     {
420e7efe135SRashmica Gupta         printParams(paramMap);
421e7efe135SRashmica Gupta     }
422e7efe135SRashmica Gupta }
423e7efe135SRashmica Gupta 
424abcc94faSVijay Khemka void VirtualSensor::setSensorValue(double value)
425abcc94faSVijay Khemka {
426543bf668SPatrick Williams     value = std::clamp(value, ValueIface::minValue(), ValueIface::maxValue());
427abcc94faSVijay Khemka     ValueIface::value(value);
428abcc94faSVijay Khemka }
429abcc94faSVijay Khemka 
430304fd0e4SRashmica Gupta double VirtualSensor::calculateValue(const std::string& calculation,
431304fd0e4SRashmica Gupta                                      const VirtualSensor::ParamMap& paramMap)
432e7efe135SRashmica Gupta {
433304fd0e4SRashmica Gupta     auto itr = std::find(calculationIfaces.begin(), calculationIfaces.end(),
434304fd0e4SRashmica Gupta                          calculation);
435304fd0e4SRashmica Gupta     if (itr == calculationIfaces.end())
436304fd0e4SRashmica Gupta     {
437e7efe135SRashmica Gupta         return std::numeric_limits<double>::quiet_NaN();
438e7efe135SRashmica Gupta     }
439304fd0e4SRashmica Gupta     else if (calculation == "xyz.openbmc_project.Configuration.ModifiedMedian")
440304fd0e4SRashmica Gupta     {
441304fd0e4SRashmica Gupta         return calculateModifiedMedianValue(paramMap);
442304fd0e4SRashmica Gupta     }
443304fd0e4SRashmica Gupta     return std::numeric_limits<double>::quiet_NaN();
444304fd0e4SRashmica Gupta }
445304fd0e4SRashmica Gupta 
446304fd0e4SRashmica Gupta bool VirtualSensor::sensorInRange(double value)
447304fd0e4SRashmica Gupta {
448304fd0e4SRashmica Gupta     if (value <= this->maxValidInput && value >= this->minValidInput)
449304fd0e4SRashmica Gupta     {
450304fd0e4SRashmica Gupta         return true;
451304fd0e4SRashmica Gupta     }
452304fd0e4SRashmica Gupta     return false;
453304fd0e4SRashmica Gupta }
454e7efe135SRashmica Gupta 
455abcc94faSVijay Khemka void VirtualSensor::updateVirtualSensor()
4563ed9a516SVijay Khemka {
4573ed9a516SVijay Khemka     for (auto& param : paramMap)
4583ed9a516SVijay Khemka     {
4593ed9a516SVijay Khemka         auto& name = param.first;
4603ed9a516SVijay Khemka         auto& data = param.second;
4613ed9a516SVijay Khemka         if (auto var = symbols.get_variable(name))
4623ed9a516SVijay Khemka         {
4633ed9a516SVijay Khemka             var->ref() = data->getParamValue();
4643ed9a516SVijay Khemka         }
4653ed9a516SVijay Khemka         else
4663ed9a516SVijay Khemka         {
4673ed9a516SVijay Khemka             /* Invalid parameter */
4683ed9a516SVijay Khemka             throw std::invalid_argument("ParamName not found in symbols");
4693ed9a516SVijay Khemka         }
4703ed9a516SVijay Khemka     }
471e7efe135SRashmica Gupta     auto itr =
472e7efe135SRashmica Gupta         std::find(calculationIfaces.begin(), calculationIfaces.end(), exprStr);
473304fd0e4SRashmica Gupta     auto val = (itr == calculationIfaces.end())
474304fd0e4SRashmica Gupta                    ? expression.value()
475304fd0e4SRashmica Gupta                    : calculateValue(exprStr, paramMap);
47632a7156bSVijay Khemka 
47732a7156bSVijay Khemka     /* Set sensor value to dbus interface */
4783ed9a516SVijay Khemka     setSensorValue(val);
47932a7156bSVijay Khemka 
4803ed9a516SVijay Khemka     if (DEBUG)
481e7efe135SRashmica Gupta     {
482fbd7145eSPatrick Williams         debug("Sensor {NAME} = {VALUE}", "NAME", this->name, "VALUE", val);
483e7efe135SRashmica Gupta     }
48432a7156bSVijay Khemka 
4858f5e6119SMatt Spinler     /* Check sensor thresholds and log required message */
486b306b03dSMatt Spinler     checkThresholds(val, perfLossIface);
487fdb826d5SPatrick Williams     checkThresholds(val, warningIface);
488fdb826d5SPatrick Williams     checkThresholds(val, criticalIface);
489fdb826d5SPatrick Williams     checkThresholds(val, softShutdownIface);
490fdb826d5SPatrick Williams     checkThresholds(val, hardShutdownIface);
4913ed9a516SVijay Khemka }
492abcc94faSVijay Khemka 
493304fd0e4SRashmica Gupta double VirtualSensor::calculateModifiedMedianValue(
494304fd0e4SRashmica Gupta     const VirtualSensor::ParamMap& paramMap)
495304fd0e4SRashmica Gupta {
496304fd0e4SRashmica Gupta     std::vector<double> values;
497304fd0e4SRashmica Gupta 
498304fd0e4SRashmica Gupta     for (auto& param : paramMap)
499304fd0e4SRashmica Gupta     {
500304fd0e4SRashmica Gupta         auto& name = param.first;
501304fd0e4SRashmica Gupta         if (auto var = symbols.get_variable(name))
502304fd0e4SRashmica Gupta         {
503304fd0e4SRashmica Gupta             if (!sensorInRange(var->ref()))
504304fd0e4SRashmica Gupta             {
505304fd0e4SRashmica Gupta                 continue;
506304fd0e4SRashmica Gupta             }
507304fd0e4SRashmica Gupta             values.push_back(var->ref());
508304fd0e4SRashmica Gupta         }
509304fd0e4SRashmica Gupta     }
510304fd0e4SRashmica Gupta 
511304fd0e4SRashmica Gupta     size_t size = values.size();
512304fd0e4SRashmica Gupta     std::sort(values.begin(), values.end());
513304fd0e4SRashmica Gupta     switch (size)
514304fd0e4SRashmica Gupta     {
515304fd0e4SRashmica Gupta         case 2:
516304fd0e4SRashmica Gupta             /* Choose biggest value */
517304fd0e4SRashmica Gupta             return values.at(1);
518304fd0e4SRashmica Gupta         case 0:
519304fd0e4SRashmica Gupta             return std::numeric_limits<double>::quiet_NaN();
520304fd0e4SRashmica Gupta         default:
521304fd0e4SRashmica Gupta             /* Choose median value */
522304fd0e4SRashmica Gupta             if (size % 2 == 0)
523304fd0e4SRashmica Gupta             {
524304fd0e4SRashmica Gupta                 // Average of the two middle values
525304fd0e4SRashmica Gupta                 return (values.at(size / 2) + values.at(size / 2 - 1)) / 2;
526304fd0e4SRashmica Gupta             }
527304fd0e4SRashmica Gupta             else
528304fd0e4SRashmica Gupta             {
529304fd0e4SRashmica Gupta                 return values.at((size - 1) / 2);
530304fd0e4SRashmica Gupta             }
531304fd0e4SRashmica Gupta     }
532304fd0e4SRashmica Gupta }
533304fd0e4SRashmica Gupta 
5343e99919bSRashmica Gupta void VirtualSensor::createThresholds(const Json& threshold,
5353e99919bSRashmica Gupta                                      const std::string& objPath)
5363e99919bSRashmica Gupta {
5373e99919bSRashmica Gupta     if (threshold.empty())
5383e99919bSRashmica Gupta     {
5393e99919bSRashmica Gupta         return;
5403e99919bSRashmica Gupta     }
5413e99919bSRashmica Gupta     // Only create the threshold interfaces if
5423e99919bSRashmica Gupta     // at least one of their values is present.
5433e99919bSRashmica Gupta     if (threshold.contains("CriticalHigh") || threshold.contains("CriticalLow"))
5443e99919bSRashmica Gupta     {
5453e99919bSRashmica Gupta         criticalIface =
5463e99919bSRashmica Gupta             std::make_unique<Threshold<CriticalObject>>(bus, objPath.c_str());
5473e99919bSRashmica Gupta 
5483e99919bSRashmica Gupta         criticalIface->criticalHigh(threshold.value(
5493e99919bSRashmica Gupta             "CriticalHigh", std::numeric_limits<double>::quiet_NaN()));
5503e99919bSRashmica Gupta         criticalIface->criticalLow(threshold.value(
5513e99919bSRashmica Gupta             "CriticalLow", std::numeric_limits<double>::quiet_NaN()));
5521dff7dceSRashmica Gupta         criticalIface->setHighHysteresis(
5531dff7dceSRashmica Gupta             threshold.value("CriticalHighHysteresis", defaultHysteresis));
5541dff7dceSRashmica Gupta         criticalIface->setLowHysteresis(
5551dff7dceSRashmica Gupta             threshold.value("CriticalLowHysteresis", defaultHysteresis));
5563e99919bSRashmica Gupta     }
5573e99919bSRashmica Gupta 
5583e99919bSRashmica Gupta     if (threshold.contains("WarningHigh") || threshold.contains("WarningLow"))
5593e99919bSRashmica Gupta     {
5603e99919bSRashmica Gupta         warningIface =
5613e99919bSRashmica Gupta             std::make_unique<Threshold<WarningObject>>(bus, objPath.c_str());
5623e99919bSRashmica Gupta 
5633e99919bSRashmica Gupta         warningIface->warningHigh(threshold.value(
5643e99919bSRashmica Gupta             "WarningHigh", std::numeric_limits<double>::quiet_NaN()));
5653e99919bSRashmica Gupta         warningIface->warningLow(threshold.value(
5663e99919bSRashmica Gupta             "WarningLow", std::numeric_limits<double>::quiet_NaN()));
5671dff7dceSRashmica Gupta         warningIface->setHighHysteresis(
5681dff7dceSRashmica Gupta             threshold.value("WarningHighHysteresis", defaultHysteresis));
5691dff7dceSRashmica Gupta         warningIface->setLowHysteresis(
5701dff7dceSRashmica Gupta             threshold.value("WarningLowHysteresis", defaultHysteresis));
5713e99919bSRashmica Gupta     }
5723e99919bSRashmica Gupta 
5733e99919bSRashmica Gupta     if (threshold.contains("HardShutdownHigh") ||
5743e99919bSRashmica Gupta         threshold.contains("HardShutdownLow"))
5753e99919bSRashmica Gupta     {
5763e99919bSRashmica Gupta         hardShutdownIface = std::make_unique<Threshold<HardShutdownObject>>(
5773e99919bSRashmica Gupta             bus, objPath.c_str());
5783e99919bSRashmica Gupta 
5793e99919bSRashmica Gupta         hardShutdownIface->hardShutdownHigh(threshold.value(
5803e99919bSRashmica Gupta             "HardShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
5813e99919bSRashmica Gupta         hardShutdownIface->hardShutdownLow(threshold.value(
5823e99919bSRashmica Gupta             "HardShutdownLow", std::numeric_limits<double>::quiet_NaN()));
5831dff7dceSRashmica Gupta         hardShutdownIface->setHighHysteresis(
5841dff7dceSRashmica Gupta             threshold.value("HardShutdownHighHysteresis", defaultHysteresis));
5851dff7dceSRashmica Gupta         hardShutdownIface->setLowHysteresis(
5861dff7dceSRashmica Gupta             threshold.value("HardShutdownLowHysteresis", defaultHysteresis));
5873e99919bSRashmica Gupta     }
5883e99919bSRashmica Gupta 
5893e99919bSRashmica Gupta     if (threshold.contains("SoftShutdownHigh") ||
5903e99919bSRashmica Gupta         threshold.contains("SoftShutdownLow"))
5913e99919bSRashmica Gupta     {
5923e99919bSRashmica Gupta         softShutdownIface = std::make_unique<Threshold<SoftShutdownObject>>(
5933e99919bSRashmica Gupta             bus, objPath.c_str());
5943e99919bSRashmica Gupta 
5953e99919bSRashmica Gupta         softShutdownIface->softShutdownHigh(threshold.value(
5963e99919bSRashmica Gupta             "SoftShutdownHigh", std::numeric_limits<double>::quiet_NaN()));
5973e99919bSRashmica Gupta         softShutdownIface->softShutdownLow(threshold.value(
5983e99919bSRashmica Gupta             "SoftShutdownLow", std::numeric_limits<double>::quiet_NaN()));
5991dff7dceSRashmica Gupta         softShutdownIface->setHighHysteresis(
6001dff7dceSRashmica Gupta             threshold.value("SoftShutdownHighHysteresis", defaultHysteresis));
6011dff7dceSRashmica Gupta         softShutdownIface->setLowHysteresis(
6021dff7dceSRashmica Gupta             threshold.value("SoftShutdownLowHysteresis", defaultHysteresis));
6033e99919bSRashmica Gupta     }
6043e99919bSRashmica Gupta 
6053e99919bSRashmica Gupta     if (threshold.contains("PerformanceLossHigh") ||
6063e99919bSRashmica Gupta         threshold.contains("PerformanceLossLow"))
6073e99919bSRashmica Gupta     {
6083e99919bSRashmica Gupta         perfLossIface = std::make_unique<Threshold<PerformanceLossObject>>(
6093e99919bSRashmica Gupta             bus, objPath.c_str());
6103e99919bSRashmica Gupta 
6113e99919bSRashmica Gupta         perfLossIface->performanceLossHigh(threshold.value(
6123e99919bSRashmica Gupta             "PerformanceLossHigh", std::numeric_limits<double>::quiet_NaN()));
6133e99919bSRashmica Gupta         perfLossIface->performanceLossLow(threshold.value(
6143e99919bSRashmica Gupta             "PerformanceLossLow", std::numeric_limits<double>::quiet_NaN()));
6151dff7dceSRashmica Gupta         perfLossIface->setHighHysteresis(threshold.value(
6161dff7dceSRashmica Gupta             "PerformanceLossHighHysteresis", defaultHysteresis));
6171dff7dceSRashmica Gupta         perfLossIface->setLowHysteresis(
6181dff7dceSRashmica Gupta             threshold.value("PerformanceLossLowHysteresis", defaultHysteresis));
6193e99919bSRashmica Gupta     }
6203e99919bSRashmica Gupta }
6213e99919bSRashmica Gupta 
622e7efe135SRashmica Gupta ManagedObjectType VirtualSensors::getObjectsFromDBus()
623e7efe135SRashmica Gupta {
624e7efe135SRashmica Gupta     ManagedObjectType objects;
625e7efe135SRashmica Gupta 
626e7efe135SRashmica Gupta     try
627e7efe135SRashmica Gupta     {
628e7efe135SRashmica Gupta         auto method = bus.new_method_call(entityManagerBusName, "/",
629e7efe135SRashmica Gupta                                           "org.freedesktop.DBus.ObjectManager",
630e7efe135SRashmica Gupta                                           "GetManagedObjects");
631e7efe135SRashmica Gupta         auto reply = bus.call(method);
632e7efe135SRashmica Gupta         reply.read(objects);
633e7efe135SRashmica Gupta     }
6348e11cccbSPatrick Williams     catch (const sdbusplus::exception_t& ex)
635e7efe135SRashmica Gupta     {
636e7efe135SRashmica Gupta         // If entity manager isn't running yet, keep going.
637e7efe135SRashmica Gupta         if (std::string("org.freedesktop.DBus.Error.ServiceUnknown") !=
638e7efe135SRashmica Gupta             ex.name())
639e7efe135SRashmica Gupta         {
640e7efe135SRashmica Gupta             throw ex.name();
641e7efe135SRashmica Gupta         }
642e7efe135SRashmica Gupta     }
643e7efe135SRashmica Gupta 
644e7efe135SRashmica Gupta     return objects;
645e7efe135SRashmica Gupta }
646e7efe135SRashmica Gupta 
6478e11cccbSPatrick Williams void VirtualSensors::propertiesChanged(sdbusplus::message_t& msg)
648e7efe135SRashmica Gupta {
649e7efe135SRashmica Gupta     std::string path;
650e7efe135SRashmica Gupta     PropertyMap properties;
651e7efe135SRashmica Gupta 
652e7efe135SRashmica Gupta     msg.read(path, properties);
653e7efe135SRashmica Gupta 
654e7efe135SRashmica Gupta     /* We get multiple callbacks for one sensor. 'Type' is a required field and
655e7efe135SRashmica Gupta      * is a unique label so use to to only proceed once per sensor */
656e7efe135SRashmica Gupta     if (properties.contains("Type"))
657e7efe135SRashmica Gupta     {
658e7efe135SRashmica Gupta         if (isCalculationType(path))
659e7efe135SRashmica Gupta         {
660e7efe135SRashmica Gupta             createVirtualSensorsFromDBus(path);
661e7efe135SRashmica Gupta         }
662e7efe135SRashmica Gupta     }
663e7efe135SRashmica Gupta }
664e7efe135SRashmica Gupta 
665abcc94faSVijay Khemka /** @brief Parsing Virtual Sensor config JSON file  */
6661204b433SGeorge Liu Json VirtualSensors::parseConfigFile(const std::string& configFile)
667abcc94faSVijay Khemka {
668abcc94faSVijay Khemka     std::ifstream jsonFile(configFile);
669abcc94faSVijay Khemka     if (!jsonFile.is_open())
670abcc94faSVijay Khemka     {
67182b39c66SPatrick Williams         error("config JSON file {FILENAME} not found", "FILENAME", configFile);
672e7efe135SRashmica Gupta         return {};
673abcc94faSVijay Khemka     }
674abcc94faSVijay Khemka 
675abcc94faSVijay Khemka     auto data = Json::parse(jsonFile, nullptr, false);
676abcc94faSVijay Khemka     if (data.is_discarded())
677abcc94faSVijay Khemka     {
67882b39c66SPatrick Williams         error("config readings JSON parser failure with {FILENAME}", "FILENAME",
67982b39c66SPatrick Williams               configFile);
680abcc94faSVijay Khemka         throw std::exception{};
681abcc94faSVijay Khemka     }
682abcc94faSVijay Khemka 
683abcc94faSVijay Khemka     return data;
684abcc94faSVijay Khemka }
685abcc94faSVijay Khemka 
686e0d371e4SVijay Khemka std::map<std::string, ValueIface::Unit> unitMap = {
687e0d371e4SVijay Khemka     {"temperature", ValueIface::Unit::DegreesC},
688e0d371e4SVijay Khemka     {"fan_tach", ValueIface::Unit::RPMS},
689e0d371e4SVijay Khemka     {"voltage", ValueIface::Unit::Volts},
690e0d371e4SVijay Khemka     {"altitude", ValueIface::Unit::Meters},
691e0d371e4SVijay Khemka     {"current", ValueIface::Unit::Amperes},
692e0d371e4SVijay Khemka     {"power", ValueIface::Unit::Watts},
693e0d371e4SVijay Khemka     {"energy", ValueIface::Unit::Joules},
6942b56ddb3SKumar Thangavel     {"utilization", ValueIface::Unit::Percent},
6954ac7a7f2SRashmica Gupta     {"airflow", ValueIface::Unit::CFM},
6964ac7a7f2SRashmica Gupta     {"pressure", ValueIface::Unit::Pascals}};
697e0d371e4SVijay Khemka 
698e7efe135SRashmica Gupta const std::string getSensorTypeFromUnit(const std::string& unit)
699e7efe135SRashmica Gupta {
700e7efe135SRashmica Gupta     std::string unitPrefix = "xyz.openbmc_project.Sensor.Value.Unit.";
701e7efe135SRashmica Gupta     for (auto [type, unitObj] : unitMap)
702e7efe135SRashmica Gupta     {
703e7efe135SRashmica Gupta         auto unitPath = ValueIface::convertUnitToString(unitObj);
704e7efe135SRashmica Gupta         if (unitPath == (unitPrefix + unit))
705e7efe135SRashmica Gupta         {
706e7efe135SRashmica Gupta             return type;
707e7efe135SRashmica Gupta         }
708e7efe135SRashmica Gupta     }
709e7efe135SRashmica Gupta     return "";
710e7efe135SRashmica Gupta }
711e7efe135SRashmica Gupta 
712e7efe135SRashmica Gupta void VirtualSensors::setupMatches()
713e7efe135SRashmica Gupta {
714e7efe135SRashmica Gupta     /* Already setup */
715e7efe135SRashmica Gupta     if (!this->matches.empty())
716e7efe135SRashmica Gupta     {
717e7efe135SRashmica Gupta         return;
718e7efe135SRashmica Gupta     }
719e7efe135SRashmica Gupta 
720e7efe135SRashmica Gupta     /* Setup matches */
7218e11cccbSPatrick Williams     auto eventHandler = [this](sdbusplus::message_t& message) {
722e7efe135SRashmica Gupta         if (message.is_method_error())
723e7efe135SRashmica Gupta         {
72482b39c66SPatrick Williams             error("Callback method error");
725e7efe135SRashmica Gupta             return;
726e7efe135SRashmica Gupta         }
727e7efe135SRashmica Gupta         this->propertiesChanged(message);
728e7efe135SRashmica Gupta     };
729e7efe135SRashmica Gupta 
730e7efe135SRashmica Gupta     for (const char* iface : calculationIfaces)
731e7efe135SRashmica Gupta     {
7328e11cccbSPatrick Williams         auto match = std::make_unique<sdbusplus::bus::match_t>(
733e7efe135SRashmica Gupta             bus,
734e7efe135SRashmica Gupta             sdbusplus::bus::match::rules::propertiesChangedNamespace(
735e7efe135SRashmica Gupta                 "/xyz/openbmc_project/inventory", iface),
736e7efe135SRashmica Gupta             eventHandler);
737e7efe135SRashmica Gupta         this->matches.emplace_back(std::move(match));
738e7efe135SRashmica Gupta     }
739e7efe135SRashmica Gupta }
740e7efe135SRashmica Gupta 
741e7efe135SRashmica Gupta void VirtualSensors::createVirtualSensorsFromDBus(
742e7efe135SRashmica Gupta     const std::string& calculationIface)
743e7efe135SRashmica Gupta {
744e7efe135SRashmica Gupta     if (calculationIface.empty())
745e7efe135SRashmica Gupta     {
74682b39c66SPatrick Williams         error("No calculation type supplied");
747e7efe135SRashmica Gupta         return;
748e7efe135SRashmica Gupta     }
749e7efe135SRashmica Gupta     auto objects = getObjectsFromDBus();
750e7efe135SRashmica Gupta 
751e7efe135SRashmica Gupta     /* Get virtual sensors config data */
752e7efe135SRashmica Gupta     for (const auto& [path, interfaceMap] : objects)
753e7efe135SRashmica Gupta     {
754e7efe135SRashmica Gupta         auto objpath = static_cast<std::string>(path);
755e7efe135SRashmica Gupta         std::string name = path.filename();
756e7efe135SRashmica Gupta         std::string sensorType, sensorUnit;
757e7efe135SRashmica Gupta 
758e7efe135SRashmica Gupta         /* Find Virtual Sensor interfaces */
759e7efe135SRashmica Gupta         if (!interfaceMap.contains(calculationIface))
760e7efe135SRashmica Gupta         {
761e7efe135SRashmica Gupta             continue;
762e7efe135SRashmica Gupta         }
763e7efe135SRashmica Gupta         if (name.empty())
764e7efe135SRashmica Gupta         {
76582b39c66SPatrick Williams             error("Virtual Sensor name not found in entity manager config");
766e7efe135SRashmica Gupta             continue;
767e7efe135SRashmica Gupta         }
768e7efe135SRashmica Gupta         if (virtualSensorsMap.contains(name))
769e7efe135SRashmica Gupta         {
77082b39c66SPatrick Williams             error("A virtual sensor named {NAME} already exists", "NAME", name);
771e7efe135SRashmica Gupta             continue;
772e7efe135SRashmica Gupta         }
773e7efe135SRashmica Gupta 
774e7efe135SRashmica Gupta         /* Extract the virtual sensor type as we need this to initialize the
775e7efe135SRashmica Gupta          * sensor */
776e7efe135SRashmica Gupta         for (const auto& [interface, propertyMap] : interfaceMap)
777e7efe135SRashmica Gupta         {
778e7efe135SRashmica Gupta             if (interface != calculationIface)
779e7efe135SRashmica Gupta             {
780e7efe135SRashmica Gupta                 continue;
781e7efe135SRashmica Gupta             }
782e7efe135SRashmica Gupta             auto itr = propertyMap.find("Units");
783e7efe135SRashmica Gupta             if (itr != propertyMap.end())
784e7efe135SRashmica Gupta             {
785e7efe135SRashmica Gupta                 sensorUnit = std::get<std::string>(itr->second);
786e7efe135SRashmica Gupta                 break;
787e7efe135SRashmica Gupta             }
788e7efe135SRashmica Gupta         }
789e7efe135SRashmica Gupta         sensorType = getSensorTypeFromUnit(sensorUnit);
790e7efe135SRashmica Gupta         if (sensorType.empty())
791e7efe135SRashmica Gupta         {
79282b39c66SPatrick Williams             error("Sensor unit type {TYPE} is not supported", "TYPE",
79382b39c66SPatrick Williams                   sensorUnit);
794e7efe135SRashmica Gupta             continue;
795e7efe135SRashmica Gupta         }
796e7efe135SRashmica Gupta 
797e7efe135SRashmica Gupta         try
798e7efe135SRashmica Gupta         {
799e7efe135SRashmica Gupta             auto virtObjPath = sensorDbusPath + sensorType + "/" + name;
800e7efe135SRashmica Gupta 
801e7efe135SRashmica Gupta             auto virtualSensorPtr = std::make_unique<VirtualSensor>(
802e7efe135SRashmica Gupta                 bus, virtObjPath.c_str(), interfaceMap, name, sensorType,
803e7efe135SRashmica Gupta                 calculationIface);
80482b39c66SPatrick Williams             info("Added a new virtual sensor: {NAME} {TYPE}", "NAME", name,
80582b39c66SPatrick Williams                  "TYPE", sensorType);
806e7efe135SRashmica Gupta             virtualSensorPtr->updateVirtualSensor();
807e7efe135SRashmica Gupta 
808e7efe135SRashmica Gupta             /* Initialize unit value for virtual sensor */
809e7efe135SRashmica Gupta             virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
810e7efe135SRashmica Gupta             virtualSensorPtr->emit_object_added();
811e7efe135SRashmica Gupta 
812e7efe135SRashmica Gupta             virtualSensorsMap.emplace(name, std::move(virtualSensorPtr));
813e7efe135SRashmica Gupta 
814e7efe135SRashmica Gupta             /* Setup match for interfaces removed */
815e7efe135SRashmica Gupta             auto intfRemoved = [this, objpath,
8168e11cccbSPatrick Williams                                 name](sdbusplus::message_t& message) {
817e7efe135SRashmica Gupta                 if (!virtualSensorsMap.contains(name))
818e7efe135SRashmica Gupta                 {
819e7efe135SRashmica Gupta                     return;
820e7efe135SRashmica Gupta                 }
821e7efe135SRashmica Gupta                 sdbusplus::message::object_path path;
822e7efe135SRashmica Gupta                 message.read(path);
823e7efe135SRashmica Gupta                 if (static_cast<const std::string&>(path) == objpath)
824e7efe135SRashmica Gupta                 {
82582b39c66SPatrick Williams                     info("Removed a virtual sensor: {NAME}", "NAME", name);
826e7efe135SRashmica Gupta                     virtualSensorsMap.erase(name);
827e7efe135SRashmica Gupta                 }
828e7efe135SRashmica Gupta             };
8298e11cccbSPatrick Williams             auto matchOnRemove = std::make_unique<sdbusplus::bus::match_t>(
830e7efe135SRashmica Gupta                 bus,
831e7efe135SRashmica Gupta                 sdbusplus::bus::match::rules::interfacesRemoved() +
832e7efe135SRashmica Gupta                     sdbusplus::bus::match::rules::argNpath(0, objpath),
833e7efe135SRashmica Gupta                 intfRemoved);
834e7efe135SRashmica Gupta             /* TODO: slight race condition here. Check that the config still
835e7efe135SRashmica Gupta              * exists */
836e7efe135SRashmica Gupta             this->matches.emplace_back(std::move(matchOnRemove));
837e7efe135SRashmica Gupta         }
838dac2663cSPatrick Williams         catch (const std::invalid_argument& ia)
839e7efe135SRashmica Gupta         {
84082b39c66SPatrick Williams             error("Failed to set up virtual sensor: {ERROR}", "ERROR", ia);
841e7efe135SRashmica Gupta         }
842e7efe135SRashmica Gupta     }
843e7efe135SRashmica Gupta }
844e7efe135SRashmica Gupta 
845abcc94faSVijay Khemka void VirtualSensors::createVirtualSensors()
846abcc94faSVijay Khemka {
847abcc94faSVijay Khemka     static const Json empty{};
848abcc94faSVijay Khemka 
849abcc94faSVijay Khemka     auto data = parseConfigFile(VIRTUAL_SENSOR_CONFIG_FILE);
850e7efe135SRashmica Gupta 
851abcc94faSVijay Khemka     // print values
852abcc94faSVijay Khemka     if (DEBUG)
853e7efe135SRashmica Gupta     {
854fbd7145eSPatrick Williams         debug("JSON: {JSON}", "JSON", data.dump());
855e7efe135SRashmica Gupta     }
856abcc94faSVijay Khemka 
857abcc94faSVijay Khemka     /* Get virtual sensors  config data */
858abcc94faSVijay Khemka     for (const auto& j : data)
859abcc94faSVijay Khemka     {
860abcc94faSVijay Khemka         auto desc = j.value("Desc", empty);
861abcc94faSVijay Khemka         if (!desc.empty())
862abcc94faSVijay Khemka         {
863e7efe135SRashmica Gupta             if (desc.value("Config", "") == "D-Bus")
864e7efe135SRashmica Gupta             {
865e7efe135SRashmica Gupta                 /* Look on D-Bus for a virtual sensor config. Set up matches
866e7efe135SRashmica Gupta                  * first because the configs may not be on D-Bus yet and we
867e7efe135SRashmica Gupta                  * don't want to miss them */
868e7efe135SRashmica Gupta                 setupMatches();
869e7efe135SRashmica Gupta 
870e7efe135SRashmica Gupta                 if (desc.contains("Type"))
871e7efe135SRashmica Gupta                 {
87282b39c66SPatrick Williams                     auto type = desc.value("Type", "");
87382b39c66SPatrick Williams                     auto path = "xyz.openbmc_project.Configuration." + type;
87482b39c66SPatrick Williams 
875e7efe135SRashmica Gupta                     if (!isCalculationType(path))
876e7efe135SRashmica Gupta                     {
87782b39c66SPatrick Williams                         error("Invalid calculation type {TYPE} supplied.",
87882b39c66SPatrick Williams                               "TYPE", type);
879e7efe135SRashmica Gupta                         continue;
880e7efe135SRashmica Gupta                     }
881e7efe135SRashmica Gupta                     createVirtualSensorsFromDBus(path);
882e7efe135SRashmica Gupta                 }
883e7efe135SRashmica Gupta                 continue;
884e7efe135SRashmica Gupta             }
885e7efe135SRashmica Gupta 
886abcc94faSVijay Khemka             std::string sensorType = desc.value("SensorType", "");
887abcc94faSVijay Khemka             std::string name = desc.value("Name", "");
888665a0a29SRashmica Gupta             std::replace(name.begin(), name.end(), ' ', '_');
889abcc94faSVijay Khemka 
890abcc94faSVijay Khemka             if (!name.empty() && !sensorType.empty())
891abcc94faSVijay Khemka             {
892e0d371e4SVijay Khemka                 if (unitMap.find(sensorType) == unitMap.end())
893e0d371e4SVijay Khemka                 {
89482b39c66SPatrick Williams                     error("Sensor type {TYPE} is not supported", "TYPE",
89582b39c66SPatrick Williams                           sensorType);
896e0d371e4SVijay Khemka                 }
897e0d371e4SVijay Khemka                 else
898e0d371e4SVijay Khemka                 {
89967d8b9d2SRashmica Gupta                     if (virtualSensorsMap.find(name) != virtualSensorsMap.end())
90067d8b9d2SRashmica Gupta                     {
90182b39c66SPatrick Williams                         error("A virtual sensor named {NAME} already exists",
90282b39c66SPatrick Williams                               "NAME", name);
90367d8b9d2SRashmica Gupta                         continue;
90467d8b9d2SRashmica Gupta                     }
905862c3d1eSRashmica Gupta                     auto objPath = sensorDbusPath + sensorType + "/" + name;
906abcc94faSVijay Khemka 
90732a7156bSVijay Khemka                     auto virtualSensorPtr = std::make_unique<VirtualSensor>(
90832a7156bSVijay Khemka                         bus, objPath.c_str(), j, name);
909abcc94faSVijay Khemka 
91082b39c66SPatrick Williams                     info("Added a new virtual sensor: {NAME}", "NAME", name);
9113ed9a516SVijay Khemka                     virtualSensorPtr->updateVirtualSensor();
912e0d371e4SVijay Khemka 
913e0d371e4SVijay Khemka                     /* Initialize unit value for virtual sensor */
914e0d371e4SVijay Khemka                     virtualSensorPtr->ValueIface::unit(unitMap[sensorType]);
915a2fa63a6SRashmica Gupta                     virtualSensorPtr->emit_object_added();
916e0d371e4SVijay Khemka 
9173ed9a516SVijay Khemka                     virtualSensorsMap.emplace(std::move(name),
9183ed9a516SVijay Khemka                                               std::move(virtualSensorPtr));
919abcc94faSVijay Khemka                 }
920e0d371e4SVijay Khemka             }
921abcc94faSVijay Khemka             else
922abcc94faSVijay Khemka             {
92382b39c66SPatrick Williams                 error(
92482b39c66SPatrick Williams                     "Sensor type ({TYPE}) or name ({NAME}) not found in config file",
92582b39c66SPatrick Williams                     "NAME", name, "TYPE", sensorType);
926abcc94faSVijay Khemka             }
927abcc94faSVijay Khemka         }
928abcc94faSVijay Khemka         else
929abcc94faSVijay Khemka         {
93082b39c66SPatrick Williams             error("Descriptor for new virtual sensor not found in config file");
931abcc94faSVijay Khemka         }
932abcc94faSVijay Khemka     }
933abcc94faSVijay Khemka }
934abcc94faSVijay Khemka 
935abcc94faSVijay Khemka } // namespace virtualSensor
936abcc94faSVijay Khemka } // namespace phosphor
937abcc94faSVijay Khemka 
938abcc94faSVijay Khemka /**
939abcc94faSVijay Khemka  * @brief Main
940abcc94faSVijay Khemka  */
941abcc94faSVijay Khemka int main()
942abcc94faSVijay Khemka {
943abcc94faSVijay Khemka     // Get a handle to system dbus
944abcc94faSVijay Khemka     auto bus = sdbusplus::bus::new_default();
945abcc94faSVijay Khemka 
9466c19e7d2SMatt Spinler     // Add the ObjectManager interface
9478e11cccbSPatrick Williams     sdbusplus::server::manager_t objManager(bus, "/");
9486c19e7d2SMatt Spinler 
949abcc94faSVijay Khemka     // Create an virtual sensors object
950abcc94faSVijay Khemka     phosphor::virtualSensor::VirtualSensors virtualSensors(bus);
951abcc94faSVijay Khemka 
952abcc94faSVijay Khemka     // Request service bus name
953abcc94faSVijay Khemka     bus.request_name(busName);
954abcc94faSVijay Khemka 
955*e667239dSPatrick Williams     // Run the dbus loop.
956*e667239dSPatrick Williams     bus.process_loop();
957abcc94faSVijay Khemka 
958abcc94faSVijay Khemka     return 0;
959abcc94faSVijay Khemka }
960