| 1 |
#ifndef DEBOUNCE_H |
| 2 |
#define DEBOUNCE_H |
| 3 |
|
| 4 |
#include <thread> |
| 5 |
#include <unordered_map> |
| 6 |
#include <functional> |
| 7 |
#include "Signal.hh" |
| 8 |
|
| 9 |
#define MIN_WAIT_TIME 50 |
| 10 |
#define MAX_WAIT_TIME 500 |
| 11 |
|
| 12 |
#ifdef __wasm32__ |
| 13 |
extern "C" { |
| 14 |
int set_timeout(int ms, void *ctx); |
| 15 |
void clear_timeout(int timeout); |
| 16 |
void on_timeout(void *ctx); |
| 17 |
}; |
| 18 |
#endif |
| 19 |
|
| 20 |
class Debounce { |
| 21 |
public: |
| 22 |
static std::shared_ptr<Debounce> getShared(); |
| 23 |
|
| 24 |
Debounce(); |
| 25 |
~Debounce(); |
| 26 |
|
| 27 |
void add(void *key, std::function<void()> cb); |
| 28 |
void remove(void *key); |
| 29 |
void trigger(); |
| 30 |
void notify(); |
| 31 |
|
| 32 |
private: |
| 33 |
bool mRunning; |
| 34 |
std::mutex mMutex; |
| 35 |
#ifdef __wasm32__ |
| 36 |
int mTimeout; |
| 37 |
#else |
| 38 |
Signal mWaitSignal; |
| 39 |
std::thread mThread; |
| 40 |
#endif |
| 41 |
std::unordered_map<void *, std::function<void()>> mCallbacks; |
| 42 |
std::chrono::time_point<std::chrono::steady_clock> mLastTime; |
| 43 |
|
| 44 |
void loop(); |
| 45 |
void notifyIfReady(); |
| 46 |
void wait(); |
| 47 |
}; |
| 48 |
|
| 49 |
#endif |