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