blob: 81dfe42a22e23a6572b648996a96248911da80c7 [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
Brian Silverman6a54ff32020-04-28 16:41:39 -07004#include <sched.h>
5
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <atomic>
7#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08008#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07009
Alex Perrycb7da4b2019-08-28 19:35:56 -070010#include "aos/configuration.h"
11#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080012#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080013#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080014#include "aos/events/event_loop_generated.h"
15#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050017#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080018#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/json_to_flatbuffer.h"
20#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080021#include "aos/util/phased_loop.h"
Brian Silverman0fc69932020-01-24 21:54:02 -080022
23#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070024#include "flatbuffers/flatbuffers.h"
25#include "glog/logging.h"
26
Austin Schuh39788ff2019-12-01 18:22:57 -080027DECLARE_bool(timing_reports);
28DECLARE_int32(timing_report_ms);
29
Alex Perrycb7da4b2019-08-28 19:35:56 -070030namespace aos {
31
Austin Schuh39788ff2019-12-01 18:22:57 -080032class EventLoop;
33class WatcherState;
34
Austin Schuh6231cc32019-12-07 13:06:15 -080035// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
36// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070037struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080038 // Time that the message was sent on this node, or the timer was triggered.
39 monotonic_clock::time_point monotonic_event_time;
40 // Realtime the message was sent on this node. This is set to min_time for
41 // Timers and PhasedLoops.
42 realtime_clock::time_point realtime_event_time;
43
44 // For a single-node configuration, these two are identical to *_event_time.
45 // In a multinode configuration, these are the times that the message was
46 // sent on the original node.
47 monotonic_clock::time_point monotonic_remote_time;
48 realtime_clock::time_point realtime_remote_time;
49
Austin Schuh6231cc32019-12-07 13:06:15 -080050 // The rest are only valid for Watchers and Fetchers.
Alex Perrycb7da4b2019-08-28 19:35:56 -070051 // Index in the queue.
52 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080053 // Index into the remote queue. Useful to determine if data was lost. In a
54 // single-node configuration, this will match queue_index.
55 uint32_t remote_queue_index;
56
Alex Perrycb7da4b2019-08-28 19:35:56 -070057 // Size of the data sent.
58 size_t size;
59 // Pointer to the data.
60 void *data;
61};
62
63// Raw version of fetcher. Contains a local variable that the fetcher will
64// update. This is used for reflection and as an interface to implement typed
65// fetchers.
66class RawFetcher {
67 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080068 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070069 RawFetcher(const RawFetcher &) = delete;
70 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080071 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070072
Austin Schuh39788ff2019-12-01 18:22:57 -080073 // Fetches the next message in the queue without blocking. Returns true if
74 // there was a new message and we got it.
75 bool FetchNext();
76
77 // Fetches the latest message without blocking.
78 bool Fetch();
79
80 // Returns the channel this fetcher uses.
81 const Channel *channel() const { return channel_; }
82 // Returns the context for the current message.
83 const Context &context() const { return context_; }
84
85 protected:
86 EventLoop *event_loop() { return event_loop_; }
87
Alex Perrycb7da4b2019-08-28 19:35:56 -070088 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080089
90 private:
91 friend class EventLoop;
92 // Implementation
93 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
94 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
95
Brian Silverman79ec7fc2020-06-08 20:11:22 -050096 EventLoop *const event_loop_;
97 const Channel *const channel_;
98 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080099
100 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500101 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102};
103
104// Raw version of sender. Sends a block of data. This is used for reflection
105// and as a building block to implement typed senders.
106class RawSender {
107 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800108 RawSender(EventLoop *event_loop, const Channel *channel);
109 RawSender(const RawSender &) = delete;
110 RawSender &operator=(const RawSender &) = delete;
111
112 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
114 // Sends a message without copying it. The users starts by copying up to
115 // size() bytes into the data backed by data(). They then call Send to send.
116 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800117 // If provided, monotonic_remote_time, realtime_remote_time, and
118 // remote_queue_index are attached to the message and are available in the
119 // context on the read side. If they are not populated, the read side will
120 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 virtual void *data() = 0;
122 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800123 bool Send(size_t size,
124 aos::monotonic_clock::time_point monotonic_remote_time =
125 aos::monotonic_clock::min_time,
126 aos::realtime_clock::time_point realtime_remote_time =
127 aos::realtime_clock::min_time,
128 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700129
130 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800131 // The remote arguments have the same meaning as in Send above.
132 bool Send(const void *data, size_t size,
133 aos::monotonic_clock::time_point monotonic_remote_time =
134 aos::monotonic_clock::min_time,
135 aos::realtime_clock::time_point realtime_remote_time =
136 aos::realtime_clock::min_time,
137 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700138
Austin Schuh54cf95f2019-11-29 13:14:18 -0800139 const Channel *channel() const { return channel_; }
140
Austin Schuhad154822019-12-27 15:45:13 -0800141 // Returns the time_points that the last message was sent at.
142 aos::monotonic_clock::time_point monotonic_sent_time() const {
143 return monotonic_sent_time_;
144 }
145 aos::realtime_clock::time_point realtime_sent_time() const {
146 return realtime_sent_time_;
147 }
148 // Returns the queue index that this was sent with.
149 uint32_t sent_queue_index() const { return sent_queue_index_; }
150
Brian Silvermana1652f32020-01-29 20:41:44 -0800151 // Returns the associated flatbuffers-style allocator. This must be
152 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800153 ChannelPreallocatedAllocator *fbb_allocator() {
154 fbb_allocator_ = ChannelPreallocatedAllocator(
155 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800156 return &fbb_allocator_;
157 }
158
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800160 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800161
Austin Schuhad154822019-12-27 15:45:13 -0800162 aos::monotonic_clock::time_point monotonic_sent_time_ =
163 aos::monotonic_clock::min_time;
164 aos::realtime_clock::time_point realtime_sent_time_ =
165 aos::realtime_clock::min_time;
166 uint32_t sent_queue_index_ = 0xffffffff;
167
Austin Schuh39788ff2019-12-01 18:22:57 -0800168 private:
169 friend class EventLoop;
170
Austin Schuhad154822019-12-27 15:45:13 -0800171 virtual bool DoSend(const void *data, size_t size,
172 aos::monotonic_clock::time_point monotonic_remote_time,
173 aos::realtime_clock::time_point realtime_remote_time,
174 uint32_t remote_queue_index) = 0;
175 virtual bool DoSend(size_t size,
176 aos::monotonic_clock::time_point monotonic_remote_time,
177 aos::realtime_clock::time_point realtime_remote_time,
178 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800179
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500180 EventLoop *const event_loop_;
181 const Channel *const channel_;
182 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183
Austin Schuh39788ff2019-12-01 18:22:57 -0800184 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500185 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800186
Austin Schuh1af273d2020-03-07 20:11:34 -0800187 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800188};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189
190// Fetches the newest message from a channel.
191// This provides a polling based interface for channels.
192template <typename T>
193class Fetcher {
194 public:
195 Fetcher() {}
196
197 // Fetches the next message. Returns true if it fetched a new message. This
198 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800199 bool FetchNext() {
200 const bool result = fetcher_->FetchNext();
201 if (result) {
202 CheckChannelDataAlignment(fetcher_->context().data,
203 fetcher_->context().size);
204 }
205 return result;
206 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700207
208 // Fetches the most recent message. Returns true if it fetched a new message.
209 // This will return the latest message regardless of if it was sent before or
210 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800211 bool Fetch() {
212 const bool result = fetcher_->Fetch();
213 if (result) {
214 CheckChannelDataAlignment(fetcher_->context().data,
215 fetcher_->context().size);
216 }
217 return result;
218 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700219
220 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
221 // available message.
222 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800223 return fetcher_->context().data != nullptr
224 ? flatbuffers::GetRoot<T>(
225 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700226 : nullptr;
227 }
228
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700229 // Returns the channel this fetcher uses
230 const Channel *channel() const { return fetcher_->channel(); }
231
Alex Perrycb7da4b2019-08-28 19:35:56 -0700232 // Returns the context holding timestamps and other metadata about the
233 // message.
234 const Context &context() const { return fetcher_->context(); }
235
236 const T &operator*() const { return *get(); }
237 const T *operator->() const { return get(); }
238
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700239 // Returns true if this fetcher is valid and connected to a channel.
240 operator bool() const { return static_cast<bool>(fetcher_); }
241
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242 private:
243 friend class EventLoop;
244 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
245 : fetcher_(::std::move(fetcher)) {}
246 ::std::unique_ptr<RawFetcher> fetcher_;
247};
248
249// Sends messages to a channel.
250template <typename T>
251class Sender {
252 public:
253 Sender() {}
254
255 // Represents a single message about to be sent to the queue.
256 // The lifecycle goes:
257 //
258 // Builder builder = sender.MakeBuilder();
259 // T::Builder t_builder = builder.MakeBuilder<T>();
260 // Populate(&t_builder);
261 // builder.Send(t_builder.Finish());
262 class Builder {
263 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800264 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800265 : fbb_(allocator->size(), allocator),
266 allocator_(allocator),
267 sender_(sender) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800268 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800269 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800271 Builder() {}
272 Builder(const Builder &) = delete;
273 Builder(Builder &&) = default;
274
275 Builder &operator=(const Builder &) = delete;
276 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277
278 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
279
280 template <typename T2>
281 typename T2::Builder MakeBuilder() {
282 return typename T2::Builder(fbb_);
283 }
284
285 bool Send(flatbuffers::Offset<T> offset) {
286 fbb_.Finish(offset);
Brian Silverman9dd793b2020-01-31 23:52:21 -0800287 const bool result = sender_->Send(fbb_.GetSize());
288 // Ensure fbb_ knows it shouldn't access the memory any more.
289 fbb_ = flatbuffers::FlatBufferBuilder();
290 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 }
292
293 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800294 void CheckSent() {
295 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
296 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297
298 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800300 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301 RawSender *sender_;
302 };
303
304 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800305 //
306 // Only a single one of these may be "alive" for this object at any point in
307 // time. After calling Send on the result, it is no longer "alive". This means
308 // that you must manually reset a variable holding the return value (by
309 // assigning a default-constructed Builder to it) before calling this method
310 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311 Builder MakeBuilder();
312
Austin Schuha28cbc32019-12-27 16:28:04 -0800313 // Sends a prebuilt flatbuffer.
314 bool Send(const Flatbuffer<T> &flatbuffer);
315
Austin Schuh39788ff2019-12-01 18:22:57 -0800316 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800317 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700318
Brian Silverman454bc112020-03-05 14:21:25 -0800319 operator bool() { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800320
Austin Schuh7bc59052020-02-16 23:48:33 -0800321 // Returns the time_points that the last message was sent at.
322 aos::monotonic_clock::time_point monotonic_sent_time() const {
323 return sender_->monotonic_sent_time();
324 }
325 aos::realtime_clock::time_point realtime_sent_time() const {
326 return sender_->realtime_sent_time();
327 }
328 // Returns the queue index that this was sent with.
329 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
330
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 private:
332 friend class EventLoop;
333 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
334 std::unique_ptr<RawSender> sender_;
335};
336
337// Interface for timers
338class TimerHandler {
339 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800340 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700341
342 // Timer should sleep until base, base + offset, base + offset * 2, ...
343 // If repeat_offset isn't set, the timer only expires once.
344 virtual void Setup(monotonic_clock::time_point base,
345 monotonic_clock::duration repeat_offset =
346 ::aos::monotonic_clock::zero()) = 0;
347
348 // Stop future calls to callback().
349 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800350
351 // Sets and gets the name of the timer. Set this if you want a descriptive
352 // name in the timing report.
353 void set_name(std::string_view name) { name_ = std::string(name); }
354 const std::string_view name() const { return name_; }
355
Austin Schuh39788ff2019-12-01 18:22:57 -0800356 protected:
357 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
358
Austin Schuhcde39fd2020-02-22 20:58:24 -0800359 monotonic_clock::time_point Call(
360 std::function<monotonic_clock::time_point()> get_time,
361 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800362
Austin Schuh1540c2f2019-11-29 21:59:29 -0800363 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800364 friend class EventLoop;
365
366 EventLoop *event_loop_;
367 // The function to call when Call is called.
368 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800369 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800370
371 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500372 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373};
374
375// Interface for phased loops. They are built on timers.
376class PhasedLoopHandler {
377 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800378 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700379
380 // Sets the interval and offset. Any changes to interval and offset only take
381 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800382 void set_interval_and_offset(const monotonic_clock::duration interval,
383 const monotonic_clock::duration offset) {
384 phased_loop_.set_interval_and_offset(interval, offset);
385 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800386
387 // Sets and gets the name of the timer. Set this if you want a descriptive
388 // name in the timing report.
389 void set_name(std::string_view name) { name_ = std::string(name); }
390 const std::string_view name() const { return name_; }
391
Austin Schuh39788ff2019-12-01 18:22:57 -0800392 protected:
393 void Call(std::function<monotonic_clock::time_point()> get_time,
394 std::function<void(monotonic_clock::time_point)> schedule);
395
396 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
397 const monotonic_clock::duration interval,
398 const monotonic_clock::duration offset);
399
Austin Schuh1540c2f2019-11-29 21:59:29 -0800400 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 friend class EventLoop;
402
403 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
404 monotonic_clock::time_point monotonic_now) {
405 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
406 schedule(phased_loop_.sleep_time());
407 }
408
409 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
410
411 EventLoop *event_loop_;
412 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800413 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800414 time::PhasedLoop phased_loop_;
415
416 int cycles_elapsed_ = 0;
417
418 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500419 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420};
421
Brian Silverman6a54ff32020-04-28 16:41:39 -0700422inline cpu_set_t MakeCpusetFromCpus(std::initializer_list<int> cpus) {
423 cpu_set_t result;
424 CPU_ZERO(&result);
425 for (int cpu : cpus) {
426 CPU_SET(cpu, &result);
427 }
428 return result;
429}
430
Alex Perrycb7da4b2019-08-28 19:35:56 -0700431class EventLoop {
432 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800433 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434
Austin Schuh39788ff2019-12-01 18:22:57 -0800435 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436
437 // Current time.
438 virtual monotonic_clock::time_point monotonic_now() = 0;
439 virtual realtime_clock::time_point realtime_now() = 0;
440
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700441 // Returns true if the channel exists in the configuration.
442 template <typename T>
443 bool HasChannel(const std::string_view channel_name) {
444 return configuration::GetChannel(configuration_, channel_name,
445 T::GetFullyQualifiedName(), name(),
446 node()) != nullptr;
447 }
448
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449 // Note, it is supported to create:
450 // multiple fetchers, and (one sender or one watcher) per <name, type>
451 // tuple.
452
453 // Makes a class that will always fetch the most recent value
454 // sent to the provided channel.
455 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800456 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800457 const Channel *channel =
458 configuration::GetChannel(configuration_, channel_name,
459 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 CHECK(channel != nullptr)
461 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
462 << T::GetFullyQualifiedName() << "\" } not found in config.";
463
Austin Schuhca4828c2019-12-28 14:21:35 -0800464 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
465 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
466 << "\", \"type\": \"" << T::GetFullyQualifiedName()
467 << "\" } is not able to be fetched on this node. Check your "
468 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800469 }
470
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471 return Fetcher<T>(MakeRawFetcher(channel));
472 }
473
474 // Makes class that allows constructing and sending messages to
475 // the provided channel.
476 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800477 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800478 const Channel *channel =
479 configuration::GetChannel(configuration_, channel_name,
480 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 CHECK(channel != nullptr)
482 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800483 << T::GetFullyQualifiedName() << "\" } not found in config for "
484 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485
Austin Schuhca4828c2019-12-28 14:21:35 -0800486 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
487 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
488 << "\", \"type\": \"" << T::GetFullyQualifiedName()
489 << "\" } is not able to be sent on this node. Check your "
490 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800491 }
492
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 return Sender<T>(MakeRawSender(channel));
494 }
495
496 // This will watch messages sent to the provided channel.
497 //
Brian Silverman454bc112020-03-05 14:21:25 -0800498 // w must have a non-polymorphic operator() (aka it can only be called with a
499 // single set of arguments; no overloading or templates). It must be callable
500 // with this signature:
501 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502 //
Brian Silverman454bc112020-03-05 14:21:25 -0800503 // Lambdas are a common form for w. A std::function will work too.
504 //
505 // Note that bind expressions have polymorphic call operators, so they are not
506 // allowed.
507 //
508 // We template Watch as a whole instead of using std::function<void(const T
509 // &)> to allow deducing MessageType from lambdas and other things which are
510 // implicitly convertible to std::function, but not actually std::function
511 // instantiations. Template deduction guides might allow solving this
512 // differently in newer versions of C++, but those have their own corner
513 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800515 void MakeWatcher(const std::string_view channel_name, Watch &&w);
516
517 // Like MakeWatcher, but doesn't have access to the message data. This may be
518 // implemented to use less resources than an equivalent MakeWatcher.
519 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800520 // The function will still have access to context(), although that will have
521 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800522 template <typename MessageType>
523 void MakeNoArgWatcher(const std::string_view channel_name,
524 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525
526 // The passed in function will be called when the event loop starts.
527 // Use this to run code once the thread goes into "real-time-mode",
528 virtual void OnRun(::std::function<void()> on_run) = 0;
529
Austin Schuh217a9782019-12-21 23:02:50 -0800530 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800531 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532
Austin Schuh217a9782019-12-21 23:02:50 -0800533 // Returns the node that this event loop is running on. Returns nullptr if we
534 // are running in single-node mode.
535 virtual const Node *node() const = 0;
536
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 // Creates a timer that executes callback when the timer expires
538 // Returns a TimerHandle for configuration of the timer
539 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
540
541 // Creates a timer that executes callback periodically at the specified
542 // interval and offset. Returns a PhasedLoopHandler for interacting with the
543 // timer.
544 virtual PhasedLoopHandler *AddPhasedLoop(
545 ::std::function<void(int)> callback,
546 const monotonic_clock::duration interval,
547 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
548
Austin Schuh217a9782019-12-21 23:02:50 -0800549 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550
551 // Threadsafe.
552 bool is_running() const { return is_running_.load(); }
553
554 // Sets the scheduler priority to run the event loop at. This may not be
555 // called after we go into "real-time-mode".
556 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558
Brian Silverman6a54ff32020-04-28 16:41:39 -0700559 // Sets the scheduler affinity to run the event loop with. This may only be
560 // called before Run().
561 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
562
Austin Schuh217a9782019-12-21 23:02:50 -0800563 // Fetches new messages from the provided channel (path, type).
564 //
565 // Note: this channel must be a member of the exact configuration object this
566 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
568 const Channel *channel) = 0;
569
Austin Schuh217a9782019-12-21 23:02:50 -0800570 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571 virtual void MakeRawWatcher(
572 const Channel *channel,
573 std::function<void(const Context &context, const void *message)>
574 watcher) = 0;
575
Brian Silverman454bc112020-03-05 14:21:25 -0800576 // Watches channel (name, type) for new messages, without needing to extract
577 // the message contents. Default implementation simply re-uses MakeRawWatcher.
578 virtual void MakeRawNoArgWatcher(
579 const Channel *channel,
580 std::function<void(const Context &context)> watcher) {
581 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800582 Context new_context = context;
583 new_context.data = nullptr;
584 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800585 });
586 }
587
Austin Schuh217a9782019-12-21 23:02:50 -0800588 // Creates a raw sender for the provided channel. This is used for reflection
589 // based sending.
590 // Note: this ignores any node constraints. Ignore at your own peril.
591 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
592
Austin Schuh6231cc32019-12-07 13:06:15 -0800593 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594 const Context &context() const { return context_; }
595
596 // Returns the configuration that this event loop was built with.
597 const Configuration *configuration() const { return configuration_; }
598
Austin Schuh39788ff2019-12-01 18:22:57 -0800599 // Prevents the event loop from sending a timing report.
600 void SkipTimingReport() { skip_timing_report_ = true; }
601
Tyler Chatow67ddb032020-01-12 14:30:04 -0800602 // Prevents AOS_LOG being sent to message on /aos
603 void SkipAosLog() { skip_logger_ = true; }
604
Alex Perrycb7da4b2019-08-28 19:35:56 -0700605 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800606 // Sets the name of the event loop. This is the application name.
607 virtual void set_name(const std::string_view name) = 0;
608
Alex Perrycb7da4b2019-08-28 19:35:56 -0700609 void set_is_running(bool value) { is_running_.store(value); }
610
Austin Schuh39788ff2019-12-01 18:22:57 -0800611 // Validates that channel exists inside configuration_ and finds its index.
612 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700613
Brian Silverman5120afb2020-01-31 17:44:35 -0800614 // Returns the state for the watcher on the corresponding channel. This
615 // watcher must exist before calling this.
616 WatcherState *GetWatcherState(const Channel *channel);
617
Brian Silverman6d2b3592020-06-18 14:40:15 -0700618 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800619 template <typename T>
620 static RawSender *GetRawSender(aos::Sender<T> *sender) {
621 return sender->sender_.get();
622 }
623
Brian Silverman6d2b3592020-06-18 14:40:15 -0700624 // Returns a Fetcher's protected RawFetcher.
625 template <typename T>
626 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
627 return fetcher->fetcher_.get();
628 }
629
Austin Schuh6231cc32019-12-07 13:06:15 -0800630 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631 Context context_;
632
Austin Schuh39788ff2019-12-01 18:22:57 -0800633 friend class RawSender;
634 friend class TimerHandler;
635 friend class RawFetcher;
636 friend class PhasedLoopHandler;
637 friend class WatcherState;
638
639 // Methods used to implement timing reports.
640 void NewSender(RawSender *sender);
641 void DeleteSender(RawSender *sender);
642 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
643 PhasedLoopHandler *NewPhasedLoop(
644 std::unique_ptr<PhasedLoopHandler> phased_loop);
645 void NewFetcher(RawFetcher *fetcher);
646 void DeleteFetcher(RawFetcher *fetcher);
647 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
648
Brian Silverman0fc69932020-01-24 21:54:02 -0800649 // Tracks that we have a (single) watcher on the given channel.
650 void TakeWatcher(const Channel *channel);
651 // Tracks that we have at least one sender on the given channel.
652 void TakeSender(const Channel *channel);
653
Austin Schuh39788ff2019-12-01 18:22:57 -0800654 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800655 std::vector<RawFetcher *> fetchers_;
656
Austin Schuh39788ff2019-12-01 18:22:57 -0800657 std::vector<std::unique_ptr<TimerHandler>> timers_;
658 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800659 std::vector<std::unique_ptr<WatcherState>> watchers_;
660
661 void SendTimingReport();
662 void UpdateTimingReport();
663 void MaybeScheduleTimingReports();
664
665 std::unique_ptr<RawSender> timing_report_sender_;
666
Austin Schuh7d87b672019-12-01 20:23:49 -0800667 // Tracks which event sources (timers and watchers) have data, and which
668 // don't. Added events may not change their event_time().
669 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
670 // t2 to run, t2 should then be picked up without a context switch.
671 void AddEvent(EventLoopEvent *event);
672 void RemoveEvent(EventLoopEvent *event);
673 size_t EventCount() const { return events_.size(); }
674 EventLoopEvent *PopEvent();
675 EventLoopEvent *PeekEvent() { return events_.front(); }
676 void ReserveEvents();
677
678 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700679 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800680
Tyler Chatow67ddb032020-01-12 14:30:04 -0800681 // If true, don't send AOS_LOG to /aos
682 bool skip_logger_ = false;
683
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800684 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800685 virtual pid_t GetTid() = 0;
686
687 FlatbufferDetachedBuffer<timing::Report> timing_report_;
688
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800689 ::std::atomic<bool> is_running_{false};
690
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800692
693 // If true, don't send out timing reports.
694 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800695
696 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700697};
698
699} // namespace aos
700
701#include "aos/events/event_loop_tmpl.h"
702
703#endif // AOS_EVENTS_EVENT_LOOP_H