blob: 29c9eddcec7dcdfc2f03926a9bde77d3d6c7ff5d [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/simulated_event_loop.h"
2
3#include <algorithm>
4#include <deque>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08005#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006
7#include "absl/container/btree_map.h"
8#include "absl/container/btree_set.h"
9#include "aos/json_to_flatbuffer.h"
10#include "aos/util/phased_loop.h"
11
12namespace aos {
13
14// Container for both a message, and the context for it for simulation. This
15// makes tracking the timestamps associated with the data easy.
16struct SimulatedMessage {
17 // Struct to let us force data to be well aligned.
18 struct OveralignedChar {
19 char data alignas(32);
20 };
21
22 // Context for the data.
23 Context context;
24
25 // The data.
26 char *data() { return reinterpret_cast<char *>(&actual_data[0]); }
27
28 // Then the data.
29 OveralignedChar actual_data[];
30};
31
Austin Schuh7d87b672019-12-01 20:23:49 -080032class SimulatedEventLoop;
Alex Perrycb7da4b2019-08-28 19:35:56 -070033class SimulatedFetcher;
Austin Schuh39788ff2019-12-01 18:22:57 -080034class SimulatedChannel;
35
Austin Schuh7d87b672019-12-01 20:23:49 -080036class SimulatedWatcher : public WatcherState {
Austin Schuh39788ff2019-12-01 18:22:57 -080037 public:
Austin Schuh7d87b672019-12-01 20:23:49 -080038 SimulatedWatcher(
39 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
40 const Channel *channel,
41 std::function<void(const Context &context, const void *message)> fn);
Austin Schuh39788ff2019-12-01 18:22:57 -080042
Austin Schuh7d87b672019-12-01 20:23:49 -080043 ~SimulatedWatcher() override;
Austin Schuh39788ff2019-12-01 18:22:57 -080044
45 void Startup(EventLoop * /*event_loop*/) override {}
46
Austin Schuh7d87b672019-12-01 20:23:49 -080047 void Schedule(std::shared_ptr<SimulatedMessage> message);
48
49 void HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -080050
51 void SetSimulatedChannel(SimulatedChannel *channel) {
52 simulated_channel_ = channel;
53 }
54
55 private:
Austin Schuh7d87b672019-12-01 20:23:49 -080056 void DoSchedule(monotonic_clock::time_point event_time);
57
58 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
59
60 SimulatedEventLoop *simulated_event_loop_;
61 EventHandler<SimulatedWatcher> event_;
62 EventScheduler *scheduler_;
63 EventScheduler::Token token_;
Austin Schuh39788ff2019-12-01 18:22:57 -080064 SimulatedChannel *simulated_channel_ = nullptr;
65};
Alex Perrycb7da4b2019-08-28 19:35:56 -070066
67class SimulatedChannel {
68 public:
69 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -080070 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070071 scheduler_(scheduler),
72 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
73
74 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
75
76 // Makes a connected raw sender which calls Send below.
77 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
78
79 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -080080 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -070081
82 // Registers a watcher for the queue.
Austin Schuh7d87b672019-12-01 20:23:49 -080083 void MakeRawWatcher(SimulatedWatcher *watcher);
Austin Schuh39788ff2019-12-01 18:22:57 -080084
Austin Schuh7d87b672019-12-01 20:23:49 -080085 void RemoveWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -080086 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
87 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070088
89 // Sends the message to all the connected receivers and fetchers.
90 void Send(std::shared_ptr<SimulatedMessage> message);
91
92 // Unregisters a fetcher.
93 void UnregisterFetcher(SimulatedFetcher *fetcher);
94
95 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
96
Austin Schuh39788ff2019-12-01 18:22:57 -080097 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Austin Schuh5f1cc5c2019-12-01 18:01:11 -080099 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101 }
102
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 const Channel *channel() const { return channel_; }
104
105 ::aos::monotonic_clock::time_point monotonic_now() const {
106 return scheduler_->monotonic_now();
107 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108
109 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800110 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111
112 // List of all watchers.
Austin Schuh7d87b672019-12-01 20:23:49 -0800113 ::std::vector<SimulatedWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700114
115 // List of all fetchers.
116 ::std::vector<SimulatedFetcher *> fetchers_;
117 std::shared_ptr<SimulatedMessage> latest_message_;
118 EventScheduler *scheduler_;
119
120 ipc_lib::QueueIndex next_queue_index_;
121};
122
123namespace {
124
125// Creates a SimulatedMessage with size bytes of storage.
126// This is a shared_ptr so we don't have to implement refcounting or copying.
127std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
128 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
129 malloc(sizeof(SimulatedMessage) + size));
130 message->context.size = size;
131 message->context.data = message->data();
132
133 return std::shared_ptr<SimulatedMessage>(message, free);
134}
135
136class SimulatedSender : public RawSender {
137 public:
138 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800139 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800140 simulated_channel_(simulated_channel),
141 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700142 ~SimulatedSender() {}
143
144 void *data() override {
145 if (!message_) {
146 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
147 }
148 return message_->data();
149 }
150
151 size_t size() override { return simulated_channel_->max_size(); }
152
Austin Schuh39788ff2019-12-01 18:22:57 -0800153 bool DoSend(size_t length) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700154 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
155 message_->context.monotonic_sent_time = event_loop_->monotonic_now();
156 message_->context.realtime_sent_time = event_loop_->realtime_now();
157 CHECK_LE(length, message_->context.size);
158 message_->context.size = length;
159
160 // TODO(austin): Track sending too fast.
161 simulated_channel_->Send(message_);
162
163 // Drop the reference to the message so that we allocate a new message for
164 // next time. Otherwise we will continue to reuse the same memory for all
165 // messages and corrupt it.
166 message_.reset();
167 return true;
168 }
169
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 bool DoSend(const void *msg, size_t size) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
172
173 // This is wasteful, but since flatbuffers fill from the back end of the
174 // queue, we need it to be full sized.
175 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
176
177 // Now fill in the message. size is already populated above, and
178 // queue_index will be populated in queue_. Put this at the back of the
179 // data segment.
180 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
181
182 return Send(size);
183 }
184
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185 private:
186 SimulatedChannel *simulated_channel_;
187 EventLoop *event_loop_;
188
189 std::shared_ptr<SimulatedMessage> message_;
190};
191} // namespace
192
193class SimulatedFetcher : public RawFetcher {
194 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800195 explicit SimulatedFetcher(EventLoop *event_loop, SimulatedChannel *queue)
196 : RawFetcher(event_loop, queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
198
Austin Schuh39788ff2019-12-01 18:22:57 -0800199 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
200 if (msgs_.size() == 0) {
201 return std::make_pair(false, monotonic_clock::min_time);
202 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700203
204 SetMsg(msgs_.front());
205 msgs_.pop_front();
Austin Schuh39788ff2019-12-01 18:22:57 -0800206 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700207 }
208
Austin Schuh39788ff2019-12-01 18:22:57 -0800209 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210 if (msgs_.size() == 0) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800211 // TODO(austin): Can we just do this logic unconditionally? It is a lot
212 // simpler. And call clear, obviously.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213 if (!msg_ && queue_->latest_message()) {
214 SetMsg(queue_->latest_message());
Austin Schuh39788ff2019-12-01 18:22:57 -0800215 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700216 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800217 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218 }
219 }
220
221 // We've had a message enqueued, so we don't need to go looking for the
222 // latest message from before we started.
223 SetMsg(msgs_.back());
224 msgs_.clear();
Austin Schuh39788ff2019-12-01 18:22:57 -0800225 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700226 }
227
228 private:
229 friend class SimulatedChannel;
230
231 // Updates the state inside RawFetcher to point to the data in msg_.
232 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
233 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700234 context_ = msg_->context;
235 }
236
237 // Internal method for Simulation to add a message to the buffer.
238 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
239 msgs_.emplace_back(buffer);
240 }
241
242 SimulatedChannel *queue_;
243 std::shared_ptr<SimulatedMessage> msg_;
244
245 // Messages queued up but not in use.
246 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
247};
248
249class SimulatedTimerHandler : public TimerHandler {
250 public:
251 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800252 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800253 ::std::function<void()> fn);
Austin Schuh7d87b672019-12-01 20:23:49 -0800254 ~SimulatedTimerHandler() { Disable(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255
256 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800257 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700258
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800259 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700260
Austin Schuh7d87b672019-12-01 20:23:49 -0800261 void Disable() override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700262
263 ::aos::monotonic_clock::time_point monotonic_now() const {
264 return scheduler_->monotonic_now();
265 }
266
267 private:
Austin Schuh7d87b672019-12-01 20:23:49 -0800268 SimulatedEventLoop *simulated_event_loop_;
269 EventHandler<SimulatedTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700270 EventScheduler *scheduler_;
271 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800272
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273 monotonic_clock::time_point base_;
274 monotonic_clock::duration repeat_offset_;
275};
276
277class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
278 public:
279 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800280 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281 ::std::function<void(int)> fn,
282 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800283 const monotonic_clock::duration offset);
Austin Schuh7d87b672019-12-01 20:23:49 -0800284 ~SimulatedPhasedLoopHandler();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700285
Austin Schuh7d87b672019-12-01 20:23:49 -0800286 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700287
Austin Schuh7d87b672019-12-01 20:23:49 -0800288 void Schedule(monotonic_clock::time_point sleep_time) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289
290 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800291 SimulatedEventLoop *simulated_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800292 EventHandler<SimulatedPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293
Austin Schuh39788ff2019-12-01 18:22:57 -0800294 EventScheduler *scheduler_;
295 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296};
297
298class SimulatedEventLoop : public EventLoop {
299 public:
300 explicit SimulatedEventLoop(
301 EventScheduler *scheduler,
302 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
303 *channels,
304 const Configuration *configuration,
305 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800306 *raw_event_loops,
307 pid_t tid)
308 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309 scheduler_(scheduler),
310 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800311 raw_event_loops_(raw_event_loops),
312 tid_(tid) {
313 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
314 if (!has_setup_) {
315 Setup();
316 has_setup_ = true;
317 }
318 set_is_running(value);
319 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 }
321 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 // Trigger any remaining senders or fetchers to be cleared before destroying
323 // the event loop so the book keeping matches.
324 timing_report_sender_.reset();
325
326 // Force everything with a registered fd with epoll to be destroyed now.
327 timers_.clear();
328 phased_loops_.clear();
329 watchers_.clear();
330
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
332 ++it) {
333 if (it->first == this) {
334 raw_event_loops_->erase(it);
335 break;
336 }
337 }
338 }
339
Austin Schuh7d87b672019-12-01 20:23:49 -0800340 std::chrono::nanoseconds send_delay() const { return send_delay_; }
341 void set_send_delay(std::chrono::nanoseconds send_delay) {
342 send_delay_ = send_delay;
343 }
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 ::aos::monotonic_clock::time_point monotonic_now() override {
346 return scheduler_->monotonic_now();
347 }
348
349 ::aos::realtime_clock::time_point realtime_now() override {
350 return scheduler_->realtime_now();
351 }
352
353 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
354
355 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
356
357 void MakeRawWatcher(
358 const Channel *channel,
359 ::std::function<void(const Context &context, const void *message)>
360 watcher) override;
361
362 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800363 CHECK(!is_running());
364 return NewTimer(::std::unique_ptr<TimerHandler>(
365 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 }
367
368 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
369 const monotonic_clock::duration interval,
370 const monotonic_clock::duration offset =
371 ::std::chrono::seconds(0)) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800372 return NewPhasedLoop(
373 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
374 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 }
376
377 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800378 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700379 }
380
James Kuszmaul3ae42262019-11-08 12:33:41 -0800381 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700382 name_ = std::string(name);
383 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800384 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385
386 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
387
388 void Take(const Channel *channel);
389
Austin Schuh39788ff2019-12-01 18:22:57 -0800390 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800392 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 }
394
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 int priority() const override { return priority_; }
396
397 void Setup() { MaybeScheduleTimingReports(); }
398
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800400 friend class SimulatedTimerHandler;
Austin Schuh7d87b672019-12-01 20:23:49 -0800401 friend class SimulatedPhasedLoopHandler;
402 friend class SimulatedWatcher;
403
404 void HandleEvent() {
405 while (true) {
406 if (EventCount() == 0 || PeekEvent()->event_time() > monotonic_now()) {
407 break;
408 }
409
410 EventLoopEvent *event = PopEvent();
411 event->HandleEvent();
412 }
413 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800414
Austin Schuh39788ff2019-12-01 18:22:57 -0800415 pid_t GetTid() override { return tid_; }
416
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 EventScheduler *scheduler_;
418 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
419 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
420 *raw_event_loops_;
421 absl::btree_set<SimpleChannel> taken_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700422
423 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800424
425 int priority_ = 0;
426
427 bool has_setup_ = false;
428
Austin Schuh7d87b672019-12-01 20:23:49 -0800429 std::chrono::nanoseconds send_delay_;
430
Austin Schuh39788ff2019-12-01 18:22:57 -0800431 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432};
433
Austin Schuh7d87b672019-12-01 20:23:49 -0800434void SimulatedEventLoopFactory::set_send_delay(
435 std::chrono::nanoseconds send_delay) {
436 send_delay_ = send_delay;
437 for (std::pair<EventLoop *, std::function<void(bool)>> &loop :
438 raw_event_loops_) {
439 reinterpret_cast<SimulatedEventLoop *>(loop.first)
440 ->set_send_delay(send_delay_);
441 }
442}
443
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444void SimulatedEventLoop::MakeRawWatcher(
445 const Channel *channel,
446 std::function<void(const Context &channel, const void *message)> watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800447 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 Take(channel);
Austin Schuh7d87b672019-12-01 20:23:49 -0800449 std::unique_ptr<SimulatedWatcher> shm_watcher(
450 new SimulatedWatcher(this, scheduler_, channel, std::move(watcher)));
Austin Schuh39788ff2019-12-01 18:22:57 -0800451
452 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
453 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454}
455
456std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
457 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800458 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 Take(channel);
460 return GetSimulatedChannel(channel)->MakeRawSender(this);
461}
462
463std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
464 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800465 ChannelIndex(channel);
466 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467}
468
469SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
470 const Channel *channel) {
471 auto it = channels_->find(SimpleChannel(channel));
472 if (it == channels_->end()) {
473 it = channels_
474 ->emplace(SimpleChannel(channel),
475 std::unique_ptr<SimulatedChannel>(
476 new SimulatedChannel(channel, scheduler_)))
477 .first;
478 }
479 return it->second.get();
480}
481
Austin Schuh7d87b672019-12-01 20:23:49 -0800482SimulatedWatcher::SimulatedWatcher(
483 SimulatedEventLoop *simulated_event_loop, EventScheduler *scheduler,
484 const Channel *channel,
485 std::function<void(const Context &context, const void *message)> fn)
486 : WatcherState(simulated_event_loop, channel, std::move(fn)),
487 simulated_event_loop_(simulated_event_loop),
488 event_(this),
489 scheduler_(scheduler),
490 token_(scheduler_->InvalidToken()) {}
491
492SimulatedWatcher::~SimulatedWatcher() {
493 simulated_event_loop_->RemoveEvent(&event_);
494 if (token_ != scheduler_->InvalidToken()) {
495 scheduler_->Deschedule(token_);
496 }
497 simulated_channel_->RemoveWatcher(this);
498}
499
500void SimulatedWatcher::Schedule(std::shared_ptr<SimulatedMessage> message) {
501 monotonic_clock::time_point event_time = scheduler_->monotonic_now();
502
503 // Messages are queued in order. If we are the first, add ourselves.
504 // Otherwise, don't.
505 if (msgs_.size() == 0) {
506 event_.set_event_time(message->context.monotonic_sent_time);
507 simulated_event_loop_->AddEvent(&event_);
508
509 DoSchedule(event_time);
510 }
511
512 msgs_.emplace_back(message);
513}
514
515void SimulatedWatcher::HandleEvent() {
516 CHECK_NE(msgs_.size(), 0u) << ": No events to handle.";
517
518 const monotonic_clock::time_point monotonic_now =
519 simulated_event_loop_->monotonic_now();
520 DoCallCallback([monotonic_now]() { return monotonic_now; },
521 msgs_.front()->context);
522
523 msgs_.pop_front();
524 if (msgs_.size() != 0) {
525 event_.set_event_time(msgs_.front()->context.monotonic_sent_time);
526 simulated_event_loop_->AddEvent(&event_);
527
528 DoSchedule(event_.event_time());
529 } else {
530 token_ = scheduler_->InvalidToken();
531 }
532}
533
534void SimulatedWatcher::DoSchedule(monotonic_clock::time_point event_time) {
535 token_ =
536 scheduler_->Schedule(event_time + simulated_event_loop_->send_delay(),
537 [this]() { simulated_event_loop_->HandleEvent(); });
538}
539
540void SimulatedChannel::MakeRawWatcher(SimulatedWatcher *watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800541 watcher->SetSimulatedChannel(this);
542 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543}
544
545::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
546 EventLoop *event_loop) {
547 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
548}
549
Austin Schuh39788ff2019-12-01 18:22:57 -0800550::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
551 EventLoop *event_loop) {
552 ::std::unique_ptr<SimulatedFetcher> fetcher(
553 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 fetchers_.push_back(fetcher.get());
555 return ::std::move(fetcher);
556}
557
558void SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
559 message->context.queue_index = next_queue_index_.index();
560 message->context.data =
561 message->data() + channel()->max_size() - message->context.size;
562 next_queue_index_ = next_queue_index_.Increment();
563
564 latest_message_ = message;
565 if (scheduler_->is_running()) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800566 for (SimulatedWatcher *watcher : watchers_) {
567 watcher->Schedule(message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700568 }
569 }
570 for (auto &fetcher : fetchers_) {
571 fetcher->Enqueue(message);
572 }
573}
574
575void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
576 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
577}
578
579SimpleChannel::SimpleChannel(const Channel *channel)
580 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
581 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
582
Austin Schuh39788ff2019-12-01 18:22:57 -0800583SimulatedTimerHandler::SimulatedTimerHandler(
584 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
585 ::std::function<void()> fn)
586 : TimerHandler(simulated_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800587 simulated_event_loop_(simulated_event_loop),
588 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800589 scheduler_(scheduler),
590 token_(scheduler_->InvalidToken()) {}
591
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800592void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
593 monotonic_clock::duration repeat_offset) {
594 Disable();
595 const ::aos::monotonic_clock::time_point monotonic_now =
596 scheduler_->monotonic_now();
597 base_ = base;
598 repeat_offset_ = repeat_offset;
599 if (base < monotonic_now) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800600 token_ = scheduler_->Schedule(
601 monotonic_now, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800602 } else {
Austin Schuh7d87b672019-12-01 20:23:49 -0800603 token_ = scheduler_->Schedule(
604 base, [this]() { simulated_event_loop_->HandleEvent(); });
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800605 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800606 event_.set_event_time(base_);
607 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800608}
609
610void SimulatedTimerHandler::HandleEvent() {
611 const ::aos::monotonic_clock::time_point monotonic_now =
612 scheduler_->monotonic_now();
613 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
614 // Reschedule.
615 while (base_ <= monotonic_now) base_ += repeat_offset_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800616 token_ = scheduler_->Schedule(
617 base_, [this]() { simulated_event_loop_->HandleEvent(); });
618 event_.set_event_time(base_);
619 simulated_event_loop_->AddEvent(&event_);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800620 } else {
621 token_ = scheduler_->InvalidToken();
622 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800623
Austin Schuh39788ff2019-12-01 18:22:57 -0800624 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800625}
626
Austin Schuh7d87b672019-12-01 20:23:49 -0800627void SimulatedTimerHandler::Disable() {
628 simulated_event_loop_->RemoveEvent(&event_);
629 if (token_ != scheduler_->InvalidToken()) {
630 scheduler_->Deschedule(token_);
631 token_ = scheduler_->InvalidToken();
632 }
633}
634
Austin Schuh39788ff2019-12-01 18:22:57 -0800635SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
636 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
637 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
638 const monotonic_clock::duration offset)
639 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
640 simulated_event_loop_(simulated_event_loop),
Austin Schuh7d87b672019-12-01 20:23:49 -0800641 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800642 scheduler_(scheduler),
643 token_(scheduler_->InvalidToken()) {}
644
Austin Schuh7d87b672019-12-01 20:23:49 -0800645SimulatedPhasedLoopHandler::~SimulatedPhasedLoopHandler() {
646 if (token_ != scheduler_->InvalidToken()) {
647 scheduler_->Deschedule(token_);
648 token_ = scheduler_->InvalidToken();
649 }
650 simulated_event_loop_->RemoveEvent(&event_);
651}
652
653void SimulatedPhasedLoopHandler::HandleEvent() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800654 monotonic_clock::time_point monotonic_now =
655 simulated_event_loop_->monotonic_now();
656 Call(
657 [monotonic_now]() { return monotonic_now; },
658 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
659}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800660
Austin Schuh7d87b672019-12-01 20:23:49 -0800661void SimulatedPhasedLoopHandler::Schedule(
662 monotonic_clock::time_point sleep_time) {
663 token_ = scheduler_->Schedule(
664 sleep_time, [this]() { simulated_event_loop_->HandleEvent(); });
665 event_.set_event_time(sleep_time);
666 simulated_event_loop_->AddEvent(&event_);
667}
668
Alex Perrycb7da4b2019-08-28 19:35:56 -0700669void SimulatedEventLoop::Take(const Channel *channel) {
670 CHECK(!is_running()) << ": Cannot add new objects while running.";
671
672 auto result = taken_.insert(SimpleChannel(channel));
673 CHECK(result.second) << ": " << FlatbufferToJson(channel)
674 << " is already being used.";
675}
676
677SimulatedEventLoopFactory::SimulatedEventLoopFactory(
678 const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800679 : configuration_(CHECK_NOTNULL(configuration)) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700680SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
681
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800682::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
683 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 pid_t tid = tid_;
685 ++tid_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800686 ::std::unique_ptr<SimulatedEventLoop> result(new SimulatedEventLoop(
Austin Schuh39788ff2019-12-01 18:22:57 -0800687 &scheduler_, &channels_, configuration_, &raw_event_loops_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800688 result->set_name(name);
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 result->set_send_delay(send_delay_);
690 return std::move(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691}
692
693void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
694 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
695 raw_event_loops_) {
696 event_loop.second(true);
697 }
698 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800699 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
700 raw_event_loops_) {
701 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700702 }
703}
704
705void SimulatedEventLoopFactory::Run() {
706 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
707 raw_event_loops_) {
708 event_loop.second(true);
709 }
710 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800711 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
712 raw_event_loops_) {
713 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700714 }
715}
716
717} // namespace aos