blob: d0e3f2aed3e6fba790e78ffe7bfa05843154f05f [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"
James Kuszmaulb1c11052023-11-06 13:20:53 -080023#include "aos/flatbuffers/builder.h"
Brian Silverman79ec7fc2020-06-08 20:11:22 -050024#include "aos/ftrace.h"
Brian Silvermana1652f32020-01-29 20:41:44 -080025#include "aos/ipc_lib/data_alignment.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070026#include "aos/json_to_flatbuffer.h"
27#include "aos/time/time.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080028#include "aos/util/phased_loop.h"
Austin Schuh4385b142021-03-14 21:31:13 -070029#include "aos/uuid.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070030
Austin Schuh39788ff2019-12-01 18:22:57 -080031DECLARE_bool(timing_reports);
32DECLARE_int32(timing_report_ms);
33
Alex Perrycb7da4b2019-08-28 19:35:56 -070034namespace aos {
35
Austin Schuh39788ff2019-12-01 18:22:57 -080036class EventLoop;
37class WatcherState;
38
Alex Perrycb7da4b2019-08-28 19:35:56 -070039// Raw version of fetcher. Contains a local variable that the fetcher will
40// update. This is used for reflection and as an interface to implement typed
41// fetchers.
42class RawFetcher {
43 public:
Austin Schuh39788ff2019-12-01 18:22:57 -080044 RawFetcher(EventLoop *event_loop, const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -070045 RawFetcher(const RawFetcher &) = delete;
46 RawFetcher &operator=(const RawFetcher &) = delete;
Austin Schuh39788ff2019-12-01 18:22:57 -080047 virtual ~RawFetcher();
Alex Perrycb7da4b2019-08-28 19:35:56 -070048
Austin Schuh39788ff2019-12-01 18:22:57 -080049 // Fetches the next message in the queue without blocking. Returns true if
50 // there was a new message and we got it.
51 bool FetchNext();
Austin Schuh98ed26f2023-07-19 14:12:28 -070052 // Fetches the next message if there is one, and the provided function returns
53 // true. The data and buffer_index are the only pieces of the Context which
54 // are zeroed out. The function must be valid.
55 bool FetchNextIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080056
57 // Fetches the latest message without blocking.
58 bool Fetch();
Austin Schuh98ed26f2023-07-19 14:12:28 -070059 // Fetches the latest message conditionally without blocking. fn must be
60 // valid.
61 bool FetchIf(std::function<bool(const Context &context)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080062
63 // Returns the channel this fetcher uses.
64 const Channel *channel() const { return channel_; }
65 // Returns the context for the current message.
66 const Context &context() const { return context_; }
67
68 protected:
69 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -070070 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh39788ff2019-12-01 18:22:57 -080071
Alex Perrycb7da4b2019-08-28 19:35:56 -070072 Context context_;
Austin Schuh39788ff2019-12-01 18:22:57 -080073
74 private:
75 friend class EventLoop;
76 // Implementation
77 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNext() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070078 virtual std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
79 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080080 virtual std::pair<bool, monotonic_clock::time_point> DoFetch() = 0;
Austin Schuh98ed26f2023-07-19 14:12:28 -070081 virtual std::pair<bool, monotonic_clock::time_point> DoFetchIf(
82 std::function<bool(const Context &)> fn) = 0;
Austin Schuh39788ff2019-12-01 18:22:57 -080083
Brian Silverman79ec7fc2020-06-08 20:11:22 -050084 EventLoop *const event_loop_;
85 const Channel *const channel_;
86 const std::string ftrace_prefix_;
Austin Schuh39788ff2019-12-01 18:22:57 -080087
88 internal::RawFetcherTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -050089 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -070090};
91
Austin Schuhe0ab4de2023-05-03 08:05:08 -070092using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
93
94// Holds storage for a span object and the data referenced by that span for
95// compatibility with SharedSpan users. If constructed with MakeSharedSpan, span
96// points to only the aligned segment of the entire data.
97struct AlignedOwningSpan {
98 AlignedOwningSpan(absl::Span<const uint8_t> new_span) : span(new_span) {}
99
100 AlignedOwningSpan(const AlignedOwningSpan &) = delete;
101 AlignedOwningSpan &operator=(const AlignedOwningSpan &) = delete;
102 absl::Span<const uint8_t> span;
103 char *data() { return reinterpret_cast<char *>(this + 1); }
104};
105
106// Constructs a span which owns its data through a shared_ptr. The owning span
107// points to a const view of the data; also returns a temporary mutable span
108// which is only valid while the const shared span is kept alive.
109std::pair<SharedSpan, absl::Span<uint8_t>> MakeSharedSpan(size_t size);
110
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111// Raw version of sender. Sends a block of data. This is used for reflection
112// and as a building block to implement typed senders.
113class RawSender {
114 public:
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700115 using SharedSpan = std::shared_ptr<const absl::Span<const uint8_t>>;
116
Austin Schuh50e3dca2023-07-23 14:34:27 -0700117 enum class [[nodiscard]] Error {
118 // Represents success and no error
119 kOk,
milind1f1dca32021-07-03 13:50:07 -0700120
Austin Schuh50e3dca2023-07-23 14:34:27 -0700121 // Error for messages on channels being sent faster than their
122 // frequency and channel storage duration allow
123 kMessagesSentTooFast,
124 // Access to Redzone was attempted in Sender Queue
125 kInvalidRedzone,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700126 };
milind1f1dca32021-07-03 13:50:07 -0700127
Austin Schuh39788ff2019-12-01 18:22:57 -0800128 RawSender(EventLoop *event_loop, const Channel *channel);
129 RawSender(const RawSender &) = delete;
130 RawSender &operator=(const RawSender &) = delete;
131
132 virtual ~RawSender();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133
Brian Silverman9809c5f2022-07-23 16:12:23 -0700134 // Returns the buffer to write new messages into. This is always valid, and
135 // may change after calling any of the Send functions.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700136 virtual void *data() = 0;
137 virtual size_t size() = 0;
milind1f1dca32021-07-03 13:50:07 -0700138
139 // Sends a message without copying it. The users starts by copying up to
140 // size() bytes into the data backed by data(). They then call Send to send.
141 // Returns Error::kOk on a successful send, or
142 // Error::kMessagesSentTooFast if messages were sent too fast. If provided,
143 // monotonic_remote_time, realtime_remote_time, and remote_queue_index are
144 // attached to the message and are available in the context on the read side.
145 // If they are not populated, the read side will get the sent times instead.
146 Error Send(size_t size);
147 Error Send(size_t size, monotonic_clock::time_point monotonic_remote_time,
148 realtime_clock::time_point realtime_remote_time,
149 uint32_t remote_queue_index, const UUID &source_boot_uuid);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150
151 // Sends a single block of data by copying it.
Austin Schuhad154822019-12-27 15:45:13 -0800152 // The remote arguments have the same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700153 // Returns Error::kMessagesSentTooFast if messages were sent too fast
154 Error Send(const void *data, size_t size);
155 Error Send(const void *data, size_t size,
156 monotonic_clock::time_point monotonic_remote_time,
157 realtime_clock::time_point realtime_remote_time,
158 uint32_t remote_queue_index, const UUID &source_boot_uuid);
159
160 // CHECKs that no sending Error occurred and logs the channel_ data if
161 // one did
162 void CheckOk(const Error err);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700164 // Sends a single block of data by refcounting it to avoid copies. The data
165 // must not change after being passed into Send. The remote arguments have the
166 // same meaning as in Send above.
milind1f1dca32021-07-03 13:50:07 -0700167 Error Send(const SharedSpan data);
168 Error Send(const SharedSpan data,
169 monotonic_clock::time_point monotonic_remote_time,
170 realtime_clock::time_point realtime_remote_time,
171 uint32_t remote_queue_index, const UUID &remote_boot_uuid);
Austin Schuh54cf95f2019-11-29 13:14:18 -0800172 const Channel *channel() const { return channel_; }
173
Austin Schuhad154822019-12-27 15:45:13 -0800174 // Returns the time_points that the last message was sent at.
175 aos::monotonic_clock::time_point monotonic_sent_time() const {
176 return monotonic_sent_time_;
177 }
178 aos::realtime_clock::time_point realtime_sent_time() const {
179 return realtime_sent_time_;
180 }
181 // Returns the queue index that this was sent with.
182 uint32_t sent_queue_index() const { return sent_queue_index_; }
183
Brian Silvermana1652f32020-01-29 20:41:44 -0800184 // Returns the associated flatbuffers-style allocator. This must be
185 // deallocated before the message is sent.
Austin Schuh1af273d2020-03-07 20:11:34 -0800186 ChannelPreallocatedAllocator *fbb_allocator() {
James Kuszmaulb1c11052023-11-06 13:20:53 -0800187 CHECK(!static_allocator_.has_value())
188 << ": May not mix-and-match static and raw flatbuffer builders.";
189 if (fbb_allocator_.has_value()) {
190 CHECK(!fbb_allocator_.value().allocated())
191 << ": May not have multiple active allocators on a single sender.";
192 }
193 return &fbb_allocator_.emplace(reinterpret_cast<uint8_t *>(data()), size(),
194 channel());
195 }
196
197 fbs::SpanAllocator *static_allocator() {
198 CHECK(!fbb_allocator_.has_value())
199 << ": May not mix-and-match static and raw flatbuffer builders.";
200 return &static_allocator_.emplace(
201 std::span<uint8_t>{reinterpret_cast<uint8_t *>(data()), size()});
Brian Silvermana1652f32020-01-29 20:41:44 -0800202 }
203
Brian Silverman4f4e0612020-08-12 19:54:41 -0700204 // Index of the buffer which is currently exposed by data() and the various
205 // other accessors. This is the message the caller should be filling out.
206 virtual int buffer_index() = 0;
207
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208 protected:
Austin Schuh39788ff2019-12-01 18:22:57 -0800209 EventLoop *event_loop() { return event_loop_; }
Austin Schuh3054f5f2021-07-21 15:38:01 -0700210 const EventLoop *event_loop() const { return event_loop_; }
Austin Schuh54cf95f2019-11-29 13:14:18 -0800211
Austin Schuhb5c6f972021-03-14 21:53:07 -0700212 monotonic_clock::time_point monotonic_sent_time_ = monotonic_clock::min_time;
213 realtime_clock::time_point realtime_sent_time_ = realtime_clock::min_time;
Austin Schuhad154822019-12-27 15:45:13 -0800214 uint32_t sent_queue_index_ = 0xffffffff;
215
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 private:
217 friend class EventLoop;
218
milind1f1dca32021-07-03 13:50:07 -0700219 virtual Error DoSend(const void *data, size_t size,
220 monotonic_clock::time_point monotonic_remote_time,
221 realtime_clock::time_point realtime_remote_time,
222 uint32_t remote_queue_index,
223 const UUID &source_boot_uuid) = 0;
224 virtual Error DoSend(size_t size,
225 monotonic_clock::time_point monotonic_remote_time,
226 realtime_clock::time_point realtime_remote_time,
227 uint32_t remote_queue_index,
228 const UUID &source_boot_uuid) = 0;
229 virtual Error DoSend(const SharedSpan data,
230 monotonic_clock::time_point monotonic_remote_time,
231 realtime_clock::time_point realtime_remote_time,
232 uint32_t remote_queue_index,
233 const UUID &source_boot_uuid);
Austin Schuh39788ff2019-12-01 18:22:57 -0800234
James Kuszmaul93abac12022-04-14 15:05:10 -0700235 void RecordSendResult(const Error error, size_t message_size);
236
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500237 EventLoop *const event_loop_;
238 const Channel *const channel_;
239 const std::string ftrace_prefix_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700240
Austin Schuh39788ff2019-12-01 18:22:57 -0800241 internal::RawSenderTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500242 Ftrace ftrace_;
Brian Silvermana1652f32020-01-29 20:41:44 -0800243
James Kuszmaulb1c11052023-11-06 13:20:53 -0800244 // Depending on which API is being used, we will populate either
245 // fbb_allocator_ (for use with FlatBufferBuilders) or the SpanAllocator (for
246 // use with the static flatbuffer API).
247 std::optional<ChannelPreallocatedAllocator> fbb_allocator_;
248 std::optional<fbs::SpanAllocator> static_allocator_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800249};
Alex Perrycb7da4b2019-08-28 19:35:56 -0700250
milind1f1dca32021-07-03 13:50:07 -0700251// Needed for compatibility with glog
252std::ostream &operator<<(std::ostream &os, const RawSender::Error err);
253
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254// Fetches the newest message from a channel.
255// This provides a polling based interface for channels.
256template <typename T>
257class Fetcher {
258 public:
259 Fetcher() {}
260
261 // Fetches the next message. Returns true if it fetched a new message. This
262 // method will only return messages sent after the Fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800263 bool FetchNext() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800264 const bool result = CHECK_NOTNULL(fetcher_)->FetchNext();
Brian Silvermana1652f32020-01-29 20:41:44 -0800265 if (result) {
266 CheckChannelDataAlignment(fetcher_->context().data,
267 fetcher_->context().size);
268 }
269 return result;
270 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700271
Austin Schuh98ed26f2023-07-19 14:12:28 -0700272 // Fetches the next message if there is one, and the provided function returns
273 // true. The data and buffer_index are the only pieces of the Context which
274 // are zeroed out. The function must be valid.
275 bool FetchNextIf(std::function<bool(const Context &)> fn) {
276 const bool result = CHECK_NOTNULL(fetcher_)->FetchNextIf(std::move(fn));
277 if (result) {
278 CheckChannelDataAlignment(fetcher_->context().data,
279 fetcher_->context().size);
280 }
281 return result;
282 }
283
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 // Fetches the most recent message. Returns true if it fetched a new message.
285 // This will return the latest message regardless of if it was sent before or
286 // after the fetcher was created.
Brian Silvermana1652f32020-01-29 20:41:44 -0800287 bool Fetch() {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800288 const bool result = CHECK_NOTNULL(fetcher_)->Fetch();
Brian Silvermana1652f32020-01-29 20:41:44 -0800289 if (result) {
290 CheckChannelDataAlignment(fetcher_->context().data,
291 fetcher_->context().size);
292 }
293 return result;
294 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700295
Austin Schuh98ed26f2023-07-19 14:12:28 -0700296 // Fetches the most recent message conditionally. Returns true if it fetched a
297 // new message. This will return the latest message regardless of if it was
298 // sent before or after the fetcher was created. The function must be valid.
299 bool FetchIf(std::function<bool(const Context &)> fn) {
300 const bool result = CHECK_NOTNULL(fetcher_)->FetchIf(std::move(fn));
301 if (result) {
302 CheckChannelDataAlignment(fetcher_->context().data,
303 fetcher_->context().size);
304 }
305 return result;
306 }
307
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 // Returns a pointer to the contained flatbuffer, or nullptr if there is no
309 // available message.
310 const T *get() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800311 return CHECK_NOTNULL(fetcher_)->context().data != nullptr
Austin Schuh39788ff2019-12-01 18:22:57 -0800312 ? flatbuffers::GetRoot<T>(
313 reinterpret_cast<const char *>(fetcher_->context().data))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314 : nullptr;
315 }
316
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700317 // Returns the channel this fetcher uses
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800318 const Channel *channel() const { return CHECK_NOTNULL(fetcher_)->channel(); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700319
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 // Returns the context holding timestamps and other metadata about the
321 // message.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800322 const Context &context() const { return CHECK_NOTNULL(fetcher_)->context(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323
324 const T &operator*() const { return *get(); }
325 const T *operator->() const { return get(); }
326
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800327 // Returns true if this fetcher is valid and connected to a channel. If you,
328 // e.g., are using TryMakeFetcher, then you must check valid() before
329 // attempting to use the Fetcher.
Milind Upadhyay49174a72021-04-10 16:24:57 -0700330 bool valid() const { return static_cast<bool>(fetcher_); }
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700331
Austin Schuhca75b6a2020-12-15 21:12:24 -0800332 // Copies the current flatbuffer into a FlatbufferVector.
333 FlatbufferVector<T> CopyFlatBuffer() const {
334 return context().template CopyFlatBuffer<T>();
335 }
336
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337 private:
338 friend class EventLoop;
339 Fetcher(::std::unique_ptr<RawFetcher> fetcher)
340 : fetcher_(::std::move(fetcher)) {}
341 ::std::unique_ptr<RawFetcher> fetcher_;
342};
343
344// Sends messages to a channel.
James Kuszmaulb1c11052023-11-06 13:20:53 -0800345// The type T used with the Sender may either be a raw flatbuffer type (e.g.,
346// aos::examples::Ping) or the static flatbuffer type (e.g.
347// aos::examples::PingStatic). The Builder type that you use must correspond
348// with the flatbuffer type being used.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700349template <typename T>
350class Sender {
351 public:
352 Sender() {}
353
James Kuszmaulb1c11052023-11-06 13:20:53 -0800354 // Represents a single message that is about to be sent on the channel.
355 // Uses the static flatbuffer API rather than the FlatBufferBuilder paradigm.
356 //
357 // Typical usage pattern is:
358 //
359 // Sender<PingStatic>::Builder builder = sender.MakeStaticBuilder()
360 // builder.get()->set_value(971);
361 // builder.CheckOk(builder.Send());
362 class StaticBuilder {
363 public:
364 StaticBuilder(RawSender *sender, fbs::SpanAllocator *allocator)
365 : builder_(allocator), sender_(CHECK_NOTNULL(sender)) {}
366 StaticBuilder(const StaticBuilder &) = delete;
367 StaticBuilder(StaticBuilder &&) = default;
368
369 StaticBuilder &operator=(const StaticBuilder &) = delete;
370 StaticBuilder &operator=(StaticBuilder &&) = default;
371
372 fbs::Builder<T> *builder() {
373 DCHECK(builder_.has_value());
374 return &builder_.value();
375 }
376
377 T *get() { return builder()->get(); }
378
379 RawSender::Error Send() {
380 const auto err = sender_->Send(builder_.value().buffer().size());
381 builder_.reset();
382 return err;
383 }
384
385 // Equivalent to RawSender::CheckOk
386 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
387
388 private:
389 std::optional<fbs::Builder<T>> builder_;
390 RawSender *sender_;
391 };
392
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 // Represents a single message about to be sent to the queue.
394 // The lifecycle goes:
395 //
396 // Builder builder = sender.MakeBuilder();
397 // T::Builder t_builder = builder.MakeBuilder<T>();
398 // Populate(&t_builder);
399 // builder.Send(t_builder.Finish());
400 class Builder {
401 public:
Austin Schuh1af273d2020-03-07 20:11:34 -0800402 Builder(RawSender *sender, ChannelPreallocatedAllocator *allocator)
Brian Silverman9dd793b2020-01-31 23:52:21 -0800403 : fbb_(allocator->size(), allocator),
404 allocator_(allocator),
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800405 sender_(CHECK_NOTNULL(sender)) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800406 CheckChannelDataAlignment(allocator->data(), allocator->size());
Austin Schuhd7b15da2020-02-17 15:06:11 -0800407 fbb_.ForceDefaults(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 }
Brian Silvermana1652f32020-01-29 20:41:44 -0800409 Builder() {}
410 Builder(const Builder &) = delete;
411 Builder(Builder &&) = default;
412
413 Builder &operator=(const Builder &) = delete;
414 Builder &operator=(Builder &&) = default;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700415
416 flatbuffers::FlatBufferBuilder *fbb() { return &fbb_; }
417
418 template <typename T2>
419 typename T2::Builder MakeBuilder() {
420 return typename T2::Builder(fbb_);
421 }
422
milind1f1dca32021-07-03 13:50:07 -0700423 RawSender::Error Send(flatbuffers::Offset<T> offset) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700424 fbb_.Finish(offset);
milind1f1dca32021-07-03 13:50:07 -0700425 const auto err = sender_->Send(fbb_.GetSize());
Brian Silverman9dd793b2020-01-31 23:52:21 -0800426 // Ensure fbb_ knows it shouldn't access the memory any more.
427 fbb_ = flatbuffers::FlatBufferBuilder();
milind1f1dca32021-07-03 13:50:07 -0700428 return err;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700429 }
430
milind1f1dca32021-07-03 13:50:07 -0700431 // Equivalent to RawSender::CheckOk
432 void CheckOk(const RawSender::Error err) { sender_->CheckOk(err); };
433
Alex Perrycb7da4b2019-08-28 19:35:56 -0700434 // CHECKs that this message was sent.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800435 void CheckSent() {
436 CHECK(!allocator_->is_allocated()) << ": Message was not sent yet";
437 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438
Brian Silverman341b57e2020-06-23 16:23:18 -0700439 // Detaches a buffer, for later use calling Sender::Send directly.
440 //
441 // Note that the underlying memory remains with the Sender, so creating
442 // another Builder before destroying the FlatbufferDetachedBuffer will fail.
443 FlatbufferDetachedBuffer<T> Detach(flatbuffers::Offset<T> offset) {
444 fbb_.Finish(offset);
445 return fbb_.Release();
446 }
447
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449 flatbuffers::FlatBufferBuilder fbb_;
Austin Schuh1af273d2020-03-07 20:11:34 -0800450 ChannelPreallocatedAllocator *allocator_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 RawSender *sender_;
452 };
453
454 // Constructs an above builder.
Brian Silverman9dd793b2020-01-31 23:52:21 -0800455 //
456 // Only a single one of these may be "alive" for this object at any point in
457 // time. After calling Send on the result, it is no longer "alive". This means
458 // that you must manually reset a variable holding the return value (by
459 // assigning a default-constructed Builder to it) before calling this method
460 // again to overwrite the value in the variable.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 Builder MakeBuilder();
James Kuszmaulb1c11052023-11-06 13:20:53 -0800462 StaticBuilder MakeStaticBuilder() {
463 return StaticBuilder(sender_.get(), sender_->static_allocator());
464 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465
Austin Schuha28cbc32019-12-27 16:28:04 -0800466 // Sends a prebuilt flatbuffer.
James Kuszmaulad523042022-10-05 16:47:33 -0700467 // This will copy the data out of the provided flatbuffer, and so does not
468 // have to correspond to an existing Builder.
milind1f1dca32021-07-03 13:50:07 -0700469 RawSender::Error Send(const NonSizePrefixedFlatbuffer<T> &flatbuffer);
Austin Schuha28cbc32019-12-27 16:28:04 -0800470
Brian Silverman341b57e2020-06-23 16:23:18 -0700471 // Sends a prebuilt flatbuffer which was detached from a Builder created via
472 // MakeBuilder() on this object.
milind1f1dca32021-07-03 13:50:07 -0700473 RawSender::Error SendDetached(FlatbufferDetachedBuffer<T> detached);
474
475 // Equivalent to RawSender::CheckOk
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800476 void CheckOk(const RawSender::Error err) {
477 CHECK_NOTNULL(sender_)->CheckOk(err);
478 };
Brian Silverman341b57e2020-06-23 16:23:18 -0700479
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800480 // Returns the name of the underlying queue, if valid. You must check valid()
481 // first.
482 const Channel *channel() const { return CHECK_NOTNULL(sender_)->channel(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483
James Kuszmaulad523042022-10-05 16:47:33 -0700484 // Returns true if the Sender is a valid Sender. If you, e.g., are using
485 // TryMakeSender, then you must check valid() before attempting to use the
486 // Sender.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800487 // TODO(austin): Deprecate the operator bool.
Austin Schuha0c41ba2020-09-10 22:59:14 -0700488 operator bool() const { return sender_ ? true : false; }
Austin Schuhe33c08d2022-02-03 18:15:21 -0800489 bool valid() const { return static_cast<bool>(sender_); }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800490
Austin Schuh7bc59052020-02-16 23:48:33 -0800491 // Returns the time_points that the last message was sent at.
492 aos::monotonic_clock::time_point monotonic_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800493 return CHECK_NOTNULL(sender_)->monotonic_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800494 }
495 aos::realtime_clock::time_point realtime_sent_time() const {
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800496 return CHECK_NOTNULL(sender_)->realtime_sent_time();
Austin Schuh7bc59052020-02-16 23:48:33 -0800497 }
498 // Returns the queue index that this was sent with.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800499 uint32_t sent_queue_index() const {
500 return CHECK_NOTNULL(sender_)->sent_queue_index();
501 }
Austin Schuh7bc59052020-02-16 23:48:33 -0800502
Brian Silverman4f4e0612020-08-12 19:54:41 -0700503 // Returns the buffer index which MakeBuilder() will expose access to. This is
504 // the buffer the caller can fill out.
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800505 int buffer_index() const { return CHECK_NOTNULL(sender_)->buffer_index(); }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700506
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 private:
508 friend class EventLoop;
509 Sender(std::unique_ptr<RawSender> sender) : sender_(std::move(sender)) {}
510 std::unique_ptr<RawSender> sender_;
511};
512
milind1f1dca32021-07-03 13:50:07 -0700513// Class for keeping a count of send failures on a certain channel
514class SendFailureCounter {
515 public:
516 inline void Count(const RawSender::Error err) {
517 failures_ += static_cast<size_t>(err != RawSender::Error::kOk);
518 just_failed_ = (err != RawSender::Error::kOk);
519 }
520
521 inline size_t failures() const { return failures_; }
522 inline bool just_failed() const { return just_failed_; }
523
524 private:
525 size_t failures_ = 0;
526 bool just_failed_ = false;
527};
528
Brian Silverman4f4e0612020-08-12 19:54:41 -0700529// Interface for timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530class TimerHandler {
531 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800532 virtual ~TimerHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533
534 // Timer should sleep until base, base + offset, base + offset * 2, ...
535 // If repeat_offset isn't set, the timer only expires once.
James Kuszmaul8866e642022-06-10 16:00:36 -0700536 // base must be greater than or equal to zero.
Philipp Schradera6712522023-07-05 20:25:11 -0700537 virtual void Schedule(monotonic_clock::time_point base,
538 monotonic_clock::duration repeat_offset =
539 ::aos::monotonic_clock::zero()) = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540
541 // Stop future calls to callback().
542 virtual void Disable() = 0;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800543
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700544 // Check if the timer is disabled
545 virtual bool IsDisabled() = 0;
546
Austin Schuh1540c2f2019-11-29 21:59:29 -0800547 // Sets and gets the name of the timer. Set this if you want a descriptive
548 // name in the timing report.
549 void set_name(std::string_view name) { name_ = std::string(name); }
550 const std::string_view name() const { return name_; }
551
Austin Schuh39788ff2019-12-01 18:22:57 -0800552 protected:
553 TimerHandler(EventLoop *event_loop, std::function<void()> fn);
554
Austin Schuh9b1d6282022-06-10 17:03:21 -0700555 template <typename T>
556 monotonic_clock::time_point Call(T get_time,
557 monotonic_clock::time_point event_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800558
Austin Schuh1540c2f2019-11-29 21:59:29 -0800559 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800560 friend class EventLoop;
561
562 EventLoop *event_loop_;
563 // The function to call when Call is called.
564 std::function<void()> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800565 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800566
567 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500568 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700569};
570
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800571// Interface for phased loops. They are built on timers.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572class PhasedLoopHandler {
573 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800574 virtual ~PhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800576 // Sets the interval and offset. Any changes to interval and offset only take
577 // effect when the handler finishes running or upon a call to Reschedule().
578 //
579 // The precise semantics of the monotonic_now parameter are defined in
580 // phased_loop.h. The way that it gets used in this interface is to control
581 // what the cycles elapsed counter will read on the following call to your
582 // handler. In an idealized simulation environment, if you call
583 // set_interval_and_offset() during the phased loop offset without setting
584 // monotonic_now, then you should always see a count of 1 on the next cycle.
585 //
586 // With the default behavior (this is called inside your handler and with
587 // monotonic_now = nullopt), the next phased loop call will occur at most
588 // interval time after the current time. Note that in many cases this will
589 // *not* be the preferred behavior (in most cases, you would likely aim to
590 // keep the average frequency of the calls reasonably consistent).
591 //
592 // A combination of the monotonic_now parameter and manually calling
593 // Reschedule() outside of the phased loop handler can be used to alter the
594 // behavior of cycles_elapsed. For the default behavior, you can set
595 // monotonic_now to the current time. If you call set_interval_and_offset()
596 // and Reschedule() with the same monotonic_now, that will cause the next
597 // callback to occur in the range (monotonic_now, monotonic_now + interval]
598 // and get called with a count of 1 (if the event is actually able to happen
599 // when it is scheduled to). E.g., if you are just adjusting the phased loop
600 // offset (but not the interval) and want to maintain a consistent frequency,
601 // you may call these functions with monotonic_now = now + interval / 2.
602 void set_interval_and_offset(
603 const monotonic_clock::duration interval,
604 const monotonic_clock::duration offset,
605 std::optional<monotonic_clock::time_point> monotonic_now = std::nullopt) {
606 phased_loop_.set_interval_and_offset(interval, offset, monotonic_now);
Austin Schuh39788ff2019-12-01 18:22:57 -0800607 }
Austin Schuh1540c2f2019-11-29 21:59:29 -0800608
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800609 // Reruns the scheduler for the phased loop, scheduling the next callback at
610 // the next available time after monotonic_now. This allows
611 // set_interval_and_offset() to be called and have the changes take effect
612 // before the next handler finishes. This will have no effect if run during
613 // the phased loop's own handler.
614 void Reschedule(monotonic_clock::time_point monotonic_now) {
615 cycles_elapsed_ += phased_loop_.Iterate(monotonic_now);
616 Schedule(phased_loop_.sleep_time());
617 }
618
619 // Sets and gets the name of the timer. Set this if you want a descriptive
Austin Schuh1540c2f2019-11-29 21:59:29 -0800620 // name in the timing report.
621 void set_name(std::string_view name) { name_ = std::string(name); }
622 const std::string_view name() const { return name_; }
623
Austin Schuh39788ff2019-12-01 18:22:57 -0800624 protected:
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800625 void Call(std::function<monotonic_clock::time_point()> get_time);
Austin Schuh39788ff2019-12-01 18:22:57 -0800626
627 PhasedLoopHandler(EventLoop *event_loop, std::function<void(int)> fn,
628 const monotonic_clock::duration interval,
629 const monotonic_clock::duration offset);
630
Austin Schuh1540c2f2019-11-29 21:59:29 -0800631 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800632 friend class EventLoop;
633
Austin Schuh39788ff2019-12-01 18:22:57 -0800634 virtual void Schedule(monotonic_clock::time_point sleep_time) = 0;
635
636 EventLoop *event_loop_;
637 std::function<void(int)> fn_;
Austin Schuh1540c2f2019-11-29 21:59:29 -0800638 std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800639 time::PhasedLoop phased_loop_;
640
641 int cycles_elapsed_ = 0;
642
643 internal::TimerTiming timing_;
Brian Silverman79ec7fc2020-06-08 20:11:22 -0500644 Ftrace ftrace_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645};
646
Austin Schuh3054f5f2021-07-21 15:38:01 -0700647// Note, it is supported to create only:
648// multiple fetchers, and (one sender or one watcher) per <name, type>
649// tuple.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650class EventLoop {
651 public:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700652 // Holds configuration by reference for the lifetime of this object. It may
653 // never be mutated externally in any way.
Austin Schuh83c7f702021-01-19 22:36:29 -0800654 EventLoop(const Configuration *configuration);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655
Austin Schuh39788ff2019-12-01 18:22:57 -0800656 virtual ~EventLoop();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657
658 // Current time.
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800659 virtual monotonic_clock::time_point monotonic_now() const = 0;
660 virtual realtime_clock::time_point realtime_now() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700662 template <typename T>
Austin Schuha0654152021-02-21 21:38:24 -0800663 const Channel *GetChannel(const std::string_view channel_name) {
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800664 return configuration::GetChannel(configuration(), channel_name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800665 T::GetFullyQualifiedName(), name(), node(),
Austin Schuha0654152021-02-21 21:38:24 -0800666 true);
667 }
milind1f1dca32021-07-03 13:50:07 -0700668 // Returns true if the channel exists in the configuration.
Austin Schuha0654152021-02-21 21:38:24 -0800669 template <typename T>
670 bool HasChannel(const std::string_view channel_name) {
671 return GetChannel<T>(channel_name) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700672 }
673
Brian Silverman631b6262021-11-10 12:25:08 -0800674 // Like MakeFetcher, but returns an invalid fetcher if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800675 // not readable on this node or does not exist. You must check valid() on the
676 // Fetcher before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800677 template <typename T>
678 Fetcher<T> TryMakeFetcher(const std::string_view channel_name) {
679 const Channel *const channel = GetChannel<T>(channel_name);
680 if (channel == nullptr) {
681 return Fetcher<T>();
682 }
683
684 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
685 return Fetcher<T>();
686 }
687
688 return Fetcher<T>(MakeRawFetcher(channel));
689 }
690
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 // Makes a class that will always fetch the most recent value
692 // sent to the provided channel.
693 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800694 Fetcher<T> MakeFetcher(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800695 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700696 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
697 << T::GetFullyQualifiedName() << "\" } not found in config.";
698
Brian Silverman631b6262021-11-10 12:25:08 -0800699 Fetcher<T> result = TryMakeFetcher<T>(channel_name);
700 if (!result.valid()) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800701 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
702 << "\", \"type\": \"" << T::GetFullyQualifiedName()
703 << "\" } is not able to be fetched on this node. Check your "
704 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800705 }
706
Brian Silverman631b6262021-11-10 12:25:08 -0800707 return result;
708 }
709
710 // Like MakeSender, but returns an invalid sender if the given channel is
Sanjay Narayanan570dc932022-12-06 14:12:04 -0800711 // not sendable on this node or does not exist. You must check valid() on the
712 // Sender before using it.
Brian Silverman631b6262021-11-10 12:25:08 -0800713 template <typename T>
714 Sender<T> TryMakeSender(const std::string_view channel_name) {
715 const Channel *channel = GetChannel<T>(channel_name);
716 if (channel == nullptr) {
717 return Sender<T>();
718 }
719
720 if (!configuration::ChannelIsSendableOnNode(channel, node())) {
721 return Sender<T>();
722 }
723
724 return Sender<T>(MakeRawSender(channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700725 }
726
727 // Makes class that allows constructing and sending messages to
728 // the provided channel.
729 template <typename T>
James Kuszmaul3ae42262019-11-08 12:33:41 -0800730 Sender<T> MakeSender(const std::string_view channel_name) {
Brian Silverman631b6262021-11-10 12:25:08 -0800731 CHECK(HasChannel<T>(channel_name))
Alex Perrycb7da4b2019-08-28 19:35:56 -0700732 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
Austin Schuh28fedcb2020-02-08 15:59:58 -0800733 << T::GetFullyQualifiedName() << "\" } not found in config for "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700734 << name()
Austin Schuhcaa2a5d2020-11-01 22:38:20 -0800735 << (configuration::MultiNode(configuration())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 ? absl::StrCat(" on node ", node()->name()->string_view())
737 : ".");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700738
Brian Silverman631b6262021-11-10 12:25:08 -0800739 Sender<T> result = TryMakeSender<T>(channel_name);
740 if (!result) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800741 LOG(FATAL) << "Channel { \"name\": \"" << channel_name
742 << "\", \"type\": \"" << T::GetFullyQualifiedName()
743 << "\" } is not able to be sent on this node. Check your "
744 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800745 }
746
Brian Silverman631b6262021-11-10 12:25:08 -0800747 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700748 }
749
750 // This will watch messages sent to the provided channel.
751 //
Brian Silverman454bc112020-03-05 14:21:25 -0800752 // w must have a non-polymorphic operator() (aka it can only be called with a
753 // single set of arguments; no overloading or templates). It must be callable
754 // with this signature:
755 // void(const MessageType &);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700756 //
Brian Silverman454bc112020-03-05 14:21:25 -0800757 // Lambdas are a common form for w. A std::function will work too.
758 //
759 // Note that bind expressions have polymorphic call operators, so they are not
760 // allowed.
761 //
762 // We template Watch as a whole instead of using std::function<void(const T
763 // &)> to allow deducing MessageType from lambdas and other things which are
764 // implicitly convertible to std::function, but not actually std::function
765 // instantiations. Template deduction guides might allow solving this
766 // differently in newer versions of C++, but those have their own corner
767 // cases.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700768 template <typename Watch>
Brian Silverman454bc112020-03-05 14:21:25 -0800769 void MakeWatcher(const std::string_view channel_name, Watch &&w);
770
771 // Like MakeWatcher, but doesn't have access to the message data. This may be
772 // implemented to use less resources than an equivalent MakeWatcher.
773 //
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800774 // The function will still have access to context(), although that will have
775 // its data field set to nullptr.
Brian Silverman454bc112020-03-05 14:21:25 -0800776 template <typename MessageType>
777 void MakeNoArgWatcher(const std::string_view channel_name,
778 std::function<void()> w);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779
780 // The passed in function will be called when the event loop starts.
781 // Use this to run code once the thread goes into "real-time-mode",
782 virtual void OnRun(::std::function<void()> on_run) = 0;
783
Austin Schuh217a9782019-12-21 23:02:50 -0800784 // Gets the name of the event loop. This is the application name.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800785 virtual const std::string_view name() const = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786
Austin Schuh217a9782019-12-21 23:02:50 -0800787 // Returns the node that this event loop is running on. Returns nullptr if we
788 // are running in single-node mode.
789 virtual const Node *node() const = 0;
790
Alex Perrycb7da4b2019-08-28 19:35:56 -0700791 // Creates a timer that executes callback when the timer expires
792 // Returns a TimerHandle for configuration of the timer
milind-u61227f22021-08-29 15:58:33 -0700793 // TODO(milind): callback should take the number of cycles elapsed as a
794 // parameter.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700795 virtual TimerHandler *AddTimer(::std::function<void()> callback) = 0;
796
797 // Creates a timer that executes callback periodically at the specified
798 // interval and offset. Returns a PhasedLoopHandler for interacting with the
799 // timer.
800 virtual PhasedLoopHandler *AddPhasedLoop(
801 ::std::function<void(int)> callback,
802 const monotonic_clock::duration interval,
803 const monotonic_clock::duration offset = ::std::chrono::seconds(0)) = 0;
804
Austin Schuh217a9782019-12-21 23:02:50 -0800805 // TODO(austin): OnExit for cleanup.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700806
Austin Schuh3054f5f2021-07-21 15:38:01 -0700807 // May be safely called from any thread.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808 bool is_running() const { return is_running_.load(); }
809
810 // Sets the scheduler priority to run the event loop at. This may not be
811 // called after we go into "real-time-mode".
812 virtual void SetRuntimeRealtimePriority(int priority) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700813 // Defaults to 0 if this loop will not run realtime.
814 virtual int runtime_realtime_priority() const = 0;
815
Austin Schuh070019a2022-12-20 22:23:09 -0800816 static cpu_set_t DefaultAffinity();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700817
Brian Silverman6a54ff32020-04-28 16:41:39 -0700818 // Sets the scheduler affinity to run the event loop with. This may only be
819 // called before Run().
820 virtual void SetRuntimeAffinity(const cpu_set_t &cpuset) = 0;
Austin Schuh65493d62022-08-17 15:10:37 -0700821 // Defaults to DefaultAffinity() if this loop will not run pinned.
822 virtual const cpu_set_t &runtime_affinity() const = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700823
Austin Schuh217a9782019-12-21 23:02:50 -0800824 // Fetches new messages from the provided channel (path, type).
825 //
826 // Note: this channel must be a member of the exact configuration object this
827 // was built with.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700828 virtual std::unique_ptr<RawFetcher> MakeRawFetcher(
829 const Channel *channel) = 0;
830
Austin Schuh217a9782019-12-21 23:02:50 -0800831 // Watches channel (name, type) for new messages.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700832 virtual void MakeRawWatcher(
833 const Channel *channel,
834 std::function<void(const Context &context, const void *message)>
835 watcher) = 0;
836
Brian Silverman454bc112020-03-05 14:21:25 -0800837 // Watches channel (name, type) for new messages, without needing to extract
838 // the message contents. Default implementation simply re-uses MakeRawWatcher.
839 virtual void MakeRawNoArgWatcher(
840 const Channel *channel,
841 std::function<void(const Context &context)> watcher) {
842 MakeRawWatcher(channel, [watcher](const Context &context, const void *) {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800843 Context new_context = context;
844 new_context.data = nullptr;
Brian Silverman4f4e0612020-08-12 19:54:41 -0700845 new_context.buffer_index = -1;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800846 watcher(new_context);
Brian Silverman454bc112020-03-05 14:21:25 -0800847 });
848 }
849
Austin Schuh217a9782019-12-21 23:02:50 -0800850 // Creates a raw sender for the provided channel. This is used for reflection
851 // based sending.
852 // Note: this ignores any node constraints. Ignore at your own peril.
853 virtual std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) = 0;
854
Austin Schuh6231cc32019-12-07 13:06:15 -0800855 // Returns the context for the current callback.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700856 const Context &context() const { return context_; }
857
858 // Returns the configuration that this event loop was built with.
859 const Configuration *configuration() const { return configuration_; }
860
Austin Schuh39788ff2019-12-01 18:22:57 -0800861 // Prevents the event loop from sending a timing report.
Brian Silvermanbf889922021-11-10 12:41:57 -0800862 void SkipTimingReport();
Austin Schuh39788ff2019-12-01 18:22:57 -0800863
Brian Silverman4f4e0612020-08-12 19:54:41 -0700864 // Prevents AOS_LOG being sent to message on /aos.
Tyler Chatow67ddb032020-01-12 14:30:04 -0800865 void SkipAosLog() { skip_logger_ = true; }
866
Brian Silverman4f4e0612020-08-12 19:54:41 -0700867 // Returns the number of buffers for this channel. This corresponds with the
868 // range of Context::buffer_index values for this channel.
869 virtual int NumberBuffers(const Channel *channel) = 0;
870
Austin Schuh20ac95d2020-12-05 17:24:19 -0800871 // Returns the boot UUID.
Austin Schuh83c7f702021-01-19 22:36:29 -0800872 virtual const UUID &boot_uuid() const = 0;
Austin Schuh20ac95d2020-12-05 17:24:19 -0800873
James Kuszmaul762e8692023-07-31 14:57:53 -0700874 // Sets the version string that will be used in any newly constructed
875 // EventLoop objects. This can be overridden for individual EventLoop's by
876 // calling EventLoop::SetVersionString(). The version string is populated into
877 // the timing report message. Makes a copy of the provided string_view.
878 static void SetDefaultVersionString(std::string_view version);
879
880 // Overrides the version string for this event loop. Makes a copy of the
881 // provided string_view.
882 void SetVersionString(std::string_view version);
883
James Kuszmaulb740f452023-11-14 17:44:29 -0800884 std::optional<std::string_view> VersionString() const {
885 return version_string_;
886 }
887
Alex Perrycb7da4b2019-08-28 19:35:56 -0700888 protected:
Austin Schuh217a9782019-12-21 23:02:50 -0800889 // Sets the name of the event loop. This is the application name.
890 virtual void set_name(const std::string_view name) = 0;
891
Alex Perrycb7da4b2019-08-28 19:35:56 -0700892 void set_is_running(bool value) { is_running_.store(value); }
893
Austin Schuh39788ff2019-12-01 18:22:57 -0800894 // Validates that channel exists inside configuration_ and finds its index.
895 int ChannelIndex(const Channel *channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700896
Brian Silverman5120afb2020-01-31 17:44:35 -0800897 // Returns the state for the watcher on the corresponding channel. This
898 // watcher must exist before calling this.
899 WatcherState *GetWatcherState(const Channel *channel);
900
Brian Silverman6d2b3592020-06-18 14:40:15 -0700901 // Returns a Sender's protected RawSender.
Brian Silverman5120afb2020-01-31 17:44:35 -0800902 template <typename T>
903 static RawSender *GetRawSender(aos::Sender<T> *sender) {
904 return sender->sender_.get();
905 }
906
Brian Silverman6d2b3592020-06-18 14:40:15 -0700907 // Returns a Fetcher's protected RawFetcher.
908 template <typename T>
909 static RawFetcher *GetRawFetcher(aos::Fetcher<T> *fetcher) {
910 return fetcher->fetcher_.get();
911 }
912
Austin Schuh6231cc32019-12-07 13:06:15 -0800913 // Context available for watchers, timers, and phased loops.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700914 Context context_;
915
Austin Schuh39788ff2019-12-01 18:22:57 -0800916 friend class RawSender;
917 friend class TimerHandler;
918 friend class RawFetcher;
919 friend class PhasedLoopHandler;
920 friend class WatcherState;
921
922 // Methods used to implement timing reports.
923 void NewSender(RawSender *sender);
924 void DeleteSender(RawSender *sender);
925 TimerHandler *NewTimer(std::unique_ptr<TimerHandler> timer);
926 PhasedLoopHandler *NewPhasedLoop(
927 std::unique_ptr<PhasedLoopHandler> phased_loop);
928 void NewFetcher(RawFetcher *fetcher);
929 void DeleteFetcher(RawFetcher *fetcher);
930 WatcherState *NewWatcher(std::unique_ptr<WatcherState> watcher);
931
Brian Silverman0fc69932020-01-24 21:54:02 -0800932 // Tracks that we have a (single) watcher on the given channel.
933 void TakeWatcher(const Channel *channel);
934 // Tracks that we have at least one sender on the given channel.
935 void TakeSender(const Channel *channel);
936
Austin Schuh39788ff2019-12-01 18:22:57 -0800937 std::vector<RawSender *> senders_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800938 std::vector<RawFetcher *> fetchers_;
939
Austin Schuh39788ff2019-12-01 18:22:57 -0800940 std::vector<std::unique_ptr<TimerHandler>> timers_;
941 std::vector<std::unique_ptr<PhasedLoopHandler>> phased_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800942 std::vector<std::unique_ptr<WatcherState>> watchers_;
943
Brian Silvermance418d02021-11-03 11:25:52 -0700944 // Does nothing if timing reports are disabled.
Austin Schuh39788ff2019-12-01 18:22:57 -0800945 void SendTimingReport();
Brian Silvermance418d02021-11-03 11:25:52 -0700946
Austin Schuh39788ff2019-12-01 18:22:57 -0800947 void UpdateTimingReport();
948 void MaybeScheduleTimingReports();
949
950 std::unique_ptr<RawSender> timing_report_sender_;
951
Austin Schuh7d87b672019-12-01 20:23:49 -0800952 // Tracks which event sources (timers and watchers) have data, and which
953 // don't. Added events may not change their event_time().
954 // TODO(austin): Test case 1: timer triggers at t1, handler takes until after
955 // t2 to run, t2 should then be picked up without a context switch.
956 void AddEvent(EventLoopEvent *event);
957 void RemoveEvent(EventLoopEvent *event);
958 size_t EventCount() const { return events_.size(); }
959 EventLoopEvent *PopEvent();
960 EventLoopEvent *PeekEvent() { return events_.front(); }
961 void ReserveEvents();
962
963 std::vector<EventLoopEvent *> events_;
Brian Silvermanbd405c02020-06-23 16:25:23 -0700964 size_t event_generation_ = 1;
Austin Schuh7d87b672019-12-01 20:23:49 -0800965
Tyler Chatow67ddb032020-01-12 14:30:04 -0800966 // If true, don't send AOS_LOG to /aos
967 bool skip_logger_ = false;
968
Austin Schuha9012be2021-07-21 15:19:11 -0700969 // Sets context_ for a timed event which is supposed to happen at the provided
970 // time.
971 void SetTimerContext(monotonic_clock::time_point monotonic_event_time);
Austin Schuh0debde12022-08-17 16:25:17 -0700972 // Clears context_ so it only has invalid times and elements in it.
973 void ClearContext();
Austin Schuha9012be2021-07-21 15:19:11 -0700974
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800975 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800976 virtual pid_t GetTid() = 0;
977
James Kuszmaul762e8692023-07-31 14:57:53 -0700978 // Default version string to be used in the timing report for any newly
979 // created EventLoop objects.
980 static std::optional<std::string> default_version_string_;
981
982 // Timing report version string for this event loop.
983 std::optional<std::string> version_string_;
984
Austin Schuh39788ff2019-12-01 18:22:57 -0800985 FlatbufferDetachedBuffer<timing::Report> timing_report_;
986
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800987 ::std::atomic<bool> is_running_{false};
988
Alex Perrycb7da4b2019-08-28 19:35:56 -0700989 const Configuration *configuration_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800990
991 // If true, don't send out timing reports.
992 bool skip_timing_report_ = false;
Brian Silverman0fc69932020-01-24 21:54:02 -0800993
milind1f1dca32021-07-03 13:50:07 -0700994 SendFailureCounter timing_report_failure_counter_;
995
Brian Silverman0fc69932020-01-24 21:54:02 -0800996 absl::btree_set<const Channel *> taken_watchers_, taken_senders_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700997};
998
Brian Silvermane1fe2512022-08-14 23:18:50 -0700999// Interface for terminating execution of an EventLoop.
1000//
1001// Prefer this over binding a lambda to an Exit() method when passing ownership
1002// in complicated ways because implementations should have assertions to catch
1003// it outliving the object it's referring to, instead of having a
1004// use-after-free.
1005//
1006// This is not exposed by EventLoop directly because different EventLoop
1007// implementations provide this functionality at different scopes, or possibly
1008// not at all.
1009class ExitHandle {
1010 public:
1011 ExitHandle() = default;
1012 virtual ~ExitHandle() = default;
1013
1014 // Exits some set of event loops. Details depend on the implementation.
1015 //
1016 // This means no more events will be processed, but any currently being
1017 // processed will finish.
1018 virtual void Exit() = 0;
1019};
1020
Alex Perrycb7da4b2019-08-28 19:35:56 -07001021} // namespace aos
1022
Austin Schuhb8075812020-10-19 09:36:49 -07001023#include "aos/events/event_loop_tmpl.h" // IWYU pragma: export
Alex Perrycb7da4b2019-08-28 19:35:56 -07001024
1025#endif // AOS_EVENTS_EVENT_LOOP_H