-
Notifications
You must be signed in to change notification settings - Fork 128
/
sensors.hpp
2954 lines (2741 loc) · 111 KB
/
sensors.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#pragma once
#include "app.hpp"
#include "dbus_singleton.hpp"
#include "dbus_utility.hpp"
#include "generated/enums/sensor.hpp"
#include "query.hpp"
#include "registries/privilege_registry.hpp"
#include "str_utility.hpp"
#include "utils/dbus_utils.hpp"
#include "utils/json_utils.hpp"
#include "utils/query_param.hpp"
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/algorithm/replace_copy_if.hpp>
#include <boost/system/error_code.hpp>
#include <boost/url/format.hpp>
#include <sdbusplus/asio/property.hpp>
#include <sdbusplus/unpack_properties.hpp>
#include <array>
#include <cmath>
#include <iterator>
#include <limits>
#include <map>
#include <ranges>
#include <set>
#include <string_view>
#include <utility>
#include <variant>
namespace redfish
{
namespace sensors
{
namespace node
{
static constexpr std::string_view power = "Power";
static constexpr std::string_view sensors = "Sensors";
static constexpr std::string_view thermal = "Thermal";
} // namespace node
// clang-format off
namespace dbus
{
constexpr auto powerPaths = std::to_array<std::string_view>({
"/xyz/openbmc_project/sensors/voltage",
"/xyz/openbmc_project/sensors/power"
});
constexpr auto sensorPaths = std::to_array<std::string_view>({
"/xyz/openbmc_project/sensors/power",
"/xyz/openbmc_project/sensors/current",
"/xyz/openbmc_project/sensors/airflow",
"/xyz/openbmc_project/sensors/humidity",
#ifdef BMCWEB_NEW_POWERSUBSYSTEM_THERMALSUBSYSTEM
"/xyz/openbmc_project/sensors/voltage",
"/xyz/openbmc_project/sensors/fan_tach",
"/xyz/openbmc_project/sensors/temperature",
"/xyz/openbmc_project/sensors/fan_pwm",
"/xyz/openbmc_project/sensors/altitude",
"/xyz/openbmc_project/sensors/energy",
#endif
"/xyz/openbmc_project/sensors/utilization"
});
constexpr auto thermalPaths = std::to_array<std::string_view>({
"/xyz/openbmc_project/sensors/fan_tach",
"/xyz/openbmc_project/sensors/temperature",
"/xyz/openbmc_project/sensors/fan_pwm"
});
} // namespace dbus
// clang-format on
using sensorPair =
std::pair<std::string_view, std::span<const std::string_view>>;
static constexpr std::array<sensorPair, 3> paths = {
{{node::power, dbus::powerPaths},
{node::sensors, dbus::sensorPaths},
{node::thermal, dbus::thermalPaths}}};
inline sensor::ReadingType toReadingType(std::string_view sensorType)
{
if (sensorType == "voltage")
{
return sensor::ReadingType::Voltage;
}
if (sensorType == "power")
{
return sensor::ReadingType::Power;
}
if (sensorType == "current")
{
return sensor::ReadingType::Current;
}
if (sensorType == "fan_tach")
{
return sensor::ReadingType::Rotational;
}
if (sensorType == "temperature")
{
return sensor::ReadingType::Temperature;
}
if (sensorType == "fan_pwm" || sensorType == "utilization")
{
return sensor::ReadingType::Percent;
}
if (sensorType == "humidity")
{
return sensor::ReadingType::Humidity;
}
if (sensorType == "altitude")
{
return sensor::ReadingType::Altitude;
}
if (sensorType == "airflow")
{
return sensor::ReadingType::AirFlow;
}
if (sensorType == "energy")
{
return sensor::ReadingType::EnergyJoules;
}
return sensor::ReadingType::Invalid;
}
inline std::string_view toReadingUnits(std::string_view sensorType)
{
if (sensorType == "voltage")
{
return "V";
}
if (sensorType == "power")
{
return "W";
}
if (sensorType == "current")
{
return "A";
}
if (sensorType == "fan_tach")
{
return "RPM";
}
if (sensorType == "temperature")
{
return "Cel";
}
if (sensorType == "fan_pwm" || sensorType == "utilization" ||
sensorType == "humidity")
{
return "%";
}
if (sensorType == "altitude")
{
return "m";
}
if (sensorType == "airflow")
{
return "cft_i/min";
}
if (sensorType == "energy")
{
return "J";
}
return "";
}
} // namespace sensors
/**
* SensorsAsyncResp
* Gathers data needed for response processing after async calls are done
*/
class SensorsAsyncResp
{
public:
using DataCompleteCb = std::function<void(
const boost::beast::http::status status,
const std::map<std::string, std::string>& uriToDbus)>;
struct SensorData
{
const std::string name;
std::string uri;
const std::string dbusPath;
};
SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
const std::string& chassisIdIn,
std::span<const std::string_view> typesIn,
std::string_view subNode) :
asyncResp(asyncRespIn),
chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
efficientExpand(false)
{}
// Store extra data about sensor mapping and return it in callback
SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
const std::string& chassisIdIn,
std::span<const std::string_view> typesIn,
std::string_view subNode,
DataCompleteCb&& creationComplete) :
asyncResp(asyncRespIn),
chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
efficientExpand(false), metadata{std::vector<SensorData>()},
dataComplete{std::move(creationComplete)}
{}
// sensor collections expand
SensorsAsyncResp(const std::shared_ptr<bmcweb::AsyncResp>& asyncRespIn,
const std::string& chassisIdIn,
std::span<const std::string_view> typesIn,
const std::string_view& subNode, bool efficientExpandIn) :
asyncResp(asyncRespIn),
chassisId(chassisIdIn), types(typesIn), chassisSubNode(subNode),
efficientExpand(efficientExpandIn)
{}
~SensorsAsyncResp()
{
if (asyncResp->res.result() ==
boost::beast::http::status::internal_server_error)
{
// Reset the json object to clear out any data that made it in
// before the error happened todo(ed) handle error condition with
// proper code
asyncResp->res.jsonValue = nlohmann::json::object();
}
if (dataComplete && metadata)
{
std::map<std::string, std::string> map;
if (asyncResp->res.result() == boost::beast::http::status::ok)
{
for (auto& sensor : *metadata)
{
map.emplace(sensor.uri, sensor.dbusPath);
}
}
dataComplete(asyncResp->res.result(), map);
}
}
SensorsAsyncResp(const SensorsAsyncResp&) = delete;
SensorsAsyncResp(SensorsAsyncResp&&) = delete;
SensorsAsyncResp& operator=(const SensorsAsyncResp&) = delete;
SensorsAsyncResp& operator=(SensorsAsyncResp&&) = delete;
void addMetadata(const nlohmann::json& sensorObject,
const std::string& dbusPath)
{
if (metadata)
{
metadata->emplace_back(SensorData{
sensorObject["Name"], sensorObject["@odata.id"], dbusPath});
}
}
void updateUri(const std::string& name, const std::string& uri)
{
if (metadata)
{
for (auto& sensor : *metadata)
{
if (sensor.name == name)
{
sensor.uri = uri;
}
}
}
}
const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
const std::string chassisId;
const std::span<const std::string_view> types;
const std::string chassisSubNode;
const bool efficientExpand;
private:
std::optional<std::vector<SensorData>> metadata;
DataCompleteCb dataComplete;
};
/**
* Possible states for physical inventory leds
*/
enum class LedState
{
OFF,
ON,
BLINK,
UNKNOWN
};
/**
* D-Bus inventory item associated with one or more sensors.
*/
class InventoryItem
{
public:
explicit InventoryItem(const std::string& objPath) : objectPath(objPath)
{
// Set inventory item name to last node of object path
sdbusplus::message::object_path path(objectPath);
name = path.filename();
if (name.empty())
{
BMCWEB_LOG_ERROR("Failed to find '/' in {}", objectPath);
}
}
std::string objectPath;
std::string name;
bool isPresent = true;
bool isFunctional = true;
bool isPowerSupply = false;
int powerSupplyEfficiencyPercent = -1;
std::string manufacturer;
std::string model;
std::string partNumber;
std::string serialNumber;
std::set<std::string> sensors;
std::string ledObjectPath;
LedState ledState = LedState::UNKNOWN;
};
/**
* @brief Get objects with connection necessary for sensors
* @param SensorsAsyncResp Pointer to object holding response data
* @param sensorNames Sensors retrieved from chassis
* @param callback Callback for processing gathered connections
*/
template <typename Callback>
void getObjectsWithConnection(
const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp,
const std::shared_ptr<std::set<std::string>>& sensorNames,
Callback&& callback)
{
BMCWEB_LOG_DEBUG("getObjectsWithConnection enter");
const std::string path = "/xyz/openbmc_project/sensors";
constexpr std::array<std::string_view, 1> interfaces = {
"xyz.openbmc_project.Sensor.Value"};
// Make call to ObjectMapper to find all sensors objects
dbus::utility::getSubTree(
path, 2, interfaces,
[callback{std::forward<Callback>(callback)}, sensorsAsyncResp,
sensorNames](const boost::system::error_code& ec,
const dbus::utility::MapperGetSubTreeResponse& subtree) {
// Response handler for parsing objects subtree
BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler enter");
if (ec)
{
messages::internalError(sensorsAsyncResp->asyncResp->res);
BMCWEB_LOG_ERROR(
"getObjectsWithConnection resp_handler: Dbus error {}", ec);
return;
}
BMCWEB_LOG_DEBUG("Found {} subtrees", subtree.size());
// Make unique list of connections only for requested sensor types and
// found in the chassis
std::set<std::string> connections;
std::set<std::pair<std::string, std::string>> objectsWithConnection;
BMCWEB_LOG_DEBUG("sensorNames list count: {}", sensorNames->size());
for (const std::string& tsensor : *sensorNames)
{
BMCWEB_LOG_DEBUG("Sensor to find: {}", tsensor);
}
for (const std::pair<
std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>&
object : subtree)
{
if (sensorNames->find(object.first) != sensorNames->end())
{
for (const std::pair<std::string, std::vector<std::string>>&
objData : object.second)
{
BMCWEB_LOG_DEBUG("Adding connection: {}", objData.first);
connections.insert(objData.first);
objectsWithConnection.insert(
std::make_pair(object.first, objData.first));
}
}
}
BMCWEB_LOG_DEBUG("Found {} connections", connections.size());
callback(std::move(connections), std::move(objectsWithConnection));
BMCWEB_LOG_DEBUG("getObjectsWithConnection resp_handler exit");
});
BMCWEB_LOG_DEBUG("getObjectsWithConnection exit");
}
/**
* @brief Create connections necessary for sensors
* @param SensorsAsyncResp Pointer to object holding response data
* @param sensorNames Sensors retrieved from chassis
* @param callback Callback for processing gathered connections
*/
template <typename Callback>
void getConnections(std::shared_ptr<SensorsAsyncResp> sensorsAsyncResp,
const std::shared_ptr<std::set<std::string>> sensorNames,
Callback&& callback)
{
auto objectsWithConnectionCb =
[callback](const std::set<std::string>& connections,
const std::set<std::pair<std::string, std::string>>&
/*objectsWithConnection*/) { callback(connections); };
getObjectsWithConnection(sensorsAsyncResp, sensorNames,
std::move(objectsWithConnectionCb));
}
/**
* @brief Shrinks the list of sensors for processing
* @param SensorsAysncResp The class holding the Redfish response
* @param allSensors A list of all the sensors associated to the
* chassis element (i.e. baseboard, front panel, etc...)
* @param activeSensors A list that is a reduction of the incoming
* allSensors list. Eliminate Thermal sensors when a Power request is
* made, and eliminate Power sensors when a Thermal request is made.
*/
inline void reduceSensorList(
crow::Response& res, std::string_view chassisSubNode,
std::span<const std::string_view> sensorTypes,
const std::vector<std::string>* allSensors,
const std::shared_ptr<std::set<std::string>>& activeSensors)
{
if ((allSensors == nullptr) || (activeSensors == nullptr))
{
messages::resourceNotFound(res, chassisSubNode,
chassisSubNode == sensors::node::thermal
? "Temperatures"
: "Voltages");
return;
}
if (allSensors->empty())
{
// Nothing to do, the activeSensors object is also empty
return;
}
for (std::string_view type : sensorTypes)
{
for (const std::string& sensor : *allSensors)
{
if (sensor.starts_with(type))
{
activeSensors->emplace(sensor);
}
}
}
}
/*
*Populates the top level collection for a given subnode. Populates
*SensorCollection, Power, or Thermal schemas.
*
* */
inline void populateChassisNode(nlohmann::json& jsonValue,
std::string_view chassisSubNode)
{
if (chassisSubNode == sensors::node::power)
{
jsonValue["@odata.type"] = "#Power.v1_5_2.Power";
}
else if (chassisSubNode == sensors::node::thermal)
{
jsonValue["@odata.type"] = "#Thermal.v1_4_0.Thermal";
jsonValue["Fans"] = nlohmann::json::array();
jsonValue["Temperatures"] = nlohmann::json::array();
}
else if (chassisSubNode == sensors::node::sensors)
{
jsonValue["@odata.type"] = "#SensorCollection.SensorCollection";
jsonValue["Description"] = "Collection of Sensors for this Chassis";
jsonValue["Members"] = nlohmann::json::array();
jsonValue["Members@odata.count"] = 0;
}
if (chassisSubNode != sensors::node::sensors)
{
jsonValue["Id"] = chassisSubNode;
}
jsonValue["Name"] = chassisSubNode;
}
/**
* @brief Retrieves requested chassis sensors and redundancy data from DBus .
* @param SensorsAsyncResp Pointer to object holding response data
* @param callback Callback for next step in gathered sensor processing
*/
template <typename Callback>
void getChassis(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
std::string_view chassisId, std::string_view chassisSubNode,
std::span<const std::string_view> sensorTypes,
Callback&& callback)
{
BMCWEB_LOG_DEBUG("getChassis enter");
constexpr std::array<std::string_view, 2> interfaces = {
"xyz.openbmc_project.Inventory.Item.Board",
"xyz.openbmc_project.Inventory.Item.Chassis"};
// Get the Chassis Collection
dbus::utility::getSubTreePaths(
"/xyz/openbmc_project/inventory", 0, interfaces,
[callback{std::forward<Callback>(callback)}, asyncResp,
chassisIdStr{std::string(chassisId)},
chassisSubNode{std::string(chassisSubNode)}, sensorTypes](
const boost::system::error_code& ec,
const dbus::utility::MapperGetSubTreePathsResponse& chassisPaths) {
BMCWEB_LOG_DEBUG("getChassis respHandler enter");
if (ec)
{
BMCWEB_LOG_ERROR("getChassis respHandler DBUS error: {}", ec);
messages::internalError(asyncResp->res);
return;
}
const std::string* chassisPath = nullptr;
for (const std::string& chassis : chassisPaths)
{
sdbusplus::message::object_path path(chassis);
std::string chassisName = path.filename();
if (chassisName.empty())
{
BMCWEB_LOG_ERROR("Failed to find '/' in {}", chassis);
continue;
}
if (chassisName == chassisIdStr)
{
chassisPath = &chassis;
break;
}
}
if (chassisPath == nullptr)
{
messages::resourceNotFound(asyncResp->res, "Chassis", chassisIdStr);
return;
}
populateChassisNode(asyncResp->res.jsonValue, chassisSubNode);
asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
"/redfish/v1/Chassis/{}/{}", chassisIdStr, chassisSubNode);
// Get the list of all sensors for this Chassis element
std::string sensorPath = *chassisPath + "/all_sensors";
dbus::utility::getAssociationEndPoints(
sensorPath,
[asyncResp, chassisSubNode, sensorTypes,
callback{std::forward<const Callback>(callback)}](
const boost::system::error_code& ec2,
const dbus::utility::MapperEndPoints& nodeSensorList) {
if (ec2)
{
if (ec2.value() != EBADR)
{
messages::internalError(asyncResp->res);
return;
}
}
const std::shared_ptr<std::set<std::string>> culledSensorList =
std::make_shared<std::set<std::string>>();
reduceSensorList(asyncResp->res, chassisSubNode, sensorTypes,
&nodeSensorList, culledSensorList);
BMCWEB_LOG_DEBUG("Finishing with {}", culledSensorList->size());
callback(culledSensorList);
});
});
BMCWEB_LOG_DEBUG("getChassis exit");
}
/**
* @brief Returns the Redfish State value for the specified inventory item.
* @param inventoryItem D-Bus inventory item associated with a sensor.
* @return State value for inventory item.
*/
inline std::string getState(const InventoryItem* inventoryItem)
{
if ((inventoryItem != nullptr) && !(inventoryItem->isPresent))
{
return "Absent";
}
return "Enabled";
}
/**
* @brief Returns the Redfish Health value for the specified sensor.
* @param sensorJson Sensor JSON object.
* @param valuesDict Map of all sensor DBus values.
* @param inventoryItem D-Bus inventory item associated with the sensor. Will
* be nullptr if no associated inventory item was found.
* @return Health value for sensor.
*/
inline std::string getHealth(nlohmann::json& sensorJson,
const dbus::utility::DBusPropertiesMap& valuesDict,
const InventoryItem* inventoryItem)
{
// Get current health value (if any) in the sensor JSON object. Some JSON
// objects contain multiple sensors (such as PowerSupplies). We want to set
// the overall health to be the most severe of any of the sensors.
std::string currentHealth;
auto statusIt = sensorJson.find("Status");
if (statusIt != sensorJson.end())
{
auto healthIt = statusIt->find("Health");
if (healthIt != statusIt->end())
{
std::string* health = healthIt->get_ptr<std::string*>();
if (health != nullptr)
{
currentHealth = *health;
}
}
}
// If current health in JSON object is already Critical, return that. This
// should override the sensor health, which might be less severe.
if (currentHealth == "Critical")
{
return "Critical";
}
const bool* criticalAlarmHigh = nullptr;
const bool* criticalAlarmLow = nullptr;
const bool* warningAlarmHigh = nullptr;
const bool* warningAlarmLow = nullptr;
const bool success = sdbusplus::unpackPropertiesNoThrow(
dbus_utils::UnpackErrorPrinter(), valuesDict, "CriticalAlarmHigh",
criticalAlarmHigh, "CriticalAlarmLow", criticalAlarmLow,
"WarningAlarmHigh", warningAlarmHigh, "WarningAlarmLow",
warningAlarmLow);
if (success)
{
// Check if sensor has critical threshold alarm
if ((criticalAlarmHigh != nullptr && *criticalAlarmHigh) ||
(criticalAlarmLow != nullptr && *criticalAlarmLow))
{
return "Critical";
}
}
// Check if associated inventory item is not functional
if ((inventoryItem != nullptr) && !(inventoryItem->isFunctional))
{
return "Critical";
}
// If current health in JSON object is already Warning, return that. This
// should override the sensor status, which might be less severe.
if (currentHealth == "Warning")
{
return "Warning";
}
if (success)
{
// Check if sensor has warning threshold alarm
if ((warningAlarmHigh != nullptr && *warningAlarmHigh) ||
(warningAlarmLow != nullptr && *warningAlarmLow))
{
return "Warning";
}
}
return "OK";
}
inline void setLedState(nlohmann::json& sensorJson,
const InventoryItem* inventoryItem)
{
if (inventoryItem != nullptr && !inventoryItem->ledObjectPath.empty())
{
switch (inventoryItem->ledState)
{
case LedState::OFF:
sensorJson["IndicatorLED"] = "Off";
break;
case LedState::ON:
sensorJson["IndicatorLED"] = "Lit";
break;
case LedState::BLINK:
sensorJson["IndicatorLED"] = "Blinking";
break;
case LedState::UNKNOWN:
break;
}
}
}
/**
* @brief Builds a json sensor representation of a sensor.
* @param sensorName The name of the sensor to be built
* @param sensorType The type (temperature, fan_tach, etc) of the sensor to
* build
* @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
* @param propertiesDict A dictionary of the properties to build the sensor
* from.
* @param sensorJson The json object to fill
* @param inventoryItem D-Bus inventory item associated with the sensor. Will
* be nullptr if no associated inventory item was found.
*/
inline void objectPropertiesToJson(
std::string_view sensorName, std::string_view sensorType,
std::string_view chassisSubNode,
const dbus::utility::DBusPropertiesMap& propertiesDict,
nlohmann::json& sensorJson, InventoryItem* inventoryItem)
{
if (chassisSubNode == sensors::node::sensors)
{
std::string subNodeEscaped(sensorType);
auto remove = std::ranges::remove(subNodeEscaped, '_');
subNodeEscaped.erase(std::ranges::begin(remove), subNodeEscaped.end());
// For sensors in SensorCollection we set Id instead of MemberId,
// including power sensors.
subNodeEscaped += '_';
subNodeEscaped += sensorName;
sensorJson["Id"] = std::move(subNodeEscaped);
std::string sensorNameEs(sensorName);
std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
sensorJson["Name"] = std::move(sensorNameEs);
}
else if (sensorType != "power")
{
// Set MemberId and Name for non-power sensors. For PowerSupplies and
// PowerControl, those properties have more general values because
// multiple sensors can be stored in the same JSON object.
std::string sensorNameEs(sensorName);
std::replace(sensorNameEs.begin(), sensorNameEs.end(), '_', ' ');
sensorJson["Name"] = std::move(sensorNameEs);
}
sensorJson["Status"]["State"] = getState(inventoryItem);
sensorJson["Status"]["Health"] = getHealth(sensorJson, propertiesDict,
inventoryItem);
// Parameter to set to override the type we get from dbus, and force it to
// int, regardless of what is available. This is used for schemas like fan,
// that require integers, not floats.
bool forceToInt = false;
nlohmann::json::json_pointer unit("/Reading");
if (chassisSubNode == sensors::node::sensors)
{
sensorJson["@odata.type"] = "#Sensor.v1_2_0.Sensor";
sensor::ReadingType readingType = sensors::toReadingType(sensorType);
if (readingType == sensor::ReadingType::Invalid)
{
BMCWEB_LOG_ERROR("Redfish cannot map reading type for {}",
sensorType);
}
else
{
sensorJson["ReadingType"] = readingType;
}
std::string_view readingUnits = sensors::toReadingUnits(sensorType);
if (readingUnits.empty())
{
BMCWEB_LOG_ERROR("Redfish cannot map reading unit for {}",
sensorType);
}
else
{
sensorJson["ReadingUnits"] = readingUnits;
}
}
else if (sensorType == "temperature")
{
unit = "/ReadingCelsius"_json_pointer;
sensorJson["@odata.type"] = "#Thermal.v1_3_0.Temperature";
// TODO(ed) Documentation says that path should be type fan_tach,
// implementation seems to implement fan
}
else if (sensorType == "fan" || sensorType == "fan_tach")
{
unit = "/Reading"_json_pointer;
sensorJson["ReadingUnits"] = "RPM";
sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
setLedState(sensorJson, inventoryItem);
forceToInt = true;
}
else if (sensorType == "fan_pwm")
{
unit = "/Reading"_json_pointer;
sensorJson["ReadingUnits"] = "Percent";
sensorJson["@odata.type"] = "#Thermal.v1_3_0.Fan";
setLedState(sensorJson, inventoryItem);
forceToInt = true;
}
else if (sensorType == "voltage")
{
unit = "/ReadingVolts"_json_pointer;
sensorJson["@odata.type"] = "#Power.v1_0_0.Voltage";
}
else if (sensorType == "power")
{
if (boost::iequals(sensorName, "total_power"))
{
sensorJson["@odata.type"] = "#Power.v1_0_0.PowerControl";
// Put multiple "sensors" into a single PowerControl, so have
// generic names for MemberId and Name. Follows Redfish mockup.
sensorJson["MemberId"] = "0";
sensorJson["Name"] = "Chassis Power Control";
unit = "/PowerConsumedWatts"_json_pointer;
}
else if (!(boost::ifind_first(sensorName, "input").empty()))
{
unit = "/PowerInputWatts"_json_pointer;
}
else
{
unit = "/PowerOutputWatts"_json_pointer;
}
}
else
{
BMCWEB_LOG_ERROR("Redfish cannot map object type for {}", sensorName);
return;
}
// Map of dbus interface name, dbus property name and redfish property_name
std::vector<
std::tuple<const char*, const char*, nlohmann::json::json_pointer>>
properties;
properties.reserve(7);
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "Value", unit);
if (chassisSubNode == sensors::node::sensors)
{
properties.emplace_back(
"xyz.openbmc_project.Sensor.Threshold.Warning", "WarningHigh",
"/Thresholds/UpperCaution/Reading"_json_pointer);
properties.emplace_back(
"xyz.openbmc_project.Sensor.Threshold.Warning", "WarningLow",
"/Thresholds/LowerCaution/Reading"_json_pointer);
properties.emplace_back(
"xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalHigh",
"/Thresholds/UpperCritical/Reading"_json_pointer);
properties.emplace_back(
"xyz.openbmc_project.Sensor.Threshold.Critical", "CriticalLow",
"/Thresholds/LowerCritical/Reading"_json_pointer);
}
else if (sensorType != "power")
{
properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
"WarningHigh",
"/UpperThresholdNonCritical"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Warning",
"WarningLow",
"/LowerThresholdNonCritical"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
"CriticalHigh",
"/UpperThresholdCritical"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Threshold.Critical",
"CriticalLow",
"/LowerThresholdCritical"_json_pointer);
}
// TODO Need to get UpperThresholdFatal and LowerThresholdFatal
if (chassisSubNode == sensors::node::sensors)
{
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
"/ReadingRangeMin"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
"/ReadingRangeMax"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Accuracy",
"Accuracy", "/Accuracy"_json_pointer);
}
else if (sensorType == "temperature")
{
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
"/MinReadingRangeTemp"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
"/MaxReadingRangeTemp"_json_pointer);
}
else if (sensorType != "power")
{
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MinValue",
"/MinReadingRange"_json_pointer);
properties.emplace_back("xyz.openbmc_project.Sensor.Value", "MaxValue",
"/MaxReadingRange"_json_pointer);
}
for (const std::tuple<const char*, const char*,
nlohmann::json::json_pointer>& p : properties)
{
for (const auto& [valueName, valueVariant] : propertiesDict)
{
if (valueName != std::get<1>(p))
{
continue;
}
// The property we want to set may be nested json, so use
// a json_pointer for easy indexing into the json structure.
const nlohmann::json::json_pointer& key = std::get<2>(p);
const double* doubleValue = std::get_if<double>(&valueVariant);
if (doubleValue == nullptr)
{
BMCWEB_LOG_ERROR("Got value interface that wasn't double");
continue;
}
if (!std::isfinite(*doubleValue))
{
if (valueName == "Value")
{
// Readings are allowed to be NAN for unavailable; coerce
// them to null in the json response.
sensorJson[key] = nullptr;
continue;
}
BMCWEB_LOG_WARNING("Sensor value for {} was unexpectedly {}",
valueName, *doubleValue);
continue;
}
if (forceToInt)
{
sensorJson[key] = static_cast<int64_t>(*doubleValue);
}
else
{
sensorJson[key] = *doubleValue;
}
}
}
}
/**
* @brief Builds a json sensor representation of a sensor.
* @param sensorName The name of the sensor to be built
* @param sensorType The type (temperature, fan_tach, etc) of the sensor to
* build
* @param chassisSubNode The subnode (thermal, sensor, ect) of the sensor
* @param interfacesDict A dictionary of the interfaces and properties of said
* interfaces to be built from
* @param sensorJson The json object to fill
* @param inventoryItem D-Bus inventory item associated with the sensor. Will
* be nullptr if no associated inventory item was found.
*/
inline void objectInterfacesToJson(
const std::string& sensorName, const std::string& sensorType,
const std::string& chassisSubNode,
const dbus::utility::DBusInterfacesMap& interfacesDict,
nlohmann::json& sensorJson, InventoryItem* inventoryItem)
{
for (const auto& [interface, valuesDict] : interfacesDict)
{
objectPropertiesToJson(sensorName, sensorType, chassisSubNode,
valuesDict, sensorJson, inventoryItem);
}
BMCWEB_LOG_DEBUG("Added sensor {}", sensorName);
}
inline void populateFanRedundancy(
const std::shared_ptr<SensorsAsyncResp>& sensorsAsyncResp)
{
constexpr std::array<std::string_view, 1> interfaces = {
"xyz.openbmc_project.Control.FanRedundancy"};
dbus::utility::getSubTree(
"/xyz/openbmc_project/control", 2, interfaces,
[sensorsAsyncResp](
const boost::system::error_code& ec,
const dbus::utility::MapperGetSubTreeResponse& resp) {
if (ec)
{
return; // don't have to have this interface
}
for (const std::pair<std::string, dbus::utility::MapperServiceMap>&
pathPair : resp)