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