blob: 0a22abecd3a100186b142612989b46d8313114db [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
2#define AOS_EVENTS_EVENT_LOOP_H_
3
4#include <atomic>
5#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08006#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include "aos/configuration.h"
9#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080010#include "aos/events/channel_preallocated_allocator.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.
Austin Schuh1af273d2020-03-07 20:11:34 -0800148 ChannelPreallocatedAllocator *fbb_allocator() {
149 fbb_allocator_ = ChannelPreallocatedAllocator(
150 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800151 return &fbb_allocator_;
152 }
153
Alex Perrycb7da4b2019-08-28 19:35:56 -0700154 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800155 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800156
Austin Schuhad154822019-12-27 15:45:13 -0800157 aos::monotonic_clock::time_point monotonic_sent_time_ =
158 aos::monotonic_clock::min_time;
159 aos::realtime_clock::time_point realtime_sent_time_ =
160 aos::realtime_clock::min_time;
161 uint32_t sent_queue_index_ = 0xffffffff;
162
Austin Schuh39788ff2019-12-01 18:22:57 -0800163 private:
164 friend class EventLoop;
165
Austin Schuhad154822019-12-27 15:45:13 -0800166 virtual bool DoSend(const void *data, size_t size,
167 aos::monotonic_clock::time_point monotonic_remote_time,
168 aos::realtime_clock::time_point realtime_remote_time,
169 uint32_t remote_queue_index) = 0;
170 virtual bool DoSend(size_t size,
171 aos::monotonic_clock::time_point monotonic_remote_time,
172 aos::realtime_clock::time_point realtime_remote_time,
173 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800174
175 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800176 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700177
Austin Schuh39788ff2019-12-01 18:22:57 -0800178 internal::RawSenderTiming timing_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800179
Austin Schuh1af273d2020-03-07 20:11:34 -0800180 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800181};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182
183// Fetches the newest message from a channel.
184// This provides a polling based interface for channels.
185template <typename T>
186class Fetcher {
187 public:
188 Fetcher() {}
189
190 // Fetches the next message. Returns true if it fetched a new message. This
191 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800192 bool FetchNext() {
193 const bool result = fetcher_->FetchNext();
194 if (result) {
195 CheckChannelDataAlignment(fetcher_->context().data,
196 fetcher_->context().size);
197 }
198 return result;
199 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700200
201 // Fetches the most recent message. Returns true if it fetched a new message.
202 // This will return the latest message regardless of if it was sent before or
203 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800204 bool Fetch() {
205 const bool result = fetcher_->Fetch();
206 if (result) {
207 CheckChannelDataAlignment(fetcher_->context().data,
208 fetcher_->context().size);
209 }
210 return result;
211 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700212
213 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
214 // available message.
215 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 return fetcher_->context().data != nullptr
217 ? flatbuffers::GetRoot<T>(
218 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700219 : nullptr;
220 }
221
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700222 // Returns the channel this fetcher uses
223 const Channel *channel() const { return fetcher_->channel(); }
224
Alex Perrycb7da4b2019-08-28 19:35:56 -0700225 // Returns the context holding timestamps and other metadata about the
226 // message.
227 const Context &context() const { return fetcher_->context(); }
228
229 const T &operator*() const { return *get(); }
230 const T *operator->() const { return get(); }
231
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700232 // Returns true if this fetcher is valid and connected to a channel.
233 operator bool() const { return static_cast<bool>(fetcher_); }
234
Alex Perrycb7da4b2019-08-28 19:35:56 -0700235 private:
236 friend class EventLoop;
237 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
238 : fetcher_(::std::move(fetcher)) {}
239 ::std::unique_ptr<RawFetcher> fetcher_;
240};
241
242// Sends messages to a channel.
243template <typename T>
244class Sender {
245 public:
246 Sender() {}
247
248 // Represents a single message about to be sent to the queue.
249 // The lifecycle goes:
250 //
251 // Builder builder = sender.MakeBuilder();
252 // T::Builder t_builder = builder.MakeBuilder<T>();
253 // Populate(&t_builder);
254 // builder.Send(t_builder.Finish());
255 class Builder {
256 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800257 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800258 : fbb_(allocator->size(), allocator),
259 allocator_(allocator),
260 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800261 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800262 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800264 Builder() {}
265 Builder(const Builder &) = delete;
266 Builder(Builder &&) = default;
267
268 Builder &operator=(const Builder &) = delete;
269 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270
271 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
272
273 template <typename T2>
274 typename T2::Builder MakeBuilder() {
275 return typename T2::Builder(fbb_);
276 }
277
278 bool Send(flatbuffers::Offset<T> offset) {
279 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800280 const bool result = sender_->Send(fbb_.GetSize());
281 // Ensure fbb_ knows it shouldn't access the memory any more.
282 fbb_ = flatbuffers::FlatBufferBuilder();
283 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 }
285
286 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800287 void CheckSent() {
288 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
289 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290
291 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800293 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700294 RawSender *sender_;
295 };
296
297 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800298 //
299 // Only a single one of these may be "alive" for this object at any point in
300 // time. After calling Send on the result, it is no longer "alive". This means
301 // that you must manually reset a variable holding the return value (by
302 // assigning a default-constructed Builder to it) before calling this method
303 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304 Builder MakeBuilder();
305
Austin Schuha28cbc32019-12-27 16:28:04 -0800306 // Sends a prebuilt flatbuffer.
307 bool Send(const Flatbuffer<T> &flatbuffer);
308
Austin Schuh39788ff2019-12-01 18:22:57 -0800309 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800310 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311
Brian Silverman454bc112020-03-05 14:21:25 -0800312 operator bool() { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800313
Austin Schuh7bc59052020-02-16 23:48:33 -0800314 // Returns the time_points that the last message was sent at.
315 aos::monotonic_clock::time_point monotonic_sent_time() const {
316 return sender_->monotonic_sent_time();
317 }
318 aos::realtime_clock::time_point realtime_sent_time() const {
319 return sender_->realtime_sent_time();
320 }
321 // Returns the queue index that this was sent with.
322 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
323
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324 private:
325 friend class EventLoop;
326 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
327 std::unique_ptr<RawSender> sender_;
328};
329
330// Interface for timers
331class TimerHandler {
332 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800333 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334
335 // Timer should sleep until base, base + offset, base + offset * 2, ...
336 // If repeat_offset isn't set, the timer only expires once.
337 virtual void Setup(monotonic_clock::time_point base,
338 monotonic_clock::duration repeat_offset =
339 ::aos::monotonic_clock::zero()) = 0;
340
341 // Stop future calls to callback().
342 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800343
344 // Sets and gets the name of the timer. Set this if you want a descriptive
345 // name in the timing report.
346 void set_name(std::string_view name) { name_ = std::string(name); }
347 const std::string_view name() const { return name_; }
348
Austin Schuh39788ff2019-12-01 18:22:57 -0800349 protected:
350 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
351
Austin Schuhcde39fd2020-02-22 20:58:24 -0800352 monotonic_clock::time_point Call(
353 std::function<monotonic_clock::time_point()> get_time,
354 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800355
Austin Schuh1540c2f2019-11-29 21:59:29 -0800356 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800357 friend class EventLoop;
358
359 EventLoop *event_loop_;
360 // The function to call when Call is called.
361 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800362 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800363
364 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365};
366
367// Interface for phased loops. They are built on timers.
368class PhasedLoopHandler {
369 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800370 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700371
372 // Sets the interval and offset. Any changes to interval and offset only take
373 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800374 void set_interval_and_offset(const monotonic_clock::duration interval,
375 const monotonic_clock::duration offset) {
376 phased_loop_.set_interval_and_offset(interval, offset);
377 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800378
379 // Sets and gets the name of the timer. Set this if you want a descriptive
380 // name in the timing report.
381 void set_name(std::string_view name) { name_ = std::string(name); }
382 const std::string_view name() const { return name_; }
383
Austin Schuh39788ff2019-12-01 18:22:57 -0800384 protected:
385 void Call(std::function<monotonic_clock::time_point()> get_time,
386 std::function<void(monotonic_clock::time_point)> schedule);
387
388 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
389 const monotonic_clock::duration interval,
390 const monotonic_clock::duration offset);
391
Austin Schuh1540c2f2019-11-29 21:59:29 -0800392 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800393 friend class EventLoop;
394
395 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
396 monotonic_clock::time_point monotonic_now) {
397 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
398 schedule(phased_loop_.sleep_time());
399 }
400
401 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
402
403 EventLoop *event_loop_;
404 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800405 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800406 time::PhasedLoop phased_loop_;
407
408 int cycles_elapsed_ = 0;
409
410 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411};
412
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413class EventLoop {
414 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800415 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416
Austin Schuh39788ff2019-12-01 18:22:57 -0800417 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418
419 // Current time.
420 virtual monotonic_clock::time_point monotonic_now() = 0;
421 virtual realtime_clock::time_point realtime_now() = 0;
422
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700423 // Returns true if the channel exists in the configuration.
424 template <typename T>
425 bool HasChannel(const std::string_view channel_name) {
426 return configuration::GetChannel(configuration_, channel_name,
427 T::GetFullyQualifiedName(), name(),
428 node()) != nullptr;
429 }
430
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431 // Note, it is supported to create:
432 // multiple fetchers, and (one sender or one watcher) per <name, type>
433 // tuple.
434
435 // Makes a class that will always fetch the most recent value
436 // sent to the provided channel.
437 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800438 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800439 const Channel *channel =
440 configuration::GetChannel(configuration_, channel_name,
441 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442 CHECK(channel != nullptr)
443 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
444 << T::GetFullyQualifiedName() << "\" } not found in config.";
445
Austin Schuhca4828c2019-12-28 14:21:35 -0800446 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
447 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
448 << "\", \"type\": \"" << T::GetFullyQualifiedName()
449 << "\" } is not able to be fetched on this node. Check your "
450 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800451 }
452
Alex Perrycb7da4b2019-08-28 19:35:56 -0700453 return Fetcher<T>(MakeRawFetcher(channel));
454 }
455
456 // Makes class that allows constructing and sending messages to
457 // the provided channel.
458 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800459 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800460 const Channel *channel =
461 configuration::GetChannel(configuration_, channel_name,
462 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700463 CHECK(channel != nullptr)
464 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800465 << T::GetFullyQualifiedName() << "\" } not found in config for "
466 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467
Austin Schuhca4828c2019-12-28 14:21:35 -0800468 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
469 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
470 << "\", \"type\": \"" << T::GetFullyQualifiedName()
471 << "\" } is not able to be sent on this node. Check your "
472 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800473 }
474
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 return Sender<T>(MakeRawSender(channel));
476 }
477
478 // This will watch messages sent to the provided channel.
479 //
Brian Silverman454bc112020-03-05 14:21:25 -0800480 // w must have a non-polymorphic operator() (aka it can only be called with a
481 // single set of arguments; no overloading or templates). It must be callable
482 // with this signature:
483 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484 //
Brian Silverman454bc112020-03-05 14:21:25 -0800485 // Lambdas are a common form for w. A std::function will work too.
486 //
487 // Note that bind expressions have polymorphic call operators, so they are not
488 // allowed.
489 //
490 // We template Watch as a whole instead of using std::function<void(const T
491 // &)> to allow deducing MessageType from lambdas and other things which are
492 // implicitly convertible to std::function, but not actually std::function
493 // instantiations. Template deduction guides might allow solving this
494 // differently in newer versions of C++, but those have their own corner
495 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800497 void MakeWatcher(const std::string_view channel_name, Watch &&w);
498
499 // Like MakeWatcher, but doesn't have access to the message data. This may be
500 // implemented to use less resources than an equivalent MakeWatcher.
501 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800502 // The function will still have access to context(), although that will have
503 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800504 template <typename MessageType>
505 void MakeNoArgWatcher(const std::string_view channel_name,
506 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507
508 // The passed in function will be called when the event loop starts.
509 // Use this to run code once the thread goes into "real-time-mode",
510 virtual void OnRun(::std::function<void()> on_run) = 0;
511
Austin Schuh217a9782019-12-21 23:02:50 -0800512 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800513 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514
Austin Schuh217a9782019-12-21 23:02:50 -0800515 // Returns the node that this event loop is running on. Returns nullptr if we
516 // are running in single-node mode.
517 virtual const Node *node() const = 0;
518
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519 // Creates a timer that executes callback when the timer expires
520 // Returns a TimerHandle for configuration of the timer
521 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
522
523 // Creates a timer that executes callback periodically at the specified
524 // interval and offset. Returns a PhasedLoopHandler for interacting with the
525 // timer.
526 virtual PhasedLoopHandler *AddPhasedLoop(
527 ::std::function<void(int)> callback,
528 const monotonic_clock::duration interval,
529 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
530
Austin Schuh217a9782019-12-21 23:02:50 -0800531 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532
533 // Threadsafe.
534 bool is_running() const { return is_running_.load(); }
535
536 // Sets the scheduler priority to run the event loop at. This may not be
537 // called after we go into "real-time-mode".
538 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540
Austin Schuh217a9782019-12-21 23:02:50 -0800541 // Fetches new messages from the provided channel (path, type).
542 //
543 // Note: this channel must be a member of the exact configuration object this
544 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
546 const Channel *channel) = 0;
547
Austin Schuh217a9782019-12-21 23:02:50 -0800548 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549 virtual void MakeRawWatcher(
550 const Channel *channel,
551 std::function<void(const Context &context, const void *message)>
552 watcher) = 0;
553
Brian Silverman454bc112020-03-05 14:21:25 -0800554 // Watches channel (name, type) for new messages, without needing to extract
555 // the message contents. Default implementation simply re-uses MakeRawWatcher.
556 virtual void MakeRawNoArgWatcher(
557 const Channel *channel,
558 std::function<void(const Context &context)> watcher) {
559 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800560 Context new_context = context;
561 new_context.data = nullptr;
562 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800563 });
564 }
565
Austin Schuh217a9782019-12-21 23:02:50 -0800566 // Creates a raw sender for the provided channel. This is used for reflection
567 // based sending.
568 // Note: this ignores any node constraints. Ignore at your own peril.
569 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
570
Austin Schuh6231cc32019-12-07 13:06:15 -0800571 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572 const Context &context() const { return context_; }
573
574 // Returns the configuration that this event loop was built with.
575 const Configuration *configuration() const { return configuration_; }
576
Austin Schuh39788ff2019-12-01 18:22:57 -0800577 // Prevents the event loop from sending a timing report.
578 void SkipTimingReport() { skip_timing_report_ = true; }
579
Tyler Chatow67ddb032020-01-12 14:30:04 -0800580 // Prevents AOS_LOG being sent to message on /aos
581 void SkipAosLog() { skip_logger_ = true; }
582
Alex Perrycb7da4b2019-08-28 19:35:56 -0700583 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800584 // Sets the name of the event loop. This is the application name.
585 virtual void set_name(const std::string_view name) = 0;
586
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587 void set_is_running(bool value) { is_running_.store(value); }
588
Austin Schuh39788ff2019-12-01 18:22:57 -0800589 // Validates that channel exists inside configuration_ and finds its index.
590 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591
Brian Silverman5120afb2020-01-31 17:44:35 -0800592 // Returns the state for the watcher on the corresponding channel. This
593 // watcher must exist before calling this.
594 WatcherState *GetWatcherState(const Channel *channel);
595
596 // Returns a Sender's protected RawSender
597 template <typename T>
598 static RawSender *GetRawSender(aos::Sender<T> *sender) {
599 return sender->sender_.get();
600 }
601
Austin Schuh6231cc32019-12-07 13:06:15 -0800602 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 Context context_;
604
Austin Schuh39788ff2019-12-01 18:22:57 -0800605 friend class RawSender;
606 friend class TimerHandler;
607 friend class RawFetcher;
608 friend class PhasedLoopHandler;
609 friend class WatcherState;
610
611 // Methods used to implement timing reports.
612 void NewSender(RawSender *sender);
613 void DeleteSender(RawSender *sender);
614 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
615 PhasedLoopHandler *NewPhasedLoop(
616 std::unique_ptr<PhasedLoopHandler> phased_loop);
617 void NewFetcher(RawFetcher *fetcher);
618 void DeleteFetcher(RawFetcher *fetcher);
619 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
620
Brian Silverman0fc69932020-01-24 21:54:02 -0800621 // Tracks that we have a (single) watcher on the given channel.
622 void TakeWatcher(const Channel *channel);
623 // Tracks that we have at least one sender on the given channel.
624 void TakeSender(const Channel *channel);
625
Austin Schuh39788ff2019-12-01 18:22:57 -0800626 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800627 std::vector<RawFetcher *> fetchers_;
628
Austin Schuh39788ff2019-12-01 18:22:57 -0800629 std::vector<std::unique_ptr<TimerHandler>> timers_;
630 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800631 std::vector<std::unique_ptr<WatcherState>> watchers_;
632
633 void SendTimingReport();
634 void UpdateTimingReport();
635 void MaybeScheduleTimingReports();
636
637 std::unique_ptr<RawSender> timing_report_sender_;
638
Austin Schuh7d87b672019-12-01 20:23:49 -0800639 // Tracks which event sources (timers and watchers) have data, and which
640 // don't. Added events may not change their event_time().
641 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
642 // t2 to run, t2 should then be picked up without a context switch.
643 void AddEvent(EventLoopEvent *event);
644 void RemoveEvent(EventLoopEvent *event);
645 size_t EventCount() const { return events_.size(); }
646 EventLoopEvent *PopEvent();
647 EventLoopEvent *PeekEvent() { return events_.front(); }
648 void ReserveEvents();
649
650 std::vector<EventLoopEvent *> events_;
651
Tyler Chatow67ddb032020-01-12 14:30:04 -0800652 // If true, don't send AOS_LOG to /aos
653 bool skip_logger_ = false;
654
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800655 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800656 virtual pid_t GetTid() = 0;
657
658 FlatbufferDetachedBuffer<timing::Report> timing_report_;
659
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800660 ::std::atomic<bool> is_running_{false};
661
Alex Perrycb7da4b2019-08-28 19:35:56 -0700662 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800663
664 // If true, don't send out timing reports.
665 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800666
667 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700668};
669
670} // namespace aos
671
672#include "aos/events/event_loop_tmpl.h"
673
674#endif // AOS_EVENTS_EVENT_LOOP_H