blob: 3926e262c9f4064da9d6d561caa06e49254c04ad [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>
milind1f1dca32021-07-03 13:50:07 -07007#include <ostream>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include <string>
James Kuszmaul3ae42262019-11-08 12:33:41 -08009#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -070010
Austin Schuh3054f5f2021-07-21 15:38:01 -070011#include "absl/container/btree_set.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070012#include "flatbuffers/flatbuffers.h"
13#include "glog/logging.h"
14
Alex Perrycb7da4b2019-08-28 19:35:56 -070015#include "aos/configuration.h"
16#include "aos/configuration_generated.h"
Austin Schuh1af273d2020-03-07 20:11:34 -080017#include "aos/events/channel_preallocated_allocator.h"
Austin Schuh82ea7382023-07-14 15:17:34 -070018#include "aos/events/context.h"
Austin Schuh7d87b672019-12-01 20:23:49 -080019#include "aos/events/event_loop_event.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080020#include "aos/events/event_loop_generated.h"
21#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070022#include "aos/flatbuffers.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050023#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080024#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "aos/json_to_flatbuffer.h"
26#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080027#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070028#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070029
Austin Schuh39788ff2019-12-01 18:22:57 -080030DECLARE_bool(timing_reports);
31DECLARE_int32(timing_report_ms);
32
Alex Perrycb7da4b2019-08-28 19:35:56 -070033namespace aos {
34
Austin Schuh39788ff2019-12-01 18:22:57 -080035class EventLoop;
36class WatcherState;
37
Alex Perrycb7da4b2019-08-28 19:35:56 -070038// Raw version of fetcher. Contains a local variable that the fetcher will
39// update. This is used for reflection and as an interface to implement typed
40// fetchers.
41class RawFetcher {
42 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080043 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070044 RawFetcher(const RawFetcher &) = delete;
45 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080046 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070047
Austin Schuh39788ff2019-12-01 18:22:57 -080048 // Fetches the next message in the queue without blocking. Returns true if
49 // there was a new message and we got it.
50 bool FetchNext();
Austin Schuh98ed26f2023-07-19 14:12:28 -070051 // Fetches the next message if there is one, and the provided function returns
52 // true. The data and buffer_index are the only pieces of the Context which
53 // are zeroed out. The function must be valid.
54 bool FetchNextIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080055
56 // Fetches the latest message without blocking.
57 bool Fetch();
Austin Schuh98ed26f2023-07-19 14:12:28 -070058 // Fetches the latest message conditionally without blocking. fn must be
59 // valid.
60 bool FetchIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080061
62 // Returns the channel this fetcher uses.
63 const Channel *channel() const { return channel_; }
64 // Returns the context for the current message.
65 const Context &context() const { return context_; }
66
67 protected:
68 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -070069 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -080070
Alex Perrycb7da4b2019-08-28 19:35:56 -070071 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080072
73 private:
74 friend class EventLoop;
75 // Implementation
76 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070077 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
78 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080079 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070080 virtual std::pair<bool, monotonic_clock::time_point> DoFetchIf(
81 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080082
Brian Silverman79ec7fc2020-06-08 20:11:22 -050083 EventLoop *const event_loop_;
84 const Channel *const channel_;
85 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080086
87 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050088 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070089};
90
Austin Schuhe0ab4de2023-05-03 08:05:08 -070091using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
92
93// Holds storage for a span object and the data referenced by that span for
94// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
95// points to only the aligned segment of the entire data.
96struct AlignedOwningSpan {
97 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
98
99 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
100 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
101 absl::Span<const uint8_t> span;
102 char *data() { return reinterpret_cast<char *>(this + 1); }
103};
104
105// Constructs a span which owns its data through a shared_ptr. The owning span
106// points to a const view of the data; also returns a temporary mutable span
107// which is only valid while the const shared span is kept alive.
108std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
109
Alex Perrycb7da4b2019-08-28 19:35:56 -0700110// Raw version of sender. Sends a block of data. This is used for reflection
111// and as a building block to implement typed senders.
112class RawSender {
113 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700114 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
115
Brian Silverman183859c2022-05-14 02:03:06 -0700116 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700117 // Represents success and no error
118 kOk,
119
120 // Error for messages on channels being sent faster than their
121 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700122 kMessagesSentTooFast,
123 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700124 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700125 };
milind1f1dca32021-07-03 13:50:07 -0700126
Austin Schuh39788ff2019-12-01 18:22:57 -0800127 RawSender(EventLoop *event_loop, const Channel *channel);
128 RawSender(const RawSender &) = delete;
129 RawSender &operator=(const RawSender &) = delete;
130
131 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700132
Brian Silverman9809c5f2022-07-23 16:12:23 -0700133 // Returns the buffer to write new messages into. This is always valid, and
134 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700135 virtual void *data() = 0;
136 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700137
138 // Sends a message without copying it. The users starts by copying up to
139 // size() bytes into the data backed by data(). They then call Send to send.
140 // Returns Error::kOk on a successful send, or
141 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
142 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
143 // attached to the message and are available in the context on the read side.
144 // If they are not populated, the read side will get the sent times instead.
145 Error Send(size_t size);
146 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
147 realtime_clock::time_point realtime_remote_time,
148 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149
150 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800151 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700152 // Returns Error::kMessagesSentTooFast if messages were sent too fast
153 Error Send(const void *data, size_t size);
154 Error Send(const void *data, size_t size,
155 monotonic_clock::time_point monotonic_remote_time,
156 realtime_clock::time_point realtime_remote_time,
157 uint32_t remote_queue_index, const UUID &source_boot_uuid);
158
159 // CHECKs that no sending Error occurred and logs the channel_ data if
160 // one did
161 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700162
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700163 // Sends a single block of data by refcounting it to avoid copies. The data
164 // must not change after being passed into Send. The remote arguments have the
165 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700166 Error Send(const SharedSpan data);
167 Error Send(const SharedSpan data,
168 monotonic_clock::time_point monotonic_remote_time,
169 realtime_clock::time_point realtime_remote_time,
170 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800171 const Channel *channel() const { return channel_; }
172
Austin Schuhad154822019-12-27 15:45:13 -0800173 // Returns the time_points that the last message was sent at.
174 aos::monotonic_clock::time_point monotonic_sent_time() const {
175 return monotonic_sent_time_;
176 }
177 aos::realtime_clock::time_point realtime_sent_time() const {
178 return realtime_sent_time_;
179 }
180 // Returns the queue index that this was sent with.
181 uint32_t sent_queue_index() const { return sent_queue_index_; }
182
Brian Silvermana1652f32020-01-29 20:41:44 -0800183 // Returns the associated flatbuffers-style allocator. This must be
184 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800185 ChannelPreallocatedAllocator *fbb_allocator() {
186 fbb_allocator_ = ChannelPreallocatedAllocator(
187 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800188 return &fbb_allocator_;
189 }
190
Brian Silverman4f4e0612020-08-12 19:54:41 -0700191 // Index of the buffer which is currently exposed by data() and the various
192 // other accessors. This is the message the caller should be filling out.
193 virtual int buffer_index() = 0;
194
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800196 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700197 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800198
Austin Schuhb5c6f972021-03-14 21:53:07 -0700199 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
200 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800201 uint32_t sent_queue_index_ = 0xffffffff;
202
Austin Schuh39788ff2019-12-01 18:22:57 -0800203 private:
204 friend class EventLoop;
205
milind1f1dca32021-07-03 13:50:07 -0700206 virtual Error DoSend(const void *data, size_t size,
207 monotonic_clock::time_point monotonic_remote_time,
208 realtime_clock::time_point realtime_remote_time,
209 uint32_t remote_queue_index,
210 const UUID &source_boot_uuid) = 0;
211 virtual Error DoSend(size_t size,
212 monotonic_clock::time_point monotonic_remote_time,
213 realtime_clock::time_point realtime_remote_time,
214 uint32_t remote_queue_index,
215 const UUID &source_boot_uuid) = 0;
216 virtual Error DoSend(const SharedSpan data,
217 monotonic_clock::time_point monotonic_remote_time,
218 realtime_clock::time_point realtime_remote_time,
219 uint32_t remote_queue_index,
220 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800221
James Kuszmaul93abac12022-04-14 15:05:10 -0700222 void RecordSendResult(const Error error, size_t message_size);
223
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500224 EventLoop *const event_loop_;
225 const Channel *const channel_;
226 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700227
Austin Schuh39788ff2019-12-01 18:22:57 -0800228 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500229 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800230
Austin Schuh1af273d2020-03-07 20:11:34 -0800231 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800232};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700233
milind1f1dca32021-07-03 13:50:07 -0700234// Needed for compatibility with glog
235std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
236
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237// Fetches the newest message from a channel.
238// This provides a polling based interface for channels.
239template <typename T>
240class Fetcher {
241 public:
242 Fetcher() {}
243
244 // Fetches the next message. Returns true if it fetched a new message. This
245 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800246 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800247 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800248 if (result) {
249 CheckChannelDataAlignment(fetcher_->context().data,
250 fetcher_->context().size);
251 }
252 return result;
253 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254
Austin Schuh98ed26f2023-07-19 14:12:28 -0700255 // Fetches the next message if there is one, and the provided function returns
256 // true. The data and buffer_index are the only pieces of the Context which
257 // are zeroed out. The function must be valid.
258 bool FetchNextIf(std::function<bool(const Context &)> fn) {
259 const bool result = CHECK_NOTNULL(fetcher_)->FetchNextIf(std::move(fn));
260 if (result) {
261 CheckChannelDataAlignment(fetcher_->context().data,
262 fetcher_->context().size);
263 }
264 return result;
265 }
266
Alex Perrycb7da4b2019-08-28 19:35:56 -0700267 // Fetches the most recent message. Returns true if it fetched a new message.
268 // This will return the latest message regardless of if it was sent before or
269 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800270 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800271 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800272 if (result) {
273 CheckChannelDataAlignment(fetcher_->context().data,
274 fetcher_->context().size);
275 }
276 return result;
277 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700278
Austin Schuh98ed26f2023-07-19 14:12:28 -0700279 // Fetches the most recent message conditionally. Returns true if it fetched a
280 // new message. This will return the latest message regardless of if it was
281 // sent before or after the fetcher was created. The function must be valid.
282 bool FetchIf(std::function<bool(const Context &)> fn) {
283 const bool result = CHECK_NOTNULL(fetcher_)->FetchIf(std::move(fn));
284 if (result) {
285 CheckChannelDataAlignment(fetcher_->context().data,
286 fetcher_->context().size);
287 }
288 return result;
289 }
290
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
292 // available message.
293 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800294 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800295 ? flatbuffers::GetRoot<T>(
296 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297 : nullptr;
298 }
299
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700300 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800301 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700302
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 // Returns the context holding timestamps and other metadata about the
304 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800305 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700306
307 const T &operator*() const { return *get(); }
308 const T *operator->() const { return get(); }
309
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800310 // Returns true if this fetcher is valid and connected to a channel. If you,
311 // e.g., are using TryMakeFetcher, then you must check valid() before
312 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700313 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700314
Austin Schuhca75b6a2020-12-15 21:12:24 -0800315 // Copies the current flatbuffer into a FlatbufferVector.
316 FlatbufferVector<T> CopyFlatBuffer() const {
317 return context().template CopyFlatBuffer<T>();
318 }
319
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 private:
321 friend class EventLoop;
322 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
323 : fetcher_(::std::move(fetcher)) {}
324 ::std::unique_ptr<RawFetcher> fetcher_;
325};
326
327// Sends messages to a channel.
328template <typename T>
329class Sender {
330 public:
331 Sender() {}
332
333 // Represents a single message about to be sent to the queue.
334 // The lifecycle goes:
335 //
336 // Builder builder = sender.MakeBuilder();
337 // T::Builder t_builder = builder.MakeBuilder<T>();
338 // Populate(&t_builder);
339 // builder.Send(t_builder.Finish());
340 class Builder {
341 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800342 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800343 : fbb_(allocator->size(), allocator),
344 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800345 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800346 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800347 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800349 Builder() {}
350 Builder(const Builder &) = delete;
351 Builder(Builder &&) = default;
352
353 Builder &operator=(const Builder &) = delete;
354 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355
356 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
357
358 template <typename T2>
359 typename T2::Builder MakeBuilder() {
360 return typename T2::Builder(fbb_);
361 }
362
milind1f1dca32021-07-03 13:50:07 -0700363 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700364 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700365 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800366 // Ensure fbb_ knows it shouldn't access the memory any more.
367 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700368 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700369 }
370
milind1f1dca32021-07-03 13:50:07 -0700371 // Equivalent to RawSender::CheckOk
372 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
373
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800375 void CheckSent() {
376 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
377 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700378
Brian Silverman341b57e2020-06-23 16:23:18 -0700379 // Detaches a buffer, for later use calling Sender::Send directly.
380 //
381 // Note that the underlying memory remains with the Sender, so creating
382 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
383 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
384 fbb_.Finish(offset);
385 return fbb_.Release();
386 }
387
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800390 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 RawSender *sender_;
392 };
393
394 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800395 //
396 // Only a single one of these may be "alive" for this object at any point in
397 // time. After calling Send on the result, it is no longer "alive". This means
398 // that you must manually reset a variable holding the return value (by
399 // assigning a default-constructed Builder to it) before calling this method
400 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 Builder MakeBuilder();
402
Austin Schuha28cbc32019-12-27 16:28:04 -0800403 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700404 // This will copy the data out of the provided flatbuffer, and so does not
405 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700406 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800407
Brian Silverman341b57e2020-06-23 16:23:18 -0700408 // Sends a prebuilt flatbuffer which was detached from a Builder created via
409 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700410 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
411
412 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800413 void CheckOk(const RawSender::Error err) {
414 CHECK_NOTNULL(sender_)->CheckOk(err);
415 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700416
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800417 // Returns the name of the underlying queue, if valid. You must check valid()
418 // first.
419 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420
James Kuszmaulad523042022-10-05 16:47:33 -0700421 // Returns true if the Sender is a valid Sender. If you, e.g., are using
422 // TryMakeSender, then you must check valid() before attempting to use the
423 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800424 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700425 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800426 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800427
Austin Schuh7bc59052020-02-16 23:48:33 -0800428 // Returns the time_points that the last message was sent at.
429 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800430 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800431 }
432 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800433 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800434 }
435 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800436 uint32_t sent_queue_index() const {
437 return CHECK_NOTNULL(sender_)->sent_queue_index();
438 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800439
Brian Silverman4f4e0612020-08-12 19:54:41 -0700440 // Returns the buffer index which MakeBuilder() will expose access to. This is
441 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800442 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700443
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444 private:
445 friend class EventLoop;
446 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
447 std::unique_ptr<RawSender> sender_;
448};
449
milind1f1dca32021-07-03 13:50:07 -0700450// Class for keeping a count of send failures on a certain channel
451class SendFailureCounter {
452 public:
453 inline void Count(const RawSender::Error err) {
454 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
455 just_failed_ = (err != RawSender::Error::kOk);
456 }
457
458 inline size_t failures() const { return failures_; }
459 inline bool just_failed() const { return just_failed_; }
460
461 private:
462 size_t failures_ = 0;
463 bool just_failed_ = false;
464};
465
Brian Silverman4f4e0612020-08-12 19:54:41 -0700466// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467class TimerHandler {
468 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800469 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470
471 // Timer should sleep until base, base + offset, base + offset * 2, ...
472 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700473 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700474 virtual void Schedule(monotonic_clock::time_point base,
475 monotonic_clock::duration repeat_offset =
476 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477
478 // Stop future calls to callback().
479 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800480
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700481 // Check if the timer is disabled
482 virtual bool IsDisabled() = 0;
483
Austin Schuh1540c2f2019-11-29 21:59:29 -0800484 // Sets and gets the name of the timer. Set this if you want a descriptive
485 // name in the timing report.
486 void set_name(std::string_view name) { name_ = std::string(name); }
487 const std::string_view name() const { return name_; }
488
Austin Schuh39788ff2019-12-01 18:22:57 -0800489 protected:
490 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
491
Austin Schuh9b1d6282022-06-10 17:03:21 -0700492 template <typename T>
493 monotonic_clock::time_point Call(T get_time,
494 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800495
Austin Schuh1540c2f2019-11-29 21:59:29 -0800496 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800497 friend class EventLoop;
498
499 EventLoop *event_loop_;
500 // The function to call when Call is called.
501 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800502 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800503
504 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500505 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506};
507
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800508// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509class PhasedLoopHandler {
510 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800511 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800513 // Sets the interval and offset. Any changes to interval and offset only take
514 // effect when the handler finishes running or upon a call to Reschedule().
515 //
516 // The precise semantics of the monotonic_now parameter are defined in
517 // phased_loop.h. The way that it gets used in this interface is to control
518 // what the cycles elapsed counter will read on the following call to your
519 // handler. In an idealized simulation environment, if you call
520 // set_interval_and_offset() during the phased loop offset without setting
521 // monotonic_now, then you should always see a count of 1 on the next cycle.
522 //
523 // With the default behavior (this is called inside your handler and with
524 // monotonic_now = nullopt), the next phased loop call will occur at most
525 // interval time after the current time. Note that in many cases this will
526 // *not* be the preferred behavior (in most cases, you would likely aim to
527 // keep the average frequency of the calls reasonably consistent).
528 //
529 // A combination of the monotonic_now parameter and manually calling
530 // Reschedule() outside of the phased loop handler can be used to alter the
531 // behavior of cycles_elapsed. For the default behavior, you can set
532 // monotonic_now to the current time. If you call set_interval_and_offset()
533 // and Reschedule() with the same monotonic_now, that will cause the next
534 // callback to occur in the range (monotonic_now, monotonic_now + interval]
535 // and get called with a count of 1 (if the event is actually able to happen
536 // when it is scheduled to). E.g., if you are just adjusting the phased loop
537 // offset (but not the interval) and want to maintain a consistent frequency,
538 // you may call these functions with monotonic_now = now + interval / 2.
539 void set_interval_and_offset(
540 const monotonic_clock::duration interval,
541 const monotonic_clock::duration offset,
542 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
543 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800544 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800545
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800546 // Reruns the scheduler for the phased loop, scheduling the next callback at
547 // the next available time after monotonic_now. This allows
548 // set_interval_and_offset() to be called and have the changes take effect
549 // before the next handler finishes. This will have no effect if run during
550 // the phased loop's own handler.
551 void Reschedule(monotonic_clock::time_point monotonic_now) {
552 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
553 Schedule(phased_loop_.sleep_time());
554 }
555
556 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800557 // name in the timing report.
558 void set_name(std::string_view name) { name_ = std::string(name); }
559 const std::string_view name() const { return name_; }
560
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800562 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800563
564 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
565 const monotonic_clock::duration interval,
566 const monotonic_clock::duration offset);
567
Austin Schuh1540c2f2019-11-29 21:59:29 -0800568 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800569 friend class EventLoop;
570
Austin Schuh39788ff2019-12-01 18:22:57 -0800571 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
572
573 EventLoop *event_loop_;
574 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800575 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800576 time::PhasedLoop phased_loop_;
577
578 int cycles_elapsed_ = 0;
579
580 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500581 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582};
583
Austin Schuh3054f5f2021-07-21 15:38:01 -0700584// Note, it is supported to create only:
585// multiple fetchers, and (one sender or one watcher) per <name, type>
586// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700587class EventLoop {
588 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700589 // Holds configuration by reference for the lifetime of this object. It may
590 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800591 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700592
Austin Schuh39788ff2019-12-01 18:22:57 -0800593 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700594
595 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800596 virtual monotonic_clock::time_point monotonic_now() const = 0;
597 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700599 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800600 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800601 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800602 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800603 true);
604 }
milind1f1dca32021-07-03 13:50:07 -0700605 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800606 template <typename T>
607 bool HasChannel(const std::string_view channel_name) {
608 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700609 }
610
Brian Silverman631b6262021-11-10 12:25:08 -0800611 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800612 // not readable on this node or does not exist. You must check valid() on the
613 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800614 template <typename T>
615 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
616 const Channel *const channel = GetChannel<T>(channel_name);
617 if (channel == nullptr) {
618 return Fetcher<T>();
619 }
620
621 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
622 return Fetcher<T>();
623 }
624
625 return Fetcher<T>(MakeRawFetcher(channel));
626 }
627
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 // Makes a class that will always fetch the most recent value
629 // sent to the provided channel.
630 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800631 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800632 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700633 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
634 << T::GetFullyQualifiedName() << "\" } not found in config.";
635
Brian Silverman631b6262021-11-10 12:25:08 -0800636 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
637 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800638 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
639 << "\", \"type\": \"" << T::GetFullyQualifiedName()
640 << "\" } is not able to be fetched on this node. Check your "
641 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800642 }
643
Brian Silverman631b6262021-11-10 12:25:08 -0800644 return result;
645 }
646
647 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800648 // not sendable on this node or does not exist. You must check valid() on the
649 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800650 template <typename T>
651 Sender<T> TryMakeSender(const std::string_view channel_name) {
652 const Channel *channel = GetChannel<T>(channel_name);
653 if (channel == nullptr) {
654 return Sender<T>();
655 }
656
657 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
658 return Sender<T>();
659 }
660
661 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700662 }
663
664 // Makes class that allows constructing and sending messages to
665 // the provided channel.
666 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800667 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800668 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700669 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800670 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700671 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800672 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700673 ? absl::StrCat(" on node ", node()->name()->string_view())
674 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700675
Brian Silverman631b6262021-11-10 12:25:08 -0800676 Sender<T> result = TryMakeSender<T>(channel_name);
677 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800678 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
679 << "\", \"type\": \"" << T::GetFullyQualifiedName()
680 << "\" } is not able to be sent on this node. Check your "
681 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800682 }
683
Brian Silverman631b6262021-11-10 12:25:08 -0800684 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 }
686
687 // This will watch messages sent to the provided channel.
688 //
Brian Silverman454bc112020-03-05 14:21:25 -0800689 // w must have a non-polymorphic operator() (aka it can only be called with a
690 // single set of arguments; no overloading or templates). It must be callable
691 // with this signature:
692 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 //
Brian Silverman454bc112020-03-05 14:21:25 -0800694 // Lambdas are a common form for w. A std::function will work too.
695 //
696 // Note that bind expressions have polymorphic call operators, so they are not
697 // allowed.
698 //
699 // We template Watch as a whole instead of using std::function<void(const T
700 // &)> to allow deducing MessageType from lambdas and other things which are
701 // implicitly convertible to std::function, but not actually std::function
702 // instantiations. Template deduction guides might allow solving this
703 // differently in newer versions of C++, but those have their own corner
704 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800706 void MakeWatcher(const std::string_view channel_name, Watch &&w);
707
708 // Like MakeWatcher, but doesn't have access to the message data. This may be
709 // implemented to use less resources than an equivalent MakeWatcher.
710 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800711 // The function will still have access to context(), although that will have
712 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800713 template <typename MessageType>
714 void MakeNoArgWatcher(const std::string_view channel_name,
715 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700716
717 // The passed in function will be called when the event loop starts.
718 // Use this to run code once the thread goes into "real-time-mode",
719 virtual void OnRun(::std::function<void()> on_run) = 0;
720
Austin Schuh217a9782019-12-21 23:02:50 -0800721 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800722 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700723
Austin Schuh217a9782019-12-21 23:02:50 -0800724 // Returns the node that this event loop is running on. Returns nullptr if we
725 // are running in single-node mode.
726 virtual const Node *node() const = 0;
727
Alex Perrycb7da4b2019-08-28 19:35:56 -0700728 // Creates a timer that executes callback when the timer expires
729 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700730 // TODO(milind): callback should take the number of cycles elapsed as a
731 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700732 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
733
734 // Creates a timer that executes callback periodically at the specified
735 // interval and offset. Returns a PhasedLoopHandler for interacting with the
736 // timer.
737 virtual PhasedLoopHandler *AddPhasedLoop(
738 ::std::function<void(int)> callback,
739 const monotonic_clock::duration interval,
740 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
741
Austin Schuh217a9782019-12-21 23:02:50 -0800742 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700743
Austin Schuh3054f5f2021-07-21 15:38:01 -0700744 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700745 bool is_running() const { return is_running_.load(); }
746
747 // Sets the scheduler priority to run the event loop at. This may not be
748 // called after we go into "real-time-mode".
749 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700750 // Defaults to 0 if this loop will not run realtime.
751 virtual int runtime_realtime_priority() const = 0;
752
Austin Schuh070019a2022-12-20 22:23:09 -0800753 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700754
Brian Silverman6a54ff32020-04-28 16:41:39 -0700755 // Sets the scheduler affinity to run the event loop with. This may only be
756 // called before Run().
757 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700758 // Defaults to DefaultAffinity() if this loop will not run pinned.
759 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700760
Austin Schuh217a9782019-12-21 23:02:50 -0800761 // Fetches new messages from the provided channel (path, type).
762 //
763 // Note: this channel must be a member of the exact configuration object this
764 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
766 const Channel *channel) = 0;
767
Austin Schuh217a9782019-12-21 23:02:50 -0800768 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700769 virtual void MakeRawWatcher(
770 const Channel *channel,
771 std::function<void(const Context &context, const void *message)>
772 watcher) = 0;
773
Brian Silverman454bc112020-03-05 14:21:25 -0800774 // Watches channel (name, type) for new messages, without needing to extract
775 // the message contents. Default implementation simply re-uses MakeRawWatcher.
776 virtual void MakeRawNoArgWatcher(
777 const Channel *channel,
778 std::function<void(const Context &context)> watcher) {
779 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800780 Context new_context = context;
781 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700782 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800783 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800784 });
785 }
786
Austin Schuh217a9782019-12-21 23:02:50 -0800787 // Creates a raw sender for the provided channel. This is used for reflection
788 // based sending.
789 // Note: this ignores any node constraints. Ignore at your own peril.
790 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
791
Austin Schuh6231cc32019-12-07 13:06:15 -0800792 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700793 const Context &context() const { return context_; }
794
795 // Returns the configuration that this event loop was built with.
796 const Configuration *configuration() const { return configuration_; }
797
Austin Schuh39788ff2019-12-01 18:22:57 -0800798 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800799 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800800
Brian Silverman4f4e0612020-08-12 19:54:41 -0700801 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800802 void SkipAosLog() { skip_logger_ = true; }
803
Brian Silverman4f4e0612020-08-12 19:54:41 -0700804 // Returns the number of buffers for this channel. This corresponds with the
805 // range of Context::buffer_index values for this channel.
806 virtual int NumberBuffers(const Channel *channel) = 0;
807
Austin Schuh20ac95d2020-12-05 17:24:19 -0800808 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800809 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800810
Alex Perrycb7da4b2019-08-28 19:35:56 -0700811 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800812 // Sets the name of the event loop. This is the application name.
813 virtual void set_name(const std::string_view name) = 0;
814
Alex Perrycb7da4b2019-08-28 19:35:56 -0700815 void set_is_running(bool value) { is_running_.store(value); }
816
Austin Schuh39788ff2019-12-01 18:22:57 -0800817 // Validates that channel exists inside configuration_ and finds its index.
818 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700819
Brian Silverman5120afb2020-01-31 17:44:35 -0800820 // Returns the state for the watcher on the corresponding channel. This
821 // watcher must exist before calling this.
822 WatcherState *GetWatcherState(const Channel *channel);
823
Brian Silverman6d2b3592020-06-18 14:40:15 -0700824 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800825 template <typename T>
826 static RawSender *GetRawSender(aos::Sender<T> *sender) {
827 return sender->sender_.get();
828 }
829
Brian Silverman6d2b3592020-06-18 14:40:15 -0700830 // Returns a Fetcher's protected RawFetcher.
831 template <typename T>
832 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
833 return fetcher->fetcher_.get();
834 }
835
Austin Schuh6231cc32019-12-07 13:06:15 -0800836 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700837 Context context_;
838
Austin Schuh39788ff2019-12-01 18:22:57 -0800839 friend class RawSender;
840 friend class TimerHandler;
841 friend class RawFetcher;
842 friend class PhasedLoopHandler;
843 friend class WatcherState;
844
845 // Methods used to implement timing reports.
846 void NewSender(RawSender *sender);
847 void DeleteSender(RawSender *sender);
848 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
849 PhasedLoopHandler *NewPhasedLoop(
850 std::unique_ptr<PhasedLoopHandler> phased_loop);
851 void NewFetcher(RawFetcher *fetcher);
852 void DeleteFetcher(RawFetcher *fetcher);
853 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
854
Brian Silverman0fc69932020-01-24 21:54:02 -0800855 // Tracks that we have a (single) watcher on the given channel.
856 void TakeWatcher(const Channel *channel);
857 // Tracks that we have at least one sender on the given channel.
858 void TakeSender(const Channel *channel);
859
Austin Schuh39788ff2019-12-01 18:22:57 -0800860 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800861 std::vector<RawFetcher *> fetchers_;
862
Austin Schuh39788ff2019-12-01 18:22:57 -0800863 std::vector<std::unique_ptr<TimerHandler>> timers_;
864 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800865 std::vector<std::unique_ptr<WatcherState>> watchers_;
866
Brian Silvermance418d02021-11-03 11:25:52 -0700867 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800868 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700869
Austin Schuh39788ff2019-12-01 18:22:57 -0800870 void UpdateTimingReport();
871 void MaybeScheduleTimingReports();
872
873 std::unique_ptr<RawSender> timing_report_sender_;
874
Austin Schuh7d87b672019-12-01 20:23:49 -0800875 // Tracks which event sources (timers and watchers) have data, and which
876 // don't. Added events may not change their event_time().
877 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
878 // t2 to run, t2 should then be picked up without a context switch.
879 void AddEvent(EventLoopEvent *event);
880 void RemoveEvent(EventLoopEvent *event);
881 size_t EventCount() const { return events_.size(); }
882 EventLoopEvent *PopEvent();
883 EventLoopEvent *PeekEvent() { return events_.front(); }
884 void ReserveEvents();
885
886 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700887 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800888
Tyler Chatow67ddb032020-01-12 14:30:04 -0800889 // If true, don't send AOS_LOG to /aos
890 bool skip_logger_ = false;
891
Austin Schuha9012be2021-07-21 15:19:11 -0700892 // Sets context_ for a timed event which is supposed to happen at the provided
893 // time.
894 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700895 // Clears context_ so it only has invalid times and elements in it.
896 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700897
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800898 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800899 virtual pid_t GetTid() = 0;
900
901 FlatbufferDetachedBuffer<timing::Report> timing_report_;
902
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800903 ::std::atomic<bool> is_running_{false};
904
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800906
907 // If true, don't send out timing reports.
908 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800909
milind1f1dca32021-07-03 13:50:07 -0700910 SendFailureCounter timing_report_failure_counter_;
911
Brian Silverman0fc69932020-01-24 21:54:02 -0800912 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700913};
914
Brian Silvermane1fe2512022-08-14 23:18:50 -0700915// Interface for terminating execution of an EventLoop.
916//
917// Prefer this over binding a lambda to an Exit() method when passing ownership
918// in complicated ways because implementations should have assertions to catch
919// it outliving the object it's referring to, instead of having a
920// use-after-free.
921//
922// This is not exposed by EventLoop directly because different EventLoop
923// implementations provide this functionality at different scopes, or possibly
924// not at all.
925class ExitHandle {
926 public:
927 ExitHandle() = default;
928 virtual ~ExitHandle() = default;
929
930 // Exits some set of event loops. Details depend on the implementation.
931 //
932 // This means no more events will be processed, but any currently being
933 // processed will finish.
934 virtual void Exit() = 0;
935};
936
Alex Perrycb7da4b2019-08-28 19:35:56 -0700937} // namespace aos
938
Austin Schuhb8075812020-10-19 09:36:49 -0700939#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700940
941#endif // AOS_EVENTS_EVENT_LOOP_H