blob: 8d9f19bc8da9220e6579555b972e8b0724efa15d [file] [log] [blame]
Krzysztof Grobelnyc8e3a642020-10-23 12:29:16 +02001#include "metric.hpp"
Krzysztof Grobelny6ccfcbf2020-11-04 09:31:36 +01002
3#include "interfaces/types.hpp"
4#include "utils/transform.hpp"
5
6#include <algorithm>
7
8Metric::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
16void 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
27const std::vector<MetricValue>& Metric::getReadings() const
28{
29 return readings;
30}
31
32void Metric::sensorUpdated(interfaces::Sensor& sensor, uint64_t timestamp)
33{
34 MetricValue& mv = findMetric(sensor);
35 mv.timestamp = timestamp;
36}
37
38void 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
46MetricValue& 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
55nlohmann::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}