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