blob: ed365c383202242dbf04864fe7cf19ea6618449b [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_EVENT_LOOP_H_
Brian Silverman5120afb2020-01-31 17:44:35 -08002
Alex Perrycb7da4b2019-08-28 19:35:56 -07003#define AOS_EVENTS_EVENT_LOOP_H_
4
5#include <atomic>
6#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08007#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include "aos/configuration.h"
10#include "aos/configuration_generated.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080011#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080012#include "aos/events/event_loop_generated.h"
13#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/flatbuffers.h"
15#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
Alex Perrycb7da4b2019-08-28 19:35:56 -0700145 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800146 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800147
Austin Schuhad154822019-12-27 15:45:13 -0800148 aos::monotonic_clock::time_point monotonic_sent_time_ =
149 aos::monotonic_clock::min_time;
150 aos::realtime_clock::time_point realtime_sent_time_ =
151 aos::realtime_clock::min_time;
152 uint32_t sent_queue_index_ = 0xffffffff;
153
Austin Schuh39788ff2019-12-01 18:22:57 -0800154 private:
155 friend class EventLoop;
156
Austin Schuhad154822019-12-27 15:45:13 -0800157 virtual bool DoSend(const void *data, size_t size,
158 aos::monotonic_clock::time_point monotonic_remote_time,
159 aos::realtime_clock::time_point realtime_remote_time,
160 uint32_t remote_queue_index) = 0;
161 virtual bool DoSend(size_t size,
162 aos::monotonic_clock::time_point monotonic_remote_time,
163 aos::realtime_clock::time_point realtime_remote_time,
164 uint32_t remote_queue_index) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800165
166 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800167 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168
Austin Schuh39788ff2019-12-01 18:22:57 -0800169 internal::RawSenderTiming timing_;
170};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
172// Fetches the newest message from a channel.
173// This provides a polling based interface for channels.
174template <typename T>
175class Fetcher {
176 public:
177 Fetcher() {}
178
179 // Fetches the next message. Returns true if it fetched a new message. This
180 // method will only return messages sent after the Fetcher was created.
181 bool FetchNext() { return fetcher_->FetchNext(); }
182
183 // Fetches the most recent message. Returns true if it fetched a new message.
184 // This will return the latest message regardless of if it was sent before or
185 // after the fetcher was created.
186 bool Fetch() { return fetcher_->Fetch(); }
187
188 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
189 // available message.
190 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800191 return fetcher_->context().data != nullptr
192 ? flatbuffers::GetRoot<T>(
193 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700194 : nullptr;
195 }
196
197 // Returns the context holding timestamps and other metadata about the
198 // message.
199 const Context &context() const { return fetcher_->context(); }
200
201 const T &operator*() const { return *get(); }
202 const T *operator->() const { return get(); }
203
204 private:
205 friend class EventLoop;
206 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
207 : fetcher_(::std::move(fetcher)) {}
208 ::std::unique_ptr<RawFetcher> fetcher_;
209};
210
211// Sends messages to a channel.
212template <typename T>
213class Sender {
214 public:
215 Sender() {}
216
217 // Represents a single message about to be sent to the queue.
218 // The lifecycle goes:
219 //
220 // Builder builder = sender.MakeBuilder();
221 // T::Builder t_builder = builder.MakeBuilder<T>();
222 // Populate(&t_builder);
223 // builder.Send(t_builder.Finish());
224 class Builder {
225 public:
226 Builder(RawSender *sender, void *data, size_t size)
227 : alloc_(data, size), fbb_(size, &alloc_), sender_(sender) {
228 fbb_.ForceDefaults(1);
229 }
230
231 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
232
233 template <typename T2>
234 typename T2::Builder MakeBuilder() {
235 return typename T2::Builder(fbb_);
236 }
237
238 bool Send(flatbuffers::Offset<T> offset) {
239 fbb_.Finish(offset);
240 return sender_->Send(fbb_.GetSize());
241 }
242
243 // CHECKs that this message was sent.
244 void CheckSent() { fbb_.Finished(); }
245
246 private:
247 PreallocatedAllocator alloc_;
248 flatbuffers::FlatBufferBuilder fbb_;
249 RawSender *sender_;
250 };
251
252 // Constructs an above builder.
253 Builder MakeBuilder();
254
Austin Schuha28cbc32019-12-27 16:28:04 -0800255 // Sends a prebuilt flatbuffer.
256 bool Send(const Flatbuffer<T> &flatbuffer);
257
Austin Schuh39788ff2019-12-01 18:22:57 -0800258 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800259 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700260
261 private:
262 friend class EventLoop;
263 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
264 std::unique_ptr<RawSender> sender_;
265};
266
267// Interface for timers
268class TimerHandler {
269 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800270 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271
272 // Timer should sleep until base, base + offset, base + offset * 2, ...
273 // If repeat_offset isn't set, the timer only expires once.
274 virtual void Setup(monotonic_clock::time_point base,
275 monotonic_clock::duration repeat_offset =
276 ::aos::monotonic_clock::zero()) = 0;
277
278 // Stop future calls to callback().
279 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800280
281 // Sets and gets the name of the timer. Set this if you want a descriptive
282 // name in the timing report.
283 void set_name(std::string_view name) { name_ = std::string(name); }
284 const std::string_view name() const { return name_; }
285
Austin Schuh39788ff2019-12-01 18:22:57 -0800286 protected:
287 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
288
289 void Call(std::function<monotonic_clock::time_point()> get_time,
290 monotonic_clock::time_point event_time);
291
Austin Schuh1540c2f2019-11-29 21:59:29 -0800292 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800293 friend class EventLoop;
294
295 EventLoop *event_loop_;
296 // The function to call when Call is called.
297 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800298 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800299
300 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301};
302
303// Interface for phased loops. They are built on timers.
304class PhasedLoopHandler {
305 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800306 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
308 // Sets the interval and offset. Any changes to interval and offset only take
309 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800310 void set_interval_and_offset(const monotonic_clock::duration interval,
311 const monotonic_clock::duration offset) {
312 phased_loop_.set_interval_and_offset(interval, offset);
313 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800314
315 // Sets and gets the name of the timer. Set this if you want a descriptive
316 // name in the timing report.
317 void set_name(std::string_view name) { name_ = std::string(name); }
318 const std::string_view name() const { return name_; }
319
Austin Schuh39788ff2019-12-01 18:22:57 -0800320 protected:
321 void Call(std::function<monotonic_clock::time_point()> get_time,
322 std::function<void(monotonic_clock::time_point)> schedule);
323
324 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
325 const monotonic_clock::duration interval,
326 const monotonic_clock::duration offset);
327
Austin Schuh1540c2f2019-11-29 21:59:29 -0800328 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800329 friend class EventLoop;
330
331 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
332 monotonic_clock::time_point monotonic_now) {
333 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
334 schedule(phased_loop_.sleep_time());
335 }
336
337 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
338
339 EventLoop *event_loop_;
340 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800341 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800342 time::PhasedLoop phased_loop_;
343
344 int cycles_elapsed_ = 0;
345
346 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347};
348
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349class EventLoop {
350 public:
351 EventLoop(const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800352 : timing_report_(flatbuffers::DetachedBuffer()),
353 configuration_(configuration) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
Austin Schuh39788ff2019-12-01 18:22:57 -0800355 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700356
357 // Current time.
358 virtual monotonic_clock::time_point monotonic_now() = 0;
359 virtual realtime_clock::time_point realtime_now() = 0;
360
361 // Note, it is supported to create:
362 // multiple fetchers, and (one sender or one watcher) per <name, type>
363 // tuple.
364
365 // Makes a class that will always fetch the most recent value
366 // sent to the provided channel.
367 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800368 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800369 const Channel *channel =
370 configuration::GetChannel(configuration_, channel_name,
371 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700372 CHECK(channel != nullptr)
373 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
374 << T::GetFullyQualifiedName() << "\" } not found in config.";
375
Austin Schuhca4828c2019-12-28 14:21:35 -0800376 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
377 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
378 << "\", \"type\": \"" << T::GetFullyQualifiedName()
379 << "\" } is not able to be fetched on this node. Check your "
380 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800381 }
382
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383 return Fetcher<T>(MakeRawFetcher(channel));
384 }
385
386 // Makes class that allows constructing and sending messages to
387 // the provided channel.
388 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800389 Sender<T> MakeSender(const std::string_view channel_name) {
Austin Schuhbca6cf02019-12-22 17:28:34 -0800390 const Channel *channel =
391 configuration::GetChannel(configuration_, channel_name,
392 T::GetFullyQualifiedName(), name(), node());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 CHECK(channel != nullptr)
394 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
395 << T::GetFullyQualifiedName() << "\" } not found in config.";
396
Austin Schuhca4828c2019-12-28 14:21:35 -0800397 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
398 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
399 << "\", \"type\": \"" << T::GetFullyQualifiedName()
400 << "\" } is not able to be sent on this node. Check your "
401 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800402 }
403
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404 return Sender<T>(MakeRawSender(channel));
405 }
406
407 // This will watch messages sent to the provided channel.
408 //
409 // Watch is a functor that have a call signature like so:
410 // void Event(const MessageType& type);
411 //
412 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
413 // TODO(austin): Do we need a functor? Or is a std::function good enough?
414 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800415 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700416
417 // The passed in function will be called when the event loop starts.
418 // Use this to run code once the thread goes into "real-time-mode",
419 virtual void OnRun(::std::function<void()> on_run) = 0;
420
Austin Schuh217a9782019-12-21 23:02:50 -0800421 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800422 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700423
Austin Schuh217a9782019-12-21 23:02:50 -0800424 // Returns the node that this event loop is running on. Returns nullptr if we
425 // are running in single-node mode.
426 virtual const Node *node() const = 0;
427
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428 // Creates a timer that executes callback when the timer expires
429 // Returns a TimerHandle for configuration of the timer
430 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
431
432 // Creates a timer that executes callback periodically at the specified
433 // interval and offset. Returns a PhasedLoopHandler for interacting with the
434 // timer.
435 virtual PhasedLoopHandler *AddPhasedLoop(
436 ::std::function<void(int)> callback,
437 const monotonic_clock::duration interval,
438 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
439
Austin Schuh217a9782019-12-21 23:02:50 -0800440 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700441
442 // Threadsafe.
443 bool is_running() const { return is_running_.load(); }
444
445 // Sets the scheduler priority to run the event loop at. This may not be
446 // called after we go into "real-time-mode".
447 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800448 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449
Austin Schuh217a9782019-12-21 23:02:50 -0800450 // Fetches new messages from the provided channel (path, type).
451 //
452 // Note: this channel must be a member of the exact configuration object this
453 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
455 const Channel *channel) = 0;
456
Austin Schuh217a9782019-12-21 23:02:50 -0800457 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458 virtual void MakeRawWatcher(
459 const Channel *channel,
460 std::function<void(const Context &context, const void *message)>
461 watcher) = 0;
462
Austin Schuh217a9782019-12-21 23:02:50 -0800463 // Creates a raw sender for the provided channel. This is used for reflection
464 // based sending.
465 // Note: this ignores any node constraints. Ignore at your own peril.
466 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
467
Austin Schuh6231cc32019-12-07 13:06:15 -0800468 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 const Context &context() const { return context_; }
470
471 // Returns the configuration that this event loop was built with.
472 const Configuration *configuration() const { return configuration_; }
473
Austin Schuh39788ff2019-12-01 18:22:57 -0800474 // Prevents the event loop from sending a timing report.
475 void SkipTimingReport() { skip_timing_report_ = true; }
476
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800478 // Sets the name of the event loop. This is the application name.
479 virtual void set_name(const std::string_view name) = 0;
480
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 void set_is_running(bool value) { is_running_.store(value); }
482
Austin Schuh39788ff2019-12-01 18:22:57 -0800483 // Validates that channel exists inside configuration_ and finds its index.
484 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485
Brian Silverman5120afb2020-01-31 17:44:35 -0800486 // Returns the state for the watcher on the corresponding channel. This
487 // watcher must exist before calling this.
488 WatcherState *GetWatcherState(const Channel *channel);
489
490 // Returns a Sender's protected RawSender
491 template <typename T>
492 static RawSender *GetRawSender(aos::Sender<T> *sender) {
493 return sender->sender_.get();
494 }
495
Austin Schuh6231cc32019-12-07 13:06:15 -0800496 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497 Context context_;
498
Austin Schuh39788ff2019-12-01 18:22:57 -0800499 friend class RawSender;
500 friend class TimerHandler;
501 friend class RawFetcher;
502 friend class PhasedLoopHandler;
503 friend class WatcherState;
504
505 // Methods used to implement timing reports.
506 void NewSender(RawSender *sender);
507 void DeleteSender(RawSender *sender);
508 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
509 PhasedLoopHandler *NewPhasedLoop(
510 std::unique_ptr<PhasedLoopHandler> phased_loop);
511 void NewFetcher(RawFetcher *fetcher);
512 void DeleteFetcher(RawFetcher *fetcher);
513 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
514
Brian Silverman0fc69932020-01-24 21:54:02 -0800515 // Tracks that we have a (single) watcher on the given channel.
516 void TakeWatcher(const Channel *channel);
517 // Tracks that we have at least one sender on the given channel.
518 void TakeSender(const Channel *channel);
519
Austin Schuh39788ff2019-12-01 18:22:57 -0800520 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 std::vector<RawFetcher *> fetchers_;
522
Austin Schuh39788ff2019-12-01 18:22:57 -0800523 std::vector<std::unique_ptr<TimerHandler>> timers_;
524 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800525 std::vector<std::unique_ptr<WatcherState>> watchers_;
526
527 void SendTimingReport();
528 void UpdateTimingReport();
529 void MaybeScheduleTimingReports();
530
531 std::unique_ptr<RawSender> timing_report_sender_;
532
Austin Schuh7d87b672019-12-01 20:23:49 -0800533 // Tracks which event sources (timers and watchers) have data, and which
534 // don't. Added events may not change their event_time().
535 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
536 // t2 to run, t2 should then be picked up without a context switch.
537 void AddEvent(EventLoopEvent *event);
538 void RemoveEvent(EventLoopEvent *event);
539 size_t EventCount() const { return events_.size(); }
540 EventLoopEvent *PopEvent();
541 EventLoopEvent *PeekEvent() { return events_.front(); }
542 void ReserveEvents();
543
544 std::vector<EventLoopEvent *> events_;
545
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800546 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800547 virtual pid_t GetTid() = 0;
548
549 FlatbufferDetachedBuffer<timing::Report> timing_report_;
550
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800551 ::std::atomic<bool> is_running_{false};
552
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800554
555 // If true, don't send out timing reports.
556 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800557
558 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559};
560
561} // namespace aos
562
563#include "aos/events/event_loop_tmpl.h"
564
565#endif // AOS_EVENTS_EVENT_LOOP_H