Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 1 | #ifndef AOS_EVENTS_EVENT_LOOP_EVENT_H |
| 2 | #define AOS_EVENTS_EVENT_LOOP_EVENT_H |
| 3 | |
| 4 | #include "aos/time/time.h" |
| 5 | #include "glog/logging.h" |
| 6 | |
| 7 | namespace aos { |
| 8 | |
| 9 | // Common interface to track when callbacks and timers should have happened. |
| 10 | class EventLoopEvent { |
| 11 | public: |
| 12 | virtual ~EventLoopEvent() {} |
| 13 | |
| 14 | bool valid() const { return event_time_ != monotonic_clock::max_time; } |
| 15 | void Invalidate() { event_time_ = monotonic_clock::max_time; } |
| 16 | |
| 17 | monotonic_clock::time_point event_time() const { |
| 18 | DCHECK(valid()); |
| 19 | return event_time_; |
| 20 | } |
| 21 | |
| 22 | virtual void HandleEvent() = 0; |
| 23 | |
| 24 | void set_event_time(monotonic_clock::time_point event_time) { |
| 25 | event_time_ = event_time; |
| 26 | } |
| 27 | |
| 28 | private: |
| 29 | monotonic_clock::time_point event_time_ = monotonic_clock::max_time; |
| 30 | }; |
| 31 | |
| 32 | // Adapter class to implement EventLoopEvent by calling HandleEvent on T. |
| 33 | template <typename T> |
| 34 | class EventHandler final : public EventLoopEvent { |
| 35 | public: |
| 36 | EventHandler(T *t) : t_(t) {} |
| 37 | ~EventHandler() = default; |
| 38 | void HandleEvent() override { t_->HandleEvent(); } |
| 39 | |
| 40 | private: |
| 41 | T *const t_; |
| 42 | }; |
| 43 | |
| 44 | } // namespace aos |
| 45 | |
| 46 | #endif // AOS_EVENTS_EVENT_LOOP_EVENT_H |