blob: 4d1ff07452398f76fb55f11d4defe6275b4d18ac [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
Stephan Pleines5ecc8f12024-05-31 20:35:21 -07004#include <stddef.h>
5
6#include <chrono>
7
Austin Schuh7d87b672019-12-01 20:23:49 -08008#include "glog/logging.h"
9
Philipp Schrader790cb542023-07-05 21:06:52 -070010#include "aos/time/time.h"
11
Austin Schuh7d87b672019-12-01 20:23:49 -080012namespace aos {
13
14// Common interface to track when callbacks and timers should have happened.
15class EventLoopEvent {
16 public:
17 virtual ~EventLoopEvent() {}
18
19 bool valid() const { return event_time_ != monotonic_clock::max_time; }
Brian Silvermanbd405c02020-06-23 16:25:23 -070020 void Invalidate() {
21 event_time_ = monotonic_clock::max_time;
22 generation_ = 0;
23 }
Austin Schuh7d87b672019-12-01 20:23:49 -080024
25 monotonic_clock::time_point event_time() const {
26 DCHECK(valid());
27 return event_time_;
28 }
Austin Schuh7d87b672019-12-01 20:23:49 -080029 void set_event_time(monotonic_clock::time_point event_time) {
30 event_time_ = event_time;
31 }
32
Brian Silvermanbd405c02020-06-23 16:25:23 -070033 // Internal book-keeping for EventLoop.
34 size_t generation() const {
35 DCHECK(valid());
36 return generation_;
37 }
38 void set_generation(size_t generation) { generation_ = generation; }
39
Austin Schuhf4b09c72021-12-08 12:04:37 -080040 virtual void HandleEvent() noexcept = 0;
Brian Silvermanbd405c02020-06-23 16:25:23 -070041
Austin Schuh7d87b672019-12-01 20:23:49 -080042 private:
43 monotonic_clock::time_point event_time_ = monotonic_clock::max_time;
Brian Silvermanbd405c02020-06-23 16:25:23 -070044 size_t generation_ = 0;
Austin Schuh7d87b672019-12-01 20:23:49 -080045};
46
47// Adapter class to implement EventLoopEvent by calling HandleEvent on T.
48template <typename T>
49class EventHandler final : public EventLoopEvent {
50 public:
51 EventHandler(T *t) : t_(t) {}
Brian Silvermanbd405c02020-06-23 16:25:23 -070052 ~EventHandler() override = default;
Austin Schuhf4b09c72021-12-08 12:04:37 -080053 void HandleEvent() noexcept override { t_->HandleEvent(); }
Austin Schuh7d87b672019-12-01 20:23:49 -080054
55 private:
56 T *const t_;
57};
58
59} // namespace aos
60
61#endif // AOS_EVENTS_EVENT_LOOP_EVENT_H