SensESP 3.0.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
debounce.h
Go to the documentation of this file.
1#ifndef SENSESP_TRANSFORMS_DEBOUNCE_H_
2#define SENSESP_TRANSFORMS_DEBOUNCE_H_
3
5#include "transform.h"
6
7namespace sensesp {
8
31template <class T>
32class Debounce : public SymmetricTransform<T> {
33 public:
34 Debounce(int ms_min_delay = 15, String config_path = "")
35 : SymmetricTransform<T>(config_path), ms_min_delay_{ms_min_delay} {
36 this->load();
37 }
38
39 virtual void set(const T& input) override {
40 // Input has changed since the last emit, or this is the first
41 // input since the program started to run.
42
43 if (input != debounced_value_ || !value_received_) {
44 debounced_value_ = input;
45
46 if (event_) {
47 event_->remove(event_loop());
48 event_ = nullptr;
49 }
50 event_ = event_loop()->onDelay(ms_min_delay_, [this, input]() {
51 this->event_ = nullptr;
52 this->debounced_value_ = input;
53 this->emit(input);
54 });
55 value_received_ = true;
56 }
57 }
58
59 private:
60 int ms_min_delay_;
61 bool value_received_ = false;
62 T debounced_value_;
63 reactesp::DelayEvent* event_ = nullptr;
64 virtual bool to_json(JsonObject& doc) override {
65 doc["min_delay"] = ms_min_delay_;
66 return true;
67 }
68
69 virtual bool from_json(const JsonObject& config) override {
70 const String expected[] = {"min_delay"};
71 for (auto str : expected) {
72 if (!config[str].is<JsonVariant>()) {
73 return false;
74 }
75 }
76 ms_min_delay_ = config["min_delay"];
77 return true;
78 }
79};
80
81const String ConfigSchema(const Debounce<bool>& obj);
82
86
87} // namespace sensesp
88
89#endif
Implements debounce code for a button or switch.
Definition debounce.h:32
Debounce(int ms_min_delay=15, String config_path="")
Definition debounce.h:34
virtual void set(const T &input) override
Definition debounce.h:39
virtual bool load() override
Load and populate the object from a persistent storage.
Definition saveable.cpp:8
A common type of transform that consumes, transforms, then outputs values of the same data type.
Definition transform.h:94
void emit(const T &new_value)
const String ConfigSchema(const SmartSwitchController &obj)
std::shared_ptr< reactesp::EventLoop > event_loop()
Definition sensesp.cpp:9
Debounce< float > DebounceFloat
Definition debounce.h:85
Debounce< bool > DebounceBool
Definition debounce.h:83
Debounce< int > DebounceInt
Definition debounce.h:84