xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 8b24275d7696c9df071d11e16a0f905b1e800163)
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>
44fe04d49cSNan Zhou #include <set>
457a1dbc48SGeorge Liu #include <string_view>
46b5a76932SEd Tanous #include <utility>
47abf2add6SEd Tanous #include <variant>
4808777fb0SLewanczyk, Dawid 
491abe55efSEd Tanous namespace redfish
501abe55efSEd Tanous {
5108777fb0SLewanczyk, Dawid 
52a0ec28b6SAdrian Ambrożewicz namespace sensors
53a0ec28b6SAdrian Ambrożewicz {
54a0ec28b6SAdrian Ambrożewicz namespace node
55a0ec28b6SAdrian Ambrożewicz {
56a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
57a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
58a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
59a0ec28b6SAdrian Ambrożewicz } // namespace node
60a0ec28b6SAdrian Ambrożewicz 
6102da7c5aSEd Tanous // clang-format off
62a0ec28b6SAdrian Ambrożewicz namespace dbus
63a0ec28b6SAdrian Ambrożewicz {
64cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6702da7c5aSEd Tanous });
68c2bf7f99SWludzik, Jozef 
69cf9e417dSEd Tanous constexpr auto sensorPaths = std::to_array<std::string_view>({
7002da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
71a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
727088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
735deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
74e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
75e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
76e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
77e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
78e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
79e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
80e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
81e8204933SGeorge Liu #endif
8202da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
8302da7c5aSEd Tanous });
8402da7c5aSEd Tanous 
85cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
8602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
87a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8802da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
8902da7c5aSEd Tanous });
9002da7c5aSEd Tanous 
91c2bf7f99SWludzik, Jozef } // namespace dbus
9202da7c5aSEd Tanous // clang-format on
9302da7c5aSEd Tanous 
94cf9e417dSEd Tanous using sensorPair =
95cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
9602da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
97cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
98cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
99cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
100c2bf7f99SWludzik, Jozef 
1010ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
102c2bf7f99SWludzik, Jozef {
103c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
104c2bf7f99SWludzik, Jozef     {
1050ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
106c2bf7f99SWludzik, Jozef     }
107c2bf7f99SWludzik, Jozef     if (sensorType == "power")
108c2bf7f99SWludzik, Jozef     {
1090ec8b83dSEd Tanous         return sensor::ReadingType::Power;
110c2bf7f99SWludzik, Jozef     }
111c2bf7f99SWludzik, Jozef     if (sensorType == "current")
112c2bf7f99SWludzik, Jozef     {
1130ec8b83dSEd Tanous         return sensor::ReadingType::Current;
114c2bf7f99SWludzik, Jozef     }
115c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
116c2bf7f99SWludzik, Jozef     {
1170ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
118c2bf7f99SWludzik, Jozef     }
119c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
120c2bf7f99SWludzik, Jozef     {
1210ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
122c2bf7f99SWludzik, Jozef     }
123c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
124c2bf7f99SWludzik, Jozef     {
1250ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
126c2bf7f99SWludzik, Jozef     }
1275deabed9SGunnar Mills     if (sensorType == "humidity")
1285deabed9SGunnar Mills     {
1290ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1305deabed9SGunnar Mills     }
131c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
132c2bf7f99SWludzik, Jozef     {
1330ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
134c2bf7f99SWludzik, Jozef     }
135c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
136c2bf7f99SWludzik, Jozef     {
1370ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
138c2bf7f99SWludzik, Jozef     }
139c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
140c2bf7f99SWludzik, Jozef     {
1410ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
142c2bf7f99SWludzik, Jozef     }
1430ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
144c2bf7f99SWludzik, Jozef }
145c2bf7f99SWludzik, Jozef 
1461d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
147c2bf7f99SWludzik, Jozef {
148c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
149c2bf7f99SWludzik, Jozef     {
150c2bf7f99SWludzik, Jozef         return "V";
151c2bf7f99SWludzik, Jozef     }
152c2bf7f99SWludzik, Jozef     if (sensorType == "power")
153c2bf7f99SWludzik, Jozef     {
154c2bf7f99SWludzik, Jozef         return "W";
155c2bf7f99SWludzik, Jozef     }
156c2bf7f99SWludzik, Jozef     if (sensorType == "current")
157c2bf7f99SWludzik, Jozef     {
158c2bf7f99SWludzik, Jozef         return "A";
159c2bf7f99SWludzik, Jozef     }
160c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
161c2bf7f99SWludzik, Jozef     {
162c2bf7f99SWludzik, Jozef         return "RPM";
163c2bf7f99SWludzik, Jozef     }
164c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
165c2bf7f99SWludzik, Jozef     {
166c2bf7f99SWludzik, Jozef         return "Cel";
167c2bf7f99SWludzik, Jozef     }
1685deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1695deabed9SGunnar Mills         sensorType == "humidity")
170c2bf7f99SWludzik, Jozef     {
171c2bf7f99SWludzik, Jozef         return "%";
172c2bf7f99SWludzik, Jozef     }
173c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
174c2bf7f99SWludzik, Jozef     {
175c2bf7f99SWludzik, Jozef         return "m";
176c2bf7f99SWludzik, Jozef     }
177c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
178c2bf7f99SWludzik, Jozef     {
179c2bf7f99SWludzik, Jozef         return "cft_i/min";
180c2bf7f99SWludzik, Jozef     }
181c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
182c2bf7f99SWludzik, Jozef     {
183c2bf7f99SWludzik, Jozef         return "J";
184c2bf7f99SWludzik, Jozef     }
185c2bf7f99SWludzik, Jozef     return "";
186a0ec28b6SAdrian Ambrożewicz }
187a0ec28b6SAdrian Ambrożewicz } // namespace sensors
188a0ec28b6SAdrian Ambrożewicz 
18908777fb0SLewanczyk, Dawid /**
190588c3f0dSKowalski, Kamil  * SensorsAsyncResp
19108777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
19208777fb0SLewanczyk, Dawid  */
1931abe55efSEd Tanous class SensorsAsyncResp
1941abe55efSEd Tanous {
19508777fb0SLewanczyk, Dawid   public:
196a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
197a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
198fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
199a0ec28b6SAdrian Ambrożewicz 
200a0ec28b6SAdrian Ambrożewicz     struct SensorData
201a0ec28b6SAdrian Ambrożewicz     {
202a0ec28b6SAdrian Ambrożewicz         const std::string name;
203a0ec28b6SAdrian Ambrożewicz         std::string uri;
204a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
205a0ec28b6SAdrian Ambrożewicz     };
206a0ec28b6SAdrian Ambrożewicz 
2078a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2088d1b46d7Szhanghch05                      const std::string& chassisIdIn,
209cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21002da7c5aSEd Tanous                      std::string_view subNode) :
2118a592810SEd Tanous         asyncResp(asyncRespIn),
212928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
213928fefb9SNan Zhou         efficientExpand(false)
2141214b7e7SGunnar Mills     {}
21508777fb0SLewanczyk, Dawid 
216a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2178a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2188d1b46d7Szhanghch05                      const std::string& chassisIdIn,
219cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22002da7c5aSEd Tanous                      std::string_view subNode,
221a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2228a592810SEd Tanous         asyncResp(asyncRespIn),
223928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
224928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
225a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
226a0ec28b6SAdrian Ambrożewicz     {}
227a0ec28b6SAdrian Ambrożewicz 
228928fefb9SNan Zhou     // sensor collections expand
2298a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
230928fefb9SNan Zhou                      const std::string& chassisIdIn,
231cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2328a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2338a592810SEd Tanous         asyncResp(asyncRespIn),
234928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2358a592810SEd Tanous         efficientExpand(efficientExpandIn)
236928fefb9SNan Zhou     {}
237928fefb9SNan Zhou 
2381abe55efSEd Tanous     ~SensorsAsyncResp()
2391abe55efSEd Tanous     {
2408d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2418d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2421abe55efSEd Tanous         {
2431abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2441abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2451abe55efSEd Tanous             // proper code
2468d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24708777fb0SLewanczyk, Dawid         }
248a0ec28b6SAdrian Ambrożewicz 
249a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
250a0ec28b6SAdrian Ambrożewicz         {
251fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2528d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
253a0ec28b6SAdrian Ambrożewicz             {
254a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
255a0ec28b6SAdrian Ambrożewicz                 {
256c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
257a0ec28b6SAdrian Ambrożewicz                 }
258a0ec28b6SAdrian Ambrożewicz             }
2598d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
260a0ec28b6SAdrian Ambrożewicz         }
26108777fb0SLewanczyk, Dawid     }
262588c3f0dSKowalski, Kamil 
263ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
264ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
265ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
266ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
267ecd6a3a2SEd Tanous 
268a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
269c1d019a6SEd Tanous                      const std::string& dbusPath)
270a0ec28b6SAdrian Ambrożewicz     {
271a0ec28b6SAdrian Ambrożewicz         if (metadata)
272a0ec28b6SAdrian Ambrożewicz         {
273c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
274c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
275a0ec28b6SAdrian Ambrożewicz         }
276a0ec28b6SAdrian Ambrożewicz     }
277a0ec28b6SAdrian Ambrożewicz 
278a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
279a0ec28b6SAdrian Ambrożewicz     {
280a0ec28b6SAdrian Ambrożewicz         if (metadata)
281a0ec28b6SAdrian Ambrożewicz         {
282a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
283a0ec28b6SAdrian Ambrożewicz             {
284a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
285a0ec28b6SAdrian Ambrożewicz                 {
286a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
287a0ec28b6SAdrian Ambrożewicz                 }
288a0ec28b6SAdrian Ambrożewicz             }
289a0ec28b6SAdrian Ambrożewicz         }
290a0ec28b6SAdrian Ambrożewicz     }
291a0ec28b6SAdrian Ambrożewicz 
2928d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
293a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
294cf9e417dSEd Tanous     const std::span<const std::string_view> types;
295a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
296928fefb9SNan Zhou     const bool efficientExpand;
297a0ec28b6SAdrian Ambrożewicz 
298a0ec28b6SAdrian Ambrożewicz   private:
299a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
300a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
30108777fb0SLewanczyk, Dawid };
30208777fb0SLewanczyk, Dawid 
30308777fb0SLewanczyk, Dawid /**
304d500549bSAnthony Wilson  * Possible states for physical inventory leds
305d500549bSAnthony Wilson  */
306d500549bSAnthony Wilson enum class LedState
307d500549bSAnthony Wilson {
308d500549bSAnthony Wilson     OFF,
309d500549bSAnthony Wilson     ON,
310d500549bSAnthony Wilson     BLINK,
311d500549bSAnthony Wilson     UNKNOWN
312d500549bSAnthony Wilson };
313d500549bSAnthony Wilson 
314d500549bSAnthony Wilson /**
315adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
316adc4f0dbSShawn McCarney  */
317adc4f0dbSShawn McCarney class InventoryItem
318adc4f0dbSShawn McCarney {
319adc4f0dbSShawn McCarney   public:
3204e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
321adc4f0dbSShawn McCarney     {
322adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
32328aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
32428aa8de5SGeorge Liu         name = path.filename();
32528aa8de5SGeorge Liu         if (name.empty())
326adc4f0dbSShawn McCarney         {
32728aa8de5SGeorge Liu             BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath;
328adc4f0dbSShawn McCarney         }
329adc4f0dbSShawn McCarney     }
330adc4f0dbSShawn McCarney 
331adc4f0dbSShawn McCarney     std::string objectPath;
332adc4f0dbSShawn McCarney     std::string name;
333e05aec50SEd Tanous     bool isPresent = true;
334e05aec50SEd Tanous     bool isFunctional = true;
335e05aec50SEd Tanous     bool isPowerSupply = false;
336e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
337adc4f0dbSShawn McCarney     std::string manufacturer;
338adc4f0dbSShawn McCarney     std::string model;
339adc4f0dbSShawn McCarney     std::string partNumber;
340adc4f0dbSShawn McCarney     std::string serialNumber;
341adc4f0dbSShawn McCarney     std::set<std::string> sensors;
342d500549bSAnthony Wilson     std::string ledObjectPath;
343e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
344adc4f0dbSShawn McCarney };
345adc4f0dbSShawn McCarney 
346adc4f0dbSShawn McCarney /**
347413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
348588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
34908777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
35008777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
35108777fb0SLewanczyk, Dawid  */
35208777fb0SLewanczyk, Dawid template <typename Callback>
353413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
35481ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
355fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3561abe55efSEd Tanous     Callback&& callback)
3571abe55efSEd Tanous {
358413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter";
35903b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
360e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
36108777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
36208777fb0SLewanczyk, Dawid 
363e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
364e99073f5SGeorge Liu     dbus::utility::getSubTree(
365e99073f5SGeorge Liu         path, 2, interfaces,
366002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
367e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
368002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
369e99073f5SGeorge Liu         // Response handler for parsing objects subtree
370413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter";
3711abe55efSEd Tanous         if (ec)
3721abe55efSEd Tanous         {
3738d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
374413961deSRichard Marian Thomaiyar             BMCWEB_LOG_ERROR
375413961deSRichard Marian Thomaiyar                 << "getObjectsWithConnection resp_handler: Dbus error " << ec;
37608777fb0SLewanczyk, Dawid             return;
37708777fb0SLewanczyk, Dawid         }
37808777fb0SLewanczyk, Dawid 
37955c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
38008777fb0SLewanczyk, Dawid 
38108777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
38208777fb0SLewanczyk, Dawid         // found in the chassis
383fe04d49cSNan Zhou         std::set<std::string> connections;
384413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
38508777fb0SLewanczyk, Dawid 
38649c53ac9SJohnathan Mantey         BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size();
38749c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3881abe55efSEd Tanous         {
38955c7b7a2SEd Tanous             BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
39008777fb0SLewanczyk, Dawid         }
39108777fb0SLewanczyk, Dawid 
39208777fb0SLewanczyk, Dawid         for (const std::pair<
39308777fb0SLewanczyk, Dawid                  std::string,
39408777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3951abe55efSEd Tanous                  object : subtree)
3961abe55efSEd Tanous         {
39749c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3981abe55efSEd Tanous             {
39949c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
4001abe55efSEd Tanous                          objData : object.second)
4011abe55efSEd Tanous                 {
40249c53ac9SJohnathan Mantey                     BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
40308777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
404de629b6eSShawn McCarney                     objectsWithConnection.insert(
405de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
40608777fb0SLewanczyk, Dawid                 }
40708777fb0SLewanczyk, Dawid             }
40808777fb0SLewanczyk, Dawid         }
40955c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
410413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
411413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit";
412e99073f5SGeorge Liu         });
413413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit";
414413961deSRichard Marian Thomaiyar }
415413961deSRichard Marian Thomaiyar 
416413961deSRichard Marian Thomaiyar /**
417413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
418413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
419413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
420413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
421413961deSRichard Marian Thomaiyar  */
422413961deSRichard Marian Thomaiyar template <typename Callback>
423fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
424fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
425413961deSRichard Marian Thomaiyar                     Callback&& callback)
426413961deSRichard Marian Thomaiyar {
427413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
428fe04d49cSNan Zhou         [callback](const std::set<std::string>& connections,
429413961deSRichard Marian Thomaiyar                    const std::set<std::pair<std::string, std::string>>&
4303174e4dfSEd Tanous                    /*objectsWithConnection*/) { callback(connections); };
43181ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
432413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
43308777fb0SLewanczyk, Dawid }
43408777fb0SLewanczyk, Dawid 
43508777fb0SLewanczyk, Dawid /**
43649c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
43749c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
43849c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
43949c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
44049c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
44149c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
44249c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
44349c53ac9SJohnathan Mantey  */
44423a21a1cSEd Tanous inline void reduceSensorList(
4457f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
446cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
44749c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
448fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
44949c53ac9SJohnathan Mantey {
45049c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
45149c53ac9SJohnathan Mantey     {
4527f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4537f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
454a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
45549c53ac9SJohnathan Mantey                                        : "Voltages");
45649c53ac9SJohnathan Mantey 
45749c53ac9SJohnathan Mantey         return;
45849c53ac9SJohnathan Mantey     }
45949c53ac9SJohnathan Mantey     if (allSensors->empty())
46049c53ac9SJohnathan Mantey     {
46149c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
46249c53ac9SJohnathan Mantey         return;
46349c53ac9SJohnathan Mantey     }
46449c53ac9SJohnathan Mantey 
4657f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
46649c53ac9SJohnathan Mantey     {
46749c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
46849c53ac9SJohnathan Mantey         {
46911ba3979SEd Tanous             if (sensor.starts_with(type))
47049c53ac9SJohnathan Mantey             {
47149c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
47249c53ac9SJohnathan Mantey             }
47349c53ac9SJohnathan Mantey         }
47449c53ac9SJohnathan Mantey     }
47549c53ac9SJohnathan Mantey }
47649c53ac9SJohnathan Mantey 
4777f1cc26dSEd Tanous /*
4787f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4797f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4807f1cc26dSEd Tanous  *
4817f1cc26dSEd Tanous  * */
4827f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4837f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4847f1cc26dSEd Tanous {
4857f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4867f1cc26dSEd Tanous     {
4877f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4887f1cc26dSEd Tanous     }
4897f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4907f1cc26dSEd Tanous     {
4917f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
4927f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
4937f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
4947f1cc26dSEd Tanous     }
4957f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
4967f1cc26dSEd Tanous     {
4977f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
4987f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
4997f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
5007f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5017f1cc26dSEd Tanous     }
5027f1cc26dSEd Tanous 
5037f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5047f1cc26dSEd Tanous     {
5057f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5067f1cc26dSEd Tanous     }
5077f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5087f1cc26dSEd Tanous }
5097f1cc26dSEd Tanous 
51049c53ac9SJohnathan Mantey /**
51108777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
512588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
51308777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
51408777fb0SLewanczyk, Dawid  */
51508777fb0SLewanczyk, Dawid template <typename Callback>
5167f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5177f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
518cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
519cf9e417dSEd Tanous                 Callback&& callback)
5201abe55efSEd Tanous {
52155c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis enter";
5227a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
52349c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
524adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5257a1dbc48SGeorge Liu 
5267a1dbc48SGeorge Liu     // Get the Chassis Collection
5277a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5287a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5297f1cc26dSEd Tanous         [callback{std::forward<Callback>(callback)}, asyncResp,
5307f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5317f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5327a1dbc48SGeorge Liu             const boost::system::error_code& ec,
533002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
53455c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
5351abe55efSEd Tanous         if (ec)
5361abe55efSEd Tanous         {
53755c7b7a2SEd Tanous             BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
5387f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
53908777fb0SLewanczyk, Dawid             return;
54008777fb0SLewanczyk, Dawid         }
54149c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
54249c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5431abe55efSEd Tanous         {
54428aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
545f8fe53e7SEd Tanous             std::string chassisName = path.filename();
54628aa8de5SGeorge Liu             if (chassisName.empty())
5471abe55efSEd Tanous             {
54849c53ac9SJohnathan Mantey                 BMCWEB_LOG_ERROR << "Failed to find '/' in " << chassis;
549daf36e2eSEd Tanous                 continue;
550daf36e2eSEd Tanous             }
5517f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5521abe55efSEd Tanous             {
55349c53ac9SJohnathan Mantey                 chassisPath = &chassis;
55449c53ac9SJohnathan Mantey                 break;
555daf36e2eSEd Tanous             }
55649c53ac9SJohnathan Mantey         }
55749c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5581abe55efSEd Tanous         {
5597f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
56049c53ac9SJohnathan Mantey             return;
5611abe55efSEd Tanous         }
5627f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
56308777fb0SLewanczyk, Dawid 
564ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
565ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
56695a3ecadSAnthony Wilson 
5678fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5688fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5696c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5706c3e9451SGeorge Liu             sensorPath,
5717f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
572f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
573*8b24275dSEd Tanous                 const boost::system::error_code& ec2,
5746c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
575*8b24275dSEd Tanous             if (ec2)
57649c53ac9SJohnathan Mantey             {
577*8b24275dSEd Tanous                 if (ec2.value() != EBADR)
57849c53ac9SJohnathan Mantey                 {
5797f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
58049c53ac9SJohnathan Mantey                     return;
58149c53ac9SJohnathan Mantey                 }
58249c53ac9SJohnathan Mantey             }
583fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
584fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5857f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5867f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
5877f1cc26dSEd Tanous             BMCWEB_LOG_DEBUG << "Finishing with " << culledSensorList->size();
58849c53ac9SJohnathan Mantey             callback(culledSensorList);
5891e1e598dSJonathan Doman             });
5907a1dbc48SGeorge Liu         });
59155c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis exit";
59208777fb0SLewanczyk, Dawid }
59308777fb0SLewanczyk, Dawid 
59408777fb0SLewanczyk, Dawid /**
595adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
596adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
597adc4f0dbSShawn McCarney  * @return State value for inventory item.
59834dd179eSJames Feist  */
59923a21a1cSEd Tanous inline std::string getState(const InventoryItem* inventoryItem)
600adc4f0dbSShawn McCarney {
601adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
602adc4f0dbSShawn McCarney     {
603adc4f0dbSShawn McCarney         return "Absent";
604adc4f0dbSShawn McCarney     }
60534dd179eSJames Feist 
606adc4f0dbSShawn McCarney     return "Enabled";
607adc4f0dbSShawn McCarney }
608adc4f0dbSShawn McCarney 
609adc4f0dbSShawn McCarney /**
610adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
611adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6121d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
613adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
614adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
615adc4f0dbSShawn McCarney  * @return Health value for sensor.
616adc4f0dbSShawn McCarney  */
6171d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6181d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
619adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
62034dd179eSJames Feist {
621adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
622adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
623adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
624adc4f0dbSShawn McCarney     std::string currentHealth;
625adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
626adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
627adc4f0dbSShawn McCarney     {
628adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
629adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
630adc4f0dbSShawn McCarney         {
631adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
632adc4f0dbSShawn McCarney             if (health != nullptr)
633adc4f0dbSShawn McCarney             {
634adc4f0dbSShawn McCarney                 currentHealth = *health;
635adc4f0dbSShawn McCarney             }
636adc4f0dbSShawn McCarney         }
637adc4f0dbSShawn McCarney     }
638adc4f0dbSShawn McCarney 
639adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
640adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
641adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
642adc4f0dbSShawn McCarney     {
643adc4f0dbSShawn McCarney         return "Critical";
644adc4f0dbSShawn McCarney     }
645adc4f0dbSShawn McCarney 
646c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
647c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
648c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
649c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
650711ac7a9SEd Tanous 
651c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
652c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
653c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
654c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
655c1343bf6SKrzysztof Grobelny         warningAlarmLow);
656c1343bf6SKrzysztof Grobelny 
657c1343bf6SKrzysztof Grobelny     if (success)
65834dd179eSJames Feist     {
659c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
660c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
661c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
66234dd179eSJames Feist         {
66334dd179eSJames Feist             return "Critical";
66434dd179eSJames Feist         }
66534dd179eSJames Feist     }
66634dd179eSJames Feist 
667adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
668adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
669adc4f0dbSShawn McCarney     {
670adc4f0dbSShawn McCarney         return "Critical";
671adc4f0dbSShawn McCarney     }
672adc4f0dbSShawn McCarney 
673adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
674adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
675adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
676adc4f0dbSShawn McCarney     {
677adc4f0dbSShawn McCarney         return "Warning";
678adc4f0dbSShawn McCarney     }
679adc4f0dbSShawn McCarney 
680c1343bf6SKrzysztof Grobelny     if (success)
681c1343bf6SKrzysztof Grobelny     {
682adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
683c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
684c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
68534dd179eSJames Feist         {
686ebe4d91eSEd Tanous             return "Warning";
68734dd179eSJames Feist         }
68834dd179eSJames Feist     }
689adc4f0dbSShawn McCarney 
69034dd179eSJames Feist     return "OK";
69134dd179eSJames Feist }
69234dd179eSJames Feist 
69323a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
694d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
695d500549bSAnthony Wilson {
696d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
697d500549bSAnthony Wilson     {
698d500549bSAnthony Wilson         switch (inventoryItem->ledState)
699d500549bSAnthony Wilson         {
700d500549bSAnthony Wilson             case LedState::OFF:
701d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
702d500549bSAnthony Wilson                 break;
703d500549bSAnthony Wilson             case LedState::ON:
704d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
705d500549bSAnthony Wilson                 break;
706d500549bSAnthony Wilson             case LedState::BLINK:
707d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
708d500549bSAnthony Wilson                 break;
70923a21a1cSEd Tanous             case LedState::UNKNOWN:
710d500549bSAnthony Wilson                 break;
711d500549bSAnthony Wilson         }
712d500549bSAnthony Wilson     }
713d500549bSAnthony Wilson }
714d500549bSAnthony Wilson 
71534dd179eSJames Feist /**
71608777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
71708777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
718274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
71908777fb0SLewanczyk, Dawid  * build
7201d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
7211d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7221d7c0054SEd Tanous  * from.
7231d7c0054SEd Tanous  * @param sensorJson  The json object to fill
724adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
725adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
72608777fb0SLewanczyk, Dawid  */
7271d7c0054SEd Tanous inline void objectPropertiesToJson(
7281d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7291d7c0054SEd Tanous     std::string_view chassisSubNode,
7301d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
73181ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7321abe55efSEd Tanous {
7331d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
734adc4f0dbSShawn McCarney     {
735c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
736c1d019a6SEd Tanous         subNodeEscaped.erase(
737c1d019a6SEd Tanous             std::remove(subNodeEscaped.begin(), subNodeEscaped.end(), '_'),
738c1d019a6SEd Tanous             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         {
777c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading type for "
778c2bf7f99SWludzik, Jozef                              << 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         {
788c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for "
789c2bf7f99SWludzik, Jozef                              << 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         }
8351d7c0054SEd Tanous         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     {
84655c7b7a2SEd 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             {
93140e4f380SEd 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                 }
943283860f5SEd Tanous                 BMCWEB_LOG_WARNING << "Sensor value for " << valueName
944283860f5SEd Tanous                                    << " was unexpectedly " << *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,
9741d7c0054SEd Tanous     const dbus::utility::DBusInteracesMap& 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     }
982c1d019a6SEd 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](
1013*8b24275dSEd Tanous                     const boost::system::error_code& ec2,
10146c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
1015*8b24275dSEd 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                 }
1020002d39b4SEd Tanous                 auto found =
1021002d39b4SEd Tanous                     std::find_if(endpoints.begin(), endpoints.end(),
10228bd25ccdSJames Feist                                  [sensorsAsyncResp](const std::string& entry) {
1023002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10248bd25ccdSJames Feist                            std::string::npos;
10258bd25ccdSJames Feist                     });
10268bd25ccdSJames Feist 
10271e1e598dSJonathan Doman                 if (found == endpoints.end())
10288bd25ccdSJames Feist                 {
10298bd25ccdSJames Feist                     return;
10308bd25ccdSJames Feist                 }
103186d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
103286d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
103386d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10348bd25ccdSJames Feist                     [path, sensorsAsyncResp](
1035*8b24275dSEd Tanous                         const boost::system::error_code& ec3,
103686d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
1037*8b24275dSEd Tanous                     if (ec3)
10388bd25ccdSJames Feist                     {
10398bd25ccdSJames Feist                         return; // don't have to have this
10408bd25ccdSJames Feist                                 // interface
10418bd25ccdSJames Feist                     }
10428bd25ccdSJames Feist 
104386d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
104486d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
104586d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
104686d89ed7SKrzysztof Grobelny 
104786d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
104886d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
104986d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
105086d89ed7SKrzysztof Grobelny                         collection, "Status", status);
105186d89ed7SKrzysztof Grobelny 
105286d89ed7SKrzysztof Grobelny                     if (!success)
105386d89ed7SKrzysztof Grobelny                     {
105486d89ed7SKrzysztof Grobelny                         messages::internalError(
105586d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
105686d89ed7SKrzysztof Grobelny                         return;
105786d89ed7SKrzysztof Grobelny                     }
105886d89ed7SKrzysztof Grobelny 
105986d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
106086d89ed7SKrzysztof Grobelny                         status == nullptr)
10618bd25ccdSJames Feist                     {
1062002d39b4SEd Tanous                         BMCWEB_LOG_ERROR << "Invalid redundancy interface";
10638bd25ccdSJames Feist                         messages::internalError(
10648d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10658bd25ccdSJames Feist                         return;
10668bd25ccdSJames Feist                     }
10678bd25ccdSJames Feist 
1068002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
106928aa8de5SGeorge Liu                     std::string name = objectPath.filename();
107028aa8de5SGeorge Liu                     if (name.empty())
10718bd25ccdSJames Feist                     {
10728bd25ccdSJames Feist                         // this should be impossible
10738bd25ccdSJames Feist                         messages::internalError(
10748d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10758bd25ccdSJames Feist                         return;
10768bd25ccdSJames Feist                     }
1077002d39b4SEd Tanous                     std::replace(name.begin(), name.end(), '_', ' ');
10788bd25ccdSJames Feist 
10798bd25ccdSJames Feist                     std::string health;
10808bd25ccdSJames Feist 
108111ba3979SEd Tanous                     if (status->ends_with("Full"))
10828bd25ccdSJames Feist                     {
10838bd25ccdSJames Feist                         health = "OK";
10848bd25ccdSJames Feist                     }
108511ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
10868bd25ccdSJames Feist                     {
10878bd25ccdSJames Feist                         health = "Warning";
10888bd25ccdSJames Feist                     }
10898bd25ccdSJames Feist                     else
10908bd25ccdSJames Feist                     {
10918bd25ccdSJames Feist                         health = "Critical";
10928bd25ccdSJames Feist                     }
10931476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
10948bd25ccdSJames Feist                     const auto& fanRedfish =
1095002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
10968bd25ccdSJames Feist                     for (const std::string& item : *collection)
10978bd25ccdSJames Feist                     {
10988a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
10998a592810SEd Tanous                         std::string itemName = itemPath.filename();
110028aa8de5SGeorge Liu                         if (itemName.empty())
110128aa8de5SGeorge Liu                         {
110228aa8de5SGeorge Liu                             continue;
110328aa8de5SGeorge Liu                         }
11048bd25ccdSJames Feist                         /*
11058bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11068bd25ccdSJames Feist                         std::replace(itemName.begin(),
11078bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
1108002d39b4SEd Tanous                         auto schemaItem =
1109002d39b4SEd Tanous                             std::find_if(fanRedfish.begin(), fanRedfish.end(),
11108bd25ccdSJames Feist                                          [itemName](const nlohmann::json& fan) {
11113e35c761SGeorge Liu                             return fan["Name"] == itemName;
11128bd25ccdSJames Feist                             });
11138bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11148bd25ccdSJames Feist                         {
11158a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11168a592810SEd Tanous                             collectionId["@odata.id"] =
11171476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11181476687dSEd Tanous                             redfishCollection.emplace_back(
11198a592810SEd Tanous                                 std::move(collectionId));
11208bd25ccdSJames Feist                         }
11218bd25ccdSJames Feist                         else
11228bd25ccdSJames Feist                         {
1123002d39b4SEd Tanous                             BMCWEB_LOG_ERROR << "failed to find fan in schema";
11248bd25ccdSJames Feist                             messages::internalError(
11258d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11268bd25ccdSJames Feist                             return;
11278bd25ccdSJames Feist                         }
11288bd25ccdSJames Feist                     }
11298bd25ccdSJames Feist 
113089492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
113126f6976fSEd Tanous                                               ? 0
113289492a15SPatrick Williams                                               : collection->size() -
113389492a15SPatrick Williams                                                     *allowedFailures;
1134002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11358bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11361476687dSEd Tanous 
11371476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1138ef4c65b7SEd Tanous                     boost::urls::url url =
1139ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1140ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1141eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1142eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1143eddfc437SWilly Tu                                          .to_string());
1144eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1145002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11461476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11471476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11481476687dSEd Tanous                     redundancy["Name"] = name;
11491476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11501476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11511476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11521476687dSEd Tanous 
1153b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
115486d89ed7SKrzysztof Grobelny                     });
11551e1e598dSJonathan Doman                 });
11568bd25ccdSJames Feist         }
1157e99073f5SGeorge Liu         });
11588bd25ccdSJames Feist }
11598bd25ccdSJames Feist 
1160b5a76932SEd Tanous inline void
116181ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
116249c53ac9SJohnathan Mantey {
11638d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
116449c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
116581ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
116649c53ac9SJohnathan Mantey     {
116749c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
116849c53ac9SJohnathan Mantey     }
116949c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
117049c53ac9SJohnathan Mantey     {
117149c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
117249c53ac9SJohnathan Mantey         if (entry != response.end())
117349c53ac9SJohnathan Mantey         {
117449c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
117502cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
117649c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
117749c53ac9SJohnathan Mantey             });
117849c53ac9SJohnathan Mantey 
117949c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
118049c53ac9SJohnathan Mantey             size_t count = 0;
118149c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
118249c53ac9SJohnathan Mantey             {
118349c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
118449c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
118549c53ac9SJohnathan Mantey                 {
118649c53ac9SJohnathan Mantey                     continue;
118749c53ac9SJohnathan Mantey                 }
118849c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
118949c53ac9SJohnathan Mantey                 if (value != nullptr)
119049c53ac9SJohnathan Mantey                 {
1191eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
11923e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
119349c53ac9SJohnathan Mantey                     count++;
119481ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
119549c53ac9SJohnathan Mantey                 }
119649c53ac9SJohnathan Mantey             }
119749c53ac9SJohnathan Mantey         }
119849c53ac9SJohnathan Mantey     }
119949c53ac9SJohnathan Mantey }
120049c53ac9SJohnathan Mantey 
120108777fb0SLewanczyk, Dawid /**
1202adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1203adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1204adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1205adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12068fb49dd6SShawn McCarney  */
120723a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1208b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1209adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12108fb49dd6SShawn McCarney {
1211adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12128fb49dd6SShawn McCarney     {
1213adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12148fb49dd6SShawn McCarney         {
1215adc4f0dbSShawn McCarney             return &inventoryItem;
12168fb49dd6SShawn McCarney         }
12178fb49dd6SShawn McCarney     }
12188fb49dd6SShawn McCarney     return nullptr;
12198fb49dd6SShawn McCarney }
12208fb49dd6SShawn McCarney 
12218fb49dd6SShawn McCarney /**
1222adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1223adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1224adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1225adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12268fb49dd6SShawn McCarney  */
122723a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1228b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1229adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1230adc4f0dbSShawn McCarney {
1231adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1232adc4f0dbSShawn McCarney     {
1233adc4f0dbSShawn McCarney         if (inventoryItem.sensors.count(sensorObjPath) > 0)
1234adc4f0dbSShawn McCarney         {
1235adc4f0dbSShawn McCarney             return &inventoryItem;
1236adc4f0dbSShawn McCarney         }
1237adc4f0dbSShawn McCarney     }
1238adc4f0dbSShawn McCarney     return nullptr;
1239adc4f0dbSShawn McCarney }
1240adc4f0dbSShawn McCarney 
1241adc4f0dbSShawn McCarney /**
1242d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1243d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1244d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1245d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1246d500549bSAnthony Wilson  */
1247d500549bSAnthony Wilson inline InventoryItem*
1248d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1249d500549bSAnthony Wilson                             const std::string& ledObjPath)
1250d500549bSAnthony Wilson {
1251d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1252d500549bSAnthony Wilson     {
1253d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1254d500549bSAnthony Wilson         {
1255d500549bSAnthony Wilson             return &inventoryItem;
1256d500549bSAnthony Wilson         }
1257d500549bSAnthony Wilson     }
1258d500549bSAnthony Wilson     return nullptr;
1259d500549bSAnthony Wilson }
1260d500549bSAnthony Wilson 
1261d500549bSAnthony Wilson /**
1262adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1263adc4f0dbSShawn McCarney  *
1264adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1265adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1266adc4f0dbSShawn McCarney  * added to the vector.
1267adc4f0dbSShawn McCarney  *
1268adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1269adc4f0dbSShawn McCarney  * InventoryItem.
1270adc4f0dbSShawn McCarney  *
1271adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1272adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1273adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1274adc4f0dbSShawn McCarney  */
1275b5a76932SEd Tanous inline void addInventoryItem(
1276b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1277b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1278adc4f0dbSShawn McCarney {
1279adc4f0dbSShawn McCarney     // Look for inventory item in vector
128089492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
128189492a15SPatrick Williams                                                      invItemObjPath);
1282adc4f0dbSShawn McCarney 
1283adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1284adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1285adc4f0dbSShawn McCarney     {
1286adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1287adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1288adc4f0dbSShawn McCarney     }
1289adc4f0dbSShawn McCarney 
1290adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1291adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1292adc4f0dbSShawn McCarney }
1293adc4f0dbSShawn McCarney 
1294adc4f0dbSShawn McCarney /**
1295adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1296adc4f0dbSShawn McCarney  *
1297adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1298adc4f0dbSShawn McCarney  * specified InventoryItem.
1299adc4f0dbSShawn McCarney  *
1300adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1301adc4f0dbSShawn McCarney  * response.
1302adc4f0dbSShawn McCarney  *
1303adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1304adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1305adc4f0dbSShawn McCarney  * for the specified inventory item.
1306adc4f0dbSShawn McCarney  */
130723a21a1cSEd Tanous inline void storeInventoryItemData(
1308adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
1309711ac7a9SEd Tanous     const dbus::utility::DBusInteracesMap& interfacesDict)
13108fb49dd6SShawn McCarney {
1311adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1312711ac7a9SEd Tanous 
13139eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13148fb49dd6SShawn McCarney     {
1315711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13168fb49dd6SShawn McCarney         {
13179eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1318711ac7a9SEd Tanous             {
1319711ac7a9SEd Tanous                 if (name == "Present")
1320711ac7a9SEd Tanous                 {
1321711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1322adc4f0dbSShawn McCarney                     if (value != nullptr)
13238fb49dd6SShawn McCarney                     {
1324adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13258fb49dd6SShawn McCarney                     }
13268fb49dd6SShawn McCarney                 }
13278fb49dd6SShawn McCarney             }
1328711ac7a9SEd Tanous         }
1329adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1330711ac7a9SEd Tanous 
1331711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13328fb49dd6SShawn McCarney         {
1333adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13348fb49dd6SShawn McCarney         }
1335adc4f0dbSShawn McCarney 
1336adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1337711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1338adc4f0dbSShawn McCarney         {
13399eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1340711ac7a9SEd Tanous             {
1341711ac7a9SEd Tanous                 if (name == "Manufacturer")
1342adc4f0dbSShawn McCarney                 {
1343adc4f0dbSShawn McCarney                     const std::string* value =
1344711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1345adc4f0dbSShawn McCarney                     if (value != nullptr)
1346adc4f0dbSShawn McCarney                     {
1347adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1348adc4f0dbSShawn McCarney                     }
1349adc4f0dbSShawn McCarney                 }
1350711ac7a9SEd Tanous                 if (name == "Model")
1351adc4f0dbSShawn McCarney                 {
1352adc4f0dbSShawn McCarney                     const std::string* value =
1353711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1354adc4f0dbSShawn McCarney                     if (value != nullptr)
1355adc4f0dbSShawn McCarney                     {
1356adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1357adc4f0dbSShawn McCarney                     }
1358adc4f0dbSShawn McCarney                 }
1359711ac7a9SEd Tanous                 if (name == "SerialNumber")
1360adc4f0dbSShawn McCarney                 {
1361adc4f0dbSShawn McCarney                     const std::string* value =
1362711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1363adc4f0dbSShawn McCarney                     if (value != nullptr)
1364adc4f0dbSShawn McCarney                     {
1365adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1366adc4f0dbSShawn McCarney                     }
1367adc4f0dbSShawn McCarney                 }
1368711ac7a9SEd Tanous                 if (name == "PartNumber")
1369711ac7a9SEd Tanous                 {
1370711ac7a9SEd Tanous                     const std::string* value =
1371711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1372711ac7a9SEd Tanous                     if (value != nullptr)
1373711ac7a9SEd Tanous                     {
1374711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1375711ac7a9SEd Tanous                     }
1376711ac7a9SEd Tanous                 }
1377711ac7a9SEd Tanous             }
1378adc4f0dbSShawn McCarney         }
1379adc4f0dbSShawn McCarney 
1380711ac7a9SEd Tanous         if (interface ==
1381711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1382adc4f0dbSShawn McCarney         {
13839eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1384adc4f0dbSShawn McCarney             {
1385711ac7a9SEd Tanous                 if (name == "Functional")
1386711ac7a9SEd Tanous                 {
1387711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1388adc4f0dbSShawn McCarney                     if (value != nullptr)
1389adc4f0dbSShawn McCarney                     {
1390adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
13918fb49dd6SShawn McCarney                     }
13928fb49dd6SShawn McCarney                 }
13938fb49dd6SShawn McCarney             }
13948fb49dd6SShawn McCarney         }
1395711ac7a9SEd Tanous     }
1396711ac7a9SEd Tanous }
13978fb49dd6SShawn McCarney 
13988fb49dd6SShawn McCarney /**
1399adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
14008fb49dd6SShawn McCarney  *
1401adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1402adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1403adc4f0dbSShawn McCarney  * inventoryItems vector.
14048fb49dd6SShawn McCarney  *
1405adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1406adc4f0dbSShawn McCarney  * response.
1407adc4f0dbSShawn McCarney  *
1408adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1409adc4f0dbSShawn McCarney  * been obtained.
1410adc4f0dbSShawn McCarney  *
1411adc4f0dbSShawn McCarney  * The callback must have the following signature:
1412adc4f0dbSShawn McCarney  *   @code
1413d500549bSAnthony Wilson  *   callback(void)
1414adc4f0dbSShawn McCarney  *   @endcode
1415adc4f0dbSShawn McCarney  *
1416adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1417adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1418adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14198fb49dd6SShawn McCarney  *
14208fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1421adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1422adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14238fb49dd6SShawn McCarney  * implements ObjectManager.
1424adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1425adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1426adc4f0dbSShawn McCarney  * in recursive calls to this function.
14278fb49dd6SShawn McCarney  */
1428adc4f0dbSShawn McCarney template <typename Callback>
1429adc4f0dbSShawn McCarney static void getInventoryItemsData(
14308fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1431adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1432d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1433d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14348fb49dd6SShawn McCarney {
1435adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData enter";
14368fb49dd6SShawn McCarney 
1437adc4f0dbSShawn McCarney     // If no more connections left, call callback
1438adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14398fb49dd6SShawn McCarney     {
1440d500549bSAnthony Wilson         callback();
1441adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1442adc4f0dbSShawn McCarney         return;
1443adc4f0dbSShawn McCarney     }
1444adc4f0dbSShawn McCarney 
1445adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1446fe04d49cSNan Zhou     auto it = invConnections->begin();
1447fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1448adc4f0dbSShawn McCarney     if (it != invConnections->end())
1449adc4f0dbSShawn McCarney     {
1450adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1451adc4f0dbSShawn McCarney 
14525eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14535eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14545eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14555eb468daSGeorge Liu             invConnection, path,
14565eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
14575eb468daSGeorge Liu              callback{std::forward<Callback>(callback)}, invConnectionsIndex](
14585e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
145902cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
1460adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter";
14618fb49dd6SShawn McCarney             if (ec)
14628fb49dd6SShawn McCarney             {
14638fb49dd6SShawn McCarney                 BMCWEB_LOG_ERROR
1464adc4f0dbSShawn McCarney                     << "getInventoryItemsData respHandler DBus error " << ec;
14658d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14668fb49dd6SShawn McCarney                 return;
14678fb49dd6SShawn McCarney             }
14688fb49dd6SShawn McCarney 
14698fb49dd6SShawn McCarney             // Loop through returned object paths
14708fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14718fb49dd6SShawn McCarney             {
14728fb49dd6SShawn McCarney                 const std::string& objPath =
14738fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14748fb49dd6SShawn McCarney 
1475adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
147689492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
147789492a15SPatrick Williams                                                                  objPath);
1478adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
14798fb49dd6SShawn McCarney                 {
1480adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1481adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
14828fb49dd6SShawn McCarney                 }
14838fb49dd6SShawn McCarney             }
14848fb49dd6SShawn McCarney 
1485adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1486adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1487d0090733SEd Tanous                                   invConnections, std::move(callback),
1488d0090733SEd Tanous                                   invConnectionsIndex + 1);
1489adc4f0dbSShawn McCarney 
1490adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit";
14915eb468daSGeorge Liu             });
14928fb49dd6SShawn McCarney     }
14938fb49dd6SShawn McCarney 
1494adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
14958fb49dd6SShawn McCarney }
14968fb49dd6SShawn McCarney 
14978fb49dd6SShawn McCarney /**
1498adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
14998fb49dd6SShawn McCarney  *
1500adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1501adc4f0dbSShawn McCarney  * items that are associated with sensors.
15028fb49dd6SShawn McCarney  *
15038fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15048fb49dd6SShawn McCarney  * been obtained.
15058fb49dd6SShawn McCarney  *
15068fb49dd6SShawn McCarney  * The callback must have the following signature:
15078fb49dd6SShawn McCarney  *   @code
1508fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15098fb49dd6SShawn McCarney  *   @endcode
15108fb49dd6SShawn McCarney  *
15118fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1512adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15138fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15148fb49dd6SShawn McCarney  */
15158fb49dd6SShawn McCarney template <typename Callback>
15168fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1517b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1518b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15198fb49dd6SShawn McCarney     Callback&& callback)
15208fb49dd6SShawn McCarney {
15218fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter";
15228fb49dd6SShawn McCarney 
15238fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1524e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15258fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1526adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1527adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15288fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15298fb49dd6SShawn McCarney 
1530e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1531e99073f5SGeorge Liu     dbus::utility::getSubTree(
1532e99073f5SGeorge Liu         path, 0, interfaces,
1533002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1534002d39b4SEd Tanous          inventoryItems](
1535e99073f5SGeorge Liu             const boost::system::error_code& ec,
1536002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1537e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
15388fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter";
15398fb49dd6SShawn McCarney         if (ec)
15408fb49dd6SShawn McCarney         {
15418d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
15428fb49dd6SShawn McCarney             BMCWEB_LOG_ERROR
15438fb49dd6SShawn McCarney                 << "getInventoryItemsConnections respHandler DBus error " << ec;
15448fb49dd6SShawn McCarney             return;
15458fb49dd6SShawn McCarney         }
15468fb49dd6SShawn McCarney 
15478fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1548fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1549fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15508fb49dd6SShawn McCarney 
15518fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15528fb49dd6SShawn McCarney         for (const std::pair<
15538fb49dd6SShawn McCarney                  std::string,
15548fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15558fb49dd6SShawn McCarney                  object : subtree)
15568fb49dd6SShawn McCarney         {
1557adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15588fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1559adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15608fb49dd6SShawn McCarney             {
15618fb49dd6SShawn McCarney                 // Store all connections to inventory item
15628fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15638fb49dd6SShawn McCarney                          objData : object.second)
15648fb49dd6SShawn McCarney                 {
15658fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15668fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15678fb49dd6SShawn McCarney                 }
15688fb49dd6SShawn McCarney             }
15698fb49dd6SShawn McCarney         }
1570d500549bSAnthony Wilson 
15718fb49dd6SShawn McCarney         callback(invConnections);
15728fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit";
1573e99073f5SGeorge Liu         });
15748fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit";
15758fb49dd6SShawn McCarney }
15768fb49dd6SShawn McCarney 
15778fb49dd6SShawn McCarney /**
1578adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
15798fb49dd6SShawn McCarney  *
15808fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1581d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1582d500549bSAnthony Wilson  * their LEDs, if any.
15838fb49dd6SShawn McCarney  *
15848fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
15858fb49dd6SShawn McCarney  * has been obtained.
15868fb49dd6SShawn McCarney  *
15878fb49dd6SShawn McCarney  * The callback must have the following signature:
15888fb49dd6SShawn McCarney  *   @code
1589adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
15908fb49dd6SShawn McCarney  *   @endcode
15918fb49dd6SShawn McCarney  *
15928fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
15938fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
15948fb49dd6SShawn McCarney  * implements ObjectManager.
15958fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
15968fb49dd6SShawn McCarney  */
15978fb49dd6SShawn McCarney template <typename Callback>
1598adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1599b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1600fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16018fb49dd6SShawn McCarney     Callback&& callback)
16028fb49dd6SShawn McCarney {
1603adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter";
16048fb49dd6SShawn McCarney 
16055eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16065eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16075eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16085eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
160902cad96eSEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
16105e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
161102cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
1612adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter";
16138fb49dd6SShawn McCarney         if (ec)
16148fb49dd6SShawn McCarney         {
1615adc4f0dbSShawn McCarney             BMCWEB_LOG_ERROR
1616adc4f0dbSShawn McCarney                 << "getInventoryItemAssociations respHandler DBus error " << ec;
16178d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16188fb49dd6SShawn McCarney             return;
16198fb49dd6SShawn McCarney         }
16208fb49dd6SShawn McCarney 
1621adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1622adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1623adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1624adc4f0dbSShawn McCarney 
16258fb49dd6SShawn McCarney         // Loop through returned object paths
16268fb49dd6SShawn McCarney         std::string sensorAssocPath;
16278fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16288fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16298fb49dd6SShawn McCarney         {
16308fb49dd6SShawn McCarney             const std::string& objPath =
16318fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16328fb49dd6SShawn McCarney 
16338fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16348fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16358fb49dd6SShawn McCarney             {
16368fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16378fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16388fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16398fb49dd6SShawn McCarney                 {
16408fb49dd6SShawn McCarney                     // Get Association interface for object path
1641711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16428fb49dd6SShawn McCarney                     {
1643711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1644711ac7a9SEd Tanous                         {
1645711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1646711ac7a9SEd Tanous                             {
1647711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16488fb49dd6SShawn McCarney                                 {
16498fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16508fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1651711ac7a9SEd Tanous                                             &value);
1652711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1653711ac7a9SEd Tanous                                         !endpoints->empty())
16548fb49dd6SShawn McCarney                                     {
1655adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1656adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1657adc4f0dbSShawn McCarney                                             endpoints->front();
1658711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1659711ac7a9SEd Tanous                                                          invItemPath,
1660adc4f0dbSShawn McCarney                                                          sensorName);
16618fb49dd6SShawn McCarney                                     }
16628fb49dd6SShawn McCarney                                 }
16638fb49dd6SShawn McCarney                             }
1664711ac7a9SEd Tanous                         }
1665711ac7a9SEd Tanous                     }
16668fb49dd6SShawn McCarney                     break;
16678fb49dd6SShawn McCarney                 }
16688fb49dd6SShawn McCarney             }
16698fb49dd6SShawn McCarney         }
16708fb49dd6SShawn McCarney 
1671d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1672d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1673d500549bSAnthony Wilson         std::string inventoryAssocPath;
1674d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1675d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1676d500549bSAnthony Wilson         {
1677d500549bSAnthony Wilson             const std::string& objPath =
1678d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1679d500549bSAnthony Wilson 
1680d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1681d500549bSAnthony Wilson             {
1682d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1683d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1684d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1685d500549bSAnthony Wilson                 {
1686711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1687d500549bSAnthony Wilson                     {
1688711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1689711ac7a9SEd Tanous                         {
1690711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1691711ac7a9SEd Tanous                             {
1692711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1693d500549bSAnthony Wilson                                 {
1694d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1695d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1696711ac7a9SEd Tanous                                             &value);
1697711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1698711ac7a9SEd Tanous                                         !endpoints->empty())
1699d500549bSAnthony Wilson                                     {
1700711ac7a9SEd Tanous                                         // Add inventory item to vector
1701d500549bSAnthony Wilson                                         // Store LED path in inventory item
1702711ac7a9SEd Tanous                                         const std::string& ledPath =
1703711ac7a9SEd Tanous                                             endpoints->front();
1704d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1705d500549bSAnthony Wilson                                     }
1706d500549bSAnthony Wilson                                 }
1707d500549bSAnthony Wilson                             }
1708711ac7a9SEd Tanous                         }
1709711ac7a9SEd Tanous                     }
1710711ac7a9SEd Tanous 
1711d500549bSAnthony Wilson                     break;
1712d500549bSAnthony Wilson                 }
1713d500549bSAnthony Wilson             }
1714d500549bSAnthony Wilson         }
1715adc4f0dbSShawn McCarney         callback(inventoryItems);
1716adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit";
17175eb468daSGeorge Liu         });
17188fb49dd6SShawn McCarney 
1719adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit";
17208fb49dd6SShawn McCarney }
17218fb49dd6SShawn McCarney 
17228fb49dd6SShawn McCarney /**
1723d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1724d500549bSAnthony Wilson  *
1725d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1726d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1727d500549bSAnthony Wilson  * inventoryItems vector.
1728d500549bSAnthony Wilson  *
1729d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1730d500549bSAnthony Wilson  * response.
1731d500549bSAnthony Wilson  *
1732d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1733d500549bSAnthony Wilson  * has been obtained.
1734d500549bSAnthony Wilson  *
1735d500549bSAnthony Wilson  * The callback must have the following signature:
1736d500549bSAnthony Wilson  *   @code
173742cbe538SGunnar Mills  *   callback()
1738d500549bSAnthony Wilson  *   @endcode
1739d500549bSAnthony Wilson  *
1740d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1741d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1742d500549bSAnthony Wilson  * last asynchronous function has completed.
1743d500549bSAnthony Wilson  *
1744d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1745d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1746d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1747d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1748d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1749d500549bSAnthony Wilson  * in recursive calls to this function.
1750d500549bSAnthony Wilson  */
1751d500549bSAnthony Wilson template <typename Callback>
1752d500549bSAnthony Wilson void getInventoryLedData(
1753d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1754d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1755fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1756d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1757d500549bSAnthony Wilson {
1758d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData enter";
1759d500549bSAnthony Wilson 
1760d500549bSAnthony Wilson     // If no more connections left, call callback
1761d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1762d500549bSAnthony Wilson     {
176342cbe538SGunnar Mills         callback();
1764d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1765d500549bSAnthony Wilson         return;
1766d500549bSAnthony Wilson     }
1767d500549bSAnthony Wilson 
1768d500549bSAnthony Wilson     // Get inventory item data from current connection
1769fe04d49cSNan Zhou     auto it = ledConnections->begin();
1770fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1771d500549bSAnthony Wilson     if (it != ledConnections->end())
1772d500549bSAnthony Wilson     {
1773d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1774d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1775d500549bSAnthony Wilson         // Response handler for Get State property
17761e1e598dSJonathan Doman         auto respHandler =
17771e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1778f94c4ecfSEd Tanous              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
17795e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
1780d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter";
1781d500549bSAnthony Wilson             if (ec)
1782d500549bSAnthony Wilson             {
1783d500549bSAnthony Wilson                 BMCWEB_LOG_ERROR
1784d500549bSAnthony Wilson                     << "getInventoryLedData respHandler DBus error " << ec;
17858d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1786d500549bSAnthony Wilson                 return;
1787d500549bSAnthony Wilson             }
1788d500549bSAnthony Wilson 
17891e1e598dSJonathan Doman             BMCWEB_LOG_DEBUG << "Led state: " << state;
1790d500549bSAnthony Wilson             // Find inventory item with this LED object path
1791d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1792d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1793d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1794d500549bSAnthony Wilson             {
1795d500549bSAnthony Wilson                 // Store LED state in InventoryItem
179611ba3979SEd Tanous                 if (state.ends_with("On"))
1797d500549bSAnthony Wilson                 {
1798d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1799d500549bSAnthony Wilson                 }
180011ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1801d500549bSAnthony Wilson                 {
1802d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1803d500549bSAnthony Wilson                 }
180411ba3979SEd Tanous                 else if (state.ends_with("Off"))
1805d500549bSAnthony Wilson                 {
1806d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1807d500549bSAnthony Wilson                 }
1808d500549bSAnthony Wilson                 else
1809d500549bSAnthony Wilson                 {
1810d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1811d500549bSAnthony Wilson                 }
1812d500549bSAnthony Wilson             }
1813d500549bSAnthony Wilson 
1814d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1815d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1816d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1817d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1818d500549bSAnthony Wilson 
1819d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit";
1820d500549bSAnthony Wilson         };
1821d500549bSAnthony Wilson 
1822d500549bSAnthony Wilson         // Get the State property for the current LED
18231e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18241e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18251e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18261e1e598dSJonathan Doman             std::move(respHandler));
1827d500549bSAnthony Wilson     }
1828d500549bSAnthony Wilson 
1829d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1830d500549bSAnthony Wilson }
1831d500549bSAnthony Wilson 
1832d500549bSAnthony Wilson /**
1833d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1834d500549bSAnthony Wilson  *
1835d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1836d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1837d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1838d500549bSAnthony Wilson  *
1839d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1840d500549bSAnthony Wilson  * response.
1841d500549bSAnthony Wilson  *
1842d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1843d500549bSAnthony Wilson  * been obtained.
1844d500549bSAnthony Wilson  *
1845d500549bSAnthony Wilson  * The callback must have the following signature:
1846d500549bSAnthony Wilson  *   @code
184742cbe538SGunnar Mills  *   callback()
1848d500549bSAnthony Wilson  *   @endcode
1849d500549bSAnthony Wilson  *
1850d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1851d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1852d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1853d500549bSAnthony Wilson  */
1854d500549bSAnthony Wilson template <typename Callback>
1855d500549bSAnthony Wilson void getInventoryLeds(
1856d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1857d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1858d500549bSAnthony Wilson     Callback&& callback)
1859d500549bSAnthony Wilson {
1860d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds enter";
1861d500549bSAnthony Wilson 
1862d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1863e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1864d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1865d500549bSAnthony Wilson 
1866e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1867e99073f5SGeorge Liu     dbus::utility::getSubTree(
1868e99073f5SGeorge Liu         path, 0, interfaces,
1869002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1870002d39b4SEd Tanous          inventoryItems](
1871e99073f5SGeorge Liu             const boost::system::error_code& ec,
1872002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1873e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
1874d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter";
1875d500549bSAnthony Wilson         if (ec)
1876d500549bSAnthony Wilson         {
18778d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
1878d500549bSAnthony Wilson             BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error "
1879d500549bSAnthony Wilson                              << ec;
1880d500549bSAnthony Wilson             return;
1881d500549bSAnthony Wilson         }
1882d500549bSAnthony Wilson 
1883d500549bSAnthony Wilson         // Build map of LED object paths to connections
1884fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1885fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1886d500549bSAnthony Wilson 
1887d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1888d500549bSAnthony Wilson         for (const std::pair<
1889d500549bSAnthony Wilson                  std::string,
1890d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1891d500549bSAnthony Wilson                  object : subtree)
1892d500549bSAnthony Wilson         {
1893d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1894d500549bSAnthony Wilson             // items
1895d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1896d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1897d500549bSAnthony Wilson             {
1898d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1899d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1900d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
1901d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> "
1902d500549bSAnthony Wilson                                  << connection;
1903d500549bSAnthony Wilson             }
1904d500549bSAnthony Wilson         }
1905d500549bSAnthony Wilson 
1906d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1907d500549bSAnthony Wilson                             std::move(callback));
1908d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit";
1909e99073f5SGeorge Liu         });
1910d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds exit";
1911d500549bSAnthony Wilson }
1912d500549bSAnthony Wilson 
1913d500549bSAnthony Wilson /**
191442cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
191542cbe538SGunnar Mills  *
191642cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
191742cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
191842cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
191942cbe538SGunnar Mills  *
192042cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
192142cbe538SGunnar Mills  * response.
192242cbe538SGunnar Mills  *
192342cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
192442cbe538SGunnar Mills  * when data has been obtained.
192542cbe538SGunnar Mills  *
192642cbe538SGunnar Mills  * The callback must have the following signature:
192742cbe538SGunnar Mills  *   @code
192842cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
192942cbe538SGunnar Mills  *   @endcode
193042cbe538SGunnar Mills  *
193142cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
193242cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
193342cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
193442cbe538SGunnar Mills  *        Supply Attributes
193542cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
193642cbe538SGunnar Mills  */
193742cbe538SGunnar Mills template <typename Callback>
193842cbe538SGunnar Mills void getPowerSupplyAttributesData(
1939b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
194042cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1941fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
194242cbe538SGunnar Mills     Callback&& callback)
194342cbe538SGunnar Mills {
194442cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter";
194542cbe538SGunnar Mills 
194642cbe538SGunnar Mills     if (psAttributesConnections.empty())
194742cbe538SGunnar Mills     {
194842cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!";
194942cbe538SGunnar Mills         callback(inventoryItems);
195042cbe538SGunnar Mills         return;
195142cbe538SGunnar Mills     }
195242cbe538SGunnar Mills 
195342cbe538SGunnar Mills     // Assuming just one connection (service) for now
1954fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
195542cbe538SGunnar Mills 
195642cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
195742cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
195842cbe538SGunnar Mills 
195942cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
1960002d39b4SEd Tanous     auto respHandler =
1961002d39b4SEd Tanous         [sensorsAsyncResp, inventoryItems,
1962f94c4ecfSEd Tanous          callback{std::forward<Callback>(callback)}](
19635e7e2dc5SEd Tanous             const boost::system::error_code& ec, const uint32_t value) {
196442cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter";
196542cbe538SGunnar Mills         if (ec)
196642cbe538SGunnar Mills         {
196742cbe538SGunnar Mills             BMCWEB_LOG_ERROR
196842cbe538SGunnar Mills                 << "getPowerSupplyAttributesData respHandler DBus error " << ec;
19698d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
197042cbe538SGunnar Mills             return;
197142cbe538SGunnar Mills         }
197242cbe538SGunnar Mills 
19731e1e598dSJonathan Doman         BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value;
197442cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
197542cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
197642cbe538SGunnar Mills         {
197755f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
197842cbe538SGunnar Mills             {
197942cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19801e1e598dSJonathan Doman                     static_cast<int>(value);
198142cbe538SGunnar Mills             }
198242cbe538SGunnar Mills         }
198342cbe538SGunnar Mills 
198442cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit";
198542cbe538SGunnar Mills         callback(inventoryItems);
198642cbe538SGunnar Mills     };
198742cbe538SGunnar Mills 
198842cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
198942cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
19901e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
19911e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
19921e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
19931e1e598dSJonathan Doman         std::move(respHandler));
199442cbe538SGunnar Mills 
199542cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit";
199642cbe538SGunnar Mills }
199742cbe538SGunnar Mills 
199842cbe538SGunnar Mills /**
199942cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
200042cbe538SGunnar Mills  *
200142cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
200242cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
200342cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
200442cbe538SGunnar Mills  * item.
200542cbe538SGunnar Mills  *
200642cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
200742cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
200842cbe538SGunnar Mills  *
200942cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
201042cbe538SGunnar Mills  * when information has been obtained.
201142cbe538SGunnar Mills  *
201242cbe538SGunnar Mills  * The callback must have the following signature:
201342cbe538SGunnar Mills  *   @code
201442cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
201542cbe538SGunnar Mills  *   @endcode
201642cbe538SGunnar Mills  *
201742cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
201842cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
201942cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
202042cbe538SGunnar Mills  */
202142cbe538SGunnar Mills template <typename Callback>
202242cbe538SGunnar Mills void getPowerSupplyAttributes(
202342cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
202442cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
202542cbe538SGunnar Mills     Callback&& callback)
202642cbe538SGunnar Mills {
202742cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter";
202842cbe538SGunnar Mills 
202942cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2030a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
203142cbe538SGunnar Mills     {
203242cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power";
203342cbe538SGunnar Mills         callback(inventoryItems);
203442cbe538SGunnar Mills         return;
203542cbe538SGunnar Mills     }
203642cbe538SGunnar Mills 
2037e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
203842cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
203942cbe538SGunnar Mills 
2040e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2041e99073f5SGeorge Liu     dbus::utility::getSubTree(
2042e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
2043b9d36b47SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2044b9d36b47SEd Tanous          inventoryItems](
2045e99073f5SGeorge Liu             const boost::system::error_code& ec,
2046b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2047e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
204842cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter";
204942cbe538SGunnar Mills         if (ec)
205042cbe538SGunnar Mills         {
20518d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
205242cbe538SGunnar Mills             BMCWEB_LOG_ERROR
205342cbe538SGunnar Mills                 << "getPowerSupplyAttributes respHandler DBus error " << ec;
205442cbe538SGunnar Mills             return;
205542cbe538SGunnar Mills         }
205626f6976fSEd Tanous         if (subtree.empty())
205742cbe538SGunnar Mills         {
205842cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!";
205942cbe538SGunnar Mills             callback(inventoryItems);
206042cbe538SGunnar Mills             return;
206142cbe538SGunnar Mills         }
206242cbe538SGunnar Mills 
206342cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
206442cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
206542cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2066fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
206742cbe538SGunnar Mills 
206842cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
206942cbe538SGunnar Mills         {
207042cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
207142cbe538SGunnar Mills             callback(inventoryItems);
207242cbe538SGunnar Mills             return;
207342cbe538SGunnar Mills         }
207442cbe538SGunnar Mills 
207542cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
207642cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
207742cbe538SGunnar Mills 
207842cbe538SGunnar Mills         if (connection.empty())
207942cbe538SGunnar Mills         {
208042cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
208142cbe538SGunnar Mills             callback(inventoryItems);
208242cbe538SGunnar Mills             return;
208342cbe538SGunnar Mills         }
208442cbe538SGunnar Mills 
208542cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
208642cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> "
208742cbe538SGunnar Mills                          << connection;
208842cbe538SGunnar Mills 
208942cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
209042cbe538SGunnar Mills                                      psAttributesConnections,
209142cbe538SGunnar Mills                                      std::move(callback));
209242cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit";
2093e99073f5SGeorge Liu         });
209442cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit";
209542cbe538SGunnar Mills }
209642cbe538SGunnar Mills 
209742cbe538SGunnar Mills /**
2098adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
20998fb49dd6SShawn McCarney  *
21008fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2101adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21028fb49dd6SShawn McCarney  *
2103adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2104adc4f0dbSShawn McCarney  * response.
21058fb49dd6SShawn McCarney  *
2106adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2107adc4f0dbSShawn McCarney  * inventory items have been obtained.
2108adc4f0dbSShawn McCarney  *
2109adc4f0dbSShawn McCarney  * The callback must have the following signature:
2110adc4f0dbSShawn McCarney  *   @code
2111adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2112adc4f0dbSShawn McCarney  *   @endcode
21138fb49dd6SShawn McCarney  *
21148fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21158fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21168fb49dd6SShawn McCarney  * implements ObjectManager.
2117adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21188fb49dd6SShawn McCarney  */
2119adc4f0dbSShawn McCarney template <typename Callback>
2120d0090733SEd Tanous static void
2121d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2122fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2123adc4f0dbSShawn McCarney                       Callback&& callback)
21248fb49dd6SShawn McCarney {
2125adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems enter";
2126adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2127d0090733SEd Tanous         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2128adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
2129adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter";
21308fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2131d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2132f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
2133fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
21348fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter";
2135002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2136d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
2137d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter";
213842cbe538SGunnar Mills 
2139002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2140002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
214142cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter";
214242cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2143002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
214442cbe538SGunnar Mills                                              std::move(callback));
214542cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit";
214642cbe538SGunnar Mills                 };
214742cbe538SGunnar Mills 
2148d500549bSAnthony Wilson                 // Find led connections and get the data
2149d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
215042cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
2151d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit";
2152d500549bSAnthony Wilson             };
21538fb49dd6SShawn McCarney 
2154adc4f0dbSShawn McCarney             // Get inventory item data from connections
2155adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2156d0090733SEd Tanous                                   invConnections,
2157d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
21588fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit";
21598fb49dd6SShawn McCarney         };
21608fb49dd6SShawn McCarney 
2161adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2162002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21638fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
2164adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit";
21658fb49dd6SShawn McCarney     };
21668fb49dd6SShawn McCarney 
2167adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2168d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2169adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
2170adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems exit";
2171adc4f0dbSShawn McCarney }
2172adc4f0dbSShawn McCarney 
2173adc4f0dbSShawn McCarney /**
2174adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2175adc4f0dbSShawn McCarney  *
2176adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2177adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2178adc4f0dbSShawn McCarney  * array.
2179adc4f0dbSShawn McCarney  *
2180adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2181adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2182adc4f0dbSShawn McCarney  * object.
2183adc4f0dbSShawn McCarney  *
2184adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2185adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2186adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2187adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2188adc4f0dbSShawn McCarney  */
218923a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2190adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2191adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2192adc4f0dbSShawn McCarney {
2193adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2194adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2195adc4f0dbSShawn McCarney     {
2196f7afb17bSAlexander Hansen         if (powerSupply["Name"] ==
2197f7afb17bSAlexander Hansen             boost::replace_all_copy(inventoryItem.name, "_", " "))
2198adc4f0dbSShawn McCarney         {
2199adc4f0dbSShawn McCarney             return powerSupply;
2200adc4f0dbSShawn McCarney         }
2201adc4f0dbSShawn McCarney     }
2202adc4f0dbSShawn McCarney 
2203adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2204adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2205adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2206ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2207ef4c65b7SEd Tanous                                                chassisId);
2208eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2209eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
2210adc4f0dbSShawn McCarney     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2211adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2212adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2213adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2214adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2215d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2216adc4f0dbSShawn McCarney 
221742cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
221842cbe538SGunnar Mills     {
221942cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
222042cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
222142cbe538SGunnar Mills     }
222242cbe538SGunnar Mills 
222342cbe538SGunnar Mills     powerSupply["Status"]["State"] = getState(&inventoryItem);
2224adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2225adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2226adc4f0dbSShawn McCarney 
2227adc4f0dbSShawn McCarney     return powerSupply;
22288fb49dd6SShawn McCarney }
22298fb49dd6SShawn McCarney 
22308fb49dd6SShawn McCarney /**
2231de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2232de629b6eSShawn McCarney  *
2233de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2234de629b6eSShawn McCarney  *
2235de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2236de629b6eSShawn McCarney  * information has been obtained.
2237de629b6eSShawn McCarney  *
2238adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2239de629b6eSShawn McCarney  *
2240de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2241de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2242de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2243de629b6eSShawn McCarney  *
2244de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2245de629b6eSShawn McCarney  *
2246adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2247adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2248adc4f0dbSShawn McCarney  *
2249de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2250adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2251de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2252de629b6eSShawn McCarney  * implements ObjectManager.
2253adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2254de629b6eSShawn McCarney  */
225523a21a1cSEd Tanous inline void getSensorData(
225681ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2257fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2258fe04d49cSNan Zhou     const std::set<std::string>& connections,
2259b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2260de629b6eSShawn McCarney {
2261de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData enter";
2262de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2263de629b6eSShawn McCarney     for (const std::string& connection : connections)
2264de629b6eSShawn McCarney     {
22655eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
22665eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
22675eb468daSGeorge Liu         dbus::utility::getManagedObjects(
22685eb468daSGeorge Liu             connection, sensorPath,
2269002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
22705e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
227102cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
2272de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
2273de629b6eSShawn McCarney             if (ec)
2274de629b6eSShawn McCarney             {
2275de629b6eSShawn McCarney                 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
22768d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2277de629b6eSShawn McCarney                 return;
2278de629b6eSShawn McCarney             }
2279de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2280de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2281de629b6eSShawn McCarney             {
2282de629b6eSShawn McCarney                 const std::string& objPath =
2283de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
2284de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
2285de629b6eSShawn McCarney                                  << objPath;
2286de629b6eSShawn McCarney 
2287de629b6eSShawn McCarney                 std::vector<std::string> split;
2288de629b6eSShawn McCarney                 // Reserve space for
2289de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2290de629b6eSShawn McCarney                 split.reserve(6);
229150ebd4afSEd Tanous                 // NOLINTNEXTLINE
229250ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2293de629b6eSShawn McCarney                 if (split.size() < 6)
2294de629b6eSShawn McCarney                 {
2295de629b6eSShawn McCarney                     BMCWEB_LOG_ERROR << "Got path that isn't long enough "
2296de629b6eSShawn McCarney                                      << objPath;
2297de629b6eSShawn McCarney                     continue;
2298de629b6eSShawn McCarney                 }
229950ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2300de629b6eSShawn McCarney                 // string at the beginning
2301de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2302de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
2303de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "sensorName " << sensorName
2304de629b6eSShawn McCarney                                  << " sensorType " << sensorType;
230549c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2306de629b6eSShawn McCarney                 {
2307accdbb2cSAndrew Geissler                     BMCWEB_LOG_DEBUG << sensorName << " not in sensor list ";
2308de629b6eSShawn McCarney                     continue;
2309de629b6eSShawn McCarney                 }
2310de629b6eSShawn McCarney 
2311adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2312adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2313adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2314adc4f0dbSShawn McCarney 
231595a3ecadSAnthony Wilson                 const std::string& sensorSchema =
231681ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
231795a3ecadSAnthony Wilson 
231895a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
231995a3ecadSAnthony Wilson 
2320928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2321928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
232295a3ecadSAnthony Wilson                 {
2323c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
2324c1d019a6SEd Tanous                     sensorTypeEscaped.erase(
2325c1d019a6SEd Tanous                         std::remove(sensorTypeEscaped.begin(),
2326c1d019a6SEd Tanous                                     sensorTypeEscaped.end(), '_'),
2327c1d019a6SEd Tanous                         sensorTypeEscaped.end());
2328c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2329c1d019a6SEd Tanous                     sensorId += "_";
2330c1d019a6SEd Tanous                     sensorId += sensorName;
2331c1d019a6SEd Tanous 
23328d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2333ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2334c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2335ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2336ef4c65b7SEd Tanous                                             sensorId);
23378d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
233895a3ecadSAnthony Wilson                 }
233995a3ecadSAnthony Wilson                 else
234095a3ecadSAnthony Wilson                 {
2341271584abSEd Tanous                     std::string fieldName;
2342928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2343928fefb9SNan Zhou                     {
2344928fefb9SNan Zhou                         fieldName = "Members";
2345928fefb9SNan Zhou                     }
2346928fefb9SNan Zhou                     else if (sensorType == "temperature")
2347de629b6eSShawn McCarney                     {
2348de629b6eSShawn McCarney                         fieldName = "Temperatures";
2349de629b6eSShawn McCarney                     }
2350de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2351de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2352de629b6eSShawn McCarney                     {
2353de629b6eSShawn McCarney                         fieldName = "Fans";
2354de629b6eSShawn McCarney                     }
2355de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2356de629b6eSShawn McCarney                     {
2357de629b6eSShawn McCarney                         fieldName = "Voltages";
2358de629b6eSShawn McCarney                     }
2359de629b6eSShawn McCarney                     else if (sensorType == "power")
2360de629b6eSShawn McCarney                     {
236155f79e6fSEd Tanous                         if (sensorName == "total_power")
2362028f7ebcSEddie James                         {
2363028f7ebcSEddie James                             fieldName = "PowerControl";
2364028f7ebcSEddie James                         }
2365adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2366adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2367028f7ebcSEddie James                         {
2368de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2369de629b6eSShawn McCarney                         }
2370adc4f0dbSShawn McCarney                         else
2371adc4f0dbSShawn McCarney                         {
2372adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2373adc4f0dbSShawn McCarney                             continue;
2374adc4f0dbSShawn McCarney                         }
2375028f7ebcSEddie James                     }
2376de629b6eSShawn McCarney                     else
2377de629b6eSShawn McCarney                     {
2378de629b6eSShawn McCarney                         BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
2379de629b6eSShawn McCarney                                          << sensorType;
2380de629b6eSShawn McCarney                         continue;
2381de629b6eSShawn McCarney                     }
2382de629b6eSShawn McCarney 
2383de629b6eSShawn McCarney                     nlohmann::json& tempArray =
23848d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2385adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
238649c53ac9SJohnathan Mantey                     {
2387adc4f0dbSShawn McCarney                         if (tempArray.empty())
23887ab06f49SGunnar Mills                         {
238995a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
239095a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
239195a3ecadSAnthony Wilson                             // naming in power.hpp.
23921476687dSEd Tanous                             nlohmann::json::object_t power;
2393ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2394ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2395eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2396eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2397eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2398eddfc437SWilly Tu                                                  .to_string());
2399eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2400b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2401adc4f0dbSShawn McCarney                         }
2402adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2403adc4f0dbSShawn McCarney                     }
2404adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2405adc4f0dbSShawn McCarney                     {
2406adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2407adc4f0dbSShawn McCarney                         {
2408adc4f0dbSShawn McCarney                             sensorJson =
2409adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
241081ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2411adc4f0dbSShawn McCarney                         }
241249c53ac9SJohnathan Mantey                     }
2413928fefb9SNan Zhou                     else if (fieldName == "Members")
2414928fefb9SNan Zhou                     {
2415677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
2416677bb756SEd Tanous                         sensorTypeEscaped.erase(
2417677bb756SEd Tanous                             std::remove(sensorTypeEscaped.begin(),
2418677bb756SEd Tanous                                         sensorTypeEscaped.end(), '_'),
2419677bb756SEd Tanous                             sensorTypeEscaped.end());
2420677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2421677bb756SEd Tanous                         sensorId += "_";
2422677bb756SEd Tanous                         sensorId += sensorName;
2423677bb756SEd Tanous 
24241476687dSEd Tanous                         nlohmann::json::object_t member;
2425ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2426ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2427677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2428677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2429b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2430928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2431928fefb9SNan Zhou                     }
243249c53ac9SJohnathan Mantey                     else
243349c53ac9SJohnathan Mantey                     {
24341476687dSEd Tanous                         nlohmann::json::object_t member;
2435ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2436ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2437eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2438eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2439eddfc437SWilly Tu                         url.set_fragment(
2440eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2441eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2442b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2443adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
244449c53ac9SJohnathan Mantey                     }
244595a3ecadSAnthony Wilson                 }
2446de629b6eSShawn McCarney 
2447adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2448adc4f0dbSShawn McCarney                 {
24491d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24501d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24511d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24521d7c0054SEd Tanous                                            inventoryItem);
24531d7c0054SEd Tanous 
24541d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24551d7c0054SEd Tanous                     path += sensorType;
24561d7c0054SEd Tanous                     path += "/";
24571d7c0054SEd Tanous                     path += sensorName;
2458c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2459adc4f0dbSShawn McCarney                 }
2460de629b6eSShawn McCarney             }
246181ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
246249c53ac9SJohnathan Mantey             {
246381ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2464928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2465928fefb9SNan Zhou                         sensors::node::sensors &&
2466928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2467928fefb9SNan Zhou                 {
2468928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2469928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2470928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2471928fefb9SNan Zhou                             .size();
2472928fefb9SNan Zhou                 }
2473928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2474928fefb9SNan Zhou                          sensors::node::thermal)
24758bd25ccdSJames Feist                 {
247681ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
24778bd25ccdSJames Feist                 }
247849c53ac9SJohnathan Mantey             }
2479de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
24805eb468daSGeorge Liu             });
248123a21a1cSEd Tanous     }
2482de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData exit";
2483de629b6eSShawn McCarney }
2484de629b6eSShawn McCarney 
2485fe04d49cSNan Zhou inline void
2486fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2487fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
24881abe55efSEd Tanous {
2489fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2490fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
249155c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb enter";
2492adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2493d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2494d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2495adc4f0dbSShawn McCarney                               inventoryItems) {
2496adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter";
249749c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2498002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2499d0090733SEd Tanous                           inventoryItems);
2500adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit";
2501adc4f0dbSShawn McCarney         };
2502adc4f0dbSShawn McCarney 
2503adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2504d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2505adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2506adc4f0dbSShawn McCarney 
250755c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb exit";
250808777fb0SLewanczyk, Dawid     };
2509de629b6eSShawn McCarney 
2510de629b6eSShawn McCarney     // Get set of connections that provide sensor values
251181ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
251295a3ecadSAnthony Wilson }
251395a3ecadSAnthony Wilson 
251495a3ecadSAnthony Wilson /**
251595a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
251695a3ecadSAnthony Wilson  *        chassis.
251795a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
251895a3ecadSAnthony Wilson  */
2519b5a76932SEd Tanous inline void
252081ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
252195a3ecadSAnthony Wilson {
252295a3ecadSAnthony Wilson     BMCWEB_LOG_DEBUG << "getChassisData enter";
252395a3ecadSAnthony Wilson     auto getChassisCb =
252481ce609eSEd Tanous         [sensorsAsyncResp](
2525fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
252695a3ecadSAnthony Wilson         BMCWEB_LOG_DEBUG << "getChassisCb enter";
252781ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
252855c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassisCb exit";
252908777fb0SLewanczyk, Dawid     };
2530928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2531928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2532928fefb9SNan Zhou     {
25338d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25348d1b46d7Szhanghch05             nlohmann::json::array();
2535928fefb9SNan Zhou     }
253626f03899SShawn McCarney     // Get set of sensors in chassis
25377f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25387f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25397f1cc26dSEd Tanous                std::move(getChassisCb));
254055c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassisData exit";
2541271584abSEd Tanous }
254208777fb0SLewanczyk, Dawid 
2543413961deSRichard Marian Thomaiyar /**
254449c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
254549c53ac9SJohnathan Mantey  * the chassis node
254649c53ac9SJohnathan Mantey  *
254749c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
254849c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
254949c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
255049c53ac9SJohnathan Mantey  *                         repeated calls to this function
255149c53ac9SJohnathan Mantey  */
2552fe04d49cSNan Zhou inline bool
2553fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
255402cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2555fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
255649c53ac9SJohnathan Mantey {
2557fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
255849c53ac9SJohnathan Mantey     {
255928aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2560b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
256128aa8de5SGeorge Liu         if (thisSensorName.empty())
256249c53ac9SJohnathan Mantey         {
256349c53ac9SJohnathan Mantey             continue;
256449c53ac9SJohnathan Mantey         }
256549c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
256649c53ac9SJohnathan Mantey         {
256749c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
256849c53ac9SJohnathan Mantey             return true;
256949c53ac9SJohnathan Mantey         }
257049c53ac9SJohnathan Mantey     }
257149c53ac9SJohnathan Mantey     return false;
257249c53ac9SJohnathan Mantey }
257349c53ac9SJohnathan Mantey 
2574c71d6125SEd Tanous inline std::pair<std::string, std::string>
2575c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2576c71d6125SEd Tanous {
2577c71d6125SEd Tanous     size_t index = sensorId.find('_');
2578c71d6125SEd Tanous     if (index == std::string::npos)
2579c71d6125SEd Tanous     {
2580c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2581c71d6125SEd Tanous     }
2582c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2583c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2584c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2585c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2586c71d6125SEd Tanous     {
2587c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2588c71d6125SEd Tanous     }
2589c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2590c71d6125SEd Tanous }
2591c71d6125SEd Tanous 
259249c53ac9SJohnathan Mantey /**
2593413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2594413961deSRichard Marian Thomaiyar  *
25958d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
25964bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2597413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2598413961deSRichard Marian Thomaiyar  */
259923a21a1cSEd Tanous inline void setSensorsOverride(
2600b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26014bb3dc34SCarol Wang     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2602397fd61fSjayaprakash Mutyala         allCollections)
2603413961deSRichard Marian Thomaiyar {
260470d1d0aaSjayaprakash Mutyala     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
26054bb3dc34SCarol Wang                     << sensorAsyncResp->chassisSubNode << "\n";
2606413961deSRichard Marian Thomaiyar 
2607543f4400SEd Tanous     const char* propertyValueName = nullptr;
2608f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2609413961deSRichard Marian Thomaiyar     std::string memberId;
2610543f4400SEd Tanous     double value = 0.0;
2611f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2612f65af9e8SRichard Marian Thomaiyar     {
2613f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2614f65af9e8SRichard Marian Thomaiyar         {
2615f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2616f65af9e8SRichard Marian Thomaiyar         }
2617f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2618f65af9e8SRichard Marian Thomaiyar         {
2619f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2620f65af9e8SRichard Marian Thomaiyar         }
2621f65af9e8SRichard Marian Thomaiyar         else
2622f65af9e8SRichard Marian Thomaiyar         {
2623f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2624f65af9e8SRichard Marian Thomaiyar         }
2625f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2626f65af9e8SRichard Marian Thomaiyar         {
26278d1b46d7Szhanghch05             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
26288d1b46d7Szhanghch05                                      "MemberId", memberId, propertyValueName,
26298d1b46d7Szhanghch05                                      value))
2630413961deSRichard Marian Thomaiyar             {
2631413961deSRichard Marian Thomaiyar                 return;
2632413961deSRichard Marian Thomaiyar             }
2633f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2634f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2635f65af9e8SRichard Marian Thomaiyar         }
2636f65af9e8SRichard Marian Thomaiyar     }
26374bb3dc34SCarol Wang 
2638002d39b4SEd Tanous     auto getChassisSensorListCb =
2639002d39b4SEd Tanous         [sensorAsyncResp, overrideMap](
2640fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
264149c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
264249c53ac9SJohnathan Mantey         // chassis node
2643fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2644fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2645f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2646413961deSRichard Marian Thomaiyar         {
2647f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2648c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2649c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2650c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2651c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2652f65af9e8SRichard Marian Thomaiyar             {
2653f65af9e8SRichard Marian Thomaiyar                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
26548d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2655f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2656413961deSRichard Marian Thomaiyar                 return;
2657413961deSRichard Marian Thomaiyar             }
2658f65af9e8SRichard Marian Thomaiyar         }
2659413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2660002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2661fe04d49cSNan Zhou             [sensorAsyncResp,
2662fe04d49cSNan Zhou              overrideMap](const std::set<std::string>& /*connections*/,
2663002d39b4SEd Tanous                           const std::set<std::pair<std::string, std::string>>&
2664413961deSRichard Marian Thomaiyar                               objectsWithConnection) {
2665f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2666413961deSRichard Marian Thomaiyar             {
2667413961deSRichard Marian Thomaiyar                 BMCWEB_LOG_INFO
2668f65af9e8SRichard Marian Thomaiyar                     << "Unable to find all objects with proper connection "
2669f65af9e8SRichard Marian Thomaiyar                     << objectsWithConnection.size() << " requested "
2670f65af9e8SRichard Marian Thomaiyar                     << overrideMap.size() << "\n";
26714f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2672a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2673a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2674413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2675413961deSRichard Marian Thomaiyar                                                : "Voltages",
2676f65af9e8SRichard Marian Thomaiyar                                            "Count");
2677f65af9e8SRichard Marian Thomaiyar                 return;
2678f65af9e8SRichard Marian Thomaiyar             }
2679f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2680f65af9e8SRichard Marian Thomaiyar             {
268128aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
268228aa8de5SGeorge Liu                 std::string sensorName = path.filename();
268328aa8de5SGeorge Liu                 if (sensorName.empty())
2684f65af9e8SRichard Marian Thomaiyar                 {
26854f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2686f65af9e8SRichard Marian Thomaiyar                     return;
2687f65af9e8SRichard Marian Thomaiyar                 }
2688f65af9e8SRichard Marian Thomaiyar 
2689f65af9e8SRichard Marian Thomaiyar                 const auto& iterator = overrideMap.find(sensorName);
2690f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2691f65af9e8SRichard Marian Thomaiyar                 {
2692f65af9e8SRichard Marian Thomaiyar                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2693f65af9e8SRichard Marian Thomaiyar                                     << item.first << "\n";
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                         {
27074f277b54SJayaprakash Mutyala                             BMCWEB_LOG_WARNING
27084f277b54SJayaprakash Mutyala                                 << "Manufacturing mode is not Enabled...can't "
27094f277b54SJayaprakash Mutyala                                    "Override the sensor value. ";
27104f277b54SJayaprakash Mutyala 
27114f277b54SJayaprakash Mutyala                             messages::insufficientPrivilege(
27128d1b46d7Szhanghch05                                 sensorAsyncResp->asyncResp->res);
2713413961deSRichard Marian Thomaiyar                             return;
2714413961deSRichard Marian Thomaiyar                         }
27154f277b54SJayaprakash Mutyala                         BMCWEB_LOG_DEBUG
27164f277b54SJayaprakash Mutyala                             << "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     {
2754a0ec28b6SAdrian Ambrożewicz         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2755a0ec28b6SAdrian Ambrożewicz         mapComplete(boost::beast::http::status::bad_request, {});
2756a0ec28b6SAdrian Ambrożewicz         return;
2757a0ec28b6SAdrian Ambrożewicz     }
2758d51e072fSKrzysztof Grobelny 
275972374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2760fe04d49cSNan Zhou     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2761a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2762fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2763fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2764fe04d49cSNan Zhou     };
2765a0ec28b6SAdrian Ambrożewicz 
2766a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2767d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2768a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2769a0ec28b6SAdrian Ambrożewicz }
2770a0ec28b6SAdrian Ambrożewicz 
2771bacb2162SNan Zhou namespace sensors
2772bacb2162SNan Zhou {
2773928fefb9SNan Zhou 
2774bacb2162SNan Zhou inline void getChassisCallback(
2775c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2776c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2777fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2778bacb2162SNan Zhou {
2779bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2780bacb2162SNan Zhou 
2781c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2782c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2783bacb2162SNan Zhou     {
2784bacb2162SNan Zhou         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2785bacb2162SNan Zhou 
2786bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2787bacb2162SNan Zhou         std::string sensorName = path.filename();
2788bacb2162SNan Zhou         if (sensorName.empty())
2789bacb2162SNan Zhou         {
2790bacb2162SNan Zhou             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2791c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2792bacb2162SNan Zhou             return;
2793bacb2162SNan Zhou         }
2794c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2795c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2796c1d019a6SEd Tanous         // type in the URI
2797c1d019a6SEd Tanous         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2798c1d019a6SEd Tanous 
27991476687dSEd Tanous         nlohmann::json::object_t member;
2800c1d019a6SEd Tanous         std::string id = type;
2801c1d019a6SEd Tanous         id += "_";
2802c1d019a6SEd Tanous         id += sensorName;
2803ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2804ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2805c1d019a6SEd Tanous 
2806b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2807bacb2162SNan Zhou     }
2808bacb2162SNan Zhou 
2809c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2810bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2811bacb2162SNan Zhou }
2812e6bd846dSNan Zhou 
2813ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2814ac106bf6SEd Tanous     App& app, const crow::Request& req,
2815ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2816de167a6fSNan Zhou     const std::string& chassisId)
2817de167a6fSNan Zhou {
2818de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2819de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2820de167a6fSNan Zhou     };
2821de167a6fSNan Zhou     query_param::Query delegatedQuery;
2822ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2823de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2824de167a6fSNan Zhou     {
2825de167a6fSNan Zhou         return;
2826de167a6fSNan Zhou     }
2827de167a6fSNan Zhou 
2828de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2829de167a6fSNan Zhou     {
2830de167a6fSNan Zhou         // we perform efficient expand.
2831ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2832ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2833de167a6fSNan Zhou             sensors::node::sensors,
2834de167a6fSNan Zhou             /*efficientExpand=*/true);
2835ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2836de167a6fSNan Zhou 
2837de167a6fSNan Zhou         BMCWEB_LOG_DEBUG
2838de167a6fSNan Zhou             << "SensorCollection doGet exit via efficient expand handler";
2839de167a6fSNan Zhou         return;
28400bad320cSEd Tanous     }
2841de167a6fSNan Zhou 
2842de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2843de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2844ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2845ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2846ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2847c1d019a6SEd Tanous }
28487f1cc26dSEd Tanous 
2849c1d019a6SEd Tanous inline void
2850c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2851c1d019a6SEd Tanous                       const std::string& sensorPath,
2852c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2853c1d019a6SEd Tanous {
2854c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2855c1d019a6SEd Tanous     {
2856c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2857c1d019a6SEd Tanous         return;
2858c1d019a6SEd Tanous     }
2859c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2860c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
2861c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2862c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2863c1343bf6SKrzysztof Grobelny 
2864c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2865c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2866c1d019a6SEd Tanous         [asyncResp,
28675e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2868c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2869c1d019a6SEd Tanous         if (ec)
2870c1d019a6SEd Tanous         {
2871c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2872c1d019a6SEd Tanous             return;
2873c1d019a6SEd Tanous         }
2874c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2875c1d019a6SEd Tanous         std::string name = path.filename();
2876c1d019a6SEd Tanous         path = path.parent_path();
2877c1d019a6SEd Tanous         std::string type = path.filename();
2878c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2879c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2880c1343bf6SKrzysztof Grobelny         });
2881de167a6fSNan Zhou }
2882de167a6fSNan Zhou 
2883e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2884c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2885677bb756SEd Tanous                             const std::string& chassisId,
2886c1d019a6SEd Tanous                             const std::string& sensorId)
2887e6bd846dSNan Zhou {
2888c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2889e6bd846dSNan Zhou     {
2890e6bd846dSNan Zhou         return;
2891e6bd846dSNan Zhou     }
2892c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2893c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2894c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2895c1d019a6SEd Tanous     {
2896c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2897c1d019a6SEd Tanous         return;
2898c1d019a6SEd Tanous     }
2899c71d6125SEd Tanous 
2900ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2901ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2902c1d019a6SEd Tanous 
2903e6bd846dSNan Zhou     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
2904e6bd846dSNan Zhou 
29052b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2906e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2907c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2908c71d6125SEd Tanous                              '/' + nameType.second;
2909e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2910e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29112b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29122b73119cSGeorge Liu         sensorPath, interfaces,
2913aec0ec30SMyung Bae         [asyncResp, sensorId,
29142b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2915c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
2916e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 enter";
2917aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2918aec0ec30SMyung Bae         {
2919aec0ec30SMyung Bae             BMCWEB_LOG_WARNING << "Sensor not found from getSensorPaths";
2920aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2921aec0ec30SMyung Bae             return;
2922aec0ec30SMyung Bae         }
2923e6bd846dSNan Zhou         if (ec)
2924e6bd846dSNan Zhou         {
2925c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2926b90d14f2SMyung Bae             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
2927e6bd846dSNan Zhou                              << "Dbus error " << ec;
2928e6bd846dSNan Zhou             return;
2929e6bd846dSNan Zhou         }
2930c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
2931e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 exit";
29322b73119cSGeorge Liu         });
2933e6bd846dSNan Zhou }
2934e6bd846dSNan Zhou 
2935bacb2162SNan Zhou } // namespace sensors
2936bacb2162SNan Zhou 
29377e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
293895a3ecadSAnthony Wilson {
29397e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2940ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2941002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2942de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
294395a3ecadSAnthony Wilson }
294495a3ecadSAnthony Wilson 
29457e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
294695a3ecadSAnthony Wilson {
29477e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2948ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2949002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2950e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
295195a3ecadSAnthony Wilson }
295295a3ecadSAnthony Wilson 
295308777fb0SLewanczyk, Dawid } // namespace redfish
2954