xref: /openbmc/bmcweb/features/redfish/lib/sensors.hpp (revision e93abac6d60c4b409ad72086dac153f23d793ac1)
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"
21aaf08ac7SMatt Simmering #include "generated/enums/resource.hpp"
220ec8b83dSEd Tanous #include "generated/enums/sensor.hpp"
233ccb3adbSEd Tanous #include "query.hpp"
243ccb3adbSEd Tanous #include "registries/privilege_registry.hpp"
2550ebd4afSEd Tanous #include "str_utility.hpp"
263ccb3adbSEd Tanous #include "utils/dbus_utils.hpp"
273ccb3adbSEd Tanous #include "utils/json_utils.hpp"
283ccb3adbSEd Tanous #include "utils/query_param.hpp"
290ec8b83dSEd Tanous 
30e99073f5SGeorge Liu #include <boost/system/error_code.hpp>
31ef4c65b7SEd Tanous #include <boost/url/format.hpp>
321e1e598dSJonathan Doman #include <sdbusplus/asio/property.hpp>
3386d89ed7SKrzysztof Grobelny #include <sdbusplus/unpack_properties.hpp>
341214b7e7SGunnar Mills 
357a1dbc48SGeorge Liu #include <array>
361214b7e7SGunnar Mills #include <cmath>
37fe04d49cSNan Zhou #include <iterator>
38283860f5SEd Tanous #include <limits>
39fe04d49cSNan Zhou #include <map>
403544d2a7SEd Tanous #include <ranges>
41fe04d49cSNan Zhou #include <set>
4218f8f608SEd Tanous #include <string>
437a1dbc48SGeorge Liu #include <string_view>
44b5a76932SEd Tanous #include <utility>
45abf2add6SEd Tanous #include <variant>
4608777fb0SLewanczyk, Dawid 
471abe55efSEd Tanous namespace redfish
481abe55efSEd Tanous {
4908777fb0SLewanczyk, Dawid 
50a0ec28b6SAdrian Ambrożewicz namespace sensors
51a0ec28b6SAdrian Ambrożewicz {
52a0ec28b6SAdrian Ambrożewicz namespace node
53a0ec28b6SAdrian Ambrożewicz {
54a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view power = "Power";
55a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view sensors = "Sensors";
56a0ec28b6SAdrian Ambrożewicz static constexpr std::string_view thermal = "Thermal";
57a0ec28b6SAdrian Ambrożewicz } // namespace node
58a0ec28b6SAdrian Ambrożewicz 
5902da7c5aSEd Tanous // clang-format off
60a0ec28b6SAdrian Ambrożewicz namespace dbus
61a0ec28b6SAdrian Ambrożewicz {
62cf9e417dSEd Tanous constexpr auto powerPaths = std::to_array<std::string_view>({
6302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/voltage",
6402da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/power"
6502da7c5aSEd Tanous });
66c2bf7f99SWludzik, Jozef 
6725b54dbaSEd Tanous constexpr auto getSensorPaths(){
6825b54dbaSEd Tanous     if constexpr(BMCWEB_REDFISH_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM){
6925b54dbaSEd Tanous     return std::to_array<std::string_view>({
7002da7c5aSEd Tanous         "/xyz/openbmc_project/sensors/power",
71a0ec28b6SAdrian Ambrożewicz         "/xyz/openbmc_project/sensors/current",
727088690cSBasheer Ahmed Muddebihal         "/xyz/openbmc_project/sensors/airflow",
735deabed9SGunnar Mills         "/xyz/openbmc_project/sensors/humidity",
74e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/voltage",
75e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_tach",
76e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/temperature",
77e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/fan_pwm",
78e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/altitude",
79e8204933SGeorge Liu         "/xyz/openbmc_project/sensors/energy",
8025b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
8125b54dbaSEd Tanous     } else {
8225b54dbaSEd Tanous       return  std::to_array<std::string_view>({"/xyz/openbmc_project/sensors/power",
8325b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/current",
8425b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/airflow",
8525b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/humidity",
8625b54dbaSEd Tanous         "/xyz/openbmc_project/sensors/utilization"});
8725b54dbaSEd Tanous }
8825b54dbaSEd Tanous }
8925b54dbaSEd Tanous 
9025b54dbaSEd Tanous constexpr auto sensorPaths = getSensorPaths();
9102da7c5aSEd Tanous 
92cf9e417dSEd Tanous constexpr auto thermalPaths = std::to_array<std::string_view>({
9302da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_tach",
94a0ec28b6SAdrian Ambrożewicz     "/xyz/openbmc_project/sensors/temperature",
9502da7c5aSEd Tanous     "/xyz/openbmc_project/sensors/fan_pwm"
9602da7c5aSEd Tanous });
9702da7c5aSEd Tanous 
98c2bf7f99SWludzik, Jozef } // namespace dbus
9902da7c5aSEd Tanous // clang-format on
10002da7c5aSEd Tanous 
101cf9e417dSEd Tanous using sensorPair =
102cf9e417dSEd Tanous     std::pair<std::string_view, std::span<const std::string_view>>;
10302da7c5aSEd Tanous static constexpr std::array<sensorPair, 3> paths = {
104cf9e417dSEd Tanous     {{node::power, dbus::powerPaths},
105cf9e417dSEd Tanous      {node::sensors, dbus::sensorPaths},
106cf9e417dSEd Tanous      {node::thermal, dbus::thermalPaths}}};
107c2bf7f99SWludzik, Jozef 
1080ec8b83dSEd Tanous inline sensor::ReadingType toReadingType(std::string_view sensorType)
109c2bf7f99SWludzik, Jozef {
110c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
111c2bf7f99SWludzik, Jozef     {
1120ec8b83dSEd Tanous         return sensor::ReadingType::Voltage;
113c2bf7f99SWludzik, Jozef     }
114c2bf7f99SWludzik, Jozef     if (sensorType == "power")
115c2bf7f99SWludzik, Jozef     {
1160ec8b83dSEd Tanous         return sensor::ReadingType::Power;
117c2bf7f99SWludzik, Jozef     }
118c2bf7f99SWludzik, Jozef     if (sensorType == "current")
119c2bf7f99SWludzik, Jozef     {
1200ec8b83dSEd Tanous         return sensor::ReadingType::Current;
121c2bf7f99SWludzik, Jozef     }
122c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
123c2bf7f99SWludzik, Jozef     {
1240ec8b83dSEd Tanous         return sensor::ReadingType::Rotational;
125c2bf7f99SWludzik, Jozef     }
126c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
127c2bf7f99SWludzik, Jozef     {
1280ec8b83dSEd Tanous         return sensor::ReadingType::Temperature;
129c2bf7f99SWludzik, Jozef     }
130c2bf7f99SWludzik, Jozef     if (sensorType == "fan_pwm" || sensorType == "utilization")
131c2bf7f99SWludzik, Jozef     {
1320ec8b83dSEd Tanous         return sensor::ReadingType::Percent;
133c2bf7f99SWludzik, Jozef     }
1345deabed9SGunnar Mills     if (sensorType == "humidity")
1355deabed9SGunnar Mills     {
1360ec8b83dSEd Tanous         return sensor::ReadingType::Humidity;
1375deabed9SGunnar Mills     }
138c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
139c2bf7f99SWludzik, Jozef     {
1400ec8b83dSEd Tanous         return sensor::ReadingType::Altitude;
141c2bf7f99SWludzik, Jozef     }
142c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
143c2bf7f99SWludzik, Jozef     {
1440ec8b83dSEd Tanous         return sensor::ReadingType::AirFlow;
145c2bf7f99SWludzik, Jozef     }
146c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
147c2bf7f99SWludzik, Jozef     {
1480ec8b83dSEd Tanous         return sensor::ReadingType::EnergyJoules;
149c2bf7f99SWludzik, Jozef     }
1500ec8b83dSEd Tanous     return sensor::ReadingType::Invalid;
151c2bf7f99SWludzik, Jozef }
152c2bf7f99SWludzik, Jozef 
1531d7c0054SEd Tanous inline std::string_view toReadingUnits(std::string_view sensorType)
154c2bf7f99SWludzik, Jozef {
155c2bf7f99SWludzik, Jozef     if (sensorType == "voltage")
156c2bf7f99SWludzik, Jozef     {
157c2bf7f99SWludzik, Jozef         return "V";
158c2bf7f99SWludzik, Jozef     }
159c2bf7f99SWludzik, Jozef     if (sensorType == "power")
160c2bf7f99SWludzik, Jozef     {
161c2bf7f99SWludzik, Jozef         return "W";
162c2bf7f99SWludzik, Jozef     }
163c2bf7f99SWludzik, Jozef     if (sensorType == "current")
164c2bf7f99SWludzik, Jozef     {
165c2bf7f99SWludzik, Jozef         return "A";
166c2bf7f99SWludzik, Jozef     }
167c2bf7f99SWludzik, Jozef     if (sensorType == "fan_tach")
168c2bf7f99SWludzik, Jozef     {
169c2bf7f99SWludzik, Jozef         return "RPM";
170c2bf7f99SWludzik, Jozef     }
171c2bf7f99SWludzik, Jozef     if (sensorType == "temperature")
172c2bf7f99SWludzik, Jozef     {
173c2bf7f99SWludzik, Jozef         return "Cel";
174c2bf7f99SWludzik, Jozef     }
1755deabed9SGunnar Mills     if (sensorType == "fan_pwm" || sensorType == "utilization" ||
1765deabed9SGunnar Mills         sensorType == "humidity")
177c2bf7f99SWludzik, Jozef     {
178c2bf7f99SWludzik, Jozef         return "%";
179c2bf7f99SWludzik, Jozef     }
180c2bf7f99SWludzik, Jozef     if (sensorType == "altitude")
181c2bf7f99SWludzik, Jozef     {
182c2bf7f99SWludzik, Jozef         return "m";
183c2bf7f99SWludzik, Jozef     }
184c2bf7f99SWludzik, Jozef     if (sensorType == "airflow")
185c2bf7f99SWludzik, Jozef     {
186c2bf7f99SWludzik, Jozef         return "cft_i/min";
187c2bf7f99SWludzik, Jozef     }
188c2bf7f99SWludzik, Jozef     if (sensorType == "energy")
189c2bf7f99SWludzik, Jozef     {
190c2bf7f99SWludzik, Jozef         return "J";
191c2bf7f99SWludzik, Jozef     }
192c2bf7f99SWludzik, Jozef     return "";
193a0ec28b6SAdrian Ambrożewicz }
194a0ec28b6SAdrian Ambrożewicz } // namespace sensors
195a0ec28b6SAdrian Ambrożewicz 
19608777fb0SLewanczyk, Dawid /**
197588c3f0dSKowalski, Kamil  * SensorsAsyncResp
19808777fb0SLewanczyk, Dawid  * Gathers data needed for response processing after async calls are done
19908777fb0SLewanczyk, Dawid  */
2001abe55efSEd Tanous class SensorsAsyncResp
2011abe55efSEd Tanous {
20208777fb0SLewanczyk, Dawid   public:
203a0ec28b6SAdrian Ambrożewicz     using DataCompleteCb = std::function<void(
204a0ec28b6SAdrian Ambrożewicz         const boost::beast::http::status status,
205fe04d49cSNan Zhou         const std::map<std::string, std::string>& uriToDbus)>;
206a0ec28b6SAdrian Ambrożewicz 
207a0ec28b6SAdrian Ambrożewicz     struct SensorData
208a0ec28b6SAdrian Ambrożewicz     {
209a0ec28b6SAdrian Ambrożewicz         const std::string name;
210a0ec28b6SAdrian Ambrożewicz         std::string uri;
211a0ec28b6SAdrian Ambrożewicz         const std::string dbusPath;
212a0ec28b6SAdrian Ambrożewicz     };
213a0ec28b6SAdrian Ambrożewicz 
2148a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2158d1b46d7Szhanghch05                      const std::string& chassisIdIn,
216cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
21702da7c5aSEd Tanous                      std::string_view subNode) :
2188a592810SEd Tanous         asyncResp(asyncRespIn),
219928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
220928fefb9SNan Zhou         efficientExpand(false)
2211214b7e7SGunnar Mills     {}
22208777fb0SLewanczyk, Dawid 
223a0ec28b6SAdrian Ambrożewicz     // Store extra data about sensor mapping and return it in callback
2248a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
2258d1b46d7Szhanghch05                      const std::string& chassisIdIn,
226cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
22702da7c5aSEd Tanous                      std::string_view subNode,
228a0ec28b6SAdrian Ambrożewicz                      DataCompleteCb&& creationComplete) :
2298a592810SEd Tanous         asyncResp(asyncRespIn),
230928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
231928fefb9SNan Zhou         efficientExpand(false), metadata{std::vector<SensorData>()},
232a0ec28b6SAdrian Ambrożewicz         dataComplete{std::move(creationComplete)}
233a0ec28b6SAdrian Ambrożewicz     {}
234a0ec28b6SAdrian Ambrożewicz 
235928fefb9SNan Zhou     // sensor collections expand
2368a592810SEd Tanous     SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
237928fefb9SNan Zhou                      const std::string& chassisIdIn,
238cf9e417dSEd Tanous                      std::span<const std::string_view> typesIn,
2398a592810SEd Tanous                      const std::string_view& subNode, bool efficientExpandIn) :
2408a592810SEd Tanous         asyncResp(asyncRespIn),
241928fefb9SNan Zhou         chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
2428a592810SEd Tanous         efficientExpand(efficientExpandIn)
243928fefb9SNan Zhou     {}
244928fefb9SNan Zhou 
2451abe55efSEd Tanous     ~SensorsAsyncResp()
2461abe55efSEd Tanous     {
2478d1b46d7Szhanghch05         if (asyncResp->res.result() ==
2488d1b46d7Szhanghch05             boost::beast::http::status::internal_server_error)
2491abe55efSEd Tanous         {
2501abe55efSEd Tanous             // Reset the json object to clear out any data that made it in
2511abe55efSEd Tanous             // before the error happened todo(ed) handle error condition with
2521abe55efSEd Tanous             // proper code
2538d1b46d7Szhanghch05             asyncResp->res.jsonValue = nlohmann::json::object();
25408777fb0SLewanczyk, Dawid         }
255a0ec28b6SAdrian Ambrożewicz 
256a0ec28b6SAdrian Ambrożewicz         if (dataComplete && metadata)
257a0ec28b6SAdrian Ambrożewicz         {
258fe04d49cSNan Zhou             std::map<std::string, std::string> map;
2598d1b46d7Szhanghch05             if (asyncResp->res.result() == boost::beast::http::status::ok)
260a0ec28b6SAdrian Ambrożewicz             {
261a0ec28b6SAdrian Ambrożewicz                 for (auto& sensor : *metadata)
262a0ec28b6SAdrian Ambrożewicz                 {
263c1d019a6SEd Tanous                     map.emplace(sensor.uri, sensor.dbusPath);
264a0ec28b6SAdrian Ambrożewicz                 }
265a0ec28b6SAdrian Ambrożewicz             }
2668d1b46d7Szhanghch05             dataComplete(asyncResp->res.result(), map);
267a0ec28b6SAdrian Ambrożewicz         }
26808777fb0SLewanczyk, Dawid     }
269588c3f0dSKowalski, Kamil 
270ecd6a3a2SEd Tanous     SensorsAsyncResp(const SensorsAsyncResp&) = delete;
271ecd6a3a2SEd Tanous     SensorsAsyncResp(SensorsAsyncResp&&) = delete;
272ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
273ecd6a3a2SEd Tanous     SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
274ecd6a3a2SEd Tanous 
275a0ec28b6SAdrian Ambrożewicz     void addMetadata(const nlohmann::json& sensorObject,
276c1d019a6SEd Tanous                      const std::string& dbusPath)
277a0ec28b6SAdrian Ambrożewicz     {
278a0ec28b6SAdrian Ambrożewicz         if (metadata)
279a0ec28b6SAdrian Ambrożewicz         {
280c1d019a6SEd Tanous             metadata->emplace_back(SensorData{
281c1d019a6SEd Tanous                 sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
282a0ec28b6SAdrian Ambrożewicz         }
283a0ec28b6SAdrian Ambrożewicz     }
284a0ec28b6SAdrian Ambrożewicz 
285a0ec28b6SAdrian Ambrożewicz     void updateUri(const std::string& name, const std::string& uri)
286a0ec28b6SAdrian Ambrożewicz     {
287a0ec28b6SAdrian Ambrożewicz         if (metadata)
288a0ec28b6SAdrian Ambrożewicz         {
289a0ec28b6SAdrian Ambrożewicz             for (auto& sensor : *metadata)
290a0ec28b6SAdrian Ambrożewicz             {
291a0ec28b6SAdrian Ambrożewicz                 if (sensor.name == name)
292a0ec28b6SAdrian Ambrożewicz                 {
293a0ec28b6SAdrian Ambrożewicz                     sensor.uri = uri;
294a0ec28b6SAdrian Ambrożewicz                 }
295a0ec28b6SAdrian Ambrożewicz             }
296a0ec28b6SAdrian Ambrożewicz         }
297a0ec28b6SAdrian Ambrożewicz     }
298a0ec28b6SAdrian Ambrożewicz 
2998d1b46d7Szhanghch05     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
300a0ec28b6SAdrian Ambrożewicz     const std::string chassisId;
301cf9e417dSEd Tanous     const std::span<const std::string_view> types;
302a0ec28b6SAdrian Ambrożewicz     const std::string chassisSubNode;
303928fefb9SNan Zhou     const bool efficientExpand;
304a0ec28b6SAdrian Ambrożewicz 
305a0ec28b6SAdrian Ambrożewicz   private:
306a0ec28b6SAdrian Ambrożewicz     std::optional<std::vector<SensorData>> metadata;
307a0ec28b6SAdrian Ambrożewicz     DataCompleteCb dataComplete;
30808777fb0SLewanczyk, Dawid };
30908777fb0SLewanczyk, Dawid 
31008777fb0SLewanczyk, Dawid /**
311d500549bSAnthony Wilson  * Possible states for physical inventory leds
312d500549bSAnthony Wilson  */
313d500549bSAnthony Wilson enum class LedState
314d500549bSAnthony Wilson {
315d500549bSAnthony Wilson     OFF,
316d500549bSAnthony Wilson     ON,
317d500549bSAnthony Wilson     BLINK,
318d500549bSAnthony Wilson     UNKNOWN
319d500549bSAnthony Wilson };
320d500549bSAnthony Wilson 
321d500549bSAnthony Wilson /**
322adc4f0dbSShawn McCarney  * D-Bus inventory item associated with one or more sensors.
323adc4f0dbSShawn McCarney  */
324adc4f0dbSShawn McCarney class InventoryItem
325adc4f0dbSShawn McCarney {
326adc4f0dbSShawn McCarney   public:
3274e23a444SEd Tanous     explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
328adc4f0dbSShawn McCarney     {
329adc4f0dbSShawn McCarney         // Set inventory item name to last node of object path
33028aa8de5SGeorge Liu         sdbusplus::message::object_path path(objectPath);
33128aa8de5SGeorge Liu         name = path.filename();
33228aa8de5SGeorge Liu         if (name.empty())
333adc4f0dbSShawn McCarney         {
33462598e31SEd Tanous             BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
335adc4f0dbSShawn McCarney         }
336adc4f0dbSShawn McCarney     }
337adc4f0dbSShawn McCarney 
338adc4f0dbSShawn McCarney     std::string objectPath;
339adc4f0dbSShawn McCarney     std::string name;
340e05aec50SEd Tanous     bool isPresent = true;
341e05aec50SEd Tanous     bool isFunctional = true;
342e05aec50SEd Tanous     bool isPowerSupply = false;
343e05aec50SEd Tanous     int powerSupplyEfficiencyPercent = -1;
344adc4f0dbSShawn McCarney     std::string manufacturer;
345adc4f0dbSShawn McCarney     std::string model;
346adc4f0dbSShawn McCarney     std::string partNumber;
347adc4f0dbSShawn McCarney     std::string serialNumber;
348adc4f0dbSShawn McCarney     std::set<std::string> sensors;
349d500549bSAnthony Wilson     std::string ledObjectPath;
350e05aec50SEd Tanous     LedState ledState = LedState::UNKNOWN;
351adc4f0dbSShawn McCarney };
352adc4f0dbSShawn McCarney 
353adc4f0dbSShawn McCarney /**
354413961deSRichard Marian Thomaiyar  * @brief Get objects with connection necessary for sensors
355588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp Pointer to object holding response data
35608777fb0SLewanczyk, Dawid  * @param sensorNames Sensors retrieved from chassis
35708777fb0SLewanczyk, Dawid  * @param callback Callback for processing gathered connections
35808777fb0SLewanczyk, Dawid  */
35908777fb0SLewanczyk, Dawid template <typename Callback>
360413961deSRichard Marian Thomaiyar void getObjectsWithConnection(
36181ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
362fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
3631abe55efSEd Tanous     Callback&& callback)
3641abe55efSEd Tanous {
36562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
36603b5bae3SJames Feist     const std::string path = "/xyz/openbmc_project/sensors";
367e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
36808777fb0SLewanczyk, Dawid         "xyz.openbmc_project.Sensor.Value"};
36908777fb0SLewanczyk, Dawid 
370e99073f5SGeorge Liu     // Make call to ObjectMapper to find all sensors objects
371e99073f5SGeorge Liu     dbus::utility::getSubTree(
372e99073f5SGeorge Liu         path, 2, interfaces,
3738cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
374e99073f5SGeorge Liu          sensorNames](const boost::system::error_code& ec,
375002d39b4SEd Tanous                       const dbus::utility::MapperGetSubTreeResponse& subtree) {
376e99073f5SGeorge Liu         // Response handler for parsing objects subtree
37762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
3781abe55efSEd Tanous         if (ec)
3791abe55efSEd Tanous         {
3808d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
38162598e31SEd Tanous             BMCWEB_LOG_ERROR(
38262598e31SEd Tanous                 "getObjectsWithConnection resp_handler: Dbus error {}", ec);
38308777fb0SLewanczyk, Dawid             return;
38408777fb0SLewanczyk, Dawid         }
38508777fb0SLewanczyk, Dawid 
38662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
38708777fb0SLewanczyk, Dawid 
38808777fb0SLewanczyk, Dawid         // Make unique list of connections only for requested sensor types and
38908777fb0SLewanczyk, Dawid         // found in the chassis
390fe04d49cSNan Zhou         std::set<std::string> connections;
391413961deSRichard Marian Thomaiyar         std::set<std::pair<std::string, std::string>> objectsWithConnection;
39208777fb0SLewanczyk, Dawid 
39362598e31SEd Tanous         BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
39449c53ac9SJohnathan Mantey         for (const std::string& tsensor : *sensorNames)
3951abe55efSEd Tanous         {
39662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
39708777fb0SLewanczyk, Dawid         }
39808777fb0SLewanczyk, Dawid 
39908777fb0SLewanczyk, Dawid         for (const std::pair<
40008777fb0SLewanczyk, Dawid                  std::string,
40108777fb0SLewanczyk, Dawid                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
4021abe55efSEd Tanous                  object : subtree)
4031abe55efSEd Tanous         {
40449c53ac9SJohnathan Mantey             if (sensorNames->find(object.first) != sensorNames->end())
4051abe55efSEd Tanous             {
40649c53ac9SJohnathan Mantey                 for (const std::pair<std::string, std::vector<std::string>>&
4071abe55efSEd Tanous                          objData : object.second)
4081abe55efSEd Tanous                 {
40962598e31SEd Tanous                     BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
41008777fb0SLewanczyk, Dawid                     connections.insert(objData.first);
411de629b6eSShawn McCarney                     objectsWithConnection.insert(
412de629b6eSShawn McCarney                         std::make_pair(object.first, objData.first));
41308777fb0SLewanczyk, Dawid                 }
41408777fb0SLewanczyk, Dawid             }
41508777fb0SLewanczyk, Dawid         }
41662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
417413961deSRichard Marian Thomaiyar         callback(std::move(connections), std::move(objectsWithConnection));
41862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
419e99073f5SGeorge Liu     });
42062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
421413961deSRichard Marian Thomaiyar }
422413961deSRichard Marian Thomaiyar 
423413961deSRichard Marian Thomaiyar /**
424413961deSRichard Marian Thomaiyar  * @brief Create connections necessary for sensors
425413961deSRichard Marian Thomaiyar  * @param SensorsAsyncResp Pointer to object holding response data
426413961deSRichard Marian Thomaiyar  * @param sensorNames Sensors retrieved from chassis
427413961deSRichard Marian Thomaiyar  * @param callback Callback for processing gathered connections
428413961deSRichard Marian Thomaiyar  */
429413961deSRichard Marian Thomaiyar template <typename Callback>
430fe04d49cSNan Zhou void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
431fe04d49cSNan Zhou                     const std::shared_ptr<std::set<std::string>> sensorNames,
432413961deSRichard Marian Thomaiyar                     Callback&& callback)
433413961deSRichard Marian Thomaiyar {
434413961deSRichard Marian Thomaiyar     auto objectsWithConnectionCb =
4358cb2c024SEd Tanous         [callback = std::forward<Callback>(callback)](
4368cb2c024SEd Tanous             const std::set<std::string>& connections,
437413961deSRichard Marian Thomaiyar             const std::set<std::pair<std::string, std::string>>&
4383174e4dfSEd Tanous             /*objectsWithConnection*/) { callback(connections); };
43981ce609eSEd Tanous     getObjectsWithConnection(sensorsAsyncResp, sensorNames,
440413961deSRichard Marian Thomaiyar                              std::move(objectsWithConnectionCb));
44108777fb0SLewanczyk, Dawid }
44208777fb0SLewanczyk, Dawid 
44308777fb0SLewanczyk, Dawid /**
44449c53ac9SJohnathan Mantey  * @brief Shrinks the list of sensors for processing
44549c53ac9SJohnathan Mantey  * @param SensorsAysncResp  The class holding the Redfish response
44649c53ac9SJohnathan Mantey  * @param allSensors  A list of all the sensors associated to the
44749c53ac9SJohnathan Mantey  * chassis element (i.e. baseboard, front panel, etc...)
44849c53ac9SJohnathan Mantey  * @param activeSensors A list that is a reduction of the incoming
44949c53ac9SJohnathan Mantey  * allSensors list.  Eliminate Thermal sensors when a Power request is
45049c53ac9SJohnathan Mantey  * made, and eliminate Power sensors when a Thermal request is made.
45149c53ac9SJohnathan Mantey  */
45223a21a1cSEd Tanous inline void reduceSensorList(
4537f1cc26dSEd Tanous     crow::Response& res, std::string_view chassisSubNode,
454cf9e417dSEd Tanous     std::span<const std::string_view> sensorTypes,
45549c53ac9SJohnathan Mantey     const std::vector<std::string>* allSensors,
456fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& activeSensors)
45749c53ac9SJohnathan Mantey {
45849c53ac9SJohnathan Mantey     if ((allSensors == nullptr) || (activeSensors == nullptr))
45949c53ac9SJohnathan Mantey     {
4607f1cc26dSEd Tanous         messages::resourceNotFound(res, chassisSubNode,
4617f1cc26dSEd Tanous                                    chassisSubNode == sensors::node::thermal
462a0ec28b6SAdrian Ambrożewicz                                        ? "Temperatures"
46349c53ac9SJohnathan Mantey                                        : "Voltages");
46449c53ac9SJohnathan Mantey 
46549c53ac9SJohnathan Mantey         return;
46649c53ac9SJohnathan Mantey     }
46749c53ac9SJohnathan Mantey     if (allSensors->empty())
46849c53ac9SJohnathan Mantey     {
46949c53ac9SJohnathan Mantey         // Nothing to do, the activeSensors object is also empty
47049c53ac9SJohnathan Mantey         return;
47149c53ac9SJohnathan Mantey     }
47249c53ac9SJohnathan Mantey 
4737f1cc26dSEd Tanous     for (std::string_view type : sensorTypes)
47449c53ac9SJohnathan Mantey     {
47549c53ac9SJohnathan Mantey         for (const std::string& sensor : *allSensors)
47649c53ac9SJohnathan Mantey         {
47711ba3979SEd Tanous             if (sensor.starts_with(type))
47849c53ac9SJohnathan Mantey             {
47949c53ac9SJohnathan Mantey                 activeSensors->emplace(sensor);
48049c53ac9SJohnathan Mantey             }
48149c53ac9SJohnathan Mantey         }
48249c53ac9SJohnathan Mantey     }
48349c53ac9SJohnathan Mantey }
48449c53ac9SJohnathan Mantey 
4857f1cc26dSEd Tanous /*
4867f1cc26dSEd Tanous  *Populates the top level collection for a given subnode.  Populates
4877f1cc26dSEd Tanous  *SensorCollection, Power, or Thermal schemas.
4887f1cc26dSEd Tanous  *
4897f1cc26dSEd Tanous  * */
4907f1cc26dSEd Tanous inline void populateChassisNode(nlohmann::json& jsonValue,
4917f1cc26dSEd Tanous                                 std::string_view chassisSubNode)
4927f1cc26dSEd Tanous {
4937f1cc26dSEd Tanous     if (chassisSubNode == sensors::node::power)
4947f1cc26dSEd Tanous     {
4957f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
4967f1cc26dSEd Tanous     }
4977f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::thermal)
4987f1cc26dSEd Tanous     {
4997f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
5007f1cc26dSEd Tanous         jsonValue["Fans"] = nlohmann::json::array();
5017f1cc26dSEd Tanous         jsonValue["Temperatures"] = nlohmann::json::array();
5027f1cc26dSEd Tanous     }
5037f1cc26dSEd Tanous     else if (chassisSubNode == sensors::node::sensors)
5047f1cc26dSEd Tanous     {
5057f1cc26dSEd Tanous         jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
5067f1cc26dSEd Tanous         jsonValue["Description"] = "Collection of Sensors for this Chassis";
5077f1cc26dSEd Tanous         jsonValue["Members"] = nlohmann::json::array();
5087f1cc26dSEd Tanous         jsonValue["Members@odata.count"] = 0;
5097f1cc26dSEd Tanous     }
5107f1cc26dSEd Tanous 
5117f1cc26dSEd Tanous     if (chassisSubNode != sensors::node::sensors)
5127f1cc26dSEd Tanous     {
5137f1cc26dSEd Tanous         jsonValue["Id"] = chassisSubNode;
5147f1cc26dSEd Tanous     }
5157f1cc26dSEd Tanous     jsonValue["Name"] = chassisSubNode;
5167f1cc26dSEd Tanous }
5177f1cc26dSEd Tanous 
51849c53ac9SJohnathan Mantey /**
51908777fb0SLewanczyk, Dawid  * @brief Retrieves requested chassis sensors and redundancy data from DBus .
520588c3f0dSKowalski, Kamil  * @param SensorsAsyncResp   Pointer to object holding response data
52108777fb0SLewanczyk, Dawid  * @param callback  Callback for next step in gathered sensor processing
52208777fb0SLewanczyk, Dawid  */
52308777fb0SLewanczyk, Dawid template <typename Callback>
5247f1cc26dSEd Tanous void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
5257f1cc26dSEd Tanous                 std::string_view chassisId, std::string_view chassisSubNode,
526cf9e417dSEd Tanous                 std::span<const std::string_view> sensorTypes,
527cf9e417dSEd Tanous                 Callback&& callback)
5281abe55efSEd Tanous {
52962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis enter");
5307a1dbc48SGeorge Liu     constexpr std::array<std::string_view, 2> interfaces = {
53149c53ac9SJohnathan Mantey         "xyz.openbmc_project.Inventory.Item.Board",
532adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.Chassis"};
5337a1dbc48SGeorge Liu 
5347a1dbc48SGeorge Liu     // Get the Chassis Collection
5357a1dbc48SGeorge Liu     dbus::utility::getSubTreePaths(
5367a1dbc48SGeorge Liu         "/xyz/openbmc_project/inventory", 0, interfaces,
5378cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), asyncResp,
5387f1cc26dSEd Tanous          chassisIdStr{std::string(chassisId)},
5397f1cc26dSEd Tanous          chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
5407a1dbc48SGeorge Liu             const boost::system::error_code& ec,
541002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
54262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassis respHandler enter");
5431abe55efSEd Tanous         if (ec)
5441abe55efSEd Tanous         {
54562598e31SEd Tanous             BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
5467f1cc26dSEd Tanous             messages::internalError(asyncResp->res);
54708777fb0SLewanczyk, Dawid             return;
54808777fb0SLewanczyk, Dawid         }
54949c53ac9SJohnathan Mantey         const std::string* chassisPath = nullptr;
55049c53ac9SJohnathan Mantey         for (const std::string& chassis : chassisPaths)
5511abe55efSEd Tanous         {
55228aa8de5SGeorge Liu             sdbusplus::message::object_path path(chassis);
553f8fe53e7SEd Tanous             std::string chassisName = path.filename();
55428aa8de5SGeorge Liu             if (chassisName.empty())
5551abe55efSEd Tanous             {
55662598e31SEd Tanous                 BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
557daf36e2eSEd Tanous                 continue;
558daf36e2eSEd Tanous             }
5597f1cc26dSEd Tanous             if (chassisName == chassisIdStr)
5601abe55efSEd Tanous             {
56149c53ac9SJohnathan Mantey                 chassisPath = &chassis;
56249c53ac9SJohnathan Mantey                 break;
563daf36e2eSEd Tanous             }
56449c53ac9SJohnathan Mantey         }
56549c53ac9SJohnathan Mantey         if (chassisPath == nullptr)
5661abe55efSEd Tanous         {
5677f1cc26dSEd Tanous             messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
56849c53ac9SJohnathan Mantey             return;
5691abe55efSEd Tanous         }
5707f1cc26dSEd Tanous         populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
57108777fb0SLewanczyk, Dawid 
572ef4c65b7SEd Tanous         asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
573ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
57495a3ecadSAnthony Wilson 
5758fb49dd6SShawn McCarney         // Get the list of all sensors for this Chassis element
5768fb49dd6SShawn McCarney         std::string sensorPath = *chassisPath + "/all_sensors";
5776c3e9451SGeorge Liu         dbus::utility::getAssociationEndPoints(
5786c3e9451SGeorge Liu             sensorPath,
5797f1cc26dSEd Tanous             [asyncResp, chassisSubNode, sensorTypes,
5808cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
5818b24275dSEd Tanous                 const boost::system::error_code& ec2,
5826c3e9451SGeorge Liu                 const dbus::utility::MapperEndPoints& nodeSensorList) {
5838b24275dSEd Tanous             if (ec2)
58449c53ac9SJohnathan Mantey             {
5858b24275dSEd Tanous                 if (ec2.value() != EBADR)
58649c53ac9SJohnathan Mantey                 {
5877f1cc26dSEd Tanous                     messages::internalError(asyncResp->res);
58849c53ac9SJohnathan Mantey                     return;
58949c53ac9SJohnathan Mantey                 }
59049c53ac9SJohnathan Mantey             }
591fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>> culledSensorList =
592fe04d49cSNan Zhou                 std::make_shared<std::set<std::string>>();
5937f1cc26dSEd Tanous             reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
5947f1cc26dSEd Tanous                              &nodeSensorList, culledSensorList);
59562598e31SEd Tanous             BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
59649c53ac9SJohnathan Mantey             callback(culledSensorList);
5971e1e598dSJonathan Doman         });
5987a1dbc48SGeorge Liu     });
59962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassis exit");
60008777fb0SLewanczyk, Dawid }
60108777fb0SLewanczyk, Dawid 
60208777fb0SLewanczyk, Dawid /**
603adc4f0dbSShawn McCarney  * @brief Returns the Redfish State value for the specified inventory item.
604adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with a sensor.
605aaf08ac7SMatt Simmering  * @param sensorAvailable Boolean representing if D-Bus sensor is marked as
606aaf08ac7SMatt Simmering  * available.
607adc4f0dbSShawn McCarney  * @return State value for inventory item.
60834dd179eSJames Feist  */
609aaf08ac7SMatt Simmering inline resource::State getState(const InventoryItem* inventoryItem,
610aaf08ac7SMatt Simmering                                 const bool sensorAvailable)
611adc4f0dbSShawn McCarney {
612adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
613adc4f0dbSShawn McCarney     {
614aaf08ac7SMatt Simmering         return resource::State::Absent;
615adc4f0dbSShawn McCarney     }
61634dd179eSJames Feist 
617aaf08ac7SMatt Simmering     if (!sensorAvailable)
618aaf08ac7SMatt Simmering     {
619aaf08ac7SMatt Simmering         return resource::State::UnavailableOffline;
620aaf08ac7SMatt Simmering     }
621aaf08ac7SMatt Simmering 
622aaf08ac7SMatt Simmering     return resource::State::Enabled;
623adc4f0dbSShawn McCarney }
624adc4f0dbSShawn McCarney 
625adc4f0dbSShawn McCarney /**
626adc4f0dbSShawn McCarney  * @brief Returns the Redfish Health value for the specified sensor.
627adc4f0dbSShawn McCarney  * @param sensorJson Sensor JSON object.
6281d7c0054SEd Tanous  * @param valuesDict Map of all sensor DBus values.
629adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
630adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
631adc4f0dbSShawn McCarney  * @return Health value for sensor.
632adc4f0dbSShawn McCarney  */
6331d7c0054SEd Tanous inline std::string getHealth(nlohmann::json& sensorJson,
6341d7c0054SEd Tanous                              const dbus::utility::DBusPropertiesMap& valuesDict,
635adc4f0dbSShawn McCarney                              const InventoryItem* inventoryItem)
63634dd179eSJames Feist {
637adc4f0dbSShawn McCarney     // Get current health value (if any) in the sensor JSON object.  Some JSON
638adc4f0dbSShawn McCarney     // objects contain multiple sensors (such as PowerSupplies).  We want to set
639adc4f0dbSShawn McCarney     // the overall health to be the most severe of any of the sensors.
640adc4f0dbSShawn McCarney     std::string currentHealth;
641adc4f0dbSShawn McCarney     auto statusIt = sensorJson.find("Status");
642adc4f0dbSShawn McCarney     if (statusIt != sensorJson.end())
643adc4f0dbSShawn McCarney     {
644adc4f0dbSShawn McCarney         auto healthIt = statusIt->find("Health");
645adc4f0dbSShawn McCarney         if (healthIt != statusIt->end())
646adc4f0dbSShawn McCarney         {
647adc4f0dbSShawn McCarney             std::string* health = healthIt->get_ptr<std::string*>();
648adc4f0dbSShawn McCarney             if (health != nullptr)
649adc4f0dbSShawn McCarney             {
650adc4f0dbSShawn McCarney                 currentHealth = *health;
651adc4f0dbSShawn McCarney             }
652adc4f0dbSShawn McCarney         }
653adc4f0dbSShawn McCarney     }
654adc4f0dbSShawn McCarney 
655adc4f0dbSShawn McCarney     // If current health in JSON object is already Critical, return that.  This
656adc4f0dbSShawn McCarney     // should override the sensor health, which might be less severe.
657adc4f0dbSShawn McCarney     if (currentHealth == "Critical")
658adc4f0dbSShawn McCarney     {
659adc4f0dbSShawn McCarney         return "Critical";
660adc4f0dbSShawn McCarney     }
661adc4f0dbSShawn McCarney 
662c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmHigh = nullptr;
663c1343bf6SKrzysztof Grobelny     const bool* criticalAlarmLow = nullptr;
664c1343bf6SKrzysztof Grobelny     const bool* warningAlarmHigh = nullptr;
665c1343bf6SKrzysztof Grobelny     const bool* warningAlarmLow = nullptr;
666711ac7a9SEd Tanous 
667c1343bf6SKrzysztof Grobelny     const bool success = sdbusplus::unpackPropertiesNoThrow(
668c1343bf6SKrzysztof Grobelny         dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
669c1343bf6SKrzysztof Grobelny         criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
670c1343bf6SKrzysztof Grobelny         "WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
671c1343bf6SKrzysztof Grobelny         warningAlarmLow);
672c1343bf6SKrzysztof Grobelny 
673c1343bf6SKrzysztof Grobelny     if (success)
67434dd179eSJames Feist     {
675c1343bf6SKrzysztof Grobelny         // Check if sensor has critical threshold alarm
676c1343bf6SKrzysztof Grobelny         if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
677c1343bf6SKrzysztof Grobelny             (criticalAlarmLow != nullptr && *criticalAlarmLow))
67834dd179eSJames Feist         {
67934dd179eSJames Feist             return "Critical";
68034dd179eSJames Feist         }
68134dd179eSJames Feist     }
68234dd179eSJames Feist 
683adc4f0dbSShawn McCarney     // Check if associated inventory item is not functional
684adc4f0dbSShawn McCarney     if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
685adc4f0dbSShawn McCarney     {
686adc4f0dbSShawn McCarney         return "Critical";
687adc4f0dbSShawn McCarney     }
688adc4f0dbSShawn McCarney 
689adc4f0dbSShawn McCarney     // If current health in JSON object is already Warning, return that. This
690adc4f0dbSShawn McCarney     // should override the sensor status, which might be less severe.
691adc4f0dbSShawn McCarney     if (currentHealth == "Warning")
692adc4f0dbSShawn McCarney     {
693adc4f0dbSShawn McCarney         return "Warning";
694adc4f0dbSShawn McCarney     }
695adc4f0dbSShawn McCarney 
696c1343bf6SKrzysztof Grobelny     if (success)
697c1343bf6SKrzysztof Grobelny     {
698adc4f0dbSShawn McCarney         // Check if sensor has warning threshold alarm
699c1343bf6SKrzysztof Grobelny         if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
700c1343bf6SKrzysztof Grobelny             (warningAlarmLow != nullptr && *warningAlarmLow))
70134dd179eSJames Feist         {
702ebe4d91eSEd Tanous             return "Warning";
70334dd179eSJames Feist         }
70434dd179eSJames Feist     }
705adc4f0dbSShawn McCarney 
70634dd179eSJames Feist     return "OK";
70734dd179eSJames Feist }
70834dd179eSJames Feist 
70923a21a1cSEd Tanous inline void setLedState(nlohmann::json& sensorJson,
710d500549bSAnthony Wilson                         const InventoryItem* inventoryItem)
711d500549bSAnthony Wilson {
712d500549bSAnthony Wilson     if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
713d500549bSAnthony Wilson     {
714d500549bSAnthony Wilson         switch (inventoryItem->ledState)
715d500549bSAnthony Wilson         {
716d500549bSAnthony Wilson             case LedState::OFF:
717d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Off";
718d500549bSAnthony Wilson                 break;
719d500549bSAnthony Wilson             case LedState::ON:
720d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Lit";
721d500549bSAnthony Wilson                 break;
722d500549bSAnthony Wilson             case LedState::BLINK:
723d500549bSAnthony Wilson                 sensorJson["IndicatorLED"] = "Blinking";
724d500549bSAnthony Wilson                 break;
7254da0490bSEd Tanous             default:
726d500549bSAnthony Wilson                 break;
727d500549bSAnthony Wilson         }
728d500549bSAnthony Wilson     }
729d500549bSAnthony Wilson }
730d500549bSAnthony Wilson 
73134dd179eSJames Feist /**
73208777fb0SLewanczyk, Dawid  * @brief Builds a json sensor representation of a sensor.
73308777fb0SLewanczyk, Dawid  * @param sensorName  The name of the sensor to be built
734274fad5aSGunnar Mills  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
73508777fb0SLewanczyk, Dawid  * build
7368ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
7371d7c0054SEd Tanous  * @param propertiesDict A dictionary of the properties to build the sensor
7381d7c0054SEd Tanous  * from.
7391d7c0054SEd Tanous  * @param sensorJson  The json object to fill
740adc4f0dbSShawn McCarney  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
741adc4f0dbSShawn McCarney  * be nullptr if no associated inventory item was found.
74208777fb0SLewanczyk, Dawid  */
7431d7c0054SEd Tanous inline void objectPropertiesToJson(
7441d7c0054SEd Tanous     std::string_view sensorName, std::string_view sensorType,
7451d7c0054SEd Tanous     std::string_view chassisSubNode,
7461d7c0054SEd Tanous     const dbus::utility::DBusPropertiesMap& propertiesDict,
74781ce609eSEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
7481abe55efSEd Tanous {
7491d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
750adc4f0dbSShawn McCarney     {
751c71d6125SEd Tanous         std::string subNodeEscaped(sensorType);
7523544d2a7SEd Tanous         auto remove = std::ranges::remove(subNodeEscaped, '_');
7533544d2a7SEd Tanous         subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
754c1d019a6SEd Tanous 
755c1d019a6SEd Tanous         // For sensors in SensorCollection we set Id instead of MemberId,
756c1d019a6SEd Tanous         // including power sensors.
757c1d019a6SEd Tanous         subNodeEscaped += '_';
758c1d019a6SEd Tanous         subNodeEscaped += sensorName;
759c1d019a6SEd Tanous         sensorJson["Id"] = std::move(subNodeEscaped);
760c1d019a6SEd Tanous 
7611d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7621d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7631d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
76495a3ecadSAnthony Wilson     }
76595a3ecadSAnthony Wilson     else if (sensorType != "power")
76695a3ecadSAnthony Wilson     {
76795a3ecadSAnthony Wilson         // Set MemberId and Name for non-power sensors.  For PowerSupplies and
76895a3ecadSAnthony Wilson         // PowerControl, those properties have more general values because
76995a3ecadSAnthony Wilson         // multiple sensors can be stored in the same JSON object.
7701d7c0054SEd Tanous         std::string sensorNameEs(sensorName);
7711d7c0054SEd Tanous         std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
7721d7c0054SEd Tanous         sensorJson["Name"] = std::move(sensorNameEs);
773adc4f0dbSShawn McCarney     }
774e742b6ccSEd Tanous 
775aaf08ac7SMatt Simmering     const bool* checkAvailable = nullptr;
776aaf08ac7SMatt Simmering     bool available = true;
777aaf08ac7SMatt Simmering     const bool success = sdbusplus::unpackPropertiesNoThrow(
778aaf08ac7SMatt Simmering         dbus_utils::UnpackErrorPrinter(), propertiesDict, "Available",
779aaf08ac7SMatt Simmering         checkAvailable);
780aaf08ac7SMatt Simmering     if (!success)
781aaf08ac7SMatt Simmering     {
782aaf08ac7SMatt Simmering         messages::internalError();
783aaf08ac7SMatt Simmering     }
784aaf08ac7SMatt Simmering     if (checkAvailable != nullptr)
785aaf08ac7SMatt Simmering     {
786aaf08ac7SMatt Simmering         available = *checkAvailable;
787aaf08ac7SMatt Simmering     }
788aaf08ac7SMatt Simmering 
789aaf08ac7SMatt Simmering     sensorJson["Status"]["State"] = getState(inventoryItem, available);
79089492a15SPatrick Williams     sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
79189492a15SPatrick Williams                                                inventoryItem);
79208777fb0SLewanczyk, Dawid 
79308777fb0SLewanczyk, Dawid     // Parameter to set to override the type we get from dbus, and force it to
79408777fb0SLewanczyk, Dawid     // int, regardless of what is available.  This is used for schemas like fan,
79508777fb0SLewanczyk, Dawid     // that require integers, not floats.
79608777fb0SLewanczyk, Dawid     bool forceToInt = false;
79708777fb0SLewanczyk, Dawid 
7983929aca1SAnthony Wilson     nlohmann::json::json_pointer unit("/Reading");
7991d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
80095a3ecadSAnthony Wilson     {
8012a4ba195SShounak Mitra         sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
802c2bf7f99SWludzik, Jozef 
8030ec8b83dSEd Tanous         sensor::ReadingType readingType = sensors::toReadingType(sensorType);
8040ec8b83dSEd Tanous         if (readingType == sensor::ReadingType::Invalid)
80595a3ecadSAnthony Wilson         {
80662598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
80762598e31SEd Tanous                              sensorType);
80895a3ecadSAnthony Wilson         }
809c2bf7f99SWludzik, Jozef         else
81095a3ecadSAnthony Wilson         {
811c2bf7f99SWludzik, Jozef             sensorJson["ReadingType"] = readingType;
81295a3ecadSAnthony Wilson         }
813c2bf7f99SWludzik, Jozef 
8141d7c0054SEd Tanous         std::string_view readingUnits = sensors::toReadingUnits(sensorType);
815c2bf7f99SWludzik, Jozef         if (readingUnits.empty())
816f8ede15eSAdrian Ambrożewicz         {
81762598e31SEd Tanous             BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
81862598e31SEd Tanous                              sensorType);
819c2bf7f99SWludzik, Jozef         }
820c2bf7f99SWludzik, Jozef         else
821c2bf7f99SWludzik, Jozef         {
822c2bf7f99SWludzik, Jozef             sensorJson["ReadingUnits"] = readingUnits;
823f8ede15eSAdrian Ambrożewicz         }
82495a3ecadSAnthony Wilson     }
82595a3ecadSAnthony Wilson     else if (sensorType == "temperature")
8261abe55efSEd Tanous     {
8273929aca1SAnthony Wilson         unit = "/ReadingCelsius"_json_pointer;
82881ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
82908777fb0SLewanczyk, Dawid         // TODO(ed) Documentation says that path should be type fan_tach,
83008777fb0SLewanczyk, Dawid         // implementation seems to implement fan
8311abe55efSEd Tanous     }
8321abe55efSEd Tanous     else if (sensorType == "fan" || sensorType == "fan_tach")
8331abe55efSEd Tanous     {
8343929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
83581ce609eSEd Tanous         sensorJson["ReadingUnits"] = "RPM";
83681ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
83781ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
83808777fb0SLewanczyk, Dawid         forceToInt = true;
8391abe55efSEd Tanous     }
8406f6d0d32SEd Tanous     else if (sensorType == "fan_pwm")
8416f6d0d32SEd Tanous     {
8423929aca1SAnthony Wilson         unit = "/Reading"_json_pointer;
84381ce609eSEd Tanous         sensorJson["ReadingUnits"] = "Percent";
84481ce609eSEd Tanous         sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
84581ce609eSEd Tanous         setLedState(sensorJson, inventoryItem);
8466f6d0d32SEd Tanous         forceToInt = true;
8476f6d0d32SEd Tanous     }
8481abe55efSEd Tanous     else if (sensorType == "voltage")
8491abe55efSEd Tanous     {
8503929aca1SAnthony Wilson         unit = "/ReadingVolts"_json_pointer;
85181ce609eSEd Tanous         sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
8521abe55efSEd Tanous     }
8532474adfaSEd Tanous     else if (sensorType == "power")
8542474adfaSEd Tanous     {
85518f8f608SEd Tanous         std::string lower;
85618f8f608SEd Tanous         std::ranges::transform(sensorName, std::back_inserter(lower),
85718f8f608SEd Tanous                                bmcweb::asciiToLower);
85818f8f608SEd Tanous         if (lower == "total_power")
859028f7ebcSEddie James         {
86081ce609eSEd Tanous             sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
8617ab06f49SGunnar Mills             // Put multiple "sensors" into a single PowerControl, so have
8627ab06f49SGunnar Mills             // generic names for MemberId and Name. Follows Redfish mockup.
86381ce609eSEd Tanous             sensorJson["MemberId"] = "0";
86481ce609eSEd Tanous             sensorJson["Name"] = "Chassis Power Control";
8653929aca1SAnthony Wilson             unit = "/PowerConsumedWatts"_json_pointer;
866028f7ebcSEddie James         }
86718f8f608SEd Tanous         else if (lower.find("input") != std::string::npos)
86849c53ac9SJohnathan Mantey         {
8693929aca1SAnthony Wilson             unit = "/PowerInputWatts"_json_pointer;
87049c53ac9SJohnathan Mantey         }
87149c53ac9SJohnathan Mantey         else
87249c53ac9SJohnathan Mantey         {
8733929aca1SAnthony Wilson             unit = "/PowerOutputWatts"_json_pointer;
87449c53ac9SJohnathan Mantey         }
8752474adfaSEd Tanous     }
8761abe55efSEd Tanous     else
8771abe55efSEd Tanous     {
87862598e31SEd Tanous         BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
87908777fb0SLewanczyk, Dawid         return;
88008777fb0SLewanczyk, Dawid     }
88108777fb0SLewanczyk, Dawid     // Map of dbus interface name, dbus property name and redfish property_name
8823929aca1SAnthony Wilson     std::vector<
8833929aca1SAnthony Wilson         std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
8843929aca1SAnthony Wilson         properties;
88508777fb0SLewanczyk, Dawid     properties.reserve(7);
88608777fb0SLewanczyk, Dawid 
88708777fb0SLewanczyk, Dawid     properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
888de629b6eSShawn McCarney 
8891d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
8903929aca1SAnthony Wilson     {
8913929aca1SAnthony Wilson         properties.emplace_back(
8923929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
8933929aca1SAnthony Wilson             "/Thresholds/UpperCaution/Reading"_json_pointer);
8943929aca1SAnthony Wilson         properties.emplace_back(
8953929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
8963929aca1SAnthony Wilson             "/Thresholds/LowerCaution/Reading"_json_pointer);
8973929aca1SAnthony Wilson         properties.emplace_back(
8983929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
8993929aca1SAnthony Wilson             "/Thresholds/UpperCritical/Reading"_json_pointer);
9003929aca1SAnthony Wilson         properties.emplace_back(
9013929aca1SAnthony Wilson             "xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
9023929aca1SAnthony Wilson             "/Thresholds/LowerCritical/Reading"_json_pointer);
9033929aca1SAnthony Wilson     }
9043929aca1SAnthony Wilson     else if (sensorType != "power")
905de629b6eSShawn McCarney     {
90608777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9073929aca1SAnthony Wilson                                 "WarningHigh",
9083929aca1SAnthony Wilson                                 "/UpperThresholdNonCritical"_json_pointer);
90908777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
9103929aca1SAnthony Wilson                                 "WarningLow",
9113929aca1SAnthony Wilson                                 "/LowerThresholdNonCritical"_json_pointer);
91208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9133929aca1SAnthony Wilson                                 "CriticalHigh",
9143929aca1SAnthony Wilson                                 "/UpperThresholdCritical"_json_pointer);
91508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
9163929aca1SAnthony Wilson                                 "CriticalLow",
9173929aca1SAnthony Wilson                                 "/LowerThresholdCritical"_json_pointer);
918de629b6eSShawn McCarney     }
91908777fb0SLewanczyk, Dawid 
9202474adfaSEd Tanous     // TODO Need to get UpperThresholdFatal and LowerThresholdFatal
9212474adfaSEd Tanous 
9221d7c0054SEd Tanous     if (chassisSubNode == sensors::node::sensors)
92395a3ecadSAnthony Wilson     {
92495a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9253929aca1SAnthony Wilson                                 "/ReadingRangeMin"_json_pointer);
92695a3ecadSAnthony Wilson         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9273929aca1SAnthony Wilson                                 "/ReadingRangeMax"_json_pointer);
92851c35a8fSGeorge Liu         properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
92951c35a8fSGeorge Liu                                 "Accuracy", "/Accuracy"_json_pointer);
93095a3ecadSAnthony Wilson     }
93195a3ecadSAnthony Wilson     else if (sensorType == "temperature")
9321abe55efSEd Tanous     {
93308777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9343929aca1SAnthony Wilson                                 "/MinReadingRangeTemp"_json_pointer);
93508777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9363929aca1SAnthony Wilson                                 "/MaxReadingRangeTemp"_json_pointer);
9371abe55efSEd Tanous     }
938adc4f0dbSShawn McCarney     else if (sensorType != "power")
9391abe55efSEd Tanous     {
94008777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
9413929aca1SAnthony Wilson                                 "/MinReadingRange"_json_pointer);
94208777fb0SLewanczyk, Dawid         properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
9433929aca1SAnthony Wilson                                 "/MaxReadingRange"_json_pointer);
94408777fb0SLewanczyk, Dawid     }
94508777fb0SLewanczyk, Dawid 
9463929aca1SAnthony Wilson     for (const std::tuple<const char*, const char*,
9473929aca1SAnthony Wilson                           nlohmann::json::json_pointer>& p : properties)
9481abe55efSEd Tanous     {
9491d7c0054SEd Tanous         for (const auto& [valueName, valueVariant] : propertiesDict)
950711ac7a9SEd Tanous         {
951711ac7a9SEd Tanous             if (valueName != std::get<1>(p))
952711ac7a9SEd Tanous             {
953711ac7a9SEd Tanous                 continue;
954711ac7a9SEd Tanous             }
9553929aca1SAnthony Wilson 
9563929aca1SAnthony Wilson             // The property we want to set may be nested json, so use
9573929aca1SAnthony Wilson             // a json_pointer for easy indexing into the json structure.
9583929aca1SAnthony Wilson             const nlohmann::json::json_pointer& key = std::get<2>(p);
9593929aca1SAnthony Wilson 
960abf2add6SEd Tanous             const double* doubleValue = std::get_if<double>(&valueVariant);
96140e4f380SEd Tanous             if (doubleValue == nullptr)
9621abe55efSEd Tanous             {
96362598e31SEd Tanous                 BMCWEB_LOG_ERROR("Got value interface that wasn't double");
9646f6d0d32SEd Tanous                 continue;
96508777fb0SLewanczyk, Dawid             }
966283860f5SEd Tanous             if (!std::isfinite(*doubleValue))
967283860f5SEd Tanous             {
968283860f5SEd Tanous                 if (valueName == "Value")
969283860f5SEd Tanous                 {
970283860f5SEd Tanous                     // Readings are allowed to be NAN for unavailable;  coerce
971283860f5SEd Tanous                     // them to null in the json response.
972283860f5SEd Tanous                     sensorJson[key] = nullptr;
973283860f5SEd Tanous                     continue;
974283860f5SEd Tanous                 }
97562598e31SEd Tanous                 BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
97662598e31SEd Tanous                                    valueName, *doubleValue);
977283860f5SEd Tanous                 continue;
978283860f5SEd Tanous             }
9796f6d0d32SEd Tanous             if (forceToInt)
9806f6d0d32SEd Tanous             {
98140e4f380SEd Tanous                 sensorJson[key] = static_cast<int64_t>(*doubleValue);
9826f6d0d32SEd Tanous             }
9836f6d0d32SEd Tanous             else
9846f6d0d32SEd Tanous             {
98540e4f380SEd Tanous                 sensorJson[key] = *doubleValue;
98608777fb0SLewanczyk, Dawid             }
98708777fb0SLewanczyk, Dawid         }
98808777fb0SLewanczyk, Dawid     }
98908777fb0SLewanczyk, Dawid }
99008777fb0SLewanczyk, Dawid 
9911d7c0054SEd Tanous /**
9921d7c0054SEd Tanous  * @brief Builds a json sensor representation of a sensor.
9931d7c0054SEd Tanous  * @param sensorName  The name of the sensor to be built
9941d7c0054SEd Tanous  * @param sensorType  The type (temperature, fan_tach, etc) of the sensor to
9951d7c0054SEd Tanous  * build
9968ece0e45SEd Tanous  * @param chassisSubNode The subnode (thermal, sensor, etc) of the sensor
9971d7c0054SEd Tanous  * @param interfacesDict  A dictionary of the interfaces and properties of said
9981d7c0054SEd Tanous  * interfaces to be built from
9991d7c0054SEd Tanous  * @param sensorJson  The json object to fill
10001d7c0054SEd Tanous  * @param inventoryItem D-Bus inventory item associated with the sensor.  Will
10011d7c0054SEd Tanous  * be nullptr if no associated inventory item was found.
10021d7c0054SEd Tanous  */
10031d7c0054SEd Tanous inline void objectInterfacesToJson(
10041d7c0054SEd Tanous     const std::string& sensorName, const std::string& sensorType,
10051d7c0054SEd Tanous     const std::string& chassisSubNode,
100680f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict,
10071d7c0054SEd Tanous     nlohmann::json& sensorJson, InventoryItem* inventoryItem)
10081d7c0054SEd Tanous {
10091d7c0054SEd Tanous     for (const auto& [interface, valuesDict] : interfacesDict)
10101d7c0054SEd Tanous     {
10111d7c0054SEd Tanous         objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
10121d7c0054SEd Tanous                                valuesDict, sensorJson, inventoryItem);
10131d7c0054SEd Tanous     }
101462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
10151d7c0054SEd Tanous }
10161d7c0054SEd Tanous 
1017b5a76932SEd Tanous inline void populateFanRedundancy(
1018b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
10198bd25ccdSJames Feist {
1020e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1021e99073f5SGeorge Liu         "xyz.openbmc_project.Control.FanRedundancy"};
1022e99073f5SGeorge Liu     dbus::utility::getSubTree(
1023e99073f5SGeorge Liu         "/xyz/openbmc_project/control", 2, interfaces,
1024b9d36b47SEd Tanous         [sensorsAsyncResp](
1025e99073f5SGeorge Liu             const boost::system::error_code& ec,
1026b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& resp) {
10278bd25ccdSJames Feist         if (ec)
10288bd25ccdSJames Feist         {
10298bd25ccdSJames Feist             return; // don't have to have this interface
10308bd25ccdSJames Feist         }
10316c3e9451SGeorge Liu         for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
1032e278c18fSEd Tanous                  pathPair : resp)
10338bd25ccdSJames Feist         {
1034e278c18fSEd Tanous             const std::string& path = pathPair.first;
10356c3e9451SGeorge Liu             const dbus::utility::MapperServiceMap& objDict = pathPair.second;
10368bd25ccdSJames Feist             if (objDict.empty())
10378bd25ccdSJames Feist             {
10388bd25ccdSJames Feist                 continue; // this should be impossible
10398bd25ccdSJames Feist             }
10408bd25ccdSJames Feist 
10418bd25ccdSJames Feist             const std::string& owner = objDict.begin()->first;
10426c3e9451SGeorge Liu             dbus::utility::getAssociationEndPoints(
10436c3e9451SGeorge Liu                 path + "/chassis",
10446c3e9451SGeorge Liu                 [path, owner, sensorsAsyncResp](
10458b24275dSEd Tanous                     const boost::system::error_code& ec2,
10466c3e9451SGeorge Liu                     const dbus::utility::MapperEndPoints& endpoints) {
10478b24275dSEd Tanous                 if (ec2)
10488bd25ccdSJames Feist                 {
10498bd25ccdSJames Feist                     return; // if they don't have an association we
10508bd25ccdSJames Feist                             // can't tell what chassis is
10518bd25ccdSJames Feist                 }
10523544d2a7SEd Tanous                 auto found = std::ranges::find_if(
10533544d2a7SEd Tanous                     endpoints, [sensorsAsyncResp](const std::string& entry) {
1054002d39b4SEd Tanous                     return entry.find(sensorsAsyncResp->chassisId) !=
10558bd25ccdSJames Feist                            std::string::npos;
10568bd25ccdSJames Feist                 });
10578bd25ccdSJames Feist 
10581e1e598dSJonathan Doman                 if (found == endpoints.end())
10598bd25ccdSJames Feist                 {
10608bd25ccdSJames Feist                     return;
10618bd25ccdSJames Feist                 }
106286d89ed7SKrzysztof Grobelny                 sdbusplus::asio::getAllProperties(
106386d89ed7SKrzysztof Grobelny                     *crow::connections::systemBus, owner, path,
106486d89ed7SKrzysztof Grobelny                     "xyz.openbmc_project.Control.FanRedundancy",
10658bd25ccdSJames Feist                     [path, sensorsAsyncResp](
10668b24275dSEd Tanous                         const boost::system::error_code& ec3,
106786d89ed7SKrzysztof Grobelny                         const dbus::utility::DBusPropertiesMap& ret) {
10688b24275dSEd Tanous                     if (ec3)
10698bd25ccdSJames Feist                     {
10708bd25ccdSJames Feist                         return; // don't have to have this
10718bd25ccdSJames Feist                                 // interface
10728bd25ccdSJames Feist                     }
10738bd25ccdSJames Feist 
107486d89ed7SKrzysztof Grobelny                     const uint8_t* allowedFailures = nullptr;
107586d89ed7SKrzysztof Grobelny                     const std::vector<std::string>* collection = nullptr;
107686d89ed7SKrzysztof Grobelny                     const std::string* status = nullptr;
107786d89ed7SKrzysztof Grobelny 
107886d89ed7SKrzysztof Grobelny                     const bool success = sdbusplus::unpackPropertiesNoThrow(
107986d89ed7SKrzysztof Grobelny                         dbus_utils::UnpackErrorPrinter(), ret,
108086d89ed7SKrzysztof Grobelny                         "AllowedFailures", allowedFailures, "Collection",
108186d89ed7SKrzysztof Grobelny                         collection, "Status", status);
108286d89ed7SKrzysztof Grobelny 
108386d89ed7SKrzysztof Grobelny                     if (!success)
108486d89ed7SKrzysztof Grobelny                     {
108586d89ed7SKrzysztof Grobelny                         messages::internalError(
108686d89ed7SKrzysztof Grobelny                             sensorsAsyncResp->asyncResp->res);
108786d89ed7SKrzysztof Grobelny                         return;
108886d89ed7SKrzysztof Grobelny                     }
108986d89ed7SKrzysztof Grobelny 
109086d89ed7SKrzysztof Grobelny                     if (allowedFailures == nullptr || collection == nullptr ||
109186d89ed7SKrzysztof Grobelny                         status == nullptr)
10928bd25ccdSJames Feist                     {
109362598e31SEd Tanous                         BMCWEB_LOG_ERROR("Invalid redundancy interface");
10948bd25ccdSJames Feist                         messages::internalError(
10958d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
10968bd25ccdSJames Feist                         return;
10978bd25ccdSJames Feist                     }
10988bd25ccdSJames Feist 
1099002d39b4SEd Tanous                     sdbusplus::message::object_path objectPath(path);
110028aa8de5SGeorge Liu                     std::string name = objectPath.filename();
110128aa8de5SGeorge Liu                     if (name.empty())
11028bd25ccdSJames Feist                     {
11038bd25ccdSJames Feist                         // this should be impossible
11048bd25ccdSJames Feist                         messages::internalError(
11058d1b46d7Szhanghch05                             sensorsAsyncResp->asyncResp->res);
11068bd25ccdSJames Feist                         return;
11078bd25ccdSJames Feist                     }
110818f8f608SEd Tanous                     std::ranges::replace(name, '_', ' ');
11098bd25ccdSJames Feist 
11108bd25ccdSJames Feist                     std::string health;
11118bd25ccdSJames Feist 
111211ba3979SEd Tanous                     if (status->ends_with("Full"))
11138bd25ccdSJames Feist                     {
11148bd25ccdSJames Feist                         health = "OK";
11158bd25ccdSJames Feist                     }
111611ba3979SEd Tanous                     else if (status->ends_with("Degraded"))
11178bd25ccdSJames Feist                     {
11188bd25ccdSJames Feist                         health = "Warning";
11198bd25ccdSJames Feist                     }
11208bd25ccdSJames Feist                     else
11218bd25ccdSJames Feist                     {
11228bd25ccdSJames Feist                         health = "Critical";
11238bd25ccdSJames Feist                     }
11241476687dSEd Tanous                     nlohmann::json::array_t redfishCollection;
11258bd25ccdSJames Feist                     const auto& fanRedfish =
1126002d39b4SEd Tanous                         sensorsAsyncResp->asyncResp->res.jsonValue["Fans"];
11278bd25ccdSJames Feist                     for (const std::string& item : *collection)
11288bd25ccdSJames Feist                     {
11298a592810SEd Tanous                         sdbusplus::message::object_path itemPath(item);
11308a592810SEd Tanous                         std::string itemName = itemPath.filename();
113128aa8de5SGeorge Liu                         if (itemName.empty())
113228aa8de5SGeorge Liu                         {
113328aa8de5SGeorge Liu                             continue;
113428aa8de5SGeorge Liu                         }
11358bd25ccdSJames Feist                         /*
11368bd25ccdSJames Feist                         todo(ed): merge patch that fixes the names
11378bd25ccdSJames Feist                         std::replace(itemName.begin(),
11388bd25ccdSJames Feist                                      itemName.end(), '_', ' ');*/
11393544d2a7SEd Tanous                         auto schemaItem = std::ranges::find_if(
11403544d2a7SEd Tanous                             fanRedfish, [itemName](const nlohmann::json& fan) {
11413e35c761SGeorge Liu                             return fan["Name"] == itemName;
11428bd25ccdSJames Feist                         });
11438bd25ccdSJames Feist                         if (schemaItem != fanRedfish.end())
11448bd25ccdSJames Feist                         {
11458a592810SEd Tanous                             nlohmann::json::object_t collectionId;
11468a592810SEd Tanous                             collectionId["@odata.id"] =
11471476687dSEd Tanous                                 (*schemaItem)["@odata.id"];
11481476687dSEd Tanous                             redfishCollection.emplace_back(
11498a592810SEd Tanous                                 std::move(collectionId));
11508bd25ccdSJames Feist                         }
11518bd25ccdSJames Feist                         else
11528bd25ccdSJames Feist                         {
115362598e31SEd Tanous                             BMCWEB_LOG_ERROR("failed to find fan in schema");
11548bd25ccdSJames Feist                             messages::internalError(
11558d1b46d7Szhanghch05                                 sensorsAsyncResp->asyncResp->res);
11568bd25ccdSJames Feist                             return;
11578bd25ccdSJames Feist                         }
11588bd25ccdSJames Feist                     }
11598bd25ccdSJames Feist 
116089492a15SPatrick Williams                     size_t minNumNeeded = collection->empty()
116126f6976fSEd Tanous                                               ? 0
116289492a15SPatrick Williams                                               : collection->size() -
116389492a15SPatrick Williams                                                     *allowedFailures;
1164002d39b4SEd Tanous                     nlohmann::json& jResp = sensorsAsyncResp->asyncResp->res
11658bd25ccdSJames Feist                                                 .jsonValue["Redundancy"];
11661476687dSEd Tanous 
11671476687dSEd Tanous                     nlohmann::json::object_t redundancy;
1168ef4c65b7SEd Tanous                     boost::urls::url url =
1169ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}",
1170ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisId,
1171eddfc437SWilly Tu                                             sensorsAsyncResp->chassisSubNode);
1172eddfc437SWilly Tu                     url.set_fragment(("/Redundancy"_json_pointer / jResp.size())
1173eddfc437SWilly Tu                                          .to_string());
1174eddfc437SWilly Tu                     redundancy["@odata.id"] = std::move(url);
1175002d39b4SEd Tanous                     redundancy["@odata.type"] = "#Redundancy.v1_3_2.Redundancy";
11761476687dSEd Tanous                     redundancy["MinNumNeeded"] = minNumNeeded;
11771476687dSEd Tanous                     redundancy["Mode"] = "N+m";
11781476687dSEd Tanous                     redundancy["Name"] = name;
11791476687dSEd Tanous                     redundancy["RedundancySet"] = redfishCollection;
11801476687dSEd Tanous                     redundancy["Status"]["Health"] = health;
11811476687dSEd Tanous                     redundancy["Status"]["State"] = "Enabled";
11821476687dSEd Tanous 
1183b2ba3072SPatrick Williams                     jResp.emplace_back(std::move(redundancy));
118486d89ed7SKrzysztof Grobelny                 });
11851e1e598dSJonathan Doman             });
11868bd25ccdSJames Feist         }
1187e99073f5SGeorge Liu     });
11888bd25ccdSJames Feist }
11898bd25ccdSJames Feist 
1190b5a76932SEd Tanous inline void
119181ce609eSEd Tanous     sortJSONResponse(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
119249c53ac9SJohnathan Mantey {
11938d1b46d7Szhanghch05     nlohmann::json& response = sensorsAsyncResp->asyncResp->res.jsonValue;
119449c53ac9SJohnathan Mantey     std::array<std::string, 2> sensorHeaders{"Temperatures", "Fans"};
119581ce609eSEd Tanous     if (sensorsAsyncResp->chassisSubNode == sensors::node::power)
119649c53ac9SJohnathan Mantey     {
119749c53ac9SJohnathan Mantey         sensorHeaders = {"Voltages", "PowerSupplies"};
119849c53ac9SJohnathan Mantey     }
119949c53ac9SJohnathan Mantey     for (const std::string& sensorGroup : sensorHeaders)
120049c53ac9SJohnathan Mantey     {
120149c53ac9SJohnathan Mantey         nlohmann::json::iterator entry = response.find(sensorGroup);
120249c53ac9SJohnathan Mantey         if (entry != response.end())
120349c53ac9SJohnathan Mantey         {
120449c53ac9SJohnathan Mantey             std::sort(entry->begin(), entry->end(),
120502cad96eSEd Tanous                       [](const nlohmann::json& c1, const nlohmann::json& c2) {
120649c53ac9SJohnathan Mantey                 return c1["Name"] < c2["Name"];
120749c53ac9SJohnathan Mantey             });
120849c53ac9SJohnathan Mantey 
120949c53ac9SJohnathan Mantey             // add the index counts to the end of each entry
121049c53ac9SJohnathan Mantey             size_t count = 0;
121149c53ac9SJohnathan Mantey             for (nlohmann::json& sensorJson : *entry)
121249c53ac9SJohnathan Mantey             {
121349c53ac9SJohnathan Mantey                 nlohmann::json::iterator odata = sensorJson.find("@odata.id");
121449c53ac9SJohnathan Mantey                 if (odata == sensorJson.end())
121549c53ac9SJohnathan Mantey                 {
121649c53ac9SJohnathan Mantey                     continue;
121749c53ac9SJohnathan Mantey                 }
121849c53ac9SJohnathan Mantey                 std::string* value = odata->get_ptr<std::string*>();
121949c53ac9SJohnathan Mantey                 if (value != nullptr)
122049c53ac9SJohnathan Mantey                 {
1221eddfc437SWilly Tu                     *value += "/" + std::to_string(count);
12223e35c761SGeorge Liu                     sensorJson["MemberId"] = std::to_string(count);
122349c53ac9SJohnathan Mantey                     count++;
122481ce609eSEd Tanous                     sensorsAsyncResp->updateUri(sensorJson["Name"], *value);
122549c53ac9SJohnathan Mantey                 }
122649c53ac9SJohnathan Mantey             }
122749c53ac9SJohnathan Mantey         }
122849c53ac9SJohnathan Mantey     }
122949c53ac9SJohnathan Mantey }
123049c53ac9SJohnathan Mantey 
123108777fb0SLewanczyk, Dawid /**
1232adc4f0dbSShawn McCarney  * @brief Finds the inventory item with the specified object path.
1233adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1234adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1235adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12368fb49dd6SShawn McCarney  */
123723a21a1cSEd Tanous inline InventoryItem* findInventoryItem(
1238b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1239adc4f0dbSShawn McCarney     const std::string& invItemObjPath)
12408fb49dd6SShawn McCarney {
1241adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
12428fb49dd6SShawn McCarney     {
1243adc4f0dbSShawn McCarney         if (inventoryItem.objectPath == invItemObjPath)
12448fb49dd6SShawn McCarney         {
1245adc4f0dbSShawn McCarney             return &inventoryItem;
12468fb49dd6SShawn McCarney         }
12478fb49dd6SShawn McCarney     }
12488fb49dd6SShawn McCarney     return nullptr;
12498fb49dd6SShawn McCarney }
12508fb49dd6SShawn McCarney 
12518fb49dd6SShawn McCarney /**
1252adc4f0dbSShawn McCarney  * @brief Finds the inventory item associated with the specified sensor.
1253adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1254adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor.
1255adc4f0dbSShawn McCarney  * @return Inventory item within vector, or nullptr if no match found.
12568fb49dd6SShawn McCarney  */
125723a21a1cSEd Tanous inline InventoryItem* findInventoryItemForSensor(
1258b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1259adc4f0dbSShawn McCarney     const std::string& sensorObjPath)
1260adc4f0dbSShawn McCarney {
1261adc4f0dbSShawn McCarney     for (InventoryItem& inventoryItem : *inventoryItems)
1262adc4f0dbSShawn McCarney     {
1263db0d36efSEd Tanous         if (inventoryItem.sensors.contains(sensorObjPath))
1264adc4f0dbSShawn McCarney         {
1265adc4f0dbSShawn McCarney             return &inventoryItem;
1266adc4f0dbSShawn McCarney         }
1267adc4f0dbSShawn McCarney     }
1268adc4f0dbSShawn McCarney     return nullptr;
1269adc4f0dbSShawn McCarney }
1270adc4f0dbSShawn McCarney 
1271adc4f0dbSShawn McCarney /**
1272d500549bSAnthony Wilson  * @brief Finds the inventory item associated with the specified led path.
1273d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1274d500549bSAnthony Wilson  * @param ledObjPath D-Bus object path of led.
1275d500549bSAnthony Wilson  * @return Inventory item within vector, or nullptr if no match found.
1276d500549bSAnthony Wilson  */
1277d500549bSAnthony Wilson inline InventoryItem*
1278d500549bSAnthony Wilson     findInventoryItemForLed(std::vector<InventoryItem>& inventoryItems,
1279d500549bSAnthony Wilson                             const std::string& ledObjPath)
1280d500549bSAnthony Wilson {
1281d500549bSAnthony Wilson     for (InventoryItem& inventoryItem : inventoryItems)
1282d500549bSAnthony Wilson     {
1283d500549bSAnthony Wilson         if (inventoryItem.ledObjectPath == ledObjPath)
1284d500549bSAnthony Wilson         {
1285d500549bSAnthony Wilson             return &inventoryItem;
1286d500549bSAnthony Wilson         }
1287d500549bSAnthony Wilson     }
1288d500549bSAnthony Wilson     return nullptr;
1289d500549bSAnthony Wilson }
1290d500549bSAnthony Wilson 
1291d500549bSAnthony Wilson /**
1292adc4f0dbSShawn McCarney  * @brief Adds inventory item and associated sensor to specified vector.
1293adc4f0dbSShawn McCarney  *
1294adc4f0dbSShawn McCarney  * Adds a new InventoryItem to the vector if necessary.  Searches for an
1295adc4f0dbSShawn McCarney  * existing InventoryItem with the specified object path.  If not found, one is
1296adc4f0dbSShawn McCarney  * added to the vector.
1297adc4f0dbSShawn McCarney  *
1298adc4f0dbSShawn McCarney  * Next, the specified sensor is added to the set of sensors associated with the
1299adc4f0dbSShawn McCarney  * InventoryItem.
1300adc4f0dbSShawn McCarney  *
1301adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1302adc4f0dbSShawn McCarney  * @param invItemObjPath D-Bus object path of inventory item.
1303adc4f0dbSShawn McCarney  * @param sensorObjPath D-Bus object path of sensor
1304adc4f0dbSShawn McCarney  */
1305b5a76932SEd Tanous inline void addInventoryItem(
1306b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
1307b5a76932SEd Tanous     const std::string& invItemObjPath, const std::string& sensorObjPath)
1308adc4f0dbSShawn McCarney {
1309adc4f0dbSShawn McCarney     // Look for inventory item in vector
131089492a15SPatrick Williams     InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
131189492a15SPatrick Williams                                                      invItemObjPath);
1312adc4f0dbSShawn McCarney 
1313adc4f0dbSShawn McCarney     // If inventory item doesn't exist in vector, add it
1314adc4f0dbSShawn McCarney     if (inventoryItem == nullptr)
1315adc4f0dbSShawn McCarney     {
1316adc4f0dbSShawn McCarney         inventoryItems->emplace_back(invItemObjPath);
1317adc4f0dbSShawn McCarney         inventoryItem = &(inventoryItems->back());
1318adc4f0dbSShawn McCarney     }
1319adc4f0dbSShawn McCarney 
1320adc4f0dbSShawn McCarney     // Add sensor to set of sensors associated with inventory item
1321adc4f0dbSShawn McCarney     inventoryItem->sensors.emplace(sensorObjPath);
1322adc4f0dbSShawn McCarney }
1323adc4f0dbSShawn McCarney 
1324adc4f0dbSShawn McCarney /**
1325adc4f0dbSShawn McCarney  * @brief Stores D-Bus data in the specified inventory item.
1326adc4f0dbSShawn McCarney  *
1327adc4f0dbSShawn McCarney  * Finds D-Bus data in the specified map of interfaces.  Stores the data in the
1328adc4f0dbSShawn McCarney  * specified InventoryItem.
1329adc4f0dbSShawn McCarney  *
1330adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1331adc4f0dbSShawn McCarney  * response.
1332adc4f0dbSShawn McCarney  *
1333adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item where data will be stored.
1334adc4f0dbSShawn McCarney  * @param interfacesDict Map containing D-Bus interfaces and their properties
1335adc4f0dbSShawn McCarney  * for the specified inventory item.
1336adc4f0dbSShawn McCarney  */
133723a21a1cSEd Tanous inline void storeInventoryItemData(
1338adc4f0dbSShawn McCarney     InventoryItem& inventoryItem,
133980f79a40SMichael Shen     const dbus::utility::DBusInterfacesMap& interfacesDict)
13408fb49dd6SShawn McCarney {
1341adc4f0dbSShawn McCarney     // Get properties from Inventory.Item interface
1342711ac7a9SEd Tanous 
13439eb808c1SEd Tanous     for (const auto& [interface, values] : interfacesDict)
13448fb49dd6SShawn McCarney     {
1345711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item")
13468fb49dd6SShawn McCarney         {
13479eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1348711ac7a9SEd Tanous             {
1349711ac7a9SEd Tanous                 if (name == "Present")
1350711ac7a9SEd Tanous                 {
1351711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1352adc4f0dbSShawn McCarney                     if (value != nullptr)
13538fb49dd6SShawn McCarney                     {
1354adc4f0dbSShawn McCarney                         inventoryItem.isPresent = *value;
13558fb49dd6SShawn McCarney                     }
13568fb49dd6SShawn McCarney                 }
13578fb49dd6SShawn McCarney             }
1358711ac7a9SEd Tanous         }
1359adc4f0dbSShawn McCarney         // Check if Inventory.Item.PowerSupply interface is present
1360711ac7a9SEd Tanous 
1361711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Item.PowerSupply")
13628fb49dd6SShawn McCarney         {
1363adc4f0dbSShawn McCarney             inventoryItem.isPowerSupply = true;
13648fb49dd6SShawn McCarney         }
1365adc4f0dbSShawn McCarney 
1366adc4f0dbSShawn McCarney         // Get properties from Inventory.Decorator.Asset interface
1367711ac7a9SEd Tanous         if (interface == "xyz.openbmc_project.Inventory.Decorator.Asset")
1368adc4f0dbSShawn McCarney         {
13699eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1370711ac7a9SEd Tanous             {
1371711ac7a9SEd Tanous                 if (name == "Manufacturer")
1372adc4f0dbSShawn McCarney                 {
1373adc4f0dbSShawn McCarney                     const std::string* value =
1374711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1375adc4f0dbSShawn McCarney                     if (value != nullptr)
1376adc4f0dbSShawn McCarney                     {
1377adc4f0dbSShawn McCarney                         inventoryItem.manufacturer = *value;
1378adc4f0dbSShawn McCarney                     }
1379adc4f0dbSShawn McCarney                 }
1380711ac7a9SEd Tanous                 if (name == "Model")
1381adc4f0dbSShawn McCarney                 {
1382adc4f0dbSShawn McCarney                     const std::string* value =
1383711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1384adc4f0dbSShawn McCarney                     if (value != nullptr)
1385adc4f0dbSShawn McCarney                     {
1386adc4f0dbSShawn McCarney                         inventoryItem.model = *value;
1387adc4f0dbSShawn McCarney                     }
1388adc4f0dbSShawn McCarney                 }
1389711ac7a9SEd Tanous                 if (name == "SerialNumber")
1390adc4f0dbSShawn McCarney                 {
1391adc4f0dbSShawn McCarney                     const std::string* value =
1392711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1393adc4f0dbSShawn McCarney                     if (value != nullptr)
1394adc4f0dbSShawn McCarney                     {
1395adc4f0dbSShawn McCarney                         inventoryItem.serialNumber = *value;
1396adc4f0dbSShawn McCarney                     }
1397adc4f0dbSShawn McCarney                 }
1398711ac7a9SEd Tanous                 if (name == "PartNumber")
1399711ac7a9SEd Tanous                 {
1400711ac7a9SEd Tanous                     const std::string* value =
1401711ac7a9SEd Tanous                         std::get_if<std::string>(&dbusValue);
1402711ac7a9SEd Tanous                     if (value != nullptr)
1403711ac7a9SEd Tanous                     {
1404711ac7a9SEd Tanous                         inventoryItem.partNumber = *value;
1405711ac7a9SEd Tanous                     }
1406711ac7a9SEd Tanous                 }
1407711ac7a9SEd Tanous             }
1408adc4f0dbSShawn McCarney         }
1409adc4f0dbSShawn McCarney 
1410711ac7a9SEd Tanous         if (interface ==
1411711ac7a9SEd Tanous             "xyz.openbmc_project.State.Decorator.OperationalStatus")
1412adc4f0dbSShawn McCarney         {
14139eb808c1SEd Tanous             for (const auto& [name, dbusValue] : values)
1414adc4f0dbSShawn McCarney             {
1415711ac7a9SEd Tanous                 if (name == "Functional")
1416711ac7a9SEd Tanous                 {
1417711ac7a9SEd Tanous                     const bool* value = std::get_if<bool>(&dbusValue);
1418adc4f0dbSShawn McCarney                     if (value != nullptr)
1419adc4f0dbSShawn McCarney                     {
1420adc4f0dbSShawn McCarney                         inventoryItem.isFunctional = *value;
14218fb49dd6SShawn McCarney                     }
14228fb49dd6SShawn McCarney                 }
14238fb49dd6SShawn McCarney             }
14248fb49dd6SShawn McCarney         }
1425711ac7a9SEd Tanous     }
1426711ac7a9SEd Tanous }
14278fb49dd6SShawn McCarney 
14288fb49dd6SShawn McCarney /**
1429adc4f0dbSShawn McCarney  * @brief Gets D-Bus data for inventory items associated with sensors.
14308fb49dd6SShawn McCarney  *
1431adc4f0dbSShawn McCarney  * Uses the specified connections (services) to obtain D-Bus data for inventory
1432adc4f0dbSShawn McCarney  * items associated with sensors.  Stores the resulting data in the
1433adc4f0dbSShawn McCarney  * inventoryItems vector.
14348fb49dd6SShawn McCarney  *
1435adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
1436adc4f0dbSShawn McCarney  * response.
1437adc4f0dbSShawn McCarney  *
1438adc4f0dbSShawn McCarney  * Finds the inventory item data asynchronously.  Invokes callback when data has
1439adc4f0dbSShawn McCarney  * been obtained.
1440adc4f0dbSShawn McCarney  *
1441adc4f0dbSShawn McCarney  * The callback must have the following signature:
1442adc4f0dbSShawn McCarney  *   @code
1443d500549bSAnthony Wilson  *   callback(void)
1444adc4f0dbSShawn McCarney  *   @endcode
1445adc4f0dbSShawn McCarney  *
1446adc4f0dbSShawn McCarney  * This function is called recursively, obtaining data asynchronously from one
1447adc4f0dbSShawn McCarney  * connection in each call.  This ensures the callback is not invoked until the
1448adc4f0dbSShawn McCarney  * last asynchronous function has completed.
14498fb49dd6SShawn McCarney  *
14508fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1451adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
1452adc4f0dbSShawn McCarney  * @param invConnections Connections that provide data for the inventory items.
14538fb49dd6SShawn McCarney  * implements ObjectManager.
1454adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory data has been obtained.
1455adc4f0dbSShawn McCarney  * @param invConnectionsIndex Current index in invConnections.  Only specified
1456adc4f0dbSShawn McCarney  * in recursive calls to this function.
14578fb49dd6SShawn McCarney  */
1458adc4f0dbSShawn McCarney template <typename Callback>
1459adc4f0dbSShawn McCarney static void getInventoryItemsData(
14608fb49dd6SShawn McCarney     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1461adc4f0dbSShawn McCarney     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1462d0090733SEd Tanous     std::shared_ptr<std::set<std::string>> invConnections, Callback&& callback,
1463d0090733SEd Tanous     size_t invConnectionsIndex = 0)
14648fb49dd6SShawn McCarney {
146562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData enter");
14668fb49dd6SShawn McCarney 
1467adc4f0dbSShawn McCarney     // If no more connections left, call callback
1468adc4f0dbSShawn McCarney     if (invConnectionsIndex >= invConnections->size())
14698fb49dd6SShawn McCarney     {
1470d500549bSAnthony Wilson         callback();
147162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
1472adc4f0dbSShawn McCarney         return;
1473adc4f0dbSShawn McCarney     }
1474adc4f0dbSShawn McCarney 
1475adc4f0dbSShawn McCarney     // Get inventory item data from current connection
1476fe04d49cSNan Zhou     auto it = invConnections->begin();
1477fe04d49cSNan Zhou     std::advance(it, invConnectionsIndex);
1478adc4f0dbSShawn McCarney     if (it != invConnections->end())
1479adc4f0dbSShawn McCarney     {
1480adc4f0dbSShawn McCarney         const std::string& invConnection = *it;
1481adc4f0dbSShawn McCarney 
14825eb468daSGeorge Liu         // Get all object paths and their interfaces for current connection
14835eb468daSGeorge Liu         sdbusplus::message::object_path path("/xyz/openbmc_project/inventory");
14845eb468daSGeorge Liu         dbus::utility::getManagedObjects(
14855eb468daSGeorge Liu             invConnection, path,
14865eb468daSGeorge Liu             [sensorsAsyncResp, inventoryItems, invConnections,
14878cb2c024SEd Tanous              callback = std::forward<Callback>(callback), invConnectionsIndex](
14885e7e2dc5SEd Tanous                 const boost::system::error_code& ec,
148902cad96eSEd Tanous                 const dbus::utility::ManagedObjectType& resp) {
149062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler enter");
14918fb49dd6SShawn McCarney             if (ec)
14928fb49dd6SShawn McCarney             {
149362598e31SEd Tanous                 BMCWEB_LOG_ERROR(
149462598e31SEd Tanous                     "getInventoryItemsData respHandler DBus error {}", ec);
14958d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
14968fb49dd6SShawn McCarney                 return;
14978fb49dd6SShawn McCarney             }
14988fb49dd6SShawn McCarney 
14998fb49dd6SShawn McCarney             // Loop through returned object paths
15008fb49dd6SShawn McCarney             for (const auto& objDictEntry : resp)
15018fb49dd6SShawn McCarney             {
15028fb49dd6SShawn McCarney                 const std::string& objPath =
15038fb49dd6SShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
15048fb49dd6SShawn McCarney 
1505adc4f0dbSShawn McCarney                 // If this object path is one of the specified inventory items
150689492a15SPatrick Williams                 InventoryItem* inventoryItem = findInventoryItem(inventoryItems,
150789492a15SPatrick Williams                                                                  objPath);
1508adc4f0dbSShawn McCarney                 if (inventoryItem != nullptr)
15098fb49dd6SShawn McCarney                 {
1510adc4f0dbSShawn McCarney                     // Store inventory data in InventoryItem
1511adc4f0dbSShawn McCarney                     storeInventoryItemData(*inventoryItem, objDictEntry.second);
15128fb49dd6SShawn McCarney                 }
15138fb49dd6SShawn McCarney             }
15148fb49dd6SShawn McCarney 
1515adc4f0dbSShawn McCarney             // Recurse to get inventory item data from next connection
1516adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
1517d0090733SEd Tanous                                   invConnections, std::move(callback),
1518d0090733SEd Tanous                                   invConnectionsIndex + 1);
1519adc4f0dbSShawn McCarney 
152062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsData respHandler exit");
15215eb468daSGeorge Liu         });
15228fb49dd6SShawn McCarney     }
15238fb49dd6SShawn McCarney 
152462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsData exit");
15258fb49dd6SShawn McCarney }
15268fb49dd6SShawn McCarney 
15278fb49dd6SShawn McCarney /**
1528adc4f0dbSShawn McCarney  * @brief Gets connections that provide D-Bus data for inventory items.
15298fb49dd6SShawn McCarney  *
1530adc4f0dbSShawn McCarney  * Gets the D-Bus connections (services) that provide data for the inventory
1531adc4f0dbSShawn McCarney  * items that are associated with sensors.
15328fb49dd6SShawn McCarney  *
15338fb49dd6SShawn McCarney  * Finds the connections asynchronously.  Invokes callback when information has
15348fb49dd6SShawn McCarney  * been obtained.
15358fb49dd6SShawn McCarney  *
15368fb49dd6SShawn McCarney  * The callback must have the following signature:
15378fb49dd6SShawn McCarney  *   @code
1538fe04d49cSNan Zhou  *   callback(std::shared_ptr<std::set<std::string>> invConnections)
15398fb49dd6SShawn McCarney  *   @endcode
15408fb49dd6SShawn McCarney  *
15418fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
1542adc4f0dbSShawn McCarney  * @param inventoryItems D-Bus inventory items associated with sensors.
15438fb49dd6SShawn McCarney  * @param callback Callback to invoke when connections have been obtained.
15448fb49dd6SShawn McCarney  */
15458fb49dd6SShawn McCarney template <typename Callback>
15468fb49dd6SShawn McCarney static void getInventoryItemsConnections(
1547b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1548b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems,
15498fb49dd6SShawn McCarney     Callback&& callback)
15508fb49dd6SShawn McCarney {
155162598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections enter");
15528fb49dd6SShawn McCarney 
15538fb49dd6SShawn McCarney     const std::string path = "/xyz/openbmc_project/inventory";
1554e99073f5SGeorge Liu     constexpr std::array<std::string_view, 4> interfaces = {
15558fb49dd6SShawn McCarney         "xyz.openbmc_project.Inventory.Item",
1556adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Item.PowerSupply",
1557adc4f0dbSShawn McCarney         "xyz.openbmc_project.Inventory.Decorator.Asset",
15588fb49dd6SShawn McCarney         "xyz.openbmc_project.State.Decorator.OperationalStatus"};
15598fb49dd6SShawn McCarney 
1560e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1561e99073f5SGeorge Liu     dbus::utility::getSubTree(
1562e99073f5SGeorge Liu         path, 0, interfaces,
15638cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1564002d39b4SEd Tanous          inventoryItems](
1565e99073f5SGeorge Liu             const boost::system::error_code& ec,
1566002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1567e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
156862598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler enter");
15698fb49dd6SShawn McCarney         if (ec)
15708fb49dd6SShawn McCarney         {
15718d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
157262598e31SEd Tanous             BMCWEB_LOG_ERROR(
157362598e31SEd Tanous                 "getInventoryItemsConnections respHandler DBus error {}", ec);
15748fb49dd6SShawn McCarney             return;
15758fb49dd6SShawn McCarney         }
15768fb49dd6SShawn McCarney 
15778fb49dd6SShawn McCarney         // Make unique list of connections for desired inventory items
1578fe04d49cSNan Zhou         std::shared_ptr<std::set<std::string>> invConnections =
1579fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
15808fb49dd6SShawn McCarney 
15818fb49dd6SShawn McCarney         // Loop through objects from GetSubTree
15828fb49dd6SShawn McCarney         for (const std::pair<
15838fb49dd6SShawn McCarney                  std::string,
15848fb49dd6SShawn McCarney                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
15858fb49dd6SShawn McCarney                  object : subtree)
15868fb49dd6SShawn McCarney         {
1587adc4f0dbSShawn McCarney             // Check if object path is one of the specified inventory items
15888fb49dd6SShawn McCarney             const std::string& objPath = object.first;
1589adc4f0dbSShawn McCarney             if (findInventoryItem(inventoryItems, objPath) != nullptr)
15908fb49dd6SShawn McCarney             {
15918fb49dd6SShawn McCarney                 // Store all connections to inventory item
15928fb49dd6SShawn McCarney                 for (const std::pair<std::string, std::vector<std::string>>&
15938fb49dd6SShawn McCarney                          objData : object.second)
15948fb49dd6SShawn McCarney                 {
15958fb49dd6SShawn McCarney                     const std::string& invConnection = objData.first;
15968fb49dd6SShawn McCarney                     invConnections->insert(invConnection);
15978fb49dd6SShawn McCarney                 }
15988fb49dd6SShawn McCarney             }
15998fb49dd6SShawn McCarney         }
1600d500549bSAnthony Wilson 
16018fb49dd6SShawn McCarney         callback(invConnections);
160262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemsConnections respHandler exit");
1603e99073f5SGeorge Liu     });
160462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemsConnections exit");
16058fb49dd6SShawn McCarney }
16068fb49dd6SShawn McCarney 
16078fb49dd6SShawn McCarney /**
1608adc4f0dbSShawn McCarney  * @brief Gets associations from sensors to inventory items.
16098fb49dd6SShawn McCarney  *
16108fb49dd6SShawn McCarney  * Looks for ObjectMapper associations from the specified sensors to related
1611d500549bSAnthony Wilson  * inventory items. Then finds the associations from those inventory items to
1612d500549bSAnthony Wilson  * their LEDs, if any.
16138fb49dd6SShawn McCarney  *
16148fb49dd6SShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when information
16158fb49dd6SShawn McCarney  * has been obtained.
16168fb49dd6SShawn McCarney  *
16178fb49dd6SShawn McCarney  * The callback must have the following signature:
16188fb49dd6SShawn McCarney  *   @code
1619adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
16208fb49dd6SShawn McCarney  *   @endcode
16218fb49dd6SShawn McCarney  *
16228fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
16238fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
16248fb49dd6SShawn McCarney  * implements ObjectManager.
16258fb49dd6SShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
16268fb49dd6SShawn McCarney  */
16278fb49dd6SShawn McCarney template <typename Callback>
1628adc4f0dbSShawn McCarney static void getInventoryItemAssociations(
1629b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
1630fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
16318fb49dd6SShawn McCarney     Callback&& callback)
16328fb49dd6SShawn McCarney {
163362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations enter");
16348fb49dd6SShawn McCarney 
16355eb468daSGeorge Liu     // Call GetManagedObjects on the ObjectMapper to get all associations
16365eb468daSGeorge Liu     sdbusplus::message::object_path path("/");
16375eb468daSGeorge Liu     dbus::utility::getManagedObjects(
16385eb468daSGeorge Liu         "xyz.openbmc_project.ObjectMapper", path,
16398cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
16405e7e2dc5SEd Tanous          sensorNames](const boost::system::error_code& ec,
164102cad96eSEd Tanous                       const dbus::utility::ManagedObjectType& resp) {
164262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler enter");
16438fb49dd6SShawn McCarney         if (ec)
16448fb49dd6SShawn McCarney         {
164562598e31SEd Tanous             BMCWEB_LOG_ERROR(
164662598e31SEd Tanous                 "getInventoryItemAssociations respHandler DBus error {}", ec);
16478d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
16488fb49dd6SShawn McCarney             return;
16498fb49dd6SShawn McCarney         }
16508fb49dd6SShawn McCarney 
1651adc4f0dbSShawn McCarney         // Create vector to hold list of inventory items
1652adc4f0dbSShawn McCarney         std::shared_ptr<std::vector<InventoryItem>> inventoryItems =
1653adc4f0dbSShawn McCarney             std::make_shared<std::vector<InventoryItem>>();
1654adc4f0dbSShawn McCarney 
16558fb49dd6SShawn McCarney         // Loop through returned object paths
16568fb49dd6SShawn McCarney         std::string sensorAssocPath;
16578fb49dd6SShawn McCarney         sensorAssocPath.reserve(128); // avoid memory allocations
16588fb49dd6SShawn McCarney         for (const auto& objDictEntry : resp)
16598fb49dd6SShawn McCarney         {
16608fb49dd6SShawn McCarney             const std::string& objPath =
16618fb49dd6SShawn McCarney                 static_cast<const std::string&>(objDictEntry.first);
16628fb49dd6SShawn McCarney 
16638fb49dd6SShawn McCarney             // If path is inventory association for one of the specified sensors
16648fb49dd6SShawn McCarney             for (const std::string& sensorName : *sensorNames)
16658fb49dd6SShawn McCarney             {
16668fb49dd6SShawn McCarney                 sensorAssocPath = sensorName;
16678fb49dd6SShawn McCarney                 sensorAssocPath += "/inventory";
16688fb49dd6SShawn McCarney                 if (objPath == sensorAssocPath)
16698fb49dd6SShawn McCarney                 {
16708fb49dd6SShawn McCarney                     // Get Association interface for object path
1671711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
16728fb49dd6SShawn McCarney                     {
1673711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1674711ac7a9SEd Tanous                         {
1675711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1676711ac7a9SEd Tanous                             {
1677711ac7a9SEd Tanous                                 if (valueName == "endpoints")
16788fb49dd6SShawn McCarney                                 {
16798fb49dd6SShawn McCarney                                     const std::vector<std::string>* endpoints =
16808fb49dd6SShawn McCarney                                         std::get_if<std::vector<std::string>>(
1681711ac7a9SEd Tanous                                             &value);
1682711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1683711ac7a9SEd Tanous                                         !endpoints->empty())
16848fb49dd6SShawn McCarney                                     {
1685adc4f0dbSShawn McCarney                                         // Add inventory item to vector
1686adc4f0dbSShawn McCarney                                         const std::string& invItemPath =
1687adc4f0dbSShawn McCarney                                             endpoints->front();
1688711ac7a9SEd Tanous                                         addInventoryItem(inventoryItems,
1689711ac7a9SEd Tanous                                                          invItemPath,
1690adc4f0dbSShawn McCarney                                                          sensorName);
16918fb49dd6SShawn McCarney                                     }
16928fb49dd6SShawn McCarney                                 }
16938fb49dd6SShawn McCarney                             }
1694711ac7a9SEd Tanous                         }
1695711ac7a9SEd Tanous                     }
16968fb49dd6SShawn McCarney                     break;
16978fb49dd6SShawn McCarney                 }
16988fb49dd6SShawn McCarney             }
16998fb49dd6SShawn McCarney         }
17008fb49dd6SShawn McCarney 
1701d500549bSAnthony Wilson         // Now loop through the returned object paths again, this time to
1702d500549bSAnthony Wilson         // find the leds associated with the inventory items we just found
1703d500549bSAnthony Wilson         std::string inventoryAssocPath;
1704d500549bSAnthony Wilson         inventoryAssocPath.reserve(128); // avoid memory allocations
1705d500549bSAnthony Wilson         for (const auto& objDictEntry : resp)
1706d500549bSAnthony Wilson         {
1707d500549bSAnthony Wilson             const std::string& objPath =
1708d500549bSAnthony Wilson                 static_cast<const std::string&>(objDictEntry.first);
1709d500549bSAnthony Wilson 
1710d500549bSAnthony Wilson             for (InventoryItem& inventoryItem : *inventoryItems)
1711d500549bSAnthony Wilson             {
1712d500549bSAnthony Wilson                 inventoryAssocPath = inventoryItem.objectPath;
1713d500549bSAnthony Wilson                 inventoryAssocPath += "/leds";
1714d500549bSAnthony Wilson                 if (objPath == inventoryAssocPath)
1715d500549bSAnthony Wilson                 {
1716711ac7a9SEd Tanous                     for (const auto& [interface, values] : objDictEntry.second)
1717d500549bSAnthony Wilson                     {
1718711ac7a9SEd Tanous                         if (interface == "xyz.openbmc_project.Association")
1719711ac7a9SEd Tanous                         {
1720711ac7a9SEd Tanous                             for (const auto& [valueName, value] : values)
1721711ac7a9SEd Tanous                             {
1722711ac7a9SEd Tanous                                 if (valueName == "endpoints")
1723d500549bSAnthony Wilson                                 {
1724d500549bSAnthony Wilson                                     const std::vector<std::string>* endpoints =
1725d500549bSAnthony Wilson                                         std::get_if<std::vector<std::string>>(
1726711ac7a9SEd Tanous                                             &value);
1727711ac7a9SEd Tanous                                     if ((endpoints != nullptr) &&
1728711ac7a9SEd Tanous                                         !endpoints->empty())
1729d500549bSAnthony Wilson                                     {
1730711ac7a9SEd Tanous                                         // Add inventory item to vector
1731d500549bSAnthony Wilson                                         // Store LED path in inventory item
1732711ac7a9SEd Tanous                                         const std::string& ledPath =
1733711ac7a9SEd Tanous                                             endpoints->front();
1734d500549bSAnthony Wilson                                         inventoryItem.ledObjectPath = ledPath;
1735d500549bSAnthony Wilson                                     }
1736d500549bSAnthony Wilson                                 }
1737d500549bSAnthony Wilson                             }
1738711ac7a9SEd Tanous                         }
1739711ac7a9SEd Tanous                     }
1740711ac7a9SEd Tanous 
1741d500549bSAnthony Wilson                     break;
1742d500549bSAnthony Wilson                 }
1743d500549bSAnthony Wilson             }
1744d500549bSAnthony Wilson         }
1745adc4f0dbSShawn McCarney         callback(inventoryItems);
174662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociations respHandler exit");
17475eb468daSGeorge Liu     });
17488fb49dd6SShawn McCarney 
174962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItemAssociations exit");
17508fb49dd6SShawn McCarney }
17518fb49dd6SShawn McCarney 
17528fb49dd6SShawn McCarney /**
1753d500549bSAnthony Wilson  * @brief Gets D-Bus data for inventory item leds associated with sensors.
1754d500549bSAnthony Wilson  *
1755d500549bSAnthony Wilson  * Uses the specified connections (services) to obtain D-Bus data for inventory
1756d500549bSAnthony Wilson  * item leds associated with sensors.  Stores the resulting data in the
1757d500549bSAnthony Wilson  * inventoryItems vector.
1758d500549bSAnthony Wilson  *
1759d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1760d500549bSAnthony Wilson  * response.
1761d500549bSAnthony Wilson  *
1762d500549bSAnthony Wilson  * Finds the inventory item led data asynchronously.  Invokes callback when data
1763d500549bSAnthony Wilson  * has been obtained.
1764d500549bSAnthony Wilson  *
1765d500549bSAnthony Wilson  * The callback must have the following signature:
1766d500549bSAnthony Wilson  *   @code
176742cbe538SGunnar Mills  *   callback()
1768d500549bSAnthony Wilson  *   @endcode
1769d500549bSAnthony Wilson  *
1770d500549bSAnthony Wilson  * This function is called recursively, obtaining data asynchronously from one
1771d500549bSAnthony Wilson  * connection in each call.  This ensures the callback is not invoked until the
1772d500549bSAnthony Wilson  * last asynchronous function has completed.
1773d500549bSAnthony Wilson  *
1774d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1775d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1776d500549bSAnthony Wilson  * @param ledConnections Connections that provide data for the inventory leds.
1777d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory data has been obtained.
1778d500549bSAnthony Wilson  * @param ledConnectionsIndex Current index in ledConnections.  Only specified
1779d500549bSAnthony Wilson  * in recursive calls to this function.
1780d500549bSAnthony Wilson  */
1781d500549bSAnthony Wilson template <typename Callback>
1782d500549bSAnthony Wilson void getInventoryLedData(
1783d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1784d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1785fe04d49cSNan Zhou     std::shared_ptr<std::map<std::string, std::string>> ledConnections,
1786d500549bSAnthony Wilson     Callback&& callback, size_t ledConnectionsIndex = 0)
1787d500549bSAnthony Wilson {
178862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData enter");
1789d500549bSAnthony Wilson 
1790d500549bSAnthony Wilson     // If no more connections left, call callback
1791d500549bSAnthony Wilson     if (ledConnectionsIndex >= ledConnections->size())
1792d500549bSAnthony Wilson     {
179342cbe538SGunnar Mills         callback();
179462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1795d500549bSAnthony Wilson         return;
1796d500549bSAnthony Wilson     }
1797d500549bSAnthony Wilson 
1798d500549bSAnthony Wilson     // Get inventory item data from current connection
1799fe04d49cSNan Zhou     auto it = ledConnections->begin();
1800fe04d49cSNan Zhou     std::advance(it, ledConnectionsIndex);
1801d500549bSAnthony Wilson     if (it != ledConnections->end())
1802d500549bSAnthony Wilson     {
1803d500549bSAnthony Wilson         const std::string& ledPath = (*it).first;
1804d500549bSAnthony Wilson         const std::string& ledConnection = (*it).second;
1805d500549bSAnthony Wilson         // Response handler for Get State property
18061e1e598dSJonathan Doman         auto respHandler =
18071e1e598dSJonathan Doman             [sensorsAsyncResp, inventoryItems, ledConnections, ledPath,
18088cb2c024SEd Tanous              callback = std::forward<Callback>(callback), ledConnectionsIndex](
18095e7e2dc5SEd Tanous                 const boost::system::error_code& ec, const std::string& state) {
181062598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler enter");
1811d500549bSAnthony Wilson             if (ec)
1812d500549bSAnthony Wilson             {
181362598e31SEd Tanous                 BMCWEB_LOG_ERROR(
181462598e31SEd Tanous                     "getInventoryLedData respHandler DBus error {}", ec);
18158d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
1816d500549bSAnthony Wilson                 return;
1817d500549bSAnthony Wilson             }
1818d500549bSAnthony Wilson 
181962598e31SEd Tanous             BMCWEB_LOG_DEBUG("Led state: {}", state);
1820d500549bSAnthony Wilson             // Find inventory item with this LED object path
1821d500549bSAnthony Wilson             InventoryItem* inventoryItem =
1822d500549bSAnthony Wilson                 findInventoryItemForLed(*inventoryItems, ledPath);
1823d500549bSAnthony Wilson             if (inventoryItem != nullptr)
1824d500549bSAnthony Wilson             {
1825d500549bSAnthony Wilson                 // Store LED state in InventoryItem
182611ba3979SEd Tanous                 if (state.ends_with("On"))
1827d500549bSAnthony Wilson                 {
1828d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::ON;
1829d500549bSAnthony Wilson                 }
183011ba3979SEd Tanous                 else if (state.ends_with("Blink"))
1831d500549bSAnthony Wilson                 {
1832d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::BLINK;
1833d500549bSAnthony Wilson                 }
183411ba3979SEd Tanous                 else if (state.ends_with("Off"))
1835d500549bSAnthony Wilson                 {
1836d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::OFF;
1837d500549bSAnthony Wilson                 }
1838d500549bSAnthony Wilson                 else
1839d500549bSAnthony Wilson                 {
1840d500549bSAnthony Wilson                     inventoryItem->ledState = LedState::UNKNOWN;
1841d500549bSAnthony Wilson                 }
1842d500549bSAnthony Wilson             }
1843d500549bSAnthony Wilson 
1844d500549bSAnthony Wilson             // Recurse to get LED data from next connection
1845d500549bSAnthony Wilson             getInventoryLedData(sensorsAsyncResp, inventoryItems,
1846d500549bSAnthony Wilson                                 ledConnections, std::move(callback),
1847d500549bSAnthony Wilson                                 ledConnectionsIndex + 1);
1848d500549bSAnthony Wilson 
184962598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryLedData respHandler exit");
1850d500549bSAnthony Wilson         };
1851d500549bSAnthony Wilson 
1852d500549bSAnthony Wilson         // Get the State property for the current LED
18531e1e598dSJonathan Doman         sdbusplus::asio::getProperty<std::string>(
18541e1e598dSJonathan Doman             *crow::connections::systemBus, ledConnection, ledPath,
18551e1e598dSJonathan Doman             "xyz.openbmc_project.Led.Physical", "State",
18561e1e598dSJonathan Doman             std::move(respHandler));
1857d500549bSAnthony Wilson     }
1858d500549bSAnthony Wilson 
185962598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLedData exit");
1860d500549bSAnthony Wilson }
1861d500549bSAnthony Wilson 
1862d500549bSAnthony Wilson /**
1863d500549bSAnthony Wilson  * @brief Gets LED data for LEDs associated with given inventory items.
1864d500549bSAnthony Wilson  *
1865d500549bSAnthony Wilson  * Gets the D-Bus connections (services) that provide LED data for the LEDs
1866d500549bSAnthony Wilson  * associated with the specified inventory items.  Then gets the LED data from
1867d500549bSAnthony Wilson  * each connection and stores it in the inventory item.
1868d500549bSAnthony Wilson  *
1869d500549bSAnthony Wilson  * This data is later used to provide sensor property values in the JSON
1870d500549bSAnthony Wilson  * response.
1871d500549bSAnthony Wilson  *
1872d500549bSAnthony Wilson  * Finds the LED data asynchronously.  Invokes callback when information has
1873d500549bSAnthony Wilson  * been obtained.
1874d500549bSAnthony Wilson  *
1875d500549bSAnthony Wilson  * The callback must have the following signature:
1876d500549bSAnthony Wilson  *   @code
187742cbe538SGunnar Mills  *   callback()
1878d500549bSAnthony Wilson  *   @endcode
1879d500549bSAnthony Wilson  *
1880d500549bSAnthony Wilson  * @param sensorsAsyncResp Pointer to object holding response data.
1881d500549bSAnthony Wilson  * @param inventoryItems D-Bus inventory items associated with sensors.
1882d500549bSAnthony Wilson  * @param callback Callback to invoke when inventory items have been obtained.
1883d500549bSAnthony Wilson  */
1884d500549bSAnthony Wilson template <typename Callback>
1885d500549bSAnthony Wilson void getInventoryLeds(
1886d500549bSAnthony Wilson     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
1887d500549bSAnthony Wilson     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1888d500549bSAnthony Wilson     Callback&& callback)
1889d500549bSAnthony Wilson {
189062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds enter");
1891d500549bSAnthony Wilson 
1892d500549bSAnthony Wilson     const std::string path = "/xyz/openbmc_project";
1893e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
1894d500549bSAnthony Wilson         "xyz.openbmc_project.Led.Physical"};
1895d500549bSAnthony Wilson 
1896e99073f5SGeorge Liu     // Make call to ObjectMapper to find all inventory items
1897e99073f5SGeorge Liu     dbus::utility::getSubTree(
1898e99073f5SGeorge Liu         path, 0, interfaces,
18998cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
1900002d39b4SEd Tanous          inventoryItems](
1901e99073f5SGeorge Liu             const boost::system::error_code& ec,
1902002d39b4SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
1903e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
190462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler enter");
1905d500549bSAnthony Wilson         if (ec)
1906d500549bSAnthony Wilson         {
19078d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
190862598e31SEd Tanous             BMCWEB_LOG_ERROR("getInventoryLeds respHandler DBus error {}", ec);
1909d500549bSAnthony Wilson             return;
1910d500549bSAnthony Wilson         }
1911d500549bSAnthony Wilson 
1912d500549bSAnthony Wilson         // Build map of LED object paths to connections
1913fe04d49cSNan Zhou         std::shared_ptr<std::map<std::string, std::string>> ledConnections =
1914fe04d49cSNan Zhou             std::make_shared<std::map<std::string, std::string>>();
1915d500549bSAnthony Wilson 
1916d500549bSAnthony Wilson         // Loop through objects from GetSubTree
1917d500549bSAnthony Wilson         for (const std::pair<
1918d500549bSAnthony Wilson                  std::string,
1919d500549bSAnthony Wilson                  std::vector<std::pair<std::string, std::vector<std::string>>>>&
1920d500549bSAnthony Wilson                  object : subtree)
1921d500549bSAnthony Wilson         {
1922d500549bSAnthony Wilson             // Check if object path is LED for one of the specified inventory
1923d500549bSAnthony Wilson             // items
1924d500549bSAnthony Wilson             const std::string& ledPath = object.first;
1925d500549bSAnthony Wilson             if (findInventoryItemForLed(*inventoryItems, ledPath) != nullptr)
1926d500549bSAnthony Wilson             {
1927d500549bSAnthony Wilson                 // Add mapping from ledPath to connection
1928d500549bSAnthony Wilson                 const std::string& connection = object.second.begin()->first;
1929d500549bSAnthony Wilson                 (*ledConnections)[ledPath] = connection;
193062598e31SEd Tanous                 BMCWEB_LOG_DEBUG("Added mapping {} -> {}", ledPath, connection);
1931d500549bSAnthony Wilson             }
1932d500549bSAnthony Wilson         }
1933d500549bSAnthony Wilson 
1934d500549bSAnthony Wilson         getInventoryLedData(sensorsAsyncResp, inventoryItems, ledConnections,
1935d500549bSAnthony Wilson                             std::move(callback));
193662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryLeds respHandler exit");
1937e99073f5SGeorge Liu     });
193862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryLeds exit");
1939d500549bSAnthony Wilson }
1940d500549bSAnthony Wilson 
1941d500549bSAnthony Wilson /**
194242cbe538SGunnar Mills  * @brief Gets D-Bus data for Power Supply Attributes such as EfficiencyPercent
194342cbe538SGunnar Mills  *
194442cbe538SGunnar Mills  * Uses the specified connections (services) (currently assumes just one) to
194542cbe538SGunnar Mills  * obtain D-Bus data for Power Supply Attributes. Stores the resulting data in
194642cbe538SGunnar Mills  * the inventoryItems vector. Only stores data in Power Supply inventoryItems.
194742cbe538SGunnar Mills  *
194842cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
194942cbe538SGunnar Mills  * response.
195042cbe538SGunnar Mills  *
195142cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously.  Invokes callback
195242cbe538SGunnar Mills  * when data has been obtained.
195342cbe538SGunnar Mills  *
195442cbe538SGunnar Mills  * The callback must have the following signature:
195542cbe538SGunnar Mills  *   @code
195642cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
195742cbe538SGunnar Mills  *   @endcode
195842cbe538SGunnar Mills  *
195942cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
196042cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
196142cbe538SGunnar Mills  * @param psAttributesConnections Connections that provide data for the Power
196242cbe538SGunnar Mills  *        Supply Attributes
196342cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
196442cbe538SGunnar Mills  */
196542cbe538SGunnar Mills template <typename Callback>
196642cbe538SGunnar Mills void getPowerSupplyAttributesData(
1967b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
196842cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
1969fe04d49cSNan Zhou     const std::map<std::string, std::string>& psAttributesConnections,
197042cbe538SGunnar Mills     Callback&& callback)
197142cbe538SGunnar Mills {
197262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData enter");
197342cbe538SGunnar Mills 
197442cbe538SGunnar Mills     if (psAttributesConnections.empty())
197542cbe538SGunnar Mills     {
197662598e31SEd Tanous         BMCWEB_LOG_DEBUG("Can't find PowerSupplyAttributes, no connections!");
197742cbe538SGunnar Mills         callback(inventoryItems);
197842cbe538SGunnar Mills         return;
197942cbe538SGunnar Mills     }
198042cbe538SGunnar Mills 
198142cbe538SGunnar Mills     // Assuming just one connection (service) for now
1982fe04d49cSNan Zhou     auto it = psAttributesConnections.begin();
198342cbe538SGunnar Mills 
198442cbe538SGunnar Mills     const std::string& psAttributesPath = (*it).first;
198542cbe538SGunnar Mills     const std::string& psAttributesConnection = (*it).second;
198642cbe538SGunnar Mills 
198742cbe538SGunnar Mills     // Response handler for Get DeratingFactor property
19885a39f77aSPatrick Williams     auto respHandler = [sensorsAsyncResp, inventoryItems,
19898cb2c024SEd Tanous                         callback = std::forward<Callback>(callback)](
19905a39f77aSPatrick Williams                            const boost::system::error_code& ec,
19915a39f77aSPatrick Williams                            const uint32_t value) {
199262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler enter");
199342cbe538SGunnar Mills         if (ec)
199442cbe538SGunnar Mills         {
199562598e31SEd Tanous             BMCWEB_LOG_ERROR(
199662598e31SEd Tanous                 "getPowerSupplyAttributesData respHandler DBus error {}", ec);
19978d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
199842cbe538SGunnar Mills             return;
199942cbe538SGunnar Mills         }
200042cbe538SGunnar Mills 
200162598e31SEd Tanous         BMCWEB_LOG_DEBUG("PS EfficiencyPercent value: {}", value);
200242cbe538SGunnar Mills         // Store value in Power Supply Inventory Items
200342cbe538SGunnar Mills         for (InventoryItem& inventoryItem : *inventoryItems)
200442cbe538SGunnar Mills         {
200555f79e6fSEd Tanous             if (inventoryItem.isPowerSupply)
200642cbe538SGunnar Mills             {
200742cbe538SGunnar Mills                 inventoryItem.powerSupplyEfficiencyPercent =
20081e1e598dSJonathan Doman                     static_cast<int>(value);
200942cbe538SGunnar Mills             }
201042cbe538SGunnar Mills         }
201142cbe538SGunnar Mills 
201262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData respHandler exit");
201342cbe538SGunnar Mills         callback(inventoryItems);
201442cbe538SGunnar Mills     };
201542cbe538SGunnar Mills 
201642cbe538SGunnar Mills     // Get the DeratingFactor property for the PowerSupplyAttributes
201742cbe538SGunnar Mills     // Currently only property on the interface/only one we care about
20181e1e598dSJonathan Doman     sdbusplus::asio::getProperty<uint32_t>(
20191e1e598dSJonathan Doman         *crow::connections::systemBus, psAttributesConnection, psAttributesPath,
20201e1e598dSJonathan Doman         "xyz.openbmc_project.Control.PowerSupplyAttributes", "DeratingFactor",
20211e1e598dSJonathan Doman         std::move(respHandler));
202242cbe538SGunnar Mills 
202362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributesData exit");
202442cbe538SGunnar Mills }
202542cbe538SGunnar Mills 
202642cbe538SGunnar Mills /**
202742cbe538SGunnar Mills  * @brief Gets the Power Supply Attributes such as EfficiencyPercent
202842cbe538SGunnar Mills  *
202942cbe538SGunnar Mills  * Gets the D-Bus connection (service) that provides Power Supply Attributes
203042cbe538SGunnar Mills  * data. Then gets the Power Supply Attributes data from the connection
203142cbe538SGunnar Mills  * (currently just assumes 1 connection) and stores the data in the inventory
203242cbe538SGunnar Mills  * item.
203342cbe538SGunnar Mills  *
203442cbe538SGunnar Mills  * This data is later used to provide sensor property values in the JSON
203542cbe538SGunnar Mills  * response. DeratingFactor on D-Bus is mapped to EfficiencyPercent on Redfish.
203642cbe538SGunnar Mills  *
203742cbe538SGunnar Mills  * Finds the Power Supply Attributes data asynchronously. Invokes callback
203842cbe538SGunnar Mills  * when information has been obtained.
203942cbe538SGunnar Mills  *
204042cbe538SGunnar Mills  * The callback must have the following signature:
204142cbe538SGunnar Mills  *   @code
204242cbe538SGunnar Mills  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
204342cbe538SGunnar Mills  *   @endcode
204442cbe538SGunnar Mills  *
204542cbe538SGunnar Mills  * @param sensorsAsyncResp Pointer to object holding response data.
204642cbe538SGunnar Mills  * @param inventoryItems D-Bus inventory items associated with sensors.
204742cbe538SGunnar Mills  * @param callback Callback to invoke when data has been obtained.
204842cbe538SGunnar Mills  */
204942cbe538SGunnar Mills template <typename Callback>
205042cbe538SGunnar Mills void getPowerSupplyAttributes(
205142cbe538SGunnar Mills     std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
205242cbe538SGunnar Mills     std::shared_ptr<std::vector<InventoryItem>> inventoryItems,
205342cbe538SGunnar Mills     Callback&& callback)
205442cbe538SGunnar Mills {
205562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes enter");
205642cbe538SGunnar Mills 
205742cbe538SGunnar Mills     // Only need the power supply attributes when the Power Schema
2058a0ec28b6SAdrian Ambrożewicz     if (sensorsAsyncResp->chassisSubNode != sensors::node::power)
205942cbe538SGunnar Mills     {
206062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit since not Power");
206142cbe538SGunnar Mills         callback(inventoryItems);
206242cbe538SGunnar Mills         return;
206342cbe538SGunnar Mills     }
206442cbe538SGunnar Mills 
2065e99073f5SGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
206642cbe538SGunnar Mills         "xyz.openbmc_project.Control.PowerSupplyAttributes"};
206742cbe538SGunnar Mills 
2068e99073f5SGeorge Liu     // Make call to ObjectMapper to find the PowerSupplyAttributes service
2069e99073f5SGeorge Liu     dbus::utility::getSubTree(
2070e99073f5SGeorge Liu         "/xyz/openbmc_project", 0, interfaces,
20718cb2c024SEd Tanous         [callback = std::forward<Callback>(callback), sensorsAsyncResp,
2072b9d36b47SEd Tanous          inventoryItems](
2073e99073f5SGeorge Liu             const boost::system::error_code& ec,
2074b9d36b47SEd Tanous             const dbus::utility::MapperGetSubTreeResponse& subtree) {
2075e99073f5SGeorge Liu         // Response handler for parsing output from GetSubTree
207662598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler enter");
207742cbe538SGunnar Mills         if (ec)
207842cbe538SGunnar Mills         {
20798d1b46d7Szhanghch05             messages::internalError(sensorsAsyncResp->asyncResp->res);
208062598e31SEd Tanous             BMCWEB_LOG_ERROR(
208162598e31SEd Tanous                 "getPowerSupplyAttributes respHandler DBus error {}", ec);
208242cbe538SGunnar Mills             return;
208342cbe538SGunnar Mills         }
208426f6976fSEd Tanous         if (subtree.empty())
208542cbe538SGunnar Mills         {
208662598e31SEd Tanous             BMCWEB_LOG_DEBUG("Can't find Power Supply Attributes!");
208742cbe538SGunnar Mills             callback(inventoryItems);
208842cbe538SGunnar Mills             return;
208942cbe538SGunnar Mills         }
209042cbe538SGunnar Mills 
209142cbe538SGunnar Mills         // Currently we only support 1 power supply attribute, use this for
209242cbe538SGunnar Mills         // all the power supplies. Build map of object path to connection.
209342cbe538SGunnar Mills         // Assume just 1 connection and 1 path for now.
2094fe04d49cSNan Zhou         std::map<std::string, std::string> psAttributesConnections;
209542cbe538SGunnar Mills 
209642cbe538SGunnar Mills         if (subtree[0].first.empty() || subtree[0].second.empty())
209742cbe538SGunnar Mills         {
209862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
209942cbe538SGunnar Mills             callback(inventoryItems);
210042cbe538SGunnar Mills             return;
210142cbe538SGunnar Mills         }
210242cbe538SGunnar Mills 
210342cbe538SGunnar Mills         const std::string& psAttributesPath = subtree[0].first;
210442cbe538SGunnar Mills         const std::string& connection = subtree[0].second.begin()->first;
210542cbe538SGunnar Mills 
210642cbe538SGunnar Mills         if (connection.empty())
210742cbe538SGunnar Mills         {
210862598e31SEd Tanous             BMCWEB_LOG_DEBUG("Power Supply Attributes mapper error!");
210942cbe538SGunnar Mills             callback(inventoryItems);
211042cbe538SGunnar Mills             return;
211142cbe538SGunnar Mills         }
211242cbe538SGunnar Mills 
211342cbe538SGunnar Mills         psAttributesConnections[psAttributesPath] = connection;
211462598e31SEd Tanous         BMCWEB_LOG_DEBUG("Added mapping {} -> {}", psAttributesPath,
211562598e31SEd Tanous                          connection);
211642cbe538SGunnar Mills 
211742cbe538SGunnar Mills         getPowerSupplyAttributesData(sensorsAsyncResp, inventoryItems,
211842cbe538SGunnar Mills                                      psAttributesConnections,
211942cbe538SGunnar Mills                                      std::move(callback));
212062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getPowerSupplyAttributes respHandler exit");
2121e99073f5SGeorge Liu     });
212262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getPowerSupplyAttributes exit");
212342cbe538SGunnar Mills }
212442cbe538SGunnar Mills 
212542cbe538SGunnar Mills /**
2126adc4f0dbSShawn McCarney  * @brief Gets inventory items associated with sensors.
21278fb49dd6SShawn McCarney  *
21288fb49dd6SShawn McCarney  * Finds the inventory items that are associated with the specified sensors.
2129adc4f0dbSShawn McCarney  * Then gets D-Bus data for the inventory items, such as presence and VPD.
21308fb49dd6SShawn McCarney  *
2131adc4f0dbSShawn McCarney  * This data is later used to provide sensor property values in the JSON
2132adc4f0dbSShawn McCarney  * response.
21338fb49dd6SShawn McCarney  *
2134adc4f0dbSShawn McCarney  * Finds the inventory items asynchronously.  Invokes callback when the
2135adc4f0dbSShawn McCarney  * inventory items have been obtained.
2136adc4f0dbSShawn McCarney  *
2137adc4f0dbSShawn McCarney  * The callback must have the following signature:
2138adc4f0dbSShawn McCarney  *   @code
2139adc4f0dbSShawn McCarney  *   callback(std::shared_ptr<std::vector<InventoryItem>> inventoryItems)
2140adc4f0dbSShawn McCarney  *   @endcode
21418fb49dd6SShawn McCarney  *
21428fb49dd6SShawn McCarney  * @param sensorsAsyncResp Pointer to object holding response data.
21438fb49dd6SShawn McCarney  * @param sensorNames All sensors within the current chassis.
21448fb49dd6SShawn McCarney  * implements ObjectManager.
2145adc4f0dbSShawn McCarney  * @param callback Callback to invoke when inventory items have been obtained.
21468fb49dd6SShawn McCarney  */
2147adc4f0dbSShawn McCarney template <typename Callback>
2148d0090733SEd Tanous static void
2149d0090733SEd Tanous     getInventoryItems(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
2150fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>> sensorNames,
2151adc4f0dbSShawn McCarney                       Callback&& callback)
21528fb49dd6SShawn McCarney {
215362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems enter");
2154adc4f0dbSShawn McCarney     auto getInventoryItemAssociationsCb =
21558cb2c024SEd Tanous         [sensorsAsyncResp, callback = std::forward<Callback>(callback)](
2156adc4f0dbSShawn McCarney             std::shared_ptr<std::vector<InventoryItem>> inventoryItems) {
215762598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb enter");
21588fb49dd6SShawn McCarney         auto getInventoryItemsConnectionsCb =
2159d0090733SEd Tanous             [sensorsAsyncResp, inventoryItems,
21608cb2c024SEd Tanous              callback = std::forward<const Callback>(callback)](
2161fe04d49cSNan Zhou                 std::shared_ptr<std::set<std::string>> invConnections) {
216262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb enter");
2163002d39b4SEd Tanous             auto getInventoryItemsDataCb = [sensorsAsyncResp, inventoryItems,
2164d500549bSAnthony Wilson                                             callback{std::move(callback)}]() {
216562598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb enter");
216642cbe538SGunnar Mills 
2167002d39b4SEd Tanous                 auto getInventoryLedsCb = [sensorsAsyncResp, inventoryItems,
2168002d39b4SEd Tanous                                            callback{std::move(callback)}]() {
216962598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb enter");
217042cbe538SGunnar Mills                     // Find Power Supply Attributes and get the data
2171002d39b4SEd Tanous                     getPowerSupplyAttributes(sensorsAsyncResp, inventoryItems,
217242cbe538SGunnar Mills                                              std::move(callback));
217362598e31SEd Tanous                     BMCWEB_LOG_DEBUG("getInventoryLedsCb exit");
217442cbe538SGunnar Mills                 };
217542cbe538SGunnar Mills 
2176d500549bSAnthony Wilson                 // Find led connections and get the data
2177d500549bSAnthony Wilson                 getInventoryLeds(sensorsAsyncResp, inventoryItems,
217842cbe538SGunnar Mills                                  std::move(getInventoryLedsCb));
217962598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getInventoryItemsDataCb exit");
2180d500549bSAnthony Wilson             };
21818fb49dd6SShawn McCarney 
2182adc4f0dbSShawn McCarney             // Get inventory item data from connections
2183adc4f0dbSShawn McCarney             getInventoryItemsData(sensorsAsyncResp, inventoryItems,
2184d0090733SEd Tanous                                   invConnections,
2185d500549bSAnthony Wilson                                   std::move(getInventoryItemsDataCb));
218662598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsConnectionsCb exit");
21878fb49dd6SShawn McCarney         };
21888fb49dd6SShawn McCarney 
2189adc4f0dbSShawn McCarney         // Get connections that provide inventory item data
2190002d39b4SEd Tanous         getInventoryItemsConnections(sensorsAsyncResp, inventoryItems,
21918fb49dd6SShawn McCarney                                      std::move(getInventoryItemsConnectionsCb));
219262598e31SEd Tanous         BMCWEB_LOG_DEBUG("getInventoryItemAssociationsCb exit");
21938fb49dd6SShawn McCarney     };
21948fb49dd6SShawn McCarney 
2195adc4f0dbSShawn McCarney     // Get associations from sensors to inventory items
2196d0090733SEd Tanous     getInventoryItemAssociations(sensorsAsyncResp, sensorNames,
2197adc4f0dbSShawn McCarney                                  std::move(getInventoryItemAssociationsCb));
219862598e31SEd Tanous     BMCWEB_LOG_DEBUG("getInventoryItems exit");
2199adc4f0dbSShawn McCarney }
2200adc4f0dbSShawn McCarney 
2201adc4f0dbSShawn McCarney /**
2202adc4f0dbSShawn McCarney  * @brief Returns JSON PowerSupply object for the specified inventory item.
2203adc4f0dbSShawn McCarney  *
2204adc4f0dbSShawn McCarney  * Searches for a JSON PowerSupply object that matches the specified inventory
2205adc4f0dbSShawn McCarney  * item.  If one is not found, a new PowerSupply object is added to the JSON
2206adc4f0dbSShawn McCarney  * array.
2207adc4f0dbSShawn McCarney  *
2208adc4f0dbSShawn McCarney  * Multiple sensors are often associated with one power supply inventory item.
2209adc4f0dbSShawn McCarney  * As a result, multiple sensor values are stored in one JSON PowerSupply
2210adc4f0dbSShawn McCarney  * object.
2211adc4f0dbSShawn McCarney  *
2212adc4f0dbSShawn McCarney  * @param powerSupplyArray JSON array containing Redfish PowerSupply objects.
2213adc4f0dbSShawn McCarney  * @param inventoryItem Inventory item for the power supply.
2214adc4f0dbSShawn McCarney  * @param chassisId Chassis that contains the power supply.
2215adc4f0dbSShawn McCarney  * @return JSON PowerSupply object for the specified inventory item.
2216adc4f0dbSShawn McCarney  */
221723a21a1cSEd Tanous inline nlohmann::json& getPowerSupply(nlohmann::json& powerSupplyArray,
2218adc4f0dbSShawn McCarney                                       const InventoryItem& inventoryItem,
2219adc4f0dbSShawn McCarney                                       const std::string& chassisId)
2220adc4f0dbSShawn McCarney {
222118f8f608SEd Tanous     std::string nameS;
22226f4bd290SAlexander Hansen     nameS.resize(inventoryItem.name.size());
222318f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, nameS.begin(), '_', ' ');
2224adc4f0dbSShawn McCarney     // Check if matching PowerSupply object already exists in JSON array
2225adc4f0dbSShawn McCarney     for (nlohmann::json& powerSupply : powerSupplyArray)
2226adc4f0dbSShawn McCarney     {
222718f8f608SEd Tanous         nlohmann::json::iterator nameIt = powerSupply.find("Name");
222818f8f608SEd Tanous         if (nameIt == powerSupply.end())
222918f8f608SEd Tanous         {
223018f8f608SEd Tanous             continue;
223118f8f608SEd Tanous         }
223218f8f608SEd Tanous         const std::string* name = nameIt->get_ptr<std::string*>();
223318f8f608SEd Tanous         if (name == nullptr)
223418f8f608SEd Tanous         {
223518f8f608SEd Tanous             continue;
223618f8f608SEd Tanous         }
223718f8f608SEd Tanous         if (nameS == *name)
2238adc4f0dbSShawn McCarney         {
2239adc4f0dbSShawn McCarney             return powerSupply;
2240adc4f0dbSShawn McCarney         }
2241adc4f0dbSShawn McCarney     }
2242adc4f0dbSShawn McCarney 
2243adc4f0dbSShawn McCarney     // Add new PowerSupply object to JSON array
2244adc4f0dbSShawn McCarney     powerSupplyArray.push_back({});
2245adc4f0dbSShawn McCarney     nlohmann::json& powerSupply = powerSupplyArray.back();
2246ef4c65b7SEd Tanous     boost::urls::url url = boost::urls::format("/redfish/v1/Chassis/{}/Power",
2247ef4c65b7SEd Tanous                                                chassisId);
2248eddfc437SWilly Tu     url.set_fragment(("/PowerSupplies"_json_pointer).to_string());
2249eddfc437SWilly Tu     powerSupply["@odata.id"] = std::move(url);
225018f8f608SEd Tanous     std::string escaped;
22516f4bd290SAlexander Hansen     escaped.resize(inventoryItem.name.size());
225218f8f608SEd Tanous     std::ranges::replace_copy(inventoryItem.name, escaped.begin(), '_', ' ');
225318f8f608SEd Tanous     powerSupply["Name"] = std::move(escaped);
2254adc4f0dbSShawn McCarney     powerSupply["Manufacturer"] = inventoryItem.manufacturer;
2255adc4f0dbSShawn McCarney     powerSupply["Model"] = inventoryItem.model;
2256adc4f0dbSShawn McCarney     powerSupply["PartNumber"] = inventoryItem.partNumber;
2257adc4f0dbSShawn McCarney     powerSupply["SerialNumber"] = inventoryItem.serialNumber;
2258d500549bSAnthony Wilson     setLedState(powerSupply, &inventoryItem);
2259adc4f0dbSShawn McCarney 
226042cbe538SGunnar Mills     if (inventoryItem.powerSupplyEfficiencyPercent >= 0)
226142cbe538SGunnar Mills     {
226242cbe538SGunnar Mills         powerSupply["EfficiencyPercent"] =
226342cbe538SGunnar Mills             inventoryItem.powerSupplyEfficiencyPercent;
226442cbe538SGunnar Mills     }
226542cbe538SGunnar Mills 
2266aaf08ac7SMatt Simmering     powerSupply["Status"]["State"] = getState(&inventoryItem, true);
2267adc4f0dbSShawn McCarney     const char* health = inventoryItem.isFunctional ? "OK" : "Critical";
2268adc4f0dbSShawn McCarney     powerSupply["Status"]["Health"] = health;
2269adc4f0dbSShawn McCarney 
2270adc4f0dbSShawn McCarney     return powerSupply;
22718fb49dd6SShawn McCarney }
22728fb49dd6SShawn McCarney 
22738fb49dd6SShawn McCarney /**
2274de629b6eSShawn McCarney  * @brief Gets the values of the specified sensors.
2275de629b6eSShawn McCarney  *
2276de629b6eSShawn McCarney  * Stores the results as JSON in the SensorsAsyncResp.
2277de629b6eSShawn McCarney  *
2278de629b6eSShawn McCarney  * Gets the sensor values asynchronously.  Stores the results later when the
2279de629b6eSShawn McCarney  * information has been obtained.
2280de629b6eSShawn McCarney  *
2281adc4f0dbSShawn McCarney  * The sensorNames set contains all requested sensors for the current chassis.
2282de629b6eSShawn McCarney  *
2283de629b6eSShawn McCarney  * To minimize the number of DBus calls, the DBus method
2284de629b6eSShawn McCarney  * org.freedesktop.DBus.ObjectManager.GetManagedObjects() is used to get the
2285de629b6eSShawn McCarney  * values of all sensors provided by a connection (service).
2286de629b6eSShawn McCarney  *
2287de629b6eSShawn McCarney  * The connections set contains all the connections that provide sensor values.
2288de629b6eSShawn McCarney  *
2289adc4f0dbSShawn McCarney  * The InventoryItem vector contains D-Bus inventory items associated with the
2290adc4f0dbSShawn McCarney  * sensors.  Inventory item data is needed for some Redfish sensor properties.
2291adc4f0dbSShawn McCarney  *
2292de629b6eSShawn McCarney  * @param SensorsAsyncResp Pointer to object holding response data.
2293adc4f0dbSShawn McCarney  * @param sensorNames All requested sensors within the current chassis.
2294de629b6eSShawn McCarney  * @param connections Connections that provide sensor values.
2295de629b6eSShawn McCarney  * implements ObjectManager.
2296adc4f0dbSShawn McCarney  * @param inventoryItems Inventory items associated with the sensors.
2297de629b6eSShawn McCarney  */
229823a21a1cSEd Tanous inline void getSensorData(
229981ce609eSEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2300fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames,
2301fe04d49cSNan Zhou     const std::set<std::string>& connections,
2302b5a76932SEd Tanous     const std::shared_ptr<std::vector<InventoryItem>>& inventoryItems)
2303de629b6eSShawn McCarney {
230462598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData enter");
2305de629b6eSShawn McCarney     // Get managed objects from all services exposing sensors
2306de629b6eSShawn McCarney     for (const std::string& connection : connections)
2307de629b6eSShawn McCarney     {
23085eb468daSGeorge Liu         sdbusplus::message::object_path sensorPath(
23095eb468daSGeorge Liu             "/xyz/openbmc_project/sensors");
23105eb468daSGeorge Liu         dbus::utility::getManagedObjects(
23115eb468daSGeorge Liu             connection, sensorPath,
2312002d39b4SEd Tanous             [sensorsAsyncResp, sensorNames,
23135e7e2dc5SEd Tanous              inventoryItems](const boost::system::error_code& ec,
231402cad96eSEd Tanous                              const dbus::utility::ManagedObjectType& resp) {
231562598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb enter");
2316de629b6eSShawn McCarney             if (ec)
2317de629b6eSShawn McCarney             {
231862598e31SEd Tanous                 BMCWEB_LOG_ERROR("getManagedObjectsCb DBUS error: {}", ec);
23198d1b46d7Szhanghch05                 messages::internalError(sensorsAsyncResp->asyncResp->res);
2320de629b6eSShawn McCarney                 return;
2321de629b6eSShawn McCarney             }
2322de629b6eSShawn McCarney             // Go through all objects and update response with sensor data
2323de629b6eSShawn McCarney             for (const auto& objDictEntry : resp)
2324de629b6eSShawn McCarney             {
2325de629b6eSShawn McCarney                 const std::string& objPath =
2326de629b6eSShawn McCarney                     static_cast<const std::string&>(objDictEntry.first);
232762598e31SEd Tanous                 BMCWEB_LOG_DEBUG("getManagedObjectsCb parsing object {}",
232862598e31SEd Tanous                                  objPath);
2329de629b6eSShawn McCarney 
2330de629b6eSShawn McCarney                 std::vector<std::string> split;
2331de629b6eSShawn McCarney                 // Reserve space for
2332de629b6eSShawn McCarney                 // /xyz/openbmc_project/sensors/<name>/<subname>
2333de629b6eSShawn McCarney                 split.reserve(6);
233450ebd4afSEd Tanous                 // NOLINTNEXTLINE
233550ebd4afSEd Tanous                 bmcweb::split(split, objPath, '/');
2336de629b6eSShawn McCarney                 if (split.size() < 6)
2337de629b6eSShawn McCarney                 {
233862598e31SEd Tanous                     BMCWEB_LOG_ERROR("Got path that isn't long enough {}",
233962598e31SEd Tanous                                      objPath);
2340de629b6eSShawn McCarney                     continue;
2341de629b6eSShawn McCarney                 }
234250ebd4afSEd Tanous                 // These indexes aren't intuitive, as split puts an empty
2343de629b6eSShawn McCarney                 // string at the beginning
2344de629b6eSShawn McCarney                 const std::string& sensorType = split[4];
2345de629b6eSShawn McCarney                 const std::string& sensorName = split[5];
234662598e31SEd Tanous                 BMCWEB_LOG_DEBUG("sensorName {} sensorType {}", sensorName,
234762598e31SEd Tanous                                  sensorType);
234849c53ac9SJohnathan Mantey                 if (sensorNames->find(objPath) == sensorNames->end())
2349de629b6eSShawn McCarney                 {
235062598e31SEd Tanous                     BMCWEB_LOG_DEBUG("{} not in sensor list ", sensorName);
2351de629b6eSShawn McCarney                     continue;
2352de629b6eSShawn McCarney                 }
2353de629b6eSShawn McCarney 
2354adc4f0dbSShawn McCarney                 // Find inventory item (if any) associated with sensor
2355adc4f0dbSShawn McCarney                 InventoryItem* inventoryItem =
2356adc4f0dbSShawn McCarney                     findInventoryItemForSensor(inventoryItems, objPath);
2357adc4f0dbSShawn McCarney 
235895a3ecadSAnthony Wilson                 const std::string& sensorSchema =
235981ce609eSEd Tanous                     sensorsAsyncResp->chassisSubNode;
236095a3ecadSAnthony Wilson 
236195a3ecadSAnthony Wilson                 nlohmann::json* sensorJson = nullptr;
236295a3ecadSAnthony Wilson 
2363928fefb9SNan Zhou                 if (sensorSchema == sensors::node::sensors &&
2364928fefb9SNan Zhou                     !sensorsAsyncResp->efficientExpand)
236595a3ecadSAnthony Wilson                 {
2366c1d019a6SEd Tanous                     std::string sensorTypeEscaped(sensorType);
23673544d2a7SEd Tanous                     auto remove = std::ranges::remove(sensorTypeEscaped, '_');
23683544d2a7SEd Tanous 
23693544d2a7SEd Tanous                     sensorTypeEscaped.erase(std::ranges::begin(remove),
2370c1d019a6SEd Tanous                                             sensorTypeEscaped.end());
2371c1d019a6SEd Tanous                     std::string sensorId(sensorTypeEscaped);
2372c1d019a6SEd Tanous                     sensorId += "_";
2373c1d019a6SEd Tanous                     sensorId += sensorName;
2374c1d019a6SEd Tanous 
23758d1b46d7Szhanghch05                     sensorsAsyncResp->asyncResp->res.jsonValue["@odata.id"] =
2376ef4c65b7SEd Tanous                         boost::urls::format("/redfish/v1/Chassis/{}/{}/{}",
2377c1d019a6SEd Tanous                                             sensorsAsyncResp->chassisId,
2378ef4c65b7SEd Tanous                                             sensorsAsyncResp->chassisSubNode,
2379ef4c65b7SEd Tanous                                             sensorId);
23808d1b46d7Szhanghch05                     sensorJson = &(sensorsAsyncResp->asyncResp->res.jsonValue);
238195a3ecadSAnthony Wilson                 }
238295a3ecadSAnthony Wilson                 else
238395a3ecadSAnthony Wilson                 {
2384271584abSEd Tanous                     std::string fieldName;
2385928fefb9SNan Zhou                     if (sensorsAsyncResp->efficientExpand)
2386928fefb9SNan Zhou                     {
2387928fefb9SNan Zhou                         fieldName = "Members";
2388928fefb9SNan Zhou                     }
2389928fefb9SNan Zhou                     else if (sensorType == "temperature")
2390de629b6eSShawn McCarney                     {
2391de629b6eSShawn McCarney                         fieldName = "Temperatures";
2392de629b6eSShawn McCarney                     }
2393de629b6eSShawn McCarney                     else if (sensorType == "fan" || sensorType == "fan_tach" ||
2394de629b6eSShawn McCarney                              sensorType == "fan_pwm")
2395de629b6eSShawn McCarney                     {
2396de629b6eSShawn McCarney                         fieldName = "Fans";
2397de629b6eSShawn McCarney                     }
2398de629b6eSShawn McCarney                     else if (sensorType == "voltage")
2399de629b6eSShawn McCarney                     {
2400de629b6eSShawn McCarney                         fieldName = "Voltages";
2401de629b6eSShawn McCarney                     }
2402de629b6eSShawn McCarney                     else if (sensorType == "power")
2403de629b6eSShawn McCarney                     {
240455f79e6fSEd Tanous                         if (sensorName == "total_power")
2405028f7ebcSEddie James                         {
2406028f7ebcSEddie James                             fieldName = "PowerControl";
2407028f7ebcSEddie James                         }
2408adc4f0dbSShawn McCarney                         else if ((inventoryItem != nullptr) &&
2409adc4f0dbSShawn McCarney                                  (inventoryItem->isPowerSupply))
2410028f7ebcSEddie James                         {
2411de629b6eSShawn McCarney                             fieldName = "PowerSupplies";
2412de629b6eSShawn McCarney                         }
2413adc4f0dbSShawn McCarney                         else
2414adc4f0dbSShawn McCarney                         {
2415adc4f0dbSShawn McCarney                             // Other power sensors are in SensorCollection
2416adc4f0dbSShawn McCarney                             continue;
2417adc4f0dbSShawn McCarney                         }
2418028f7ebcSEddie James                     }
2419de629b6eSShawn McCarney                     else
2420de629b6eSShawn McCarney                     {
242162598e31SEd Tanous                         BMCWEB_LOG_ERROR("Unsure how to handle sensorType {}",
242262598e31SEd Tanous                                          sensorType);
2423de629b6eSShawn McCarney                         continue;
2424de629b6eSShawn McCarney                     }
2425de629b6eSShawn McCarney 
2426de629b6eSShawn McCarney                     nlohmann::json& tempArray =
24278d1b46d7Szhanghch05                         sensorsAsyncResp->asyncResp->res.jsonValue[fieldName];
2428adc4f0dbSShawn McCarney                     if (fieldName == "PowerControl")
242949c53ac9SJohnathan Mantey                     {
2430adc4f0dbSShawn McCarney                         if (tempArray.empty())
24317ab06f49SGunnar Mills                         {
243295a3ecadSAnthony Wilson                             // Put multiple "sensors" into a single
243395a3ecadSAnthony Wilson                             // PowerControl. Follows MemberId naming and
243495a3ecadSAnthony Wilson                             // naming in power.hpp.
24351476687dSEd Tanous                             nlohmann::json::object_t power;
2436ef4c65b7SEd Tanous                             boost::urls::url url = boost::urls::format(
2437ef4c65b7SEd Tanous                                 "/redfish/v1/Chassis/{}/{}",
2438eddfc437SWilly Tu                                 sensorsAsyncResp->chassisId,
2439eddfc437SWilly Tu                                 sensorsAsyncResp->chassisSubNode);
2440eddfc437SWilly Tu                             url.set_fragment((""_json_pointer / fieldName / "0")
2441eddfc437SWilly Tu                                                  .to_string());
2442eddfc437SWilly Tu                             power["@odata.id"] = std::move(url);
2443b2ba3072SPatrick Williams                             tempArray.emplace_back(std::move(power));
2444adc4f0dbSShawn McCarney                         }
2445adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
2446adc4f0dbSShawn McCarney                     }
2447adc4f0dbSShawn McCarney                     else if (fieldName == "PowerSupplies")
2448adc4f0dbSShawn McCarney                     {
2449adc4f0dbSShawn McCarney                         if (inventoryItem != nullptr)
2450adc4f0dbSShawn McCarney                         {
2451adc4f0dbSShawn McCarney                             sensorJson =
2452adc4f0dbSShawn McCarney                                 &(getPowerSupply(tempArray, *inventoryItem,
245381ce609eSEd Tanous                                                  sensorsAsyncResp->chassisId));
2454adc4f0dbSShawn McCarney                         }
245549c53ac9SJohnathan Mantey                     }
2456928fefb9SNan Zhou                     else if (fieldName == "Members")
2457928fefb9SNan Zhou                     {
2458677bb756SEd Tanous                         std::string sensorTypeEscaped(sensorType);
24593544d2a7SEd Tanous                         auto remove = std::ranges::remove(sensorTypeEscaped,
24603544d2a7SEd Tanous                                                           '_');
24613544d2a7SEd Tanous                         sensorTypeEscaped.erase(std::ranges::begin(remove),
2462677bb756SEd Tanous                                                 sensorTypeEscaped.end());
2463677bb756SEd Tanous                         std::string sensorId(sensorTypeEscaped);
2464677bb756SEd Tanous                         sensorId += "_";
2465677bb756SEd Tanous                         sensorId += sensorName;
2466677bb756SEd Tanous 
24671476687dSEd Tanous                         nlohmann::json::object_t member;
2468ef4c65b7SEd Tanous                         member["@odata.id"] = boost::urls::format(
2469ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}/{}",
2470677bb756SEd Tanous                             sensorsAsyncResp->chassisId,
2471677bb756SEd Tanous                             sensorsAsyncResp->chassisSubNode, sensorId);
2472b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2473928fefb9SNan Zhou                         sensorJson = &(tempArray.back());
2474928fefb9SNan Zhou                     }
247549c53ac9SJohnathan Mantey                     else
247649c53ac9SJohnathan Mantey                     {
24771476687dSEd Tanous                         nlohmann::json::object_t member;
2478ef4c65b7SEd Tanous                         boost::urls::url url = boost::urls::format(
2479ef4c65b7SEd Tanous                             "/redfish/v1/Chassis/{}/{}",
2480eddfc437SWilly Tu                             sensorsAsyncResp->chassisId,
2481eddfc437SWilly Tu                             sensorsAsyncResp->chassisSubNode);
2482eddfc437SWilly Tu                         url.set_fragment(
2483eddfc437SWilly Tu                             (""_json_pointer / fieldName).to_string());
2484eddfc437SWilly Tu                         member["@odata.id"] = std::move(url);
2485b2ba3072SPatrick Williams                         tempArray.emplace_back(std::move(member));
2486adc4f0dbSShawn McCarney                         sensorJson = &(tempArray.back());
248749c53ac9SJohnathan Mantey                     }
248895a3ecadSAnthony Wilson                 }
2489de629b6eSShawn McCarney 
2490adc4f0dbSShawn McCarney                 if (sensorJson != nullptr)
2491adc4f0dbSShawn McCarney                 {
24921d7c0054SEd Tanous                     objectInterfacesToJson(sensorName, sensorType,
24931d7c0054SEd Tanous                                            sensorsAsyncResp->chassisSubNode,
24941d7c0054SEd Tanous                                            objDictEntry.second, *sensorJson,
24951d7c0054SEd Tanous                                            inventoryItem);
24961d7c0054SEd Tanous 
24971d7c0054SEd Tanous                     std::string path = "/xyz/openbmc_project/sensors/";
24981d7c0054SEd Tanous                     path += sensorType;
24991d7c0054SEd Tanous                     path += "/";
25001d7c0054SEd Tanous                     path += sensorName;
2501c1d019a6SEd Tanous                     sensorsAsyncResp->addMetadata(*sensorJson, path);
2502adc4f0dbSShawn McCarney                 }
2503de629b6eSShawn McCarney             }
250481ce609eSEd Tanous             if (sensorsAsyncResp.use_count() == 1)
250549c53ac9SJohnathan Mantey             {
250681ce609eSEd Tanous                 sortJSONResponse(sensorsAsyncResp);
2507928fefb9SNan Zhou                 if (sensorsAsyncResp->chassisSubNode ==
2508928fefb9SNan Zhou                         sensors::node::sensors &&
2509928fefb9SNan Zhou                     sensorsAsyncResp->efficientExpand)
2510928fefb9SNan Zhou                 {
2511928fefb9SNan Zhou                     sensorsAsyncResp->asyncResp->res
2512928fefb9SNan Zhou                         .jsonValue["Members@odata.count"] =
2513928fefb9SNan Zhou                         sensorsAsyncResp->asyncResp->res.jsonValue["Members"]
2514928fefb9SNan Zhou                             .size();
2515928fefb9SNan Zhou                 }
2516928fefb9SNan Zhou                 else if (sensorsAsyncResp->chassisSubNode ==
2517928fefb9SNan Zhou                          sensors::node::thermal)
25188bd25ccdSJames Feist                 {
251981ce609eSEd Tanous                     populateFanRedundancy(sensorsAsyncResp);
25208bd25ccdSJames Feist                 }
252149c53ac9SJohnathan Mantey             }
252262598e31SEd Tanous             BMCWEB_LOG_DEBUG("getManagedObjectsCb exit");
25235eb468daSGeorge Liu         });
252423a21a1cSEd Tanous     }
252562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getSensorData exit");
2526de629b6eSShawn McCarney }
2527de629b6eSShawn McCarney 
2528fe04d49cSNan Zhou inline void
2529fe04d49cSNan Zhou     processSensorList(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
2530fe04d49cSNan Zhou                       const std::shared_ptr<std::set<std::string>>& sensorNames)
25311abe55efSEd Tanous {
2532fe04d49cSNan Zhou     auto getConnectionCb = [sensorsAsyncResp, sensorNames](
2533fe04d49cSNan Zhou                                const std::set<std::string>& connections) {
253462598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb enter");
2535adc4f0dbSShawn McCarney         auto getInventoryItemsCb =
2536d0090733SEd Tanous             [sensorsAsyncResp, sensorNames,
2537d0090733SEd Tanous              connections](const std::shared_ptr<std::vector<InventoryItem>>&
2538adc4f0dbSShawn McCarney                               inventoryItems) {
253962598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb enter");
254049c53ac9SJohnathan Mantey             // Get sensor data and store results in JSON
2541002d39b4SEd Tanous             getSensorData(sensorsAsyncResp, sensorNames, connections,
2542d0090733SEd Tanous                           inventoryItems);
254362598e31SEd Tanous             BMCWEB_LOG_DEBUG("getInventoryItemsCb exit");
2544adc4f0dbSShawn McCarney         };
2545adc4f0dbSShawn McCarney 
2546adc4f0dbSShawn McCarney         // Get inventory items associated with sensors
2547d0090733SEd Tanous         getInventoryItems(sensorsAsyncResp, sensorNames,
2548adc4f0dbSShawn McCarney                           std::move(getInventoryItemsCb));
2549adc4f0dbSShawn McCarney 
255062598e31SEd Tanous         BMCWEB_LOG_DEBUG("getConnectionCb exit");
255108777fb0SLewanczyk, Dawid     };
2552de629b6eSShawn McCarney 
2553de629b6eSShawn McCarney     // Get set of connections that provide sensor values
255481ce609eSEd Tanous     getConnections(sensorsAsyncResp, sensorNames, std::move(getConnectionCb));
255595a3ecadSAnthony Wilson }
255695a3ecadSAnthony Wilson 
255795a3ecadSAnthony Wilson /**
255895a3ecadSAnthony Wilson  * @brief Entry point for retrieving sensors data related to requested
255995a3ecadSAnthony Wilson  *        chassis.
256095a3ecadSAnthony Wilson  * @param SensorsAsyncResp   Pointer to object holding response data
256195a3ecadSAnthony Wilson  */
2562b5a76932SEd Tanous inline void
256381ce609eSEd Tanous     getChassisData(const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
256495a3ecadSAnthony Wilson {
256562598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData enter");
256695a3ecadSAnthony Wilson     auto getChassisCb =
256781ce609eSEd Tanous         [sensorsAsyncResp](
2568fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorNames) {
256962598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb enter");
257081ce609eSEd Tanous         processSensorList(sensorsAsyncResp, sensorNames);
257162598e31SEd Tanous         BMCWEB_LOG_DEBUG("getChassisCb exit");
257208777fb0SLewanczyk, Dawid     };
2573928fefb9SNan Zhou     // SensorCollection doesn't contain the Redundancy property
2574928fefb9SNan Zhou     if (sensorsAsyncResp->chassisSubNode != sensors::node::sensors)
2575928fefb9SNan Zhou     {
25768d1b46d7Szhanghch05         sensorsAsyncResp->asyncResp->res.jsonValue["Redundancy"] =
25778d1b46d7Szhanghch05             nlohmann::json::array();
2578928fefb9SNan Zhou     }
257926f03899SShawn McCarney     // Get set of sensors in chassis
25807f1cc26dSEd Tanous     getChassis(sensorsAsyncResp->asyncResp, sensorsAsyncResp->chassisId,
25817f1cc26dSEd Tanous                sensorsAsyncResp->chassisSubNode, sensorsAsyncResp->types,
25827f1cc26dSEd Tanous                std::move(getChassisCb));
258362598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisData exit");
2584271584abSEd Tanous }
258508777fb0SLewanczyk, Dawid 
2586413961deSRichard Marian Thomaiyar /**
258749c53ac9SJohnathan Mantey  * @brief Find the requested sensorName in the list of all sensors supplied by
258849c53ac9SJohnathan Mantey  * the chassis node
258949c53ac9SJohnathan Mantey  *
259049c53ac9SJohnathan Mantey  * @param sensorName   The sensor name supplied in the PATCH request
259149c53ac9SJohnathan Mantey  * @param sensorsList  The list of sensors managed by the chassis node
259249c53ac9SJohnathan Mantey  * @param sensorsModified  The list of sensors that were found as a result of
259349c53ac9SJohnathan Mantey  *                         repeated calls to this function
259449c53ac9SJohnathan Mantey  */
2595fe04d49cSNan Zhou inline bool
2596fe04d49cSNan Zhou     findSensorNameUsingSensorPath(std::string_view sensorName,
259702cad96eSEd Tanous                                   const std::set<std::string>& sensorsList,
2598fe04d49cSNan Zhou                                   std::set<std::string>& sensorsModified)
259949c53ac9SJohnathan Mantey {
2600fe04d49cSNan Zhou     for (const auto& chassisSensor : sensorsList)
260149c53ac9SJohnathan Mantey     {
260228aa8de5SGeorge Liu         sdbusplus::message::object_path path(chassisSensor);
2603b00dcc27SEd Tanous         std::string thisSensorName = path.filename();
260428aa8de5SGeorge Liu         if (thisSensorName.empty())
260549c53ac9SJohnathan Mantey         {
260649c53ac9SJohnathan Mantey             continue;
260749c53ac9SJohnathan Mantey         }
260849c53ac9SJohnathan Mantey         if (thisSensorName == sensorName)
260949c53ac9SJohnathan Mantey         {
261049c53ac9SJohnathan Mantey             sensorsModified.emplace(chassisSensor);
261149c53ac9SJohnathan Mantey             return true;
261249c53ac9SJohnathan Mantey         }
261349c53ac9SJohnathan Mantey     }
261449c53ac9SJohnathan Mantey     return false;
261549c53ac9SJohnathan Mantey }
261649c53ac9SJohnathan Mantey 
2617c71d6125SEd Tanous inline std::pair<std::string, std::string>
2618c71d6125SEd Tanous     splitSensorNameAndType(std::string_view sensorId)
2619c71d6125SEd Tanous {
2620c71d6125SEd Tanous     size_t index = sensorId.find('_');
2621c71d6125SEd Tanous     if (index == std::string::npos)
2622c71d6125SEd Tanous     {
2623c71d6125SEd Tanous         return std::make_pair<std::string, std::string>("", "");
2624c71d6125SEd Tanous     }
2625c71d6125SEd Tanous     std::string sensorType{sensorId.substr(0, index)};
2626c71d6125SEd Tanous     std::string sensorName{sensorId.substr(index + 1)};
2627c71d6125SEd Tanous     // fan_pwm and fan_tach need special handling
2628c71d6125SEd Tanous     if (sensorType == "fantach" || sensorType == "fanpwm")
2629c71d6125SEd Tanous     {
2630c71d6125SEd Tanous         sensorType.insert(3, 1, '_');
2631c71d6125SEd Tanous     }
2632c71d6125SEd Tanous     return std::make_pair(sensorType, sensorName);
2633c71d6125SEd Tanous }
2634c71d6125SEd Tanous 
263549c53ac9SJohnathan Mantey /**
2636413961deSRichard Marian Thomaiyar  * @brief Entry point for overriding sensor values of given sensor
2637413961deSRichard Marian Thomaiyar  *
26388d1b46d7Szhanghch05  * @param sensorAsyncResp   response object
26394bb3dc34SCarol Wang  * @param allCollections   Collections extract from sensors' request patch info
2640413961deSRichard Marian Thomaiyar  * @param chassisSubNode   Chassis Node for which the query has to happen
2641413961deSRichard Marian Thomaiyar  */
264223a21a1cSEd Tanous inline void setSensorsOverride(
2643b5a76932SEd Tanous     const std::shared_ptr<SensorsAsyncResp>& sensorAsyncResp,
26440885057cSEd Tanous     std::unordered_map<std::string, std::vector<nlohmann::json::object_t>>&
2645397fd61fSjayaprakash Mutyala         allCollections)
2646413961deSRichard Marian Thomaiyar {
264762598e31SEd Tanous     BMCWEB_LOG_INFO("setSensorsOverride for subNode{}",
264862598e31SEd Tanous                     sensorAsyncResp->chassisSubNode);
2649413961deSRichard Marian Thomaiyar 
2650d02aad39SEd Tanous     std::string_view propertyValueName;
2651f65af9e8SRichard Marian Thomaiyar     std::unordered_map<std::string, std::pair<double, std::string>> overrideMap;
2652413961deSRichard Marian Thomaiyar     std::string memberId;
2653543f4400SEd Tanous     double value = 0.0;
2654f65af9e8SRichard Marian Thomaiyar     for (auto& collectionItems : allCollections)
2655f65af9e8SRichard Marian Thomaiyar     {
2656f65af9e8SRichard Marian Thomaiyar         if (collectionItems.first == "Temperatures")
2657f65af9e8SRichard Marian Thomaiyar         {
2658f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingCelsius";
2659f65af9e8SRichard Marian Thomaiyar         }
2660f65af9e8SRichard Marian Thomaiyar         else if (collectionItems.first == "Fans")
2661f65af9e8SRichard Marian Thomaiyar         {
2662f65af9e8SRichard Marian Thomaiyar             propertyValueName = "Reading";
2663f65af9e8SRichard Marian Thomaiyar         }
2664f65af9e8SRichard Marian Thomaiyar         else
2665f65af9e8SRichard Marian Thomaiyar         {
2666f65af9e8SRichard Marian Thomaiyar             propertyValueName = "ReadingVolts";
2667f65af9e8SRichard Marian Thomaiyar         }
2668f65af9e8SRichard Marian Thomaiyar         for (auto& item : collectionItems.second)
2669f65af9e8SRichard Marian Thomaiyar         {
26700885057cSEd Tanous             if (!json_util::readJsonObject(
26710885057cSEd Tanous                     item, sensorAsyncResp->asyncResp->res, "MemberId", memberId,
26720885057cSEd Tanous                     propertyValueName, value))
2673413961deSRichard Marian Thomaiyar             {
2674413961deSRichard Marian Thomaiyar                 return;
2675413961deSRichard Marian Thomaiyar             }
2676f65af9e8SRichard Marian Thomaiyar             overrideMap.emplace(memberId,
2677f65af9e8SRichard Marian Thomaiyar                                 std::make_pair(value, collectionItems.first));
2678f65af9e8SRichard Marian Thomaiyar         }
2679f65af9e8SRichard Marian Thomaiyar     }
26804bb3dc34SCarol Wang 
2681002d39b4SEd Tanous     auto getChassisSensorListCb =
2682d02aad39SEd Tanous         [sensorAsyncResp, overrideMap,
2683d02aad39SEd Tanous          propertyValueNameStr = std::string(propertyValueName)](
2684fe04d49cSNan Zhou             const std::shared_ptr<std::set<std::string>>& sensorsList) {
268549c53ac9SJohnathan Mantey         // Match sensor names in the PATCH request to those managed by the
268649c53ac9SJohnathan Mantey         // chassis node
2687fe04d49cSNan Zhou         const std::shared_ptr<std::set<std::string>> sensorNames =
2688fe04d49cSNan Zhou             std::make_shared<std::set<std::string>>();
2689f65af9e8SRichard Marian Thomaiyar         for (const auto& item : overrideMap)
2690413961deSRichard Marian Thomaiyar         {
2691f65af9e8SRichard Marian Thomaiyar             const auto& sensor = item.first;
2692c71d6125SEd Tanous             std::pair<std::string, std::string> sensorNameType =
2693c71d6125SEd Tanous                 splitSensorNameAndType(sensor);
2694c71d6125SEd Tanous             if (!findSensorNameUsingSensorPath(sensorNameType.second,
2695c71d6125SEd Tanous                                                *sensorsList, *sensorNames))
2696f65af9e8SRichard Marian Thomaiyar             {
269762598e31SEd Tanous                 BMCWEB_LOG_INFO("Unable to find memberId {}", item.first);
26988d1b46d7Szhanghch05                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2699f65af9e8SRichard Marian Thomaiyar                                            item.second.second, item.first);
2700413961deSRichard Marian Thomaiyar                 return;
2701413961deSRichard Marian Thomaiyar             }
2702f65af9e8SRichard Marian Thomaiyar         }
2703413961deSRichard Marian Thomaiyar         // Get the connection to which the memberId belongs
2704002d39b4SEd Tanous         auto getObjectsWithConnectionCb =
2705d02aad39SEd Tanous             [sensorAsyncResp, overrideMap, propertyValueNameStr](
2706d02aad39SEd Tanous                 const std::set<std::string>& /*connections*/,
2707002d39b4SEd Tanous                 const std::set<std::pair<std::string, std::string>>&
2708413961deSRichard Marian Thomaiyar                     objectsWithConnection) {
2709f65af9e8SRichard Marian Thomaiyar             if (objectsWithConnection.size() != overrideMap.size())
2710413961deSRichard Marian Thomaiyar             {
271162598e31SEd Tanous                 BMCWEB_LOG_INFO(
271262598e31SEd Tanous                     "Unable to find all objects with proper connection {} requested {}",
271362598e31SEd Tanous                     objectsWithConnection.size(), overrideMap.size());
27144f277b54SJayaprakash Mutyala                 messages::resourceNotFound(sensorAsyncResp->asyncResp->res,
2715a0ec28b6SAdrian Ambrożewicz                                            sensorAsyncResp->chassisSubNode ==
2716a0ec28b6SAdrian Ambrożewicz                                                    sensors::node::thermal
2717413961deSRichard Marian Thomaiyar                                                ? "Temperatures"
2718413961deSRichard Marian Thomaiyar                                                : "Voltages",
2719f65af9e8SRichard Marian Thomaiyar                                            "Count");
2720f65af9e8SRichard Marian Thomaiyar                 return;
2721f65af9e8SRichard Marian Thomaiyar             }
2722f65af9e8SRichard Marian Thomaiyar             for (const auto& item : objectsWithConnection)
2723f65af9e8SRichard Marian Thomaiyar             {
272428aa8de5SGeorge Liu                 sdbusplus::message::object_path path(item.first);
272528aa8de5SGeorge Liu                 std::string sensorName = path.filename();
272628aa8de5SGeorge Liu                 if (sensorName.empty())
2727f65af9e8SRichard Marian Thomaiyar                 {
27284f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2729f65af9e8SRichard Marian Thomaiyar                     return;
2730f65af9e8SRichard Marian Thomaiyar                 }
27313f5eb755SBan Feng                 std::string id = path.parent_path().filename();
27323544d2a7SEd Tanous                 auto remove = std::ranges::remove(id, '_');
27333544d2a7SEd Tanous                 id.erase(std::ranges::begin(remove), id.end());
27343f5eb755SBan Feng                 id += "_";
27353f5eb755SBan Feng                 id += sensorName;
2736f65af9e8SRichard Marian Thomaiyar 
27373f5eb755SBan Feng                 const auto& iterator = overrideMap.find(id);
2738f65af9e8SRichard Marian Thomaiyar                 if (iterator == overrideMap.end())
2739f65af9e8SRichard Marian Thomaiyar                 {
274062598e31SEd Tanous                     BMCWEB_LOG_INFO("Unable to find sensor object{}",
274162598e31SEd Tanous                                     item.first);
27424f277b54SJayaprakash Mutyala                     messages::internalError(sensorAsyncResp->asyncResp->res);
2743413961deSRichard Marian Thomaiyar                     return;
2744413961deSRichard Marian Thomaiyar                 }
2745*e93abac6SGinu George                 setDbusProperty(sensorAsyncResp->asyncResp,
2746*e93abac6SGinu George                                 propertyValueNameStr, item.second, item.first,
2747*e93abac6SGinu George                                 "xyz.openbmc_project.Sensor.Value", "Value",
2748d02aad39SEd Tanous                                 iterator->second.first);
2749f65af9e8SRichard Marian Thomaiyar             }
2750413961deSRichard Marian Thomaiyar         };
2751413961deSRichard Marian Thomaiyar         // Get object with connection for the given sensor name
2752413961deSRichard Marian Thomaiyar         getObjectsWithConnection(sensorAsyncResp, sensorNames,
2753413961deSRichard Marian Thomaiyar                                  std::move(getObjectsWithConnectionCb));
2754413961deSRichard Marian Thomaiyar     };
2755413961deSRichard Marian Thomaiyar     // get full sensor list for the given chassisId and cross verify the sensor.
27567f1cc26dSEd Tanous     getChassis(sensorAsyncResp->asyncResp, sensorAsyncResp->chassisId,
27577f1cc26dSEd Tanous                sensorAsyncResp->chassisSubNode, sensorAsyncResp->types,
27587f1cc26dSEd Tanous                std::move(getChassisSensorListCb));
2759413961deSRichard Marian Thomaiyar }
2760413961deSRichard Marian Thomaiyar 
2761a0ec28b6SAdrian Ambrożewicz /**
2762a0ec28b6SAdrian Ambrożewicz  * @brief Retrieves mapping of Redfish URIs to sensor value property to D-Bus
2763a0ec28b6SAdrian Ambrożewicz  * path of the sensor.
2764a0ec28b6SAdrian Ambrożewicz  *
2765a0ec28b6SAdrian Ambrożewicz  * Function builds valid Redfish response for sensor query of given chassis and
2766a0ec28b6SAdrian Ambrożewicz  * node. It then builds metadata about Redfish<->D-Bus correlations and provides
2767a0ec28b6SAdrian Ambrożewicz  * it to caller in a callback.
2768a0ec28b6SAdrian Ambrożewicz  *
2769a0ec28b6SAdrian Ambrożewicz  * @param chassis   Chassis for which retrieval should be performed
2770a0ec28b6SAdrian Ambrożewicz  * @param node  Node (group) of sensors. See sensors::node for supported values
2771a0ec28b6SAdrian Ambrożewicz  * @param mapComplete   Callback to be called with retrieval result
2772a0ec28b6SAdrian Ambrożewicz  */
2773931edc79SEd Tanous template <typename Callback>
2774021d32cfSKrzysztof Grobelny inline void retrieveUriToDbusMap(const std::string& chassis,
2775021d32cfSKrzysztof Grobelny                                  const std::string& node,
2776931edc79SEd Tanous                                  Callback&& mapComplete)
2777a0ec28b6SAdrian Ambrożewicz {
277802da7c5aSEd Tanous     decltype(sensors::paths)::const_iterator pathIt =
277902da7c5aSEd Tanous         std::find_if(sensors::paths.cbegin(), sensors::paths.cend(),
278002da7c5aSEd Tanous                      [&node](auto&& val) { return val.first == node; });
278102da7c5aSEd Tanous     if (pathIt == sensors::paths.cend())
2782a0ec28b6SAdrian Ambrożewicz     {
278362598e31SEd Tanous         BMCWEB_LOG_ERROR("Wrong node provided : {}", node);
27846804b5c8SEd Tanous         std::map<std::string, std::string> noop;
27856804b5c8SEd Tanous         mapComplete(boost::beast::http::status::bad_request, noop);
2786a0ec28b6SAdrian Ambrożewicz         return;
2787a0ec28b6SAdrian Ambrożewicz     }
2788d51e072fSKrzysztof Grobelny 
278972374eb7SNan Zhou     auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
2790931edc79SEd Tanous     auto callback = [asyncResp,
27918cb2c024SEd Tanous                      mapCompleteCb = std::forward<Callback>(mapComplete)](
2792a0ec28b6SAdrian Ambrożewicz                         const boost::beast::http::status status,
2793fe04d49cSNan Zhou                         const std::map<std::string, std::string>& uriToDbus) {
2794fe04d49cSNan Zhou         mapCompleteCb(status, uriToDbus);
2795fe04d49cSNan Zhou     };
2796a0ec28b6SAdrian Ambrożewicz 
2797a0ec28b6SAdrian Ambrożewicz     auto resp = std::make_shared<SensorsAsyncResp>(
2798d51e072fSKrzysztof Grobelny         asyncResp, chassis, pathIt->second, node, std::move(callback));
2799a0ec28b6SAdrian Ambrożewicz     getChassisData(resp);
2800a0ec28b6SAdrian Ambrożewicz }
2801a0ec28b6SAdrian Ambrożewicz 
2802bacb2162SNan Zhou namespace sensors
2803bacb2162SNan Zhou {
2804928fefb9SNan Zhou 
2805bacb2162SNan Zhou inline void getChassisCallback(
2806c1d019a6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2807c1d019a6SEd Tanous     std::string_view chassisId, std::string_view chassisSubNode,
2808fe04d49cSNan Zhou     const std::shared_ptr<std::set<std::string>>& sensorNames)
2809bacb2162SNan Zhou {
281062598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback enter ");
2811bacb2162SNan Zhou 
2812c1d019a6SEd Tanous     nlohmann::json& entriesArray = asyncResp->res.jsonValue["Members"];
2813c1d019a6SEd Tanous     for (const std::string& sensor : *sensorNames)
2814bacb2162SNan Zhou     {
281562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Adding sensor: {}", sensor);
2816bacb2162SNan Zhou 
2817bacb2162SNan Zhou         sdbusplus::message::object_path path(sensor);
2818bacb2162SNan Zhou         std::string sensorName = path.filename();
2819bacb2162SNan Zhou         if (sensorName.empty())
2820bacb2162SNan Zhou         {
282162598e31SEd Tanous             BMCWEB_LOG_ERROR("Invalid sensor path: {}", sensor);
2822c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2823bacb2162SNan Zhou             return;
2824bacb2162SNan Zhou         }
2825c1d019a6SEd Tanous         std::string type = path.parent_path().filename();
2826c1d019a6SEd Tanous         // fan_tach has an underscore in it, so remove it to "normalize" the
2827c1d019a6SEd Tanous         // type in the URI
28283544d2a7SEd Tanous         auto remove = std::ranges::remove(type, '_');
28293544d2a7SEd Tanous         type.erase(std::ranges::begin(remove), type.end());
2830c1d019a6SEd Tanous 
28311476687dSEd Tanous         nlohmann::json::object_t member;
2832c1d019a6SEd Tanous         std::string id = type;
2833c1d019a6SEd Tanous         id += "_";
2834c1d019a6SEd Tanous         id += sensorName;
2835ef4c65b7SEd Tanous         member["@odata.id"] = boost::urls::format(
2836ef4c65b7SEd Tanous             "/redfish/v1/Chassis/{}/{}/{}", chassisId, chassisSubNode, id);
2837c1d019a6SEd Tanous 
2838b2ba3072SPatrick Williams         entriesArray.emplace_back(std::move(member));
2839bacb2162SNan Zhou     }
2840bacb2162SNan Zhou 
2841c1d019a6SEd Tanous     asyncResp->res.jsonValue["Members@odata.count"] = entriesArray.size();
284262598e31SEd Tanous     BMCWEB_LOG_DEBUG("getChassisCallback exit");
2843bacb2162SNan Zhou }
2844e6bd846dSNan Zhou 
2845ac106bf6SEd Tanous inline void handleSensorCollectionGet(
2846ac106bf6SEd Tanous     App& app, const crow::Request& req,
2847ac106bf6SEd Tanous     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2848de167a6fSNan Zhou     const std::string& chassisId)
2849de167a6fSNan Zhou {
2850de167a6fSNan Zhou     query_param::QueryCapabilities capabilities = {
2851de167a6fSNan Zhou         .canDelegateExpandLevel = 1,
2852de167a6fSNan Zhou     };
2853de167a6fSNan Zhou     query_param::Query delegatedQuery;
2854ac106bf6SEd Tanous     if (!redfish::setUpRedfishRouteWithDelegation(app, req, asyncResp,
2855de167a6fSNan Zhou                                                   delegatedQuery, capabilities))
2856de167a6fSNan Zhou     {
2857de167a6fSNan Zhou         return;
2858de167a6fSNan Zhou     }
2859de167a6fSNan Zhou 
2860de167a6fSNan Zhou     if (delegatedQuery.expandType != query_param::ExpandType::None)
2861de167a6fSNan Zhou     {
2862de167a6fSNan Zhou         // we perform efficient expand.
2863ac106bf6SEd Tanous         auto sensorsAsyncResp = std::make_shared<SensorsAsyncResp>(
2864ac106bf6SEd Tanous             asyncResp, chassisId, sensors::dbus::sensorPaths,
2865de167a6fSNan Zhou             sensors::node::sensors,
2866de167a6fSNan Zhou             /*efficientExpand=*/true);
2867ac106bf6SEd Tanous         getChassisData(sensorsAsyncResp);
2868de167a6fSNan Zhou 
286962598e31SEd Tanous         BMCWEB_LOG_DEBUG(
287062598e31SEd Tanous             "SensorCollection doGet exit via efficient expand handler");
2871de167a6fSNan Zhou         return;
28720bad320cSEd Tanous     }
2873de167a6fSNan Zhou 
2874de167a6fSNan Zhou     // We get all sensors as hyperlinkes in the chassis (this
2875de167a6fSNan Zhou     // implies we reply on the default query parameters handler)
2876ac106bf6SEd Tanous     getChassis(asyncResp, chassisId, sensors::node::sensors, dbus::sensorPaths,
2877ac106bf6SEd Tanous                std::bind_front(sensors::getChassisCallback, asyncResp,
2878ac106bf6SEd Tanous                                chassisId, sensors::node::sensors));
2879c1d019a6SEd Tanous }
28807f1cc26dSEd Tanous 
2881c1d019a6SEd Tanous inline void
2882c1d019a6SEd Tanous     getSensorFromDbus(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2883c1d019a6SEd Tanous                       const std::string& sensorPath,
2884c1d019a6SEd Tanous                       const ::dbus::utility::MapperGetObject& mapperResponse)
2885c1d019a6SEd Tanous {
2886c1d019a6SEd Tanous     if (mapperResponse.size() != 1)
2887c1d019a6SEd Tanous     {
2888c1d019a6SEd Tanous         messages::internalError(asyncResp->res);
2889c1d019a6SEd Tanous         return;
2890c1d019a6SEd Tanous     }
2891c1d019a6SEd Tanous     const auto& valueIface = *mapperResponse.begin();
2892c1d019a6SEd Tanous     const std::string& connectionName = valueIface.first;
289362598e31SEd Tanous     BMCWEB_LOG_DEBUG("Looking up {}", connectionName);
289462598e31SEd Tanous     BMCWEB_LOG_DEBUG("Path {}", sensorPath);
2895c1343bf6SKrzysztof Grobelny 
2896c1343bf6SKrzysztof Grobelny     sdbusplus::asio::getAllProperties(
2897c1343bf6SKrzysztof Grobelny         *crow::connections::systemBus, connectionName, sensorPath, "",
2898c1d019a6SEd Tanous         [asyncResp,
28995e7e2dc5SEd Tanous          sensorPath](const boost::system::error_code& ec,
2900c1d019a6SEd Tanous                      const ::dbus::utility::DBusPropertiesMap& valuesDict) {
2901c1d019a6SEd Tanous         if (ec)
2902c1d019a6SEd Tanous         {
2903c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
2904c1d019a6SEd Tanous             return;
2905c1d019a6SEd Tanous         }
2906c1d019a6SEd Tanous         sdbusplus::message::object_path path(sensorPath);
2907c1d019a6SEd Tanous         std::string name = path.filename();
2908c1d019a6SEd Tanous         path = path.parent_path();
2909c1d019a6SEd Tanous         std::string type = path.filename();
2910c1d019a6SEd Tanous         objectPropertiesToJson(name, type, sensors::node::sensors, valuesDict,
2911c1d019a6SEd Tanous                                asyncResp->res.jsonValue, nullptr);
2912c1343bf6SKrzysztof Grobelny     });
2913de167a6fSNan Zhou }
2914de167a6fSNan Zhou 
2915e6bd846dSNan Zhou inline void handleSensorGet(App& app, const crow::Request& req,
2916c1d019a6SEd Tanous                             const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
2917677bb756SEd Tanous                             const std::string& chassisId,
2918c1d019a6SEd Tanous                             const std::string& sensorId)
2919e6bd846dSNan Zhou {
2920c1d019a6SEd Tanous     if (!redfish::setUpRedfishRoute(app, req, asyncResp))
2921e6bd846dSNan Zhou     {
2922e6bd846dSNan Zhou         return;
2923e6bd846dSNan Zhou     }
2924c71d6125SEd Tanous     std::pair<std::string, std::string> nameType =
2925c71d6125SEd Tanous         splitSensorNameAndType(sensorId);
2926c71d6125SEd Tanous     if (nameType.first.empty() || nameType.second.empty())
2927c1d019a6SEd Tanous     {
2928c1d019a6SEd Tanous         messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2929c1d019a6SEd Tanous         return;
2930c1d019a6SEd Tanous     }
2931c71d6125SEd Tanous 
2932ef4c65b7SEd Tanous     asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
2933ef4c65b7SEd Tanous         "/redfish/v1/Chassis/{}/Sensors/{}", chassisId, sensorId);
2934c1d019a6SEd Tanous 
293562598e31SEd Tanous     BMCWEB_LOG_DEBUG("Sensor doGet enter");
2936e6bd846dSNan Zhou 
29372b73119cSGeorge Liu     constexpr std::array<std::string_view, 1> interfaces = {
2938e6bd846dSNan Zhou         "xyz.openbmc_project.Sensor.Value"};
2939c71d6125SEd Tanous     std::string sensorPath = "/xyz/openbmc_project/sensors/" + nameType.first +
2940c71d6125SEd Tanous                              '/' + nameType.second;
2941e6bd846dSNan Zhou     // Get a list of all of the sensors that implement Sensor.Value
2942e6bd846dSNan Zhou     // and get the path and service name associated with the sensor
29432b73119cSGeorge Liu     ::dbus::utility::getDbusObject(
29442b73119cSGeorge Liu         sensorPath, interfaces,
2945aec0ec30SMyung Bae         [asyncResp, sensorId,
29462b73119cSGeorge Liu          sensorPath](const boost::system::error_code& ec,
2947c1d019a6SEd Tanous                      const ::dbus::utility::MapperGetObject& subtree) {
294862598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 enter");
2949aec0ec30SMyung Bae         if (ec == boost::system::errc::io_error)
2950aec0ec30SMyung Bae         {
295162598e31SEd Tanous             BMCWEB_LOG_WARNING("Sensor not found from getSensorPaths");
2952aec0ec30SMyung Bae             messages::resourceNotFound(asyncResp->res, sensorId, "Sensor");
2953aec0ec30SMyung Bae             return;
2954aec0ec30SMyung Bae         }
2955e6bd846dSNan Zhou         if (ec)
2956e6bd846dSNan Zhou         {
2957c1d019a6SEd Tanous             messages::internalError(asyncResp->res);
295862598e31SEd Tanous             BMCWEB_LOG_ERROR(
295962598e31SEd Tanous                 "Sensor getSensorPaths resp_handler: Dbus error {}", ec);
2960e6bd846dSNan Zhou             return;
2961e6bd846dSNan Zhou         }
2962c1d019a6SEd Tanous         getSensorFromDbus(asyncResp, sensorPath, subtree);
296362598e31SEd Tanous         BMCWEB_LOG_DEBUG("respHandler1 exit");
29642b73119cSGeorge Liu     });
2965e6bd846dSNan Zhou }
2966e6bd846dSNan Zhou 
2967bacb2162SNan Zhou } // namespace sensors
2968bacb2162SNan Zhou 
29697e860f15SJohn Edward Broadbent inline void requestRoutesSensorCollection(App& app)
297095a3ecadSAnthony Wilson {
29717e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/")
2972ed398213SEd Tanous         .privileges(redfish::privileges::getSensorCollection)
2973002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2974de167a6fSNan Zhou             std::bind_front(sensors::handleSensorCollectionGet, std::ref(app)));
297595a3ecadSAnthony Wilson }
297695a3ecadSAnthony Wilson 
29777e860f15SJohn Edward Broadbent inline void requestRoutesSensor(App& app)
297895a3ecadSAnthony Wilson {
29797e860f15SJohn Edward Broadbent     BMCWEB_ROUTE(app, "/redfish/v1/Chassis/<str>/Sensors/<str>/")
2980ed398213SEd Tanous         .privileges(redfish::privileges::getSensor)
2981002d39b4SEd Tanous         .methods(boost::beast::http::verb::get)(
2982e6bd846dSNan Zhou             std::bind_front(sensors::handleSensorGet, std::ref(app)));
298395a3ecadSAnthony Wilson }
298495a3ecadSAnthony Wilson 
298508777fb0SLewanczyk, Dawid } // namespace redfish
2986