blob: 9618a32d703c8df2e889411662c22205915551f6 [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 Schuh7d87b672019-12-01 20:23:49 -080010#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080011#include "aos/events/event_loop_generated.h"
12#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/flatbuffers.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080014#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070015#include "aos/json_to_flatbuffer.h"
16#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080017#include "aos/util/phased_loop.h"
Brian Silverman0fc69932020-01-24 21:54:02 -080018
19#include "absl/container/btree_set.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "flatbuffers/flatbuffers.h"
21#include "glog/logging.h"
22
Austin Schuh39788ff2019-12-01 18:22:57 -080023DECLARE_bool(timing_reports);
24DECLARE_int32(timing_report_ms);
25
Alex Perrycb7da4b2019-08-28 19:35:56 -070026namespace aos {
27
Austin Schuh39788ff2019-12-01 18:22:57 -080028class EventLoop;
29class WatcherState;
30
Austin Schuh6231cc32019-12-07 13:06:15 -080031// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
32// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070033struct Context {
Austin Schuhad154822019-12-27 15:45:13 -080034 // Time that the message was sent on this node, or the timer was triggered.
35 monotonic_clock::time_point monotonic_event_time;
36 // Realtime the message was sent on this node. This is set to min_time for
37 // Timers and PhasedLoops.
38 realtime_clock::time_point realtime_event_time;
39
40 // For a single-node configuration, these two are identical to *_event_time.
41 // In a multinode configuration, these are the times that the message was
42 // sent on the original node.
43 monotonic_clock::time_point monotonic_remote_time;
44 realtime_clock::time_point realtime_remote_time;
45
Austin Schuh6231cc32019-12-07 13:06:15 -080046 // The rest are only valid for Watchers and Fetchers.
Alex Perrycb7da4b2019-08-28 19:35:56 -070047 // Index in the queue.
48 uint32_t queue_index;
Austin Schuhad154822019-12-27 15:45:13 -080049 // Index into the remote queue. Useful to determine if data was lost. In a
50 // single-node configuration, this will match queue_index.
51 uint32_t remote_queue_index;
52
Alex Perrycb7da4b2019-08-28 19:35:56 -070053 // Size of the data sent.
54 size_t size;
55 // Pointer to the data.
56 void *data;
57};
58
59// Raw version of fetcher. Contains a local variable that the fetcher will
60// update. This is used for reflection and as an interface to implement typed
61// fetchers.
62class RawFetcher {
63 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080064 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070065 RawFetcher(const RawFetcher &) = delete;
66 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080067 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070068
Austin Schuh39788ff2019-12-01 18:22:57 -080069 // Fetches the next message in the queue without blocking. Returns true if
70 // there was a new message and we got it.
71 bool FetchNext();
72
73 // Fetches the latest message without blocking.
74 bool Fetch();
75
76 // Returns the channel this fetcher uses.
77 const Channel *channel() const { return channel_; }
78 // Returns the context for the current message.
79 const Context &context() const { return context_; }
80
81 protected:
82 EventLoop *event_loop() { return event_loop_; }
83
Alex Perrycb7da4b2019-08-28 19:35:56 -070084 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080085
86 private:
87 friend class EventLoop;
88 // Implementation
89 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
90 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
91
92 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -080093 const Channel *channel_;
Austin Schuh39788ff2019-12-01 18:22:57 -080094
95 internal::RawFetcherTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070096};
97
98// Raw version of sender. Sends a block of data. This is used for reflection
99// and as a building block to implement typed senders.
100class RawSender {
101 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 RawSender(EventLoop *event_loop, const Channel *channel);
103 RawSender(const RawSender &) = delete;
104 RawSender &operator=(const RawSender &) = delete;
105
106 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700107
108 // Sends a message without copying it. The users starts by copying up to
109 // size() bytes into the data backed by data(). They then call Send to send.
110 // Returns true on a successful send.
Austin Schuhad154822019-12-27 15:45:13 -0800111 // If provided, monotonic_remote_time, realtime_remote_time, and
112 // remote_queue_index are attached to the message and are available in the
113 // context on the read side. If they are not populated, the read side will
114 // get the sent times instead.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700115 virtual void *data() = 0;
116 virtual size_t size() = 0;
Austin Schuhad154822019-12-27 15:45:13 -0800117 bool Send(size_t size,
118 aos::monotonic_clock::time_point monotonic_remote_time =
119 aos::monotonic_clock::min_time,
120 aos::realtime_clock::time_point realtime_remote_time =
121 aos::realtime_clock::min_time,
122 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700123
124 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800125 // The remote arguments have the same meaning as in Send above.
126 bool Send(const void *data, size_t size,
127 aos::monotonic_clock::time_point monotonic_remote_time =
128 aos::monotonic_clock::min_time,
129 aos::realtime_clock::time_point realtime_remote_time =
130 aos::realtime_clock::min_time,
131 uint32_t remote_queue_index = 0xffffffffu);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700132
Austin Schuh54cf95f2019-11-29 13:14:18 -0800133 const Channel *channel() const { return channel_; }
134
Austin Schuhad154822019-12-27 15:45:13 -0800135 // Returns the time_points that the last message was sent at.
136 aos::monotonic_clock::time_point monotonic_sent_time() const {
137 return monotonic_sent_time_;
138 }
139 aos::realtime_clock::time_point realtime_sent_time() const {
140 return realtime_sent_time_;
141 }
142 // Returns the queue index that this was sent with.
143 uint32_t sent_queue_index() const { return sent_queue_index_; }
144
Brian Silvermana1652f32020-01-29 20:41:44 -0800145 // Returns the associated flatbuffers-style allocator. This must be
146 // deallocated before the message is sent.
147 PreallocatedAllocator *fbb_allocator() {
148 fbb_allocator_ = PreallocatedAllocator(data(), size());
149 return &fbb_allocator_;
150 }
151
Alex Perrycb7da4b2019-08-28 19:35:56 -0700152 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800153 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800154
Austin Schuhad154822019-12-27 15:45:13 -0800155 aos::monotonic_clock::time_point monotonic_sent_time_ =
156 aos::monotonic_clock::min_time;
157 aos::realtime_clock::time_point realtime_sent_time_ =
158 aos::realtime_clock::min_time;
159 uint32_t sent_queue_index_ = 0xffffffff;
160
Austin Schuh39788ff2019-12-01 18:22:57 -0800161 private:
162 friend class EventLoop;
163
Austin Schuhad154822019-12-27 15:45:13 -0800164 virtual bool DoSend(const void *data, size_t size,
165 aos::monotonic_clock::time_point monotonic_remote_time,
166 aos::realtime_clock::time_point realtime_remote_time,
167 uint32_t remote_queue_index) = 0;
168 virtual bool DoSend(size_t size,
169 aos::monotonic_clock::time_point monotonic_remote_time,
170 aos::realtime_clock::time_point realtime_remote_time,
171 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800172
173 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800174 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
Austin Schuh39788ff2019-12-01 18:22:57 -0800176 internal::RawSenderTiming timing_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800177
178 PreallocatedAllocator fbb_allocator_{nullptr, 0};
Austin Schuh39788ff2019-12-01 18:22:57 -0800179};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180
181// Fetches the newest message from a channel.
182// This provides a polling based interface for channels.
183template <typename T>
184class Fetcher {
185 public:
186 Fetcher() {}
187
188 // Fetches the next message. Returns true if it fetched a new message. This
189 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800190 bool FetchNext() {
191 const bool result = fetcher_->FetchNext();
192 if (result) {
193 CheckChannelDataAlignment(fetcher_->context().data,
194 fetcher_->context().size);
195 }
196 return result;
197 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700198
199 // Fetches the most recent message. Returns true if it fetched a new message.
200 // This will return the latest message regardless of if it was sent before or
201 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800202 bool Fetch() {
203 const bool result = fetcher_->Fetch();
204 if (result) {
205 CheckChannelDataAlignment(fetcher_->context().data,
206 fetcher_->context().size);
207 }
208 return result;
209 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
211 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
212 // available message.
213 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800214 return fetcher_->context().data != nullptr
215 ? flatbuffers::GetRoot<T>(
216 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217 : nullptr;
218 }
219
220 // Returns the context holding timestamps and other metadata about the
221 // message.
222 const Context &context() const { return fetcher_->context(); }
223
224 const T &operator*() const { return *get(); }
225 const T *operator->() const { return get(); }
226
227 private:
228 friend class EventLoop;
229 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
230 : fetcher_(::std::move(fetcher)) {}
231 ::std::unique_ptr<RawFetcher> fetcher_;
232};
233
234// Sends messages to a channel.
235template <typename T>
236class Sender {
237 public:
238 Sender() {}
239
240 // Represents a single message about to be sent to the queue.
241 // The lifecycle goes:
242 //
243 // Builder builder = sender.MakeBuilder();
244 // T::Builder t_builder = builder.MakeBuilder<T>();
245 // Populate(&t_builder);
246 // builder.Send(t_builder.Finish());
247 class Builder {
248 public:
Brian Silvermana1652f32020-01-29 20:41:44 -0800249 Builder(RawSender *sender, PreallocatedAllocator *allocator)
250 : fbb_(allocator->size(), allocator), sender_(sender) {
251 CheckChannelDataAlignment(allocator->data(), allocator->size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252 fbb_.ForceDefaults(1);
253 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800254 Builder() {}
255 Builder(const Builder &) = delete;
256 Builder(Builder &&) = default;
257
258 Builder &operator=(const Builder &) = delete;
259 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700260
261 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
262
263 template <typename T2>
264 typename T2::Builder MakeBuilder() {
265 return typename T2::Builder(fbb_);
266 }
267
268 bool Send(flatbuffers::Offset<T> offset) {
269 fbb_.Finish(offset);
270 return sender_->Send(fbb_.GetSize());
271 }
272
273 // CHECKs that this message was sent.
274 void CheckSent() { fbb_.Finished(); }
275
276 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277 flatbuffers::FlatBufferBuilder fbb_;
278 RawSender *sender_;
279 };
280
281 // Constructs an above builder.
282 Builder MakeBuilder();
283
Austin Schuha28cbc32019-12-27 16:28:04 -0800284 // Sends a prebuilt flatbuffer.
285 bool Send(const Flatbuffer<T> &flatbuffer);
286
Austin Schuh39788ff2019-12-01 18:22:57 -0800287 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800288 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289
290 private:
291 friend class EventLoop;
292 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
293 std::unique_ptr<RawSender> sender_;
294};
295
296// Interface for timers
297class TimerHandler {
298 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800299 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300
301 // Timer should sleep until base, base + offset, base + offset * 2, ...
302 // If repeat_offset isn't set, the timer only expires once.
303 virtual void Setup(monotonic_clock::time_point base,
304 monotonic_clock::duration repeat_offset =
305 ::aos::monotonic_clock::zero()) = 0;
306
307 // Stop future calls to callback().
308 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800309
310 // Sets and gets the name of the timer. Set this if you want a descriptive
311 // name in the timing report.
312 void set_name(std::string_view name) { name_ = std::string(name); }
313 const std::string_view name() const { return name_; }
314
Austin Schuh39788ff2019-12-01 18:22:57 -0800315 protected:
316 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
317
318 void Call(std::function<monotonic_clock::time_point()> get_time,
319 monotonic_clock::time_point event_time);
320
Austin Schuh1540c2f2019-11-29 21:59:29 -0800321 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 friend class EventLoop;
323
324 EventLoop *event_loop_;
325 // The function to call when Call is called.
326 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800327 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800328
329 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700330};
331
332// Interface for phased loops. They are built on timers.
333class PhasedLoopHandler {
334 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700336
337 // Sets the interval and offset. Any changes to interval and offset only take
338 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800339 void set_interval_and_offset(const monotonic_clock::duration interval,
340 const monotonic_clock::duration offset) {
341 phased_loop_.set_interval_and_offset(interval, offset);
342 }
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 void Call(std::function<monotonic_clock::time_point()> get_time,
351 std::function<void(monotonic_clock::time_point)> schedule);
352
353 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
354 const monotonic_clock::duration interval,
355 const monotonic_clock::duration offset);
356
Austin Schuh1540c2f2019-11-29 21:59:29 -0800357 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800358 friend class EventLoop;
359
360 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
361 monotonic_clock::time_point monotonic_now) {
362 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
363 schedule(phased_loop_.sleep_time());
364 }
365
366 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
367
368 EventLoop *event_loop_;
369 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800370 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800371 time::PhasedLoop phased_loop_;
372
373 int cycles_elapsed_ = 0;
374
375 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376};
377
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378class EventLoop {
379 public:
380 EventLoop(const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800381 : timing_report_(flatbuffers::DetachedBuffer()),
382 configuration_(configuration) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383
Austin Schuh39788ff2019-12-01 18:22:57 -0800384 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385
386 // Current time.
387 virtual monotonic_clock::time_point monotonic_now() = 0;
388 virtual realtime_clock::time_point realtime_now() = 0;
389
390 // Note, it is supported to create:
391 // multiple fetchers, and (one sender or one watcher) per <name, type>
392 // tuple.
393
394 // Makes a class that will always fetch the most recent value
395 // sent to the provided channel.
396 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800397 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800398 const Channel *channel =
399 configuration::GetChannel(configuration_, channel_name,
400 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 CHECK(channel != nullptr)
402 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
403 << T::GetFullyQualifiedName() << "\" } not found in config.";
404
Austin Schuhca4828c2019-12-28 14:21:35 -0800405 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
406 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
407 << "\", \"type\": \"" << T::GetFullyQualifiedName()
408 << "\" } is not able to be fetched on this node. Check your "
409 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800410 }
411
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412 return Fetcher<T>(MakeRawFetcher(channel));
413 }
414
415 // Makes class that allows constructing and sending messages to
416 // the provided channel.
417 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800418 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800419 const Channel *channel =
420 configuration::GetChannel(configuration_, channel_name,
421 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422 CHECK(channel != nullptr)
423 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
424 << T::GetFullyQualifiedName() << "\" } not found in config.";
425
Austin Schuhca4828c2019-12-28 14:21:35 -0800426 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
427 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
428 << "\", \"type\": \"" << T::GetFullyQualifiedName()
429 << "\" } is not able to be sent on this node. Check your "
430 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800431 }
432
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433 return Sender<T>(MakeRawSender(channel));
434 }
435
436 // This will watch messages sent to the provided channel.
437 //
438 // Watch is a functor that have a call signature like so:
439 // void Event(const MessageType& type);
440 //
441 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
442 // TODO(austin): Do we need a functor? Or is a std::function good enough?
443 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800444 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445
446 // The passed in function will be called when the event loop starts.
447 // Use this to run code once the thread goes into "real-time-mode",
448 virtual void OnRun(::std::function<void()> on_run) = 0;
449
Austin Schuh217a9782019-12-21 23:02:50 -0800450 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800451 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700452
Austin Schuh217a9782019-12-21 23:02:50 -0800453 // Returns the node that this event loop is running on. Returns nullptr if we
454 // are running in single-node mode.
455 virtual const Node *node() const = 0;
456
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 // Creates a timer that executes callback when the timer expires
458 // Returns a TimerHandle for configuration of the timer
459 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
460
461 // Creates a timer that executes callback periodically at the specified
462 // interval and offset. Returns a PhasedLoopHandler for interacting with the
463 // timer.
464 virtual PhasedLoopHandler *AddPhasedLoop(
465 ::std::function<void(int)> callback,
466 const monotonic_clock::duration interval,
467 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
468
Austin Schuh217a9782019-12-21 23:02:50 -0800469 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470
471 // Threadsafe.
472 bool is_running() const { return is_running_.load(); }
473
474 // Sets the scheduler priority to run the event loop at. This may not be
475 // called after we go into "real-time-mode".
476 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800477 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478
Austin Schuh217a9782019-12-21 23:02:50 -0800479 // Fetches new messages from the provided channel (path, type).
480 //
481 // Note: this channel must be a member of the exact configuration object this
482 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
484 const Channel *channel) = 0;
485
Austin Schuh217a9782019-12-21 23:02:50 -0800486 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700487 virtual void MakeRawWatcher(
488 const Channel *channel,
489 std::function<void(const Context &context, const void *message)>
490 watcher) = 0;
491
Austin Schuh217a9782019-12-21 23:02:50 -0800492 // Creates a raw sender for the provided channel. This is used for reflection
493 // based sending.
494 // Note: this ignores any node constraints. Ignore at your own peril.
495 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
496
Austin Schuh6231cc32019-12-07 13:06:15 -0800497 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700498 const Context &context() const { return context_; }
499
500 // Returns the configuration that this event loop was built with.
501 const Configuration *configuration() const { return configuration_; }
502
Austin Schuh39788ff2019-12-01 18:22:57 -0800503 // Prevents the event loop from sending a timing report.
504 void SkipTimingReport() { skip_timing_report_ = true; }
505
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800507 // Sets the name of the event loop. This is the application name.
508 virtual void set_name(const std::string_view name) = 0;
509
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510 void set_is_running(bool value) { is_running_.store(value); }
511
Austin Schuh39788ff2019-12-01 18:22:57 -0800512 // Validates that channel exists inside configuration_ and finds its index.
513 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700514
Austin Schuh6231cc32019-12-07 13:06:15 -0800515 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700516 Context context_;
517
Austin Schuh39788ff2019-12-01 18:22:57 -0800518 friend class RawSender;
519 friend class TimerHandler;
520 friend class RawFetcher;
521 friend class PhasedLoopHandler;
522 friend class WatcherState;
523
524 // Methods used to implement timing reports.
525 void NewSender(RawSender *sender);
526 void DeleteSender(RawSender *sender);
527 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
528 PhasedLoopHandler *NewPhasedLoop(
529 std::unique_ptr<PhasedLoopHandler> phased_loop);
530 void NewFetcher(RawFetcher *fetcher);
531 void DeleteFetcher(RawFetcher *fetcher);
532 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
533
Brian Silverman0fc69932020-01-24 21:54:02 -0800534 // Tracks that we have a (single) watcher on the given channel.
535 void TakeWatcher(const Channel *channel);
536 // Tracks that we have at least one sender on the given channel.
537 void TakeSender(const Channel *channel);
538
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800540 std::vector<RawFetcher *> fetchers_;
541
Austin Schuh39788ff2019-12-01 18:22:57 -0800542 std::vector<std::unique_ptr<TimerHandler>> timers_;
543 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800544 std::vector<std::unique_ptr<WatcherState>> watchers_;
545
546 void SendTimingReport();
547 void UpdateTimingReport();
548 void MaybeScheduleTimingReports();
549
550 std::unique_ptr<RawSender> timing_report_sender_;
551
Austin Schuh7d87b672019-12-01 20:23:49 -0800552 // Tracks which event sources (timers and watchers) have data, and which
553 // don't. Added events may not change their event_time().
554 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
555 // t2 to run, t2 should then be picked up without a context switch.
556 void AddEvent(EventLoopEvent *event);
557 void RemoveEvent(EventLoopEvent *event);
558 size_t EventCount() const { return events_.size(); }
559 EventLoopEvent *PopEvent();
560 EventLoopEvent *PeekEvent() { return events_.front(); }
561 void ReserveEvents();
562
563 std::vector<EventLoopEvent *> events_;
564
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800565 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800566 virtual pid_t GetTid() = 0;
567
568 FlatbufferDetachedBuffer<timing::Report> timing_report_;
569
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800570 ::std::atomic<bool> is_running_{false};
571
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800573
574 // If true, don't send out timing reports.
575 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800576
577 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700578};
579
580} // namespace aos
581
582#include "aos/events/event_loop_tmpl.h"
583
584#endif // AOS_EVENTS_EVENT_LOOP_H