SensESP 2.7.2
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
time_counter.h
Go to the documentation of this file.
2#ifndef SENSESP_TRANSFORMS_TIME_COUNTER_H_
3#define SENSESP_TRANSFORMS_TIME_COUNTER_H_
4
5namespace sensesp {
6
7static const char kTimeCounterSchema[] = R"({
8 "type": "object",
9 "properties": {
10 "duration": {
11 "type": "number",
12 "title": "Total Duration",
13 "description": "Total accumulated duration while the input state is non-zero or true, in seconds"
14 }
15 },
16 "required": ["duration"]
17
18})";
19
30template <typename T>
31class TimeCounter : public Transform<T, float> {
32 public:
37
38 virtual void set_input(T input, uint8_t input_channel = 0) override {
39 if (previous_state_ == -1) {
40 // Initialize the previous state
41 previous_state_ = (bool)input;
44 }
45
46 // if previous_state_ is true, accumulate duration
47 if (previous_state_) {
49 }
50
51 if (input) {
52 if (previous_state_ == 0) {
53 // State change from false to true
57 }
58 } else {
59 if (previous_state_ == 1) {
60 // State change from true to false
63 this->save_configuration(); // Save configuration to flash, so that
64 // the duration is persistent
65 }
66 }
67 this->emit((float)duration_ / 1000.);
68 }
69
70 virtual void get_configuration(JsonObject& root) override {
71 root["duration"] = duration_;
72 }
73
74 virtual bool set_configuration(const JsonObject& config) override {
75 debugD("Setting TimeCounter configuration");
76 if (!config.containsKey("duration")) {
77 return false;
78 }
79 duration_at_start_ = config["duration"];
81 debugD("duration_at_start_ = %ld", duration_at_start_);
82 return true;
83 }
84
85 virtual String get_config_schema() override {
86 return kTimeCounterSchema;
87 }
88
89 protected:
90 int previous_state_ = -1; // -1 means uninitialized
91 unsigned long start_time_;
92 unsigned long duration_ = 0.;
93 unsigned long duration_at_start_ = 0.;
94};
95
96} // namespace sensesp
97
98#endif // SENSESP_TRANSFORMS_TIME_COUNTER_H_
virtual void save_configuration()
virtual void load_configuration()
Construct a new transform based on a single function.
A transform that outputs the duration of the input value being true or non-null.
virtual void get_configuration(JsonObject &root) override
unsigned long duration_
virtual String get_config_schema() override
unsigned long start_time_
virtual bool set_configuration(const JsonObject &config) override
unsigned long duration_at_start_
TimeCounter(String config_path)
virtual void set_input(T input, uint8_t input_channel=0) override
The main Transform class. A transform is identified primarily by the type of value that is produces (...
Definition transform.h:54
void emit(T new_value)
#define debugD(fmt,...)
Definition local_debug.h:47