Loading [MathJax]/extensions/tex2jax.js
SensESP 3.1.0
Universal Signal K sensor toolkit ESP32
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
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 virtual bool to_json(JsonObject& doc) override {
60 doc["min_delay"] = ms_min_delay_;
61 return true;
62 }
63
64 virtual bool from_json(const JsonObject& config) override {
65 const String expected[] = {"min_delay"};
66 for (auto str : expected) {
67 if (!config[str].is<JsonVariant>()) {
68 return false;
69 }
70 }
71 ms_min_delay_ = config["min_delay"];
72 return true;
73 }
74
75 protected:
77 bool value_received_ = false;
79 reactesp::DelayEvent* event_ = nullptr;
80};
81
82template <typename T>
83const String ConfigSchema(const Debounce<T>& obj) {
84 return R"###({"type":"object","properties":{"min_delay":{"title":"Minimum delay","type":"number","description":"The minimum time in ms between inputs for output to happen"}}})###";
85}
86
90
91} // namespace sensesp
92
93#endif
Implements debounce code for a button or switch.
Definition debounce.h:32
reactesp::DelayEvent * event_
Definition debounce.h:79
Debounce(int ms_min_delay=15, String config_path="")
Definition debounce.h:34
virtual bool to_json(JsonObject &doc) override
Definition debounce.h:59
virtual bool from_json(const JsonObject &config) override
Definition debounce.h:64
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:89
Debounce< bool > DebounceBool
Definition debounce.h:87
Debounce< int > DebounceInt
Definition debounce.h:88