blob: 4f24dc0b7ceb36cb11a605b55734de14a483a399 [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
Alex Perrycb7da4b2019-08-28 19:35:56 -070027// Struct available on Watchers and Fetchers with context about the current
28// message.
29struct Context {
30 // Time that the message was sent.
31 monotonic_clock::time_point monotonic_sent_time;
32 realtime_clock::time_point realtime_sent_time;
33 // Index in the queue.
34 uint32_t queue_index;
35 // Size of the data sent.
36 size_t size;
37 // Pointer to the data.
38 void *data;
39};
40
41// Raw version of fetcher. Contains a local variable that the fetcher will
42// update. This is used for reflection and as an interface to implement typed
43// fetchers.
44class RawFetcher {
45 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080046 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070047 RawFetcher(const RawFetcher &) = delete;
48 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080049 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070050
Austin Schuh39788ff2019-12-01 18:22:57 -080051 // Fetches the next message in the queue without blocking. Returns true if
52 // there was a new message and we got it.
53 bool FetchNext();
54
55 // Fetches the latest message without blocking.
56 bool Fetch();
57
58 // Returns the channel this fetcher uses.
59 const Channel *channel() const { return channel_; }
60 // Returns the context for the current message.
61 const Context &context() const { return context_; }
62
63 protected:
64 EventLoop *event_loop() { return event_loop_; }
65
Alex Perrycb7da4b2019-08-28 19:35:56 -070066 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080067
68 private:
69 friend class EventLoop;
70 // Implementation
71 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
72 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
73
74 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -080075 const Channel *channel_;
Austin Schuh39788ff2019-12-01 18:22:57 -080076
77 internal::RawFetcherTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070078};
79
80// Raw version of sender. Sends a block of data. This is used for reflection
81// and as a building block to implement typed senders.
82class RawSender {
83 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080084 RawSender(EventLoop *event_loop, const Channel *channel);
85 RawSender(const RawSender &) = delete;
86 RawSender &operator=(const RawSender &) = delete;
87
88 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -070089
90 // Sends a message without copying it. The users starts by copying up to
91 // size() bytes into the data backed by data(). They then call Send to send.
92 // Returns true on a successful send.
93 virtual void *data() = 0;
94 virtual size_t size() = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080095 bool Send(size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -070096
97 // Sends a single block of data by copying it.
Austin Schuh39788ff2019-12-01 18:22:57 -080098 bool Send(const void *data, size_t size);
Alex Perrycb7da4b2019-08-28 19:35:56 -070099
Austin Schuh54cf95f2019-11-29 13:14:18 -0800100 const Channel *channel() const { return channel_; }
101
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 EventLoop *event_loop() { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800104
Austin Schuh39788ff2019-12-01 18:22:57 -0800105 private:
106 friend class EventLoop;
107
108 virtual bool DoSend(const void *data, size_t size) = 0;
109 virtual bool DoSend(size_t size) = 0;
110
111 EventLoop *event_loop_;
Austin Schuh54cf95f2019-11-29 13:14:18 -0800112 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
Austin Schuh39788ff2019-12-01 18:22:57 -0800114 internal::RawSenderTiming timing_;
115};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116
117// Fetches the newest message from a channel.
118// This provides a polling based interface for channels.
119template <typename T>
120class Fetcher {
121 public:
122 Fetcher() {}
123
124 // Fetches the next message. Returns true if it fetched a new message. This
125 // method will only return messages sent after the Fetcher was created.
126 bool FetchNext() { return fetcher_->FetchNext(); }
127
128 // Fetches the most recent message. Returns true if it fetched a new message.
129 // This will return the latest message regardless of if it was sent before or
130 // after the fetcher was created.
131 bool Fetch() { return fetcher_->Fetch(); }
132
133 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
134 // available message.
135 const T *get() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800136 return fetcher_->context().data != nullptr
137 ? flatbuffers::GetRoot<T>(
138 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139 : nullptr;
140 }
141
142 // Returns the context holding timestamps and other metadata about the
143 // message.
144 const Context &context() const { return fetcher_->context(); }
145
146 const T &operator*() const { return *get(); }
147 const T *operator->() const { return get(); }
148
149 private:
150 friend class EventLoop;
151 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
152 : fetcher_(::std::move(fetcher)) {}
153 ::std::unique_ptr<RawFetcher> fetcher_;
154};
155
156// Sends messages to a channel.
157template <typename T>
158class Sender {
159 public:
160 Sender() {}
161
162 // Represents a single message about to be sent to the queue.
163 // The lifecycle goes:
164 //
165 // Builder builder = sender.MakeBuilder();
166 // T::Builder t_builder = builder.MakeBuilder<T>();
167 // Populate(&t_builder);
168 // builder.Send(t_builder.Finish());
169 class Builder {
170 public:
171 Builder(RawSender *sender, void *data, size_t size)
172 : alloc_(data, size), fbb_(size, &alloc_), sender_(sender) {
173 fbb_.ForceDefaults(1);
174 }
175
176 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
177
178 template <typename T2>
179 typename T2::Builder MakeBuilder() {
180 return typename T2::Builder(fbb_);
181 }
182
183 bool Send(flatbuffers::Offset<T> offset) {
184 fbb_.Finish(offset);
185 return sender_->Send(fbb_.GetSize());
186 }
187
188 // CHECKs that this message was sent.
189 void CheckSent() { fbb_.Finished(); }
190
191 private:
192 PreallocatedAllocator alloc_;
193 flatbuffers::FlatBufferBuilder fbb_;
194 RawSender *sender_;
195 };
196
197 // Constructs an above builder.
198 Builder MakeBuilder();
199
Austin Schuh39788ff2019-12-01 18:22:57 -0800200 // Returns the name of the underlying queue.
Austin Schuh1e869472019-12-01 13:36:10 -0800201 const Channel *channel() const { return sender_->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202
203 private:
204 friend class EventLoop;
205 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
206 std::unique_ptr<RawSender> sender_;
207};
208
209// Interface for timers
210class TimerHandler {
211 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800212 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213
214 // Timer should sleep until base, base + offset, base + offset * 2, ...
215 // If repeat_offset isn't set, the timer only expires once.
216 virtual void Setup(monotonic_clock::time_point base,
217 monotonic_clock::duration repeat_offset =
218 ::aos::monotonic_clock::zero()) = 0;
219
220 // Stop future calls to callback().
221 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800222
223 // Sets and gets the name of the timer. Set this if you want a descriptive
224 // name in the timing report.
225 void set_name(std::string_view name) { name_ = std::string(name); }
226 const std::string_view name() const { return name_; }
227
Austin Schuh39788ff2019-12-01 18:22:57 -0800228 protected:
229 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
230
231 void Call(std::function<monotonic_clock::time_point()> get_time,
232 monotonic_clock::time_point event_time);
233
Austin Schuh1540c2f2019-11-29 21:59:29 -0800234 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800235 friend class EventLoop;
236
237 EventLoop *event_loop_;
238 // The function to call when Call is called.
239 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800240 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800241
242 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243};
244
245// Interface for phased loops. They are built on timers.
246class PhasedLoopHandler {
247 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800248 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700249
250 // Sets the interval and offset. Any changes to interval and offset only take
251 // effect when the handler finishes running.
Austin Schuh39788ff2019-12-01 18:22:57 -0800252 void set_interval_and_offset(const monotonic_clock::duration interval,
253 const monotonic_clock::duration offset) {
254 phased_loop_.set_interval_and_offset(interval, offset);
255 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800256
257 // Sets and gets the name of the timer. Set this if you want a descriptive
258 // name in the timing report.
259 void set_name(std::string_view name) { name_ = std::string(name); }
260 const std::string_view name() const { return name_; }
261
Austin Schuh39788ff2019-12-01 18:22:57 -0800262 protected:
263 void Call(std::function<monotonic_clock::time_point()> get_time,
264 std::function<void(monotonic_clock::time_point)> schedule);
265
266 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
267 const monotonic_clock::duration interval,
268 const monotonic_clock::duration offset);
269
Austin Schuh1540c2f2019-11-29 21:59:29 -0800270 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800271 friend class EventLoop;
272
273 void Reschedule(std::function<void(monotonic_clock::time_point)> schedule,
274 monotonic_clock::time_point monotonic_now) {
275 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
276 schedule(phased_loop_.sleep_time());
277 }
278
279 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
280
281 EventLoop *event_loop_;
282 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800283 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800284 time::PhasedLoop phased_loop_;
285
286 int cycles_elapsed_ = 0;
287
288 internal::TimerTiming timing_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289};
290
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291class EventLoop {
292 public:
293 EventLoop(const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800294 : timing_report_(flatbuffers::DetachedBuffer()),
295 configuration_(configuration) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296
Austin Schuh39788ff2019-12-01 18:22:57 -0800297 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700298
299 // Current time.
300 virtual monotonic_clock::time_point monotonic_now() = 0;
301 virtual realtime_clock::time_point realtime_now() = 0;
302
303 // Note, it is supported to create:
304 // multiple fetchers, and (one sender or one watcher) per <name, type>
305 // tuple.
306
307 // Makes a class that will always fetch the most recent value
308 // sent to the provided channel.
309 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800310 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700311 const Channel *channel = configuration::GetChannel(
312 configuration_, channel_name, T::GetFullyQualifiedName(), name());
313 CHECK(channel != nullptr)
314 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
315 << T::GetFullyQualifiedName() << "\" } not found in config.";
316
317 return Fetcher<T>(MakeRawFetcher(channel));
318 }
319
320 // Makes class that allows constructing and sending messages to
321 // the provided channel.
322 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800323 Sender<T> MakeSender(const std::string_view channel_name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700324 const Channel *channel = configuration::GetChannel(
325 configuration_, channel_name, T::GetFullyQualifiedName(), name());
326 CHECK(channel != nullptr)
327 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
328 << T::GetFullyQualifiedName() << "\" } not found in config.";
329
330 return Sender<T>(MakeRawSender(channel));
331 }
332
333 // This will watch messages sent to the provided channel.
334 //
335 // Watch is a functor that have a call signature like so:
336 // void Event(const MessageType& type);
337 //
338 // TODO(parker): Need to support ::std::bind. For now, use lambdas.
339 // TODO(austin): Do we need a functor? Or is a std::function good enough?
340 template <typename Watch>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800341 void MakeWatcher(const std::string_view name, Watch &&w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342
343 // The passed in function will be called when the event loop starts.
344 // Use this to run code once the thread goes into "real-time-mode",
345 virtual void OnRun(::std::function<void()> on_run) = 0;
346
347 // Sets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800348 virtual void set_name(const std::string_view name) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349 // Gets the name of the event loop.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800350 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700351
352 // Creates a timer that executes callback when the timer expires
353 // Returns a TimerHandle for configuration of the timer
354 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
355
356 // Creates a timer that executes callback periodically at the specified
357 // interval and offset. Returns a PhasedLoopHandler for interacting with the
358 // timer.
359 virtual PhasedLoopHandler *AddPhasedLoop(
360 ::std::function<void(int)> callback,
361 const monotonic_clock::duration interval,
362 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
363
364 // TODO(austin): OnExit
365
366 // Threadsafe.
367 bool is_running() const { return is_running_.load(); }
368
369 // Sets the scheduler priority to run the event loop at. This may not be
370 // called after we go into "real-time-mode".
371 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -0800372 virtual int priority() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700373
374 // Fetches new messages from the provided channel (path, type). Note: this
375 // channel must be a member of the exact configuration object this was built
376 // with.
377 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
378 const Channel *channel) = 0;
379
380 // Will watch channel (name, type) for new messages
381 virtual void MakeRawWatcher(
382 const Channel *channel,
383 std::function<void(const Context &context, const void *message)>
384 watcher) = 0;
385
386 // Returns the context for the current message.
387 // TODO(austin): Fill out whatever is useful for timers.
388 const Context &context() const { return context_; }
389
390 // Returns the configuration that this event loop was built with.
391 const Configuration *configuration() const { return configuration_; }
392
Austin Schuh54cf95f2019-11-29 13:14:18 -0800393 // Will send new messages from channel (path, type).
394 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
395
Austin Schuh39788ff2019-12-01 18:22:57 -0800396 // Prevents the event loop from sending a timing report.
397 void SkipTimingReport() { skip_timing_report_ = true; }
398
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 protected:
400 void set_is_running(bool value) { is_running_.store(value); }
401
Austin Schuh39788ff2019-12-01 18:22:57 -0800402 // Validates that channel exists inside configuration_ and finds its index.
403 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404
Alex Perrycb7da4b2019-08-28 19:35:56 -0700405 // Context available for watchers.
406 Context context_;
407
Austin Schuh39788ff2019-12-01 18:22:57 -0800408 friend class RawSender;
409 friend class TimerHandler;
410 friend class RawFetcher;
411 friend class PhasedLoopHandler;
412 friend class WatcherState;
413
414 // Methods used to implement timing reports.
415 void NewSender(RawSender *sender);
416 void DeleteSender(RawSender *sender);
417 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
418 PhasedLoopHandler *NewPhasedLoop(
419 std::unique_ptr<PhasedLoopHandler> phased_loop);
420 void NewFetcher(RawFetcher *fetcher);
421 void DeleteFetcher(RawFetcher *fetcher);
422 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
423
424 std::vector<RawSender *> senders_;
425 std::vector<std::unique_ptr<TimerHandler>> timers_;
426 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
427 std::vector<RawFetcher *> fetchers_;
428 std::vector<std::unique_ptr<WatcherState>> watchers_;
429
430 void SendTimingReport();
431 void UpdateTimingReport();
432 void MaybeScheduleTimingReports();
433
434 std::unique_ptr<RawSender> timing_report_sender_;
435
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800436 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800437 virtual pid_t GetTid() = 0;
438
439 FlatbufferDetachedBuffer<timing::Report> timing_report_;
440
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800441 ::std::atomic<bool> is_running_{false};
442
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800444
445 // If true, don't send out timing reports.
446 bool skip_timing_report_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700447};
448
449} // namespace aos
450
451#include "aos/events/event_loop_tmpl.h"
452
453#endif // AOS_EVENTS_EVENT_LOOP_H