blob: 0f335e5349b7b221f78df4c476443453182beb1c [file] [log] [blame]
Austin Schuh6b6dfa52019-06-12 20:16:20 -07001#ifndef AOS_EVENTS_EPOLL_H_
2#define AOS_EVENTS_EPOLL_H_
3
4#include <fcntl.h>
5#include <sys/epoll.h>
6#include <sys/timerfd.h>
7#include <unistd.h>
8#include <atomic>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include <functional>
Austin Schuh6b6dfa52019-06-12 20:16:20 -070010#include <vector>
11
Austin Schuh6b6dfa52019-06-12 20:16:20 -070012#include "aos/time/time.h"
13
14namespace aos {
15namespace internal {
16
17// Class wrapping up timerfd.
18class TimerFd {
19 public:
20 TimerFd();
Austin Schuhf257f3c2019-10-27 21:00:43 -070021 ~TimerFd();
Austin Schuh6b6dfa52019-06-12 20:16:20 -070022
23 TimerFd(const TimerFd &) = delete;
24 TimerFd &operator=(const TimerFd &) = delete;
25 TimerFd(TimerFd &&) = delete;
26 TimerFd &operator=(TimerFd &&) = delete;
27
28 // Sets the trigger time and repeat for the timerfd.
29 // An interval of 0 results in a single expiration.
30 void SetTime(monotonic_clock::time_point start,
31 monotonic_clock::duration interval);
32
33 // Disarms the timer.
34 void Disable() {
35 // Disarm the timer by feeding zero values
36 SetTime(::aos::monotonic_clock::epoch(), ::aos::monotonic_clock::zero());
37 }
38
39 // Reads the event. Ignores it.
40 void Read();
41
42 // Returns the file descriptor associated with the timerfd.
43 int fd() { return fd_; }
44
45 private:
46 int fd_ = -1;
47};
48
49// Class to wrap epoll and call a callback when an event happens.
50class EPoll {
51 public:
52 EPoll();
53 ~EPoll();
54 EPoll(const EPoll &) = delete;
55 EPoll &operator=(const EPoll &) = delete;
56 EPoll(EPoll &&) = delete;
57 EPoll &operator=(EPoll &&) = delete;
58
59 // Runs until Quit() is called.
60 void Run();
61
62 // Quits. Async safe.
63 void Quit();
64
65 // Registers a function to be called if the fd becomes readable.
66 // There should only be 1 function registered for each fd.
67 void OnReadable(int fd, ::std::function<void()> function);
68
69 // Removes fd from the event loop.
70 // All Fds must be cleaned up before this class is destroyed.
71 void DeleteFd(int fd);
72
73 private:
74 ::std::atomic<bool> run_{true};
75
76 // Main epoll fd.
77 int epoll_fd_;
78
79 // Structure whose pointer should be returned by epoll. Makes looking up the
80 // function fast and easy.
81 struct EventData {
82 int fd;
83 ::std::function<void()> in_fn;
84 };
85 ::std::vector<::std::unique_ptr<EventData>> fns_;
86
87 // Pipe pair for handling quit.
88 int quit_signal_fd_;
89 int quit_epoll_fd_;
90};
91
92} // namespace internal
93} // namespace aos
94
95#endif // AOS_EVENTS_EPOLL_H_