xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision c71d61258bd3cd8573166011b450a1eecce2c572)
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 
180ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
190ec8b83dSEd Tanous 
207e860f15SJohn Edward Broadbent #include <app.hpp>
2111ba3979SEd Tanous #include <boost/algorithm/string/classification.hpp>
221d7c0054SEd Tanous #include <boost/algorithm/string/find.hpp>
231d7c0054SEd Tanous #include <boost/algorithm/string/predicate.hpp>
24*c71d6125SEd Tanous #include <boost/algorithm/string/replace.hpp>
2508777fb0SLewanczyk, Dawid #include <boost/algorithm/string/split.hpp>
2608777fb0SLewanczyk, Dawid #include <boost/range/algorithm/replace_copy_if.hpp>
271abe55efSEd Tanous #include <dbus_singleton.hpp>
28168e20c1SEd Tanous #include <dbus_utility.hpp>
2945ca1b86SEd Tanous #include <query.hpp>
30ed398213SEd Tanous #include <registries/privilege_registry.hpp>
311e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3286d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
3386d89ed7SKrzysztof Grobelny #include <utils/dbus_utils.hpp>
34413961deSRichard Marian Thomaiyar #include <utils/json_utils.hpp>
35928fefb9SNan Zhou #include <utils/query_param.hpp>
361214b7e7SGunnar Mills 
371214b7e7SGunnar Mills #include <cmath>
38fe04d49cSNan Zhou #include <iterator>
39fe04d49cSNan Zhou #include <map>
40fe04d49cSNan Zhou #include <set>
41b5a76932SEd Tanous #include <utility>
42abf2add6SEd Tanous #include <variant>
4308777fb0SLewanczyk, Dawid 
441abe55efSEd Tanous namespace redfish
451abe55efSEd Tanous {
4608777fb0SLewanczyk, Dawid 
47a0ec28b6SAdrian Ambrożewicz namespace sensors
48a0ec28b6SAdrian Ambrożewicz {
49a0ec28b6SAdrian Ambrożewicz namespace node
50a0ec28b6SAdrian Ambrożewicz {
51a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
52a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
53a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
54a0ec28b6SAdrian Ambrożewicz } // namespace node
55a0ec28b6SAdrian Ambrożewicz 
5602da7c5aSEd Tanous // clang-format off
57a0ec28b6SAdrian Ambrożewicz namespace dbus
58a0ec28b6SAdrian Ambrożewicz {
594ee8e211SEd Tanous static auto powerPaths = std::to_array<std::string_view>({
6002da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6102da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6202da7c5aSEd Tanous });
63c2bf7f99SWludzik, Jozef 
644ee8e211SEd Tanous static auto sensorPaths = std::to_array<std::string_view>({
6502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
66a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
677088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
685deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
69e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
70e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
71e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
72e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
73e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
74e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
75e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
76e8204933SGeorge Liu #endif
7702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
7802da7c5aSEd Tanous });
7902da7c5aSEd Tanous 
804ee8e211SEd Tanous static auto thermalPaths = std::to_array<std::string_view>({
8102da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
82a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
8402da7c5aSEd Tanous });
8502da7c5aSEd Tanous 
86c2bf7f99SWludzik, Jozef } // namespace dbus
8702da7c5aSEd Tanous // clang-format on
8802da7c5aSEd Tanous 
8902da7c5aSEd Tanous using sensorPair = std::pair<std::string_view, std::span<std::string_view>>;
9002da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
9102da7c5aSEd Tanous     {{node::power, std::span<std::string_view>(dbus::powerPaths)},
9202da7c5aSEd Tanous      {node::sensors, std::span<std::string_view>(dbus::sensorPaths)},
9302da7c5aSEd Tanous      {node::thermal, std::span<std::string_view>(dbus::thermalPaths)}}};
94c2bf7f99SWludzik, Jozef 
950ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
96c2bf7f99SWludzik, Jozef {
97c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
98c2bf7f99SWludzik, Jozef     {
990ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
100c2bf7f99SWludzik, Jozef     }
101c2bf7f99SWludzik, Jozef     if (sensorType == "power")
102c2bf7f99SWludzik, Jozef     {
1030ec8b83dSEd Tanous         return sensor::ReadingType::Power;
104c2bf7f99SWludzik, Jozef     }
105c2bf7f99SWludzik, Jozef     if (sensorType == "current")
106c2bf7f99SWludzik, Jozef     {
1070ec8b83dSEd Tanous         return sensor::ReadingType::Current;
108c2bf7f99SWludzik, Jozef     }
109c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
110c2bf7f99SWludzik, Jozef     {
1110ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
112c2bf7f99SWludzik, Jozef     }
113c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
114c2bf7f99SWludzik, Jozef     {
1150ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
116c2bf7f99SWludzik, Jozef     }
117c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
118c2bf7f99SWludzik, Jozef     {
1190ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
120c2bf7f99SWludzik, Jozef     }
1215deabed9SGunnar Mills     if (sensorType == "humidity")
1225deabed9SGunnar Mills     {
1230ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1245deabed9SGunnar Mills     }
125c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
126c2bf7f99SWludzik, Jozef     {
1270ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
128c2bf7f99SWludzik, Jozef     }
129c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
130c2bf7f99SWludzik, Jozef     {
1310ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
132c2bf7f99SWludzik, Jozef     }
133c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
134c2bf7f99SWludzik, Jozef     {
1350ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
136c2bf7f99SWludzik, Jozef     }
1370ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
138c2bf7f99SWludzik, Jozef }
139c2bf7f99SWludzik, Jozef 
1401d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
141c2bf7f99SWludzik, Jozef {
142c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
143c2bf7f99SWludzik, Jozef     {
144c2bf7f99SWludzik, Jozef         return "V";
145c2bf7f99SWludzik, Jozef     }
146c2bf7f99SWludzik, Jozef     if (sensorType == "power")
147c2bf7f99SWludzik, Jozef     {
148c2bf7f99SWludzik, Jozef         return "W";
149c2bf7f99SWludzik, Jozef     }
150c2bf7f99SWludzik, Jozef     if (sensorType == "current")
151c2bf7f99SWludzik, Jozef     {
152c2bf7f99SWludzik, Jozef         return "A";
153c2bf7f99SWludzik, Jozef     }
154c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
155c2bf7f99SWludzik, Jozef     {
156c2bf7f99SWludzik, Jozef         return "RPM";
157c2bf7f99SWludzik, Jozef     }
158c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
159c2bf7f99SWludzik, Jozef     {
160c2bf7f99SWludzik, Jozef         return "Cel";
161c2bf7f99SWludzik, Jozef     }
1625deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1635deabed9SGunnar Mills         sensorType == "humidity")
164c2bf7f99SWludzik, Jozef     {
165c2bf7f99SWludzik, Jozef         return "%";
166c2bf7f99SWludzik, Jozef     }
167c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
168c2bf7f99SWludzik, Jozef     {
169c2bf7f99SWludzik, Jozef         return "m";
170c2bf7f99SWludzik, Jozef     }
171c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
172c2bf7f99SWludzik, Jozef     {
173c2bf7f99SWludzik, Jozef         return "cft_i/min";
174c2bf7f99SWludzik, Jozef     }
175c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
176c2bf7f99SWludzik, Jozef     {
177c2bf7f99SWludzik, Jozef         return "J";
178c2bf7f99SWludzik, Jozef     }
179c2bf7f99SWludzik, Jozef     return "";
180a0ec28b6SAdrian Ambrożewicz }
181a0ec28b6SAdrian Ambrożewicz } // namespace sensors
182a0ec28b6SAdrian Ambrożewicz 
18308777fb0SLewanczyk, Dawid /**
184588c3f0dSKowalski, Kamil  * SensorsAsyncResp
18508777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
18608777fb0SLewanczyk, Dawid  */
1871abe55efSEd Tanous class SensorsAsyncResp
1881abe55efSEd Tanous {
18908777fb0SLewanczyk, Dawid   public:
190a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
191a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
192fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
193a0ec28b6SAdrian Ambrożewicz 
194a0ec28b6SAdrian Ambrożewicz     struct SensorData
195a0ec28b6SAdrian Ambrożewicz     {
196a0ec28b6SAdrian Ambrożewicz         const std::string name;
197a0ec28b6SAdrian Ambrożewicz         std::string uri;
198a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
199a0ec28b6SAdrian Ambrożewicz     };
200a0ec28b6SAdrian Ambrożewicz 
2018a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2028d1b46d7Szhanghch05                      const std::string& chassisIdIn,
20302da7c5aSEd Tanous                      std::span<std::string_view> typesIn,
20402da7c5aSEd Tanous                      std::string_view subNode) :
2058a592810SEd Tanous         asyncResp(asyncRespIn),
206928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
207928fefb9SNan Zhou         efficientExpand(false)
2081214b7e7SGunnar Mills     {}
20908777fb0SLewanczyk, Dawid 
210a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2118a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2128d1b46d7Szhanghch05                      const std::string& chassisIdIn,
21302da7c5aSEd Tanous                      std::span<std::string_view> typesIn,
21402da7c5aSEd Tanous                      std::string_view subNode,
215a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2168a592810SEd Tanous         asyncResp(asyncRespIn),
217928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
218928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
219a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
220a0ec28b6SAdrian Ambrożewicz     {}
221a0ec28b6SAdrian Ambrożewicz 
222928fefb9SNan Zhou     // sensor collections expand
2238a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
224928fefb9SNan Zhou                      const std::string& chassisIdIn,
22502da7c5aSEd Tanous                      const std::span<std::string_view> typesIn,
2268a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2278a592810SEd Tanous         asyncResp(asyncRespIn),
228928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2298a592810SEd Tanous         efficientExpand(efficientExpandIn)
230928fefb9SNan Zhou     {}
231928fefb9SNan Zhou 
2321abe55efSEd Tanous     ~SensorsAsyncResp()
2331abe55efSEd Tanous     {
2348d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2358d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2361abe55efSEd Tanous         {
2371abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2381abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2391abe55efSEd Tanous             // proper code
2408d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24108777fb0SLewanczyk, Dawid         }
242a0ec28b6SAdrian Ambrożewicz 
243a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
244a0ec28b6SAdrian Ambrożewicz         {
245fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2468d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
247a0ec28b6SAdrian Ambrożewicz             {
248a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
249a0ec28b6SAdrian Ambrożewicz                 {
250c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
251a0ec28b6SAdrian Ambrożewicz                 }
252a0ec28b6SAdrian Ambrożewicz             }
2538d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
254a0ec28b6SAdrian Ambrożewicz         }
25508777fb0SLewanczyk, Dawid     }
256588c3f0dSKowalski, Kamil 
257ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
258ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
259ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
260ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
261ecd6a3a2SEd Tanous 
262a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
263c1d019a6SEd Tanous                      const std::string& dbusPath)
264a0ec28b6SAdrian Ambrożewicz     {
265a0ec28b6SAdrian Ambrożewicz         if (metadata)
266a0ec28b6SAdrian Ambrożewicz         {
267c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
268c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
269a0ec28b6SAdrian Ambrożewicz         }
270a0ec28b6SAdrian Ambrożewicz     }
271a0ec28b6SAdrian Ambrożewicz 
272a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
273a0ec28b6SAdrian Ambrożewicz     {
274a0ec28b6SAdrian Ambrożewicz         if (metadata)
275a0ec28b6SAdrian Ambrożewicz         {
276a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
277a0ec28b6SAdrian Ambrożewicz             {
278a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
279a0ec28b6SAdrian Ambrożewicz                 {
280a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
281a0ec28b6SAdrian Ambrożewicz                 }
282a0ec28b6SAdrian Ambrożewicz             }
283a0ec28b6SAdrian Ambrożewicz         }
284a0ec28b6SAdrian Ambrożewicz     }
285a0ec28b6SAdrian Ambrożewicz 
2868d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
287a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
28802da7c5aSEd Tanous     const std::span<std::string_view> types;
289a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
290928fefb9SNan Zhou     const bool efficientExpand;
291a0ec28b6SAdrian Ambrożewicz 
292a0ec28b6SAdrian Ambrożewicz   private:
293a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
294a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
29508777fb0SLewanczyk, Dawid };
29608777fb0SLewanczyk, Dawid 
29708777fb0SLewanczyk, Dawid /**
298d500549bSAnthony Wilson  * Possible states for physical inventory leds
299d500549bSAnthony Wilson  */
300d500549bSAnthony Wilson enum class LedState
301d500549bSAnthony Wilson {
302d500549bSAnthony Wilson     OFF,
303d500549bSAnthony Wilson     ON,
304d500549bSAnthony Wilson     BLINK,
305d500549bSAnthony Wilson     UNKNOWN
306d500549bSAnthony Wilson };
307d500549bSAnthony Wilson 
308d500549bSAnthony Wilson /**
309adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
310adc4f0dbSShawn McCarney  */
311adc4f0dbSShawn McCarney class InventoryItem
312adc4f0dbSShawn McCarney {
313adc4f0dbSShawn McCarney   public:
3144e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
315adc4f0dbSShawn McCarney     {
316adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
31728aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
31828aa8de5SGeorge Liu         name = path.filename();
31928aa8de5SGeorge Liu         if (name.empty())
320adc4f0dbSShawn McCarney         {
32128aa8de5SGeorge Liu             BMCWEB_LOG_ERROR << "Failed to find '/' in " << objectPath;
322adc4f0dbSShawn McCarney         }
323adc4f0dbSShawn McCarney     }
324adc4f0dbSShawn McCarney 
325adc4f0dbSShawn McCarney     std::string objectPath;
326adc4f0dbSShawn McCarney     std::string name;
327e05aec50SEd Tanous     bool isPresent = true;
328e05aec50SEd Tanous     bool isFunctional = true;
329e05aec50SEd Tanous     bool isPowerSupply = false;
330e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
331adc4f0dbSShawn McCarney     std::string manufacturer;
332adc4f0dbSShawn McCarney     std::string model;
333adc4f0dbSShawn McCarney     std::string partNumber;
334adc4f0dbSShawn McCarney     std::string serialNumber;
335adc4f0dbSShawn McCarney     std::set<std::string> sensors;
336d500549bSAnthony Wilson     std::string ledObjectPath;
337e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
338adc4f0dbSShawn McCarney };
339adc4f0dbSShawn McCarney 
340adc4f0dbSShawn McCarney /**
341413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
342588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
34308777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
34408777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
34508777fb0SLewanczyk, Dawid  */
34608777fb0SLewanczyk, Dawid template <typename Callback>
347413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
34881ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
349fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3501abe55efSEd Tanous     Callback&& callback)
3511abe55efSEd Tanous {
352413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection enter";
35303b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
35408777fb0SLewanczyk, Dawid     const std::array<std::string, 1> interfaces = {
35508777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
35608777fb0SLewanczyk, Dawid 
35708777fb0SLewanczyk, Dawid     // Response handler for parsing objects subtree
358002d39b4SEd Tanous     auto respHandler =
359002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
360002d39b4SEd Tanous          sensorNames](const boost::system::error_code ec,
361002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
362413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler enter";
3631abe55efSEd Tanous         if (ec)
3641abe55efSEd Tanous         {
3658d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
366413961deSRichard Marian Thomaiyar             BMCWEB_LOG_ERROR
367413961deSRichard Marian Thomaiyar                 << "getObjectsWithConnection resp_handler: Dbus error " << ec;
36808777fb0SLewanczyk, Dawid             return;
36908777fb0SLewanczyk, Dawid         }
37008777fb0SLewanczyk, Dawid 
37155c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
37208777fb0SLewanczyk, Dawid 
37308777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
37408777fb0SLewanczyk, Dawid         // found in the chassis
375fe04d49cSNan Zhou         std::set<std::string> connections;
376413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
37708777fb0SLewanczyk, Dawid 
37849c53ac9SJohnathan Mantey         BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames->size();
37949c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3801abe55efSEd Tanous         {
38155c7b7a2SEd Tanous             BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
38208777fb0SLewanczyk, Dawid         }
38308777fb0SLewanczyk, Dawid 
38408777fb0SLewanczyk, Dawid         for (const std::pair<
38508777fb0SLewanczyk, Dawid                  std::string,
38608777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3871abe55efSEd Tanous                  object : subtree)
3881abe55efSEd Tanous         {
38949c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3901abe55efSEd Tanous             {
39149c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
3921abe55efSEd Tanous                          objData : object.second)
3931abe55efSEd Tanous                 {
39449c53ac9SJohnathan Mantey                     BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
39508777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
396de629b6eSShawn McCarney                     objectsWithConnection.insert(
397de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
39808777fb0SLewanczyk, Dawid                 }
39908777fb0SLewanczyk, Dawid             }
40008777fb0SLewanczyk, Dawid         }
40155c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
402413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
403413961deSRichard Marian Thomaiyar         BMCWEB_LOG_DEBUG << "getObjectsWithConnection resp_handler exit";
40408777fb0SLewanczyk, Dawid     };
40508777fb0SLewanczyk, Dawid     // Make call to ObjectMapper to find all sensors objects
40655c7b7a2SEd Tanous     crow::connections::systemBus->async_method_call(
40755c7b7a2SEd Tanous         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
4081abe55efSEd Tanous         "/xyz/openbmc_project/object_mapper",
4091abe55efSEd Tanous         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 2, interfaces);
410413961deSRichard Marian Thomaiyar     BMCWEB_LOG_DEBUG << "getObjectsWithConnection exit";
411413961deSRichard Marian Thomaiyar }
412413961deSRichard Marian Thomaiyar 
413413961deSRichard Marian Thomaiyar /**
414413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
415413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
416413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
417413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
418413961deSRichard Marian Thomaiyar  */
419413961deSRichard Marian Thomaiyar template <typename Callback>
420fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
421fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
422413961deSRichard Marian Thomaiyar                     Callback&& callback)
423413961deSRichard Marian Thomaiyar {
424413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
425fe04d49cSNan Zhou         [callback](const std::set<std::string>& connections,
426413961deSRichard Marian Thomaiyar                    const std::set<std::pair<std::string, std::string>>&
4273174e4dfSEd Tanous                    /*objectsWithConnection*/) { callback(connections); };
42881ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
429413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
43008777fb0SLewanczyk, Dawid }
43108777fb0SLewanczyk, Dawid 
43208777fb0SLewanczyk, Dawid /**
43349c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
43449c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
43549c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
43649c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
43749c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
43849c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
43949c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
44049c53ac9SJohnathan Mantey  */
44123a21a1cSEd Tanous inline void reduceSensorList(
4427f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
4437f1cc26dSEd Tanous     std::span<std::string_view> sensorTypes,
44449c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
445fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
44649c53ac9SJohnathan Mantey {
44749c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
44849c53ac9SJohnathan Mantey     {
4497f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4507f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
451a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
45249c53ac9SJohnathan Mantey                                        : "Voltages");
45349c53ac9SJohnathan Mantey 
45449c53ac9SJohnathan Mantey         return;
45549c53ac9SJohnathan Mantey     }
45649c53ac9SJohnathan Mantey     if (allSensors->empty())
45749c53ac9SJohnathan Mantey     {
45849c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
45949c53ac9SJohnathan Mantey         return;
46049c53ac9SJohnathan Mantey     }
46149c53ac9SJohnathan Mantey 
4627f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
46349c53ac9SJohnathan Mantey     {
46449c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
46549c53ac9SJohnathan Mantey         {
46611ba3979SEd Tanous             if (sensor.starts_with(type))
46749c53ac9SJohnathan Mantey             {
46849c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
46949c53ac9SJohnathan Mantey             }
47049c53ac9SJohnathan Mantey         }
47149c53ac9SJohnathan Mantey     }
47249c53ac9SJohnathan Mantey }
47349c53ac9SJohnathan Mantey 
4747f1cc26dSEd Tanous /*
4757f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4767f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4777f1cc26dSEd Tanous  *
4787f1cc26dSEd Tanous  * */
4797f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4807f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4817f1cc26dSEd Tanous {
4827f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4837f1cc26dSEd Tanous     {
4847f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4857f1cc26dSEd Tanous     }
4867f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4877f1cc26dSEd Tanous     {
4887f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
4897f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
4907f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
4917f1cc26dSEd Tanous     }
4927f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
4937f1cc26dSEd Tanous     {
4947f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
4957f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
4967f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
4977f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
4987f1cc26dSEd Tanous     }
4997f1cc26dSEd Tanous 
5007f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5017f1cc26dSEd Tanous     {
5027f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5037f1cc26dSEd Tanous     }
5047f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5057f1cc26dSEd Tanous }
5067f1cc26dSEd Tanous 
50749c53ac9SJohnathan Mantey /**
50808777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
509588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
51008777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
51108777fb0SLewanczyk, Dawid  */
51208777fb0SLewanczyk, Dawid template <typename Callback>
5137f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5147f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
5157f1cc26dSEd Tanous                 std::span<std::string_view> sensorTypes, Callback&& callback)
5161abe55efSEd Tanous {
51755c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis enter";
518adc4f0dbSShawn McCarney     const std::array<const char*, 2> interfaces = {
51949c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
520adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
521002d39b4SEd Tanous     auto respHandler =
5227f1cc26dSEd Tanous         [callback{std::forward<Callback>(callback)}, asyncResp,
5237f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5247f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
52549c53ac9SJohnathan Mantey             const boost::system::error_code ec,
526002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
52755c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
5281abe55efSEd Tanous         if (ec)
5291abe55efSEd Tanous         {
53055c7b7a2SEd Tanous             BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
5317f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
53208777fb0SLewanczyk, Dawid             return;
53308777fb0SLewanczyk, Dawid         }
53449c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
53549c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5361abe55efSEd Tanous         {
53728aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
538f8fe53e7SEd Tanous             std::string chassisName = path.filename();
53928aa8de5SGeorge Liu             if (chassisName.empty())
5401abe55efSEd Tanous             {
54149c53ac9SJohnathan Mantey                 BMCWEB_LOG_ERROR << "Failed to find '/' in " << chassis;
542daf36e2eSEd Tanous                 continue;
543daf36e2eSEd Tanous             }
5447f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5451abe55efSEd Tanous             {
54649c53ac9SJohnathan Mantey                 chassisPath = &chassis;
54749c53ac9SJohnathan Mantey                 break;
548daf36e2eSEd Tanous             }
54949c53ac9SJohnathan Mantey         }
55049c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5511abe55efSEd Tanous         {
5527f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
55349c53ac9SJohnathan Mantey             return;
5541abe55efSEd Tanous         }
5557f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
55608777fb0SLewanczyk, Dawid 
5577f1cc26dSEd Tanous         asyncResp->res.jsonValue["@odata.id"] =
5587f1cc26dSEd Tanous             "/redfish/v1/Chassis/" + chassisIdStr + "/" + chassisSubNode;
55995a3ecadSAnthony Wilson 
5608fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5618fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5621e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::vector<std::string>>(
5631e1e598dSJonathan Doman             *crow::connections::systemBus, "xyz.openbmc_project.ObjectMapper",
5641e1e598dSJonathan Doman             sensorPath, "xyz.openbmc_project.Association", "endpoints",
5657f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
566f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
567271584abSEd Tanous                 const boost::system::error_code& e,
5681e1e598dSJonathan Doman                 const std::vector<std::string>& nodeSensorList) {
569271584abSEd Tanous             if (e)
57049c53ac9SJohnathan Mantey             {
571271584abSEd Tanous                 if (e.value() != EBADR)
57249c53ac9SJohnathan Mantey                 {
5737f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
57449c53ac9SJohnathan Mantey                     return;
57549c53ac9SJohnathan Mantey                 }
57649c53ac9SJohnathan Mantey             }
577fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
578fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5797f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5807f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
5817f1cc26dSEd Tanous             BMCWEB_LOG_DEBUG << "Finishing with " << culledSensorList->size();
58249c53ac9SJohnathan Mantey             callback(culledSensorList);
5831e1e598dSJonathan Doman             });
58449c53ac9SJohnathan Mantey     };
58549c53ac9SJohnathan Mantey 
58649c53ac9SJohnathan Mantey     // Get the Chassis Collection
58749c53ac9SJohnathan Mantey     crow::connections::systemBus->async_method_call(
58849c53ac9SJohnathan Mantey         respHandler, "xyz.openbmc_project.ObjectMapper",
58949c53ac9SJohnathan Mantey         "/xyz/openbmc_project/object_mapper",
59049c53ac9SJohnathan Mantey         "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths",
591271584abSEd Tanous         "/xyz/openbmc_project/inventory", 0, interfaces);
59255c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassis exit";
59308777fb0SLewanczyk, Dawid }
59408777fb0SLewanczyk, Dawid 
59508777fb0SLewanczyk, Dawid /**
596adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
597adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
598adc4f0dbSShawn McCarney  * @return State value for inventory item.
59934dd179eSJames Feist  */
60023a21a1cSEd Tanous inline std::string getState(const InventoryItem* inventoryItem)
601adc4f0dbSShawn McCarney {
602adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
603adc4f0dbSShawn McCarney     {
604adc4f0dbSShawn McCarney         return "Absent";
605adc4f0dbSShawn McCarney     }
60634dd179eSJames Feist 
607adc4f0dbSShawn McCarney     return "Enabled";
608adc4f0dbSShawn McCarney }
609adc4f0dbSShawn McCarney 
610adc4f0dbSShawn McCarney /**
611adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
612adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6131d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
614adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
615adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
616adc4f0dbSShawn McCarney  * @return Health value for sensor.
617adc4f0dbSShawn McCarney  */
6181d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6191d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
620adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
62134dd179eSJames Feist {
622adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
623adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
624adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
625adc4f0dbSShawn McCarney     std::string currentHealth;
626adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
627adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
628adc4f0dbSShawn McCarney     {
629adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
630adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
631adc4f0dbSShawn McCarney         {
632adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
633adc4f0dbSShawn McCarney             if (health != nullptr)
634adc4f0dbSShawn McCarney             {
635adc4f0dbSShawn McCarney                 currentHealth = *health;
636adc4f0dbSShawn McCarney             }
637adc4f0dbSShawn McCarney         }
638adc4f0dbSShawn McCarney     }
639adc4f0dbSShawn McCarney 
640adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
641adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
642adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
643adc4f0dbSShawn McCarney     {
644adc4f0dbSShawn McCarney         return "Critical";
645adc4f0dbSShawn McCarney     }
646adc4f0dbSShawn McCarney 
647c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
648c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
649c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
650c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
651711ac7a9SEd Tanous 
652c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
653c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
654c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
655c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
656c1343bf6SKrzysztof Grobelny         warningAlarmLow);
657c1343bf6SKrzysztof Grobelny 
658c1343bf6SKrzysztof Grobelny     if (success)
65934dd179eSJames Feist     {
660c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
661c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
662c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
66334dd179eSJames Feist         {
66434dd179eSJames Feist             return "Critical";
66534dd179eSJames Feist         }
66634dd179eSJames Feist     }
66734dd179eSJames Feist 
668adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
669adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
670adc4f0dbSShawn McCarney     {
671adc4f0dbSShawn McCarney         return "Critical";
672adc4f0dbSShawn McCarney     }
673adc4f0dbSShawn McCarney 
674adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
675adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
676adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
677adc4f0dbSShawn McCarney     {
678adc4f0dbSShawn McCarney         return "Warning";
679adc4f0dbSShawn McCarney     }
680adc4f0dbSShawn McCarney 
681c1343bf6SKrzysztof Grobelny     if (success)
682c1343bf6SKrzysztof Grobelny     {
683adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
684c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
685c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
68634dd179eSJames Feist         {
687ebe4d91eSEd Tanous             return "Warning";
68834dd179eSJames Feist         }
68934dd179eSJames Feist     }
690adc4f0dbSShawn McCarney 
69134dd179eSJames Feist     return "OK";
69234dd179eSJames Feist }
69334dd179eSJames Feist 
69423a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
695d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
696d500549bSAnthony Wilson {
697d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
698d500549bSAnthony Wilson     {
699d500549bSAnthony Wilson         switch (inventoryItem->ledState)
700d500549bSAnthony Wilson         {
701d500549bSAnthony Wilson             case LedState::OFF:
702d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
703d500549bSAnthony Wilson                 break;
704d500549bSAnthony Wilson             case LedState::ON:
705d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
706d500549bSAnthony Wilson                 break;
707d500549bSAnthony Wilson             case LedState::BLINK:
708d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
709d500549bSAnthony Wilson                 break;
71023a21a1cSEd Tanous             case LedState::UNKNOWN:
711d500549bSAnthony Wilson                 break;
712d500549bSAnthony Wilson         }
713d500549bSAnthony Wilson     }
714d500549bSAnthony Wilson }
715d500549bSAnthony Wilson 
71634dd179eSJames Feist /**
71708777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
71808777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
719274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
72008777fb0SLewanczyk, Dawid  * build
7211d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
7221d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7231d7c0054SEd Tanous  * from.
7241d7c0054SEd Tanous  * @param sensorJson  The json object to fill
725adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
726adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
72708777fb0SLewanczyk, Dawid  */
7281d7c0054SEd Tanous inline void objectPropertiesToJson(
7291d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7301d7c0054SEd Tanous     std::string_view chassisSubNode,
7311d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
73281ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7331abe55efSEd Tanous {
7341d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
735adc4f0dbSShawn McCarney     {
736*c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
737c1d019a6SEd Tanous         subNodeEscaped.erase(
738c1d019a6SEd Tanous             std::remove(subNodeEscaped.begin(), subNodeEscaped.end(), '_'),
739c1d019a6SEd Tanous             subNodeEscaped.end());
740c1d019a6SEd Tanous 
741c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
742c1d019a6SEd Tanous         // including power sensors.
743c1d019a6SEd Tanous         subNodeEscaped += '_';
744c1d019a6SEd Tanous         subNodeEscaped += sensorName;
745c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
746c1d019a6SEd Tanous 
7471d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7481d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7491d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
75095a3ecadSAnthony Wilson     }
75195a3ecadSAnthony Wilson     else if (sensorType != "power")
75295a3ecadSAnthony Wilson     {
75395a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
75495a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
75595a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
75681ce609eSEd Tanous         sensorJson["MemberId"] = sensorName;
7571d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7581d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7591d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
760adc4f0dbSShawn McCarney     }
761e742b6ccSEd Tanous 
76281ce609eSEd Tanous     sensorJson["Status"]["State"] = getState(inventoryItem);
76381ce609eSEd Tanous     sensorJson["Status"]["Health"] =
7641d7c0054SEd Tanous         getHealth(sensorJson, propertiesDict, inventoryItem);
76508777fb0SLewanczyk, Dawid 
76608777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
76708777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
76808777fb0SLewanczyk, Dawid     // that require integers, not floats.
76908777fb0SLewanczyk, Dawid     bool forceToInt = false;
77008777fb0SLewanczyk, Dawid 
7713929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7721d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
77395a3ecadSAnthony Wilson     {
7742a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
775c2bf7f99SWludzik, Jozef 
7760ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
7770ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
77895a3ecadSAnthony Wilson         {
779c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading type for "
780c2bf7f99SWludzik, Jozef                              << sensorType;
78195a3ecadSAnthony Wilson         }
782c2bf7f99SWludzik, Jozef         else
78395a3ecadSAnthony Wilson         {
784c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
78595a3ecadSAnthony Wilson         }
786c2bf7f99SWludzik, Jozef 
7871d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
788c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
789f8ede15eSAdrian Ambrożewicz         {
790c2bf7f99SWludzik, Jozef             BMCWEB_LOG_ERROR << "Redfish cannot map reading unit for "
791c2bf7f99SWludzik, Jozef                              << sensorType;
792c2bf7f99SWludzik, Jozef         }
793c2bf7f99SWludzik, Jozef         else
794c2bf7f99SWludzik, Jozef         {
795c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
796f8ede15eSAdrian Ambrożewicz         }
79795a3ecadSAnthony Wilson     }
79895a3ecadSAnthony Wilson     else if (sensorType == "temperature")
7991abe55efSEd Tanous     {
8003929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
80181ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
80208777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
80308777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8041abe55efSEd Tanous     }
8051abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8061abe55efSEd Tanous     {
8073929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
80881ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
80981ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
81081ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
81108777fb0SLewanczyk, Dawid         forceToInt = true;
8121abe55efSEd Tanous     }
8136f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8146f6d0d32SEd Tanous     {
8153929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
81681ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
81781ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
81881ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8196f6d0d32SEd Tanous         forceToInt = true;
8206f6d0d32SEd Tanous     }
8211abe55efSEd Tanous     else if (sensorType == "voltage")
8221abe55efSEd Tanous     {
8233929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
82481ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8251abe55efSEd Tanous     }
8262474adfaSEd Tanous     else if (sensorType == "power")
8272474adfaSEd Tanous     {
8281d7c0054SEd Tanous         if (boost::iequals(sensorName, "total_power"))
829028f7ebcSEddie James         {
83081ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8317ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8327ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
83381ce609eSEd Tanous             sensorJson["MemberId"] = "0";
83481ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8353929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
836028f7ebcSEddie James         }
8371d7c0054SEd Tanous         else if (boost::ifind_first(sensorName, "input").empty())
83849c53ac9SJohnathan Mantey         {
8393929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
84049c53ac9SJohnathan Mantey         }
84149c53ac9SJohnathan Mantey         else
84249c53ac9SJohnathan Mantey         {
8433929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
84449c53ac9SJohnathan Mantey         }
8452474adfaSEd Tanous     }
8461abe55efSEd Tanous     else
8471abe55efSEd Tanous     {
84855c7b7a2SEd Tanous         BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
84908777fb0SLewanczyk, Dawid         return;
85008777fb0SLewanczyk, Dawid     }
85108777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8523929aca1SAnthony Wilson     std::vector<
8533929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8543929aca1SAnthony Wilson         properties;
85508777fb0SLewanczyk, Dawid     properties.reserve(7);
85608777fb0SLewanczyk, Dawid 
85708777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
858de629b6eSShawn McCarney 
8591d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8603929aca1SAnthony Wilson     {
8613929aca1SAnthony Wilson         properties.emplace_back(
8623929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8633929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8643929aca1SAnthony Wilson         properties.emplace_back(
8653929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8663929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8673929aca1SAnthony Wilson         properties.emplace_back(
8683929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8693929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
8703929aca1SAnthony Wilson         properties.emplace_back(
8713929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
8723929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
8733929aca1SAnthony Wilson     }
8743929aca1SAnthony Wilson     else if (sensorType != "power")
875de629b6eSShawn McCarney     {
87608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8773929aca1SAnthony Wilson                                 "WarningHigh",
8783929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
87908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8803929aca1SAnthony Wilson                                 "WarningLow",
8813929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
88208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8833929aca1SAnthony Wilson                                 "CriticalHigh",
8843929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
88508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8863929aca1SAnthony Wilson                                 "CriticalLow",
8873929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
888de629b6eSShawn McCarney     }
88908777fb0SLewanczyk, Dawid 
8902474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
8912474adfaSEd Tanous 
8921d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
89395a3ecadSAnthony Wilson     {
89495a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
8953929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
89695a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
8973929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
89851c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
89951c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
90095a3ecadSAnthony Wilson     }
90195a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9021abe55efSEd Tanous     {
90308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9043929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
90508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9063929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9071abe55efSEd Tanous     }
908adc4f0dbSShawn McCarney     else if (sensorType != "power")
9091abe55efSEd Tanous     {
91008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9113929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
91208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9133929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
91408777fb0SLewanczyk, Dawid     }
91508777fb0SLewanczyk, Dawid 
9163929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9173929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9181abe55efSEd Tanous     {
9191d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
920711ac7a9SEd Tanous         {
921711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
922711ac7a9SEd Tanous             {
923711ac7a9SEd Tanous                 continue;
924711ac7a9SEd Tanous             }
9253929aca1SAnthony Wilson 
9263929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9273929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9283929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9293929aca1SAnthony Wilson 
930abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
93140e4f380SEd Tanous             if (doubleValue == nullptr)
9321abe55efSEd Tanous             {
93340e4f380SEd Tanous                 BMCWEB_LOG_ERROR << "Got value interface that wasn't double";
9346f6d0d32SEd Tanous                 continue;
93508777fb0SLewanczyk, Dawid             }
9366f6d0d32SEd Tanous             if (forceToInt)
9376f6d0d32SEd Tanous             {
93840e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9396f6d0d32SEd Tanous             }
9406f6d0d32SEd Tanous             else
9416f6d0d32SEd Tanous             {
94240e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
94308777fb0SLewanczyk, Dawid             }
94408777fb0SLewanczyk, Dawid         }
94508777fb0SLewanczyk, Dawid     }
94608777fb0SLewanczyk, Dawid }
94708777fb0SLewanczyk, Dawid 
9481d7c0054SEd Tanous /**
9491d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9501d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9511d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9521d7c0054SEd Tanous  * build
9531d7c0054SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
9541d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9551d7c0054SEd Tanous  * interfaces to be built from
9561d7c0054SEd Tanous  * @param sensorJson  The json object to fill
9571d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
9581d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
9591d7c0054SEd Tanous  */
9601d7c0054SEd Tanous inline void objectInterfacesToJson(
9611d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
9621d7c0054SEd Tanous     const std::string& chassisSubNode,
9631d7c0054SEd Tanous     const dbus::utility::DBusInteracesMap& interfacesDict,
9641d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
9651d7c0054SEd Tanous {
9661d7c0054SEd Tanous 
9671d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
9681d7c0054SEd Tanous     {
9691d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
9701d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
9711d7c0054SEd Tanous     }
972c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Added sensor " << sensorName;
9731d7c0054SEd Tanous }
9741d7c0054SEd Tanous 
975b5a76932SEd Tanous inline void populateFanRedundancy(
976b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
9778bd25ccdSJames Feist {
9788bd25ccdSJames Feist     crow::connections::systemBus->async_method_call(
979b9d36b47SEd Tanous         [sensorsAsyncResp](
980b9d36b47SEd Tanous             const boost::system::error_code ec,
981b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
9828bd25ccdSJames Feist         if (ec)
9838bd25ccdSJames Feist         {
9848bd25ccdSJames Feist             return; // don't have to have this interface
9858bd25ccdSJames Feist         }
986002d39b4SEd Tanous         for (const std::pair<
987002d39b4SEd Tanous                  std::string,
988002d39b4SEd Tanous                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
989e278c18fSEd Tanous                  pathPair : resp)
9908bd25ccdSJames Feist         {
991e278c18fSEd Tanous             const std::string& path = pathPair.first;
992002d39b4SEd Tanous             const std::vector<std::pair<std::string, std::vector<std::string>>>&
993002d39b4SEd Tanous                 objDict = pathPair.second;
9948bd25ccdSJames Feist             if (objDict.empty())
9958bd25ccdSJames Feist             {
9968bd25ccdSJames Feist                 continue; // this should be impossible
9978bd25ccdSJames Feist             }
9988bd25ccdSJames Feist 
9998bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10001e1e598dSJonathan Doman             sdbusplus::asio::getProperty<std::vector<std::string>>(
10011e1e598dSJonathan Doman                 *crow::connections::systemBus,
10021e1e598dSJonathan Doman                 "xyz.openbmc_project.ObjectMapper", path + "/chassis",
10031e1e598dSJonathan Doman                 "xyz.openbmc_project.Association", "endpoints",
1004002d39b4SEd Tanous                 [path, owner,
1005002d39b4SEd Tanous                  sensorsAsyncResp](const boost::system::error_code e,
10061e1e598dSJonathan Doman                                    const std::vector<std::string>& endpoints) {
1007271584abSEd Tanous                 if (e)
10088bd25ccdSJames Feist                 {
10098bd25ccdSJames Feist                     return; // if they don't have an association we
10108bd25ccdSJames Feist                             // can't tell what chassis is
10118bd25ccdSJames Feist                 }
1012002d39b4SEd Tanous                 auto found =
1013002d39b4SEd Tanous                     std::find_if(endpoints.begin(), endpoints.end(),
10148bd25ccdSJames Feist                                  [sensorsAsyncResp](const std::string& entry) {
1015002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10168bd25ccdSJames Feist                            std::string::npos;
10178bd25ccdSJames Feist                     });
10188bd25ccdSJames Feist 
10191e1e598dSJonathan Doman                 if (found == endpoints.end())
10208bd25ccdSJames Feist                 {
10218bd25ccdSJames Feist                     return;
10228bd25ccdSJames Feist                 }
102386d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
102486d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
102586d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10268bd25ccdSJames Feist                     [path, sensorsAsyncResp](
1027271584abSEd Tanous                         const boost::system::error_code& err,
102886d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
1029271584abSEd Tanous                     if (err)
10308bd25ccdSJames Feist                     {
10318bd25ccdSJames Feist                         return; // don't have to have this
10328bd25ccdSJames Feist                                 // interface
10338bd25ccdSJames Feist                     }
10348bd25ccdSJames Feist 
103586d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
103686d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
103786d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
103886d89ed7SKrzysztof Grobelny 
103986d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
104086d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
104186d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
104286d89ed7SKrzysztof Grobelny                         collection, "Status", status);
104386d89ed7SKrzysztof Grobelny 
104486d89ed7SKrzysztof Grobelny                     if (!success)
104586d89ed7SKrzysztof Grobelny                     {
104686d89ed7SKrzysztof Grobelny                         messages::internalError(
104786d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
104886d89ed7SKrzysztof Grobelny                         return;
104986d89ed7SKrzysztof Grobelny                     }
105086d89ed7SKrzysztof Grobelny 
105186d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
105286d89ed7SKrzysztof Grobelny                         status == nullptr)
10538bd25ccdSJames Feist                     {
1054002d39b4SEd Tanous                         BMCWEB_LOG_ERROR << "Invalid redundancy interface";
10558bd25ccdSJames Feist                         messages::internalError(
10568d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10578bd25ccdSJames Feist                         return;
10588bd25ccdSJames Feist                     }
10598bd25ccdSJames Feist 
1060002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
106128aa8de5SGeorge Liu                     std::string name = objectPath.filename();
106228aa8de5SGeorge Liu                     if (name.empty())
10638bd25ccdSJames Feist                     {
10648bd25ccdSJames Feist                         // this should be impossible
10658bd25ccdSJames Feist                         messages::internalError(
10668d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10678bd25ccdSJames Feist                         return;
10688bd25ccdSJames Feist                     }
1069002d39b4SEd Tanous                     std::replace(name.begin(), name.end(), '_', ' ');
10708bd25ccdSJames Feist 
10718bd25ccdSJames Feist                     std::string health;
10728bd25ccdSJames Feist 
107311ba3979SEd Tanous                     if (status->ends_with("Full"))
10748bd25ccdSJames Feist                     {
10758bd25ccdSJames Feist                         health = "OK";
10768bd25ccdSJames Feist                     }
107711ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
10788bd25ccdSJames Feist                     {
10798bd25ccdSJames Feist                         health = "Warning";
10808bd25ccdSJames Feist                     }
10818bd25ccdSJames Feist                     else
10828bd25ccdSJames Feist                     {
10838bd25ccdSJames Feist                         health = "Critical";
10848bd25ccdSJames Feist                     }
10851476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
10868bd25ccdSJames Feist                     const auto& fanRedfish =
1087002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
10888bd25ccdSJames Feist                     for (const std::string& item : *collection)
10898bd25ccdSJames Feist                     {
10908a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
10918a592810SEd Tanous                         std::string itemName = itemPath.filename();
109228aa8de5SGeorge Liu                         if (itemName.empty())
109328aa8de5SGeorge Liu                         {
109428aa8de5SGeorge Liu                             continue;
109528aa8de5SGeorge Liu                         }
10968bd25ccdSJames Feist                         /*
10978bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
10988bd25ccdSJames Feist                         std::replace(itemName.begin(),
10998bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
1100002d39b4SEd Tanous                         auto schemaItem =
1101002d39b4SEd Tanous                             std::find_if(fanRedfish.begin(), fanRedfish.end(),
11028bd25ccdSJames Feist                                          [itemName](const nlohmann::json& fan) {
11038bd25ccdSJames Feist                             return fan["MemberId"] == itemName;
11048bd25ccdSJames Feist                             });
11058bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11068bd25ccdSJames Feist                         {
11078a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11088a592810SEd Tanous                             collectionId["@odata.id"] =
11091476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11101476687dSEd Tanous                             redfishCollection.emplace_back(
11118a592810SEd Tanous                                 std::move(collectionId));
11128bd25ccdSJames Feist                         }
11138bd25ccdSJames Feist                         else
11148bd25ccdSJames Feist                         {
1115002d39b4SEd Tanous                             BMCWEB_LOG_ERROR << "failed to find fan in schema";
11168bd25ccdSJames Feist                             messages::internalError(
11178d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11188bd25ccdSJames Feist                             return;
11198bd25ccdSJames Feist                         }
11208bd25ccdSJames Feist                     }
11218bd25ccdSJames Feist 
11223e9e72ebSKuiying Wang                     size_t minNumNeeded =
112326f6976fSEd Tanous                         collection->empty()
112426f6976fSEd Tanous                             ? 0
112526f6976fSEd Tanous                             : collection->size() - *allowedFailures;
1126002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11278bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11281476687dSEd Tanous 
11291476687dSEd Tanous                     nlohmann::json::object_t redundancy;
11301476687dSEd Tanous                     redundancy["@odata.id"] =
1131002d39b4SEd Tanous                         "/redfish/v1/Chassis/" + sensorsAsyncResp->chassisId +
1132002d39b4SEd Tanous                         "/" + sensorsAsyncResp->chassisSubNode +
1133002d39b4SEd Tanous                         "#/Redundancy/" + std::to_string(jResp.size());
1134002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11351476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11361476687dSEd Tanous                     redundancy["MemberId"] = name;
11371476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11381476687dSEd Tanous                     redundancy["Name"] = name;
11391476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11401476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11411476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11421476687dSEd Tanous 
11431476687dSEd Tanous                     jResp.push_back(std::move(redundancy));
114486d89ed7SKrzysztof Grobelny                     });
11451e1e598dSJonathan Doman                 });
11468bd25ccdSJames Feist         }
11478bd25ccdSJames Feist         },
11488bd25ccdSJames Feist         "xyz.openbmc_project.ObjectMapper",
11498bd25ccdSJames Feist         "/xyz/openbmc_project/object_mapper",
11508bd25ccdSJames Feist         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
11518bd25ccdSJames Feist         "/xyz/openbmc_project/control", 2,
11528bd25ccdSJames Feist         std::array<const char*, 1>{
11538bd25ccdSJames Feist             "xyz.openbmc_project.Control.FanRedundancy"});
11548bd25ccdSJames Feist }
11558bd25ccdSJames Feist 
1156b5a76932SEd Tanous inline void
115781ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
115849c53ac9SJohnathan Mantey {
11598d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
116049c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
116181ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
116249c53ac9SJohnathan Mantey     {
116349c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
116449c53ac9SJohnathan Mantey     }
116549c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
116649c53ac9SJohnathan Mantey     {
116749c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
116849c53ac9SJohnathan Mantey         if (entry != response.end())
116949c53ac9SJohnathan Mantey         {
117049c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
117102cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
117249c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
117349c53ac9SJohnathan Mantey             });
117449c53ac9SJohnathan Mantey 
117549c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
117649c53ac9SJohnathan Mantey             size_t count = 0;
117749c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
117849c53ac9SJohnathan Mantey             {
117949c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
118049c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
118149c53ac9SJohnathan Mantey                 {
118249c53ac9SJohnathan Mantey                     continue;
118349c53ac9SJohnathan Mantey                 }
118449c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
118549c53ac9SJohnathan Mantey                 if (value != nullptr)
118649c53ac9SJohnathan Mantey                 {
118749c53ac9SJohnathan Mantey                     *value += std::to_string(count);
118849c53ac9SJohnathan Mantey                     count++;
118981ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
119049c53ac9SJohnathan Mantey                 }
119149c53ac9SJohnathan Mantey             }
119249c53ac9SJohnathan Mantey         }
119349c53ac9SJohnathan Mantey     }
119449c53ac9SJohnathan Mantey }
119549c53ac9SJohnathan Mantey 
119608777fb0SLewanczyk, Dawid /**
1197adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1198adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1199adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1200adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12018fb49dd6SShawn McCarney  */
120223a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1203b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1204adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12058fb49dd6SShawn McCarney {
1206adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12078fb49dd6SShawn McCarney     {
1208adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12098fb49dd6SShawn McCarney         {
1210adc4f0dbSShawn McCarney             return &inventoryItem;
12118fb49dd6SShawn McCarney         }
12128fb49dd6SShawn McCarney     }
12138fb49dd6SShawn McCarney     return nullptr;
12148fb49dd6SShawn McCarney }
12158fb49dd6SShawn McCarney 
12168fb49dd6SShawn McCarney /**
1217adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1218adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1219adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1220adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12218fb49dd6SShawn McCarney  */
122223a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1223b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1224adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1225adc4f0dbSShawn McCarney {
1226adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1227adc4f0dbSShawn McCarney     {
1228adc4f0dbSShawn McCarney         if (inventoryItem.sensors.count(sensorObjPath) > 0)
1229adc4f0dbSShawn McCarney         {
1230adc4f0dbSShawn McCarney             return &inventoryItem;
1231adc4f0dbSShawn McCarney         }
1232adc4f0dbSShawn McCarney     }
1233adc4f0dbSShawn McCarney     return nullptr;
1234adc4f0dbSShawn McCarney }
1235adc4f0dbSShawn McCarney 
1236adc4f0dbSShawn McCarney /**
1237d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1238d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1239d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1240d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1241d500549bSAnthony Wilson  */
1242d500549bSAnthony Wilson inline InventoryItem*
1243d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1244d500549bSAnthony Wilson                             const std::string& ledObjPath)
1245d500549bSAnthony Wilson {
1246d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1247d500549bSAnthony Wilson     {
1248d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1249d500549bSAnthony Wilson         {
1250d500549bSAnthony Wilson             return &inventoryItem;
1251d500549bSAnthony Wilson         }
1252d500549bSAnthony Wilson     }
1253d500549bSAnthony Wilson     return nullptr;
1254d500549bSAnthony Wilson }
1255d500549bSAnthony Wilson 
1256d500549bSAnthony Wilson /**
1257adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1258adc4f0dbSShawn McCarney  *
1259adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1260adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1261adc4f0dbSShawn McCarney  * added to the vector.
1262adc4f0dbSShawn McCarney  *
1263adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1264adc4f0dbSShawn McCarney  * InventoryItem.
1265adc4f0dbSShawn McCarney  *
1266adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1267adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1268adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1269adc4f0dbSShawn McCarney  */
1270b5a76932SEd Tanous inline void addInventoryItem(
1271b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1272b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1273adc4f0dbSShawn McCarney {
1274adc4f0dbSShawn McCarney     // Look for inventory item in vector
1275adc4f0dbSShawn McCarney     InventoryItem* inventoryItem =
1276adc4f0dbSShawn McCarney         findInventoryItem(inventoryItems, invItemObjPath);
1277adc4f0dbSShawn McCarney 
1278adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1279adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1280adc4f0dbSShawn McCarney     {
1281adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1282adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1283adc4f0dbSShawn McCarney     }
1284adc4f0dbSShawn McCarney 
1285adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1286adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1287adc4f0dbSShawn McCarney }
1288adc4f0dbSShawn McCarney 
1289adc4f0dbSShawn McCarney /**
1290adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1291adc4f0dbSShawn McCarney  *
1292adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1293adc4f0dbSShawn McCarney  * specified InventoryItem.
1294adc4f0dbSShawn McCarney  *
1295adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1296adc4f0dbSShawn McCarney  * response.
1297adc4f0dbSShawn McCarney  *
1298adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1299adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1300adc4f0dbSShawn McCarney  * for the specified inventory item.
1301adc4f0dbSShawn McCarney  */
130223a21a1cSEd Tanous inline void storeInventoryItemData(
1303adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
1304711ac7a9SEd Tanous     const dbus::utility::DBusInteracesMap& interfacesDict)
13058fb49dd6SShawn McCarney {
1306adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1307711ac7a9SEd Tanous 
13089eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13098fb49dd6SShawn McCarney     {
1310711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13118fb49dd6SShawn McCarney         {
13129eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1313711ac7a9SEd Tanous             {
1314711ac7a9SEd Tanous                 if (name == "Present")
1315711ac7a9SEd Tanous                 {
1316711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1317adc4f0dbSShawn McCarney                     if (value != nullptr)
13188fb49dd6SShawn McCarney                     {
1319adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13208fb49dd6SShawn McCarney                     }
13218fb49dd6SShawn McCarney                 }
13228fb49dd6SShawn McCarney             }
1323711ac7a9SEd Tanous         }
1324adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1325711ac7a9SEd Tanous 
1326711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13278fb49dd6SShawn McCarney         {
1328adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13298fb49dd6SShawn McCarney         }
1330adc4f0dbSShawn McCarney 
1331adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1332711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1333adc4f0dbSShawn McCarney         {
13349eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1335711ac7a9SEd Tanous             {
1336711ac7a9SEd Tanous                 if (name == "Manufacturer")
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.manufacturer = *value;
1343adc4f0dbSShawn McCarney                     }
1344adc4f0dbSShawn McCarney                 }
1345711ac7a9SEd Tanous                 if (name == "Model")
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.model = *value;
1352adc4f0dbSShawn McCarney                     }
1353adc4f0dbSShawn McCarney                 }
1354711ac7a9SEd Tanous                 if (name == "SerialNumber")
1355adc4f0dbSShawn McCarney                 {
1356adc4f0dbSShawn McCarney                     const std::string* value =
1357711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1358adc4f0dbSShawn McCarney                     if (value != nullptr)
1359adc4f0dbSShawn McCarney                     {
1360adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1361adc4f0dbSShawn McCarney                     }
1362adc4f0dbSShawn McCarney                 }
1363711ac7a9SEd Tanous                 if (name == "PartNumber")
1364711ac7a9SEd Tanous                 {
1365711ac7a9SEd Tanous                     const std::string* value =
1366711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1367711ac7a9SEd Tanous                     if (value != nullptr)
1368711ac7a9SEd Tanous                     {
1369711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1370711ac7a9SEd Tanous                     }
1371711ac7a9SEd Tanous                 }
1372711ac7a9SEd Tanous             }
1373adc4f0dbSShawn McCarney         }
1374adc4f0dbSShawn McCarney 
1375711ac7a9SEd Tanous         if (interface ==
1376711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1377adc4f0dbSShawn McCarney         {
13789eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1379adc4f0dbSShawn McCarney             {
1380711ac7a9SEd Tanous                 if (name == "Functional")
1381711ac7a9SEd Tanous                 {
1382711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1383adc4f0dbSShawn McCarney                     if (value != nullptr)
1384adc4f0dbSShawn McCarney                     {
1385adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
13868fb49dd6SShawn McCarney                     }
13878fb49dd6SShawn McCarney                 }
13888fb49dd6SShawn McCarney             }
13898fb49dd6SShawn McCarney         }
1390711ac7a9SEd Tanous     }
1391711ac7a9SEd Tanous }
13928fb49dd6SShawn McCarney 
13938fb49dd6SShawn McCarney /**
1394adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
13958fb49dd6SShawn McCarney  *
1396adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1397adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1398adc4f0dbSShawn McCarney  * inventoryItems vector.
13998fb49dd6SShawn McCarney  *
1400adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1401adc4f0dbSShawn McCarney  * response.
1402adc4f0dbSShawn McCarney  *
1403adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1404adc4f0dbSShawn McCarney  * been obtained.
1405adc4f0dbSShawn McCarney  *
1406adc4f0dbSShawn McCarney  * The callback must have the following signature:
1407adc4f0dbSShawn McCarney  *   @code
1408d500549bSAnthony Wilson  *   callback(void)
1409adc4f0dbSShawn McCarney  *   @endcode
1410adc4f0dbSShawn McCarney  *
1411adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1412adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1413adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14148fb49dd6SShawn McCarney  *
14158fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1416adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1417adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14188fb49dd6SShawn McCarney  * implements ObjectManager.
1419adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1420adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1421adc4f0dbSShawn McCarney  * in recursive calls to this function.
14228fb49dd6SShawn McCarney  */
1423adc4f0dbSShawn McCarney template <typename Callback>
1424adc4f0dbSShawn McCarney static void getInventoryItemsData(
14258fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1426adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1427d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1428d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14298fb49dd6SShawn McCarney {
1430adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData enter";
14318fb49dd6SShawn McCarney 
1432adc4f0dbSShawn McCarney     // If no more connections left, call callback
1433adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14348fb49dd6SShawn McCarney     {
1435d500549bSAnthony Wilson         callback();
1436adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
1437adc4f0dbSShawn McCarney         return;
1438adc4f0dbSShawn McCarney     }
1439adc4f0dbSShawn McCarney 
1440adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1441fe04d49cSNan Zhou     auto it = invConnections->begin();
1442fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1443adc4f0dbSShawn McCarney     if (it != invConnections->end())
1444adc4f0dbSShawn McCarney     {
1445adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1446adc4f0dbSShawn McCarney 
14478fb49dd6SShawn McCarney         // Response handler for GetManagedObjects
1448d0090733SEd Tanous         auto respHandler = [sensorsAsyncResp, inventoryItems, invConnections,
1449d0090733SEd Tanous                             callback{std::forward<Callback>(callback)},
1450d0090733SEd Tanous                             invConnectionsIndex](
145102cad96eSEd Tanous                                const boost::system::error_code ec,
145202cad96eSEd Tanous                                const dbus::utility::ManagedObjectType& resp) {
1453adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler enter";
14548fb49dd6SShawn McCarney             if (ec)
14558fb49dd6SShawn McCarney             {
14568fb49dd6SShawn McCarney                 BMCWEB_LOG_ERROR
1457adc4f0dbSShawn McCarney                     << "getInventoryItemsData respHandler DBus error " << ec;
14588d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14598fb49dd6SShawn McCarney                 return;
14608fb49dd6SShawn McCarney             }
14618fb49dd6SShawn McCarney 
14628fb49dd6SShawn McCarney             // Loop through returned object paths
14638fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14648fb49dd6SShawn McCarney             {
14658fb49dd6SShawn McCarney                 const std::string& objPath =
14668fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14678fb49dd6SShawn McCarney 
1468adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
1469adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
1470adc4f0dbSShawn McCarney                     findInventoryItem(inventoryItems, objPath);
1471adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
14728fb49dd6SShawn McCarney                 {
1473adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1474adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
14758fb49dd6SShawn McCarney                 }
14768fb49dd6SShawn McCarney             }
14778fb49dd6SShawn McCarney 
1478adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1479adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1480d0090733SEd Tanous                                   invConnections, std::move(callback),
1481d0090733SEd Tanous                                   invConnectionsIndex + 1);
1482adc4f0dbSShawn McCarney 
1483adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsData respHandler exit";
14848fb49dd6SShawn McCarney         };
14858fb49dd6SShawn McCarney 
14868fb49dd6SShawn McCarney         // Get all object paths and their interfaces for current connection
14878fb49dd6SShawn McCarney         crow::connections::systemBus->async_method_call(
1488d0090733SEd Tanous             std::move(respHandler), invConnection,
1489f8bb0ff3SEd Tanous             "/xyz/openbmc_project/inventory",
14908fb49dd6SShawn McCarney             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
14918fb49dd6SShawn McCarney     }
14928fb49dd6SShawn McCarney 
1493adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsData exit";
14948fb49dd6SShawn McCarney }
14958fb49dd6SShawn McCarney 
14968fb49dd6SShawn McCarney /**
1497adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
14988fb49dd6SShawn McCarney  *
1499adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1500adc4f0dbSShawn McCarney  * items that are associated with sensors.
15018fb49dd6SShawn McCarney  *
15028fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15038fb49dd6SShawn McCarney  * been obtained.
15048fb49dd6SShawn McCarney  *
15058fb49dd6SShawn McCarney  * The callback must have the following signature:
15068fb49dd6SShawn McCarney  *   @code
1507fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15088fb49dd6SShawn McCarney  *   @endcode
15098fb49dd6SShawn McCarney  *
15108fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1511adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15128fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15138fb49dd6SShawn McCarney  */
15148fb49dd6SShawn McCarney template <typename Callback>
15158fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1516b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1517b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15188fb49dd6SShawn McCarney     Callback&& callback)
15198fb49dd6SShawn McCarney {
15208fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections enter";
15218fb49dd6SShawn McCarney 
15228fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1523adc4f0dbSShawn McCarney     const std::array<std::string, 4> interfaces = {
15248fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1525adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1526adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15278fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15288fb49dd6SShawn McCarney 
15298fb49dd6SShawn McCarney     // Response handler for parsing output from GetSubTree
1530002d39b4SEd Tanous     auto respHandler =
1531002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1532002d39b4SEd Tanous          inventoryItems](
1533b9d36b47SEd Tanous             const boost::system::error_code ec,
1534002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
15358fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler enter";
15368fb49dd6SShawn McCarney         if (ec)
15378fb49dd6SShawn McCarney         {
15388d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
15398fb49dd6SShawn McCarney             BMCWEB_LOG_ERROR
15408fb49dd6SShawn McCarney                 << "getInventoryItemsConnections respHandler DBus error " << ec;
15418fb49dd6SShawn McCarney             return;
15428fb49dd6SShawn McCarney         }
15438fb49dd6SShawn McCarney 
15448fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1545fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1546fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15478fb49dd6SShawn McCarney 
15488fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15498fb49dd6SShawn McCarney         for (const std::pair<
15508fb49dd6SShawn McCarney                  std::string,
15518fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15528fb49dd6SShawn McCarney                  object : subtree)
15538fb49dd6SShawn McCarney         {
1554adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15558fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1556adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15578fb49dd6SShawn McCarney             {
15588fb49dd6SShawn McCarney                 // Store all connections to inventory item
15598fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15608fb49dd6SShawn McCarney                          objData : object.second)
15618fb49dd6SShawn McCarney                 {
15628fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15638fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15648fb49dd6SShawn McCarney                 }
15658fb49dd6SShawn McCarney             }
15668fb49dd6SShawn McCarney         }
1567d500549bSAnthony Wilson 
15688fb49dd6SShawn McCarney         callback(invConnections);
15698fb49dd6SShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemsConnections respHandler exit";
15708fb49dd6SShawn McCarney     };
15718fb49dd6SShawn McCarney 
15728fb49dd6SShawn McCarney     // Make call to ObjectMapper to find all inventory items
15738fb49dd6SShawn McCarney     crow::connections::systemBus->async_method_call(
15748fb49dd6SShawn McCarney         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
15758fb49dd6SShawn McCarney         "/xyz/openbmc_project/object_mapper",
15768fb49dd6SShawn McCarney         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
15778fb49dd6SShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemsConnections exit";
15788fb49dd6SShawn McCarney }
15798fb49dd6SShawn McCarney 
15808fb49dd6SShawn McCarney /**
1581adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
15828fb49dd6SShawn McCarney  *
15838fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1584d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1585d500549bSAnthony Wilson  * their LEDs, if any.
15868fb49dd6SShawn McCarney  *
15878fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
15888fb49dd6SShawn McCarney  * has been obtained.
15898fb49dd6SShawn McCarney  *
15908fb49dd6SShawn McCarney  * The callback must have the following signature:
15918fb49dd6SShawn McCarney  *   @code
1592adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
15938fb49dd6SShawn McCarney  *   @endcode
15948fb49dd6SShawn McCarney  *
15958fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
15968fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
15978fb49dd6SShawn McCarney  * implements ObjectManager.
15988fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
15998fb49dd6SShawn McCarney  */
16008fb49dd6SShawn McCarney template <typename Callback>
1601adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1602b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1603fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16048fb49dd6SShawn McCarney     Callback&& callback)
16058fb49dd6SShawn McCarney {
1606adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations enter";
16078fb49dd6SShawn McCarney 
16088fb49dd6SShawn McCarney     // Response handler for GetManagedObjects
160902cad96eSEd Tanous     auto respHandler =
161002cad96eSEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
16118fb49dd6SShawn McCarney          sensorNames](const boost::system::error_code ec,
161202cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
1613adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler enter";
16148fb49dd6SShawn McCarney         if (ec)
16158fb49dd6SShawn McCarney         {
1616adc4f0dbSShawn McCarney             BMCWEB_LOG_ERROR
1617adc4f0dbSShawn McCarney                 << "getInventoryItemAssociations respHandler DBus error " << ec;
16188d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16198fb49dd6SShawn McCarney             return;
16208fb49dd6SShawn McCarney         }
16218fb49dd6SShawn McCarney 
1622adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1623adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1624adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1625adc4f0dbSShawn McCarney 
16268fb49dd6SShawn McCarney         // Loop through returned object paths
16278fb49dd6SShawn McCarney         std::string sensorAssocPath;
16288fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16298fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16308fb49dd6SShawn McCarney         {
16318fb49dd6SShawn McCarney             const std::string& objPath =
16328fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16338fb49dd6SShawn McCarney 
16348fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16358fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16368fb49dd6SShawn McCarney             {
16378fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16388fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16398fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16408fb49dd6SShawn McCarney                 {
16418fb49dd6SShawn McCarney                     // Get Association interface for object path
1642711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16438fb49dd6SShawn McCarney                     {
1644711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1645711ac7a9SEd Tanous                         {
1646711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1647711ac7a9SEd Tanous                             {
1648711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16498fb49dd6SShawn McCarney                                 {
16508fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16518fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1652711ac7a9SEd Tanous                                             &value);
1653711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1654711ac7a9SEd Tanous                                         !endpoints->empty())
16558fb49dd6SShawn McCarney                                     {
1656adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1657adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1658adc4f0dbSShawn McCarney                                             endpoints->front();
1659711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1660711ac7a9SEd Tanous                                                          invItemPath,
1661adc4f0dbSShawn McCarney                                                          sensorName);
16628fb49dd6SShawn McCarney                                     }
16638fb49dd6SShawn McCarney                                 }
16648fb49dd6SShawn McCarney                             }
1665711ac7a9SEd Tanous                         }
1666711ac7a9SEd Tanous                     }
16678fb49dd6SShawn McCarney                     break;
16688fb49dd6SShawn McCarney                 }
16698fb49dd6SShawn McCarney             }
16708fb49dd6SShawn McCarney         }
16718fb49dd6SShawn McCarney 
1672d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1673d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1674d500549bSAnthony Wilson         std::string inventoryAssocPath;
1675d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1676d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1677d500549bSAnthony Wilson         {
1678d500549bSAnthony Wilson             const std::string& objPath =
1679d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1680d500549bSAnthony Wilson 
1681d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1682d500549bSAnthony Wilson             {
1683d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1684d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1685d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1686d500549bSAnthony Wilson                 {
1687711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1688d500549bSAnthony Wilson                     {
1689711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1690711ac7a9SEd Tanous                         {
1691711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1692711ac7a9SEd Tanous                             {
1693711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1694d500549bSAnthony Wilson                                 {
1695d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1696d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1697711ac7a9SEd Tanous                                             &value);
1698711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1699711ac7a9SEd Tanous                                         !endpoints->empty())
1700d500549bSAnthony Wilson                                     {
1701711ac7a9SEd Tanous                                         // Add inventory item to vector
1702d500549bSAnthony Wilson                                         // Store LED path in inventory item
1703711ac7a9SEd Tanous                                         const std::string& ledPath =
1704711ac7a9SEd Tanous                                             endpoints->front();
1705d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1706d500549bSAnthony Wilson                                     }
1707d500549bSAnthony Wilson                                 }
1708d500549bSAnthony Wilson                             }
1709711ac7a9SEd Tanous                         }
1710711ac7a9SEd Tanous                     }
1711711ac7a9SEd Tanous 
1712d500549bSAnthony Wilson                     break;
1713d500549bSAnthony Wilson                 }
1714d500549bSAnthony Wilson             }
1715d500549bSAnthony Wilson         }
1716adc4f0dbSShawn McCarney         callback(inventoryItems);
1717adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociations respHandler exit";
17188fb49dd6SShawn McCarney     };
17198fb49dd6SShawn McCarney 
17208fb49dd6SShawn McCarney     // Call GetManagedObjects on the ObjectMapper to get all associations
17218fb49dd6SShawn McCarney     crow::connections::systemBus->async_method_call(
1722d0090733SEd Tanous         std::move(respHandler), "xyz.openbmc_project.ObjectMapper", "/",
17238fb49dd6SShawn McCarney         "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
17248fb49dd6SShawn McCarney 
1725adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItemAssociations exit";
17268fb49dd6SShawn McCarney }
17278fb49dd6SShawn McCarney 
17288fb49dd6SShawn McCarney /**
1729d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1730d500549bSAnthony Wilson  *
1731d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1732d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1733d500549bSAnthony Wilson  * inventoryItems vector.
1734d500549bSAnthony Wilson  *
1735d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1736d500549bSAnthony Wilson  * response.
1737d500549bSAnthony Wilson  *
1738d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1739d500549bSAnthony Wilson  * has been obtained.
1740d500549bSAnthony Wilson  *
1741d500549bSAnthony Wilson  * The callback must have the following signature:
1742d500549bSAnthony Wilson  *   @code
174342cbe538SGunnar Mills  *   callback()
1744d500549bSAnthony Wilson  *   @endcode
1745d500549bSAnthony Wilson  *
1746d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1747d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1748d500549bSAnthony Wilson  * last asynchronous function has completed.
1749d500549bSAnthony Wilson  *
1750d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1751d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1752d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1753d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1754d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1755d500549bSAnthony Wilson  * in recursive calls to this function.
1756d500549bSAnthony Wilson  */
1757d500549bSAnthony Wilson template <typename Callback>
1758d500549bSAnthony Wilson void getInventoryLedData(
1759d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1760d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1761fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1762d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1763d500549bSAnthony Wilson {
1764d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData enter";
1765d500549bSAnthony Wilson 
1766d500549bSAnthony Wilson     // If no more connections left, call callback
1767d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1768d500549bSAnthony Wilson     {
176942cbe538SGunnar Mills         callback();
1770d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1771d500549bSAnthony Wilson         return;
1772d500549bSAnthony Wilson     }
1773d500549bSAnthony Wilson 
1774d500549bSAnthony Wilson     // Get inventory item data from current connection
1775fe04d49cSNan Zhou     auto it = ledConnections->begin();
1776fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1777d500549bSAnthony Wilson     if (it != ledConnections->end())
1778d500549bSAnthony Wilson     {
1779d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1780d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1781d500549bSAnthony Wilson         // Response handler for Get State property
17821e1e598dSJonathan Doman         auto respHandler =
17831e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1784f94c4ecfSEd Tanous              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
17851e1e598dSJonathan Doman                 const boost::system::error_code ec, const std::string& state) {
1786d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler enter";
1787d500549bSAnthony Wilson             if (ec)
1788d500549bSAnthony Wilson             {
1789d500549bSAnthony Wilson                 BMCWEB_LOG_ERROR
1790d500549bSAnthony Wilson                     << "getInventoryLedData respHandler DBus error " << ec;
17918d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1792d500549bSAnthony Wilson                 return;
1793d500549bSAnthony Wilson             }
1794d500549bSAnthony Wilson 
17951e1e598dSJonathan Doman             BMCWEB_LOG_DEBUG << "Led state: " << state;
1796d500549bSAnthony Wilson             // Find inventory item with this LED object path
1797d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1798d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1799d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1800d500549bSAnthony Wilson             {
1801d500549bSAnthony Wilson                 // Store LED state in InventoryItem
180211ba3979SEd Tanous                 if (state.ends_with("On"))
1803d500549bSAnthony Wilson                 {
1804d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1805d500549bSAnthony Wilson                 }
180611ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1807d500549bSAnthony Wilson                 {
1808d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1809d500549bSAnthony Wilson                 }
181011ba3979SEd Tanous                 else if (state.ends_with("Off"))
1811d500549bSAnthony Wilson                 {
1812d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1813d500549bSAnthony Wilson                 }
1814d500549bSAnthony Wilson                 else
1815d500549bSAnthony Wilson                 {
1816d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1817d500549bSAnthony Wilson                 }
1818d500549bSAnthony Wilson             }
1819d500549bSAnthony Wilson 
1820d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1821d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1822d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1823d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1824d500549bSAnthony Wilson 
1825d500549bSAnthony Wilson             BMCWEB_LOG_DEBUG << "getInventoryLedData respHandler exit";
1826d500549bSAnthony Wilson         };
1827d500549bSAnthony Wilson 
1828d500549bSAnthony Wilson         // Get the State property for the current LED
18291e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18301e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18311e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18321e1e598dSJonathan Doman             std::move(respHandler));
1833d500549bSAnthony Wilson     }
1834d500549bSAnthony Wilson 
1835d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLedData exit";
1836d500549bSAnthony Wilson }
1837d500549bSAnthony Wilson 
1838d500549bSAnthony Wilson /**
1839d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1840d500549bSAnthony Wilson  *
1841d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1842d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1843d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1844d500549bSAnthony Wilson  *
1845d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1846d500549bSAnthony Wilson  * response.
1847d500549bSAnthony Wilson  *
1848d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1849d500549bSAnthony Wilson  * been obtained.
1850d500549bSAnthony Wilson  *
1851d500549bSAnthony Wilson  * The callback must have the following signature:
1852d500549bSAnthony Wilson  *   @code
185342cbe538SGunnar Mills  *   callback()
1854d500549bSAnthony Wilson  *   @endcode
1855d500549bSAnthony Wilson  *
1856d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1857d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1858d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1859d500549bSAnthony Wilson  */
1860d500549bSAnthony Wilson template <typename Callback>
1861d500549bSAnthony Wilson void getInventoryLeds(
1862d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1863d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1864d500549bSAnthony Wilson     Callback&& callback)
1865d500549bSAnthony Wilson {
1866d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds enter";
1867d500549bSAnthony Wilson 
1868d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1869d500549bSAnthony Wilson     const std::array<std::string, 1> interfaces = {
1870d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1871d500549bSAnthony Wilson 
1872d500549bSAnthony Wilson     // Response handler for parsing output from GetSubTree
1873002d39b4SEd Tanous     auto respHandler =
1874002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1875002d39b4SEd Tanous          inventoryItems](
1876b9d36b47SEd Tanous             const boost::system::error_code ec,
1877002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1878d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler enter";
1879d500549bSAnthony Wilson         if (ec)
1880d500549bSAnthony Wilson         {
18818d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
1882d500549bSAnthony Wilson             BMCWEB_LOG_ERROR << "getInventoryLeds respHandler DBus error "
1883d500549bSAnthony Wilson                              << ec;
1884d500549bSAnthony Wilson             return;
1885d500549bSAnthony Wilson         }
1886d500549bSAnthony Wilson 
1887d500549bSAnthony Wilson         // Build map of LED object paths to connections
1888fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1889fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1890d500549bSAnthony Wilson 
1891d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1892d500549bSAnthony Wilson         for (const std::pair<
1893d500549bSAnthony Wilson                  std::string,
1894d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1895d500549bSAnthony Wilson                  object : subtree)
1896d500549bSAnthony Wilson         {
1897d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1898d500549bSAnthony Wilson             // items
1899d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1900d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1901d500549bSAnthony Wilson             {
1902d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1903d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1904d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
1905d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "Added mapping " << ledPath << " -> "
1906d500549bSAnthony Wilson                                  << connection;
1907d500549bSAnthony Wilson             }
1908d500549bSAnthony Wilson         }
1909d500549bSAnthony Wilson 
1910d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1911d500549bSAnthony Wilson                             std::move(callback));
1912d500549bSAnthony Wilson         BMCWEB_LOG_DEBUG << "getInventoryLeds respHandler exit";
1913d500549bSAnthony Wilson     };
1914d500549bSAnthony Wilson     // Make call to ObjectMapper to find all inventory items
1915d500549bSAnthony Wilson     crow::connections::systemBus->async_method_call(
1916d500549bSAnthony Wilson         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
1917d500549bSAnthony Wilson         "/xyz/openbmc_project/object_mapper",
1918d500549bSAnthony Wilson         "xyz.openbmc_project.ObjectMapper", "GetSubTree", path, 0, interfaces);
1919d500549bSAnthony Wilson     BMCWEB_LOG_DEBUG << "getInventoryLeds exit";
1920d500549bSAnthony Wilson }
1921d500549bSAnthony Wilson 
1922d500549bSAnthony Wilson /**
192342cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
192442cbe538SGunnar Mills  *
192542cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
192642cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
192742cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
192842cbe538SGunnar Mills  *
192942cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
193042cbe538SGunnar Mills  * response.
193142cbe538SGunnar Mills  *
193242cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
193342cbe538SGunnar Mills  * when data has been obtained.
193442cbe538SGunnar Mills  *
193542cbe538SGunnar Mills  * The callback must have the following signature:
193642cbe538SGunnar Mills  *   @code
193742cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
193842cbe538SGunnar Mills  *   @endcode
193942cbe538SGunnar Mills  *
194042cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
194142cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
194242cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
194342cbe538SGunnar Mills  *        Supply Attributes
194442cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
194542cbe538SGunnar Mills  */
194642cbe538SGunnar Mills template <typename Callback>
194742cbe538SGunnar Mills void getPowerSupplyAttributesData(
1948b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
194942cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1950fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
195142cbe538SGunnar Mills     Callback&& callback)
195242cbe538SGunnar Mills {
195342cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData enter";
195442cbe538SGunnar Mills 
195542cbe538SGunnar Mills     if (psAttributesConnections.empty())
195642cbe538SGunnar Mills     {
195742cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Can't find PowerSupplyAttributes, no connections!";
195842cbe538SGunnar Mills         callback(inventoryItems);
195942cbe538SGunnar Mills         return;
196042cbe538SGunnar Mills     }
196142cbe538SGunnar Mills 
196242cbe538SGunnar Mills     // Assuming just one connection (service) for now
1963fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
196442cbe538SGunnar Mills 
196542cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
196642cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
196742cbe538SGunnar Mills 
196842cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
1969002d39b4SEd Tanous     auto respHandler =
1970002d39b4SEd Tanous         [sensorsAsyncResp, inventoryItems,
1971f94c4ecfSEd Tanous          callback{std::forward<Callback>(callback)}](
1972002d39b4SEd Tanous             const boost::system::error_code ec, const uint32_t value) {
197342cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler enter";
197442cbe538SGunnar Mills         if (ec)
197542cbe538SGunnar Mills         {
197642cbe538SGunnar Mills             BMCWEB_LOG_ERROR
197742cbe538SGunnar Mills                 << "getPowerSupplyAttributesData respHandler DBus error " << ec;
19788d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
197942cbe538SGunnar Mills             return;
198042cbe538SGunnar Mills         }
198142cbe538SGunnar Mills 
19821e1e598dSJonathan Doman         BMCWEB_LOG_DEBUG << "PS EfficiencyPercent value: " << value;
198342cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
198442cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
198542cbe538SGunnar Mills         {
198655f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
198742cbe538SGunnar Mills             {
198842cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19891e1e598dSJonathan Doman                     static_cast<int>(value);
199042cbe538SGunnar Mills             }
199142cbe538SGunnar Mills         }
199242cbe538SGunnar Mills 
199342cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData respHandler exit";
199442cbe538SGunnar Mills         callback(inventoryItems);
199542cbe538SGunnar Mills     };
199642cbe538SGunnar Mills 
199742cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
199842cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
19991e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
20001e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
20011e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
20021e1e598dSJonathan Doman         std::move(respHandler));
200342cbe538SGunnar Mills 
200442cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributesData exit";
200542cbe538SGunnar Mills }
200642cbe538SGunnar Mills 
200742cbe538SGunnar Mills /**
200842cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
200942cbe538SGunnar Mills  *
201042cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
201142cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
201242cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
201342cbe538SGunnar Mills  * item.
201442cbe538SGunnar Mills  *
201542cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
201642cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
201742cbe538SGunnar Mills  *
201842cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
201942cbe538SGunnar Mills  * when information has been obtained.
202042cbe538SGunnar Mills  *
202142cbe538SGunnar Mills  * The callback must have the following signature:
202242cbe538SGunnar Mills  *   @code
202342cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
202442cbe538SGunnar Mills  *   @endcode
202542cbe538SGunnar Mills  *
202642cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
202742cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
202842cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
202942cbe538SGunnar Mills  */
203042cbe538SGunnar Mills template <typename Callback>
203142cbe538SGunnar Mills void getPowerSupplyAttributes(
203242cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
203342cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
203442cbe538SGunnar Mills     Callback&& callback)
203542cbe538SGunnar Mills {
203642cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes enter";
203742cbe538SGunnar Mills 
203842cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2039a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
204042cbe538SGunnar Mills     {
204142cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit since not Power";
204242cbe538SGunnar Mills         callback(inventoryItems);
204342cbe538SGunnar Mills         return;
204442cbe538SGunnar Mills     }
204542cbe538SGunnar Mills 
204642cbe538SGunnar Mills     const std::array<std::string, 1> interfaces = {
204742cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
204842cbe538SGunnar Mills 
204942cbe538SGunnar Mills     // Response handler for parsing output from GetSubTree
2050b9d36b47SEd Tanous     auto respHandler =
2051b9d36b47SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2052b9d36b47SEd Tanous          inventoryItems](
2053b9d36b47SEd Tanous             const boost::system::error_code ec,
2054b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
205542cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler enter";
205642cbe538SGunnar Mills         if (ec)
205742cbe538SGunnar Mills         {
20588d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
205942cbe538SGunnar Mills             BMCWEB_LOG_ERROR
206042cbe538SGunnar Mills                 << "getPowerSupplyAttributes respHandler DBus error " << ec;
206142cbe538SGunnar Mills             return;
206242cbe538SGunnar Mills         }
206326f6976fSEd Tanous         if (subtree.empty())
206442cbe538SGunnar Mills         {
206542cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Can't find Power Supply Attributes!";
206642cbe538SGunnar Mills             callback(inventoryItems);
206742cbe538SGunnar Mills             return;
206842cbe538SGunnar Mills         }
206942cbe538SGunnar Mills 
207042cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
207142cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
207242cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2073fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
207442cbe538SGunnar Mills 
207542cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
207642cbe538SGunnar Mills         {
207742cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
207842cbe538SGunnar Mills             callback(inventoryItems);
207942cbe538SGunnar Mills             return;
208042cbe538SGunnar Mills         }
208142cbe538SGunnar Mills 
208242cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
208342cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
208442cbe538SGunnar Mills 
208542cbe538SGunnar Mills         if (connection.empty())
208642cbe538SGunnar Mills         {
208742cbe538SGunnar Mills             BMCWEB_LOG_DEBUG << "Power Supply Attributes mapper error!";
208842cbe538SGunnar Mills             callback(inventoryItems);
208942cbe538SGunnar Mills             return;
209042cbe538SGunnar Mills         }
209142cbe538SGunnar Mills 
209242cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
209342cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "Added mapping " << psAttributesPath << " -> "
209442cbe538SGunnar Mills                          << connection;
209542cbe538SGunnar Mills 
209642cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
209742cbe538SGunnar Mills                                      psAttributesConnections,
209842cbe538SGunnar Mills                                      std::move(callback));
209942cbe538SGunnar Mills         BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes respHandler exit";
210042cbe538SGunnar Mills     };
210142cbe538SGunnar Mills     // Make call to ObjectMapper to find the PowerSupplyAttributes service
210242cbe538SGunnar Mills     crow::connections::systemBus->async_method_call(
210342cbe538SGunnar Mills         std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
210442cbe538SGunnar Mills         "/xyz/openbmc_project/object_mapper",
210542cbe538SGunnar Mills         "xyz.openbmc_project.ObjectMapper", "GetSubTree",
210642cbe538SGunnar Mills         "/xyz/openbmc_project", 0, interfaces);
210742cbe538SGunnar Mills     BMCWEB_LOG_DEBUG << "getPowerSupplyAttributes exit";
210842cbe538SGunnar Mills }
210942cbe538SGunnar Mills 
211042cbe538SGunnar Mills /**
2111adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
21128fb49dd6SShawn McCarney  *
21138fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2114adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21158fb49dd6SShawn McCarney  *
2116adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2117adc4f0dbSShawn McCarney  * response.
21188fb49dd6SShawn McCarney  *
2119adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2120adc4f0dbSShawn McCarney  * inventory items have been obtained.
2121adc4f0dbSShawn McCarney  *
2122adc4f0dbSShawn McCarney  * The callback must have the following signature:
2123adc4f0dbSShawn McCarney  *   @code
2124adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2125adc4f0dbSShawn McCarney  *   @endcode
21268fb49dd6SShawn McCarney  *
21278fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21288fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21298fb49dd6SShawn McCarney  * implements ObjectManager.
2130adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21318fb49dd6SShawn McCarney  */
2132adc4f0dbSShawn McCarney template <typename Callback>
2133d0090733SEd Tanous static void
2134d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2135fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2136adc4f0dbSShawn McCarney                       Callback&& callback)
21378fb49dd6SShawn McCarney {
2138adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems enter";
2139adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2140d0090733SEd Tanous         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2141adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
2142adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb enter";
21438fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2144d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2145f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
2146fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
21478fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb enter";
2148002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2149d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
2150d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb enter";
215142cbe538SGunnar Mills 
2152002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2153002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
215442cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb enter";
215542cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2156002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
215742cbe538SGunnar Mills                                              std::move(callback));
215842cbe538SGunnar Mills                     BMCWEB_LOG_DEBUG << "getInventoryLedsCb exit";
215942cbe538SGunnar Mills                 };
216042cbe538SGunnar Mills 
2161d500549bSAnthony Wilson                 // Find led connections and get the data
2162d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
216342cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
2164d500549bSAnthony Wilson                 BMCWEB_LOG_DEBUG << "getInventoryItemsDataCb exit";
2165d500549bSAnthony Wilson             };
21668fb49dd6SShawn McCarney 
2167adc4f0dbSShawn McCarney             // Get inventory item data from connections
2168adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2169d0090733SEd Tanous                                   invConnections,
2170d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
21718fb49dd6SShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsConnectionsCb exit";
21728fb49dd6SShawn McCarney         };
21738fb49dd6SShawn McCarney 
2174adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2175002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21768fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
2177adc4f0dbSShawn McCarney         BMCWEB_LOG_DEBUG << "getInventoryItemAssociationsCb exit";
21788fb49dd6SShawn McCarney     };
21798fb49dd6SShawn McCarney 
2180adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2181d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2182adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
2183adc4f0dbSShawn McCarney     BMCWEB_LOG_DEBUG << "getInventoryItems exit";
2184adc4f0dbSShawn McCarney }
2185adc4f0dbSShawn McCarney 
2186adc4f0dbSShawn McCarney /**
2187adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2188adc4f0dbSShawn McCarney  *
2189adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2190adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2191adc4f0dbSShawn McCarney  * array.
2192adc4f0dbSShawn McCarney  *
2193adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2194adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2195adc4f0dbSShawn McCarney  * object.
2196adc4f0dbSShawn McCarney  *
2197adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2198adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2199adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2200adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2201adc4f0dbSShawn McCarney  */
220223a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2203adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2204adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2205adc4f0dbSShawn McCarney {
2206adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2207adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2208adc4f0dbSShawn McCarney     {
2209adc4f0dbSShawn McCarney         if (powerSupply["MemberId"] == inventoryItem.name)
2210adc4f0dbSShawn McCarney         {
2211adc4f0dbSShawn McCarney             return powerSupply;
2212adc4f0dbSShawn McCarney         }
2213adc4f0dbSShawn McCarney     }
2214adc4f0dbSShawn McCarney 
2215adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2216adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2217adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2218adc4f0dbSShawn McCarney     powerSupply["@odata.id"] =
2219adc4f0dbSShawn McCarney         "/redfish/v1/Chassis/" + chassisId + "/Power#/PowerSupplies/";
2220adc4f0dbSShawn McCarney     powerSupply["MemberId"] = inventoryItem.name;
2221adc4f0dbSShawn McCarney     powerSupply["Name"] = boost::replace_all_copy(inventoryItem.name, "_", " ");
2222adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2223adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2224adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2225adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2226d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2227adc4f0dbSShawn McCarney 
222842cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
222942cbe538SGunnar Mills     {
223042cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
223142cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
223242cbe538SGunnar Mills     }
223342cbe538SGunnar Mills 
223442cbe538SGunnar Mills     powerSupply["Status"]["State"] = getState(&inventoryItem);
2235adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2236adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2237adc4f0dbSShawn McCarney 
2238adc4f0dbSShawn McCarney     return powerSupply;
22398fb49dd6SShawn McCarney }
22408fb49dd6SShawn McCarney 
22418fb49dd6SShawn McCarney /**
2242de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2243de629b6eSShawn McCarney  *
2244de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2245de629b6eSShawn McCarney  *
2246de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2247de629b6eSShawn McCarney  * information has been obtained.
2248de629b6eSShawn McCarney  *
2249adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2250de629b6eSShawn McCarney  *
2251de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2252de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2253de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2254de629b6eSShawn McCarney  *
2255de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2256de629b6eSShawn McCarney  *
2257adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2258adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2259adc4f0dbSShawn McCarney  *
2260de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2261adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2262de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2263de629b6eSShawn McCarney  * implements ObjectManager.
2264adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2265de629b6eSShawn McCarney  */
226623a21a1cSEd Tanous inline void getSensorData(
226781ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2268fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2269fe04d49cSNan Zhou     const std::set<std::string>& connections,
2270b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2271de629b6eSShawn McCarney {
2272de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData enter";
2273de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2274de629b6eSShawn McCarney     for (const std::string& connection : connections)
2275de629b6eSShawn McCarney     {
2276de629b6eSShawn McCarney         // Response handler to process managed objects
2277002d39b4SEd Tanous         auto getManagedObjectsCb =
2278002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
2279002d39b4SEd Tanous              inventoryItems](const boost::system::error_code ec,
228002cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
2281de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
2282de629b6eSShawn McCarney             if (ec)
2283de629b6eSShawn McCarney             {
2284de629b6eSShawn McCarney                 BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
22858d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2286de629b6eSShawn McCarney                 return;
2287de629b6eSShawn McCarney             }
2288de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2289de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2290de629b6eSShawn McCarney             {
2291de629b6eSShawn McCarney                 const std::string& objPath =
2292de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
2293de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
2294de629b6eSShawn McCarney                                  << objPath;
2295de629b6eSShawn McCarney 
2296de629b6eSShawn McCarney                 std::vector<std::string> split;
2297de629b6eSShawn McCarney                 // Reserve space for
2298de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2299de629b6eSShawn McCarney                 split.reserve(6);
2300de629b6eSShawn McCarney                 boost::algorithm::split(split, objPath, boost::is_any_of("/"));
2301de629b6eSShawn McCarney                 if (split.size() < 6)
2302de629b6eSShawn McCarney                 {
2303de629b6eSShawn McCarney                     BMCWEB_LOG_ERROR << "Got path that isn't long enough "
2304de629b6eSShawn McCarney                                      << objPath;
2305de629b6eSShawn McCarney                     continue;
2306de629b6eSShawn McCarney                 }
2307de629b6eSShawn McCarney                 // These indexes aren't intuitive, as boost::split puts an empty
2308de629b6eSShawn McCarney                 // string at the beginning
2309de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2310de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
2311de629b6eSShawn McCarney                 BMCWEB_LOG_DEBUG << "sensorName " << sensorName
2312de629b6eSShawn McCarney                                  << " sensorType " << sensorType;
231349c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2314de629b6eSShawn McCarney                 {
2315accdbb2cSAndrew Geissler                     BMCWEB_LOG_DEBUG << sensorName << " not in sensor list ";
2316de629b6eSShawn McCarney                     continue;
2317de629b6eSShawn McCarney                 }
2318de629b6eSShawn McCarney 
2319adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2320adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2321adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2322adc4f0dbSShawn McCarney 
232395a3ecadSAnthony Wilson                 const std::string& sensorSchema =
232481ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
232595a3ecadSAnthony Wilson 
232695a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
232795a3ecadSAnthony Wilson 
2328928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2329928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
233095a3ecadSAnthony Wilson                 {
2331c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
2332c1d019a6SEd Tanous                     sensorTypeEscaped.erase(
2333c1d019a6SEd Tanous                         std::remove(sensorTypeEscaped.begin(),
2334c1d019a6SEd Tanous                                     sensorTypeEscaped.end(), '_'),
2335c1d019a6SEd Tanous                         sensorTypeEscaped.end());
2336c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2337c1d019a6SEd Tanous                     sensorId += "_";
2338c1d019a6SEd Tanous                     sensorId += sensorName;
2339c1d019a6SEd Tanous 
23408d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2341c1d019a6SEd Tanous                         crow::utility::urlFromPieces(
2342c1d019a6SEd Tanous                             "redfish", "v1", "Chassis",
2343c1d019a6SEd Tanous                             sensorsAsyncResp->chassisId,
2344c1d019a6SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
23458d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
234695a3ecadSAnthony Wilson                 }
234795a3ecadSAnthony Wilson                 else
234895a3ecadSAnthony Wilson                 {
2349271584abSEd Tanous                     std::string fieldName;
2350928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2351928fefb9SNan Zhou                     {
2352928fefb9SNan Zhou                         fieldName = "Members";
2353928fefb9SNan Zhou                     }
2354928fefb9SNan Zhou                     else if (sensorType == "temperature")
2355de629b6eSShawn McCarney                     {
2356de629b6eSShawn McCarney                         fieldName = "Temperatures";
2357de629b6eSShawn McCarney                     }
2358de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2359de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2360de629b6eSShawn McCarney                     {
2361de629b6eSShawn McCarney                         fieldName = "Fans";
2362de629b6eSShawn McCarney                     }
2363de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2364de629b6eSShawn McCarney                     {
2365de629b6eSShawn McCarney                         fieldName = "Voltages";
2366de629b6eSShawn McCarney                     }
2367de629b6eSShawn McCarney                     else if (sensorType == "power")
2368de629b6eSShawn McCarney                     {
236955f79e6fSEd Tanous                         if (sensorName == "total_power")
2370028f7ebcSEddie James                         {
2371028f7ebcSEddie James                             fieldName = "PowerControl";
2372028f7ebcSEddie James                         }
2373adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2374adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2375028f7ebcSEddie James                         {
2376de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2377de629b6eSShawn McCarney                         }
2378adc4f0dbSShawn McCarney                         else
2379adc4f0dbSShawn McCarney                         {
2380adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2381adc4f0dbSShawn McCarney                             continue;
2382adc4f0dbSShawn McCarney                         }
2383028f7ebcSEddie James                     }
2384de629b6eSShawn McCarney                     else
2385de629b6eSShawn McCarney                     {
2386de629b6eSShawn McCarney                         BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
2387de629b6eSShawn McCarney                                          << sensorType;
2388de629b6eSShawn McCarney                         continue;
2389de629b6eSShawn McCarney                     }
2390de629b6eSShawn McCarney 
2391de629b6eSShawn McCarney                     nlohmann::json& tempArray =
23928d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2393adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
239449c53ac9SJohnathan Mantey                     {
2395adc4f0dbSShawn McCarney                         if (tempArray.empty())
23967ab06f49SGunnar Mills                         {
239795a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
239895a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
239995a3ecadSAnthony Wilson                             // naming in power.hpp.
24001476687dSEd Tanous                             nlohmann::json::object_t power;
24011476687dSEd Tanous                             power["@odata.id"] =
2402adc4f0dbSShawn McCarney                                 "/redfish/v1/Chassis/" +
240381ce609eSEd Tanous                                 sensorsAsyncResp->chassisId + "/" +
240481ce609eSEd Tanous                                 sensorsAsyncResp->chassisSubNode + "#/" +
24051476687dSEd Tanous                                 fieldName + "/0";
24061476687dSEd Tanous                             tempArray.push_back(std::move(power));
2407adc4f0dbSShawn McCarney                         }
2408adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2409adc4f0dbSShawn McCarney                     }
2410adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2411adc4f0dbSShawn McCarney                     {
2412adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2413adc4f0dbSShawn McCarney                         {
2414adc4f0dbSShawn McCarney                             sensorJson =
2415adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
241681ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2417adc4f0dbSShawn McCarney                         }
241849c53ac9SJohnathan Mantey                     }
2419928fefb9SNan Zhou                     else if (fieldName == "Members")
2420928fefb9SNan Zhou                     {
2421677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
2422677bb756SEd Tanous                         sensorTypeEscaped.erase(
2423677bb756SEd Tanous                             std::remove(sensorTypeEscaped.begin(),
2424677bb756SEd Tanous                                         sensorTypeEscaped.end(), '_'),
2425677bb756SEd Tanous                             sensorTypeEscaped.end());
2426677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2427677bb756SEd Tanous                         sensorId += "_";
2428677bb756SEd Tanous                         sensorId += sensorName;
2429677bb756SEd Tanous 
24301476687dSEd Tanous                         nlohmann::json::object_t member;
2431677bb756SEd Tanous                         member["@odata.id"] = crow::utility::urlFromPieces(
2432677bb756SEd Tanous                             "redfish", "v1", "Chassis",
2433677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2434677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
24351476687dSEd Tanous                         tempArray.push_back(std::move(member));
2436928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2437928fefb9SNan Zhou                     }
243849c53ac9SJohnathan Mantey                     else
243949c53ac9SJohnathan Mantey                     {
24401476687dSEd Tanous                         nlohmann::json::object_t member;
24411476687dSEd Tanous                         member["@odata.id"] = "/redfish/v1/Chassis/" +
24421476687dSEd Tanous                                               sensorsAsyncResp->chassisId +
24431476687dSEd Tanous                                               "/" +
24441476687dSEd Tanous                                               sensorsAsyncResp->chassisSubNode +
24451476687dSEd Tanous                                               "#/" + fieldName + "/";
24461476687dSEd Tanous                         tempArray.push_back(std::move(member));
2447adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
244849c53ac9SJohnathan Mantey                     }
244995a3ecadSAnthony Wilson                 }
2450de629b6eSShawn McCarney 
2451adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2452adc4f0dbSShawn McCarney                 {
24531d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24541d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24551d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24561d7c0054SEd Tanous                                            inventoryItem);
24571d7c0054SEd Tanous 
24581d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24591d7c0054SEd Tanous                     path += sensorType;
24601d7c0054SEd Tanous                     path += "/";
24611d7c0054SEd Tanous                     path += sensorName;
2462c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2463adc4f0dbSShawn McCarney                 }
2464de629b6eSShawn McCarney             }
246581ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
246649c53ac9SJohnathan Mantey             {
246781ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2468928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2469928fefb9SNan Zhou                         sensors::node::sensors &&
2470928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2471928fefb9SNan Zhou                 {
2472928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2473928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2474928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2475928fefb9SNan Zhou                             .size();
2476928fefb9SNan Zhou                 }
2477928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2478928fefb9SNan Zhou                          sensors::node::thermal)
24798bd25ccdSJames Feist                 {
248081ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
24818bd25ccdSJames Feist                 }
248249c53ac9SJohnathan Mantey             }
2483de629b6eSShawn McCarney             BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
2484de629b6eSShawn McCarney         };
2485de629b6eSShawn McCarney 
2486de629b6eSShawn McCarney         crow::connections::systemBus->async_method_call(
2487d0090733SEd Tanous             getManagedObjectsCb, connection, "/xyz/openbmc_project/sensors",
2488de629b6eSShawn McCarney             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
248923a21a1cSEd Tanous     }
2490de629b6eSShawn McCarney     BMCWEB_LOG_DEBUG << "getSensorData exit";
2491de629b6eSShawn McCarney }
2492de629b6eSShawn McCarney 
2493fe04d49cSNan Zhou inline void
2494fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2495fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
24961abe55efSEd Tanous {
2497fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2498fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
249955c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb enter";
2500adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2501d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2502d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2503adc4f0dbSShawn McCarney                               inventoryItems) {
2504adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb enter";
250549c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2506002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2507d0090733SEd Tanous                           inventoryItems);
2508adc4f0dbSShawn McCarney             BMCWEB_LOG_DEBUG << "getInventoryItemsCb exit";
2509adc4f0dbSShawn McCarney         };
2510adc4f0dbSShawn McCarney 
2511adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2512d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2513adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2514adc4f0dbSShawn McCarney 
251555c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getConnectionCb exit";
251608777fb0SLewanczyk, Dawid     };
2517de629b6eSShawn McCarney 
2518de629b6eSShawn McCarney     // Get set of connections that provide sensor values
251981ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
252095a3ecadSAnthony Wilson }
252195a3ecadSAnthony Wilson 
252295a3ecadSAnthony Wilson /**
252395a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
252495a3ecadSAnthony Wilson  *        chassis.
252595a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
252695a3ecadSAnthony Wilson  */
2527b5a76932SEd Tanous inline void
252881ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
252995a3ecadSAnthony Wilson {
253095a3ecadSAnthony Wilson     BMCWEB_LOG_DEBUG << "getChassisData enter";
253195a3ecadSAnthony Wilson     auto getChassisCb =
253281ce609eSEd Tanous         [sensorsAsyncResp](
2533fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
253495a3ecadSAnthony Wilson         BMCWEB_LOG_DEBUG << "getChassisCb enter";
253581ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
253655c7b7a2SEd Tanous         BMCWEB_LOG_DEBUG << "getChassisCb exit";
253708777fb0SLewanczyk, Dawid     };
2538928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2539928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2540928fefb9SNan Zhou     {
25418d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25428d1b46d7Szhanghch05             nlohmann::json::array();
2543928fefb9SNan Zhou     }
254426f03899SShawn McCarney     // Get set of sensors in chassis
25457f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25467f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25477f1cc26dSEd Tanous                std::move(getChassisCb));
254855c7b7a2SEd Tanous     BMCWEB_LOG_DEBUG << "getChassisData exit";
2549271584abSEd Tanous }
255008777fb0SLewanczyk, Dawid 
2551413961deSRichard Marian Thomaiyar /**
255249c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
255349c53ac9SJohnathan Mantey  * the chassis node
255449c53ac9SJohnathan Mantey  *
255549c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
255649c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
255749c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
255849c53ac9SJohnathan Mantey  *                         repeated calls to this function
255949c53ac9SJohnathan Mantey  */
2560fe04d49cSNan Zhou inline bool
2561fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
256202cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2563fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
256449c53ac9SJohnathan Mantey {
2565fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
256649c53ac9SJohnathan Mantey     {
256728aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2568b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
256928aa8de5SGeorge Liu         if (thisSensorName.empty())
257049c53ac9SJohnathan Mantey         {
257149c53ac9SJohnathan Mantey             continue;
257249c53ac9SJohnathan Mantey         }
257349c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
257449c53ac9SJohnathan Mantey         {
257549c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
257649c53ac9SJohnathan Mantey             return true;
257749c53ac9SJohnathan Mantey         }
257849c53ac9SJohnathan Mantey     }
257949c53ac9SJohnathan Mantey     return false;
258049c53ac9SJohnathan Mantey }
258149c53ac9SJohnathan Mantey 
2582*c71d6125SEd Tanous inline std::pair<std::string, std::string>
2583*c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2584*c71d6125SEd Tanous {
2585*c71d6125SEd Tanous     size_t index = sensorId.find('_');
2586*c71d6125SEd Tanous     if (index == std::string::npos)
2587*c71d6125SEd Tanous     {
2588*c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2589*c71d6125SEd Tanous     }
2590*c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2591*c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2592*c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2593*c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2594*c71d6125SEd Tanous     {
2595*c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2596*c71d6125SEd Tanous     }
2597*c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2598*c71d6125SEd Tanous }
2599*c71d6125SEd Tanous 
260049c53ac9SJohnathan Mantey /**
2601413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2602413961deSRichard Marian Thomaiyar  *
26038d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
26044bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2605413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2606413961deSRichard Marian Thomaiyar  */
260723a21a1cSEd Tanous inline void setSensorsOverride(
2608b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26094bb3dc34SCarol Wang     std::unordered_map<std::string, std::vector<nlohmann::json>>&
2610397fd61fSjayaprakash Mutyala         allCollections)
2611413961deSRichard Marian Thomaiyar {
261270d1d0aaSjayaprakash Mutyala     BMCWEB_LOG_INFO << "setSensorsOverride for subNode"
26134bb3dc34SCarol Wang                     << sensorAsyncResp->chassisSubNode << "\n";
2614413961deSRichard Marian Thomaiyar 
2615543f4400SEd Tanous     const char* propertyValueName = nullptr;
2616f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2617413961deSRichard Marian Thomaiyar     std::string memberId;
2618543f4400SEd Tanous     double value = 0.0;
2619f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2620f65af9e8SRichard Marian Thomaiyar     {
2621f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2622f65af9e8SRichard Marian Thomaiyar         {
2623f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2624f65af9e8SRichard Marian Thomaiyar         }
2625f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2626f65af9e8SRichard Marian Thomaiyar         {
2627f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2628f65af9e8SRichard Marian Thomaiyar         }
2629f65af9e8SRichard Marian Thomaiyar         else
2630f65af9e8SRichard Marian Thomaiyar         {
2631f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2632f65af9e8SRichard Marian Thomaiyar         }
2633f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2634f65af9e8SRichard Marian Thomaiyar         {
26358d1b46d7Szhanghch05             if (!json_util::readJson(item, sensorAsyncResp->asyncResp->res,
26368d1b46d7Szhanghch05                                      "MemberId", memberId, propertyValueName,
26378d1b46d7Szhanghch05                                      value))
2638413961deSRichard Marian Thomaiyar             {
2639413961deSRichard Marian Thomaiyar                 return;
2640413961deSRichard Marian Thomaiyar             }
2641f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2642f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2643f65af9e8SRichard Marian Thomaiyar         }
2644f65af9e8SRichard Marian Thomaiyar     }
26454bb3dc34SCarol Wang 
2646002d39b4SEd Tanous     auto getChassisSensorListCb =
2647002d39b4SEd Tanous         [sensorAsyncResp, overrideMap](
2648fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
264949c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
265049c53ac9SJohnathan Mantey         // chassis node
2651fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2652fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2653f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2654413961deSRichard Marian Thomaiyar         {
2655f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2656*c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2657*c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2658*c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2659*c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2660f65af9e8SRichard Marian Thomaiyar             {
2661f65af9e8SRichard Marian Thomaiyar                 BMCWEB_LOG_INFO << "Unable to find memberId " << item.first;
26628d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2663f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2664413961deSRichard Marian Thomaiyar                 return;
2665413961deSRichard Marian Thomaiyar             }
2666f65af9e8SRichard Marian Thomaiyar         }
2667413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2668002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2669fe04d49cSNan Zhou             [sensorAsyncResp,
2670fe04d49cSNan Zhou              overrideMap](const std::set<std::string>& /*connections*/,
2671002d39b4SEd Tanous                           const std::set<std::pair<std::string, std::string>>&
2672413961deSRichard Marian Thomaiyar                               objectsWithConnection) {
2673f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2674413961deSRichard Marian Thomaiyar             {
2675413961deSRichard Marian Thomaiyar                 BMCWEB_LOG_INFO
2676f65af9e8SRichard Marian Thomaiyar                     << "Unable to find all objects with proper connection "
2677f65af9e8SRichard Marian Thomaiyar                     << objectsWithConnection.size() << " requested "
2678f65af9e8SRichard Marian Thomaiyar                     << overrideMap.size() << "\n";
26794f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2680a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2681a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2682413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2683413961deSRichard Marian Thomaiyar                                                : "Voltages",
2684f65af9e8SRichard Marian Thomaiyar                                            "Count");
2685f65af9e8SRichard Marian Thomaiyar                 return;
2686f65af9e8SRichard Marian Thomaiyar             }
2687f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2688f65af9e8SRichard Marian Thomaiyar             {
268928aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
269028aa8de5SGeorge Liu                 std::string sensorName = path.filename();
269128aa8de5SGeorge Liu                 if (sensorName.empty())
2692f65af9e8SRichard Marian Thomaiyar                 {
26934f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2694f65af9e8SRichard Marian Thomaiyar                     return;
2695f65af9e8SRichard Marian Thomaiyar                 }
2696f65af9e8SRichard Marian Thomaiyar 
2697f65af9e8SRichard Marian Thomaiyar                 const auto& iterator = overrideMap.find(sensorName);
2698f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2699f65af9e8SRichard Marian Thomaiyar                 {
2700f65af9e8SRichard Marian Thomaiyar                     BMCWEB_LOG_INFO << "Unable to find sensor object"
2701f65af9e8SRichard Marian Thomaiyar                                     << item.first << "\n";
27024f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2703413961deSRichard Marian Thomaiyar                     return;
2704413961deSRichard Marian Thomaiyar                 }
2705413961deSRichard Marian Thomaiyar                 crow::connections::systemBus->async_method_call(
2706f65af9e8SRichard Marian Thomaiyar                     [sensorAsyncResp](const boost::system::error_code ec) {
2707413961deSRichard Marian Thomaiyar                     if (ec)
2708413961deSRichard Marian Thomaiyar                     {
27094f277b54SJayaprakash Mutyala                         if (ec.value() ==
27104f277b54SJayaprakash Mutyala                             boost::system::errc::permission_denied)
27114f277b54SJayaprakash Mutyala                         {
27124f277b54SJayaprakash Mutyala                             BMCWEB_LOG_WARNING
27134f277b54SJayaprakash Mutyala                                 << "Manufacturing mode is not Enabled...can't "
27144f277b54SJayaprakash Mutyala                                    "Override the sensor value. ";
27154f277b54SJayaprakash Mutyala 
27164f277b54SJayaprakash Mutyala                             messages::insufficientPrivilege(
27178d1b46d7Szhanghch05                                 sensorAsyncResp->asyncResp->res);
2718413961deSRichard Marian Thomaiyar                             return;
2719413961deSRichard Marian Thomaiyar                         }
27204f277b54SJayaprakash Mutyala                         BMCWEB_LOG_DEBUG
27214f277b54SJayaprakash Mutyala                             << "setOverrideValueStatus DBUS error: " << ec;
27224f277b54SJayaprakash Mutyala                         messages::internalError(
27234f277b54SJayaprakash Mutyala                             sensorAsyncResp->asyncResp->res);
27244f277b54SJayaprakash Mutyala                     }
2725413961deSRichard Marian Thomaiyar                     },
27264f277b54SJayaprakash Mutyala                     item.second, item.first, "org.freedesktop.DBus.Properties",
27274f277b54SJayaprakash Mutyala                     "Set", "xyz.openbmc_project.Sensor.Value", "Value",
2728168e20c1SEd Tanous                     dbus::utility::DbusVariantType(iterator->second.first));
2729f65af9e8SRichard Marian Thomaiyar             }
2730413961deSRichard Marian Thomaiyar         };
2731413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2732413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2733413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2734413961deSRichard Marian Thomaiyar     };
2735413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27367f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27377f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27387f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2739413961deSRichard Marian Thomaiyar }
2740413961deSRichard Marian Thomaiyar 
2741a0ec28b6SAdrian Ambrożewicz /**
2742a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2743a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2744a0ec28b6SAdrian Ambrożewicz  *
2745a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2746a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2747a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2748a0ec28b6SAdrian Ambrożewicz  *
2749a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2750a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2751a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2752a0ec28b6SAdrian Ambrożewicz  */
2753021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2754021d32cfSKrzysztof Grobelny                                  const std::string& node,
2755a0ec28b6SAdrian Ambrożewicz                                  SensorsAsyncResp::DataCompleteCb&& mapComplete)
2756a0ec28b6SAdrian Ambrożewicz {
275702da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
275802da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
275902da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
276002da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2761a0ec28b6SAdrian Ambrożewicz     {
2762a0ec28b6SAdrian Ambrożewicz         BMCWEB_LOG_ERROR << "Wrong node provided : " << node;
2763a0ec28b6SAdrian Ambrożewicz         mapComplete(boost::beast::http::status::bad_request, {});
2764a0ec28b6SAdrian Ambrożewicz         return;
2765a0ec28b6SAdrian Ambrożewicz     }
2766d51e072fSKrzysztof Grobelny 
276772374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2768fe04d49cSNan Zhou     auto callback = [asyncResp, mapCompleteCb{std::move(mapComplete)}](
2769a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2770fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2771fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2772fe04d49cSNan Zhou     };
2773a0ec28b6SAdrian Ambrożewicz 
2774a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2775d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2776a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2777a0ec28b6SAdrian Ambrożewicz }
2778a0ec28b6SAdrian Ambrożewicz 
2779bacb2162SNan Zhou namespace sensors
2780bacb2162SNan Zhou {
2781928fefb9SNan Zhou 
2782bacb2162SNan Zhou inline void getChassisCallback(
2783c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2784c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2785fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2786bacb2162SNan Zhou {
2787bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback enter ";
2788bacb2162SNan Zhou 
2789c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2790c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2791bacb2162SNan Zhou     {
2792bacb2162SNan Zhou         BMCWEB_LOG_DEBUG << "Adding sensor: " << sensor;
2793bacb2162SNan Zhou 
2794bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2795bacb2162SNan Zhou         std::string sensorName = path.filename();
2796bacb2162SNan Zhou         if (sensorName.empty())
2797bacb2162SNan Zhou         {
2798bacb2162SNan Zhou             BMCWEB_LOG_ERROR << "Invalid sensor path: " << sensor;
2799c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2800bacb2162SNan Zhou             return;
2801bacb2162SNan Zhou         }
2802c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2803c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2804c1d019a6SEd Tanous         // type in the URI
2805c1d019a6SEd Tanous         type.erase(std::remove(type.begin(), type.end(), '_'), type.end());
2806c1d019a6SEd Tanous 
28071476687dSEd Tanous         nlohmann::json::object_t member;
2808c1d019a6SEd Tanous         std::string id = type;
2809c1d019a6SEd Tanous         id += "_";
2810c1d019a6SEd Tanous         id += sensorName;
2811c1d019a6SEd Tanous         member["@odata.id"] = crow::utility::urlFromPieces(
2812c1d019a6SEd Tanous             "redfish", "v1", "Chassis", chassisId, chassisSubNode, id);
2813c1d019a6SEd Tanous 
28141476687dSEd Tanous         entriesArray.push_back(std::move(member));
2815bacb2162SNan Zhou     }
2816bacb2162SNan Zhou 
2817c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
2818bacb2162SNan Zhou     BMCWEB_LOG_DEBUG << "getChassisCallback exit";
2819bacb2162SNan Zhou }
2820e6bd846dSNan Zhou 
2821de167a6fSNan Zhou inline void
2822de167a6fSNan Zhou     handleSensorCollectionGet(App& app, const crow::Request& req,
2823de167a6fSNan Zhou                               const std::shared_ptr<bmcweb::AsyncResp>& aResp,
2824de167a6fSNan Zhou                               const std::string& chassisId)
2825de167a6fSNan Zhou {
2826de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2827de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2828de167a6fSNan Zhou     };
2829de167a6fSNan Zhou     query_param::Query delegatedQuery;
28303ba00073SCarson Labrado     if (!redfish::setUpRedfishRouteWithDelegation(app, req, aResp,
2831de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2832de167a6fSNan Zhou     {
2833de167a6fSNan Zhou         return;
2834de167a6fSNan Zhou     }
2835de167a6fSNan Zhou 
2836de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2837de167a6fSNan Zhou     {
2838de167a6fSNan Zhou         // we perform efficient expand.
2839de167a6fSNan Zhou         auto asyncResp = std::make_shared<SensorsAsyncResp>(
2840de167a6fSNan Zhou             aResp, chassisId, sensors::dbus::sensorPaths,
2841de167a6fSNan Zhou             sensors::node::sensors,
2842de167a6fSNan Zhou             /*efficientExpand=*/true);
2843de167a6fSNan Zhou         getChassisData(asyncResp);
2844de167a6fSNan Zhou 
2845de167a6fSNan Zhou         BMCWEB_LOG_DEBUG
2846de167a6fSNan Zhou             << "SensorCollection doGet exit via efficient expand handler";
2847de167a6fSNan Zhou         return;
28480bad320cSEd Tanous     }
2849de167a6fSNan Zhou 
2850de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2851de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2852c1d019a6SEd Tanous     getChassis(aResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2853c1d019a6SEd Tanous                std::bind_front(sensors::getChassisCallback, aResp, chassisId,
2854c1d019a6SEd Tanous                                sensors::node::sensors));
2855c1d019a6SEd Tanous }
28567f1cc26dSEd Tanous 
2857c1d019a6SEd Tanous inline void
2858c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2859c1d019a6SEd Tanous                       const std::string& sensorPath,
2860c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2861c1d019a6SEd Tanous {
2862c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2863c1d019a6SEd Tanous     {
2864c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2865c1d019a6SEd Tanous         return;
2866c1d019a6SEd Tanous     }
2867c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2868c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
2869c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Looking up " << connectionName;
2870c1d019a6SEd Tanous     BMCWEB_LOG_DEBUG << "Path " << sensorPath;
2871c1343bf6SKrzysztof Grobelny 
2872c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2873c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2874c1d019a6SEd Tanous         [asyncResp,
2875c1d019a6SEd Tanous          sensorPath](const boost::system::error_code ec,
2876c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2877c1d019a6SEd Tanous         if (ec)
2878c1d019a6SEd Tanous         {
2879c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2880c1d019a6SEd Tanous             return;
2881c1d019a6SEd Tanous         }
2882c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2883c1d019a6SEd Tanous         std::string name = path.filename();
2884c1d019a6SEd Tanous         path = path.parent_path();
2885c1d019a6SEd Tanous         std::string type = path.filename();
2886c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2887c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2888c1343bf6SKrzysztof Grobelny         });
2889de167a6fSNan Zhou }
2890de167a6fSNan Zhou 
2891e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2892c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2893677bb756SEd Tanous                             const std::string& chassisId,
2894c1d019a6SEd Tanous                             const std::string& sensorId)
2895e6bd846dSNan Zhou {
2896c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2897e6bd846dSNan Zhou     {
2898e6bd846dSNan Zhou         return;
2899e6bd846dSNan Zhou     }
2900*c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2901*c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2902*c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2903c1d019a6SEd Tanous     {
2904c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2905c1d019a6SEd Tanous         return;
2906c1d019a6SEd Tanous     }
2907*c71d6125SEd Tanous 
2908677bb756SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = crow::utility::urlFromPieces(
2909677bb756SEd Tanous         "redfish", "v1", "Chassis", chassisId, "Sensors", sensorId);
2910c1d019a6SEd Tanous 
2911e6bd846dSNan Zhou     BMCWEB_LOG_DEBUG << "Sensor doGet enter";
2912e6bd846dSNan Zhou 
2913e6bd846dSNan Zhou     const std::array<const char*, 1> interfaces = {
2914e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2915*c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2916*c71d6125SEd Tanous                              '/' + nameType.second;
2917e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2918e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
2919e6bd846dSNan Zhou     crow::connections::systemBus->async_method_call(
2920*c71d6125SEd Tanous         [asyncResp,
2921*c71d6125SEd Tanous          sensorPath](const boost::system::error_code ec,
2922c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
2923e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 enter";
2924e6bd846dSNan Zhou         if (ec)
2925e6bd846dSNan Zhou         {
2926c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2927e6bd846dSNan Zhou             BMCWEB_LOG_ERROR << "Sensor getSensorPaths resp_handler: "
2928e6bd846dSNan Zhou                              << "Dbus error " << ec;
2929e6bd846dSNan Zhou             return;
2930e6bd846dSNan Zhou         }
2931c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
2932e6bd846dSNan Zhou         BMCWEB_LOG_DEBUG << "respHandler1 exit";
2933e6bd846dSNan Zhou         },
2934e6bd846dSNan Zhou         "xyz.openbmc_project.ObjectMapper",
2935e6bd846dSNan Zhou         "/xyz/openbmc_project/object_mapper",
2936c1d019a6SEd Tanous         "xyz.openbmc_project.ObjectMapper", "GetObject", sensorPath,
2937c1d019a6SEd Tanous         interfaces);
2938e6bd846dSNan Zhou }
2939e6bd846dSNan Zhou 
2940bacb2162SNan Zhou } // namespace sensors
2941bacb2162SNan Zhou 
29427e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
294395a3ecadSAnthony Wilson {
29447e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2945ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2946002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2947de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
294895a3ecadSAnthony Wilson }
294995a3ecadSAnthony Wilson 
29507e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
295195a3ecadSAnthony Wilson {
29527e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2953ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2954002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2955e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
295695a3ecadSAnthony Wilson }
295795a3ecadSAnthony Wilson 
295808777fb0SLewanczyk, Dawid } // namespace redfish
2959