blob: d0ca196b5395832abf7b2871d6ee12dc0752aa46 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
Brian Silverman5120afb2020-01-31 17:44:35 -08002
Alex Perrycb7da4b2019-08-28 19:35:56 -07003#define AOS_EVENTS_EVENT_LOOP_H_
4
5#include <atomic>
6#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08007#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include "aos/configuration.h"
10#include "aos/configuration_generated.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080011#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080012#include "aos/events/event_loop_generated.h"
13#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/flatbuffers.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080015#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/json_to_flatbuffer.h"
17#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080018#include "aos/util/phased_loop.h"
Brian Silverman0fc69932020-01-24 21:54:02 -080019
20#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "flatbuffers/flatbuffers.h"
22#include "glog/logging.h"
23
Austin Schuh39788ff2019-12-01 18:22:57 -080024DECLARE_bool(timing_reports);
25DECLARE_int32(timing_report_ms);
26
Alex Perrycb7da4b2019-08-28 19:35:56 -070027namespace aos {
28
Austin Schuh39788ff2019-12-01 18:22:57 -080029class EventLoop;
30class WatcherState;
31
Austin Schuh6231cc32019-12-07 13:06:15 -080032// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
33// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070034struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080035 // Time that the message was sent on this node, or the timer was triggered.
36 monotonic_clock::time_point monotonic_event_time;
37 // Realtime the message was sent on this node. This is set to min_time for
38 // Timers and PhasedLoops.
39 realtime_clock::time_point realtime_event_time;
40
41 // For a single-node configuration, these two are identical to *_event_time.
42 // In a multinode configuration, these are the times that the message was
43 // sent on the original node.
44 monotonic_clock::time_point monotonic_remote_time;
45 realtime_clock::time_point realtime_remote_time;
46
Austin Schuh6231cc32019-12-07 13:06:15 -080047 // The rest are only valid for Watchers and Fetchers.
Alex Perrycb7da4b2019-08-28 19:35:56 -070048 // Index in the queue.
49 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080050 // Index into the remote queue. Useful to determine if data was lost. In a
51 // single-node configuration, this will match queue_index.
52 uint32_t remote_queue_index;
53
Alex Perrycb7da4b2019-08-28 19:35:56 -070054 // Size of the data sent.
55 size_t size;
56 // Pointer to the data.
57 void *data;
58};
59
60// Raw version of fetcher. Contains a local variable that the fetcher will
61// update. This is used for reflection and as an interface to implement typed
62// fetchers.
63class RawFetcher {
64 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080065 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070066 RawFetcher(const RawFetcher &) = delete;
67 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080068 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070069
Austin Schuh39788ff2019-12-01 18:22:57 -080070 // Fetches the next message in the queue without blocking. Returns true if
71 // there was a new message and we got it.
72 bool FetchNext();
73
74 // Fetches the latest message without blocking.
75 bool Fetch();
76
77 // Returns the channel this fetcher uses.
78 const Channel *channel() const { return channel_; }
79 // Returns the context for the current message.
80 const Context &context() const { return context_; }
81
82 protected:
83 EventLoop *event_loop() { return event_loop_; }
84
Alex Perrycb7da4b2019-08-28 19:35:56 -070085 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080086
87 private:
88 friend class EventLoop;
89 // Implementation
90 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
91 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
92
93 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -080094 const Channel *channel_;
Austin Schuh39788ff2019-12-01 18:22:57 -080095
96 internal::RawFetcherTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070097};
98
99// Raw version of sender. Sends a block of data. This is used for reflection
100// and as a building block to implement typed senders.
101class RawSender {
102 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 RawSender(EventLoop *event_loop, const Channel *channel);
104 RawSender(const RawSender &) = delete;
105 RawSender &operator=(const RawSender &) = delete;
106
107 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108
109 // Sends a message without copying it. The users starts by copying up to
110 // size() bytes into the data backed by data(). They then call Send to send.
111 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800112 // If provided, monotonic_remote_time, realtime_remote_time, and
113 // remote_queue_index are attached to the message and are available in the
114 // context on the read side. If they are not populated, the read side will
115 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116 virtual void *data() = 0;
117 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800118 bool Send(size_t size,
119 aos::monotonic_clock::time_point monotonic_remote_time =
120 aos::monotonic_clock::min_time,
121 aos::realtime_clock::time_point realtime_remote_time =
122 aos::realtime_clock::min_time,
123 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124
125 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800126 // The remote arguments have the same meaning as in Send above.
127 bool Send(const void *data, size_t size,
128 aos::monotonic_clock::time_point monotonic_remote_time =
129 aos::monotonic_clock::min_time,
130 aos::realtime_clock::time_point realtime_remote_time =
131 aos::realtime_clock::min_time,
132 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133
Austin Schuh54cf95f2019-11-29 13:14:18 -0800134 const Channel *channel() const { return channel_; }
135
Austin Schuhad154822019-12-27 15:45:13 -0800136 // Returns the time_points that the last message was sent at.
137 aos::monotonic_clock::time_point monotonic_sent_time() const {
138 return monotonic_sent_time_;
139 }
140 aos::realtime_clock::time_point realtime_sent_time() const {
141 return realtime_sent_time_;
142 }
143 // Returns the queue index that this was sent with.
144 uint32_t sent_queue_index() const { return sent_queue_index_; }
145
Brian Silvermana1652f32020-01-29 20:41:44 -0800146 // Returns the associated flatbuffers-style allocator. This must be
147 // deallocated before the message is sent.
148 PreallocatedAllocator *fbb_allocator() {
149 fbb_allocator_ = PreallocatedAllocator(data(), size());
150 return &fbb_allocator_;
151 }
152
Alex Perrycb7da4b2019-08-28 19:35:56 -0700153 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800154 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800155
Austin Schuhad154822019-12-27 15:45:13 -0800156 aos::monotonic_clock::time_point monotonic_sent_time_ =
157 aos::monotonic_clock::min_time;
158 aos::realtime_clock::time_point realtime_sent_time_ =
159 aos::realtime_clock::min_time;
160 uint32_t sent_queue_index_ = 0xffffffff;
161
Austin Schuh39788ff2019-12-01 18:22:57 -0800162 private:
163 friend class EventLoop;
164
Austin Schuhad154822019-12-27 15:45:13 -0800165 virtual bool DoSend(const void *data, size_t size,
166 aos::monotonic_clock::time_point monotonic_remote_time,
167 aos::realtime_clock::time_point realtime_remote_time,
168 uint32_t remote_queue_index) = 0;
169 virtual bool DoSend(size_t size,
170 aos::monotonic_clock::time_point monotonic_remote_time,
171 aos::realtime_clock::time_point realtime_remote_time,
172 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800173
174 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800175 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176
Austin Schuh39788ff2019-12-01 18:22:57 -0800177 internal::RawSenderTiming timing_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800178
179 PreallocatedAllocator fbb_allocator_{nullptr, 0};
Austin Schuh39788ff2019-12-01 18:22:57 -0800180};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700181
182// Fetches the newest message from a channel.
183// This provides a polling based interface for channels.
184template <typename T>
185class Fetcher {
186 public:
187 Fetcher() {}
188
189 // Fetches the next message. Returns true if it fetched a new message. This
190 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800191 bool FetchNext() {
192 const bool result = fetcher_->FetchNext();
193 if (result) {
194 CheckChannelDataAlignment(fetcher_->context().data,
195 fetcher_->context().size);
196 }
197 return result;
198 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199
200 // Fetches the most recent message. Returns true if it fetched a new message.
201 // This will return the latest message regardless of if it was sent before or
202 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800203 bool Fetch() {
204 const bool result = fetcher_->Fetch();
205 if (result) {
206 CheckChannelDataAlignment(fetcher_->context().data,
207 fetcher_->context().size);
208 }
209 return result;
210 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211
212 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
213 // available message.
214 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800215 return fetcher_->context().data != nullptr
216 ? flatbuffers::GetRoot<T>(
217 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218 : nullptr;
219 }
220
221 // Returns the context holding timestamps and other metadata about the
222 // message.
223 const Context &context() const { return fetcher_->context(); }
224
225 const T &operator*() const { return *get(); }
226 const T *operator->() const { return get(); }
227
228 private:
229 friend class EventLoop;
230 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
231 : fetcher_(::std::move(fetcher)) {}
232 ::std::unique_ptr<RawFetcher> fetcher_;
233};
234
235// Sends messages to a channel.
236template <typename T>
237class Sender {
238 public:
239 Sender() {}
240
241 // Represents a single message about to be sent to the queue.
242 // The lifecycle goes:
243 //
244 // Builder builder = sender.MakeBuilder();
245 // T::Builder t_builder = builder.MakeBuilder<T>();
246 // Populate(&t_builder);
247 // builder.Send(t_builder.Finish());
248 class Builder {
249 public:
Brian Silvermana1652f32020-01-29 20:41:44 -0800250 Builder(RawSender *sender, PreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800251 : fbb_(allocator->size(), allocator),
252 allocator_(allocator),
253 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800254 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800255 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800257 Builder() {}
258 Builder(const Builder &) = delete;
259 Builder(Builder &&) = default;
260
261 Builder &operator=(const Builder &) = delete;
262 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263
264 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
265
266 template <typename T2>
267 typename T2::Builder MakeBuilder() {
268 return typename T2::Builder(fbb_);
269 }
270
271 bool Send(flatbuffers::Offset<T> offset) {
272 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800273 const bool result = sender_->Send(fbb_.GetSize());
274 // Ensure fbb_ knows it shouldn't access the memory any more.
275 fbb_ = flatbuffers::FlatBufferBuilder();
276 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277 }
278
279 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800280 void CheckSent() {
281 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
282 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283
284 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285 flatbuffers::FlatBufferBuilder fbb_;
Brian Silverman9dd793b2020-01-31 23:52:21 -0800286 PreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287 RawSender *sender_;
288 };
289
290 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800291 //
292 // Only a single one of these may be "alive" for this object at any point in
293 // time. After calling Send on the result, it is no longer "alive". This means
294 // that you must manually reset a variable holding the return value (by
295 // assigning a default-constructed Builder to it) before calling this method
296 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297 Builder MakeBuilder();
298
Austin Schuha28cbc32019-12-27 16:28:04 -0800299 // Sends a prebuilt flatbuffer.
300 bool Send(const Flatbuffer<T> &flatbuffer);
301
Austin Schuh39788ff2019-12-01 18:22:57 -0800302 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800303 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304
Tyler Chatow67ddb032020-01-12 14:30:04 -0800305 operator bool() {
306 return sender_ ? true : false;
307 }
308
Austin Schuh7bc59052020-02-16 23:48:33 -0800309 // Returns the time_points that the last message was sent at.
310 aos::monotonic_clock::time_point monotonic_sent_time() const {
311 return sender_->monotonic_sent_time();
312 }
313 aos::realtime_clock::time_point realtime_sent_time() const {
314 return sender_->realtime_sent_time();
315 }
316 // Returns the queue index that this was sent with.
317 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
318
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319 private:
320 friend class EventLoop;
321 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
322 std::unique_ptr<RawSender> sender_;
323};
324
325// Interface for timers
326class TimerHandler {
327 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800328 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700329
330 // Timer should sleep until base, base + offset, base + offset * 2, ...
331 // If repeat_offset isn't set, the timer only expires once.
332 virtual void Setup(monotonic_clock::time_point base,
333 monotonic_clock::duration repeat_offset =
334 ::aos::monotonic_clock::zero()) = 0;
335
336 // Stop future calls to callback().
337 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800338
339 // Sets and gets the name of the timer. Set this if you want a descriptive
340 // name in the timing report.
341 void set_name(std::string_view name) { name_ = std::string(name); }
342 const std::string_view name() const { return name_; }
343
Austin Schuh39788ff2019-12-01 18:22:57 -0800344 protected:
345 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
346
Austin Schuhcde39fd2020-02-22 20:58:24 -0800347 monotonic_clock::time_point Call(
348 std::function<monotonic_clock::time_point()> get_time,
349 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800350
Austin Schuh1540c2f2019-11-29 21:59:29 -0800351 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800352 friend class EventLoop;
353
354 EventLoop *event_loop_;
355 // The function to call when Call is called.
356 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800357 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800358
359 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360};
361
362// Interface for phased loops. They are built on timers.
363class PhasedLoopHandler {
364 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800365 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366
367 // Sets the interval and offset. Any changes to interval and offset only take
368 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800369 void set_interval_and_offset(const monotonic_clock::duration interval,
370 const monotonic_clock::duration offset) {
371 phased_loop_.set_interval_and_offset(interval, offset);
372 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800373
374 // Sets and gets the name of the timer. Set this if you want a descriptive
375 // name in the timing report.
376 void set_name(std::string_view name) { name_ = std::string(name); }
377 const std::string_view name() const { return name_; }
378
Austin Schuh39788ff2019-12-01 18:22:57 -0800379 protected:
380 void Call(std::function<monotonic_clock::time_point()> get_time,
381 std::function<void(monotonic_clock::time_point)> schedule);
382
383 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
384 const monotonic_clock::duration interval,
385 const monotonic_clock::duration offset);
386
Austin Schuh1540c2f2019-11-29 21:59:29 -0800387 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800388 friend class EventLoop;
389
390 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
391 monotonic_clock::time_point monotonic_now) {
392 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
393 schedule(phased_loop_.sleep_time());
394 }
395
396 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
397
398 EventLoop *event_loop_;
399 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800400 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 time::PhasedLoop phased_loop_;
402
403 int cycles_elapsed_ = 0;
404
405 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406};
407
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408class EventLoop {
409 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800410 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411
Austin Schuh39788ff2019-12-01 18:22:57 -0800412 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413
414 // Current time.
415 virtual monotonic_clock::time_point monotonic_now() = 0;
416 virtual realtime_clock::time_point realtime_now() = 0;
417
418 // Note, it is supported to create:
419 // multiple fetchers, and (one sender or one watcher) per <name, type>
420 // tuple.
421
422 // Makes a class that will always fetch the most recent value
423 // sent to the provided channel.
424 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800425 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800426 const Channel *channel =
427 configuration::GetChannel(configuration_, channel_name,
428 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429 CHECK(channel != nullptr)
430 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
431 << T::GetFullyQualifiedName() << "\" } not found in config.";
432
Austin Schuhca4828c2019-12-28 14:21:35 -0800433 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
434 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
435 << "\", \"type\": \"" << T::GetFullyQualifiedName()
436 << "\" } is not able to be fetched on this node. Check your "
437 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800438 }
439
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 return Fetcher<T>(MakeRawFetcher(channel));
441 }
442
443 // Makes class that allows constructing and sending messages to
444 // the provided channel.
445 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800446 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800447 const Channel *channel =
448 configuration::GetChannel(configuration_, channel_name,
449 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450 CHECK(channel != nullptr)
451 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800452 << T::GetFullyQualifiedName() << "\" } not found in config for "
453 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454
Austin Schuhca4828c2019-12-28 14:21:35 -0800455 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
456 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
457 << "\", \"type\": \"" << T::GetFullyQualifiedName()
458 << "\" } is not able to be sent on this node. Check your "
459 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800460 }
461
Alex Perrycb7da4b2019-08-28 19:35:56 -0700462 return Sender<T>(MakeRawSender(channel));
463 }
464
465 // This will watch messages sent to the provided channel.
466 //
467 // Watch is a functor that have a call signature like so:
468 // void Event(const MessageType& type);
469 //
470 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
471 // TODO(austin): Do we need a functor? Or is a std::function good enough?
472 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800473 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474
475 // The passed in function will be called when the event loop starts.
476 // Use this to run code once the thread goes into "real-time-mode",
477 virtual void OnRun(::std::function<void()> on_run) = 0;
478
Austin Schuh217a9782019-12-21 23:02:50 -0800479 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800480 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481
Austin Schuh217a9782019-12-21 23:02:50 -0800482 // Returns the node that this event loop is running on. Returns nullptr if we
483 // are running in single-node mode.
484 virtual const Node *node() const = 0;
485
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486 // Creates a timer that executes callback when the timer expires
487 // Returns a TimerHandle for configuration of the timer
488 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
489
490 // Creates a timer that executes callback periodically at the specified
491 // interval and offset. Returns a PhasedLoopHandler for interacting with the
492 // timer.
493 virtual PhasedLoopHandler *AddPhasedLoop(
494 ::std::function<void(int)> callback,
495 const monotonic_clock::duration interval,
496 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
497
Austin Schuh217a9782019-12-21 23:02:50 -0800498 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499
500 // Threadsafe.
501 bool is_running() const { return is_running_.load(); }
502
503 // Sets the scheduler priority to run the event loop at. This may not be
504 // called after we go into "real-time-mode".
505 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800506 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507
Austin Schuh217a9782019-12-21 23:02:50 -0800508 // Fetches new messages from the provided channel (path, type).
509 //
510 // Note: this channel must be a member of the exact configuration object this
511 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
513 const Channel *channel) = 0;
514
Austin Schuh217a9782019-12-21 23:02:50 -0800515 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516 virtual void MakeRawWatcher(
517 const Channel *channel,
518 std::function<void(const Context &context, const void *message)>
519 watcher) = 0;
520
Austin Schuh217a9782019-12-21 23:02:50 -0800521 // Creates a raw sender for the provided channel. This is used for reflection
522 // based sending.
523 // Note: this ignores any node constraints. Ignore at your own peril.
524 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
525
Austin Schuh6231cc32019-12-07 13:06:15 -0800526 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 const Context &context() const { return context_; }
528
529 // Returns the configuration that this event loop was built with.
530 const Configuration *configuration() const { return configuration_; }
531
Austin Schuh39788ff2019-12-01 18:22:57 -0800532 // Prevents the event loop from sending a timing report.
533 void SkipTimingReport() { skip_timing_report_ = true; }
534
Tyler Chatow67ddb032020-01-12 14:30:04 -0800535 // Prevents AOS_LOG being sent to message on /aos
536 void SkipAosLog() { skip_logger_ = true; }
537
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800539 // Sets the name of the event loop. This is the application name.
540 virtual void set_name(const std::string_view name) = 0;
541
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 void set_is_running(bool value) { is_running_.store(value); }
543
Austin Schuh39788ff2019-12-01 18:22:57 -0800544 // Validates that channel exists inside configuration_ and finds its index.
545 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546
Brian Silverman5120afb2020-01-31 17:44:35 -0800547 // Returns the state for the watcher on the corresponding channel. This
548 // watcher must exist before calling this.
549 WatcherState *GetWatcherState(const Channel *channel);
550
551 // Returns a Sender's protected RawSender
552 template <typename T>
553 static RawSender *GetRawSender(aos::Sender<T> *sender) {
554 return sender->sender_.get();
555 }
556
Austin Schuh6231cc32019-12-07 13:06:15 -0800557 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558 Context context_;
559
Austin Schuh39788ff2019-12-01 18:22:57 -0800560 friend class RawSender;
561 friend class TimerHandler;
562 friend class RawFetcher;
563 friend class PhasedLoopHandler;
564 friend class WatcherState;
565
566 // Methods used to implement timing reports.
567 void NewSender(RawSender *sender);
568 void DeleteSender(RawSender *sender);
569 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
570 PhasedLoopHandler *NewPhasedLoop(
571 std::unique_ptr<PhasedLoopHandler> phased_loop);
572 void NewFetcher(RawFetcher *fetcher);
573 void DeleteFetcher(RawFetcher *fetcher);
574 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
575
Brian Silverman0fc69932020-01-24 21:54:02 -0800576 // Tracks that we have a (single) watcher on the given channel.
577 void TakeWatcher(const Channel *channel);
578 // Tracks that we have at least one sender on the given channel.
579 void TakeSender(const Channel *channel);
580
Austin Schuh39788ff2019-12-01 18:22:57 -0800581 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800582 std::vector<RawFetcher *> fetchers_;
583
Austin Schuh39788ff2019-12-01 18:22:57 -0800584 std::vector<std::unique_ptr<TimerHandler>> timers_;
585 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800586 std::vector<std::unique_ptr<WatcherState>> watchers_;
587
588 void SendTimingReport();
589 void UpdateTimingReport();
590 void MaybeScheduleTimingReports();
591
592 std::unique_ptr<RawSender> timing_report_sender_;
593
Austin Schuh7d87b672019-12-01 20:23:49 -0800594 // Tracks which event sources (timers and watchers) have data, and which
595 // don't. Added events may not change their event_time().
596 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
597 // t2 to run, t2 should then be picked up without a context switch.
598 void AddEvent(EventLoopEvent *event);
599 void RemoveEvent(EventLoopEvent *event);
600 size_t EventCount() const { return events_.size(); }
601 EventLoopEvent *PopEvent();
602 EventLoopEvent *PeekEvent() { return events_.front(); }
603 void ReserveEvents();
604
605 std::vector<EventLoopEvent *> events_;
606
Tyler Chatow67ddb032020-01-12 14:30:04 -0800607 // If true, don't send AOS_LOG to /aos
608 bool skip_logger_ = false;
609
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800610 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800611 virtual pid_t GetTid() = 0;
612
613 FlatbufferDetachedBuffer<timing::Report> timing_report_;
614
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800615 ::std::atomic<bool> is_running_{false};
616
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800618
619 // If true, don't send out timing reports.
620 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800621
622 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623};
624
625} // namespace aos
626
627#include "aos/events/event_loop_tmpl.h"
628
629#endif // AOS_EVENTS_EVENT_LOOP_H