Debian Codegraph @

src/core/components/sensors/sensor.h

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright 2019 Juan Palacios <[email protected]>
3
4 #pragma once
5
6 #include "core/components/sensors/isensor.h"
7 #include "core/idatasource.h"
8 #include <atomic>
9 #include <functional>
10 #include <memory>
11 #include <optional>
12 #include <string>
13 #include <string_view>
14 #include <units.h>
15 #include <utility>
16 #include <vector>
17
18 template<typename Unit, typename T>
19 class Sensor : public ISensor
20 {
21 public:
22 class Exporter : public ISensor::Exporter
23 {
24 public:
25 virtual void takeValue(Unit value) = 0;
26 virtual void takeRange(std::optional<std::pair<Unit, Unit>> const &range) = 0;
27 };
28
29 Sensor(
30 std::string_view id,
31 std::vector<std::unique_ptr<IDataSource<T>>> &&dataSources,
32 std::optional<std::pair<Unit, Unit>> &&range = std::nullopt,
33 std::function<T(std::vector<T> const &)> &&transform =
34 [](std::vector<T> const &input) { return input[0]; }) noexcept
35 : id_(id)
36 , dataSources_(std::move(dataSources))
37 , range_(std::move(range))
38 , transform_(std::move(transform))
39 , value_(units::make_unit<Unit>(0))
40 {
41 transformValues_.resize(dataSources_.size(), 0);
42 }
43
44 std::string const &ID() const override
45 {
46 return id_;
47 }
48
49 void exportWith(ISensor::Exporter &e) const override
50 {
51 auto exporter = e.provideExporter(*this);
52 if (exporter.has_value()) {
53 auto &sensorExporter =
54 dynamic_cast<Sensor<Unit, T>::Exporter &>(exporter->get());
55 sensorExporter.takeValue(value());
56 sensorExporter.takeRange(range_);
57 }
58 }
59
60 void update() override
61 {
62 if (!dataSources_.empty()) {
63 for (size_t i = 0; i < dataSources_.size(); ++i)
64 dataSources_[i]->read(transformValues_[i]);
65
66 value(transform_(transformValues_));
67 }
68 }
69
70 protected:
71 Unit value() const
72 {
73 return value_.load(std::memory_order_relaxed);
74 }
75
76 void value(T value)
77 {
78 value_.store(units::make_unit<Unit>(value), std::memory_order_relaxed);
79 }
80
81 private:
82 std::string const id_;
83 std::vector<std::unique_ptr<IDataSource<T>>> const dataSources_;
84 std::optional<std::pair<Unit, Unit>> const range_;
85 std::function<T(std::vector<T> const &)> const transform_;
86
87 std::vector<T> transformValues_;
88 std::atomic<Unit> value_;
89 };