xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 1516c21b27faf8dcf7c41e9b7253da97025a5f28)
108777fb0SLewanczyk, Dawid /*
208777fb0SLewanczyk, Dawid // Copyright (c) 2018 Intel Corporation
308777fb0SLewanczyk, Dawid //
408777fb0SLewanczyk, Dawid // Licensed under the Apache License, Version 2.0 (the "License");
508777fb0SLewanczyk, Dawid // you may not use this file except in compliance with the License.
608777fb0SLewanczyk, Dawid // You may obtain a copy of the License at
708777fb0SLewanczyk, Dawid //
808777fb0SLewanczyk, Dawid //      http://www.apache.org/licenses/LICENSE-2.0
908777fb0SLewanczyk, Dawid //
1008777fb0SLewanczyk, Dawid // Unless required by applicable law or agreed to in writing, software
1108777fb0SLewanczyk, Dawid // distributed under the License is distributed on an "AS IS" BASIS,
1208777fb0SLewanczyk, Dawid // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1308777fb0SLewanczyk, Dawid // See the License for the specific language governing permissions and
1408777fb0SLewanczyk, Dawid // limitations under the License.
1508777fb0SLewanczyk, Dawid */
1608777fb0SLewanczyk, Dawid #pragma once
1708777fb0SLewanczyk, Dawid 
183ccb3adbSEd Tanous #include "app.hpp"
193ccb3adbSEd Tanous #include "dbus_singleton.hpp"
207a1dbc48SGeorge Liu #include "dbus_utility.hpp"
21539d8c6bSEd Tanous #include "generated/enums/redundancy.hpp"
22aaf08ac7SMatt Simmering #include "generated/enums/resource.hpp"
230ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
24539d8c6bSEd Tanous #include "generated/enums/thermal.hpp"
253ccb3adbSEd Tanous #include "query.hpp"
263ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2750ebd4afSEd Tanous #include "str_utility.hpp"
283ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
293ccb3adbSEd Tanous #include "utils/json_utils.hpp"
303ccb3adbSEd Tanous #include "utils/query_param.hpp"
31*1516c21bSJanet Adkins #include "utils/sensor_utils.hpp"
320ec8b83dSEd Tanous 
33e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
34ef4c65b7SEd Tanous #include <boost/url/format.hpp>
351e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3686d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
371214b7e7SGunnar Mills 
387a1dbc48SGeorge Liu #include <array>
391214b7e7SGunnar Mills #include <cmath>
40fe04d49cSNan Zhou #include <iterator>
41283860f5SEd Tanous #include <limits>
42fe04d49cSNan Zhou #include <map>
433544d2a7SEd Tanous #include <ranges>
44fe04d49cSNan Zhou #include <set>
4518f8f608SEd Tanous #include <string>
467a1dbc48SGeorge Liu #include <string_view>
47b5a76932SEd Tanous #include <utility>
48abf2add6SEd Tanous #include <variant>
4908777fb0SLewanczyk, Dawid 
501abe55efSEd Tanous namespace redfish
511abe55efSEd Tanous {
5208777fb0SLewanczyk, Dawid 
53a0ec28b6SAdrian Ambrożewicz namespace sensors
54a0ec28b6SAdrian Ambrożewicz {
55a0ec28b6SAdrian Ambrożewicz namespace node
56a0ec28b6SAdrian Ambrożewicz {
57a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
58a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
59a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
60a0ec28b6SAdrian Ambrożewicz } // namespace node
61a0ec28b6SAdrian Ambrożewicz 
6202da7c5aSEd Tanous // clang-format off
63a0ec28b6SAdrian Ambrożewicz namespace dbus
64a0ec28b6SAdrian Ambrożewicz {
65cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6802da7c5aSEd Tanous });
69c2bf7f99SWludzik, Jozef 
7025b54dbaSEd Tanous constexpr auto getSensorPaths(){
7125b54dbaSEd Tanous     if constexpr(BMCWEB_REDFISH_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM){
7225b54dbaSEd Tanous     return std::to_array<std::string_view>({
7302da7c5aSEd Tanous         "/xyz/openbmc_project/sensors/power",
74a0ec28b6SAdrian Ambrożewicz         "/xyz/openbmc_project/sensors/current",
757088690cSBasheer Ahmed Muddebihal         "/xyz/openbmc_project/sensors/airflow",
765deabed9SGunnar Mills         "/xyz/openbmc_project/sensors/humidity",
77e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/voltage",
78e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_tach",
79e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/temperature",
80e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_pwm",
81e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/altitude",
82e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/energy",
8325b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
8425b54dbaSEd Tanous     } else {
8525b54dbaSEd Tanous       return  std::to_array<std::string_view>({"/xyz/openbmc_project/sensors/power",
8625b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/current",
8725b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/airflow",
8825b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/humidity",
8925b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
9025b54dbaSEd Tanous }
9125b54dbaSEd Tanous }
9225b54dbaSEd Tanous 
9325b54dbaSEd Tanous constexpr auto sensorPaths = getSensorPaths();
9402da7c5aSEd Tanous 
95cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
9602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
97a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
9802da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
9902da7c5aSEd Tanous });
10002da7c5aSEd Tanous 
101c2bf7f99SWludzik, Jozef } // namespace dbus
10202da7c5aSEd Tanous // clang-format on
10302da7c5aSEd Tanous 
104cf9e417dSEd Tanous using sensorPair =
105cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
10602da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
107cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
108cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
109cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
110c2bf7f99SWludzik, Jozef 
1110ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
112c2bf7f99SWludzik, Jozef {
113c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
114c2bf7f99SWludzik, Jozef     {
1150ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
116c2bf7f99SWludzik, Jozef     }
117c2bf7f99SWludzik, Jozef     if (sensorType == "power")
118c2bf7f99SWludzik, Jozef     {
1190ec8b83dSEd Tanous         return sensor::ReadingType::Power;
120c2bf7f99SWludzik, Jozef     }
121c2bf7f99SWludzik, Jozef     if (sensorType == "current")
122c2bf7f99SWludzik, Jozef     {
1230ec8b83dSEd Tanous         return sensor::ReadingType::Current;
124c2bf7f99SWludzik, Jozef     }
125c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
126c2bf7f99SWludzik, Jozef     {
1270ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
128c2bf7f99SWludzik, Jozef     }
129c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
130c2bf7f99SWludzik, Jozef     {
1310ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
132c2bf7f99SWludzik, Jozef     }
133c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
134c2bf7f99SWludzik, Jozef     {
1350ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
136c2bf7f99SWludzik, Jozef     }
1375deabed9SGunnar Mills     if (sensorType == "humidity")
1385deabed9SGunnar Mills     {
1390ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1405deabed9SGunnar Mills     }
141c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
142c2bf7f99SWludzik, Jozef     {
1430ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
144c2bf7f99SWludzik, Jozef     }
145c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
146c2bf7f99SWludzik, Jozef     {
1470ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
148c2bf7f99SWludzik, Jozef     }
149c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
150c2bf7f99SWludzik, Jozef     {
1510ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
152c2bf7f99SWludzik, Jozef     }
1530ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
154c2bf7f99SWludzik, Jozef }
155c2bf7f99SWludzik, Jozef 
1561d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
157c2bf7f99SWludzik, Jozef {
158c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
159c2bf7f99SWludzik, Jozef     {
160c2bf7f99SWludzik, Jozef         return "V";
161c2bf7f99SWludzik, Jozef     }
162c2bf7f99SWludzik, Jozef     if (sensorType == "power")
163c2bf7f99SWludzik, Jozef     {
164c2bf7f99SWludzik, Jozef         return "W";
165c2bf7f99SWludzik, Jozef     }
166c2bf7f99SWludzik, Jozef     if (sensorType == "current")
167c2bf7f99SWludzik, Jozef     {
168c2bf7f99SWludzik, Jozef         return "A";
169c2bf7f99SWludzik, Jozef     }
170c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
171c2bf7f99SWludzik, Jozef     {
172c2bf7f99SWludzik, Jozef         return "RPM";
173c2bf7f99SWludzik, Jozef     }
174c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
175c2bf7f99SWludzik, Jozef     {
176c2bf7f99SWludzik, Jozef         return "Cel";
177c2bf7f99SWludzik, Jozef     }
1785deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1795deabed9SGunnar Mills         sensorType == "humidity")
180c2bf7f99SWludzik, Jozef     {
181c2bf7f99SWludzik, Jozef         return "%";
182c2bf7f99SWludzik, Jozef     }
183c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
184c2bf7f99SWludzik, Jozef     {
185c2bf7f99SWludzik, Jozef         return "m";
186c2bf7f99SWludzik, Jozef     }
187c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
188c2bf7f99SWludzik, Jozef     {
189c2bf7f99SWludzik, Jozef         return "cft_i/min";
190c2bf7f99SWludzik, Jozef     }
191c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
192c2bf7f99SWludzik, Jozef     {
193c2bf7f99SWludzik, Jozef         return "J";
194c2bf7f99SWludzik, Jozef     }
195c2bf7f99SWludzik, Jozef     return "";
196a0ec28b6SAdrian Ambrożewicz }
197a0ec28b6SAdrian Ambrożewicz } // namespace sensors
198a0ec28b6SAdrian Ambrożewicz 
19908777fb0SLewanczyk, Dawid /**
200588c3f0dSKowalski, Kamil  * SensorsAsyncResp
20108777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
20208777fb0SLewanczyk, Dawid  */
2031abe55efSEd Tanous class SensorsAsyncResp
2041abe55efSEd Tanous {
20508777fb0SLewanczyk, Dawid   public:
206a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
207a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
208fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
209a0ec28b6SAdrian Ambrożewicz 
210a0ec28b6SAdrian Ambrożewicz     struct SensorData
211a0ec28b6SAdrian Ambrożewicz     {
212a0ec28b6SAdrian Ambrożewicz         const std::string name;
213a0ec28b6SAdrian Ambrożewicz         std::string uri;
214a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
215a0ec28b6SAdrian Ambrożewicz     };
216a0ec28b6SAdrian Ambrożewicz 
2178a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2188d1b46d7Szhanghch05                      const std::string& chassisIdIn,
219cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22002da7c5aSEd Tanous                      std::string_view subNode) :
221bd79bce8SPatrick Williams         asyncResp(asyncRespIn), chassisId(chassisIdIn), types(typesIn),
222bd79bce8SPatrick Williams         chassisSubNode(subNode), efficientExpand(false)
2231214b7e7SGunnar Mills     {}
22408777fb0SLewanczyk, Dawid 
225a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2268a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2278d1b46d7Szhanghch05                      const std::string& chassisIdIn,
228cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22902da7c5aSEd Tanous                      std::string_view subNode,
230a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
231bd79bce8SPatrick Williams         asyncResp(asyncRespIn), chassisId(chassisIdIn), types(typesIn),
232bd79bce8SPatrick Williams         chassisSubNode(subNode), efficientExpand(false),
233bd79bce8SPatrick Williams         metadata{std::vector<SensorData>()},
234a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
235a0ec28b6SAdrian Ambrożewicz     {}
236a0ec28b6SAdrian Ambrożewicz 
237928fefb9SNan Zhou     // sensor collections expand
2388a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
239928fefb9SNan Zhou                      const std::string& chassisIdIn,
240cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2418a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
242bd79bce8SPatrick Williams         asyncResp(asyncRespIn), chassisId(chassisIdIn), types(typesIn),
243bd79bce8SPatrick Williams         chassisSubNode(subNode), efficientExpand(efficientExpandIn)
244928fefb9SNan Zhou     {}
245928fefb9SNan Zhou 
2461abe55efSEd Tanous     ~SensorsAsyncResp()
2471abe55efSEd Tanous     {
2488d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2498d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2501abe55efSEd Tanous         {
2511abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2521abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2531abe55efSEd Tanous             // proper code
2548d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
25508777fb0SLewanczyk, Dawid         }
256a0ec28b6SAdrian Ambrożewicz 
257a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
258a0ec28b6SAdrian Ambrożewicz         {
259fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2608d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
261a0ec28b6SAdrian Ambrożewicz             {
262a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
263a0ec28b6SAdrian Ambrożewicz                 {
264c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
265a0ec28b6SAdrian Ambrożewicz                 }
266a0ec28b6SAdrian Ambrożewicz             }
2678d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
268a0ec28b6SAdrian Ambrożewicz         }
26908777fb0SLewanczyk, Dawid     }
270588c3f0dSKowalski, Kamil 
271ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
272ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
273ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
274ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
275ecd6a3a2SEd Tanous 
276a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
277c1d019a6SEd Tanous                      const std::string& dbusPath)
278a0ec28b6SAdrian Ambrożewicz     {
279a0ec28b6SAdrian Ambrożewicz         if (metadata)
280a0ec28b6SAdrian Ambrożewicz         {
281c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
282c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
283a0ec28b6SAdrian Ambrożewicz         }
284a0ec28b6SAdrian Ambrożewicz     }
285a0ec28b6SAdrian Ambrożewicz 
286a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
287a0ec28b6SAdrian Ambrożewicz     {
288a0ec28b6SAdrian Ambrożewicz         if (metadata)
289a0ec28b6SAdrian Ambrożewicz         {
290a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
291a0ec28b6SAdrian Ambrożewicz             {
292a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
293a0ec28b6SAdrian Ambrożewicz                 {
294a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
295a0ec28b6SAdrian Ambrożewicz                 }
296a0ec28b6SAdrian Ambrożewicz             }
297a0ec28b6SAdrian Ambrożewicz         }
298a0ec28b6SAdrian Ambrożewicz     }
299a0ec28b6SAdrian Ambrożewicz 
3008d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
301a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
302cf9e417dSEd Tanous     const std::span<const std::string_view> types;
303a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
304928fefb9SNan Zhou     const bool efficientExpand;
305a0ec28b6SAdrian Ambrożewicz 
306a0ec28b6SAdrian Ambrożewicz   private:
307a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
308a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
30908777fb0SLewanczyk, Dawid };
31008777fb0SLewanczyk, Dawid 
31108777fb0SLewanczyk, Dawid /**
312d500549bSAnthony Wilson  * Possible states for physical inventory leds
313d500549bSAnthony Wilson  */
314d500549bSAnthony Wilson enum class LedState
315d500549bSAnthony Wilson {
316d500549bSAnthony Wilson     OFF,
317d500549bSAnthony Wilson     ON,
318d500549bSAnthony Wilson     BLINK,
319d500549bSAnthony Wilson     UNKNOWN
320d500549bSAnthony Wilson };
321d500549bSAnthony Wilson 
322d500549bSAnthony Wilson /**
323adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
324adc4f0dbSShawn McCarney  */
325adc4f0dbSShawn McCarney class InventoryItem
326adc4f0dbSShawn McCarney {
327adc4f0dbSShawn McCarney   public:
3284e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
329adc4f0dbSShawn McCarney     {
330adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
33128aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
33228aa8de5SGeorge Liu         name = path.filename();
33328aa8de5SGeorge Liu         if (name.empty())
334adc4f0dbSShawn McCarney         {
33562598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
336adc4f0dbSShawn McCarney         }
337adc4f0dbSShawn McCarney     }
338adc4f0dbSShawn McCarney 
339adc4f0dbSShawn McCarney     std::string objectPath;
340adc4f0dbSShawn McCarney     std::string name;
341e05aec50SEd Tanous     bool isPresent = true;
342e05aec50SEd Tanous     bool isFunctional = true;
343e05aec50SEd Tanous     bool isPowerSupply = false;
344e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
345adc4f0dbSShawn McCarney     std::string manufacturer;
346adc4f0dbSShawn McCarney     std::string model;
347adc4f0dbSShawn McCarney     std::string partNumber;
348adc4f0dbSShawn McCarney     std::string serialNumber;
349adc4f0dbSShawn McCarney     std::set<std::string> sensors;
350d500549bSAnthony Wilson     std::string ledObjectPath;
351e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
352adc4f0dbSShawn McCarney };
353adc4f0dbSShawn McCarney 
354adc4f0dbSShawn McCarney /**
355413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
356588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
35708777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
35808777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
35908777fb0SLewanczyk, Dawid  */
36008777fb0SLewanczyk, Dawid template <typename Callback>
361413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
36281ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
363fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3641abe55efSEd Tanous     Callback&& callback)
3651abe55efSEd Tanous {
36662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
36703b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
368e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
36908777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
37008777fb0SLewanczyk, Dawid 
371e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
372e99073f5SGeorge Liu     dbus::utility::getSubTree(
373e99073f5SGeorge Liu         path, 2, interfaces,
3748cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
375e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
376002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
377e99073f5SGeorge Liu             // Response handler for parsing objects subtree
37862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3791abe55efSEd Tanous             if (ec)
3801abe55efSEd Tanous             {
3818d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
38262598e31SEd Tanous                 BMCWEB_LOG_ERROR(
38362598e31SEd Tanous                     "getObjectsWithConnection resp_handler: Dbus error {}", ec);
38408777fb0SLewanczyk, Dawid                 return;
38508777fb0SLewanczyk, Dawid             }
38608777fb0SLewanczyk, Dawid 
38762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
38808777fb0SLewanczyk, Dawid 
389bd79bce8SPatrick Williams             // Make unique list of connections only for requested sensor types
390bd79bce8SPatrick Williams             // and found in the chassis
391fe04d49cSNan Zhou             std::set<std::string> connections;
392413961deSRichard Marian Thomaiyar             std::set<std::pair<std::string, std::string>> objectsWithConnection;
39308777fb0SLewanczyk, Dawid 
39462598e31SEd Tanous             BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
39549c53ac9SJohnathan Mantey             for (const std::string& tsensor : *sensorNames)
3961abe55efSEd Tanous             {
39762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
39808777fb0SLewanczyk, Dawid             }
39908777fb0SLewanczyk, Dawid 
400bd79bce8SPatrick Williams             for (const std::pair<std::string,
401bd79bce8SPatrick Williams                                  std::vector<std::pair<
402bd79bce8SPatrick Williams                                      std::string, std::vector<std::string>>>>&
4031abe55efSEd Tanous                      object : subtree)
4041abe55efSEd Tanous             {
40549c53ac9SJohnathan Mantey                 if (sensorNames->find(object.first) != sensorNames->end())
4061abe55efSEd Tanous                 {
40749c53ac9SJohnathan Mantey                     for (const std::pair<std::string, std::vector<std::string>>&
4081abe55efSEd Tanous                              objData : object.second)
4091abe55efSEd Tanous                     {
410bd79bce8SPatrick Williams                         BMCWEB_LOG_DEBUG("Adding connection: {}",
411bd79bce8SPatrick Williams                                          objData.first);
41208777fb0SLewanczyk, Dawid                         connections.insert(objData.first);
413de629b6eSShawn McCarney                         objectsWithConnection.insert(
414de629b6eSShawn McCarney                             std::make_pair(object.first, objData.first));
41508777fb0SLewanczyk, Dawid                     }
41608777fb0SLewanczyk, Dawid                 }
41708777fb0SLewanczyk, Dawid             }
41862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
419413961deSRichard Marian Thomaiyar             callback(std::move(connections), std::move(objectsWithConnection));
42062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
421e99073f5SGeorge Liu         });
42262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
423413961deSRichard Marian Thomaiyar }
424413961deSRichard Marian Thomaiyar 
425413961deSRichard Marian Thomaiyar /**
426413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
427413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
428413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
429413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
430413961deSRichard Marian Thomaiyar  */
431413961deSRichard Marian Thomaiyar template <typename Callback>
432fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
433fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
434413961deSRichard Marian Thomaiyar                     Callback&& callback)
435413961deSRichard Marian Thomaiyar {
436413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
4378cb2c024SEd Tanous         [callback = std::forward<Callback>(callback)](
4388cb2c024SEd Tanous             const std::set<std::string>& connections,
439413961deSRichard Marian Thomaiyar             const std::set<std::pair<std::string, std::string>>&
4403174e4dfSEd Tanous             /*objectsWithConnection*/) { callback(connections); };
44181ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
442413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
44308777fb0SLewanczyk, Dawid }
44408777fb0SLewanczyk, Dawid 
44508777fb0SLewanczyk, Dawid /**
44649c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
44749c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
44849c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
44949c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
45049c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
45149c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
45249c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
45349c53ac9SJohnathan Mantey  */
45423a21a1cSEd Tanous inline void reduceSensorList(
4557f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
456cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
45749c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
458fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
45949c53ac9SJohnathan Mantey {
46049c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
46149c53ac9SJohnathan Mantey     {
4627f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4637f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
464a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
46549c53ac9SJohnathan Mantey                                        : "Voltages");
46649c53ac9SJohnathan Mantey 
46749c53ac9SJohnathan Mantey         return;
46849c53ac9SJohnathan Mantey     }
46949c53ac9SJohnathan Mantey     if (allSensors->empty())
47049c53ac9SJohnathan Mantey     {
47149c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
47249c53ac9SJohnathan Mantey         return;
47349c53ac9SJohnathan Mantey     }
47449c53ac9SJohnathan Mantey 
4757f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
47649c53ac9SJohnathan Mantey     {
47749c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
47849c53ac9SJohnathan Mantey         {
47911ba3979SEd Tanous             if (sensor.starts_with(type))
48049c53ac9SJohnathan Mantey             {
48149c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
48249c53ac9SJohnathan Mantey             }
48349c53ac9SJohnathan Mantey         }
48449c53ac9SJohnathan Mantey     }
48549c53ac9SJohnathan Mantey }
48649c53ac9SJohnathan Mantey 
4877f1cc26dSEd Tanous /*
4887f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4897f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4907f1cc26dSEd Tanous  *
4917f1cc26dSEd Tanous  * */
4927f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4937f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4947f1cc26dSEd Tanous {
4957f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4967f1cc26dSEd Tanous     {
4977f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4987f1cc26dSEd Tanous     }
4997f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
5007f1cc26dSEd Tanous     {
5017f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
5027f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
5037f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
5047f1cc26dSEd Tanous     }
5057f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
5067f1cc26dSEd Tanous     {
5077f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
5087f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
5097f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
5107f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5117f1cc26dSEd Tanous     }
5127f1cc26dSEd Tanous 
5137f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5147f1cc26dSEd Tanous     {
5157f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5167f1cc26dSEd Tanous     }
5177f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5187f1cc26dSEd Tanous }
5197f1cc26dSEd Tanous 
52049c53ac9SJohnathan Mantey /**
52108777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
522588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
52308777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
52408777fb0SLewanczyk, Dawid  */
52508777fb0SLewanczyk, Dawid template <typename Callback>
5267f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5277f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
528cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
529cf9e417dSEd Tanous                 Callback&& callback)
5301abe55efSEd Tanous {
53162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5327a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
53349c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
534adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5357a1dbc48SGeorge Liu 
5367a1dbc48SGeorge Liu     // Get the Chassis Collection
5377a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5387a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5398cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), asyncResp,
5407f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5417f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5427a1dbc48SGeorge Liu             const boost::system::error_code& ec,
543002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
54462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5451abe55efSEd Tanous             if (ec)
5461abe55efSEd Tanous             {
54762598e31SEd Tanous                 BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5487f1cc26dSEd Tanous                 messages::internalError(asyncResp->res);
54908777fb0SLewanczyk, Dawid                 return;
55008777fb0SLewanczyk, Dawid             }
55149c53ac9SJohnathan Mantey             const std::string* chassisPath = nullptr;
55249c53ac9SJohnathan Mantey             for (const std::string& chassis : chassisPaths)
5531abe55efSEd Tanous             {
55428aa8de5SGeorge Liu                 sdbusplus::message::object_path path(chassis);
555f8fe53e7SEd Tanous                 std::string chassisName = path.filename();
55628aa8de5SGeorge Liu                 if (chassisName.empty())
5571abe55efSEd Tanous                 {
55862598e31SEd Tanous                     BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
559daf36e2eSEd Tanous                     continue;
560daf36e2eSEd Tanous                 }
5617f1cc26dSEd Tanous                 if (chassisName == chassisIdStr)
5621abe55efSEd Tanous                 {
56349c53ac9SJohnathan Mantey                     chassisPath = &chassis;
56449c53ac9SJohnathan Mantey                     break;
565daf36e2eSEd Tanous                 }
56649c53ac9SJohnathan Mantey             }
56749c53ac9SJohnathan Mantey             if (chassisPath == nullptr)
5681abe55efSEd Tanous             {
569bd79bce8SPatrick Williams                 messages::resourceNotFound(asyncResp->res, "Chassis",
570bd79bce8SPatrick Williams                                            chassisIdStr);
57149c53ac9SJohnathan Mantey                 return;
5721abe55efSEd Tanous             }
5737f1cc26dSEd Tanous             populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
57408777fb0SLewanczyk, Dawid 
575ef4c65b7SEd Tanous             asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
576ef4c65b7SEd Tanous                 "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
57795a3ecadSAnthony Wilson 
5788fb49dd6SShawn McCarney             // Get the list of all sensors for this Chassis element
5798fb49dd6SShawn McCarney             std::string sensorPath = *chassisPath + "/all_sensors";
5806c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
5816c3e9451SGeorge Liu                 sensorPath,
5827f1cc26dSEd Tanous                 [asyncResp, chassisSubNode, sensorTypes,
5838cb2c024SEd Tanous                  callback = std::forward<const Callback>(callback)](
5848b24275dSEd Tanous                     const boost::system::error_code& ec2,
5856c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& nodeSensorList) {
5868b24275dSEd Tanous                     if (ec2)
58749c53ac9SJohnathan Mantey                     {
5888b24275dSEd Tanous                         if (ec2.value() != EBADR)
58949c53ac9SJohnathan Mantey                         {
5907f1cc26dSEd Tanous                             messages::internalError(asyncResp->res);
59149c53ac9SJohnathan Mantey                             return;
59249c53ac9SJohnathan Mantey                         }
59349c53ac9SJohnathan Mantey                     }
594bd79bce8SPatrick Williams                     const std::shared_ptr<std::set<std::string>>
595bd79bce8SPatrick Williams                         culledSensorList =
596fe04d49cSNan Zhou                             std::make_shared<std::set<std::string>>();
597bd79bce8SPatrick Williams                     reduceSensorList(asyncResp->res, chassisSubNode,
598bd79bce8SPatrick Williams                                      sensorTypes, &nodeSensorList,
599bd79bce8SPatrick Williams                                      culledSensorList);
600bd79bce8SPatrick Williams                     BMCWEB_LOG_DEBUG("Finishing with {}",
601bd79bce8SPatrick Williams                                      culledSensorList->size());
60249c53ac9SJohnathan Mantey                     callback(culledSensorList);
6031e1e598dSJonathan Doman                 });
6047a1dbc48SGeorge Liu         });
60562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
60608777fb0SLewanczyk, Dawid }
60708777fb0SLewanczyk, Dawid 
60808777fb0SLewanczyk, Dawid /**
609adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
610adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
611aaf08ac7SMatt Simmering  * @param sensorAvailable Boolean representing if D-Bus sensor is marked as
612aaf08ac7SMatt Simmering  * available.
613adc4f0dbSShawn McCarney  * @return State value for inventory item.
61434dd179eSJames Feist  */
615aaf08ac7SMatt Simmering inline resource::State getState(const InventoryItem* inventoryItem,
616aaf08ac7SMatt Simmering                                 const bool sensorAvailable)
617adc4f0dbSShawn McCarney {
618adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
619adc4f0dbSShawn McCarney     {
620aaf08ac7SMatt Simmering         return resource::State::Absent;
621adc4f0dbSShawn McCarney     }
62234dd179eSJames Feist 
623aaf08ac7SMatt Simmering     if (!sensorAvailable)
624aaf08ac7SMatt Simmering     {
625aaf08ac7SMatt Simmering         return resource::State::UnavailableOffline;
626aaf08ac7SMatt Simmering     }
627aaf08ac7SMatt Simmering 
628aaf08ac7SMatt Simmering     return resource::State::Enabled;
629adc4f0dbSShawn McCarney }
630adc4f0dbSShawn McCarney 
631adc4f0dbSShawn McCarney /**
632adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
633adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6341d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
635adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
636adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
637adc4f0dbSShawn McCarney  * @return Health value for sensor.
638adc4f0dbSShawn McCarney  */
6391d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6401d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
641adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
64234dd179eSJames Feist {
643adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
644adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
645adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
646adc4f0dbSShawn McCarney     std::string currentHealth;
647adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
648adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
649adc4f0dbSShawn McCarney     {
650adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
651adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
652adc4f0dbSShawn McCarney         {
653adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
654adc4f0dbSShawn McCarney             if (health != nullptr)
655adc4f0dbSShawn McCarney             {
656adc4f0dbSShawn McCarney                 currentHealth = *health;
657adc4f0dbSShawn McCarney             }
658adc4f0dbSShawn McCarney         }
659adc4f0dbSShawn McCarney     }
660adc4f0dbSShawn McCarney 
661adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
662adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
663adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
664adc4f0dbSShawn McCarney     {
665adc4f0dbSShawn McCarney         return "Critical";
666adc4f0dbSShawn McCarney     }
667adc4f0dbSShawn McCarney 
668c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
669c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
670c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
671c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
672711ac7a9SEd Tanous 
673c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
674c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
675c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
676c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
677c1343bf6SKrzysztof Grobelny         warningAlarmLow);
678c1343bf6SKrzysztof Grobelny 
679c1343bf6SKrzysztof Grobelny     if (success)
68034dd179eSJames Feist     {
681c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
682c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
683c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
68434dd179eSJames Feist         {
68534dd179eSJames Feist             return "Critical";
68634dd179eSJames Feist         }
68734dd179eSJames Feist     }
68834dd179eSJames Feist 
689adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
690adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
691adc4f0dbSShawn McCarney     {
692adc4f0dbSShawn McCarney         return "Critical";
693adc4f0dbSShawn McCarney     }
694adc4f0dbSShawn McCarney 
695adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
696adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
697adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
698adc4f0dbSShawn McCarney     {
699adc4f0dbSShawn McCarney         return "Warning";
700adc4f0dbSShawn McCarney     }
701adc4f0dbSShawn McCarney 
702c1343bf6SKrzysztof Grobelny     if (success)
703c1343bf6SKrzysztof Grobelny     {
704adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
705c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
706c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
70734dd179eSJames Feist         {
708ebe4d91eSEd Tanous             return "Warning";
70934dd179eSJames Feist         }
71034dd179eSJames Feist     }
711adc4f0dbSShawn McCarney 
71234dd179eSJames Feist     return "OK";
71334dd179eSJames Feist }
71434dd179eSJames Feist 
71523a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
716d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
717d500549bSAnthony Wilson {
718d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
719d500549bSAnthony Wilson     {
720d500549bSAnthony Wilson         switch (inventoryItem->ledState)
721d500549bSAnthony Wilson         {
722d500549bSAnthony Wilson             case LedState::OFF:
723539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Off;
724d500549bSAnthony Wilson                 break;
725d500549bSAnthony Wilson             case LedState::ON:
726539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Lit;
727d500549bSAnthony Wilson                 break;
728d500549bSAnthony Wilson             case LedState::BLINK:
729539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Blinking;
730d500549bSAnthony Wilson                 break;
7314da0490bSEd Tanous             default:
732d500549bSAnthony Wilson                 break;
733d500549bSAnthony Wilson         }
734d500549bSAnthony Wilson     }
735d500549bSAnthony Wilson }
736d500549bSAnthony Wilson 
73734dd179eSJames Feist /**
73808777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
73908777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
740274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
74108777fb0SLewanczyk, Dawid  * build
7428ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
7431d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7441d7c0054SEd Tanous  * from.
7451d7c0054SEd Tanous  * @param sensorJson  The json object to fill
746adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
747adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
74808777fb0SLewanczyk, Dawid  */
7491d7c0054SEd Tanous inline void objectPropertiesToJson(
7501d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7511d7c0054SEd Tanous     std::string_view chassisSubNode,
7521d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
75381ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7541abe55efSEd Tanous {
7551d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
756adc4f0dbSShawn McCarney     {
757*1516c21bSJanet Adkins         std::string subNodeEscaped =
758*1516c21bSJanet Adkins             redfish::sensor_utils::getSensorId(sensorName, sensorType);
759c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
760c1d019a6SEd Tanous         // including power sensors.
761c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
762c1d019a6SEd Tanous 
7631d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7641d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7651d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
76695a3ecadSAnthony Wilson     }
76795a3ecadSAnthony Wilson     else if (sensorType != "power")
76895a3ecadSAnthony Wilson     {
76995a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
77095a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
77195a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7721d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7731d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7741d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
775adc4f0dbSShawn McCarney     }
776e742b6ccSEd Tanous 
777aaf08ac7SMatt Simmering     const bool* checkAvailable = nullptr;
778aaf08ac7SMatt Simmering     bool available = true;
779aaf08ac7SMatt Simmering     const bool success = sdbusplus::unpackPropertiesNoThrow(
780aaf08ac7SMatt Simmering         dbus_utils::UnpackErrorPrinter(), propertiesDict, "Available",
781aaf08ac7SMatt Simmering         checkAvailable);
782aaf08ac7SMatt Simmering     if (!success)
783aaf08ac7SMatt Simmering     {
784aaf08ac7SMatt Simmering         messages::internalError();
785aaf08ac7SMatt Simmering     }
786aaf08ac7SMatt Simmering     if (checkAvailable != nullptr)
787aaf08ac7SMatt Simmering     {
788aaf08ac7SMatt Simmering         available = *checkAvailable;
789aaf08ac7SMatt Simmering     }
790aaf08ac7SMatt Simmering 
791aaf08ac7SMatt Simmering     sensorJson["Status"]["State"] = getState(inventoryItem, available);
792bd79bce8SPatrick Williams     sensorJson["Status"]["Health"] =
793bd79bce8SPatrick Williams         getHealth(sensorJson, propertiesDict, inventoryItem);
79408777fb0SLewanczyk, Dawid 
79508777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
79608777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
79708777fb0SLewanczyk, Dawid     // that require integers, not floats.
79808777fb0SLewanczyk, Dawid     bool forceToInt = false;
79908777fb0SLewanczyk, Dawid 
8003929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
8011d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
80295a3ecadSAnthony Wilson     {
8032a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
804c2bf7f99SWludzik, Jozef 
8050ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
8060ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
80795a3ecadSAnthony Wilson         {
80862598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
80962598e31SEd Tanous                              sensorType);
81095a3ecadSAnthony Wilson         }
811c2bf7f99SWludzik, Jozef         else
81295a3ecadSAnthony Wilson         {
813c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
81495a3ecadSAnthony Wilson         }
815c2bf7f99SWludzik, Jozef 
8161d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
817c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
818f8ede15eSAdrian Ambrożewicz         {
81962598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
82062598e31SEd Tanous                              sensorType);
821c2bf7f99SWludzik, Jozef         }
822c2bf7f99SWludzik, Jozef         else
823c2bf7f99SWludzik, Jozef         {
824c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
825f8ede15eSAdrian Ambrożewicz         }
82695a3ecadSAnthony Wilson     }
82795a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8281abe55efSEd Tanous     {
8293929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
83081ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
83108777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
83208777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8331abe55efSEd Tanous     }
8341abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8351abe55efSEd Tanous     {
8363929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
837539d8c6bSEd Tanous         sensorJson["ReadingUnits"] = thermal::ReadingUnits::RPM;
83881ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
83981ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
84008777fb0SLewanczyk, Dawid         forceToInt = true;
8411abe55efSEd Tanous     }
8426f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8436f6d0d32SEd Tanous     {
8443929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
845539d8c6bSEd Tanous         sensorJson["ReadingUnits"] = thermal::ReadingUnits::Percent;
84681ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
84781ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8486f6d0d32SEd Tanous         forceToInt = true;
8496f6d0d32SEd Tanous     }
8501abe55efSEd Tanous     else if (sensorType == "voltage")
8511abe55efSEd Tanous     {
8523929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
85381ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8541abe55efSEd Tanous     }
8552474adfaSEd Tanous     else if (sensorType == "power")
8562474adfaSEd Tanous     {
85718f8f608SEd Tanous         std::string lower;
85818f8f608SEd Tanous         std::ranges::transform(sensorName, std::back_inserter(lower),
85918f8f608SEd Tanous                                bmcweb::asciiToLower);
86018f8f608SEd Tanous         if (lower == "total_power")
861028f7ebcSEddie James         {
86281ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8637ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8647ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
86581ce609eSEd Tanous             sensorJson["MemberId"] = "0";
86681ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8673929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
868028f7ebcSEddie James         }
86918f8f608SEd Tanous         else if (lower.find("input") != std::string::npos)
87049c53ac9SJohnathan Mantey         {
8713929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
87249c53ac9SJohnathan Mantey         }
87349c53ac9SJohnathan Mantey         else
87449c53ac9SJohnathan Mantey         {
8753929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
87649c53ac9SJohnathan Mantey         }
8772474adfaSEd Tanous     }
8781abe55efSEd Tanous     else
8791abe55efSEd Tanous     {
88062598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
88108777fb0SLewanczyk, Dawid         return;
88208777fb0SLewanczyk, Dawid     }
88308777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8843929aca1SAnthony Wilson     std::vector<
8853929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8863929aca1SAnthony Wilson         properties;
88708777fb0SLewanczyk, Dawid     properties.reserve(7);
88808777fb0SLewanczyk, Dawid 
88908777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
890de629b6eSShawn McCarney 
8911d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8923929aca1SAnthony Wilson     {
8933929aca1SAnthony Wilson         properties.emplace_back(
8943929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8953929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8963929aca1SAnthony Wilson         properties.emplace_back(
8973929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8983929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8993929aca1SAnthony Wilson         properties.emplace_back(
9003929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
9013929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
9023929aca1SAnthony Wilson         properties.emplace_back(
9033929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
9043929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
9053929aca1SAnthony Wilson     }
9063929aca1SAnthony Wilson     else if (sensorType != "power")
907de629b6eSShawn McCarney     {
90808777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9093929aca1SAnthony Wilson                                 "WarningHigh",
9103929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
91108777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9123929aca1SAnthony Wilson                                 "WarningLow",
9133929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
91408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9153929aca1SAnthony Wilson                                 "CriticalHigh",
9163929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
91708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9183929aca1SAnthony Wilson                                 "CriticalLow",
9193929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
920de629b6eSShawn McCarney     }
92108777fb0SLewanczyk, Dawid 
9222474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
9232474adfaSEd Tanous 
9241d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
92595a3ecadSAnthony Wilson     {
92695a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9273929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
92895a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9293929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
93051c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
93151c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
93295a3ecadSAnthony Wilson     }
93395a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9341abe55efSEd Tanous     {
93508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9363929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
93708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9383929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9391abe55efSEd Tanous     }
940adc4f0dbSShawn McCarney     else if (sensorType != "power")
9411abe55efSEd Tanous     {
94208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9433929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
94408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9453929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
94608777fb0SLewanczyk, Dawid     }
94708777fb0SLewanczyk, Dawid 
9483929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9493929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9501abe55efSEd Tanous     {
9511d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
952711ac7a9SEd Tanous         {
953711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
954711ac7a9SEd Tanous             {
955711ac7a9SEd Tanous                 continue;
956711ac7a9SEd Tanous             }
9573929aca1SAnthony Wilson 
9583929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9593929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9603929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9613929aca1SAnthony Wilson 
962abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
96340e4f380SEd Tanous             if (doubleValue == nullptr)
9641abe55efSEd Tanous             {
96562598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9666f6d0d32SEd Tanous                 continue;
96708777fb0SLewanczyk, Dawid             }
968283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
969283860f5SEd Tanous             {
970283860f5SEd Tanous                 if (valueName == "Value")
971283860f5SEd Tanous                 {
972283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
973283860f5SEd Tanous                     // them to null in the json response.
974283860f5SEd Tanous                     sensorJson[key] = nullptr;
975283860f5SEd Tanous                     continue;
976283860f5SEd Tanous                 }
97762598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
97862598e31SEd Tanous                                    valueName, *doubleValue);
979283860f5SEd Tanous                 continue;
980283860f5SEd Tanous             }
9816f6d0d32SEd Tanous             if (forceToInt)
9826f6d0d32SEd Tanous             {
98340e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9846f6d0d32SEd Tanous             }
9856f6d0d32SEd Tanous             else
9866f6d0d32SEd Tanous             {
98740e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
98808777fb0SLewanczyk, Dawid             }
98908777fb0SLewanczyk, Dawid         }
99008777fb0SLewanczyk, Dawid     }
99108777fb0SLewanczyk, Dawid }
99208777fb0SLewanczyk, Dawid 
9931d7c0054SEd Tanous /**
9941d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9951d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9961d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9971d7c0054SEd Tanous  * build
9988ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
9991d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
10001d7c0054SEd Tanous  * interfaces to be built from
10011d7c0054SEd Tanous  * @param sensorJson  The json object to fill
10021d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
10031d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
10041d7c0054SEd Tanous  */
10051d7c0054SEd Tanous inline void objectInterfacesToJson(
10061d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
10071d7c0054SEd Tanous     const std::string& chassisSubNode,
100880f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
10091d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
10101d7c0054SEd Tanous {
10111d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
10121d7c0054SEd Tanous     {
10131d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
10141d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
10151d7c0054SEd Tanous     }
101662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
10171d7c0054SEd Tanous }
10181d7c0054SEd Tanous 
1019b5a76932SEd Tanous inline void populateFanRedundancy(
1020b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
10218bd25ccdSJames Feist {
1022e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1023e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
1024e99073f5SGeorge Liu     dbus::utility::getSubTree(
1025e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
1026b9d36b47SEd Tanous         [sensorsAsyncResp](
1027e99073f5SGeorge Liu             const boost::system::error_code& ec,
1028b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
10298bd25ccdSJames Feist             if (ec)
10308bd25ccdSJames Feist             {
10318bd25ccdSJames Feist                 return; // don't have to have this interface
10328bd25ccdSJames Feist             }
10336c3e9451SGeorge Liu             for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
1034e278c18fSEd Tanous                      pathPair : resp)
10358bd25ccdSJames Feist             {
1036e278c18fSEd Tanous                 const std::string& path = pathPair.first;
1037bd79bce8SPatrick Williams                 const dbus::utility::MapperServiceMap& objDict =
1038bd79bce8SPatrick Williams                     pathPair.second;
10398bd25ccdSJames Feist                 if (objDict.empty())
10408bd25ccdSJames Feist                 {
10418bd25ccdSJames Feist                     continue; // this should be impossible
10428bd25ccdSJames Feist                 }
10438bd25ccdSJames Feist 
10448bd25ccdSJames Feist                 const std::string& owner = objDict.begin()->first;
10456c3e9451SGeorge Liu                 dbus::utility::getAssociationEndPoints(
10466c3e9451SGeorge Liu                     path + "/chassis",
10476c3e9451SGeorge Liu                     [path, owner, sensorsAsyncResp](
10488b24275dSEd Tanous                         const boost::system::error_code& ec2,
10496c3e9451SGeorge Liu                         const dbus::utility::MapperEndPoints& endpoints) {
10508b24275dSEd Tanous                         if (ec2)
10518bd25ccdSJames Feist                         {
10528bd25ccdSJames Feist                             return; // if they don't have an association we
10538bd25ccdSJames Feist                                     // can't tell what chassis is
10548bd25ccdSJames Feist                         }
10553544d2a7SEd Tanous                         auto found = std::ranges::find_if(
1056bd79bce8SPatrick Williams                             endpoints,
1057bd79bce8SPatrick Williams                             [sensorsAsyncResp](const std::string& entry) {
1058bd79bce8SPatrick Williams                                 return entry.find(
1059bd79bce8SPatrick Williams                                            sensorsAsyncResp->chassisId) !=
10608bd25ccdSJames Feist                                        std::string::npos;
10618bd25ccdSJames Feist                             });
10628bd25ccdSJames Feist 
10631e1e598dSJonathan Doman                         if (found == endpoints.end())
10648bd25ccdSJames Feist                         {
10658bd25ccdSJames Feist                             return;
10668bd25ccdSJames Feist                         }
106786d89ed7SKrzysztof Grobelny                         sdbusplus::asio::getAllProperties(
106886d89ed7SKrzysztof Grobelny                             *crow::connections::systemBus, owner, path,
106986d89ed7SKrzysztof Grobelny                             "xyz.openbmc_project.Control.FanRedundancy",
10708bd25ccdSJames Feist                             [path, sensorsAsyncResp](
10718b24275dSEd Tanous                                 const boost::system::error_code& ec3,
107286d89ed7SKrzysztof Grobelny                                 const dbus::utility::DBusPropertiesMap& ret) {
10738b24275dSEd Tanous                                 if (ec3)
10748bd25ccdSJames Feist                                 {
10758bd25ccdSJames Feist                                     return; // don't have to have this
10768bd25ccdSJames Feist                                             // interface
10778bd25ccdSJames Feist                                 }
10788bd25ccdSJames Feist 
107986d89ed7SKrzysztof Grobelny                                 const uint8_t* allowedFailures = nullptr;
1080bd79bce8SPatrick Williams                                 const std::vector<std::string>* collection =
1081bd79bce8SPatrick Williams                                     nullptr;
108286d89ed7SKrzysztof Grobelny                                 const std::string* status = nullptr;
108386d89ed7SKrzysztof Grobelny 
1084bd79bce8SPatrick Williams                                 const bool success =
1085bd79bce8SPatrick Williams                                     sdbusplus::unpackPropertiesNoThrow(
108686d89ed7SKrzysztof Grobelny                                         dbus_utils::UnpackErrorPrinter(), ret,
1087bd79bce8SPatrick Williams                                         "AllowedFailures", allowedFailures,
1088bd79bce8SPatrick Williams                                         "Collection", collection, "Status",
1089bd79bce8SPatrick Williams                                         status);
109086d89ed7SKrzysztof Grobelny 
109186d89ed7SKrzysztof Grobelny                                 if (!success)
109286d89ed7SKrzysztof Grobelny                                 {
109386d89ed7SKrzysztof Grobelny                                     messages::internalError(
109486d89ed7SKrzysztof Grobelny                                         sensorsAsyncResp->asyncResp->res);
109586d89ed7SKrzysztof Grobelny                                     return;
109686d89ed7SKrzysztof Grobelny                                 }
109786d89ed7SKrzysztof Grobelny 
1098bd79bce8SPatrick Williams                                 if (allowedFailures == nullptr ||
1099bd79bce8SPatrick Williams                                     collection == nullptr || status == nullptr)
11008bd25ccdSJames Feist                                 {
1101bd79bce8SPatrick Williams                                     BMCWEB_LOG_ERROR(
1102bd79bce8SPatrick Williams                                         "Invalid redundancy interface");
11038bd25ccdSJames Feist                                     messages::internalError(
11048d1b46d7Szhanghch05                                         sensorsAsyncResp->asyncResp->res);
11058bd25ccdSJames Feist                                     return;
11068bd25ccdSJames Feist                                 }
11078bd25ccdSJames Feist 
1108bd79bce8SPatrick Williams                                 sdbusplus::message::object_path objectPath(
1109bd79bce8SPatrick Williams                                     path);
111028aa8de5SGeorge Liu                                 std::string name = objectPath.filename();
111128aa8de5SGeorge Liu                                 if (name.empty())
11128bd25ccdSJames Feist                                 {
11138bd25ccdSJames Feist                                     // this should be impossible
11148bd25ccdSJames Feist                                     messages::internalError(
11158d1b46d7Szhanghch05                                         sensorsAsyncResp->asyncResp->res);
11168bd25ccdSJames Feist                                     return;
11178bd25ccdSJames Feist                                 }
111818f8f608SEd Tanous                                 std::ranges::replace(name, '_', ' ');
11198bd25ccdSJames Feist 
11208bd25ccdSJames Feist                                 std::string health;
11218bd25ccdSJames Feist 
112211ba3979SEd Tanous                                 if (status->ends_with("Full"))
11238bd25ccdSJames Feist                                 {
11248bd25ccdSJames Feist                                     health = "OK";
11258bd25ccdSJames Feist                                 }
112611ba3979SEd Tanous                                 else if (status->ends_with("Degraded"))
11278bd25ccdSJames Feist                                 {
11288bd25ccdSJames Feist                                     health = "Warning";
11298bd25ccdSJames Feist                                 }
11308bd25ccdSJames Feist                                 else
11318bd25ccdSJames Feist                                 {
11328bd25ccdSJames Feist                                     health = "Critical";
11338bd25ccdSJames Feist                                 }
11341476687dSEd Tanous                                 nlohmann::json::array_t redfishCollection;
11358bd25ccdSJames Feist                                 const auto& fanRedfish =
1136bd79bce8SPatrick Williams                                     sensorsAsyncResp->asyncResp->res
1137bd79bce8SPatrick Williams                                         .jsonValue["Fans"];
11388bd25ccdSJames Feist                                 for (const std::string& item : *collection)
11398bd25ccdSJames Feist                                 {
1140bd79bce8SPatrick Williams                                     sdbusplus::message::object_path itemPath(
1141bd79bce8SPatrick Williams                                         item);
11428a592810SEd Tanous                                     std::string itemName = itemPath.filename();
114328aa8de5SGeorge Liu                                     if (itemName.empty())
114428aa8de5SGeorge Liu                                     {
114528aa8de5SGeorge Liu                                         continue;
114628aa8de5SGeorge Liu                                     }
11478bd25ccdSJames Feist                                     /*
11488bd25ccdSJames Feist                                     todo(ed): merge patch that fixes the names
11498bd25ccdSJames Feist                                     std::replace(itemName.begin(),
11508bd25ccdSJames Feist                                                  itemName.end(), '_', ' ');*/
11513544d2a7SEd Tanous                                     auto schemaItem = std::ranges::find_if(
1152bd79bce8SPatrick Williams                                         fanRedfish,
1153bd79bce8SPatrick Williams                                         [itemName](const nlohmann::json& fan) {
11543e35c761SGeorge Liu                                             return fan["Name"] == itemName;
11558bd25ccdSJames Feist                                         });
11568bd25ccdSJames Feist                                     if (schemaItem != fanRedfish.end())
11578bd25ccdSJames Feist                                     {
11588a592810SEd Tanous                                         nlohmann::json::object_t collectionId;
11598a592810SEd Tanous                                         collectionId["@odata.id"] =
11601476687dSEd Tanous                                             (*schemaItem)["@odata.id"];
11611476687dSEd Tanous                                         redfishCollection.emplace_back(
11628a592810SEd Tanous                                             std::move(collectionId));
11638bd25ccdSJames Feist                                     }
11648bd25ccdSJames Feist                                     else
11658bd25ccdSJames Feist                                     {
1166bd79bce8SPatrick Williams                                         BMCWEB_LOG_ERROR(
1167bd79bce8SPatrick Williams                                             "failed to find fan in schema");
11688bd25ccdSJames Feist                                         messages::internalError(
11698d1b46d7Szhanghch05                                             sensorsAsyncResp->asyncResp->res);
11708bd25ccdSJames Feist                                         return;
11718bd25ccdSJames Feist                                     }
11728bd25ccdSJames Feist                                 }
11738bd25ccdSJames Feist 
1174bd79bce8SPatrick Williams                                 size_t minNumNeeded =
1175bd79bce8SPatrick Williams                                     collection->empty()
117626f6976fSEd Tanous                                         ? 0
1177bd79bce8SPatrick Williams                                         : collection->size() - *allowedFailures;
1178bd79bce8SPatrick Williams                                 nlohmann::json& jResp =
1179bd79bce8SPatrick Williams                                     sensorsAsyncResp->asyncResp->res
11808bd25ccdSJames Feist                                         .jsonValue["Redundancy"];
11811476687dSEd Tanous 
11821476687dSEd Tanous                                 nlohmann::json::object_t redundancy;
1183bd79bce8SPatrick Williams                                 boost::urls::url url = boost::urls::format(
1184bd79bce8SPatrick Williams                                     "/redfish/v1/Chassis/{}/{}",
1185ef4c65b7SEd Tanous                                     sensorsAsyncResp->chassisId,
1186eddfc437SWilly Tu                                     sensorsAsyncResp->chassisSubNode);
1187bd79bce8SPatrick Williams                                 url.set_fragment(
1188bd79bce8SPatrick Williams                                     ("/Redundancy"_json_pointer / jResp.size())
1189eddfc437SWilly Tu                                         .to_string());
1190eddfc437SWilly Tu                                 redundancy["@odata.id"] = std::move(url);
1191bd79bce8SPatrick Williams                                 redundancy["@odata.type"] =
1192bd79bce8SPatrick Williams                                     "#Redundancy.v1_3_2.Redundancy";
11931476687dSEd Tanous                                 redundancy["MinNumNeeded"] = minNumNeeded;
1194bd79bce8SPatrick Williams                                 redundancy["Mode"] =
1195bd79bce8SPatrick Williams                                     redundancy::RedundancyType::NPlusM;
11961476687dSEd Tanous                                 redundancy["Name"] = name;
11971476687dSEd Tanous                                 redundancy["RedundancySet"] = redfishCollection;
11981476687dSEd Tanous                                 redundancy["Status"]["Health"] = health;
1199bd79bce8SPatrick Williams                                 redundancy["Status"]["State"] =
1200bd79bce8SPatrick Williams                                     resource::State::Enabled;
12011476687dSEd Tanous 
1202b2ba3072SPatrick Williams                                 jResp.emplace_back(std::move(redundancy));
120386d89ed7SKrzysztof Grobelny                             });
12041e1e598dSJonathan Doman                     });
12058bd25ccdSJames Feist             }
1206e99073f5SGeorge Liu         });
12078bd25ccdSJames Feist }
12088bd25ccdSJames Feist 
1209b5a76932SEd Tanous inline void
121081ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
121149c53ac9SJohnathan Mantey {
12128d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
121349c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
121481ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
121549c53ac9SJohnathan Mantey     {
121649c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
121749c53ac9SJohnathan Mantey     }
121849c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
121949c53ac9SJohnathan Mantey     {
122049c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
122149c53ac9SJohnathan Mantey         if (entry != response.end())
122249c53ac9SJohnathan Mantey         {
122349c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
122402cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
122549c53ac9SJohnathan Mantey                           return c1["Name"] < c2["Name"];
122649c53ac9SJohnathan Mantey                       });
122749c53ac9SJohnathan Mantey 
122849c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
122949c53ac9SJohnathan Mantey             size_t count = 0;
123049c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
123149c53ac9SJohnathan Mantey             {
123249c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
123349c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
123449c53ac9SJohnathan Mantey                 {
123549c53ac9SJohnathan Mantey                     continue;
123649c53ac9SJohnathan Mantey                 }
123749c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
123849c53ac9SJohnathan Mantey                 if (value != nullptr)
123949c53ac9SJohnathan Mantey                 {
1240eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
12413e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
124249c53ac9SJohnathan Mantey                     count++;
124381ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
124449c53ac9SJohnathan Mantey                 }
124549c53ac9SJohnathan Mantey             }
124649c53ac9SJohnathan Mantey         }
124749c53ac9SJohnathan Mantey     }
124849c53ac9SJohnathan Mantey }
124949c53ac9SJohnathan Mantey 
125008777fb0SLewanczyk, Dawid /**
1251adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1252adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1253adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1254adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12558fb49dd6SShawn McCarney  */
125623a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1257b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1258adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12598fb49dd6SShawn McCarney {
1260adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12618fb49dd6SShawn McCarney     {
1262adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12638fb49dd6SShawn McCarney         {
1264adc4f0dbSShawn McCarney             return &inventoryItem;
12658fb49dd6SShawn McCarney         }
12668fb49dd6SShawn McCarney     }
12678fb49dd6SShawn McCarney     return nullptr;
12688fb49dd6SShawn McCarney }
12698fb49dd6SShawn McCarney 
12708fb49dd6SShawn McCarney /**
1271adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1272adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1273adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1274adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12758fb49dd6SShawn McCarney  */
127623a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1277b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1278adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1279adc4f0dbSShawn McCarney {
1280adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1281adc4f0dbSShawn McCarney     {
1282db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1283adc4f0dbSShawn McCarney         {
1284adc4f0dbSShawn McCarney             return &inventoryItem;
1285adc4f0dbSShawn McCarney         }
1286adc4f0dbSShawn McCarney     }
1287adc4f0dbSShawn McCarney     return nullptr;
1288adc4f0dbSShawn McCarney }
1289adc4f0dbSShawn McCarney 
1290adc4f0dbSShawn McCarney /**
1291d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1292d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1293d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1294d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1295d500549bSAnthony Wilson  */
1296bd79bce8SPatrick Williams inline InventoryItem* findInventoryItemForLed(
1297bd79bce8SPatrick Williams     std::vector<InventoryItem>& inventoryItems, const std::string& ledObjPath)
1298d500549bSAnthony Wilson {
1299d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1300d500549bSAnthony Wilson     {
1301d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1302d500549bSAnthony Wilson         {
1303d500549bSAnthony Wilson             return &inventoryItem;
1304d500549bSAnthony Wilson         }
1305d500549bSAnthony Wilson     }
1306d500549bSAnthony Wilson     return nullptr;
1307d500549bSAnthony Wilson }
1308d500549bSAnthony Wilson 
1309d500549bSAnthony Wilson /**
1310adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1311adc4f0dbSShawn McCarney  *
1312adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1313adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1314adc4f0dbSShawn McCarney  * added to the vector.
1315adc4f0dbSShawn McCarney  *
1316adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1317adc4f0dbSShawn McCarney  * InventoryItem.
1318adc4f0dbSShawn McCarney  *
1319adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1320adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1321adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1322adc4f0dbSShawn McCarney  */
1323b5a76932SEd Tanous inline void addInventoryItem(
1324b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1325b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1326adc4f0dbSShawn McCarney {
1327adc4f0dbSShawn McCarney     // Look for inventory item in vector
1328bd79bce8SPatrick Williams     InventoryItem* inventoryItem =
1329bd79bce8SPatrick Williams         findInventoryItem(inventoryItems, invItemObjPath);
1330adc4f0dbSShawn McCarney 
1331adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1332adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1333adc4f0dbSShawn McCarney     {
1334adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1335adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1336adc4f0dbSShawn McCarney     }
1337adc4f0dbSShawn McCarney 
1338adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1339adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1340adc4f0dbSShawn McCarney }
1341adc4f0dbSShawn McCarney 
1342adc4f0dbSShawn McCarney /**
1343adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1344adc4f0dbSShawn McCarney  *
1345adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1346adc4f0dbSShawn McCarney  * specified InventoryItem.
1347adc4f0dbSShawn McCarney  *
1348adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1349adc4f0dbSShawn McCarney  * response.
1350adc4f0dbSShawn McCarney  *
1351adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1352adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1353adc4f0dbSShawn McCarney  * for the specified inventory item.
1354adc4f0dbSShawn McCarney  */
135523a21a1cSEd Tanous inline void storeInventoryItemData(
1356adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
135780f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13588fb49dd6SShawn McCarney {
1359adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1360711ac7a9SEd Tanous 
13619eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13628fb49dd6SShawn McCarney     {
1363711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13648fb49dd6SShawn McCarney         {
13659eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1366711ac7a9SEd Tanous             {
1367711ac7a9SEd Tanous                 if (name == "Present")
1368711ac7a9SEd Tanous                 {
1369711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1370adc4f0dbSShawn McCarney                     if (value != nullptr)
13718fb49dd6SShawn McCarney                     {
1372adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13738fb49dd6SShawn McCarney                     }
13748fb49dd6SShawn McCarney                 }
13758fb49dd6SShawn McCarney             }
1376711ac7a9SEd Tanous         }
1377adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1378711ac7a9SEd Tanous 
1379711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13808fb49dd6SShawn McCarney         {
1381adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13828fb49dd6SShawn McCarney         }
1383adc4f0dbSShawn McCarney 
1384adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1385711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1386adc4f0dbSShawn McCarney         {
13879eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1388711ac7a9SEd Tanous             {
1389711ac7a9SEd Tanous                 if (name == "Manufacturer")
1390adc4f0dbSShawn McCarney                 {
1391adc4f0dbSShawn McCarney                     const std::string* value =
1392711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1393adc4f0dbSShawn McCarney                     if (value != nullptr)
1394adc4f0dbSShawn McCarney                     {
1395adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1396adc4f0dbSShawn McCarney                     }
1397adc4f0dbSShawn McCarney                 }
1398711ac7a9SEd Tanous                 if (name == "Model")
1399adc4f0dbSShawn McCarney                 {
1400adc4f0dbSShawn McCarney                     const std::string* value =
1401711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1402adc4f0dbSShawn McCarney                     if (value != nullptr)
1403adc4f0dbSShawn McCarney                     {
1404adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1405adc4f0dbSShawn McCarney                     }
1406adc4f0dbSShawn McCarney                 }
1407711ac7a9SEd Tanous                 if (name == "SerialNumber")
1408adc4f0dbSShawn McCarney                 {
1409adc4f0dbSShawn McCarney                     const std::string* value =
1410711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1411adc4f0dbSShawn McCarney                     if (value != nullptr)
1412adc4f0dbSShawn McCarney                     {
1413adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1414adc4f0dbSShawn McCarney                     }
1415adc4f0dbSShawn McCarney                 }
1416711ac7a9SEd Tanous                 if (name == "PartNumber")
1417711ac7a9SEd Tanous                 {
1418711ac7a9SEd Tanous                     const std::string* value =
1419711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1420711ac7a9SEd Tanous                     if (value != nullptr)
1421711ac7a9SEd Tanous                     {
1422711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1423711ac7a9SEd Tanous                     }
1424711ac7a9SEd Tanous                 }
1425711ac7a9SEd Tanous             }
1426adc4f0dbSShawn McCarney         }
1427adc4f0dbSShawn McCarney 
1428711ac7a9SEd Tanous         if (interface ==
1429711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1430adc4f0dbSShawn McCarney         {
14319eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1432adc4f0dbSShawn McCarney             {
1433711ac7a9SEd Tanous                 if (name == "Functional")
1434711ac7a9SEd Tanous                 {
1435711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1436adc4f0dbSShawn McCarney                     if (value != nullptr)
1437adc4f0dbSShawn McCarney                     {
1438adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
14398fb49dd6SShawn McCarney                     }
14408fb49dd6SShawn McCarney                 }
14418fb49dd6SShawn McCarney             }
14428fb49dd6SShawn McCarney         }
1443711ac7a9SEd Tanous     }
1444711ac7a9SEd Tanous }
14458fb49dd6SShawn McCarney 
14468fb49dd6SShawn McCarney /**
1447adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
14488fb49dd6SShawn McCarney  *
1449adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1450adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1451adc4f0dbSShawn McCarney  * inventoryItems vector.
14528fb49dd6SShawn McCarney  *
1453adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1454adc4f0dbSShawn McCarney  * response.
1455adc4f0dbSShawn McCarney  *
1456adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1457adc4f0dbSShawn McCarney  * been obtained.
1458adc4f0dbSShawn McCarney  *
1459adc4f0dbSShawn McCarney  * The callback must have the following signature:
1460adc4f0dbSShawn McCarney  *   @code
1461d500549bSAnthony Wilson  *   callback(void)
1462adc4f0dbSShawn McCarney  *   @endcode
1463adc4f0dbSShawn McCarney  *
1464adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1465adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1466adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14678fb49dd6SShawn McCarney  *
14688fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1469adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1470adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14718fb49dd6SShawn McCarney  * implements ObjectManager.
1472adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1473adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1474adc4f0dbSShawn McCarney  * in recursive calls to this function.
14758fb49dd6SShawn McCarney  */
1476adc4f0dbSShawn McCarney template <typename Callback>
1477adc4f0dbSShawn McCarney static void getInventoryItemsData(
14788fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1479adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1480d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1481d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14828fb49dd6SShawn McCarney {
148362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14848fb49dd6SShawn McCarney 
1485adc4f0dbSShawn McCarney     // If no more connections left, call callback
1486adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14878fb49dd6SShawn McCarney     {
1488d500549bSAnthony Wilson         callback();
148962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1490adc4f0dbSShawn McCarney         return;
1491adc4f0dbSShawn McCarney     }
1492adc4f0dbSShawn McCarney 
1493adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1494fe04d49cSNan Zhou     auto it = invConnections->begin();
1495fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1496adc4f0dbSShawn McCarney     if (it != invConnections->end())
1497adc4f0dbSShawn McCarney     {
1498adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1499adc4f0dbSShawn McCarney 
15005eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
15015eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
15025eb468daSGeorge Liu         dbus::utility::getManagedObjects(
15035eb468daSGeorge Liu             invConnection, path,
15045eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
15058cb2c024SEd Tanous              callback = std::forward<Callback>(callback), invConnectionsIndex](
15065e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
150702cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
150862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
15098fb49dd6SShawn McCarney                 if (ec)
15108fb49dd6SShawn McCarney                 {
151162598e31SEd Tanous                     BMCWEB_LOG_ERROR(
151262598e31SEd Tanous                         "getInventoryItemsData respHandler DBus error {}", ec);
15138d1b46d7Szhanghch05                     messages::internalError(sensorsAsyncResp->asyncResp->res);
15148fb49dd6SShawn McCarney                     return;
15158fb49dd6SShawn McCarney                 }
15168fb49dd6SShawn McCarney 
15178fb49dd6SShawn McCarney                 // Loop through returned object paths
15188fb49dd6SShawn McCarney                 for (const auto& objDictEntry : resp)
15198fb49dd6SShawn McCarney                 {
15208fb49dd6SShawn McCarney                     const std::string& objPath =
15218fb49dd6SShawn McCarney                         static_cast<const std::string&>(objDictEntry.first);
15228fb49dd6SShawn McCarney 
1523bd79bce8SPatrick Williams                     // If this object path is one of the specified inventory
1524bd79bce8SPatrick Williams                     // items
1525bd79bce8SPatrick Williams                     InventoryItem* inventoryItem =
1526bd79bce8SPatrick Williams                         findInventoryItem(inventoryItems, objPath);
1527adc4f0dbSShawn McCarney                     if (inventoryItem != nullptr)
15288fb49dd6SShawn McCarney                     {
1529adc4f0dbSShawn McCarney                         // Store inventory data in InventoryItem
1530bd79bce8SPatrick Williams                         storeInventoryItemData(*inventoryItem,
1531bd79bce8SPatrick Williams                                                objDictEntry.second);
15328fb49dd6SShawn McCarney                     }
15338fb49dd6SShawn McCarney                 }
15348fb49dd6SShawn McCarney 
1535adc4f0dbSShawn McCarney                 // Recurse to get inventory item data from next connection
1536adc4f0dbSShawn McCarney                 getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1537d0090733SEd Tanous                                       invConnections, std::move(callback),
1538d0090733SEd Tanous                                       invConnectionsIndex + 1);
1539adc4f0dbSShawn McCarney 
154062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
15415eb468daSGeorge Liu             });
15428fb49dd6SShawn McCarney     }
15438fb49dd6SShawn McCarney 
154462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
15458fb49dd6SShawn McCarney }
15468fb49dd6SShawn McCarney 
15478fb49dd6SShawn McCarney /**
1548adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
15498fb49dd6SShawn McCarney  *
1550adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1551adc4f0dbSShawn McCarney  * items that are associated with sensors.
15528fb49dd6SShawn McCarney  *
15538fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15548fb49dd6SShawn McCarney  * been obtained.
15558fb49dd6SShawn McCarney  *
15568fb49dd6SShawn McCarney  * The callback must have the following signature:
15578fb49dd6SShawn McCarney  *   @code
1558fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15598fb49dd6SShawn McCarney  *   @endcode
15608fb49dd6SShawn McCarney  *
15618fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1562adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15638fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15648fb49dd6SShawn McCarney  */
15658fb49dd6SShawn McCarney template <typename Callback>
15668fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1567b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1568b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15698fb49dd6SShawn McCarney     Callback&& callback)
15708fb49dd6SShawn McCarney {
157162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15728fb49dd6SShawn McCarney 
15738fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1574e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15758fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1576adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1577adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15788fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15798fb49dd6SShawn McCarney 
1580e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1581e99073f5SGeorge Liu     dbus::utility::getSubTree(
1582e99073f5SGeorge Liu         path, 0, interfaces,
15838cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1584002d39b4SEd Tanous          inventoryItems](
1585e99073f5SGeorge Liu             const boost::system::error_code& ec,
1586002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1587e99073f5SGeorge Liu             // Response handler for parsing output from GetSubTree
158862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15898fb49dd6SShawn McCarney             if (ec)
15908fb49dd6SShawn McCarney             {
15918d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
159262598e31SEd Tanous                 BMCWEB_LOG_ERROR(
1593bd79bce8SPatrick Williams                     "getInventoryItemsConnections respHandler DBus error {}",
1594bd79bce8SPatrick Williams                     ec);
15958fb49dd6SShawn McCarney                 return;
15968fb49dd6SShawn McCarney             }
15978fb49dd6SShawn McCarney 
15988fb49dd6SShawn McCarney             // Make unique list of connections for desired inventory items
1599fe04d49cSNan Zhou             std::shared_ptr<std::set<std::string>> invConnections =
1600fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
16018fb49dd6SShawn McCarney 
16028fb49dd6SShawn McCarney             // Loop through objects from GetSubTree
1603bd79bce8SPatrick Williams             for (const std::pair<std::string,
1604bd79bce8SPatrick Williams                                  std::vector<std::pair<
1605bd79bce8SPatrick Williams                                      std::string, std::vector<std::string>>>>&
16068fb49dd6SShawn McCarney                      object : subtree)
16078fb49dd6SShawn McCarney             {
1608adc4f0dbSShawn McCarney                 // Check if object path is one of the specified inventory items
16098fb49dd6SShawn McCarney                 const std::string& objPath = object.first;
1610adc4f0dbSShawn McCarney                 if (findInventoryItem(inventoryItems, objPath) != nullptr)
16118fb49dd6SShawn McCarney                 {
16128fb49dd6SShawn McCarney                     // Store all connections to inventory item
16138fb49dd6SShawn McCarney                     for (const std::pair<std::string, std::vector<std::string>>&
16148fb49dd6SShawn McCarney                              objData : object.second)
16158fb49dd6SShawn McCarney                     {
16168fb49dd6SShawn McCarney                         const std::string& invConnection = objData.first;
16178fb49dd6SShawn McCarney                         invConnections->insert(invConnection);
16188fb49dd6SShawn McCarney                     }
16198fb49dd6SShawn McCarney                 }
16208fb49dd6SShawn McCarney             }
1621d500549bSAnthony Wilson 
16228fb49dd6SShawn McCarney             callback(invConnections);
162362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1624e99073f5SGeorge Liu         });
162562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
16268fb49dd6SShawn McCarney }
16278fb49dd6SShawn McCarney 
16288fb49dd6SShawn McCarney /**
1629adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
16308fb49dd6SShawn McCarney  *
16318fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1632d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1633d500549bSAnthony Wilson  * their LEDs, if any.
16348fb49dd6SShawn McCarney  *
16358fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
16368fb49dd6SShawn McCarney  * has been obtained.
16378fb49dd6SShawn McCarney  *
16388fb49dd6SShawn McCarney  * The callback must have the following signature:
16398fb49dd6SShawn McCarney  *   @code
1640adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
16418fb49dd6SShawn McCarney  *   @endcode
16428fb49dd6SShawn McCarney  *
16438fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
16448fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
16458fb49dd6SShawn McCarney  * implements ObjectManager.
16468fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
16478fb49dd6SShawn McCarney  */
16488fb49dd6SShawn McCarney template <typename Callback>
1649adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1650b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1651fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16528fb49dd6SShawn McCarney     Callback&& callback)
16538fb49dd6SShawn McCarney {
165462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16558fb49dd6SShawn McCarney 
16565eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16575eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16585eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16595eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
16608cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
16615e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
166202cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
166362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16648fb49dd6SShawn McCarney             if (ec)
16658fb49dd6SShawn McCarney             {
166662598e31SEd Tanous                 BMCWEB_LOG_ERROR(
1667bd79bce8SPatrick Williams                     "getInventoryItemAssociations respHandler DBus error {}",
1668bd79bce8SPatrick Williams                     ec);
16698d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
16708fb49dd6SShawn McCarney                 return;
16718fb49dd6SShawn McCarney             }
16728fb49dd6SShawn McCarney 
1673adc4f0dbSShawn McCarney             // Create vector to hold list of inventory items
1674adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1675adc4f0dbSShawn McCarney                 std::make_shared<std::vector<InventoryItem>>();
1676adc4f0dbSShawn McCarney 
16778fb49dd6SShawn McCarney             // Loop through returned object paths
16788fb49dd6SShawn McCarney             std::string sensorAssocPath;
16798fb49dd6SShawn McCarney             sensorAssocPath.reserve(128); // avoid memory allocations
16808fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
16818fb49dd6SShawn McCarney             {
16828fb49dd6SShawn McCarney                 const std::string& objPath =
16838fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
16848fb49dd6SShawn McCarney 
1685bd79bce8SPatrick Williams                 // If path is inventory association for one of the specified
1686bd79bce8SPatrick Williams                 // sensors
16878fb49dd6SShawn McCarney                 for (const std::string& sensorName : *sensorNames)
16888fb49dd6SShawn McCarney                 {
16898fb49dd6SShawn McCarney                     sensorAssocPath = sensorName;
16908fb49dd6SShawn McCarney                     sensorAssocPath += "/inventory";
16918fb49dd6SShawn McCarney                     if (objPath == sensorAssocPath)
16928fb49dd6SShawn McCarney                     {
16938fb49dd6SShawn McCarney                         // Get Association interface for object path
1694bd79bce8SPatrick Williams                         for (const auto& [interface, values] :
1695bd79bce8SPatrick Williams                              objDictEntry.second)
16968fb49dd6SShawn McCarney                         {
1697711ac7a9SEd Tanous                             if (interface == "xyz.openbmc_project.Association")
1698711ac7a9SEd Tanous                             {
1699711ac7a9SEd Tanous                                 for (const auto& [valueName, value] : values)
1700711ac7a9SEd Tanous                                 {
1701711ac7a9SEd Tanous                                     if (valueName == "endpoints")
17028fb49dd6SShawn McCarney                                     {
1703bd79bce8SPatrick Williams                                         const std::vector<std::string>*
1704bd79bce8SPatrick Williams                                             endpoints = std::get_if<
1705bd79bce8SPatrick Williams                                                 std::vector<std::string>>(
1706711ac7a9SEd Tanous                                                 &value);
1707711ac7a9SEd Tanous                                         if ((endpoints != nullptr) &&
1708711ac7a9SEd Tanous                                             !endpoints->empty())
17098fb49dd6SShawn McCarney                                         {
1710adc4f0dbSShawn McCarney                                             // Add inventory item to vector
1711adc4f0dbSShawn McCarney                                             const std::string& invItemPath =
1712adc4f0dbSShawn McCarney                                                 endpoints->front();
1713711ac7a9SEd Tanous                                             addInventoryItem(inventoryItems,
1714711ac7a9SEd Tanous                                                              invItemPath,
1715adc4f0dbSShawn McCarney                                                              sensorName);
17168fb49dd6SShawn McCarney                                         }
17178fb49dd6SShawn McCarney                                     }
17188fb49dd6SShawn McCarney                                 }
1719711ac7a9SEd Tanous                             }
1720711ac7a9SEd Tanous                         }
17218fb49dd6SShawn McCarney                         break;
17228fb49dd6SShawn McCarney                     }
17238fb49dd6SShawn McCarney                 }
17248fb49dd6SShawn McCarney             }
17258fb49dd6SShawn McCarney 
1726d500549bSAnthony Wilson             // Now loop through the returned object paths again, this time to
1727d500549bSAnthony Wilson             // find the leds associated with the inventory items we just found
1728d500549bSAnthony Wilson             std::string inventoryAssocPath;
1729d500549bSAnthony Wilson             inventoryAssocPath.reserve(128); // avoid memory allocations
1730d500549bSAnthony Wilson             for (const auto& objDictEntry : resp)
1731d500549bSAnthony Wilson             {
1732d500549bSAnthony Wilson                 const std::string& objPath =
1733d500549bSAnthony Wilson                     static_cast<const std::string&>(objDictEntry.first);
1734d500549bSAnthony Wilson 
1735d500549bSAnthony Wilson                 for (InventoryItem& inventoryItem : *inventoryItems)
1736d500549bSAnthony Wilson                 {
1737d500549bSAnthony Wilson                     inventoryAssocPath = inventoryItem.objectPath;
1738d500549bSAnthony Wilson                     inventoryAssocPath += "/leds";
1739d500549bSAnthony Wilson                     if (objPath == inventoryAssocPath)
1740d500549bSAnthony Wilson                     {
1741bd79bce8SPatrick Williams                         for (const auto& [interface, values] :
1742bd79bce8SPatrick Williams                              objDictEntry.second)
1743d500549bSAnthony Wilson                         {
1744711ac7a9SEd Tanous                             if (interface == "xyz.openbmc_project.Association")
1745711ac7a9SEd Tanous                             {
1746711ac7a9SEd Tanous                                 for (const auto& [valueName, value] : values)
1747711ac7a9SEd Tanous                                 {
1748711ac7a9SEd Tanous                                     if (valueName == "endpoints")
1749d500549bSAnthony Wilson                                     {
1750bd79bce8SPatrick Williams                                         const std::vector<std::string>*
1751bd79bce8SPatrick Williams                                             endpoints = std::get_if<
1752bd79bce8SPatrick Williams                                                 std::vector<std::string>>(
1753711ac7a9SEd Tanous                                                 &value);
1754711ac7a9SEd Tanous                                         if ((endpoints != nullptr) &&
1755711ac7a9SEd Tanous                                             !endpoints->empty())
1756d500549bSAnthony Wilson                                         {
1757711ac7a9SEd Tanous                                             // Add inventory item to vector
1758d500549bSAnthony Wilson                                             // Store LED path in inventory item
1759711ac7a9SEd Tanous                                             const std::string& ledPath =
1760711ac7a9SEd Tanous                                                 endpoints->front();
1761bd79bce8SPatrick Williams                                             inventoryItem.ledObjectPath =
1762bd79bce8SPatrick Williams                                                 ledPath;
1763d500549bSAnthony Wilson                                         }
1764d500549bSAnthony Wilson                                     }
1765d500549bSAnthony Wilson                                 }
1766711ac7a9SEd Tanous                             }
1767711ac7a9SEd Tanous                         }
1768711ac7a9SEd Tanous 
1769d500549bSAnthony Wilson                         break;
1770d500549bSAnthony Wilson                     }
1771d500549bSAnthony Wilson                 }
1772d500549bSAnthony Wilson             }
1773adc4f0dbSShawn McCarney             callback(inventoryItems);
177462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17755eb468daSGeorge Liu         });
17768fb49dd6SShawn McCarney 
177762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17788fb49dd6SShawn McCarney }
17798fb49dd6SShawn McCarney 
17808fb49dd6SShawn McCarney /**
1781d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1782d500549bSAnthony Wilson  *
1783d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1784d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1785d500549bSAnthony Wilson  * inventoryItems vector.
1786d500549bSAnthony Wilson  *
1787d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1788d500549bSAnthony Wilson  * response.
1789d500549bSAnthony Wilson  *
1790d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1791d500549bSAnthony Wilson  * has been obtained.
1792d500549bSAnthony Wilson  *
1793d500549bSAnthony Wilson  * The callback must have the following signature:
1794d500549bSAnthony Wilson  *   @code
179542cbe538SGunnar Mills  *   callback()
1796d500549bSAnthony Wilson  *   @endcode
1797d500549bSAnthony Wilson  *
1798d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1799d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1800d500549bSAnthony Wilson  * last asynchronous function has completed.
1801d500549bSAnthony Wilson  *
1802d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1803d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1804d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1805d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1806d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1807d500549bSAnthony Wilson  * in recursive calls to this function.
1808d500549bSAnthony Wilson  */
1809d500549bSAnthony Wilson template <typename Callback>
1810d500549bSAnthony Wilson void getInventoryLedData(
1811d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1812d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1813fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1814d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1815d500549bSAnthony Wilson {
181662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1817d500549bSAnthony Wilson 
1818d500549bSAnthony Wilson     // If no more connections left, call callback
1819d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1820d500549bSAnthony Wilson     {
182142cbe538SGunnar Mills         callback();
182262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1823d500549bSAnthony Wilson         return;
1824d500549bSAnthony Wilson     }
1825d500549bSAnthony Wilson 
1826d500549bSAnthony Wilson     // Get inventory item data from current connection
1827fe04d49cSNan Zhou     auto it = ledConnections->begin();
1828fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1829d500549bSAnthony Wilson     if (it != ledConnections->end())
1830d500549bSAnthony Wilson     {
1831d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1832d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1833d500549bSAnthony Wilson         // Response handler for Get State property
18341e1e598dSJonathan Doman         auto respHandler =
18351e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
18368cb2c024SEd Tanous              callback = std::forward<Callback>(callback), ledConnectionsIndex](
18375e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
183862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1839d500549bSAnthony Wilson                 if (ec)
1840d500549bSAnthony Wilson                 {
184162598e31SEd Tanous                     BMCWEB_LOG_ERROR(
184262598e31SEd Tanous                         "getInventoryLedData respHandler DBus error {}", ec);
18438d1b46d7Szhanghch05                     messages::internalError(sensorsAsyncResp->asyncResp->res);
1844d500549bSAnthony Wilson                     return;
1845d500549bSAnthony Wilson                 }
1846d500549bSAnthony Wilson 
184762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Led state: {}", state);
1848d500549bSAnthony Wilson                 // Find inventory item with this LED object path
1849d500549bSAnthony Wilson                 InventoryItem* inventoryItem =
1850d500549bSAnthony Wilson                     findInventoryItemForLed(*inventoryItems, ledPath);
1851d500549bSAnthony Wilson                 if (inventoryItem != nullptr)
1852d500549bSAnthony Wilson                 {
1853d500549bSAnthony Wilson                     // Store LED state in InventoryItem
185411ba3979SEd Tanous                     if (state.ends_with("On"))
1855d500549bSAnthony Wilson                     {
1856d500549bSAnthony Wilson                         inventoryItem->ledState = LedState::ON;
1857d500549bSAnthony Wilson                     }
185811ba3979SEd Tanous                     else if (state.ends_with("Blink"))
1859d500549bSAnthony Wilson                     {
1860d500549bSAnthony Wilson                         inventoryItem->ledState = LedState::BLINK;
1861d500549bSAnthony Wilson                     }
186211ba3979SEd Tanous                     else if (state.ends_with("Off"))
1863d500549bSAnthony Wilson                     {
1864d500549bSAnthony Wilson                         inventoryItem->ledState = LedState::OFF;
1865d500549bSAnthony Wilson                     }
1866d500549bSAnthony Wilson                     else
1867d500549bSAnthony Wilson                     {
1868d500549bSAnthony Wilson                         inventoryItem->ledState = LedState::UNKNOWN;
1869d500549bSAnthony Wilson                     }
1870d500549bSAnthony Wilson                 }
1871d500549bSAnthony Wilson 
1872d500549bSAnthony Wilson                 // Recurse to get LED data from next connection
1873d500549bSAnthony Wilson                 getInventoryLedData(sensorsAsyncResp, inventoryItems,
1874d500549bSAnthony Wilson                                     ledConnections, std::move(callback),
1875d500549bSAnthony Wilson                                     ledConnectionsIndex + 1);
1876d500549bSAnthony Wilson 
187762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1878d500549bSAnthony Wilson             };
1879d500549bSAnthony Wilson 
1880d500549bSAnthony Wilson         // Get the State property for the current LED
18811e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18821e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18831e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18841e1e598dSJonathan Doman             std::move(respHandler));
1885d500549bSAnthony Wilson     }
1886d500549bSAnthony Wilson 
188762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1888d500549bSAnthony Wilson }
1889d500549bSAnthony Wilson 
1890d500549bSAnthony Wilson /**
1891d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1892d500549bSAnthony Wilson  *
1893d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1894d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1895d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1896d500549bSAnthony Wilson  *
1897d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1898d500549bSAnthony Wilson  * response.
1899d500549bSAnthony Wilson  *
1900d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1901d500549bSAnthony Wilson  * been obtained.
1902d500549bSAnthony Wilson  *
1903d500549bSAnthony Wilson  * The callback must have the following signature:
1904d500549bSAnthony Wilson  *   @code
190542cbe538SGunnar Mills  *   callback()
1906d500549bSAnthony Wilson  *   @endcode
1907d500549bSAnthony Wilson  *
1908d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1909d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1910d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1911d500549bSAnthony Wilson  */
1912d500549bSAnthony Wilson template <typename Callback>
1913d500549bSAnthony Wilson void getInventoryLeds(
1914d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1915d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1916d500549bSAnthony Wilson     Callback&& callback)
1917d500549bSAnthony Wilson {
191862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1919d500549bSAnthony Wilson 
1920d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1921e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1922d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1923d500549bSAnthony Wilson 
1924e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1925e99073f5SGeorge Liu     dbus::utility::getSubTree(
1926e99073f5SGeorge Liu         path, 0, interfaces,
19278cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1928002d39b4SEd Tanous          inventoryItems](
1929e99073f5SGeorge Liu             const boost::system::error_code& ec,
1930002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1931e99073f5SGeorge Liu             // Response handler for parsing output from GetSubTree
193262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1933d500549bSAnthony Wilson             if (ec)
1934d500549bSAnthony Wilson             {
19358d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1936bd79bce8SPatrick Williams                 BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}",
1937bd79bce8SPatrick Williams                                  ec);
1938d500549bSAnthony Wilson                 return;
1939d500549bSAnthony Wilson             }
1940d500549bSAnthony Wilson 
1941d500549bSAnthony Wilson             // Build map of LED object paths to connections
1942fe04d49cSNan Zhou             std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1943fe04d49cSNan Zhou                 std::make_shared<std::map<std::string, std::string>>();
1944d500549bSAnthony Wilson 
1945d500549bSAnthony Wilson             // Loop through objects from GetSubTree
1946bd79bce8SPatrick Williams             for (const std::pair<std::string,
1947bd79bce8SPatrick Williams                                  std::vector<std::pair<
1948bd79bce8SPatrick Williams                                      std::string, std::vector<std::string>>>>&
1949d500549bSAnthony Wilson                      object : subtree)
1950d500549bSAnthony Wilson             {
1951bd79bce8SPatrick Williams                 // Check if object path is LED for one of the specified
1952bd79bce8SPatrick Williams                 // inventory items
1953d500549bSAnthony Wilson                 const std::string& ledPath = object.first;
1954bd79bce8SPatrick Williams                 if (findInventoryItemForLed(*inventoryItems, ledPath) !=
1955bd79bce8SPatrick Williams                     nullptr)
1956d500549bSAnthony Wilson                 {
1957d500549bSAnthony Wilson                     // Add mapping from ledPath to connection
1958bd79bce8SPatrick Williams                     const std::string& connection =
1959bd79bce8SPatrick Williams                         object.second.begin()->first;
1960d500549bSAnthony Wilson                     (*ledConnections)[ledPath] = connection;
1961bd79bce8SPatrick Williams                     BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath,
1962bd79bce8SPatrick Williams                                      connection);
1963d500549bSAnthony Wilson                 }
1964d500549bSAnthony Wilson             }
1965d500549bSAnthony Wilson 
1966bd79bce8SPatrick Williams             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1967bd79bce8SPatrick Williams                                 ledConnections, std::move(callback));
196862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1969e99073f5SGeorge Liu         });
197062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1971d500549bSAnthony Wilson }
1972d500549bSAnthony Wilson 
1973d500549bSAnthony Wilson /**
197442cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
197542cbe538SGunnar Mills  *
197642cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
197742cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
197842cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
197942cbe538SGunnar Mills  *
198042cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
198142cbe538SGunnar Mills  * response.
198242cbe538SGunnar Mills  *
198342cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
198442cbe538SGunnar Mills  * when data has been obtained.
198542cbe538SGunnar Mills  *
198642cbe538SGunnar Mills  * The callback must have the following signature:
198742cbe538SGunnar Mills  *   @code
198842cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
198942cbe538SGunnar Mills  *   @endcode
199042cbe538SGunnar Mills  *
199142cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
199242cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
199342cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
199442cbe538SGunnar Mills  *        Supply Attributes
199542cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
199642cbe538SGunnar Mills  */
199742cbe538SGunnar Mills template <typename Callback>
199842cbe538SGunnar Mills void getPowerSupplyAttributesData(
1999b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
200042cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
2001fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
200242cbe538SGunnar Mills     Callback&& callback)
200342cbe538SGunnar Mills {
200462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
200542cbe538SGunnar Mills 
200642cbe538SGunnar Mills     if (psAttributesConnections.empty())
200742cbe538SGunnar Mills     {
200862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
200942cbe538SGunnar Mills         callback(inventoryItems);
201042cbe538SGunnar Mills         return;
201142cbe538SGunnar Mills     }
201242cbe538SGunnar Mills 
201342cbe538SGunnar Mills     // Assuming just one connection (service) for now
2014fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
201542cbe538SGunnar Mills 
201642cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
201742cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
201842cbe538SGunnar Mills 
201942cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
20205a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
20218cb2c024SEd Tanous                         callback = std::forward<Callback>(callback)](
20225a39f77aSPatrick Williams                            const boost::system::error_code& ec,
20235a39f77aSPatrick Williams                            const uint32_t value) {
202462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
202542cbe538SGunnar Mills         if (ec)
202642cbe538SGunnar Mills         {
202762598e31SEd Tanous             BMCWEB_LOG_ERROR(
202862598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
20298d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
203042cbe538SGunnar Mills             return;
203142cbe538SGunnar Mills         }
203242cbe538SGunnar Mills 
203362598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
203442cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
203542cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
203642cbe538SGunnar Mills         {
203755f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
203842cbe538SGunnar Mills             {
203942cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
20401e1e598dSJonathan Doman                     static_cast<int>(value);
204142cbe538SGunnar Mills             }
204242cbe538SGunnar Mills         }
204342cbe538SGunnar Mills 
204462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
204542cbe538SGunnar Mills         callback(inventoryItems);
204642cbe538SGunnar Mills     };
204742cbe538SGunnar Mills 
204842cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
204942cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
20501e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
20511e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
20521e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
20531e1e598dSJonathan Doman         std::move(respHandler));
205442cbe538SGunnar Mills 
205562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
205642cbe538SGunnar Mills }
205742cbe538SGunnar Mills 
205842cbe538SGunnar Mills /**
205942cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
206042cbe538SGunnar Mills  *
206142cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
206242cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
206342cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
206442cbe538SGunnar Mills  * item.
206542cbe538SGunnar Mills  *
206642cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
206742cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
206842cbe538SGunnar Mills  *
206942cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
207042cbe538SGunnar Mills  * when information has been obtained.
207142cbe538SGunnar Mills  *
207242cbe538SGunnar Mills  * The callback must have the following signature:
207342cbe538SGunnar Mills  *   @code
207442cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
207542cbe538SGunnar Mills  *   @endcode
207642cbe538SGunnar Mills  *
207742cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
207842cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
207942cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
208042cbe538SGunnar Mills  */
208142cbe538SGunnar Mills template <typename Callback>
208242cbe538SGunnar Mills void getPowerSupplyAttributes(
208342cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
208442cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
208542cbe538SGunnar Mills     Callback&& callback)
208642cbe538SGunnar Mills {
208762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
208842cbe538SGunnar Mills 
208942cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2090a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
209142cbe538SGunnar Mills     {
209262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
209342cbe538SGunnar Mills         callback(inventoryItems);
209442cbe538SGunnar Mills         return;
209542cbe538SGunnar Mills     }
209642cbe538SGunnar Mills 
2097e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
209842cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
209942cbe538SGunnar Mills 
2100e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2101e99073f5SGeorge Liu     dbus::utility::getSubTree(
2102e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
21038cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
2104b9d36b47SEd Tanous          inventoryItems](
2105e99073f5SGeorge Liu             const boost::system::error_code& ec,
2106b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2107e99073f5SGeorge Liu             // Response handler for parsing output from GetSubTree
210862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
210942cbe538SGunnar Mills             if (ec)
211042cbe538SGunnar Mills             {
21118d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
211262598e31SEd Tanous                 BMCWEB_LOG_ERROR(
211362598e31SEd Tanous                     "getPowerSupplyAttributes respHandler DBus error {}", ec);
211442cbe538SGunnar Mills                 return;
211542cbe538SGunnar Mills             }
211626f6976fSEd Tanous             if (subtree.empty())
211742cbe538SGunnar Mills             {
211862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
211942cbe538SGunnar Mills                 callback(inventoryItems);
212042cbe538SGunnar Mills                 return;
212142cbe538SGunnar Mills             }
212242cbe538SGunnar Mills 
212342cbe538SGunnar Mills             // Currently we only support 1 power supply attribute, use this for
212442cbe538SGunnar Mills             // all the power supplies. Build map of object path to connection.
212542cbe538SGunnar Mills             // Assume just 1 connection and 1 path for now.
2126fe04d49cSNan Zhou             std::map<std::string, std::string> psAttributesConnections;
212742cbe538SGunnar Mills 
212842cbe538SGunnar Mills             if (subtree[0].first.empty() || subtree[0].second.empty())
212942cbe538SGunnar Mills             {
213062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
213142cbe538SGunnar Mills                 callback(inventoryItems);
213242cbe538SGunnar Mills                 return;
213342cbe538SGunnar Mills             }
213442cbe538SGunnar Mills 
213542cbe538SGunnar Mills             const std::string& psAttributesPath = subtree[0].first;
213642cbe538SGunnar Mills             const std::string& connection = subtree[0].second.begin()->first;
213742cbe538SGunnar Mills 
213842cbe538SGunnar Mills             if (connection.empty())
213942cbe538SGunnar Mills             {
214062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
214142cbe538SGunnar Mills                 callback(inventoryItems);
214242cbe538SGunnar Mills                 return;
214342cbe538SGunnar Mills             }
214442cbe538SGunnar Mills 
214542cbe538SGunnar Mills             psAttributesConnections[psAttributesPath] = connection;
214662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
214762598e31SEd Tanous                              connection);
214842cbe538SGunnar Mills 
214942cbe538SGunnar Mills             getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
215042cbe538SGunnar Mills                                          psAttributesConnections,
215142cbe538SGunnar Mills                                          std::move(callback));
215262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2153e99073f5SGeorge Liu         });
215462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
215542cbe538SGunnar Mills }
215642cbe538SGunnar Mills 
215742cbe538SGunnar Mills /**
2158adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
21598fb49dd6SShawn McCarney  *
21608fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2161adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21628fb49dd6SShawn McCarney  *
2163adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2164adc4f0dbSShawn McCarney  * response.
21658fb49dd6SShawn McCarney  *
2166adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2167adc4f0dbSShawn McCarney  * inventory items have been obtained.
2168adc4f0dbSShawn McCarney  *
2169adc4f0dbSShawn McCarney  * The callback must have the following signature:
2170adc4f0dbSShawn McCarney  *   @code
2171adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2172adc4f0dbSShawn McCarney  *   @endcode
21738fb49dd6SShawn McCarney  *
21748fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21758fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21768fb49dd6SShawn McCarney  * implements ObjectManager.
2177adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21788fb49dd6SShawn McCarney  */
2179adc4f0dbSShawn McCarney template <typename Callback>
2180d0090733SEd Tanous static void
2181d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2182fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2183adc4f0dbSShawn McCarney                       Callback&& callback)
21848fb49dd6SShawn McCarney {
218562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2186adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
21878cb2c024SEd Tanous         [sensorsAsyncResp, callback = std::forward<Callback>(callback)](
2188adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
218962598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21908fb49dd6SShawn McCarney             auto getInventoryItemsConnectionsCb =
2191d0090733SEd Tanous                 [sensorsAsyncResp, inventoryItems,
21928cb2c024SEd Tanous                  callback = std::forward<const Callback>(callback)](
2193fe04d49cSNan Zhou                     std::shared_ptr<std::set<std::string>> invConnections) {
219462598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2195bd79bce8SPatrick Williams                     auto getInventoryItemsDataCb =
2196bd79bce8SPatrick Williams                         [sensorsAsyncResp, inventoryItems,
2197d500549bSAnthony Wilson                          callback{std::move(callback)}]() {
219862598e31SEd Tanous                             BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
219942cbe538SGunnar Mills 
2200bd79bce8SPatrick Williams                             auto getInventoryLedsCb =
2201bd79bce8SPatrick Williams                                 [sensorsAsyncResp, inventoryItems,
2202002d39b4SEd Tanous                                  callback{std::move(callback)}]() {
2203bd79bce8SPatrick Williams                                     BMCWEB_LOG_DEBUG(
2204bd79bce8SPatrick Williams                                         "getInventoryLedsCb enter");
2205bd79bce8SPatrick Williams                                     // Find Power Supply Attributes and get the
2206bd79bce8SPatrick Williams                                     // data
2207bd79bce8SPatrick Williams                                     getPowerSupplyAttributes(
2208bd79bce8SPatrick Williams                                         sensorsAsyncResp, inventoryItems,
220942cbe538SGunnar Mills                                         std::move(callback));
221062598e31SEd Tanous                                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
221142cbe538SGunnar Mills                                 };
221242cbe538SGunnar Mills 
2213d500549bSAnthony Wilson                             // Find led connections and get the data
2214d500549bSAnthony Wilson                             getInventoryLeds(sensorsAsyncResp, inventoryItems,
221542cbe538SGunnar Mills                                              std::move(getInventoryLedsCb));
221662598e31SEd Tanous                             BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2217d500549bSAnthony Wilson                         };
22188fb49dd6SShawn McCarney 
2219adc4f0dbSShawn McCarney                     // Get inventory item data from connections
2220adc4f0dbSShawn McCarney                     getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2221d0090733SEd Tanous                                           invConnections,
2222d500549bSAnthony Wilson                                           std::move(getInventoryItemsDataCb));
222362598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
22248fb49dd6SShawn McCarney                 };
22258fb49dd6SShawn McCarney 
2226adc4f0dbSShawn McCarney             // Get connections that provide inventory item data
2227bd79bce8SPatrick Williams             getInventoryItemsConnections(
2228bd79bce8SPatrick Williams                 sensorsAsyncResp, inventoryItems,
22298fb49dd6SShawn McCarney                 std::move(getInventoryItemsConnectionsCb));
223062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
22318fb49dd6SShawn McCarney         };
22328fb49dd6SShawn McCarney 
2233adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2234d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2235adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
223662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2237adc4f0dbSShawn McCarney }
2238adc4f0dbSShawn McCarney 
2239adc4f0dbSShawn McCarney /**
2240adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2241adc4f0dbSShawn McCarney  *
2242adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2243adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2244adc4f0dbSShawn McCarney  * array.
2245adc4f0dbSShawn McCarney  *
2246adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2247adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2248adc4f0dbSShawn McCarney  * object.
2249adc4f0dbSShawn McCarney  *
2250adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2251adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2252adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2253adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2254adc4f0dbSShawn McCarney  */
225523a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2256adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2257adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2258adc4f0dbSShawn McCarney {
225918f8f608SEd Tanous     std::string nameS;
22606f4bd290SAlexander Hansen     nameS.resize(inventoryItem.name.size());
226118f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, nameS.begin(), '_', ' ');
2262adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2263adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2264adc4f0dbSShawn McCarney     {
226518f8f608SEd Tanous         nlohmann::json::iterator nameIt = powerSupply.find("Name");
226618f8f608SEd Tanous         if (nameIt == powerSupply.end())
226718f8f608SEd Tanous         {
226818f8f608SEd Tanous             continue;
226918f8f608SEd Tanous         }
227018f8f608SEd Tanous         const std::string* name = nameIt->get_ptr<std::string*>();
227118f8f608SEd Tanous         if (name == nullptr)
227218f8f608SEd Tanous         {
227318f8f608SEd Tanous             continue;
227418f8f608SEd Tanous         }
227518f8f608SEd Tanous         if (nameS == *name)
2276adc4f0dbSShawn McCarney         {
2277adc4f0dbSShawn McCarney             return powerSupply;
2278adc4f0dbSShawn McCarney         }
2279adc4f0dbSShawn McCarney     }
2280adc4f0dbSShawn McCarney 
2281adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2282adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2283adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2284bd79bce8SPatrick Williams     boost::urls::url url =
2285bd79bce8SPatrick Williams         boost::urls::format("/redfish/v1/Chassis/{}/Power", chassisId);
2286eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2287eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
228818f8f608SEd Tanous     std::string escaped;
22896f4bd290SAlexander Hansen     escaped.resize(inventoryItem.name.size());
229018f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, escaped.begin(), '_', ' ');
229118f8f608SEd Tanous     powerSupply["Name"] = std::move(escaped);
2292adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2293adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2294adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2295adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2296d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2297adc4f0dbSShawn McCarney 
229842cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
229942cbe538SGunnar Mills     {
230042cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
230142cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
230242cbe538SGunnar Mills     }
230342cbe538SGunnar Mills 
2304aaf08ac7SMatt Simmering     powerSupply["Status"]["State"] = getState(&inventoryItem, true);
2305adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2306adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2307adc4f0dbSShawn McCarney 
2308adc4f0dbSShawn McCarney     return powerSupply;
23098fb49dd6SShawn McCarney }
23108fb49dd6SShawn McCarney 
23118fb49dd6SShawn McCarney /**
2312de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2313de629b6eSShawn McCarney  *
2314de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2315de629b6eSShawn McCarney  *
2316de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2317de629b6eSShawn McCarney  * information has been obtained.
2318de629b6eSShawn McCarney  *
2319adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2320de629b6eSShawn McCarney  *
2321de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2322de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2323de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2324de629b6eSShawn McCarney  *
2325de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2326de629b6eSShawn McCarney  *
2327adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2328adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2329adc4f0dbSShawn McCarney  *
2330de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2331adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2332de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2333de629b6eSShawn McCarney  * implements ObjectManager.
2334adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2335de629b6eSShawn McCarney  */
233623a21a1cSEd Tanous inline void getSensorData(
233781ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2338fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2339fe04d49cSNan Zhou     const std::set<std::string>& connections,
2340b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2341de629b6eSShawn McCarney {
234262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2343de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2344de629b6eSShawn McCarney     for (const std::string& connection : connections)
2345de629b6eSShawn McCarney     {
23465eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
23475eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
23485eb468daSGeorge Liu         dbus::utility::getManagedObjects(
23495eb468daSGeorge Liu             connection, sensorPath,
2350002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
23515e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
235202cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
235362598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2354de629b6eSShawn McCarney                 if (ec)
2355de629b6eSShawn McCarney                 {
235662598e31SEd Tanous                     BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
23578d1b46d7Szhanghch05                     messages::internalError(sensorsAsyncResp->asyncResp->res);
2358de629b6eSShawn McCarney                     return;
2359de629b6eSShawn McCarney                 }
2360de629b6eSShawn McCarney                 // Go through all objects and update response with sensor data
2361de629b6eSShawn McCarney                 for (const auto& objDictEntry : resp)
2362de629b6eSShawn McCarney                 {
2363de629b6eSShawn McCarney                     const std::string& objPath =
2364de629b6eSShawn McCarney                         static_cast<const std::string&>(objDictEntry.first);
236562598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
236662598e31SEd Tanous                                      objPath);
2367de629b6eSShawn McCarney 
2368de629b6eSShawn McCarney                     std::vector<std::string> split;
2369de629b6eSShawn McCarney                     // Reserve space for
2370de629b6eSShawn McCarney                     // /xyz/openbmc_project/sensors/<name>/<subname>
2371de629b6eSShawn McCarney                     split.reserve(6);
237250ebd4afSEd Tanous                     // NOLINTNEXTLINE
237350ebd4afSEd Tanous                     bmcweb::split(split, objPath, '/');
2374de629b6eSShawn McCarney                     if (split.size() < 6)
2375de629b6eSShawn McCarney                     {
237662598e31SEd Tanous                         BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
237762598e31SEd Tanous                                          objPath);
2378de629b6eSShawn McCarney                         continue;
2379de629b6eSShawn McCarney                     }
238050ebd4afSEd Tanous                     // These indexes aren't intuitive, as split puts an empty
2381de629b6eSShawn McCarney                     // string at the beginning
2382de629b6eSShawn McCarney                     const std::string& sensorType = split[4];
2383de629b6eSShawn McCarney                     const std::string& sensorName = split[5];
238462598e31SEd Tanous                     BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
238562598e31SEd Tanous                                      sensorType);
238649c53ac9SJohnathan Mantey                     if (sensorNames->find(objPath) == sensorNames->end())
2387de629b6eSShawn McCarney                     {
238862598e31SEd Tanous                         BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
2389de629b6eSShawn McCarney                         continue;
2390de629b6eSShawn McCarney                     }
2391de629b6eSShawn McCarney 
2392adc4f0dbSShawn McCarney                     // Find inventory item (if any) associated with sensor
2393adc4f0dbSShawn McCarney                     InventoryItem* inventoryItem =
2394adc4f0dbSShawn McCarney                         findInventoryItemForSensor(inventoryItems, objPath);
2395adc4f0dbSShawn McCarney 
239695a3ecadSAnthony Wilson                     const std::string& sensorSchema =
239781ce609eSEd Tanous                         sensorsAsyncResp->chassisSubNode;
239895a3ecadSAnthony Wilson 
239995a3ecadSAnthony Wilson                     nlohmann::json* sensorJson = nullptr;
240095a3ecadSAnthony Wilson 
2401928fefb9SNan Zhou                     if (sensorSchema == sensors::node::sensors &&
2402928fefb9SNan Zhou                         !sensorsAsyncResp->efficientExpand)
240395a3ecadSAnthony Wilson                     {
2404*1516c21bSJanet Adkins                         std::string sensorId =
2405*1516c21bSJanet Adkins                             redfish::sensor_utils::getSensorId(sensorName,
2406*1516c21bSJanet Adkins                                                                sensorType);
2407c1d019a6SEd Tanous 
2408bd79bce8SPatrick Williams                         sensorsAsyncResp->asyncResp->res
2409bd79bce8SPatrick Williams                             .jsonValue["@odata.id"] = boost::urls::format(
2410bd79bce8SPatrick Williams                             "/redfish/v1/Chassis/{}/{}/{}",
2411c1d019a6SEd Tanous                             sensorsAsyncResp->chassisId,
2412bd79bce8SPatrick Williams                             sensorsAsyncResp->chassisSubNode, sensorId);
2413bd79bce8SPatrick Williams                         sensorJson =
2414bd79bce8SPatrick Williams                             &(sensorsAsyncResp->asyncResp->res.jsonValue);
241595a3ecadSAnthony Wilson                     }
241695a3ecadSAnthony Wilson                     else
241795a3ecadSAnthony Wilson                     {
2418271584abSEd Tanous                         std::string fieldName;
2419928fefb9SNan Zhou                         if (sensorsAsyncResp->efficientExpand)
2420928fefb9SNan Zhou                         {
2421928fefb9SNan Zhou                             fieldName = "Members";
2422928fefb9SNan Zhou                         }
2423928fefb9SNan Zhou                         else if (sensorType == "temperature")
2424de629b6eSShawn McCarney                         {
2425de629b6eSShawn McCarney                             fieldName = "Temperatures";
2426de629b6eSShawn McCarney                         }
2427bd79bce8SPatrick Williams                         else if (sensorType == "fan" ||
2428bd79bce8SPatrick Williams                                  sensorType == "fan_tach" ||
2429de629b6eSShawn McCarney                                  sensorType == "fan_pwm")
2430de629b6eSShawn McCarney                         {
2431de629b6eSShawn McCarney                             fieldName = "Fans";
2432de629b6eSShawn McCarney                         }
2433de629b6eSShawn McCarney                         else if (sensorType == "voltage")
2434de629b6eSShawn McCarney                         {
2435de629b6eSShawn McCarney                             fieldName = "Voltages";
2436de629b6eSShawn McCarney                         }
2437de629b6eSShawn McCarney                         else if (sensorType == "power")
2438de629b6eSShawn McCarney                         {
243955f79e6fSEd Tanous                             if (sensorName == "total_power")
2440028f7ebcSEddie James                             {
2441028f7ebcSEddie James                                 fieldName = "PowerControl";
2442028f7ebcSEddie James                             }
2443adc4f0dbSShawn McCarney                             else if ((inventoryItem != nullptr) &&
2444adc4f0dbSShawn McCarney                                      (inventoryItem->isPowerSupply))
2445028f7ebcSEddie James                             {
2446de629b6eSShawn McCarney                                 fieldName = "PowerSupplies";
2447de629b6eSShawn McCarney                             }
2448adc4f0dbSShawn McCarney                             else
2449adc4f0dbSShawn McCarney                             {
2450adc4f0dbSShawn McCarney                                 // Other power sensors are in SensorCollection
2451adc4f0dbSShawn McCarney                                 continue;
2452adc4f0dbSShawn McCarney                             }
2453028f7ebcSEddie James                         }
2454de629b6eSShawn McCarney                         else
2455de629b6eSShawn McCarney                         {
2456bd79bce8SPatrick Williams                             BMCWEB_LOG_ERROR(
2457bd79bce8SPatrick Williams                                 "Unsure how to handle sensorType {}",
245862598e31SEd Tanous                                 sensorType);
2459de629b6eSShawn McCarney                             continue;
2460de629b6eSShawn McCarney                         }
2461de629b6eSShawn McCarney 
2462de629b6eSShawn McCarney                         nlohmann::json& tempArray =
2463bd79bce8SPatrick Williams                             sensorsAsyncResp->asyncResp->res
2464bd79bce8SPatrick Williams                                 .jsonValue[fieldName];
2465adc4f0dbSShawn McCarney                         if (fieldName == "PowerControl")
246649c53ac9SJohnathan Mantey                         {
2467adc4f0dbSShawn McCarney                             if (tempArray.empty())
24687ab06f49SGunnar Mills                             {
246995a3ecadSAnthony Wilson                                 // Put multiple "sensors" into a single
247095a3ecadSAnthony Wilson                                 // PowerControl. Follows MemberId naming and
247195a3ecadSAnthony Wilson                                 // naming in power.hpp.
24721476687dSEd Tanous                                 nlohmann::json::object_t power;
2473ef4c65b7SEd Tanous                                 boost::urls::url url = boost::urls::format(
2474ef4c65b7SEd Tanous                                     "/redfish/v1/Chassis/{}/{}",
2475eddfc437SWilly Tu                                     sensorsAsyncResp->chassisId,
2476eddfc437SWilly Tu                                     sensorsAsyncResp->chassisSubNode);
2477bd79bce8SPatrick Williams                                 url.set_fragment(
2478bd79bce8SPatrick Williams                                     (""_json_pointer / fieldName / "0")
2479eddfc437SWilly Tu                                         .to_string());
2480eddfc437SWilly Tu                                 power["@odata.id"] = std::move(url);
2481b2ba3072SPatrick Williams                                 tempArray.emplace_back(std::move(power));
2482adc4f0dbSShawn McCarney                             }
2483adc4f0dbSShawn McCarney                             sensorJson = &(tempArray.back());
2484adc4f0dbSShawn McCarney                         }
2485adc4f0dbSShawn McCarney                         else if (fieldName == "PowerSupplies")
2486adc4f0dbSShawn McCarney                         {
2487adc4f0dbSShawn McCarney                             if (inventoryItem != nullptr)
2488adc4f0dbSShawn McCarney                             {
2489bd79bce8SPatrick Williams                                 sensorJson = &(getPowerSupply(
2490bd79bce8SPatrick Williams                                     tempArray, *inventoryItem,
249181ce609eSEd Tanous                                     sensorsAsyncResp->chassisId));
2492adc4f0dbSShawn McCarney                             }
249349c53ac9SJohnathan Mantey                         }
2494928fefb9SNan Zhou                         else if (fieldName == "Members")
2495928fefb9SNan Zhou                         {
2496*1516c21bSJanet Adkins                             std::string sensorId =
2497*1516c21bSJanet Adkins                                 redfish::sensor_utils::getSensorId(sensorName,
2498*1516c21bSJanet Adkins                                                                    sensorType);
2499677bb756SEd Tanous 
25001476687dSEd Tanous                             nlohmann::json::object_t member;
2501ef4c65b7SEd Tanous                             member["@odata.id"] = boost::urls::format(
2502ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}/{}",
2503677bb756SEd Tanous                                 sensorsAsyncResp->chassisId,
2504677bb756SEd Tanous                                 sensorsAsyncResp->chassisSubNode, sensorId);
2505b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(member));
2506928fefb9SNan Zhou                             sensorJson = &(tempArray.back());
2507928fefb9SNan Zhou                         }
250849c53ac9SJohnathan Mantey                         else
250949c53ac9SJohnathan Mantey                         {
25101476687dSEd Tanous                             nlohmann::json::object_t member;
2511ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2512ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2513eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2514eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2515eddfc437SWilly Tu                             url.set_fragment(
2516eddfc437SWilly Tu                                 (""_json_pointer / fieldName).to_string());
2517eddfc437SWilly Tu                             member["@odata.id"] = std::move(url);
2518b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(member));
2519adc4f0dbSShawn McCarney                             sensorJson = &(tempArray.back());
252049c53ac9SJohnathan Mantey                         }
252195a3ecadSAnthony Wilson                     }
2522de629b6eSShawn McCarney 
2523adc4f0dbSShawn McCarney                     if (sensorJson != nullptr)
2524adc4f0dbSShawn McCarney                     {
25251d7c0054SEd Tanous                         objectInterfacesToJson(sensorName, sensorType,
25261d7c0054SEd Tanous                                                sensorsAsyncResp->chassisSubNode,
25271d7c0054SEd Tanous                                                objDictEntry.second, *sensorJson,
25281d7c0054SEd Tanous                                                inventoryItem);
25291d7c0054SEd Tanous 
25301d7c0054SEd Tanous                         std::string path = "/xyz/openbmc_project/sensors/";
25311d7c0054SEd Tanous                         path += sensorType;
25321d7c0054SEd Tanous                         path += "/";
25331d7c0054SEd Tanous                         path += sensorName;
2534c1d019a6SEd Tanous                         sensorsAsyncResp->addMetadata(*sensorJson, path);
2535adc4f0dbSShawn McCarney                     }
2536de629b6eSShawn McCarney                 }
253781ce609eSEd Tanous                 if (sensorsAsyncResp.use_count() == 1)
253849c53ac9SJohnathan Mantey                 {
253981ce609eSEd Tanous                     sortJSONResponse(sensorsAsyncResp);
2540928fefb9SNan Zhou                     if (sensorsAsyncResp->chassisSubNode ==
2541928fefb9SNan Zhou                             sensors::node::sensors &&
2542928fefb9SNan Zhou                         sensorsAsyncResp->efficientExpand)
2543928fefb9SNan Zhou                     {
2544928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res
2545928fefb9SNan Zhou                             .jsonValue["Members@odata.count"] =
2546bd79bce8SPatrick Williams                             sensorsAsyncResp->asyncResp->res
2547bd79bce8SPatrick Williams                                 .jsonValue["Members"]
2548928fefb9SNan Zhou                                 .size();
2549928fefb9SNan Zhou                     }
2550928fefb9SNan Zhou                     else if (sensorsAsyncResp->chassisSubNode ==
2551928fefb9SNan Zhou                              sensors::node::thermal)
25528bd25ccdSJames Feist                     {
255381ce609eSEd Tanous                         populateFanRedundancy(sensorsAsyncResp);
25548bd25ccdSJames Feist                     }
255549c53ac9SJohnathan Mantey                 }
255662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
25575eb468daSGeorge Liu             });
255823a21a1cSEd Tanous     }
255962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData exit");
2560de629b6eSShawn McCarney }
2561de629b6eSShawn McCarney 
2562fe04d49cSNan Zhou inline void
2563fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2564fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
25651abe55efSEd Tanous {
2566fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2567fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
256862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb enter");
2569adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2570bd79bce8SPatrick Williams             [sensorsAsyncResp, sensorNames, connections](
2571bd79bce8SPatrick Williams                 const std::shared_ptr<std::vector<InventoryItem>>&
2572adc4f0dbSShawn McCarney                     inventoryItems) {
257362598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
257449c53ac9SJohnathan Mantey                 // Get sensor data and store results in JSON
2575002d39b4SEd Tanous                 getSensorData(sensorsAsyncResp, sensorNames, connections,
2576d0090733SEd Tanous                               inventoryItems);
257762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsCb exit");
2578adc4f0dbSShawn McCarney             };
2579adc4f0dbSShawn McCarney 
2580adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2581d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2582adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2583adc4f0dbSShawn McCarney 
258462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb exit");
258508777fb0SLewanczyk, Dawid     };
2586de629b6eSShawn McCarney 
2587de629b6eSShawn McCarney     // Get set of connections that provide sensor values
258881ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
258995a3ecadSAnthony Wilson }
259095a3ecadSAnthony Wilson 
259195a3ecadSAnthony Wilson /**
259295a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
259395a3ecadSAnthony Wilson  *        chassis.
259495a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
259595a3ecadSAnthony Wilson  */
2596b5a76932SEd Tanous inline void
259781ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
259895a3ecadSAnthony Wilson {
259962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
260095a3ecadSAnthony Wilson     auto getChassisCb =
260181ce609eSEd Tanous         [sensorsAsyncResp](
2602fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
260362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getChassisCb enter");
260481ce609eSEd Tanous             processSensorList(sensorsAsyncResp, sensorNames);
260562598e31SEd Tanous             BMCWEB_LOG_DEBUG("getChassisCb exit");
260608777fb0SLewanczyk, Dawid         };
2607928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2608928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2609928fefb9SNan Zhou     {
26108d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
26118d1b46d7Szhanghch05             nlohmann::json::array();
2612928fefb9SNan Zhou     }
261326f03899SShawn McCarney     // Get set of sensors in chassis
26147f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
26157f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
26167f1cc26dSEd Tanous                std::move(getChassisCb));
261762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData exit");
2618271584abSEd Tanous }
261908777fb0SLewanczyk, Dawid 
2620413961deSRichard Marian Thomaiyar /**
262149c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
262249c53ac9SJohnathan Mantey  * the chassis node
262349c53ac9SJohnathan Mantey  *
262449c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
262549c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
262649c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
262749c53ac9SJohnathan Mantey  *                         repeated calls to this function
262849c53ac9SJohnathan Mantey  */
2629bd79bce8SPatrick Williams inline bool findSensorNameUsingSensorPath(
2630bd79bce8SPatrick Williams     std::string_view sensorName, const std::set<std::string>& sensorsList,
2631fe04d49cSNan Zhou     std::set<std::string>& sensorsModified)
263249c53ac9SJohnathan Mantey {
2633fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
263449c53ac9SJohnathan Mantey     {
263528aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2636b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
263728aa8de5SGeorge Liu         if (thisSensorName.empty())
263849c53ac9SJohnathan Mantey         {
263949c53ac9SJohnathan Mantey             continue;
264049c53ac9SJohnathan Mantey         }
264149c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
264249c53ac9SJohnathan Mantey         {
264349c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
264449c53ac9SJohnathan Mantey             return true;
264549c53ac9SJohnathan Mantey         }
264649c53ac9SJohnathan Mantey     }
264749c53ac9SJohnathan Mantey     return false;
264849c53ac9SJohnathan Mantey }
264949c53ac9SJohnathan Mantey 
265049c53ac9SJohnathan Mantey /**
2651413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2652413961deSRichard Marian Thomaiyar  *
26538d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
26544bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2655413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2656413961deSRichard Marian Thomaiyar  */
265723a21a1cSEd Tanous inline void setSensorsOverride(
2658b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26590885057cSEd Tanous     std::unordered_map<std::string, std::vector<nlohmann::json::object_t>>&
2660397fd61fSjayaprakash Mutyala         allCollections)
2661413961deSRichard Marian Thomaiyar {
266262598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
266362598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
2664413961deSRichard Marian Thomaiyar 
2665d02aad39SEd Tanous     std::string_view propertyValueName;
2666f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2667413961deSRichard Marian Thomaiyar     std::string memberId;
2668543f4400SEd Tanous     double value = 0.0;
2669f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2670f65af9e8SRichard Marian Thomaiyar     {
2671f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2672f65af9e8SRichard Marian Thomaiyar         {
2673f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2674f65af9e8SRichard Marian Thomaiyar         }
2675f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2676f65af9e8SRichard Marian Thomaiyar         {
2677f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2678f65af9e8SRichard Marian Thomaiyar         }
2679f65af9e8SRichard Marian Thomaiyar         else
2680f65af9e8SRichard Marian Thomaiyar         {
2681f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2682f65af9e8SRichard Marian Thomaiyar         }
2683f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2684f65af9e8SRichard Marian Thomaiyar         {
26850885057cSEd Tanous             if (!json_util::readJsonObject(
26860885057cSEd Tanous                     item, sensorAsyncResp->asyncResp->res, "MemberId", memberId,
26870885057cSEd Tanous                     propertyValueName, value))
2688413961deSRichard Marian Thomaiyar             {
2689413961deSRichard Marian Thomaiyar                 return;
2690413961deSRichard Marian Thomaiyar             }
2691f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2692f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2693f65af9e8SRichard Marian Thomaiyar         }
2694f65af9e8SRichard Marian Thomaiyar     }
26954bb3dc34SCarol Wang 
2696bd79bce8SPatrick Williams     auto getChassisSensorListCb = [sensorAsyncResp, overrideMap,
2697bd79bce8SPatrick Williams                                    propertyValueNameStr =
2698bd79bce8SPatrick Williams                                        std::string(propertyValueName)](
2699bd79bce8SPatrick Williams                                       const std::shared_ptr<
2700bd79bce8SPatrick Williams                                           std::set<std::string>>& sensorsList) {
270149c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
270249c53ac9SJohnathan Mantey         // chassis node
2703fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2704fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2705f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2706413961deSRichard Marian Thomaiyar         {
2707f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2708c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2709*1516c21bSJanet Adkins                 redfish::sensor_utils::splitSensorNameAndType(sensor);
2710c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2711c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2712f65af9e8SRichard Marian Thomaiyar             {
271362598e31SEd Tanous                 BMCWEB_LOG_INFO("Unable to find memberId {}", item.first);
27148d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2715f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2716413961deSRichard Marian Thomaiyar                 return;
2717413961deSRichard Marian Thomaiyar             }
2718f65af9e8SRichard Marian Thomaiyar         }
2719413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2720bd79bce8SPatrick Williams         auto getObjectsWithConnectionCb = [sensorAsyncResp, overrideMap,
2721bd79bce8SPatrick Williams                                            propertyValueNameStr](
2722bd79bce8SPatrick Williams                                               const std::set<
2723bd79bce8SPatrick Williams                                                   std::string>& /*connections*/,
2724bd79bce8SPatrick Williams                                               const std::set<std::pair<
2725bd79bce8SPatrick Williams                                                   std::string, std::string>>&
2726413961deSRichard Marian Thomaiyar                                                   objectsWithConnection) {
2727f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2728413961deSRichard Marian Thomaiyar             {
272962598e31SEd Tanous                 BMCWEB_LOG_INFO(
273062598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
273162598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
2732bd79bce8SPatrick Williams                 messages::resourceNotFound(
2733bd79bce8SPatrick Williams                     sensorAsyncResp->asyncResp->res,
2734bd79bce8SPatrick Williams                     sensorAsyncResp->chassisSubNode == sensors::node::thermal
2735413961deSRichard Marian Thomaiyar                         ? "Temperatures"
2736413961deSRichard Marian Thomaiyar                         : "Voltages",
2737f65af9e8SRichard Marian Thomaiyar                     "Count");
2738f65af9e8SRichard Marian Thomaiyar                 return;
2739f65af9e8SRichard Marian Thomaiyar             }
2740f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2741f65af9e8SRichard Marian Thomaiyar             {
274228aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
274328aa8de5SGeorge Liu                 std::string sensorName = path.filename();
274428aa8de5SGeorge Liu                 if (sensorName.empty())
2745f65af9e8SRichard Marian Thomaiyar                 {
27464f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2747f65af9e8SRichard Marian Thomaiyar                     return;
2748f65af9e8SRichard Marian Thomaiyar                 }
2749*1516c21bSJanet Adkins                 std::string id = redfish::sensor_utils::getSensorId(
2750*1516c21bSJanet Adkins                     sensorName, path.parent_path().filename());
2751f65af9e8SRichard Marian Thomaiyar 
27523f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2753f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2754f65af9e8SRichard Marian Thomaiyar                 {
275562598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
275662598e31SEd Tanous                                     item.first);
27574f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2758413961deSRichard Marian Thomaiyar                     return;
2759413961deSRichard Marian Thomaiyar                 }
2760e93abac6SGinu George                 setDbusProperty(sensorAsyncResp->asyncResp,
2761e93abac6SGinu George                                 propertyValueNameStr, item.second, item.first,
2762e93abac6SGinu George                                 "xyz.openbmc_project.Sensor.Value", "Value",
2763d02aad39SEd Tanous                                 iterator->second.first);
2764f65af9e8SRichard Marian Thomaiyar             }
2765413961deSRichard Marian Thomaiyar         };
2766413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2767413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2768413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2769413961deSRichard Marian Thomaiyar     };
2770413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27717f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27727f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27737f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2774413961deSRichard Marian Thomaiyar }
2775413961deSRichard Marian Thomaiyar 
2776a0ec28b6SAdrian Ambrożewicz /**
2777a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2778a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2779a0ec28b6SAdrian Ambrożewicz  *
2780a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2781a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2782a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2783a0ec28b6SAdrian Ambrożewicz  *
2784a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2785a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2786a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2787a0ec28b6SAdrian Ambrożewicz  */
2788931edc79SEd Tanous template <typename Callback>
2789bd79bce8SPatrick Williams inline void retrieveUriToDbusMap(
2790bd79bce8SPatrick Williams     const std::string& chassis, const std::string& node, Callback&& mapComplete)
2791a0ec28b6SAdrian Ambrożewicz {
279202da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
279302da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
279402da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
279502da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2796a0ec28b6SAdrian Ambrożewicz     {
279762598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
27986804b5c8SEd Tanous         std::map<std::string, std::string> noop;
27996804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2800a0ec28b6SAdrian Ambrożewicz         return;
2801a0ec28b6SAdrian Ambrożewicz     }
2802d51e072fSKrzysztof Grobelny 
280372374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2804bd79bce8SPatrick Williams     auto callback =
2805bd79bce8SPatrick Williams         [asyncResp, mapCompleteCb = std::forward<Callback>(mapComplete)](
2806a0ec28b6SAdrian Ambrożewicz             const boost::beast::http::status status,
2807fe04d49cSNan Zhou             const std::map<std::string, std::string>& uriToDbus) {
2808fe04d49cSNan Zhou             mapCompleteCb(status, uriToDbus);
2809fe04d49cSNan Zhou         };
2810a0ec28b6SAdrian Ambrożewicz 
2811a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2812d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2813a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2814a0ec28b6SAdrian Ambrożewicz }
2815a0ec28b6SAdrian Ambrożewicz 
2816bacb2162SNan Zhou namespace sensors
2817bacb2162SNan Zhou {
2818928fefb9SNan Zhou 
2819bacb2162SNan Zhou inline void getChassisCallback(
2820c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2821c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2822fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2823bacb2162SNan Zhou {
282462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2825bacb2162SNan Zhou 
2826c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2827c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2828bacb2162SNan Zhou     {
282962598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2830bacb2162SNan Zhou 
2831bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2832bacb2162SNan Zhou         std::string sensorName = path.filename();
2833bacb2162SNan Zhou         if (sensorName.empty())
2834bacb2162SNan Zhou         {
283562598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2836c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2837bacb2162SNan Zhou             return;
2838bacb2162SNan Zhou         }
2839c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2840*1516c21bSJanet Adkins         std::string id = redfish::sensor_utils::getSensorId(sensorName, type);
2841c1d019a6SEd Tanous 
28421476687dSEd Tanous         nlohmann::json::object_t member;
2843ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2844ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2845c1d019a6SEd Tanous 
2846b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2847bacb2162SNan Zhou     }
2848bacb2162SNan Zhou 
2849c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
285062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2851bacb2162SNan Zhou }
2852e6bd846dSNan Zhou 
2853ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2854ac106bf6SEd Tanous     App& app, const crow::Request& req,
2855ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2856de167a6fSNan Zhou     const std::string& chassisId)
2857de167a6fSNan Zhou {
2858de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2859de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2860de167a6fSNan Zhou     };
2861de167a6fSNan Zhou     query_param::Query delegatedQuery;
2862ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2863de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2864de167a6fSNan Zhou     {
2865de167a6fSNan Zhou         return;
2866de167a6fSNan Zhou     }
2867de167a6fSNan Zhou 
2868de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2869de167a6fSNan Zhou     {
2870de167a6fSNan Zhou         // we perform efficient expand.
2871ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2872ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2873de167a6fSNan Zhou             sensors::node::sensors,
2874de167a6fSNan Zhou             /*efficientExpand=*/true);
2875ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2876de167a6fSNan Zhou 
287762598e31SEd Tanous         BMCWEB_LOG_DEBUG(
287862598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2879de167a6fSNan Zhou         return;
28800bad320cSEd Tanous     }
2881de167a6fSNan Zhou 
2882de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2883de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2884ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2885ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2886ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2887c1d019a6SEd Tanous }
28887f1cc26dSEd Tanous 
2889c1d019a6SEd Tanous inline void
2890c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2891c1d019a6SEd Tanous                       const std::string& sensorPath,
2892c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2893c1d019a6SEd Tanous {
2894c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2895c1d019a6SEd Tanous     {
2896c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2897c1d019a6SEd Tanous         return;
2898c1d019a6SEd Tanous     }
2899c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2900c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
290162598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
290262598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2903c1343bf6SKrzysztof Grobelny 
2904c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2905c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2906c1d019a6SEd Tanous         [asyncResp,
29075e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2908c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2909c1d019a6SEd Tanous             if (ec)
2910c1d019a6SEd Tanous             {
2911c1d019a6SEd Tanous                 messages::internalError(asyncResp->res);
2912c1d019a6SEd Tanous                 return;
2913c1d019a6SEd Tanous             }
2914c1d019a6SEd Tanous             sdbusplus::message::object_path path(sensorPath);
2915c1d019a6SEd Tanous             std::string name = path.filename();
2916c1d019a6SEd Tanous             path = path.parent_path();
2917c1d019a6SEd Tanous             std::string type = path.filename();
2918bd79bce8SPatrick Williams             objectPropertiesToJson(name, type, sensors::node::sensors,
2919bd79bce8SPatrick Williams                                    valuesDict, asyncResp->res.jsonValue,
2920bd79bce8SPatrick Williams                                    nullptr);
2921c1343bf6SKrzysztof Grobelny         });
2922de167a6fSNan Zhou }
2923de167a6fSNan Zhou 
2924e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2925c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2926677bb756SEd Tanous                             const std::string& chassisId,
2927c1d019a6SEd Tanous                             const std::string& sensorId)
2928e6bd846dSNan Zhou {
2929c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2930e6bd846dSNan Zhou     {
2931e6bd846dSNan Zhou         return;
2932e6bd846dSNan Zhou     }
2933c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2934*1516c21bSJanet Adkins         redfish::sensor_utils::splitSensorNameAndType(sensorId);
2935c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2936c1d019a6SEd Tanous     {
2937c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2938c1d019a6SEd Tanous         return;
2939c1d019a6SEd Tanous     }
2940c71d6125SEd Tanous 
2941ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2942ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2943c1d019a6SEd Tanous 
294462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2945e6bd846dSNan Zhou 
29462b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2947e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2948c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2949c71d6125SEd Tanous                              '/' + nameType.second;
2950e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2951e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29522b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29532b73119cSGeorge Liu         sensorPath, interfaces,
2954aec0ec30SMyung Bae         [asyncResp, sensorId,
29552b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2956c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
295762598e31SEd Tanous             BMCWEB_LOG_DEBUG("respHandler1 enter");
2958aec0ec30SMyung Bae             if (ec == boost::system::errc::io_error)
2959aec0ec30SMyung Bae             {
296062598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2961aec0ec30SMyung Bae                 messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2962aec0ec30SMyung Bae                 return;
2963aec0ec30SMyung Bae             }
2964e6bd846dSNan Zhou             if (ec)
2965e6bd846dSNan Zhou             {
2966c1d019a6SEd Tanous                 messages::internalError(asyncResp->res);
296762598e31SEd Tanous                 BMCWEB_LOG_ERROR(
296862598e31SEd Tanous                     "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2969e6bd846dSNan Zhou                 return;
2970e6bd846dSNan Zhou             }
2971c1d019a6SEd Tanous             getSensorFromDbus(asyncResp, sensorPath, subtree);
297262598e31SEd Tanous             BMCWEB_LOG_DEBUG("respHandler1 exit");
29732b73119cSGeorge Liu         });
2974e6bd846dSNan Zhou }
2975e6bd846dSNan Zhou 
2976bacb2162SNan Zhou } // namespace sensors
2977bacb2162SNan Zhou 
29787e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
297995a3ecadSAnthony Wilson {
29807e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2981ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2982002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2983de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
298495a3ecadSAnthony Wilson }
298595a3ecadSAnthony Wilson 
29867e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
298795a3ecadSAnthony Wilson {
29887e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2989ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2990002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2991e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
299295a3ecadSAnthony Wilson }
299395a3ecadSAnthony Wilson 
299408777fb0SLewanczyk, Dawid } // namespace redfish
2995