Debounce.hh 883 B

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