blob: 588b851ef214b183bc1c4b9e8e944b21df6b7aba [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
Austin Schuh7d87b672019-12-01 20:23:49 -08004#include "glog/logging.h"
5
Philipp Schrader790cb542023-07-05 21:06:52 -07006#include "aos/time/time.h"
7
Austin Schuh7d87b672019-12-01 20:23:49 -08008namespace aos {
9
10// Common interface to track when callbacks and timers should have happened.
11class EventLoopEvent {
12 public:
13 virtual ~EventLoopEvent() {}
14
15 bool valid() const { return event_time_ != monotonic_clock::max_time; }
Brian Silvermanbd405c02020-06-23 16:25:23 -070016 void Invalidate() {
17 event_time_ = monotonic_clock::max_time;
18 generation_ = 0;
19 }
Austin Schuh7d87b672019-12-01 20:23:49 -080020
21 monotonic_clock::time_point event_time() const {
22 DCHECK(valid());
23 return event_time_;
24 }
Austin Schuh7d87b672019-12-01 20:23:49 -080025 void set_event_time(monotonic_clock::time_point event_time) {
26 event_time_ = event_time;
27 }
28
Brian Silvermanbd405c02020-06-23 16:25:23 -070029 // Internal book-keeping for EventLoop.
30 size_t generation() const {
31 DCHECK(valid());
32 return generation_;
33 }
34 void set_generation(size_t generation) { generation_ = generation; }
35
Austin Schuhf4b09c72021-12-08 12:04:37 -080036 virtual void HandleEvent() noexcept = 0;
Brian Silvermanbd405c02020-06-23 16:25:23 -070037
Austin Schuh7d87b672019-12-01 20:23:49 -080038 private:
39 monotonic_clock::time_point event_time_ = monotonic_clock::max_time;
Brian Silvermanbd405c02020-06-23 16:25:23 -070040 size_t generation_ = 0;
Austin Schuh7d87b672019-12-01 20:23:49 -080041};
42
43// Adapter class to implement EventLoopEvent by calling HandleEvent on T.
44template <typename T>
45class EventHandler final : public EventLoopEvent {
46 public:
47 EventHandler(T *t) : t_(t) {}
Brian Silvermanbd405c02020-06-23 16:25:23 -070048 ~EventHandler() override = default;
Austin Schuhf4b09c72021-12-08 12:04:37 -080049 void HandleEvent() noexcept override { t_->HandleEvent(); }
Austin Schuh7d87b672019-12-01 20:23:49 -080050
51 private:
52 T *const t_;
53};
54
55} // namespace aos
56
57#endif // AOS_EVENTS_EVENT_LOOP_EVENT_H