You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.3KB

  1. #pragma once
  2. #include <functional>
  3. #include <vector>
  4. namespace rack_plugin_DHE_Modules {
  5. class Latch {
  6. public:
  7. bool is_high() const { return state==State::HIGH; }
  8. /**
  9. * Suspends firing events.
  10. */
  11. void disable() {
  12. enabled = false;
  13. }
  14. /**
  15. * Resumes firing events.
  16. */
  17. void enable() {
  18. enabled = true;
  19. }
  20. /**
  21. * Registers an action to be called on each rising edge.
  22. * @param action called on each rising edge
  23. */
  24. void on_rise(std::function<void()> action) {
  25. rise_actions.push_back(std::move(action));
  26. }
  27. /**
  28. * Registers an action to be called on each falling edge.
  29. * @param action called on each falling edge
  30. */
  31. void on_fall(std::function<void()> action) {
  32. fall_actions.push_back(std::move(action));
  33. }
  34. protected:
  35. enum class State {
  36. UNKNOWN, LOW, HIGH
  37. } state = State::UNKNOWN;
  38. void set_state(State incoming_state) {
  39. if (state==incoming_state) return;
  40. state = incoming_state;
  41. fire(state==State::HIGH ? rise_actions : fall_actions);
  42. }
  43. private:
  44. bool enabled = true;
  45. std::vector<std::function<void()>> rise_actions;
  46. std::vector<std::function<void()>> fall_actions;
  47. void fire(const std::vector<std::function<void()>> &actions) const {
  48. if (!enabled)
  49. return;
  50. for (const auto &action : actions)
  51. action();
  52. }
  53. };
  54. }