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