xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision ef4c65b741724d724452a3a0efe8dff0d450514a)
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>
35*ef4c65b7SEd 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>
42fe04d49cSNan Zhou #include <map>
43fe04d49cSNan Zhou #include <set>
447a1dbc48SGeorge Liu #include <string_view>
45b5a76932SEd Tanous #include <utility>
46abf2add6SEd Tanous #include <variant>
4708777fb0SLewanczyk, Dawid 
481abe55efSEd Tanous namespace redfish
491abe55efSEd Tanous {
5008777fb0SLewanczyk, Dawid 
51a0ec28b6SAdrian Ambrożewicz namespace sensors
52a0ec28b6SAdrian Ambrożewicz {
53a0ec28b6SAdrian Ambrożewicz namespace node
54a0ec28b6SAdrian Ambrożewicz {
55a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
56a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
57a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
58a0ec28b6SAdrian Ambrożewicz } // namespace node
59a0ec28b6SAdrian Ambrożewicz 
6002da7c5aSEd Tanous // clang-format off
61a0ec28b6SAdrian Ambrożewicz namespace dbus
62a0ec28b6SAdrian Ambrożewicz {
63cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6402da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6602da7c5aSEd Tanous });
67c2bf7f99SWludzik, Jozef 
68cf9e417dSEd Tanous constexpr auto sensorPaths = std::to_array<std::string_view>({
6902da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
70a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
717088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
725deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
73e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
74e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
75e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
76e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
77e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
78e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
79e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
80e8204933SGeorge Liu #endif
8102da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
8202da7c5aSEd Tanous });
8302da7c5aSEd Tanous 
84cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
8502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
86a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
8802da7c5aSEd Tanous });
8902da7c5aSEd Tanous 
90c2bf7f99SWludzik, Jozef } // namespace dbus
9102da7c5aSEd Tanous // clang-format on
9202da7c5aSEd Tanous 
93cf9e417dSEd Tanous using sensorPair =
94cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
9502da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
96cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
97cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
98cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
99c2bf7f99SWludzik, Jozef 
1000ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
101c2bf7f99SWludzik, Jozef {
102c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
103c2bf7f99SWludzik, Jozef     {
1040ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
105c2bf7f99SWludzik, Jozef     }
106c2bf7f99SWludzik, Jozef     if (sensorType == "power")
107c2bf7f99SWludzik, Jozef     {
1080ec8b83dSEd Tanous         return sensor::ReadingType::Power;
109c2bf7f99SWludzik, Jozef     }
110c2bf7f99SWludzik, Jozef     if (sensorType == "current")
111c2bf7f99SWludzik, Jozef     {
1120ec8b83dSEd Tanous         return sensor::ReadingType::Current;
113c2bf7f99SWludzik, Jozef     }
114c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
115c2bf7f99SWludzik, Jozef     {
1160ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
117c2bf7f99SWludzik, Jozef     }
118c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
119c2bf7f99SWludzik, Jozef     {
1200ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
121c2bf7f99SWludzik, Jozef     }
122c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
123c2bf7f99SWludzik, Jozef     {
1240ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
125c2bf7f99SWludzik, Jozef     }
1265deabed9SGunnar Mills     if (sensorType == "humidity")
1275deabed9SGunnar Mills     {
1280ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1295deabed9SGunnar Mills     }
130c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
131c2bf7f99SWludzik, Jozef     {
1320ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
133c2bf7f99SWludzik, Jozef     }
134c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
135c2bf7f99SWludzik, Jozef     {
1360ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
137c2bf7f99SWludzik, Jozef     }
138c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
139c2bf7f99SWludzik, Jozef     {
1400ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
141c2bf7f99SWludzik, Jozef     }
1420ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
143c2bf7f99SWludzik, Jozef }
144c2bf7f99SWludzik, Jozef 
1451d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
146c2bf7f99SWludzik, Jozef {
147c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
148c2bf7f99SWludzik, Jozef     {
149c2bf7f99SWludzik, Jozef         return "V";
150c2bf7f99SWludzik, Jozef     }
151c2bf7f99SWludzik, Jozef     if (sensorType == "power")
152c2bf7f99SWludzik, Jozef     {
153c2bf7f99SWludzik, Jozef         return "W";
154c2bf7f99SWludzik, Jozef     }
155c2bf7f99SWludzik, Jozef     if (sensorType == "current")
156c2bf7f99SWludzik, Jozef     {
157c2bf7f99SWludzik, Jozef         return "A";
158c2bf7f99SWludzik, Jozef     }
159c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
160c2bf7f99SWludzik, Jozef     {
161c2bf7f99SWludzik, Jozef         return "RPM";
162c2bf7f99SWludzik, Jozef     }
163c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
164c2bf7f99SWludzik, Jozef     {
165c2bf7f99SWludzik, Jozef         return "Cel";
166c2bf7f99SWludzik, Jozef     }
1675deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1685deabed9SGunnar Mills         sensorType == "humidity")
169c2bf7f99SWludzik, Jozef     {
170c2bf7f99SWludzik, Jozef         return "%";
171c2bf7f99SWludzik, Jozef     }
172c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
173c2bf7f99SWludzik, Jozef     {
174c2bf7f99SWludzik, Jozef         return "m";
175c2bf7f99SWludzik, Jozef     }
176c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
177c2bf7f99SWludzik, Jozef     {
178c2bf7f99SWludzik, Jozef         return "cft_i/min";
179c2bf7f99SWludzik, Jozef     }
180c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
181c2bf7f99SWludzik, Jozef     {
182c2bf7f99SWludzik, Jozef         return "J";
183c2bf7f99SWludzik, Jozef     }
184c2bf7f99SWludzik, Jozef     return "";
185a0ec28b6SAdrian Ambrożewicz }
186a0ec28b6SAdrian Ambrożewicz } // namespace sensors
187a0ec28b6SAdrian Ambrożewicz 
18808777fb0SLewanczyk, Dawid /**
189588c3f0dSKowalski, Kamil  * SensorsAsyncResp
19008777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
19108777fb0SLewanczyk, Dawid  */
1921abe55efSEd Tanous class SensorsAsyncResp
1931abe55efSEd Tanous {
19408777fb0SLewanczyk, Dawid   public:
195a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
196a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
197fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
198a0ec28b6SAdrian Ambrożewicz 
199a0ec28b6SAdrian Ambrożewicz     struct SensorData
200a0ec28b6SAdrian Ambrożewicz     {
201a0ec28b6SAdrian Ambrożewicz         const std::string name;
202a0ec28b6SAdrian Ambrożewicz         std::string uri;
203a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
204a0ec28b6SAdrian Ambrożewicz     };
205a0ec28b6SAdrian Ambrożewicz 
2068a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2078d1b46d7Szhanghch05                      const std::string& chassisIdIn,
208cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
20902da7c5aSEd Tanous                      std::string_view subNode) :
2108a592810SEd Tanous         asyncResp(asyncRespIn),
211928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
212928fefb9SNan Zhou         efficientExpand(false)
2131214b7e7SGunnar Mills     {}
21408777fb0SLewanczyk, Dawid 
215a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2168a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2178d1b46d7Szhanghch05                      const std::string& chassisIdIn,
218cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21902da7c5aSEd Tanous                      std::string_view subNode,
220a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2218a592810SEd Tanous         asyncResp(asyncRespIn),
222928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
223928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
224a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
225a0ec28b6SAdrian Ambrożewicz     {}
226a0ec28b6SAdrian Ambrożewicz 
227928fefb9SNan Zhou     // sensor collections expand
2288a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
229928fefb9SNan Zhou                      const std::string& chassisIdIn,
230cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2318a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2328a592810SEd Tanous         asyncResp(asyncRespIn),
233928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2348a592810SEd Tanous         efficientExpand(efficientExpandIn)
235928fefb9SNan Zhou     {}
236928fefb9SNan Zhou 
2371abe55efSEd Tanous     ~SensorsAsyncResp()
2381abe55efSEd Tanous     {
2398d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2408d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2411abe55efSEd Tanous         {
2421abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2431abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2441abe55efSEd Tanous             // proper code
2458d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24608777fb0SLewanczyk, Dawid         }
247a0ec28b6SAdrian Ambrożewicz 
248a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
249a0ec28b6SAdrian Ambrożewicz         {
250fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2518d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
252a0ec28b6SAdrian Ambrożewicz             {
253a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
254a0ec28b6SAdrian Ambrożewicz                 {
255c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
256a0ec28b6SAdrian Ambrożewicz                 }
257a0ec28b6SAdrian Ambrożewicz             }
2588d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
259a0ec28b6SAdrian Ambrożewicz         }
26008777fb0SLewanczyk, Dawid     }
261588c3f0dSKowalski, Kamil 
262ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
263ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
264ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
265ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
266ecd6a3a2SEd Tanous 
267a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
268c1d019a6SEd Tanous                      const std::string& dbusPath)
269a0ec28b6SAdrian Ambrożewicz     {
270a0ec28b6SAdrian Ambrożewicz         if (metadata)
271a0ec28b6SAdrian Ambrożewicz         {
272c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
273c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
274a0ec28b6SAdrian Ambrożewicz         }
275a0ec28b6SAdrian Ambrożewicz     }
276a0ec28b6SAdrian Ambrożewicz 
277a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
278a0ec28b6SAdrian Ambrożewicz     {
279a0ec28b6SAdrian Ambrożewicz         if (metadata)
280a0ec28b6SAdrian Ambrożewicz         {
281a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
282a0ec28b6SAdrian Ambrożewicz             {
283a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
284a0ec28b6SAdrian Ambrożewicz                 {
285a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
286a0ec28b6SAdrian Ambrożewicz                 }
287a0ec28b6SAdrian Ambrożewicz             }
288a0ec28b6SAdrian Ambrożewicz         }
289a0ec28b6SAdrian Ambrożewicz     }
290a0ec28b6SAdrian Ambrożewicz 
2918d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
292a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
293cf9e417dSEd Tanous     const std::span<const std::string_view> types;
294a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
295928fefb9SNan Zhou     const bool efficientExpand;
296a0ec28b6SAdrian Ambrożewicz 
297a0ec28b6SAdrian Ambrożewicz   private:
298a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
299a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
30008777fb0SLewanczyk, Dawid };
30108777fb0SLewanczyk, Dawid 
30208777fb0SLewanczyk, Dawid /**
303d500549bSAnthony Wilson  * Possible states for physical inventory leds
304d500549bSAnthony Wilson  */
305d500549bSAnthony Wilson enum class LedState
306d500549bSAnthony Wilson {
307d500549bSAnthony Wilson     OFF,
308d500549bSAnthony Wilson     ON,
309d500549bSAnthony Wilson     BLINK,
310d500549bSAnthony Wilson     UNKNOWN
311d500549bSAnthony Wilson };
312d500549bSAnthony Wilson 
313d500549bSAnthony Wilson /**
314adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
315adc4f0dbSShawn McCarney  */
316adc4f0dbSShawn McCarney class InventoryItem
317adc4f0dbSShawn McCarney {
318adc4f0dbSShawn McCarney   public:
3194e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
320adc4f0dbSShawn McCarney     {
321adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
32228aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
32328aa8de5SGeorge Liu         name = path.filename();
32428aa8de5SGeorge Liu         if (name.empty())
325adc4f0dbSShawn McCarney         {
32628aa8de5SGeorge Liu             BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath;
327adc4f0dbSShawn McCarney         }
328adc4f0dbSShawn McCarney     }
329adc4f0dbSShawn McCarney 
330adc4f0dbSShawn McCarney     std::string objectPath;
331adc4f0dbSShawn McCarney     std::string name;
332e05aec50SEd Tanous     bool isPresent = true;
333e05aec50SEd Tanous     bool isFunctional = true;
334e05aec50SEd Tanous     bool isPowerSupply = false;
335e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
336adc4f0dbSShawn McCarney     std::string manufacturer;
337adc4f0dbSShawn McCarney     std::string model;
338adc4f0dbSShawn McCarney     std::string partNumber;
339adc4f0dbSShawn McCarney     std::string serialNumber;
340adc4f0dbSShawn McCarney     std::set<std::string> sensors;
341d500549bSAnthony Wilson     std::string ledObjectPath;
342e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
343adc4f0dbSShawn McCarney };
344adc4f0dbSShawn McCarney 
345adc4f0dbSShawn McCarney /**
346413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
347588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
34808777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
34908777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
35008777fb0SLewanczyk, Dawid  */
35108777fb0SLewanczyk, Dawid template <typename Callback>
352413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
35381ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
354fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3551abe55efSEd Tanous     Callback&& callback)
3561abe55efSEd Tanous {
357413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter";
35803b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
359e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
36008777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
36108777fb0SLewanczyk, Dawid 
362e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
363e99073f5SGeorge Liu     dbus::utility::getSubTree(
364e99073f5SGeorge Liu         path, 2, interfaces,
365002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
366e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
367002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
368e99073f5SGeorge Liu         // Response handler for parsing objects subtree
369413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter";
3701abe55efSEd Tanous         if (ec)
3711abe55efSEd Tanous         {
3728d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
373413961deSRichard Marian Thomaiyar             BMCWEB_LOG_ERROR
374413961deSRichard Marian Thomaiyar                 << "getObjectsWithConnection resp_handler: Dbus error " << ec;
37508777fb0SLewanczyk, Dawid             return;
37608777fb0SLewanczyk, Dawid         }
37708777fb0SLewanczyk, Dawid 
37855c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
37908777fb0SLewanczyk, Dawid 
38008777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
38108777fb0SLewanczyk, Dawid         // found in the chassis
382fe04d49cSNan Zhou         std::set<std::string> connections;
383413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
38408777fb0SLewanczyk, Dawid 
38549c53ac9SJohnathan Mantey         BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size();
38649c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3871abe55efSEd Tanous         {
38855c7b7a2SEd Tanous             BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
38908777fb0SLewanczyk, Dawid         }
39008777fb0SLewanczyk, Dawid 
39108777fb0SLewanczyk, Dawid         for (const std::pair<
39208777fb0SLewanczyk, Dawid                  std::string,
39308777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3941abe55efSEd Tanous                  object : subtree)
3951abe55efSEd Tanous         {
39649c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3971abe55efSEd Tanous             {
39849c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
3991abe55efSEd Tanous                          objData : object.second)
4001abe55efSEd Tanous                 {
40149c53ac9SJohnathan Mantey                     BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
40208777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
403de629b6eSShawn McCarney                     objectsWithConnection.insert(
404de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
40508777fb0SLewanczyk, Dawid                 }
40608777fb0SLewanczyk, Dawid             }
40708777fb0SLewanczyk, Dawid         }
40855c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
409413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
410413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit";
411e99073f5SGeorge Liu         });
412413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit";
413413961deSRichard Marian Thomaiyar }
414413961deSRichard Marian Thomaiyar 
415413961deSRichard Marian Thomaiyar /**
416413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
417413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
418413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
419413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
420413961deSRichard Marian Thomaiyar  */
421413961deSRichard Marian Thomaiyar template <typename Callback>
422fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
423fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
424413961deSRichard Marian Thomaiyar                     Callback&& callback)
425413961deSRichard Marian Thomaiyar {
426413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
427fe04d49cSNan Zhou         [callback](const std::set<std::string>& connections,
428413961deSRichard Marian Thomaiyar                    const std::set<std::pair<std::string, std::string>>&
4293174e4dfSEd Tanous                    /*objectsWithConnection*/) { callback(connections); };
43081ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
431413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
43208777fb0SLewanczyk, Dawid }
43308777fb0SLewanczyk, Dawid 
43408777fb0SLewanczyk, Dawid /**
43549c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
43649c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
43749c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
43849c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
43949c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
44049c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
44149c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
44249c53ac9SJohnathan Mantey  */
44323a21a1cSEd Tanous inline void reduceSensorList(
4447f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
445cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
44649c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
447fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
44849c53ac9SJohnathan Mantey {
44949c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
45049c53ac9SJohnathan Mantey     {
4517f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4527f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
453a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
45449c53ac9SJohnathan Mantey                                        : "Voltages");
45549c53ac9SJohnathan Mantey 
45649c53ac9SJohnathan Mantey         return;
45749c53ac9SJohnathan Mantey     }
45849c53ac9SJohnathan Mantey     if (allSensors->empty())
45949c53ac9SJohnathan Mantey     {
46049c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
46149c53ac9SJohnathan Mantey         return;
46249c53ac9SJohnathan Mantey     }
46349c53ac9SJohnathan Mantey 
4647f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
46549c53ac9SJohnathan Mantey     {
46649c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
46749c53ac9SJohnathan Mantey         {
46811ba3979SEd Tanous             if (sensor.starts_with(type))
46949c53ac9SJohnathan Mantey             {
47049c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
47149c53ac9SJohnathan Mantey             }
47249c53ac9SJohnathan Mantey         }
47349c53ac9SJohnathan Mantey     }
47449c53ac9SJohnathan Mantey }
47549c53ac9SJohnathan Mantey 
4767f1cc26dSEd Tanous /*
4777f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4787f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4797f1cc26dSEd Tanous  *
4807f1cc26dSEd Tanous  * */
4817f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4827f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4837f1cc26dSEd Tanous {
4847f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4857f1cc26dSEd Tanous     {
4867f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4877f1cc26dSEd Tanous     }
4887f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4897f1cc26dSEd Tanous     {
4907f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
4917f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
4927f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
4937f1cc26dSEd Tanous     }
4947f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
4957f1cc26dSEd Tanous     {
4967f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
4977f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
4987f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
4997f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5007f1cc26dSEd Tanous     }
5017f1cc26dSEd Tanous 
5027f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5037f1cc26dSEd Tanous     {
5047f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5057f1cc26dSEd Tanous     }
5067f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5077f1cc26dSEd Tanous }
5087f1cc26dSEd Tanous 
50949c53ac9SJohnathan Mantey /**
51008777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
511588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
51208777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
51308777fb0SLewanczyk, Dawid  */
51408777fb0SLewanczyk, Dawid template <typename Callback>
5157f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5167f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
517cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
518cf9e417dSEd Tanous                 Callback&& callback)
5191abe55efSEd Tanous {
52055c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis enter";
5217a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
52249c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
523adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5247a1dbc48SGeorge Liu 
5257a1dbc48SGeorge Liu     // Get the Chassis Collection
5267a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5277a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5287f1cc26dSEd Tanous         [callback{std::forward<Callback>(callback)}, asyncResp,
5297f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5307f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5317a1dbc48SGeorge Liu             const boost::system::error_code& ec,
532002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
53355c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
5341abe55efSEd Tanous         if (ec)
5351abe55efSEd Tanous         {
53655c7b7a2SEd Tanous             BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
5377f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
53808777fb0SLewanczyk, Dawid             return;
53908777fb0SLewanczyk, Dawid         }
54049c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
54149c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5421abe55efSEd Tanous         {
54328aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
544f8fe53e7SEd Tanous             std::string chassisName = path.filename();
54528aa8de5SGeorge Liu             if (chassisName.empty())
5461abe55efSEd Tanous             {
54749c53ac9SJohnathan Mantey                 BMCWEB_LOG_ERROR << "Failed to find '/' in " << chassis;
548daf36e2eSEd Tanous                 continue;
549daf36e2eSEd Tanous             }
5507f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5511abe55efSEd Tanous             {
55249c53ac9SJohnathan Mantey                 chassisPath = &chassis;
55349c53ac9SJohnathan Mantey                 break;
554daf36e2eSEd Tanous             }
55549c53ac9SJohnathan Mantey         }
55649c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5571abe55efSEd Tanous         {
5587f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
55949c53ac9SJohnathan Mantey             return;
5601abe55efSEd Tanous         }
5617f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
56208777fb0SLewanczyk, Dawid 
563*ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
564*ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
56595a3ecadSAnthony Wilson 
5668fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5678fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5686c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5696c3e9451SGeorge Liu             sensorPath,
5707f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
571f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
572271584abSEd Tanous                 const boost::system::error_code& e,
5736c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
574271584abSEd Tanous             if (e)
57549c53ac9SJohnathan Mantey             {
576271584abSEd Tanous                 if (e.value() != EBADR)
57749c53ac9SJohnathan Mantey                 {
5787f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
57949c53ac9SJohnathan Mantey                     return;
58049c53ac9SJohnathan Mantey                 }
58149c53ac9SJohnathan Mantey             }
582fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
583fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5847f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5857f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
5867f1cc26dSEd Tanous             BMCWEB_LOG_DEBUG << "Finishing with " << culledSensorList->size();
58749c53ac9SJohnathan Mantey             callback(culledSensorList);
5881e1e598dSJonathan Doman             });
5897a1dbc48SGeorge Liu         });
59055c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis exit";
59108777fb0SLewanczyk, Dawid }
59208777fb0SLewanczyk, Dawid 
59308777fb0SLewanczyk, Dawid /**
594adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
595adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
596adc4f0dbSShawn McCarney  * @return State value for inventory item.
59734dd179eSJames Feist  */
59823a21a1cSEd Tanous inline std::string getState(const InventoryItem* inventoryItem)
599adc4f0dbSShawn McCarney {
600adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
601adc4f0dbSShawn McCarney     {
602adc4f0dbSShawn McCarney         return "Absent";
603adc4f0dbSShawn McCarney     }
60434dd179eSJames Feist 
605adc4f0dbSShawn McCarney     return "Enabled";
606adc4f0dbSShawn McCarney }
607adc4f0dbSShawn McCarney 
608adc4f0dbSShawn McCarney /**
609adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
610adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6111d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
612adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
613adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
614adc4f0dbSShawn McCarney  * @return Health value for sensor.
615adc4f0dbSShawn McCarney  */
6161d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6171d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
618adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
61934dd179eSJames Feist {
620adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
621adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
622adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
623adc4f0dbSShawn McCarney     std::string currentHealth;
624adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
625adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
626adc4f0dbSShawn McCarney     {
627adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
628adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
629adc4f0dbSShawn McCarney         {
630adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
631adc4f0dbSShawn McCarney             if (health != nullptr)
632adc4f0dbSShawn McCarney             {
633adc4f0dbSShawn McCarney                 currentHealth = *health;
634adc4f0dbSShawn McCarney             }
635adc4f0dbSShawn McCarney         }
636adc4f0dbSShawn McCarney     }
637adc4f0dbSShawn McCarney 
638adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
639adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
640adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
641adc4f0dbSShawn McCarney     {
642adc4f0dbSShawn McCarney         return "Critical";
643adc4f0dbSShawn McCarney     }
644adc4f0dbSShawn McCarney 
645c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
646c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
647c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
648c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
649711ac7a9SEd Tanous 
650c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
651c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
652c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
653c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
654c1343bf6SKrzysztof Grobelny         warningAlarmLow);
655c1343bf6SKrzysztof Grobelny 
656c1343bf6SKrzysztof Grobelny     if (success)
65734dd179eSJames Feist     {
658c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
659c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
660c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
66134dd179eSJames Feist         {
66234dd179eSJames Feist             return "Critical";
66334dd179eSJames Feist         }
66434dd179eSJames Feist     }
66534dd179eSJames Feist 
666adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
667adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
668adc4f0dbSShawn McCarney     {
669adc4f0dbSShawn McCarney         return "Critical";
670adc4f0dbSShawn McCarney     }
671adc4f0dbSShawn McCarney 
672adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
673adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
674adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
675adc4f0dbSShawn McCarney     {
676adc4f0dbSShawn McCarney         return "Warning";
677adc4f0dbSShawn McCarney     }
678adc4f0dbSShawn McCarney 
679c1343bf6SKrzysztof Grobelny     if (success)
680c1343bf6SKrzysztof Grobelny     {
681adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
682c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
683c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
68434dd179eSJames Feist         {
685ebe4d91eSEd Tanous             return "Warning";
68634dd179eSJames Feist         }
68734dd179eSJames Feist     }
688adc4f0dbSShawn McCarney 
68934dd179eSJames Feist     return "OK";
69034dd179eSJames Feist }
69134dd179eSJames Feist 
69223a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
693d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
694d500549bSAnthony Wilson {
695d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
696d500549bSAnthony Wilson     {
697d500549bSAnthony Wilson         switch (inventoryItem->ledState)
698d500549bSAnthony Wilson         {
699d500549bSAnthony Wilson             case LedState::OFF:
700d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
701d500549bSAnthony Wilson                 break;
702d500549bSAnthony Wilson             case LedState::ON:
703d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
704d500549bSAnthony Wilson                 break;
705d500549bSAnthony Wilson             case LedState::BLINK:
706d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
707d500549bSAnthony Wilson                 break;
70823a21a1cSEd Tanous             case LedState::UNKNOWN:
709d500549bSAnthony Wilson                 break;
710d500549bSAnthony Wilson         }
711d500549bSAnthony Wilson     }
712d500549bSAnthony Wilson }
713d500549bSAnthony Wilson 
71434dd179eSJames Feist /**
71508777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
71608777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
717274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
71808777fb0SLewanczyk, Dawid  * build
7191d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
7201d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7211d7c0054SEd Tanous  * from.
7221d7c0054SEd Tanous  * @param sensorJson  The json object to fill
723adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
724adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
72508777fb0SLewanczyk, Dawid  */
7261d7c0054SEd Tanous inline void objectPropertiesToJson(
7271d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7281d7c0054SEd Tanous     std::string_view chassisSubNode,
7291d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
73081ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7311abe55efSEd Tanous {
7321d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
733adc4f0dbSShawn McCarney     {
734c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
735c1d019a6SEd Tanous         subNodeEscaped.erase(
736c1d019a6SEd Tanous             std::remove(subNodeEscaped.begin(), subNodeEscaped.end(), '_'),
737c1d019a6SEd Tanous             subNodeEscaped.end());
738c1d019a6SEd Tanous 
739c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
740c1d019a6SEd Tanous         // including power sensors.
741c1d019a6SEd Tanous         subNodeEscaped += '_';
742c1d019a6SEd Tanous         subNodeEscaped += sensorName;
743c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
744c1d019a6SEd Tanous 
7451d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7461d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7471d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
74895a3ecadSAnthony Wilson     }
74995a3ecadSAnthony Wilson     else if (sensorType != "power")
75095a3ecadSAnthony Wilson     {
75195a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
75295a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
75395a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7541d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7551d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7561d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
757adc4f0dbSShawn McCarney     }
758e742b6ccSEd Tanous 
75981ce609eSEd Tanous     sensorJson["Status"]["State"] = getState(inventoryItem);
76089492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
76189492a15SPatrick Williams                                                inventoryItem);
76208777fb0SLewanczyk, Dawid 
76308777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
76408777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
76508777fb0SLewanczyk, Dawid     // that require integers, not floats.
76608777fb0SLewanczyk, Dawid     bool forceToInt = false;
76708777fb0SLewanczyk, Dawid 
7683929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7691d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
77095a3ecadSAnthony Wilson     {
7712a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
772c2bf7f99SWludzik, Jozef 
7730ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
7740ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
77595a3ecadSAnthony Wilson         {
776c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading type for "
777c2bf7f99SWludzik, Jozef                              << sensorType;
77895a3ecadSAnthony Wilson         }
779c2bf7f99SWludzik, Jozef         else
78095a3ecadSAnthony Wilson         {
781c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
78295a3ecadSAnthony Wilson         }
783c2bf7f99SWludzik, Jozef 
7841d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
785c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
786f8ede15eSAdrian Ambrożewicz         {
787c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for "
788c2bf7f99SWludzik, Jozef                              << sensorType;
789c2bf7f99SWludzik, Jozef         }
790c2bf7f99SWludzik, Jozef         else
791c2bf7f99SWludzik, Jozef         {
792c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
793f8ede15eSAdrian Ambrożewicz         }
79495a3ecadSAnthony Wilson     }
79595a3ecadSAnthony Wilson     else if (sensorType == "temperature")
7961abe55efSEd Tanous     {
7973929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
79881ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
79908777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
80008777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8011abe55efSEd Tanous     }
8021abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8031abe55efSEd Tanous     {
8043929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
80581ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
80681ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
80781ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
80808777fb0SLewanczyk, Dawid         forceToInt = true;
8091abe55efSEd Tanous     }
8106f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8116f6d0d32SEd Tanous     {
8123929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
81381ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
81481ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
81581ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8166f6d0d32SEd Tanous         forceToInt = true;
8176f6d0d32SEd Tanous     }
8181abe55efSEd Tanous     else if (sensorType == "voltage")
8191abe55efSEd Tanous     {
8203929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
82181ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8221abe55efSEd Tanous     }
8232474adfaSEd Tanous     else if (sensorType == "power")
8242474adfaSEd Tanous     {
8251d7c0054SEd Tanous         if (boost::iequals(sensorName, "total_power"))
826028f7ebcSEddie James         {
82781ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8287ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8297ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
83081ce609eSEd Tanous             sensorJson["MemberId"] = "0";
83181ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8323929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
833028f7ebcSEddie James         }
8341d7c0054SEd Tanous         else if (boost::ifind_first(sensorName, "input").empty())
83549c53ac9SJohnathan Mantey         {
8363929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
83749c53ac9SJohnathan Mantey         }
83849c53ac9SJohnathan Mantey         else
83949c53ac9SJohnathan Mantey         {
8403929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
84149c53ac9SJohnathan Mantey         }
8422474adfaSEd Tanous     }
8431abe55efSEd Tanous     else
8441abe55efSEd Tanous     {
84555c7b7a2SEd Tanous         BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
84608777fb0SLewanczyk, Dawid         return;
84708777fb0SLewanczyk, Dawid     }
84808777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8493929aca1SAnthony Wilson     std::vector<
8503929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8513929aca1SAnthony Wilson         properties;
85208777fb0SLewanczyk, Dawid     properties.reserve(7);
85308777fb0SLewanczyk, Dawid 
85408777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
855de629b6eSShawn McCarney 
8561d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8573929aca1SAnthony Wilson     {
8583929aca1SAnthony Wilson         properties.emplace_back(
8593929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8603929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8613929aca1SAnthony Wilson         properties.emplace_back(
8623929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8633929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8643929aca1SAnthony Wilson         properties.emplace_back(
8653929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8663929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
8673929aca1SAnthony Wilson         properties.emplace_back(
8683929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
8693929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
8703929aca1SAnthony Wilson     }
8713929aca1SAnthony Wilson     else if (sensorType != "power")
872de629b6eSShawn McCarney     {
87308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8743929aca1SAnthony Wilson                                 "WarningHigh",
8753929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
87608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8773929aca1SAnthony Wilson                                 "WarningLow",
8783929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
87908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8803929aca1SAnthony Wilson                                 "CriticalHigh",
8813929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
88208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8833929aca1SAnthony Wilson                                 "CriticalLow",
8843929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
885de629b6eSShawn McCarney     }
88608777fb0SLewanczyk, Dawid 
8872474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
8882474adfaSEd Tanous 
8891d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
89095a3ecadSAnthony Wilson     {
89195a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
8923929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
89395a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
8943929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
89551c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
89651c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
89795a3ecadSAnthony Wilson     }
89895a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8991abe55efSEd Tanous     {
90008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9013929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
90208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9033929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9041abe55efSEd Tanous     }
905adc4f0dbSShawn McCarney     else if (sensorType != "power")
9061abe55efSEd Tanous     {
90708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9083929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
90908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9103929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
91108777fb0SLewanczyk, Dawid     }
91208777fb0SLewanczyk, Dawid 
9133929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9143929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9151abe55efSEd Tanous     {
9161d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
917711ac7a9SEd Tanous         {
918711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
919711ac7a9SEd Tanous             {
920711ac7a9SEd Tanous                 continue;
921711ac7a9SEd Tanous             }
9223929aca1SAnthony Wilson 
9233929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9243929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9253929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9263929aca1SAnthony Wilson 
927abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
92840e4f380SEd Tanous             if (doubleValue == nullptr)
9291abe55efSEd Tanous             {
93040e4f380SEd Tanous                 BMCWEB_LOG_ERROR << "Got value interface that wasn't double";
9316f6d0d32SEd Tanous                 continue;
93208777fb0SLewanczyk, Dawid             }
9336f6d0d32SEd Tanous             if (forceToInt)
9346f6d0d32SEd Tanous             {
93540e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9366f6d0d32SEd Tanous             }
9376f6d0d32SEd Tanous             else
9386f6d0d32SEd Tanous             {
93940e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
94008777fb0SLewanczyk, Dawid             }
94108777fb0SLewanczyk, Dawid         }
94208777fb0SLewanczyk, Dawid     }
94308777fb0SLewanczyk, Dawid }
94408777fb0SLewanczyk, Dawid 
9451d7c0054SEd Tanous /**
9461d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9471d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9481d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9491d7c0054SEd Tanous  * build
9501d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
9511d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9521d7c0054SEd Tanous  * interfaces to be built from
9531d7c0054SEd Tanous  * @param sensorJson  The json object to fill
9541d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
9551d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
9561d7c0054SEd Tanous  */
9571d7c0054SEd Tanous inline void objectInterfacesToJson(
9581d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
9591d7c0054SEd Tanous     const std::string& chassisSubNode,
9601d7c0054SEd Tanous     const dbus::utility::DBusInteracesMap& interfacesDict,
9611d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
9621d7c0054SEd Tanous {
9631d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
9641d7c0054SEd Tanous     {
9651d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
9661d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
9671d7c0054SEd Tanous     }
968c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Added sensor " << sensorName;
9691d7c0054SEd Tanous }
9701d7c0054SEd Tanous 
971b5a76932SEd Tanous inline void populateFanRedundancy(
972b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
9738bd25ccdSJames Feist {
974e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
975e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
976e99073f5SGeorge Liu     dbus::utility::getSubTree(
977e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
978b9d36b47SEd Tanous         [sensorsAsyncResp](
979e99073f5SGeorge Liu             const boost::system::error_code& ec,
980b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
9818bd25ccdSJames Feist         if (ec)
9828bd25ccdSJames Feist         {
9838bd25ccdSJames Feist             return; // don't have to have this interface
9848bd25ccdSJames Feist         }
9856c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
986e278c18fSEd Tanous                  pathPair : resp)
9878bd25ccdSJames Feist         {
988e278c18fSEd Tanous             const std::string& path = pathPair.first;
9896c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
9908bd25ccdSJames Feist             if (objDict.empty())
9918bd25ccdSJames Feist             {
9928bd25ccdSJames Feist                 continue; // this should be impossible
9938bd25ccdSJames Feist             }
9948bd25ccdSJames Feist 
9958bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
9966c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
9976c3e9451SGeorge Liu                 path + "/chassis",
9986c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
9996c3e9451SGeorge Liu                     const boost::system::error_code& e,
10006c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
1001271584abSEd Tanous                 if (e)
10028bd25ccdSJames Feist                 {
10038bd25ccdSJames Feist                     return; // if they don't have an association we
10048bd25ccdSJames Feist                             // can't tell what chassis is
10058bd25ccdSJames Feist                 }
1006002d39b4SEd Tanous                 auto found =
1007002d39b4SEd Tanous                     std::find_if(endpoints.begin(), endpoints.end(),
10088bd25ccdSJames Feist                                  [sensorsAsyncResp](const std::string& entry) {
1009002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10108bd25ccdSJames Feist                            std::string::npos;
10118bd25ccdSJames Feist                     });
10128bd25ccdSJames Feist 
10131e1e598dSJonathan Doman                 if (found == endpoints.end())
10148bd25ccdSJames Feist                 {
10158bd25ccdSJames Feist                     return;
10168bd25ccdSJames Feist                 }
101786d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
101886d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
101986d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10208bd25ccdSJames Feist                     [path, sensorsAsyncResp](
1021271584abSEd Tanous                         const boost::system::error_code& err,
102286d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
1023271584abSEd Tanous                     if (err)
10248bd25ccdSJames Feist                     {
10258bd25ccdSJames Feist                         return; // don't have to have this
10268bd25ccdSJames Feist                                 // interface
10278bd25ccdSJames Feist                     }
10288bd25ccdSJames Feist 
102986d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
103086d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
103186d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
103286d89ed7SKrzysztof Grobelny 
103386d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
103486d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
103586d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
103686d89ed7SKrzysztof Grobelny                         collection, "Status", status);
103786d89ed7SKrzysztof Grobelny 
103886d89ed7SKrzysztof Grobelny                     if (!success)
103986d89ed7SKrzysztof Grobelny                     {
104086d89ed7SKrzysztof Grobelny                         messages::internalError(
104186d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
104286d89ed7SKrzysztof Grobelny                         return;
104386d89ed7SKrzysztof Grobelny                     }
104486d89ed7SKrzysztof Grobelny 
104586d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
104686d89ed7SKrzysztof Grobelny                         status == nullptr)
10478bd25ccdSJames Feist                     {
1048002d39b4SEd Tanous                         BMCWEB_LOG_ERROR << "Invalid redundancy interface";
10498bd25ccdSJames Feist                         messages::internalError(
10508d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10518bd25ccdSJames Feist                         return;
10528bd25ccdSJames Feist                     }
10538bd25ccdSJames Feist 
1054002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
105528aa8de5SGeorge Liu                     std::string name = objectPath.filename();
105628aa8de5SGeorge Liu                     if (name.empty())
10578bd25ccdSJames Feist                     {
10588bd25ccdSJames Feist                         // this should be impossible
10598bd25ccdSJames Feist                         messages::internalError(
10608d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10618bd25ccdSJames Feist                         return;
10628bd25ccdSJames Feist                     }
1063002d39b4SEd Tanous                     std::replace(name.begin(), name.end(), '_', ' ');
10648bd25ccdSJames Feist 
10658bd25ccdSJames Feist                     std::string health;
10668bd25ccdSJames Feist 
106711ba3979SEd Tanous                     if (status->ends_with("Full"))
10688bd25ccdSJames Feist                     {
10698bd25ccdSJames Feist                         health = "OK";
10708bd25ccdSJames Feist                     }
107111ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
10728bd25ccdSJames Feist                     {
10738bd25ccdSJames Feist                         health = "Warning";
10748bd25ccdSJames Feist                     }
10758bd25ccdSJames Feist                     else
10768bd25ccdSJames Feist                     {
10778bd25ccdSJames Feist                         health = "Critical";
10788bd25ccdSJames Feist                     }
10791476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
10808bd25ccdSJames Feist                     const auto& fanRedfish =
1081002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
10828bd25ccdSJames Feist                     for (const std::string& item : *collection)
10838bd25ccdSJames Feist                     {
10848a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
10858a592810SEd Tanous                         std::string itemName = itemPath.filename();
108628aa8de5SGeorge Liu                         if (itemName.empty())
108728aa8de5SGeorge Liu                         {
108828aa8de5SGeorge Liu                             continue;
108928aa8de5SGeorge Liu                         }
10908bd25ccdSJames Feist                         /*
10918bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
10928bd25ccdSJames Feist                         std::replace(itemName.begin(),
10938bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
1094002d39b4SEd Tanous                         auto schemaItem =
1095002d39b4SEd Tanous                             std::find_if(fanRedfish.begin(), fanRedfish.end(),
10968bd25ccdSJames Feist                                          [itemName](const nlohmann::json& fan) {
10973e35c761SGeorge Liu                             return fan["Name"] == itemName;
10988bd25ccdSJames Feist                             });
10998bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11008bd25ccdSJames Feist                         {
11018a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11028a592810SEd Tanous                             collectionId["@odata.id"] =
11031476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11041476687dSEd Tanous                             redfishCollection.emplace_back(
11058a592810SEd Tanous                                 std::move(collectionId));
11068bd25ccdSJames Feist                         }
11078bd25ccdSJames Feist                         else
11088bd25ccdSJames Feist                         {
1109002d39b4SEd Tanous                             BMCWEB_LOG_ERROR << "failed to find fan in schema";
11108bd25ccdSJames Feist                             messages::internalError(
11118d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11128bd25ccdSJames Feist                             return;
11138bd25ccdSJames Feist                         }
11148bd25ccdSJames Feist                     }
11158bd25ccdSJames Feist 
111689492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
111726f6976fSEd Tanous                                               ? 0
111889492a15SPatrick Williams                                               : collection->size() -
111989492a15SPatrick Williams                                                     *allowedFailures;
1120002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11218bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11221476687dSEd Tanous 
11231476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1124*ef4c65b7SEd Tanous                     boost::urls::url url =
1125*ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1126*ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1127eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1128eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1129eddfc437SWilly Tu                                          .to_string());
1130eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1131002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11321476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11331476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11341476687dSEd Tanous                     redundancy["Name"] = name;
11351476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11361476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11371476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11381476687dSEd Tanous 
1139b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
114086d89ed7SKrzysztof Grobelny                     });
11411e1e598dSJonathan Doman                 });
11428bd25ccdSJames Feist         }
1143e99073f5SGeorge Liu         });
11448bd25ccdSJames Feist }
11458bd25ccdSJames Feist 
1146b5a76932SEd Tanous inline void
114781ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
114849c53ac9SJohnathan Mantey {
11498d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
115049c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
115181ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
115249c53ac9SJohnathan Mantey     {
115349c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
115449c53ac9SJohnathan Mantey     }
115549c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
115649c53ac9SJohnathan Mantey     {
115749c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
115849c53ac9SJohnathan Mantey         if (entry != response.end())
115949c53ac9SJohnathan Mantey         {
116049c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
116102cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
116249c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
116349c53ac9SJohnathan Mantey             });
116449c53ac9SJohnathan Mantey 
116549c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
116649c53ac9SJohnathan Mantey             size_t count = 0;
116749c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
116849c53ac9SJohnathan Mantey             {
116949c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
117049c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
117149c53ac9SJohnathan Mantey                 {
117249c53ac9SJohnathan Mantey                     continue;
117349c53ac9SJohnathan Mantey                 }
117449c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
117549c53ac9SJohnathan Mantey                 if (value != nullptr)
117649c53ac9SJohnathan Mantey                 {
1177eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
11783e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
117949c53ac9SJohnathan Mantey                     count++;
118081ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
118149c53ac9SJohnathan Mantey                 }
118249c53ac9SJohnathan Mantey             }
118349c53ac9SJohnathan Mantey         }
118449c53ac9SJohnathan Mantey     }
118549c53ac9SJohnathan Mantey }
118649c53ac9SJohnathan Mantey 
118708777fb0SLewanczyk, Dawid /**
1188adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1189adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1190adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1191adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
11928fb49dd6SShawn McCarney  */
119323a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1194b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1195adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
11968fb49dd6SShawn McCarney {
1197adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
11988fb49dd6SShawn McCarney     {
1199adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12008fb49dd6SShawn McCarney         {
1201adc4f0dbSShawn McCarney             return &inventoryItem;
12028fb49dd6SShawn McCarney         }
12038fb49dd6SShawn McCarney     }
12048fb49dd6SShawn McCarney     return nullptr;
12058fb49dd6SShawn McCarney }
12068fb49dd6SShawn McCarney 
12078fb49dd6SShawn McCarney /**
1208adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1209adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1210adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1211adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12128fb49dd6SShawn McCarney  */
121323a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1214b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1215adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1216adc4f0dbSShawn McCarney {
1217adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1218adc4f0dbSShawn McCarney     {
1219adc4f0dbSShawn McCarney         if (inventoryItem.sensors.count(sensorObjPath) > 0)
1220adc4f0dbSShawn McCarney         {
1221adc4f0dbSShawn McCarney             return &inventoryItem;
1222adc4f0dbSShawn McCarney         }
1223adc4f0dbSShawn McCarney     }
1224adc4f0dbSShawn McCarney     return nullptr;
1225adc4f0dbSShawn McCarney }
1226adc4f0dbSShawn McCarney 
1227adc4f0dbSShawn McCarney /**
1228d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1229d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1230d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1231d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1232d500549bSAnthony Wilson  */
1233d500549bSAnthony Wilson inline InventoryItem*
1234d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1235d500549bSAnthony Wilson                             const std::string& ledObjPath)
1236d500549bSAnthony Wilson {
1237d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1238d500549bSAnthony Wilson     {
1239d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1240d500549bSAnthony Wilson         {
1241d500549bSAnthony Wilson             return &inventoryItem;
1242d500549bSAnthony Wilson         }
1243d500549bSAnthony Wilson     }
1244d500549bSAnthony Wilson     return nullptr;
1245d500549bSAnthony Wilson }
1246d500549bSAnthony Wilson 
1247d500549bSAnthony Wilson /**
1248adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1249adc4f0dbSShawn McCarney  *
1250adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1251adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1252adc4f0dbSShawn McCarney  * added to the vector.
1253adc4f0dbSShawn McCarney  *
1254adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1255adc4f0dbSShawn McCarney  * InventoryItem.
1256adc4f0dbSShawn McCarney  *
1257adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1258adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1259adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1260adc4f0dbSShawn McCarney  */
1261b5a76932SEd Tanous inline void addInventoryItem(
1262b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1263b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1264adc4f0dbSShawn McCarney {
1265adc4f0dbSShawn McCarney     // Look for inventory item in vector
126689492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
126789492a15SPatrick Williams                                                      invItemObjPath);
1268adc4f0dbSShawn McCarney 
1269adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1270adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1271adc4f0dbSShawn McCarney     {
1272adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1273adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1274adc4f0dbSShawn McCarney     }
1275adc4f0dbSShawn McCarney 
1276adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1277adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1278adc4f0dbSShawn McCarney }
1279adc4f0dbSShawn McCarney 
1280adc4f0dbSShawn McCarney /**
1281adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1282adc4f0dbSShawn McCarney  *
1283adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1284adc4f0dbSShawn McCarney  * specified InventoryItem.
1285adc4f0dbSShawn McCarney  *
1286adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1287adc4f0dbSShawn McCarney  * response.
1288adc4f0dbSShawn McCarney  *
1289adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1290adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1291adc4f0dbSShawn McCarney  * for the specified inventory item.
1292adc4f0dbSShawn McCarney  */
129323a21a1cSEd Tanous inline void storeInventoryItemData(
1294adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
1295711ac7a9SEd Tanous     const dbus::utility::DBusInteracesMap& interfacesDict)
12968fb49dd6SShawn McCarney {
1297adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1298711ac7a9SEd Tanous 
12999eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13008fb49dd6SShawn McCarney     {
1301711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13028fb49dd6SShawn McCarney         {
13039eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1304711ac7a9SEd Tanous             {
1305711ac7a9SEd Tanous                 if (name == "Present")
1306711ac7a9SEd Tanous                 {
1307711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1308adc4f0dbSShawn McCarney                     if (value != nullptr)
13098fb49dd6SShawn McCarney                     {
1310adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13118fb49dd6SShawn McCarney                     }
13128fb49dd6SShawn McCarney                 }
13138fb49dd6SShawn McCarney             }
1314711ac7a9SEd Tanous         }
1315adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1316711ac7a9SEd Tanous 
1317711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13188fb49dd6SShawn McCarney         {
1319adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13208fb49dd6SShawn McCarney         }
1321adc4f0dbSShawn McCarney 
1322adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1323711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1324adc4f0dbSShawn McCarney         {
13259eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1326711ac7a9SEd Tanous             {
1327711ac7a9SEd Tanous                 if (name == "Manufacturer")
1328adc4f0dbSShawn McCarney                 {
1329adc4f0dbSShawn McCarney                     const std::string* value =
1330711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1331adc4f0dbSShawn McCarney                     if (value != nullptr)
1332adc4f0dbSShawn McCarney                     {
1333adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1334adc4f0dbSShawn McCarney                     }
1335adc4f0dbSShawn McCarney                 }
1336711ac7a9SEd Tanous                 if (name == "Model")
1337adc4f0dbSShawn McCarney                 {
1338adc4f0dbSShawn McCarney                     const std::string* value =
1339711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1340adc4f0dbSShawn McCarney                     if (value != nullptr)
1341adc4f0dbSShawn McCarney                     {
1342adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1343adc4f0dbSShawn McCarney                     }
1344adc4f0dbSShawn McCarney                 }
1345711ac7a9SEd Tanous                 if (name == "SerialNumber")
1346adc4f0dbSShawn McCarney                 {
1347adc4f0dbSShawn McCarney                     const std::string* value =
1348711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1349adc4f0dbSShawn McCarney                     if (value != nullptr)
1350adc4f0dbSShawn McCarney                     {
1351adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1352adc4f0dbSShawn McCarney                     }
1353adc4f0dbSShawn McCarney                 }
1354711ac7a9SEd Tanous                 if (name == "PartNumber")
1355711ac7a9SEd Tanous                 {
1356711ac7a9SEd Tanous                     const std::string* value =
1357711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1358711ac7a9SEd Tanous                     if (value != nullptr)
1359711ac7a9SEd Tanous                     {
1360711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1361711ac7a9SEd Tanous                     }
1362711ac7a9SEd Tanous                 }
1363711ac7a9SEd Tanous             }
1364adc4f0dbSShawn McCarney         }
1365adc4f0dbSShawn McCarney 
1366711ac7a9SEd Tanous         if (interface ==
1367711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1368adc4f0dbSShawn McCarney         {
13699eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1370adc4f0dbSShawn McCarney             {
1371711ac7a9SEd Tanous                 if (name == "Functional")
1372711ac7a9SEd Tanous                 {
1373711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1374adc4f0dbSShawn McCarney                     if (value != nullptr)
1375adc4f0dbSShawn McCarney                     {
1376adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
13778fb49dd6SShawn McCarney                     }
13788fb49dd6SShawn McCarney                 }
13798fb49dd6SShawn McCarney             }
13808fb49dd6SShawn McCarney         }
1381711ac7a9SEd Tanous     }
1382711ac7a9SEd Tanous }
13838fb49dd6SShawn McCarney 
13848fb49dd6SShawn McCarney /**
1385adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
13868fb49dd6SShawn McCarney  *
1387adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1388adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1389adc4f0dbSShawn McCarney  * inventoryItems vector.
13908fb49dd6SShawn McCarney  *
1391adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1392adc4f0dbSShawn McCarney  * response.
1393adc4f0dbSShawn McCarney  *
1394adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1395adc4f0dbSShawn McCarney  * been obtained.
1396adc4f0dbSShawn McCarney  *
1397adc4f0dbSShawn McCarney  * The callback must have the following signature:
1398adc4f0dbSShawn McCarney  *   @code
1399d500549bSAnthony Wilson  *   callback(void)
1400adc4f0dbSShawn McCarney  *   @endcode
1401adc4f0dbSShawn McCarney  *
1402adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1403adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1404adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14058fb49dd6SShawn McCarney  *
14068fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1407adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1408adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14098fb49dd6SShawn McCarney  * implements ObjectManager.
1410adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1411adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1412adc4f0dbSShawn McCarney  * in recursive calls to this function.
14138fb49dd6SShawn McCarney  */
1414adc4f0dbSShawn McCarney template <typename Callback>
1415adc4f0dbSShawn McCarney static void getInventoryItemsData(
14168fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1417adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1418d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1419d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14208fb49dd6SShawn McCarney {
1421adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData enter";
14228fb49dd6SShawn McCarney 
1423adc4f0dbSShawn McCarney     // If no more connections left, call callback
1424adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14258fb49dd6SShawn McCarney     {
1426d500549bSAnthony Wilson         callback();
1427adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1428adc4f0dbSShawn McCarney         return;
1429adc4f0dbSShawn McCarney     }
1430adc4f0dbSShawn McCarney 
1431adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1432fe04d49cSNan Zhou     auto it = invConnections->begin();
1433fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1434adc4f0dbSShawn McCarney     if (it != invConnections->end())
1435adc4f0dbSShawn McCarney     {
1436adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1437adc4f0dbSShawn McCarney 
14388fb49dd6SShawn McCarney         // Response handler for GetManagedObjects
1439d0090733SEd Tanous         auto respHandler = [sensorsAsyncResp, inventoryItems, invConnections,
1440d0090733SEd Tanous                             callback{std::forward<Callback>(callback)},
1441d0090733SEd Tanous                             invConnectionsIndex](
14425e7e2dc5SEd Tanous                                const boost::system::error_code& ec,
144302cad96eSEd Tanous                                const dbus::utility::ManagedObjectType& resp) {
1444adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter";
14458fb49dd6SShawn McCarney             if (ec)
14468fb49dd6SShawn McCarney             {
14478fb49dd6SShawn McCarney                 BMCWEB_LOG_ERROR
1448adc4f0dbSShawn McCarney                     << "getInventoryItemsData respHandler DBus error " << ec;
14498d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14508fb49dd6SShawn McCarney                 return;
14518fb49dd6SShawn McCarney             }
14528fb49dd6SShawn McCarney 
14538fb49dd6SShawn McCarney             // Loop through returned object paths
14548fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14558fb49dd6SShawn McCarney             {
14568fb49dd6SShawn McCarney                 const std::string& objPath =
14578fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14588fb49dd6SShawn McCarney 
1459adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
146089492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
146189492a15SPatrick Williams                                                                  objPath);
1462adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
14638fb49dd6SShawn McCarney                 {
1464adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1465adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
14668fb49dd6SShawn McCarney                 }
14678fb49dd6SShawn McCarney             }
14688fb49dd6SShawn McCarney 
1469adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1470adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1471d0090733SEd Tanous                                   invConnections, std::move(callback),
1472d0090733SEd Tanous                                   invConnectionsIndex + 1);
1473adc4f0dbSShawn McCarney 
1474adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit";
14758fb49dd6SShawn McCarney         };
14768fb49dd6SShawn McCarney 
14778fb49dd6SShawn McCarney         // Get all object paths and their interfaces for current connection
14788fb49dd6SShawn McCarney         crow::connections::systemBus->async_method_call(
1479d0090733SEd Tanous             std::move(respHandler), invConnection,
1480f8bb0ff3SEd Tanous             "/xyz/openbmc_project/inventory",
14818fb49dd6SShawn McCarney             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
14828fb49dd6SShawn McCarney     }
14838fb49dd6SShawn McCarney 
1484adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
14858fb49dd6SShawn McCarney }
14868fb49dd6SShawn McCarney 
14878fb49dd6SShawn McCarney /**
1488adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
14898fb49dd6SShawn McCarney  *
1490adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1491adc4f0dbSShawn McCarney  * items that are associated with sensors.
14928fb49dd6SShawn McCarney  *
14938fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
14948fb49dd6SShawn McCarney  * been obtained.
14958fb49dd6SShawn McCarney  *
14968fb49dd6SShawn McCarney  * The callback must have the following signature:
14978fb49dd6SShawn McCarney  *   @code
1498fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
14998fb49dd6SShawn McCarney  *   @endcode
15008fb49dd6SShawn McCarney  *
15018fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1502adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15038fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15048fb49dd6SShawn McCarney  */
15058fb49dd6SShawn McCarney template <typename Callback>
15068fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1507b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1508b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15098fb49dd6SShawn McCarney     Callback&& callback)
15108fb49dd6SShawn McCarney {
15118fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter";
15128fb49dd6SShawn McCarney 
15138fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1514e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15158fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1516adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1517adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15188fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15198fb49dd6SShawn McCarney 
1520e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1521e99073f5SGeorge Liu     dbus::utility::getSubTree(
1522e99073f5SGeorge Liu         path, 0, interfaces,
1523002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1524002d39b4SEd Tanous          inventoryItems](
1525e99073f5SGeorge Liu             const boost::system::error_code& ec,
1526002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1527e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
15288fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter";
15298fb49dd6SShawn McCarney         if (ec)
15308fb49dd6SShawn McCarney         {
15318d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
15328fb49dd6SShawn McCarney             BMCWEB_LOG_ERROR
15338fb49dd6SShawn McCarney                 << "getInventoryItemsConnections respHandler DBus error " << ec;
15348fb49dd6SShawn McCarney             return;
15358fb49dd6SShawn McCarney         }
15368fb49dd6SShawn McCarney 
15378fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1538fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1539fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15408fb49dd6SShawn McCarney 
15418fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15428fb49dd6SShawn McCarney         for (const std::pair<
15438fb49dd6SShawn McCarney                  std::string,
15448fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15458fb49dd6SShawn McCarney                  object : subtree)
15468fb49dd6SShawn McCarney         {
1547adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15488fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1549adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15508fb49dd6SShawn McCarney             {
15518fb49dd6SShawn McCarney                 // Store all connections to inventory item
15528fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15538fb49dd6SShawn McCarney                          objData : object.second)
15548fb49dd6SShawn McCarney                 {
15558fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15568fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15578fb49dd6SShawn McCarney                 }
15588fb49dd6SShawn McCarney             }
15598fb49dd6SShawn McCarney         }
1560d500549bSAnthony Wilson 
15618fb49dd6SShawn McCarney         callback(invConnections);
15628fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit";
1563e99073f5SGeorge Liu         });
15648fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit";
15658fb49dd6SShawn McCarney }
15668fb49dd6SShawn McCarney 
15678fb49dd6SShawn McCarney /**
1568adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
15698fb49dd6SShawn McCarney  *
15708fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1571d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1572d500549bSAnthony Wilson  * their LEDs, if any.
15738fb49dd6SShawn McCarney  *
15748fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
15758fb49dd6SShawn McCarney  * has been obtained.
15768fb49dd6SShawn McCarney  *
15778fb49dd6SShawn McCarney  * The callback must have the following signature:
15788fb49dd6SShawn McCarney  *   @code
1579adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
15808fb49dd6SShawn McCarney  *   @endcode
15818fb49dd6SShawn McCarney  *
15828fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
15838fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
15848fb49dd6SShawn McCarney  * implements ObjectManager.
15858fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
15868fb49dd6SShawn McCarney  */
15878fb49dd6SShawn McCarney template <typename Callback>
1588adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1589b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1590fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
15918fb49dd6SShawn McCarney     Callback&& callback)
15928fb49dd6SShawn McCarney {
1593adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter";
15948fb49dd6SShawn McCarney 
15958fb49dd6SShawn McCarney     // Response handler for GetManagedObjects
159602cad96eSEd Tanous     auto respHandler =
159702cad96eSEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
15985e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
159902cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
1600adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter";
16018fb49dd6SShawn McCarney         if (ec)
16028fb49dd6SShawn McCarney         {
1603adc4f0dbSShawn McCarney             BMCWEB_LOG_ERROR
1604adc4f0dbSShawn McCarney                 << "getInventoryItemAssociations respHandler DBus error " << ec;
16058d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16068fb49dd6SShawn McCarney             return;
16078fb49dd6SShawn McCarney         }
16088fb49dd6SShawn McCarney 
1609adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1610adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1611adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1612adc4f0dbSShawn McCarney 
16138fb49dd6SShawn McCarney         // Loop through returned object paths
16148fb49dd6SShawn McCarney         std::string sensorAssocPath;
16158fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16168fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16178fb49dd6SShawn McCarney         {
16188fb49dd6SShawn McCarney             const std::string& objPath =
16198fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16208fb49dd6SShawn McCarney 
16218fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16228fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16238fb49dd6SShawn McCarney             {
16248fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16258fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16268fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16278fb49dd6SShawn McCarney                 {
16288fb49dd6SShawn McCarney                     // Get Association interface for object path
1629711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16308fb49dd6SShawn McCarney                     {
1631711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1632711ac7a9SEd Tanous                         {
1633711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1634711ac7a9SEd Tanous                             {
1635711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16368fb49dd6SShawn McCarney                                 {
16378fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16388fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1639711ac7a9SEd Tanous                                             &value);
1640711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1641711ac7a9SEd Tanous                                         !endpoints->empty())
16428fb49dd6SShawn McCarney                                     {
1643adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1644adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1645adc4f0dbSShawn McCarney                                             endpoints->front();
1646711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1647711ac7a9SEd Tanous                                                          invItemPath,
1648adc4f0dbSShawn McCarney                                                          sensorName);
16498fb49dd6SShawn McCarney                                     }
16508fb49dd6SShawn McCarney                                 }
16518fb49dd6SShawn McCarney                             }
1652711ac7a9SEd Tanous                         }
1653711ac7a9SEd Tanous                     }
16548fb49dd6SShawn McCarney                     break;
16558fb49dd6SShawn McCarney                 }
16568fb49dd6SShawn McCarney             }
16578fb49dd6SShawn McCarney         }
16588fb49dd6SShawn McCarney 
1659d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1660d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1661d500549bSAnthony Wilson         std::string inventoryAssocPath;
1662d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1663d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1664d500549bSAnthony Wilson         {
1665d500549bSAnthony Wilson             const std::string& objPath =
1666d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1667d500549bSAnthony Wilson 
1668d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1669d500549bSAnthony Wilson             {
1670d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1671d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1672d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1673d500549bSAnthony Wilson                 {
1674711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1675d500549bSAnthony Wilson                     {
1676711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1677711ac7a9SEd Tanous                         {
1678711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1679711ac7a9SEd Tanous                             {
1680711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1681d500549bSAnthony Wilson                                 {
1682d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1683d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1684711ac7a9SEd Tanous                                             &value);
1685711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1686711ac7a9SEd Tanous                                         !endpoints->empty())
1687d500549bSAnthony Wilson                                     {
1688711ac7a9SEd Tanous                                         // Add inventory item to vector
1689d500549bSAnthony Wilson                                         // Store LED path in inventory item
1690711ac7a9SEd Tanous                                         const std::string& ledPath =
1691711ac7a9SEd Tanous                                             endpoints->front();
1692d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1693d500549bSAnthony Wilson                                     }
1694d500549bSAnthony Wilson                                 }
1695d500549bSAnthony Wilson                             }
1696711ac7a9SEd Tanous                         }
1697711ac7a9SEd Tanous                     }
1698711ac7a9SEd Tanous 
1699d500549bSAnthony Wilson                     break;
1700d500549bSAnthony Wilson                 }
1701d500549bSAnthony Wilson             }
1702d500549bSAnthony Wilson         }
1703adc4f0dbSShawn McCarney         callback(inventoryItems);
1704adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit";
17058fb49dd6SShawn McCarney     };
17068fb49dd6SShawn McCarney 
17078fb49dd6SShawn McCarney     // Call GetManagedObjects on the ObjectMapper to get all associations
17088fb49dd6SShawn McCarney     crow::connections::systemBus->async_method_call(
1709d0090733SEd Tanous         std::move(respHandler), "xyz.openbmc_project.ObjectMapper", "/",
17108fb49dd6SShawn McCarney         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
17118fb49dd6SShawn McCarney 
1712adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit";
17138fb49dd6SShawn McCarney }
17148fb49dd6SShawn McCarney 
17158fb49dd6SShawn McCarney /**
1716d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1717d500549bSAnthony Wilson  *
1718d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1719d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1720d500549bSAnthony Wilson  * inventoryItems vector.
1721d500549bSAnthony Wilson  *
1722d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1723d500549bSAnthony Wilson  * response.
1724d500549bSAnthony Wilson  *
1725d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1726d500549bSAnthony Wilson  * has been obtained.
1727d500549bSAnthony Wilson  *
1728d500549bSAnthony Wilson  * The callback must have the following signature:
1729d500549bSAnthony Wilson  *   @code
173042cbe538SGunnar Mills  *   callback()
1731d500549bSAnthony Wilson  *   @endcode
1732d500549bSAnthony Wilson  *
1733d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1734d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1735d500549bSAnthony Wilson  * last asynchronous function has completed.
1736d500549bSAnthony Wilson  *
1737d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1738d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1739d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1740d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1741d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1742d500549bSAnthony Wilson  * in recursive calls to this function.
1743d500549bSAnthony Wilson  */
1744d500549bSAnthony Wilson template <typename Callback>
1745d500549bSAnthony Wilson void getInventoryLedData(
1746d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1747d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1748fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1749d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1750d500549bSAnthony Wilson {
1751d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData enter";
1752d500549bSAnthony Wilson 
1753d500549bSAnthony Wilson     // If no more connections left, call callback
1754d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1755d500549bSAnthony Wilson     {
175642cbe538SGunnar Mills         callback();
1757d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1758d500549bSAnthony Wilson         return;
1759d500549bSAnthony Wilson     }
1760d500549bSAnthony Wilson 
1761d500549bSAnthony Wilson     // Get inventory item data from current connection
1762fe04d49cSNan Zhou     auto it = ledConnections->begin();
1763fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1764d500549bSAnthony Wilson     if (it != ledConnections->end())
1765d500549bSAnthony Wilson     {
1766d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1767d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1768d500549bSAnthony Wilson         // Response handler for Get State property
17691e1e598dSJonathan Doman         auto respHandler =
17701e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1771f94c4ecfSEd Tanous              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
17725e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
1773d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter";
1774d500549bSAnthony Wilson             if (ec)
1775d500549bSAnthony Wilson             {
1776d500549bSAnthony Wilson                 BMCWEB_LOG_ERROR
1777d500549bSAnthony Wilson                     << "getInventoryLedData respHandler DBus error " << ec;
17788d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1779d500549bSAnthony Wilson                 return;
1780d500549bSAnthony Wilson             }
1781d500549bSAnthony Wilson 
17821e1e598dSJonathan Doman             BMCWEB_LOG_DEBUG << "Led state: " << state;
1783d500549bSAnthony Wilson             // Find inventory item with this LED object path
1784d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1785d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1786d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1787d500549bSAnthony Wilson             {
1788d500549bSAnthony Wilson                 // Store LED state in InventoryItem
178911ba3979SEd Tanous                 if (state.ends_with("On"))
1790d500549bSAnthony Wilson                 {
1791d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1792d500549bSAnthony Wilson                 }
179311ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1794d500549bSAnthony Wilson                 {
1795d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1796d500549bSAnthony Wilson                 }
179711ba3979SEd Tanous                 else if (state.ends_with("Off"))
1798d500549bSAnthony Wilson                 {
1799d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1800d500549bSAnthony Wilson                 }
1801d500549bSAnthony Wilson                 else
1802d500549bSAnthony Wilson                 {
1803d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1804d500549bSAnthony Wilson                 }
1805d500549bSAnthony Wilson             }
1806d500549bSAnthony Wilson 
1807d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1808d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1809d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1810d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1811d500549bSAnthony Wilson 
1812d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit";
1813d500549bSAnthony Wilson         };
1814d500549bSAnthony Wilson 
1815d500549bSAnthony Wilson         // Get the State property for the current LED
18161e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18171e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18181e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18191e1e598dSJonathan Doman             std::move(respHandler));
1820d500549bSAnthony Wilson     }
1821d500549bSAnthony Wilson 
1822d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1823d500549bSAnthony Wilson }
1824d500549bSAnthony Wilson 
1825d500549bSAnthony Wilson /**
1826d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1827d500549bSAnthony Wilson  *
1828d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1829d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1830d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1831d500549bSAnthony Wilson  *
1832d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1833d500549bSAnthony Wilson  * response.
1834d500549bSAnthony Wilson  *
1835d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1836d500549bSAnthony Wilson  * been obtained.
1837d500549bSAnthony Wilson  *
1838d500549bSAnthony Wilson  * The callback must have the following signature:
1839d500549bSAnthony Wilson  *   @code
184042cbe538SGunnar Mills  *   callback()
1841d500549bSAnthony Wilson  *   @endcode
1842d500549bSAnthony Wilson  *
1843d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1844d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1845d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1846d500549bSAnthony Wilson  */
1847d500549bSAnthony Wilson template <typename Callback>
1848d500549bSAnthony Wilson void getInventoryLeds(
1849d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1850d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1851d500549bSAnthony Wilson     Callback&& callback)
1852d500549bSAnthony Wilson {
1853d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds enter";
1854d500549bSAnthony Wilson 
1855d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1856e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1857d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1858d500549bSAnthony Wilson 
1859e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1860e99073f5SGeorge Liu     dbus::utility::getSubTree(
1861e99073f5SGeorge Liu         path, 0, interfaces,
1862002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1863002d39b4SEd Tanous          inventoryItems](
1864e99073f5SGeorge Liu             const boost::system::error_code& ec,
1865002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1866e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
1867d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter";
1868d500549bSAnthony Wilson         if (ec)
1869d500549bSAnthony Wilson         {
18708d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
1871d500549bSAnthony Wilson             BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error "
1872d500549bSAnthony Wilson                              << ec;
1873d500549bSAnthony Wilson             return;
1874d500549bSAnthony Wilson         }
1875d500549bSAnthony Wilson 
1876d500549bSAnthony Wilson         // Build map of LED object paths to connections
1877fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1878fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1879d500549bSAnthony Wilson 
1880d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1881d500549bSAnthony Wilson         for (const std::pair<
1882d500549bSAnthony Wilson                  std::string,
1883d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1884d500549bSAnthony Wilson                  object : subtree)
1885d500549bSAnthony Wilson         {
1886d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1887d500549bSAnthony Wilson             // items
1888d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1889d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1890d500549bSAnthony Wilson             {
1891d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1892d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1893d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
1894d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> "
1895d500549bSAnthony Wilson                                  << connection;
1896d500549bSAnthony Wilson             }
1897d500549bSAnthony Wilson         }
1898d500549bSAnthony Wilson 
1899d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1900d500549bSAnthony Wilson                             std::move(callback));
1901d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit";
1902e99073f5SGeorge Liu         });
1903d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds exit";
1904d500549bSAnthony Wilson }
1905d500549bSAnthony Wilson 
1906d500549bSAnthony Wilson /**
190742cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
190842cbe538SGunnar Mills  *
190942cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
191042cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
191142cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
191242cbe538SGunnar Mills  *
191342cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
191442cbe538SGunnar Mills  * response.
191542cbe538SGunnar Mills  *
191642cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
191742cbe538SGunnar Mills  * when data has been obtained.
191842cbe538SGunnar Mills  *
191942cbe538SGunnar Mills  * The callback must have the following signature:
192042cbe538SGunnar Mills  *   @code
192142cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
192242cbe538SGunnar Mills  *   @endcode
192342cbe538SGunnar Mills  *
192442cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
192542cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
192642cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
192742cbe538SGunnar Mills  *        Supply Attributes
192842cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
192942cbe538SGunnar Mills  */
193042cbe538SGunnar Mills template <typename Callback>
193142cbe538SGunnar Mills void getPowerSupplyAttributesData(
1932b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
193342cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1934fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
193542cbe538SGunnar Mills     Callback&& callback)
193642cbe538SGunnar Mills {
193742cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter";
193842cbe538SGunnar Mills 
193942cbe538SGunnar Mills     if (psAttributesConnections.empty())
194042cbe538SGunnar Mills     {
194142cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!";
194242cbe538SGunnar Mills         callback(inventoryItems);
194342cbe538SGunnar Mills         return;
194442cbe538SGunnar Mills     }
194542cbe538SGunnar Mills 
194642cbe538SGunnar Mills     // Assuming just one connection (service) for now
1947fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
194842cbe538SGunnar Mills 
194942cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
195042cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
195142cbe538SGunnar Mills 
195242cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
1953002d39b4SEd Tanous     auto respHandler =
1954002d39b4SEd Tanous         [sensorsAsyncResp, inventoryItems,
1955f94c4ecfSEd Tanous          callback{std::forward<Callback>(callback)}](
19565e7e2dc5SEd Tanous             const boost::system::error_code& ec, const uint32_t value) {
195742cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter";
195842cbe538SGunnar Mills         if (ec)
195942cbe538SGunnar Mills         {
196042cbe538SGunnar Mills             BMCWEB_LOG_ERROR
196142cbe538SGunnar Mills                 << "getPowerSupplyAttributesData respHandler DBus error " << ec;
19628d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
196342cbe538SGunnar Mills             return;
196442cbe538SGunnar Mills         }
196542cbe538SGunnar Mills 
19661e1e598dSJonathan Doman         BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value;
196742cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
196842cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
196942cbe538SGunnar Mills         {
197055f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
197142cbe538SGunnar Mills             {
197242cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19731e1e598dSJonathan Doman                     static_cast<int>(value);
197442cbe538SGunnar Mills             }
197542cbe538SGunnar Mills         }
197642cbe538SGunnar Mills 
197742cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit";
197842cbe538SGunnar Mills         callback(inventoryItems);
197942cbe538SGunnar Mills     };
198042cbe538SGunnar Mills 
198142cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
198242cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
19831e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
19841e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
19851e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
19861e1e598dSJonathan Doman         std::move(respHandler));
198742cbe538SGunnar Mills 
198842cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit";
198942cbe538SGunnar Mills }
199042cbe538SGunnar Mills 
199142cbe538SGunnar Mills /**
199242cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
199342cbe538SGunnar Mills  *
199442cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
199542cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
199642cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
199742cbe538SGunnar Mills  * item.
199842cbe538SGunnar Mills  *
199942cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
200042cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
200142cbe538SGunnar Mills  *
200242cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
200342cbe538SGunnar Mills  * when information has been obtained.
200442cbe538SGunnar Mills  *
200542cbe538SGunnar Mills  * The callback must have the following signature:
200642cbe538SGunnar Mills  *   @code
200742cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
200842cbe538SGunnar Mills  *   @endcode
200942cbe538SGunnar Mills  *
201042cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
201142cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
201242cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
201342cbe538SGunnar Mills  */
201442cbe538SGunnar Mills template <typename Callback>
201542cbe538SGunnar Mills void getPowerSupplyAttributes(
201642cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
201742cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
201842cbe538SGunnar Mills     Callback&& callback)
201942cbe538SGunnar Mills {
202042cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter";
202142cbe538SGunnar Mills 
202242cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2023a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
202442cbe538SGunnar Mills     {
202542cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power";
202642cbe538SGunnar Mills         callback(inventoryItems);
202742cbe538SGunnar Mills         return;
202842cbe538SGunnar Mills     }
202942cbe538SGunnar Mills 
2030e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
203142cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
203242cbe538SGunnar Mills 
2033e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2034e99073f5SGeorge Liu     dbus::utility::getSubTree(
2035e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
2036b9d36b47SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2037b9d36b47SEd Tanous          inventoryItems](
2038e99073f5SGeorge Liu             const boost::system::error_code& ec,
2039b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2040e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
204142cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter";
204242cbe538SGunnar Mills         if (ec)
204342cbe538SGunnar Mills         {
20448d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
204542cbe538SGunnar Mills             BMCWEB_LOG_ERROR
204642cbe538SGunnar Mills                 << "getPowerSupplyAttributes respHandler DBus error " << ec;
204742cbe538SGunnar Mills             return;
204842cbe538SGunnar Mills         }
204926f6976fSEd Tanous         if (subtree.empty())
205042cbe538SGunnar Mills         {
205142cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!";
205242cbe538SGunnar Mills             callback(inventoryItems);
205342cbe538SGunnar Mills             return;
205442cbe538SGunnar Mills         }
205542cbe538SGunnar Mills 
205642cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
205742cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
205842cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2059fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
206042cbe538SGunnar Mills 
206142cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
206242cbe538SGunnar Mills         {
206342cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
206442cbe538SGunnar Mills             callback(inventoryItems);
206542cbe538SGunnar Mills             return;
206642cbe538SGunnar Mills         }
206742cbe538SGunnar Mills 
206842cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
206942cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
207042cbe538SGunnar Mills 
207142cbe538SGunnar Mills         if (connection.empty())
207242cbe538SGunnar Mills         {
207342cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
207442cbe538SGunnar Mills             callback(inventoryItems);
207542cbe538SGunnar Mills             return;
207642cbe538SGunnar Mills         }
207742cbe538SGunnar Mills 
207842cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
207942cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> "
208042cbe538SGunnar Mills                          << connection;
208142cbe538SGunnar Mills 
208242cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
208342cbe538SGunnar Mills                                      psAttributesConnections,
208442cbe538SGunnar Mills                                      std::move(callback));
208542cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit";
2086e99073f5SGeorge Liu         });
208742cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit";
208842cbe538SGunnar Mills }
208942cbe538SGunnar Mills 
209042cbe538SGunnar Mills /**
2091adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
20928fb49dd6SShawn McCarney  *
20938fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2094adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
20958fb49dd6SShawn McCarney  *
2096adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2097adc4f0dbSShawn McCarney  * response.
20988fb49dd6SShawn McCarney  *
2099adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2100adc4f0dbSShawn McCarney  * inventory items have been obtained.
2101adc4f0dbSShawn McCarney  *
2102adc4f0dbSShawn McCarney  * The callback must have the following signature:
2103adc4f0dbSShawn McCarney  *   @code
2104adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2105adc4f0dbSShawn McCarney  *   @endcode
21068fb49dd6SShawn McCarney  *
21078fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21088fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21098fb49dd6SShawn McCarney  * implements ObjectManager.
2110adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21118fb49dd6SShawn McCarney  */
2112adc4f0dbSShawn McCarney template <typename Callback>
2113d0090733SEd Tanous static void
2114d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2115fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2116adc4f0dbSShawn McCarney                       Callback&& callback)
21178fb49dd6SShawn McCarney {
2118adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems enter";
2119adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2120d0090733SEd Tanous         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2121adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
2122adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter";
21238fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2124d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2125f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
2126fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
21278fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter";
2128002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2129d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
2130d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter";
213142cbe538SGunnar Mills 
2132002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2133002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
213442cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter";
213542cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2136002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
213742cbe538SGunnar Mills                                              std::move(callback));
213842cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit";
213942cbe538SGunnar Mills                 };
214042cbe538SGunnar Mills 
2141d500549bSAnthony Wilson                 // Find led connections and get the data
2142d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
214342cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
2144d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit";
2145d500549bSAnthony Wilson             };
21468fb49dd6SShawn McCarney 
2147adc4f0dbSShawn McCarney             // Get inventory item data from connections
2148adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2149d0090733SEd Tanous                                   invConnections,
2150d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
21518fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit";
21528fb49dd6SShawn McCarney         };
21538fb49dd6SShawn McCarney 
2154adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2155002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21568fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
2157adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit";
21588fb49dd6SShawn McCarney     };
21598fb49dd6SShawn McCarney 
2160adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2161d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2162adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
2163adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems exit";
2164adc4f0dbSShawn McCarney }
2165adc4f0dbSShawn McCarney 
2166adc4f0dbSShawn McCarney /**
2167adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2168adc4f0dbSShawn McCarney  *
2169adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2170adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2171adc4f0dbSShawn McCarney  * array.
2172adc4f0dbSShawn McCarney  *
2173adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2174adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2175adc4f0dbSShawn McCarney  * object.
2176adc4f0dbSShawn McCarney  *
2177adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2178adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2179adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2180adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2181adc4f0dbSShawn McCarney  */
218223a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2183adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2184adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2185adc4f0dbSShawn McCarney {
2186adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2187adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2188adc4f0dbSShawn McCarney     {
2189f7afb17bSAlexander Hansen         if (powerSupply["Name"] ==
2190f7afb17bSAlexander Hansen             boost::replace_all_copy(inventoryItem.name, "_", " "))
2191adc4f0dbSShawn McCarney         {
2192adc4f0dbSShawn McCarney             return powerSupply;
2193adc4f0dbSShawn McCarney         }
2194adc4f0dbSShawn McCarney     }
2195adc4f0dbSShawn McCarney 
2196adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2197adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2198adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2199*ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2200*ef4c65b7SEd Tanous                                                chassisId);
2201eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2202eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
2203adc4f0dbSShawn McCarney     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2204adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2205adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2206adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2207adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2208d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2209adc4f0dbSShawn McCarney 
221042cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
221142cbe538SGunnar Mills     {
221242cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
221342cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
221442cbe538SGunnar Mills     }
221542cbe538SGunnar Mills 
221642cbe538SGunnar Mills     powerSupply["Status"]["State"] = getState(&inventoryItem);
2217adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2218adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2219adc4f0dbSShawn McCarney 
2220adc4f0dbSShawn McCarney     return powerSupply;
22218fb49dd6SShawn McCarney }
22228fb49dd6SShawn McCarney 
22238fb49dd6SShawn McCarney /**
2224de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2225de629b6eSShawn McCarney  *
2226de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2227de629b6eSShawn McCarney  *
2228de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2229de629b6eSShawn McCarney  * information has been obtained.
2230de629b6eSShawn McCarney  *
2231adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2232de629b6eSShawn McCarney  *
2233de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2234de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2235de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2236de629b6eSShawn McCarney  *
2237de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2238de629b6eSShawn McCarney  *
2239adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2240adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2241adc4f0dbSShawn McCarney  *
2242de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2243adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2244de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2245de629b6eSShawn McCarney  * implements ObjectManager.
2246adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2247de629b6eSShawn McCarney  */
224823a21a1cSEd Tanous inline void getSensorData(
224981ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2250fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2251fe04d49cSNan Zhou     const std::set<std::string>& connections,
2252b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2253de629b6eSShawn McCarney {
2254de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData enter";
2255de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2256de629b6eSShawn McCarney     for (const std::string& connection : connections)
2257de629b6eSShawn McCarney     {
2258de629b6eSShawn McCarney         // Response handler to process managed objects
2259002d39b4SEd Tanous         auto getManagedObjectsCb =
2260002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
22615e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
226202cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
2263de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
2264de629b6eSShawn McCarney             if (ec)
2265de629b6eSShawn McCarney             {
2266de629b6eSShawn McCarney                 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
22678d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2268de629b6eSShawn McCarney                 return;
2269de629b6eSShawn McCarney             }
2270de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2271de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2272de629b6eSShawn McCarney             {
2273de629b6eSShawn McCarney                 const std::string& objPath =
2274de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
2275de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
2276de629b6eSShawn McCarney                                  << objPath;
2277de629b6eSShawn McCarney 
2278de629b6eSShawn McCarney                 std::vector<std::string> split;
2279de629b6eSShawn McCarney                 // Reserve space for
2280de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2281de629b6eSShawn McCarney                 split.reserve(6);
228250ebd4afSEd Tanous                 // NOLINTNEXTLINE
228350ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2284de629b6eSShawn McCarney                 if (split.size() < 6)
2285de629b6eSShawn McCarney                 {
2286de629b6eSShawn McCarney                     BMCWEB_LOG_ERROR << "Got path that isn't long enough "
2287de629b6eSShawn McCarney                                      << objPath;
2288de629b6eSShawn McCarney                     continue;
2289de629b6eSShawn McCarney                 }
229050ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2291de629b6eSShawn McCarney                 // string at the beginning
2292de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2293de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
2294de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "sensorName " << sensorName
2295de629b6eSShawn McCarney                                  << " sensorType " << sensorType;
229649c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2297de629b6eSShawn McCarney                 {
2298accdbb2cSAndrew Geissler                     BMCWEB_LOG_DEBUG << sensorName << " not in sensor list ";
2299de629b6eSShawn McCarney                     continue;
2300de629b6eSShawn McCarney                 }
2301de629b6eSShawn McCarney 
2302adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2303adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2304adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2305adc4f0dbSShawn McCarney 
230695a3ecadSAnthony Wilson                 const std::string& sensorSchema =
230781ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
230895a3ecadSAnthony Wilson 
230995a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
231095a3ecadSAnthony Wilson 
2311928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2312928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
231395a3ecadSAnthony Wilson                 {
2314c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
2315c1d019a6SEd Tanous                     sensorTypeEscaped.erase(
2316c1d019a6SEd Tanous                         std::remove(sensorTypeEscaped.begin(),
2317c1d019a6SEd Tanous                                     sensorTypeEscaped.end(), '_'),
2318c1d019a6SEd Tanous                         sensorTypeEscaped.end());
2319c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2320c1d019a6SEd Tanous                     sensorId += "_";
2321c1d019a6SEd Tanous                     sensorId += sensorName;
2322c1d019a6SEd Tanous 
23238d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2324*ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2325c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2326*ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2327*ef4c65b7SEd Tanous                                             sensorId);
23288d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
232995a3ecadSAnthony Wilson                 }
233095a3ecadSAnthony Wilson                 else
233195a3ecadSAnthony Wilson                 {
2332271584abSEd Tanous                     std::string fieldName;
2333928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2334928fefb9SNan Zhou                     {
2335928fefb9SNan Zhou                         fieldName = "Members";
2336928fefb9SNan Zhou                     }
2337928fefb9SNan Zhou                     else if (sensorType == "temperature")
2338de629b6eSShawn McCarney                     {
2339de629b6eSShawn McCarney                         fieldName = "Temperatures";
2340de629b6eSShawn McCarney                     }
2341de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2342de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2343de629b6eSShawn McCarney                     {
2344de629b6eSShawn McCarney                         fieldName = "Fans";
2345de629b6eSShawn McCarney                     }
2346de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2347de629b6eSShawn McCarney                     {
2348de629b6eSShawn McCarney                         fieldName = "Voltages";
2349de629b6eSShawn McCarney                     }
2350de629b6eSShawn McCarney                     else if (sensorType == "power")
2351de629b6eSShawn McCarney                     {
235255f79e6fSEd Tanous                         if (sensorName == "total_power")
2353028f7ebcSEddie James                         {
2354028f7ebcSEddie James                             fieldName = "PowerControl";
2355028f7ebcSEddie James                         }
2356adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2357adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2358028f7ebcSEddie James                         {
2359de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2360de629b6eSShawn McCarney                         }
2361adc4f0dbSShawn McCarney                         else
2362adc4f0dbSShawn McCarney                         {
2363adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2364adc4f0dbSShawn McCarney                             continue;
2365adc4f0dbSShawn McCarney                         }
2366028f7ebcSEddie James                     }
2367de629b6eSShawn McCarney                     else
2368de629b6eSShawn McCarney                     {
2369de629b6eSShawn McCarney                         BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
2370de629b6eSShawn McCarney                                          << sensorType;
2371de629b6eSShawn McCarney                         continue;
2372de629b6eSShawn McCarney                     }
2373de629b6eSShawn McCarney 
2374de629b6eSShawn McCarney                     nlohmann::json& tempArray =
23758d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2376adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
237749c53ac9SJohnathan Mantey                     {
2378adc4f0dbSShawn McCarney                         if (tempArray.empty())
23797ab06f49SGunnar Mills                         {
238095a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
238195a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
238295a3ecadSAnthony Wilson                             // naming in power.hpp.
23831476687dSEd Tanous                             nlohmann::json::object_t power;
2384*ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2385*ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2386eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2387eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2388eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2389eddfc437SWilly Tu                                                  .to_string());
2390eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2391b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2392adc4f0dbSShawn McCarney                         }
2393adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2394adc4f0dbSShawn McCarney                     }
2395adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2396adc4f0dbSShawn McCarney                     {
2397adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2398adc4f0dbSShawn McCarney                         {
2399adc4f0dbSShawn McCarney                             sensorJson =
2400adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
240181ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2402adc4f0dbSShawn McCarney                         }
240349c53ac9SJohnathan Mantey                     }
2404928fefb9SNan Zhou                     else if (fieldName == "Members")
2405928fefb9SNan Zhou                     {
2406677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
2407677bb756SEd Tanous                         sensorTypeEscaped.erase(
2408677bb756SEd Tanous                             std::remove(sensorTypeEscaped.begin(),
2409677bb756SEd Tanous                                         sensorTypeEscaped.end(), '_'),
2410677bb756SEd Tanous                             sensorTypeEscaped.end());
2411677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2412677bb756SEd Tanous                         sensorId += "_";
2413677bb756SEd Tanous                         sensorId += sensorName;
2414677bb756SEd Tanous 
24151476687dSEd Tanous                         nlohmann::json::object_t member;
2416*ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2417*ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2418677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2419677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2420b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2421928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2422928fefb9SNan Zhou                     }
242349c53ac9SJohnathan Mantey                     else
242449c53ac9SJohnathan Mantey                     {
24251476687dSEd Tanous                         nlohmann::json::object_t member;
2426*ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2427*ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2428eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2429eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2430eddfc437SWilly Tu                         url.set_fragment(
2431eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2432eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2433b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2434adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
243549c53ac9SJohnathan Mantey                     }
243695a3ecadSAnthony Wilson                 }
2437de629b6eSShawn McCarney 
2438adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2439adc4f0dbSShawn McCarney                 {
24401d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24411d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24421d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24431d7c0054SEd Tanous                                            inventoryItem);
24441d7c0054SEd Tanous 
24451d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24461d7c0054SEd Tanous                     path += sensorType;
24471d7c0054SEd Tanous                     path += "/";
24481d7c0054SEd Tanous                     path += sensorName;
2449c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2450adc4f0dbSShawn McCarney                 }
2451de629b6eSShawn McCarney             }
245281ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
245349c53ac9SJohnathan Mantey             {
245481ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2455928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2456928fefb9SNan Zhou                         sensors::node::sensors &&
2457928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2458928fefb9SNan Zhou                 {
2459928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2460928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2461928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2462928fefb9SNan Zhou                             .size();
2463928fefb9SNan Zhou                 }
2464928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2465928fefb9SNan Zhou                          sensors::node::thermal)
24668bd25ccdSJames Feist                 {
246781ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
24688bd25ccdSJames Feist                 }
246949c53ac9SJohnathan Mantey             }
2470de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
2471de629b6eSShawn McCarney         };
2472de629b6eSShawn McCarney 
2473de629b6eSShawn McCarney         crow::connections::systemBus->async_method_call(
2474d0090733SEd Tanous             getManagedObjectsCb, connection, "/xyz/openbmc_project/sensors",
2475de629b6eSShawn McCarney             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
247623a21a1cSEd Tanous     }
2477de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData exit";
2478de629b6eSShawn McCarney }
2479de629b6eSShawn McCarney 
2480fe04d49cSNan Zhou inline void
2481fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2482fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
24831abe55efSEd Tanous {
2484fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2485fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
248655c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb enter";
2487adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2488d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2489d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2490adc4f0dbSShawn McCarney                               inventoryItems) {
2491adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter";
249249c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2493002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2494d0090733SEd Tanous                           inventoryItems);
2495adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit";
2496adc4f0dbSShawn McCarney         };
2497adc4f0dbSShawn McCarney 
2498adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2499d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2500adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2501adc4f0dbSShawn McCarney 
250255c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb exit";
250308777fb0SLewanczyk, Dawid     };
2504de629b6eSShawn McCarney 
2505de629b6eSShawn McCarney     // Get set of connections that provide sensor values
250681ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
250795a3ecadSAnthony Wilson }
250895a3ecadSAnthony Wilson 
250995a3ecadSAnthony Wilson /**
251095a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
251195a3ecadSAnthony Wilson  *        chassis.
251295a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
251395a3ecadSAnthony Wilson  */
2514b5a76932SEd Tanous inline void
251581ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
251695a3ecadSAnthony Wilson {
251795a3ecadSAnthony Wilson     BMCWEB_LOG_DEBUG << "getChassisData enter";
251895a3ecadSAnthony Wilson     auto getChassisCb =
251981ce609eSEd Tanous         [sensorsAsyncResp](
2520fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
252195a3ecadSAnthony Wilson         BMCWEB_LOG_DEBUG << "getChassisCb enter";
252281ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
252355c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassisCb exit";
252408777fb0SLewanczyk, Dawid     };
2525928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2526928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2527928fefb9SNan Zhou     {
25288d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25298d1b46d7Szhanghch05             nlohmann::json::array();
2530928fefb9SNan Zhou     }
253126f03899SShawn McCarney     // Get set of sensors in chassis
25327f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25337f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25347f1cc26dSEd Tanous                std::move(getChassisCb));
253555c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassisData exit";
2536271584abSEd Tanous }
253708777fb0SLewanczyk, Dawid 
2538413961deSRichard Marian Thomaiyar /**
253949c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
254049c53ac9SJohnathan Mantey  * the chassis node
254149c53ac9SJohnathan Mantey  *
254249c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
254349c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
254449c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
254549c53ac9SJohnathan Mantey  *                         repeated calls to this function
254649c53ac9SJohnathan Mantey  */
2547fe04d49cSNan Zhou inline bool
2548fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
254902cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2550fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
255149c53ac9SJohnathan Mantey {
2552fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
255349c53ac9SJohnathan Mantey     {
255428aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2555b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
255628aa8de5SGeorge Liu         if (thisSensorName.empty())
255749c53ac9SJohnathan Mantey         {
255849c53ac9SJohnathan Mantey             continue;
255949c53ac9SJohnathan Mantey         }
256049c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
256149c53ac9SJohnathan Mantey         {
256249c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
256349c53ac9SJohnathan Mantey             return true;
256449c53ac9SJohnathan Mantey         }
256549c53ac9SJohnathan Mantey     }
256649c53ac9SJohnathan Mantey     return false;
256749c53ac9SJohnathan Mantey }
256849c53ac9SJohnathan Mantey 
2569c71d6125SEd Tanous inline std::pair<std::string, std::string>
2570c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2571c71d6125SEd Tanous {
2572c71d6125SEd Tanous     size_t index = sensorId.find('_');
2573c71d6125SEd Tanous     if (index == std::string::npos)
2574c71d6125SEd Tanous     {
2575c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2576c71d6125SEd Tanous     }
2577c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2578c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2579c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2580c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2581c71d6125SEd Tanous     {
2582c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2583c71d6125SEd Tanous     }
2584c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2585c71d6125SEd Tanous }
2586c71d6125SEd Tanous 
258749c53ac9SJohnathan Mantey /**
2588413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2589413961deSRichard Marian Thomaiyar  *
25908d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
25914bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2592413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2593413961deSRichard Marian Thomaiyar  */
259423a21a1cSEd Tanous inline void setSensorsOverride(
2595b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
25964bb3dc34SCarol Wang     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2597397fd61fSjayaprakash Mutyala         allCollections)
2598413961deSRichard Marian Thomaiyar {
259970d1d0aaSjayaprakash Mutyala     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
26004bb3dc34SCarol Wang                     << sensorAsyncResp->chassisSubNode << "\n";
2601413961deSRichard Marian Thomaiyar 
2602543f4400SEd Tanous     const char* propertyValueName = nullptr;
2603f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2604413961deSRichard Marian Thomaiyar     std::string memberId;
2605543f4400SEd Tanous     double value = 0.0;
2606f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2607f65af9e8SRichard Marian Thomaiyar     {
2608f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2609f65af9e8SRichard Marian Thomaiyar         {
2610f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2611f65af9e8SRichard Marian Thomaiyar         }
2612f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2613f65af9e8SRichard Marian Thomaiyar         {
2614f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2615f65af9e8SRichard Marian Thomaiyar         }
2616f65af9e8SRichard Marian Thomaiyar         else
2617f65af9e8SRichard Marian Thomaiyar         {
2618f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2619f65af9e8SRichard Marian Thomaiyar         }
2620f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2621f65af9e8SRichard Marian Thomaiyar         {
26228d1b46d7Szhanghch05             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
26238d1b46d7Szhanghch05                                      "MemberId", memberId, propertyValueName,
26248d1b46d7Szhanghch05                                      value))
2625413961deSRichard Marian Thomaiyar             {
2626413961deSRichard Marian Thomaiyar                 return;
2627413961deSRichard Marian Thomaiyar             }
2628f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2629f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2630f65af9e8SRichard Marian Thomaiyar         }
2631f65af9e8SRichard Marian Thomaiyar     }
26324bb3dc34SCarol Wang 
2633002d39b4SEd Tanous     auto getChassisSensorListCb =
2634002d39b4SEd Tanous         [sensorAsyncResp, overrideMap](
2635fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
263649c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
263749c53ac9SJohnathan Mantey         // chassis node
2638fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2639fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2640f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2641413961deSRichard Marian Thomaiyar         {
2642f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2643c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2644c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2645c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2646c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2647f65af9e8SRichard Marian Thomaiyar             {
2648f65af9e8SRichard Marian Thomaiyar                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
26498d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2650f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2651413961deSRichard Marian Thomaiyar                 return;
2652413961deSRichard Marian Thomaiyar             }
2653f65af9e8SRichard Marian Thomaiyar         }
2654413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2655002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2656fe04d49cSNan Zhou             [sensorAsyncResp,
2657fe04d49cSNan Zhou              overrideMap](const std::set<std::string>& /*connections*/,
2658002d39b4SEd Tanous                           const std::set<std::pair<std::string, std::string>>&
2659413961deSRichard Marian Thomaiyar                               objectsWithConnection) {
2660f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2661413961deSRichard Marian Thomaiyar             {
2662413961deSRichard Marian Thomaiyar                 BMCWEB_LOG_INFO
2663f65af9e8SRichard Marian Thomaiyar                     << "Unable to find all objects with proper connection "
2664f65af9e8SRichard Marian Thomaiyar                     << objectsWithConnection.size() << " requested "
2665f65af9e8SRichard Marian Thomaiyar                     << overrideMap.size() << "\n";
26664f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2667a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2668a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2669413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2670413961deSRichard Marian Thomaiyar                                                : "Voltages",
2671f65af9e8SRichard Marian Thomaiyar                                            "Count");
2672f65af9e8SRichard Marian Thomaiyar                 return;
2673f65af9e8SRichard Marian Thomaiyar             }
2674f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2675f65af9e8SRichard Marian Thomaiyar             {
267628aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
267728aa8de5SGeorge Liu                 std::string sensorName = path.filename();
267828aa8de5SGeorge Liu                 if (sensorName.empty())
2679f65af9e8SRichard Marian Thomaiyar                 {
26804f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2681f65af9e8SRichard Marian Thomaiyar                     return;
2682f65af9e8SRichard Marian Thomaiyar                 }
2683f65af9e8SRichard Marian Thomaiyar 
2684f65af9e8SRichard Marian Thomaiyar                 const auto& iterator = overrideMap.find(sensorName);
2685f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2686f65af9e8SRichard Marian Thomaiyar                 {
2687f65af9e8SRichard Marian Thomaiyar                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2688f65af9e8SRichard Marian Thomaiyar                                     << item.first << "\n";
26894f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2690413961deSRichard Marian Thomaiyar                     return;
2691413961deSRichard Marian Thomaiyar                 }
2692413961deSRichard Marian Thomaiyar                 crow::connections::systemBus->async_method_call(
26935e7e2dc5SEd Tanous                     [sensorAsyncResp](const boost::system::error_code& ec) {
2694413961deSRichard Marian Thomaiyar                     if (ec)
2695413961deSRichard Marian Thomaiyar                     {
26964f277b54SJayaprakash Mutyala                         if (ec.value() ==
26974f277b54SJayaprakash Mutyala                             boost::system::errc::permission_denied)
26984f277b54SJayaprakash Mutyala                         {
26994f277b54SJayaprakash Mutyala                             BMCWEB_LOG_WARNING
27004f277b54SJayaprakash Mutyala                                 << "Manufacturing mode is not Enabled...can't "
27014f277b54SJayaprakash Mutyala                                    "Override the sensor value. ";
27024f277b54SJayaprakash Mutyala 
27034f277b54SJayaprakash Mutyala                             messages::insufficientPrivilege(
27048d1b46d7Szhanghch05                                 sensorAsyncResp->asyncResp->res);
2705413961deSRichard Marian Thomaiyar                             return;
2706413961deSRichard Marian Thomaiyar                         }
27074f277b54SJayaprakash Mutyala                         BMCWEB_LOG_DEBUG
27084f277b54SJayaprakash Mutyala                             << "setOverrideValueStatus DBUS error: " << ec;
27094f277b54SJayaprakash Mutyala                         messages::internalError(
27104f277b54SJayaprakash Mutyala                             sensorAsyncResp->asyncResp->res);
27114f277b54SJayaprakash Mutyala                     }
2712413961deSRichard Marian Thomaiyar                     },
27134f277b54SJayaprakash Mutyala                     item.second, item.first, "org.freedesktop.DBus.Properties",
27144f277b54SJayaprakash Mutyala                     "Set", "xyz.openbmc_project.Sensor.Value", "Value",
2715168e20c1SEd Tanous                     dbus::utility::DbusVariantType(iterator->second.first));
2716f65af9e8SRichard Marian Thomaiyar             }
2717413961deSRichard Marian Thomaiyar         };
2718413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2719413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2720413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2721413961deSRichard Marian Thomaiyar     };
2722413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27237f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27247f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27257f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2726413961deSRichard Marian Thomaiyar }
2727413961deSRichard Marian Thomaiyar 
2728a0ec28b6SAdrian Ambrożewicz /**
2729a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2730a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2731a0ec28b6SAdrian Ambrożewicz  *
2732a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2733a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2734a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2735a0ec28b6SAdrian Ambrożewicz  *
2736a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2737a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2738a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2739a0ec28b6SAdrian Ambrożewicz  */
2740021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2741021d32cfSKrzysztof Grobelny                                  const std::string& node,
2742a0ec28b6SAdrian Ambrożewicz                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2743a0ec28b6SAdrian Ambrożewicz {
274402da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
274502da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
274602da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
274702da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2748a0ec28b6SAdrian Ambrożewicz     {
2749a0ec28b6SAdrian Ambrożewicz         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2750a0ec28b6SAdrian Ambrożewicz         mapComplete(boost::beast::http::status::bad_request, {});
2751a0ec28b6SAdrian Ambrożewicz         return;
2752a0ec28b6SAdrian Ambrożewicz     }
2753d51e072fSKrzysztof Grobelny 
275472374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2755fe04d49cSNan Zhou     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2756a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2757fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2758fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2759fe04d49cSNan Zhou     };
2760a0ec28b6SAdrian Ambrożewicz 
2761a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2762d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2763a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2764a0ec28b6SAdrian Ambrożewicz }
2765a0ec28b6SAdrian Ambrożewicz 
2766bacb2162SNan Zhou namespace sensors
2767bacb2162SNan Zhou {
2768928fefb9SNan Zhou 
2769bacb2162SNan Zhou inline void getChassisCallback(
2770c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2771c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2772fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2773bacb2162SNan Zhou {
2774bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2775bacb2162SNan Zhou 
2776c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2777c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2778bacb2162SNan Zhou     {
2779bacb2162SNan Zhou         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2780bacb2162SNan Zhou 
2781bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2782bacb2162SNan Zhou         std::string sensorName = path.filename();
2783bacb2162SNan Zhou         if (sensorName.empty())
2784bacb2162SNan Zhou         {
2785bacb2162SNan Zhou             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2786c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2787bacb2162SNan Zhou             return;
2788bacb2162SNan Zhou         }
2789c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2790c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2791c1d019a6SEd Tanous         // type in the URI
2792c1d019a6SEd Tanous         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2793c1d019a6SEd Tanous 
27941476687dSEd Tanous         nlohmann::json::object_t member;
2795c1d019a6SEd Tanous         std::string id = type;
2796c1d019a6SEd Tanous         id += "_";
2797c1d019a6SEd Tanous         id += sensorName;
2798*ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2799*ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2800c1d019a6SEd Tanous 
2801b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2802bacb2162SNan Zhou     }
2803bacb2162SNan Zhou 
2804c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2805bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2806bacb2162SNan Zhou }
2807e6bd846dSNan Zhou 
2808de167a6fSNan Zhou inline void
2809de167a6fSNan Zhou     handleSensorCollectionGet(App& app, const crow::Request& req,
2810de167a6fSNan Zhou                               const std::shared_ptr<bmcweb::AsyncResp>& aResp,
2811de167a6fSNan Zhou                               const std::string& chassisId)
2812de167a6fSNan Zhou {
2813de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2814de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2815de167a6fSNan Zhou     };
2816de167a6fSNan Zhou     query_param::Query delegatedQuery;
28173ba00073SCarson Labrado     if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp,
2818de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2819de167a6fSNan Zhou     {
2820de167a6fSNan Zhou         return;
2821de167a6fSNan Zhou     }
2822de167a6fSNan Zhou 
2823de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2824de167a6fSNan Zhou     {
2825de167a6fSNan Zhou         // we perform efficient expand.
2826de167a6fSNan Zhou         auto asyncResp = std::make_shared<SensorsAsyncResp>(
2827de167a6fSNan Zhou             aResp, chassisId, sensors::dbus::sensorPaths,
2828de167a6fSNan Zhou             sensors::node::sensors,
2829de167a6fSNan Zhou             /*efficientExpand=*/true);
2830de167a6fSNan Zhou         getChassisData(asyncResp);
2831de167a6fSNan Zhou 
2832de167a6fSNan Zhou         BMCWEB_LOG_DEBUG
2833de167a6fSNan Zhou             << "SensorCollection doGet exit via efficient expand handler";
2834de167a6fSNan Zhou         return;
28350bad320cSEd Tanous     }
2836de167a6fSNan Zhou 
2837de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2838de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2839c1d019a6SEd Tanous     getChassis(aResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2840c1d019a6SEd Tanous                std::bind_front(sensors::getChassisCallback, aResp, chassisId,
2841c1d019a6SEd Tanous                                sensors::node::sensors));
2842c1d019a6SEd Tanous }
28437f1cc26dSEd Tanous 
2844c1d019a6SEd Tanous inline void
2845c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2846c1d019a6SEd Tanous                       const std::string& sensorPath,
2847c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2848c1d019a6SEd Tanous {
2849c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2850c1d019a6SEd Tanous     {
2851c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2852c1d019a6SEd Tanous         return;
2853c1d019a6SEd Tanous     }
2854c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2855c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
2856c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2857c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2858c1343bf6SKrzysztof Grobelny 
2859c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2860c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2861c1d019a6SEd Tanous         [asyncResp,
28625e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2863c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2864c1d019a6SEd Tanous         if (ec)
2865c1d019a6SEd Tanous         {
2866c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2867c1d019a6SEd Tanous             return;
2868c1d019a6SEd Tanous         }
2869c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2870c1d019a6SEd Tanous         std::string name = path.filename();
2871c1d019a6SEd Tanous         path = path.parent_path();
2872c1d019a6SEd Tanous         std::string type = path.filename();
2873c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2874c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2875c1343bf6SKrzysztof Grobelny         });
2876de167a6fSNan Zhou }
2877de167a6fSNan Zhou 
2878e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2879c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2880677bb756SEd Tanous                             const std::string& chassisId,
2881c1d019a6SEd Tanous                             const std::string& sensorId)
2882e6bd846dSNan Zhou {
2883c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2884e6bd846dSNan Zhou     {
2885e6bd846dSNan Zhou         return;
2886e6bd846dSNan Zhou     }
2887c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2888c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2889c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2890c1d019a6SEd Tanous     {
2891c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2892c1d019a6SEd Tanous         return;
2893c1d019a6SEd Tanous     }
2894c71d6125SEd Tanous 
2895*ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2896*ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2897c1d019a6SEd Tanous 
2898e6bd846dSNan Zhou     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
2899e6bd846dSNan Zhou 
29002b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2901e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2902c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2903c71d6125SEd Tanous                              '/' + nameType.second;
2904e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2905e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29062b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29072b73119cSGeorge Liu         sensorPath, interfaces,
2908c71d6125SEd Tanous         [asyncResp,
29092b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2910c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
2911e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 enter";
2912e6bd846dSNan Zhou         if (ec)
2913e6bd846dSNan Zhou         {
2914c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2915e6bd846dSNan Zhou             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
2916e6bd846dSNan Zhou                              << "Dbus error " << ec;
2917e6bd846dSNan Zhou             return;
2918e6bd846dSNan Zhou         }
2919c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
2920e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 exit";
29212b73119cSGeorge Liu         });
2922e6bd846dSNan Zhou }
2923e6bd846dSNan Zhou 
2924bacb2162SNan Zhou } // namespace sensors
2925bacb2162SNan Zhou 
29267e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
292795a3ecadSAnthony Wilson {
29287e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2929ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2930002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2931de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
293295a3ecadSAnthony Wilson }
293395a3ecadSAnthony Wilson 
29347e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
293595a3ecadSAnthony Wilson {
29367e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2937ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2938002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2939e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
294095a3ecadSAnthony Wilson }
294195a3ecadSAnthony Wilson 
294208777fb0SLewanczyk, Dawid } // namespace redfish
2943