blob: 16980dd2816397469a610fdce631c1733f57d359 [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 Schuh39788ff2019-12-01 18:22:57 -080010#include "aos/events/event_loop_generated.h"
11#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include "aos/flatbuffers.h"
13#include "aos/json_to_flatbuffer.h"
14#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080015#include "aos/util/phased_loop.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "flatbuffers/flatbuffers.h"
17#include "glog/logging.h"
18
Austin Schuh39788ff2019-12-01 18:22:57 -080019DECLARE_bool(timing_reports);
20DECLARE_int32(timing_report_ms);
21
Alex Perrycb7da4b2019-08-28 19:35:56 -070022namespace aos {
23
Austin Schuh39788ff2019-12-01 18:22:57 -080024class EventLoop;
25class WatcherState;
26
Austin Schuh6231cc32019-12-07 13:06:15 -080027// Struct available on Watchers, Fetchers, Timers, and PhasedLoops with context
28// about the current message.
Alex Perrycb7da4b2019-08-28 19:35:56 -070029struct Context {
Austin Schuh6231cc32019-12-07 13:06:15 -080030 // Time that the message was sent, or the timer was triggered.
Alex Perrycb7da4b2019-08-28 19:35:56 -070031 monotonic_clock::time_point monotonic_sent_time;
Austin Schuh6231cc32019-12-07 13:06:15 -080032 // Realtime the message was sent. This is set to min_time for Timers and
33 // PhasedLoops.
Alex Perrycb7da4b2019-08-28 19:35:56 -070034 realtime_clock::time_point realtime_sent_time;
Austin Schuh6231cc32019-12-07 13:06:15 -080035 // The rest are only valid for Watchers and Fetchers.
Alex Perrycb7da4b2019-08-28 19:35:56 -070036 // Index in the queue.
37 uint32_t queue_index;
38 // Size of the data sent.
39 size_t size;
40 // Pointer to the data.
41 void *data;
42};
43
44// Raw version of fetcher. Contains a local variable that the fetcher will
45// update. This is used for reflection and as an interface to implement typed
46// fetchers.
47class RawFetcher {
48 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080049 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070050 RawFetcher(const RawFetcher &) = delete;
51 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080052 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070053
Austin Schuh39788ff2019-12-01 18:22:57 -080054 // Fetches the next message in the queue without blocking. Returns true if
55 // there was a new message and we got it.
56 bool FetchNext();
57
58 // Fetches the latest message without blocking.
59 bool Fetch();
60
61 // Returns the channel this fetcher uses.
62 const Channel *channel() const { return channel_; }
63 // Returns the context for the current message.
64 const Context &context() const { return context_; }
65
66 protected:
67 EventLoop *event_loop() { return event_loop_; }
68
Alex Perrycb7da4b2019-08-28 19:35:56 -070069 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080070
71 private:
72 friend class EventLoop;
73 // Implementation
74 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
75 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
76
77 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -080078 const Channel *channel_;
Austin Schuh39788ff2019-12-01 18:22:57 -080079
80 internal::RawFetcherTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070081};
82
83// Raw version of sender. Sends a block of data. This is used for reflection
84// and as a building block to implement typed senders.
85class RawSender {
86 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080087 RawSender(EventLoop *event_loop, const Channel *channel);
88 RawSender(const RawSender &) = delete;
89 RawSender &operator=(const RawSender &) = delete;
90
91 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -070092
93 // Sends a message without copying it. The users starts by copying up to
94 // size() bytes into the data backed by data(). They then call Send to send.
95 // Returns true on a successful send.
96 virtual void *data() = 0;
97 virtual size_t size() = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080098 bool Send(size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -070099
100 // Sends a single block of data by copying it.
Austin Schuh39788ff2019-12-01 18:22:57 -0800101 bool Send(const void *data, size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102
Austin Schuh54cf95f2019-11-29 13:14:18 -0800103 const Channel *channel() const { return channel_; }
104
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800106 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800107
Austin Schuh39788ff2019-12-01 18:22:57 -0800108 private:
109 friend class EventLoop;
110
111 virtual bool DoSend(const void *data, size_t size) = 0;
112 virtual bool DoSend(size_t size) = 0;
113
114 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800115 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116
Austin Schuh39788ff2019-12-01 18:22:57 -0800117 internal::RawSenderTiming timing_;
118};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700119
120// Fetches the newest message from a channel.
121// This provides a polling based interface for channels.
122template <typename T>
123class Fetcher {
124 public:
125 Fetcher() {}
126
127 // Fetches the next message. Returns true if it fetched a new message. This
128 // method will only return messages sent after the Fetcher was created.
129 bool FetchNext() { return fetcher_->FetchNext(); }
130
131 // Fetches the most recent message. Returns true if it fetched a new message.
132 // This will return the latest message regardless of if it was sent before or
133 // after the fetcher was created.
134 bool Fetch() { return fetcher_->Fetch(); }
135
136 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
137 // available message.
138 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800139 return fetcher_->context().data != nullptr
140 ? flatbuffers::GetRoot<T>(
141 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700142 : nullptr;
143 }
144
145 // Returns the context holding timestamps and other metadata about the
146 // message.
147 const Context &context() const { return fetcher_->context(); }
148
149 const T &operator*() const { return *get(); }
150 const T *operator->() const { return get(); }
151
152 private:
153 friend class EventLoop;
154 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
155 : fetcher_(::std::move(fetcher)) {}
156 ::std::unique_ptr<RawFetcher> fetcher_;
157};
158
159// Sends messages to a channel.
160template <typename T>
161class Sender {
162 public:
163 Sender() {}
164
165 // Represents a single message about to be sent to the queue.
166 // The lifecycle goes:
167 //
168 // Builder builder = sender.MakeBuilder();
169 // T::Builder t_builder = builder.MakeBuilder<T>();
170 // Populate(&t_builder);
171 // builder.Send(t_builder.Finish());
172 class Builder {
173 public:
174 Builder(RawSender *sender, void *data, size_t size)
175 : alloc_(data, size), fbb_(size, &alloc_), sender_(sender) {
176 fbb_.ForceDefaults(1);
177 }
178
179 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
180
181 template <typename T2>
182 typename T2::Builder MakeBuilder() {
183 return typename T2::Builder(fbb_);
184 }
185
186 bool Send(flatbuffers::Offset<T> offset) {
187 fbb_.Finish(offset);
188 return sender_->Send(fbb_.GetSize());
189 }
190
191 // CHECKs that this message was sent.
192 void CheckSent() { fbb_.Finished(); }
193
194 private:
195 PreallocatedAllocator alloc_;
196 flatbuffers::FlatBufferBuilder fbb_;
197 RawSender *sender_;
198 };
199
200 // Constructs an above builder.
201 Builder MakeBuilder();
202
Austin Schuh39788ff2019-12-01 18:22:57 -0800203 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800204 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205
206 private:
207 friend class EventLoop;
208 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
209 std::unique_ptr<RawSender> sender_;
210};
211
212// Interface for timers
213class TimerHandler {
214 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800215 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700216
217 // Timer should sleep until base, base + offset, base + offset * 2, ...
218 // If repeat_offset isn't set, the timer only expires once.
219 virtual void Setup(monotonic_clock::time_point base,
220 monotonic_clock::duration repeat_offset =
221 ::aos::monotonic_clock::zero()) = 0;
222
223 // Stop future calls to callback().
224 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800225
226 // Sets and gets the name of the timer. Set this if you want a descriptive
227 // name in the timing report.
228 void set_name(std::string_view name) { name_ = std::string(name); }
229 const std::string_view name() const { return name_; }
230
Austin Schuh39788ff2019-12-01 18:22:57 -0800231 protected:
232 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
233
234 void Call(std::function<monotonic_clock::time_point()> get_time,
235 monotonic_clock::time_point event_time);
236
Austin Schuh1540c2f2019-11-29 21:59:29 -0800237 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800238 friend class EventLoop;
239
240 EventLoop *event_loop_;
241 // The function to call when Call is called.
242 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800243 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800244
245 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700246};
247
248// Interface for phased loops. They are built on timers.
249class PhasedLoopHandler {
250 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800251 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700252
253 // Sets the interval and offset. Any changes to interval and offset only take
254 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800255 void set_interval_and_offset(const monotonic_clock::duration interval,
256 const monotonic_clock::duration offset) {
257 phased_loop_.set_interval_and_offset(interval, offset);
258 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800259
260 // Sets and gets the name of the timer. Set this if you want a descriptive
261 // name in the timing report.
262 void set_name(std::string_view name) { name_ = std::string(name); }
263 const std::string_view name() const { return name_; }
264
Austin Schuh39788ff2019-12-01 18:22:57 -0800265 protected:
266 void Call(std::function<monotonic_clock::time_point()> get_time,
267 std::function<void(monotonic_clock::time_point)> schedule);
268
269 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
270 const monotonic_clock::duration interval,
271 const monotonic_clock::duration offset);
272
Austin Schuh1540c2f2019-11-29 21:59:29 -0800273 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800274 friend class EventLoop;
275
276 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
277 monotonic_clock::time_point monotonic_now) {
278 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
279 schedule(phased_loop_.sleep_time());
280 }
281
282 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
283
284 EventLoop *event_loop_;
285 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800286 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800287 time::PhasedLoop phased_loop_;
288
289 int cycles_elapsed_ = 0;
290
291 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700292};
293
Alex Perrycb7da4b2019-08-28 19:35:56 -0700294class EventLoop {
295 public:
296 EventLoop(const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800297 : timing_report_(flatbuffers::DetachedBuffer()),
298 configuration_(configuration) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700299
Austin Schuh39788ff2019-12-01 18:22:57 -0800300 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700301
302 // Current time.
303 virtual monotonic_clock::time_point monotonic_now() = 0;
304 virtual realtime_clock::time_point realtime_now() = 0;
305
306 // Note, it is supported to create:
307 // multiple fetchers, and (one sender or one watcher) per <name, type>
308 // tuple.
309
310 // Makes a class that will always fetch the most recent value
311 // sent to the provided channel.
312 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800313 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314 const Channel *channel = configuration::GetChannel(
315 configuration_, channel_name, T::GetFullyQualifiedName(), name());
316 CHECK(channel != nullptr)
317 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
318 << T::GetFullyQualifiedName() << "\" } not found in config.";
319
320 return Fetcher<T>(MakeRawFetcher(channel));
321 }
322
323 // Makes class that allows constructing and sending messages to
324 // the provided channel.
325 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800326 Sender<T> MakeSender(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 const Channel *channel = configuration::GetChannel(
328 configuration_, channel_name, T::GetFullyQualifiedName(), name());
329 CHECK(channel != nullptr)
330 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
331 << T::GetFullyQualifiedName() << "\" } not found in config.";
332
333 return Sender<T>(MakeRawSender(channel));
334 }
335
336 // This will watch messages sent to the provided channel.
337 //
338 // Watch is a functor that have a call signature like so:
339 // void Event(const MessageType& type);
340 //
341 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
342 // TODO(austin): Do we need a functor? Or is a std::function good enough?
343 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800344 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345
346 // The passed in function will be called when the event loop starts.
347 // Use this to run code once the thread goes into "real-time-mode",
348 virtual void OnRun(::std::function<void()> on_run) = 0;
349
350 // Sets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800351 virtual void set_name(const std::string_view name) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700352 // Gets the name of the event loop.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800353 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
355 // Creates a timer that executes callback when the timer expires
356 // Returns a TimerHandle for configuration of the timer
357 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
358
359 // Creates a timer that executes callback periodically at the specified
360 // interval and offset. Returns a PhasedLoopHandler for interacting with the
361 // timer.
362 virtual PhasedLoopHandler *AddPhasedLoop(
363 ::std::function<void(int)> callback,
364 const monotonic_clock::duration interval,
365 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
366
367 // TODO(austin): OnExit
368
369 // Threadsafe.
370 bool is_running() const { return is_running_.load(); }
371
372 // Sets the scheduler priority to run the event loop at. This may not be
373 // called after we go into "real-time-mode".
374 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800375 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376
377 // Fetches new messages from the provided channel (path, type). Note: this
378 // channel must be a member of the exact configuration object this was built
379 // with.
380 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
381 const Channel *channel) = 0;
382
383 // Will watch channel (name, type) for new messages
384 virtual void MakeRawWatcher(
385 const Channel *channel,
386 std::function<void(const Context &context, const void *message)>
387 watcher) = 0;
388
Austin Schuh6231cc32019-12-07 13:06:15 -0800389 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 const Context &context() const { return context_; }
391
392 // Returns the configuration that this event loop was built with.
393 const Configuration *configuration() const { return configuration_; }
394
Austin Schuh54cf95f2019-11-29 13:14:18 -0800395 // Will send new messages from channel (path, type).
396 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
397
Austin Schuh39788ff2019-12-01 18:22:57 -0800398 // Prevents the event loop from sending a timing report.
399 void SkipTimingReport() { skip_timing_report_ = true; }
400
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 protected:
402 void set_is_running(bool value) { is_running_.store(value); }
403
Austin Schuh39788ff2019-12-01 18:22:57 -0800404 // Validates that channel exists inside configuration_ and finds its index.
405 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406
Austin Schuh6231cc32019-12-07 13:06:15 -0800407 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 Context context_;
409
Austin Schuh39788ff2019-12-01 18:22:57 -0800410 friend class RawSender;
411 friend class TimerHandler;
412 friend class RawFetcher;
413 friend class PhasedLoopHandler;
414 friend class WatcherState;
415
416 // Methods used to implement timing reports.
417 void NewSender(RawSender *sender);
418 void DeleteSender(RawSender *sender);
419 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
420 PhasedLoopHandler *NewPhasedLoop(
421 std::unique_ptr<PhasedLoopHandler> phased_loop);
422 void NewFetcher(RawFetcher *fetcher);
423 void DeleteFetcher(RawFetcher *fetcher);
424 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
425
426 std::vector<RawSender *> senders_;
427 std::vector<std::unique_ptr<TimerHandler>> timers_;
428 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
429 std::vector<RawFetcher *> fetchers_;
430 std::vector<std::unique_ptr<WatcherState>> watchers_;
431
432 void SendTimingReport();
433 void UpdateTimingReport();
434 void MaybeScheduleTimingReports();
435
436 std::unique_ptr<RawSender> timing_report_sender_;
437
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800438 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800439 virtual pid_t GetTid() = 0;
440
441 FlatbufferDetachedBuffer<timing::Report> timing_report_;
442
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800443 ::std::atomic<bool> is_running_{false};
444
Alex Perrycb7da4b2019-08-28 19:35:56 -0700445 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800446
447 // If true, don't send out timing reports.
448 bool skip_timing_report_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449};
450
451} // namespace aos
452
453#include "aos/events/event_loop_tmpl.h"
454
455#endif // AOS_EVENTS_EVENT_LOOP_H