xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 6804b5c8d8bd4c571b8179589f88bcf1a1502f7b)
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"
210ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
223ccb3adbSEd Tanous #include "query.hpp"
233ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2450ebd4afSEd Tanous #include "str_utility.hpp"
253ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
263ccb3adbSEd Tanous #include "utils/json_utils.hpp"
273ccb3adbSEd Tanous #include "utils/query_param.hpp"
280ec8b83dSEd Tanous 
2911ba3979SEd Tanous #include <boost/algorithm/string/classification.hpp>
301d7c0054SEd Tanous #include <boost/algorithm/string/find.hpp>
311d7c0054SEd Tanous #include <boost/algorithm/string/predicate.hpp>
32c71d6125SEd Tanous #include <boost/algorithm/string/replace.hpp>
3308777fb0SLewanczyk, Dawid #include <boost/range/algorithm/replace_copy_if.hpp>
34e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
35ef4c65b7SEd Tanous #include <boost/url/format.hpp>
361e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3786d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
381214b7e7SGunnar Mills 
397a1dbc48SGeorge Liu #include <array>
401214b7e7SGunnar Mills #include <cmath>
41fe04d49cSNan Zhou #include <iterator>
42283860f5SEd Tanous #include <limits>
43fe04d49cSNan Zhou #include <map>
443544d2a7SEd Tanous #include <ranges>
45fe04d49cSNan Zhou #include <set>
467a1dbc48SGeorge Liu #include <string_view>
47b5a76932SEd Tanous #include <utility>
48abf2add6SEd Tanous #include <variant>
4908777fb0SLewanczyk, Dawid 
501abe55efSEd Tanous namespace redfish
511abe55efSEd Tanous {
5208777fb0SLewanczyk, Dawid 
53a0ec28b6SAdrian Ambrożewicz namespace sensors
54a0ec28b6SAdrian Ambrożewicz {
55a0ec28b6SAdrian Ambrożewicz namespace node
56a0ec28b6SAdrian Ambrożewicz {
57a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
58a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
59a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
60a0ec28b6SAdrian Ambrożewicz } // namespace node
61a0ec28b6SAdrian Ambrożewicz 
6202da7c5aSEd Tanous // clang-format off
63a0ec28b6SAdrian Ambrożewicz namespace dbus
64a0ec28b6SAdrian Ambrożewicz {
65cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6802da7c5aSEd Tanous });
69c2bf7f99SWludzik, Jozef 
70cf9e417dSEd Tanous constexpr auto sensorPaths = std::to_array<std::string_view>({
7102da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
72a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
737088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
745deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
75e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
76e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
77e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
78e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
79e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
80e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
81e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
82e8204933SGeorge Liu #endif
8302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
8402da7c5aSEd Tanous });
8502da7c5aSEd Tanous 
86cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
8702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
88a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8902da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
9002da7c5aSEd Tanous });
9102da7c5aSEd Tanous 
92c2bf7f99SWludzik, Jozef } // namespace dbus
9302da7c5aSEd Tanous // clang-format on
9402da7c5aSEd Tanous 
95cf9e417dSEd Tanous using sensorPair =
96cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
9702da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
98cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
99cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
100cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
101c2bf7f99SWludzik, Jozef 
1020ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
103c2bf7f99SWludzik, Jozef {
104c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
105c2bf7f99SWludzik, Jozef     {
1060ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
107c2bf7f99SWludzik, Jozef     }
108c2bf7f99SWludzik, Jozef     if (sensorType == "power")
109c2bf7f99SWludzik, Jozef     {
1100ec8b83dSEd Tanous         return sensor::ReadingType::Power;
111c2bf7f99SWludzik, Jozef     }
112c2bf7f99SWludzik, Jozef     if (sensorType == "current")
113c2bf7f99SWludzik, Jozef     {
1140ec8b83dSEd Tanous         return sensor::ReadingType::Current;
115c2bf7f99SWludzik, Jozef     }
116c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
117c2bf7f99SWludzik, Jozef     {
1180ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
119c2bf7f99SWludzik, Jozef     }
120c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
121c2bf7f99SWludzik, Jozef     {
1220ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
123c2bf7f99SWludzik, Jozef     }
124c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
125c2bf7f99SWludzik, Jozef     {
1260ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
127c2bf7f99SWludzik, Jozef     }
1285deabed9SGunnar Mills     if (sensorType == "humidity")
1295deabed9SGunnar Mills     {
1300ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1315deabed9SGunnar Mills     }
132c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
133c2bf7f99SWludzik, Jozef     {
1340ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
135c2bf7f99SWludzik, Jozef     }
136c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
137c2bf7f99SWludzik, Jozef     {
1380ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
139c2bf7f99SWludzik, Jozef     }
140c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
141c2bf7f99SWludzik, Jozef     {
1420ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
143c2bf7f99SWludzik, Jozef     }
1440ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
145c2bf7f99SWludzik, Jozef }
146c2bf7f99SWludzik, Jozef 
1471d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
148c2bf7f99SWludzik, Jozef {
149c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
150c2bf7f99SWludzik, Jozef     {
151c2bf7f99SWludzik, Jozef         return "V";
152c2bf7f99SWludzik, Jozef     }
153c2bf7f99SWludzik, Jozef     if (sensorType == "power")
154c2bf7f99SWludzik, Jozef     {
155c2bf7f99SWludzik, Jozef         return "W";
156c2bf7f99SWludzik, Jozef     }
157c2bf7f99SWludzik, Jozef     if (sensorType == "current")
158c2bf7f99SWludzik, Jozef     {
159c2bf7f99SWludzik, Jozef         return "A";
160c2bf7f99SWludzik, Jozef     }
161c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
162c2bf7f99SWludzik, Jozef     {
163c2bf7f99SWludzik, Jozef         return "RPM";
164c2bf7f99SWludzik, Jozef     }
165c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
166c2bf7f99SWludzik, Jozef     {
167c2bf7f99SWludzik, Jozef         return "Cel";
168c2bf7f99SWludzik, Jozef     }
1695deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1705deabed9SGunnar Mills         sensorType == "humidity")
171c2bf7f99SWludzik, Jozef     {
172c2bf7f99SWludzik, Jozef         return "%";
173c2bf7f99SWludzik, Jozef     }
174c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
175c2bf7f99SWludzik, Jozef     {
176c2bf7f99SWludzik, Jozef         return "m";
177c2bf7f99SWludzik, Jozef     }
178c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
179c2bf7f99SWludzik, Jozef     {
180c2bf7f99SWludzik, Jozef         return "cft_i/min";
181c2bf7f99SWludzik, Jozef     }
182c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
183c2bf7f99SWludzik, Jozef     {
184c2bf7f99SWludzik, Jozef         return "J";
185c2bf7f99SWludzik, Jozef     }
186c2bf7f99SWludzik, Jozef     return "";
187a0ec28b6SAdrian Ambrożewicz }
188a0ec28b6SAdrian Ambrożewicz } // namespace sensors
189a0ec28b6SAdrian Ambrożewicz 
19008777fb0SLewanczyk, Dawid /**
191588c3f0dSKowalski, Kamil  * SensorsAsyncResp
19208777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
19308777fb0SLewanczyk, Dawid  */
1941abe55efSEd Tanous class SensorsAsyncResp
1951abe55efSEd Tanous {
19608777fb0SLewanczyk, Dawid   public:
197a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
198a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
199fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
200a0ec28b6SAdrian Ambrożewicz 
201a0ec28b6SAdrian Ambrożewicz     struct SensorData
202a0ec28b6SAdrian Ambrożewicz     {
203a0ec28b6SAdrian Ambrożewicz         const std::string name;
204a0ec28b6SAdrian Ambrożewicz         std::string uri;
205a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
206a0ec28b6SAdrian Ambrożewicz     };
207a0ec28b6SAdrian Ambrożewicz 
2088a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2098d1b46d7Szhanghch05                      const std::string& chassisIdIn,
210cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21102da7c5aSEd Tanous                      std::string_view subNode) :
2128a592810SEd Tanous         asyncResp(asyncRespIn),
213928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
214928fefb9SNan Zhou         efficientExpand(false)
2151214b7e7SGunnar Mills     {}
21608777fb0SLewanczyk, Dawid 
217a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2188a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2198d1b46d7Szhanghch05                      const std::string& chassisIdIn,
220cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22102da7c5aSEd Tanous                      std::string_view subNode,
222a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2238a592810SEd Tanous         asyncResp(asyncRespIn),
224928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
225928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
226a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
227a0ec28b6SAdrian Ambrożewicz     {}
228a0ec28b6SAdrian Ambrożewicz 
229928fefb9SNan Zhou     // sensor collections expand
2308a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
231928fefb9SNan Zhou                      const std::string& chassisIdIn,
232cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2338a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2348a592810SEd Tanous         asyncResp(asyncRespIn),
235928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2368a592810SEd Tanous         efficientExpand(efficientExpandIn)
237928fefb9SNan Zhou     {}
238928fefb9SNan Zhou 
2391abe55efSEd Tanous     ~SensorsAsyncResp()
2401abe55efSEd Tanous     {
2418d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2428d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2431abe55efSEd Tanous         {
2441abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2451abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2461abe55efSEd Tanous             // proper code
2478d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24808777fb0SLewanczyk, Dawid         }
249a0ec28b6SAdrian Ambrożewicz 
250a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
251a0ec28b6SAdrian Ambrożewicz         {
252fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2538d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
254a0ec28b6SAdrian Ambrożewicz             {
255a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
256a0ec28b6SAdrian Ambrożewicz                 {
257c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
258a0ec28b6SAdrian Ambrożewicz                 }
259a0ec28b6SAdrian Ambrożewicz             }
2608d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
261a0ec28b6SAdrian Ambrożewicz         }
26208777fb0SLewanczyk, Dawid     }
263588c3f0dSKowalski, Kamil 
264ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
265ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
266ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
267ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
268ecd6a3a2SEd Tanous 
269a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
270c1d019a6SEd Tanous                      const std::string& dbusPath)
271a0ec28b6SAdrian Ambrożewicz     {
272a0ec28b6SAdrian Ambrożewicz         if (metadata)
273a0ec28b6SAdrian Ambrożewicz         {
274c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
275c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
276a0ec28b6SAdrian Ambrożewicz         }
277a0ec28b6SAdrian Ambrożewicz     }
278a0ec28b6SAdrian Ambrożewicz 
279a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
280a0ec28b6SAdrian Ambrożewicz     {
281a0ec28b6SAdrian Ambrożewicz         if (metadata)
282a0ec28b6SAdrian Ambrożewicz         {
283a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
284a0ec28b6SAdrian Ambrożewicz             {
285a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
286a0ec28b6SAdrian Ambrożewicz                 {
287a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
288a0ec28b6SAdrian Ambrożewicz                 }
289a0ec28b6SAdrian Ambrożewicz             }
290a0ec28b6SAdrian Ambrożewicz         }
291a0ec28b6SAdrian Ambrożewicz     }
292a0ec28b6SAdrian Ambrożewicz 
2938d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
294a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
295cf9e417dSEd Tanous     const std::span<const std::string_view> types;
296a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
297928fefb9SNan Zhou     const bool efficientExpand;
298a0ec28b6SAdrian Ambrożewicz 
299a0ec28b6SAdrian Ambrożewicz   private:
300a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
301a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
30208777fb0SLewanczyk, Dawid };
30308777fb0SLewanczyk, Dawid 
30408777fb0SLewanczyk, Dawid /**
305d500549bSAnthony Wilson  * Possible states for physical inventory leds
306d500549bSAnthony Wilson  */
307d500549bSAnthony Wilson enum class LedState
308d500549bSAnthony Wilson {
309d500549bSAnthony Wilson     OFF,
310d500549bSAnthony Wilson     ON,
311d500549bSAnthony Wilson     BLINK,
312d500549bSAnthony Wilson     UNKNOWN
313d500549bSAnthony Wilson };
314d500549bSAnthony Wilson 
315d500549bSAnthony Wilson /**
316adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
317adc4f0dbSShawn McCarney  */
318adc4f0dbSShawn McCarney class InventoryItem
319adc4f0dbSShawn McCarney {
320adc4f0dbSShawn McCarney   public:
3214e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
322adc4f0dbSShawn McCarney     {
323adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
32428aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
32528aa8de5SGeorge Liu         name = path.filename();
32628aa8de5SGeorge Liu         if (name.empty())
327adc4f0dbSShawn McCarney         {
32862598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
329adc4f0dbSShawn McCarney         }
330adc4f0dbSShawn McCarney     }
331adc4f0dbSShawn McCarney 
332adc4f0dbSShawn McCarney     std::string objectPath;
333adc4f0dbSShawn McCarney     std::string name;
334e05aec50SEd Tanous     bool isPresent = true;
335e05aec50SEd Tanous     bool isFunctional = true;
336e05aec50SEd Tanous     bool isPowerSupply = false;
337e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
338adc4f0dbSShawn McCarney     std::string manufacturer;
339adc4f0dbSShawn McCarney     std::string model;
340adc4f0dbSShawn McCarney     std::string partNumber;
341adc4f0dbSShawn McCarney     std::string serialNumber;
342adc4f0dbSShawn McCarney     std::set<std::string> sensors;
343d500549bSAnthony Wilson     std::string ledObjectPath;
344e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
345adc4f0dbSShawn McCarney };
346adc4f0dbSShawn McCarney 
347adc4f0dbSShawn McCarney /**
348413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
349588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
35008777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
35108777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
35208777fb0SLewanczyk, Dawid  */
35308777fb0SLewanczyk, Dawid template <typename Callback>
354413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
35581ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
356fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3571abe55efSEd Tanous     Callback&& callback)
3581abe55efSEd Tanous {
35962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
36003b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
361e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
36208777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
36308777fb0SLewanczyk, Dawid 
364e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
365e99073f5SGeorge Liu     dbus::utility::getSubTree(
366e99073f5SGeorge Liu         path, 2, interfaces,
367002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
368e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
369002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
370e99073f5SGeorge Liu         // Response handler for parsing objects subtree
37162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3721abe55efSEd Tanous         if (ec)
3731abe55efSEd Tanous         {
3748d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
37562598e31SEd Tanous             BMCWEB_LOG_ERROR(
37662598e31SEd Tanous                 "getObjectsWithConnection resp_handler: Dbus error {}", ec);
37708777fb0SLewanczyk, Dawid             return;
37808777fb0SLewanczyk, Dawid         }
37908777fb0SLewanczyk, Dawid 
38062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
38108777fb0SLewanczyk, Dawid 
38208777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
38308777fb0SLewanczyk, Dawid         // found in the chassis
384fe04d49cSNan Zhou         std::set<std::string> connections;
385413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
38608777fb0SLewanczyk, Dawid 
38762598e31SEd Tanous         BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
38849c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3891abe55efSEd Tanous         {
39062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
39108777fb0SLewanczyk, Dawid         }
39208777fb0SLewanczyk, Dawid 
39308777fb0SLewanczyk, Dawid         for (const std::pair<
39408777fb0SLewanczyk, Dawid                  std::string,
39508777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3961abe55efSEd Tanous                  object : subtree)
3971abe55efSEd Tanous         {
39849c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3991abe55efSEd Tanous             {
40049c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
4011abe55efSEd Tanous                          objData : object.second)
4021abe55efSEd Tanous                 {
40362598e31SEd Tanous                     BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
40408777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
405de629b6eSShawn McCarney                     objectsWithConnection.insert(
406de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
40708777fb0SLewanczyk, Dawid                 }
40808777fb0SLewanczyk, Dawid             }
40908777fb0SLewanczyk, Dawid         }
41062598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
411413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
41262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
413e99073f5SGeorge Liu     });
41462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
415413961deSRichard Marian Thomaiyar }
416413961deSRichard Marian Thomaiyar 
417413961deSRichard Marian Thomaiyar /**
418413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
419413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
420413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
421413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
422413961deSRichard Marian Thomaiyar  */
423413961deSRichard Marian Thomaiyar template <typename Callback>
424fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
425fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
426413961deSRichard Marian Thomaiyar                     Callback&& callback)
427413961deSRichard Marian Thomaiyar {
428413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
429fe04d49cSNan Zhou         [callback](const std::set<std::string>& connections,
430413961deSRichard Marian Thomaiyar                    const std::set<std::pair<std::string, std::string>>&
4313174e4dfSEd Tanous                    /*objectsWithConnection*/) { callback(connections); };
43281ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
433413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
43408777fb0SLewanczyk, Dawid }
43508777fb0SLewanczyk, Dawid 
43608777fb0SLewanczyk, Dawid /**
43749c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
43849c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
43949c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
44049c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
44149c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
44249c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
44349c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
44449c53ac9SJohnathan Mantey  */
44523a21a1cSEd Tanous inline void reduceSensorList(
4467f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
447cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
44849c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
449fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
45049c53ac9SJohnathan Mantey {
45149c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
45249c53ac9SJohnathan Mantey     {
4537f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4547f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
455a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
45649c53ac9SJohnathan Mantey                                        : "Voltages");
45749c53ac9SJohnathan Mantey 
45849c53ac9SJohnathan Mantey         return;
45949c53ac9SJohnathan Mantey     }
46049c53ac9SJohnathan Mantey     if (allSensors->empty())
46149c53ac9SJohnathan Mantey     {
46249c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
46349c53ac9SJohnathan Mantey         return;
46449c53ac9SJohnathan Mantey     }
46549c53ac9SJohnathan Mantey 
4667f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
46749c53ac9SJohnathan Mantey     {
46849c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
46949c53ac9SJohnathan Mantey         {
47011ba3979SEd Tanous             if (sensor.starts_with(type))
47149c53ac9SJohnathan Mantey             {
47249c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
47349c53ac9SJohnathan Mantey             }
47449c53ac9SJohnathan Mantey         }
47549c53ac9SJohnathan Mantey     }
47649c53ac9SJohnathan Mantey }
47749c53ac9SJohnathan Mantey 
4787f1cc26dSEd Tanous /*
4797f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4807f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4817f1cc26dSEd Tanous  *
4827f1cc26dSEd Tanous  * */
4837f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4847f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4857f1cc26dSEd Tanous {
4867f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4877f1cc26dSEd Tanous     {
4887f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4897f1cc26dSEd Tanous     }
4907f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4917f1cc26dSEd Tanous     {
4927f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
4937f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
4947f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
4957f1cc26dSEd Tanous     }
4967f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
4977f1cc26dSEd Tanous     {
4987f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
4997f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
5007f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
5017f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5027f1cc26dSEd Tanous     }
5037f1cc26dSEd Tanous 
5047f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5057f1cc26dSEd Tanous     {
5067f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5077f1cc26dSEd Tanous     }
5087f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5097f1cc26dSEd Tanous }
5107f1cc26dSEd Tanous 
51149c53ac9SJohnathan Mantey /**
51208777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
513588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
51408777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
51508777fb0SLewanczyk, Dawid  */
51608777fb0SLewanczyk, Dawid template <typename Callback>
5177f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5187f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
519cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
520cf9e417dSEd Tanous                 Callback&& callback)
5211abe55efSEd Tanous {
52262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5237a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
52449c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
525adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5267a1dbc48SGeorge Liu 
5277a1dbc48SGeorge Liu     // Get the Chassis Collection
5287a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5297a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5307f1cc26dSEd Tanous         [callback{std::forward<Callback>(callback)}, asyncResp,
5317f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5327f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5337a1dbc48SGeorge Liu             const boost::system::error_code& ec,
534002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
53562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5361abe55efSEd Tanous         if (ec)
5371abe55efSEd Tanous         {
53862598e31SEd Tanous             BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5397f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
54008777fb0SLewanczyk, Dawid             return;
54108777fb0SLewanczyk, Dawid         }
54249c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
54349c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5441abe55efSEd Tanous         {
54528aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
546f8fe53e7SEd Tanous             std::string chassisName = path.filename();
54728aa8de5SGeorge Liu             if (chassisName.empty())
5481abe55efSEd Tanous             {
54962598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
550daf36e2eSEd Tanous                 continue;
551daf36e2eSEd Tanous             }
5527f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5531abe55efSEd Tanous             {
55449c53ac9SJohnathan Mantey                 chassisPath = &chassis;
55549c53ac9SJohnathan Mantey                 break;
556daf36e2eSEd Tanous             }
55749c53ac9SJohnathan Mantey         }
55849c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5591abe55efSEd Tanous         {
5607f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
56149c53ac9SJohnathan Mantey             return;
5621abe55efSEd Tanous         }
5637f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
56408777fb0SLewanczyk, Dawid 
565ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
566ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
56795a3ecadSAnthony Wilson 
5688fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5698fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5706c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5716c3e9451SGeorge Liu             sensorPath,
5727f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
573f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
5748b24275dSEd Tanous                 const boost::system::error_code& ec2,
5756c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
5768b24275dSEd Tanous             if (ec2)
57749c53ac9SJohnathan Mantey             {
5788b24275dSEd Tanous                 if (ec2.value() != EBADR)
57949c53ac9SJohnathan Mantey                 {
5807f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
58149c53ac9SJohnathan Mantey                     return;
58249c53ac9SJohnathan Mantey                 }
58349c53ac9SJohnathan Mantey             }
584fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
585fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5867f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5877f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
58862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
58949c53ac9SJohnathan Mantey             callback(culledSensorList);
5901e1e598dSJonathan Doman         });
5917a1dbc48SGeorge Liu     });
59262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
59308777fb0SLewanczyk, Dawid }
59408777fb0SLewanczyk, Dawid 
59508777fb0SLewanczyk, Dawid /**
596adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
597adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
598adc4f0dbSShawn McCarney  * @return State value for inventory item.
59934dd179eSJames Feist  */
60023a21a1cSEd Tanous inline std::string getState(const InventoryItem* inventoryItem)
601adc4f0dbSShawn McCarney {
602adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
603adc4f0dbSShawn McCarney     {
604adc4f0dbSShawn McCarney         return "Absent";
605adc4f0dbSShawn McCarney     }
60634dd179eSJames Feist 
607adc4f0dbSShawn McCarney     return "Enabled";
608adc4f0dbSShawn McCarney }
609adc4f0dbSShawn McCarney 
610adc4f0dbSShawn McCarney /**
611adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
612adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6131d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
614adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
615adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
616adc4f0dbSShawn McCarney  * @return Health value for sensor.
617adc4f0dbSShawn McCarney  */
6181d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6191d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
620adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
62134dd179eSJames Feist {
622adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
623adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
624adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
625adc4f0dbSShawn McCarney     std::string currentHealth;
626adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
627adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
628adc4f0dbSShawn McCarney     {
629adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
630adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
631adc4f0dbSShawn McCarney         {
632adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
633adc4f0dbSShawn McCarney             if (health != nullptr)
634adc4f0dbSShawn McCarney             {
635adc4f0dbSShawn McCarney                 currentHealth = *health;
636adc4f0dbSShawn McCarney             }
637adc4f0dbSShawn McCarney         }
638adc4f0dbSShawn McCarney     }
639adc4f0dbSShawn McCarney 
640adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
641adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
642adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
643adc4f0dbSShawn McCarney     {
644adc4f0dbSShawn McCarney         return "Critical";
645adc4f0dbSShawn McCarney     }
646adc4f0dbSShawn McCarney 
647c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
648c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
649c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
650c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
651711ac7a9SEd Tanous 
652c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
653c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
654c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
655c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
656c1343bf6SKrzysztof Grobelny         warningAlarmLow);
657c1343bf6SKrzysztof Grobelny 
658c1343bf6SKrzysztof Grobelny     if (success)
65934dd179eSJames Feist     {
660c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
661c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
662c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
66334dd179eSJames Feist         {
66434dd179eSJames Feist             return "Critical";
66534dd179eSJames Feist         }
66634dd179eSJames Feist     }
66734dd179eSJames Feist 
668adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
669adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
670adc4f0dbSShawn McCarney     {
671adc4f0dbSShawn McCarney         return "Critical";
672adc4f0dbSShawn McCarney     }
673adc4f0dbSShawn McCarney 
674adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
675adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
676adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
677adc4f0dbSShawn McCarney     {
678adc4f0dbSShawn McCarney         return "Warning";
679adc4f0dbSShawn McCarney     }
680adc4f0dbSShawn McCarney 
681c1343bf6SKrzysztof Grobelny     if (success)
682c1343bf6SKrzysztof Grobelny     {
683adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
684c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
685c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
68634dd179eSJames Feist         {
687ebe4d91eSEd Tanous             return "Warning";
68834dd179eSJames Feist         }
68934dd179eSJames Feist     }
690adc4f0dbSShawn McCarney 
69134dd179eSJames Feist     return "OK";
69234dd179eSJames Feist }
69334dd179eSJames Feist 
69423a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
695d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
696d500549bSAnthony Wilson {
697d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
698d500549bSAnthony Wilson     {
699d500549bSAnthony Wilson         switch (inventoryItem->ledState)
700d500549bSAnthony Wilson         {
701d500549bSAnthony Wilson             case LedState::OFF:
702d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
703d500549bSAnthony Wilson                 break;
704d500549bSAnthony Wilson             case LedState::ON:
705d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
706d500549bSAnthony Wilson                 break;
707d500549bSAnthony Wilson             case LedState::BLINK:
708d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
709d500549bSAnthony Wilson                 break;
71023a21a1cSEd Tanous             case LedState::UNKNOWN:
711d500549bSAnthony Wilson                 break;
712d500549bSAnthony Wilson         }
713d500549bSAnthony Wilson     }
714d500549bSAnthony Wilson }
715d500549bSAnthony Wilson 
71634dd179eSJames Feist /**
71708777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
71808777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
719274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
72008777fb0SLewanczyk, Dawid  * build
7211d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
7221d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7231d7c0054SEd Tanous  * from.
7241d7c0054SEd Tanous  * @param sensorJson  The json object to fill
725adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
726adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
72708777fb0SLewanczyk, Dawid  */
7281d7c0054SEd Tanous inline void objectPropertiesToJson(
7291d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7301d7c0054SEd Tanous     std::string_view chassisSubNode,
7311d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
73281ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7331abe55efSEd Tanous {
7341d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
735adc4f0dbSShawn McCarney     {
736c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
7373544d2a7SEd Tanous         auto remove = std::ranges::remove(subNodeEscaped, '_');
7383544d2a7SEd Tanous         subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
739c1d019a6SEd Tanous 
740c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
741c1d019a6SEd Tanous         // including power sensors.
742c1d019a6SEd Tanous         subNodeEscaped += '_';
743c1d019a6SEd Tanous         subNodeEscaped += sensorName;
744c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
745c1d019a6SEd Tanous 
7461d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7471d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7481d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
74995a3ecadSAnthony Wilson     }
75095a3ecadSAnthony Wilson     else if (sensorType != "power")
75195a3ecadSAnthony Wilson     {
75295a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
75395a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
75495a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7551d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7561d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7571d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
758adc4f0dbSShawn McCarney     }
759e742b6ccSEd Tanous 
76081ce609eSEd Tanous     sensorJson["Status"]["State"] = getState(inventoryItem);
76189492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
76289492a15SPatrick Williams                                                inventoryItem);
76308777fb0SLewanczyk, Dawid 
76408777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
76508777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
76608777fb0SLewanczyk, Dawid     // that require integers, not floats.
76708777fb0SLewanczyk, Dawid     bool forceToInt = false;
76808777fb0SLewanczyk, Dawid 
7693929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7701d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
77195a3ecadSAnthony Wilson     {
7722a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
773c2bf7f99SWludzik, Jozef 
7740ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
7750ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
77695a3ecadSAnthony Wilson         {
77762598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
77862598e31SEd Tanous                              sensorType);
77995a3ecadSAnthony Wilson         }
780c2bf7f99SWludzik, Jozef         else
78195a3ecadSAnthony Wilson         {
782c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
78395a3ecadSAnthony Wilson         }
784c2bf7f99SWludzik, Jozef 
7851d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
786c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
787f8ede15eSAdrian Ambrożewicz         {
78862598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
78962598e31SEd Tanous                              sensorType);
790c2bf7f99SWludzik, Jozef         }
791c2bf7f99SWludzik, Jozef         else
792c2bf7f99SWludzik, Jozef         {
793c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
794f8ede15eSAdrian Ambrożewicz         }
79595a3ecadSAnthony Wilson     }
79695a3ecadSAnthony Wilson     else if (sensorType == "temperature")
7971abe55efSEd Tanous     {
7983929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
79981ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
80008777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
80108777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8021abe55efSEd Tanous     }
8031abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8041abe55efSEd Tanous     {
8053929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
80681ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
80781ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
80881ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
80908777fb0SLewanczyk, Dawid         forceToInt = true;
8101abe55efSEd Tanous     }
8116f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8126f6d0d32SEd Tanous     {
8133929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
81481ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
81581ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
81681ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8176f6d0d32SEd Tanous         forceToInt = true;
8186f6d0d32SEd Tanous     }
8191abe55efSEd Tanous     else if (sensorType == "voltage")
8201abe55efSEd Tanous     {
8213929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
82281ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8231abe55efSEd Tanous     }
8242474adfaSEd Tanous     else if (sensorType == "power")
8252474adfaSEd Tanous     {
8261d7c0054SEd Tanous         if (boost::iequals(sensorName, "total_power"))
827028f7ebcSEddie James         {
82881ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8297ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8307ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
83181ce609eSEd Tanous             sensorJson["MemberId"] = "0";
83281ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8333929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
834028f7ebcSEddie James         }
8350f3fbe52SAnjaliintel-21         else if (!(boost::ifind_first(sensorName, "input").empty()))
83649c53ac9SJohnathan Mantey         {
8373929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
83849c53ac9SJohnathan Mantey         }
83949c53ac9SJohnathan Mantey         else
84049c53ac9SJohnathan Mantey         {
8413929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
84249c53ac9SJohnathan Mantey         }
8432474adfaSEd Tanous     }
8441abe55efSEd Tanous     else
8451abe55efSEd Tanous     {
84662598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
84708777fb0SLewanczyk, Dawid         return;
84808777fb0SLewanczyk, Dawid     }
84908777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8503929aca1SAnthony Wilson     std::vector<
8513929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8523929aca1SAnthony Wilson         properties;
85308777fb0SLewanczyk, Dawid     properties.reserve(7);
85408777fb0SLewanczyk, Dawid 
85508777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
856de629b6eSShawn McCarney 
8571d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8583929aca1SAnthony Wilson     {
8593929aca1SAnthony Wilson         properties.emplace_back(
8603929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8613929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8623929aca1SAnthony Wilson         properties.emplace_back(
8633929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8643929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8653929aca1SAnthony Wilson         properties.emplace_back(
8663929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8673929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
8683929aca1SAnthony Wilson         properties.emplace_back(
8693929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
8703929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
8713929aca1SAnthony Wilson     }
8723929aca1SAnthony Wilson     else if (sensorType != "power")
873de629b6eSShawn McCarney     {
87408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8753929aca1SAnthony Wilson                                 "WarningHigh",
8763929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
87708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8783929aca1SAnthony Wilson                                 "WarningLow",
8793929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
88008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8813929aca1SAnthony Wilson                                 "CriticalHigh",
8823929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
88308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8843929aca1SAnthony Wilson                                 "CriticalLow",
8853929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
886de629b6eSShawn McCarney     }
88708777fb0SLewanczyk, Dawid 
8882474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
8892474adfaSEd Tanous 
8901d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
89195a3ecadSAnthony Wilson     {
89295a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
8933929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
89495a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
8953929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
89651c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
89751c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
89895a3ecadSAnthony Wilson     }
89995a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9001abe55efSEd Tanous     {
90108777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9023929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
90308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9043929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9051abe55efSEd Tanous     }
906adc4f0dbSShawn McCarney     else if (sensorType != "power")
9071abe55efSEd Tanous     {
90808777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9093929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
91008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9113929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
91208777fb0SLewanczyk, Dawid     }
91308777fb0SLewanczyk, Dawid 
9143929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9153929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9161abe55efSEd Tanous     {
9171d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
918711ac7a9SEd Tanous         {
919711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
920711ac7a9SEd Tanous             {
921711ac7a9SEd Tanous                 continue;
922711ac7a9SEd Tanous             }
9233929aca1SAnthony Wilson 
9243929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9253929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9263929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9273929aca1SAnthony Wilson 
928abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
92940e4f380SEd Tanous             if (doubleValue == nullptr)
9301abe55efSEd Tanous             {
93162598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9326f6d0d32SEd Tanous                 continue;
93308777fb0SLewanczyk, Dawid             }
934283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
935283860f5SEd Tanous             {
936283860f5SEd Tanous                 if (valueName == "Value")
937283860f5SEd Tanous                 {
938283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
939283860f5SEd Tanous                     // them to null in the json response.
940283860f5SEd Tanous                     sensorJson[key] = nullptr;
941283860f5SEd Tanous                     continue;
942283860f5SEd Tanous                 }
94362598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
94462598e31SEd Tanous                                    valueName, *doubleValue);
945283860f5SEd Tanous                 continue;
946283860f5SEd Tanous             }
9476f6d0d32SEd Tanous             if (forceToInt)
9486f6d0d32SEd Tanous             {
94940e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9506f6d0d32SEd Tanous             }
9516f6d0d32SEd Tanous             else
9526f6d0d32SEd Tanous             {
95340e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
95408777fb0SLewanczyk, Dawid             }
95508777fb0SLewanczyk, Dawid         }
95608777fb0SLewanczyk, Dawid     }
95708777fb0SLewanczyk, Dawid }
95808777fb0SLewanczyk, Dawid 
9591d7c0054SEd Tanous /**
9601d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9611d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9621d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9631d7c0054SEd Tanous  * build
9641d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
9651d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9661d7c0054SEd Tanous  * interfaces to be built from
9671d7c0054SEd Tanous  * @param sensorJson  The json object to fill
9681d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
9691d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
9701d7c0054SEd Tanous  */
9711d7c0054SEd Tanous inline void objectInterfacesToJson(
9721d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
9731d7c0054SEd Tanous     const std::string& chassisSubNode,
97480f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
9751d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
9761d7c0054SEd Tanous {
9771d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
9781d7c0054SEd Tanous     {
9791d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
9801d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
9811d7c0054SEd Tanous     }
98262598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
9831d7c0054SEd Tanous }
9841d7c0054SEd Tanous 
985b5a76932SEd Tanous inline void populateFanRedundancy(
986b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
9878bd25ccdSJames Feist {
988e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
989e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
990e99073f5SGeorge Liu     dbus::utility::getSubTree(
991e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
992b9d36b47SEd Tanous         [sensorsAsyncResp](
993e99073f5SGeorge Liu             const boost::system::error_code& ec,
994b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
9958bd25ccdSJames Feist         if (ec)
9968bd25ccdSJames Feist         {
9978bd25ccdSJames Feist             return; // don't have to have this interface
9988bd25ccdSJames Feist         }
9996c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
1000e278c18fSEd Tanous                  pathPair : resp)
10018bd25ccdSJames Feist         {
1002e278c18fSEd Tanous             const std::string& path = pathPair.first;
10036c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
10048bd25ccdSJames Feist             if (objDict.empty())
10058bd25ccdSJames Feist             {
10068bd25ccdSJames Feist                 continue; // this should be impossible
10078bd25ccdSJames Feist             }
10088bd25ccdSJames Feist 
10098bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10106c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
10116c3e9451SGeorge Liu                 path + "/chassis",
10126c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
10138b24275dSEd Tanous                     const boost::system::error_code& ec2,
10146c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
10158b24275dSEd Tanous                 if (ec2)
10168bd25ccdSJames Feist                 {
10178bd25ccdSJames Feist                     return; // if they don't have an association we
10188bd25ccdSJames Feist                             // can't tell what chassis is
10198bd25ccdSJames Feist                 }
10203544d2a7SEd Tanous                 auto found = std::ranges::find_if(
10213544d2a7SEd Tanous                     endpoints, [sensorsAsyncResp](const std::string& entry) {
1022002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10238bd25ccdSJames Feist                            std::string::npos;
10248bd25ccdSJames Feist                 });
10258bd25ccdSJames Feist 
10261e1e598dSJonathan Doman                 if (found == endpoints.end())
10278bd25ccdSJames Feist                 {
10288bd25ccdSJames Feist                     return;
10298bd25ccdSJames Feist                 }
103086d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
103186d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
103286d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10338bd25ccdSJames Feist                     [path, sensorsAsyncResp](
10348b24275dSEd Tanous                         const boost::system::error_code& ec3,
103586d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
10368b24275dSEd Tanous                     if (ec3)
10378bd25ccdSJames Feist                     {
10388bd25ccdSJames Feist                         return; // don't have to have this
10398bd25ccdSJames Feist                                 // interface
10408bd25ccdSJames Feist                     }
10418bd25ccdSJames Feist 
104286d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
104386d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
104486d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
104586d89ed7SKrzysztof Grobelny 
104686d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
104786d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
104886d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
104986d89ed7SKrzysztof Grobelny                         collection, "Status", status);
105086d89ed7SKrzysztof Grobelny 
105186d89ed7SKrzysztof Grobelny                     if (!success)
105286d89ed7SKrzysztof Grobelny                     {
105386d89ed7SKrzysztof Grobelny                         messages::internalError(
105486d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
105586d89ed7SKrzysztof Grobelny                         return;
105686d89ed7SKrzysztof Grobelny                     }
105786d89ed7SKrzysztof Grobelny 
105886d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
105986d89ed7SKrzysztof Grobelny                         status == nullptr)
10608bd25ccdSJames Feist                     {
106162598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid redundancy interface");
10628bd25ccdSJames Feist                         messages::internalError(
10638d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10648bd25ccdSJames Feist                         return;
10658bd25ccdSJames Feist                     }
10668bd25ccdSJames Feist 
1067002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
106828aa8de5SGeorge Liu                     std::string name = objectPath.filename();
106928aa8de5SGeorge Liu                     if (name.empty())
10708bd25ccdSJames Feist                     {
10718bd25ccdSJames Feist                         // this should be impossible
10728bd25ccdSJames Feist                         messages::internalError(
10738d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10748bd25ccdSJames Feist                         return;
10758bd25ccdSJames Feist                     }
1076002d39b4SEd Tanous                     std::replace(name.begin(), name.end(), '_', ' ');
10778bd25ccdSJames Feist 
10788bd25ccdSJames Feist                     std::string health;
10798bd25ccdSJames Feist 
108011ba3979SEd Tanous                     if (status->ends_with("Full"))
10818bd25ccdSJames Feist                     {
10828bd25ccdSJames Feist                         health = "OK";
10838bd25ccdSJames Feist                     }
108411ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
10858bd25ccdSJames Feist                     {
10868bd25ccdSJames Feist                         health = "Warning";
10878bd25ccdSJames Feist                     }
10888bd25ccdSJames Feist                     else
10898bd25ccdSJames Feist                     {
10908bd25ccdSJames Feist                         health = "Critical";
10918bd25ccdSJames Feist                     }
10921476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
10938bd25ccdSJames Feist                     const auto& fanRedfish =
1094002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
10958bd25ccdSJames Feist                     for (const std::string& item : *collection)
10968bd25ccdSJames Feist                     {
10978a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
10988a592810SEd Tanous                         std::string itemName = itemPath.filename();
109928aa8de5SGeorge Liu                         if (itemName.empty())
110028aa8de5SGeorge Liu                         {
110128aa8de5SGeorge Liu                             continue;
110228aa8de5SGeorge Liu                         }
11038bd25ccdSJames Feist                         /*
11048bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11058bd25ccdSJames Feist                         std::replace(itemName.begin(),
11068bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
11073544d2a7SEd Tanous                         auto schemaItem = std::ranges::find_if(
11083544d2a7SEd Tanous                             fanRedfish, [itemName](const nlohmann::json& fan) {
11093e35c761SGeorge Liu                             return fan["Name"] == itemName;
11108bd25ccdSJames Feist                         });
11118bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11128bd25ccdSJames Feist                         {
11138a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11148a592810SEd Tanous                             collectionId["@odata.id"] =
11151476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11161476687dSEd Tanous                             redfishCollection.emplace_back(
11178a592810SEd Tanous                                 std::move(collectionId));
11188bd25ccdSJames Feist                         }
11198bd25ccdSJames Feist                         else
11208bd25ccdSJames Feist                         {
112162598e31SEd Tanous                             BMCWEB_LOG_ERROR("failed to find fan in schema");
11228bd25ccdSJames Feist                             messages::internalError(
11238d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11248bd25ccdSJames Feist                             return;
11258bd25ccdSJames Feist                         }
11268bd25ccdSJames Feist                     }
11278bd25ccdSJames Feist 
112889492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
112926f6976fSEd Tanous                                               ? 0
113089492a15SPatrick Williams                                               : collection->size() -
113189492a15SPatrick Williams                                                     *allowedFailures;
1132002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11338bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11341476687dSEd Tanous 
11351476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1136ef4c65b7SEd Tanous                     boost::urls::url url =
1137ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1138ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1139eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1140eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1141eddfc437SWilly Tu                                          .to_string());
1142eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1143002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11441476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11451476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11461476687dSEd Tanous                     redundancy["Name"] = name;
11471476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11481476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11491476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11501476687dSEd Tanous 
1151b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
115286d89ed7SKrzysztof Grobelny                 });
11531e1e598dSJonathan Doman             });
11548bd25ccdSJames Feist         }
1155e99073f5SGeorge Liu     });
11568bd25ccdSJames Feist }
11578bd25ccdSJames Feist 
1158b5a76932SEd Tanous inline void
115981ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
116049c53ac9SJohnathan Mantey {
11618d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
116249c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
116381ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
116449c53ac9SJohnathan Mantey     {
116549c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
116649c53ac9SJohnathan Mantey     }
116749c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
116849c53ac9SJohnathan Mantey     {
116949c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
117049c53ac9SJohnathan Mantey         if (entry != response.end())
117149c53ac9SJohnathan Mantey         {
117249c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
117302cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
117449c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
117549c53ac9SJohnathan Mantey             });
117649c53ac9SJohnathan Mantey 
117749c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
117849c53ac9SJohnathan Mantey             size_t count = 0;
117949c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
118049c53ac9SJohnathan Mantey             {
118149c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
118249c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
118349c53ac9SJohnathan Mantey                 {
118449c53ac9SJohnathan Mantey                     continue;
118549c53ac9SJohnathan Mantey                 }
118649c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
118749c53ac9SJohnathan Mantey                 if (value != nullptr)
118849c53ac9SJohnathan Mantey                 {
1189eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
11903e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
119149c53ac9SJohnathan Mantey                     count++;
119281ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
119349c53ac9SJohnathan Mantey                 }
119449c53ac9SJohnathan Mantey             }
119549c53ac9SJohnathan Mantey         }
119649c53ac9SJohnathan Mantey     }
119749c53ac9SJohnathan Mantey }
119849c53ac9SJohnathan Mantey 
119908777fb0SLewanczyk, Dawid /**
1200adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1201adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1202adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1203adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12048fb49dd6SShawn McCarney  */
120523a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1206b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1207adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12088fb49dd6SShawn McCarney {
1209adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12108fb49dd6SShawn McCarney     {
1211adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12128fb49dd6SShawn McCarney         {
1213adc4f0dbSShawn McCarney             return &inventoryItem;
12148fb49dd6SShawn McCarney         }
12158fb49dd6SShawn McCarney     }
12168fb49dd6SShawn McCarney     return nullptr;
12178fb49dd6SShawn McCarney }
12188fb49dd6SShawn McCarney 
12198fb49dd6SShawn McCarney /**
1220adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1221adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1222adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1223adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12248fb49dd6SShawn McCarney  */
122523a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1226b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1227adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1228adc4f0dbSShawn McCarney {
1229adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1230adc4f0dbSShawn McCarney     {
1231db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1232adc4f0dbSShawn McCarney         {
1233adc4f0dbSShawn McCarney             return &inventoryItem;
1234adc4f0dbSShawn McCarney         }
1235adc4f0dbSShawn McCarney     }
1236adc4f0dbSShawn McCarney     return nullptr;
1237adc4f0dbSShawn McCarney }
1238adc4f0dbSShawn McCarney 
1239adc4f0dbSShawn McCarney /**
1240d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1241d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1242d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1243d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1244d500549bSAnthony Wilson  */
1245d500549bSAnthony Wilson inline InventoryItem*
1246d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1247d500549bSAnthony Wilson                             const std::string& ledObjPath)
1248d500549bSAnthony Wilson {
1249d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1250d500549bSAnthony Wilson     {
1251d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1252d500549bSAnthony Wilson         {
1253d500549bSAnthony Wilson             return &inventoryItem;
1254d500549bSAnthony Wilson         }
1255d500549bSAnthony Wilson     }
1256d500549bSAnthony Wilson     return nullptr;
1257d500549bSAnthony Wilson }
1258d500549bSAnthony Wilson 
1259d500549bSAnthony Wilson /**
1260adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1261adc4f0dbSShawn McCarney  *
1262adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1263adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1264adc4f0dbSShawn McCarney  * added to the vector.
1265adc4f0dbSShawn McCarney  *
1266adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1267adc4f0dbSShawn McCarney  * InventoryItem.
1268adc4f0dbSShawn McCarney  *
1269adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1270adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1271adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1272adc4f0dbSShawn McCarney  */
1273b5a76932SEd Tanous inline void addInventoryItem(
1274b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1275b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1276adc4f0dbSShawn McCarney {
1277adc4f0dbSShawn McCarney     // Look for inventory item in vector
127889492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
127989492a15SPatrick Williams                                                      invItemObjPath);
1280adc4f0dbSShawn McCarney 
1281adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1282adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1283adc4f0dbSShawn McCarney     {
1284adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1285adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1286adc4f0dbSShawn McCarney     }
1287adc4f0dbSShawn McCarney 
1288adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1289adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1290adc4f0dbSShawn McCarney }
1291adc4f0dbSShawn McCarney 
1292adc4f0dbSShawn McCarney /**
1293adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1294adc4f0dbSShawn McCarney  *
1295adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1296adc4f0dbSShawn McCarney  * specified InventoryItem.
1297adc4f0dbSShawn McCarney  *
1298adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1299adc4f0dbSShawn McCarney  * response.
1300adc4f0dbSShawn McCarney  *
1301adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1302adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1303adc4f0dbSShawn McCarney  * for the specified inventory item.
1304adc4f0dbSShawn McCarney  */
130523a21a1cSEd Tanous inline void storeInventoryItemData(
1306adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
130780f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13088fb49dd6SShawn McCarney {
1309adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1310711ac7a9SEd Tanous 
13119eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13128fb49dd6SShawn McCarney     {
1313711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13148fb49dd6SShawn McCarney         {
13159eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1316711ac7a9SEd Tanous             {
1317711ac7a9SEd Tanous                 if (name == "Present")
1318711ac7a9SEd Tanous                 {
1319711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1320adc4f0dbSShawn McCarney                     if (value != nullptr)
13218fb49dd6SShawn McCarney                     {
1322adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13238fb49dd6SShawn McCarney                     }
13248fb49dd6SShawn McCarney                 }
13258fb49dd6SShawn McCarney             }
1326711ac7a9SEd Tanous         }
1327adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1328711ac7a9SEd Tanous 
1329711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13308fb49dd6SShawn McCarney         {
1331adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13328fb49dd6SShawn McCarney         }
1333adc4f0dbSShawn McCarney 
1334adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1335711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1336adc4f0dbSShawn McCarney         {
13379eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1338711ac7a9SEd Tanous             {
1339711ac7a9SEd Tanous                 if (name == "Manufacturer")
1340adc4f0dbSShawn McCarney                 {
1341adc4f0dbSShawn McCarney                     const std::string* value =
1342711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1343adc4f0dbSShawn McCarney                     if (value != nullptr)
1344adc4f0dbSShawn McCarney                     {
1345adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1346adc4f0dbSShawn McCarney                     }
1347adc4f0dbSShawn McCarney                 }
1348711ac7a9SEd Tanous                 if (name == "Model")
1349adc4f0dbSShawn McCarney                 {
1350adc4f0dbSShawn McCarney                     const std::string* value =
1351711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1352adc4f0dbSShawn McCarney                     if (value != nullptr)
1353adc4f0dbSShawn McCarney                     {
1354adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1355adc4f0dbSShawn McCarney                     }
1356adc4f0dbSShawn McCarney                 }
1357711ac7a9SEd Tanous                 if (name == "SerialNumber")
1358adc4f0dbSShawn McCarney                 {
1359adc4f0dbSShawn McCarney                     const std::string* value =
1360711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1361adc4f0dbSShawn McCarney                     if (value != nullptr)
1362adc4f0dbSShawn McCarney                     {
1363adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1364adc4f0dbSShawn McCarney                     }
1365adc4f0dbSShawn McCarney                 }
1366711ac7a9SEd Tanous                 if (name == "PartNumber")
1367711ac7a9SEd Tanous                 {
1368711ac7a9SEd Tanous                     const std::string* value =
1369711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1370711ac7a9SEd Tanous                     if (value != nullptr)
1371711ac7a9SEd Tanous                     {
1372711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1373711ac7a9SEd Tanous                     }
1374711ac7a9SEd Tanous                 }
1375711ac7a9SEd Tanous             }
1376adc4f0dbSShawn McCarney         }
1377adc4f0dbSShawn McCarney 
1378711ac7a9SEd Tanous         if (interface ==
1379711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1380adc4f0dbSShawn McCarney         {
13819eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1382adc4f0dbSShawn McCarney             {
1383711ac7a9SEd Tanous                 if (name == "Functional")
1384711ac7a9SEd Tanous                 {
1385711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1386adc4f0dbSShawn McCarney                     if (value != nullptr)
1387adc4f0dbSShawn McCarney                     {
1388adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
13898fb49dd6SShawn McCarney                     }
13908fb49dd6SShawn McCarney                 }
13918fb49dd6SShawn McCarney             }
13928fb49dd6SShawn McCarney         }
1393711ac7a9SEd Tanous     }
1394711ac7a9SEd Tanous }
13958fb49dd6SShawn McCarney 
13968fb49dd6SShawn McCarney /**
1397adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
13988fb49dd6SShawn McCarney  *
1399adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1400adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1401adc4f0dbSShawn McCarney  * inventoryItems vector.
14028fb49dd6SShawn McCarney  *
1403adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1404adc4f0dbSShawn McCarney  * response.
1405adc4f0dbSShawn McCarney  *
1406adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1407adc4f0dbSShawn McCarney  * been obtained.
1408adc4f0dbSShawn McCarney  *
1409adc4f0dbSShawn McCarney  * The callback must have the following signature:
1410adc4f0dbSShawn McCarney  *   @code
1411d500549bSAnthony Wilson  *   callback(void)
1412adc4f0dbSShawn McCarney  *   @endcode
1413adc4f0dbSShawn McCarney  *
1414adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1415adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1416adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14178fb49dd6SShawn McCarney  *
14188fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1419adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1420adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14218fb49dd6SShawn McCarney  * implements ObjectManager.
1422adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1423adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1424adc4f0dbSShawn McCarney  * in recursive calls to this function.
14258fb49dd6SShawn McCarney  */
1426adc4f0dbSShawn McCarney template <typename Callback>
1427adc4f0dbSShawn McCarney static void getInventoryItemsData(
14288fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1429adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1430d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1431d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14328fb49dd6SShawn McCarney {
143362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14348fb49dd6SShawn McCarney 
1435adc4f0dbSShawn McCarney     // If no more connections left, call callback
1436adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14378fb49dd6SShawn McCarney     {
1438d500549bSAnthony Wilson         callback();
143962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1440adc4f0dbSShawn McCarney         return;
1441adc4f0dbSShawn McCarney     }
1442adc4f0dbSShawn McCarney 
1443adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1444fe04d49cSNan Zhou     auto it = invConnections->begin();
1445fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1446adc4f0dbSShawn McCarney     if (it != invConnections->end())
1447adc4f0dbSShawn McCarney     {
1448adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1449adc4f0dbSShawn McCarney 
14505eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14515eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14525eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14535eb468daSGeorge Liu             invConnection, path,
14545eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
14555eb468daSGeorge Liu              callback{std::forward<Callback>(callback)}, invConnectionsIndex](
14565e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
145702cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
145862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
14598fb49dd6SShawn McCarney             if (ec)
14608fb49dd6SShawn McCarney             {
146162598e31SEd Tanous                 BMCWEB_LOG_ERROR(
146262598e31SEd Tanous                     "getInventoryItemsData respHandler DBus error {}", ec);
14638d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14648fb49dd6SShawn McCarney                 return;
14658fb49dd6SShawn McCarney             }
14668fb49dd6SShawn McCarney 
14678fb49dd6SShawn McCarney             // Loop through returned object paths
14688fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14698fb49dd6SShawn McCarney             {
14708fb49dd6SShawn McCarney                 const std::string& objPath =
14718fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14728fb49dd6SShawn McCarney 
1473adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
147489492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
147589492a15SPatrick Williams                                                                  objPath);
1476adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
14778fb49dd6SShawn McCarney                 {
1478adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1479adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
14808fb49dd6SShawn McCarney                 }
14818fb49dd6SShawn McCarney             }
14828fb49dd6SShawn McCarney 
1483adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1484adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1485d0090733SEd Tanous                                   invConnections, std::move(callback),
1486d0090733SEd Tanous                                   invConnectionsIndex + 1);
1487adc4f0dbSShawn McCarney 
148862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
14895eb468daSGeorge Liu         });
14908fb49dd6SShawn McCarney     }
14918fb49dd6SShawn McCarney 
149262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
14938fb49dd6SShawn McCarney }
14948fb49dd6SShawn McCarney 
14958fb49dd6SShawn McCarney /**
1496adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
14978fb49dd6SShawn McCarney  *
1498adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1499adc4f0dbSShawn McCarney  * items that are associated with sensors.
15008fb49dd6SShawn McCarney  *
15018fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15028fb49dd6SShawn McCarney  * been obtained.
15038fb49dd6SShawn McCarney  *
15048fb49dd6SShawn McCarney  * The callback must have the following signature:
15058fb49dd6SShawn McCarney  *   @code
1506fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15078fb49dd6SShawn McCarney  *   @endcode
15088fb49dd6SShawn McCarney  *
15098fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1510adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15118fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15128fb49dd6SShawn McCarney  */
15138fb49dd6SShawn McCarney template <typename Callback>
15148fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1515b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1516b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15178fb49dd6SShawn McCarney     Callback&& callback)
15188fb49dd6SShawn McCarney {
151962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15208fb49dd6SShawn McCarney 
15218fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1522e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15238fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1524adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1525adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15268fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15278fb49dd6SShawn McCarney 
1528e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1529e99073f5SGeorge Liu     dbus::utility::getSubTree(
1530e99073f5SGeorge Liu         path, 0, interfaces,
1531002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1532002d39b4SEd Tanous          inventoryItems](
1533e99073f5SGeorge Liu             const boost::system::error_code& ec,
1534002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1535e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
153662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15378fb49dd6SShawn McCarney         if (ec)
15388fb49dd6SShawn McCarney         {
15398d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
154062598e31SEd Tanous             BMCWEB_LOG_ERROR(
154162598e31SEd Tanous                 "getInventoryItemsConnections respHandler DBus error {}", ec);
15428fb49dd6SShawn McCarney             return;
15438fb49dd6SShawn McCarney         }
15448fb49dd6SShawn McCarney 
15458fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1546fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1547fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15488fb49dd6SShawn McCarney 
15498fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15508fb49dd6SShawn McCarney         for (const std::pair<
15518fb49dd6SShawn McCarney                  std::string,
15528fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15538fb49dd6SShawn McCarney                  object : subtree)
15548fb49dd6SShawn McCarney         {
1555adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15568fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1557adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15588fb49dd6SShawn McCarney             {
15598fb49dd6SShawn McCarney                 // Store all connections to inventory item
15608fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15618fb49dd6SShawn McCarney                          objData : object.second)
15628fb49dd6SShawn McCarney                 {
15638fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15648fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15658fb49dd6SShawn McCarney                 }
15668fb49dd6SShawn McCarney             }
15678fb49dd6SShawn McCarney         }
1568d500549bSAnthony Wilson 
15698fb49dd6SShawn McCarney         callback(invConnections);
157062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1571e99073f5SGeorge Liu     });
157262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
15738fb49dd6SShawn McCarney }
15748fb49dd6SShawn McCarney 
15758fb49dd6SShawn McCarney /**
1576adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
15778fb49dd6SShawn McCarney  *
15788fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1579d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1580d500549bSAnthony Wilson  * their LEDs, if any.
15818fb49dd6SShawn McCarney  *
15828fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
15838fb49dd6SShawn McCarney  * has been obtained.
15848fb49dd6SShawn McCarney  *
15858fb49dd6SShawn McCarney  * The callback must have the following signature:
15868fb49dd6SShawn McCarney  *   @code
1587adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
15888fb49dd6SShawn McCarney  *   @endcode
15898fb49dd6SShawn McCarney  *
15908fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
15918fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
15928fb49dd6SShawn McCarney  * implements ObjectManager.
15938fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
15948fb49dd6SShawn McCarney  */
15958fb49dd6SShawn McCarney template <typename Callback>
1596adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1597b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1598fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
15998fb49dd6SShawn McCarney     Callback&& callback)
16008fb49dd6SShawn McCarney {
160162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16028fb49dd6SShawn McCarney 
16035eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16045eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16055eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16065eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
160702cad96eSEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
16085e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
160902cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
161062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16118fb49dd6SShawn McCarney         if (ec)
16128fb49dd6SShawn McCarney         {
161362598e31SEd Tanous             BMCWEB_LOG_ERROR(
161462598e31SEd Tanous                 "getInventoryItemAssociations respHandler DBus error {}", ec);
16158d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16168fb49dd6SShawn McCarney             return;
16178fb49dd6SShawn McCarney         }
16188fb49dd6SShawn McCarney 
1619adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1620adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1621adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1622adc4f0dbSShawn McCarney 
16238fb49dd6SShawn McCarney         // Loop through returned object paths
16248fb49dd6SShawn McCarney         std::string sensorAssocPath;
16258fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16268fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16278fb49dd6SShawn McCarney         {
16288fb49dd6SShawn McCarney             const std::string& objPath =
16298fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16308fb49dd6SShawn McCarney 
16318fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16328fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16338fb49dd6SShawn McCarney             {
16348fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16358fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16368fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16378fb49dd6SShawn McCarney                 {
16388fb49dd6SShawn McCarney                     // Get Association interface for object path
1639711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16408fb49dd6SShawn McCarney                     {
1641711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1642711ac7a9SEd Tanous                         {
1643711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1644711ac7a9SEd Tanous                             {
1645711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16468fb49dd6SShawn McCarney                                 {
16478fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16488fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1649711ac7a9SEd Tanous                                             &value);
1650711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1651711ac7a9SEd Tanous                                         !endpoints->empty())
16528fb49dd6SShawn McCarney                                     {
1653adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1654adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1655adc4f0dbSShawn McCarney                                             endpoints->front();
1656711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1657711ac7a9SEd Tanous                                                          invItemPath,
1658adc4f0dbSShawn McCarney                                                          sensorName);
16598fb49dd6SShawn McCarney                                     }
16608fb49dd6SShawn McCarney                                 }
16618fb49dd6SShawn McCarney                             }
1662711ac7a9SEd Tanous                         }
1663711ac7a9SEd Tanous                     }
16648fb49dd6SShawn McCarney                     break;
16658fb49dd6SShawn McCarney                 }
16668fb49dd6SShawn McCarney             }
16678fb49dd6SShawn McCarney         }
16688fb49dd6SShawn McCarney 
1669d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1670d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1671d500549bSAnthony Wilson         std::string inventoryAssocPath;
1672d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1673d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1674d500549bSAnthony Wilson         {
1675d500549bSAnthony Wilson             const std::string& objPath =
1676d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1677d500549bSAnthony Wilson 
1678d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1679d500549bSAnthony Wilson             {
1680d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1681d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1682d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1683d500549bSAnthony Wilson                 {
1684711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1685d500549bSAnthony Wilson                     {
1686711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1687711ac7a9SEd Tanous                         {
1688711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1689711ac7a9SEd Tanous                             {
1690711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1691d500549bSAnthony Wilson                                 {
1692d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1693d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1694711ac7a9SEd Tanous                                             &value);
1695711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1696711ac7a9SEd Tanous                                         !endpoints->empty())
1697d500549bSAnthony Wilson                                     {
1698711ac7a9SEd Tanous                                         // Add inventory item to vector
1699d500549bSAnthony Wilson                                         // Store LED path in inventory item
1700711ac7a9SEd Tanous                                         const std::string& ledPath =
1701711ac7a9SEd Tanous                                             endpoints->front();
1702d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1703d500549bSAnthony Wilson                                     }
1704d500549bSAnthony Wilson                                 }
1705d500549bSAnthony Wilson                             }
1706711ac7a9SEd Tanous                         }
1707711ac7a9SEd Tanous                     }
1708711ac7a9SEd Tanous 
1709d500549bSAnthony Wilson                     break;
1710d500549bSAnthony Wilson                 }
1711d500549bSAnthony Wilson             }
1712d500549bSAnthony Wilson         }
1713adc4f0dbSShawn McCarney         callback(inventoryItems);
171462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17155eb468daSGeorge Liu     });
17168fb49dd6SShawn McCarney 
171762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17188fb49dd6SShawn McCarney }
17198fb49dd6SShawn McCarney 
17208fb49dd6SShawn McCarney /**
1721d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1722d500549bSAnthony Wilson  *
1723d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1724d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1725d500549bSAnthony Wilson  * inventoryItems vector.
1726d500549bSAnthony Wilson  *
1727d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1728d500549bSAnthony Wilson  * response.
1729d500549bSAnthony Wilson  *
1730d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1731d500549bSAnthony Wilson  * has been obtained.
1732d500549bSAnthony Wilson  *
1733d500549bSAnthony Wilson  * The callback must have the following signature:
1734d500549bSAnthony Wilson  *   @code
173542cbe538SGunnar Mills  *   callback()
1736d500549bSAnthony Wilson  *   @endcode
1737d500549bSAnthony Wilson  *
1738d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1739d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1740d500549bSAnthony Wilson  * last asynchronous function has completed.
1741d500549bSAnthony Wilson  *
1742d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1743d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1744d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1745d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1746d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1747d500549bSAnthony Wilson  * in recursive calls to this function.
1748d500549bSAnthony Wilson  */
1749d500549bSAnthony Wilson template <typename Callback>
1750d500549bSAnthony Wilson void getInventoryLedData(
1751d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1752d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1753fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1754d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1755d500549bSAnthony Wilson {
175662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1757d500549bSAnthony Wilson 
1758d500549bSAnthony Wilson     // If no more connections left, call callback
1759d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1760d500549bSAnthony Wilson     {
176142cbe538SGunnar Mills         callback();
176262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1763d500549bSAnthony Wilson         return;
1764d500549bSAnthony Wilson     }
1765d500549bSAnthony Wilson 
1766d500549bSAnthony Wilson     // Get inventory item data from current connection
1767fe04d49cSNan Zhou     auto it = ledConnections->begin();
1768fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1769d500549bSAnthony Wilson     if (it != ledConnections->end())
1770d500549bSAnthony Wilson     {
1771d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1772d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1773d500549bSAnthony Wilson         // Response handler for Get State property
17741e1e598dSJonathan Doman         auto respHandler =
17751e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1776f94c4ecfSEd Tanous              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
17775e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
177862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1779d500549bSAnthony Wilson             if (ec)
1780d500549bSAnthony Wilson             {
178162598e31SEd Tanous                 BMCWEB_LOG_ERROR(
178262598e31SEd Tanous                     "getInventoryLedData respHandler DBus error {}", ec);
17838d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1784d500549bSAnthony Wilson                 return;
1785d500549bSAnthony Wilson             }
1786d500549bSAnthony Wilson 
178762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Led state: {}", state);
1788d500549bSAnthony Wilson             // Find inventory item with this LED object path
1789d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1790d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1791d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1792d500549bSAnthony Wilson             {
1793d500549bSAnthony Wilson                 // Store LED state in InventoryItem
179411ba3979SEd Tanous                 if (state.ends_with("On"))
1795d500549bSAnthony Wilson                 {
1796d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1797d500549bSAnthony Wilson                 }
179811ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1799d500549bSAnthony Wilson                 {
1800d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1801d500549bSAnthony Wilson                 }
180211ba3979SEd Tanous                 else if (state.ends_with("Off"))
1803d500549bSAnthony Wilson                 {
1804d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1805d500549bSAnthony Wilson                 }
1806d500549bSAnthony Wilson                 else
1807d500549bSAnthony Wilson                 {
1808d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1809d500549bSAnthony Wilson                 }
1810d500549bSAnthony Wilson             }
1811d500549bSAnthony Wilson 
1812d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1813d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1814d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1815d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1816d500549bSAnthony Wilson 
181762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1818d500549bSAnthony Wilson         };
1819d500549bSAnthony Wilson 
1820d500549bSAnthony Wilson         // Get the State property for the current LED
18211e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18221e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18231e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18241e1e598dSJonathan Doman             std::move(respHandler));
1825d500549bSAnthony Wilson     }
1826d500549bSAnthony Wilson 
182762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1828d500549bSAnthony Wilson }
1829d500549bSAnthony Wilson 
1830d500549bSAnthony Wilson /**
1831d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1832d500549bSAnthony Wilson  *
1833d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1834d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1835d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1836d500549bSAnthony Wilson  *
1837d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1838d500549bSAnthony Wilson  * response.
1839d500549bSAnthony Wilson  *
1840d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1841d500549bSAnthony Wilson  * been obtained.
1842d500549bSAnthony Wilson  *
1843d500549bSAnthony Wilson  * The callback must have the following signature:
1844d500549bSAnthony Wilson  *   @code
184542cbe538SGunnar Mills  *   callback()
1846d500549bSAnthony Wilson  *   @endcode
1847d500549bSAnthony Wilson  *
1848d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1849d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1850d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1851d500549bSAnthony Wilson  */
1852d500549bSAnthony Wilson template <typename Callback>
1853d500549bSAnthony Wilson void getInventoryLeds(
1854d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1855d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1856d500549bSAnthony Wilson     Callback&& callback)
1857d500549bSAnthony Wilson {
185862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1859d500549bSAnthony Wilson 
1860d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1861e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1862d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1863d500549bSAnthony Wilson 
1864e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1865e99073f5SGeorge Liu     dbus::utility::getSubTree(
1866e99073f5SGeorge Liu         path, 0, interfaces,
1867002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1868002d39b4SEd Tanous          inventoryItems](
1869e99073f5SGeorge Liu             const boost::system::error_code& ec,
1870002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1871e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
187262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1873d500549bSAnthony Wilson         if (ec)
1874d500549bSAnthony Wilson         {
18758d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
187662598e31SEd Tanous             BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}", ec);
1877d500549bSAnthony Wilson             return;
1878d500549bSAnthony Wilson         }
1879d500549bSAnthony Wilson 
1880d500549bSAnthony Wilson         // Build map of LED object paths to connections
1881fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1882fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1883d500549bSAnthony Wilson 
1884d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1885d500549bSAnthony Wilson         for (const std::pair<
1886d500549bSAnthony Wilson                  std::string,
1887d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1888d500549bSAnthony Wilson                  object : subtree)
1889d500549bSAnthony Wilson         {
1890d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1891d500549bSAnthony Wilson             // items
1892d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1893d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1894d500549bSAnthony Wilson             {
1895d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1896d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1897d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
189862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath, connection);
1899d500549bSAnthony Wilson             }
1900d500549bSAnthony Wilson         }
1901d500549bSAnthony Wilson 
1902d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1903d500549bSAnthony Wilson                             std::move(callback));
190462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1905e99073f5SGeorge Liu     });
190662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1907d500549bSAnthony Wilson }
1908d500549bSAnthony Wilson 
1909d500549bSAnthony Wilson /**
191042cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
191142cbe538SGunnar Mills  *
191242cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
191342cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
191442cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
191542cbe538SGunnar Mills  *
191642cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
191742cbe538SGunnar Mills  * response.
191842cbe538SGunnar Mills  *
191942cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
192042cbe538SGunnar Mills  * when data has been obtained.
192142cbe538SGunnar Mills  *
192242cbe538SGunnar Mills  * The callback must have the following signature:
192342cbe538SGunnar Mills  *   @code
192442cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
192542cbe538SGunnar Mills  *   @endcode
192642cbe538SGunnar Mills  *
192742cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
192842cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
192942cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
193042cbe538SGunnar Mills  *        Supply Attributes
193142cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
193242cbe538SGunnar Mills  */
193342cbe538SGunnar Mills template <typename Callback>
193442cbe538SGunnar Mills void getPowerSupplyAttributesData(
1935b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
193642cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1937fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
193842cbe538SGunnar Mills     Callback&& callback)
193942cbe538SGunnar Mills {
194062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
194142cbe538SGunnar Mills 
194242cbe538SGunnar Mills     if (psAttributesConnections.empty())
194342cbe538SGunnar Mills     {
194462598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
194542cbe538SGunnar Mills         callback(inventoryItems);
194642cbe538SGunnar Mills         return;
194742cbe538SGunnar Mills     }
194842cbe538SGunnar Mills 
194942cbe538SGunnar Mills     // Assuming just one connection (service) for now
1950fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
195142cbe538SGunnar Mills 
195242cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
195342cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
195442cbe538SGunnar Mills 
195542cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
19565a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
1957f94c4ecfSEd Tanous                         callback{std::forward<Callback>(callback)}](
19585a39f77aSPatrick Williams                            const boost::system::error_code& ec,
19595a39f77aSPatrick Williams                            const uint32_t value) {
196062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
196142cbe538SGunnar Mills         if (ec)
196242cbe538SGunnar Mills         {
196362598e31SEd Tanous             BMCWEB_LOG_ERROR(
196462598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
19658d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
196642cbe538SGunnar Mills             return;
196742cbe538SGunnar Mills         }
196842cbe538SGunnar Mills 
196962598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
197042cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
197142cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
197242cbe538SGunnar Mills         {
197355f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
197442cbe538SGunnar Mills             {
197542cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19761e1e598dSJonathan Doman                     static_cast<int>(value);
197742cbe538SGunnar Mills             }
197842cbe538SGunnar Mills         }
197942cbe538SGunnar Mills 
198062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
198142cbe538SGunnar Mills         callback(inventoryItems);
198242cbe538SGunnar Mills     };
198342cbe538SGunnar Mills 
198442cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
198542cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
19861e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
19871e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
19881e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
19891e1e598dSJonathan Doman         std::move(respHandler));
199042cbe538SGunnar Mills 
199162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
199242cbe538SGunnar Mills }
199342cbe538SGunnar Mills 
199442cbe538SGunnar Mills /**
199542cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
199642cbe538SGunnar Mills  *
199742cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
199842cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
199942cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
200042cbe538SGunnar Mills  * item.
200142cbe538SGunnar Mills  *
200242cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
200342cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
200442cbe538SGunnar Mills  *
200542cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
200642cbe538SGunnar Mills  * when information has been obtained.
200742cbe538SGunnar Mills  *
200842cbe538SGunnar Mills  * The callback must have the following signature:
200942cbe538SGunnar Mills  *   @code
201042cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
201142cbe538SGunnar Mills  *   @endcode
201242cbe538SGunnar Mills  *
201342cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
201442cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
201542cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
201642cbe538SGunnar Mills  */
201742cbe538SGunnar Mills template <typename Callback>
201842cbe538SGunnar Mills void getPowerSupplyAttributes(
201942cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
202042cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
202142cbe538SGunnar Mills     Callback&& callback)
202242cbe538SGunnar Mills {
202362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
202442cbe538SGunnar Mills 
202542cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2026a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
202742cbe538SGunnar Mills     {
202862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
202942cbe538SGunnar Mills         callback(inventoryItems);
203042cbe538SGunnar Mills         return;
203142cbe538SGunnar Mills     }
203242cbe538SGunnar Mills 
2033e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
203442cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
203542cbe538SGunnar Mills 
2036e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2037e99073f5SGeorge Liu     dbus::utility::getSubTree(
2038e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
2039b9d36b47SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2040b9d36b47SEd Tanous          inventoryItems](
2041e99073f5SGeorge Liu             const boost::system::error_code& ec,
2042b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2043e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
204462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
204542cbe538SGunnar Mills         if (ec)
204642cbe538SGunnar Mills         {
20478d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
204862598e31SEd Tanous             BMCWEB_LOG_ERROR(
204962598e31SEd Tanous                 "getPowerSupplyAttributes respHandler DBus error {}", ec);
205042cbe538SGunnar Mills             return;
205142cbe538SGunnar Mills         }
205226f6976fSEd Tanous         if (subtree.empty())
205342cbe538SGunnar Mills         {
205462598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
205542cbe538SGunnar Mills             callback(inventoryItems);
205642cbe538SGunnar Mills             return;
205742cbe538SGunnar Mills         }
205842cbe538SGunnar Mills 
205942cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
206042cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
206142cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2062fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
206342cbe538SGunnar Mills 
206442cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
206542cbe538SGunnar Mills         {
206662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
206742cbe538SGunnar Mills             callback(inventoryItems);
206842cbe538SGunnar Mills             return;
206942cbe538SGunnar Mills         }
207042cbe538SGunnar Mills 
207142cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
207242cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
207342cbe538SGunnar Mills 
207442cbe538SGunnar Mills         if (connection.empty())
207542cbe538SGunnar Mills         {
207662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
207742cbe538SGunnar Mills             callback(inventoryItems);
207842cbe538SGunnar Mills             return;
207942cbe538SGunnar Mills         }
208042cbe538SGunnar Mills 
208142cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
208262598e31SEd Tanous         BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
208362598e31SEd Tanous                          connection);
208442cbe538SGunnar Mills 
208542cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
208642cbe538SGunnar Mills                                      psAttributesConnections,
208742cbe538SGunnar Mills                                      std::move(callback));
208862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2089e99073f5SGeorge Liu     });
209062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
209142cbe538SGunnar Mills }
209242cbe538SGunnar Mills 
209342cbe538SGunnar Mills /**
2094adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
20958fb49dd6SShawn McCarney  *
20968fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2097adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
20988fb49dd6SShawn McCarney  *
2099adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2100adc4f0dbSShawn McCarney  * response.
21018fb49dd6SShawn McCarney  *
2102adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2103adc4f0dbSShawn McCarney  * inventory items have been obtained.
2104adc4f0dbSShawn McCarney  *
2105adc4f0dbSShawn McCarney  * The callback must have the following signature:
2106adc4f0dbSShawn McCarney  *   @code
2107adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2108adc4f0dbSShawn McCarney  *   @endcode
21098fb49dd6SShawn McCarney  *
21108fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21118fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21128fb49dd6SShawn McCarney  * implements ObjectManager.
2113adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21148fb49dd6SShawn McCarney  */
2115adc4f0dbSShawn McCarney template <typename Callback>
2116d0090733SEd Tanous static void
2117d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2118fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2119adc4f0dbSShawn McCarney                       Callback&& callback)
21208fb49dd6SShawn McCarney {
212162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2122adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2123d0090733SEd Tanous         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2124adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
212562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21268fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2127d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2128f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
2129fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
213062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2131002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2132d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
213362598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
213442cbe538SGunnar Mills 
2135002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2136002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
213762598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb enter");
213842cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2139002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
214042cbe538SGunnar Mills                                              std::move(callback));
214162598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
214242cbe538SGunnar Mills                 };
214342cbe538SGunnar Mills 
2144d500549bSAnthony Wilson                 // Find led connections and get the data
2145d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
214642cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
214762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2148d500549bSAnthony Wilson             };
21498fb49dd6SShawn McCarney 
2150adc4f0dbSShawn McCarney             // Get inventory item data from connections
2151adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2152d0090733SEd Tanous                                   invConnections,
2153d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
215462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
21558fb49dd6SShawn McCarney         };
21568fb49dd6SShawn McCarney 
2157adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2158002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21598fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
216062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
21618fb49dd6SShawn McCarney     };
21628fb49dd6SShawn McCarney 
2163adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2164d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2165adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
216662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2167adc4f0dbSShawn McCarney }
2168adc4f0dbSShawn McCarney 
2169adc4f0dbSShawn McCarney /**
2170adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2171adc4f0dbSShawn McCarney  *
2172adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2173adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2174adc4f0dbSShawn McCarney  * array.
2175adc4f0dbSShawn McCarney  *
2176adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2177adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2178adc4f0dbSShawn McCarney  * object.
2179adc4f0dbSShawn McCarney  *
2180adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2181adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2182adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2183adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2184adc4f0dbSShawn McCarney  */
218523a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2186adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2187adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2188adc4f0dbSShawn McCarney {
2189adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2190adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2191adc4f0dbSShawn McCarney     {
2192f7afb17bSAlexander Hansen         if (powerSupply["Name"] ==
2193f7afb17bSAlexander Hansen             boost::replace_all_copy(inventoryItem.name, "_", " "))
2194adc4f0dbSShawn McCarney         {
2195adc4f0dbSShawn McCarney             return powerSupply;
2196adc4f0dbSShawn McCarney         }
2197adc4f0dbSShawn McCarney     }
2198adc4f0dbSShawn McCarney 
2199adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2200adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2201adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2202ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2203ef4c65b7SEd Tanous                                                chassisId);
2204eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2205eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
2206adc4f0dbSShawn McCarney     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2207adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2208adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2209adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2210adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2211d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2212adc4f0dbSShawn McCarney 
221342cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
221442cbe538SGunnar Mills     {
221542cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
221642cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
221742cbe538SGunnar Mills     }
221842cbe538SGunnar Mills 
221942cbe538SGunnar Mills     powerSupply["Status"]["State"] = getState(&inventoryItem);
2220adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2221adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2222adc4f0dbSShawn McCarney 
2223adc4f0dbSShawn McCarney     return powerSupply;
22248fb49dd6SShawn McCarney }
22258fb49dd6SShawn McCarney 
22268fb49dd6SShawn McCarney /**
2227de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2228de629b6eSShawn McCarney  *
2229de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2230de629b6eSShawn McCarney  *
2231de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2232de629b6eSShawn McCarney  * information has been obtained.
2233de629b6eSShawn McCarney  *
2234adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2235de629b6eSShawn McCarney  *
2236de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2237de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2238de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2239de629b6eSShawn McCarney  *
2240de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2241de629b6eSShawn McCarney  *
2242adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2243adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2244adc4f0dbSShawn McCarney  *
2245de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2246adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2247de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2248de629b6eSShawn McCarney  * implements ObjectManager.
2249adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2250de629b6eSShawn McCarney  */
225123a21a1cSEd Tanous inline void getSensorData(
225281ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2253fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2254fe04d49cSNan Zhou     const std::set<std::string>& connections,
2255b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2256de629b6eSShawn McCarney {
225762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2258de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2259de629b6eSShawn McCarney     for (const std::string& connection : connections)
2260de629b6eSShawn McCarney     {
22615eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
22625eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
22635eb468daSGeorge Liu         dbus::utility::getManagedObjects(
22645eb468daSGeorge Liu             connection, sensorPath,
2265002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
22665e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
226702cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
226862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2269de629b6eSShawn McCarney             if (ec)
2270de629b6eSShawn McCarney             {
227162598e31SEd Tanous                 BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
22728d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2273de629b6eSShawn McCarney                 return;
2274de629b6eSShawn McCarney             }
2275de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2276de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2277de629b6eSShawn McCarney             {
2278de629b6eSShawn McCarney                 const std::string& objPath =
2279de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
228062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
228162598e31SEd Tanous                                  objPath);
2282de629b6eSShawn McCarney 
2283de629b6eSShawn McCarney                 std::vector<std::string> split;
2284de629b6eSShawn McCarney                 // Reserve space for
2285de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2286de629b6eSShawn McCarney                 split.reserve(6);
228750ebd4afSEd Tanous                 // NOLINTNEXTLINE
228850ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2289de629b6eSShawn McCarney                 if (split.size() < 6)
2290de629b6eSShawn McCarney                 {
229162598e31SEd Tanous                     BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
229262598e31SEd Tanous                                      objPath);
2293de629b6eSShawn McCarney                     continue;
2294de629b6eSShawn McCarney                 }
229550ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2296de629b6eSShawn McCarney                 // string at the beginning
2297de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2298de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
229962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
230062598e31SEd Tanous                                  sensorType);
230149c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2302de629b6eSShawn McCarney                 {
230362598e31SEd Tanous                     BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
2304de629b6eSShawn McCarney                     continue;
2305de629b6eSShawn McCarney                 }
2306de629b6eSShawn McCarney 
2307adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2308adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2309adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2310adc4f0dbSShawn McCarney 
231195a3ecadSAnthony Wilson                 const std::string& sensorSchema =
231281ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
231395a3ecadSAnthony Wilson 
231495a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
231595a3ecadSAnthony Wilson 
2316928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2317928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
231895a3ecadSAnthony Wilson                 {
2319c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
23203544d2a7SEd Tanous                     auto remove = std::ranges::remove(sensorTypeEscaped, '_');
23213544d2a7SEd Tanous 
23223544d2a7SEd Tanous                     sensorTypeEscaped.erase(std::ranges::begin(remove),
2323c1d019a6SEd Tanous                                             sensorTypeEscaped.end());
2324c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2325c1d019a6SEd Tanous                     sensorId += "_";
2326c1d019a6SEd Tanous                     sensorId += sensorName;
2327c1d019a6SEd Tanous 
23288d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2329ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2330c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2331ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2332ef4c65b7SEd Tanous                                             sensorId);
23338d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
233495a3ecadSAnthony Wilson                 }
233595a3ecadSAnthony Wilson                 else
233695a3ecadSAnthony Wilson                 {
2337271584abSEd Tanous                     std::string fieldName;
2338928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2339928fefb9SNan Zhou                     {
2340928fefb9SNan Zhou                         fieldName = "Members";
2341928fefb9SNan Zhou                     }
2342928fefb9SNan Zhou                     else if (sensorType == "temperature")
2343de629b6eSShawn McCarney                     {
2344de629b6eSShawn McCarney                         fieldName = "Temperatures";
2345de629b6eSShawn McCarney                     }
2346de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2347de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2348de629b6eSShawn McCarney                     {
2349de629b6eSShawn McCarney                         fieldName = "Fans";
2350de629b6eSShawn McCarney                     }
2351de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2352de629b6eSShawn McCarney                     {
2353de629b6eSShawn McCarney                         fieldName = "Voltages";
2354de629b6eSShawn McCarney                     }
2355de629b6eSShawn McCarney                     else if (sensorType == "power")
2356de629b6eSShawn McCarney                     {
235755f79e6fSEd Tanous                         if (sensorName == "total_power")
2358028f7ebcSEddie James                         {
2359028f7ebcSEddie James                             fieldName = "PowerControl";
2360028f7ebcSEddie James                         }
2361adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2362adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2363028f7ebcSEddie James                         {
2364de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2365de629b6eSShawn McCarney                         }
2366adc4f0dbSShawn McCarney                         else
2367adc4f0dbSShawn McCarney                         {
2368adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2369adc4f0dbSShawn McCarney                             continue;
2370adc4f0dbSShawn McCarney                         }
2371028f7ebcSEddie James                     }
2372de629b6eSShawn McCarney                     else
2373de629b6eSShawn McCarney                     {
237462598e31SEd Tanous                         BMCWEB_LOG_ERROR("Unsure how to handle sensorType {}",
237562598e31SEd Tanous                                          sensorType);
2376de629b6eSShawn McCarney                         continue;
2377de629b6eSShawn McCarney                     }
2378de629b6eSShawn McCarney 
2379de629b6eSShawn McCarney                     nlohmann::json& tempArray =
23808d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2381adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
238249c53ac9SJohnathan Mantey                     {
2383adc4f0dbSShawn McCarney                         if (tempArray.empty())
23847ab06f49SGunnar Mills                         {
238595a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
238695a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
238795a3ecadSAnthony Wilson                             // naming in power.hpp.
23881476687dSEd Tanous                             nlohmann::json::object_t power;
2389ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2390ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2391eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2392eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2393eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2394eddfc437SWilly Tu                                                  .to_string());
2395eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2396b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2397adc4f0dbSShawn McCarney                         }
2398adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2399adc4f0dbSShawn McCarney                     }
2400adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2401adc4f0dbSShawn McCarney                     {
2402adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2403adc4f0dbSShawn McCarney                         {
2404adc4f0dbSShawn McCarney                             sensorJson =
2405adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
240681ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2407adc4f0dbSShawn McCarney                         }
240849c53ac9SJohnathan Mantey                     }
2409928fefb9SNan Zhou                     else if (fieldName == "Members")
2410928fefb9SNan Zhou                     {
2411677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
24123544d2a7SEd Tanous                         auto remove = std::ranges::remove(sensorTypeEscaped,
24133544d2a7SEd Tanous                                                           '_');
24143544d2a7SEd Tanous                         sensorTypeEscaped.erase(std::ranges::begin(remove),
2415677bb756SEd Tanous                                                 sensorTypeEscaped.end());
2416677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2417677bb756SEd Tanous                         sensorId += "_";
2418677bb756SEd Tanous                         sensorId += sensorName;
2419677bb756SEd Tanous 
24201476687dSEd Tanous                         nlohmann::json::object_t member;
2421ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2422ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2423677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2424677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2425b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2426928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2427928fefb9SNan Zhou                     }
242849c53ac9SJohnathan Mantey                     else
242949c53ac9SJohnathan Mantey                     {
24301476687dSEd Tanous                         nlohmann::json::object_t member;
2431ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2432ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2433eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2434eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2435eddfc437SWilly Tu                         url.set_fragment(
2436eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2437eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2438b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2439adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
244049c53ac9SJohnathan Mantey                     }
244195a3ecadSAnthony Wilson                 }
2442de629b6eSShawn McCarney 
2443adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2444adc4f0dbSShawn McCarney                 {
24451d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24461d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24471d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24481d7c0054SEd Tanous                                            inventoryItem);
24491d7c0054SEd Tanous 
24501d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24511d7c0054SEd Tanous                     path += sensorType;
24521d7c0054SEd Tanous                     path += "/";
24531d7c0054SEd Tanous                     path += sensorName;
2454c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2455adc4f0dbSShawn McCarney                 }
2456de629b6eSShawn McCarney             }
245781ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
245849c53ac9SJohnathan Mantey             {
245981ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2460928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2461928fefb9SNan Zhou                         sensors::node::sensors &&
2462928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2463928fefb9SNan Zhou                 {
2464928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2465928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2466928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2467928fefb9SNan Zhou                             .size();
2468928fefb9SNan Zhou                 }
2469928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2470928fefb9SNan Zhou                          sensors::node::thermal)
24718bd25ccdSJames Feist                 {
247281ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
24738bd25ccdSJames Feist                 }
247449c53ac9SJohnathan Mantey             }
247562598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
24765eb468daSGeorge Liu         });
247723a21a1cSEd Tanous     }
247862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData exit");
2479de629b6eSShawn McCarney }
2480de629b6eSShawn McCarney 
2481fe04d49cSNan Zhou inline void
2482fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2483fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
24841abe55efSEd Tanous {
2485fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2486fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
248762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb enter");
2488adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2489d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2490d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2491adc4f0dbSShawn McCarney                               inventoryItems) {
249262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
249349c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2494002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2495d0090733SEd Tanous                           inventoryItems);
249662598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb exit");
2497adc4f0dbSShawn McCarney         };
2498adc4f0dbSShawn McCarney 
2499adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2500d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2501adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2502adc4f0dbSShawn McCarney 
250362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb exit");
250408777fb0SLewanczyk, Dawid     };
2505de629b6eSShawn McCarney 
2506de629b6eSShawn McCarney     // Get set of connections that provide sensor values
250781ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
250895a3ecadSAnthony Wilson }
250995a3ecadSAnthony Wilson 
251095a3ecadSAnthony Wilson /**
251195a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
251295a3ecadSAnthony Wilson  *        chassis.
251395a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
251495a3ecadSAnthony Wilson  */
2515b5a76932SEd Tanous inline void
251681ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
251795a3ecadSAnthony Wilson {
251862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
251995a3ecadSAnthony Wilson     auto getChassisCb =
252081ce609eSEd Tanous         [sensorsAsyncResp](
2521fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
252262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb enter");
252381ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
252462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb exit");
252508777fb0SLewanczyk, Dawid     };
2526928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2527928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2528928fefb9SNan Zhou     {
25298d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25308d1b46d7Szhanghch05             nlohmann::json::array();
2531928fefb9SNan Zhou     }
253226f03899SShawn McCarney     // Get set of sensors in chassis
25337f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25347f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25357f1cc26dSEd Tanous                std::move(getChassisCb));
253662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData exit");
2537271584abSEd Tanous }
253808777fb0SLewanczyk, Dawid 
2539413961deSRichard Marian Thomaiyar /**
254049c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
254149c53ac9SJohnathan Mantey  * the chassis node
254249c53ac9SJohnathan Mantey  *
254349c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
254449c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
254549c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
254649c53ac9SJohnathan Mantey  *                         repeated calls to this function
254749c53ac9SJohnathan Mantey  */
2548fe04d49cSNan Zhou inline bool
2549fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
255002cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2551fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
255249c53ac9SJohnathan Mantey {
2553fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
255449c53ac9SJohnathan Mantey     {
255528aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2556b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
255728aa8de5SGeorge Liu         if (thisSensorName.empty())
255849c53ac9SJohnathan Mantey         {
255949c53ac9SJohnathan Mantey             continue;
256049c53ac9SJohnathan Mantey         }
256149c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
256249c53ac9SJohnathan Mantey         {
256349c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
256449c53ac9SJohnathan Mantey             return true;
256549c53ac9SJohnathan Mantey         }
256649c53ac9SJohnathan Mantey     }
256749c53ac9SJohnathan Mantey     return false;
256849c53ac9SJohnathan Mantey }
256949c53ac9SJohnathan Mantey 
2570c71d6125SEd Tanous inline std::pair<std::string, std::string>
2571c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2572c71d6125SEd Tanous {
2573c71d6125SEd Tanous     size_t index = sensorId.find('_');
2574c71d6125SEd Tanous     if (index == std::string::npos)
2575c71d6125SEd Tanous     {
2576c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2577c71d6125SEd Tanous     }
2578c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2579c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2580c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2581c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2582c71d6125SEd Tanous     {
2583c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2584c71d6125SEd Tanous     }
2585c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2586c71d6125SEd Tanous }
2587c71d6125SEd Tanous 
258849c53ac9SJohnathan Mantey /**
2589413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2590413961deSRichard Marian Thomaiyar  *
25918d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
25924bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2593413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2594413961deSRichard Marian Thomaiyar  */
259523a21a1cSEd Tanous inline void setSensorsOverride(
2596b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
25974bb3dc34SCarol Wang     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2598397fd61fSjayaprakash Mutyala         allCollections)
2599413961deSRichard Marian Thomaiyar {
260062598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
260162598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
2602413961deSRichard Marian Thomaiyar 
2603543f4400SEd Tanous     const char* propertyValueName = nullptr;
2604f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2605413961deSRichard Marian Thomaiyar     std::string memberId;
2606543f4400SEd Tanous     double value = 0.0;
2607f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2608f65af9e8SRichard Marian Thomaiyar     {
2609f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2610f65af9e8SRichard Marian Thomaiyar         {
2611f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2612f65af9e8SRichard Marian Thomaiyar         }
2613f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2614f65af9e8SRichard Marian Thomaiyar         {
2615f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2616f65af9e8SRichard Marian Thomaiyar         }
2617f65af9e8SRichard Marian Thomaiyar         else
2618f65af9e8SRichard Marian Thomaiyar         {
2619f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2620f65af9e8SRichard Marian Thomaiyar         }
2621f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2622f65af9e8SRichard Marian Thomaiyar         {
26238d1b46d7Szhanghch05             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
26248d1b46d7Szhanghch05                                      "MemberId", memberId, propertyValueName,
26258d1b46d7Szhanghch05                                      value))
2626413961deSRichard Marian Thomaiyar             {
2627413961deSRichard Marian Thomaiyar                 return;
2628413961deSRichard Marian Thomaiyar             }
2629f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2630f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2631f65af9e8SRichard Marian Thomaiyar         }
2632f65af9e8SRichard Marian Thomaiyar     }
26334bb3dc34SCarol Wang 
2634002d39b4SEd Tanous     auto getChassisSensorListCb =
2635002d39b4SEd Tanous         [sensorAsyncResp, overrideMap](
2636fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
263749c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
263849c53ac9SJohnathan Mantey         // chassis node
2639fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2640fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2641f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2642413961deSRichard Marian Thomaiyar         {
2643f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2644c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2645c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2646c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2647c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2648f65af9e8SRichard Marian Thomaiyar             {
264962598e31SEd Tanous                 BMCWEB_LOG_INFO("Unable to find memberId {}", item.first);
26508d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2651f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2652413961deSRichard Marian Thomaiyar                 return;
2653413961deSRichard Marian Thomaiyar             }
2654f65af9e8SRichard Marian Thomaiyar         }
2655413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2656002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2657fe04d49cSNan Zhou             [sensorAsyncResp,
2658fe04d49cSNan Zhou              overrideMap](const std::set<std::string>& /*connections*/,
2659002d39b4SEd Tanous                           const std::set<std::pair<std::string, std::string>>&
2660413961deSRichard Marian Thomaiyar                               objectsWithConnection) {
2661f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2662413961deSRichard Marian Thomaiyar             {
266362598e31SEd Tanous                 BMCWEB_LOG_INFO(
266462598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
266562598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
26664f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2667a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2668a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2669413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2670413961deSRichard Marian Thomaiyar                                                : "Voltages",
2671f65af9e8SRichard Marian Thomaiyar                                            "Count");
2672f65af9e8SRichard Marian Thomaiyar                 return;
2673f65af9e8SRichard Marian Thomaiyar             }
2674f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2675f65af9e8SRichard Marian Thomaiyar             {
267628aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
267728aa8de5SGeorge Liu                 std::string sensorName = path.filename();
267828aa8de5SGeorge Liu                 if (sensorName.empty())
2679f65af9e8SRichard Marian Thomaiyar                 {
26804f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2681f65af9e8SRichard Marian Thomaiyar                     return;
2682f65af9e8SRichard Marian Thomaiyar                 }
26833f5eb755SBan Feng                 std::string id = path.parent_path().filename();
26843544d2a7SEd Tanous                 auto remove = std::ranges::remove(id, '_');
26853544d2a7SEd Tanous                 id.erase(std::ranges::begin(remove), id.end());
26863f5eb755SBan Feng                 id += "_";
26873f5eb755SBan Feng                 id += sensorName;
2688f65af9e8SRichard Marian Thomaiyar 
26893f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2690f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2691f65af9e8SRichard Marian Thomaiyar                 {
269262598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
269362598e31SEd Tanous                                     item.first);
26944f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2695413961deSRichard Marian Thomaiyar                     return;
2696413961deSRichard Marian Thomaiyar                 }
26979ae226faSGeorge Liu                 sdbusplus::asio::setProperty(
26989ae226faSGeorge Liu                     *crow::connections::systemBus, item.second, item.first,
26999ae226faSGeorge Liu                     "xyz.openbmc_project.Sensor.Value", "Value",
27009ae226faSGeorge Liu                     iterator->second.first,
27015e7e2dc5SEd Tanous                     [sensorAsyncResp](const boost::system::error_code& ec) {
2702413961deSRichard Marian Thomaiyar                     if (ec)
2703413961deSRichard Marian Thomaiyar                     {
27044f277b54SJayaprakash Mutyala                         if (ec.value() ==
27054f277b54SJayaprakash Mutyala                             boost::system::errc::permission_denied)
27064f277b54SJayaprakash Mutyala                         {
270762598e31SEd Tanous                             BMCWEB_LOG_WARNING(
270862598e31SEd Tanous                                 "Manufacturing mode is not Enabled...can't "
270962598e31SEd Tanous                                 "Override the sensor value. ");
27104f277b54SJayaprakash Mutyala 
27114f277b54SJayaprakash Mutyala                             messages::insufficientPrivilege(
27128d1b46d7Szhanghch05                                 sensorAsyncResp->asyncResp->res);
2713413961deSRichard Marian Thomaiyar                             return;
2714413961deSRichard Marian Thomaiyar                         }
271562598e31SEd Tanous                         BMCWEB_LOG_DEBUG(
271662598e31SEd Tanous                             "setOverrideValueStatus DBUS error: {}", ec);
27174f277b54SJayaprakash Mutyala                         messages::internalError(
27184f277b54SJayaprakash Mutyala                             sensorAsyncResp->asyncResp->res);
27194f277b54SJayaprakash Mutyala                     }
27209ae226faSGeorge Liu                 });
2721f65af9e8SRichard Marian Thomaiyar             }
2722413961deSRichard Marian Thomaiyar         };
2723413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2724413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2725413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2726413961deSRichard Marian Thomaiyar     };
2727413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27287f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27297f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27307f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2731413961deSRichard Marian Thomaiyar }
2732413961deSRichard Marian Thomaiyar 
2733a0ec28b6SAdrian Ambrożewicz /**
2734a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2735a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2736a0ec28b6SAdrian Ambrożewicz  *
2737a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2738a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2739a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2740a0ec28b6SAdrian Ambrożewicz  *
2741a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2742a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2743a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2744a0ec28b6SAdrian Ambrożewicz  */
2745021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2746021d32cfSKrzysztof Grobelny                                  const std::string& node,
2747a0ec28b6SAdrian Ambrożewicz                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2748a0ec28b6SAdrian Ambrożewicz {
274902da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
275002da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
275102da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
275202da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2753a0ec28b6SAdrian Ambrożewicz     {
275462598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
2755*6804b5c8SEd Tanous         std::map<std::string, std::string> noop;
2756*6804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2757a0ec28b6SAdrian Ambrożewicz         return;
2758a0ec28b6SAdrian Ambrożewicz     }
2759d51e072fSKrzysztof Grobelny 
276072374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2761fe04d49cSNan Zhou     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2762a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2763fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2764fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2765fe04d49cSNan Zhou     };
2766a0ec28b6SAdrian Ambrożewicz 
2767a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2768d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2769a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2770a0ec28b6SAdrian Ambrożewicz }
2771a0ec28b6SAdrian Ambrożewicz 
2772bacb2162SNan Zhou namespace sensors
2773bacb2162SNan Zhou {
2774928fefb9SNan Zhou 
2775bacb2162SNan Zhou inline void getChassisCallback(
2776c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2777c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2778fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2779bacb2162SNan Zhou {
278062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2781bacb2162SNan Zhou 
2782c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2783c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2784bacb2162SNan Zhou     {
278562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2786bacb2162SNan Zhou 
2787bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2788bacb2162SNan Zhou         std::string sensorName = path.filename();
2789bacb2162SNan Zhou         if (sensorName.empty())
2790bacb2162SNan Zhou         {
279162598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2792c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2793bacb2162SNan Zhou             return;
2794bacb2162SNan Zhou         }
2795c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2796c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2797c1d019a6SEd Tanous         // type in the URI
27983544d2a7SEd Tanous         auto remove = std::ranges::remove(type, '_');
27993544d2a7SEd Tanous         type.erase(std::ranges::begin(remove), type.end());
2800c1d019a6SEd Tanous 
28011476687dSEd Tanous         nlohmann::json::object_t member;
2802c1d019a6SEd Tanous         std::string id = type;
2803c1d019a6SEd Tanous         id += "_";
2804c1d019a6SEd Tanous         id += sensorName;
2805ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2806ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2807c1d019a6SEd Tanous 
2808b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2809bacb2162SNan Zhou     }
2810bacb2162SNan Zhou 
2811c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
281262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2813bacb2162SNan Zhou }
2814e6bd846dSNan Zhou 
2815ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2816ac106bf6SEd Tanous     App& app, const crow::Request& req,
2817ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2818de167a6fSNan Zhou     const std::string& chassisId)
2819de167a6fSNan Zhou {
2820de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2821de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2822de167a6fSNan Zhou     };
2823de167a6fSNan Zhou     query_param::Query delegatedQuery;
2824ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2825de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2826de167a6fSNan Zhou     {
2827de167a6fSNan Zhou         return;
2828de167a6fSNan Zhou     }
2829de167a6fSNan Zhou 
2830de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2831de167a6fSNan Zhou     {
2832de167a6fSNan Zhou         // we perform efficient expand.
2833ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2834ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2835de167a6fSNan Zhou             sensors::node::sensors,
2836de167a6fSNan Zhou             /*efficientExpand=*/true);
2837ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2838de167a6fSNan Zhou 
283962598e31SEd Tanous         BMCWEB_LOG_DEBUG(
284062598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2841de167a6fSNan Zhou         return;
28420bad320cSEd Tanous     }
2843de167a6fSNan Zhou 
2844de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2845de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2846ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2847ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2848ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2849c1d019a6SEd Tanous }
28507f1cc26dSEd Tanous 
2851c1d019a6SEd Tanous inline void
2852c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2853c1d019a6SEd Tanous                       const std::string& sensorPath,
2854c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2855c1d019a6SEd Tanous {
2856c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2857c1d019a6SEd Tanous     {
2858c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2859c1d019a6SEd Tanous         return;
2860c1d019a6SEd Tanous     }
2861c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2862c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
286362598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
286462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2865c1343bf6SKrzysztof Grobelny 
2866c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2867c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2868c1d019a6SEd Tanous         [asyncResp,
28695e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2870c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2871c1d019a6SEd Tanous         if (ec)
2872c1d019a6SEd Tanous         {
2873c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2874c1d019a6SEd Tanous             return;
2875c1d019a6SEd Tanous         }
2876c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2877c1d019a6SEd Tanous         std::string name = path.filename();
2878c1d019a6SEd Tanous         path = path.parent_path();
2879c1d019a6SEd Tanous         std::string type = path.filename();
2880c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2881c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2882c1343bf6SKrzysztof Grobelny     });
2883de167a6fSNan Zhou }
2884de167a6fSNan Zhou 
2885e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2886c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2887677bb756SEd Tanous                             const std::string& chassisId,
2888c1d019a6SEd Tanous                             const std::string& sensorId)
2889e6bd846dSNan Zhou {
2890c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2891e6bd846dSNan Zhou     {
2892e6bd846dSNan Zhou         return;
2893e6bd846dSNan Zhou     }
2894c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2895c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2896c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2897c1d019a6SEd Tanous     {
2898c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2899c1d019a6SEd Tanous         return;
2900c1d019a6SEd Tanous     }
2901c71d6125SEd Tanous 
2902ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2903ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2904c1d019a6SEd Tanous 
290562598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2906e6bd846dSNan Zhou 
29072b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2908e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2909c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2910c71d6125SEd Tanous                              '/' + nameType.second;
2911e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2912e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29132b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29142b73119cSGeorge Liu         sensorPath, interfaces,
2915aec0ec30SMyung Bae         [asyncResp, sensorId,
29162b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2917c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
291862598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 enter");
2919aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2920aec0ec30SMyung Bae         {
292162598e31SEd Tanous             BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2922aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2923aec0ec30SMyung Bae             return;
2924aec0ec30SMyung Bae         }
2925e6bd846dSNan Zhou         if (ec)
2926e6bd846dSNan Zhou         {
2927c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
292862598e31SEd Tanous             BMCWEB_LOG_ERROR(
292962598e31SEd Tanous                 "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2930e6bd846dSNan Zhou             return;
2931e6bd846dSNan Zhou         }
2932c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
293362598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 exit");
29342b73119cSGeorge Liu     });
2935e6bd846dSNan Zhou }
2936e6bd846dSNan Zhou 
2937bacb2162SNan Zhou } // namespace sensors
2938bacb2162SNan Zhou 
29397e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
294095a3ecadSAnthony Wilson {
29417e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2942ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2943002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2944de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
294595a3ecadSAnthony Wilson }
294695a3ecadSAnthony Wilson 
29477e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
294895a3ecadSAnthony Wilson {
29497e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2950ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2951002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2952e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
295395a3ecadSAnthony Wilson }
295495a3ecadSAnthony Wilson 
295508777fb0SLewanczyk, Dawid } // namespace redfish
2956