xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision c71d61258bd3cd8573166011b450a1eecce2c572)
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/replace.hpp>
25 #include <boost/algorithm/string/split.hpp>
26 #include <boost/range/algorithm/replace_copy_if.hpp>
27 #include <dbus_singleton.hpp>
28 #include <dbus_utility.hpp>
29 #include <query.hpp>
30 #include <registries/privilege_registry.hpp>
31 #include <sdbusplus/asio/property.hpp>
32 #include <sdbusplus/unpack_properties.hpp>
33 #include <utils/dbus_utils.hpp>
34 #include <utils/json_utils.hpp>
35 #include <utils/query_param.hpp>
36 
37 #include <cmath>
38 #include <iterator>
39 #include <map>
40 #include <set>
41 #include <utility>
42 #include <variant>
43 
44 namespace redfish
45 {
46 
47 namespace sensors
48 {
49 namespace node
50 {
51 static constexpr std::string_view power = "Power";
52 static constexpr std::string_view sensors = "Sensors";
53 static constexpr std::string_view thermal = "Thermal";
54 } // namespace node
55 
56 // clang-format off
57 namespace dbus
58 {
59 static auto powerPaths = std::to_array<std::string_view>({
60     "/xyz/openbmc_project/sensors/voltage",
61     "/xyz/openbmc_project/sensors/power"
62 });
63 
64 static auto sensorPaths = std::to_array<std::string_view>({
65     "/xyz/openbmc_project/sensors/power",
66     "/xyz/openbmc_project/sensors/current",
67     "/xyz/openbmc_project/sensors/airflow",
68     "/xyz/openbmc_project/sensors/humidity",
69 #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
70     "/xyz/openbmc_project/sensors/voltage",
71     "/xyz/openbmc_project/sensors/fan_tach",
72     "/xyz/openbmc_project/sensors/temperature",
73     "/xyz/openbmc_project/sensors/fan_pwm",
74     "/xyz/openbmc_project/sensors/altitude",
75     "/xyz/openbmc_project/sensors/energy",
76 #endif
77     "/xyz/openbmc_project/sensors/utilization"
78 });
79 
80 static auto thermalPaths = std::to_array<std::string_view>({
81     "/xyz/openbmc_project/sensors/fan_tach",
82     "/xyz/openbmc_project/sensors/temperature",
83     "/xyz/openbmc_project/sensors/fan_pwm"
84 });
85 
86 } // namespace dbus
87 // clang-format on
88 
89 using sensorPair = std::pair<std::string_view, std::span<std::string_view>>;
90 static constexpr std::array<sensorPair, 3> paths = {
91     {{node::power, std::span<std::string_view>(dbus::powerPaths)},
92      {node::sensors, std::span<std::string_view>(dbus::sensorPaths)},
93      {node::thermal, std::span<std::string_view>(dbus::thermalPaths)}}};
94 
95 inline sensor::ReadingType toReadingType(std::string_view sensorType)
96 {
97     if (sensorType == "voltage")
98     {
99         return sensor::ReadingType::Voltage;
100     }
101     if (sensorType == "power")
102     {
103         return sensor::ReadingType::Power;
104     }
105     if (sensorType == "current")
106     {
107         return sensor::ReadingType::Current;
108     }
109     if (sensorType == "fan_tach")
110     {
111         return sensor::ReadingType::Rotational;
112     }
113     if (sensorType == "temperature")
114     {
115         return sensor::ReadingType::Temperature;
116     }
117     if (sensorType == "fan_pwm" || sensorType == "utilization")
118     {
119         return sensor::ReadingType::Percent;
120     }
121     if (sensorType == "humidity")
122     {
123         return sensor::ReadingType::Humidity;
124     }
125     if (sensorType == "altitude")
126     {
127         return sensor::ReadingType::Altitude;
128     }
129     if (sensorType == "airflow")
130     {
131         return sensor::ReadingType::AirFlow;
132     }
133     if (sensorType == "energy")
134     {
135         return sensor::ReadingType::EnergyJoules;
136     }
137     return sensor::ReadingType::Invalid;
138 }
139 
140 inline std::string_view toReadingUnits(std::string_view sensorType)
141 {
142     if (sensorType == "voltage")
143     {
144         return "V";
145     }
146     if (sensorType == "power")
147     {
148         return "W";
149     }
150     if (sensorType == "current")
151     {
152         return "A";
153     }
154     if (sensorType == "fan_tach")
155     {
156         return "RPM";
157     }
158     if (sensorType == "temperature")
159     {
160         return "Cel";
161     }
162     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
163         sensorType == "humidity")
164     {
165         return "%";
166     }
167     if (sensorType == "altitude")
168     {
169         return "m";
170     }
171     if (sensorType == "airflow")
172     {
173         return "cft_i/min";
174     }
175     if (sensorType == "energy")
176     {
177         return "J";
178     }
179     return "";
180 }
181 } // namespace sensors
182 
183 /**
184  * SensorsAsyncResp
185  * Gathers data needed for response processing after async calls are done
186  */
187 class SensorsAsyncResp
188 {
189   public:
190     using DataCompleteCb = std::function<void(
191         const boost::beast::http::status status,
192         const std::map<std::string, std::string>& uriToDbus)>;
193 
194     struct SensorData
195     {
196         const std::string name;
197         std::string uri;
198         const std::string dbusPath;
199     };
200 
201     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
202                      const std::string& chassisIdIn,
203                      std::span<std::string_view> typesIn,
204                      std::string_view subNode) :
205         asyncResp(asyncRespIn),
206         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
207         efficientExpand(false)
208     {}
209 
210     // Store extra data about sensor mapping and return it in callback
211     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
212                      const std::string& chassisIdIn,
213                      std::span<std::string_view> typesIn,
214                      std::string_view subNode,
215                      DataCompleteCb&& creationComplete) :
216         asyncResp(asyncRespIn),
217         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
218         efficientExpand(false), metadata{std::vector<SensorData>()},
219         dataComplete{std::move(creationComplete)}
220     {}
221 
222     // sensor collections expand
223     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
224                      const std::string& chassisIdIn,
225                      const std::span<std::string_view> typesIn,
226                      const std::string_view& subNode, bool efficientExpandIn) :
227         asyncResp(asyncRespIn),
228         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
229         efficientExpand(efficientExpandIn)
230     {}
231 
232     ~SensorsAsyncResp()
233     {
234         if (asyncResp->res.result() ==
235             boost::beast::http::status::internal_server_error)
236         {
237             // Reset the json object to clear out any data that made it in
238             // before the error happened todo(ed) handle error condition with
239             // proper code
240             asyncResp->res.jsonValue = nlohmann::json::object();
241         }
242 
243         if (dataComplete && metadata)
244         {
245             std::map<std::string, std::string> map;
246             if (asyncResp->res.result() == boost::beast::http::status::ok)
247             {
248                 for (auto& sensor : *metadata)
249                 {
250                     map.emplace(sensor.uri, sensor.dbusPath);
251                 }
252             }
253             dataComplete(asyncResp->res.result(), map);
254         }
255     }
256 
257     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
258     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
259     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
260     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
261 
262     void addMetadata(const nlohmann::json& sensorObject,
263                      const std::string& dbusPath)
264     {
265         if (metadata)
266         {
267             metadata->emplace_back(SensorData{
268                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
269         }
270     }
271 
272     void updateUri(const std::string& name, const std::string& uri)
273     {
274         if (metadata)
275         {
276             for (auto& sensor : *metadata)
277             {
278                 if (sensor.name == name)
279                 {
280                     sensor.uri = uri;
281                 }
282             }
283         }
284     }
285 
286     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
287     const std::string chassisId;
288     const std::span<std::string_view> types;
289     const std::string chassisSubNode;
290     const bool efficientExpand;
291 
292   private:
293     std::optional<std::vector<SensorData>> metadata;
294     DataCompleteCb dataComplete;
295 };
296 
297 /**
298  * Possible states for physical inventory leds
299  */
300 enum class LedState
301 {
302     OFF,
303     ON,
304     BLINK,
305     UNKNOWN
306 };
307 
308 /**
309  * D-Bus inventory item associated with one or more sensors.
310  */
311 class InventoryItem
312 {
313   public:
314     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
315     {
316         // Set inventory item name to last node of object path
317         sdbusplus::message::object_path path(objectPath);
318         name = path.filename();
319         if (name.empty())
320         {
321             BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath;
322         }
323     }
324 
325     std::string objectPath;
326     std::string name;
327     bool isPresent = true;
328     bool isFunctional = true;
329     bool isPowerSupply = false;
330     int powerSupplyEfficiencyPercent = -1;
331     std::string manufacturer;
332     std::string model;
333     std::string partNumber;
334     std::string serialNumber;
335     std::set<std::string> sensors;
336     std::string ledObjectPath;
337     LedState ledState = LedState::UNKNOWN;
338 };
339 
340 /**
341  * @brief Get objects with connection necessary for sensors
342  * @param SensorsAsyncResp Pointer to object holding response data
343  * @param sensorNames Sensors retrieved from chassis
344  * @param callback Callback for processing gathered connections
345  */
346 template <typename Callback>
347 void getObjectsWithConnection(
348     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
349     const std::shared_ptr<std::set<std::string>>& sensorNames,
350     Callback&& callback)
351 {
352     BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter";
353     const std::string path = "/xyz/openbmc_project/sensors";
354     const std::array<std::string, 1> interfaces = {
355         "xyz.openbmc_project.Sensor.Value"};
356 
357     // Response handler for parsing objects subtree
358     auto respHandler =
359         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
360          sensorNames](const boost::system::error_code ec,
361                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
362         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter";
363         if (ec)
364         {
365             messages::internalError(sensorsAsyncResp->asyncResp->res);
366             BMCWEB_LOG_ERROR
367                 << "getObjectsWithConnection resp_handler: Dbus error " << ec;
368             return;
369         }
370 
371         BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
372 
373         // Make unique list of connections only for requested sensor types and
374         // found in the chassis
375         std::set<std::string> connections;
376         std::set<std::pair<std::string, std::string>> objectsWithConnection;
377 
378         BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size();
379         for (const std::string& tsensor : *sensorNames)
380         {
381             BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
382         }
383 
384         for (const std::pair<
385                  std::string,
386                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
387                  object : subtree)
388         {
389             if (sensorNames->find(object.first) != sensorNames->end())
390             {
391                 for (const std::pair<std::string, std::vector<std::string>>&
392                          objData : object.second)
393                 {
394                     BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
395                     connections.insert(objData.first);
396                     objectsWithConnection.insert(
397                         std::make_pair(object.first, objData.first));
398                 }
399             }
400         }
401         BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
402         callback(std::move(connections), std::move(objectsWithConnection));
403         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit";
404     };
405     // Make call to ObjectMapper to find all sensors objects
406     crow::connections::systemBus->async_method_call(
407         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
408         "/xyz/openbmc_project/object_mapper",
409         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 2, interfaces);
410     BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit";
411 }
412 
413 /**
414  * @brief Create connections necessary for sensors
415  * @param SensorsAsyncResp Pointer to object holding response data
416  * @param sensorNames Sensors retrieved from chassis
417  * @param callback Callback for processing gathered connections
418  */
419 template <typename Callback>
420 void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
421                     const std::shared_ptr<std::set<std::string>> sensorNames,
422                     Callback&& callback)
423 {
424     auto objectsWithConnectionCb =
425         [callback](const std::set<std::string>& connections,
426                    const std::set<std::pair<std::string, std::string>>&
427                    /*objectsWithConnection*/) { callback(connections); };
428     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
429                              std::move(objectsWithConnectionCb));
430 }
431 
432 /**
433  * @brief Shrinks the list of sensors for processing
434  * @param SensorsAysncResp  The class holding the Redfish response
435  * @param allSensors  A list of all the sensors associated to the
436  * chassis element (i.e. baseboard, front panel, etc...)
437  * @param activeSensors A list that is a reduction of the incoming
438  * allSensors list.  Eliminate Thermal sensors when a Power request is
439  * made, and eliminate Power sensors when a Thermal request is made.
440  */
441 inline void reduceSensorList(
442     crow::Response& res, std::string_view chassisSubNode,
443     std::span<std::string_view> sensorTypes,
444     const std::vector<std::string>* allSensors,
445     const std::shared_ptr<std::set<std::string>>& activeSensors)
446 {
447     if ((allSensors == nullptr) || (activeSensors == nullptr))
448     {
449         messages::resourceNotFound(res, chassisSubNode,
450                                    chassisSubNode == sensors::node::thermal
451                                        ? "Temperatures"
452                                        : "Voltages");
453 
454         return;
455     }
456     if (allSensors->empty())
457     {
458         // Nothing to do, the activeSensors object is also empty
459         return;
460     }
461 
462     for (std::string_view type : sensorTypes)
463     {
464         for (const std::string& sensor : *allSensors)
465         {
466             if (sensor.starts_with(type))
467             {
468                 activeSensors->emplace(sensor);
469             }
470         }
471     }
472 }
473 
474 /*
475  *Populates the top level collection for a given subnode.  Populates
476  *SensorCollection, Power, or Thermal schemas.
477  *
478  * */
479 inline void populateChassisNode(nlohmann::json& jsonValue,
480                                 std::string_view chassisSubNode)
481 {
482     if (chassisSubNode == sensors::node::power)
483     {
484         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
485     }
486     else if (chassisSubNode == sensors::node::thermal)
487     {
488         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
489         jsonValue["Fans"] = nlohmann::json::array();
490         jsonValue["Temperatures"] = nlohmann::json::array();
491     }
492     else if (chassisSubNode == sensors::node::sensors)
493     {
494         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
495         jsonValue["Description"] = "Collection of Sensors for this Chassis";
496         jsonValue["Members"] = nlohmann::json::array();
497         jsonValue["Members@odata.count"] = 0;
498     }
499 
500     if (chassisSubNode != sensors::node::sensors)
501     {
502         jsonValue["Id"] = chassisSubNode;
503     }
504     jsonValue["Name"] = chassisSubNode;
505 }
506 
507 /**
508  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
509  * @param SensorsAsyncResp   Pointer to object holding response data
510  * @param callback  Callback for next step in gathered sensor processing
511  */
512 template <typename Callback>
513 void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
514                 std::string_view chassisId, std::string_view chassisSubNode,
515                 std::span<std::string_view> sensorTypes, Callback&& callback)
516 {
517     BMCWEB_LOG_DEBUG << "getChassis enter";
518     const std::array<const char*, 2> interfaces = {
519         "xyz.openbmc_project.Inventory.Item.Board",
520         "xyz.openbmc_project.Inventory.Item.Chassis"};
521     auto respHandler =
522         [callback{std::forward<Callback>(callback)}, asyncResp,
523          chassisIdStr{std::string(chassisId)},
524          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
525             const boost::system::error_code ec,
526             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
527         BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
528         if (ec)
529         {
530             BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
531             messages::internalError(asyncResp->res);
532             return;
533         }
534         const std::string* chassisPath = nullptr;
535         for (const std::string& chassis : chassisPaths)
536         {
537             sdbusplus::message::object_path path(chassis);
538             std::string 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(sensorType);
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 inline std::pair<std::string, std::string>
2583     splitSensorNameAndType(std::string_view sensorId)
2584 {
2585     size_t index = sensorId.find('_');
2586     if (index == std::string::npos)
2587     {
2588         return std::make_pair<std::string, std::string>("", "");
2589     }
2590     std::string sensorType{sensorId.substr(0, index)};
2591     std::string sensorName{sensorId.substr(index + 1)};
2592     // fan_pwm and fan_tach need special handling
2593     if (sensorType == "fantach" || sensorType == "fanpwm")
2594     {
2595         sensorType.insert(3, 1, '_');
2596     }
2597     return std::make_pair(sensorType, sensorName);
2598 }
2599 
2600 /**
2601  * @brief Entry point for overriding sensor values of given sensor
2602  *
2603  * @param sensorAsyncResp   response object
2604  * @param allCollections   Collections extract from sensors' request patch info
2605  * @param chassisSubNode   Chassis Node for which the query has to happen
2606  */
2607 inline void setSensorsOverride(
2608     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
2609     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2610         allCollections)
2611 {
2612     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
2613                     << sensorAsyncResp->chassisSubNode << "\n";
2614 
2615     const char* propertyValueName = nullptr;
2616     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2617     std::string memberId;
2618     double value = 0.0;
2619     for (auto& collectionItems : allCollections)
2620     {
2621         if (collectionItems.first == "Temperatures")
2622         {
2623             propertyValueName = "ReadingCelsius";
2624         }
2625         else if (collectionItems.first == "Fans")
2626         {
2627             propertyValueName = "Reading";
2628         }
2629         else
2630         {
2631             propertyValueName = "ReadingVolts";
2632         }
2633         for (auto& item : collectionItems.second)
2634         {
2635             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
2636                                      "MemberId", memberId, propertyValueName,
2637                                      value))
2638             {
2639                 return;
2640             }
2641             overrideMap.emplace(memberId,
2642                                 std::make_pair(value, collectionItems.first));
2643         }
2644     }
2645 
2646     auto getChassisSensorListCb =
2647         [sensorAsyncResp, overrideMap](
2648             const std::shared_ptr<std::set<std::string>>& sensorsList) {
2649         // Match sensor names in the PATCH request to those managed by the
2650         // chassis node
2651         const std::shared_ptr<std::set<std::string>> sensorNames =
2652             std::make_shared<std::set<std::string>>();
2653         for (const auto& item : overrideMap)
2654         {
2655             const auto& sensor = item.first;
2656             std::pair<std::string, std::string> sensorNameType =
2657                 splitSensorNameAndType(sensor);
2658             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2659                                                *sensorsList, *sensorNames))
2660             {
2661                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
2662                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2663                                            item.second.second, item.first);
2664                 return;
2665             }
2666         }
2667         // Get the connection to which the memberId belongs
2668         auto getObjectsWithConnectionCb =
2669             [sensorAsyncResp,
2670              overrideMap](const std::set<std::string>& /*connections*/,
2671                           const std::set<std::pair<std::string, std::string>>&
2672                               objectsWithConnection) {
2673             if (objectsWithConnection.size() != overrideMap.size())
2674             {
2675                 BMCWEB_LOG_INFO
2676                     << "Unable to find all objects with proper connection "
2677                     << objectsWithConnection.size() << " requested "
2678                     << overrideMap.size() << "\n";
2679                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2680                                            sensorAsyncResp->chassisSubNode ==
2681                                                    sensors::node::thermal
2682                                                ? "Temperatures"
2683                                                : "Voltages",
2684                                            "Count");
2685                 return;
2686             }
2687             for (const auto& item : objectsWithConnection)
2688             {
2689                 sdbusplus::message::object_path path(item.first);
2690                 std::string sensorName = path.filename();
2691                 if (sensorName.empty())
2692                 {
2693                     messages::internalError(sensorAsyncResp->asyncResp->res);
2694                     return;
2695                 }
2696 
2697                 const auto& iterator = overrideMap.find(sensorName);
2698                 if (iterator == overrideMap.end())
2699                 {
2700                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2701                                     << item.first << "\n";
2702                     messages::internalError(sensorAsyncResp->asyncResp->res);
2703                     return;
2704                 }
2705                 crow::connections::systemBus->async_method_call(
2706                     [sensorAsyncResp](const boost::system::error_code ec) {
2707                     if (ec)
2708                     {
2709                         if (ec.value() ==
2710                             boost::system::errc::permission_denied)
2711                         {
2712                             BMCWEB_LOG_WARNING
2713                                 << "Manufacturing mode is not Enabled...can't "
2714                                    "Override the sensor value. ";
2715 
2716                             messages::insufficientPrivilege(
2717                                 sensorAsyncResp->asyncResp->res);
2718                             return;
2719                         }
2720                         BMCWEB_LOG_DEBUG
2721                             << "setOverrideValueStatus DBUS error: " << ec;
2722                         messages::internalError(
2723                             sensorAsyncResp->asyncResp->res);
2724                     }
2725                     },
2726                     item.second, item.first, "org.freedesktop.DBus.Properties",
2727                     "Set", "xyz.openbmc_project.Sensor.Value", "Value",
2728                     dbus::utility::DbusVariantType(iterator->second.first));
2729             }
2730         };
2731         // Get object with connection for the given sensor name
2732         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2733                                  std::move(getObjectsWithConnectionCb));
2734     };
2735     // get full sensor list for the given chassisId and cross verify the sensor.
2736     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
2737                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
2738                std::move(getChassisSensorListCb));
2739 }
2740 
2741 /**
2742  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2743  * path of the sensor.
2744  *
2745  * Function builds valid Redfish response for sensor query of given chassis and
2746  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2747  * it to caller in a callback.
2748  *
2749  * @param chassis   Chassis for which retrieval should be performed
2750  * @param node  Node (group) of sensors. See sensors::node for supported values
2751  * @param mapComplete   Callback to be called with retrieval result
2752  */
2753 inline void retrieveUriToDbusMap(const std::string& chassis,
2754                                  const std::string& node,
2755                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2756 {
2757     decltype(sensors::paths)::const_iterator pathIt =
2758         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
2759                      [&node](auto&& val) { return val.first == node; });
2760     if (pathIt == sensors::paths.cend())
2761     {
2762         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2763         mapComplete(boost::beast::http::status::bad_request, {});
2764         return;
2765     }
2766 
2767     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2768     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2769                         const boost::beast::http::status status,
2770                         const std::map<std::string, std::string>& uriToDbus) {
2771         mapCompleteCb(status, uriToDbus);
2772     };
2773 
2774     auto resp = std::make_shared<SensorsAsyncResp>(
2775         asyncResp, chassis, pathIt->second, node, std::move(callback));
2776     getChassisData(resp);
2777 }
2778 
2779 namespace sensors
2780 {
2781 
2782 inline void getChassisCallback(
2783     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2784     std::string_view chassisId, std::string_view chassisSubNode,
2785     const std::shared_ptr<std::set<std::string>>& sensorNames)
2786 {
2787     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2788 
2789     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2790     for (const std::string& sensor : *sensorNames)
2791     {
2792         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2793 
2794         sdbusplus::message::object_path path(sensor);
2795         std::string sensorName = path.filename();
2796         if (sensorName.empty())
2797         {
2798             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2799             messages::internalError(asyncResp->res);
2800             return;
2801         }
2802         std::string type = path.parent_path().filename();
2803         // fan_tach has an underscore in it, so remove it to "normalize" the
2804         // type in the URI
2805         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2806 
2807         nlohmann::json::object_t member;
2808         std::string id = type;
2809         id += "_";
2810         id += sensorName;
2811         member["@odata.id"] = crow::utility::urlFromPieces(
2812             "redfish", "v1", "Chassis", chassisId, chassisSubNode, id);
2813 
2814         entriesArray.push_back(std::move(member));
2815     }
2816 
2817     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2818     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2819 }
2820 
2821 inline void
2822     handleSensorCollectionGet(App& app, const crow::Request& req,
2823                               const std::shared_ptr<bmcweb::AsyncResp>& aResp,
2824                               const std::string& chassisId)
2825 {
2826     query_param::QueryCapabilities capabilities = {
2827         .canDelegateExpandLevel = 1,
2828     };
2829     query_param::Query delegatedQuery;
2830     if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp,
2831                                                   delegatedQuery, capabilities))
2832     {
2833         return;
2834     }
2835 
2836     if (delegatedQuery.expandType != query_param::ExpandType::None)
2837     {
2838         // we perform efficient expand.
2839         auto asyncResp = std::make_shared<SensorsAsyncResp>(
2840             aResp, chassisId, sensors::dbus::sensorPaths,
2841             sensors::node::sensors,
2842             /*efficientExpand=*/true);
2843         getChassisData(asyncResp);
2844 
2845         BMCWEB_LOG_DEBUG
2846             << "SensorCollection doGet exit via efficient expand handler";
2847         return;
2848     }
2849 
2850     // We get all sensors as hyperlinkes in the chassis (this
2851     // implies we reply on the default query parameters handler)
2852     getChassis(aResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2853                std::bind_front(sensors::getChassisCallback, aResp, chassisId,
2854                                sensors::node::sensors));
2855 }
2856 
2857 inline void
2858     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2859                       const std::string& sensorPath,
2860                       const ::dbus::utility::MapperGetObject& mapperResponse)
2861 {
2862     if (mapperResponse.size() != 1)
2863     {
2864         messages::internalError(asyncResp->res);
2865         return;
2866     }
2867     const auto& valueIface = *mapperResponse.begin();
2868     const std::string& connectionName = valueIface.first;
2869     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2870     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2871 
2872     sdbusplus::asio::getAllProperties(
2873         *crow::connections::systemBus, connectionName, sensorPath, "",
2874         [asyncResp,
2875          sensorPath](const boost::system::error_code ec,
2876                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2877         if (ec)
2878         {
2879             messages::internalError(asyncResp->res);
2880             return;
2881         }
2882         sdbusplus::message::object_path path(sensorPath);
2883         std::string name = path.filename();
2884         path = path.parent_path();
2885         std::string type = path.filename();
2886         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2887                                asyncResp->res.jsonValue, nullptr);
2888         });
2889 }
2890 
2891 inline void handleSensorGet(App& app, const crow::Request& req,
2892                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2893                             const std::string& chassisId,
2894                             const std::string& sensorId)
2895 {
2896     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2897     {
2898         return;
2899     }
2900     std::pair<std::string, std::string> nameType =
2901         splitSensorNameAndType(sensorId);
2902     if (nameType.first.empty() || nameType.second.empty())
2903     {
2904         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2905         return;
2906     }
2907 
2908     asyncResp->res.jsonValue["@odata.id"] = crow::utility::urlFromPieces(
2909         "redfish", "v1", "Chassis", chassisId, "Sensors", sensorId);
2910 
2911     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
2912 
2913     const std::array<const char*, 1> interfaces = {
2914         "xyz.openbmc_project.Sensor.Value"};
2915     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2916                              '/' + nameType.second;
2917     // Get a list of all of the sensors that implement Sensor.Value
2918     // and get the path and service name associated with the sensor
2919     crow::connections::systemBus->async_method_call(
2920         [asyncResp,
2921          sensorPath](const boost::system::error_code ec,
2922                      const ::dbus::utility::MapperGetObject& subtree) {
2923         BMCWEB_LOG_DEBUG << "respHandler1 enter";
2924         if (ec)
2925         {
2926             messages::internalError(asyncResp->res);
2927             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
2928                              << "Dbus error " << ec;
2929             return;
2930         }
2931         getSensorFromDbus(asyncResp, sensorPath, subtree);
2932         BMCWEB_LOG_DEBUG << "respHandler1 exit";
2933         },
2934         "xyz.openbmc_project.ObjectMapper",
2935         "/xyz/openbmc_project/object_mapper",
2936         "xyz.openbmc_project.ObjectMapper", "GetObject", sensorPath,
2937         interfaces);
2938 }
2939 
2940 } // namespace sensors
2941 
2942 inline void requestRoutesSensorCollection(App& app)
2943 {
2944     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2945         .privileges(redfish::privileges::getSensorCollection)
2946         .methods(boost::beast::http::verb::get)(
2947             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
2948 }
2949 
2950 inline void requestRoutesSensor(App& app)
2951 {
2952     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2953         .privileges(redfish::privileges::getSensor)
2954         .methods(boost::beast::http::verb::get)(
2955             std::bind_front(sensors::handleSensorGet, std::ref(app)));
2956 }
2957 
2958 } // namespace redfish
2959