1 #include "metric.hpp" 2 3 #include "interfaces/types.hpp" 4 #include "utils/transform.hpp" 5 6 #include <algorithm> 7 8 Metric::Metric(std::vector<std::shared_ptr<interfaces::Sensor>> sensors, 9 std::string operationType, std::string id, 10 std::string metadata) : 11 sensors(std::move(sensors)), 12 operationType(std::move(operationType)), id(std::move(id)), 13 metadata(std::move(metadata)) 14 {} 15 16 void Metric::initialize() 17 { 18 readings = std::vector<MetricValue>(sensors.size(), 19 MetricValue{id, metadata, 0., 0u}); 20 21 for (auto& sensor : sensors) 22 { 23 sensor->registerForUpdates(weak_from_this()); 24 } 25 } 26 27 const std::vector<MetricValue>& Metric::getReadings() const 28 { 29 return readings; 30 } 31 32 void Metric::sensorUpdated(interfaces::Sensor& sensor, uint64_t timestamp) 33 { 34 MetricValue& mv = findMetric(sensor); 35 mv.timestamp = timestamp; 36 } 37 38 void Metric::sensorUpdated(interfaces::Sensor& sensor, uint64_t timestamp, 39 double value) 40 { 41 MetricValue& mv = findMetric(sensor); 42 mv.timestamp = timestamp; 43 mv.value = value; 44 } 45 46 MetricValue& Metric::findMetric(interfaces::Sensor& sensor) 47 { 48 auto it = 49 std::find_if(sensors.begin(), sensors.end(), 50 [&sensor](const auto& s) { return s.get() == &sensor; }); 51 auto index = std::distance(sensors.begin(), it); 52 return readings.at(index); 53 } 54 55 nlohmann::json Metric::to_json() const 56 { 57 auto sensorPaths = utils::transform( 58 sensors, [](const auto& sensor) -> sdbusplus::message::object_path { 59 return sdbusplus::message::object_path(sensor->id().service + ":" + 60 sensor->id().path); 61 }); 62 return LabeledReadingParameter::to_json(ReadingParameters::value_type( 63 std::move(sensorPaths), operationType, id, metadata)); 64 } 65