blob: 1ad5c905c4275bae43736a8bf06165be12812340 [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.
Brian Silvermaneaa41d62020-07-08 19:47:35 -070060 const void *data;
Alex Perrycb7da4b2019-08-28 19:35:56 -070061};
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
Brian Silverman341b57e2020-06-23 16:23:18 -0700298 // Detaches a buffer, for later use calling Sender::Send directly.
299 //
300 // Note that the underlying memory remains with the Sender, so creating
301 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
302 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
303 fbb_.Finish(offset);
304 return fbb_.Release();
305 }
306
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800309 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310 RawSender *sender_;
311 };
312
313 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800314 //
315 // Only a single one of these may be "alive" for this object at any point in
316 // time. After calling Send on the result, it is no longer "alive". This means
317 // that you must manually reset a variable holding the return value (by
318 // assigning a default-constructed Builder to it) before calling this method
319 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 Builder MakeBuilder();
321
Austin Schuha28cbc32019-12-27 16:28:04 -0800322 // Sends a prebuilt flatbuffer.
323 bool Send(const Flatbuffer<T> &flatbuffer);
324
Brian Silverman341b57e2020-06-23 16:23:18 -0700325 // Sends a prebuilt flatbuffer which was detached from a Builder created via
326 // MakeBuilder() on this object.
327 bool SendDetached(FlatbufferDetachedBuffer<T> detached);
328
Austin Schuh39788ff2019-12-01 18:22:57 -0800329 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800330 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331
Brian Silverman454bc112020-03-05 14:21:25 -0800332 operator bool() { return sender_ ? true : false; }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800333
Austin Schuh7bc59052020-02-16 23:48:33 -0800334 // Returns the time_points that the last message was sent at.
335 aos::monotonic_clock::time_point monotonic_sent_time() const {
336 return sender_->monotonic_sent_time();
337 }
338 aos::realtime_clock::time_point realtime_sent_time() const {
339 return sender_->realtime_sent_time();
340 }
341 // Returns the queue index that this was sent with.
342 uint32_t sent_queue_index() const { return sender_->sent_queue_index(); }
343
Alex Perrycb7da4b2019-08-28 19:35:56 -0700344 private:
345 friend class EventLoop;
346 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
347 std::unique_ptr<RawSender> sender_;
348};
349
350// Interface for timers
351class TimerHandler {
352 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800353 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
355 // Timer should sleep until base, base + offset, base + offset * 2, ...
356 // If repeat_offset isn't set, the timer only expires once.
357 virtual void Setup(monotonic_clock::time_point base,
358 monotonic_clock::duration repeat_offset =
359 ::aos::monotonic_clock::zero()) = 0;
360
361 // Stop future calls to callback().
362 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800363
364 // Sets and gets the name of the timer. Set this if you want a descriptive
365 // name in the timing report.
366 void set_name(std::string_view name) { name_ = std::string(name); }
367 const std::string_view name() const { return name_; }
368
Austin Schuh39788ff2019-12-01 18:22:57 -0800369 protected:
370 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
371
Austin Schuhcde39fd2020-02-22 20:58:24 -0800372 monotonic_clock::time_point Call(
373 std::function<monotonic_clock::time_point()> get_time,
374 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800375
Austin Schuh1540c2f2019-11-29 21:59:29 -0800376 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800377 friend class EventLoop;
378
379 EventLoop *event_loop_;
380 // The function to call when Call is called.
381 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800382 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800383
384 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500385 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700386};
387
388// Interface for phased loops. They are built on timers.
389class PhasedLoopHandler {
390 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800391 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700392
393 // Sets the interval and offset. Any changes to interval and offset only take
394 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 void set_interval_and_offset(const monotonic_clock::duration interval,
396 const monotonic_clock::duration offset) {
397 phased_loop_.set_interval_and_offset(interval, offset);
398 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800399
400 // Sets and gets the name of the timer. Set this if you want a descriptive
401 // name in the timing report.
402 void set_name(std::string_view name) { name_ = std::string(name); }
403 const std::string_view name() const { return name_; }
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 protected:
406 void Call(std::function<monotonic_clock::time_point()> get_time,
407 std::function<void(monotonic_clock::time_point)> schedule);
408
409 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
410 const monotonic_clock::duration interval,
411 const monotonic_clock::duration offset);
412
Austin Schuh1540c2f2019-11-29 21:59:29 -0800413 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800414 friend class EventLoop;
415
416 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
417 monotonic_clock::time_point monotonic_now) {
418 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
419 schedule(phased_loop_.sleep_time());
420 }
421
422 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
423
424 EventLoop *event_loop_;
425 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800426 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800427 time::PhasedLoop phased_loop_;
428
429 int cycles_elapsed_ = 0;
430
431 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500432 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433};
434
Brian Silverman6a54ff32020-04-28 16:41:39 -0700435inline cpu_set_t MakeCpusetFromCpus(std::initializer_list<int> cpus) {
436 cpu_set_t result;
437 CPU_ZERO(&result);
438 for (int cpu : cpus) {
439 CPU_SET(cpu, &result);
440 }
441 return result;
442}
443
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444class EventLoop {
445 public:
Tyler Chatow67ddb032020-01-12 14:30:04 -0800446 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447
Austin Schuh39788ff2019-12-01 18:22:57 -0800448 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449
450 // Current time.
451 virtual monotonic_clock::time_point monotonic_now() = 0;
452 virtual realtime_clock::time_point realtime_now() = 0;
453
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700454 // Returns true if the channel exists in the configuration.
455 template <typename T>
456 bool HasChannel(const std::string_view channel_name) {
457 return configuration::GetChannel(configuration_, channel_name,
458 T::GetFullyQualifiedName(), name(),
459 node()) != nullptr;
460 }
461
Alex Perrycb7da4b2019-08-28 19:35:56 -0700462 // Note, it is supported to create:
463 // multiple fetchers, and (one sender or one watcher) per <name, type>
464 // tuple.
465
466 // Makes a class that will always fetch the most recent value
467 // sent to the provided channel.
468 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800469 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800470 const Channel *channel =
471 configuration::GetChannel(configuration_, channel_name,
472 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700473 CHECK(channel != nullptr)
474 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
475 << T::GetFullyQualifiedName() << "\" } not found in config.";
476
Austin Schuhca4828c2019-12-28 14:21:35 -0800477 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
478 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
479 << "\", \"type\": \"" << T::GetFullyQualifiedName()
480 << "\" } is not able to be fetched on this node. Check your "
481 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800482 }
483
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484 return Fetcher<T>(MakeRawFetcher(channel));
485 }
486
487 // Makes class that allows constructing and sending messages to
488 // the provided channel.
489 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800490 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800491 const Channel *channel =
492 configuration::GetChannel(configuration_, channel_name,
493 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 CHECK(channel != nullptr)
495 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800496 << T::GetFullyQualifiedName() << "\" } not found in config for "
497 << name() << ".";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498
Austin Schuhca4828c2019-12-28 14:21:35 -0800499 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
500 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
501 << "\", \"type\": \"" << T::GetFullyQualifiedName()
502 << "\" } is not able to be sent on this node. Check your "
503 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800504 }
505
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506 return Sender<T>(MakeRawSender(channel));
507 }
508
509 // This will watch messages sent to the provided channel.
510 //
Brian Silverman454bc112020-03-05 14:21:25 -0800511 // w must have a non-polymorphic operator() (aka it can only be called with a
512 // single set of arguments; no overloading or templates). It must be callable
513 // with this signature:
514 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515 //
Brian Silverman454bc112020-03-05 14:21:25 -0800516 // Lambdas are a common form for w. A std::function will work too.
517 //
518 // Note that bind expressions have polymorphic call operators, so they are not
519 // allowed.
520 //
521 // We template Watch as a whole instead of using std::function<void(const T
522 // &)> to allow deducing MessageType from lambdas and other things which are
523 // implicitly convertible to std::function, but not actually std::function
524 // instantiations. Template deduction guides might allow solving this
525 // differently in newer versions of C++, but those have their own corner
526 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700527 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800528 void MakeWatcher(const std::string_view channel_name, Watch &&w);
529
530 // Like MakeWatcher, but doesn't have access to the message data. This may be
531 // implemented to use less resources than an equivalent MakeWatcher.
532 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800533 // The function will still have access to context(), although that will have
534 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800535 template <typename MessageType>
536 void MakeNoArgWatcher(const std::string_view channel_name,
537 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538
539 // The passed in function will be called when the event loop starts.
540 // Use this to run code once the thread goes into "real-time-mode",
541 virtual void OnRun(::std::function<void()> on_run) = 0;
542
Austin Schuh217a9782019-12-21 23:02:50 -0800543 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800544 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545
Austin Schuh217a9782019-12-21 23:02:50 -0800546 // Returns the node that this event loop is running on. Returns nullptr if we
547 // are running in single-node mode.
548 virtual const Node *node() const = 0;
549
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 // Creates a timer that executes callback when the timer expires
551 // Returns a TimerHandle for configuration of the timer
552 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
553
554 // Creates a timer that executes callback periodically at the specified
555 // interval and offset. Returns a PhasedLoopHandler for interacting with the
556 // timer.
557 virtual PhasedLoopHandler *AddPhasedLoop(
558 ::std::function<void(int)> callback,
559 const monotonic_clock::duration interval,
560 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
561
Austin Schuh217a9782019-12-21 23:02:50 -0800562 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563
564 // Threadsafe.
565 bool is_running() const { return is_running_.load(); }
566
567 // Sets the scheduler priority to run the event loop at. This may not be
568 // called after we go into "real-time-mode".
569 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800570 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571
Brian Silverman6a54ff32020-04-28 16:41:39 -0700572 // Sets the scheduler affinity to run the event loop with. This may only be
573 // called before Run().
574 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
575
Austin Schuh217a9782019-12-21 23:02:50 -0800576 // Fetches new messages from the provided channel (path, type).
577 //
578 // Note: this channel must be a member of the exact configuration object this
579 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
581 const Channel *channel) = 0;
582
Austin Schuh217a9782019-12-21 23:02:50 -0800583 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700584 virtual void MakeRawWatcher(
585 const Channel *channel,
586 std::function<void(const Context &context, const void *message)>
587 watcher) = 0;
588
Brian Silverman454bc112020-03-05 14:21:25 -0800589 // Watches channel (name, type) for new messages, without needing to extract
590 // the message contents. Default implementation simply re-uses MakeRawWatcher.
591 virtual void MakeRawNoArgWatcher(
592 const Channel *channel,
593 std::function<void(const Context &context)> watcher) {
594 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800595 Context new_context = context;
596 new_context.data = nullptr;
597 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800598 });
599 }
600
Austin Schuh217a9782019-12-21 23:02:50 -0800601 // Creates a raw sender for the provided channel. This is used for reflection
602 // based sending.
603 // Note: this ignores any node constraints. Ignore at your own peril.
604 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
605
Austin Schuh6231cc32019-12-07 13:06:15 -0800606 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700607 const Context &context() const { return context_; }
608
609 // Returns the configuration that this event loop was built with.
610 const Configuration *configuration() const { return configuration_; }
611
Austin Schuh39788ff2019-12-01 18:22:57 -0800612 // Prevents the event loop from sending a timing report.
613 void SkipTimingReport() { skip_timing_report_ = true; }
614
Tyler Chatow67ddb032020-01-12 14:30:04 -0800615 // Prevents AOS_LOG being sent to message on /aos
616 void SkipAosLog() { skip_logger_ = true; }
617
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800619 // Sets the name of the event loop. This is the application name.
620 virtual void set_name(const std::string_view name) = 0;
621
Alex Perrycb7da4b2019-08-28 19:35:56 -0700622 void set_is_running(bool value) { is_running_.store(value); }
623
Austin Schuh39788ff2019-12-01 18:22:57 -0800624 // Validates that channel exists inside configuration_ and finds its index.
625 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700626
Brian Silverman5120afb2020-01-31 17:44:35 -0800627 // Returns the state for the watcher on the corresponding channel. This
628 // watcher must exist before calling this.
629 WatcherState *GetWatcherState(const Channel *channel);
630
Brian Silverman6d2b3592020-06-18 14:40:15 -0700631 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800632 template <typename T>
633 static RawSender *GetRawSender(aos::Sender<T> *sender) {
634 return sender->sender_.get();
635 }
636
Brian Silverman6d2b3592020-06-18 14:40:15 -0700637 // Returns a Fetcher's protected RawFetcher.
638 template <typename T>
639 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
640 return fetcher->fetcher_.get();
641 }
642
Austin Schuh6231cc32019-12-07 13:06:15 -0800643 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644 Context context_;
645
Austin Schuh39788ff2019-12-01 18:22:57 -0800646 friend class RawSender;
647 friend class TimerHandler;
648 friend class RawFetcher;
649 friend class PhasedLoopHandler;
650 friend class WatcherState;
651
652 // Methods used to implement timing reports.
653 void NewSender(RawSender *sender);
654 void DeleteSender(RawSender *sender);
655 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
656 PhasedLoopHandler *NewPhasedLoop(
657 std::unique_ptr<PhasedLoopHandler> phased_loop);
658 void NewFetcher(RawFetcher *fetcher);
659 void DeleteFetcher(RawFetcher *fetcher);
660 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
661
Brian Silverman0fc69932020-01-24 21:54:02 -0800662 // Tracks that we have a (single) watcher on the given channel.
663 void TakeWatcher(const Channel *channel);
664 // Tracks that we have at least one sender on the given channel.
665 void TakeSender(const Channel *channel);
666
Austin Schuh39788ff2019-12-01 18:22:57 -0800667 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800668 std::vector<RawFetcher *> fetchers_;
669
Austin Schuh39788ff2019-12-01 18:22:57 -0800670 std::vector<std::unique_ptr<TimerHandler>> timers_;
671 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800672 std::vector<std::unique_ptr<WatcherState>> watchers_;
673
674 void SendTimingReport();
675 void UpdateTimingReport();
676 void MaybeScheduleTimingReports();
677
678 std::unique_ptr<RawSender> timing_report_sender_;
679
Austin Schuh7d87b672019-12-01 20:23:49 -0800680 // Tracks which event sources (timers and watchers) have data, and which
681 // don't. Added events may not change their event_time().
682 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
683 // t2 to run, t2 should then be picked up without a context switch.
684 void AddEvent(EventLoopEvent *event);
685 void RemoveEvent(EventLoopEvent *event);
686 size_t EventCount() const { return events_.size(); }
687 EventLoopEvent *PopEvent();
688 EventLoopEvent *PeekEvent() { return events_.front(); }
689 void ReserveEvents();
690
691 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700692 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800693
Tyler Chatow67ddb032020-01-12 14:30:04 -0800694 // If true, don't send AOS_LOG to /aos
695 bool skip_logger_ = false;
696
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800697 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800698 virtual pid_t GetTid() = 0;
699
700 FlatbufferDetachedBuffer<timing::Report> timing_report_;
701
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800702 ::std::atomic<bool> is_running_{false};
703
Alex Perrycb7da4b2019-08-28 19:35:56 -0700704 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800705
706 // If true, don't send out timing reports.
707 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800708
709 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710};
711
712} // namespace aos
713
714#include "aos/events/event_loop_tmpl.h"
715
716#endif // AOS_EVENTS_EVENT_LOOP_H