blob: 808a4fe3dee7d6576b6f83dd01455a5c00fba61c [file] [log] [blame]
Austin Schuh7d87b672019-12-01 20:23:49 -08001#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
7namespace aos {
8
9// Common interface to track when callbacks and timers should have happened.
10class EventLoopEvent {
11 public:
12 virtual ~EventLoopEvent() {}
13
14 bool valid() const { return event_time_ != monotonic_clock::max_time; }
Brian Silvermanbd405c02020-06-23 16:25:23 -070015 void Invalidate() {
16 event_time_ = monotonic_clock::max_time;
17 generation_ = 0;
18 }
Austin Schuh7d87b672019-12-01 20:23:49 -080019
20 monotonic_clock::time_point event_time() const {
21 DCHECK(valid());
22 return event_time_;
23 }
Austin Schuh7d87b672019-12-01 20:23:49 -080024 void set_event_time(monotonic_clock::time_point event_time) {
25 event_time_ = event_time;
26 }
27
Brian Silvermanbd405c02020-06-23 16:25:23 -070028 // Internal book-keeping for EventLoop.
29 size_t generation() const {
30 DCHECK(valid());
31 return generation_;
32 }
33 void set_generation(size_t generation) { generation_ = generation; }
34
35 virtual void HandleEvent() = 0;
36
Austin Schuh7d87b672019-12-01 20:23:49 -080037 private:
38 monotonic_clock::time_point event_time_ = monotonic_clock::max_time;
Brian Silvermanbd405c02020-06-23 16:25:23 -070039 size_t generation_ = 0;
Austin Schuh7d87b672019-12-01 20:23:49 -080040};
41
42// Adapter class to implement EventLoopEvent by calling HandleEvent on T.
43template <typename T>
44class EventHandler final : public EventLoopEvent {
45 public:
46 EventHandler(T *t) : t_(t) {}
Brian Silvermanbd405c02020-06-23 16:25:23 -070047 ~EventHandler() override = default;
Austin Schuh7d87b672019-12-01 20:23:49 -080048 void HandleEvent() override { t_->HandleEvent(); }
49
50 private:
51 T *const t_;
52};
53
54} // namespace aos
55
56#endif // AOS_EVENTS_EVENT_LOOP_EVENT_H