xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 8cb2c024c4625e2fe2f0b107a865faffcd4bb770)
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"
21aaf08ac7SMatt Simmering #include "generated/enums/resource.hpp"
220ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
233ccb3adbSEd Tanous #include "query.hpp"
243ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2550ebd4afSEd Tanous #include "str_utility.hpp"
263ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
273ccb3adbSEd Tanous #include "utils/json_utils.hpp"
283ccb3adbSEd Tanous #include "utils/query_param.hpp"
290ec8b83dSEd Tanous 
30e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
31ef4c65b7SEd Tanous #include <boost/url/format.hpp>
321e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3386d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
341214b7e7SGunnar Mills 
357a1dbc48SGeorge Liu #include <array>
361214b7e7SGunnar Mills #include <cmath>
37fe04d49cSNan Zhou #include <iterator>
38283860f5SEd Tanous #include <limits>
39fe04d49cSNan Zhou #include <map>
403544d2a7SEd Tanous #include <ranges>
41fe04d49cSNan Zhou #include <set>
4218f8f608SEd Tanous #include <string>
437a1dbc48SGeorge Liu #include <string_view>
44b5a76932SEd Tanous #include <utility>
45abf2add6SEd Tanous #include <variant>
4608777fb0SLewanczyk, Dawid 
471abe55efSEd Tanous namespace redfish
481abe55efSEd Tanous {
4908777fb0SLewanczyk, Dawid 
50a0ec28b6SAdrian Ambrożewicz namespace sensors
51a0ec28b6SAdrian Ambrożewicz {
52a0ec28b6SAdrian Ambrożewicz namespace node
53a0ec28b6SAdrian Ambrożewicz {
54a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
55a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
56a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
57a0ec28b6SAdrian Ambrożewicz } // namespace node
58a0ec28b6SAdrian Ambrożewicz 
5902da7c5aSEd Tanous // clang-format off
60a0ec28b6SAdrian Ambrożewicz namespace dbus
61a0ec28b6SAdrian Ambrożewicz {
62cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6402da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6502da7c5aSEd Tanous });
66c2bf7f99SWludzik, Jozef 
67cf9e417dSEd Tanous constexpr auto sensorPaths = std::to_array<std::string_view>({
6802da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
69a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
707088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
715deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
72e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
73e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
74e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
75e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
76e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
77e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
78e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
79e8204933SGeorge Liu #endif
8002da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
8102da7c5aSEd Tanous });
8202da7c5aSEd Tanous 
83cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
8402da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
85a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
8702da7c5aSEd Tanous });
8802da7c5aSEd Tanous 
89c2bf7f99SWludzik, Jozef } // namespace dbus
9002da7c5aSEd Tanous // clang-format on
9102da7c5aSEd Tanous 
92cf9e417dSEd Tanous using sensorPair =
93cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
9402da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
95cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
96cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
97cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
98c2bf7f99SWludzik, Jozef 
990ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
100c2bf7f99SWludzik, Jozef {
101c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
102c2bf7f99SWludzik, Jozef     {
1030ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
104c2bf7f99SWludzik, Jozef     }
105c2bf7f99SWludzik, Jozef     if (sensorType == "power")
106c2bf7f99SWludzik, Jozef     {
1070ec8b83dSEd Tanous         return sensor::ReadingType::Power;
108c2bf7f99SWludzik, Jozef     }
109c2bf7f99SWludzik, Jozef     if (sensorType == "current")
110c2bf7f99SWludzik, Jozef     {
1110ec8b83dSEd Tanous         return sensor::ReadingType::Current;
112c2bf7f99SWludzik, Jozef     }
113c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
114c2bf7f99SWludzik, Jozef     {
1150ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
116c2bf7f99SWludzik, Jozef     }
117c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
118c2bf7f99SWludzik, Jozef     {
1190ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
120c2bf7f99SWludzik, Jozef     }
121c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
122c2bf7f99SWludzik, Jozef     {
1230ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
124c2bf7f99SWludzik, Jozef     }
1255deabed9SGunnar Mills     if (sensorType == "humidity")
1265deabed9SGunnar Mills     {
1270ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1285deabed9SGunnar Mills     }
129c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
130c2bf7f99SWludzik, Jozef     {
1310ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
132c2bf7f99SWludzik, Jozef     }
133c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
134c2bf7f99SWludzik, Jozef     {
1350ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
136c2bf7f99SWludzik, Jozef     }
137c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
138c2bf7f99SWludzik, Jozef     {
1390ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
140c2bf7f99SWludzik, Jozef     }
1410ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
142c2bf7f99SWludzik, Jozef }
143c2bf7f99SWludzik, Jozef 
1441d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
145c2bf7f99SWludzik, Jozef {
146c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
147c2bf7f99SWludzik, Jozef     {
148c2bf7f99SWludzik, Jozef         return "V";
149c2bf7f99SWludzik, Jozef     }
150c2bf7f99SWludzik, Jozef     if (sensorType == "power")
151c2bf7f99SWludzik, Jozef     {
152c2bf7f99SWludzik, Jozef         return "W";
153c2bf7f99SWludzik, Jozef     }
154c2bf7f99SWludzik, Jozef     if (sensorType == "current")
155c2bf7f99SWludzik, Jozef     {
156c2bf7f99SWludzik, Jozef         return "A";
157c2bf7f99SWludzik, Jozef     }
158c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
159c2bf7f99SWludzik, Jozef     {
160c2bf7f99SWludzik, Jozef         return "RPM";
161c2bf7f99SWludzik, Jozef     }
162c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
163c2bf7f99SWludzik, Jozef     {
164c2bf7f99SWludzik, Jozef         return "Cel";
165c2bf7f99SWludzik, Jozef     }
1665deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1675deabed9SGunnar Mills         sensorType == "humidity")
168c2bf7f99SWludzik, Jozef     {
169c2bf7f99SWludzik, Jozef         return "%";
170c2bf7f99SWludzik, Jozef     }
171c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
172c2bf7f99SWludzik, Jozef     {
173c2bf7f99SWludzik, Jozef         return "m";
174c2bf7f99SWludzik, Jozef     }
175c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
176c2bf7f99SWludzik, Jozef     {
177c2bf7f99SWludzik, Jozef         return "cft_i/min";
178c2bf7f99SWludzik, Jozef     }
179c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
180c2bf7f99SWludzik, Jozef     {
181c2bf7f99SWludzik, Jozef         return "J";
182c2bf7f99SWludzik, Jozef     }
183c2bf7f99SWludzik, Jozef     return "";
184a0ec28b6SAdrian Ambrożewicz }
185a0ec28b6SAdrian Ambrożewicz } // namespace sensors
186a0ec28b6SAdrian Ambrożewicz 
18708777fb0SLewanczyk, Dawid /**
188588c3f0dSKowalski, Kamil  * SensorsAsyncResp
18908777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
19008777fb0SLewanczyk, Dawid  */
1911abe55efSEd Tanous class SensorsAsyncResp
1921abe55efSEd Tanous {
19308777fb0SLewanczyk, Dawid   public:
194a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
195a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
196fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
197a0ec28b6SAdrian Ambrożewicz 
198a0ec28b6SAdrian Ambrożewicz     struct SensorData
199a0ec28b6SAdrian Ambrożewicz     {
200a0ec28b6SAdrian Ambrożewicz         const std::string name;
201a0ec28b6SAdrian Ambrożewicz         std::string uri;
202a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
203a0ec28b6SAdrian Ambrożewicz     };
204a0ec28b6SAdrian Ambrożewicz 
2058a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2068d1b46d7Szhanghch05                      const std::string& chassisIdIn,
207cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
20802da7c5aSEd Tanous                      std::string_view subNode) :
2098a592810SEd Tanous         asyncResp(asyncRespIn),
210928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
211928fefb9SNan Zhou         efficientExpand(false)
2121214b7e7SGunnar Mills     {}
21308777fb0SLewanczyk, Dawid 
214a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2158a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2168d1b46d7Szhanghch05                      const std::string& chassisIdIn,
217cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21802da7c5aSEd Tanous                      std::string_view subNode,
219a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2208a592810SEd Tanous         asyncResp(asyncRespIn),
221928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
222928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
223a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
224a0ec28b6SAdrian Ambrożewicz     {}
225a0ec28b6SAdrian Ambrożewicz 
226928fefb9SNan Zhou     // sensor collections expand
2278a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
228928fefb9SNan Zhou                      const std::string& chassisIdIn,
229cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2308a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2318a592810SEd Tanous         asyncResp(asyncRespIn),
232928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2338a592810SEd Tanous         efficientExpand(efficientExpandIn)
234928fefb9SNan Zhou     {}
235928fefb9SNan Zhou 
2361abe55efSEd Tanous     ~SensorsAsyncResp()
2371abe55efSEd Tanous     {
2388d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2398d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2401abe55efSEd Tanous         {
2411abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2421abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2431abe55efSEd Tanous             // proper code
2448d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24508777fb0SLewanczyk, Dawid         }
246a0ec28b6SAdrian Ambrożewicz 
247a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
248a0ec28b6SAdrian Ambrożewicz         {
249fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2508d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
251a0ec28b6SAdrian Ambrożewicz             {
252a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
253a0ec28b6SAdrian Ambrożewicz                 {
254c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
255a0ec28b6SAdrian Ambrożewicz                 }
256a0ec28b6SAdrian Ambrożewicz             }
2578d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
258a0ec28b6SAdrian Ambrożewicz         }
25908777fb0SLewanczyk, Dawid     }
260588c3f0dSKowalski, Kamil 
261ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
262ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
263ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
264ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
265ecd6a3a2SEd Tanous 
266a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
267c1d019a6SEd Tanous                      const std::string& dbusPath)
268a0ec28b6SAdrian Ambrożewicz     {
269a0ec28b6SAdrian Ambrożewicz         if (metadata)
270a0ec28b6SAdrian Ambrożewicz         {
271c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
272c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
273a0ec28b6SAdrian Ambrożewicz         }
274a0ec28b6SAdrian Ambrożewicz     }
275a0ec28b6SAdrian Ambrożewicz 
276a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
277a0ec28b6SAdrian Ambrożewicz     {
278a0ec28b6SAdrian Ambrożewicz         if (metadata)
279a0ec28b6SAdrian Ambrożewicz         {
280a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
281a0ec28b6SAdrian Ambrożewicz             {
282a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
283a0ec28b6SAdrian Ambrożewicz                 {
284a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
285a0ec28b6SAdrian Ambrożewicz                 }
286a0ec28b6SAdrian Ambrożewicz             }
287a0ec28b6SAdrian Ambrożewicz         }
288a0ec28b6SAdrian Ambrożewicz     }
289a0ec28b6SAdrian Ambrożewicz 
2908d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
291a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
292cf9e417dSEd Tanous     const std::span<const std::string_view> types;
293a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
294928fefb9SNan Zhou     const bool efficientExpand;
295a0ec28b6SAdrian Ambrożewicz 
296a0ec28b6SAdrian Ambrożewicz   private:
297a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
298a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
29908777fb0SLewanczyk, Dawid };
30008777fb0SLewanczyk, Dawid 
30108777fb0SLewanczyk, Dawid /**
302d500549bSAnthony Wilson  * Possible states for physical inventory leds
303d500549bSAnthony Wilson  */
304d500549bSAnthony Wilson enum class LedState
305d500549bSAnthony Wilson {
306d500549bSAnthony Wilson     OFF,
307d500549bSAnthony Wilson     ON,
308d500549bSAnthony Wilson     BLINK,
309d500549bSAnthony Wilson     UNKNOWN
310d500549bSAnthony Wilson };
311d500549bSAnthony Wilson 
312d500549bSAnthony Wilson /**
313adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
314adc4f0dbSShawn McCarney  */
315adc4f0dbSShawn McCarney class InventoryItem
316adc4f0dbSShawn McCarney {
317adc4f0dbSShawn McCarney   public:
3184e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
319adc4f0dbSShawn McCarney     {
320adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
32128aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
32228aa8de5SGeorge Liu         name = path.filename();
32328aa8de5SGeorge Liu         if (name.empty())
324adc4f0dbSShawn McCarney         {
32562598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
326adc4f0dbSShawn McCarney         }
327adc4f0dbSShawn McCarney     }
328adc4f0dbSShawn McCarney 
329adc4f0dbSShawn McCarney     std::string objectPath;
330adc4f0dbSShawn McCarney     std::string name;
331e05aec50SEd Tanous     bool isPresent = true;
332e05aec50SEd Tanous     bool isFunctional = true;
333e05aec50SEd Tanous     bool isPowerSupply = false;
334e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
335adc4f0dbSShawn McCarney     std::string manufacturer;
336adc4f0dbSShawn McCarney     std::string model;
337adc4f0dbSShawn McCarney     std::string partNumber;
338adc4f0dbSShawn McCarney     std::string serialNumber;
339adc4f0dbSShawn McCarney     std::set<std::string> sensors;
340d500549bSAnthony Wilson     std::string ledObjectPath;
341e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
342adc4f0dbSShawn McCarney };
343adc4f0dbSShawn McCarney 
344adc4f0dbSShawn McCarney /**
345413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
346588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
34708777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
34808777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
34908777fb0SLewanczyk, Dawid  */
35008777fb0SLewanczyk, Dawid template <typename Callback>
351413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
35281ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
353fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3541abe55efSEd Tanous     Callback&& callback)
3551abe55efSEd Tanous {
35662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
35703b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
358e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
35908777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
36008777fb0SLewanczyk, Dawid 
361e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
362e99073f5SGeorge Liu     dbus::utility::getSubTree(
363e99073f5SGeorge Liu         path, 2, interfaces,
364*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
365e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
366002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
367e99073f5SGeorge Liu         // Response handler for parsing objects subtree
36862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3691abe55efSEd Tanous         if (ec)
3701abe55efSEd Tanous         {
3718d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
37262598e31SEd Tanous             BMCWEB_LOG_ERROR(
37362598e31SEd Tanous                 "getObjectsWithConnection resp_handler: Dbus error {}", ec);
37408777fb0SLewanczyk, Dawid             return;
37508777fb0SLewanczyk, Dawid         }
37608777fb0SLewanczyk, Dawid 
37762598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
37808777fb0SLewanczyk, Dawid 
37908777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
38008777fb0SLewanczyk, Dawid         // found in the chassis
381fe04d49cSNan Zhou         std::set<std::string> connections;
382413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
38308777fb0SLewanczyk, Dawid 
38462598e31SEd Tanous         BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
38549c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3861abe55efSEd Tanous         {
38762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
38808777fb0SLewanczyk, Dawid         }
38908777fb0SLewanczyk, Dawid 
39008777fb0SLewanczyk, Dawid         for (const std::pair<
39108777fb0SLewanczyk, Dawid                  std::string,
39208777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3931abe55efSEd Tanous                  object : subtree)
3941abe55efSEd Tanous         {
39549c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3961abe55efSEd Tanous             {
39749c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
3981abe55efSEd Tanous                          objData : object.second)
3991abe55efSEd Tanous                 {
40062598e31SEd Tanous                     BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
40108777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
402de629b6eSShawn McCarney                     objectsWithConnection.insert(
403de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
40408777fb0SLewanczyk, Dawid                 }
40508777fb0SLewanczyk, Dawid             }
40608777fb0SLewanczyk, Dawid         }
40762598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
408413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
40962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
410e99073f5SGeorge Liu     });
41162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
412413961deSRichard Marian Thomaiyar }
413413961deSRichard Marian Thomaiyar 
414413961deSRichard Marian Thomaiyar /**
415413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
416413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
417413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
418413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
419413961deSRichard Marian Thomaiyar  */
420413961deSRichard Marian Thomaiyar template <typename Callback>
421fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
422fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
423413961deSRichard Marian Thomaiyar                     Callback&& callback)
424413961deSRichard Marian Thomaiyar {
425413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
426*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback)](
427*8cb2c024SEd Tanous             const std::set<std::string>& connections,
428413961deSRichard Marian Thomaiyar             const std::set<std::pair<std::string, std::string>>&
4293174e4dfSEd Tanous             /*objectsWithConnection*/) { callback(connections); };
43081ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
431413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
43208777fb0SLewanczyk, Dawid }
43308777fb0SLewanczyk, Dawid 
43408777fb0SLewanczyk, Dawid /**
43549c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
43649c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
43749c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
43849c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
43949c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
44049c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
44149c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
44249c53ac9SJohnathan Mantey  */
44323a21a1cSEd Tanous inline void reduceSensorList(
4447f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
445cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
44649c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
447fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
44849c53ac9SJohnathan Mantey {
44949c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
45049c53ac9SJohnathan Mantey     {
4517f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4527f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
453a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
45449c53ac9SJohnathan Mantey                                        : "Voltages");
45549c53ac9SJohnathan Mantey 
45649c53ac9SJohnathan Mantey         return;
45749c53ac9SJohnathan Mantey     }
45849c53ac9SJohnathan Mantey     if (allSensors->empty())
45949c53ac9SJohnathan Mantey     {
46049c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
46149c53ac9SJohnathan Mantey         return;
46249c53ac9SJohnathan Mantey     }
46349c53ac9SJohnathan Mantey 
4647f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
46549c53ac9SJohnathan Mantey     {
46649c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
46749c53ac9SJohnathan Mantey         {
46811ba3979SEd Tanous             if (sensor.starts_with(type))
46949c53ac9SJohnathan Mantey             {
47049c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
47149c53ac9SJohnathan Mantey             }
47249c53ac9SJohnathan Mantey         }
47349c53ac9SJohnathan Mantey     }
47449c53ac9SJohnathan Mantey }
47549c53ac9SJohnathan Mantey 
4767f1cc26dSEd Tanous /*
4777f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4787f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4797f1cc26dSEd Tanous  *
4807f1cc26dSEd Tanous  * */
4817f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4827f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4837f1cc26dSEd Tanous {
4847f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4857f1cc26dSEd Tanous     {
4867f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4877f1cc26dSEd Tanous     }
4887f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4897f1cc26dSEd Tanous     {
4907f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
4917f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
4927f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
4937f1cc26dSEd Tanous     }
4947f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
4957f1cc26dSEd Tanous     {
4967f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
4977f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
4987f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
4997f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5007f1cc26dSEd Tanous     }
5017f1cc26dSEd Tanous 
5027f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5037f1cc26dSEd Tanous     {
5047f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5057f1cc26dSEd Tanous     }
5067f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5077f1cc26dSEd Tanous }
5087f1cc26dSEd Tanous 
50949c53ac9SJohnathan Mantey /**
51008777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
511588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
51208777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
51308777fb0SLewanczyk, Dawid  */
51408777fb0SLewanczyk, Dawid template <typename Callback>
5157f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5167f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
517cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
518cf9e417dSEd Tanous                 Callback&& callback)
5191abe55efSEd Tanous {
52062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5217a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
52249c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
523adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5247a1dbc48SGeorge Liu 
5257a1dbc48SGeorge Liu     // Get the Chassis Collection
5267a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5277a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
528*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), asyncResp,
5297f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5307f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5317a1dbc48SGeorge Liu             const boost::system::error_code& ec,
532002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
53362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5341abe55efSEd Tanous         if (ec)
5351abe55efSEd Tanous         {
53662598e31SEd Tanous             BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5377f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
53808777fb0SLewanczyk, Dawid             return;
53908777fb0SLewanczyk, Dawid         }
54049c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
54149c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5421abe55efSEd Tanous         {
54328aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
544f8fe53e7SEd Tanous             std::string chassisName = path.filename();
54528aa8de5SGeorge Liu             if (chassisName.empty())
5461abe55efSEd Tanous             {
54762598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
548daf36e2eSEd Tanous                 continue;
549daf36e2eSEd Tanous             }
5507f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5511abe55efSEd Tanous             {
55249c53ac9SJohnathan Mantey                 chassisPath = &chassis;
55349c53ac9SJohnathan Mantey                 break;
554daf36e2eSEd Tanous             }
55549c53ac9SJohnathan Mantey         }
55649c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5571abe55efSEd Tanous         {
5587f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
55949c53ac9SJohnathan Mantey             return;
5601abe55efSEd Tanous         }
5617f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
56208777fb0SLewanczyk, Dawid 
563ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
564ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
56595a3ecadSAnthony Wilson 
5668fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5678fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5686c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5696c3e9451SGeorge Liu             sensorPath,
5707f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
571*8cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
5728b24275dSEd Tanous                 const boost::system::error_code& ec2,
5736c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
5748b24275dSEd Tanous             if (ec2)
57549c53ac9SJohnathan Mantey             {
5768b24275dSEd Tanous                 if (ec2.value() != EBADR)
57749c53ac9SJohnathan Mantey                 {
5787f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
57949c53ac9SJohnathan Mantey                     return;
58049c53ac9SJohnathan Mantey                 }
58149c53ac9SJohnathan Mantey             }
582fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
583fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5847f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5857f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
58662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
58749c53ac9SJohnathan Mantey             callback(culledSensorList);
5881e1e598dSJonathan Doman         });
5897a1dbc48SGeorge Liu     });
59062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
59108777fb0SLewanczyk, Dawid }
59208777fb0SLewanczyk, Dawid 
59308777fb0SLewanczyk, Dawid /**
594adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
595adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
596aaf08ac7SMatt Simmering  * @param sensorAvailable Boolean representing if D-Bus sensor is marked as
597aaf08ac7SMatt Simmering  * available.
598adc4f0dbSShawn McCarney  * @return State value for inventory item.
59934dd179eSJames Feist  */
600aaf08ac7SMatt Simmering inline resource::State getState(const InventoryItem* inventoryItem,
601aaf08ac7SMatt Simmering                                 const bool sensorAvailable)
602adc4f0dbSShawn McCarney {
603adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
604adc4f0dbSShawn McCarney     {
605aaf08ac7SMatt Simmering         return resource::State::Absent;
606adc4f0dbSShawn McCarney     }
60734dd179eSJames Feist 
608aaf08ac7SMatt Simmering     if (!sensorAvailable)
609aaf08ac7SMatt Simmering     {
610aaf08ac7SMatt Simmering         return resource::State::UnavailableOffline;
611aaf08ac7SMatt Simmering     }
612aaf08ac7SMatt Simmering 
613aaf08ac7SMatt Simmering     return resource::State::Enabled;
614adc4f0dbSShawn McCarney }
615adc4f0dbSShawn McCarney 
616adc4f0dbSShawn McCarney /**
617adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
618adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6191d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
620adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
621adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
622adc4f0dbSShawn McCarney  * @return Health value for sensor.
623adc4f0dbSShawn McCarney  */
6241d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6251d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
626adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
62734dd179eSJames Feist {
628adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
629adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
630adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
631adc4f0dbSShawn McCarney     std::string currentHealth;
632adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
633adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
634adc4f0dbSShawn McCarney     {
635adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
636adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
637adc4f0dbSShawn McCarney         {
638adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
639adc4f0dbSShawn McCarney             if (health != nullptr)
640adc4f0dbSShawn McCarney             {
641adc4f0dbSShawn McCarney                 currentHealth = *health;
642adc4f0dbSShawn McCarney             }
643adc4f0dbSShawn McCarney         }
644adc4f0dbSShawn McCarney     }
645adc4f0dbSShawn McCarney 
646adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
647adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
648adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
649adc4f0dbSShawn McCarney     {
650adc4f0dbSShawn McCarney         return "Critical";
651adc4f0dbSShawn McCarney     }
652adc4f0dbSShawn McCarney 
653c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
654c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
655c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
656c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
657711ac7a9SEd Tanous 
658c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
659c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
660c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
661c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
662c1343bf6SKrzysztof Grobelny         warningAlarmLow);
663c1343bf6SKrzysztof Grobelny 
664c1343bf6SKrzysztof Grobelny     if (success)
66534dd179eSJames Feist     {
666c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
667c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
668c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
66934dd179eSJames Feist         {
67034dd179eSJames Feist             return "Critical";
67134dd179eSJames Feist         }
67234dd179eSJames Feist     }
67334dd179eSJames Feist 
674adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
675adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
676adc4f0dbSShawn McCarney     {
677adc4f0dbSShawn McCarney         return "Critical";
678adc4f0dbSShawn McCarney     }
679adc4f0dbSShawn McCarney 
680adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
681adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
682adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
683adc4f0dbSShawn McCarney     {
684adc4f0dbSShawn McCarney         return "Warning";
685adc4f0dbSShawn McCarney     }
686adc4f0dbSShawn McCarney 
687c1343bf6SKrzysztof Grobelny     if (success)
688c1343bf6SKrzysztof Grobelny     {
689adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
690c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
691c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
69234dd179eSJames Feist         {
693ebe4d91eSEd Tanous             return "Warning";
69434dd179eSJames Feist         }
69534dd179eSJames Feist     }
696adc4f0dbSShawn McCarney 
69734dd179eSJames Feist     return "OK";
69834dd179eSJames Feist }
69934dd179eSJames Feist 
70023a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
701d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
702d500549bSAnthony Wilson {
703d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
704d500549bSAnthony Wilson     {
705d500549bSAnthony Wilson         switch (inventoryItem->ledState)
706d500549bSAnthony Wilson         {
707d500549bSAnthony Wilson             case LedState::OFF:
708d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
709d500549bSAnthony Wilson                 break;
710d500549bSAnthony Wilson             case LedState::ON:
711d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
712d500549bSAnthony Wilson                 break;
713d500549bSAnthony Wilson             case LedState::BLINK:
714d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
715d500549bSAnthony Wilson                 break;
7164da0490bSEd Tanous             default:
717d500549bSAnthony Wilson                 break;
718d500549bSAnthony Wilson         }
719d500549bSAnthony Wilson     }
720d500549bSAnthony Wilson }
721d500549bSAnthony Wilson 
72234dd179eSJames Feist /**
72308777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
72408777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
725274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
72608777fb0SLewanczyk, Dawid  * build
7278ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
7281d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7291d7c0054SEd Tanous  * from.
7301d7c0054SEd Tanous  * @param sensorJson  The json object to fill
731adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
732adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
73308777fb0SLewanczyk, Dawid  */
7341d7c0054SEd Tanous inline void objectPropertiesToJson(
7351d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7361d7c0054SEd Tanous     std::string_view chassisSubNode,
7371d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
73881ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7391abe55efSEd Tanous {
7401d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
741adc4f0dbSShawn McCarney     {
742c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
7433544d2a7SEd Tanous         auto remove = std::ranges::remove(subNodeEscaped, '_');
7443544d2a7SEd Tanous         subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
745c1d019a6SEd Tanous 
746c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
747c1d019a6SEd Tanous         // including power sensors.
748c1d019a6SEd Tanous         subNodeEscaped += '_';
749c1d019a6SEd Tanous         subNodeEscaped += sensorName;
750c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
751c1d019a6SEd Tanous 
7521d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7531d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7541d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
75595a3ecadSAnthony Wilson     }
75695a3ecadSAnthony Wilson     else if (sensorType != "power")
75795a3ecadSAnthony Wilson     {
75895a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
75995a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
76095a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7611d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7621d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7631d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
764adc4f0dbSShawn McCarney     }
765e742b6ccSEd Tanous 
766aaf08ac7SMatt Simmering     const bool* checkAvailable = nullptr;
767aaf08ac7SMatt Simmering     bool available = true;
768aaf08ac7SMatt Simmering     const bool success = sdbusplus::unpackPropertiesNoThrow(
769aaf08ac7SMatt Simmering         dbus_utils::UnpackErrorPrinter(), propertiesDict, "Available",
770aaf08ac7SMatt Simmering         checkAvailable);
771aaf08ac7SMatt Simmering     if (!success)
772aaf08ac7SMatt Simmering     {
773aaf08ac7SMatt Simmering         messages::internalError();
774aaf08ac7SMatt Simmering     }
775aaf08ac7SMatt Simmering     if (checkAvailable != nullptr)
776aaf08ac7SMatt Simmering     {
777aaf08ac7SMatt Simmering         available = *checkAvailable;
778aaf08ac7SMatt Simmering     }
779aaf08ac7SMatt Simmering 
780aaf08ac7SMatt Simmering     sensorJson["Status"]["State"] = getState(inventoryItem, available);
78189492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
78289492a15SPatrick Williams                                                inventoryItem);
78308777fb0SLewanczyk, Dawid 
78408777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
78508777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
78608777fb0SLewanczyk, Dawid     // that require integers, not floats.
78708777fb0SLewanczyk, Dawid     bool forceToInt = false;
78808777fb0SLewanczyk, Dawid 
7893929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7901d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
79195a3ecadSAnthony Wilson     {
7922a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
793c2bf7f99SWludzik, Jozef 
7940ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
7950ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
79695a3ecadSAnthony Wilson         {
79762598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
79862598e31SEd Tanous                              sensorType);
79995a3ecadSAnthony Wilson         }
800c2bf7f99SWludzik, Jozef         else
80195a3ecadSAnthony Wilson         {
802c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
80395a3ecadSAnthony Wilson         }
804c2bf7f99SWludzik, Jozef 
8051d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
806c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
807f8ede15eSAdrian Ambrożewicz         {
80862598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
80962598e31SEd Tanous                              sensorType);
810c2bf7f99SWludzik, Jozef         }
811c2bf7f99SWludzik, Jozef         else
812c2bf7f99SWludzik, Jozef         {
813c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
814f8ede15eSAdrian Ambrożewicz         }
81595a3ecadSAnthony Wilson     }
81695a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8171abe55efSEd Tanous     {
8183929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
81981ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
82008777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
82108777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8221abe55efSEd Tanous     }
8231abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8241abe55efSEd Tanous     {
8253929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
82681ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
82781ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
82881ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
82908777fb0SLewanczyk, Dawid         forceToInt = true;
8301abe55efSEd Tanous     }
8316f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8326f6d0d32SEd Tanous     {
8333929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
83481ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
83581ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
83681ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8376f6d0d32SEd Tanous         forceToInt = true;
8386f6d0d32SEd Tanous     }
8391abe55efSEd Tanous     else if (sensorType == "voltage")
8401abe55efSEd Tanous     {
8413929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
84281ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8431abe55efSEd Tanous     }
8442474adfaSEd Tanous     else if (sensorType == "power")
8452474adfaSEd Tanous     {
84618f8f608SEd Tanous         std::string lower;
84718f8f608SEd Tanous         std::ranges::transform(sensorName, std::back_inserter(lower),
84818f8f608SEd Tanous                                bmcweb::asciiToLower);
84918f8f608SEd Tanous         if (lower == "total_power")
850028f7ebcSEddie James         {
85181ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8527ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8537ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
85481ce609eSEd Tanous             sensorJson["MemberId"] = "0";
85581ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8563929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
857028f7ebcSEddie James         }
85818f8f608SEd Tanous         else if (lower.find("input") != std::string::npos)
85949c53ac9SJohnathan Mantey         {
8603929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
86149c53ac9SJohnathan Mantey         }
86249c53ac9SJohnathan Mantey         else
86349c53ac9SJohnathan Mantey         {
8643929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
86549c53ac9SJohnathan Mantey         }
8662474adfaSEd Tanous     }
8671abe55efSEd Tanous     else
8681abe55efSEd Tanous     {
86962598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
87008777fb0SLewanczyk, Dawid         return;
87108777fb0SLewanczyk, Dawid     }
87208777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8733929aca1SAnthony Wilson     std::vector<
8743929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8753929aca1SAnthony Wilson         properties;
87608777fb0SLewanczyk, Dawid     properties.reserve(7);
87708777fb0SLewanczyk, Dawid 
87808777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
879de629b6eSShawn McCarney 
8801d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8813929aca1SAnthony Wilson     {
8823929aca1SAnthony Wilson         properties.emplace_back(
8833929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8843929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8853929aca1SAnthony Wilson         properties.emplace_back(
8863929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8873929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8883929aca1SAnthony Wilson         properties.emplace_back(
8893929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8903929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
8913929aca1SAnthony Wilson         properties.emplace_back(
8923929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
8933929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
8943929aca1SAnthony Wilson     }
8953929aca1SAnthony Wilson     else if (sensorType != "power")
896de629b6eSShawn McCarney     {
89708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8983929aca1SAnthony Wilson                                 "WarningHigh",
8993929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
90008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9013929aca1SAnthony Wilson                                 "WarningLow",
9023929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
90308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9043929aca1SAnthony Wilson                                 "CriticalHigh",
9053929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
90608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9073929aca1SAnthony Wilson                                 "CriticalLow",
9083929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
909de629b6eSShawn McCarney     }
91008777fb0SLewanczyk, Dawid 
9112474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
9122474adfaSEd Tanous 
9131d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
91495a3ecadSAnthony Wilson     {
91595a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9163929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
91795a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9183929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
91951c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
92051c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
92195a3ecadSAnthony Wilson     }
92295a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9231abe55efSEd Tanous     {
92408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9253929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
92608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9273929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9281abe55efSEd Tanous     }
929adc4f0dbSShawn McCarney     else if (sensorType != "power")
9301abe55efSEd Tanous     {
93108777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9323929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
93308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9343929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
93508777fb0SLewanczyk, Dawid     }
93608777fb0SLewanczyk, Dawid 
9373929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9383929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9391abe55efSEd Tanous     {
9401d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
941711ac7a9SEd Tanous         {
942711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
943711ac7a9SEd Tanous             {
944711ac7a9SEd Tanous                 continue;
945711ac7a9SEd Tanous             }
9463929aca1SAnthony Wilson 
9473929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9483929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9493929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9503929aca1SAnthony Wilson 
951abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
95240e4f380SEd Tanous             if (doubleValue == nullptr)
9531abe55efSEd Tanous             {
95462598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9556f6d0d32SEd Tanous                 continue;
95608777fb0SLewanczyk, Dawid             }
957283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
958283860f5SEd Tanous             {
959283860f5SEd Tanous                 if (valueName == "Value")
960283860f5SEd Tanous                 {
961283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
962283860f5SEd Tanous                     // them to null in the json response.
963283860f5SEd Tanous                     sensorJson[key] = nullptr;
964283860f5SEd Tanous                     continue;
965283860f5SEd Tanous                 }
96662598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
96762598e31SEd Tanous                                    valueName, *doubleValue);
968283860f5SEd Tanous                 continue;
969283860f5SEd Tanous             }
9706f6d0d32SEd Tanous             if (forceToInt)
9716f6d0d32SEd Tanous             {
97240e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9736f6d0d32SEd Tanous             }
9746f6d0d32SEd Tanous             else
9756f6d0d32SEd Tanous             {
97640e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
97708777fb0SLewanczyk, Dawid             }
97808777fb0SLewanczyk, Dawid         }
97908777fb0SLewanczyk, Dawid     }
98008777fb0SLewanczyk, Dawid }
98108777fb0SLewanczyk, Dawid 
9821d7c0054SEd Tanous /**
9831d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9841d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9851d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9861d7c0054SEd Tanous  * build
9878ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
9881d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9891d7c0054SEd Tanous  * interfaces to be built from
9901d7c0054SEd Tanous  * @param sensorJson  The json object to fill
9911d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
9921d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
9931d7c0054SEd Tanous  */
9941d7c0054SEd Tanous inline void objectInterfacesToJson(
9951d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
9961d7c0054SEd Tanous     const std::string& chassisSubNode,
99780f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
9981d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
9991d7c0054SEd Tanous {
10001d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
10011d7c0054SEd Tanous     {
10021d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
10031d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
10041d7c0054SEd Tanous     }
100562598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
10061d7c0054SEd Tanous }
10071d7c0054SEd Tanous 
1008b5a76932SEd Tanous inline void populateFanRedundancy(
1009b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
10108bd25ccdSJames Feist {
1011e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1012e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
1013e99073f5SGeorge Liu     dbus::utility::getSubTree(
1014e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
1015b9d36b47SEd Tanous         [sensorsAsyncResp](
1016e99073f5SGeorge Liu             const boost::system::error_code& ec,
1017b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
10188bd25ccdSJames Feist         if (ec)
10198bd25ccdSJames Feist         {
10208bd25ccdSJames Feist             return; // don't have to have this interface
10218bd25ccdSJames Feist         }
10226c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
1023e278c18fSEd Tanous                  pathPair : resp)
10248bd25ccdSJames Feist         {
1025e278c18fSEd Tanous             const std::string& path = pathPair.first;
10266c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
10278bd25ccdSJames Feist             if (objDict.empty())
10288bd25ccdSJames Feist             {
10298bd25ccdSJames Feist                 continue; // this should be impossible
10308bd25ccdSJames Feist             }
10318bd25ccdSJames Feist 
10328bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10336c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
10346c3e9451SGeorge Liu                 path + "/chassis",
10356c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
10368b24275dSEd Tanous                     const boost::system::error_code& ec2,
10376c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
10388b24275dSEd Tanous                 if (ec2)
10398bd25ccdSJames Feist                 {
10408bd25ccdSJames Feist                     return; // if they don't have an association we
10418bd25ccdSJames Feist                             // can't tell what chassis is
10428bd25ccdSJames Feist                 }
10433544d2a7SEd Tanous                 auto found = std::ranges::find_if(
10443544d2a7SEd Tanous                     endpoints, [sensorsAsyncResp](const std::string& entry) {
1045002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10468bd25ccdSJames Feist                            std::string::npos;
10478bd25ccdSJames Feist                 });
10488bd25ccdSJames Feist 
10491e1e598dSJonathan Doman                 if (found == endpoints.end())
10508bd25ccdSJames Feist                 {
10518bd25ccdSJames Feist                     return;
10528bd25ccdSJames Feist                 }
105386d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
105486d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
105586d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10568bd25ccdSJames Feist                     [path, sensorsAsyncResp](
10578b24275dSEd Tanous                         const boost::system::error_code& ec3,
105886d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
10598b24275dSEd Tanous                     if (ec3)
10608bd25ccdSJames Feist                     {
10618bd25ccdSJames Feist                         return; // don't have to have this
10628bd25ccdSJames Feist                                 // interface
10638bd25ccdSJames Feist                     }
10648bd25ccdSJames Feist 
106586d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
106686d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
106786d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
106886d89ed7SKrzysztof Grobelny 
106986d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
107086d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
107186d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
107286d89ed7SKrzysztof Grobelny                         collection, "Status", status);
107386d89ed7SKrzysztof Grobelny 
107486d89ed7SKrzysztof Grobelny                     if (!success)
107586d89ed7SKrzysztof Grobelny                     {
107686d89ed7SKrzysztof Grobelny                         messages::internalError(
107786d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
107886d89ed7SKrzysztof Grobelny                         return;
107986d89ed7SKrzysztof Grobelny                     }
108086d89ed7SKrzysztof Grobelny 
108186d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
108286d89ed7SKrzysztof Grobelny                         status == nullptr)
10838bd25ccdSJames Feist                     {
108462598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid redundancy interface");
10858bd25ccdSJames Feist                         messages::internalError(
10868d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10878bd25ccdSJames Feist                         return;
10888bd25ccdSJames Feist                     }
10898bd25ccdSJames Feist 
1090002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
109128aa8de5SGeorge Liu                     std::string name = objectPath.filename();
109228aa8de5SGeorge Liu                     if (name.empty())
10938bd25ccdSJames Feist                     {
10948bd25ccdSJames Feist                         // this should be impossible
10958bd25ccdSJames Feist                         messages::internalError(
10968d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10978bd25ccdSJames Feist                         return;
10988bd25ccdSJames Feist                     }
109918f8f608SEd Tanous                     std::ranges::replace(name, '_', ' ');
11008bd25ccdSJames Feist 
11018bd25ccdSJames Feist                     std::string health;
11028bd25ccdSJames Feist 
110311ba3979SEd Tanous                     if (status->ends_with("Full"))
11048bd25ccdSJames Feist                     {
11058bd25ccdSJames Feist                         health = "OK";
11068bd25ccdSJames Feist                     }
110711ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
11088bd25ccdSJames Feist                     {
11098bd25ccdSJames Feist                         health = "Warning";
11108bd25ccdSJames Feist                     }
11118bd25ccdSJames Feist                     else
11128bd25ccdSJames Feist                     {
11138bd25ccdSJames Feist                         health = "Critical";
11148bd25ccdSJames Feist                     }
11151476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
11168bd25ccdSJames Feist                     const auto& fanRedfish =
1117002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
11188bd25ccdSJames Feist                     for (const std::string& item : *collection)
11198bd25ccdSJames Feist                     {
11208a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
11218a592810SEd Tanous                         std::string itemName = itemPath.filename();
112228aa8de5SGeorge Liu                         if (itemName.empty())
112328aa8de5SGeorge Liu                         {
112428aa8de5SGeorge Liu                             continue;
112528aa8de5SGeorge Liu                         }
11268bd25ccdSJames Feist                         /*
11278bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11288bd25ccdSJames Feist                         std::replace(itemName.begin(),
11298bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
11303544d2a7SEd Tanous                         auto schemaItem = std::ranges::find_if(
11313544d2a7SEd Tanous                             fanRedfish, [itemName](const nlohmann::json& fan) {
11323e35c761SGeorge Liu                             return fan["Name"] == itemName;
11338bd25ccdSJames Feist                         });
11348bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11358bd25ccdSJames Feist                         {
11368a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11378a592810SEd Tanous                             collectionId["@odata.id"] =
11381476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11391476687dSEd Tanous                             redfishCollection.emplace_back(
11408a592810SEd Tanous                                 std::move(collectionId));
11418bd25ccdSJames Feist                         }
11428bd25ccdSJames Feist                         else
11438bd25ccdSJames Feist                         {
114462598e31SEd Tanous                             BMCWEB_LOG_ERROR("failed to find fan in schema");
11458bd25ccdSJames Feist                             messages::internalError(
11468d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11478bd25ccdSJames Feist                             return;
11488bd25ccdSJames Feist                         }
11498bd25ccdSJames Feist                     }
11508bd25ccdSJames Feist 
115189492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
115226f6976fSEd Tanous                                               ? 0
115389492a15SPatrick Williams                                               : collection->size() -
115489492a15SPatrick Williams                                                     *allowedFailures;
1155002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11568bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11571476687dSEd Tanous 
11581476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1159ef4c65b7SEd Tanous                     boost::urls::url url =
1160ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1161ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1162eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1163eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1164eddfc437SWilly Tu                                          .to_string());
1165eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1166002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11671476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11681476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11691476687dSEd Tanous                     redundancy["Name"] = name;
11701476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11711476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11721476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11731476687dSEd Tanous 
1174b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
117586d89ed7SKrzysztof Grobelny                 });
11761e1e598dSJonathan Doman             });
11778bd25ccdSJames Feist         }
1178e99073f5SGeorge Liu     });
11798bd25ccdSJames Feist }
11808bd25ccdSJames Feist 
1181b5a76932SEd Tanous inline void
118281ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
118349c53ac9SJohnathan Mantey {
11848d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
118549c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
118681ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
118749c53ac9SJohnathan Mantey     {
118849c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
118949c53ac9SJohnathan Mantey     }
119049c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
119149c53ac9SJohnathan Mantey     {
119249c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
119349c53ac9SJohnathan Mantey         if (entry != response.end())
119449c53ac9SJohnathan Mantey         {
119549c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
119602cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
119749c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
119849c53ac9SJohnathan Mantey             });
119949c53ac9SJohnathan Mantey 
120049c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
120149c53ac9SJohnathan Mantey             size_t count = 0;
120249c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
120349c53ac9SJohnathan Mantey             {
120449c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
120549c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
120649c53ac9SJohnathan Mantey                 {
120749c53ac9SJohnathan Mantey                     continue;
120849c53ac9SJohnathan Mantey                 }
120949c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
121049c53ac9SJohnathan Mantey                 if (value != nullptr)
121149c53ac9SJohnathan Mantey                 {
1212eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
12133e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
121449c53ac9SJohnathan Mantey                     count++;
121581ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
121649c53ac9SJohnathan Mantey                 }
121749c53ac9SJohnathan Mantey             }
121849c53ac9SJohnathan Mantey         }
121949c53ac9SJohnathan Mantey     }
122049c53ac9SJohnathan Mantey }
122149c53ac9SJohnathan Mantey 
122208777fb0SLewanczyk, Dawid /**
1223adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1224adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1225adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1226adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12278fb49dd6SShawn McCarney  */
122823a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1229b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1230adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12318fb49dd6SShawn McCarney {
1232adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12338fb49dd6SShawn McCarney     {
1234adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12358fb49dd6SShawn McCarney         {
1236adc4f0dbSShawn McCarney             return &inventoryItem;
12378fb49dd6SShawn McCarney         }
12388fb49dd6SShawn McCarney     }
12398fb49dd6SShawn McCarney     return nullptr;
12408fb49dd6SShawn McCarney }
12418fb49dd6SShawn McCarney 
12428fb49dd6SShawn McCarney /**
1243adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1244adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1245adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1246adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12478fb49dd6SShawn McCarney  */
124823a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1249b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1250adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1251adc4f0dbSShawn McCarney {
1252adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1253adc4f0dbSShawn McCarney     {
1254db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1255adc4f0dbSShawn McCarney         {
1256adc4f0dbSShawn McCarney             return &inventoryItem;
1257adc4f0dbSShawn McCarney         }
1258adc4f0dbSShawn McCarney     }
1259adc4f0dbSShawn McCarney     return nullptr;
1260adc4f0dbSShawn McCarney }
1261adc4f0dbSShawn McCarney 
1262adc4f0dbSShawn McCarney /**
1263d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1264d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1265d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1266d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1267d500549bSAnthony Wilson  */
1268d500549bSAnthony Wilson inline InventoryItem*
1269d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1270d500549bSAnthony Wilson                             const std::string& ledObjPath)
1271d500549bSAnthony Wilson {
1272d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1273d500549bSAnthony Wilson     {
1274d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1275d500549bSAnthony Wilson         {
1276d500549bSAnthony Wilson             return &inventoryItem;
1277d500549bSAnthony Wilson         }
1278d500549bSAnthony Wilson     }
1279d500549bSAnthony Wilson     return nullptr;
1280d500549bSAnthony Wilson }
1281d500549bSAnthony Wilson 
1282d500549bSAnthony Wilson /**
1283adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1284adc4f0dbSShawn McCarney  *
1285adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1286adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1287adc4f0dbSShawn McCarney  * added to the vector.
1288adc4f0dbSShawn McCarney  *
1289adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1290adc4f0dbSShawn McCarney  * InventoryItem.
1291adc4f0dbSShawn McCarney  *
1292adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1293adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1294adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1295adc4f0dbSShawn McCarney  */
1296b5a76932SEd Tanous inline void addInventoryItem(
1297b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1298b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1299adc4f0dbSShawn McCarney {
1300adc4f0dbSShawn McCarney     // Look for inventory item in vector
130189492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
130289492a15SPatrick Williams                                                      invItemObjPath);
1303adc4f0dbSShawn McCarney 
1304adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1305adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1306adc4f0dbSShawn McCarney     {
1307adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1308adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1309adc4f0dbSShawn McCarney     }
1310adc4f0dbSShawn McCarney 
1311adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1312adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1313adc4f0dbSShawn McCarney }
1314adc4f0dbSShawn McCarney 
1315adc4f0dbSShawn McCarney /**
1316adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1317adc4f0dbSShawn McCarney  *
1318adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1319adc4f0dbSShawn McCarney  * specified InventoryItem.
1320adc4f0dbSShawn McCarney  *
1321adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1322adc4f0dbSShawn McCarney  * response.
1323adc4f0dbSShawn McCarney  *
1324adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1325adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1326adc4f0dbSShawn McCarney  * for the specified inventory item.
1327adc4f0dbSShawn McCarney  */
132823a21a1cSEd Tanous inline void storeInventoryItemData(
1329adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
133080f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13318fb49dd6SShawn McCarney {
1332adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1333711ac7a9SEd Tanous 
13349eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13358fb49dd6SShawn McCarney     {
1336711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13378fb49dd6SShawn McCarney         {
13389eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1339711ac7a9SEd Tanous             {
1340711ac7a9SEd Tanous                 if (name == "Present")
1341711ac7a9SEd Tanous                 {
1342711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1343adc4f0dbSShawn McCarney                     if (value != nullptr)
13448fb49dd6SShawn McCarney                     {
1345adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13468fb49dd6SShawn McCarney                     }
13478fb49dd6SShawn McCarney                 }
13488fb49dd6SShawn McCarney             }
1349711ac7a9SEd Tanous         }
1350adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1351711ac7a9SEd Tanous 
1352711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13538fb49dd6SShawn McCarney         {
1354adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13558fb49dd6SShawn McCarney         }
1356adc4f0dbSShawn McCarney 
1357adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1358711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1359adc4f0dbSShawn McCarney         {
13609eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1361711ac7a9SEd Tanous             {
1362711ac7a9SEd Tanous                 if (name == "Manufacturer")
1363adc4f0dbSShawn McCarney                 {
1364adc4f0dbSShawn McCarney                     const std::string* value =
1365711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1366adc4f0dbSShawn McCarney                     if (value != nullptr)
1367adc4f0dbSShawn McCarney                     {
1368adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1369adc4f0dbSShawn McCarney                     }
1370adc4f0dbSShawn McCarney                 }
1371711ac7a9SEd Tanous                 if (name == "Model")
1372adc4f0dbSShawn McCarney                 {
1373adc4f0dbSShawn McCarney                     const std::string* value =
1374711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1375adc4f0dbSShawn McCarney                     if (value != nullptr)
1376adc4f0dbSShawn McCarney                     {
1377adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1378adc4f0dbSShawn McCarney                     }
1379adc4f0dbSShawn McCarney                 }
1380711ac7a9SEd Tanous                 if (name == "SerialNumber")
1381adc4f0dbSShawn McCarney                 {
1382adc4f0dbSShawn McCarney                     const std::string* value =
1383711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1384adc4f0dbSShawn McCarney                     if (value != nullptr)
1385adc4f0dbSShawn McCarney                     {
1386adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1387adc4f0dbSShawn McCarney                     }
1388adc4f0dbSShawn McCarney                 }
1389711ac7a9SEd Tanous                 if (name == "PartNumber")
1390711ac7a9SEd Tanous                 {
1391711ac7a9SEd Tanous                     const std::string* value =
1392711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1393711ac7a9SEd Tanous                     if (value != nullptr)
1394711ac7a9SEd Tanous                     {
1395711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1396711ac7a9SEd Tanous                     }
1397711ac7a9SEd Tanous                 }
1398711ac7a9SEd Tanous             }
1399adc4f0dbSShawn McCarney         }
1400adc4f0dbSShawn McCarney 
1401711ac7a9SEd Tanous         if (interface ==
1402711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1403adc4f0dbSShawn McCarney         {
14049eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1405adc4f0dbSShawn McCarney             {
1406711ac7a9SEd Tanous                 if (name == "Functional")
1407711ac7a9SEd Tanous                 {
1408711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1409adc4f0dbSShawn McCarney                     if (value != nullptr)
1410adc4f0dbSShawn McCarney                     {
1411adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
14128fb49dd6SShawn McCarney                     }
14138fb49dd6SShawn McCarney                 }
14148fb49dd6SShawn McCarney             }
14158fb49dd6SShawn McCarney         }
1416711ac7a9SEd Tanous     }
1417711ac7a9SEd Tanous }
14188fb49dd6SShawn McCarney 
14198fb49dd6SShawn McCarney /**
1420adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
14218fb49dd6SShawn McCarney  *
1422adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1423adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1424adc4f0dbSShawn McCarney  * inventoryItems vector.
14258fb49dd6SShawn McCarney  *
1426adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1427adc4f0dbSShawn McCarney  * response.
1428adc4f0dbSShawn McCarney  *
1429adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1430adc4f0dbSShawn McCarney  * been obtained.
1431adc4f0dbSShawn McCarney  *
1432adc4f0dbSShawn McCarney  * The callback must have the following signature:
1433adc4f0dbSShawn McCarney  *   @code
1434d500549bSAnthony Wilson  *   callback(void)
1435adc4f0dbSShawn McCarney  *   @endcode
1436adc4f0dbSShawn McCarney  *
1437adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1438adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1439adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14408fb49dd6SShawn McCarney  *
14418fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1442adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1443adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14448fb49dd6SShawn McCarney  * implements ObjectManager.
1445adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1446adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1447adc4f0dbSShawn McCarney  * in recursive calls to this function.
14488fb49dd6SShawn McCarney  */
1449adc4f0dbSShawn McCarney template <typename Callback>
1450adc4f0dbSShawn McCarney static void getInventoryItemsData(
14518fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1452adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1453d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1454d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14558fb49dd6SShawn McCarney {
145662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14578fb49dd6SShawn McCarney 
1458adc4f0dbSShawn McCarney     // If no more connections left, call callback
1459adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14608fb49dd6SShawn McCarney     {
1461d500549bSAnthony Wilson         callback();
146262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1463adc4f0dbSShawn McCarney         return;
1464adc4f0dbSShawn McCarney     }
1465adc4f0dbSShawn McCarney 
1466adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1467fe04d49cSNan Zhou     auto it = invConnections->begin();
1468fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1469adc4f0dbSShawn McCarney     if (it != invConnections->end())
1470adc4f0dbSShawn McCarney     {
1471adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1472adc4f0dbSShawn McCarney 
14735eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14745eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14755eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14765eb468daSGeorge Liu             invConnection, path,
14775eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
1478*8cb2c024SEd Tanous              callback = std::forward<Callback>(callback), invConnectionsIndex](
14795e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
148002cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
148162598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
14828fb49dd6SShawn McCarney             if (ec)
14838fb49dd6SShawn McCarney             {
148462598e31SEd Tanous                 BMCWEB_LOG_ERROR(
148562598e31SEd Tanous                     "getInventoryItemsData respHandler DBus error {}", ec);
14868d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14878fb49dd6SShawn McCarney                 return;
14888fb49dd6SShawn McCarney             }
14898fb49dd6SShawn McCarney 
14908fb49dd6SShawn McCarney             // Loop through returned object paths
14918fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14928fb49dd6SShawn McCarney             {
14938fb49dd6SShawn McCarney                 const std::string& objPath =
14948fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14958fb49dd6SShawn McCarney 
1496adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
149789492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
149889492a15SPatrick Williams                                                                  objPath);
1499adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
15008fb49dd6SShawn McCarney                 {
1501adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1502adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
15038fb49dd6SShawn McCarney                 }
15048fb49dd6SShawn McCarney             }
15058fb49dd6SShawn McCarney 
1506adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1507adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1508d0090733SEd Tanous                                   invConnections, std::move(callback),
1509d0090733SEd Tanous                                   invConnectionsIndex + 1);
1510adc4f0dbSShawn McCarney 
151162598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
15125eb468daSGeorge Liu         });
15138fb49dd6SShawn McCarney     }
15148fb49dd6SShawn McCarney 
151562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
15168fb49dd6SShawn McCarney }
15178fb49dd6SShawn McCarney 
15188fb49dd6SShawn McCarney /**
1519adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
15208fb49dd6SShawn McCarney  *
1521adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1522adc4f0dbSShawn McCarney  * items that are associated with sensors.
15238fb49dd6SShawn McCarney  *
15248fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15258fb49dd6SShawn McCarney  * been obtained.
15268fb49dd6SShawn McCarney  *
15278fb49dd6SShawn McCarney  * The callback must have the following signature:
15288fb49dd6SShawn McCarney  *   @code
1529fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15308fb49dd6SShawn McCarney  *   @endcode
15318fb49dd6SShawn McCarney  *
15328fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1533adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15348fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15358fb49dd6SShawn McCarney  */
15368fb49dd6SShawn McCarney template <typename Callback>
15378fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1538b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1539b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15408fb49dd6SShawn McCarney     Callback&& callback)
15418fb49dd6SShawn McCarney {
154262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15438fb49dd6SShawn McCarney 
15448fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1545e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15468fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1547adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1548adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15498fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15508fb49dd6SShawn McCarney 
1551e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1552e99073f5SGeorge Liu     dbus::utility::getSubTree(
1553e99073f5SGeorge Liu         path, 0, interfaces,
1554*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1555002d39b4SEd Tanous          inventoryItems](
1556e99073f5SGeorge Liu             const boost::system::error_code& ec,
1557002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1558e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
155962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15608fb49dd6SShawn McCarney         if (ec)
15618fb49dd6SShawn McCarney         {
15628d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
156362598e31SEd Tanous             BMCWEB_LOG_ERROR(
156462598e31SEd Tanous                 "getInventoryItemsConnections respHandler DBus error {}", ec);
15658fb49dd6SShawn McCarney             return;
15668fb49dd6SShawn McCarney         }
15678fb49dd6SShawn McCarney 
15688fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1569fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1570fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15718fb49dd6SShawn McCarney 
15728fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15738fb49dd6SShawn McCarney         for (const std::pair<
15748fb49dd6SShawn McCarney                  std::string,
15758fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15768fb49dd6SShawn McCarney                  object : subtree)
15778fb49dd6SShawn McCarney         {
1578adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15798fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1580adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15818fb49dd6SShawn McCarney             {
15828fb49dd6SShawn McCarney                 // Store all connections to inventory item
15838fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15848fb49dd6SShawn McCarney                          objData : object.second)
15858fb49dd6SShawn McCarney                 {
15868fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15878fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15888fb49dd6SShawn McCarney                 }
15898fb49dd6SShawn McCarney             }
15908fb49dd6SShawn McCarney         }
1591d500549bSAnthony Wilson 
15928fb49dd6SShawn McCarney         callback(invConnections);
159362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1594e99073f5SGeorge Liu     });
159562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
15968fb49dd6SShawn McCarney }
15978fb49dd6SShawn McCarney 
15988fb49dd6SShawn McCarney /**
1599adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
16008fb49dd6SShawn McCarney  *
16018fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1602d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1603d500549bSAnthony Wilson  * their LEDs, if any.
16048fb49dd6SShawn McCarney  *
16058fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
16068fb49dd6SShawn McCarney  * has been obtained.
16078fb49dd6SShawn McCarney  *
16088fb49dd6SShawn McCarney  * The callback must have the following signature:
16098fb49dd6SShawn McCarney  *   @code
1610adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
16118fb49dd6SShawn McCarney  *   @endcode
16128fb49dd6SShawn McCarney  *
16138fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
16148fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
16158fb49dd6SShawn McCarney  * implements ObjectManager.
16168fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
16178fb49dd6SShawn McCarney  */
16188fb49dd6SShawn McCarney template <typename Callback>
1619adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1620b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1621fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16228fb49dd6SShawn McCarney     Callback&& callback)
16238fb49dd6SShawn McCarney {
162462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16258fb49dd6SShawn McCarney 
16265eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16275eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16285eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16295eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
1630*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
16315e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
163202cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
163362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16348fb49dd6SShawn McCarney         if (ec)
16358fb49dd6SShawn McCarney         {
163662598e31SEd Tanous             BMCWEB_LOG_ERROR(
163762598e31SEd Tanous                 "getInventoryItemAssociations respHandler DBus error {}", ec);
16388d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16398fb49dd6SShawn McCarney             return;
16408fb49dd6SShawn McCarney         }
16418fb49dd6SShawn McCarney 
1642adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1643adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1644adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1645adc4f0dbSShawn McCarney 
16468fb49dd6SShawn McCarney         // Loop through returned object paths
16478fb49dd6SShawn McCarney         std::string sensorAssocPath;
16488fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16498fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16508fb49dd6SShawn McCarney         {
16518fb49dd6SShawn McCarney             const std::string& objPath =
16528fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16538fb49dd6SShawn McCarney 
16548fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16558fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16568fb49dd6SShawn McCarney             {
16578fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16588fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16598fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16608fb49dd6SShawn McCarney                 {
16618fb49dd6SShawn McCarney                     // Get Association interface for object path
1662711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16638fb49dd6SShawn McCarney                     {
1664711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1665711ac7a9SEd Tanous                         {
1666711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1667711ac7a9SEd Tanous                             {
1668711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16698fb49dd6SShawn McCarney                                 {
16708fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16718fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1672711ac7a9SEd Tanous                                             &value);
1673711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1674711ac7a9SEd Tanous                                         !endpoints->empty())
16758fb49dd6SShawn McCarney                                     {
1676adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1677adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1678adc4f0dbSShawn McCarney                                             endpoints->front();
1679711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1680711ac7a9SEd Tanous                                                          invItemPath,
1681adc4f0dbSShawn McCarney                                                          sensorName);
16828fb49dd6SShawn McCarney                                     }
16838fb49dd6SShawn McCarney                                 }
16848fb49dd6SShawn McCarney                             }
1685711ac7a9SEd Tanous                         }
1686711ac7a9SEd Tanous                     }
16878fb49dd6SShawn McCarney                     break;
16888fb49dd6SShawn McCarney                 }
16898fb49dd6SShawn McCarney             }
16908fb49dd6SShawn McCarney         }
16918fb49dd6SShawn McCarney 
1692d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1693d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1694d500549bSAnthony Wilson         std::string inventoryAssocPath;
1695d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1696d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1697d500549bSAnthony Wilson         {
1698d500549bSAnthony Wilson             const std::string& objPath =
1699d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1700d500549bSAnthony Wilson 
1701d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1702d500549bSAnthony Wilson             {
1703d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1704d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1705d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1706d500549bSAnthony Wilson                 {
1707711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1708d500549bSAnthony Wilson                     {
1709711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1710711ac7a9SEd Tanous                         {
1711711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1712711ac7a9SEd Tanous                             {
1713711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1714d500549bSAnthony Wilson                                 {
1715d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1716d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1717711ac7a9SEd Tanous                                             &value);
1718711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1719711ac7a9SEd Tanous                                         !endpoints->empty())
1720d500549bSAnthony Wilson                                     {
1721711ac7a9SEd Tanous                                         // Add inventory item to vector
1722d500549bSAnthony Wilson                                         // Store LED path in inventory item
1723711ac7a9SEd Tanous                                         const std::string& ledPath =
1724711ac7a9SEd Tanous                                             endpoints->front();
1725d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1726d500549bSAnthony Wilson                                     }
1727d500549bSAnthony Wilson                                 }
1728d500549bSAnthony Wilson                             }
1729711ac7a9SEd Tanous                         }
1730711ac7a9SEd Tanous                     }
1731711ac7a9SEd Tanous 
1732d500549bSAnthony Wilson                     break;
1733d500549bSAnthony Wilson                 }
1734d500549bSAnthony Wilson             }
1735d500549bSAnthony Wilson         }
1736adc4f0dbSShawn McCarney         callback(inventoryItems);
173762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17385eb468daSGeorge Liu     });
17398fb49dd6SShawn McCarney 
174062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17418fb49dd6SShawn McCarney }
17428fb49dd6SShawn McCarney 
17438fb49dd6SShawn McCarney /**
1744d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1745d500549bSAnthony Wilson  *
1746d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1747d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1748d500549bSAnthony Wilson  * inventoryItems vector.
1749d500549bSAnthony Wilson  *
1750d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1751d500549bSAnthony Wilson  * response.
1752d500549bSAnthony Wilson  *
1753d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1754d500549bSAnthony Wilson  * has been obtained.
1755d500549bSAnthony Wilson  *
1756d500549bSAnthony Wilson  * The callback must have the following signature:
1757d500549bSAnthony Wilson  *   @code
175842cbe538SGunnar Mills  *   callback()
1759d500549bSAnthony Wilson  *   @endcode
1760d500549bSAnthony Wilson  *
1761d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1762d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1763d500549bSAnthony Wilson  * last asynchronous function has completed.
1764d500549bSAnthony Wilson  *
1765d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1766d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1767d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1768d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1769d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1770d500549bSAnthony Wilson  * in recursive calls to this function.
1771d500549bSAnthony Wilson  */
1772d500549bSAnthony Wilson template <typename Callback>
1773d500549bSAnthony Wilson void getInventoryLedData(
1774d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1775d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1776fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1777d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1778d500549bSAnthony Wilson {
177962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1780d500549bSAnthony Wilson 
1781d500549bSAnthony Wilson     // If no more connections left, call callback
1782d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1783d500549bSAnthony Wilson     {
178442cbe538SGunnar Mills         callback();
178562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1786d500549bSAnthony Wilson         return;
1787d500549bSAnthony Wilson     }
1788d500549bSAnthony Wilson 
1789d500549bSAnthony Wilson     // Get inventory item data from current connection
1790fe04d49cSNan Zhou     auto it = ledConnections->begin();
1791fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1792d500549bSAnthony Wilson     if (it != ledConnections->end())
1793d500549bSAnthony Wilson     {
1794d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1795d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1796d500549bSAnthony Wilson         // Response handler for Get State property
17971e1e598dSJonathan Doman         auto respHandler =
17981e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1799*8cb2c024SEd Tanous              callback = std::forward<Callback>(callback), ledConnectionsIndex](
18005e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
180162598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1802d500549bSAnthony Wilson             if (ec)
1803d500549bSAnthony Wilson             {
180462598e31SEd Tanous                 BMCWEB_LOG_ERROR(
180562598e31SEd Tanous                     "getInventoryLedData respHandler DBus error {}", ec);
18068d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1807d500549bSAnthony Wilson                 return;
1808d500549bSAnthony Wilson             }
1809d500549bSAnthony Wilson 
181062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Led state: {}", state);
1811d500549bSAnthony Wilson             // Find inventory item with this LED object path
1812d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1813d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1814d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1815d500549bSAnthony Wilson             {
1816d500549bSAnthony Wilson                 // Store LED state in InventoryItem
181711ba3979SEd Tanous                 if (state.ends_with("On"))
1818d500549bSAnthony Wilson                 {
1819d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1820d500549bSAnthony Wilson                 }
182111ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1822d500549bSAnthony Wilson                 {
1823d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1824d500549bSAnthony Wilson                 }
182511ba3979SEd Tanous                 else if (state.ends_with("Off"))
1826d500549bSAnthony Wilson                 {
1827d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1828d500549bSAnthony Wilson                 }
1829d500549bSAnthony Wilson                 else
1830d500549bSAnthony Wilson                 {
1831d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1832d500549bSAnthony Wilson                 }
1833d500549bSAnthony Wilson             }
1834d500549bSAnthony Wilson 
1835d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1836d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1837d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1838d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1839d500549bSAnthony Wilson 
184062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1841d500549bSAnthony Wilson         };
1842d500549bSAnthony Wilson 
1843d500549bSAnthony Wilson         // Get the State property for the current LED
18441e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18451e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18461e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18471e1e598dSJonathan Doman             std::move(respHandler));
1848d500549bSAnthony Wilson     }
1849d500549bSAnthony Wilson 
185062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1851d500549bSAnthony Wilson }
1852d500549bSAnthony Wilson 
1853d500549bSAnthony Wilson /**
1854d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1855d500549bSAnthony Wilson  *
1856d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1857d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1858d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1859d500549bSAnthony Wilson  *
1860d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1861d500549bSAnthony Wilson  * response.
1862d500549bSAnthony Wilson  *
1863d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1864d500549bSAnthony Wilson  * been obtained.
1865d500549bSAnthony Wilson  *
1866d500549bSAnthony Wilson  * The callback must have the following signature:
1867d500549bSAnthony Wilson  *   @code
186842cbe538SGunnar Mills  *   callback()
1869d500549bSAnthony Wilson  *   @endcode
1870d500549bSAnthony Wilson  *
1871d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1872d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1873d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1874d500549bSAnthony Wilson  */
1875d500549bSAnthony Wilson template <typename Callback>
1876d500549bSAnthony Wilson void getInventoryLeds(
1877d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1878d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1879d500549bSAnthony Wilson     Callback&& callback)
1880d500549bSAnthony Wilson {
188162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1882d500549bSAnthony Wilson 
1883d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1884e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1885d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1886d500549bSAnthony Wilson 
1887e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1888e99073f5SGeorge Liu     dbus::utility::getSubTree(
1889e99073f5SGeorge Liu         path, 0, interfaces,
1890*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1891002d39b4SEd Tanous          inventoryItems](
1892e99073f5SGeorge Liu             const boost::system::error_code& ec,
1893002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1894e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
189562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1896d500549bSAnthony Wilson         if (ec)
1897d500549bSAnthony Wilson         {
18988d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
189962598e31SEd Tanous             BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}", ec);
1900d500549bSAnthony Wilson             return;
1901d500549bSAnthony Wilson         }
1902d500549bSAnthony Wilson 
1903d500549bSAnthony Wilson         // Build map of LED object paths to connections
1904fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1905fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1906d500549bSAnthony Wilson 
1907d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1908d500549bSAnthony Wilson         for (const std::pair<
1909d500549bSAnthony Wilson                  std::string,
1910d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1911d500549bSAnthony Wilson                  object : subtree)
1912d500549bSAnthony Wilson         {
1913d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1914d500549bSAnthony Wilson             // items
1915d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1916d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1917d500549bSAnthony Wilson             {
1918d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1919d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1920d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
192162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath, connection);
1922d500549bSAnthony Wilson             }
1923d500549bSAnthony Wilson         }
1924d500549bSAnthony Wilson 
1925d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1926d500549bSAnthony Wilson                             std::move(callback));
192762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1928e99073f5SGeorge Liu     });
192962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1930d500549bSAnthony Wilson }
1931d500549bSAnthony Wilson 
1932d500549bSAnthony Wilson /**
193342cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
193442cbe538SGunnar Mills  *
193542cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
193642cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
193742cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
193842cbe538SGunnar Mills  *
193942cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
194042cbe538SGunnar Mills  * response.
194142cbe538SGunnar Mills  *
194242cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
194342cbe538SGunnar Mills  * when data has been obtained.
194442cbe538SGunnar Mills  *
194542cbe538SGunnar Mills  * The callback must have the following signature:
194642cbe538SGunnar Mills  *   @code
194742cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
194842cbe538SGunnar Mills  *   @endcode
194942cbe538SGunnar Mills  *
195042cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
195142cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
195242cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
195342cbe538SGunnar Mills  *        Supply Attributes
195442cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
195542cbe538SGunnar Mills  */
195642cbe538SGunnar Mills template <typename Callback>
195742cbe538SGunnar Mills void getPowerSupplyAttributesData(
1958b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
195942cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1960fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
196142cbe538SGunnar Mills     Callback&& callback)
196242cbe538SGunnar Mills {
196362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
196442cbe538SGunnar Mills 
196542cbe538SGunnar Mills     if (psAttributesConnections.empty())
196642cbe538SGunnar Mills     {
196762598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
196842cbe538SGunnar Mills         callback(inventoryItems);
196942cbe538SGunnar Mills         return;
197042cbe538SGunnar Mills     }
197142cbe538SGunnar Mills 
197242cbe538SGunnar Mills     // Assuming just one connection (service) for now
1973fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
197442cbe538SGunnar Mills 
197542cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
197642cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
197742cbe538SGunnar Mills 
197842cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
19795a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
1980*8cb2c024SEd Tanous                         callback = std::forward<Callback>(callback)](
19815a39f77aSPatrick Williams                            const boost::system::error_code& ec,
19825a39f77aSPatrick Williams                            const uint32_t value) {
198362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
198442cbe538SGunnar Mills         if (ec)
198542cbe538SGunnar Mills         {
198662598e31SEd Tanous             BMCWEB_LOG_ERROR(
198762598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
19888d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
198942cbe538SGunnar Mills             return;
199042cbe538SGunnar Mills         }
199142cbe538SGunnar Mills 
199262598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
199342cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
199442cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
199542cbe538SGunnar Mills         {
199655f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
199742cbe538SGunnar Mills             {
199842cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19991e1e598dSJonathan Doman                     static_cast<int>(value);
200042cbe538SGunnar Mills             }
200142cbe538SGunnar Mills         }
200242cbe538SGunnar Mills 
200362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
200442cbe538SGunnar Mills         callback(inventoryItems);
200542cbe538SGunnar Mills     };
200642cbe538SGunnar Mills 
200742cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
200842cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
20091e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
20101e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
20111e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
20121e1e598dSJonathan Doman         std::move(respHandler));
201342cbe538SGunnar Mills 
201462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
201542cbe538SGunnar Mills }
201642cbe538SGunnar Mills 
201742cbe538SGunnar Mills /**
201842cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
201942cbe538SGunnar Mills  *
202042cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
202142cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
202242cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
202342cbe538SGunnar Mills  * item.
202442cbe538SGunnar Mills  *
202542cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
202642cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
202742cbe538SGunnar Mills  *
202842cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
202942cbe538SGunnar Mills  * when information has been obtained.
203042cbe538SGunnar Mills  *
203142cbe538SGunnar Mills  * The callback must have the following signature:
203242cbe538SGunnar Mills  *   @code
203342cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
203442cbe538SGunnar Mills  *   @endcode
203542cbe538SGunnar Mills  *
203642cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
203742cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
203842cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
203942cbe538SGunnar Mills  */
204042cbe538SGunnar Mills template <typename Callback>
204142cbe538SGunnar Mills void getPowerSupplyAttributes(
204242cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
204342cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
204442cbe538SGunnar Mills     Callback&& callback)
204542cbe538SGunnar Mills {
204662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
204742cbe538SGunnar Mills 
204842cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2049a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
205042cbe538SGunnar Mills     {
205162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
205242cbe538SGunnar Mills         callback(inventoryItems);
205342cbe538SGunnar Mills         return;
205442cbe538SGunnar Mills     }
205542cbe538SGunnar Mills 
2056e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
205742cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
205842cbe538SGunnar Mills 
2059e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2060e99073f5SGeorge Liu     dbus::utility::getSubTree(
2061e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
2062*8cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
2063b9d36b47SEd Tanous          inventoryItems](
2064e99073f5SGeorge Liu             const boost::system::error_code& ec,
2065b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2066e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
206762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
206842cbe538SGunnar Mills         if (ec)
206942cbe538SGunnar Mills         {
20708d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
207162598e31SEd Tanous             BMCWEB_LOG_ERROR(
207262598e31SEd Tanous                 "getPowerSupplyAttributes respHandler DBus error {}", ec);
207342cbe538SGunnar Mills             return;
207442cbe538SGunnar Mills         }
207526f6976fSEd Tanous         if (subtree.empty())
207642cbe538SGunnar Mills         {
207762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
207842cbe538SGunnar Mills             callback(inventoryItems);
207942cbe538SGunnar Mills             return;
208042cbe538SGunnar Mills         }
208142cbe538SGunnar Mills 
208242cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
208342cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
208442cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2085fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
208642cbe538SGunnar Mills 
208742cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
208842cbe538SGunnar Mills         {
208962598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
209042cbe538SGunnar Mills             callback(inventoryItems);
209142cbe538SGunnar Mills             return;
209242cbe538SGunnar Mills         }
209342cbe538SGunnar Mills 
209442cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
209542cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
209642cbe538SGunnar Mills 
209742cbe538SGunnar Mills         if (connection.empty())
209842cbe538SGunnar Mills         {
209962598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
210042cbe538SGunnar Mills             callback(inventoryItems);
210142cbe538SGunnar Mills             return;
210242cbe538SGunnar Mills         }
210342cbe538SGunnar Mills 
210442cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
210562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
210662598e31SEd Tanous                          connection);
210742cbe538SGunnar Mills 
210842cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
210942cbe538SGunnar Mills                                      psAttributesConnections,
211042cbe538SGunnar Mills                                      std::move(callback));
211162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2112e99073f5SGeorge Liu     });
211362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
211442cbe538SGunnar Mills }
211542cbe538SGunnar Mills 
211642cbe538SGunnar Mills /**
2117adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
21188fb49dd6SShawn McCarney  *
21198fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2120adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21218fb49dd6SShawn McCarney  *
2122adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2123adc4f0dbSShawn McCarney  * response.
21248fb49dd6SShawn McCarney  *
2125adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2126adc4f0dbSShawn McCarney  * inventory items have been obtained.
2127adc4f0dbSShawn McCarney  *
2128adc4f0dbSShawn McCarney  * The callback must have the following signature:
2129adc4f0dbSShawn McCarney  *   @code
2130adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2131adc4f0dbSShawn McCarney  *   @endcode
21328fb49dd6SShawn McCarney  *
21338fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21348fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21358fb49dd6SShawn McCarney  * implements ObjectManager.
2136adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21378fb49dd6SShawn McCarney  */
2138adc4f0dbSShawn McCarney template <typename Callback>
2139d0090733SEd Tanous static void
2140d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2141fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2142adc4f0dbSShawn McCarney                       Callback&& callback)
21438fb49dd6SShawn McCarney {
214462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2145adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2146*8cb2c024SEd Tanous         [sensorsAsyncResp, callback = std::forward<Callback>(callback)](
2147adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
214862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21498fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2150d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2151*8cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
2152fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
215362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2154002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2155d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
215662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
215742cbe538SGunnar Mills 
2158002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2159002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
216062598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb enter");
216142cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2162002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
216342cbe538SGunnar Mills                                              std::move(callback));
216462598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
216542cbe538SGunnar Mills                 };
216642cbe538SGunnar Mills 
2167d500549bSAnthony Wilson                 // Find led connections and get the data
2168d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
216942cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
217062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2171d500549bSAnthony Wilson             };
21728fb49dd6SShawn McCarney 
2173adc4f0dbSShawn McCarney             // Get inventory item data from connections
2174adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2175d0090733SEd Tanous                                   invConnections,
2176d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
217762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
21788fb49dd6SShawn McCarney         };
21798fb49dd6SShawn McCarney 
2180adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2181002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21828fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
218362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
21848fb49dd6SShawn McCarney     };
21858fb49dd6SShawn McCarney 
2186adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2187d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2188adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
218962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2190adc4f0dbSShawn McCarney }
2191adc4f0dbSShawn McCarney 
2192adc4f0dbSShawn McCarney /**
2193adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2194adc4f0dbSShawn McCarney  *
2195adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2196adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2197adc4f0dbSShawn McCarney  * array.
2198adc4f0dbSShawn McCarney  *
2199adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2200adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2201adc4f0dbSShawn McCarney  * object.
2202adc4f0dbSShawn McCarney  *
2203adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2204adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2205adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2206adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2207adc4f0dbSShawn McCarney  */
220823a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2209adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2210adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2211adc4f0dbSShawn McCarney {
221218f8f608SEd Tanous     std::string nameS;
22136f4bd290SAlexander Hansen     nameS.resize(inventoryItem.name.size());
221418f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, nameS.begin(), '_', ' ');
2215adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2216adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2217adc4f0dbSShawn McCarney     {
221818f8f608SEd Tanous         nlohmann::json::iterator nameIt = powerSupply.find("Name");
221918f8f608SEd Tanous         if (nameIt == powerSupply.end())
222018f8f608SEd Tanous         {
222118f8f608SEd Tanous             continue;
222218f8f608SEd Tanous         }
222318f8f608SEd Tanous         const std::string* name = nameIt->get_ptr<std::string*>();
222418f8f608SEd Tanous         if (name == nullptr)
222518f8f608SEd Tanous         {
222618f8f608SEd Tanous             continue;
222718f8f608SEd Tanous         }
222818f8f608SEd Tanous         if (nameS == *name)
2229adc4f0dbSShawn McCarney         {
2230adc4f0dbSShawn McCarney             return powerSupply;
2231adc4f0dbSShawn McCarney         }
2232adc4f0dbSShawn McCarney     }
2233adc4f0dbSShawn McCarney 
2234adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2235adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2236adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2237ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2238ef4c65b7SEd Tanous                                                chassisId);
2239eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2240eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
224118f8f608SEd Tanous     std::string escaped;
22426f4bd290SAlexander Hansen     escaped.resize(inventoryItem.name.size());
224318f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, escaped.begin(), '_', ' ');
224418f8f608SEd Tanous     powerSupply["Name"] = std::move(escaped);
2245adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2246adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2247adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2248adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2249d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2250adc4f0dbSShawn McCarney 
225142cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
225242cbe538SGunnar Mills     {
225342cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
225442cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
225542cbe538SGunnar Mills     }
225642cbe538SGunnar Mills 
2257aaf08ac7SMatt Simmering     powerSupply["Status"]["State"] = getState(&inventoryItem, true);
2258adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2259adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2260adc4f0dbSShawn McCarney 
2261adc4f0dbSShawn McCarney     return powerSupply;
22628fb49dd6SShawn McCarney }
22638fb49dd6SShawn McCarney 
22648fb49dd6SShawn McCarney /**
2265de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2266de629b6eSShawn McCarney  *
2267de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2268de629b6eSShawn McCarney  *
2269de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2270de629b6eSShawn McCarney  * information has been obtained.
2271de629b6eSShawn McCarney  *
2272adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2273de629b6eSShawn McCarney  *
2274de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2275de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2276de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2277de629b6eSShawn McCarney  *
2278de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2279de629b6eSShawn McCarney  *
2280adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2281adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2282adc4f0dbSShawn McCarney  *
2283de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2284adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2285de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2286de629b6eSShawn McCarney  * implements ObjectManager.
2287adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2288de629b6eSShawn McCarney  */
228923a21a1cSEd Tanous inline void getSensorData(
229081ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2291fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2292fe04d49cSNan Zhou     const std::set<std::string>& connections,
2293b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2294de629b6eSShawn McCarney {
229562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2296de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2297de629b6eSShawn McCarney     for (const std::string& connection : connections)
2298de629b6eSShawn McCarney     {
22995eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
23005eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
23015eb468daSGeorge Liu         dbus::utility::getManagedObjects(
23025eb468daSGeorge Liu             connection, sensorPath,
2303002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
23045e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
230502cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
230662598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2307de629b6eSShawn McCarney             if (ec)
2308de629b6eSShawn McCarney             {
230962598e31SEd Tanous                 BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
23108d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2311de629b6eSShawn McCarney                 return;
2312de629b6eSShawn McCarney             }
2313de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2314de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2315de629b6eSShawn McCarney             {
2316de629b6eSShawn McCarney                 const std::string& objPath =
2317de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
231862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
231962598e31SEd Tanous                                  objPath);
2320de629b6eSShawn McCarney 
2321de629b6eSShawn McCarney                 std::vector<std::string> split;
2322de629b6eSShawn McCarney                 // Reserve space for
2323de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2324de629b6eSShawn McCarney                 split.reserve(6);
232550ebd4afSEd Tanous                 // NOLINTNEXTLINE
232650ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2327de629b6eSShawn McCarney                 if (split.size() < 6)
2328de629b6eSShawn McCarney                 {
232962598e31SEd Tanous                     BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
233062598e31SEd Tanous                                      objPath);
2331de629b6eSShawn McCarney                     continue;
2332de629b6eSShawn McCarney                 }
233350ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2334de629b6eSShawn McCarney                 // string at the beginning
2335de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2336de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
233762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
233862598e31SEd Tanous                                  sensorType);
233949c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2340de629b6eSShawn McCarney                 {
234162598e31SEd Tanous                     BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
2342de629b6eSShawn McCarney                     continue;
2343de629b6eSShawn McCarney                 }
2344de629b6eSShawn McCarney 
2345adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2346adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2347adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2348adc4f0dbSShawn McCarney 
234995a3ecadSAnthony Wilson                 const std::string& sensorSchema =
235081ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
235195a3ecadSAnthony Wilson 
235295a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
235395a3ecadSAnthony Wilson 
2354928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2355928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
235695a3ecadSAnthony Wilson                 {
2357c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
23583544d2a7SEd Tanous                     auto remove = std::ranges::remove(sensorTypeEscaped, '_');
23593544d2a7SEd Tanous 
23603544d2a7SEd Tanous                     sensorTypeEscaped.erase(std::ranges::begin(remove),
2361c1d019a6SEd Tanous                                             sensorTypeEscaped.end());
2362c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2363c1d019a6SEd Tanous                     sensorId += "_";
2364c1d019a6SEd Tanous                     sensorId += sensorName;
2365c1d019a6SEd Tanous 
23668d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2367ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2368c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2369ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2370ef4c65b7SEd Tanous                                             sensorId);
23718d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
237295a3ecadSAnthony Wilson                 }
237395a3ecadSAnthony Wilson                 else
237495a3ecadSAnthony Wilson                 {
2375271584abSEd Tanous                     std::string fieldName;
2376928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2377928fefb9SNan Zhou                     {
2378928fefb9SNan Zhou                         fieldName = "Members";
2379928fefb9SNan Zhou                     }
2380928fefb9SNan Zhou                     else if (sensorType == "temperature")
2381de629b6eSShawn McCarney                     {
2382de629b6eSShawn McCarney                         fieldName = "Temperatures";
2383de629b6eSShawn McCarney                     }
2384de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2385de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2386de629b6eSShawn McCarney                     {
2387de629b6eSShawn McCarney                         fieldName = "Fans";
2388de629b6eSShawn McCarney                     }
2389de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2390de629b6eSShawn McCarney                     {
2391de629b6eSShawn McCarney                         fieldName = "Voltages";
2392de629b6eSShawn McCarney                     }
2393de629b6eSShawn McCarney                     else if (sensorType == "power")
2394de629b6eSShawn McCarney                     {
239555f79e6fSEd Tanous                         if (sensorName == "total_power")
2396028f7ebcSEddie James                         {
2397028f7ebcSEddie James                             fieldName = "PowerControl";
2398028f7ebcSEddie James                         }
2399adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2400adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2401028f7ebcSEddie James                         {
2402de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2403de629b6eSShawn McCarney                         }
2404adc4f0dbSShawn McCarney                         else
2405adc4f0dbSShawn McCarney                         {
2406adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2407adc4f0dbSShawn McCarney                             continue;
2408adc4f0dbSShawn McCarney                         }
2409028f7ebcSEddie James                     }
2410de629b6eSShawn McCarney                     else
2411de629b6eSShawn McCarney                     {
241262598e31SEd Tanous                         BMCWEB_LOG_ERROR("Unsure how to handle sensorType {}",
241362598e31SEd Tanous                                          sensorType);
2414de629b6eSShawn McCarney                         continue;
2415de629b6eSShawn McCarney                     }
2416de629b6eSShawn McCarney 
2417de629b6eSShawn McCarney                     nlohmann::json& tempArray =
24188d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2419adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
242049c53ac9SJohnathan Mantey                     {
2421adc4f0dbSShawn McCarney                         if (tempArray.empty())
24227ab06f49SGunnar Mills                         {
242395a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
242495a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
242595a3ecadSAnthony Wilson                             // naming in power.hpp.
24261476687dSEd Tanous                             nlohmann::json::object_t power;
2427ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2428ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2429eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2430eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2431eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2432eddfc437SWilly Tu                                                  .to_string());
2433eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2434b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2435adc4f0dbSShawn McCarney                         }
2436adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2437adc4f0dbSShawn McCarney                     }
2438adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2439adc4f0dbSShawn McCarney                     {
2440adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2441adc4f0dbSShawn McCarney                         {
2442adc4f0dbSShawn McCarney                             sensorJson =
2443adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
244481ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2445adc4f0dbSShawn McCarney                         }
244649c53ac9SJohnathan Mantey                     }
2447928fefb9SNan Zhou                     else if (fieldName == "Members")
2448928fefb9SNan Zhou                     {
2449677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
24503544d2a7SEd Tanous                         auto remove = std::ranges::remove(sensorTypeEscaped,
24513544d2a7SEd Tanous                                                           '_');
24523544d2a7SEd Tanous                         sensorTypeEscaped.erase(std::ranges::begin(remove),
2453677bb756SEd Tanous                                                 sensorTypeEscaped.end());
2454677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2455677bb756SEd Tanous                         sensorId += "_";
2456677bb756SEd Tanous                         sensorId += sensorName;
2457677bb756SEd Tanous 
24581476687dSEd Tanous                         nlohmann::json::object_t member;
2459ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2460ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2461677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2462677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2463b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2464928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2465928fefb9SNan Zhou                     }
246649c53ac9SJohnathan Mantey                     else
246749c53ac9SJohnathan Mantey                     {
24681476687dSEd Tanous                         nlohmann::json::object_t member;
2469ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2470ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2471eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2472eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2473eddfc437SWilly Tu                         url.set_fragment(
2474eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2475eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2476b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2477adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
247849c53ac9SJohnathan Mantey                     }
247995a3ecadSAnthony Wilson                 }
2480de629b6eSShawn McCarney 
2481adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2482adc4f0dbSShawn McCarney                 {
24831d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24841d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24851d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24861d7c0054SEd Tanous                                            inventoryItem);
24871d7c0054SEd Tanous 
24881d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24891d7c0054SEd Tanous                     path += sensorType;
24901d7c0054SEd Tanous                     path += "/";
24911d7c0054SEd Tanous                     path += sensorName;
2492c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2493adc4f0dbSShawn McCarney                 }
2494de629b6eSShawn McCarney             }
249581ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
249649c53ac9SJohnathan Mantey             {
249781ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2498928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2499928fefb9SNan Zhou                         sensors::node::sensors &&
2500928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2501928fefb9SNan Zhou                 {
2502928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2503928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2504928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2505928fefb9SNan Zhou                             .size();
2506928fefb9SNan Zhou                 }
2507928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2508928fefb9SNan Zhou                          sensors::node::thermal)
25098bd25ccdSJames Feist                 {
251081ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
25118bd25ccdSJames Feist                 }
251249c53ac9SJohnathan Mantey             }
251362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
25145eb468daSGeorge Liu         });
251523a21a1cSEd Tanous     }
251662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData exit");
2517de629b6eSShawn McCarney }
2518de629b6eSShawn McCarney 
2519fe04d49cSNan Zhou inline void
2520fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2521fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
25221abe55efSEd Tanous {
2523fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2524fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
252562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb enter");
2526adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2527d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2528d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2529adc4f0dbSShawn McCarney                               inventoryItems) {
253062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
253149c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2532002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2533d0090733SEd Tanous                           inventoryItems);
253462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb exit");
2535adc4f0dbSShawn McCarney         };
2536adc4f0dbSShawn McCarney 
2537adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2538d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2539adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2540adc4f0dbSShawn McCarney 
254162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb exit");
254208777fb0SLewanczyk, Dawid     };
2543de629b6eSShawn McCarney 
2544de629b6eSShawn McCarney     // Get set of connections that provide sensor values
254581ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
254695a3ecadSAnthony Wilson }
254795a3ecadSAnthony Wilson 
254895a3ecadSAnthony Wilson /**
254995a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
255095a3ecadSAnthony Wilson  *        chassis.
255195a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
255295a3ecadSAnthony Wilson  */
2553b5a76932SEd Tanous inline void
255481ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
255595a3ecadSAnthony Wilson {
255662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
255795a3ecadSAnthony Wilson     auto getChassisCb =
255881ce609eSEd Tanous         [sensorsAsyncResp](
2559fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
256062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb enter");
256181ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
256262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb exit");
256308777fb0SLewanczyk, Dawid     };
2564928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2565928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2566928fefb9SNan Zhou     {
25678d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25688d1b46d7Szhanghch05             nlohmann::json::array();
2569928fefb9SNan Zhou     }
257026f03899SShawn McCarney     // Get set of sensors in chassis
25717f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25727f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25737f1cc26dSEd Tanous                std::move(getChassisCb));
257462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData exit");
2575271584abSEd Tanous }
257608777fb0SLewanczyk, Dawid 
2577413961deSRichard Marian Thomaiyar /**
257849c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
257949c53ac9SJohnathan Mantey  * the chassis node
258049c53ac9SJohnathan Mantey  *
258149c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
258249c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
258349c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
258449c53ac9SJohnathan Mantey  *                         repeated calls to this function
258549c53ac9SJohnathan Mantey  */
2586fe04d49cSNan Zhou inline bool
2587fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
258802cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2589fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
259049c53ac9SJohnathan Mantey {
2591fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
259249c53ac9SJohnathan Mantey     {
259328aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2594b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
259528aa8de5SGeorge Liu         if (thisSensorName.empty())
259649c53ac9SJohnathan Mantey         {
259749c53ac9SJohnathan Mantey             continue;
259849c53ac9SJohnathan Mantey         }
259949c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
260049c53ac9SJohnathan Mantey         {
260149c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
260249c53ac9SJohnathan Mantey             return true;
260349c53ac9SJohnathan Mantey         }
260449c53ac9SJohnathan Mantey     }
260549c53ac9SJohnathan Mantey     return false;
260649c53ac9SJohnathan Mantey }
260749c53ac9SJohnathan Mantey 
2608c71d6125SEd Tanous inline std::pair<std::string, std::string>
2609c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2610c71d6125SEd Tanous {
2611c71d6125SEd Tanous     size_t index = sensorId.find('_');
2612c71d6125SEd Tanous     if (index == std::string::npos)
2613c71d6125SEd Tanous     {
2614c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2615c71d6125SEd Tanous     }
2616c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2617c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2618c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2619c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2620c71d6125SEd Tanous     {
2621c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2622c71d6125SEd Tanous     }
2623c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2624c71d6125SEd Tanous }
2625c71d6125SEd Tanous 
262649c53ac9SJohnathan Mantey /**
2627413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2628413961deSRichard Marian Thomaiyar  *
26298d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
26304bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2631413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2632413961deSRichard Marian Thomaiyar  */
263323a21a1cSEd Tanous inline void setSensorsOverride(
2634b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26350885057cSEd Tanous     std::unordered_map<std::string, std::vector<nlohmann::json::object_t>>&
2636397fd61fSjayaprakash Mutyala         allCollections)
2637413961deSRichard Marian Thomaiyar {
263862598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
263962598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
2640413961deSRichard Marian Thomaiyar 
2641d02aad39SEd Tanous     std::string_view propertyValueName;
2642f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2643413961deSRichard Marian Thomaiyar     std::string memberId;
2644543f4400SEd Tanous     double value = 0.0;
2645f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2646f65af9e8SRichard Marian Thomaiyar     {
2647f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2648f65af9e8SRichard Marian Thomaiyar         {
2649f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2650f65af9e8SRichard Marian Thomaiyar         }
2651f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2652f65af9e8SRichard Marian Thomaiyar         {
2653f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2654f65af9e8SRichard Marian Thomaiyar         }
2655f65af9e8SRichard Marian Thomaiyar         else
2656f65af9e8SRichard Marian Thomaiyar         {
2657f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2658f65af9e8SRichard Marian Thomaiyar         }
2659f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2660f65af9e8SRichard Marian Thomaiyar         {
26610885057cSEd Tanous             if (!json_util::readJsonObject(
26620885057cSEd Tanous                     item, sensorAsyncResp->asyncResp->res, "MemberId", memberId,
26630885057cSEd Tanous                     propertyValueName, value))
2664413961deSRichard Marian Thomaiyar             {
2665413961deSRichard Marian Thomaiyar                 return;
2666413961deSRichard Marian Thomaiyar             }
2667f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2668f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2669f65af9e8SRichard Marian Thomaiyar         }
2670f65af9e8SRichard Marian Thomaiyar     }
26714bb3dc34SCarol Wang 
2672002d39b4SEd Tanous     auto getChassisSensorListCb =
2673d02aad39SEd Tanous         [sensorAsyncResp, overrideMap,
2674d02aad39SEd Tanous          propertyValueNameStr = std::string(propertyValueName)](
2675fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
267649c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
267749c53ac9SJohnathan Mantey         // chassis node
2678fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2679fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2680f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2681413961deSRichard Marian Thomaiyar         {
2682f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2683c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2684c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2685c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2686c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2687f65af9e8SRichard Marian Thomaiyar             {
268862598e31SEd Tanous                 BMCWEB_LOG_INFO("Unable to find memberId {}", item.first);
26898d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2690f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2691413961deSRichard Marian Thomaiyar                 return;
2692413961deSRichard Marian Thomaiyar             }
2693f65af9e8SRichard Marian Thomaiyar         }
2694413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2695002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2696d02aad39SEd Tanous             [sensorAsyncResp, overrideMap, propertyValueNameStr](
2697d02aad39SEd Tanous                 const std::set<std::string>& /*connections*/,
2698002d39b4SEd Tanous                 const std::set<std::pair<std::string, std::string>>&
2699413961deSRichard Marian Thomaiyar                     objectsWithConnection) {
2700f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2701413961deSRichard Marian Thomaiyar             {
270262598e31SEd Tanous                 BMCWEB_LOG_INFO(
270362598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
270462598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
27054f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2706a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2707a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2708413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2709413961deSRichard Marian Thomaiyar                                                : "Voltages",
2710f65af9e8SRichard Marian Thomaiyar                                            "Count");
2711f65af9e8SRichard Marian Thomaiyar                 return;
2712f65af9e8SRichard Marian Thomaiyar             }
2713f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2714f65af9e8SRichard Marian Thomaiyar             {
271528aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
271628aa8de5SGeorge Liu                 std::string sensorName = path.filename();
271728aa8de5SGeorge Liu                 if (sensorName.empty())
2718f65af9e8SRichard Marian Thomaiyar                 {
27194f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2720f65af9e8SRichard Marian Thomaiyar                     return;
2721f65af9e8SRichard Marian Thomaiyar                 }
27223f5eb755SBan Feng                 std::string id = path.parent_path().filename();
27233544d2a7SEd Tanous                 auto remove = std::ranges::remove(id, '_');
27243544d2a7SEd Tanous                 id.erase(std::ranges::begin(remove), id.end());
27253f5eb755SBan Feng                 id += "_";
27263f5eb755SBan Feng                 id += sensorName;
2727f65af9e8SRichard Marian Thomaiyar 
27283f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2729f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2730f65af9e8SRichard Marian Thomaiyar                 {
273162598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
273262598e31SEd Tanous                                     item.first);
27334f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2734413961deSRichard Marian Thomaiyar                     return;
2735413961deSRichard Marian Thomaiyar                 }
2736d02aad39SEd Tanous                 setDbusProperty(sensorAsyncResp->asyncResp, item.second,
2737d02aad39SEd Tanous                                 item.first, "xyz.openbmc_project.Sensor.Value",
2738d02aad39SEd Tanous                                 "Value", propertyValueNameStr,
2739d02aad39SEd Tanous                                 iterator->second.first);
2740f65af9e8SRichard Marian Thomaiyar             }
2741413961deSRichard Marian Thomaiyar         };
2742413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2743413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2744413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2745413961deSRichard Marian Thomaiyar     };
2746413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27477f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27487f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27497f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2750413961deSRichard Marian Thomaiyar }
2751413961deSRichard Marian Thomaiyar 
2752a0ec28b6SAdrian Ambrożewicz /**
2753a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2754a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2755a0ec28b6SAdrian Ambrożewicz  *
2756a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2757a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2758a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2759a0ec28b6SAdrian Ambrożewicz  *
2760a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2761a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2762a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2763a0ec28b6SAdrian Ambrożewicz  */
2764931edc79SEd Tanous template <typename Callback>
2765021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2766021d32cfSKrzysztof Grobelny                                  const std::string& node,
2767931edc79SEd Tanous                                  Callback&& mapComplete)
2768a0ec28b6SAdrian Ambrożewicz {
276902da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
277002da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
277102da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
277202da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2773a0ec28b6SAdrian Ambrożewicz     {
277462598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
27756804b5c8SEd Tanous         std::map<std::string, std::string> noop;
27766804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2777a0ec28b6SAdrian Ambrożewicz         return;
2778a0ec28b6SAdrian Ambrożewicz     }
2779d51e072fSKrzysztof Grobelny 
278072374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2781931edc79SEd Tanous     auto callback = [asyncResp,
2782*8cb2c024SEd Tanous                      mapCompleteCb = std::forward<Callback>(mapComplete)](
2783a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2784fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2785fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2786fe04d49cSNan Zhou     };
2787a0ec28b6SAdrian Ambrożewicz 
2788a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2789d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2790a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2791a0ec28b6SAdrian Ambrożewicz }
2792a0ec28b6SAdrian Ambrożewicz 
2793bacb2162SNan Zhou namespace sensors
2794bacb2162SNan Zhou {
2795928fefb9SNan Zhou 
2796bacb2162SNan Zhou inline void getChassisCallback(
2797c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2798c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2799fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2800bacb2162SNan Zhou {
280162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2802bacb2162SNan Zhou 
2803c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2804c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2805bacb2162SNan Zhou     {
280662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2807bacb2162SNan Zhou 
2808bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2809bacb2162SNan Zhou         std::string sensorName = path.filename();
2810bacb2162SNan Zhou         if (sensorName.empty())
2811bacb2162SNan Zhou         {
281262598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2813c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2814bacb2162SNan Zhou             return;
2815bacb2162SNan Zhou         }
2816c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2817c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2818c1d019a6SEd Tanous         // type in the URI
28193544d2a7SEd Tanous         auto remove = std::ranges::remove(type, '_');
28203544d2a7SEd Tanous         type.erase(std::ranges::begin(remove), type.end());
2821c1d019a6SEd Tanous 
28221476687dSEd Tanous         nlohmann::json::object_t member;
2823c1d019a6SEd Tanous         std::string id = type;
2824c1d019a6SEd Tanous         id += "_";
2825c1d019a6SEd Tanous         id += sensorName;
2826ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2827ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2828c1d019a6SEd Tanous 
2829b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2830bacb2162SNan Zhou     }
2831bacb2162SNan Zhou 
2832c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
283362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2834bacb2162SNan Zhou }
2835e6bd846dSNan Zhou 
2836ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2837ac106bf6SEd Tanous     App& app, const crow::Request& req,
2838ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2839de167a6fSNan Zhou     const std::string& chassisId)
2840de167a6fSNan Zhou {
2841de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2842de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2843de167a6fSNan Zhou     };
2844de167a6fSNan Zhou     query_param::Query delegatedQuery;
2845ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2846de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2847de167a6fSNan Zhou     {
2848de167a6fSNan Zhou         return;
2849de167a6fSNan Zhou     }
2850de167a6fSNan Zhou 
2851de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2852de167a6fSNan Zhou     {
2853de167a6fSNan Zhou         // we perform efficient expand.
2854ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2855ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2856de167a6fSNan Zhou             sensors::node::sensors,
2857de167a6fSNan Zhou             /*efficientExpand=*/true);
2858ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2859de167a6fSNan Zhou 
286062598e31SEd Tanous         BMCWEB_LOG_DEBUG(
286162598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2862de167a6fSNan Zhou         return;
28630bad320cSEd Tanous     }
2864de167a6fSNan Zhou 
2865de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2866de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2867ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2868ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2869ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2870c1d019a6SEd Tanous }
28717f1cc26dSEd Tanous 
2872c1d019a6SEd Tanous inline void
2873c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2874c1d019a6SEd Tanous                       const std::string& sensorPath,
2875c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2876c1d019a6SEd Tanous {
2877c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2878c1d019a6SEd Tanous     {
2879c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2880c1d019a6SEd Tanous         return;
2881c1d019a6SEd Tanous     }
2882c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2883c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
288462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
288562598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2886c1343bf6SKrzysztof Grobelny 
2887c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2888c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2889c1d019a6SEd Tanous         [asyncResp,
28905e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2891c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2892c1d019a6SEd Tanous         if (ec)
2893c1d019a6SEd Tanous         {
2894c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2895c1d019a6SEd Tanous             return;
2896c1d019a6SEd Tanous         }
2897c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2898c1d019a6SEd Tanous         std::string name = path.filename();
2899c1d019a6SEd Tanous         path = path.parent_path();
2900c1d019a6SEd Tanous         std::string type = path.filename();
2901c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2902c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2903c1343bf6SKrzysztof Grobelny     });
2904de167a6fSNan Zhou }
2905de167a6fSNan Zhou 
2906e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2907c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2908677bb756SEd Tanous                             const std::string& chassisId,
2909c1d019a6SEd Tanous                             const std::string& sensorId)
2910e6bd846dSNan Zhou {
2911c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2912e6bd846dSNan Zhou     {
2913e6bd846dSNan Zhou         return;
2914e6bd846dSNan Zhou     }
2915c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2916c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2917c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2918c1d019a6SEd Tanous     {
2919c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2920c1d019a6SEd Tanous         return;
2921c1d019a6SEd Tanous     }
2922c71d6125SEd Tanous 
2923ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2924ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2925c1d019a6SEd Tanous 
292662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2927e6bd846dSNan Zhou 
29282b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2929e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2930c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2931c71d6125SEd Tanous                              '/' + nameType.second;
2932e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2933e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29342b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29352b73119cSGeorge Liu         sensorPath, interfaces,
2936aec0ec30SMyung Bae         [asyncResp, sensorId,
29372b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2938c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
293962598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 enter");
2940aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2941aec0ec30SMyung Bae         {
294262598e31SEd Tanous             BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2943aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2944aec0ec30SMyung Bae             return;
2945aec0ec30SMyung Bae         }
2946e6bd846dSNan Zhou         if (ec)
2947e6bd846dSNan Zhou         {
2948c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
294962598e31SEd Tanous             BMCWEB_LOG_ERROR(
295062598e31SEd Tanous                 "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2951e6bd846dSNan Zhou             return;
2952e6bd846dSNan Zhou         }
2953c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
295462598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 exit");
29552b73119cSGeorge Liu     });
2956e6bd846dSNan Zhou }
2957e6bd846dSNan Zhou 
2958bacb2162SNan Zhou } // namespace sensors
2959bacb2162SNan Zhou 
29607e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
296195a3ecadSAnthony Wilson {
29627e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2963ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2964002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2965de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
296695a3ecadSAnthony Wilson }
296795a3ecadSAnthony Wilson 
29687e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
296995a3ecadSAnthony Wilson {
29707e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2971ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2972002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2973e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
297495a3ecadSAnthony Wilson }
297595a3ecadSAnthony Wilson 
297608777fb0SLewanczyk, Dawid } // namespace redfish
2977