xref: /openbmc/bmcweb/redfish-core/lib/sensors.hpp (revision 74ab83c5)
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     // Check if sensor has critical threshold alarm
717 
718     for (const auto& [valueName, value] : valuesDict)
719     {
720         if (valueName == "CriticalAlarmHigh" || valueName == "CriticalAlarmLow")
721         {
722             const bool* asserted = std::get_if<bool>(&value);
723             if (asserted == nullptr)
724             {
725                 BMCWEB_LOG_ERROR << "Illegal sensor threshold";
726             }
727             else if (*asserted)
728             {
729                 return "Critical";
730             }
731         }
732     }
733 
734     // Check if associated inventory item is not functional
735     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
736     {
737         return "Critical";
738     }
739 
740     // If current health in JSON object is already Warning, return that.  This
741     // should override the sensor status, which might be less severe.
742     if (currentHealth == "Warning")
743     {
744         return "Warning";
745     }
746 
747     // Check if sensor has warning threshold alarm
748     for (const auto& [valueName, value] : valuesDict)
749     {
750         if (valueName == "WarningAlarmHigh" || valueName == "WarningAlarmLow")
751         {
752             const bool* asserted = std::get_if<bool>(&value);
753             if (asserted == nullptr)
754             {
755                 BMCWEB_LOG_ERROR << "Illegal sensor threshold";
756             }
757             else if (*asserted)
758             {
759                 return "Warning";
760             }
761         }
762     }
763 
764     return "OK";
765 }
766 
767 inline void setLedState(nlohmann::json& sensorJson,
768                         const InventoryItem* inventoryItem)
769 {
770     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
771     {
772         switch (inventoryItem->ledState)
773         {
774             case LedState::OFF:
775                 sensorJson["IndicatorLED"] = "Off";
776                 break;
777             case LedState::ON:
778                 sensorJson["IndicatorLED"] = "Lit";
779                 break;
780             case LedState::BLINK:
781                 sensorJson["IndicatorLED"] = "Blinking";
782                 break;
783             case LedState::UNKNOWN:
784                 break;
785         }
786     }
787 }
788 
789 /**
790  * @brief Builds a json sensor representation of a sensor.
791  * @param sensorName  The name of the sensor to be built
792  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
793  * build
794  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
795  * @param propertiesDict A dictionary of the properties to build the sensor
796  * from.
797  * @param sensorJson  The json object to fill
798  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
799  * be nullptr if no associated inventory item was found.
800  */
801 inline void objectPropertiesToJson(
802     std::string_view sensorName, std::string_view sensorType,
803     std::string_view chassisSubNode,
804     const dbus::utility::DBusPropertiesMap& propertiesDict,
805     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
806 {
807     // Assume values exist as is (10^0 == 1) if no scale exists
808     int64_t scaleMultiplier = 0;
809     for (const auto& [valueName, value] : propertiesDict)
810     {
811         if (valueName == "Scale")
812         {
813             const int64_t* int64Value = std::get_if<int64_t>(&value);
814             if (int64Value != nullptr)
815             {
816                 scaleMultiplier = *int64Value;
817             }
818         }
819     }
820 
821     if (chassisSubNode == sensors::node::sensors)
822     {
823         std::string subNodeEscaped(chassisSubNode);
824         subNodeEscaped.erase(
825             std::remove(subNodeEscaped.begin(), subNodeEscaped.end(), '_'),
826             subNodeEscaped.end());
827 
828         // For sensors in SensorCollection we set Id instead of MemberId,
829         // including power sensors.
830         subNodeEscaped += '_';
831         subNodeEscaped += sensorName;
832         sensorJson["Id"] = std::move(subNodeEscaped);
833 
834         std::string sensorNameEs(sensorName);
835         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
836         sensorJson["Name"] = std::move(sensorNameEs);
837     }
838     else if (sensorType != "power")
839     {
840         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
841         // PowerControl, those properties have more general values because
842         // multiple sensors can be stored in the same JSON object.
843         sensorJson["MemberId"] = sensorName;
844         std::string sensorNameEs(sensorName);
845         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
846         sensorJson["Name"] = std::move(sensorNameEs);
847     }
848 
849     sensorJson["Status"]["State"] = getState(inventoryItem);
850     sensorJson["Status"]["Health"] =
851         getHealth(sensorJson, propertiesDict, inventoryItem);
852 
853     // Parameter to set to override the type we get from dbus, and force it to
854     // int, regardless of what is available.  This is used for schemas like fan,
855     // that require integers, not floats.
856     bool forceToInt = false;
857 
858     nlohmann::json::json_pointer unit("/Reading");
859     if (chassisSubNode == sensors::node::sensors)
860     {
861         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
862 
863         std::string_view readingType = sensors::toReadingType(sensorType);
864         if (readingType.empty())
865         {
866             BMCWEB_LOG_ERROR << "Redfish cannot map reading type for "
867                              << sensorType;
868         }
869         else
870         {
871             sensorJson["ReadingType"] = readingType;
872         }
873 
874         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
875         if (readingUnits.empty())
876         {
877             BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for "
878                              << sensorType;
879         }
880         else
881         {
882             sensorJson["ReadingUnits"] = readingUnits;
883         }
884     }
885     else if (sensorType == "temperature")
886     {
887         unit = "/ReadingCelsius"_json_pointer;
888         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
889         // TODO(ed) Documentation says that path should be type fan_tach,
890         // implementation seems to implement fan
891     }
892     else if (sensorType == "fan" || sensorType == "fan_tach")
893     {
894         unit = "/Reading"_json_pointer;
895         sensorJson["ReadingUnits"] = "RPM";
896         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
897         setLedState(sensorJson, inventoryItem);
898         forceToInt = true;
899     }
900     else if (sensorType == "fan_pwm")
901     {
902         unit = "/Reading"_json_pointer;
903         sensorJson["ReadingUnits"] = "Percent";
904         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
905         setLedState(sensorJson, inventoryItem);
906         forceToInt = true;
907     }
908     else if (sensorType == "voltage")
909     {
910         unit = "/ReadingVolts"_json_pointer;
911         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
912     }
913     else if (sensorType == "power")
914     {
915         if (boost::iequals(sensorName, "total_power"))
916         {
917             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
918             // Put multiple "sensors" into a single PowerControl, so have
919             // generic names for MemberId and Name. Follows Redfish mockup.
920             sensorJson["MemberId"] = "0";
921             sensorJson["Name"] = "Chassis Power Control";
922             unit = "/PowerConsumedWatts"_json_pointer;
923         }
924         else if (boost::ifind_first(sensorName, "input").empty())
925         {
926             unit = "/PowerInputWatts"_json_pointer;
927         }
928         else
929         {
930             unit = "/PowerOutputWatts"_json_pointer;
931         }
932     }
933     else
934     {
935         BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
936         return;
937     }
938     // Map of dbus interface name, dbus property name and redfish property_name
939     std::vector<
940         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
941         properties;
942     properties.reserve(7);
943 
944     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
945 
946     if (chassisSubNode == sensors::node::sensors)
947     {
948         properties.emplace_back(
949             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
950             "/Thresholds/UpperCaution/Reading"_json_pointer);
951         properties.emplace_back(
952             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
953             "/Thresholds/LowerCaution/Reading"_json_pointer);
954         properties.emplace_back(
955             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
956             "/Thresholds/UpperCritical/Reading"_json_pointer);
957         properties.emplace_back(
958             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
959             "/Thresholds/LowerCritical/Reading"_json_pointer);
960     }
961     else if (sensorType != "power")
962     {
963         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
964                                 "WarningHigh",
965                                 "/UpperThresholdNonCritical"_json_pointer);
966         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
967                                 "WarningLow",
968                                 "/LowerThresholdNonCritical"_json_pointer);
969         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
970                                 "CriticalHigh",
971                                 "/UpperThresholdCritical"_json_pointer);
972         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
973                                 "CriticalLow",
974                                 "/LowerThresholdCritical"_json_pointer);
975     }
976 
977     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
978 
979     if (chassisSubNode == sensors::node::sensors)
980     {
981         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
982                                 "/ReadingRangeMin"_json_pointer);
983         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
984                                 "/ReadingRangeMax"_json_pointer);
985     }
986     else if (sensorType == "temperature")
987     {
988         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
989                                 "/MinReadingRangeTemp"_json_pointer);
990         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
991                                 "/MaxReadingRangeTemp"_json_pointer);
992     }
993     else if (sensorType != "power")
994     {
995         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
996                                 "/MinReadingRange"_json_pointer);
997         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
998                                 "/MaxReadingRange"_json_pointer);
999     }
1000 
1001     for (const std::tuple<const char*, const char*,
1002                           nlohmann::json::json_pointer>& p : properties)
1003     {
1004         for (const auto& [valueName, valueVariant] : propertiesDict)
1005         {
1006             if (valueName != std::get<1>(p))
1007             {
1008                 continue;
1009             }
1010 
1011             // The property we want to set may be nested json, so use
1012             // a json_pointer for easy indexing into the json structure.
1013             const nlohmann::json::json_pointer& key = std::get<2>(p);
1014 
1015             // Attempt to pull the int64 directly
1016             const int64_t* int64Value = std::get_if<int64_t>(&valueVariant);
1017 
1018             const double* doubleValue = std::get_if<double>(&valueVariant);
1019             const uint32_t* uValue = std::get_if<uint32_t>(&valueVariant);
1020             double temp = 0.0;
1021             if (int64Value != nullptr)
1022             {
1023                 temp = static_cast<double>(*int64Value);
1024             }
1025             else if (doubleValue != nullptr)
1026             {
1027                 temp = *doubleValue;
1028             }
1029             else if (uValue != nullptr)
1030             {
1031                 temp = *uValue;
1032             }
1033             else
1034             {
1035                 BMCWEB_LOG_ERROR
1036                     << "Got value interface that wasn't int or double";
1037                 continue;
1038             }
1039             temp = temp * std::pow(10, scaleMultiplier);
1040             if (forceToInt)
1041             {
1042                 sensorJson[key] = static_cast<int64_t>(temp);
1043             }
1044             else
1045             {
1046                 sensorJson[key] = temp;
1047             }
1048         }
1049     }
1050 }
1051 
1052 /**
1053  * @brief Builds a json sensor representation of a sensor.
1054  * @param sensorName  The name of the sensor to be built
1055  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
1056  * build
1057  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
1058  * @param interfacesDict  A dictionary of the interfaces and properties of said
1059  * interfaces to be built from
1060  * @param sensorJson  The json object to fill
1061  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
1062  * be nullptr if no associated inventory item was found.
1063  */
1064 inline void objectInterfacesToJson(
1065     const std::string& sensorName, const std::string& sensorType,
1066     const std::string& chassisSubNode,
1067     const dbus::utility::DBusInteracesMap& interfacesDict,
1068     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
1069 {
1070 
1071     for (const auto& [interface, valuesDict] : interfacesDict)
1072     {
1073         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
1074                                valuesDict, sensorJson, inventoryItem);
1075     }
1076     BMCWEB_LOG_DEBUG << "Added sensor " << sensorName;
1077 }
1078 
1079 inline void populateFanRedundancy(
1080     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
1081 {
1082     crow::connections::systemBus->async_method_call(
1083         [sensorsAsyncResp](
1084             const boost::system::error_code ec,
1085             const dbus::utility::MapperGetSubTreeResponse& resp) {
1086         if (ec)
1087         {
1088             return; // don't have to have this interface
1089         }
1090         for (const std::pair<
1091                  std::string,
1092                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1093                  pathPair : resp)
1094         {
1095             const std::string& path = pathPair.first;
1096             const std::vector<std::pair<std::string, std::vector<std::string>>>&
1097                 objDict = pathPair.second;
1098             if (objDict.empty())
1099             {
1100                 continue; // this should be impossible
1101             }
1102 
1103             const std::string& owner = objDict.begin()->first;
1104             sdbusplus::asio::getProperty<std::vector<std::string>>(
1105                 *crow::connections::systemBus,
1106                 "xyz.openbmc_project.ObjectMapper", path + "/chassis",
1107                 "xyz.openbmc_project.Association", "endpoints",
1108                 [path, owner,
1109                  sensorsAsyncResp](const boost::system::error_code e,
1110                                    const std::vector<std::string>& endpoints) {
1111                 if (e)
1112                 {
1113                     return; // if they don't have an association we
1114                             // can't tell what chassis is
1115                 }
1116                 auto found =
1117                     std::find_if(endpoints.begin(), endpoints.end(),
1118                                  [sensorsAsyncResp](const std::string& entry) {
1119                     return entry.find(sensorsAsyncResp->chassisId) !=
1120                            std::string::npos;
1121                     });
1122 
1123                 if (found == endpoints.end())
1124                 {
1125                     return;
1126                 }
1127                 sdbusplus::asio::getAllProperties(
1128                     *crow::connections::systemBus, owner, path,
1129                     "xyz.openbmc_project.Control.FanRedundancy",
1130                     [path, sensorsAsyncResp](
1131                         const boost::system::error_code& err,
1132                         const dbus::utility::DBusPropertiesMap& ret) {
1133                     if (err)
1134                     {
1135                         return; // don't have to have this
1136                                 // interface
1137                     }
1138 
1139                     const uint8_t* allowedFailures = nullptr;
1140                     const std::vector<std::string>* collection = nullptr;
1141                     const std::string* status = nullptr;
1142 
1143                     const bool success = sdbusplus::unpackPropertiesNoThrow(
1144                         dbus_utils::UnpackErrorPrinter(), ret,
1145                         "AllowedFailures", allowedFailures, "Collection",
1146                         collection, "Status", status);
1147 
1148                     if (!success)
1149                     {
1150                         messages::internalError(
1151                             sensorsAsyncResp->asyncResp->res);
1152                         return;
1153                     }
1154 
1155                     if (allowedFailures == nullptr || collection == nullptr ||
1156                         status == nullptr)
1157                     {
1158                         BMCWEB_LOG_ERROR << "Invalid redundancy interface";
1159                         messages::internalError(
1160                             sensorsAsyncResp->asyncResp->res);
1161                         return;
1162                     }
1163 
1164                     sdbusplus::message::object_path objectPath(path);
1165                     std::string name = objectPath.filename();
1166                     if (name.empty())
1167                     {
1168                         // this should be impossible
1169                         messages::internalError(
1170                             sensorsAsyncResp->asyncResp->res);
1171                         return;
1172                     }
1173                     std::replace(name.begin(), name.end(), '_', ' ');
1174 
1175                     std::string health;
1176 
1177                     if (status->ends_with("Full"))
1178                     {
1179                         health = "OK";
1180                     }
1181                     else if (status->ends_with("Degraded"))
1182                     {
1183                         health = "Warning";
1184                     }
1185                     else
1186                     {
1187                         health = "Critical";
1188                     }
1189                     nlohmann::json::array_t redfishCollection;
1190                     const auto& fanRedfish =
1191                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
1192                     for (const std::string& item : *collection)
1193                     {
1194                         sdbusplus::message::object_path itemPath(item);
1195                         std::string itemName = itemPath.filename();
1196                         if (itemName.empty())
1197                         {
1198                             continue;
1199                         }
1200                         /*
1201                         todo(ed): merge patch that fixes the names
1202                         std::replace(itemName.begin(),
1203                                      itemName.end(), '_', ' ');*/
1204                         auto schemaItem =
1205                             std::find_if(fanRedfish.begin(), fanRedfish.end(),
1206                                          [itemName](const nlohmann::json& fan) {
1207                             return fan["MemberId"] == itemName;
1208                             });
1209                         if (schemaItem != fanRedfish.end())
1210                         {
1211                             nlohmann::json::object_t collectionId;
1212                             collectionId["@odata.id"] =
1213                                 (*schemaItem)["@odata.id"];
1214                             redfishCollection.emplace_back(
1215                                 std::move(collectionId));
1216                         }
1217                         else
1218                         {
1219                             BMCWEB_LOG_ERROR << "failed to find fan in schema";
1220                             messages::internalError(
1221                                 sensorsAsyncResp->asyncResp->res);
1222                             return;
1223                         }
1224                     }
1225 
1226                     size_t minNumNeeded =
1227                         collection->empty()
1228                             ? 0
1229                             : collection->size() - *allowedFailures;
1230                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
1231                                                 .jsonValue["Redundancy"];
1232 
1233                     nlohmann::json::object_t redundancy;
1234                     redundancy["@odata.id"] =
1235                         "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId +
1236                         "/" + sensorsAsyncResp->chassisSubNode +
1237                         "#/Redundancy/" + std::to_string(jResp.size());
1238                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
1239                     redundancy["MinNumNeeded"] = minNumNeeded;
1240                     redundancy["MemberId"] = name;
1241                     redundancy["Mode"] = "N+m";
1242                     redundancy["Name"] = name;
1243                     redundancy["RedundancySet"] = redfishCollection;
1244                     redundancy["Status"]["Health"] = health;
1245                     redundancy["Status"]["State"] = "Enabled";
1246 
1247                     jResp.push_back(std::move(redundancy));
1248                     });
1249                 });
1250         }
1251         },
1252         "xyz.openbmc_project.ObjectMapper",
1253         "/xyz/openbmc_project/object_mapper",
1254         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
1255         "/xyz/openbmc_project/control", 2,
1256         std::array<const char*, 1>{
1257             "xyz.openbmc_project.Control.FanRedundancy"});
1258 }
1259 
1260 inline void
1261     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
1262 {
1263     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
1264     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
1265     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
1266     {
1267         sensorHeaders = {"Voltages", "PowerSupplies"};
1268     }
1269     for (const std::string& sensorGroup : sensorHeaders)
1270     {
1271         nlohmann::json::iterator entry = response.find(sensorGroup);
1272         if (entry != response.end())
1273         {
1274             std::sort(entry->begin(), entry->end(),
1275                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
1276                 return c1["Name"] < c2["Name"];
1277             });
1278 
1279             // add the index counts to the end of each entry
1280             size_t count = 0;
1281             for (nlohmann::json& sensorJson : *entry)
1282             {
1283                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
1284                 if (odata == sensorJson.end())
1285                 {
1286                     continue;
1287                 }
1288                 std::string* value = odata->get_ptr<std::string*>();
1289                 if (value != nullptr)
1290                 {
1291                     *value += std::to_string(count);
1292                     count++;
1293                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
1294                 }
1295             }
1296         }
1297     }
1298 }
1299 
1300 /**
1301  * @brief Finds the inventory item with the specified object path.
1302  * @param inventoryItems D-Bus inventory items associated with sensors.
1303  * @param invItemObjPath D-Bus object path of inventory item.
1304  * @return Inventory item within vector, or nullptr if no match found.
1305  */
1306 inline InventoryItem* findInventoryItem(
1307     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1308     const std::string& invItemObjPath)
1309 {
1310     for (InventoryItem& inventoryItem : *inventoryItems)
1311     {
1312         if (inventoryItem.objectPath == invItemObjPath)
1313         {
1314             return &inventoryItem;
1315         }
1316     }
1317     return nullptr;
1318 }
1319 
1320 /**
1321  * @brief Finds the inventory item associated with the specified sensor.
1322  * @param inventoryItems D-Bus inventory items associated with sensors.
1323  * @param sensorObjPath D-Bus object path of sensor.
1324  * @return Inventory item within vector, or nullptr if no match found.
1325  */
1326 inline InventoryItem* findInventoryItemForSensor(
1327     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1328     const std::string& sensorObjPath)
1329 {
1330     for (InventoryItem& inventoryItem : *inventoryItems)
1331     {
1332         if (inventoryItem.sensors.count(sensorObjPath) > 0)
1333         {
1334             return &inventoryItem;
1335         }
1336     }
1337     return nullptr;
1338 }
1339 
1340 /**
1341  * @brief Finds the inventory item associated with the specified led path.
1342  * @param inventoryItems D-Bus inventory items associated with sensors.
1343  * @param ledObjPath D-Bus object path of led.
1344  * @return Inventory item within vector, or nullptr if no match found.
1345  */
1346 inline InventoryItem*
1347     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1348                             const std::string& ledObjPath)
1349 {
1350     for (InventoryItem& inventoryItem : inventoryItems)
1351     {
1352         if (inventoryItem.ledObjectPath == ledObjPath)
1353         {
1354             return &inventoryItem;
1355         }
1356     }
1357     return nullptr;
1358 }
1359 
1360 /**
1361  * @brief Adds inventory item and associated sensor to specified vector.
1362  *
1363  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1364  * existing InventoryItem with the specified object path.  If not found, one is
1365  * added to the vector.
1366  *
1367  * Next, the specified sensor is added to the set of sensors associated with the
1368  * InventoryItem.
1369  *
1370  * @param inventoryItems D-Bus inventory items associated with sensors.
1371  * @param invItemObjPath D-Bus object path of inventory item.
1372  * @param sensorObjPath D-Bus object path of sensor
1373  */
1374 inline void addInventoryItem(
1375     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1376     const std::string& invItemObjPath, const std::string& sensorObjPath)
1377 {
1378     // Look for inventory item in vector
1379     InventoryItem* inventoryItem =
1380         findInventoryItem(inventoryItems, invItemObjPath);
1381 
1382     // If inventory item doesn't exist in vector, add it
1383     if (inventoryItem == nullptr)
1384     {
1385         inventoryItems->emplace_back(invItemObjPath);
1386         inventoryItem = &(inventoryItems->back());
1387     }
1388 
1389     // Add sensor to set of sensors associated with inventory item
1390     inventoryItem->sensors.emplace(sensorObjPath);
1391 }
1392 
1393 /**
1394  * @brief Stores D-Bus data in the specified inventory item.
1395  *
1396  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1397  * specified InventoryItem.
1398  *
1399  * This data is later used to provide sensor property values in the JSON
1400  * response.
1401  *
1402  * @param inventoryItem Inventory item where data will be stored.
1403  * @param interfacesDict Map containing D-Bus interfaces and their properties
1404  * for the specified inventory item.
1405  */
1406 inline void storeInventoryItemData(
1407     InventoryItem& inventoryItem,
1408     const dbus::utility::DBusInteracesMap& interfacesDict)
1409 {
1410     // Get properties from Inventory.Item interface
1411 
1412     for (const auto& [interface, values] : interfacesDict)
1413     {
1414         if (interface == "xyz.openbmc_project.Inventory.Item")
1415         {
1416             for (const auto& [name, dbusValue] : values)
1417             {
1418                 if (name == "Present")
1419                 {
1420                     const bool* value = std::get_if<bool>(&dbusValue);
1421                     if (value != nullptr)
1422                     {
1423                         inventoryItem.isPresent = *value;
1424                     }
1425                 }
1426             }
1427         }
1428         // Check if Inventory.Item.PowerSupply interface is present
1429 
1430         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
1431         {
1432             inventoryItem.isPowerSupply = true;
1433         }
1434 
1435         // Get properties from Inventory.Decorator.Asset interface
1436         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1437         {
1438             for (const auto& [name, dbusValue] : values)
1439             {
1440                 if (name == "Manufacturer")
1441                 {
1442                     const std::string* value =
1443                         std::get_if<std::string>(&dbusValue);
1444                     if (value != nullptr)
1445                     {
1446                         inventoryItem.manufacturer = *value;
1447                     }
1448                 }
1449                 if (name == "Model")
1450                 {
1451                     const std::string* value =
1452                         std::get_if<std::string>(&dbusValue);
1453                     if (value != nullptr)
1454                     {
1455                         inventoryItem.model = *value;
1456                     }
1457                 }
1458                 if (name == "SerialNumber")
1459                 {
1460                     const std::string* value =
1461                         std::get_if<std::string>(&dbusValue);
1462                     if (value != nullptr)
1463                     {
1464                         inventoryItem.serialNumber = *value;
1465                     }
1466                 }
1467                 if (name == "PartNumber")
1468                 {
1469                     const std::string* value =
1470                         std::get_if<std::string>(&dbusValue);
1471                     if (value != nullptr)
1472                     {
1473                         inventoryItem.partNumber = *value;
1474                     }
1475                 }
1476             }
1477         }
1478 
1479         if (interface ==
1480             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1481         {
1482             for (const auto& [name, dbusValue] : values)
1483             {
1484                 if (name == "Functional")
1485                 {
1486                     const bool* value = std::get_if<bool>(&dbusValue);
1487                     if (value != nullptr)
1488                     {
1489                         inventoryItem.isFunctional = *value;
1490                     }
1491                 }
1492             }
1493         }
1494     }
1495 }
1496 
1497 /**
1498  * @brief Gets D-Bus data for inventory items associated with sensors.
1499  *
1500  * Uses the specified connections (services) to obtain D-Bus data for inventory
1501  * items associated with sensors.  Stores the resulting data in the
1502  * inventoryItems vector.
1503  *
1504  * This data is later used to provide sensor property values in the JSON
1505  * response.
1506  *
1507  * Finds the inventory item data asynchronously.  Invokes callback when data has
1508  * been obtained.
1509  *
1510  * The callback must have the following signature:
1511  *   @code
1512  *   callback(void)
1513  *   @endcode
1514  *
1515  * This function is called recursively, obtaining data asynchronously from one
1516  * connection in each call.  This ensures the callback is not invoked until the
1517  * last asynchronous function has completed.
1518  *
1519  * @param sensorsAsyncResp Pointer to object holding response data.
1520  * @param inventoryItems D-Bus inventory items associated with sensors.
1521  * @param invConnections Connections that provide data for the inventory items.
1522  * @param objectMgrPaths Mappings from connection name to DBus object path that
1523  * implements ObjectManager.
1524  * @param callback Callback to invoke when inventory data has been obtained.
1525  * @param invConnectionsIndex Current index in invConnections.  Only specified
1526  * in recursive calls to this function.
1527  */
1528 template <typename Callback>
1529 static void getInventoryItemsData(
1530     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1531     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1532     std::shared_ptr<std::set<std::string>> invConnections,
1533     std::shared_ptr<std::map<std::string, std::string>> objectMgrPaths,
1534     Callback&& callback, size_t invConnectionsIndex = 0)
1535 {
1536     BMCWEB_LOG_DEBUG << "getInventoryItemsData enter";
1537 
1538     // If no more connections left, call callback
1539     if (invConnectionsIndex >= invConnections->size())
1540     {
1541         callback();
1542         BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1543         return;
1544     }
1545 
1546     // Get inventory item data from current connection
1547     auto it = invConnections->begin();
1548     std::advance(it, invConnectionsIndex);
1549     if (it != invConnections->end())
1550     {
1551         const std::string& invConnection = *it;
1552 
1553         // Response handler for GetManagedObjects
1554         auto respHandler =
1555             [sensorsAsyncResp, inventoryItems, invConnections, objectMgrPaths,
1556              callback{std::forward<Callback>(callback)}, invConnectionsIndex](
1557                 const boost::system::error_code ec,
1558                 const dbus::utility::ManagedObjectType& resp) {
1559             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter";
1560             if (ec)
1561             {
1562                 BMCWEB_LOG_ERROR
1563                     << "getInventoryItemsData respHandler DBus error " << ec;
1564                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1565                 return;
1566             }
1567 
1568             // Loop through returned object paths
1569             for (const auto& objDictEntry : resp)
1570             {
1571                 const std::string& objPath =
1572                     static_cast<const std::string&>(objDictEntry.first);
1573 
1574                 // If this object path is one of the specified inventory items
1575                 InventoryItem* inventoryItem =
1576                     findInventoryItem(inventoryItems, objPath);
1577                 if (inventoryItem != nullptr)
1578                 {
1579                     // Store inventory data in InventoryItem
1580                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
1581                 }
1582             }
1583 
1584             // Recurse to get inventory item data from next connection
1585             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1586                                   invConnections, objectMgrPaths,
1587                                   std::move(callback), invConnectionsIndex + 1);
1588 
1589             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit";
1590         };
1591 
1592         // Find DBus object path that implements ObjectManager for the current
1593         // connection.  If no mapping found, default to "/".
1594         auto iter = objectMgrPaths->find(invConnection);
1595         const std::string& objectMgrPath =
1596             (iter != objectMgrPaths->end()) ? iter->second : "/";
1597         BMCWEB_LOG_DEBUG << "ObjectManager path for " << invConnection << " is "
1598                          << objectMgrPath;
1599 
1600         // Get all object paths and their interfaces for current connection
1601         crow::connections::systemBus->async_method_call(
1602             std::move(respHandler), invConnection, objectMgrPath,
1603             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1604     }
1605 
1606     BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1607 }
1608 
1609 /**
1610  * @brief Gets connections that provide D-Bus data for inventory items.
1611  *
1612  * Gets the D-Bus connections (services) that provide data for the inventory
1613  * items that are associated with sensors.
1614  *
1615  * Finds the connections asynchronously.  Invokes callback when information has
1616  * been obtained.
1617  *
1618  * The callback must have the following signature:
1619  *   @code
1620  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
1621  *   @endcode
1622  *
1623  * @param sensorsAsyncResp Pointer to object holding response data.
1624  * @param inventoryItems D-Bus inventory items associated with sensors.
1625  * @param callback Callback to invoke when connections have been obtained.
1626  */
1627 template <typename Callback>
1628 static void getInventoryItemsConnections(
1629     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1630     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1631     Callback&& callback)
1632 {
1633     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter";
1634 
1635     const std::string path = "/xyz/openbmc_project/inventory";
1636     const std::array<std::string, 4> interfaces = {
1637         "xyz.openbmc_project.Inventory.Item",
1638         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1639         "xyz.openbmc_project.Inventory.Decorator.Asset",
1640         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
1641 
1642     // Response handler for parsing output from GetSubTree
1643     auto respHandler =
1644         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1645          inventoryItems](
1646             const boost::system::error_code ec,
1647             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1648         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter";
1649         if (ec)
1650         {
1651             messages::internalError(sensorsAsyncResp->asyncResp->res);
1652             BMCWEB_LOG_ERROR
1653                 << "getInventoryItemsConnections respHandler DBus error " << ec;
1654             return;
1655         }
1656 
1657         // Make unique list of connections for desired inventory items
1658         std::shared_ptr<std::set<std::string>> invConnections =
1659             std::make_shared<std::set<std::string>>();
1660 
1661         // Loop through objects from GetSubTree
1662         for (const std::pair<
1663                  std::string,
1664                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1665                  object : subtree)
1666         {
1667             // Check if object path is one of the specified inventory items
1668             const std::string& objPath = object.first;
1669             if (findInventoryItem(inventoryItems, objPath) != nullptr)
1670             {
1671                 // Store all connections to inventory item
1672                 for (const std::pair<std::string, std::vector<std::string>>&
1673                          objData : object.second)
1674                 {
1675                     const std::string& invConnection = objData.first;
1676                     invConnections->insert(invConnection);
1677                 }
1678             }
1679         }
1680 
1681         callback(invConnections);
1682         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit";
1683     };
1684 
1685     // Make call to ObjectMapper to find all inventory items
1686     crow::connections::systemBus->async_method_call(
1687         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
1688         "/xyz/openbmc_project/object_mapper",
1689         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
1690     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit";
1691 }
1692 
1693 /**
1694  * @brief Gets associations from sensors to inventory items.
1695  *
1696  * Looks for ObjectMapper associations from the specified sensors to related
1697  * inventory items. Then finds the associations from those inventory items to
1698  * their LEDs, if any.
1699  *
1700  * Finds the inventory items asynchronously.  Invokes callback when information
1701  * has been obtained.
1702  *
1703  * The callback must have the following signature:
1704  *   @code
1705  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
1706  *   @endcode
1707  *
1708  * @param sensorsAsyncResp Pointer to object holding response data.
1709  * @param sensorNames All sensors within the current chassis.
1710  * @param objectMgrPaths Mappings from connection name to DBus object path that
1711  * implements ObjectManager.
1712  * @param callback Callback to invoke when inventory items have been obtained.
1713  */
1714 template <typename Callback>
1715 static void getInventoryItemAssociations(
1716     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1717     const std::shared_ptr<std::set<std::string>>& sensorNames,
1718     const std::shared_ptr<std::map<std::string, std::string>>& objectMgrPaths,
1719     Callback&& callback)
1720 {
1721     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter";
1722 
1723     // Response handler for GetManagedObjects
1724     auto respHandler =
1725         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1726          sensorNames](const boost::system::error_code ec,
1727                       const dbus::utility::ManagedObjectType& resp) {
1728         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter";
1729         if (ec)
1730         {
1731             BMCWEB_LOG_ERROR
1732                 << "getInventoryItemAssociations respHandler DBus error " << ec;
1733             messages::internalError(sensorsAsyncResp->asyncResp->res);
1734             return;
1735         }
1736 
1737         // Create vector to hold list of inventory items
1738         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1739             std::make_shared<std::vector<InventoryItem>>();
1740 
1741         // Loop through returned object paths
1742         std::string sensorAssocPath;
1743         sensorAssocPath.reserve(128); // avoid memory allocations
1744         for (const auto& objDictEntry : resp)
1745         {
1746             const std::string& objPath =
1747                 static_cast<const std::string&>(objDictEntry.first);
1748 
1749             // If path is inventory association for one of the specified sensors
1750             for (const std::string& sensorName : *sensorNames)
1751             {
1752                 sensorAssocPath = sensorName;
1753                 sensorAssocPath += "/inventory";
1754                 if (objPath == sensorAssocPath)
1755                 {
1756                     // Get Association interface for object path
1757                     for (const auto& [interface, values] : objDictEntry.second)
1758                     {
1759                         if (interface == "xyz.openbmc_project.Association")
1760                         {
1761                             for (const auto& [valueName, value] : values)
1762                             {
1763                                 if (valueName == "endpoints")
1764                                 {
1765                                     const std::vector<std::string>* endpoints =
1766                                         std::get_if<std::vector<std::string>>(
1767                                             &value);
1768                                     if ((endpoints != nullptr) &&
1769                                         !endpoints->empty())
1770                                     {
1771                                         // Add inventory item to vector
1772                                         const std::string& invItemPath =
1773                                             endpoints->front();
1774                                         addInventoryItem(inventoryItems,
1775                                                          invItemPath,
1776                                                          sensorName);
1777                                     }
1778                                 }
1779                             }
1780                         }
1781                     }
1782                     break;
1783                 }
1784             }
1785         }
1786 
1787         // Now loop through the returned object paths again, this time to
1788         // find the leds associated with the inventory items we just found
1789         std::string inventoryAssocPath;
1790         inventoryAssocPath.reserve(128); // avoid memory allocations
1791         for (const auto& objDictEntry : resp)
1792         {
1793             const std::string& objPath =
1794                 static_cast<const std::string&>(objDictEntry.first);
1795 
1796             for (InventoryItem& inventoryItem : *inventoryItems)
1797             {
1798                 inventoryAssocPath = inventoryItem.objectPath;
1799                 inventoryAssocPath += "/leds";
1800                 if (objPath == inventoryAssocPath)
1801                 {
1802                     for (const auto& [interface, values] : objDictEntry.second)
1803                     {
1804                         if (interface == "xyz.openbmc_project.Association")
1805                         {
1806                             for (const auto& [valueName, value] : values)
1807                             {
1808                                 if (valueName == "endpoints")
1809                                 {
1810                                     const std::vector<std::string>* endpoints =
1811                                         std::get_if<std::vector<std::string>>(
1812                                             &value);
1813                                     if ((endpoints != nullptr) &&
1814                                         !endpoints->empty())
1815                                     {
1816                                         // Add inventory item to vector
1817                                         // Store LED path in inventory item
1818                                         const std::string& ledPath =
1819                                             endpoints->front();
1820                                         inventoryItem.ledObjectPath = ledPath;
1821                                     }
1822                                 }
1823                             }
1824                         }
1825                     }
1826 
1827                     break;
1828                 }
1829             }
1830         }
1831         callback(inventoryItems);
1832         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit";
1833     };
1834 
1835     // Find DBus object path that implements ObjectManager for ObjectMapper
1836     std::string connection = "xyz.openbmc_project.ObjectMapper";
1837     auto iter = objectMgrPaths->find(connection);
1838     const std::string& objectMgrPath =
1839         (iter != objectMgrPaths->end()) ? iter->second : "/";
1840     BMCWEB_LOG_DEBUG << "ObjectManager path for " << connection << " is "
1841                      << objectMgrPath;
1842 
1843     // Call GetManagedObjects on the ObjectMapper to get all associations
1844     crow::connections::systemBus->async_method_call(
1845         std::move(respHandler), connection, objectMgrPath,
1846         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
1847 
1848     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit";
1849 }
1850 
1851 /**
1852  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1853  *
1854  * Uses the specified connections (services) to obtain D-Bus data for inventory
1855  * item leds associated with sensors.  Stores the resulting data in the
1856  * inventoryItems vector.
1857  *
1858  * This data is later used to provide sensor property values in the JSON
1859  * response.
1860  *
1861  * Finds the inventory item led data asynchronously.  Invokes callback when data
1862  * has been obtained.
1863  *
1864  * The callback must have the following signature:
1865  *   @code
1866  *   callback()
1867  *   @endcode
1868  *
1869  * This function is called recursively, obtaining data asynchronously from one
1870  * connection in each call.  This ensures the callback is not invoked until the
1871  * last asynchronous function has completed.
1872  *
1873  * @param sensorsAsyncResp Pointer to object holding response data.
1874  * @param inventoryItems D-Bus inventory items associated with sensors.
1875  * @param ledConnections Connections that provide data for the inventory leds.
1876  * @param callback Callback to invoke when inventory data has been obtained.
1877  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1878  * in recursive calls to this function.
1879  */
1880 template <typename Callback>
1881 void getInventoryLedData(
1882     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1883     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1884     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1885     Callback&& callback, size_t ledConnectionsIndex = 0)
1886 {
1887     BMCWEB_LOG_DEBUG << "getInventoryLedData enter";
1888 
1889     // If no more connections left, call callback
1890     if (ledConnectionsIndex >= ledConnections->size())
1891     {
1892         callback();
1893         BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1894         return;
1895     }
1896 
1897     // Get inventory item data from current connection
1898     auto it = ledConnections->begin();
1899     std::advance(it, ledConnectionsIndex);
1900     if (it != ledConnections->end())
1901     {
1902         const std::string& ledPath = (*it).first;
1903         const std::string& ledConnection = (*it).second;
1904         // Response handler for Get State property
1905         auto respHandler =
1906             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1907              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
1908                 const boost::system::error_code ec, const std::string& state) {
1909             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter";
1910             if (ec)
1911             {
1912                 BMCWEB_LOG_ERROR
1913                     << "getInventoryLedData respHandler DBus error " << ec;
1914                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1915                 return;
1916             }
1917 
1918             BMCWEB_LOG_DEBUG << "Led state: " << state;
1919             // Find inventory item with this LED object path
1920             InventoryItem* inventoryItem =
1921                 findInventoryItemForLed(*inventoryItems, ledPath);
1922             if (inventoryItem != nullptr)
1923             {
1924                 // Store LED state in InventoryItem
1925                 if (state.ends_with("On"))
1926                 {
1927                     inventoryItem->ledState = LedState::ON;
1928                 }
1929                 else if (state.ends_with("Blink"))
1930                 {
1931                     inventoryItem->ledState = LedState::BLINK;
1932                 }
1933                 else if (state.ends_with("Off"))
1934                 {
1935                     inventoryItem->ledState = LedState::OFF;
1936                 }
1937                 else
1938                 {
1939                     inventoryItem->ledState = LedState::UNKNOWN;
1940                 }
1941             }
1942 
1943             // Recurse to get LED data from next connection
1944             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1945                                 ledConnections, std::move(callback),
1946                                 ledConnectionsIndex + 1);
1947 
1948             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit";
1949         };
1950 
1951         // Get the State property for the current LED
1952         sdbusplus::asio::getProperty<std::string>(
1953             *crow::connections::systemBus, ledConnection, ledPath,
1954             "xyz.openbmc_project.Led.Physical", "State",
1955             std::move(respHandler));
1956     }
1957 
1958     BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1959 }
1960 
1961 /**
1962  * @brief Gets LED data for LEDs associated with given inventory items.
1963  *
1964  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1965  * associated with the specified inventory items.  Then gets the LED data from
1966  * each connection and stores it in the inventory item.
1967  *
1968  * This data is later used to provide sensor property values in the JSON
1969  * response.
1970  *
1971  * Finds the LED data asynchronously.  Invokes callback when information has
1972  * been obtained.
1973  *
1974  * The callback must have the following signature:
1975  *   @code
1976  *   callback()
1977  *   @endcode
1978  *
1979  * @param sensorsAsyncResp Pointer to object holding response data.
1980  * @param inventoryItems D-Bus inventory items associated with sensors.
1981  * @param callback Callback to invoke when inventory items have been obtained.
1982  */
1983 template <typename Callback>
1984 void getInventoryLeds(
1985     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1986     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1987     Callback&& callback)
1988 {
1989     BMCWEB_LOG_DEBUG << "getInventoryLeds enter";
1990 
1991     const std::string path = "/xyz/openbmc_project";
1992     const std::array<std::string, 1> interfaces = {
1993         "xyz.openbmc_project.Led.Physical"};
1994 
1995     // Response handler for parsing output from GetSubTree
1996     auto respHandler =
1997         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1998          inventoryItems](
1999             const boost::system::error_code ec,
2000             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2001         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter";
2002         if (ec)
2003         {
2004             messages::internalError(sensorsAsyncResp->asyncResp->res);
2005             BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error "
2006                              << ec;
2007             return;
2008         }
2009 
2010         // Build map of LED object paths to connections
2011         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
2012             std::make_shared<std::map<std::string, std::string>>();
2013 
2014         // Loop through objects from GetSubTree
2015         for (const std::pair<
2016                  std::string,
2017                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
2018                  object : subtree)
2019         {
2020             // Check if object path is LED for one of the specified inventory
2021             // items
2022             const std::string& ledPath = object.first;
2023             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
2024             {
2025                 // Add mapping from ledPath to connection
2026                 const std::string& connection = object.second.begin()->first;
2027                 (*ledConnections)[ledPath] = connection;
2028                 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> "
2029                                  << connection;
2030             }
2031         }
2032 
2033         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
2034                             std::move(callback));
2035         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit";
2036     };
2037     // Make call to ObjectMapper to find all inventory items
2038     crow::connections::systemBus->async_method_call(
2039         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
2040         "/xyz/openbmc_project/object_mapper",
2041         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
2042     BMCWEB_LOG_DEBUG << "getInventoryLeds exit";
2043 }
2044 
2045 /**
2046  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
2047  *
2048  * Uses the specified connections (services) (currently assumes just one) to
2049  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
2050  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
2051  *
2052  * This data is later used to provide sensor property values in the JSON
2053  * response.
2054  *
2055  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
2056  * when data has been obtained.
2057  *
2058  * The callback must have the following signature:
2059  *   @code
2060  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2061  *   @endcode
2062  *
2063  * @param sensorsAsyncResp Pointer to object holding response data.
2064  * @param inventoryItems D-Bus inventory items associated with sensors.
2065  * @param psAttributesConnections Connections that provide data for the Power
2066  *        Supply Attributes
2067  * @param callback Callback to invoke when data has been obtained.
2068  */
2069 template <typename Callback>
2070 void getPowerSupplyAttributesData(
2071     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2072     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
2073     const std::map<std::string, std::string>& psAttributesConnections,
2074     Callback&& callback)
2075 {
2076     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter";
2077 
2078     if (psAttributesConnections.empty())
2079     {
2080         BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!";
2081         callback(inventoryItems);
2082         return;
2083     }
2084 
2085     // Assuming just one connection (service) for now
2086     auto it = psAttributesConnections.begin();
2087 
2088     const std::string& psAttributesPath = (*it).first;
2089     const std::string& psAttributesConnection = (*it).second;
2090 
2091     // Response handler for Get DeratingFactor property
2092     auto respHandler =
2093         [sensorsAsyncResp, inventoryItems,
2094          callback{std::forward<Callback>(callback)}](
2095             const boost::system::error_code ec, const uint32_t value) {
2096         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter";
2097         if (ec)
2098         {
2099             BMCWEB_LOG_ERROR
2100                 << "getPowerSupplyAttributesData respHandler DBus error " << ec;
2101             messages::internalError(sensorsAsyncResp->asyncResp->res);
2102             return;
2103         }
2104 
2105         BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value;
2106         // Store value in Power Supply Inventory Items
2107         for (InventoryItem& inventoryItem : *inventoryItems)
2108         {
2109             if (inventoryItem.isPowerSupply)
2110             {
2111                 inventoryItem.powerSupplyEfficiencyPercent =
2112                     static_cast<int>(value);
2113             }
2114         }
2115 
2116         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit";
2117         callback(inventoryItems);
2118     };
2119 
2120     // Get the DeratingFactor property for the PowerSupplyAttributes
2121     // Currently only property on the interface/only one we care about
2122     sdbusplus::asio::getProperty<uint32_t>(
2123         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
2124         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
2125         std::move(respHandler));
2126 
2127     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit";
2128 }
2129 
2130 /**
2131  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
2132  *
2133  * Gets the D-Bus connection (service) that provides Power Supply Attributes
2134  * data. Then gets the Power Supply Attributes data from the connection
2135  * (currently just assumes 1 connection) and stores the data in the inventory
2136  * item.
2137  *
2138  * This data is later used to provide sensor property values in the JSON
2139  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
2140  *
2141  * Finds the Power Supply Attributes data asynchronously. Invokes callback
2142  * when information has been obtained.
2143  *
2144  * The callback must have the following signature:
2145  *   @code
2146  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2147  *   @endcode
2148  *
2149  * @param sensorsAsyncResp Pointer to object holding response data.
2150  * @param inventoryItems D-Bus inventory items associated with sensors.
2151  * @param callback Callback to invoke when data has been obtained.
2152  */
2153 template <typename Callback>
2154 void getPowerSupplyAttributes(
2155     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2156     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
2157     Callback&& callback)
2158 {
2159     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter";
2160 
2161     // Only need the power supply attributes when the Power Schema
2162     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
2163     {
2164         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power";
2165         callback(inventoryItems);
2166         return;
2167     }
2168 
2169     const std::array<std::string, 1> interfaces = {
2170         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
2171 
2172     // Response handler for parsing output from GetSubTree
2173     auto respHandler =
2174         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2175          inventoryItems](
2176             const boost::system::error_code ec,
2177             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2178         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter";
2179         if (ec)
2180         {
2181             messages::internalError(sensorsAsyncResp->asyncResp->res);
2182             BMCWEB_LOG_ERROR
2183                 << "getPowerSupplyAttributes respHandler DBus error " << ec;
2184             return;
2185         }
2186         if (subtree.empty())
2187         {
2188             BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!";
2189             callback(inventoryItems);
2190             return;
2191         }
2192 
2193         // Currently we only support 1 power supply attribute, use this for
2194         // all the power supplies. Build map of object path to connection.
2195         // Assume just 1 connection and 1 path for now.
2196         std::map<std::string, std::string> psAttributesConnections;
2197 
2198         if (subtree[0].first.empty() || subtree[0].second.empty())
2199         {
2200             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
2201             callback(inventoryItems);
2202             return;
2203         }
2204 
2205         const std::string& psAttributesPath = subtree[0].first;
2206         const std::string& connection = subtree[0].second.begin()->first;
2207 
2208         if (connection.empty())
2209         {
2210             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
2211             callback(inventoryItems);
2212             return;
2213         }
2214 
2215         psAttributesConnections[psAttributesPath] = connection;
2216         BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> "
2217                          << connection;
2218 
2219         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
2220                                      psAttributesConnections,
2221                                      std::move(callback));
2222         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit";
2223     };
2224     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2225     crow::connections::systemBus->async_method_call(
2226         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
2227         "/xyz/openbmc_project/object_mapper",
2228         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
2229         "/xyz/openbmc_project", 0, interfaces);
2230     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit";
2231 }
2232 
2233 /**
2234  * @brief Gets inventory items associated with sensors.
2235  *
2236  * Finds the inventory items that are associated with the specified sensors.
2237  * Then gets D-Bus data for the inventory items, such as presence and VPD.
2238  *
2239  * This data is later used to provide sensor property values in the JSON
2240  * response.
2241  *
2242  * Finds the inventory items asynchronously.  Invokes callback when the
2243  * inventory items have been obtained.
2244  *
2245  * The callback must have the following signature:
2246  *   @code
2247  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2248  *   @endcode
2249  *
2250  * @param sensorsAsyncResp Pointer to object holding response data.
2251  * @param sensorNames All sensors within the current chassis.
2252  * @param objectMgrPaths Mappings from connection name to DBus object path that
2253  * implements ObjectManager.
2254  * @param callback Callback to invoke when inventory items have been obtained.
2255  */
2256 template <typename Callback>
2257 static void getInventoryItems(
2258     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2259     const std::shared_ptr<std::set<std::string>> sensorNames,
2260     std::shared_ptr<std::map<std::string, std::string>> objectMgrPaths,
2261     Callback&& callback)
2262 {
2263     BMCWEB_LOG_DEBUG << "getInventoryItems enter";
2264     auto getInventoryItemAssociationsCb =
2265         [sensorsAsyncResp, objectMgrPaths,
2266          callback{std::forward<Callback>(callback)}](
2267             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
2268         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter";
2269         auto getInventoryItemsConnectionsCb =
2270             [sensorsAsyncResp, inventoryItems, objectMgrPaths,
2271              callback{std::forward<const Callback>(callback)}](
2272                 std::shared_ptr<std::set<std::string>> invConnections) {
2273             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter";
2274             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2275                                             callback{std::move(callback)}]() {
2276                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter";
2277 
2278                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2279                                            callback{std::move(callback)}]() {
2280                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter";
2281                     // Find Power Supply Attributes and get the data
2282                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
2283                                              std::move(callback));
2284                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit";
2285                 };
2286 
2287                 // Find led connections and get the data
2288                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
2289                                  std::move(getInventoryLedsCb));
2290                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit";
2291             };
2292 
2293             // Get inventory item data from connections
2294             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2295                                   invConnections, objectMgrPaths,
2296                                   std::move(getInventoryItemsDataCb));
2297             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit";
2298         };
2299 
2300         // Get connections that provide inventory item data
2301         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
2302                                      std::move(getInventoryItemsConnectionsCb));
2303         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit";
2304     };
2305 
2306     // Get associations from sensors to inventory items
2307     getInventoryItemAssociations(sensorsAsyncResp, sensorNames, objectMgrPaths,
2308                                  std::move(getInventoryItemAssociationsCb));
2309     BMCWEB_LOG_DEBUG << "getInventoryItems exit";
2310 }
2311 
2312 /**
2313  * @brief Returns JSON PowerSupply object for the specified inventory item.
2314  *
2315  * Searches for a JSON PowerSupply object that matches the specified inventory
2316  * item.  If one is not found, a new PowerSupply object is added to the JSON
2317  * array.
2318  *
2319  * Multiple sensors are often associated with one power supply inventory item.
2320  * As a result, multiple sensor values are stored in one JSON PowerSupply
2321  * object.
2322  *
2323  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2324  * @param inventoryItem Inventory item for the power supply.
2325  * @param chassisId Chassis that contains the power supply.
2326  * @return JSON PowerSupply object for the specified inventory item.
2327  */
2328 inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2329                                       const InventoryItem& inventoryItem,
2330                                       const std::string& chassisId)
2331 {
2332     // Check if matching PowerSupply object already exists in JSON array
2333     for (nlohmann::json& powerSupply : powerSupplyArray)
2334     {
2335         if (powerSupply["MemberId"] == inventoryItem.name)
2336         {
2337             return powerSupply;
2338         }
2339     }
2340 
2341     // Add new PowerSupply object to JSON array
2342     powerSupplyArray.push_back({});
2343     nlohmann::json& powerSupply = powerSupplyArray.back();
2344     powerSupply["@odata.id"] =
2345         "/redfish/v1/Chassis/" + chassisId + "/Power#/PowerSupplies/";
2346     powerSupply["MemberId"] = inventoryItem.name;
2347     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2348     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2349     powerSupply["Model"] = inventoryItem.model;
2350     powerSupply["PartNumber"] = inventoryItem.partNumber;
2351     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2352     setLedState(powerSupply, &inventoryItem);
2353 
2354     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
2355     {
2356         powerSupply["EfficiencyPercent"] =
2357             inventoryItem.powerSupplyEfficiencyPercent;
2358     }
2359 
2360     powerSupply["Status"]["State"] = getState(&inventoryItem);
2361     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2362     powerSupply["Status"]["Health"] = health;
2363 
2364     return powerSupply;
2365 }
2366 
2367 /**
2368  * @brief Gets the values of the specified sensors.
2369  *
2370  * Stores the results as JSON in the SensorsAsyncResp.
2371  *
2372  * Gets the sensor values asynchronously.  Stores the results later when the
2373  * information has been obtained.
2374  *
2375  * The sensorNames set contains all requested sensors for the current chassis.
2376  *
2377  * To minimize the number of DBus calls, the DBus method
2378  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2379  * values of all sensors provided by a connection (service).
2380  *
2381  * The connections set contains all the connections that provide sensor values.
2382  *
2383  * The objectMgrPaths map contains mappings from a connection name to the
2384  * corresponding DBus object path that implements ObjectManager.
2385  *
2386  * The InventoryItem vector contains D-Bus inventory items associated with the
2387  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2388  *
2389  * @param SensorsAsyncResp Pointer to object holding response data.
2390  * @param sensorNames All requested sensors within the current chassis.
2391  * @param connections Connections that provide sensor values.
2392  * @param objectMgrPaths Mappings from connection name to DBus object path that
2393  * implements ObjectManager.
2394  * @param inventoryItems Inventory items associated with the sensors.
2395  */
2396 inline void getSensorData(
2397     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2398     const std::shared_ptr<std::set<std::string>>& sensorNames,
2399     const std::set<std::string>& connections,
2400     const std::shared_ptr<std::map<std::string, std::string>>& objectMgrPaths,
2401     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2402 {
2403     BMCWEB_LOG_DEBUG << "getSensorData enter";
2404     // Get managed objects from all services exposing sensors
2405     for (const std::string& connection : connections)
2406     {
2407         // Response handler to process managed objects
2408         auto getManagedObjectsCb =
2409             [sensorsAsyncResp, sensorNames,
2410              inventoryItems](const boost::system::error_code ec,
2411                              const dbus::utility::ManagedObjectType& resp) {
2412             BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
2413             if (ec)
2414             {
2415                 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
2416                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2417                 return;
2418             }
2419             // Go through all objects and update response with sensor data
2420             for (const auto& objDictEntry : resp)
2421             {
2422                 const std::string& objPath =
2423                     static_cast<const std::string&>(objDictEntry.first);
2424                 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
2425                                  << objPath;
2426 
2427                 std::vector<std::string> split;
2428                 // Reserve space for
2429                 // /xyz/openbmc_project/sensors/<name>/<subname>
2430                 split.reserve(6);
2431                 boost::algorithm::split(split, objPath, boost::is_any_of("/"));
2432                 if (split.size() < 6)
2433                 {
2434                     BMCWEB_LOG_ERROR << "Got path that isn't long enough "
2435                                      << objPath;
2436                     continue;
2437                 }
2438                 // These indexes aren't intuitive, as boost::split puts an empty
2439                 // string at the beginning
2440                 const std::string& sensorType = split[4];
2441                 const std::string& sensorName = split[5];
2442                 BMCWEB_LOG_DEBUG << "sensorName " << sensorName
2443                                  << " sensorType " << sensorType;
2444                 if (sensorNames->find(objPath) == sensorNames->end())
2445                 {
2446                     BMCWEB_LOG_DEBUG << sensorName << " not in sensor list ";
2447                     continue;
2448                 }
2449 
2450                 // Find inventory item (if any) associated with sensor
2451                 InventoryItem* inventoryItem =
2452                     findInventoryItemForSensor(inventoryItems, objPath);
2453 
2454                 const std::string& sensorSchema =
2455                     sensorsAsyncResp->chassisSubNode;
2456 
2457                 nlohmann::json* sensorJson = nullptr;
2458 
2459                 if (sensorSchema == sensors::node::sensors &&
2460                     !sensorsAsyncResp->efficientExpand)
2461                 {
2462                     std::string sensorTypeEscaped(sensorType);
2463                     sensorTypeEscaped.erase(
2464                         std::remove(sensorTypeEscaped.begin(),
2465                                     sensorTypeEscaped.end(), '_'),
2466                         sensorTypeEscaped.end());
2467                     std::string sensorId(sensorTypeEscaped);
2468                     sensorId += "_";
2469                     sensorId += sensorName;
2470 
2471                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2472                         crow::utility::urlFromPieces(
2473                             "redfish", "v1", "Chassis",
2474                             sensorsAsyncResp->chassisId,
2475                             sensorsAsyncResp->chassisSubNode, sensorId);
2476                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
2477                 }
2478                 else
2479                 {
2480                     std::string fieldName;
2481                     if (sensorsAsyncResp->efficientExpand)
2482                     {
2483                         fieldName = "Members";
2484                     }
2485                     else if (sensorType == "temperature")
2486                     {
2487                         fieldName = "Temperatures";
2488                     }
2489                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2490                              sensorType == "fan_pwm")
2491                     {
2492                         fieldName = "Fans";
2493                     }
2494                     else if (sensorType == "voltage")
2495                     {
2496                         fieldName = "Voltages";
2497                     }
2498                     else if (sensorType == "power")
2499                     {
2500                         if (sensorName == "total_power")
2501                         {
2502                             fieldName = "PowerControl";
2503                         }
2504                         else if ((inventoryItem != nullptr) &&
2505                                  (inventoryItem->isPowerSupply))
2506                         {
2507                             fieldName = "PowerSupplies";
2508                         }
2509                         else
2510                         {
2511                             // Other power sensors are in SensorCollection
2512                             continue;
2513                         }
2514                     }
2515                     else
2516                     {
2517                         BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
2518                                          << sensorType;
2519                         continue;
2520                     }
2521 
2522                     nlohmann::json& tempArray =
2523                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2524                     if (fieldName == "PowerControl")
2525                     {
2526                         if (tempArray.empty())
2527                         {
2528                             // Put multiple "sensors" into a single
2529                             // PowerControl. Follows MemberId naming and
2530                             // naming in power.hpp.
2531                             nlohmann::json::object_t power;
2532                             power["@odata.id"] =
2533                                 "/redfish/v1/Chassis/" +
2534                                 sensorsAsyncResp->chassisId + "/" +
2535                                 sensorsAsyncResp->chassisSubNode + "#/" +
2536                                 fieldName + "/0";
2537                             tempArray.push_back(std::move(power));
2538                         }
2539                         sensorJson = &(tempArray.back());
2540                     }
2541                     else if (fieldName == "PowerSupplies")
2542                     {
2543                         if (inventoryItem != nullptr)
2544                         {
2545                             sensorJson =
2546                                 &(getPowerSupply(tempArray, *inventoryItem,
2547                                                  sensorsAsyncResp->chassisId));
2548                         }
2549                     }
2550                     else if (fieldName == "Members")
2551                     {
2552                         nlohmann::json::object_t member;
2553                         member["@odata.id"] =
2554                             "/redfish/v1/Chassis/" +
2555                             sensorsAsyncResp->chassisId + "/" +
2556                             sensorsAsyncResp->chassisSubNode + "/" + sensorName;
2557                         tempArray.push_back(std::move(member));
2558                         sensorJson = &(tempArray.back());
2559                     }
2560                     else
2561                     {
2562                         nlohmann::json::object_t member;
2563                         member["@odata.id"] = "/redfish/v1/Chassis/" +
2564                                               sensorsAsyncResp->chassisId +
2565                                               "/" +
2566                                               sensorsAsyncResp->chassisSubNode +
2567                                               "#/" + fieldName + "/";
2568                         tempArray.push_back(std::move(member));
2569                         sensorJson = &(tempArray.back());
2570                     }
2571                 }
2572 
2573                 if (sensorJson != nullptr)
2574                 {
2575                     objectInterfacesToJson(sensorName, sensorType,
2576                                            sensorsAsyncResp->chassisSubNode,
2577                                            objDictEntry.second, *sensorJson,
2578                                            inventoryItem);
2579 
2580                     std::string path = "/xyz/openbmc_project/sensors/";
2581                     path += sensorType;
2582                     path += "/";
2583                     path += sensorName;
2584                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2585                 }
2586             }
2587             if (sensorsAsyncResp.use_count() == 1)
2588             {
2589                 sortJSONResponse(sensorsAsyncResp);
2590                 if (sensorsAsyncResp->chassisSubNode ==
2591                         sensors::node::sensors &&
2592                     sensorsAsyncResp->efficientExpand)
2593                 {
2594                     sensorsAsyncResp->asyncResp->res
2595                         .jsonValue["Members@odata.count"] =
2596                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2597                             .size();
2598                 }
2599                 else if (sensorsAsyncResp->chassisSubNode ==
2600                          sensors::node::thermal)
2601                 {
2602                     populateFanRedundancy(sensorsAsyncResp);
2603                 }
2604             }
2605             BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
2606         };
2607 
2608         // Find DBus object path that implements ObjectManager for the current
2609         // connection.  If no mapping found, default to "/".
2610         auto iter = objectMgrPaths->find(connection);
2611         const std::string& objectMgrPath =
2612             (iter != objectMgrPaths->end()) ? iter->second : "/";
2613         BMCWEB_LOG_DEBUG << "ObjectManager path for " << connection << " is "
2614                          << objectMgrPath;
2615 
2616         crow::connections::systemBus->async_method_call(
2617             getManagedObjectsCb, connection, objectMgrPath,
2618             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
2619     }
2620     BMCWEB_LOG_DEBUG << "getSensorData exit";
2621 }
2622 
2623 inline void
2624     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2625                       const std::shared_ptr<std::set<std::string>>& sensorNames)
2626 {
2627     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2628                                const std::set<std::string>& connections) {
2629         BMCWEB_LOG_DEBUG << "getConnectionCb enter";
2630         auto getObjectManagerPathsCb =
2631             [sensorsAsyncResp, sensorNames, connections](
2632                 const std::shared_ptr<std::map<std::string, std::string>>&
2633                     objectMgrPaths) {
2634             BMCWEB_LOG_DEBUG << "getObjectManagerPathsCb enter";
2635             auto getInventoryItemsCb =
2636                 [sensorsAsyncResp, sensorNames, connections, objectMgrPaths](
2637                     const std::shared_ptr<std::vector<InventoryItem>>&
2638                         inventoryItems) {
2639                 BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter";
2640                 // Get sensor data and store results in JSON
2641                 getSensorData(sensorsAsyncResp, sensorNames, connections,
2642                               objectMgrPaths, inventoryItems);
2643                 BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit";
2644             };
2645 
2646             // Get inventory items associated with sensors
2647             getInventoryItems(sensorsAsyncResp, sensorNames, objectMgrPaths,
2648                               std::move(getInventoryItemsCb));
2649 
2650             BMCWEB_LOG_DEBUG << "getObjectManagerPathsCb exit";
2651         };
2652 
2653         // Get mapping from connection names to the DBus object
2654         // paths that implement the ObjectManager interface
2655         getObjectManagerPaths(sensorsAsyncResp,
2656                               std::move(getObjectManagerPathsCb));
2657         BMCWEB_LOG_DEBUG << "getConnectionCb exit";
2658     };
2659 
2660     // Get set of connections that provide sensor values
2661     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
2662 }
2663 
2664 /**
2665  * @brief Entry point for retrieving sensors data related to requested
2666  *        chassis.
2667  * @param SensorsAsyncResp   Pointer to object holding response data
2668  */
2669 inline void
2670     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
2671 {
2672     BMCWEB_LOG_DEBUG << "getChassisData enter";
2673     auto getChassisCb =
2674         [sensorsAsyncResp](
2675             const std::shared_ptr<std::set<std::string>>& sensorNames) {
2676         BMCWEB_LOG_DEBUG << "getChassisCb enter";
2677         processSensorList(sensorsAsyncResp, sensorNames);
2678         BMCWEB_LOG_DEBUG << "getChassisCb exit";
2679     };
2680     // SensorCollection doesn't contain the Redundancy property
2681     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2682     {
2683         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
2684             nlohmann::json::array();
2685     }
2686     // Get set of sensors in chassis
2687     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
2688                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
2689                std::move(getChassisCb));
2690     BMCWEB_LOG_DEBUG << "getChassisData exit";
2691 }
2692 
2693 /**
2694  * @brief Find the requested sensorName in the list of all sensors supplied by
2695  * the chassis node
2696  *
2697  * @param sensorName   The sensor name supplied in the PATCH request
2698  * @param sensorsList  The list of sensors managed by the chassis node
2699  * @param sensorsModified  The list of sensors that were found as a result of
2700  *                         repeated calls to this function
2701  */
2702 inline bool
2703     findSensorNameUsingSensorPath(std::string_view sensorName,
2704                                   const std::set<std::string>& sensorsList,
2705                                   std::set<std::string>& sensorsModified)
2706 {
2707     for (const auto& chassisSensor : sensorsList)
2708     {
2709         sdbusplus::message::object_path path(chassisSensor);
2710         std::string thisSensorName = path.filename();
2711         if (thisSensorName.empty())
2712         {
2713             continue;
2714         }
2715         if (thisSensorName == sensorName)
2716         {
2717             sensorsModified.emplace(chassisSensor);
2718             return true;
2719         }
2720     }
2721     return false;
2722 }
2723 
2724 /**
2725  * @brief Entry point for overriding sensor values of given sensor
2726  *
2727  * @param sensorAsyncResp   response object
2728  * @param allCollections   Collections extract from sensors' request patch info
2729  * @param chassisSubNode   Chassis Node for which the query has to happen
2730  */
2731 inline void setSensorsOverride(
2732     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
2733     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2734         allCollections)
2735 {
2736     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
2737                     << sensorAsyncResp->chassisSubNode << "\n";
2738 
2739     const char* propertyValueName = nullptr;
2740     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2741     std::string memberId;
2742     double value = 0.0;
2743     for (auto& collectionItems : allCollections)
2744     {
2745         if (collectionItems.first == "Temperatures")
2746         {
2747             propertyValueName = "ReadingCelsius";
2748         }
2749         else if (collectionItems.first == "Fans")
2750         {
2751             propertyValueName = "Reading";
2752         }
2753         else
2754         {
2755             propertyValueName = "ReadingVolts";
2756         }
2757         for (auto& item : collectionItems.second)
2758         {
2759             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
2760                                      "MemberId", memberId, propertyValueName,
2761                                      value))
2762             {
2763                 return;
2764             }
2765             overrideMap.emplace(memberId,
2766                                 std::make_pair(value, collectionItems.first));
2767         }
2768     }
2769 
2770     auto getChassisSensorListCb =
2771         [sensorAsyncResp, overrideMap](
2772             const std::shared_ptr<std::set<std::string>>& sensorsList) {
2773         // Match sensor names in the PATCH request to those managed by the
2774         // chassis node
2775         const std::shared_ptr<std::set<std::string>> sensorNames =
2776             std::make_shared<std::set<std::string>>();
2777         for (const auto& item : overrideMap)
2778         {
2779             const auto& sensor = item.first;
2780             if (!findSensorNameUsingSensorPath(sensor, *sensorsList,
2781                                                *sensorNames))
2782             {
2783                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
2784                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2785                                            item.second.second, item.first);
2786                 return;
2787             }
2788         }
2789         // Get the connection to which the memberId belongs
2790         auto getObjectsWithConnectionCb =
2791             [sensorAsyncResp,
2792              overrideMap](const std::set<std::string>& /*connections*/,
2793                           const std::set<std::pair<std::string, std::string>>&
2794                               objectsWithConnection) {
2795             if (objectsWithConnection.size() != overrideMap.size())
2796             {
2797                 BMCWEB_LOG_INFO
2798                     << "Unable to find all objects with proper connection "
2799                     << objectsWithConnection.size() << " requested "
2800                     << overrideMap.size() << "\n";
2801                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2802                                            sensorAsyncResp->chassisSubNode ==
2803                                                    sensors::node::thermal
2804                                                ? "Temperatures"
2805                                                : "Voltages",
2806                                            "Count");
2807                 return;
2808             }
2809             for (const auto& item : objectsWithConnection)
2810             {
2811                 sdbusplus::message::object_path path(item.first);
2812                 std::string sensorName = path.filename();
2813                 if (sensorName.empty())
2814                 {
2815                     messages::internalError(sensorAsyncResp->asyncResp->res);
2816                     return;
2817                 }
2818 
2819                 const auto& iterator = overrideMap.find(sensorName);
2820                 if (iterator == overrideMap.end())
2821                 {
2822                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2823                                     << item.first << "\n";
2824                     messages::internalError(sensorAsyncResp->asyncResp->res);
2825                     return;
2826                 }
2827                 crow::connections::systemBus->async_method_call(
2828                     [sensorAsyncResp](const boost::system::error_code ec) {
2829                     if (ec)
2830                     {
2831                         if (ec.value() ==
2832                             boost::system::errc::permission_denied)
2833                         {
2834                             BMCWEB_LOG_WARNING
2835                                 << "Manufacturing mode is not Enabled...can't "
2836                                    "Override the sensor value. ";
2837 
2838                             messages::insufficientPrivilege(
2839                                 sensorAsyncResp->asyncResp->res);
2840                             return;
2841                         }
2842                         BMCWEB_LOG_DEBUG
2843                             << "setOverrideValueStatus DBUS error: " << ec;
2844                         messages::internalError(
2845                             sensorAsyncResp->asyncResp->res);
2846                     }
2847                     },
2848                     item.second, item.first, "org.freedesktop.DBus.Properties",
2849                     "Set", "xyz.openbmc_project.Sensor.Value", "Value",
2850                     dbus::utility::DbusVariantType(iterator->second.first));
2851             }
2852         };
2853         // Get object with connection for the given sensor name
2854         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2855                                  std::move(getObjectsWithConnectionCb));
2856     };
2857     // get full sensor list for the given chassisId and cross verify the sensor.
2858     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
2859                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
2860                std::move(getChassisSensorListCb));
2861 }
2862 
2863 /**
2864  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2865  * path of the sensor.
2866  *
2867  * Function builds valid Redfish response for sensor query of given chassis and
2868  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2869  * it to caller in a callback.
2870  *
2871  * @param chassis   Chassis for which retrieval should be performed
2872  * @param node  Node (group) of sensors. See sensors::node for supported values
2873  * @param mapComplete   Callback to be called with retrieval result
2874  */
2875 inline void retrieveUriToDbusMap(const std::string& chassis,
2876                                  const std::string& node,
2877                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2878 {
2879     decltype(sensors::paths)::const_iterator pathIt =
2880         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
2881                      [&node](auto&& val) { return val.first == node; });
2882     if (pathIt == sensors::paths.cend())
2883     {
2884         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2885         mapComplete(boost::beast::http::status::bad_request, {});
2886         return;
2887     }
2888 
2889     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2890     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2891                         const boost::beast::http::status status,
2892                         const std::map<std::string, std::string>& uriToDbus) {
2893         mapCompleteCb(status, uriToDbus);
2894     };
2895 
2896     auto resp = std::make_shared<SensorsAsyncResp>(
2897         asyncResp, chassis, pathIt->second, node, std::move(callback));
2898     getChassisData(resp);
2899 }
2900 
2901 namespace sensors
2902 {
2903 
2904 inline void getChassisCallback(
2905     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2906     std::string_view chassisId, std::string_view chassisSubNode,
2907     const std::shared_ptr<std::set<std::string>>& sensorNames)
2908 {
2909     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2910 
2911     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2912     for (const std::string& sensor : *sensorNames)
2913     {
2914         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2915 
2916         sdbusplus::message::object_path path(sensor);
2917         std::string sensorName = path.filename();
2918         if (sensorName.empty())
2919         {
2920             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2921             messages::internalError(asyncResp->res);
2922             return;
2923         }
2924         std::string type = path.parent_path().filename();
2925         // fan_tach has an underscore in it, so remove it to "normalize" the
2926         // type in the URI
2927         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2928 
2929         nlohmann::json::object_t member;
2930         std::string id = type;
2931         id += "_";
2932         id += sensorName;
2933         member["@odata.id"] = crow::utility::urlFromPieces(
2934             "redfish", "v1", "Chassis", chassisId, chassisSubNode, id);
2935 
2936         entriesArray.push_back(std::move(member));
2937     }
2938 
2939     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2940     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2941 }
2942 
2943 inline void
2944     handleSensorCollectionGet(App& app, const crow::Request& req,
2945                               const std::shared_ptr<bmcweb::AsyncResp>& aResp,
2946                               const std::string& chassisId)
2947 {
2948     query_param::QueryCapabilities capabilities = {
2949         .canDelegateExpandLevel = 1,
2950     };
2951     query_param::Query delegatedQuery;
2952     if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp,
2953                                                   delegatedQuery, capabilities))
2954     {
2955         return;
2956     }
2957 
2958     if (delegatedQuery.expandType != query_param::ExpandType::None)
2959     {
2960         // we perform efficient expand.
2961         auto asyncResp = std::make_shared<SensorsAsyncResp>(
2962             aResp, chassisId, sensors::dbus::sensorPaths,
2963             sensors::node::sensors,
2964             /*efficientExpand=*/true);
2965         getChassisData(asyncResp);
2966 
2967         BMCWEB_LOG_DEBUG
2968             << "SensorCollection doGet exit via efficient expand handler";
2969         return;
2970     }
2971 
2972     // We get all sensors as hyperlinkes in the chassis (this
2973     // implies we reply on the default query parameters handler)
2974     getChassis(aResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2975                std::bind_front(sensors::getChassisCallback, aResp, chassisId,
2976                                sensors::node::sensors));
2977 }
2978 
2979 inline void
2980     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2981                       const std::string& sensorPath,
2982                       const ::dbus::utility::MapperGetObject& mapperResponse)
2983 {
2984     if (mapperResponse.size() != 1)
2985     {
2986         messages::internalError(asyncResp->res);
2987         return;
2988     }
2989     const auto& valueIface = *mapperResponse.begin();
2990     const std::string& connectionName = valueIface.first;
2991     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2992     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2993     crow::connections::systemBus->async_method_call(
2994         [asyncResp,
2995          sensorPath](const boost::system::error_code ec,
2996                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2997         if (ec)
2998         {
2999             messages::internalError(asyncResp->res);
3000             return;
3001         }
3002         sdbusplus::message::object_path path(sensorPath);
3003         std::string name = path.filename();
3004         path = path.parent_path();
3005         std::string type = path.filename();
3006         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
3007                                asyncResp->res.jsonValue, nullptr);
3008         },
3009         connectionName, sensorPath, "org.freedesktop.DBus.Properties", "GetAll",
3010         "");
3011 }
3012 
3013 inline void handleSensorGet(App& app, const crow::Request& req,
3014                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
3015                             const std::string& /*chassisId*/,
3016                             const std::string& sensorId)
3017 {
3018     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
3019     {
3020         return;
3021     }
3022     size_t index = sensorId.find('_');
3023     if (index == std::string::npos)
3024     {
3025         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
3026         return;
3027     }
3028     std::string sensorType = sensorId.substr(0, index);
3029     std::string sensorName = sensorId.substr(index + 1);
3030     // fan_pwm and fan_tach need special handling
3031     if (sensorType == "fantach" || sensorType == "fanpwm")
3032     {
3033         sensorType.insert(3, 1, '_');
3034     }
3035 
3036     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
3037 
3038     const std::array<const char*, 1> interfaces = {
3039         "xyz.openbmc_project.Sensor.Value"};
3040     std::string sensorPath =
3041         "/xyz/openbmc_project/sensors/" + sensorType + '/' + sensorName;
3042     // Get a list of all of the sensors that implement Sensor.Value
3043     // and get the path and service name associated with the sensor
3044     crow::connections::systemBus->async_method_call(
3045         [asyncResp, sensorPath,
3046          sensorName](const boost::system::error_code ec,
3047                      const ::dbus::utility::MapperGetObject& subtree) {
3048         BMCWEB_LOG_DEBUG << "respHandler1 enter";
3049         if (ec)
3050         {
3051             messages::internalError(asyncResp->res);
3052             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
3053                              << "Dbus error " << ec;
3054             return;
3055         }
3056         getSensorFromDbus(asyncResp, sensorPath, subtree);
3057         BMCWEB_LOG_DEBUG << "respHandler1 exit";
3058         },
3059         "xyz.openbmc_project.ObjectMapper",
3060         "/xyz/openbmc_project/object_mapper",
3061         "xyz.openbmc_project.ObjectMapper", "GetObject", sensorPath,
3062         interfaces);
3063 }
3064 
3065 } // namespace sensors
3066 
3067 inline void requestRoutesSensorCollection(App& app)
3068 {
3069     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
3070         .privileges(redfish::privileges::getSensorCollection)
3071         .methods(boost::beast::http::verb::get)(
3072             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
3073 }
3074 
3075 inline void requestRoutesSensor(App& app)
3076 {
3077     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
3078         .privileges(redfish::privileges::getSensor)
3079         .methods(boost::beast::http::verb::get)(
3080             std::bind_front(sensors::handleSensorGet, std::ref(app)));
3081 }
3082 
3083 } // namespace redfish
3084