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