xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 18f8f608b966c802b3e2a389e3c1ec5a1fd9407b)
108777fb0SLewanczyk, Dawid /*
208777fb0SLewanczyk, Dawid // Copyright (c) 2018 Intel Corporation
308777fb0SLewanczyk, Dawid //
408777fb0SLewanczyk, Dawid // Licensed under the Apache License, Version 2.0 (the "License");
508777fb0SLewanczyk, Dawid // you may not use this file except in compliance with the License.
608777fb0SLewanczyk, Dawid // You may obtain a copy of the License at
708777fb0SLewanczyk, Dawid //
808777fb0SLewanczyk, Dawid //      http://www.apache.org/licenses/LICENSE-2.0
908777fb0SLewanczyk, Dawid //
1008777fb0SLewanczyk, Dawid // Unless required by applicable law or agreed to in writing, software
1108777fb0SLewanczyk, Dawid // distributed under the License is distributed on an "AS IS" BASIS,
1208777fb0SLewanczyk, Dawid // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1308777fb0SLewanczyk, Dawid // See the License for the specific language governing permissions and
1408777fb0SLewanczyk, Dawid // limitations under the License.
1508777fb0SLewanczyk, Dawid */
1608777fb0SLewanczyk, Dawid #pragma once
1708777fb0SLewanczyk, Dawid 
183ccb3adbSEd Tanous #include "app.hpp"
193ccb3adbSEd Tanous #include "dbus_singleton.hpp"
207a1dbc48SGeorge Liu #include "dbus_utility.hpp"
210ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
223ccb3adbSEd Tanous #include "query.hpp"
233ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2450ebd4afSEd Tanous #include "str_utility.hpp"
253ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
263ccb3adbSEd Tanous #include "utils/json_utils.hpp"
273ccb3adbSEd Tanous #include "utils/query_param.hpp"
280ec8b83dSEd Tanous 
29e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
30ef4c65b7SEd Tanous #include <boost/url/format.hpp>
311e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3286d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
331214b7e7SGunnar Mills 
347a1dbc48SGeorge Liu #include <array>
351214b7e7SGunnar Mills #include <cmath>
36fe04d49cSNan Zhou #include <iterator>
37283860f5SEd Tanous #include <limits>
38fe04d49cSNan Zhou #include <map>
393544d2a7SEd Tanous #include <ranges>
40fe04d49cSNan Zhou #include <set>
41*18f8f608SEd Tanous #include <string>
427a1dbc48SGeorge Liu #include <string_view>
43b5a76932SEd Tanous #include <utility>
44abf2add6SEd Tanous #include <variant>
4508777fb0SLewanczyk, Dawid 
461abe55efSEd Tanous namespace redfish
471abe55efSEd Tanous {
4808777fb0SLewanczyk, Dawid 
49a0ec28b6SAdrian Ambrożewicz namespace sensors
50a0ec28b6SAdrian Ambrożewicz {
51a0ec28b6SAdrian Ambrożewicz namespace node
52a0ec28b6SAdrian Ambrożewicz {
53a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
54a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
55a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
56a0ec28b6SAdrian Ambrożewicz } // namespace node
57a0ec28b6SAdrian Ambrożewicz 
5802da7c5aSEd Tanous // clang-format off
59a0ec28b6SAdrian Ambrożewicz namespace dbus
60a0ec28b6SAdrian Ambrożewicz {
61cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6202da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6402da7c5aSEd Tanous });
65c2bf7f99SWludzik, Jozef 
66cf9e417dSEd Tanous constexpr auto sensorPaths = std::to_array<std::string_view>({
6702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power",
68a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/current",
697088690cSBasheer Ahmed Muddebihal     "/xyz/openbmc_project/sensors/airflow",
705deabed9SGunnar Mills     "/xyz/openbmc_project/sensors/humidity",
71e8204933SGeorge Liu #ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
72e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/voltage",
73e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_tach",
74e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/temperature",
75e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/fan_pwm",
76e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/altitude",
77e8204933SGeorge Liu     "/xyz/openbmc_project/sensors/energy",
78e8204933SGeorge Liu #endif
7902da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/utilization"
8002da7c5aSEd Tanous });
8102da7c5aSEd Tanous 
82cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
8302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
84a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
8502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
8602da7c5aSEd Tanous });
8702da7c5aSEd Tanous 
88c2bf7f99SWludzik, Jozef } // namespace dbus
8902da7c5aSEd Tanous // clang-format on
9002da7c5aSEd Tanous 
91cf9e417dSEd Tanous using sensorPair =
92cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
9302da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
94cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
95cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
96cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
97c2bf7f99SWludzik, Jozef 
980ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
99c2bf7f99SWludzik, Jozef {
100c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
101c2bf7f99SWludzik, Jozef     {
1020ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
103c2bf7f99SWludzik, Jozef     }
104c2bf7f99SWludzik, Jozef     if (sensorType == "power")
105c2bf7f99SWludzik, Jozef     {
1060ec8b83dSEd Tanous         return sensor::ReadingType::Power;
107c2bf7f99SWludzik, Jozef     }
108c2bf7f99SWludzik, Jozef     if (sensorType == "current")
109c2bf7f99SWludzik, Jozef     {
1100ec8b83dSEd Tanous         return sensor::ReadingType::Current;
111c2bf7f99SWludzik, Jozef     }
112c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
113c2bf7f99SWludzik, Jozef     {
1140ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
115c2bf7f99SWludzik, Jozef     }
116c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
117c2bf7f99SWludzik, Jozef     {
1180ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
119c2bf7f99SWludzik, Jozef     }
120c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
121c2bf7f99SWludzik, Jozef     {
1220ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
123c2bf7f99SWludzik, Jozef     }
1245deabed9SGunnar Mills     if (sensorType == "humidity")
1255deabed9SGunnar Mills     {
1260ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1275deabed9SGunnar Mills     }
128c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
129c2bf7f99SWludzik, Jozef     {
1300ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
131c2bf7f99SWludzik, Jozef     }
132c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
133c2bf7f99SWludzik, Jozef     {
1340ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
135c2bf7f99SWludzik, Jozef     }
136c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
137c2bf7f99SWludzik, Jozef     {
1380ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
139c2bf7f99SWludzik, Jozef     }
1400ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
141c2bf7f99SWludzik, Jozef }
142c2bf7f99SWludzik, Jozef 
1431d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
144c2bf7f99SWludzik, Jozef {
145c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
146c2bf7f99SWludzik, Jozef     {
147c2bf7f99SWludzik, Jozef         return "V";
148c2bf7f99SWludzik, Jozef     }
149c2bf7f99SWludzik, Jozef     if (sensorType == "power")
150c2bf7f99SWludzik, Jozef     {
151c2bf7f99SWludzik, Jozef         return "W";
152c2bf7f99SWludzik, Jozef     }
153c2bf7f99SWludzik, Jozef     if (sensorType == "current")
154c2bf7f99SWludzik, Jozef     {
155c2bf7f99SWludzik, Jozef         return "A";
156c2bf7f99SWludzik, Jozef     }
157c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
158c2bf7f99SWludzik, Jozef     {
159c2bf7f99SWludzik, Jozef         return "RPM";
160c2bf7f99SWludzik, Jozef     }
161c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
162c2bf7f99SWludzik, Jozef     {
163c2bf7f99SWludzik, Jozef         return "Cel";
164c2bf7f99SWludzik, Jozef     }
1655deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1665deabed9SGunnar Mills         sensorType == "humidity")
167c2bf7f99SWludzik, Jozef     {
168c2bf7f99SWludzik, Jozef         return "%";
169c2bf7f99SWludzik, Jozef     }
170c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
171c2bf7f99SWludzik, Jozef     {
172c2bf7f99SWludzik, Jozef         return "m";
173c2bf7f99SWludzik, Jozef     }
174c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
175c2bf7f99SWludzik, Jozef     {
176c2bf7f99SWludzik, Jozef         return "cft_i/min";
177c2bf7f99SWludzik, Jozef     }
178c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
179c2bf7f99SWludzik, Jozef     {
180c2bf7f99SWludzik, Jozef         return "J";
181c2bf7f99SWludzik, Jozef     }
182c2bf7f99SWludzik, Jozef     return "";
183a0ec28b6SAdrian Ambrożewicz }
184a0ec28b6SAdrian Ambrożewicz } // namespace sensors
185a0ec28b6SAdrian Ambrożewicz 
18608777fb0SLewanczyk, Dawid /**
187588c3f0dSKowalski, Kamil  * SensorsAsyncResp
18808777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
18908777fb0SLewanczyk, Dawid  */
1901abe55efSEd Tanous class SensorsAsyncResp
1911abe55efSEd Tanous {
19208777fb0SLewanczyk, Dawid   public:
193a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
194a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
195fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
196a0ec28b6SAdrian Ambrożewicz 
197a0ec28b6SAdrian Ambrożewicz     struct SensorData
198a0ec28b6SAdrian Ambrożewicz     {
199a0ec28b6SAdrian Ambrożewicz         const std::string name;
200a0ec28b6SAdrian Ambrożewicz         std::string uri;
201a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
202a0ec28b6SAdrian Ambrożewicz     };
203a0ec28b6SAdrian Ambrożewicz 
2048a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2058d1b46d7Szhanghch05                      const std::string& chassisIdIn,
206cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
20702da7c5aSEd Tanous                      std::string_view subNode) :
2088a592810SEd Tanous         asyncResp(asyncRespIn),
209928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
210928fefb9SNan Zhou         efficientExpand(false)
2111214b7e7SGunnar Mills     {}
21208777fb0SLewanczyk, Dawid 
213a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2148a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2158d1b46d7Szhanghch05                      const std::string& chassisIdIn,
216cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21702da7c5aSEd Tanous                      std::string_view subNode,
218a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2198a592810SEd Tanous         asyncResp(asyncRespIn),
220928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
221928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
222a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
223a0ec28b6SAdrian Ambrożewicz     {}
224a0ec28b6SAdrian Ambrożewicz 
225928fefb9SNan Zhou     // sensor collections expand
2268a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
227928fefb9SNan Zhou                      const std::string& chassisIdIn,
228cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2298a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2308a592810SEd Tanous         asyncResp(asyncRespIn),
231928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2328a592810SEd Tanous         efficientExpand(efficientExpandIn)
233928fefb9SNan Zhou     {}
234928fefb9SNan Zhou 
2351abe55efSEd Tanous     ~SensorsAsyncResp()
2361abe55efSEd Tanous     {
2378d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2388d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2391abe55efSEd Tanous         {
2401abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2411abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2421abe55efSEd Tanous             // proper code
2438d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
24408777fb0SLewanczyk, Dawid         }
245a0ec28b6SAdrian Ambrożewicz 
246a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
247a0ec28b6SAdrian Ambrożewicz         {
248fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2498d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
250a0ec28b6SAdrian Ambrożewicz             {
251a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
252a0ec28b6SAdrian Ambrożewicz                 {
253c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
254a0ec28b6SAdrian Ambrożewicz                 }
255a0ec28b6SAdrian Ambrożewicz             }
2568d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
257a0ec28b6SAdrian Ambrożewicz         }
25808777fb0SLewanczyk, Dawid     }
259588c3f0dSKowalski, Kamil 
260ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
261ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
262ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
263ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
264ecd6a3a2SEd Tanous 
265a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
266c1d019a6SEd Tanous                      const std::string& dbusPath)
267a0ec28b6SAdrian Ambrożewicz     {
268a0ec28b6SAdrian Ambrożewicz         if (metadata)
269a0ec28b6SAdrian Ambrożewicz         {
270c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
271c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
272a0ec28b6SAdrian Ambrożewicz         }
273a0ec28b6SAdrian Ambrożewicz     }
274a0ec28b6SAdrian Ambrożewicz 
275a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
276a0ec28b6SAdrian Ambrożewicz     {
277a0ec28b6SAdrian Ambrożewicz         if (metadata)
278a0ec28b6SAdrian Ambrożewicz         {
279a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
280a0ec28b6SAdrian Ambrożewicz             {
281a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
282a0ec28b6SAdrian Ambrożewicz                 {
283a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
284a0ec28b6SAdrian Ambrożewicz                 }
285a0ec28b6SAdrian Ambrożewicz             }
286a0ec28b6SAdrian Ambrożewicz         }
287a0ec28b6SAdrian Ambrożewicz     }
288a0ec28b6SAdrian Ambrożewicz 
2898d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
290a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
291cf9e417dSEd Tanous     const std::span<const std::string_view> types;
292a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
293928fefb9SNan Zhou     const bool efficientExpand;
294a0ec28b6SAdrian Ambrożewicz 
295a0ec28b6SAdrian Ambrożewicz   private:
296a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
297a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
29808777fb0SLewanczyk, Dawid };
29908777fb0SLewanczyk, Dawid 
30008777fb0SLewanczyk, Dawid /**
301d500549bSAnthony Wilson  * Possible states for physical inventory leds
302d500549bSAnthony Wilson  */
303d500549bSAnthony Wilson enum class LedState
304d500549bSAnthony Wilson {
305d500549bSAnthony Wilson     OFF,
306d500549bSAnthony Wilson     ON,
307d500549bSAnthony Wilson     BLINK,
308d500549bSAnthony Wilson     UNKNOWN
309d500549bSAnthony Wilson };
310d500549bSAnthony Wilson 
311d500549bSAnthony Wilson /**
312adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
313adc4f0dbSShawn McCarney  */
314adc4f0dbSShawn McCarney class InventoryItem
315adc4f0dbSShawn McCarney {
316adc4f0dbSShawn McCarney   public:
3174e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
318adc4f0dbSShawn McCarney     {
319adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
32028aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
32128aa8de5SGeorge Liu         name = path.filename();
32228aa8de5SGeorge Liu         if (name.empty())
323adc4f0dbSShawn McCarney         {
32462598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
325adc4f0dbSShawn McCarney         }
326adc4f0dbSShawn McCarney     }
327adc4f0dbSShawn McCarney 
328adc4f0dbSShawn McCarney     std::string objectPath;
329adc4f0dbSShawn McCarney     std::string name;
330e05aec50SEd Tanous     bool isPresent = true;
331e05aec50SEd Tanous     bool isFunctional = true;
332e05aec50SEd Tanous     bool isPowerSupply = false;
333e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
334adc4f0dbSShawn McCarney     std::string manufacturer;
335adc4f0dbSShawn McCarney     std::string model;
336adc4f0dbSShawn McCarney     std::string partNumber;
337adc4f0dbSShawn McCarney     std::string serialNumber;
338adc4f0dbSShawn McCarney     std::set<std::string> sensors;
339d500549bSAnthony Wilson     std::string ledObjectPath;
340e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
341adc4f0dbSShawn McCarney };
342adc4f0dbSShawn McCarney 
343adc4f0dbSShawn McCarney /**
344413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
345588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
34608777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
34708777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
34808777fb0SLewanczyk, Dawid  */
34908777fb0SLewanczyk, Dawid template <typename Callback>
350413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
35181ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
352fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3531abe55efSEd Tanous     Callback&& callback)
3541abe55efSEd Tanous {
35562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
35603b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
357e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
35808777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
35908777fb0SLewanczyk, Dawid 
360e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
361e99073f5SGeorge Liu     dbus::utility::getSubTree(
362e99073f5SGeorge Liu         path, 2, interfaces,
363002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
364e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
365002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
366e99073f5SGeorge Liu         // Response handler for parsing objects subtree
36762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3681abe55efSEd Tanous         if (ec)
3691abe55efSEd Tanous         {
3708d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
37162598e31SEd Tanous             BMCWEB_LOG_ERROR(
37262598e31SEd Tanous                 "getObjectsWithConnection resp_handler: Dbus error {}", ec);
37308777fb0SLewanczyk, Dawid             return;
37408777fb0SLewanczyk, Dawid         }
37508777fb0SLewanczyk, Dawid 
37662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
37708777fb0SLewanczyk, Dawid 
37808777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
37908777fb0SLewanczyk, Dawid         // found in the chassis
380fe04d49cSNan Zhou         std::set<std::string> connections;
381413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
38208777fb0SLewanczyk, Dawid 
38362598e31SEd Tanous         BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
38449c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3851abe55efSEd Tanous         {
38662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
38708777fb0SLewanczyk, Dawid         }
38808777fb0SLewanczyk, Dawid 
38908777fb0SLewanczyk, Dawid         for (const std::pair<
39008777fb0SLewanczyk, Dawid                  std::string,
39108777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
3921abe55efSEd Tanous                  object : subtree)
3931abe55efSEd Tanous         {
39449c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
3951abe55efSEd Tanous             {
39649c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
3971abe55efSEd Tanous                          objData : object.second)
3981abe55efSEd Tanous                 {
39962598e31SEd Tanous                     BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
40008777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
401de629b6eSShawn McCarney                     objectsWithConnection.insert(
402de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
40308777fb0SLewanczyk, Dawid                 }
40408777fb0SLewanczyk, Dawid             }
40508777fb0SLewanczyk, Dawid         }
40662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
407413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
40862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
409e99073f5SGeorge Liu     });
41062598e31SEd Tanous     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,
443cf9e417dSEd Tanous     std::span<const 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,
515cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
516cf9e417dSEd Tanous                 Callback&& callback)
5171abe55efSEd Tanous {
51862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5197a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
52049c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
521adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5227a1dbc48SGeorge Liu 
5237a1dbc48SGeorge Liu     // Get the Chassis Collection
5247a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5257a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5267f1cc26dSEd Tanous         [callback{std::forward<Callback>(callback)}, asyncResp,
5277f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5287f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5297a1dbc48SGeorge Liu             const boost::system::error_code& ec,
530002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
53162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5321abe55efSEd Tanous         if (ec)
5331abe55efSEd Tanous         {
53462598e31SEd Tanous             BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5357f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
53608777fb0SLewanczyk, Dawid             return;
53708777fb0SLewanczyk, Dawid         }
53849c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
53949c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5401abe55efSEd Tanous         {
54128aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
542f8fe53e7SEd Tanous             std::string chassisName = path.filename();
54328aa8de5SGeorge Liu             if (chassisName.empty())
5441abe55efSEd Tanous             {
54562598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
546daf36e2eSEd Tanous                 continue;
547daf36e2eSEd Tanous             }
5487f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5491abe55efSEd Tanous             {
55049c53ac9SJohnathan Mantey                 chassisPath = &chassis;
55149c53ac9SJohnathan Mantey                 break;
552daf36e2eSEd Tanous             }
55349c53ac9SJohnathan Mantey         }
55449c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5551abe55efSEd Tanous         {
5567f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
55749c53ac9SJohnathan Mantey             return;
5581abe55efSEd Tanous         }
5597f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
56008777fb0SLewanczyk, Dawid 
561ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
562ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
56395a3ecadSAnthony Wilson 
5648fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5658fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5666c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5676c3e9451SGeorge Liu             sensorPath,
5687f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
569f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
5708b24275dSEd Tanous                 const boost::system::error_code& ec2,
5716c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
5728b24275dSEd Tanous             if (ec2)
57349c53ac9SJohnathan Mantey             {
5748b24275dSEd Tanous                 if (ec2.value() != EBADR)
57549c53ac9SJohnathan Mantey                 {
5767f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
57749c53ac9SJohnathan Mantey                     return;
57849c53ac9SJohnathan Mantey                 }
57949c53ac9SJohnathan Mantey             }
580fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
581fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5827f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5837f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
58462598e31SEd Tanous             BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
58549c53ac9SJohnathan Mantey             callback(culledSensorList);
5861e1e598dSJonathan Doman         });
5877a1dbc48SGeorge Liu     });
58862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
58908777fb0SLewanczyk, Dawid }
59008777fb0SLewanczyk, Dawid 
59108777fb0SLewanczyk, Dawid /**
592adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
593adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
594adc4f0dbSShawn McCarney  * @return State value for inventory item.
59534dd179eSJames Feist  */
59623a21a1cSEd Tanous inline std::string getState(const InventoryItem* inventoryItem)
597adc4f0dbSShawn McCarney {
598adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
599adc4f0dbSShawn McCarney     {
600adc4f0dbSShawn McCarney         return "Absent";
601adc4f0dbSShawn McCarney     }
60234dd179eSJames Feist 
603adc4f0dbSShawn McCarney     return "Enabled";
604adc4f0dbSShawn McCarney }
605adc4f0dbSShawn McCarney 
606adc4f0dbSShawn McCarney /**
607adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
608adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6091d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
610adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
611adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
612adc4f0dbSShawn McCarney  * @return Health value for sensor.
613adc4f0dbSShawn McCarney  */
6141d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6151d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
616adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
61734dd179eSJames Feist {
618adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
619adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
620adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
621adc4f0dbSShawn McCarney     std::string currentHealth;
622adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
623adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
624adc4f0dbSShawn McCarney     {
625adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
626adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
627adc4f0dbSShawn McCarney         {
628adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
629adc4f0dbSShawn McCarney             if (health != nullptr)
630adc4f0dbSShawn McCarney             {
631adc4f0dbSShawn McCarney                 currentHealth = *health;
632adc4f0dbSShawn McCarney             }
633adc4f0dbSShawn McCarney         }
634adc4f0dbSShawn McCarney     }
635adc4f0dbSShawn McCarney 
636adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
637adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
638adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
639adc4f0dbSShawn McCarney     {
640adc4f0dbSShawn McCarney         return "Critical";
641adc4f0dbSShawn McCarney     }
642adc4f0dbSShawn McCarney 
643c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
644c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
645c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
646c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
647711ac7a9SEd Tanous 
648c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
649c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
650c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
651c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
652c1343bf6SKrzysztof Grobelny         warningAlarmLow);
653c1343bf6SKrzysztof Grobelny 
654c1343bf6SKrzysztof Grobelny     if (success)
65534dd179eSJames Feist     {
656c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
657c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
658c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
65934dd179eSJames Feist         {
66034dd179eSJames Feist             return "Critical";
66134dd179eSJames Feist         }
66234dd179eSJames Feist     }
66334dd179eSJames Feist 
664adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
665adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
666adc4f0dbSShawn McCarney     {
667adc4f0dbSShawn McCarney         return "Critical";
668adc4f0dbSShawn McCarney     }
669adc4f0dbSShawn McCarney 
670adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
671adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
672adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
673adc4f0dbSShawn McCarney     {
674adc4f0dbSShawn McCarney         return "Warning";
675adc4f0dbSShawn McCarney     }
676adc4f0dbSShawn McCarney 
677c1343bf6SKrzysztof Grobelny     if (success)
678c1343bf6SKrzysztof Grobelny     {
679adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
680c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
681c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
68234dd179eSJames Feist         {
683ebe4d91eSEd Tanous             return "Warning";
68434dd179eSJames Feist         }
68534dd179eSJames Feist     }
686adc4f0dbSShawn McCarney 
68734dd179eSJames Feist     return "OK";
68834dd179eSJames Feist }
68934dd179eSJames Feist 
69023a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
691d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
692d500549bSAnthony Wilson {
693d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
694d500549bSAnthony Wilson     {
695d500549bSAnthony Wilson         switch (inventoryItem->ledState)
696d500549bSAnthony Wilson         {
697d500549bSAnthony Wilson             case LedState::OFF:
698d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
699d500549bSAnthony Wilson                 break;
700d500549bSAnthony Wilson             case LedState::ON:
701d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
702d500549bSAnthony Wilson                 break;
703d500549bSAnthony Wilson             case LedState::BLINK:
704d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
705d500549bSAnthony Wilson                 break;
70623a21a1cSEd Tanous             case LedState::UNKNOWN:
707d500549bSAnthony Wilson                 break;
708d500549bSAnthony Wilson         }
709d500549bSAnthony Wilson     }
710d500549bSAnthony Wilson }
711d500549bSAnthony Wilson 
71234dd179eSJames Feist /**
71308777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
71408777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
715274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
71608777fb0SLewanczyk, Dawid  * build
7178ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
7181d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7191d7c0054SEd Tanous  * from.
7201d7c0054SEd Tanous  * @param sensorJson  The json object to fill
721adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
722adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
72308777fb0SLewanczyk, Dawid  */
7241d7c0054SEd Tanous inline void objectPropertiesToJson(
7251d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7261d7c0054SEd Tanous     std::string_view chassisSubNode,
7271d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
72881ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7291abe55efSEd Tanous {
7301d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
731adc4f0dbSShawn McCarney     {
732c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
7333544d2a7SEd Tanous         auto remove = std::ranges::remove(subNodeEscaped, '_');
7343544d2a7SEd Tanous         subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
735c1d019a6SEd Tanous 
736c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
737c1d019a6SEd Tanous         // including power sensors.
738c1d019a6SEd Tanous         subNodeEscaped += '_';
739c1d019a6SEd Tanous         subNodeEscaped += sensorName;
740c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
741c1d019a6SEd Tanous 
7421d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7431d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7441d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
74595a3ecadSAnthony Wilson     }
74695a3ecadSAnthony Wilson     else if (sensorType != "power")
74795a3ecadSAnthony Wilson     {
74895a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
74995a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
75095a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7511d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7521d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7531d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
754adc4f0dbSShawn McCarney     }
755e742b6ccSEd Tanous 
75681ce609eSEd Tanous     sensorJson["Status"]["State"] = getState(inventoryItem);
75789492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
75889492a15SPatrick Williams                                                inventoryItem);
75908777fb0SLewanczyk, Dawid 
76008777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
76108777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
76208777fb0SLewanczyk, Dawid     // that require integers, not floats.
76308777fb0SLewanczyk, Dawid     bool forceToInt = false;
76408777fb0SLewanczyk, Dawid 
7653929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7661d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
76795a3ecadSAnthony Wilson     {
7682a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
769c2bf7f99SWludzik, Jozef 
7700ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
7710ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
77295a3ecadSAnthony Wilson         {
77362598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
77462598e31SEd Tanous                              sensorType);
77595a3ecadSAnthony Wilson         }
776c2bf7f99SWludzik, Jozef         else
77795a3ecadSAnthony Wilson         {
778c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
77995a3ecadSAnthony Wilson         }
780c2bf7f99SWludzik, Jozef 
7811d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
782c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
783f8ede15eSAdrian Ambrożewicz         {
78462598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
78562598e31SEd Tanous                              sensorType);
786c2bf7f99SWludzik, Jozef         }
787c2bf7f99SWludzik, Jozef         else
788c2bf7f99SWludzik, Jozef         {
789c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
790f8ede15eSAdrian Ambrożewicz         }
79195a3ecadSAnthony Wilson     }
79295a3ecadSAnthony Wilson     else if (sensorType == "temperature")
7931abe55efSEd Tanous     {
7943929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
79581ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
79608777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
79708777fb0SLewanczyk, Dawid         // implementation seems to implement fan
7981abe55efSEd Tanous     }
7991abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8001abe55efSEd Tanous     {
8013929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
80281ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
80381ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
80481ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
80508777fb0SLewanczyk, Dawid         forceToInt = true;
8061abe55efSEd Tanous     }
8076f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8086f6d0d32SEd Tanous     {
8093929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
81081ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
81181ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
81281ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8136f6d0d32SEd Tanous         forceToInt = true;
8146f6d0d32SEd Tanous     }
8151abe55efSEd Tanous     else if (sensorType == "voltage")
8161abe55efSEd Tanous     {
8173929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
81881ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8191abe55efSEd Tanous     }
8202474adfaSEd Tanous     else if (sensorType == "power")
8212474adfaSEd Tanous     {
822*18f8f608SEd Tanous         std::string lower;
823*18f8f608SEd Tanous         std::ranges::transform(sensorName, std::back_inserter(lower),
824*18f8f608SEd Tanous                                bmcweb::asciiToLower);
825*18f8f608SEd Tanous         if (lower == "total_power")
826028f7ebcSEddie James         {
82781ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8287ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8297ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
83081ce609eSEd Tanous             sensorJson["MemberId"] = "0";
83181ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8323929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
833028f7ebcSEddie James         }
834*18f8f608SEd Tanous         else if (lower.find("input") != std::string::npos)
83549c53ac9SJohnathan Mantey         {
8363929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
83749c53ac9SJohnathan Mantey         }
83849c53ac9SJohnathan Mantey         else
83949c53ac9SJohnathan Mantey         {
8403929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
84149c53ac9SJohnathan Mantey         }
8422474adfaSEd Tanous     }
8431abe55efSEd Tanous     else
8441abe55efSEd Tanous     {
84562598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
84608777fb0SLewanczyk, Dawid         return;
84708777fb0SLewanczyk, Dawid     }
84808777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8493929aca1SAnthony Wilson     std::vector<
8503929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8513929aca1SAnthony Wilson         properties;
85208777fb0SLewanczyk, Dawid     properties.reserve(7);
85308777fb0SLewanczyk, Dawid 
85408777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
855de629b6eSShawn McCarney 
8561d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8573929aca1SAnthony Wilson     {
8583929aca1SAnthony Wilson         properties.emplace_back(
8593929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8603929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8613929aca1SAnthony Wilson         properties.emplace_back(
8623929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8633929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8643929aca1SAnthony Wilson         properties.emplace_back(
8653929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8663929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
8673929aca1SAnthony Wilson         properties.emplace_back(
8683929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
8693929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
8703929aca1SAnthony Wilson     }
8713929aca1SAnthony Wilson     else if (sensorType != "power")
872de629b6eSShawn McCarney     {
87308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8743929aca1SAnthony Wilson                                 "WarningHigh",
8753929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
87608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
8773929aca1SAnthony Wilson                                 "WarningLow",
8783929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
87908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8803929aca1SAnthony Wilson                                 "CriticalHigh",
8813929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
88208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
8833929aca1SAnthony Wilson                                 "CriticalLow",
8843929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
885de629b6eSShawn McCarney     }
88608777fb0SLewanczyk, Dawid 
8872474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
8882474adfaSEd Tanous 
8891d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
89095a3ecadSAnthony Wilson     {
89195a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
8923929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
89395a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
8943929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
89551c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
89651c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
89795a3ecadSAnthony Wilson     }
89895a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8991abe55efSEd Tanous     {
90008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9013929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
90208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9033929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9041abe55efSEd Tanous     }
905adc4f0dbSShawn McCarney     else if (sensorType != "power")
9061abe55efSEd Tanous     {
90708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9083929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
90908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9103929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
91108777fb0SLewanczyk, Dawid     }
91208777fb0SLewanczyk, Dawid 
9133929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9143929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9151abe55efSEd Tanous     {
9161d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
917711ac7a9SEd Tanous         {
918711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
919711ac7a9SEd Tanous             {
920711ac7a9SEd Tanous                 continue;
921711ac7a9SEd Tanous             }
9223929aca1SAnthony Wilson 
9233929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9243929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9253929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9263929aca1SAnthony Wilson 
927abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
92840e4f380SEd Tanous             if (doubleValue == nullptr)
9291abe55efSEd Tanous             {
93062598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9316f6d0d32SEd Tanous                 continue;
93208777fb0SLewanczyk, Dawid             }
933283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
934283860f5SEd Tanous             {
935283860f5SEd Tanous                 if (valueName == "Value")
936283860f5SEd Tanous                 {
937283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
938283860f5SEd Tanous                     // them to null in the json response.
939283860f5SEd Tanous                     sensorJson[key] = nullptr;
940283860f5SEd Tanous                     continue;
941283860f5SEd Tanous                 }
94262598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
94362598e31SEd Tanous                                    valueName, *doubleValue);
944283860f5SEd Tanous                 continue;
945283860f5SEd Tanous             }
9466f6d0d32SEd Tanous             if (forceToInt)
9476f6d0d32SEd Tanous             {
94840e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9496f6d0d32SEd Tanous             }
9506f6d0d32SEd Tanous             else
9516f6d0d32SEd Tanous             {
95240e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
95308777fb0SLewanczyk, Dawid             }
95408777fb0SLewanczyk, Dawid         }
95508777fb0SLewanczyk, Dawid     }
95608777fb0SLewanczyk, Dawid }
95708777fb0SLewanczyk, Dawid 
9581d7c0054SEd Tanous /**
9591d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9601d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9611d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9621d7c0054SEd Tanous  * build
9638ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
9641d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9651d7c0054SEd Tanous  * interfaces to be built from
9661d7c0054SEd Tanous  * @param sensorJson  The json object to fill
9671d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
9681d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
9691d7c0054SEd Tanous  */
9701d7c0054SEd Tanous inline void objectInterfacesToJson(
9711d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
9721d7c0054SEd Tanous     const std::string& chassisSubNode,
97380f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
9741d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
9751d7c0054SEd Tanous {
9761d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
9771d7c0054SEd Tanous     {
9781d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
9791d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
9801d7c0054SEd Tanous     }
98162598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
9821d7c0054SEd Tanous }
9831d7c0054SEd Tanous 
984b5a76932SEd Tanous inline void populateFanRedundancy(
985b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
9868bd25ccdSJames Feist {
987e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
988e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
989e99073f5SGeorge Liu     dbus::utility::getSubTree(
990e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
991b9d36b47SEd Tanous         [sensorsAsyncResp](
992e99073f5SGeorge Liu             const boost::system::error_code& ec,
993b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
9948bd25ccdSJames Feist         if (ec)
9958bd25ccdSJames Feist         {
9968bd25ccdSJames Feist             return; // don't have to have this interface
9978bd25ccdSJames Feist         }
9986c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
999e278c18fSEd Tanous                  pathPair : resp)
10008bd25ccdSJames Feist         {
1001e278c18fSEd Tanous             const std::string& path = pathPair.first;
10026c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
10038bd25ccdSJames Feist             if (objDict.empty())
10048bd25ccdSJames Feist             {
10058bd25ccdSJames Feist                 continue; // this should be impossible
10068bd25ccdSJames Feist             }
10078bd25ccdSJames Feist 
10088bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10096c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
10106c3e9451SGeorge Liu                 path + "/chassis",
10116c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
10128b24275dSEd Tanous                     const boost::system::error_code& ec2,
10136c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
10148b24275dSEd Tanous                 if (ec2)
10158bd25ccdSJames Feist                 {
10168bd25ccdSJames Feist                     return; // if they don't have an association we
10178bd25ccdSJames Feist                             // can't tell what chassis is
10188bd25ccdSJames Feist                 }
10193544d2a7SEd Tanous                 auto found = std::ranges::find_if(
10203544d2a7SEd Tanous                     endpoints, [sensorsAsyncResp](const std::string& entry) {
1021002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10228bd25ccdSJames Feist                            std::string::npos;
10238bd25ccdSJames Feist                 });
10248bd25ccdSJames Feist 
10251e1e598dSJonathan Doman                 if (found == endpoints.end())
10268bd25ccdSJames Feist                 {
10278bd25ccdSJames Feist                     return;
10288bd25ccdSJames Feist                 }
102986d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
103086d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
103186d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10328bd25ccdSJames Feist                     [path, sensorsAsyncResp](
10338b24275dSEd Tanous                         const boost::system::error_code& ec3,
103486d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
10358b24275dSEd Tanous                     if (ec3)
10368bd25ccdSJames Feist                     {
10378bd25ccdSJames Feist                         return; // don't have to have this
10388bd25ccdSJames Feist                                 // interface
10398bd25ccdSJames Feist                     }
10408bd25ccdSJames Feist 
104186d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
104286d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
104386d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
104486d89ed7SKrzysztof Grobelny 
104586d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
104686d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
104786d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
104886d89ed7SKrzysztof Grobelny                         collection, "Status", status);
104986d89ed7SKrzysztof Grobelny 
105086d89ed7SKrzysztof Grobelny                     if (!success)
105186d89ed7SKrzysztof Grobelny                     {
105286d89ed7SKrzysztof Grobelny                         messages::internalError(
105386d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
105486d89ed7SKrzysztof Grobelny                         return;
105586d89ed7SKrzysztof Grobelny                     }
105686d89ed7SKrzysztof Grobelny 
105786d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
105886d89ed7SKrzysztof Grobelny                         status == nullptr)
10598bd25ccdSJames Feist                     {
106062598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid redundancy interface");
10618bd25ccdSJames Feist                         messages::internalError(
10628d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10638bd25ccdSJames Feist                         return;
10648bd25ccdSJames Feist                     }
10658bd25ccdSJames Feist 
1066002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
106728aa8de5SGeorge Liu                     std::string name = objectPath.filename();
106828aa8de5SGeorge Liu                     if (name.empty())
10698bd25ccdSJames Feist                     {
10708bd25ccdSJames Feist                         // this should be impossible
10718bd25ccdSJames Feist                         messages::internalError(
10728d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10738bd25ccdSJames Feist                         return;
10748bd25ccdSJames Feist                     }
1075*18f8f608SEd Tanous                     std::ranges::replace(name, '_', ' ');
10768bd25ccdSJames Feist 
10778bd25ccdSJames Feist                     std::string health;
10788bd25ccdSJames Feist 
107911ba3979SEd Tanous                     if (status->ends_with("Full"))
10808bd25ccdSJames Feist                     {
10818bd25ccdSJames Feist                         health = "OK";
10828bd25ccdSJames Feist                     }
108311ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
10848bd25ccdSJames Feist                     {
10858bd25ccdSJames Feist                         health = "Warning";
10868bd25ccdSJames Feist                     }
10878bd25ccdSJames Feist                     else
10888bd25ccdSJames Feist                     {
10898bd25ccdSJames Feist                         health = "Critical";
10908bd25ccdSJames Feist                     }
10911476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
10928bd25ccdSJames Feist                     const auto& fanRedfish =
1093002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
10948bd25ccdSJames Feist                     for (const std::string& item : *collection)
10958bd25ccdSJames Feist                     {
10968a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
10978a592810SEd Tanous                         std::string itemName = itemPath.filename();
109828aa8de5SGeorge Liu                         if (itemName.empty())
109928aa8de5SGeorge Liu                         {
110028aa8de5SGeorge Liu                             continue;
110128aa8de5SGeorge Liu                         }
11028bd25ccdSJames Feist                         /*
11038bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11048bd25ccdSJames Feist                         std::replace(itemName.begin(),
11058bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
11063544d2a7SEd Tanous                         auto schemaItem = std::ranges::find_if(
11073544d2a7SEd Tanous                             fanRedfish, [itemName](const nlohmann::json& fan) {
11083e35c761SGeorge Liu                             return fan["Name"] == itemName;
11098bd25ccdSJames Feist                         });
11108bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11118bd25ccdSJames Feist                         {
11128a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11138a592810SEd Tanous                             collectionId["@odata.id"] =
11141476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11151476687dSEd Tanous                             redfishCollection.emplace_back(
11168a592810SEd Tanous                                 std::move(collectionId));
11178bd25ccdSJames Feist                         }
11188bd25ccdSJames Feist                         else
11198bd25ccdSJames Feist                         {
112062598e31SEd Tanous                             BMCWEB_LOG_ERROR("failed to find fan in schema");
11218bd25ccdSJames Feist                             messages::internalError(
11228d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11238bd25ccdSJames Feist                             return;
11248bd25ccdSJames Feist                         }
11258bd25ccdSJames Feist                     }
11268bd25ccdSJames Feist 
112789492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
112826f6976fSEd Tanous                                               ? 0
112989492a15SPatrick Williams                                               : collection->size() -
113089492a15SPatrick Williams                                                     *allowedFailures;
1131002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11328bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11331476687dSEd Tanous 
11341476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1135ef4c65b7SEd Tanous                     boost::urls::url url =
1136ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1137ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1138eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1139eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1140eddfc437SWilly Tu                                          .to_string());
1141eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1142002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11431476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11441476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11451476687dSEd Tanous                     redundancy["Name"] = name;
11461476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11471476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11481476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11491476687dSEd Tanous 
1150b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
115186d89ed7SKrzysztof Grobelny                 });
11521e1e598dSJonathan Doman             });
11538bd25ccdSJames Feist         }
1154e99073f5SGeorge Liu     });
11558bd25ccdSJames Feist }
11568bd25ccdSJames Feist 
1157b5a76932SEd Tanous inline void
115881ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
115949c53ac9SJohnathan Mantey {
11608d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
116149c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
116281ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
116349c53ac9SJohnathan Mantey     {
116449c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
116549c53ac9SJohnathan Mantey     }
116649c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
116749c53ac9SJohnathan Mantey     {
116849c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
116949c53ac9SJohnathan Mantey         if (entry != response.end())
117049c53ac9SJohnathan Mantey         {
117149c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
117202cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
117349c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
117449c53ac9SJohnathan Mantey             });
117549c53ac9SJohnathan Mantey 
117649c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
117749c53ac9SJohnathan Mantey             size_t count = 0;
117849c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
117949c53ac9SJohnathan Mantey             {
118049c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
118149c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
118249c53ac9SJohnathan Mantey                 {
118349c53ac9SJohnathan Mantey                     continue;
118449c53ac9SJohnathan Mantey                 }
118549c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
118649c53ac9SJohnathan Mantey                 if (value != nullptr)
118749c53ac9SJohnathan Mantey                 {
1188eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
11893e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
119049c53ac9SJohnathan Mantey                     count++;
119181ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
119249c53ac9SJohnathan Mantey                 }
119349c53ac9SJohnathan Mantey             }
119449c53ac9SJohnathan Mantey         }
119549c53ac9SJohnathan Mantey     }
119649c53ac9SJohnathan Mantey }
119749c53ac9SJohnathan Mantey 
119808777fb0SLewanczyk, Dawid /**
1199adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1200adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1201adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1202adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12038fb49dd6SShawn McCarney  */
120423a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1205b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1206adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12078fb49dd6SShawn McCarney {
1208adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12098fb49dd6SShawn McCarney     {
1210adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12118fb49dd6SShawn McCarney         {
1212adc4f0dbSShawn McCarney             return &inventoryItem;
12138fb49dd6SShawn McCarney         }
12148fb49dd6SShawn McCarney     }
12158fb49dd6SShawn McCarney     return nullptr;
12168fb49dd6SShawn McCarney }
12178fb49dd6SShawn McCarney 
12188fb49dd6SShawn McCarney /**
1219adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1220adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1221adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1222adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12238fb49dd6SShawn McCarney  */
122423a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1225b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1226adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1227adc4f0dbSShawn McCarney {
1228adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1229adc4f0dbSShawn McCarney     {
1230db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1231adc4f0dbSShawn McCarney         {
1232adc4f0dbSShawn McCarney             return &inventoryItem;
1233adc4f0dbSShawn McCarney         }
1234adc4f0dbSShawn McCarney     }
1235adc4f0dbSShawn McCarney     return nullptr;
1236adc4f0dbSShawn McCarney }
1237adc4f0dbSShawn McCarney 
1238adc4f0dbSShawn McCarney /**
1239d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1240d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1241d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1242d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1243d500549bSAnthony Wilson  */
1244d500549bSAnthony Wilson inline InventoryItem*
1245d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1246d500549bSAnthony Wilson                             const std::string& ledObjPath)
1247d500549bSAnthony Wilson {
1248d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1249d500549bSAnthony Wilson     {
1250d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1251d500549bSAnthony Wilson         {
1252d500549bSAnthony Wilson             return &inventoryItem;
1253d500549bSAnthony Wilson         }
1254d500549bSAnthony Wilson     }
1255d500549bSAnthony Wilson     return nullptr;
1256d500549bSAnthony Wilson }
1257d500549bSAnthony Wilson 
1258d500549bSAnthony Wilson /**
1259adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1260adc4f0dbSShawn McCarney  *
1261adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1262adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1263adc4f0dbSShawn McCarney  * added to the vector.
1264adc4f0dbSShawn McCarney  *
1265adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1266adc4f0dbSShawn McCarney  * InventoryItem.
1267adc4f0dbSShawn McCarney  *
1268adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1269adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1270adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1271adc4f0dbSShawn McCarney  */
1272b5a76932SEd Tanous inline void addInventoryItem(
1273b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1274b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1275adc4f0dbSShawn McCarney {
1276adc4f0dbSShawn McCarney     // Look for inventory item in vector
127789492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
127889492a15SPatrick Williams                                                      invItemObjPath);
1279adc4f0dbSShawn McCarney 
1280adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1281adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1282adc4f0dbSShawn McCarney     {
1283adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1284adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1285adc4f0dbSShawn McCarney     }
1286adc4f0dbSShawn McCarney 
1287adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1288adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1289adc4f0dbSShawn McCarney }
1290adc4f0dbSShawn McCarney 
1291adc4f0dbSShawn McCarney /**
1292adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1293adc4f0dbSShawn McCarney  *
1294adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1295adc4f0dbSShawn McCarney  * specified InventoryItem.
1296adc4f0dbSShawn McCarney  *
1297adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1298adc4f0dbSShawn McCarney  * response.
1299adc4f0dbSShawn McCarney  *
1300adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1301adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1302adc4f0dbSShawn McCarney  * for the specified inventory item.
1303adc4f0dbSShawn McCarney  */
130423a21a1cSEd Tanous inline void storeInventoryItemData(
1305adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
130680f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13078fb49dd6SShawn McCarney {
1308adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1309711ac7a9SEd Tanous 
13109eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13118fb49dd6SShawn McCarney     {
1312711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13138fb49dd6SShawn McCarney         {
13149eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1315711ac7a9SEd Tanous             {
1316711ac7a9SEd Tanous                 if (name == "Present")
1317711ac7a9SEd Tanous                 {
1318711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1319adc4f0dbSShawn McCarney                     if (value != nullptr)
13208fb49dd6SShawn McCarney                     {
1321adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13228fb49dd6SShawn McCarney                     }
13238fb49dd6SShawn McCarney                 }
13248fb49dd6SShawn McCarney             }
1325711ac7a9SEd Tanous         }
1326adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1327711ac7a9SEd Tanous 
1328711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13298fb49dd6SShawn McCarney         {
1330adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13318fb49dd6SShawn McCarney         }
1332adc4f0dbSShawn McCarney 
1333adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1334711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1335adc4f0dbSShawn McCarney         {
13369eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1337711ac7a9SEd Tanous             {
1338711ac7a9SEd Tanous                 if (name == "Manufacturer")
1339adc4f0dbSShawn McCarney                 {
1340adc4f0dbSShawn McCarney                     const std::string* value =
1341711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1342adc4f0dbSShawn McCarney                     if (value != nullptr)
1343adc4f0dbSShawn McCarney                     {
1344adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1345adc4f0dbSShawn McCarney                     }
1346adc4f0dbSShawn McCarney                 }
1347711ac7a9SEd Tanous                 if (name == "Model")
1348adc4f0dbSShawn McCarney                 {
1349adc4f0dbSShawn McCarney                     const std::string* value =
1350711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1351adc4f0dbSShawn McCarney                     if (value != nullptr)
1352adc4f0dbSShawn McCarney                     {
1353adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1354adc4f0dbSShawn McCarney                     }
1355adc4f0dbSShawn McCarney                 }
1356711ac7a9SEd Tanous                 if (name == "SerialNumber")
1357adc4f0dbSShawn McCarney                 {
1358adc4f0dbSShawn McCarney                     const std::string* value =
1359711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1360adc4f0dbSShawn McCarney                     if (value != nullptr)
1361adc4f0dbSShawn McCarney                     {
1362adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1363adc4f0dbSShawn McCarney                     }
1364adc4f0dbSShawn McCarney                 }
1365711ac7a9SEd Tanous                 if (name == "PartNumber")
1366711ac7a9SEd Tanous                 {
1367711ac7a9SEd Tanous                     const std::string* value =
1368711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1369711ac7a9SEd Tanous                     if (value != nullptr)
1370711ac7a9SEd Tanous                     {
1371711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1372711ac7a9SEd Tanous                     }
1373711ac7a9SEd Tanous                 }
1374711ac7a9SEd Tanous             }
1375adc4f0dbSShawn McCarney         }
1376adc4f0dbSShawn McCarney 
1377711ac7a9SEd Tanous         if (interface ==
1378711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1379adc4f0dbSShawn McCarney         {
13809eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1381adc4f0dbSShawn McCarney             {
1382711ac7a9SEd Tanous                 if (name == "Functional")
1383711ac7a9SEd Tanous                 {
1384711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1385adc4f0dbSShawn McCarney                     if (value != nullptr)
1386adc4f0dbSShawn McCarney                     {
1387adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
13888fb49dd6SShawn McCarney                     }
13898fb49dd6SShawn McCarney                 }
13908fb49dd6SShawn McCarney             }
13918fb49dd6SShawn McCarney         }
1392711ac7a9SEd Tanous     }
1393711ac7a9SEd Tanous }
13948fb49dd6SShawn McCarney 
13958fb49dd6SShawn McCarney /**
1396adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
13978fb49dd6SShawn McCarney  *
1398adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1399adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1400adc4f0dbSShawn McCarney  * inventoryItems vector.
14018fb49dd6SShawn McCarney  *
1402adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1403adc4f0dbSShawn McCarney  * response.
1404adc4f0dbSShawn McCarney  *
1405adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1406adc4f0dbSShawn McCarney  * been obtained.
1407adc4f0dbSShawn McCarney  *
1408adc4f0dbSShawn McCarney  * The callback must have the following signature:
1409adc4f0dbSShawn McCarney  *   @code
1410d500549bSAnthony Wilson  *   callback(void)
1411adc4f0dbSShawn McCarney  *   @endcode
1412adc4f0dbSShawn McCarney  *
1413adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1414adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1415adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14168fb49dd6SShawn McCarney  *
14178fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1418adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1419adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14208fb49dd6SShawn McCarney  * implements ObjectManager.
1421adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1422adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1423adc4f0dbSShawn McCarney  * in recursive calls to this function.
14248fb49dd6SShawn McCarney  */
1425adc4f0dbSShawn McCarney template <typename Callback>
1426adc4f0dbSShawn McCarney static void getInventoryItemsData(
14278fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1428adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1429d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1430d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14318fb49dd6SShawn McCarney {
143262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14338fb49dd6SShawn McCarney 
1434adc4f0dbSShawn McCarney     // If no more connections left, call callback
1435adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14368fb49dd6SShawn McCarney     {
1437d500549bSAnthony Wilson         callback();
143862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1439adc4f0dbSShawn McCarney         return;
1440adc4f0dbSShawn McCarney     }
1441adc4f0dbSShawn McCarney 
1442adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1443fe04d49cSNan Zhou     auto it = invConnections->begin();
1444fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1445adc4f0dbSShawn McCarney     if (it != invConnections->end())
1446adc4f0dbSShawn McCarney     {
1447adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1448adc4f0dbSShawn McCarney 
14495eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14505eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14515eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14525eb468daSGeorge Liu             invConnection, path,
14535eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
14545eb468daSGeorge Liu              callback{std::forward<Callback>(callback)}, invConnectionsIndex](
14555e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
145602cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
145762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
14588fb49dd6SShawn McCarney             if (ec)
14598fb49dd6SShawn McCarney             {
146062598e31SEd Tanous                 BMCWEB_LOG_ERROR(
146162598e31SEd Tanous                     "getInventoryItemsData respHandler DBus error {}", ec);
14628d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14638fb49dd6SShawn McCarney                 return;
14648fb49dd6SShawn McCarney             }
14658fb49dd6SShawn McCarney 
14668fb49dd6SShawn McCarney             // Loop through returned object paths
14678fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
14688fb49dd6SShawn McCarney             {
14698fb49dd6SShawn McCarney                 const std::string& objPath =
14708fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
14718fb49dd6SShawn McCarney 
1472adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
147389492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
147489492a15SPatrick Williams                                                                  objPath);
1475adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
14768fb49dd6SShawn McCarney                 {
1477adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1478adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
14798fb49dd6SShawn McCarney                 }
14808fb49dd6SShawn McCarney             }
14818fb49dd6SShawn McCarney 
1482adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1483adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1484d0090733SEd Tanous                                   invConnections, std::move(callback),
1485d0090733SEd Tanous                                   invConnectionsIndex + 1);
1486adc4f0dbSShawn McCarney 
148762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
14885eb468daSGeorge Liu         });
14898fb49dd6SShawn McCarney     }
14908fb49dd6SShawn McCarney 
149162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
14928fb49dd6SShawn McCarney }
14938fb49dd6SShawn McCarney 
14948fb49dd6SShawn McCarney /**
1495adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
14968fb49dd6SShawn McCarney  *
1497adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1498adc4f0dbSShawn McCarney  * items that are associated with sensors.
14998fb49dd6SShawn McCarney  *
15008fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15018fb49dd6SShawn McCarney  * been obtained.
15028fb49dd6SShawn McCarney  *
15038fb49dd6SShawn McCarney  * The callback must have the following signature:
15048fb49dd6SShawn McCarney  *   @code
1505fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15068fb49dd6SShawn McCarney  *   @endcode
15078fb49dd6SShawn McCarney  *
15088fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1509adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15108fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15118fb49dd6SShawn McCarney  */
15128fb49dd6SShawn McCarney template <typename Callback>
15138fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1514b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1515b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15168fb49dd6SShawn McCarney     Callback&& callback)
15178fb49dd6SShawn McCarney {
151862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15198fb49dd6SShawn McCarney 
15208fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1521e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15228fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1523adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1524adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15258fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15268fb49dd6SShawn McCarney 
1527e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1528e99073f5SGeorge Liu     dbus::utility::getSubTree(
1529e99073f5SGeorge Liu         path, 0, interfaces,
1530002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1531002d39b4SEd Tanous          inventoryItems](
1532e99073f5SGeorge Liu             const boost::system::error_code& ec,
1533002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1534e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
153562598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15368fb49dd6SShawn McCarney         if (ec)
15378fb49dd6SShawn McCarney         {
15388d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
153962598e31SEd Tanous             BMCWEB_LOG_ERROR(
154062598e31SEd Tanous                 "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);
156962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1570e99073f5SGeorge Liu     });
157162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
15728fb49dd6SShawn McCarney }
15738fb49dd6SShawn McCarney 
15748fb49dd6SShawn McCarney /**
1575adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
15768fb49dd6SShawn McCarney  *
15778fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1578d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1579d500549bSAnthony Wilson  * their LEDs, if any.
15808fb49dd6SShawn McCarney  *
15818fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
15828fb49dd6SShawn McCarney  * has been obtained.
15838fb49dd6SShawn McCarney  *
15848fb49dd6SShawn McCarney  * The callback must have the following signature:
15858fb49dd6SShawn McCarney  *   @code
1586adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
15878fb49dd6SShawn McCarney  *   @endcode
15888fb49dd6SShawn McCarney  *
15898fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
15908fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
15918fb49dd6SShawn McCarney  * implements ObjectManager.
15928fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
15938fb49dd6SShawn McCarney  */
15948fb49dd6SShawn McCarney template <typename Callback>
1595adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1596b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1597fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
15988fb49dd6SShawn McCarney     Callback&& callback)
15998fb49dd6SShawn McCarney {
160062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16018fb49dd6SShawn McCarney 
16025eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16035eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16045eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16055eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
160602cad96eSEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
16075e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
160802cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
160962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16108fb49dd6SShawn McCarney         if (ec)
16118fb49dd6SShawn McCarney         {
161262598e31SEd Tanous             BMCWEB_LOG_ERROR(
161362598e31SEd Tanous                 "getInventoryItemAssociations respHandler DBus error {}", ec);
16148d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16158fb49dd6SShawn McCarney             return;
16168fb49dd6SShawn McCarney         }
16178fb49dd6SShawn McCarney 
1618adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1619adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1620adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1621adc4f0dbSShawn McCarney 
16228fb49dd6SShawn McCarney         // Loop through returned object paths
16238fb49dd6SShawn McCarney         std::string sensorAssocPath;
16248fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16258fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16268fb49dd6SShawn McCarney         {
16278fb49dd6SShawn McCarney             const std::string& objPath =
16288fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16298fb49dd6SShawn McCarney 
16308fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16318fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16328fb49dd6SShawn McCarney             {
16338fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16348fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16358fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16368fb49dd6SShawn McCarney                 {
16378fb49dd6SShawn McCarney                     // Get Association interface for object path
1638711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16398fb49dd6SShawn McCarney                     {
1640711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1641711ac7a9SEd Tanous                         {
1642711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1643711ac7a9SEd Tanous                             {
1644711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16458fb49dd6SShawn McCarney                                 {
16468fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16478fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1648711ac7a9SEd Tanous                                             &value);
1649711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1650711ac7a9SEd Tanous                                         !endpoints->empty())
16518fb49dd6SShawn McCarney                                     {
1652adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1653adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1654adc4f0dbSShawn McCarney                                             endpoints->front();
1655711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1656711ac7a9SEd Tanous                                                          invItemPath,
1657adc4f0dbSShawn McCarney                                                          sensorName);
16588fb49dd6SShawn McCarney                                     }
16598fb49dd6SShawn McCarney                                 }
16608fb49dd6SShawn McCarney                             }
1661711ac7a9SEd Tanous                         }
1662711ac7a9SEd Tanous                     }
16638fb49dd6SShawn McCarney                     break;
16648fb49dd6SShawn McCarney                 }
16658fb49dd6SShawn McCarney             }
16668fb49dd6SShawn McCarney         }
16678fb49dd6SShawn McCarney 
1668d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1669d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1670d500549bSAnthony Wilson         std::string inventoryAssocPath;
1671d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1672d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1673d500549bSAnthony Wilson         {
1674d500549bSAnthony Wilson             const std::string& objPath =
1675d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1676d500549bSAnthony Wilson 
1677d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1678d500549bSAnthony Wilson             {
1679d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1680d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1681d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1682d500549bSAnthony Wilson                 {
1683711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1684d500549bSAnthony Wilson                     {
1685711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1686711ac7a9SEd Tanous                         {
1687711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1688711ac7a9SEd Tanous                             {
1689711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1690d500549bSAnthony Wilson                                 {
1691d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1692d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1693711ac7a9SEd Tanous                                             &value);
1694711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1695711ac7a9SEd Tanous                                         !endpoints->empty())
1696d500549bSAnthony Wilson                                     {
1697711ac7a9SEd Tanous                                         // Add inventory item to vector
1698d500549bSAnthony Wilson                                         // Store LED path in inventory item
1699711ac7a9SEd Tanous                                         const std::string& ledPath =
1700711ac7a9SEd Tanous                                             endpoints->front();
1701d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1702d500549bSAnthony Wilson                                     }
1703d500549bSAnthony Wilson                                 }
1704d500549bSAnthony Wilson                             }
1705711ac7a9SEd Tanous                         }
1706711ac7a9SEd Tanous                     }
1707711ac7a9SEd Tanous 
1708d500549bSAnthony Wilson                     break;
1709d500549bSAnthony Wilson                 }
1710d500549bSAnthony Wilson             }
1711d500549bSAnthony Wilson         }
1712adc4f0dbSShawn McCarney         callback(inventoryItems);
171362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17145eb468daSGeorge Liu     });
17158fb49dd6SShawn McCarney 
171662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17178fb49dd6SShawn McCarney }
17188fb49dd6SShawn McCarney 
17198fb49dd6SShawn McCarney /**
1720d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1721d500549bSAnthony Wilson  *
1722d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1723d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1724d500549bSAnthony Wilson  * inventoryItems vector.
1725d500549bSAnthony Wilson  *
1726d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1727d500549bSAnthony Wilson  * response.
1728d500549bSAnthony Wilson  *
1729d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1730d500549bSAnthony Wilson  * has been obtained.
1731d500549bSAnthony Wilson  *
1732d500549bSAnthony Wilson  * The callback must have the following signature:
1733d500549bSAnthony Wilson  *   @code
173442cbe538SGunnar Mills  *   callback()
1735d500549bSAnthony Wilson  *   @endcode
1736d500549bSAnthony Wilson  *
1737d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1738d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1739d500549bSAnthony Wilson  * last asynchronous function has completed.
1740d500549bSAnthony Wilson  *
1741d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1742d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1743d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1744d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1745d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1746d500549bSAnthony Wilson  * in recursive calls to this function.
1747d500549bSAnthony Wilson  */
1748d500549bSAnthony Wilson template <typename Callback>
1749d500549bSAnthony Wilson void getInventoryLedData(
1750d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1751d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1752fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1753d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1754d500549bSAnthony Wilson {
175562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1756d500549bSAnthony Wilson 
1757d500549bSAnthony Wilson     // If no more connections left, call callback
1758d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1759d500549bSAnthony Wilson     {
176042cbe538SGunnar Mills         callback();
176162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1762d500549bSAnthony Wilson         return;
1763d500549bSAnthony Wilson     }
1764d500549bSAnthony Wilson 
1765d500549bSAnthony Wilson     // Get inventory item data from current connection
1766fe04d49cSNan Zhou     auto it = ledConnections->begin();
1767fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1768d500549bSAnthony Wilson     if (it != ledConnections->end())
1769d500549bSAnthony Wilson     {
1770d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1771d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1772d500549bSAnthony Wilson         // Response handler for Get State property
17731e1e598dSJonathan Doman         auto respHandler =
17741e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
1775f94c4ecfSEd Tanous              callback{std::forward<Callback>(callback)}, ledConnectionsIndex](
17765e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
177762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1778d500549bSAnthony Wilson             if (ec)
1779d500549bSAnthony Wilson             {
178062598e31SEd Tanous                 BMCWEB_LOG_ERROR(
178162598e31SEd Tanous                     "getInventoryLedData respHandler DBus error {}", ec);
17828d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1783d500549bSAnthony Wilson                 return;
1784d500549bSAnthony Wilson             }
1785d500549bSAnthony Wilson 
178662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Led state: {}", state);
1787d500549bSAnthony Wilson             // Find inventory item with this LED object path
1788d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1789d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1790d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1791d500549bSAnthony Wilson             {
1792d500549bSAnthony Wilson                 // Store LED state in InventoryItem
179311ba3979SEd Tanous                 if (state.ends_with("On"))
1794d500549bSAnthony Wilson                 {
1795d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1796d500549bSAnthony Wilson                 }
179711ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1798d500549bSAnthony Wilson                 {
1799d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1800d500549bSAnthony Wilson                 }
180111ba3979SEd Tanous                 else if (state.ends_with("Off"))
1802d500549bSAnthony Wilson                 {
1803d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1804d500549bSAnthony Wilson                 }
1805d500549bSAnthony Wilson                 else
1806d500549bSAnthony Wilson                 {
1807d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1808d500549bSAnthony Wilson                 }
1809d500549bSAnthony Wilson             }
1810d500549bSAnthony Wilson 
1811d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1812d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1813d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1814d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1815d500549bSAnthony Wilson 
181662598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1817d500549bSAnthony Wilson         };
1818d500549bSAnthony Wilson 
1819d500549bSAnthony Wilson         // Get the State property for the current LED
18201e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18211e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18221e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18231e1e598dSJonathan Doman             std::move(respHandler));
1824d500549bSAnthony Wilson     }
1825d500549bSAnthony Wilson 
182662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1827d500549bSAnthony Wilson }
1828d500549bSAnthony Wilson 
1829d500549bSAnthony Wilson /**
1830d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1831d500549bSAnthony Wilson  *
1832d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1833d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1834d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1835d500549bSAnthony Wilson  *
1836d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1837d500549bSAnthony Wilson  * response.
1838d500549bSAnthony Wilson  *
1839d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1840d500549bSAnthony Wilson  * been obtained.
1841d500549bSAnthony Wilson  *
1842d500549bSAnthony Wilson  * The callback must have the following signature:
1843d500549bSAnthony Wilson  *   @code
184442cbe538SGunnar Mills  *   callback()
1845d500549bSAnthony Wilson  *   @endcode
1846d500549bSAnthony Wilson  *
1847d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1848d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1849d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1850d500549bSAnthony Wilson  */
1851d500549bSAnthony Wilson template <typename Callback>
1852d500549bSAnthony Wilson void getInventoryLeds(
1853d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1854d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1855d500549bSAnthony Wilson     Callback&& callback)
1856d500549bSAnthony Wilson {
185762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1858d500549bSAnthony Wilson 
1859d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1860e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1861d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1862d500549bSAnthony Wilson 
1863e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1864e99073f5SGeorge Liu     dbus::utility::getSubTree(
1865e99073f5SGeorge Liu         path, 0, interfaces,
1866002d39b4SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
1867002d39b4SEd Tanous          inventoryItems](
1868e99073f5SGeorge Liu             const boost::system::error_code& ec,
1869002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1870e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
187162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1872d500549bSAnthony Wilson         if (ec)
1873d500549bSAnthony Wilson         {
18748d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
187562598e31SEd Tanous             BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}", ec);
1876d500549bSAnthony Wilson             return;
1877d500549bSAnthony Wilson         }
1878d500549bSAnthony Wilson 
1879d500549bSAnthony Wilson         // Build map of LED object paths to connections
1880fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1881fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1882d500549bSAnthony Wilson 
1883d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1884d500549bSAnthony Wilson         for (const std::pair<
1885d500549bSAnthony Wilson                  std::string,
1886d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1887d500549bSAnthony Wilson                  object : subtree)
1888d500549bSAnthony Wilson         {
1889d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1890d500549bSAnthony Wilson             // items
1891d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1892d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1893d500549bSAnthony Wilson             {
1894d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1895d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1896d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
189762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath, connection);
1898d500549bSAnthony Wilson             }
1899d500549bSAnthony Wilson         }
1900d500549bSAnthony Wilson 
1901d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1902d500549bSAnthony Wilson                             std::move(callback));
190362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1904e99073f5SGeorge Liu     });
190562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1906d500549bSAnthony Wilson }
1907d500549bSAnthony Wilson 
1908d500549bSAnthony Wilson /**
190942cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
191042cbe538SGunnar Mills  *
191142cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
191242cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
191342cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
191442cbe538SGunnar Mills  *
191542cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
191642cbe538SGunnar Mills  * response.
191742cbe538SGunnar Mills  *
191842cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
191942cbe538SGunnar Mills  * when data has been obtained.
192042cbe538SGunnar Mills  *
192142cbe538SGunnar Mills  * The callback must have the following signature:
192242cbe538SGunnar Mills  *   @code
192342cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
192442cbe538SGunnar Mills  *   @endcode
192542cbe538SGunnar Mills  *
192642cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
192742cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
192842cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
192942cbe538SGunnar Mills  *        Supply Attributes
193042cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
193142cbe538SGunnar Mills  */
193242cbe538SGunnar Mills template <typename Callback>
193342cbe538SGunnar Mills void getPowerSupplyAttributesData(
1934b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
193542cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1936fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
193742cbe538SGunnar Mills     Callback&& callback)
193842cbe538SGunnar Mills {
193962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
194042cbe538SGunnar Mills 
194142cbe538SGunnar Mills     if (psAttributesConnections.empty())
194242cbe538SGunnar Mills     {
194362598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
194442cbe538SGunnar Mills         callback(inventoryItems);
194542cbe538SGunnar Mills         return;
194642cbe538SGunnar Mills     }
194742cbe538SGunnar Mills 
194842cbe538SGunnar Mills     // Assuming just one connection (service) for now
1949fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
195042cbe538SGunnar Mills 
195142cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
195242cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
195342cbe538SGunnar Mills 
195442cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
19555a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
1956f94c4ecfSEd Tanous                         callback{std::forward<Callback>(callback)}](
19575a39f77aSPatrick Williams                            const boost::system::error_code& ec,
19585a39f77aSPatrick Williams                            const uint32_t value) {
195962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
196042cbe538SGunnar Mills         if (ec)
196142cbe538SGunnar Mills         {
196262598e31SEd Tanous             BMCWEB_LOG_ERROR(
196362598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
19648d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
196542cbe538SGunnar Mills             return;
196642cbe538SGunnar Mills         }
196742cbe538SGunnar Mills 
196862598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
196942cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
197042cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
197142cbe538SGunnar Mills         {
197255f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
197342cbe538SGunnar Mills             {
197442cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
19751e1e598dSJonathan Doman                     static_cast<int>(value);
197642cbe538SGunnar Mills             }
197742cbe538SGunnar Mills         }
197842cbe538SGunnar Mills 
197962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
198042cbe538SGunnar Mills         callback(inventoryItems);
198142cbe538SGunnar Mills     };
198242cbe538SGunnar Mills 
198342cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
198442cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
19851e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
19861e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
19871e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
19881e1e598dSJonathan Doman         std::move(respHandler));
198942cbe538SGunnar Mills 
199062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
199142cbe538SGunnar Mills }
199242cbe538SGunnar Mills 
199342cbe538SGunnar Mills /**
199442cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
199542cbe538SGunnar Mills  *
199642cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
199742cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
199842cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
199942cbe538SGunnar Mills  * item.
200042cbe538SGunnar Mills  *
200142cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
200242cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
200342cbe538SGunnar Mills  *
200442cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
200542cbe538SGunnar Mills  * when information has been obtained.
200642cbe538SGunnar Mills  *
200742cbe538SGunnar Mills  * The callback must have the following signature:
200842cbe538SGunnar Mills  *   @code
200942cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
201042cbe538SGunnar Mills  *   @endcode
201142cbe538SGunnar Mills  *
201242cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
201342cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
201442cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
201542cbe538SGunnar Mills  */
201642cbe538SGunnar Mills template <typename Callback>
201742cbe538SGunnar Mills void getPowerSupplyAttributes(
201842cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
201942cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
202042cbe538SGunnar Mills     Callback&& callback)
202142cbe538SGunnar Mills {
202262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
202342cbe538SGunnar Mills 
202442cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2025a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
202642cbe538SGunnar Mills     {
202762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
202842cbe538SGunnar Mills         callback(inventoryItems);
202942cbe538SGunnar Mills         return;
203042cbe538SGunnar Mills     }
203142cbe538SGunnar Mills 
2032e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
203342cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
203442cbe538SGunnar Mills 
2035e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2036e99073f5SGeorge Liu     dbus::utility::getSubTree(
2037e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
2038b9d36b47SEd Tanous         [callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
2039b9d36b47SEd Tanous          inventoryItems](
2040e99073f5SGeorge Liu             const boost::system::error_code& ec,
2041b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2042e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
204362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
204442cbe538SGunnar Mills         if (ec)
204542cbe538SGunnar Mills         {
20468d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
204762598e31SEd Tanous             BMCWEB_LOG_ERROR(
204862598e31SEd Tanous                 "getPowerSupplyAttributes respHandler DBus error {}", ec);
204942cbe538SGunnar Mills             return;
205042cbe538SGunnar Mills         }
205126f6976fSEd Tanous         if (subtree.empty())
205242cbe538SGunnar Mills         {
205362598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
205442cbe538SGunnar Mills             callback(inventoryItems);
205542cbe538SGunnar Mills             return;
205642cbe538SGunnar Mills         }
205742cbe538SGunnar Mills 
205842cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
205942cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
206042cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2061fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
206242cbe538SGunnar Mills 
206342cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
206442cbe538SGunnar Mills         {
206562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
206642cbe538SGunnar Mills             callback(inventoryItems);
206742cbe538SGunnar Mills             return;
206842cbe538SGunnar Mills         }
206942cbe538SGunnar Mills 
207042cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
207142cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
207242cbe538SGunnar Mills 
207342cbe538SGunnar Mills         if (connection.empty())
207442cbe538SGunnar Mills         {
207562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
207642cbe538SGunnar Mills             callback(inventoryItems);
207742cbe538SGunnar Mills             return;
207842cbe538SGunnar Mills         }
207942cbe538SGunnar Mills 
208042cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
208162598e31SEd Tanous         BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
208262598e31SEd Tanous                          connection);
208342cbe538SGunnar Mills 
208442cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
208542cbe538SGunnar Mills                                      psAttributesConnections,
208642cbe538SGunnar Mills                                      std::move(callback));
208762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2088e99073f5SGeorge Liu     });
208962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
209042cbe538SGunnar Mills }
209142cbe538SGunnar Mills 
209242cbe538SGunnar Mills /**
2093adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
20948fb49dd6SShawn McCarney  *
20958fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2096adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
20978fb49dd6SShawn McCarney  *
2098adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2099adc4f0dbSShawn McCarney  * response.
21008fb49dd6SShawn McCarney  *
2101adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2102adc4f0dbSShawn McCarney  * inventory items have been obtained.
2103adc4f0dbSShawn McCarney  *
2104adc4f0dbSShawn McCarney  * The callback must have the following signature:
2105adc4f0dbSShawn McCarney  *   @code
2106adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2107adc4f0dbSShawn McCarney  *   @endcode
21088fb49dd6SShawn McCarney  *
21098fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21108fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21118fb49dd6SShawn McCarney  * implements ObjectManager.
2112adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21138fb49dd6SShawn McCarney  */
2114adc4f0dbSShawn McCarney template <typename Callback>
2115d0090733SEd Tanous static void
2116d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2117fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2118adc4f0dbSShawn McCarney                       Callback&& callback)
21198fb49dd6SShawn McCarney {
212062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2121adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
2122d0090733SEd Tanous         [sensorsAsyncResp, callback{std::forward<Callback>(callback)}](
2123adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
212462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21258fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2126d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
2127f94c4ecfSEd Tanous              callback{std::forward<const Callback>(callback)}](
2128fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
212962598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2130002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2131d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
213262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
213342cbe538SGunnar Mills 
2134002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2135002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
213662598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb enter");
213742cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2138002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
213942cbe538SGunnar Mills                                              std::move(callback));
214062598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
214142cbe538SGunnar Mills                 };
214242cbe538SGunnar Mills 
2143d500549bSAnthony Wilson                 // Find led connections and get the data
2144d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
214542cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
214662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2147d500549bSAnthony Wilson             };
21488fb49dd6SShawn McCarney 
2149adc4f0dbSShawn McCarney             // Get inventory item data from connections
2150adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2151d0090733SEd Tanous                                   invConnections,
2152d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
215362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
21548fb49dd6SShawn McCarney         };
21558fb49dd6SShawn McCarney 
2156adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2157002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21588fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
215962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
21608fb49dd6SShawn McCarney     };
21618fb49dd6SShawn McCarney 
2162adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2163d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2164adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
216562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2166adc4f0dbSShawn McCarney }
2167adc4f0dbSShawn McCarney 
2168adc4f0dbSShawn McCarney /**
2169adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2170adc4f0dbSShawn McCarney  *
2171adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2172adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2173adc4f0dbSShawn McCarney  * array.
2174adc4f0dbSShawn McCarney  *
2175adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2176adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2177adc4f0dbSShawn McCarney  * object.
2178adc4f0dbSShawn McCarney  *
2179adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2180adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2181adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2182adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2183adc4f0dbSShawn McCarney  */
218423a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2185adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2186adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2187adc4f0dbSShawn McCarney {
2188*18f8f608SEd Tanous     std::string nameS;
2189*18f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, nameS.begin(), '_', ' ');
2190adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2191adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2192adc4f0dbSShawn McCarney     {
2193*18f8f608SEd Tanous         nlohmann::json::iterator nameIt = powerSupply.find("Name");
2194*18f8f608SEd Tanous         if (nameIt == powerSupply.end())
2195*18f8f608SEd Tanous         {
2196*18f8f608SEd Tanous             continue;
2197*18f8f608SEd Tanous         }
2198*18f8f608SEd Tanous         const std::string* name = nameIt->get_ptr<std::string*>();
2199*18f8f608SEd Tanous         if (name == nullptr)
2200*18f8f608SEd Tanous         {
2201*18f8f608SEd Tanous             continue;
2202*18f8f608SEd Tanous         }
2203*18f8f608SEd Tanous         if (nameS == *name)
2204adc4f0dbSShawn McCarney         {
2205adc4f0dbSShawn McCarney             return powerSupply;
2206adc4f0dbSShawn McCarney         }
2207adc4f0dbSShawn McCarney     }
2208adc4f0dbSShawn McCarney 
2209adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2210adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2211adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2212ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2213ef4c65b7SEd Tanous                                                chassisId);
2214eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2215eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
2216*18f8f608SEd Tanous     std::string escaped;
2217*18f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, escaped.begin(), '_', ' ');
2218*18f8f608SEd Tanous     powerSupply["Name"] = std::move(escaped);
2219adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2220adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2221adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2222adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2223d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2224adc4f0dbSShawn McCarney 
222542cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
222642cbe538SGunnar Mills     {
222742cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
222842cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
222942cbe538SGunnar Mills     }
223042cbe538SGunnar Mills 
223142cbe538SGunnar Mills     powerSupply["Status"]["State"] = getState(&inventoryItem);
2232adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2233adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2234adc4f0dbSShawn McCarney 
2235adc4f0dbSShawn McCarney     return powerSupply;
22368fb49dd6SShawn McCarney }
22378fb49dd6SShawn McCarney 
22388fb49dd6SShawn McCarney /**
2239de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2240de629b6eSShawn McCarney  *
2241de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2242de629b6eSShawn McCarney  *
2243de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2244de629b6eSShawn McCarney  * information has been obtained.
2245de629b6eSShawn McCarney  *
2246adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2247de629b6eSShawn McCarney  *
2248de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2249de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2250de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2251de629b6eSShawn McCarney  *
2252de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2253de629b6eSShawn McCarney  *
2254adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2255adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2256adc4f0dbSShawn McCarney  *
2257de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2258adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2259de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2260de629b6eSShawn McCarney  * implements ObjectManager.
2261adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2262de629b6eSShawn McCarney  */
226323a21a1cSEd Tanous inline void getSensorData(
226481ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2265fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2266fe04d49cSNan Zhou     const std::set<std::string>& connections,
2267b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2268de629b6eSShawn McCarney {
226962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2270de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2271de629b6eSShawn McCarney     for (const std::string& connection : connections)
2272de629b6eSShawn McCarney     {
22735eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
22745eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
22755eb468daSGeorge Liu         dbus::utility::getManagedObjects(
22765eb468daSGeorge Liu             connection, sensorPath,
2277002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
22785e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
227902cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
228062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2281de629b6eSShawn McCarney             if (ec)
2282de629b6eSShawn McCarney             {
228362598e31SEd Tanous                 BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
22848d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2285de629b6eSShawn McCarney                 return;
2286de629b6eSShawn McCarney             }
2287de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2288de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2289de629b6eSShawn McCarney             {
2290de629b6eSShawn McCarney                 const std::string& objPath =
2291de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
229262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
229362598e31SEd Tanous                                  objPath);
2294de629b6eSShawn McCarney 
2295de629b6eSShawn McCarney                 std::vector<std::string> split;
2296de629b6eSShawn McCarney                 // Reserve space for
2297de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2298de629b6eSShawn McCarney                 split.reserve(6);
229950ebd4afSEd Tanous                 // NOLINTNEXTLINE
230050ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2301de629b6eSShawn McCarney                 if (split.size() < 6)
2302de629b6eSShawn McCarney                 {
230362598e31SEd Tanous                     BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
230462598e31SEd Tanous                                      objPath);
2305de629b6eSShawn McCarney                     continue;
2306de629b6eSShawn McCarney                 }
230750ebd4afSEd Tanous                 // These indexes aren't intuitive, as 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];
231162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
231262598e31SEd Tanous                                  sensorType);
231349c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2314de629b6eSShawn McCarney                 {
231562598e31SEd Tanous                     BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
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);
23323544d2a7SEd Tanous                     auto remove = std::ranges::remove(sensorTypeEscaped, '_');
23333544d2a7SEd Tanous 
23343544d2a7SEd Tanous                     sensorTypeEscaped.erase(std::ranges::begin(remove),
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"] =
2341ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2342c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2343ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2344ef4c65b7SEd Tanous                                             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                     {
238662598e31SEd Tanous                         BMCWEB_LOG_ERROR("Unsure how to handle sensorType {}",
238762598e31SEd Tanous                                          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;
2401ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2402ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2403eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2404eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2405eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2406eddfc437SWilly Tu                                                  .to_string());
2407eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2408b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2409adc4f0dbSShawn McCarney                         }
2410adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2411adc4f0dbSShawn McCarney                     }
2412adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2413adc4f0dbSShawn McCarney                     {
2414adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2415adc4f0dbSShawn McCarney                         {
2416adc4f0dbSShawn McCarney                             sensorJson =
2417adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
241881ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2419adc4f0dbSShawn McCarney                         }
242049c53ac9SJohnathan Mantey                     }
2421928fefb9SNan Zhou                     else if (fieldName == "Members")
2422928fefb9SNan Zhou                     {
2423677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
24243544d2a7SEd Tanous                         auto remove = std::ranges::remove(sensorTypeEscaped,
24253544d2a7SEd Tanous                                                           '_');
24263544d2a7SEd Tanous                         sensorTypeEscaped.erase(std::ranges::begin(remove),
2427677bb756SEd Tanous                                                 sensorTypeEscaped.end());
2428677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2429677bb756SEd Tanous                         sensorId += "_";
2430677bb756SEd Tanous                         sensorId += sensorName;
2431677bb756SEd Tanous 
24321476687dSEd Tanous                         nlohmann::json::object_t member;
2433ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2434ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2435677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2436677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2437b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2438928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2439928fefb9SNan Zhou                     }
244049c53ac9SJohnathan Mantey                     else
244149c53ac9SJohnathan Mantey                     {
24421476687dSEd Tanous                         nlohmann::json::object_t member;
2443ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2444ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2445eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2446eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2447eddfc437SWilly Tu                         url.set_fragment(
2448eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2449eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2450b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2451adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
245249c53ac9SJohnathan Mantey                     }
245395a3ecadSAnthony Wilson                 }
2454de629b6eSShawn McCarney 
2455adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2456adc4f0dbSShawn McCarney                 {
24571d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24581d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24591d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24601d7c0054SEd Tanous                                            inventoryItem);
24611d7c0054SEd Tanous 
24621d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24631d7c0054SEd Tanous                     path += sensorType;
24641d7c0054SEd Tanous                     path += "/";
24651d7c0054SEd Tanous                     path += sensorName;
2466c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2467adc4f0dbSShawn McCarney                 }
2468de629b6eSShawn McCarney             }
246981ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
247049c53ac9SJohnathan Mantey             {
247181ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2472928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2473928fefb9SNan Zhou                         sensors::node::sensors &&
2474928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2475928fefb9SNan Zhou                 {
2476928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2477928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2478928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2479928fefb9SNan Zhou                             .size();
2480928fefb9SNan Zhou                 }
2481928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2482928fefb9SNan Zhou                          sensors::node::thermal)
24838bd25ccdSJames Feist                 {
248481ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
24858bd25ccdSJames Feist                 }
248649c53ac9SJohnathan Mantey             }
248762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
24885eb468daSGeorge Liu         });
248923a21a1cSEd Tanous     }
249062598e31SEd Tanous     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) {
249962598e31SEd 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) {
250462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
250549c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2506002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2507d0090733SEd Tanous                           inventoryItems);
250862598e31SEd Tanous             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 
251562598e31SEd 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 {
253062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
253195a3ecadSAnthony Wilson     auto getChassisCb =
253281ce609eSEd Tanous         [sensorsAsyncResp](
2533fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
253462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb enter");
253581ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
253662598e31SEd 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));
254862598e31SEd 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 
2582c71d6125SEd Tanous inline std::pair<std::string, std::string>
2583c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2584c71d6125SEd Tanous {
2585c71d6125SEd Tanous     size_t index = sensorId.find('_');
2586c71d6125SEd Tanous     if (index == std::string::npos)
2587c71d6125SEd Tanous     {
2588c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2589c71d6125SEd Tanous     }
2590c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2591c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2592c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2593c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2594c71d6125SEd Tanous     {
2595c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2596c71d6125SEd Tanous     }
2597c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2598c71d6125SEd Tanous }
2599c71d6125SEd 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 {
261262598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
261362598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
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;
2656c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2657c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2658c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2659c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2660f65af9e8SRichard Marian Thomaiyar             {
266162598e31SEd Tanous                 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             {
267562598e31SEd Tanous                 BMCWEB_LOG_INFO(
267662598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
267762598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
26784f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2679a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2680a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2681413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2682413961deSRichard Marian Thomaiyar                                                : "Voltages",
2683f65af9e8SRichard Marian Thomaiyar                                            "Count");
2684f65af9e8SRichard Marian Thomaiyar                 return;
2685f65af9e8SRichard Marian Thomaiyar             }
2686f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2687f65af9e8SRichard Marian Thomaiyar             {
268828aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
268928aa8de5SGeorge Liu                 std::string sensorName = path.filename();
269028aa8de5SGeorge Liu                 if (sensorName.empty())
2691f65af9e8SRichard Marian Thomaiyar                 {
26924f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2693f65af9e8SRichard Marian Thomaiyar                     return;
2694f65af9e8SRichard Marian Thomaiyar                 }
26953f5eb755SBan Feng                 std::string id = path.parent_path().filename();
26963544d2a7SEd Tanous                 auto remove = std::ranges::remove(id, '_');
26973544d2a7SEd Tanous                 id.erase(std::ranges::begin(remove), id.end());
26983f5eb755SBan Feng                 id += "_";
26993f5eb755SBan Feng                 id += sensorName;
2700f65af9e8SRichard Marian Thomaiyar 
27013f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2702f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2703f65af9e8SRichard Marian Thomaiyar                 {
270462598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
270562598e31SEd Tanous                                     item.first);
27064f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2707413961deSRichard Marian Thomaiyar                     return;
2708413961deSRichard Marian Thomaiyar                 }
27099ae226faSGeorge Liu                 sdbusplus::asio::setProperty(
27109ae226faSGeorge Liu                     *crow::connections::systemBus, item.second, item.first,
27119ae226faSGeorge Liu                     "xyz.openbmc_project.Sensor.Value", "Value",
27129ae226faSGeorge Liu                     iterator->second.first,
27135e7e2dc5SEd Tanous                     [sensorAsyncResp](const boost::system::error_code& ec) {
2714413961deSRichard Marian Thomaiyar                     if (ec)
2715413961deSRichard Marian Thomaiyar                     {
27164f277b54SJayaprakash Mutyala                         if (ec.value() ==
27174f277b54SJayaprakash Mutyala                             boost::system::errc::permission_denied)
27184f277b54SJayaprakash Mutyala                         {
271962598e31SEd Tanous                             BMCWEB_LOG_WARNING(
272062598e31SEd Tanous                                 "Manufacturing mode is not Enabled...can't "
272162598e31SEd Tanous                                 "Override the sensor value. ");
27224f277b54SJayaprakash Mutyala 
27234f277b54SJayaprakash Mutyala                             messages::insufficientPrivilege(
27248d1b46d7Szhanghch05                                 sensorAsyncResp->asyncResp->res);
2725413961deSRichard Marian Thomaiyar                             return;
2726413961deSRichard Marian Thomaiyar                         }
272762598e31SEd Tanous                         BMCWEB_LOG_DEBUG(
272862598e31SEd Tanous                             "setOverrideValueStatus DBUS error: {}", ec);
27294f277b54SJayaprakash Mutyala                         messages::internalError(
27304f277b54SJayaprakash Mutyala                             sensorAsyncResp->asyncResp->res);
27314f277b54SJayaprakash Mutyala                     }
27329ae226faSGeorge Liu                 });
2733f65af9e8SRichard Marian Thomaiyar             }
2734413961deSRichard Marian Thomaiyar         };
2735413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2736413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2737413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2738413961deSRichard Marian Thomaiyar     };
2739413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27407f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27417f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27427f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2743413961deSRichard Marian Thomaiyar }
2744413961deSRichard Marian Thomaiyar 
2745a0ec28b6SAdrian Ambrożewicz /**
2746a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2747a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2748a0ec28b6SAdrian Ambrożewicz  *
2749a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2750a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2751a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2752a0ec28b6SAdrian Ambrożewicz  *
2753a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2754a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2755a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2756a0ec28b6SAdrian Ambrożewicz  */
2757931edc79SEd Tanous template <typename Callback>
2758021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2759021d32cfSKrzysztof Grobelny                                  const std::string& node,
2760931edc79SEd Tanous                                  Callback&& mapComplete)
2761a0ec28b6SAdrian Ambrożewicz {
276202da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
276302da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
276402da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
276502da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2766a0ec28b6SAdrian Ambrożewicz     {
276762598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
27686804b5c8SEd Tanous         std::map<std::string, std::string> noop;
27696804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2770a0ec28b6SAdrian Ambrożewicz         return;
2771a0ec28b6SAdrian Ambrożewicz     }
2772d51e072fSKrzysztof Grobelny 
277372374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2774931edc79SEd Tanous     auto callback = [asyncResp,
2775931edc79SEd Tanous                      mapCompleteCb{std::forward<Callback>(mapComplete)}](
2776a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2777fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2778fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2779fe04d49cSNan Zhou     };
2780a0ec28b6SAdrian Ambrożewicz 
2781a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2782d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2783a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2784a0ec28b6SAdrian Ambrożewicz }
2785a0ec28b6SAdrian Ambrożewicz 
2786bacb2162SNan Zhou namespace sensors
2787bacb2162SNan Zhou {
2788928fefb9SNan Zhou 
2789bacb2162SNan Zhou inline void getChassisCallback(
2790c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2791c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2792fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2793bacb2162SNan Zhou {
279462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2795bacb2162SNan Zhou 
2796c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2797c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2798bacb2162SNan Zhou     {
279962598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2800bacb2162SNan Zhou 
2801bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2802bacb2162SNan Zhou         std::string sensorName = path.filename();
2803bacb2162SNan Zhou         if (sensorName.empty())
2804bacb2162SNan Zhou         {
280562598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2806c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2807bacb2162SNan Zhou             return;
2808bacb2162SNan Zhou         }
2809c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2810c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2811c1d019a6SEd Tanous         // type in the URI
28123544d2a7SEd Tanous         auto remove = std::ranges::remove(type, '_');
28133544d2a7SEd Tanous         type.erase(std::ranges::begin(remove), type.end());
2814c1d019a6SEd Tanous 
28151476687dSEd Tanous         nlohmann::json::object_t member;
2816c1d019a6SEd Tanous         std::string id = type;
2817c1d019a6SEd Tanous         id += "_";
2818c1d019a6SEd Tanous         id += sensorName;
2819ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2820ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2821c1d019a6SEd Tanous 
2822b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2823bacb2162SNan Zhou     }
2824bacb2162SNan Zhou 
2825c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
282662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2827bacb2162SNan Zhou }
2828e6bd846dSNan Zhou 
2829ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2830ac106bf6SEd Tanous     App& app, const crow::Request& req,
2831ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2832de167a6fSNan Zhou     const std::string& chassisId)
2833de167a6fSNan Zhou {
2834de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2835de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2836de167a6fSNan Zhou     };
2837de167a6fSNan Zhou     query_param::Query delegatedQuery;
2838ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2839de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2840de167a6fSNan Zhou     {
2841de167a6fSNan Zhou         return;
2842de167a6fSNan Zhou     }
2843de167a6fSNan Zhou 
2844de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2845de167a6fSNan Zhou     {
2846de167a6fSNan Zhou         // we perform efficient expand.
2847ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2848ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2849de167a6fSNan Zhou             sensors::node::sensors,
2850de167a6fSNan Zhou             /*efficientExpand=*/true);
2851ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2852de167a6fSNan Zhou 
285362598e31SEd Tanous         BMCWEB_LOG_DEBUG(
285462598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2855de167a6fSNan Zhou         return;
28560bad320cSEd Tanous     }
2857de167a6fSNan Zhou 
2858de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2859de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2860ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2861ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2862ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2863c1d019a6SEd Tanous }
28647f1cc26dSEd Tanous 
2865c1d019a6SEd Tanous inline void
2866c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2867c1d019a6SEd Tanous                       const std::string& sensorPath,
2868c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2869c1d019a6SEd Tanous {
2870c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2871c1d019a6SEd Tanous     {
2872c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2873c1d019a6SEd Tanous         return;
2874c1d019a6SEd Tanous     }
2875c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2876c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
287762598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
287862598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2879c1343bf6SKrzysztof Grobelny 
2880c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2881c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2882c1d019a6SEd Tanous         [asyncResp,
28835e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2884c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2885c1d019a6SEd Tanous         if (ec)
2886c1d019a6SEd Tanous         {
2887c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2888c1d019a6SEd Tanous             return;
2889c1d019a6SEd Tanous         }
2890c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2891c1d019a6SEd Tanous         std::string name = path.filename();
2892c1d019a6SEd Tanous         path = path.parent_path();
2893c1d019a6SEd Tanous         std::string type = path.filename();
2894c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2895c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2896c1343bf6SKrzysztof Grobelny     });
2897de167a6fSNan Zhou }
2898de167a6fSNan Zhou 
2899e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2900c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2901677bb756SEd Tanous                             const std::string& chassisId,
2902c1d019a6SEd Tanous                             const std::string& sensorId)
2903e6bd846dSNan Zhou {
2904c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2905e6bd846dSNan Zhou     {
2906e6bd846dSNan Zhou         return;
2907e6bd846dSNan Zhou     }
2908c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2909c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2910c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2911c1d019a6SEd Tanous     {
2912c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2913c1d019a6SEd Tanous         return;
2914c1d019a6SEd Tanous     }
2915c71d6125SEd Tanous 
2916ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2917ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2918c1d019a6SEd Tanous 
291962598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2920e6bd846dSNan Zhou 
29212b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2922e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2923c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2924c71d6125SEd Tanous                              '/' + nameType.second;
2925e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2926e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29272b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29282b73119cSGeorge Liu         sensorPath, interfaces,
2929aec0ec30SMyung Bae         [asyncResp, sensorId,
29302b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2931c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
293262598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 enter");
2933aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2934aec0ec30SMyung Bae         {
293562598e31SEd Tanous             BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2936aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2937aec0ec30SMyung Bae             return;
2938aec0ec30SMyung Bae         }
2939e6bd846dSNan Zhou         if (ec)
2940e6bd846dSNan Zhou         {
2941c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
294262598e31SEd Tanous             BMCWEB_LOG_ERROR(
294362598e31SEd Tanous                 "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2944e6bd846dSNan Zhou             return;
2945e6bd846dSNan Zhou         }
2946c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
294762598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 exit");
29482b73119cSGeorge Liu     });
2949e6bd846dSNan Zhou }
2950e6bd846dSNan Zhou 
2951bacb2162SNan Zhou } // namespace sensors
2952bacb2162SNan Zhou 
29537e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
295495a3ecadSAnthony Wilson {
29557e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2956ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2957002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2958de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
295995a3ecadSAnthony Wilson }
296095a3ecadSAnthony Wilson 
29617e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
296295a3ecadSAnthony Wilson {
29637e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2964ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2965002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2966e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
296795a3ecadSAnthony Wilson }
296895a3ecadSAnthony Wilson 
296908777fb0SLewanczyk, Dawid } // namespace redfish
2970