blob: 6e823f00c6415699cf55a5f5848be9929c792a69 [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 Schuh99f7c6a2024-06-25 22:07:44 -07008#include "absl/log/check.h"
9#include "absl/log/log.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080010
Philipp Schrader790cb542023-07-05 21:06:52 -070011#include "aos/time/time.h"
12
Austin Schuh7d87b672019-12-01 20:23:49 -080013namespace aos {
14
15// Common interface to track when callbacks and timers should have happened.
16class EventLoopEvent {
17 public:
18 virtual ~EventLoopEvent() {}
19
20 bool valid() const { return event_time_ != monotonic_clock::max_time; }
Brian Silvermanbd405c02020-06-23 16:25:23 -070021 void Invalidate() {
22 event_time_ = monotonic_clock::max_time;
23 generation_ = 0;
24 }
Austin Schuh7d87b672019-12-01 20:23:49 -080025
26 monotonic_clock::time_point event_time() const {
27 DCHECK(valid());
28 return event_time_;
29 }
Austin Schuh7d87b672019-12-01 20:23:49 -080030 void set_event_time(monotonic_clock::time_point event_time) {
31 event_time_ = event_time;
32 }
33
Brian Silvermanbd405c02020-06-23 16:25:23 -070034 // Internal book-keeping for EventLoop.
35 size_t generation() const {
36 DCHECK(valid());
37 return generation_;
38 }
39 void set_generation(size_t generation) { generation_ = generation; }
40
Austin Schuhf4b09c72021-12-08 12:04:37 -080041 virtual void HandleEvent() noexcept = 0;
Brian Silvermanbd405c02020-06-23 16:25:23 -070042
Austin Schuh7d87b672019-12-01 20:23:49 -080043 private:
44 monotonic_clock::time_point event_time_ = monotonic_clock::max_time;
Brian Silvermanbd405c02020-06-23 16:25:23 -070045 size_t generation_ = 0;
Austin Schuh7d87b672019-12-01 20:23:49 -080046};
47
48// Adapter class to implement EventLoopEvent by calling HandleEvent on T.
49template <typename T>
50class EventHandler final : public EventLoopEvent {
51 public:
52 EventHandler(T *t) : t_(t) {}
Brian Silvermanbd405c02020-06-23 16:25:23 -070053 ~EventHandler() override = default;
Austin Schuhf4b09c72021-12-08 12:04:37 -080054 void HandleEvent() noexcept override { t_->HandleEvent(); }
Austin Schuh7d87b672019-12-01 20:23:49 -080055
56 private:
57 T *const t_;
58};
59
60} // namespace aos
61
62#endif // AOS_EVENTS_EVENT_LOOP_EVENT_H