blob: 17e3e003288760ce4c1c9cdb07d8ec8802283f5d [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();
51
52 // Fetches the latest message without blocking.
53 bool Fetch();
54
55 // Returns the channel this fetcher uses.
56 const Channel *channel() const { return channel_; }
57 // Returns the context for the current message.
58 const Context &context() const { return context_; }
59
60 protected:
61 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -070062 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -080063
Alex Perrycb7da4b2019-08-28 19:35:56 -070064 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080065
66 private:
67 friend class EventLoop;
68 // Implementation
69 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
70 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
71
Brian Silverman79ec7fc2020-06-08 20:11:22 -050072 EventLoop *const event_loop_;
73 const Channel *const channel_;
74 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080075
76 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050077 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070078};
79
Austin Schuhe0ab4de2023-05-03 08:05:08 -070080using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
81
82// Holds storage for a span object and the data referenced by that span for
83// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
84// points to only the aligned segment of the entire data.
85struct AlignedOwningSpan {
86 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
87
88 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
89 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
90 absl::Span<const uint8_t> span;
91 char *data() { return reinterpret_cast<char *>(this + 1); }
92};
93
94// Constructs a span which owns its data through a shared_ptr. The owning span
95// points to a const view of the data; also returns a temporary mutable span
96// which is only valid while the const shared span is kept alive.
97std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
98
Alex Perrycb7da4b2019-08-28 19:35:56 -070099// Raw version of sender. Sends a block of data. This is used for reflection
100// and as a building block to implement typed senders.
101class RawSender {
102 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700103 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
104
Brian Silverman183859c2022-05-14 02:03:06 -0700105 enum class [[nodiscard]] Error{
milind1f1dca32021-07-03 13:50:07 -0700106 // Represents success and no error
107 kOk,
108
109 // Error for messages on channels being sent faster than their
110 // frequency and channel storage duration allow
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700111 kMessagesSentTooFast,
112 // Access to Redzone was attempted in Sender Queue
Brian Silverman183859c2022-05-14 02:03:06 -0700113 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700114 };
milind1f1dca32021-07-03 13:50:07 -0700115
Austin Schuh39788ff2019-12-01 18:22:57 -0800116 RawSender(EventLoop *event_loop, const Channel *channel);
117 RawSender(const RawSender &) = delete;
118 RawSender &operator=(const RawSender &) = delete;
119
120 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121
Brian Silverman9809c5f2022-07-23 16:12:23 -0700122 // Returns the buffer to write new messages into. This is always valid, and
123 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124 virtual void *data() = 0;
125 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700126
127 // Sends a message without copying it. The users starts by copying up to
128 // size() bytes into the data backed by data(). They then call Send to send.
129 // Returns Error::kOk on a successful send, or
130 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
131 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
132 // attached to the message and are available in the context on the read side.
133 // If they are not populated, the read side will get the sent times instead.
134 Error Send(size_t size);
135 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
136 realtime_clock::time_point realtime_remote_time,
137 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700138
139 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800140 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700141 // Returns Error::kMessagesSentTooFast if messages were sent too fast
142 Error Send(const void *data, size_t size);
143 Error Send(const void *data, size_t size,
144 monotonic_clock::time_point monotonic_remote_time,
145 realtime_clock::time_point realtime_remote_time,
146 uint32_t remote_queue_index, const UUID &source_boot_uuid);
147
148 // CHECKs that no sending Error occurred and logs the channel_ data if
149 // one did
150 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700151
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700152 // Sends a single block of data by refcounting it to avoid copies. The data
153 // must not change after being passed into Send. The remote arguments have the
154 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700155 Error Send(const SharedSpan data);
156 Error Send(const SharedSpan data,
157 monotonic_clock::time_point monotonic_remote_time,
158 realtime_clock::time_point realtime_remote_time,
159 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800160 const Channel *channel() const { return channel_; }
161
Austin Schuhad154822019-12-27 15:45:13 -0800162 // Returns the time_points that the last message was sent at.
163 aos::monotonic_clock::time_point monotonic_sent_time() const {
164 return monotonic_sent_time_;
165 }
166 aos::realtime_clock::time_point realtime_sent_time() const {
167 return realtime_sent_time_;
168 }
169 // Returns the queue index that this was sent with.
170 uint32_t sent_queue_index() const { return sent_queue_index_; }
171
Brian Silvermana1652f32020-01-29 20:41:44 -0800172 // Returns the associated flatbuffers-style allocator. This must be
173 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800174 ChannelPreallocatedAllocator *fbb_allocator() {
175 fbb_allocator_ = ChannelPreallocatedAllocator(
176 reinterpret_cast<uint8_t *>(data()), size(), channel());
Brian Silvermana1652f32020-01-29 20:41:44 -0800177 return &fbb_allocator_;
178 }
179
Brian Silverman4f4e0612020-08-12 19:54:41 -0700180 // Index of the buffer which is currently exposed by data() and the various
181 // other accessors. This is the message the caller should be filling out.
182 virtual int buffer_index() = 0;
183
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800185 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700186 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800187
Austin Schuhb5c6f972021-03-14 21:53:07 -0700188 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
189 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800190 uint32_t sent_queue_index_ = 0xffffffff;
191
Austin Schuh39788ff2019-12-01 18:22:57 -0800192 private:
193 friend class EventLoop;
194
milind1f1dca32021-07-03 13:50:07 -0700195 virtual Error DoSend(const void *data, size_t size,
196 monotonic_clock::time_point monotonic_remote_time,
197 realtime_clock::time_point realtime_remote_time,
198 uint32_t remote_queue_index,
199 const UUID &source_boot_uuid) = 0;
200 virtual Error DoSend(size_t size,
201 monotonic_clock::time_point monotonic_remote_time,
202 realtime_clock::time_point realtime_remote_time,
203 uint32_t remote_queue_index,
204 const UUID &source_boot_uuid) = 0;
205 virtual Error DoSend(const SharedSpan data,
206 monotonic_clock::time_point monotonic_remote_time,
207 realtime_clock::time_point realtime_remote_time,
208 uint32_t remote_queue_index,
209 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800210
James Kuszmaul93abac12022-04-14 15:05:10 -0700211 void RecordSendResult(const Error error, size_t message_size);
212
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500213 EventLoop *const event_loop_;
214 const Channel *const channel_;
215 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700216
Austin Schuh39788ff2019-12-01 18:22:57 -0800217 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500218 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800219
Austin Schuh1af273d2020-03-07 20:11:34 -0800220 ChannelPreallocatedAllocator fbb_allocator_{nullptr, 0, nullptr};
Austin Schuh39788ff2019-12-01 18:22:57 -0800221};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700222
milind1f1dca32021-07-03 13:50:07 -0700223// Needed for compatibility with glog
224std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
225
Alex Perrycb7da4b2019-08-28 19:35:56 -0700226// Fetches the newest message from a channel.
227// This provides a polling based interface for channels.
228template <typename T>
229class Fetcher {
230 public:
231 Fetcher() {}
232
233 // Fetches the next message. Returns true if it fetched a new message. This
234 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800235 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800236 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800237 if (result) {
238 CheckChannelDataAlignment(fetcher_->context().data,
239 fetcher_->context().size);
240 }
241 return result;
242 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243
244 // Fetches the most recent message. Returns true if it fetched a new message.
245 // This will return the latest message regardless of if it was sent before or
246 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800247 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800248 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800249 if (result) {
250 CheckChannelDataAlignment(fetcher_->context().data,
251 fetcher_->context().size);
252 }
253 return result;
254 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255
256 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
257 // available message.
258 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800259 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800260 ? flatbuffers::GetRoot<T>(
261 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700262 : nullptr;
263 }
264
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700265 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800266 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700267
Alex Perrycb7da4b2019-08-28 19:35:56 -0700268 // Returns the context holding timestamps and other metadata about the
269 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800270 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271
272 const T &operator*() const { return *get(); }
273 const T *operator->() const { return get(); }
274
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800275 // Returns true if this fetcher is valid and connected to a channel. If you,
276 // e.g., are using TryMakeFetcher, then you must check valid() before
277 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700278 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700279
Austin Schuhca75b6a2020-12-15 21:12:24 -0800280 // Copies the current flatbuffer into a FlatbufferVector.
281 FlatbufferVector<T> CopyFlatBuffer() const {
282 return context().template CopyFlatBuffer<T>();
283 }
284
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285 private:
286 friend class EventLoop;
287 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
288 : fetcher_(::std::move(fetcher)) {}
289 ::std::unique_ptr<RawFetcher> fetcher_;
290};
291
292// Sends messages to a channel.
293template <typename T>
294class Sender {
295 public:
296 Sender() {}
297
298 // Represents a single message about to be sent to the queue.
299 // The lifecycle goes:
300 //
301 // Builder builder = sender.MakeBuilder();
302 // T::Builder t_builder = builder.MakeBuilder<T>();
303 // Populate(&t_builder);
304 // builder.Send(t_builder.Finish());
305 class Builder {
306 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800307 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800308 : fbb_(allocator->size(), allocator),
309 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800310 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800311 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800312 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800314 Builder() {}
315 Builder(const Builder &) = delete;
316 Builder(Builder &&) = default;
317
318 Builder &operator=(const Builder &) = delete;
319 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320
321 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
322
323 template <typename T2>
324 typename T2::Builder MakeBuilder() {
325 return typename T2::Builder(fbb_);
326 }
327
milind1f1dca32021-07-03 13:50:07 -0700328 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700329 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700330 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800331 // Ensure fbb_ knows it shouldn't access the memory any more.
332 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700333 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334 }
335
milind1f1dca32021-07-03 13:50:07 -0700336 // Equivalent to RawSender::CheckOk
337 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
338
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800340 void CheckSent() {
341 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
342 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343
Brian Silverman341b57e2020-06-23 16:23:18 -0700344 // Detaches a buffer, for later use calling Sender::Send directly.
345 //
346 // Note that the underlying memory remains with the Sender, so creating
347 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
348 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
349 fbb_.Finish(offset);
350 return fbb_.Release();
351 }
352
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800355 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700356 RawSender *sender_;
357 };
358
359 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800360 //
361 // Only a single one of these may be "alive" for this object at any point in
362 // time. After calling Send on the result, it is no longer "alive". This means
363 // that you must manually reset a variable holding the return value (by
364 // assigning a default-constructed Builder to it) before calling this method
365 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 Builder MakeBuilder();
367
Austin Schuha28cbc32019-12-27 16:28:04 -0800368 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700369 // This will copy the data out of the provided flatbuffer, and so does not
370 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700371 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800372
Brian Silverman341b57e2020-06-23 16:23:18 -0700373 // Sends a prebuilt flatbuffer which was detached from a Builder created via
374 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700375 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
376
377 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800378 void CheckOk(const RawSender::Error err) {
379 CHECK_NOTNULL(sender_)->CheckOk(err);
380 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700381
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800382 // Returns the name of the underlying queue, if valid. You must check valid()
383 // first.
384 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385
James Kuszmaulad523042022-10-05 16:47:33 -0700386 // Returns true if the Sender is a valid Sender. If you, e.g., are using
387 // TryMakeSender, then you must check valid() before attempting to use the
388 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800389 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700390 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800391 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800392
Austin Schuh7bc59052020-02-16 23:48:33 -0800393 // Returns the time_points that the last message was sent at.
394 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800395 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800396 }
397 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800398 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800399 }
400 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800401 uint32_t sent_queue_index() const {
402 return CHECK_NOTNULL(sender_)->sent_queue_index();
403 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800404
Brian Silverman4f4e0612020-08-12 19:54:41 -0700405 // Returns the buffer index which MakeBuilder() will expose access to. This is
406 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800407 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700408
Alex Perrycb7da4b2019-08-28 19:35:56 -0700409 private:
410 friend class EventLoop;
411 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
412 std::unique_ptr<RawSender> sender_;
413};
414
milind1f1dca32021-07-03 13:50:07 -0700415// Class for keeping a count of send failures on a certain channel
416class SendFailureCounter {
417 public:
418 inline void Count(const RawSender::Error err) {
419 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
420 just_failed_ = (err != RawSender::Error::kOk);
421 }
422
423 inline size_t failures() const { return failures_; }
424 inline bool just_failed() const { return just_failed_; }
425
426 private:
427 size_t failures_ = 0;
428 bool just_failed_ = false;
429};
430
Brian Silverman4f4e0612020-08-12 19:54:41 -0700431// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432class TimerHandler {
433 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800434 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435
436 // Timer should sleep until base, base + offset, base + offset * 2, ...
437 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700438 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700439 virtual void Schedule(monotonic_clock::time_point base,
440 monotonic_clock::duration repeat_offset =
441 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700442
443 // Stop future calls to callback().
444 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800445
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700446 // Check if the timer is disabled
447 virtual bool IsDisabled() = 0;
448
Austin Schuh1540c2f2019-11-29 21:59:29 -0800449 // Sets and gets the name of the timer. Set this if you want a descriptive
450 // name in the timing report.
451 void set_name(std::string_view name) { name_ = std::string(name); }
452 const std::string_view name() const { return name_; }
453
Austin Schuh39788ff2019-12-01 18:22:57 -0800454 protected:
455 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
456
Austin Schuh9b1d6282022-06-10 17:03:21 -0700457 template <typename T>
458 monotonic_clock::time_point Call(T get_time,
459 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800460
Austin Schuh1540c2f2019-11-29 21:59:29 -0800461 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800462 friend class EventLoop;
463
464 EventLoop *event_loop_;
465 // The function to call when Call is called.
466 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800467 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800468
469 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500470 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700471};
472
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800473// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700474class PhasedLoopHandler {
475 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800476 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700477
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800478 // Sets the interval and offset. Any changes to interval and offset only take
479 // effect when the handler finishes running or upon a call to Reschedule().
480 //
481 // The precise semantics of the monotonic_now parameter are defined in
482 // phased_loop.h. The way that it gets used in this interface is to control
483 // what the cycles elapsed counter will read on the following call to your
484 // handler. In an idealized simulation environment, if you call
485 // set_interval_and_offset() during the phased loop offset without setting
486 // monotonic_now, then you should always see a count of 1 on the next cycle.
487 //
488 // With the default behavior (this is called inside your handler and with
489 // monotonic_now = nullopt), the next phased loop call will occur at most
490 // interval time after the current time. Note that in many cases this will
491 // *not* be the preferred behavior (in most cases, you would likely aim to
492 // keep the average frequency of the calls reasonably consistent).
493 //
494 // A combination of the monotonic_now parameter and manually calling
495 // Reschedule() outside of the phased loop handler can be used to alter the
496 // behavior of cycles_elapsed. For the default behavior, you can set
497 // monotonic_now to the current time. If you call set_interval_and_offset()
498 // and Reschedule() with the same monotonic_now, that will cause the next
499 // callback to occur in the range (monotonic_now, monotonic_now + interval]
500 // and get called with a count of 1 (if the event is actually able to happen
501 // when it is scheduled to). E.g., if you are just adjusting the phased loop
502 // offset (but not the interval) and want to maintain a consistent frequency,
503 // you may call these functions with monotonic_now = now + interval / 2.
504 void set_interval_and_offset(
505 const monotonic_clock::duration interval,
506 const monotonic_clock::duration offset,
507 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
508 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800509 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800510
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800511 // Reruns the scheduler for the phased loop, scheduling the next callback at
512 // the next available time after monotonic_now. This allows
513 // set_interval_and_offset() to be called and have the changes take effect
514 // before the next handler finishes. This will have no effect if run during
515 // the phased loop's own handler.
516 void Reschedule(monotonic_clock::time_point monotonic_now) {
517 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
518 Schedule(phased_loop_.sleep_time());
519 }
520
521 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800522 // name in the timing report.
523 void set_name(std::string_view name) { name_ = std::string(name); }
524 const std::string_view name() const { return name_; }
525
Austin Schuh39788ff2019-12-01 18:22:57 -0800526 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800527 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800528
529 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
530 const monotonic_clock::duration interval,
531 const monotonic_clock::duration offset);
532
Austin Schuh1540c2f2019-11-29 21:59:29 -0800533 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800534 friend class EventLoop;
535
Austin Schuh39788ff2019-12-01 18:22:57 -0800536 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
537
538 EventLoop *event_loop_;
539 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800540 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800541 time::PhasedLoop phased_loop_;
542
543 int cycles_elapsed_ = 0;
544
545 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500546 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547};
548
Austin Schuh3054f5f2021-07-21 15:38:01 -0700549// Note, it is supported to create only:
550// multiple fetchers, and (one sender or one watcher) per <name, type>
551// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552class EventLoop {
553 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700554 // Holds configuration by reference for the lifetime of this object. It may
555 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800556 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559
560 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800561 virtual monotonic_clock::time_point monotonic_now() const = 0;
562 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700564 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800565 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800566 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800567 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800568 true);
569 }
milind1f1dca32021-07-03 13:50:07 -0700570 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800571 template <typename T>
572 bool HasChannel(const std::string_view channel_name) {
573 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700574 }
575
Brian Silverman631b6262021-11-10 12:25:08 -0800576 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800577 // not readable on this node or does not exist. You must check valid() on the
578 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800579 template <typename T>
580 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
581 const Channel *const channel = GetChannel<T>(channel_name);
582 if (channel == nullptr) {
583 return Fetcher<T>();
584 }
585
586 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
587 return Fetcher<T>();
588 }
589
590 return Fetcher<T>(MakeRawFetcher(channel));
591 }
592
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593 // Makes a class that will always fetch the most recent value
594 // sent to the provided channel.
595 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800596 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800597 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
599 << T::GetFullyQualifiedName() << "\" } not found in config.";
600
Brian Silverman631b6262021-11-10 12:25:08 -0800601 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
602 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800603 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
604 << "\", \"type\": \"" << T::GetFullyQualifiedName()
605 << "\" } is not able to be fetched on this node. Check your "
606 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800607 }
608
Brian Silverman631b6262021-11-10 12:25:08 -0800609 return result;
610 }
611
612 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800613 // not sendable on this node or does not exist. You must check valid() on the
614 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800615 template <typename T>
616 Sender<T> TryMakeSender(const std::string_view channel_name) {
617 const Channel *channel = GetChannel<T>(channel_name);
618 if (channel == nullptr) {
619 return Sender<T>();
620 }
621
622 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
623 return Sender<T>();
624 }
625
626 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700627 }
628
629 // Makes class that allows constructing and sending messages to
630 // the provided channel.
631 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800632 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800633 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800635 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700636 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800637 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700638 ? absl::StrCat(" on node ", node()->name()->string_view())
639 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700640
Brian Silverman631b6262021-11-10 12:25:08 -0800641 Sender<T> result = TryMakeSender<T>(channel_name);
642 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800643 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
644 << "\", \"type\": \"" << T::GetFullyQualifiedName()
645 << "\" } is not able to be sent on this node. Check your "
646 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800647 }
648
Brian Silverman631b6262021-11-10 12:25:08 -0800649 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650 }
651
652 // This will watch messages sent to the provided channel.
653 //
Brian Silverman454bc112020-03-05 14:21:25 -0800654 // w must have a non-polymorphic operator() (aka it can only be called with a
655 // single set of arguments; no overloading or templates). It must be callable
656 // with this signature:
657 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658 //
Brian Silverman454bc112020-03-05 14:21:25 -0800659 // Lambdas are a common form for w. A std::function will work too.
660 //
661 // Note that bind expressions have polymorphic call operators, so they are not
662 // allowed.
663 //
664 // We template Watch as a whole instead of using std::function<void(const T
665 // &)> to allow deducing MessageType from lambdas and other things which are
666 // implicitly convertible to std::function, but not actually std::function
667 // instantiations. Template deduction guides might allow solving this
668 // differently in newer versions of C++, but those have their own corner
669 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700670 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800671 void MakeWatcher(const std::string_view channel_name, Watch &&w);
672
673 // Like MakeWatcher, but doesn't have access to the message data. This may be
674 // implemented to use less resources than an equivalent MakeWatcher.
675 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800676 // The function will still have access to context(), although that will have
677 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800678 template <typename MessageType>
679 void MakeNoArgWatcher(const std::string_view channel_name,
680 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681
682 // The passed in function will be called when the event loop starts.
683 // Use this to run code once the thread goes into "real-time-mode",
684 virtual void OnRun(::std::function<void()> on_run) = 0;
685
Austin Schuh217a9782019-12-21 23:02:50 -0800686 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800687 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688
Austin Schuh217a9782019-12-21 23:02:50 -0800689 // Returns the node that this event loop is running on. Returns nullptr if we
690 // are running in single-node mode.
691 virtual const Node *node() const = 0;
692
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 // Creates a timer that executes callback when the timer expires
694 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700695 // TODO(milind): callback should take the number of cycles elapsed as a
696 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700697 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
698
699 // Creates a timer that executes callback periodically at the specified
700 // interval and offset. Returns a PhasedLoopHandler for interacting with the
701 // timer.
702 virtual PhasedLoopHandler *AddPhasedLoop(
703 ::std::function<void(int)> callback,
704 const monotonic_clock::duration interval,
705 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
706
Austin Schuh217a9782019-12-21 23:02:50 -0800707 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700708
Austin Schuh3054f5f2021-07-21 15:38:01 -0700709 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710 bool is_running() const { return is_running_.load(); }
711
712 // Sets the scheduler priority to run the event loop at. This may not be
713 // called after we go into "real-time-mode".
714 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700715 // Defaults to 0 if this loop will not run realtime.
716 virtual int runtime_realtime_priority() const = 0;
717
Austin Schuh070019a2022-12-20 22:23:09 -0800718 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719
Brian Silverman6a54ff32020-04-28 16:41:39 -0700720 // Sets the scheduler affinity to run the event loop with. This may only be
721 // called before Run().
722 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700723 // Defaults to DefaultAffinity() if this loop will not run pinned.
724 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700725
Austin Schuh217a9782019-12-21 23:02:50 -0800726 // Fetches new messages from the provided channel (path, type).
727 //
728 // Note: this channel must be a member of the exact configuration object this
729 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700730 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
731 const Channel *channel) = 0;
732
Austin Schuh217a9782019-12-21 23:02:50 -0800733 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734 virtual void MakeRawWatcher(
735 const Channel *channel,
736 std::function<void(const Context &context, const void *message)>
737 watcher) = 0;
738
Brian Silverman454bc112020-03-05 14:21:25 -0800739 // Watches channel (name, type) for new messages, without needing to extract
740 // the message contents. Default implementation simply re-uses MakeRawWatcher.
741 virtual void MakeRawNoArgWatcher(
742 const Channel *channel,
743 std::function<void(const Context &context)> watcher) {
744 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800745 Context new_context = context;
746 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700747 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800748 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800749 });
750 }
751
Austin Schuh217a9782019-12-21 23:02:50 -0800752 // Creates a raw sender for the provided channel. This is used for reflection
753 // based sending.
754 // Note: this ignores any node constraints. Ignore at your own peril.
755 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
756
Austin Schuh6231cc32019-12-07 13:06:15 -0800757 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700758 const Context &context() const { return context_; }
759
760 // Returns the configuration that this event loop was built with.
761 const Configuration *configuration() const { return configuration_; }
762
Austin Schuh39788ff2019-12-01 18:22:57 -0800763 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800764 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800765
Brian Silverman4f4e0612020-08-12 19:54:41 -0700766 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800767 void SkipAosLog() { skip_logger_ = true; }
768
Brian Silverman4f4e0612020-08-12 19:54:41 -0700769 // Returns the number of buffers for this channel. This corresponds with the
770 // range of Context::buffer_index values for this channel.
771 virtual int NumberBuffers(const Channel *channel) = 0;
772
Austin Schuh20ac95d2020-12-05 17:24:19 -0800773 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800774 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800775
Alex Perrycb7da4b2019-08-28 19:35:56 -0700776 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800777 // Sets the name of the event loop. This is the application name.
778 virtual void set_name(const std::string_view name) = 0;
779
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780 void set_is_running(bool value) { is_running_.store(value); }
781
Austin Schuh39788ff2019-12-01 18:22:57 -0800782 // Validates that channel exists inside configuration_ and finds its index.
783 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700784
Brian Silverman5120afb2020-01-31 17:44:35 -0800785 // Returns the state for the watcher on the corresponding channel. This
786 // watcher must exist before calling this.
787 WatcherState *GetWatcherState(const Channel *channel);
788
Brian Silverman6d2b3592020-06-18 14:40:15 -0700789 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800790 template <typename T>
791 static RawSender *GetRawSender(aos::Sender<T> *sender) {
792 return sender->sender_.get();
793 }
794
Brian Silverman6d2b3592020-06-18 14:40:15 -0700795 // Returns a Fetcher's protected RawFetcher.
796 template <typename T>
797 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
798 return fetcher->fetcher_.get();
799 }
800
Austin Schuh6231cc32019-12-07 13:06:15 -0800801 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700802 Context context_;
803
Austin Schuh39788ff2019-12-01 18:22:57 -0800804 friend class RawSender;
805 friend class TimerHandler;
806 friend class RawFetcher;
807 friend class PhasedLoopHandler;
808 friend class WatcherState;
809
810 // Methods used to implement timing reports.
811 void NewSender(RawSender *sender);
812 void DeleteSender(RawSender *sender);
813 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
814 PhasedLoopHandler *NewPhasedLoop(
815 std::unique_ptr<PhasedLoopHandler> phased_loop);
816 void NewFetcher(RawFetcher *fetcher);
817 void DeleteFetcher(RawFetcher *fetcher);
818 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
819
Brian Silverman0fc69932020-01-24 21:54:02 -0800820 // Tracks that we have a (single) watcher on the given channel.
821 void TakeWatcher(const Channel *channel);
822 // Tracks that we have at least one sender on the given channel.
823 void TakeSender(const Channel *channel);
824
Austin Schuh39788ff2019-12-01 18:22:57 -0800825 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800826 std::vector<RawFetcher *> fetchers_;
827
Austin Schuh39788ff2019-12-01 18:22:57 -0800828 std::vector<std::unique_ptr<TimerHandler>> timers_;
829 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800830 std::vector<std::unique_ptr<WatcherState>> watchers_;
831
Brian Silvermance418d02021-11-03 11:25:52 -0700832 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800833 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700834
Austin Schuh39788ff2019-12-01 18:22:57 -0800835 void UpdateTimingReport();
836 void MaybeScheduleTimingReports();
837
838 std::unique_ptr<RawSender> timing_report_sender_;
839
Austin Schuh7d87b672019-12-01 20:23:49 -0800840 // Tracks which event sources (timers and watchers) have data, and which
841 // don't. Added events may not change their event_time().
842 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
843 // t2 to run, t2 should then be picked up without a context switch.
844 void AddEvent(EventLoopEvent *event);
845 void RemoveEvent(EventLoopEvent *event);
846 size_t EventCount() const { return events_.size(); }
847 EventLoopEvent *PopEvent();
848 EventLoopEvent *PeekEvent() { return events_.front(); }
849 void ReserveEvents();
850
851 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700852 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800853
Tyler Chatow67ddb032020-01-12 14:30:04 -0800854 // If true, don't send AOS_LOG to /aos
855 bool skip_logger_ = false;
856
Austin Schuha9012be2021-07-21 15:19:11 -0700857 // Sets context_ for a timed event which is supposed to happen at the provided
858 // time.
859 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700860 // Clears context_ so it only has invalid times and elements in it.
861 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700862
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800863 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800864 virtual pid_t GetTid() = 0;
865
866 FlatbufferDetachedBuffer<timing::Report> timing_report_;
867
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800868 ::std::atomic<bool> is_running_{false};
869
Alex Perrycb7da4b2019-08-28 19:35:56 -0700870 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800871
872 // If true, don't send out timing reports.
873 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800874
milind1f1dca32021-07-03 13:50:07 -0700875 SendFailureCounter timing_report_failure_counter_;
876
Brian Silverman0fc69932020-01-24 21:54:02 -0800877 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700878};
879
Brian Silvermane1fe2512022-08-14 23:18:50 -0700880// Interface for terminating execution of an EventLoop.
881//
882// Prefer this over binding a lambda to an Exit() method when passing ownership
883// in complicated ways because implementations should have assertions to catch
884// it outliving the object it's referring to, instead of having a
885// use-after-free.
886//
887// This is not exposed by EventLoop directly because different EventLoop
888// implementations provide this functionality at different scopes, or possibly
889// not at all.
890class ExitHandle {
891 public:
892 ExitHandle() = default;
893 virtual ~ExitHandle() = default;
894
895 // Exits some set of event loops. Details depend on the implementation.
896 //
897 // This means no more events will be processed, but any currently being
898 // processed will finish.
899 virtual void Exit() = 0;
900};
901
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902} // namespace aos
903
Austin Schuhb8075812020-10-19 09:36:49 -0700904#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905
906#endif // AOS_EVENTS_EVENT_LOOP_H