xref: /openbmc/bmcweb/redfish-core/lib/sensors.hpp (revision 5a19396d081c5cb68d3e880529ecd552d1c4f5a0)
1 /*
2 // Copyright (c) 2018 Intel Corporation
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 */
16 #pragma once
17 
18 #include "generated/enums/sensor.hpp"
19 
20 #include <app.hpp>
21 #include <boost/algorithm/string/classification.hpp>
22 #include <boost/algorithm/string/find.hpp>
23 #include <boost/algorithm/string/predicate.hpp>
24 #include <boost/algorithm/string/split.hpp>
25 #include <boost/range/algorithm/replace_copy_if.hpp>
26 #include <dbus_singleton.hpp>
27 #include <dbus_utility.hpp>
28 #include <query.hpp>
29 #include <registries/privilege_registry.hpp>
30 #include <sdbusplus/asio/property.hpp>
31 #include <sdbusplus/unpack_properties.hpp>
32 #include <utils/dbus_utils.hpp>
33 #include <utils/json_utils.hpp>
34 #include <utils/query_param.hpp>
35 
36 #include <cmath>
37 #include <iterator>
38 #include <map>
39 #include <set>
40 #include <utility>
41 #include <variant>
42 
43 namespace redfish
44 {
45 
46 namespace sensors
47 {
48 namespace node
49 {
50 static constexpr std::string_view power = "Power";
51 static constexpr std::string_view sensors = "Sensors";
52 static constexpr std::string_view thermal = "Thermal";
53 } // namespace node
54 
55 // clang-format off
56 namespace dbus
57 {
58 static auto powerPaths = std::to_array<std::string_view>({
59     "/xyz/openbmc_project/sensors/voltage",
60     "/xyz/openbmc_project/sensors/power"
61 });
62 
63 static auto sensorPaths = std::to_array<std::string_view>({
64     "/xyz/openbmc_project/sensors/power",
65     "/xyz/openbmc_project/sensors/current",
66     "/xyz/openbmc_project/sensors/airflow",
67     "/xyz/openbmc_project/sensors/humidity",
68 #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
69     "/xyz/openbmc_project/sensors/voltage",
70     "/xyz/openbmc_project/sensors/fan_tach",
71     "/xyz/openbmc_project/sensors/temperature",
72     "/xyz/openbmc_project/sensors/fan_pwm",
73     "/xyz/openbmc_project/sensors/altitude",
74     "/xyz/openbmc_project/sensors/energy",
75 #endif
76     "/xyz/openbmc_project/sensors/utilization"
77 });
78 
79 static auto thermalPaths = std::to_array<std::string_view>({
80     "/xyz/openbmc_project/sensors/fan_tach",
81     "/xyz/openbmc_project/sensors/temperature",
82     "/xyz/openbmc_project/sensors/fan_pwm"
83 });
84 
85 } // namespace dbus
86 // clang-format on
87 
88 using sensorPair = std::pair<std::string_view, std::span<std::string_view>>;
89 static constexpr std::array<sensorPair, 3> paths = {
90     {{node::power, std::span<std::string_view>(dbus::powerPaths)},
91      {node::sensors, std::span<std::string_view>(dbus::sensorPaths)},
92      {node::thermal, std::span<std::string_view>(dbus::thermalPaths)}}};
93 
94 inline sensor::ReadingType toReadingType(std::string_view sensorType)
95 {
96     if (sensorType == "voltage")
97     {
98         return sensor::ReadingType::Voltage;
99     }
100     if (sensorType == "power")
101     {
102         return sensor::ReadingType::Power;
103     }
104     if (sensorType == "current")
105     {
106         return sensor::ReadingType::Current;
107     }
108     if (sensorType == "fan_tach")
109     {
110         return sensor::ReadingType::Rotational;
111     }
112     if (sensorType == "temperature")
113     {
114         return sensor::ReadingType::Temperature;
115     }
116     if (sensorType == "fan_pwm" || sensorType == "utilization")
117     {
118         return sensor::ReadingType::Percent;
119     }
120     if (sensorType == "humidity")
121     {
122         return sensor::ReadingType::Humidity;
123     }
124     if (sensorType == "altitude")
125     {
126         return sensor::ReadingType::Altitude;
127     }
128     if (sensorType == "airflow")
129     {
130         return sensor::ReadingType::AirFlow;
131     }
132     if (sensorType == "energy")
133     {
134         return sensor::ReadingType::EnergyJoules;
135     }
136     return sensor::ReadingType::Invalid;
137 }
138 
139 inline std::string_view toReadingUnits(std::string_view sensorType)
140 {
141     if (sensorType == "voltage")
142     {
143         return "V";
144     }
145     if (sensorType == "power")
146     {
147         return "W";
148     }
149     if (sensorType == "current")
150     {
151         return "A";
152     }
153     if (sensorType == "fan_tach")
154     {
155         return "RPM";
156     }
157     if (sensorType == "temperature")
158     {
159         return "Cel";
160     }
161     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
162         sensorType == "humidity")
163     {
164         return "%";
165     }
166     if (sensorType == "altitude")
167     {
168         return "m";
169     }
170     if (sensorType == "airflow")
171     {
172         return "cft_i/min";
173     }
174     if (sensorType == "energy")
175     {
176         return "J";
177     }
178     return "";
179 }
180 } // namespace sensors
181 
182 /**
183  * SensorsAsyncResp
184  * Gathers data needed for response processing after async calls are done
185  */
186 class SensorsAsyncResp
187 {
188   public:
189     using DataCompleteCb = std::function<void(
190         const boost::beast::http::status status,
191         const std::map<std::string, std::string>& uriToDbus)>;
192 
193     struct SensorData
194     {
195         const std::string name;
196         std::string uri;
197         const std::string dbusPath;
198     };
199 
200     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
201                      const std::string& chassisIdIn,
202                      std::span<std::string_view> typesIn,
203                      std::string_view subNode) :
204         asyncResp(asyncRespIn),
205         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
206         efficientExpand(false)
207     {}
208 
209     // Store extra data about sensor mapping and return it in callback
210     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
211                      const std::string& chassisIdIn,
212                      std::span<std::string_view> typesIn,
213                      std::string_view subNode,
214                      DataCompleteCb&& creationComplete) :
215         asyncResp(asyncRespIn),
216         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
217         efficientExpand(false), metadata{std::vector<SensorData>()},
218         dataComplete{std::move(creationComplete)}
219     {}
220 
221     // sensor collections expand
222     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
223                      const std::string& chassisIdIn,
224                      const std::span<std::string_view> typesIn,
225                      const std::string_view& subNode, bool efficientExpandIn) :
226         asyncResp(asyncRespIn),
227         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
228         efficientExpand(efficientExpandIn)
229     {}
230 
231     ~SensorsAsyncResp()
232     {
233         if (asyncResp->res.result() ==
234             boost::beast::http::status::internal_server_error)
235         {
236             // Reset the json object to clear out any data that made it in
237             // before the error happened todo(ed) handle error condition with
238             // proper code
239             asyncResp->res.jsonValue = nlohmann::json::object();
240         }
241 
242         if (dataComplete && metadata)
243         {
244             std::map<std::string, std::string> map;
245             if (asyncResp->res.result() == boost::beast::http::status::ok)
246             {
247                 for (auto& sensor : *metadata)
248                 {
249                     map.emplace(sensor.uri, sensor.dbusPath);
250                 }
251             }
252             dataComplete(asyncResp->res.result(), map);
253         }
254     }
255 
256     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
257     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
258     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
259     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
260 
261     void addMetadata(const nlohmann::json& sensorObject,
262                      const std::string& dbusPath)
263     {
264         if (metadata)
265         {
266             metadata->emplace_back(SensorData{
267                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
268         }
269     }
270 
271     void updateUri(const std::string& name, const std::string& uri)
272     {
273         if (metadata)
274         {
275             for (auto& sensor : *metadata)
276             {
277                 if (sensor.name == name)
278                 {
279                     sensor.uri = uri;
280                 }
281             }
282         }
283     }
284 
285     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
286     const std::string chassisId;
287     const std::span<std::string_view> types;
288     const std::string chassisSubNode;
289     const bool efficientExpand;
290 
291   private:
292     std::optional<std::vector<SensorData>> metadata;
293     DataCompleteCb dataComplete;
294 };
295 
296 /**
297  * Possible states for physical inventory leds
298  */
299 enum class LedState
300 {
301     OFF,
302     ON,
303     BLINK,
304     UNKNOWN
305 };
306 
307 /**
308  * D-Bus inventory item associated with one or more sensors.
309  */
310 class InventoryItem
311 {
312   public:
313     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
314     {
315         // Set inventory item name to last node of object path
316         sdbusplus::message::object_path path(objectPath);
317         name = path.filename();
318         if (name.empty())
319         {
320             BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath;
321         }
322     }
323 
324     std::string objectPath;
325     std::string name;
326     bool isPresent = true;
327     bool isFunctional = true;
328     bool isPowerSupply = false;
329     int powerSupplyEfficiencyPercent = -1;
330     std::string manufacturer;
331     std::string model;
332     std::string partNumber;
333     std::string serialNumber;
334     std::set<std::string> sensors;
335     std::string ledObjectPath;
336     LedState ledState = LedState::UNKNOWN;
337 };
338 
339 /**
340  * @brief Get objects with connection necessary for sensors
341  * @param SensorsAsyncResp Pointer to object holding response data
342  * @param sensorNames Sensors retrieved from chassis
343  * @param callback Callback for processing gathered connections
344  */
345 template <typename Callback>
346 void getObjectsWithConnection(
347     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
348     const std::shared_ptr<std::set<std::string>>& sensorNames,
349     Callback&& callback)
350 {
351     BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter";
352     const std::string path = "/xyz/openbmc_project/sensors";
353     const std::array<std::string, 1> interfaces = {
354         "xyz.openbmc_project.Sensor.Value"};
355 
356     // Response handler for parsing objects subtree
357     auto respHandler =
358         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
359          sensorNames](const boost::system::error_code ec,
360                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
361         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter";
362         if (ec)
363         {
364             messages::internalError(sensorsAsyncResp->asyncResp->res);
365             BMCWEB_LOG_ERROR
366                 << "getObjectsWithConnection resp_handler: Dbus error " << ec;
367             return;
368         }
369 
370         BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
371 
372         // Make unique list of connections only for requested sensor types and
373         // found in the chassis
374         std::set<std::string> connections;
375         std::set<std::pair<std::string, std::string>> objectsWithConnection;
376 
377         BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size();
378         for (const std::string& tsensor : *sensorNames)
379         {
380             BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
381         }
382 
383         for (const std::pair<
384                  std::string,
385                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
386                  object : subtree)
387         {
388             if (sensorNames->find(object.first) != sensorNames->end())
389             {
390                 for (const std::pair<std::string, std::vector<std::string>>&
391                          objData : object.second)
392                 {
393                     BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
394                     connections.insert(objData.first);
395                     objectsWithConnection.insert(
396                         std::make_pair(object.first, objData.first));
397                 }
398             }
399         }
400         BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
401         callback(std::move(connections), std::move(objectsWithConnection));
402         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit";
403     };
404     // Make call to ObjectMapper to find all sensors objects
405     crow::connections::systemBus->async_method_call(
406         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
407         "/xyz/openbmc_project/object_mapper",
408         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 2, interfaces);
409     BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit";
410 }
411 
412 /**
413  * @brief Create connections necessary for sensors
414  * @param SensorsAsyncResp Pointer to object holding response data
415  * @param sensorNames Sensors retrieved from chassis
416  * @param callback Callback for processing gathered connections
417  */
418 template <typename Callback>
419 void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
420                     const std::shared_ptr<std::set<std::string>> sensorNames,
421                     Callback&& callback)
422 {
423     auto objectsWithConnectionCb =
424         [callback](const std::set<std::string>& connections,
425                    const std::set<std::pair<std::string, std::string>>&
426                    /*objectsWithConnection*/) { callback(connections); };
427     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
428                              std::move(objectsWithConnectionCb));
429 }
430 
431 /**
432  * @brief Shrinks the list of sensors for processing
433  * @param SensorsAysncResp  The class holding the Redfish response
434  * @param allSensors  A list of all the sensors associated to the
435  * chassis element (i.e. baseboard, front panel, etc...)
436  * @param activeSensors A list that is a reduction of the incoming
437  * allSensors list.  Eliminate Thermal sensors when a Power request is
438  * made, and eliminate Power sensors when a Thermal request is made.
439  */
440 inline void reduceSensorList(
441     crow::Response& res, std::string_view chassisSubNode,
442     std::span<std::string_view> sensorTypes,
443     const std::vector<std::string>* allSensors,
444     const std::shared_ptr<std::set<std::string>>& activeSensors)
445 {
446     if ((allSensors == nullptr) || (activeSensors == nullptr))
447     {
448         messages::resourceNotFound(res, chassisSubNode,
449                                    chassisSubNode == sensors::node::thermal
450                                        ? "Temperatures"
451                                        : "Voltages");
452 
453         return;
454     }
455     if (allSensors->empty())
456     {
457         // Nothing to do, the activeSensors object is also empty
458         return;
459     }
460 
461     for (std::string_view type : sensorTypes)
462     {
463         for (const std::string& sensor : *allSensors)
464         {
465             if (sensor.starts_with(type))
466             {
467                 activeSensors->emplace(sensor);
468             }
469         }
470     }
471 }
472 
473 /*
474  *Populates the top level collection for a given subnode.  Populates
475  *SensorCollection, Power, or Thermal schemas.
476  *
477  * */
478 inline void populateChassisNode(nlohmann::json& jsonValue,
479                                 std::string_view chassisSubNode)
480 {
481     if (chassisSubNode == sensors::node::power)
482     {
483         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
484     }
485     else if (chassisSubNode == sensors::node::thermal)
486     {
487         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
488         jsonValue["Fans"] = nlohmann::json::array();
489         jsonValue["Temperatures"] = nlohmann::json::array();
490     }
491     else if (chassisSubNode == sensors::node::sensors)
492     {
493         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
494         jsonValue["Description"] = "Collection of Sensors for this Chassis";
495         jsonValue["Members"] = nlohmann::json::array();
496         jsonValue["Members@odata.count"] = 0;
497     }
498 
499     if (chassisSubNode != sensors::node::sensors)
500     {
501         jsonValue["Id"] = chassisSubNode;
502     }
503     jsonValue["Name"] = chassisSubNode;
504 }
505 
506 /**
507  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
508  * @param SensorsAsyncResp   Pointer to object holding response data
509  * @param callback  Callback for next step in gathered sensor processing
510  */
511 template <typename Callback>
512 void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
513                 std::string_view chassisId, std::string_view chassisSubNode,
514                 std::span<std::string_view> sensorTypes, Callback&& callback)
515 {
516     BMCWEB_LOG_DEBUG << "getChassis enter";
517     const std::array<const char*, 2> interfaces = {
518         "xyz.openbmc_project.Inventory.Item.Board",
519         "xyz.openbmc_project.Inventory.Item.Chassis"};
520     auto respHandler =
521         [callback{std::forward<Callback>(callback)}, asyncResp,
522          chassisIdStr{std::string(chassisId)},
523          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
524             const boost::system::error_code ec,
525             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
526         BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
527         if (ec)
528         {
529             BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
530             messages::internalError(asyncResp->res);
531             return;
532         }
533         const std::string* chassisPath = nullptr;
534         std::string chassisName;
535         for (const std::string& chassis : chassisPaths)
536         {
537             sdbusplus::message::object_path path(chassis);
538             chassisName = path.filename();
539             if (chassisName.empty())
540             {
541                 BMCWEB_LOG_ERROR << "Failed to find '/' in " << chassis;
542                 continue;
543             }
544             if (chassisName == chassisIdStr)
545             {
546                 chassisPath = &chassis;
547                 break;
548             }
549         }
550         if (chassisPath == nullptr)
551         {
552             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
553             return;
554         }
555         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
556 
557         asyncResp->res.jsonValue["@odata.id"] =
558             "/redfish/v1/Chassis/" + chassisIdStr + "/" + chassisSubNode;
559 
560         // Get the list of all sensors for this Chassis element
561         std::string sensorPath = *chassisPath + "/all_sensors";
562         sdbusplus::asio::getProperty<std::vector<std::string>>(
563             *crow::connections::systemBus, "xyz.openbmc_project.ObjectMapper",
564             sensorPath, "xyz.openbmc_project.Association", "endpoints",
565             [asyncResp, chassisSubNode, sensorTypes,
566              callback{std::forward<const Callback>(callback)}](
567                 const boost::system::error_code& e,
568                 const std::vector<std::string>& nodeSensorList) {
569             if (e)
570             {
571                 if (e.value() != EBADR)
572                 {
573                     messages::internalError(asyncResp->res);
574                     return;
575                 }
576             }
577             const std::shared_ptr<std::set<std::string>> culledSensorList =
578                 std::make_shared<std::set<std::string>>();
579             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
580                              &nodeSensorList, culledSensorList);
581             BMCWEB_LOG_DEBUG << "Finishing with " << culledSensorList->size();
582             callback(culledSensorList);
583             });
584     };
585 
586     // Get the Chassis Collection
587     crow::connections::systemBus->async_method_call(
588         respHandler, "xyz.openbmc_project.ObjectMapper",
589         "/xyz/openbmc_project/object_mapper",
590         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
591         "/xyz/openbmc_project/inventory", 0, interfaces);
592     BMCWEB_LOG_DEBUG << "getChassis exit";
593 }
594 
595 /**
596  * @brief Returns the Redfish State value for the specified inventory item.
597  * @param inventoryItem D-Bus inventory item associated with a sensor.
598  * @return State value for inventory item.
599  */
600 inline std::string getState(const InventoryItem* inventoryItem)
601 {
602     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
603     {
604         return "Absent";
605     }
606 
607     return "Enabled";
608 }
609 
610 /**
611  * @brief Returns the Redfish Health value for the specified sensor.
612  * @param sensorJson Sensor JSON object.
613  * @param valuesDict Map of all sensor DBus values.
614  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
615  * be nullptr if no associated inventory item was found.
616  * @return Health value for sensor.
617  */
618 inline std::string getHealth(nlohmann::json& sensorJson,
619                              const dbus::utility::DBusPropertiesMap& valuesDict,
620                              const InventoryItem* inventoryItem)
621 {
622     // Get current health value (if any) in the sensor JSON object.  Some JSON
623     // objects contain multiple sensors (such as PowerSupplies).  We want to set
624     // the overall health to be the most severe of any of the sensors.
625     std::string currentHealth;
626     auto statusIt = sensorJson.find("Status");
627     if (statusIt != sensorJson.end())
628     {
629         auto healthIt = statusIt->find("Health");
630         if (healthIt != statusIt->end())
631         {
632             std::string* health = healthIt->get_ptr<std::string*>();
633             if (health != nullptr)
634             {
635                 currentHealth = *health;
636             }
637         }
638     }
639 
640     // If current health in JSON object is already Critical, return that.  This
641     // should override the sensor health, which might be less severe.
642     if (currentHealth == "Critical")
643     {
644         return "Critical";
645     }
646 
647     const bool* criticalAlarmHigh = nullptr;
648     const bool* criticalAlarmLow = nullptr;
649     const bool* warningAlarmHigh = nullptr;
650     const bool* warningAlarmLow = nullptr;
651 
652     const bool success = sdbusplus::unpackPropertiesNoThrow(
653         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
654         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
655         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
656         warningAlarmLow);
657 
658     if (success)
659     {
660         // Check if sensor has critical threshold alarm
661         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
662             (criticalAlarmLow != nullptr && *criticalAlarmLow))
663         {
664             return "Critical";
665         }
666     }
667 
668     // Check if associated inventory item is not functional
669     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
670     {
671         return "Critical";
672     }
673 
674     // If current health in JSON object is already Warning, return that. This
675     // should override the sensor status, which might be less severe.
676     if (currentHealth == "Warning")
677     {
678         return "Warning";
679     }
680 
681     if (success)
682     {
683         // Check if sensor has warning threshold alarm
684         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
685             (warningAlarmLow != nullptr && *warningAlarmLow))
686         {
687             return "Warning";
688         }
689     }
690 
691     return "OK";
692 }
693 
694 inline void setLedState(nlohmann::json& sensorJson,
695                         const InventoryItem* inventoryItem)
696 {
697     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
698     {
699         switch (inventoryItem->ledState)
700         {
701             case LedState::OFF:
702                 sensorJson["IndicatorLED"] = "Off";
703                 break;
704             case LedState::ON:
705                 sensorJson["IndicatorLED"] = "Lit";
706                 break;
707             case LedState::BLINK:
708                 sensorJson["IndicatorLED"] = "Blinking";
709                 break;
710             case LedState::UNKNOWN:
711                 break;
712         }
713     }
714 }
715 
716 /**
717  * @brief Builds a json sensor representation of a sensor.
718  * @param sensorName  The name of the sensor to be built
719  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
720  * build
721  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
722  * @param propertiesDict A dictionary of the properties to build the sensor
723  * from.
724  * @param sensorJson  The json object to fill
725  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
726  * be nullptr if no associated inventory item was found.
727  */
728 inline void objectPropertiesToJson(
729     std::string_view sensorName, std::string_view sensorType,
730     std::string_view chassisSubNode,
731     const dbus::utility::DBusPropertiesMap& propertiesDict,
732     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
733 {
734     if (chassisSubNode == sensors::node::sensors)
735     {
736         std::string subNodeEscaped(chassisSubNode);
737         subNodeEscaped.erase(
738             std::remove(subNodeEscaped.begin(), subNodeEscaped.end(), '_'),
739             subNodeEscaped.end());
740 
741         // For sensors in SensorCollection we set Id instead of MemberId,
742         // including power sensors.
743         subNodeEscaped += '_';
744         subNodeEscaped += sensorName;
745         sensorJson["Id"] = std::move(subNodeEscaped);
746 
747         std::string sensorNameEs(sensorName);
748         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
749         sensorJson["Name"] = std::move(sensorNameEs);
750     }
751     else if (sensorType != "power")
752     {
753         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
754         // PowerControl, those properties have more general values because
755         // multiple sensors can be stored in the same JSON object.
756         sensorJson["MemberId"] = sensorName;
757         std::string sensorNameEs(sensorName);
758         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
759         sensorJson["Name"] = std::move(sensorNameEs);
760     }
761 
762     sensorJson["Status"]["State"] = getState(inventoryItem);
763     sensorJson["Status"]["Health"] =
764         getHealth(sensorJson, propertiesDict, inventoryItem);
765 
766     // Parameter to set to override the type we get from dbus, and force it to
767     // int, regardless of what is available.  This is used for schemas like fan,
768     // that require integers, not floats.
769     bool forceToInt = false;
770 
771     nlohmann::json::json_pointer unit("/Reading");
772     if (chassisSubNode == sensors::node::sensors)
773     {
774         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
775 
776         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
777         if (readingType == sensor::ReadingType::Invalid)
778         {
779             BMCWEB_LOG_ERROR << "Redfish cannot map reading type for "
780                              << sensorType;
781         }
782         else
783         {
784             sensorJson["ReadingType"] = readingType;
785         }
786 
787         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
788         if (readingUnits.empty())
789         {
790             BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for "
791                              << sensorType;
792         }
793         else
794         {
795             sensorJson["ReadingUnits"] = readingUnits;
796         }
797     }
798     else if (sensorType == "temperature")
799     {
800         unit = "/ReadingCelsius"_json_pointer;
801         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
802         // TODO(ed) Documentation says that path should be type fan_tach,
803         // implementation seems to implement fan
804     }
805     else if (sensorType == "fan" || sensorType == "fan_tach")
806     {
807         unit = "/Reading"_json_pointer;
808         sensorJson["ReadingUnits"] = "RPM";
809         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
810         setLedState(sensorJson, inventoryItem);
811         forceToInt = true;
812     }
813     else if (sensorType == "fan_pwm")
814     {
815         unit = "/Reading"_json_pointer;
816         sensorJson["ReadingUnits"] = "Percent";
817         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
818         setLedState(sensorJson, inventoryItem);
819         forceToInt = true;
820     }
821     else if (sensorType == "voltage")
822     {
823         unit = "/ReadingVolts"_json_pointer;
824         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
825     }
826     else if (sensorType == "power")
827     {
828         if (boost::iequals(sensorName, "total_power"))
829         {
830             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
831             // Put multiple "sensors" into a single PowerControl, so have
832             // generic names for MemberId and Name. Follows Redfish mockup.
833             sensorJson["MemberId"] = "0";
834             sensorJson["Name"] = "Chassis Power Control";
835             unit = "/PowerConsumedWatts"_json_pointer;
836         }
837         else if (boost::ifind_first(sensorName, "input").empty())
838         {
839             unit = "/PowerInputWatts"_json_pointer;
840         }
841         else
842         {
843             unit = "/PowerOutputWatts"_json_pointer;
844         }
845     }
846     else
847     {
848         BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
849         return;
850     }
851     // Map of dbus interface name, dbus property name and redfish property_name
852     std::vector<
853         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
854         properties;
855     properties.reserve(7);
856 
857     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
858 
859     if (chassisSubNode == sensors::node::sensors)
860     {
861         properties.emplace_back(
862             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
863             "/Thresholds/UpperCaution/Reading"_json_pointer);
864         properties.emplace_back(
865             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
866             "/Thresholds/LowerCaution/Reading"_json_pointer);
867         properties.emplace_back(
868             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
869             "/Thresholds/UpperCritical/Reading"_json_pointer);
870         properties.emplace_back(
871             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
872             "/Thresholds/LowerCritical/Reading"_json_pointer);
873     }
874     else if (sensorType != "power")
875     {
876         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
877                                 "WarningHigh",
878                                 "/UpperThresholdNonCritical"_json_pointer);
879         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
880                                 "WarningLow",
881                                 "/LowerThresholdNonCritical"_json_pointer);
882         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
883                                 "CriticalHigh",
884                                 "/UpperThresholdCritical"_json_pointer);
885         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
886                                 "CriticalLow",
887                                 "/LowerThresholdCritical"_json_pointer);
888     }
889 
890     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
891 
892     if (chassisSubNode == sensors::node::sensors)
893     {
894         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
895                                 "/ReadingRangeMin"_json_pointer);
896         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
897                                 "/ReadingRangeMax"_json_pointer);
898         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
899                                 "Accuracy", "/Accuracy"_json_pointer);
900     }
901     else if (sensorType == "temperature")
902     {
903         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
904                                 "/MinReadingRangeTemp"_json_pointer);
905         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
906                                 "/MaxReadingRangeTemp"_json_pointer);
907     }
908     else if (sensorType != "power")
909     {
910         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
911                                 "/MinReadingRange"_json_pointer);
912         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
913                                 "/MaxReadingRange"_json_pointer);
914     }
915 
916     for (const std::tuple<const char*, const char*,
917                           nlohmann::json::json_pointer>& p : properties)
918     {
919         for (const auto& [valueName, valueVariant] : propertiesDict)
920         {
921             if (valueName != std::get<1>(p))
922             {
923                 continue;
924             }
925 
926             // The property we want to set may be nested json, so use
927             // a json_pointer for easy indexing into the json structure.
928             const nlohmann::json::json_pointer& key = std::get<2>(p);
929 
930             const double* doubleValue = std::get_if<double>(&valueVariant);
931             if (doubleValue == nullptr)
932             {
933                 BMCWEB_LOG_ERROR << "Got value interface that wasn't double";
934                 continue;
935             }
936             if (forceToInt)
937             {
938                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
939             }
940             else
941             {
942                 sensorJson[key] = *doubleValue;
943             }
944         }
945     }
946 }
947 
948 /**
949  * @brief Builds a json sensor representation of a sensor.
950  * @param sensorName  The name of the sensor to be built
951  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
952  * build
953  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
954  * @param interfacesDict  A dictionary of the interfaces and properties of said
955  * interfaces to be built from
956  * @param sensorJson  The json object to fill
957  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
958  * be nullptr if no associated inventory item was found.
959  */
960 inline void objectInterfacesToJson(
961     const std::string& sensorName, const std::string& sensorType,
962     const std::string& chassisSubNode,
963     const dbus::utility::DBusInteracesMap& interfacesDict,
964     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
965 {
966 
967     for (const auto& [interface, valuesDict] : interfacesDict)
968     {
969         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
970                                valuesDict, sensorJson, inventoryItem);
971     }
972     BMCWEB_LOG_DEBUG << "Added sensor " << sensorName;
973 }
974 
975 inline void populateFanRedundancy(
976     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
977 {
978     crow::connections::systemBus->async_method_call(
979         [sensorsAsyncResp](
980             const boost::system::error_code ec,
981             const dbus::utility::MapperGetSubTreeResponse& resp) {
982         if (ec)
983         {
984             return; // don't have to have this interface
985         }
986         for (const std::pair<
987                  std::string,
988                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
989                  pathPair : resp)
990         {
991             const std::string& path = pathPair.first;
992             const std::vector<std::pair<std::string, std::vector<std::string>>>&
993                 objDict = pathPair.second;
994             if (objDict.empty())
995             {
996                 continue; // this should be impossible
997             }
998 
999             const std::string& owner = objDict.begin()->first;
1000             sdbusplus::asio::getProperty<std::vector<std::string>>(
1001                 *crow::connections::systemBus,
1002                 "xyz.openbmc_project.ObjectMapper", path + "/chassis",
1003                 "xyz.openbmc_project.Association", "endpoints",
1004                 [path, owner,
1005                  sensorsAsyncResp](const boost::system::error_code e,
1006                                    const std::vector<std::string>& endpoints) {
1007                 if (e)
1008                 {
1009                     return; // if they don't have an association we
1010                             // can't tell what chassis is
1011                 }
1012                 auto found =
1013                     std::find_if(endpoints.begin(), endpoints.end(),
1014                                  [sensorsAsyncResp](const std::string& entry) {
1015                     return entry.find(sensorsAsyncResp->chassisId) !=
1016                            std::string::npos;
1017                     });
1018 
1019                 if (found == endpoints.end())
1020                 {
1021                     return;
1022                 }
1023                 sdbusplus::asio::getAllProperties(
1024                     *crow::connections::systemBus, owner, path,
1025                     "xyz.openbmc_project.Control.FanRedundancy",
1026                     [path, sensorsAsyncResp](
1027                         const boost::system::error_code& err,
1028                         const dbus::utility::DBusPropertiesMap& ret) {
1029                     if (err)
1030                     {
1031                         return; // don't have to have this
1032                                 // interface
1033                     }
1034 
1035                     const uint8_t* allowedFailures = nullptr;
1036                     const std::vector<std::string>* collection = nullptr;
1037                     const std::string* status = nullptr;
1038 
1039                     const bool success = sdbusplus::unpackPropertiesNoThrow(
1040                         dbus_utils::UnpackErrorPrinter(), ret,
1041                         "AllowedFailures", allowedFailures, "Collection",
1042                         collection, "Status", status);
1043 
1044                     if (!success)
1045                     {
1046                         messages::internalError(
1047                             sensorsAsyncResp->asyncResp->res);
1048                         return;
1049                     }
1050 
1051                     if (allowedFailures == nullptr || collection == nullptr ||
1052                         status == nullptr)
1053                     {
1054                         BMCWEB_LOG_ERROR << "Invalid redundancy interface";
1055                         messages::internalError(
1056                             sensorsAsyncResp->asyncResp->res);
1057                         return;
1058                     }
1059 
1060                     sdbusplus::message::object_path objectPath(path);
1061                     std::string name = objectPath.filename();
1062                     if (name.empty())
1063                     {
1064                         // this should be impossible
1065                         messages::internalError(
1066                             sensorsAsyncResp->asyncResp->res);
1067                         return;
1068                     }
1069                     std::replace(name.begin(), name.end(), '_', ' ');
1070 
1071                     std::string health;
1072 
1073                     if (status->ends_with("Full"))
1074                     {
1075                         health = "OK";
1076                     }
1077                     else if (status->ends_with("Degraded"))
1078                     {
1079                         health = "Warning";
1080                     }
1081                     else
1082                     {
1083                         health = "Critical";
1084                     }
1085                     nlohmann::json::array_t redfishCollection;
1086                     const auto& fanRedfish =
1087                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
1088                     for (const std::string& item : *collection)
1089                     {
1090                         sdbusplus::message::object_path itemPath(item);
1091                         std::string itemName = itemPath.filename();
1092                         if (itemName.empty())
1093                         {
1094                             continue;
1095                         }
1096                         /*
1097                         todo(ed): merge patch that fixes the names
1098                         std::replace(itemName.begin(),
1099                                      itemName.end(), '_', ' ');*/
1100                         auto schemaItem =
1101                             std::find_if(fanRedfish.begin(), fanRedfish.end(),
1102                                          [itemName](const nlohmann::json& fan) {
1103                             return fan["MemberId"] == itemName;
1104                             });
1105                         if (schemaItem != fanRedfish.end())
1106                         {
1107                             nlohmann::json::object_t collectionId;
1108                             collectionId["@odata.id"] =
1109                                 (*schemaItem)["@odata.id"];
1110                             redfishCollection.emplace_back(
1111                                 std::move(collectionId));
1112                         }
1113                         else
1114                         {
1115                             BMCWEB_LOG_ERROR << "failed to find fan in schema";
1116                             messages::internalError(
1117                                 sensorsAsyncResp->asyncResp->res);
1118                             return;
1119                         }
1120                     }
1121 
1122                     size_t minNumNeeded =
1123                         collection->empty()
1124                             ? 0
1125                             : collection->size() - *allowedFailures;
1126                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
1127                                                 .jsonValue["Redundancy"];
1128 
1129                     nlohmann::json::object_t redundancy;
1130                     redundancy["@odata.id"] =
1131                         "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId +
1132                         "/" + sensorsAsyncResp->chassisSubNode +
1133                         "#/Redundancy/" + std::to_string(jResp.size());
1134                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
1135                     redundancy["MinNumNeeded"] = minNumNeeded;
1136                     redundancy["MemberId"] = name;
1137                     redundancy["Mode"] = "N+m";
1138                     redundancy["Name"] = name;
1139                     redundancy["RedundancySet"] = redfishCollection;
1140                     redundancy["Status"]["Health"] = health;
1141                     redundancy["Status"]["State"] = "Enabled";
1142 
1143                     jResp.push_back(std::move(redundancy));
1144                     });
1145                 });
1146         }
1147         },
1148         "xyz.openbmc_project.ObjectMapper",
1149         "/xyz/openbmc_project/object_mapper",
1150         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
1151         "/xyz/openbmc_project/control", 2,
1152         std::array<const char*, 1>{
1153             "xyz.openbmc_project.Control.FanRedundancy"});
1154 }
1155 
1156 inline void
1157     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
1158 {
1159     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
1160     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
1161     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
1162     {
1163         sensorHeaders = {"Voltages", "PowerSupplies"};
1164     }
1165     for (const std::string& sensorGroup : sensorHeaders)
1166     {
1167         nlohmann::json::iterator entry = response.find(sensorGroup);
1168         if (entry != response.end())
1169         {
1170             std::sort(entry->begin(), entry->end(),
1171                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
1172                 return c1["Name"] < c2["Name"];
1173             });
1174 
1175             // add the index counts to the end of each entry
1176             size_t count = 0;
1177             for (nlohmann::json& sensorJson : *entry)
1178             {
1179                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
1180                 if (odata == sensorJson.end())
1181                 {
1182                     continue;
1183                 }
1184                 std::string* value = odata->get_ptr<std::string*>();
1185                 if (value != nullptr)
1186                 {
1187                     *value += std::to_string(count);
1188                     count++;
1189                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
1190                 }
1191             }
1192         }
1193     }
1194 }
1195 
1196 /**
1197  * @brief Finds the inventory item with the specified object path.
1198  * @param inventoryItems D-Bus inventory items associated with sensors.
1199  * @param invItemObjPath D-Bus object path of inventory item.
1200  * @return Inventory item within vector, or nullptr if no match found.
1201  */
1202 inline InventoryItem* findInventoryItem(
1203     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1204     const std::string& invItemObjPath)
1205 {
1206     for (InventoryItem& inventoryItem : *inventoryItems)
1207     {
1208         if (inventoryItem.objectPath == invItemObjPath)
1209         {
1210             return &inventoryItem;
1211         }
1212     }
1213     return nullptr;
1214 }
1215 
1216 /**
1217  * @brief Finds the inventory item associated with the specified sensor.
1218  * @param inventoryItems D-Bus inventory items associated with sensors.
1219  * @param sensorObjPath D-Bus object path of sensor.
1220  * @return Inventory item within vector, or nullptr if no match found.
1221  */
1222 inline InventoryItem* findInventoryItemForSensor(
1223     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1224     const std::string& sensorObjPath)
1225 {
1226     for (InventoryItem& inventoryItem : *inventoryItems)
1227     {
1228         if (inventoryItem.sensors.count(sensorObjPath) > 0)
1229         {
1230             return &inventoryItem;
1231         }
1232     }
1233     return nullptr;
1234 }
1235 
1236 /**
1237  * @brief Finds the inventory item associated with the specified led path.
1238  * @param inventoryItems D-Bus inventory items associated with sensors.
1239  * @param ledObjPath D-Bus object path of led.
1240  * @return Inventory item within vector, or nullptr if no match found.
1241  */
1242 inline InventoryItem*
1243     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1244                             const std::string& ledObjPath)
1245 {
1246     for (InventoryItem& inventoryItem : inventoryItems)
1247     {
1248         if (inventoryItem.ledObjectPath == ledObjPath)
1249         {
1250             return &inventoryItem;
1251         }
1252     }
1253     return nullptr;
1254 }
1255 
1256 /**
1257  * @brief Adds inventory item and associated sensor to specified vector.
1258  *
1259  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1260  * existing InventoryItem with the specified object path.  If not found, one is
1261  * added to the vector.
1262  *
1263  * Next, the specified sensor is added to the set of sensors associated with the
1264  * InventoryItem.
1265  *
1266  * @param inventoryItems D-Bus inventory items associated with sensors.
1267  * @param invItemObjPath D-Bus object path of inventory item.
1268  * @param sensorObjPath D-Bus object path of sensor
1269  */
1270 inline void addInventoryItem(
1271     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1272     const std::string& invItemObjPath, const std::string& sensorObjPath)
1273 {
1274     // Look for inventory item in vector
1275     InventoryItem* inventoryItem =
1276         findInventoryItem(inventoryItems, invItemObjPath);
1277 
1278     // If inventory item doesn't exist in vector, add it
1279     if (inventoryItem == nullptr)
1280     {
1281         inventoryItems->emplace_back(invItemObjPath);
1282         inventoryItem = &(inventoryItems->back());
1283     }
1284 
1285     // Add sensor to set of sensors associated with inventory item
1286     inventoryItem->sensors.emplace(sensorObjPath);
1287 }
1288 
1289 /**
1290  * @brief Stores D-Bus data in the specified inventory item.
1291  *
1292  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1293  * specified InventoryItem.
1294  *
1295  * This data is later used to provide sensor property values in the JSON
1296  * response.
1297  *
1298  * @param inventoryItem Inventory item where data will be stored.
1299  * @param interfacesDict Map containing D-Bus interfaces and their properties
1300  * for the specified inventory item.
1301  */
1302 inline void storeInventoryItemData(
1303     InventoryItem& inventoryItem,
1304     const dbus::utility::DBusInteracesMap& interfacesDict)
1305 {
1306     // Get properties from Inventory.Item interface
1307 
1308     for (const auto& [interface, values] : interfacesDict)
1309     {
1310         if (interface == "xyz.openbmc_project.Inventory.Item")
1311         {
1312             for (const auto& [name, dbusValue] : values)
1313             {
1314                 if (name == "Present")
1315                 {
1316                     const bool* value = std::get_if<bool>(&dbusValue);
1317                     if (value != nullptr)
1318                     {
1319                         inventoryItem.isPresent = *value;
1320                     }
1321                 }
1322             }
1323         }
1324         // Check if Inventory.Item.PowerSupply interface is present
1325 
1326         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
1327         {
1328             inventoryItem.isPowerSupply = true;
1329         }
1330 
1331         // Get properties from Inventory.Decorator.Asset interface
1332         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1333         {
1334             for (const auto& [name, dbusValue] : values)
1335             {
1336                 if (name == "Manufacturer")
1337                 {
1338                     const std::string* value =
1339                         std::get_if<std::string>(&dbusValue);
1340                     if (value != nullptr)
1341                     {
1342                         inventoryItem.manufacturer = *value;
1343                     }
1344                 }
1345                 if (name == "Model")
1346                 {
1347                     const std::string* value =
1348                         std::get_if<std::string>(&dbusValue);
1349                     if (value != nullptr)
1350                     {
1351                         inventoryItem.model = *value;
1352                     }
1353                 }
1354                 if (name == "SerialNumber")
1355                 {
1356                     const std::string* value =
1357                         std::get_if<std::string>(&dbusValue);
1358                     if (value != nullptr)
1359                     {
1360                         inventoryItem.serialNumber = *value;
1361                     }
1362                 }
1363                 if (name == "PartNumber")
1364                 {
1365                     const std::string* value =
1366                         std::get_if<std::string>(&dbusValue);
1367                     if (value != nullptr)
1368                     {
1369                         inventoryItem.partNumber = *value;
1370                     }
1371                 }
1372             }
1373         }
1374 
1375         if (interface ==
1376             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1377         {
1378             for (const auto& [name, dbusValue] : values)
1379             {
1380                 if (name == "Functional")
1381                 {
1382                     const bool* value = std::get_if<bool>(&dbusValue);
1383                     if (value != nullptr)
1384                     {
1385                         inventoryItem.isFunctional = *value;
1386                     }
1387                 }
1388             }
1389         }
1390     }
1391 }
1392 
1393 /**
1394  * @brief Gets D-Bus data for inventory items associated with sensors.
1395  *
1396  * Uses the specified connections (services) to obtain D-Bus data for inventory
1397  * items associated with sensors.  Stores the resulting data in the
1398  * inventoryItems vector.
1399  *
1400  * This data is later used to provide sensor property values in the JSON
1401  * response.
1402  *
1403  * Finds the inventory item data asynchronously.  Invokes callback when data has
1404  * been obtained.
1405  *
1406  * The callback must have the following signature:
1407  *   @code
1408  *   callback(void)
1409  *   @endcode
1410  *
1411  * This function is called recursively, obtaining data asynchronously from one
1412  * connection in each call.  This ensures the callback is not invoked until the
1413  * last asynchronous function has completed.
1414  *
1415  * @param sensorsAsyncResp Pointer to object holding response data.
1416  * @param inventoryItems D-Bus inventory items associated with sensors.
1417  * @param invConnections Connections that provide data for the inventory items.
1418  * implements ObjectManager.
1419  * @param callback Callback to invoke when inventory data has been obtained.
1420  * @param invConnectionsIndex Current index in invConnections.  Only specified
1421  * in recursive calls to this function.
1422  */
1423 template <typename Callback>
1424 static void getInventoryItemsData(
1425     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1426     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1427     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1428     size_t invConnectionsIndex = 0)
1429 {
1430     BMCWEB_LOG_DEBUG << "getInventoryItemsData enter";
1431 
1432     // If no more connections left, call callback
1433     if (invConnectionsIndex >= invConnections->size())
1434     {
1435         callback();
1436         BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1437         return;
1438     }
1439 
1440     // Get inventory item data from current connection
1441     auto it = invConnections->begin();
1442     std::advance(it, invConnectionsIndex);
1443     if (it != invConnections->end())
1444     {
1445         const std::string& invConnection = *it;
1446 
1447         // Response handler for GetManagedObjects
1448         auto respHandler = [sensorsAsyncResp, inventoryItems, invConnections,
1449                             callback{std::forward<Callback>(callback)},
1450                             invConnectionsIndex](
1451                                const boost::system::error_code ec,
1452                                const dbus::utility::ManagedObjectType& resp) {
1453             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter";
1454             if (ec)
1455             {
1456                 BMCWEB_LOG_ERROR
1457                     << "getInventoryItemsData respHandler DBus error " << ec;
1458                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1459                 return;
1460             }
1461 
1462             // Loop through returned object paths
1463             for (const auto& objDictEntry : resp)
1464             {
1465                 const std::string& objPath =
1466                     static_cast<const std::string&>(objDictEntry.first);
1467 
1468                 // If this object path is one of the specified inventory items
1469                 InventoryItem* inventoryItem =
1470                     findInventoryItem(inventoryItems, objPath);
1471                 if (inventoryItem != nullptr)
1472                 {
1473                     // Store inventory data in InventoryItem
1474                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
1475                 }
1476             }
1477 
1478             // Recurse to get inventory item data from next connection
1479             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1480                                   invConnections, std::move(callback),
1481                                   invConnectionsIndex + 1);
1482 
1483             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit";
1484         };
1485 
1486         // Get all object paths and their interfaces for current connection
1487         crow::connections::systemBus->async_method_call(
1488             std::move(respHandler), invConnection,
1489             "/xyz/openbmc_project/inventory",
1490             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1491     }
1492 
1493     BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1494 }
1495 
1496 /**
1497  * @brief Gets connections that provide D-Bus data for inventory items.
1498  *
1499  * Gets the D-Bus connections (services) that provide data for the inventory
1500  * items that are associated with sensors.
1501  *
1502  * Finds the connections asynchronously.  Invokes callback when information has
1503  * been obtained.
1504  *
1505  * The callback must have the following signature:
1506  *   @code
1507  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
1508  *   @endcode
1509  *
1510  * @param sensorsAsyncResp Pointer to object holding response data.
1511  * @param inventoryItems D-Bus inventory items associated with sensors.
1512  * @param callback Callback to invoke when connections have been obtained.
1513  */
1514 template <typename Callback>
1515 static void getInventoryItemsConnections(
1516     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1517     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1518     Callback&& callback)
1519 {
1520     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter";
1521 
1522     const std::string path = "/xyz/openbmc_project/inventory";
1523     const std::array<std::string, 4> interfaces = {
1524         "xyz.openbmc_project.Inventory.Item",
1525         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1526         "xyz.openbmc_project.Inventory.Decorator.Asset",
1527         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
1528 
1529     // Response handler for parsing output from GetSubTree
1530     auto respHandler =
1531         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1532          inventoryItems](
1533             const boost::system::error_code ec,
1534             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1535         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter";
1536         if (ec)
1537         {
1538             messages::internalError(sensorsAsyncResp->asyncResp->res);
1539             BMCWEB_LOG_ERROR
1540                 << "getInventoryItemsConnections respHandler DBus error " << ec;
1541             return;
1542         }
1543 
1544         // Make unique list of connections for desired inventory items
1545         std::shared_ptr<std::set<std::string>> invConnections =
1546             std::make_shared<std::set<std::string>>();
1547 
1548         // Loop through objects from GetSubTree
1549         for (const std::pair<
1550                  std::string,
1551                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1552                  object : subtree)
1553         {
1554             // Check if object path is one of the specified inventory items
1555             const std::string& objPath = object.first;
1556             if (findInventoryItem(inventoryItems, objPath) != nullptr)
1557             {
1558                 // Store all connections to inventory item
1559                 for (const std::pair<std::string, std::vector<std::string>>&
1560                          objData : object.second)
1561                 {
1562                     const std::string& invConnection = objData.first;
1563                     invConnections->insert(invConnection);
1564                 }
1565             }
1566         }
1567 
1568         callback(invConnections);
1569         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit";
1570     };
1571 
1572     // Make call to ObjectMapper to find all inventory items
1573     crow::connections::systemBus->async_method_call(
1574         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
1575         "/xyz/openbmc_project/object_mapper",
1576         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
1577     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit";
1578 }
1579 
1580 /**
1581  * @brief Gets associations from sensors to inventory items.
1582  *
1583  * Looks for ObjectMapper associations from the specified sensors to related
1584  * inventory items. Then finds the associations from those inventory items to
1585  * their LEDs, if any.
1586  *
1587  * Finds the inventory items asynchronously.  Invokes callback when information
1588  * has been obtained.
1589  *
1590  * The callback must have the following signature:
1591  *   @code
1592  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
1593  *   @endcode
1594  *
1595  * @param sensorsAsyncResp Pointer to object holding response data.
1596  * @param sensorNames All sensors within the current chassis.
1597  * implements ObjectManager.
1598  * @param callback Callback to invoke when inventory items have been obtained.
1599  */
1600 template <typename Callback>
1601 static void getInventoryItemAssociations(
1602     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1603     const std::shared_ptr<std::set<std::string>>& sensorNames,
1604     Callback&& callback)
1605 {
1606     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter";
1607 
1608     // Response handler for GetManagedObjects
1609     auto respHandler =
1610         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1611          sensorNames](const boost::system::error_code ec,
1612                       const dbus::utility::ManagedObjectType& resp) {
1613         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter";
1614         if (ec)
1615         {
1616             BMCWEB_LOG_ERROR
1617                 << "getInventoryItemAssociations respHandler DBus error " << ec;
1618             messages::internalError(sensorsAsyncResp->asyncResp->res);
1619             return;
1620         }
1621 
1622         // Create vector to hold list of inventory items
1623         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1624             std::make_shared<std::vector<InventoryItem>>();
1625 
1626         // Loop through returned object paths
1627         std::string sensorAssocPath;
1628         sensorAssocPath.reserve(128); // avoid memory allocations
1629         for (const auto& objDictEntry : resp)
1630         {
1631             const std::string& objPath =
1632                 static_cast<const std::string&>(objDictEntry.first);
1633 
1634             // If path is inventory association for one of the specified sensors
1635             for (const std::string& sensorName : *sensorNames)
1636             {
1637                 sensorAssocPath = sensorName;
1638                 sensorAssocPath += "/inventory";
1639                 if (objPath == sensorAssocPath)
1640                 {
1641                     // Get Association interface for object path
1642                     for (const auto& [interface, values] : objDictEntry.second)
1643                     {
1644                         if (interface == "xyz.openbmc_project.Association")
1645                         {
1646                             for (const auto& [valueName, value] : values)
1647                             {
1648                                 if (valueName == "endpoints")
1649                                 {
1650                                     const std::vector<std::string>* endpoints =
1651                                         std::get_if<std::vector<std::string>>(
1652                                             &value);
1653                                     if ((endpoints != nullptr) &&
1654                                         !endpoints->empty())
1655                                     {
1656                                         // Add inventory item to vector
1657                                         const std::string& invItemPath =
1658                                             endpoints->front();
1659                                         addInventoryItem(inventoryItems,
1660                                                          invItemPath,
1661                                                          sensorName);
1662                                     }
1663                                 }
1664                             }
1665                         }
1666                     }
1667                     break;
1668                 }
1669             }
1670         }
1671 
1672         // Now loop through the returned object paths again, this time to
1673         // find the leds associated with the inventory items we just found
1674         std::string inventoryAssocPath;
1675         inventoryAssocPath.reserve(128); // avoid memory allocations
1676         for (const auto& objDictEntry : resp)
1677         {
1678             const std::string& objPath =
1679                 static_cast<const std::string&>(objDictEntry.first);
1680 
1681             for (InventoryItem& inventoryItem : *inventoryItems)
1682             {
1683                 inventoryAssocPath = inventoryItem.objectPath;
1684                 inventoryAssocPath += "/leds";
1685                 if (objPath == inventoryAssocPath)
1686                 {
1687                     for (const auto& [interface, values] : objDictEntry.second)
1688                     {
1689                         if (interface == "xyz.openbmc_project.Association")
1690                         {
1691                             for (const auto& [valueName, value] : values)
1692                             {
1693                                 if (valueName == "endpoints")
1694                                 {
1695                                     const std::vector<std::string>* endpoints =
1696                                         std::get_if<std::vector<std::string>>(
1697                                             &value);
1698                                     if ((endpoints != nullptr) &&
1699                                         !endpoints->empty())
1700                                     {
1701                                         // Add inventory item to vector
1702                                         // Store LED path in inventory item
1703                                         const std::string& ledPath =
1704                                             endpoints->front();
1705                                         inventoryItem.ledObjectPath = ledPath;
1706                                     }
1707                                 }
1708                             }
1709                         }
1710                     }
1711 
1712                     break;
1713                 }
1714             }
1715         }
1716         callback(inventoryItems);
1717         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit";
1718     };
1719 
1720     // Call GetManagedObjects on the ObjectMapper to get all associations
1721     crow::connections::systemBus->async_method_call(
1722         std::move(respHandler), "xyz.openbmc_project.ObjectMapper", "/",
1723         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1724 
1725     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit";
1726 }
1727 
1728 /**
1729  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1730  *
1731  * Uses the specified connections (services) to obtain D-Bus data for inventory
1732  * item leds associated with sensors.  Stores the resulting data in the
1733  * inventoryItems vector.
1734  *
1735  * This data is later used to provide sensor property values in the JSON
1736  * response.
1737  *
1738  * Finds the inventory item led data asynchronously.  Invokes callback when data
1739  * has been obtained.
1740  *
1741  * The callback must have the following signature:
1742  *   @code
1743  *   callback()
1744  *   @endcode
1745  *
1746  * This function is called recursively, obtaining data asynchronously from one
1747  * connection in each call.  This ensures the callback is not invoked until the
1748  * last asynchronous function has completed.
1749  *
1750  * @param sensorsAsyncResp Pointer to object holding response data.
1751  * @param inventoryItems D-Bus inventory items associated with sensors.
1752  * @param ledConnections Connections that provide data for the inventory leds.
1753  * @param callback Callback to invoke when inventory data has been obtained.
1754  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1755  * in recursive calls to this function.
1756  */
1757 template <typename Callback>
1758 void getInventoryLedData(
1759     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1760     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1761     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1762     Callback&& callback, size_t ledConnectionsIndex = 0)
1763 {
1764     BMCWEB_LOG_DEBUG << "getInventoryLedData enter";
1765 
1766     // If no more connections left, call callback
1767     if (ledConnectionsIndex >= ledConnections->size())
1768     {
1769         callback();
1770         BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1771         return;
1772     }
1773 
1774     // Get inventory item data from current connection
1775     auto it = ledConnections->begin();
1776     std::advance(it, ledConnectionsIndex);
1777     if (it != ledConnections->end())
1778     {
1779         const std::string& ledPath = (*it).first;
1780         const std::string& ledConnection = (*it).second;
1781         // Response handler for Get State property
1782         auto respHandler =
1783             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1784              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
1785                 const boost::system::error_code ec, const std::string& state) {
1786             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter";
1787             if (ec)
1788             {
1789                 BMCWEB_LOG_ERROR
1790                     << "getInventoryLedData respHandler DBus error " << ec;
1791                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1792                 return;
1793             }
1794 
1795             BMCWEB_LOG_DEBUG << "Led state: " << state;
1796             // Find inventory item with this LED object path
1797             InventoryItem* inventoryItem =
1798                 findInventoryItemForLed(*inventoryItems, ledPath);
1799             if (inventoryItem != nullptr)
1800             {
1801                 // Store LED state in InventoryItem
1802                 if (state.ends_with("On"))
1803                 {
1804                     inventoryItem->ledState = LedState::ON;
1805                 }
1806                 else if (state.ends_with("Blink"))
1807                 {
1808                     inventoryItem->ledState = LedState::BLINK;
1809                 }
1810                 else if (state.ends_with("Off"))
1811                 {
1812                     inventoryItem->ledState = LedState::OFF;
1813                 }
1814                 else
1815                 {
1816                     inventoryItem->ledState = LedState::UNKNOWN;
1817                 }
1818             }
1819 
1820             // Recurse to get LED data from next connection
1821             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1822                                 ledConnections, std::move(callback),
1823                                 ledConnectionsIndex + 1);
1824 
1825             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit";
1826         };
1827 
1828         // Get the State property for the current LED
1829         sdbusplus::asio::getProperty<std::string>(
1830             *crow::connections::systemBus, ledConnection, ledPath,
1831             "xyz.openbmc_project.Led.Physical", "State",
1832             std::move(respHandler));
1833     }
1834 
1835     BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1836 }
1837 
1838 /**
1839  * @brief Gets LED data for LEDs associated with given inventory items.
1840  *
1841  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1842  * associated with the specified inventory items.  Then gets the LED data from
1843  * each connection and stores it in the inventory item.
1844  *
1845  * This data is later used to provide sensor property values in the JSON
1846  * response.
1847  *
1848  * Finds the LED data asynchronously.  Invokes callback when information has
1849  * been obtained.
1850  *
1851  * The callback must have the following signature:
1852  *   @code
1853  *   callback()
1854  *   @endcode
1855  *
1856  * @param sensorsAsyncResp Pointer to object holding response data.
1857  * @param inventoryItems D-Bus inventory items associated with sensors.
1858  * @param callback Callback to invoke when inventory items have been obtained.
1859  */
1860 template <typename Callback>
1861 void getInventoryLeds(
1862     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1863     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1864     Callback&& callback)
1865 {
1866     BMCWEB_LOG_DEBUG << "getInventoryLeds enter";
1867 
1868     const std::string path = "/xyz/openbmc_project";
1869     const std::array<std::string, 1> interfaces = {
1870         "xyz.openbmc_project.Led.Physical"};
1871 
1872     // Response handler for parsing output from GetSubTree
1873     auto respHandler =
1874         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1875          inventoryItems](
1876             const boost::system::error_code ec,
1877             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1878         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter";
1879         if (ec)
1880         {
1881             messages::internalError(sensorsAsyncResp->asyncResp->res);
1882             BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error "
1883                              << ec;
1884             return;
1885         }
1886 
1887         // Build map of LED object paths to connections
1888         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1889             std::make_shared<std::map<std::string, std::string>>();
1890 
1891         // Loop through objects from GetSubTree
1892         for (const std::pair<
1893                  std::string,
1894                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1895                  object : subtree)
1896         {
1897             // Check if object path is LED for one of the specified inventory
1898             // items
1899             const std::string& ledPath = object.first;
1900             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1901             {
1902                 // Add mapping from ledPath to connection
1903                 const std::string& connection = object.second.begin()->first;
1904                 (*ledConnections)[ledPath] = connection;
1905                 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> "
1906                                  << connection;
1907             }
1908         }
1909 
1910         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1911                             std::move(callback));
1912         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit";
1913     };
1914     // Make call to ObjectMapper to find all inventory items
1915     crow::connections::systemBus->async_method_call(
1916         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
1917         "/xyz/openbmc_project/object_mapper",
1918         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
1919     BMCWEB_LOG_DEBUG << "getInventoryLeds exit";
1920 }
1921 
1922 /**
1923  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
1924  *
1925  * Uses the specified connections (services) (currently assumes just one) to
1926  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
1927  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
1928  *
1929  * This data is later used to provide sensor property values in the JSON
1930  * response.
1931  *
1932  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
1933  * when data has been obtained.
1934  *
1935  * The callback must have the following signature:
1936  *   @code
1937  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
1938  *   @endcode
1939  *
1940  * @param sensorsAsyncResp Pointer to object holding response data.
1941  * @param inventoryItems D-Bus inventory items associated with sensors.
1942  * @param psAttributesConnections Connections that provide data for the Power
1943  *        Supply Attributes
1944  * @param callback Callback to invoke when data has been obtained.
1945  */
1946 template <typename Callback>
1947 void getPowerSupplyAttributesData(
1948     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1949     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1950     const std::map<std::string, std::string>& psAttributesConnections,
1951     Callback&& callback)
1952 {
1953     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter";
1954 
1955     if (psAttributesConnections.empty())
1956     {
1957         BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!";
1958         callback(inventoryItems);
1959         return;
1960     }
1961 
1962     // Assuming just one connection (service) for now
1963     auto it = psAttributesConnections.begin();
1964 
1965     const std::string& psAttributesPath = (*it).first;
1966     const std::string& psAttributesConnection = (*it).second;
1967 
1968     // Response handler for Get DeratingFactor property
1969     auto respHandler =
1970         [sensorsAsyncResp, inventoryItems,
1971          callback{std::forward<Callback>(callback)}](
1972             const boost::system::error_code ec, const uint32_t value) {
1973         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter";
1974         if (ec)
1975         {
1976             BMCWEB_LOG_ERROR
1977                 << "getPowerSupplyAttributesData respHandler DBus error " << ec;
1978             messages::internalError(sensorsAsyncResp->asyncResp->res);
1979             return;
1980         }
1981 
1982         BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value;
1983         // Store value in Power Supply Inventory Items
1984         for (InventoryItem& inventoryItem : *inventoryItems)
1985         {
1986             if (inventoryItem.isPowerSupply)
1987             {
1988                 inventoryItem.powerSupplyEfficiencyPercent =
1989                     static_cast<int>(value);
1990             }
1991         }
1992 
1993         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit";
1994         callback(inventoryItems);
1995     };
1996 
1997     // Get the DeratingFactor property for the PowerSupplyAttributes
1998     // Currently only property on the interface/only one we care about
1999     sdbusplus::asio::getProperty<uint32_t>(
2000         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
2001         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
2002         std::move(respHandler));
2003 
2004     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit";
2005 }
2006 
2007 /**
2008  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
2009  *
2010  * Gets the D-Bus connection (service) that provides Power Supply Attributes
2011  * data. Then gets the Power Supply Attributes data from the connection
2012  * (currently just assumes 1 connection) and stores the data in the inventory
2013  * item.
2014  *
2015  * This data is later used to provide sensor property values in the JSON
2016  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
2017  *
2018  * Finds the Power Supply Attributes data asynchronously. Invokes callback
2019  * when information has been obtained.
2020  *
2021  * The callback must have the following signature:
2022  *   @code
2023  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2024  *   @endcode
2025  *
2026  * @param sensorsAsyncResp Pointer to object holding response data.
2027  * @param inventoryItems D-Bus inventory items associated with sensors.
2028  * @param callback Callback to invoke when data has been obtained.
2029  */
2030 template <typename Callback>
2031 void getPowerSupplyAttributes(
2032     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2033     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
2034     Callback&& callback)
2035 {
2036     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter";
2037 
2038     // Only need the power supply attributes when the Power Schema
2039     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
2040     {
2041         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power";
2042         callback(inventoryItems);
2043         return;
2044     }
2045 
2046     const std::array<std::string, 1> interfaces = {
2047         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
2048 
2049     // Response handler for parsing output from GetSubTree
2050     auto respHandler =
2051         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2052          inventoryItems](
2053             const boost::system::error_code ec,
2054             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2055         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter";
2056         if (ec)
2057         {
2058             messages::internalError(sensorsAsyncResp->asyncResp->res);
2059             BMCWEB_LOG_ERROR
2060                 << "getPowerSupplyAttributes respHandler DBus error " << ec;
2061             return;
2062         }
2063         if (subtree.empty())
2064         {
2065             BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!";
2066             callback(inventoryItems);
2067             return;
2068         }
2069 
2070         // Currently we only support 1 power supply attribute, use this for
2071         // all the power supplies. Build map of object path to connection.
2072         // Assume just 1 connection and 1 path for now.
2073         std::map<std::string, std::string> psAttributesConnections;
2074 
2075         if (subtree[0].first.empty() || subtree[0].second.empty())
2076         {
2077             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
2078             callback(inventoryItems);
2079             return;
2080         }
2081 
2082         const std::string& psAttributesPath = subtree[0].first;
2083         const std::string& connection = subtree[0].second.begin()->first;
2084 
2085         if (connection.empty())
2086         {
2087             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
2088             callback(inventoryItems);
2089             return;
2090         }
2091 
2092         psAttributesConnections[psAttributesPath] = connection;
2093         BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> "
2094                          << connection;
2095 
2096         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
2097                                      psAttributesConnections,
2098                                      std::move(callback));
2099         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit";
2100     };
2101     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2102     crow::connections::systemBus->async_method_call(
2103         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
2104         "/xyz/openbmc_project/object_mapper",
2105         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
2106         "/xyz/openbmc_project", 0, interfaces);
2107     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit";
2108 }
2109 
2110 /**
2111  * @brief Gets inventory items associated with sensors.
2112  *
2113  * Finds the inventory items that are associated with the specified sensors.
2114  * Then gets D-Bus data for the inventory items, such as presence and VPD.
2115  *
2116  * This data is later used to provide sensor property values in the JSON
2117  * response.
2118  *
2119  * Finds the inventory items asynchronously.  Invokes callback when the
2120  * inventory items have been obtained.
2121  *
2122  * The callback must have the following signature:
2123  *   @code
2124  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2125  *   @endcode
2126  *
2127  * @param sensorsAsyncResp Pointer to object holding response data.
2128  * @param sensorNames All sensors within the current chassis.
2129  * implements ObjectManager.
2130  * @param callback Callback to invoke when inventory items have been obtained.
2131  */
2132 template <typename Callback>
2133 static void
2134     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2135                       const std::shared_ptr<std::set<std::string>> sensorNames,
2136                       Callback&& callback)
2137 {
2138     BMCWEB_LOG_DEBUG << "getInventoryItems enter";
2139     auto getInventoryItemAssociationsCb =
2140         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2141             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
2142         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter";
2143         auto getInventoryItemsConnectionsCb =
2144             [sensorsAsyncResp, inventoryItems,
2145              callback{std::forward<const Callback>(callback)}](
2146                 std::shared_ptr<std::set<std::string>> invConnections) {
2147             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter";
2148             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2149                                             callback{std::move(callback)}]() {
2150                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter";
2151 
2152                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2153                                            callback{std::move(callback)}]() {
2154                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter";
2155                     // Find Power Supply Attributes and get the data
2156                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
2157                                              std::move(callback));
2158                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit";
2159                 };
2160 
2161                 // Find led connections and get the data
2162                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
2163                                  std::move(getInventoryLedsCb));
2164                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit";
2165             };
2166 
2167             // Get inventory item data from connections
2168             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2169                                   invConnections,
2170                                   std::move(getInventoryItemsDataCb));
2171             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit";
2172         };
2173 
2174         // Get connections that provide inventory item data
2175         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
2176                                      std::move(getInventoryItemsConnectionsCb));
2177         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit";
2178     };
2179 
2180     // Get associations from sensors to inventory items
2181     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2182                                  std::move(getInventoryItemAssociationsCb));
2183     BMCWEB_LOG_DEBUG << "getInventoryItems exit";
2184 }
2185 
2186 /**
2187  * @brief Returns JSON PowerSupply object for the specified inventory item.
2188  *
2189  * Searches for a JSON PowerSupply object that matches the specified inventory
2190  * item.  If one is not found, a new PowerSupply object is added to the JSON
2191  * array.
2192  *
2193  * Multiple sensors are often associated with one power supply inventory item.
2194  * As a result, multiple sensor values are stored in one JSON PowerSupply
2195  * object.
2196  *
2197  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2198  * @param inventoryItem Inventory item for the power supply.
2199  * @param chassisId Chassis that contains the power supply.
2200  * @return JSON PowerSupply object for the specified inventory item.
2201  */
2202 inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2203                                       const InventoryItem& inventoryItem,
2204                                       const std::string& chassisId)
2205 {
2206     // Check if matching PowerSupply object already exists in JSON array
2207     for (nlohmann::json& powerSupply : powerSupplyArray)
2208     {
2209         if (powerSupply["MemberId"] == inventoryItem.name)
2210         {
2211             return powerSupply;
2212         }
2213     }
2214 
2215     // Add new PowerSupply object to JSON array
2216     powerSupplyArray.push_back({});
2217     nlohmann::json& powerSupply = powerSupplyArray.back();
2218     powerSupply["@odata.id"] =
2219         "/redfish/v1/Chassis/" + chassisId + "/Power#/PowerSupplies/";
2220     powerSupply["MemberId"] = inventoryItem.name;
2221     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2222     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2223     powerSupply["Model"] = inventoryItem.model;
2224     powerSupply["PartNumber"] = inventoryItem.partNumber;
2225     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2226     setLedState(powerSupply, &inventoryItem);
2227 
2228     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
2229     {
2230         powerSupply["EfficiencyPercent"] =
2231             inventoryItem.powerSupplyEfficiencyPercent;
2232     }
2233 
2234     powerSupply["Status"]["State"] = getState(&inventoryItem);
2235     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2236     powerSupply["Status"]["Health"] = health;
2237 
2238     return powerSupply;
2239 }
2240 
2241 /**
2242  * @brief Gets the values of the specified sensors.
2243  *
2244  * Stores the results as JSON in the SensorsAsyncResp.
2245  *
2246  * Gets the sensor values asynchronously.  Stores the results later when the
2247  * information has been obtained.
2248  *
2249  * The sensorNames set contains all requested sensors for the current chassis.
2250  *
2251  * To minimize the number of DBus calls, the DBus method
2252  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2253  * values of all sensors provided by a connection (service).
2254  *
2255  * The connections set contains all the connections that provide sensor values.
2256  *
2257  * The InventoryItem vector contains D-Bus inventory items associated with the
2258  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2259  *
2260  * @param SensorsAsyncResp Pointer to object holding response data.
2261  * @param sensorNames All requested sensors within the current chassis.
2262  * @param connections Connections that provide sensor values.
2263  * implements ObjectManager.
2264  * @param inventoryItems Inventory items associated with the sensors.
2265  */
2266 inline void getSensorData(
2267     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2268     const std::shared_ptr<std::set<std::string>>& sensorNames,
2269     const std::set<std::string>& connections,
2270     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2271 {
2272     BMCWEB_LOG_DEBUG << "getSensorData enter";
2273     // Get managed objects from all services exposing sensors
2274     for (const std::string& connection : connections)
2275     {
2276         // Response handler to process managed objects
2277         auto getManagedObjectsCb =
2278             [sensorsAsyncResp, sensorNames,
2279              inventoryItems](const boost::system::error_code ec,
2280                              const dbus::utility::ManagedObjectType& resp) {
2281             BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
2282             if (ec)
2283             {
2284                 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
2285                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2286                 return;
2287             }
2288             // Go through all objects and update response with sensor data
2289             for (const auto& objDictEntry : resp)
2290             {
2291                 const std::string& objPath =
2292                     static_cast<const std::string&>(objDictEntry.first);
2293                 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
2294                                  << objPath;
2295 
2296                 std::vector<std::string> split;
2297                 // Reserve space for
2298                 // /xyz/openbmc_project/sensors/<name>/<subname>
2299                 split.reserve(6);
2300                 boost::algorithm::split(split, objPath, boost::is_any_of("/"));
2301                 if (split.size() < 6)
2302                 {
2303                     BMCWEB_LOG_ERROR << "Got path that isn't long enough "
2304                                      << objPath;
2305                     continue;
2306                 }
2307                 // These indexes aren't intuitive, as boost::split puts an empty
2308                 // string at the beginning
2309                 const std::string& sensorType = split[4];
2310                 const std::string& sensorName = split[5];
2311                 BMCWEB_LOG_DEBUG << "sensorName " << sensorName
2312                                  << " sensorType " << sensorType;
2313                 if (sensorNames->find(objPath) == sensorNames->end())
2314                 {
2315                     BMCWEB_LOG_DEBUG << sensorName << " not in sensor list ";
2316                     continue;
2317                 }
2318 
2319                 // Find inventory item (if any) associated with sensor
2320                 InventoryItem* inventoryItem =
2321                     findInventoryItemForSensor(inventoryItems, objPath);
2322 
2323                 const std::string& sensorSchema =
2324                     sensorsAsyncResp->chassisSubNode;
2325 
2326                 nlohmann::json* sensorJson = nullptr;
2327 
2328                 if (sensorSchema == sensors::node::sensors &&
2329                     !sensorsAsyncResp->efficientExpand)
2330                 {
2331                     std::string sensorTypeEscaped(sensorType);
2332                     sensorTypeEscaped.erase(
2333                         std::remove(sensorTypeEscaped.begin(),
2334                                     sensorTypeEscaped.end(), '_'),
2335                         sensorTypeEscaped.end());
2336                     std::string sensorId(sensorTypeEscaped);
2337                     sensorId += "_";
2338                     sensorId += sensorName;
2339 
2340                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2341                         crow::utility::urlFromPieces(
2342                             "redfish", "v1", "Chassis",
2343                             sensorsAsyncResp->chassisId,
2344                             sensorsAsyncResp->chassisSubNode, sensorId);
2345                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
2346                 }
2347                 else
2348                 {
2349                     std::string fieldName;
2350                     if (sensorsAsyncResp->efficientExpand)
2351                     {
2352                         fieldName = "Members";
2353                     }
2354                     else if (sensorType == "temperature")
2355                     {
2356                         fieldName = "Temperatures";
2357                     }
2358                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2359                              sensorType == "fan_pwm")
2360                     {
2361                         fieldName = "Fans";
2362                     }
2363                     else if (sensorType == "voltage")
2364                     {
2365                         fieldName = "Voltages";
2366                     }
2367                     else if (sensorType == "power")
2368                     {
2369                         if (sensorName == "total_power")
2370                         {
2371                             fieldName = "PowerControl";
2372                         }
2373                         else if ((inventoryItem != nullptr) &&
2374                                  (inventoryItem->isPowerSupply))
2375                         {
2376                             fieldName = "PowerSupplies";
2377                         }
2378                         else
2379                         {
2380                             // Other power sensors are in SensorCollection
2381                             continue;
2382                         }
2383                     }
2384                     else
2385                     {
2386                         BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
2387                                          << sensorType;
2388                         continue;
2389                     }
2390 
2391                     nlohmann::json& tempArray =
2392                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2393                     if (fieldName == "PowerControl")
2394                     {
2395                         if (tempArray.empty())
2396                         {
2397                             // Put multiple "sensors" into a single
2398                             // PowerControl. Follows MemberId naming and
2399                             // naming in power.hpp.
2400                             nlohmann::json::object_t power;
2401                             power["@odata.id"] =
2402                                 "/redfish/v1/Chassis/" +
2403                                 sensorsAsyncResp->chassisId + "/" +
2404                                 sensorsAsyncResp->chassisSubNode + "#/" +
2405                                 fieldName + "/0";
2406                             tempArray.push_back(std::move(power));
2407                         }
2408                         sensorJson = &(tempArray.back());
2409                     }
2410                     else if (fieldName == "PowerSupplies")
2411                     {
2412                         if (inventoryItem != nullptr)
2413                         {
2414                             sensorJson =
2415                                 &(getPowerSupply(tempArray, *inventoryItem,
2416                                                  sensorsAsyncResp->chassisId));
2417                         }
2418                     }
2419                     else if (fieldName == "Members")
2420                     {
2421                         std::string sensorTypeEscaped(sensorType);
2422                         sensorTypeEscaped.erase(
2423                             std::remove(sensorTypeEscaped.begin(),
2424                                         sensorTypeEscaped.end(), '_'),
2425                             sensorTypeEscaped.end());
2426                         std::string sensorId(sensorTypeEscaped);
2427                         sensorId += "_";
2428                         sensorId += sensorName;
2429 
2430                         nlohmann::json::object_t member;
2431                         member["@odata.id"] = crow::utility::urlFromPieces(
2432                             "redfish", "v1", "Chassis",
2433                             sensorsAsyncResp->chassisId,
2434                             sensorsAsyncResp->chassisSubNode, sensorId);
2435                         tempArray.push_back(std::move(member));
2436                         sensorJson = &(tempArray.back());
2437                     }
2438                     else
2439                     {
2440                         nlohmann::json::object_t member;
2441                         member["@odata.id"] = "/redfish/v1/Chassis/" +
2442                                               sensorsAsyncResp->chassisId +
2443                                               "/" +
2444                                               sensorsAsyncResp->chassisSubNode +
2445                                               "#/" + fieldName + "/";
2446                         tempArray.push_back(std::move(member));
2447                         sensorJson = &(tempArray.back());
2448                     }
2449                 }
2450 
2451                 if (sensorJson != nullptr)
2452                 {
2453                     objectInterfacesToJson(sensorName, sensorType,
2454                                            sensorsAsyncResp->chassisSubNode,
2455                                            objDictEntry.second, *sensorJson,
2456                                            inventoryItem);
2457 
2458                     std::string path = "/xyz/openbmc_project/sensors/";
2459                     path += sensorType;
2460                     path += "/";
2461                     path += sensorName;
2462                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2463                 }
2464             }
2465             if (sensorsAsyncResp.use_count() == 1)
2466             {
2467                 sortJSONResponse(sensorsAsyncResp);
2468                 if (sensorsAsyncResp->chassisSubNode ==
2469                         sensors::node::sensors &&
2470                     sensorsAsyncResp->efficientExpand)
2471                 {
2472                     sensorsAsyncResp->asyncResp->res
2473                         .jsonValue["Members@odata.count"] =
2474                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2475                             .size();
2476                 }
2477                 else if (sensorsAsyncResp->chassisSubNode ==
2478                          sensors::node::thermal)
2479                 {
2480                     populateFanRedundancy(sensorsAsyncResp);
2481                 }
2482             }
2483             BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
2484         };
2485 
2486         crow::connections::systemBus->async_method_call(
2487             getManagedObjectsCb, connection, "/xyz/openbmc_project/sensors",
2488             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
2489     }
2490     BMCWEB_LOG_DEBUG << "getSensorData exit";
2491 }
2492 
2493 inline void
2494     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2495                       const std::shared_ptr<std::set<std::string>>& sensorNames)
2496 {
2497     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2498                                const std::set<std::string>& connections) {
2499         BMCWEB_LOG_DEBUG << "getConnectionCb enter";
2500         auto getInventoryItemsCb =
2501             [sensorsAsyncResp, sensorNames,
2502              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2503                               inventoryItems) {
2504             BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter";
2505             // Get sensor data and store results in JSON
2506             getSensorData(sensorsAsyncResp, sensorNames, connections,
2507                           inventoryItems);
2508             BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit";
2509         };
2510 
2511         // Get inventory items associated with sensors
2512         getInventoryItems(sensorsAsyncResp, sensorNames,
2513                           std::move(getInventoryItemsCb));
2514 
2515         BMCWEB_LOG_DEBUG << "getConnectionCb exit";
2516     };
2517 
2518     // Get set of connections that provide sensor values
2519     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
2520 }
2521 
2522 /**
2523  * @brief Entry point for retrieving sensors data related to requested
2524  *        chassis.
2525  * @param SensorsAsyncResp   Pointer to object holding response data
2526  */
2527 inline void
2528     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
2529 {
2530     BMCWEB_LOG_DEBUG << "getChassisData enter";
2531     auto getChassisCb =
2532         [sensorsAsyncResp](
2533             const std::shared_ptr<std::set<std::string>>& sensorNames) {
2534         BMCWEB_LOG_DEBUG << "getChassisCb enter";
2535         processSensorList(sensorsAsyncResp, sensorNames);
2536         BMCWEB_LOG_DEBUG << "getChassisCb exit";
2537     };
2538     // SensorCollection doesn't contain the Redundancy property
2539     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2540     {
2541         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
2542             nlohmann::json::array();
2543     }
2544     // Get set of sensors in chassis
2545     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
2546                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
2547                std::move(getChassisCb));
2548     BMCWEB_LOG_DEBUG << "getChassisData exit";
2549 }
2550 
2551 /**
2552  * @brief Find the requested sensorName in the list of all sensors supplied by
2553  * the chassis node
2554  *
2555  * @param sensorName   The sensor name supplied in the PATCH request
2556  * @param sensorsList  The list of sensors managed by the chassis node
2557  * @param sensorsModified  The list of sensors that were found as a result of
2558  *                         repeated calls to this function
2559  */
2560 inline bool
2561     findSensorNameUsingSensorPath(std::string_view sensorName,
2562                                   const std::set<std::string>& sensorsList,
2563                                   std::set<std::string>& sensorsModified)
2564 {
2565     for (const auto& chassisSensor : sensorsList)
2566     {
2567         sdbusplus::message::object_path path(chassisSensor);
2568         std::string thisSensorName = path.filename();
2569         if (thisSensorName.empty())
2570         {
2571             continue;
2572         }
2573         if (thisSensorName == sensorName)
2574         {
2575             sensorsModified.emplace(chassisSensor);
2576             return true;
2577         }
2578     }
2579     return false;
2580 }
2581 
2582 /**
2583  * @brief Entry point for overriding sensor values of given sensor
2584  *
2585  * @param sensorAsyncResp   response object
2586  * @param allCollections   Collections extract from sensors' request patch info
2587  * @param chassisSubNode   Chassis Node for which the query has to happen
2588  */
2589 inline void setSensorsOverride(
2590     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
2591     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2592         allCollections)
2593 {
2594     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
2595                     << sensorAsyncResp->chassisSubNode << "\n";
2596 
2597     const char* propertyValueName = nullptr;
2598     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2599     std::string memberId;
2600     double value = 0.0;
2601     for (auto& collectionItems : allCollections)
2602     {
2603         if (collectionItems.first == "Temperatures")
2604         {
2605             propertyValueName = "ReadingCelsius";
2606         }
2607         else if (collectionItems.first == "Fans")
2608         {
2609             propertyValueName = "Reading";
2610         }
2611         else
2612         {
2613             propertyValueName = "ReadingVolts";
2614         }
2615         for (auto& item : collectionItems.second)
2616         {
2617             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
2618                                      "MemberId", memberId, propertyValueName,
2619                                      value))
2620             {
2621                 return;
2622             }
2623             overrideMap.emplace(memberId,
2624                                 std::make_pair(value, collectionItems.first));
2625         }
2626     }
2627 
2628     auto getChassisSensorListCb =
2629         [sensorAsyncResp, overrideMap](
2630             const std::shared_ptr<std::set<std::string>>& sensorsList) {
2631         // Match sensor names in the PATCH request to those managed by the
2632         // chassis node
2633         const std::shared_ptr<std::set<std::string>> sensorNames =
2634             std::make_shared<std::set<std::string>>();
2635         for (const auto& item : overrideMap)
2636         {
2637             const auto& sensor = item.first;
2638             if (!findSensorNameUsingSensorPath(sensor, *sensorsList,
2639                                                *sensorNames))
2640             {
2641                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
2642                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2643                                            item.second.second, item.first);
2644                 return;
2645             }
2646         }
2647         // Get the connection to which the memberId belongs
2648         auto getObjectsWithConnectionCb =
2649             [sensorAsyncResp,
2650              overrideMap](const std::set<std::string>& /*connections*/,
2651                           const std::set<std::pair<std::string, std::string>>&
2652                               objectsWithConnection) {
2653             if (objectsWithConnection.size() != overrideMap.size())
2654             {
2655                 BMCWEB_LOG_INFO
2656                     << "Unable to find all objects with proper connection "
2657                     << objectsWithConnection.size() << " requested "
2658                     << overrideMap.size() << "\n";
2659                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2660                                            sensorAsyncResp->chassisSubNode ==
2661                                                    sensors::node::thermal
2662                                                ? "Temperatures"
2663                                                : "Voltages",
2664                                            "Count");
2665                 return;
2666             }
2667             for (const auto& item : objectsWithConnection)
2668             {
2669                 sdbusplus::message::object_path path(item.first);
2670                 std::string sensorName = path.filename();
2671                 if (sensorName.empty())
2672                 {
2673                     messages::internalError(sensorAsyncResp->asyncResp->res);
2674                     return;
2675                 }
2676 
2677                 const auto& iterator = overrideMap.find(sensorName);
2678                 if (iterator == overrideMap.end())
2679                 {
2680                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2681                                     << item.first << "\n";
2682                     messages::internalError(sensorAsyncResp->asyncResp->res);
2683                     return;
2684                 }
2685                 crow::connections::systemBus->async_method_call(
2686                     [sensorAsyncResp](const boost::system::error_code ec) {
2687                     if (ec)
2688                     {
2689                         if (ec.value() ==
2690                             boost::system::errc::permission_denied)
2691                         {
2692                             BMCWEB_LOG_WARNING
2693                                 << "Manufacturing mode is not Enabled...can't "
2694                                    "Override the sensor value. ";
2695 
2696                             messages::insufficientPrivilege(
2697                                 sensorAsyncResp->asyncResp->res);
2698                             return;
2699                         }
2700                         BMCWEB_LOG_DEBUG
2701                             << "setOverrideValueStatus DBUS error: " << ec;
2702                         messages::internalError(
2703                             sensorAsyncResp->asyncResp->res);
2704                     }
2705                     },
2706                     item.second, item.first, "org.freedesktop.DBus.Properties",
2707                     "Set", "xyz.openbmc_project.Sensor.Value", "Value",
2708                     dbus::utility::DbusVariantType(iterator->second.first));
2709             }
2710         };
2711         // Get object with connection for the given sensor name
2712         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2713                                  std::move(getObjectsWithConnectionCb));
2714     };
2715     // get full sensor list for the given chassisId and cross verify the sensor.
2716     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
2717                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
2718                std::move(getChassisSensorListCb));
2719 }
2720 
2721 /**
2722  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2723  * path of the sensor.
2724  *
2725  * Function builds valid Redfish response for sensor query of given chassis and
2726  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2727  * it to caller in a callback.
2728  *
2729  * @param chassis   Chassis for which retrieval should be performed
2730  * @param node  Node (group) of sensors. See sensors::node for supported values
2731  * @param mapComplete   Callback to be called with retrieval result
2732  */
2733 inline void retrieveUriToDbusMap(const std::string& chassis,
2734                                  const std::string& node,
2735                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2736 {
2737     decltype(sensors::paths)::const_iterator pathIt =
2738         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
2739                      [&node](auto&& val) { return val.first == node; });
2740     if (pathIt == sensors::paths.cend())
2741     {
2742         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2743         mapComplete(boost::beast::http::status::bad_request, {});
2744         return;
2745     }
2746 
2747     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2748     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2749                         const boost::beast::http::status status,
2750                         const std::map<std::string, std::string>& uriToDbus) {
2751         mapCompleteCb(status, uriToDbus);
2752     };
2753 
2754     auto resp = std::make_shared<SensorsAsyncResp>(
2755         asyncResp, chassis, pathIt->second, node, std::move(callback));
2756     getChassisData(resp);
2757 }
2758 
2759 namespace sensors
2760 {
2761 
2762 inline void getChassisCallback(
2763     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2764     std::string_view chassisId, std::string_view chassisSubNode,
2765     const std::shared_ptr<std::set<std::string>>& sensorNames)
2766 {
2767     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2768 
2769     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2770     for (const std::string& sensor : *sensorNames)
2771     {
2772         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2773 
2774         sdbusplus::message::object_path path(sensor);
2775         std::string sensorName = path.filename();
2776         if (sensorName.empty())
2777         {
2778             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2779             messages::internalError(asyncResp->res);
2780             return;
2781         }
2782         std::string type = path.parent_path().filename();
2783         // fan_tach has an underscore in it, so remove it to "normalize" the
2784         // type in the URI
2785         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2786 
2787         nlohmann::json::object_t member;
2788         std::string id = type;
2789         id += "_";
2790         id += sensorName;
2791         member["@odata.id"] = crow::utility::urlFromPieces(
2792             "redfish", "v1", "Chassis", chassisId, chassisSubNode, id);
2793 
2794         entriesArray.push_back(std::move(member));
2795     }
2796 
2797     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2798     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2799 }
2800 
2801 inline void
2802     handleSensorCollectionGet(App& app, const crow::Request& req,
2803                               const std::shared_ptr<bmcweb::AsyncResp>& aResp,
2804                               const std::string& chassisId)
2805 {
2806     query_param::QueryCapabilities capabilities = {
2807         .canDelegateExpandLevel = 1,
2808     };
2809     query_param::Query delegatedQuery;
2810     if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp,
2811                                                   delegatedQuery, capabilities))
2812     {
2813         return;
2814     }
2815 
2816     if (delegatedQuery.expandType != query_param::ExpandType::None)
2817     {
2818         // we perform efficient expand.
2819         auto asyncResp = std::make_shared<SensorsAsyncResp>(
2820             aResp, chassisId, sensors::dbus::sensorPaths,
2821             sensors::node::sensors,
2822             /*efficientExpand=*/true);
2823         getChassisData(asyncResp);
2824 
2825         BMCWEB_LOG_DEBUG
2826             << "SensorCollection doGet exit via efficient expand handler";
2827         return;
2828     }
2829 
2830     // We get all sensors as hyperlinkes in the chassis (this
2831     // implies we reply on the default query parameters handler)
2832     getChassis(aResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2833                std::bind_front(sensors::getChassisCallback, aResp, chassisId,
2834                                sensors::node::sensors));
2835 }
2836 
2837 inline void
2838     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2839                       const std::string& sensorPath,
2840                       const ::dbus::utility::MapperGetObject& mapperResponse)
2841 {
2842     if (mapperResponse.size() != 1)
2843     {
2844         messages::internalError(asyncResp->res);
2845         return;
2846     }
2847     const auto& valueIface = *mapperResponse.begin();
2848     const std::string& connectionName = valueIface.first;
2849     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2850     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2851 
2852     sdbusplus::asio::getAllProperties(
2853         *crow::connections::systemBus, connectionName, sensorPath, "",
2854         [asyncResp,
2855          sensorPath](const boost::system::error_code ec,
2856                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2857         if (ec)
2858         {
2859             messages::internalError(asyncResp->res);
2860             return;
2861         }
2862         sdbusplus::message::object_path path(sensorPath);
2863         std::string name = path.filename();
2864         path = path.parent_path();
2865         std::string type = path.filename();
2866         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2867                                asyncResp->res.jsonValue, nullptr);
2868         });
2869 }
2870 
2871 inline void handleSensorGet(App& app, const crow::Request& req,
2872                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2873                             const std::string& chassisId,
2874                             const std::string& sensorId)
2875 {
2876     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2877     {
2878         return;
2879     }
2880     size_t index = sensorId.find('_');
2881     if (index == std::string::npos)
2882     {
2883         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2884         return;
2885     }
2886     asyncResp->res.jsonValue["@odata.id"] = crow::utility::urlFromPieces(
2887         "redfish", "v1", "Chassis", chassisId, "Sensors", sensorId);
2888     std::string sensorType = sensorId.substr(0, index);
2889     std::string sensorName = sensorId.substr(index + 1);
2890     // fan_pwm and fan_tach need special handling
2891     if (sensorType == "fantach" || sensorType == "fanpwm")
2892     {
2893         sensorType.insert(3, 1, '_');
2894     }
2895 
2896     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
2897 
2898     const std::array<const char*, 1> interfaces = {
2899         "xyz.openbmc_project.Sensor.Value"};
2900     std::string sensorPath =
2901         "/xyz/openbmc_project/sensors/" + sensorType + '/' + sensorName;
2902     // Get a list of all of the sensors that implement Sensor.Value
2903     // and get the path and service name associated with the sensor
2904     crow::connections::systemBus->async_method_call(
2905         [asyncResp, sensorPath,
2906          sensorName](const boost::system::error_code ec,
2907                      const ::dbus::utility::MapperGetObject& subtree) {
2908         BMCWEB_LOG_DEBUG << "respHandler1 enter";
2909         if (ec)
2910         {
2911             messages::internalError(asyncResp->res);
2912             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
2913                              << "Dbus error " << ec;
2914             return;
2915         }
2916         getSensorFromDbus(asyncResp, sensorPath, subtree);
2917         BMCWEB_LOG_DEBUG << "respHandler1 exit";
2918         },
2919         "xyz.openbmc_project.ObjectMapper",
2920         "/xyz/openbmc_project/object_mapper",
2921         "xyz.openbmc_project.ObjectMapper", "GetObject", sensorPath,
2922         interfaces);
2923 }
2924 
2925 } // namespace sensors
2926 
2927 inline void requestRoutesSensorCollection(App& app)
2928 {
2929     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2930         .privileges(redfish::privileges::getSensorCollection)
2931         .methods(boost::beast::http::verb::get)(
2932             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
2933 }
2934 
2935 inline void requestRoutesSensor(App& app)
2936 {
2937     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2938         .privileges(redfish::privileges::getSensor)
2939         .methods(boost::beast::http::verb::get)(
2940             std::bind_front(sensors::handleSensorGet, std::ref(app)));
2941 }
2942 
2943 } // namespace redfish
2944