xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision 539d8c6bc399e516d39bcaa18262cf206f4c1035)
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"
21*539d8c6bSEd Tanous #include "generated/enums/redundancy.hpp"
22aaf08ac7SMatt Simmering #include "generated/enums/resource.hpp"
230ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
24*539d8c6bSEd Tanous #include "generated/enums/thermal.hpp"
253ccb3adbSEd Tanous #include "query.hpp"
263ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2750ebd4afSEd Tanous #include "str_utility.hpp"
283ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
293ccb3adbSEd Tanous #include "utils/json_utils.hpp"
303ccb3adbSEd Tanous #include "utils/query_param.hpp"
310ec8b83dSEd Tanous 
32e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
33ef4c65b7SEd Tanous #include <boost/url/format.hpp>
341e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3586d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
361214b7e7SGunnar Mills 
377a1dbc48SGeorge Liu #include <array>
381214b7e7SGunnar Mills #include <cmath>
39fe04d49cSNan Zhou #include <iterator>
40283860f5SEd Tanous #include <limits>
41fe04d49cSNan Zhou #include <map>
423544d2a7SEd Tanous #include <ranges>
43fe04d49cSNan Zhou #include <set>
4418f8f608SEd Tanous #include <string>
457a1dbc48SGeorge Liu #include <string_view>
46b5a76932SEd Tanous #include <utility>
47abf2add6SEd Tanous #include <variant>
4808777fb0SLewanczyk, Dawid 
491abe55efSEd Tanous namespace redfish
501abe55efSEd Tanous {
5108777fb0SLewanczyk, Dawid 
52a0ec28b6SAdrian Ambrożewicz namespace sensors
53a0ec28b6SAdrian Ambrożewicz {
54a0ec28b6SAdrian Ambrożewicz namespace node
55a0ec28b6SAdrian Ambrożewicz {
56a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
57a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
58a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
59a0ec28b6SAdrian Ambrożewicz } // namespace node
60a0ec28b6SAdrian Ambrożewicz 
6102da7c5aSEd Tanous // clang-format off
62a0ec28b6SAdrian Ambrożewicz namespace dbus
63a0ec28b6SAdrian Ambrożewicz {
64cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6602da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6702da7c5aSEd Tanous });
68c2bf7f99SWludzik, Jozef 
6925b54dbaSEd Tanous constexpr auto getSensorPaths(){
7025b54dbaSEd Tanous     if constexpr(BMCWEB_REDFISH_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM){
7125b54dbaSEd Tanous     return std::to_array<std::string_view>({
7202da7c5aSEd Tanous         "/xyz/openbmc_project/sensors/power",
73a0ec28b6SAdrian Ambrożewicz         "/xyz/openbmc_project/sensors/current",
747088690cSBasheer Ahmed Muddebihal         "/xyz/openbmc_project/sensors/airflow",
755deabed9SGunnar Mills         "/xyz/openbmc_project/sensors/humidity",
76e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/voltage",
77e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_tach",
78e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/temperature",
79e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_pwm",
80e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/altitude",
81e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/energy",
8225b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
8325b54dbaSEd Tanous     } else {
8425b54dbaSEd Tanous       return  std::to_array<std::string_view>({"/xyz/openbmc_project/sensors/power",
8525b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/current",
8625b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/airflow",
8725b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/humidity",
8825b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
8925b54dbaSEd Tanous }
9025b54dbaSEd Tanous }
9125b54dbaSEd Tanous 
9225b54dbaSEd Tanous constexpr auto sensorPaths = getSensorPaths();
9302da7c5aSEd Tanous 
94cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
9502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
96a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
9702da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
9802da7c5aSEd Tanous });
9902da7c5aSEd Tanous 
100c2bf7f99SWludzik, Jozef } // namespace dbus
10102da7c5aSEd Tanous // clang-format on
10202da7c5aSEd Tanous 
103cf9e417dSEd Tanous using sensorPair =
104cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
10502da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
106cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
107cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
108cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
109c2bf7f99SWludzik, Jozef 
1100ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
111c2bf7f99SWludzik, Jozef {
112c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
113c2bf7f99SWludzik, Jozef     {
1140ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
115c2bf7f99SWludzik, Jozef     }
116c2bf7f99SWludzik, Jozef     if (sensorType == "power")
117c2bf7f99SWludzik, Jozef     {
1180ec8b83dSEd Tanous         return sensor::ReadingType::Power;
119c2bf7f99SWludzik, Jozef     }
120c2bf7f99SWludzik, Jozef     if (sensorType == "current")
121c2bf7f99SWludzik, Jozef     {
1220ec8b83dSEd Tanous         return sensor::ReadingType::Current;
123c2bf7f99SWludzik, Jozef     }
124c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
125c2bf7f99SWludzik, Jozef     {
1260ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
127c2bf7f99SWludzik, Jozef     }
128c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
129c2bf7f99SWludzik, Jozef     {
1300ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
131c2bf7f99SWludzik, Jozef     }
132c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
133c2bf7f99SWludzik, Jozef     {
1340ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
135c2bf7f99SWludzik, Jozef     }
1365deabed9SGunnar Mills     if (sensorType == "humidity")
1375deabed9SGunnar Mills     {
1380ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1395deabed9SGunnar Mills     }
140c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
141c2bf7f99SWludzik, Jozef     {
1420ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
143c2bf7f99SWludzik, Jozef     }
144c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
145c2bf7f99SWludzik, Jozef     {
1460ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
147c2bf7f99SWludzik, Jozef     }
148c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
149c2bf7f99SWludzik, Jozef     {
1500ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
151c2bf7f99SWludzik, Jozef     }
1520ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
153c2bf7f99SWludzik, Jozef }
154c2bf7f99SWludzik, Jozef 
1551d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
156c2bf7f99SWludzik, Jozef {
157c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
158c2bf7f99SWludzik, Jozef     {
159c2bf7f99SWludzik, Jozef         return "V";
160c2bf7f99SWludzik, Jozef     }
161c2bf7f99SWludzik, Jozef     if (sensorType == "power")
162c2bf7f99SWludzik, Jozef     {
163c2bf7f99SWludzik, Jozef         return "W";
164c2bf7f99SWludzik, Jozef     }
165c2bf7f99SWludzik, Jozef     if (sensorType == "current")
166c2bf7f99SWludzik, Jozef     {
167c2bf7f99SWludzik, Jozef         return "A";
168c2bf7f99SWludzik, Jozef     }
169c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
170c2bf7f99SWludzik, Jozef     {
171c2bf7f99SWludzik, Jozef         return "RPM";
172c2bf7f99SWludzik, Jozef     }
173c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
174c2bf7f99SWludzik, Jozef     {
175c2bf7f99SWludzik, Jozef         return "Cel";
176c2bf7f99SWludzik, Jozef     }
1775deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1785deabed9SGunnar Mills         sensorType == "humidity")
179c2bf7f99SWludzik, Jozef     {
180c2bf7f99SWludzik, Jozef         return "%";
181c2bf7f99SWludzik, Jozef     }
182c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
183c2bf7f99SWludzik, Jozef     {
184c2bf7f99SWludzik, Jozef         return "m";
185c2bf7f99SWludzik, Jozef     }
186c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
187c2bf7f99SWludzik, Jozef     {
188c2bf7f99SWludzik, Jozef         return "cft_i/min";
189c2bf7f99SWludzik, Jozef     }
190c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
191c2bf7f99SWludzik, Jozef     {
192c2bf7f99SWludzik, Jozef         return "J";
193c2bf7f99SWludzik, Jozef     }
194c2bf7f99SWludzik, Jozef     return "";
195a0ec28b6SAdrian Ambrożewicz }
196a0ec28b6SAdrian Ambrożewicz } // namespace sensors
197a0ec28b6SAdrian Ambrożewicz 
19808777fb0SLewanczyk, Dawid /**
199588c3f0dSKowalski, Kamil  * SensorsAsyncResp
20008777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
20108777fb0SLewanczyk, Dawid  */
2021abe55efSEd Tanous class SensorsAsyncResp
2031abe55efSEd Tanous {
20408777fb0SLewanczyk, Dawid   public:
205a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
206a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
207fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
208a0ec28b6SAdrian Ambrożewicz 
209a0ec28b6SAdrian Ambrożewicz     struct SensorData
210a0ec28b6SAdrian Ambrożewicz     {
211a0ec28b6SAdrian Ambrożewicz         const std::string name;
212a0ec28b6SAdrian Ambrożewicz         std::string uri;
213a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
214a0ec28b6SAdrian Ambrożewicz     };
215a0ec28b6SAdrian Ambrożewicz 
2168a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2178d1b46d7Szhanghch05                      const std::string& chassisIdIn,
218cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21902da7c5aSEd Tanous                      std::string_view subNode) :
2208a592810SEd Tanous         asyncResp(asyncRespIn),
221928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
222928fefb9SNan Zhou         efficientExpand(false)
2231214b7e7SGunnar Mills     {}
22408777fb0SLewanczyk, Dawid 
225a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2268a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2278d1b46d7Szhanghch05                      const std::string& chassisIdIn,
228cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22902da7c5aSEd Tanous                      std::string_view subNode,
230a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2318a592810SEd Tanous         asyncResp(asyncRespIn),
232928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
233928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
234a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
235a0ec28b6SAdrian Ambrożewicz     {}
236a0ec28b6SAdrian Ambrożewicz 
237928fefb9SNan Zhou     // sensor collections expand
2388a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
239928fefb9SNan Zhou                      const std::string& chassisIdIn,
240cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2418a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2428a592810SEd Tanous         asyncResp(asyncRespIn),
243928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2448a592810SEd Tanous         efficientExpand(efficientExpandIn)
245928fefb9SNan Zhou     {}
246928fefb9SNan Zhou 
2471abe55efSEd Tanous     ~SensorsAsyncResp()
2481abe55efSEd Tanous     {
2498d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2508d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2511abe55efSEd Tanous         {
2521abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2531abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2541abe55efSEd Tanous             // proper code
2558d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
25608777fb0SLewanczyk, Dawid         }
257a0ec28b6SAdrian Ambrożewicz 
258a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
259a0ec28b6SAdrian Ambrożewicz         {
260fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2618d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
262a0ec28b6SAdrian Ambrożewicz             {
263a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
264a0ec28b6SAdrian Ambrożewicz                 {
265c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
266a0ec28b6SAdrian Ambrożewicz                 }
267a0ec28b6SAdrian Ambrożewicz             }
2688d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
269a0ec28b6SAdrian Ambrożewicz         }
27008777fb0SLewanczyk, Dawid     }
271588c3f0dSKowalski, Kamil 
272ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
273ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
274ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
275ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
276ecd6a3a2SEd Tanous 
277a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
278c1d019a6SEd Tanous                      const std::string& dbusPath)
279a0ec28b6SAdrian Ambrożewicz     {
280a0ec28b6SAdrian Ambrożewicz         if (metadata)
281a0ec28b6SAdrian Ambrożewicz         {
282c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
283c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
284a0ec28b6SAdrian Ambrożewicz         }
285a0ec28b6SAdrian Ambrożewicz     }
286a0ec28b6SAdrian Ambrożewicz 
287a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
288a0ec28b6SAdrian Ambrożewicz     {
289a0ec28b6SAdrian Ambrożewicz         if (metadata)
290a0ec28b6SAdrian Ambrożewicz         {
291a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
292a0ec28b6SAdrian Ambrożewicz             {
293a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
294a0ec28b6SAdrian Ambrożewicz                 {
295a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
296a0ec28b6SAdrian Ambrożewicz                 }
297a0ec28b6SAdrian Ambrożewicz             }
298a0ec28b6SAdrian Ambrożewicz         }
299a0ec28b6SAdrian Ambrożewicz     }
300a0ec28b6SAdrian Ambrożewicz 
3018d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
302a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
303cf9e417dSEd Tanous     const std::span<const std::string_view> types;
304a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
305928fefb9SNan Zhou     const bool efficientExpand;
306a0ec28b6SAdrian Ambrożewicz 
307a0ec28b6SAdrian Ambrożewicz   private:
308a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
309a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
31008777fb0SLewanczyk, Dawid };
31108777fb0SLewanczyk, Dawid 
31208777fb0SLewanczyk, Dawid /**
313d500549bSAnthony Wilson  * Possible states for physical inventory leds
314d500549bSAnthony Wilson  */
315d500549bSAnthony Wilson enum class LedState
316d500549bSAnthony Wilson {
317d500549bSAnthony Wilson     OFF,
318d500549bSAnthony Wilson     ON,
319d500549bSAnthony Wilson     BLINK,
320d500549bSAnthony Wilson     UNKNOWN
321d500549bSAnthony Wilson };
322d500549bSAnthony Wilson 
323d500549bSAnthony Wilson /**
324adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
325adc4f0dbSShawn McCarney  */
326adc4f0dbSShawn McCarney class InventoryItem
327adc4f0dbSShawn McCarney {
328adc4f0dbSShawn McCarney   public:
3294e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
330adc4f0dbSShawn McCarney     {
331adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
33228aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
33328aa8de5SGeorge Liu         name = path.filename();
33428aa8de5SGeorge Liu         if (name.empty())
335adc4f0dbSShawn McCarney         {
33662598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
337adc4f0dbSShawn McCarney         }
338adc4f0dbSShawn McCarney     }
339adc4f0dbSShawn McCarney 
340adc4f0dbSShawn McCarney     std::string objectPath;
341adc4f0dbSShawn McCarney     std::string name;
342e05aec50SEd Tanous     bool isPresent = true;
343e05aec50SEd Tanous     bool isFunctional = true;
344e05aec50SEd Tanous     bool isPowerSupply = false;
345e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
346adc4f0dbSShawn McCarney     std::string manufacturer;
347adc4f0dbSShawn McCarney     std::string model;
348adc4f0dbSShawn McCarney     std::string partNumber;
349adc4f0dbSShawn McCarney     std::string serialNumber;
350adc4f0dbSShawn McCarney     std::set<std::string> sensors;
351d500549bSAnthony Wilson     std::string ledObjectPath;
352e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
353adc4f0dbSShawn McCarney };
354adc4f0dbSShawn McCarney 
355adc4f0dbSShawn McCarney /**
356413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
357588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
35808777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
35908777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
36008777fb0SLewanczyk, Dawid  */
36108777fb0SLewanczyk, Dawid template <typename Callback>
362413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
36381ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
364fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3651abe55efSEd Tanous     Callback&& callback)
3661abe55efSEd Tanous {
36762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
36803b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
369e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
37008777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
37108777fb0SLewanczyk, Dawid 
372e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
373e99073f5SGeorge Liu     dbus::utility::getSubTree(
374e99073f5SGeorge Liu         path, 2, interfaces,
3758cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
376e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
377002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
378e99073f5SGeorge Liu         // Response handler for parsing objects subtree
37962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3801abe55efSEd Tanous         if (ec)
3811abe55efSEd Tanous         {
3828d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
38362598e31SEd Tanous             BMCWEB_LOG_ERROR(
38462598e31SEd Tanous                 "getObjectsWithConnection resp_handler: Dbus error {}", ec);
38508777fb0SLewanczyk, Dawid             return;
38608777fb0SLewanczyk, Dawid         }
38708777fb0SLewanczyk, Dawid 
38862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
38908777fb0SLewanczyk, Dawid 
39008777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
39108777fb0SLewanczyk, Dawid         // found in the chassis
392fe04d49cSNan Zhou         std::set<std::string> connections;
393413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
39408777fb0SLewanczyk, Dawid 
39562598e31SEd Tanous         BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
39649c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3971abe55efSEd Tanous         {
39862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
39908777fb0SLewanczyk, Dawid         }
40008777fb0SLewanczyk, Dawid 
40108777fb0SLewanczyk, Dawid         for (const std::pair<
40208777fb0SLewanczyk, Dawid                  std::string,
40308777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
4041abe55efSEd Tanous                  object : subtree)
4051abe55efSEd Tanous         {
40649c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
4071abe55efSEd Tanous             {
40849c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
4091abe55efSEd Tanous                          objData : object.second)
4101abe55efSEd Tanous                 {
41162598e31SEd Tanous                     BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
41208777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
413de629b6eSShawn McCarney                     objectsWithConnection.insert(
414de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
41508777fb0SLewanczyk, Dawid                 }
41608777fb0SLewanczyk, Dawid             }
41708777fb0SLewanczyk, Dawid         }
41862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
419413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
42062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
421e99073f5SGeorge Liu     });
42262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
423413961deSRichard Marian Thomaiyar }
424413961deSRichard Marian Thomaiyar 
425413961deSRichard Marian Thomaiyar /**
426413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
427413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
428413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
429413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
430413961deSRichard Marian Thomaiyar  */
431413961deSRichard Marian Thomaiyar template <typename Callback>
432fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
433fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
434413961deSRichard Marian Thomaiyar                     Callback&& callback)
435413961deSRichard Marian Thomaiyar {
436413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
4378cb2c024SEd Tanous         [callback = std::forward<Callback>(callback)](
4388cb2c024SEd Tanous             const std::set<std::string>& connections,
439413961deSRichard Marian Thomaiyar             const std::set<std::pair<std::string, std::string>>&
4403174e4dfSEd Tanous             /*objectsWithConnection*/) { callback(connections); };
44181ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
442413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
44308777fb0SLewanczyk, Dawid }
44408777fb0SLewanczyk, Dawid 
44508777fb0SLewanczyk, Dawid /**
44649c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
44749c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
44849c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
44949c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
45049c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
45149c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
45249c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
45349c53ac9SJohnathan Mantey  */
45423a21a1cSEd Tanous inline void reduceSensorList(
4557f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
456cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
45749c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
458fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
45949c53ac9SJohnathan Mantey {
46049c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
46149c53ac9SJohnathan Mantey     {
4627f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4637f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
464a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
46549c53ac9SJohnathan Mantey                                        : "Voltages");
46649c53ac9SJohnathan Mantey 
46749c53ac9SJohnathan Mantey         return;
46849c53ac9SJohnathan Mantey     }
46949c53ac9SJohnathan Mantey     if (allSensors->empty())
47049c53ac9SJohnathan Mantey     {
47149c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
47249c53ac9SJohnathan Mantey         return;
47349c53ac9SJohnathan Mantey     }
47449c53ac9SJohnathan Mantey 
4757f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
47649c53ac9SJohnathan Mantey     {
47749c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
47849c53ac9SJohnathan Mantey         {
47911ba3979SEd Tanous             if (sensor.starts_with(type))
48049c53ac9SJohnathan Mantey             {
48149c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
48249c53ac9SJohnathan Mantey             }
48349c53ac9SJohnathan Mantey         }
48449c53ac9SJohnathan Mantey     }
48549c53ac9SJohnathan Mantey }
48649c53ac9SJohnathan Mantey 
4877f1cc26dSEd Tanous /*
4887f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4897f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4907f1cc26dSEd Tanous  *
4917f1cc26dSEd Tanous  * */
4927f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4937f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4947f1cc26dSEd Tanous {
4957f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4967f1cc26dSEd Tanous     {
4977f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4987f1cc26dSEd Tanous     }
4997f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
5007f1cc26dSEd Tanous     {
5017f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
5027f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
5037f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
5047f1cc26dSEd Tanous     }
5057f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
5067f1cc26dSEd Tanous     {
5077f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
5087f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
5097f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
5107f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5117f1cc26dSEd Tanous     }
5127f1cc26dSEd Tanous 
5137f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5147f1cc26dSEd Tanous     {
5157f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5167f1cc26dSEd Tanous     }
5177f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5187f1cc26dSEd Tanous }
5197f1cc26dSEd Tanous 
52049c53ac9SJohnathan Mantey /**
52108777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
522588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
52308777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
52408777fb0SLewanczyk, Dawid  */
52508777fb0SLewanczyk, Dawid template <typename Callback>
5267f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5277f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
528cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
529cf9e417dSEd Tanous                 Callback&& callback)
5301abe55efSEd Tanous {
53162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5327a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
53349c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
534adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5357a1dbc48SGeorge Liu 
5367a1dbc48SGeorge Liu     // Get the Chassis Collection
5377a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5387a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5398cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), asyncResp,
5407f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5417f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5427a1dbc48SGeorge Liu             const boost::system::error_code& ec,
543002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
54462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5451abe55efSEd Tanous         if (ec)
5461abe55efSEd Tanous         {
54762598e31SEd Tanous             BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5487f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
54908777fb0SLewanczyk, Dawid             return;
55008777fb0SLewanczyk, Dawid         }
55149c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
55249c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5531abe55efSEd Tanous         {
55428aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
555f8fe53e7SEd Tanous             std::string chassisName = path.filename();
55628aa8de5SGeorge Liu             if (chassisName.empty())
5571abe55efSEd Tanous             {
55862598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
559daf36e2eSEd Tanous                 continue;
560daf36e2eSEd Tanous             }
5617f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5621abe55efSEd Tanous             {
56349c53ac9SJohnathan Mantey                 chassisPath = &chassis;
56449c53ac9SJohnathan Mantey                 break;
565daf36e2eSEd Tanous             }
56649c53ac9SJohnathan Mantey         }
56749c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5681abe55efSEd Tanous         {
5697f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
57049c53ac9SJohnathan Mantey             return;
5711abe55efSEd Tanous         }
5727f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
57308777fb0SLewanczyk, Dawid 
574ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
575ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
57695a3ecadSAnthony Wilson 
5778fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5788fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5796c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5806c3e9451SGeorge Liu             sensorPath,
5817f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
5828cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
5838b24275dSEd Tanous                 const boost::system::error_code& ec2,
5846c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
5858b24275dSEd Tanous             if (ec2)
58649c53ac9SJohnathan Mantey             {
5878b24275dSEd Tanous                 if (ec2.value() != EBADR)
58849c53ac9SJohnathan Mantey                 {
5897f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
59049c53ac9SJohnathan Mantey                     return;
59149c53ac9SJohnathan Mantey                 }
59249c53ac9SJohnathan Mantey             }
593fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
594fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5957f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5967f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
59762598e31SEd Tanous             BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
59849c53ac9SJohnathan Mantey             callback(culledSensorList);
5991e1e598dSJonathan Doman         });
6007a1dbc48SGeorge Liu     });
60162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
60208777fb0SLewanczyk, Dawid }
60308777fb0SLewanczyk, Dawid 
60408777fb0SLewanczyk, Dawid /**
605adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
606adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
607aaf08ac7SMatt Simmering  * @param sensorAvailable Boolean representing if D-Bus sensor is marked as
608aaf08ac7SMatt Simmering  * available.
609adc4f0dbSShawn McCarney  * @return State value for inventory item.
61034dd179eSJames Feist  */
611aaf08ac7SMatt Simmering inline resource::State getState(const InventoryItem* inventoryItem,
612aaf08ac7SMatt Simmering                                 const bool sensorAvailable)
613adc4f0dbSShawn McCarney {
614adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
615adc4f0dbSShawn McCarney     {
616aaf08ac7SMatt Simmering         return resource::State::Absent;
617adc4f0dbSShawn McCarney     }
61834dd179eSJames Feist 
619aaf08ac7SMatt Simmering     if (!sensorAvailable)
620aaf08ac7SMatt Simmering     {
621aaf08ac7SMatt Simmering         return resource::State::UnavailableOffline;
622aaf08ac7SMatt Simmering     }
623aaf08ac7SMatt Simmering 
624aaf08ac7SMatt Simmering     return resource::State::Enabled;
625adc4f0dbSShawn McCarney }
626adc4f0dbSShawn McCarney 
627adc4f0dbSShawn McCarney /**
628adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
629adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6301d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
631adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
632adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
633adc4f0dbSShawn McCarney  * @return Health value for sensor.
634adc4f0dbSShawn McCarney  */
6351d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6361d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
637adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
63834dd179eSJames Feist {
639adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
640adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
641adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
642adc4f0dbSShawn McCarney     std::string currentHealth;
643adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
644adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
645adc4f0dbSShawn McCarney     {
646adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
647adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
648adc4f0dbSShawn McCarney         {
649adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
650adc4f0dbSShawn McCarney             if (health != nullptr)
651adc4f0dbSShawn McCarney             {
652adc4f0dbSShawn McCarney                 currentHealth = *health;
653adc4f0dbSShawn McCarney             }
654adc4f0dbSShawn McCarney         }
655adc4f0dbSShawn McCarney     }
656adc4f0dbSShawn McCarney 
657adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
658adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
659adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
660adc4f0dbSShawn McCarney     {
661adc4f0dbSShawn McCarney         return "Critical";
662adc4f0dbSShawn McCarney     }
663adc4f0dbSShawn McCarney 
664c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
665c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
666c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
667c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
668711ac7a9SEd Tanous 
669c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
670c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
671c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
672c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
673c1343bf6SKrzysztof Grobelny         warningAlarmLow);
674c1343bf6SKrzysztof Grobelny 
675c1343bf6SKrzysztof Grobelny     if (success)
67634dd179eSJames Feist     {
677c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
678c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
679c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
68034dd179eSJames Feist         {
68134dd179eSJames Feist             return "Critical";
68234dd179eSJames Feist         }
68334dd179eSJames Feist     }
68434dd179eSJames Feist 
685adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
686adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
687adc4f0dbSShawn McCarney     {
688adc4f0dbSShawn McCarney         return "Critical";
689adc4f0dbSShawn McCarney     }
690adc4f0dbSShawn McCarney 
691adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
692adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
693adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
694adc4f0dbSShawn McCarney     {
695adc4f0dbSShawn McCarney         return "Warning";
696adc4f0dbSShawn McCarney     }
697adc4f0dbSShawn McCarney 
698c1343bf6SKrzysztof Grobelny     if (success)
699c1343bf6SKrzysztof Grobelny     {
700adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
701c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
702c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
70334dd179eSJames Feist         {
704ebe4d91eSEd Tanous             return "Warning";
70534dd179eSJames Feist         }
70634dd179eSJames Feist     }
707adc4f0dbSShawn McCarney 
70834dd179eSJames Feist     return "OK";
70934dd179eSJames Feist }
71034dd179eSJames Feist 
71123a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
712d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
713d500549bSAnthony Wilson {
714d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
715d500549bSAnthony Wilson     {
716d500549bSAnthony Wilson         switch (inventoryItem->ledState)
717d500549bSAnthony Wilson         {
718d500549bSAnthony Wilson             case LedState::OFF:
719*539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Off;
720d500549bSAnthony Wilson                 break;
721d500549bSAnthony Wilson             case LedState::ON:
722*539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Lit;
723d500549bSAnthony Wilson                 break;
724d500549bSAnthony Wilson             case LedState::BLINK:
725*539d8c6bSEd Tanous                 sensorJson["IndicatorLED"] = resource::IndicatorLED::Blinking;
726d500549bSAnthony Wilson                 break;
7274da0490bSEd Tanous             default:
728d500549bSAnthony Wilson                 break;
729d500549bSAnthony Wilson         }
730d500549bSAnthony Wilson     }
731d500549bSAnthony Wilson }
732d500549bSAnthony Wilson 
73334dd179eSJames Feist /**
73408777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
73508777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
736274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
73708777fb0SLewanczyk, Dawid  * build
7388ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
7391d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7401d7c0054SEd Tanous  * from.
7411d7c0054SEd Tanous  * @param sensorJson  The json object to fill
742adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
743adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
74408777fb0SLewanczyk, Dawid  */
7451d7c0054SEd Tanous inline void objectPropertiesToJson(
7461d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7471d7c0054SEd Tanous     std::string_view chassisSubNode,
7481d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
74981ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7501abe55efSEd Tanous {
7511d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
752adc4f0dbSShawn McCarney     {
753c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
7543544d2a7SEd Tanous         auto remove = std::ranges::remove(subNodeEscaped, '_');
7553544d2a7SEd Tanous         subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
756c1d019a6SEd Tanous 
757c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
758c1d019a6SEd Tanous         // including power sensors.
759c1d019a6SEd Tanous         subNodeEscaped += '_';
760c1d019a6SEd Tanous         subNodeEscaped += sensorName;
761c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
762c1d019a6SEd Tanous 
7631d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7641d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7651d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
76695a3ecadSAnthony Wilson     }
76795a3ecadSAnthony Wilson     else if (sensorType != "power")
76895a3ecadSAnthony Wilson     {
76995a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
77095a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
77195a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7721d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7731d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7741d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
775adc4f0dbSShawn McCarney     }
776e742b6ccSEd Tanous 
777aaf08ac7SMatt Simmering     const bool* checkAvailable = nullptr;
778aaf08ac7SMatt Simmering     bool available = true;
779aaf08ac7SMatt Simmering     const bool success = sdbusplus::unpackPropertiesNoThrow(
780aaf08ac7SMatt Simmering         dbus_utils::UnpackErrorPrinter(), propertiesDict, "Available",
781aaf08ac7SMatt Simmering         checkAvailable);
782aaf08ac7SMatt Simmering     if (!success)
783aaf08ac7SMatt Simmering     {
784aaf08ac7SMatt Simmering         messages::internalError();
785aaf08ac7SMatt Simmering     }
786aaf08ac7SMatt Simmering     if (checkAvailable != nullptr)
787aaf08ac7SMatt Simmering     {
788aaf08ac7SMatt Simmering         available = *checkAvailable;
789aaf08ac7SMatt Simmering     }
790aaf08ac7SMatt Simmering 
791aaf08ac7SMatt Simmering     sensorJson["Status"]["State"] = getState(inventoryItem, available);
79289492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
79389492a15SPatrick Williams                                                inventoryItem);
79408777fb0SLewanczyk, Dawid 
79508777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
79608777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
79708777fb0SLewanczyk, Dawid     // that require integers, not floats.
79808777fb0SLewanczyk, Dawid     bool forceToInt = false;
79908777fb0SLewanczyk, Dawid 
8003929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
8011d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
80295a3ecadSAnthony Wilson     {
8032a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
804c2bf7f99SWludzik, Jozef 
8050ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
8060ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
80795a3ecadSAnthony Wilson         {
80862598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
80962598e31SEd Tanous                              sensorType);
81095a3ecadSAnthony Wilson         }
811c2bf7f99SWludzik, Jozef         else
81295a3ecadSAnthony Wilson         {
813c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
81495a3ecadSAnthony Wilson         }
815c2bf7f99SWludzik, Jozef 
8161d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
817c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
818f8ede15eSAdrian Ambrożewicz         {
81962598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
82062598e31SEd Tanous                              sensorType);
821c2bf7f99SWludzik, Jozef         }
822c2bf7f99SWludzik, Jozef         else
823c2bf7f99SWludzik, Jozef         {
824c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
825f8ede15eSAdrian Ambrożewicz         }
82695a3ecadSAnthony Wilson     }
82795a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8281abe55efSEd Tanous     {
8293929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
83081ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
83108777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
83208777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8331abe55efSEd Tanous     }
8341abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8351abe55efSEd Tanous     {
8363929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
837*539d8c6bSEd Tanous         sensorJson["ReadingUnits"] = thermal::ReadingUnits::RPM;
83881ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
83981ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
84008777fb0SLewanczyk, Dawid         forceToInt = true;
8411abe55efSEd Tanous     }
8426f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8436f6d0d32SEd Tanous     {
8443929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
845*539d8c6bSEd Tanous         sensorJson["ReadingUnits"] = thermal::ReadingUnits::Percent;
84681ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
84781ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8486f6d0d32SEd Tanous         forceToInt = true;
8496f6d0d32SEd Tanous     }
8501abe55efSEd Tanous     else if (sensorType == "voltage")
8511abe55efSEd Tanous     {
8523929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
85381ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8541abe55efSEd Tanous     }
8552474adfaSEd Tanous     else if (sensorType == "power")
8562474adfaSEd Tanous     {
85718f8f608SEd Tanous         std::string lower;
85818f8f608SEd Tanous         std::ranges::transform(sensorName, std::back_inserter(lower),
85918f8f608SEd Tanous                                bmcweb::asciiToLower);
86018f8f608SEd Tanous         if (lower == "total_power")
861028f7ebcSEddie James         {
86281ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8637ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8647ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
86581ce609eSEd Tanous             sensorJson["MemberId"] = "0";
86681ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8673929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
868028f7ebcSEddie James         }
86918f8f608SEd Tanous         else if (lower.find("input") != std::string::npos)
87049c53ac9SJohnathan Mantey         {
8713929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
87249c53ac9SJohnathan Mantey         }
87349c53ac9SJohnathan Mantey         else
87449c53ac9SJohnathan Mantey         {
8753929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
87649c53ac9SJohnathan Mantey         }
8772474adfaSEd Tanous     }
8781abe55efSEd Tanous     else
8791abe55efSEd Tanous     {
88062598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
88108777fb0SLewanczyk, Dawid         return;
88208777fb0SLewanczyk, Dawid     }
88308777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8843929aca1SAnthony Wilson     std::vector<
8853929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8863929aca1SAnthony Wilson         properties;
88708777fb0SLewanczyk, Dawid     properties.reserve(7);
88808777fb0SLewanczyk, Dawid 
88908777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
890de629b6eSShawn McCarney 
8911d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8923929aca1SAnthony Wilson     {
8933929aca1SAnthony Wilson         properties.emplace_back(
8943929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8953929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8963929aca1SAnthony Wilson         properties.emplace_back(
8973929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8983929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8993929aca1SAnthony Wilson         properties.emplace_back(
9003929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
9013929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
9023929aca1SAnthony Wilson         properties.emplace_back(
9033929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
9043929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
9053929aca1SAnthony Wilson     }
9063929aca1SAnthony Wilson     else if (sensorType != "power")
907de629b6eSShawn McCarney     {
90808777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9093929aca1SAnthony Wilson                                 "WarningHigh",
9103929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
91108777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9123929aca1SAnthony Wilson                                 "WarningLow",
9133929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
91408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9153929aca1SAnthony Wilson                                 "CriticalHigh",
9163929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
91708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9183929aca1SAnthony Wilson                                 "CriticalLow",
9193929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
920de629b6eSShawn McCarney     }
92108777fb0SLewanczyk, Dawid 
9222474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
9232474adfaSEd Tanous 
9241d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
92595a3ecadSAnthony Wilson     {
92695a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9273929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
92895a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9293929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
93051c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
93151c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
93295a3ecadSAnthony Wilson     }
93395a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9341abe55efSEd Tanous     {
93508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9363929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
93708777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9383929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9391abe55efSEd Tanous     }
940adc4f0dbSShawn McCarney     else if (sensorType != "power")
9411abe55efSEd Tanous     {
94208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9433929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
94408777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9453929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
94608777fb0SLewanczyk, Dawid     }
94708777fb0SLewanczyk, Dawid 
9483929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9493929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9501abe55efSEd Tanous     {
9511d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
952711ac7a9SEd Tanous         {
953711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
954711ac7a9SEd Tanous             {
955711ac7a9SEd Tanous                 continue;
956711ac7a9SEd Tanous             }
9573929aca1SAnthony Wilson 
9583929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9593929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9603929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9613929aca1SAnthony Wilson 
962abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
96340e4f380SEd Tanous             if (doubleValue == nullptr)
9641abe55efSEd Tanous             {
96562598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9666f6d0d32SEd Tanous                 continue;
96708777fb0SLewanczyk, Dawid             }
968283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
969283860f5SEd Tanous             {
970283860f5SEd Tanous                 if (valueName == "Value")
971283860f5SEd Tanous                 {
972283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
973283860f5SEd Tanous                     // them to null in the json response.
974283860f5SEd Tanous                     sensorJson[key] = nullptr;
975283860f5SEd Tanous                     continue;
976283860f5SEd Tanous                 }
97762598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
97862598e31SEd Tanous                                    valueName, *doubleValue);
979283860f5SEd Tanous                 continue;
980283860f5SEd Tanous             }
9816f6d0d32SEd Tanous             if (forceToInt)
9826f6d0d32SEd Tanous             {
98340e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9846f6d0d32SEd Tanous             }
9856f6d0d32SEd Tanous             else
9866f6d0d32SEd Tanous             {
98740e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
98808777fb0SLewanczyk, Dawid             }
98908777fb0SLewanczyk, Dawid         }
99008777fb0SLewanczyk, Dawid     }
99108777fb0SLewanczyk, Dawid }
99208777fb0SLewanczyk, Dawid 
9931d7c0054SEd Tanous /**
9941d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9951d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9961d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9971d7c0054SEd Tanous  * build
9988ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
9991d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
10001d7c0054SEd Tanous  * interfaces to be built from
10011d7c0054SEd Tanous  * @param sensorJson  The json object to fill
10021d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
10031d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
10041d7c0054SEd Tanous  */
10051d7c0054SEd Tanous inline void objectInterfacesToJson(
10061d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
10071d7c0054SEd Tanous     const std::string& chassisSubNode,
100880f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
10091d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
10101d7c0054SEd Tanous {
10111d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
10121d7c0054SEd Tanous     {
10131d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
10141d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
10151d7c0054SEd Tanous     }
101662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
10171d7c0054SEd Tanous }
10181d7c0054SEd Tanous 
1019b5a76932SEd Tanous inline void populateFanRedundancy(
1020b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
10218bd25ccdSJames Feist {
1022e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1023e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
1024e99073f5SGeorge Liu     dbus::utility::getSubTree(
1025e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
1026b9d36b47SEd Tanous         [sensorsAsyncResp](
1027e99073f5SGeorge Liu             const boost::system::error_code& ec,
1028b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
10298bd25ccdSJames Feist         if (ec)
10308bd25ccdSJames Feist         {
10318bd25ccdSJames Feist             return; // don't have to have this interface
10328bd25ccdSJames Feist         }
10336c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
1034e278c18fSEd Tanous                  pathPair : resp)
10358bd25ccdSJames Feist         {
1036e278c18fSEd Tanous             const std::string& path = pathPair.first;
10376c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
10388bd25ccdSJames Feist             if (objDict.empty())
10398bd25ccdSJames Feist             {
10408bd25ccdSJames Feist                 continue; // this should be impossible
10418bd25ccdSJames Feist             }
10428bd25ccdSJames Feist 
10438bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10446c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
10456c3e9451SGeorge Liu                 path + "/chassis",
10466c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
10478b24275dSEd Tanous                     const boost::system::error_code& ec2,
10486c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
10498b24275dSEd Tanous                 if (ec2)
10508bd25ccdSJames Feist                 {
10518bd25ccdSJames Feist                     return; // if they don't have an association we
10528bd25ccdSJames Feist                             // can't tell what chassis is
10538bd25ccdSJames Feist                 }
10543544d2a7SEd Tanous                 auto found = std::ranges::find_if(
10553544d2a7SEd Tanous                     endpoints, [sensorsAsyncResp](const std::string& entry) {
1056002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10578bd25ccdSJames Feist                            std::string::npos;
10588bd25ccdSJames Feist                 });
10598bd25ccdSJames Feist 
10601e1e598dSJonathan Doman                 if (found == endpoints.end())
10618bd25ccdSJames Feist                 {
10628bd25ccdSJames Feist                     return;
10638bd25ccdSJames Feist                 }
106486d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
106586d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
106686d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10678bd25ccdSJames Feist                     [path, sensorsAsyncResp](
10688b24275dSEd Tanous                         const boost::system::error_code& ec3,
106986d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
10708b24275dSEd Tanous                     if (ec3)
10718bd25ccdSJames Feist                     {
10728bd25ccdSJames Feist                         return; // don't have to have this
10738bd25ccdSJames Feist                                 // interface
10748bd25ccdSJames Feist                     }
10758bd25ccdSJames Feist 
107686d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
107786d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
107886d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
107986d89ed7SKrzysztof Grobelny 
108086d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
108186d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
108286d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
108386d89ed7SKrzysztof Grobelny                         collection, "Status", status);
108486d89ed7SKrzysztof Grobelny 
108586d89ed7SKrzysztof Grobelny                     if (!success)
108686d89ed7SKrzysztof Grobelny                     {
108786d89ed7SKrzysztof Grobelny                         messages::internalError(
108886d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
108986d89ed7SKrzysztof Grobelny                         return;
109086d89ed7SKrzysztof Grobelny                     }
109186d89ed7SKrzysztof Grobelny 
109286d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
109386d89ed7SKrzysztof Grobelny                         status == nullptr)
10948bd25ccdSJames Feist                     {
109562598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid redundancy interface");
10968bd25ccdSJames Feist                         messages::internalError(
10978d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10988bd25ccdSJames Feist                         return;
10998bd25ccdSJames Feist                     }
11008bd25ccdSJames Feist 
1101002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
110228aa8de5SGeorge Liu                     std::string name = objectPath.filename();
110328aa8de5SGeorge Liu                     if (name.empty())
11048bd25ccdSJames Feist                     {
11058bd25ccdSJames Feist                         // this should be impossible
11068bd25ccdSJames Feist                         messages::internalError(
11078d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
11088bd25ccdSJames Feist                         return;
11098bd25ccdSJames Feist                     }
111018f8f608SEd Tanous                     std::ranges::replace(name, '_', ' ');
11118bd25ccdSJames Feist 
11128bd25ccdSJames Feist                     std::string health;
11138bd25ccdSJames Feist 
111411ba3979SEd Tanous                     if (status->ends_with("Full"))
11158bd25ccdSJames Feist                     {
11168bd25ccdSJames Feist                         health = "OK";
11178bd25ccdSJames Feist                     }
111811ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
11198bd25ccdSJames Feist                     {
11208bd25ccdSJames Feist                         health = "Warning";
11218bd25ccdSJames Feist                     }
11228bd25ccdSJames Feist                     else
11238bd25ccdSJames Feist                     {
11248bd25ccdSJames Feist                         health = "Critical";
11258bd25ccdSJames Feist                     }
11261476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
11278bd25ccdSJames Feist                     const auto& fanRedfish =
1128002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
11298bd25ccdSJames Feist                     for (const std::string& item : *collection)
11308bd25ccdSJames Feist                     {
11318a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
11328a592810SEd Tanous                         std::string itemName = itemPath.filename();
113328aa8de5SGeorge Liu                         if (itemName.empty())
113428aa8de5SGeorge Liu                         {
113528aa8de5SGeorge Liu                             continue;
113628aa8de5SGeorge Liu                         }
11378bd25ccdSJames Feist                         /*
11388bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11398bd25ccdSJames Feist                         std::replace(itemName.begin(),
11408bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
11413544d2a7SEd Tanous                         auto schemaItem = std::ranges::find_if(
11423544d2a7SEd Tanous                             fanRedfish, [itemName](const nlohmann::json& fan) {
11433e35c761SGeorge Liu                             return fan["Name"] == itemName;
11448bd25ccdSJames Feist                         });
11458bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11468bd25ccdSJames Feist                         {
11478a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11488a592810SEd Tanous                             collectionId["@odata.id"] =
11491476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11501476687dSEd Tanous                             redfishCollection.emplace_back(
11518a592810SEd Tanous                                 std::move(collectionId));
11528bd25ccdSJames Feist                         }
11538bd25ccdSJames Feist                         else
11548bd25ccdSJames Feist                         {
115562598e31SEd Tanous                             BMCWEB_LOG_ERROR("failed to find fan in schema");
11568bd25ccdSJames Feist                             messages::internalError(
11578d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11588bd25ccdSJames Feist                             return;
11598bd25ccdSJames Feist                         }
11608bd25ccdSJames Feist                     }
11618bd25ccdSJames Feist 
116289492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
116326f6976fSEd Tanous                                               ? 0
116489492a15SPatrick Williams                                               : collection->size() -
116589492a15SPatrick Williams                                                     *allowedFailures;
1166002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11678bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11681476687dSEd Tanous 
11691476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1170ef4c65b7SEd Tanous                     boost::urls::url url =
1171ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1172ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1173eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1174eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1175eddfc437SWilly Tu                                          .to_string());
1176eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1177002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11781476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
1179*539d8c6bSEd Tanous                     redundancy["Mode"] = redundancy::RedundancyType::NPlusM;
11801476687dSEd Tanous                     redundancy["Name"] = name;
11811476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11821476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
1183*539d8c6bSEd Tanous                     redundancy["Status"]["State"] = resource::State::Enabled;
11841476687dSEd Tanous 
1185b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
118686d89ed7SKrzysztof Grobelny                 });
11871e1e598dSJonathan Doman             });
11888bd25ccdSJames Feist         }
1189e99073f5SGeorge Liu     });
11908bd25ccdSJames Feist }
11918bd25ccdSJames Feist 
1192b5a76932SEd Tanous inline void
119381ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
119449c53ac9SJohnathan Mantey {
11958d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
119649c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
119781ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
119849c53ac9SJohnathan Mantey     {
119949c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
120049c53ac9SJohnathan Mantey     }
120149c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
120249c53ac9SJohnathan Mantey     {
120349c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
120449c53ac9SJohnathan Mantey         if (entry != response.end())
120549c53ac9SJohnathan Mantey         {
120649c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
120702cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
120849c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
120949c53ac9SJohnathan Mantey             });
121049c53ac9SJohnathan Mantey 
121149c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
121249c53ac9SJohnathan Mantey             size_t count = 0;
121349c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
121449c53ac9SJohnathan Mantey             {
121549c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
121649c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
121749c53ac9SJohnathan Mantey                 {
121849c53ac9SJohnathan Mantey                     continue;
121949c53ac9SJohnathan Mantey                 }
122049c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
122149c53ac9SJohnathan Mantey                 if (value != nullptr)
122249c53ac9SJohnathan Mantey                 {
1223eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
12243e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
122549c53ac9SJohnathan Mantey                     count++;
122681ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
122749c53ac9SJohnathan Mantey                 }
122849c53ac9SJohnathan Mantey             }
122949c53ac9SJohnathan Mantey         }
123049c53ac9SJohnathan Mantey     }
123149c53ac9SJohnathan Mantey }
123249c53ac9SJohnathan Mantey 
123308777fb0SLewanczyk, Dawid /**
1234adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1235adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1236adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1237adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12388fb49dd6SShawn McCarney  */
123923a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1240b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1241adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12428fb49dd6SShawn McCarney {
1243adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12448fb49dd6SShawn McCarney     {
1245adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12468fb49dd6SShawn McCarney         {
1247adc4f0dbSShawn McCarney             return &inventoryItem;
12488fb49dd6SShawn McCarney         }
12498fb49dd6SShawn McCarney     }
12508fb49dd6SShawn McCarney     return nullptr;
12518fb49dd6SShawn McCarney }
12528fb49dd6SShawn McCarney 
12538fb49dd6SShawn McCarney /**
1254adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1255adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1256adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1257adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12588fb49dd6SShawn McCarney  */
125923a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1260b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1261adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1262adc4f0dbSShawn McCarney {
1263adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1264adc4f0dbSShawn McCarney     {
1265db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1266adc4f0dbSShawn McCarney         {
1267adc4f0dbSShawn McCarney             return &inventoryItem;
1268adc4f0dbSShawn McCarney         }
1269adc4f0dbSShawn McCarney     }
1270adc4f0dbSShawn McCarney     return nullptr;
1271adc4f0dbSShawn McCarney }
1272adc4f0dbSShawn McCarney 
1273adc4f0dbSShawn McCarney /**
1274d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1275d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1276d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1277d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1278d500549bSAnthony Wilson  */
1279d500549bSAnthony Wilson inline InventoryItem*
1280d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1281d500549bSAnthony Wilson                             const std::string& ledObjPath)
1282d500549bSAnthony Wilson {
1283d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1284d500549bSAnthony Wilson     {
1285d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1286d500549bSAnthony Wilson         {
1287d500549bSAnthony Wilson             return &inventoryItem;
1288d500549bSAnthony Wilson         }
1289d500549bSAnthony Wilson     }
1290d500549bSAnthony Wilson     return nullptr;
1291d500549bSAnthony Wilson }
1292d500549bSAnthony Wilson 
1293d500549bSAnthony Wilson /**
1294adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1295adc4f0dbSShawn McCarney  *
1296adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1297adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1298adc4f0dbSShawn McCarney  * added to the vector.
1299adc4f0dbSShawn McCarney  *
1300adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1301adc4f0dbSShawn McCarney  * InventoryItem.
1302adc4f0dbSShawn McCarney  *
1303adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1304adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1305adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1306adc4f0dbSShawn McCarney  */
1307b5a76932SEd Tanous inline void addInventoryItem(
1308b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1309b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1310adc4f0dbSShawn McCarney {
1311adc4f0dbSShawn McCarney     // Look for inventory item in vector
131289492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
131389492a15SPatrick Williams                                                      invItemObjPath);
1314adc4f0dbSShawn McCarney 
1315adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1316adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1317adc4f0dbSShawn McCarney     {
1318adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1319adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1320adc4f0dbSShawn McCarney     }
1321adc4f0dbSShawn McCarney 
1322adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1323adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1324adc4f0dbSShawn McCarney }
1325adc4f0dbSShawn McCarney 
1326adc4f0dbSShawn McCarney /**
1327adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1328adc4f0dbSShawn McCarney  *
1329adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1330adc4f0dbSShawn McCarney  * specified InventoryItem.
1331adc4f0dbSShawn McCarney  *
1332adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1333adc4f0dbSShawn McCarney  * response.
1334adc4f0dbSShawn McCarney  *
1335adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1336adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1337adc4f0dbSShawn McCarney  * for the specified inventory item.
1338adc4f0dbSShawn McCarney  */
133923a21a1cSEd Tanous inline void storeInventoryItemData(
1340adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
134180f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13428fb49dd6SShawn McCarney {
1343adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1344711ac7a9SEd Tanous 
13459eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13468fb49dd6SShawn McCarney     {
1347711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13488fb49dd6SShawn McCarney         {
13499eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1350711ac7a9SEd Tanous             {
1351711ac7a9SEd Tanous                 if (name == "Present")
1352711ac7a9SEd Tanous                 {
1353711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1354adc4f0dbSShawn McCarney                     if (value != nullptr)
13558fb49dd6SShawn McCarney                     {
1356adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13578fb49dd6SShawn McCarney                     }
13588fb49dd6SShawn McCarney                 }
13598fb49dd6SShawn McCarney             }
1360711ac7a9SEd Tanous         }
1361adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1362711ac7a9SEd Tanous 
1363711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13648fb49dd6SShawn McCarney         {
1365adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13668fb49dd6SShawn McCarney         }
1367adc4f0dbSShawn McCarney 
1368adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1369711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1370adc4f0dbSShawn McCarney         {
13719eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1372711ac7a9SEd Tanous             {
1373711ac7a9SEd Tanous                 if (name == "Manufacturer")
1374adc4f0dbSShawn McCarney                 {
1375adc4f0dbSShawn McCarney                     const std::string* value =
1376711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1377adc4f0dbSShawn McCarney                     if (value != nullptr)
1378adc4f0dbSShawn McCarney                     {
1379adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1380adc4f0dbSShawn McCarney                     }
1381adc4f0dbSShawn McCarney                 }
1382711ac7a9SEd Tanous                 if (name == "Model")
1383adc4f0dbSShawn McCarney                 {
1384adc4f0dbSShawn McCarney                     const std::string* value =
1385711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1386adc4f0dbSShawn McCarney                     if (value != nullptr)
1387adc4f0dbSShawn McCarney                     {
1388adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1389adc4f0dbSShawn McCarney                     }
1390adc4f0dbSShawn McCarney                 }
1391711ac7a9SEd Tanous                 if (name == "SerialNumber")
1392adc4f0dbSShawn McCarney                 {
1393adc4f0dbSShawn McCarney                     const std::string* value =
1394711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1395adc4f0dbSShawn McCarney                     if (value != nullptr)
1396adc4f0dbSShawn McCarney                     {
1397adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1398adc4f0dbSShawn McCarney                     }
1399adc4f0dbSShawn McCarney                 }
1400711ac7a9SEd Tanous                 if (name == "PartNumber")
1401711ac7a9SEd Tanous                 {
1402711ac7a9SEd Tanous                     const std::string* value =
1403711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1404711ac7a9SEd Tanous                     if (value != nullptr)
1405711ac7a9SEd Tanous                     {
1406711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1407711ac7a9SEd Tanous                     }
1408711ac7a9SEd Tanous                 }
1409711ac7a9SEd Tanous             }
1410adc4f0dbSShawn McCarney         }
1411adc4f0dbSShawn McCarney 
1412711ac7a9SEd Tanous         if (interface ==
1413711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1414adc4f0dbSShawn McCarney         {
14159eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1416adc4f0dbSShawn McCarney             {
1417711ac7a9SEd Tanous                 if (name == "Functional")
1418711ac7a9SEd Tanous                 {
1419711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1420adc4f0dbSShawn McCarney                     if (value != nullptr)
1421adc4f0dbSShawn McCarney                     {
1422adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
14238fb49dd6SShawn McCarney                     }
14248fb49dd6SShawn McCarney                 }
14258fb49dd6SShawn McCarney             }
14268fb49dd6SShawn McCarney         }
1427711ac7a9SEd Tanous     }
1428711ac7a9SEd Tanous }
14298fb49dd6SShawn McCarney 
14308fb49dd6SShawn McCarney /**
1431adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
14328fb49dd6SShawn McCarney  *
1433adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1434adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1435adc4f0dbSShawn McCarney  * inventoryItems vector.
14368fb49dd6SShawn McCarney  *
1437adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1438adc4f0dbSShawn McCarney  * response.
1439adc4f0dbSShawn McCarney  *
1440adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1441adc4f0dbSShawn McCarney  * been obtained.
1442adc4f0dbSShawn McCarney  *
1443adc4f0dbSShawn McCarney  * The callback must have the following signature:
1444adc4f0dbSShawn McCarney  *   @code
1445d500549bSAnthony Wilson  *   callback(void)
1446adc4f0dbSShawn McCarney  *   @endcode
1447adc4f0dbSShawn McCarney  *
1448adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1449adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1450adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14518fb49dd6SShawn McCarney  *
14528fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1453adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1454adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14558fb49dd6SShawn McCarney  * implements ObjectManager.
1456adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1457adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1458adc4f0dbSShawn McCarney  * in recursive calls to this function.
14598fb49dd6SShawn McCarney  */
1460adc4f0dbSShawn McCarney template <typename Callback>
1461adc4f0dbSShawn McCarney static void getInventoryItemsData(
14628fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1463adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1464d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1465d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14668fb49dd6SShawn McCarney {
146762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14688fb49dd6SShawn McCarney 
1469adc4f0dbSShawn McCarney     // If no more connections left, call callback
1470adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14718fb49dd6SShawn McCarney     {
1472d500549bSAnthony Wilson         callback();
147362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1474adc4f0dbSShawn McCarney         return;
1475adc4f0dbSShawn McCarney     }
1476adc4f0dbSShawn McCarney 
1477adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1478fe04d49cSNan Zhou     auto it = invConnections->begin();
1479fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1480adc4f0dbSShawn McCarney     if (it != invConnections->end())
1481adc4f0dbSShawn McCarney     {
1482adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1483adc4f0dbSShawn McCarney 
14845eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14855eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14865eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14875eb468daSGeorge Liu             invConnection, path,
14885eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
14898cb2c024SEd Tanous              callback = std::forward<Callback>(callback), invConnectionsIndex](
14905e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
149102cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
149262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
14938fb49dd6SShawn McCarney             if (ec)
14948fb49dd6SShawn McCarney             {
149562598e31SEd Tanous                 BMCWEB_LOG_ERROR(
149662598e31SEd Tanous                     "getInventoryItemsData respHandler DBus error {}", ec);
14978d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14988fb49dd6SShawn McCarney                 return;
14998fb49dd6SShawn McCarney             }
15008fb49dd6SShawn McCarney 
15018fb49dd6SShawn McCarney             // Loop through returned object paths
15028fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
15038fb49dd6SShawn McCarney             {
15048fb49dd6SShawn McCarney                 const std::string& objPath =
15058fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
15068fb49dd6SShawn McCarney 
1507adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
150889492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
150989492a15SPatrick Williams                                                                  objPath);
1510adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
15118fb49dd6SShawn McCarney                 {
1512adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1513adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
15148fb49dd6SShawn McCarney                 }
15158fb49dd6SShawn McCarney             }
15168fb49dd6SShawn McCarney 
1517adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1518adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1519d0090733SEd Tanous                                   invConnections, std::move(callback),
1520d0090733SEd Tanous                                   invConnectionsIndex + 1);
1521adc4f0dbSShawn McCarney 
152262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
15235eb468daSGeorge Liu         });
15248fb49dd6SShawn McCarney     }
15258fb49dd6SShawn McCarney 
152662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
15278fb49dd6SShawn McCarney }
15288fb49dd6SShawn McCarney 
15298fb49dd6SShawn McCarney /**
1530adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
15318fb49dd6SShawn McCarney  *
1532adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1533adc4f0dbSShawn McCarney  * items that are associated with sensors.
15348fb49dd6SShawn McCarney  *
15358fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15368fb49dd6SShawn McCarney  * been obtained.
15378fb49dd6SShawn McCarney  *
15388fb49dd6SShawn McCarney  * The callback must have the following signature:
15398fb49dd6SShawn McCarney  *   @code
1540fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15418fb49dd6SShawn McCarney  *   @endcode
15428fb49dd6SShawn McCarney  *
15438fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1544adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15458fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15468fb49dd6SShawn McCarney  */
15478fb49dd6SShawn McCarney template <typename Callback>
15488fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1549b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1550b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15518fb49dd6SShawn McCarney     Callback&& callback)
15528fb49dd6SShawn McCarney {
155362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15548fb49dd6SShawn McCarney 
15558fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1556e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15578fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1558adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1559adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15608fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15618fb49dd6SShawn McCarney 
1562e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1563e99073f5SGeorge Liu     dbus::utility::getSubTree(
1564e99073f5SGeorge Liu         path, 0, interfaces,
15658cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1566002d39b4SEd Tanous          inventoryItems](
1567e99073f5SGeorge Liu             const boost::system::error_code& ec,
1568002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1569e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
157062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15718fb49dd6SShawn McCarney         if (ec)
15728fb49dd6SShawn McCarney         {
15738d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
157462598e31SEd Tanous             BMCWEB_LOG_ERROR(
157562598e31SEd Tanous                 "getInventoryItemsConnections respHandler DBus error {}", ec);
15768fb49dd6SShawn McCarney             return;
15778fb49dd6SShawn McCarney         }
15788fb49dd6SShawn McCarney 
15798fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1580fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1581fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15828fb49dd6SShawn McCarney 
15838fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15848fb49dd6SShawn McCarney         for (const std::pair<
15858fb49dd6SShawn McCarney                  std::string,
15868fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15878fb49dd6SShawn McCarney                  object : subtree)
15888fb49dd6SShawn McCarney         {
1589adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15908fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1591adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15928fb49dd6SShawn McCarney             {
15938fb49dd6SShawn McCarney                 // Store all connections to inventory item
15948fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15958fb49dd6SShawn McCarney                          objData : object.second)
15968fb49dd6SShawn McCarney                 {
15978fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15988fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15998fb49dd6SShawn McCarney                 }
16008fb49dd6SShawn McCarney             }
16018fb49dd6SShawn McCarney         }
1602d500549bSAnthony Wilson 
16038fb49dd6SShawn McCarney         callback(invConnections);
160462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1605e99073f5SGeorge Liu     });
160662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
16078fb49dd6SShawn McCarney }
16088fb49dd6SShawn McCarney 
16098fb49dd6SShawn McCarney /**
1610adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
16118fb49dd6SShawn McCarney  *
16128fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1613d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1614d500549bSAnthony Wilson  * their LEDs, if any.
16158fb49dd6SShawn McCarney  *
16168fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
16178fb49dd6SShawn McCarney  * has been obtained.
16188fb49dd6SShawn McCarney  *
16198fb49dd6SShawn McCarney  * The callback must have the following signature:
16208fb49dd6SShawn McCarney  *   @code
1621adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
16228fb49dd6SShawn McCarney  *   @endcode
16238fb49dd6SShawn McCarney  *
16248fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
16258fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
16268fb49dd6SShawn McCarney  * implements ObjectManager.
16278fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
16288fb49dd6SShawn McCarney  */
16298fb49dd6SShawn McCarney template <typename Callback>
1630adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1631b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1632fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16338fb49dd6SShawn McCarney     Callback&& callback)
16348fb49dd6SShawn McCarney {
163562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16368fb49dd6SShawn McCarney 
16375eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16385eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16395eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16405eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
16418cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
16425e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
164302cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
164462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16458fb49dd6SShawn McCarney         if (ec)
16468fb49dd6SShawn McCarney         {
164762598e31SEd Tanous             BMCWEB_LOG_ERROR(
164862598e31SEd Tanous                 "getInventoryItemAssociations respHandler DBus error {}", ec);
16498d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16508fb49dd6SShawn McCarney             return;
16518fb49dd6SShawn McCarney         }
16528fb49dd6SShawn McCarney 
1653adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1654adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1655adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1656adc4f0dbSShawn McCarney 
16578fb49dd6SShawn McCarney         // Loop through returned object paths
16588fb49dd6SShawn McCarney         std::string sensorAssocPath;
16598fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16608fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16618fb49dd6SShawn McCarney         {
16628fb49dd6SShawn McCarney             const std::string& objPath =
16638fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16648fb49dd6SShawn McCarney 
16658fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16668fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16678fb49dd6SShawn McCarney             {
16688fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16698fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16708fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16718fb49dd6SShawn McCarney                 {
16728fb49dd6SShawn McCarney                     // Get Association interface for object path
1673711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16748fb49dd6SShawn McCarney                     {
1675711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1676711ac7a9SEd Tanous                         {
1677711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1678711ac7a9SEd Tanous                             {
1679711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16808fb49dd6SShawn McCarney                                 {
16818fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16828fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1683711ac7a9SEd Tanous                                             &value);
1684711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1685711ac7a9SEd Tanous                                         !endpoints->empty())
16868fb49dd6SShawn McCarney                                     {
1687adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1688adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1689adc4f0dbSShawn McCarney                                             endpoints->front();
1690711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1691711ac7a9SEd Tanous                                                          invItemPath,
1692adc4f0dbSShawn McCarney                                                          sensorName);
16938fb49dd6SShawn McCarney                                     }
16948fb49dd6SShawn McCarney                                 }
16958fb49dd6SShawn McCarney                             }
1696711ac7a9SEd Tanous                         }
1697711ac7a9SEd Tanous                     }
16988fb49dd6SShawn McCarney                     break;
16998fb49dd6SShawn McCarney                 }
17008fb49dd6SShawn McCarney             }
17018fb49dd6SShawn McCarney         }
17028fb49dd6SShawn McCarney 
1703d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1704d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1705d500549bSAnthony Wilson         std::string inventoryAssocPath;
1706d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1707d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1708d500549bSAnthony Wilson         {
1709d500549bSAnthony Wilson             const std::string& objPath =
1710d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1711d500549bSAnthony Wilson 
1712d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1713d500549bSAnthony Wilson             {
1714d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1715d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1716d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1717d500549bSAnthony Wilson                 {
1718711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1719d500549bSAnthony Wilson                     {
1720711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1721711ac7a9SEd Tanous                         {
1722711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1723711ac7a9SEd Tanous                             {
1724711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1725d500549bSAnthony Wilson                                 {
1726d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1727d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1728711ac7a9SEd Tanous                                             &value);
1729711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1730711ac7a9SEd Tanous                                         !endpoints->empty())
1731d500549bSAnthony Wilson                                     {
1732711ac7a9SEd Tanous                                         // Add inventory item to vector
1733d500549bSAnthony Wilson                                         // Store LED path in inventory item
1734711ac7a9SEd Tanous                                         const std::string& ledPath =
1735711ac7a9SEd Tanous                                             endpoints->front();
1736d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1737d500549bSAnthony Wilson                                     }
1738d500549bSAnthony Wilson                                 }
1739d500549bSAnthony Wilson                             }
1740711ac7a9SEd Tanous                         }
1741711ac7a9SEd Tanous                     }
1742711ac7a9SEd Tanous 
1743d500549bSAnthony Wilson                     break;
1744d500549bSAnthony Wilson                 }
1745d500549bSAnthony Wilson             }
1746d500549bSAnthony Wilson         }
1747adc4f0dbSShawn McCarney         callback(inventoryItems);
174862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17495eb468daSGeorge Liu     });
17508fb49dd6SShawn McCarney 
175162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17528fb49dd6SShawn McCarney }
17538fb49dd6SShawn McCarney 
17548fb49dd6SShawn McCarney /**
1755d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1756d500549bSAnthony Wilson  *
1757d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1758d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1759d500549bSAnthony Wilson  * inventoryItems vector.
1760d500549bSAnthony Wilson  *
1761d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1762d500549bSAnthony Wilson  * response.
1763d500549bSAnthony Wilson  *
1764d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1765d500549bSAnthony Wilson  * has been obtained.
1766d500549bSAnthony Wilson  *
1767d500549bSAnthony Wilson  * The callback must have the following signature:
1768d500549bSAnthony Wilson  *   @code
176942cbe538SGunnar Mills  *   callback()
1770d500549bSAnthony Wilson  *   @endcode
1771d500549bSAnthony Wilson  *
1772d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1773d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1774d500549bSAnthony Wilson  * last asynchronous function has completed.
1775d500549bSAnthony Wilson  *
1776d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1777d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1778d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1779d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1780d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1781d500549bSAnthony Wilson  * in recursive calls to this function.
1782d500549bSAnthony Wilson  */
1783d500549bSAnthony Wilson template <typename Callback>
1784d500549bSAnthony Wilson void getInventoryLedData(
1785d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1786d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1787fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1788d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1789d500549bSAnthony Wilson {
179062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1791d500549bSAnthony Wilson 
1792d500549bSAnthony Wilson     // If no more connections left, call callback
1793d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1794d500549bSAnthony Wilson     {
179542cbe538SGunnar Mills         callback();
179662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1797d500549bSAnthony Wilson         return;
1798d500549bSAnthony Wilson     }
1799d500549bSAnthony Wilson 
1800d500549bSAnthony Wilson     // Get inventory item data from current connection
1801fe04d49cSNan Zhou     auto it = ledConnections->begin();
1802fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1803d500549bSAnthony Wilson     if (it != ledConnections->end())
1804d500549bSAnthony Wilson     {
1805d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1806d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1807d500549bSAnthony Wilson         // Response handler for Get State property
18081e1e598dSJonathan Doman         auto respHandler =
18091e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
18108cb2c024SEd Tanous              callback = std::forward<Callback>(callback), ledConnectionsIndex](
18115e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
181262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1813d500549bSAnthony Wilson             if (ec)
1814d500549bSAnthony Wilson             {
181562598e31SEd Tanous                 BMCWEB_LOG_ERROR(
181662598e31SEd Tanous                     "getInventoryLedData respHandler DBus error {}", ec);
18178d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1818d500549bSAnthony Wilson                 return;
1819d500549bSAnthony Wilson             }
1820d500549bSAnthony Wilson 
182162598e31SEd Tanous             BMCWEB_LOG_DEBUG("Led state: {}", state);
1822d500549bSAnthony Wilson             // Find inventory item with this LED object path
1823d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1824d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1825d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1826d500549bSAnthony Wilson             {
1827d500549bSAnthony Wilson                 // Store LED state in InventoryItem
182811ba3979SEd Tanous                 if (state.ends_with("On"))
1829d500549bSAnthony Wilson                 {
1830d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1831d500549bSAnthony Wilson                 }
183211ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1833d500549bSAnthony Wilson                 {
1834d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1835d500549bSAnthony Wilson                 }
183611ba3979SEd Tanous                 else if (state.ends_with("Off"))
1837d500549bSAnthony Wilson                 {
1838d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1839d500549bSAnthony Wilson                 }
1840d500549bSAnthony Wilson                 else
1841d500549bSAnthony Wilson                 {
1842d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1843d500549bSAnthony Wilson                 }
1844d500549bSAnthony Wilson             }
1845d500549bSAnthony Wilson 
1846d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1847d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1848d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1849d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1850d500549bSAnthony Wilson 
185162598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1852d500549bSAnthony Wilson         };
1853d500549bSAnthony Wilson 
1854d500549bSAnthony Wilson         // Get the State property for the current LED
18551e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18561e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18571e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18581e1e598dSJonathan Doman             std::move(respHandler));
1859d500549bSAnthony Wilson     }
1860d500549bSAnthony Wilson 
186162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1862d500549bSAnthony Wilson }
1863d500549bSAnthony Wilson 
1864d500549bSAnthony Wilson /**
1865d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1866d500549bSAnthony Wilson  *
1867d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1868d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1869d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1870d500549bSAnthony Wilson  *
1871d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1872d500549bSAnthony Wilson  * response.
1873d500549bSAnthony Wilson  *
1874d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1875d500549bSAnthony Wilson  * been obtained.
1876d500549bSAnthony Wilson  *
1877d500549bSAnthony Wilson  * The callback must have the following signature:
1878d500549bSAnthony Wilson  *   @code
187942cbe538SGunnar Mills  *   callback()
1880d500549bSAnthony Wilson  *   @endcode
1881d500549bSAnthony Wilson  *
1882d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1883d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1884d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1885d500549bSAnthony Wilson  */
1886d500549bSAnthony Wilson template <typename Callback>
1887d500549bSAnthony Wilson void getInventoryLeds(
1888d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1889d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1890d500549bSAnthony Wilson     Callback&& callback)
1891d500549bSAnthony Wilson {
189262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1893d500549bSAnthony Wilson 
1894d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1895e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1896d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1897d500549bSAnthony Wilson 
1898e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1899e99073f5SGeorge Liu     dbus::utility::getSubTree(
1900e99073f5SGeorge Liu         path, 0, interfaces,
19018cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1902002d39b4SEd Tanous          inventoryItems](
1903e99073f5SGeorge Liu             const boost::system::error_code& ec,
1904002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1905e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
190662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1907d500549bSAnthony Wilson         if (ec)
1908d500549bSAnthony Wilson         {
19098d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
191062598e31SEd Tanous             BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}", ec);
1911d500549bSAnthony Wilson             return;
1912d500549bSAnthony Wilson         }
1913d500549bSAnthony Wilson 
1914d500549bSAnthony Wilson         // Build map of LED object paths to connections
1915fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1916fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1917d500549bSAnthony Wilson 
1918d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1919d500549bSAnthony Wilson         for (const std::pair<
1920d500549bSAnthony Wilson                  std::string,
1921d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1922d500549bSAnthony Wilson                  object : subtree)
1923d500549bSAnthony Wilson         {
1924d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1925d500549bSAnthony Wilson             // items
1926d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1927d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1928d500549bSAnthony Wilson             {
1929d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1930d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1931d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
193262598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath, connection);
1933d500549bSAnthony Wilson             }
1934d500549bSAnthony Wilson         }
1935d500549bSAnthony Wilson 
1936d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1937d500549bSAnthony Wilson                             std::move(callback));
193862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1939e99073f5SGeorge Liu     });
194062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1941d500549bSAnthony Wilson }
1942d500549bSAnthony Wilson 
1943d500549bSAnthony Wilson /**
194442cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
194542cbe538SGunnar Mills  *
194642cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
194742cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
194842cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
194942cbe538SGunnar Mills  *
195042cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
195142cbe538SGunnar Mills  * response.
195242cbe538SGunnar Mills  *
195342cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
195442cbe538SGunnar Mills  * when data has been obtained.
195542cbe538SGunnar Mills  *
195642cbe538SGunnar Mills  * The callback must have the following signature:
195742cbe538SGunnar Mills  *   @code
195842cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
195942cbe538SGunnar Mills  *   @endcode
196042cbe538SGunnar Mills  *
196142cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
196242cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
196342cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
196442cbe538SGunnar Mills  *        Supply Attributes
196542cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
196642cbe538SGunnar Mills  */
196742cbe538SGunnar Mills template <typename Callback>
196842cbe538SGunnar Mills void getPowerSupplyAttributesData(
1969b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
197042cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1971fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
197242cbe538SGunnar Mills     Callback&& callback)
197342cbe538SGunnar Mills {
197462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
197542cbe538SGunnar Mills 
197642cbe538SGunnar Mills     if (psAttributesConnections.empty())
197742cbe538SGunnar Mills     {
197862598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
197942cbe538SGunnar Mills         callback(inventoryItems);
198042cbe538SGunnar Mills         return;
198142cbe538SGunnar Mills     }
198242cbe538SGunnar Mills 
198342cbe538SGunnar Mills     // Assuming just one connection (service) for now
1984fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
198542cbe538SGunnar Mills 
198642cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
198742cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
198842cbe538SGunnar Mills 
198942cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
19905a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
19918cb2c024SEd Tanous                         callback = std::forward<Callback>(callback)](
19925a39f77aSPatrick Williams                            const boost::system::error_code& ec,
19935a39f77aSPatrick Williams                            const uint32_t value) {
199462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
199542cbe538SGunnar Mills         if (ec)
199642cbe538SGunnar Mills         {
199762598e31SEd Tanous             BMCWEB_LOG_ERROR(
199862598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
19998d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
200042cbe538SGunnar Mills             return;
200142cbe538SGunnar Mills         }
200242cbe538SGunnar Mills 
200362598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
200442cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
200542cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
200642cbe538SGunnar Mills         {
200755f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
200842cbe538SGunnar Mills             {
200942cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
20101e1e598dSJonathan Doman                     static_cast<int>(value);
201142cbe538SGunnar Mills             }
201242cbe538SGunnar Mills         }
201342cbe538SGunnar Mills 
201462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
201542cbe538SGunnar Mills         callback(inventoryItems);
201642cbe538SGunnar Mills     };
201742cbe538SGunnar Mills 
201842cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
201942cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
20201e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
20211e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
20221e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
20231e1e598dSJonathan Doman         std::move(respHandler));
202442cbe538SGunnar Mills 
202562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
202642cbe538SGunnar Mills }
202742cbe538SGunnar Mills 
202842cbe538SGunnar Mills /**
202942cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
203042cbe538SGunnar Mills  *
203142cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
203242cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
203342cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
203442cbe538SGunnar Mills  * item.
203542cbe538SGunnar Mills  *
203642cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
203742cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
203842cbe538SGunnar Mills  *
203942cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
204042cbe538SGunnar Mills  * when information has been obtained.
204142cbe538SGunnar Mills  *
204242cbe538SGunnar Mills  * The callback must have the following signature:
204342cbe538SGunnar Mills  *   @code
204442cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
204542cbe538SGunnar Mills  *   @endcode
204642cbe538SGunnar Mills  *
204742cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
204842cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
204942cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
205042cbe538SGunnar Mills  */
205142cbe538SGunnar Mills template <typename Callback>
205242cbe538SGunnar Mills void getPowerSupplyAttributes(
205342cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
205442cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
205542cbe538SGunnar Mills     Callback&& callback)
205642cbe538SGunnar Mills {
205762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
205842cbe538SGunnar Mills 
205942cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2060a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
206142cbe538SGunnar Mills     {
206262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
206342cbe538SGunnar Mills         callback(inventoryItems);
206442cbe538SGunnar Mills         return;
206542cbe538SGunnar Mills     }
206642cbe538SGunnar Mills 
2067e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
206842cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
206942cbe538SGunnar Mills 
2070e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2071e99073f5SGeorge Liu     dbus::utility::getSubTree(
2072e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
20738cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
2074b9d36b47SEd Tanous          inventoryItems](
2075e99073f5SGeorge Liu             const boost::system::error_code& ec,
2076b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2077e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
207862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
207942cbe538SGunnar Mills         if (ec)
208042cbe538SGunnar Mills         {
20818d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
208262598e31SEd Tanous             BMCWEB_LOG_ERROR(
208362598e31SEd Tanous                 "getPowerSupplyAttributes respHandler DBus error {}", ec);
208442cbe538SGunnar Mills             return;
208542cbe538SGunnar Mills         }
208626f6976fSEd Tanous         if (subtree.empty())
208742cbe538SGunnar Mills         {
208862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
208942cbe538SGunnar Mills             callback(inventoryItems);
209042cbe538SGunnar Mills             return;
209142cbe538SGunnar Mills         }
209242cbe538SGunnar Mills 
209342cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
209442cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
209542cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2096fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
209742cbe538SGunnar Mills 
209842cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
209942cbe538SGunnar Mills         {
210062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
210142cbe538SGunnar Mills             callback(inventoryItems);
210242cbe538SGunnar Mills             return;
210342cbe538SGunnar Mills         }
210442cbe538SGunnar Mills 
210542cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
210642cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
210742cbe538SGunnar Mills 
210842cbe538SGunnar Mills         if (connection.empty())
210942cbe538SGunnar Mills         {
211062598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
211142cbe538SGunnar Mills             callback(inventoryItems);
211242cbe538SGunnar Mills             return;
211342cbe538SGunnar Mills         }
211442cbe538SGunnar Mills 
211542cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
211662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
211762598e31SEd Tanous                          connection);
211842cbe538SGunnar Mills 
211942cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
212042cbe538SGunnar Mills                                      psAttributesConnections,
212142cbe538SGunnar Mills                                      std::move(callback));
212262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2123e99073f5SGeorge Liu     });
212462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
212542cbe538SGunnar Mills }
212642cbe538SGunnar Mills 
212742cbe538SGunnar Mills /**
2128adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
21298fb49dd6SShawn McCarney  *
21308fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2131adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21328fb49dd6SShawn McCarney  *
2133adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2134adc4f0dbSShawn McCarney  * response.
21358fb49dd6SShawn McCarney  *
2136adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2137adc4f0dbSShawn McCarney  * inventory items have been obtained.
2138adc4f0dbSShawn McCarney  *
2139adc4f0dbSShawn McCarney  * The callback must have the following signature:
2140adc4f0dbSShawn McCarney  *   @code
2141adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2142adc4f0dbSShawn McCarney  *   @endcode
21438fb49dd6SShawn McCarney  *
21448fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21458fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21468fb49dd6SShawn McCarney  * implements ObjectManager.
2147adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21488fb49dd6SShawn McCarney  */
2149adc4f0dbSShawn McCarney template <typename Callback>
2150d0090733SEd Tanous static void
2151d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2152fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2153adc4f0dbSShawn McCarney                       Callback&& callback)
21548fb49dd6SShawn McCarney {
215562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2156adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
21578cb2c024SEd Tanous         [sensorsAsyncResp, callback = std::forward<Callback>(callback)](
2158adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
215962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21608fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2161d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
21628cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
2163fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
216462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2165002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2166d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
216762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
216842cbe538SGunnar Mills 
2169002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2170002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
217162598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb enter");
217242cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2173002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
217442cbe538SGunnar Mills                                              std::move(callback));
217562598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
217642cbe538SGunnar Mills                 };
217742cbe538SGunnar Mills 
2178d500549bSAnthony Wilson                 // Find led connections and get the data
2179d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
218042cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
218162598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2182d500549bSAnthony Wilson             };
21838fb49dd6SShawn McCarney 
2184adc4f0dbSShawn McCarney             // Get inventory item data from connections
2185adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2186d0090733SEd Tanous                                   invConnections,
2187d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
218862598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
21898fb49dd6SShawn McCarney         };
21908fb49dd6SShawn McCarney 
2191adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2192002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21938fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
219462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
21958fb49dd6SShawn McCarney     };
21968fb49dd6SShawn McCarney 
2197adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2198d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2199adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
220062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2201adc4f0dbSShawn McCarney }
2202adc4f0dbSShawn McCarney 
2203adc4f0dbSShawn McCarney /**
2204adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2205adc4f0dbSShawn McCarney  *
2206adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2207adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2208adc4f0dbSShawn McCarney  * array.
2209adc4f0dbSShawn McCarney  *
2210adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2211adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2212adc4f0dbSShawn McCarney  * object.
2213adc4f0dbSShawn McCarney  *
2214adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2215adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2216adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2217adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2218adc4f0dbSShawn McCarney  */
221923a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2220adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2221adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2222adc4f0dbSShawn McCarney {
222318f8f608SEd Tanous     std::string nameS;
22246f4bd290SAlexander Hansen     nameS.resize(inventoryItem.name.size());
222518f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, nameS.begin(), '_', ' ');
2226adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2227adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2228adc4f0dbSShawn McCarney     {
222918f8f608SEd Tanous         nlohmann::json::iterator nameIt = powerSupply.find("Name");
223018f8f608SEd Tanous         if (nameIt == powerSupply.end())
223118f8f608SEd Tanous         {
223218f8f608SEd Tanous             continue;
223318f8f608SEd Tanous         }
223418f8f608SEd Tanous         const std::string* name = nameIt->get_ptr<std::string*>();
223518f8f608SEd Tanous         if (name == nullptr)
223618f8f608SEd Tanous         {
223718f8f608SEd Tanous             continue;
223818f8f608SEd Tanous         }
223918f8f608SEd Tanous         if (nameS == *name)
2240adc4f0dbSShawn McCarney         {
2241adc4f0dbSShawn McCarney             return powerSupply;
2242adc4f0dbSShawn McCarney         }
2243adc4f0dbSShawn McCarney     }
2244adc4f0dbSShawn McCarney 
2245adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2246adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2247adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2248ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2249ef4c65b7SEd Tanous                                                chassisId);
2250eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2251eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
225218f8f608SEd Tanous     std::string escaped;
22536f4bd290SAlexander Hansen     escaped.resize(inventoryItem.name.size());
225418f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, escaped.begin(), '_', ' ');
225518f8f608SEd Tanous     powerSupply["Name"] = std::move(escaped);
2256adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2257adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2258adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2259adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2260d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2261adc4f0dbSShawn McCarney 
226242cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
226342cbe538SGunnar Mills     {
226442cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
226542cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
226642cbe538SGunnar Mills     }
226742cbe538SGunnar Mills 
2268aaf08ac7SMatt Simmering     powerSupply["Status"]["State"] = getState(&inventoryItem, true);
2269adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2270adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2271adc4f0dbSShawn McCarney 
2272adc4f0dbSShawn McCarney     return powerSupply;
22738fb49dd6SShawn McCarney }
22748fb49dd6SShawn McCarney 
22758fb49dd6SShawn McCarney /**
2276de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2277de629b6eSShawn McCarney  *
2278de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2279de629b6eSShawn McCarney  *
2280de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2281de629b6eSShawn McCarney  * information has been obtained.
2282de629b6eSShawn McCarney  *
2283adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2284de629b6eSShawn McCarney  *
2285de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2286de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2287de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2288de629b6eSShawn McCarney  *
2289de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2290de629b6eSShawn McCarney  *
2291adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2292adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2293adc4f0dbSShawn McCarney  *
2294de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2295adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2296de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2297de629b6eSShawn McCarney  * implements ObjectManager.
2298adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2299de629b6eSShawn McCarney  */
230023a21a1cSEd Tanous inline void getSensorData(
230181ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2302fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2303fe04d49cSNan Zhou     const std::set<std::string>& connections,
2304b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2305de629b6eSShawn McCarney {
230662598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2307de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2308de629b6eSShawn McCarney     for (const std::string& connection : connections)
2309de629b6eSShawn McCarney     {
23105eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
23115eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
23125eb468daSGeorge Liu         dbus::utility::getManagedObjects(
23135eb468daSGeorge Liu             connection, sensorPath,
2314002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
23155e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
231602cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
231762598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2318de629b6eSShawn McCarney             if (ec)
2319de629b6eSShawn McCarney             {
232062598e31SEd Tanous                 BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
23218d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2322de629b6eSShawn McCarney                 return;
2323de629b6eSShawn McCarney             }
2324de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2325de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2326de629b6eSShawn McCarney             {
2327de629b6eSShawn McCarney                 const std::string& objPath =
2328de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
232962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
233062598e31SEd Tanous                                  objPath);
2331de629b6eSShawn McCarney 
2332de629b6eSShawn McCarney                 std::vector<std::string> split;
2333de629b6eSShawn McCarney                 // Reserve space for
2334de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2335de629b6eSShawn McCarney                 split.reserve(6);
233650ebd4afSEd Tanous                 // NOLINTNEXTLINE
233750ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2338de629b6eSShawn McCarney                 if (split.size() < 6)
2339de629b6eSShawn McCarney                 {
234062598e31SEd Tanous                     BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
234162598e31SEd Tanous                                      objPath);
2342de629b6eSShawn McCarney                     continue;
2343de629b6eSShawn McCarney                 }
234450ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2345de629b6eSShawn McCarney                 // string at the beginning
2346de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2347de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
234862598e31SEd Tanous                 BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
234962598e31SEd Tanous                                  sensorType);
235049c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2351de629b6eSShawn McCarney                 {
235262598e31SEd Tanous                     BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
2353de629b6eSShawn McCarney                     continue;
2354de629b6eSShawn McCarney                 }
2355de629b6eSShawn McCarney 
2356adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2357adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2358adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2359adc4f0dbSShawn McCarney 
236095a3ecadSAnthony Wilson                 const std::string& sensorSchema =
236181ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
236295a3ecadSAnthony Wilson 
236395a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
236495a3ecadSAnthony Wilson 
2365928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2366928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
236795a3ecadSAnthony Wilson                 {
2368c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
23693544d2a7SEd Tanous                     auto remove = std::ranges::remove(sensorTypeEscaped, '_');
23703544d2a7SEd Tanous 
23713544d2a7SEd Tanous                     sensorTypeEscaped.erase(std::ranges::begin(remove),
2372c1d019a6SEd Tanous                                             sensorTypeEscaped.end());
2373c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2374c1d019a6SEd Tanous                     sensorId += "_";
2375c1d019a6SEd Tanous                     sensorId += sensorName;
2376c1d019a6SEd Tanous 
23778d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2378ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2379c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2380ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2381ef4c65b7SEd Tanous                                             sensorId);
23828d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
238395a3ecadSAnthony Wilson                 }
238495a3ecadSAnthony Wilson                 else
238595a3ecadSAnthony Wilson                 {
2386271584abSEd Tanous                     std::string fieldName;
2387928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2388928fefb9SNan Zhou                     {
2389928fefb9SNan Zhou                         fieldName = "Members";
2390928fefb9SNan Zhou                     }
2391928fefb9SNan Zhou                     else if (sensorType == "temperature")
2392de629b6eSShawn McCarney                     {
2393de629b6eSShawn McCarney                         fieldName = "Temperatures";
2394de629b6eSShawn McCarney                     }
2395de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2396de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2397de629b6eSShawn McCarney                     {
2398de629b6eSShawn McCarney                         fieldName = "Fans";
2399de629b6eSShawn McCarney                     }
2400de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2401de629b6eSShawn McCarney                     {
2402de629b6eSShawn McCarney                         fieldName = "Voltages";
2403de629b6eSShawn McCarney                     }
2404de629b6eSShawn McCarney                     else if (sensorType == "power")
2405de629b6eSShawn McCarney                     {
240655f79e6fSEd Tanous                         if (sensorName == "total_power")
2407028f7ebcSEddie James                         {
2408028f7ebcSEddie James                             fieldName = "PowerControl";
2409028f7ebcSEddie James                         }
2410adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2411adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2412028f7ebcSEddie James                         {
2413de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2414de629b6eSShawn McCarney                         }
2415adc4f0dbSShawn McCarney                         else
2416adc4f0dbSShawn McCarney                         {
2417adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2418adc4f0dbSShawn McCarney                             continue;
2419adc4f0dbSShawn McCarney                         }
2420028f7ebcSEddie James                     }
2421de629b6eSShawn McCarney                     else
2422de629b6eSShawn McCarney                     {
242362598e31SEd Tanous                         BMCWEB_LOG_ERROR("Unsure how to handle sensorType {}",
242462598e31SEd Tanous                                          sensorType);
2425de629b6eSShawn McCarney                         continue;
2426de629b6eSShawn McCarney                     }
2427de629b6eSShawn McCarney 
2428de629b6eSShawn McCarney                     nlohmann::json& tempArray =
24298d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2430adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
243149c53ac9SJohnathan Mantey                     {
2432adc4f0dbSShawn McCarney                         if (tempArray.empty())
24337ab06f49SGunnar Mills                         {
243495a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
243595a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
243695a3ecadSAnthony Wilson                             // naming in power.hpp.
24371476687dSEd Tanous                             nlohmann::json::object_t power;
2438ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2439ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2440eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2441eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2442eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2443eddfc437SWilly Tu                                                  .to_string());
2444eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2445b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2446adc4f0dbSShawn McCarney                         }
2447adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2448adc4f0dbSShawn McCarney                     }
2449adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2450adc4f0dbSShawn McCarney                     {
2451adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2452adc4f0dbSShawn McCarney                         {
2453adc4f0dbSShawn McCarney                             sensorJson =
2454adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
245581ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2456adc4f0dbSShawn McCarney                         }
245749c53ac9SJohnathan Mantey                     }
2458928fefb9SNan Zhou                     else if (fieldName == "Members")
2459928fefb9SNan Zhou                     {
2460677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
24613544d2a7SEd Tanous                         auto remove = std::ranges::remove(sensorTypeEscaped,
24623544d2a7SEd Tanous                                                           '_');
24633544d2a7SEd Tanous                         sensorTypeEscaped.erase(std::ranges::begin(remove),
2464677bb756SEd Tanous                                                 sensorTypeEscaped.end());
2465677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2466677bb756SEd Tanous                         sensorId += "_";
2467677bb756SEd Tanous                         sensorId += sensorName;
2468677bb756SEd Tanous 
24691476687dSEd Tanous                         nlohmann::json::object_t member;
2470ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2471ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2472677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2473677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2474b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2475928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2476928fefb9SNan Zhou                     }
247749c53ac9SJohnathan Mantey                     else
247849c53ac9SJohnathan Mantey                     {
24791476687dSEd Tanous                         nlohmann::json::object_t member;
2480ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2481ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2482eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2483eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2484eddfc437SWilly Tu                         url.set_fragment(
2485eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2486eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2487b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2488adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
248949c53ac9SJohnathan Mantey                     }
249095a3ecadSAnthony Wilson                 }
2491de629b6eSShawn McCarney 
2492adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2493adc4f0dbSShawn McCarney                 {
24941d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24951d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24961d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24971d7c0054SEd Tanous                                            inventoryItem);
24981d7c0054SEd Tanous 
24991d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
25001d7c0054SEd Tanous                     path += sensorType;
25011d7c0054SEd Tanous                     path += "/";
25021d7c0054SEd Tanous                     path += sensorName;
2503c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2504adc4f0dbSShawn McCarney                 }
2505de629b6eSShawn McCarney             }
250681ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
250749c53ac9SJohnathan Mantey             {
250881ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2509928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2510928fefb9SNan Zhou                         sensors::node::sensors &&
2511928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2512928fefb9SNan Zhou                 {
2513928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2514928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2515928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2516928fefb9SNan Zhou                             .size();
2517928fefb9SNan Zhou                 }
2518928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2519928fefb9SNan Zhou                          sensors::node::thermal)
25208bd25ccdSJames Feist                 {
252181ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
25228bd25ccdSJames Feist                 }
252349c53ac9SJohnathan Mantey             }
252462598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
25255eb468daSGeorge Liu         });
252623a21a1cSEd Tanous     }
252762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData exit");
2528de629b6eSShawn McCarney }
2529de629b6eSShawn McCarney 
2530fe04d49cSNan Zhou inline void
2531fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2532fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
25331abe55efSEd Tanous {
2534fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2535fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
253662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb enter");
2537adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2538d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2539d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2540adc4f0dbSShawn McCarney                               inventoryItems) {
254162598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
254249c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2543002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2544d0090733SEd Tanous                           inventoryItems);
254562598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb exit");
2546adc4f0dbSShawn McCarney         };
2547adc4f0dbSShawn McCarney 
2548adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2549d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2550adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2551adc4f0dbSShawn McCarney 
255262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb exit");
255308777fb0SLewanczyk, Dawid     };
2554de629b6eSShawn McCarney 
2555de629b6eSShawn McCarney     // Get set of connections that provide sensor values
255681ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
255795a3ecadSAnthony Wilson }
255895a3ecadSAnthony Wilson 
255995a3ecadSAnthony Wilson /**
256095a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
256195a3ecadSAnthony Wilson  *        chassis.
256295a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
256395a3ecadSAnthony Wilson  */
2564b5a76932SEd Tanous inline void
256581ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
256695a3ecadSAnthony Wilson {
256762598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
256895a3ecadSAnthony Wilson     auto getChassisCb =
256981ce609eSEd Tanous         [sensorsAsyncResp](
2570fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
257162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb enter");
257281ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
257362598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb exit");
257408777fb0SLewanczyk, Dawid     };
2575928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2576928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2577928fefb9SNan Zhou     {
25788d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25798d1b46d7Szhanghch05             nlohmann::json::array();
2580928fefb9SNan Zhou     }
258126f03899SShawn McCarney     // Get set of sensors in chassis
25827f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25837f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25847f1cc26dSEd Tanous                std::move(getChassisCb));
258562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData exit");
2586271584abSEd Tanous }
258708777fb0SLewanczyk, Dawid 
2588413961deSRichard Marian Thomaiyar /**
258949c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
259049c53ac9SJohnathan Mantey  * the chassis node
259149c53ac9SJohnathan Mantey  *
259249c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
259349c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
259449c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
259549c53ac9SJohnathan Mantey  *                         repeated calls to this function
259649c53ac9SJohnathan Mantey  */
2597fe04d49cSNan Zhou inline bool
2598fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
259902cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2600fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
260149c53ac9SJohnathan Mantey {
2602fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
260349c53ac9SJohnathan Mantey     {
260428aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2605b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
260628aa8de5SGeorge Liu         if (thisSensorName.empty())
260749c53ac9SJohnathan Mantey         {
260849c53ac9SJohnathan Mantey             continue;
260949c53ac9SJohnathan Mantey         }
261049c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
261149c53ac9SJohnathan Mantey         {
261249c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
261349c53ac9SJohnathan Mantey             return true;
261449c53ac9SJohnathan Mantey         }
261549c53ac9SJohnathan Mantey     }
261649c53ac9SJohnathan Mantey     return false;
261749c53ac9SJohnathan Mantey }
261849c53ac9SJohnathan Mantey 
2619c71d6125SEd Tanous inline std::pair<std::string, std::string>
2620c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2621c71d6125SEd Tanous {
2622c71d6125SEd Tanous     size_t index = sensorId.find('_');
2623c71d6125SEd Tanous     if (index == std::string::npos)
2624c71d6125SEd Tanous     {
2625c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2626c71d6125SEd Tanous     }
2627c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2628c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2629c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2630c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2631c71d6125SEd Tanous     {
2632c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2633c71d6125SEd Tanous     }
2634c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2635c71d6125SEd Tanous }
2636c71d6125SEd Tanous 
263749c53ac9SJohnathan Mantey /**
2638413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2639413961deSRichard Marian Thomaiyar  *
26408d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
26414bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2642413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2643413961deSRichard Marian Thomaiyar  */
264423a21a1cSEd Tanous inline void setSensorsOverride(
2645b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26460885057cSEd Tanous     std::unordered_map<std::string, std::vector<nlohmann::json::object_t>>&
2647397fd61fSjayaprakash Mutyala         allCollections)
2648413961deSRichard Marian Thomaiyar {
264962598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
265062598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
2651413961deSRichard Marian Thomaiyar 
2652d02aad39SEd Tanous     std::string_view propertyValueName;
2653f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2654413961deSRichard Marian Thomaiyar     std::string memberId;
2655543f4400SEd Tanous     double value = 0.0;
2656f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2657f65af9e8SRichard Marian Thomaiyar     {
2658f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2659f65af9e8SRichard Marian Thomaiyar         {
2660f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2661f65af9e8SRichard Marian Thomaiyar         }
2662f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2663f65af9e8SRichard Marian Thomaiyar         {
2664f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2665f65af9e8SRichard Marian Thomaiyar         }
2666f65af9e8SRichard Marian Thomaiyar         else
2667f65af9e8SRichard Marian Thomaiyar         {
2668f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2669f65af9e8SRichard Marian Thomaiyar         }
2670f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2671f65af9e8SRichard Marian Thomaiyar         {
26720885057cSEd Tanous             if (!json_util::readJsonObject(
26730885057cSEd Tanous                     item, sensorAsyncResp->asyncResp->res, "MemberId", memberId,
26740885057cSEd Tanous                     propertyValueName, value))
2675413961deSRichard Marian Thomaiyar             {
2676413961deSRichard Marian Thomaiyar                 return;
2677413961deSRichard Marian Thomaiyar             }
2678f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2679f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2680f65af9e8SRichard Marian Thomaiyar         }
2681f65af9e8SRichard Marian Thomaiyar     }
26824bb3dc34SCarol Wang 
2683002d39b4SEd Tanous     auto getChassisSensorListCb =
2684d02aad39SEd Tanous         [sensorAsyncResp, overrideMap,
2685d02aad39SEd Tanous          propertyValueNameStr = std::string(propertyValueName)](
2686fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
268749c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
268849c53ac9SJohnathan Mantey         // chassis node
2689fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2690fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2691f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2692413961deSRichard Marian Thomaiyar         {
2693f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2694c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2695c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2696c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2697c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2698f65af9e8SRichard Marian Thomaiyar             {
269962598e31SEd Tanous                 BMCWEB_LOG_INFO("Unable to find memberId {}", item.first);
27008d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2701f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2702413961deSRichard Marian Thomaiyar                 return;
2703413961deSRichard Marian Thomaiyar             }
2704f65af9e8SRichard Marian Thomaiyar         }
2705413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2706002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2707d02aad39SEd Tanous             [sensorAsyncResp, overrideMap, propertyValueNameStr](
2708d02aad39SEd Tanous                 const std::set<std::string>& /*connections*/,
2709002d39b4SEd Tanous                 const std::set<std::pair<std::string, std::string>>&
2710413961deSRichard Marian Thomaiyar                     objectsWithConnection) {
2711f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2712413961deSRichard Marian Thomaiyar             {
271362598e31SEd Tanous                 BMCWEB_LOG_INFO(
271462598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
271562598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
27164f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2717a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2718a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2719413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2720413961deSRichard Marian Thomaiyar                                                : "Voltages",
2721f65af9e8SRichard Marian Thomaiyar                                            "Count");
2722f65af9e8SRichard Marian Thomaiyar                 return;
2723f65af9e8SRichard Marian Thomaiyar             }
2724f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2725f65af9e8SRichard Marian Thomaiyar             {
272628aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
272728aa8de5SGeorge Liu                 std::string sensorName = path.filename();
272828aa8de5SGeorge Liu                 if (sensorName.empty())
2729f65af9e8SRichard Marian Thomaiyar                 {
27304f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2731f65af9e8SRichard Marian Thomaiyar                     return;
2732f65af9e8SRichard Marian Thomaiyar                 }
27333f5eb755SBan Feng                 std::string id = path.parent_path().filename();
27343544d2a7SEd Tanous                 auto remove = std::ranges::remove(id, '_');
27353544d2a7SEd Tanous                 id.erase(std::ranges::begin(remove), id.end());
27363f5eb755SBan Feng                 id += "_";
27373f5eb755SBan Feng                 id += sensorName;
2738f65af9e8SRichard Marian Thomaiyar 
27393f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2740f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2741f65af9e8SRichard Marian Thomaiyar                 {
274262598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
274362598e31SEd Tanous                                     item.first);
27444f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2745413961deSRichard Marian Thomaiyar                     return;
2746413961deSRichard Marian Thomaiyar                 }
2747e93abac6SGinu George                 setDbusProperty(sensorAsyncResp->asyncResp,
2748e93abac6SGinu George                                 propertyValueNameStr, item.second, item.first,
2749e93abac6SGinu George                                 "xyz.openbmc_project.Sensor.Value", "Value",
2750d02aad39SEd Tanous                                 iterator->second.first);
2751f65af9e8SRichard Marian Thomaiyar             }
2752413961deSRichard Marian Thomaiyar         };
2753413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2754413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2755413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2756413961deSRichard Marian Thomaiyar     };
2757413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27587f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27597f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27607f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2761413961deSRichard Marian Thomaiyar }
2762413961deSRichard Marian Thomaiyar 
2763a0ec28b6SAdrian Ambrożewicz /**
2764a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2765a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2766a0ec28b6SAdrian Ambrożewicz  *
2767a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2768a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2769a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2770a0ec28b6SAdrian Ambrożewicz  *
2771a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2772a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2773a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2774a0ec28b6SAdrian Ambrożewicz  */
2775931edc79SEd Tanous template <typename Callback>
2776021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2777021d32cfSKrzysztof Grobelny                                  const std::string& node,
2778931edc79SEd Tanous                                  Callback&& mapComplete)
2779a0ec28b6SAdrian Ambrożewicz {
278002da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
278102da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
278202da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
278302da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2784a0ec28b6SAdrian Ambrożewicz     {
278562598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
27866804b5c8SEd Tanous         std::map<std::string, std::string> noop;
27876804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2788a0ec28b6SAdrian Ambrożewicz         return;
2789a0ec28b6SAdrian Ambrożewicz     }
2790d51e072fSKrzysztof Grobelny 
279172374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2792931edc79SEd Tanous     auto callback = [asyncResp,
27938cb2c024SEd Tanous                      mapCompleteCb = std::forward<Callback>(mapComplete)](
2794a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2795fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2796fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2797fe04d49cSNan Zhou     };
2798a0ec28b6SAdrian Ambrożewicz 
2799a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2800d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2801a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2802a0ec28b6SAdrian Ambrożewicz }
2803a0ec28b6SAdrian Ambrożewicz 
2804bacb2162SNan Zhou namespace sensors
2805bacb2162SNan Zhou {
2806928fefb9SNan Zhou 
2807bacb2162SNan Zhou inline void getChassisCallback(
2808c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2809c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2810fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2811bacb2162SNan Zhou {
281262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2813bacb2162SNan Zhou 
2814c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2815c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2816bacb2162SNan Zhou     {
281762598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2818bacb2162SNan Zhou 
2819bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2820bacb2162SNan Zhou         std::string sensorName = path.filename();
2821bacb2162SNan Zhou         if (sensorName.empty())
2822bacb2162SNan Zhou         {
282362598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2824c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2825bacb2162SNan Zhou             return;
2826bacb2162SNan Zhou         }
2827c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2828c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2829c1d019a6SEd Tanous         // type in the URI
28303544d2a7SEd Tanous         auto remove = std::ranges::remove(type, '_');
28313544d2a7SEd Tanous         type.erase(std::ranges::begin(remove), type.end());
2832c1d019a6SEd Tanous 
28331476687dSEd Tanous         nlohmann::json::object_t member;
2834c1d019a6SEd Tanous         std::string id = type;
2835c1d019a6SEd Tanous         id += "_";
2836c1d019a6SEd Tanous         id += sensorName;
2837ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2838ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2839c1d019a6SEd Tanous 
2840b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2841bacb2162SNan Zhou     }
2842bacb2162SNan Zhou 
2843c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
284462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2845bacb2162SNan Zhou }
2846e6bd846dSNan Zhou 
2847ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2848ac106bf6SEd Tanous     App& app, const crow::Request& req,
2849ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2850de167a6fSNan Zhou     const std::string& chassisId)
2851de167a6fSNan Zhou {
2852de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2853de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2854de167a6fSNan Zhou     };
2855de167a6fSNan Zhou     query_param::Query delegatedQuery;
2856ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2857de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2858de167a6fSNan Zhou     {
2859de167a6fSNan Zhou         return;
2860de167a6fSNan Zhou     }
2861de167a6fSNan Zhou 
2862de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2863de167a6fSNan Zhou     {
2864de167a6fSNan Zhou         // we perform efficient expand.
2865ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2866ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2867de167a6fSNan Zhou             sensors::node::sensors,
2868de167a6fSNan Zhou             /*efficientExpand=*/true);
2869ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2870de167a6fSNan Zhou 
287162598e31SEd Tanous         BMCWEB_LOG_DEBUG(
287262598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2873de167a6fSNan Zhou         return;
28740bad320cSEd Tanous     }
2875de167a6fSNan Zhou 
2876de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2877de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2878ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2879ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2880ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2881c1d019a6SEd Tanous }
28827f1cc26dSEd Tanous 
2883c1d019a6SEd Tanous inline void
2884c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2885c1d019a6SEd Tanous                       const std::string& sensorPath,
2886c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2887c1d019a6SEd Tanous {
2888c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2889c1d019a6SEd Tanous     {
2890c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2891c1d019a6SEd Tanous         return;
2892c1d019a6SEd Tanous     }
2893c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2894c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
289562598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
289662598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2897c1343bf6SKrzysztof Grobelny 
2898c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2899c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2900c1d019a6SEd Tanous         [asyncResp,
29015e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2902c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2903c1d019a6SEd Tanous         if (ec)
2904c1d019a6SEd Tanous         {
2905c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2906c1d019a6SEd Tanous             return;
2907c1d019a6SEd Tanous         }
2908c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2909c1d019a6SEd Tanous         std::string name = path.filename();
2910c1d019a6SEd Tanous         path = path.parent_path();
2911c1d019a6SEd Tanous         std::string type = path.filename();
2912c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2913c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2914c1343bf6SKrzysztof Grobelny     });
2915de167a6fSNan Zhou }
2916de167a6fSNan Zhou 
2917e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2918c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2919677bb756SEd Tanous                             const std::string& chassisId,
2920c1d019a6SEd Tanous                             const std::string& sensorId)
2921e6bd846dSNan Zhou {
2922c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2923e6bd846dSNan Zhou     {
2924e6bd846dSNan Zhou         return;
2925e6bd846dSNan Zhou     }
2926c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2927c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2928c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2929c1d019a6SEd Tanous     {
2930c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2931c1d019a6SEd Tanous         return;
2932c1d019a6SEd Tanous     }
2933c71d6125SEd Tanous 
2934ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2935ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2936c1d019a6SEd Tanous 
293762598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2938e6bd846dSNan Zhou 
29392b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2940e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2941c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2942c71d6125SEd Tanous                              '/' + nameType.second;
2943e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2944e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29452b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29462b73119cSGeorge Liu         sensorPath, interfaces,
2947aec0ec30SMyung Bae         [asyncResp, sensorId,
29482b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2949c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
295062598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 enter");
2951aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2952aec0ec30SMyung Bae         {
295362598e31SEd Tanous             BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2954aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2955aec0ec30SMyung Bae             return;
2956aec0ec30SMyung Bae         }
2957e6bd846dSNan Zhou         if (ec)
2958e6bd846dSNan Zhou         {
2959c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
296062598e31SEd Tanous             BMCWEB_LOG_ERROR(
296162598e31SEd Tanous                 "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2962e6bd846dSNan Zhou             return;
2963e6bd846dSNan Zhou         }
2964c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
296562598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 exit");
29662b73119cSGeorge Liu     });
2967e6bd846dSNan Zhou }
2968e6bd846dSNan Zhou 
2969bacb2162SNan Zhou } // namespace sensors
2970bacb2162SNan Zhou 
29717e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
297295a3ecadSAnthony Wilson {
29737e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2974ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2975002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2976de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
297795a3ecadSAnthony Wilson }
297895a3ecadSAnthony Wilson 
29797e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
298095a3ecadSAnthony Wilson {
29817e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2982ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2983002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2984e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
298595a3ecadSAnthony Wilson }
298695a3ecadSAnthony Wilson 
298708777fb0SLewanczyk, Dawid } // namespace redfish
2988