blob: a9dd3e5f813978e6249615f1a5e38aeff8f9b418 [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
32class SimulatedFetcher;
Austin Schuh39788ff2019-12-01 18:22:57 -080033class SimulatedChannel;
34
35class ShmWatcher : public WatcherState {
36 public:
37 ShmWatcher(
38 EventLoop *event_loop, const Channel *channel,
39 std::function<void(const Context &context, const void *message)> fn)
40 : WatcherState(event_loop, channel, std::move(fn)),
41 event_loop_(event_loop) {}
42
43 ~ShmWatcher() override;
44
45 void Call(const Context &context) {
46 const monotonic_clock::time_point monotonic_now =
47 event_loop_->monotonic_now();
48 DoCallCallback([monotonic_now]() { return monotonic_now; }, context);
49 }
50
51 void Startup(EventLoop * /*event_loop*/) override {}
52
53 void Schedule(EventScheduler *scheduler,
54 std::shared_ptr<SimulatedMessage> message) {
55 // TODO(austin): Track the token once we schedule in the future.
56 // TODO(austin): Schedule wakeup in the future so we don't have 0 latency.
57 scheduler->Schedule(scheduler->monotonic_now(),
58 [this, message]() { Call(message->context); });
59 }
60
61 void SetSimulatedChannel(SimulatedChannel *channel) {
62 simulated_channel_ = channel;
63 }
64
65 private:
66 EventLoop *event_loop_;
67 SimulatedChannel *simulated_channel_ = nullptr;
68};
Alex Perrycb7da4b2019-08-28 19:35:56 -070069
70class SimulatedChannel {
71 public:
72 explicit SimulatedChannel(const Channel *channel, EventScheduler *scheduler)
Austin Schuh39788ff2019-12-01 18:22:57 -080073 : channel_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -070074 scheduler_(scheduler),
75 next_queue_index_(ipc_lib::QueueIndex::Zero(channel->max_size())) {}
76
77 ~SimulatedChannel() { CHECK_EQ(0u, fetchers_.size()); }
78
79 // Makes a connected raw sender which calls Send below.
80 ::std::unique_ptr<RawSender> MakeRawSender(EventLoop *event_loop);
81
82 // Makes a connected raw fetcher.
Austin Schuh39788ff2019-12-01 18:22:57 -080083 ::std::unique_ptr<RawFetcher> MakeRawFetcher(EventLoop *event_loop);
Alex Perrycb7da4b2019-08-28 19:35:56 -070084
85 // Registers a watcher for the queue.
Austin Schuh39788ff2019-12-01 18:22:57 -080086 void MakeRawWatcher(ShmWatcher *watcher);
87
88 void RemoveWatcher(ShmWatcher *watcher) {
89 watchers_.erase(std::find(watchers_.begin(), watchers_.end(), watcher));
90 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070091
92 // Sends the message to all the connected receivers and fetchers.
93 void Send(std::shared_ptr<SimulatedMessage> message);
94
95 // Unregisters a fetcher.
96 void UnregisterFetcher(SimulatedFetcher *fetcher);
97
98 std::shared_ptr<SimulatedMessage> latest_message() { return latest_message_; }
99
Austin Schuh39788ff2019-12-01 18:22:57 -0800100 size_t max_size() const { return channel()->max_size(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800102 const std::string_view name() const {
Austin Schuh39788ff2019-12-01 18:22:57 -0800103 return channel()->name()->string_view();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104 }
105
Austin Schuh39788ff2019-12-01 18:22:57 -0800106 const Channel *channel() const { return channel_; }
107
108 ::aos::monotonic_clock::time_point monotonic_now() const {
109 return scheduler_->monotonic_now();
110 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111
112 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800113 const Channel *channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700114
115 // List of all watchers.
Austin Schuh39788ff2019-12-01 18:22:57 -0800116 ::std::vector<ShmWatcher *> watchers_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
118 // List of all fetchers.
119 ::std::vector<SimulatedFetcher *> fetchers_;
120 std::shared_ptr<SimulatedMessage> latest_message_;
121 EventScheduler *scheduler_;
122
123 ipc_lib::QueueIndex next_queue_index_;
124};
125
Austin Schuh39788ff2019-12-01 18:22:57 -0800126ShmWatcher::~ShmWatcher() { simulated_channel_->RemoveWatcher(this); }
127
Alex Perrycb7da4b2019-08-28 19:35:56 -0700128namespace {
129
130// Creates a SimulatedMessage with size bytes of storage.
131// This is a shared_ptr so we don't have to implement refcounting or copying.
132std::shared_ptr<SimulatedMessage> MakeSimulatedMessage(size_t size) {
133 SimulatedMessage *message = reinterpret_cast<SimulatedMessage *>(
134 malloc(sizeof(SimulatedMessage) + size));
135 message->context.size = size;
136 message->context.data = message->data();
137
138 return std::shared_ptr<SimulatedMessage>(message, free);
139}
140
141class SimulatedSender : public RawSender {
142 public:
143 SimulatedSender(SimulatedChannel *simulated_channel, EventLoop *event_loop)
Austin Schuh39788ff2019-12-01 18:22:57 -0800144 : RawSender(event_loop, simulated_channel->channel()),
Austin Schuh54cf95f2019-11-29 13:14:18 -0800145 simulated_channel_(simulated_channel),
146 event_loop_(event_loop) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700147 ~SimulatedSender() {}
148
149 void *data() override {
150 if (!message_) {
151 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
152 }
153 return message_->data();
154 }
155
156 size_t size() override { return simulated_channel_->max_size(); }
157
Austin Schuh39788ff2019-12-01 18:22:57 -0800158 bool DoSend(size_t length) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159 CHECK_LE(length, size()) << ": Attempting to send too big a message.";
160 message_->context.monotonic_sent_time = event_loop_->monotonic_now();
161 message_->context.realtime_sent_time = event_loop_->realtime_now();
162 CHECK_LE(length, message_->context.size);
163 message_->context.size = length;
164
165 // TODO(austin): Track sending too fast.
166 simulated_channel_->Send(message_);
167
168 // Drop the reference to the message so that we allocate a new message for
169 // next time. Otherwise we will continue to reuse the same memory for all
170 // messages and corrupt it.
171 message_.reset();
172 return true;
173 }
174
Austin Schuh39788ff2019-12-01 18:22:57 -0800175 bool DoSend(const void *msg, size_t size) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176 CHECK_LE(size, this->size()) << ": Attempting to send too big a message.";
177
178 // This is wasteful, but since flatbuffers fill from the back end of the
179 // queue, we need it to be full sized.
180 message_ = MakeSimulatedMessage(simulated_channel_->max_size());
181
182 // Now fill in the message. size is already populated above, and
183 // queue_index will be populated in queue_. Put this at the back of the
184 // data segment.
185 memcpy(message_->data() + simulated_channel_->max_size() - size, msg, size);
186
187 return Send(size);
188 }
189
Alex Perrycb7da4b2019-08-28 19:35:56 -0700190 private:
191 SimulatedChannel *simulated_channel_;
192 EventLoop *event_loop_;
193
194 std::shared_ptr<SimulatedMessage> message_;
195};
196} // namespace
197
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800198class SimulatedEventLoop;
199
Alex Perrycb7da4b2019-08-28 19:35:56 -0700200class SimulatedFetcher : public RawFetcher {
201 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800202 explicit SimulatedFetcher(EventLoop *event_loop, SimulatedChannel *queue)
203 : RawFetcher(event_loop, queue->channel()), queue_(queue) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204 ~SimulatedFetcher() { queue_->UnregisterFetcher(this); }
205
Austin Schuh39788ff2019-12-01 18:22:57 -0800206 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
207 if (msgs_.size() == 0) {
208 return std::make_pair(false, monotonic_clock::min_time);
209 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
211 SetMsg(msgs_.front());
212 msgs_.pop_front();
Austin Schuh39788ff2019-12-01 18:22:57 -0800213 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214 }
215
Austin Schuh39788ff2019-12-01 18:22:57 -0800216 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217 if (msgs_.size() == 0) {
218 if (!msg_ && queue_->latest_message()) {
219 SetMsg(queue_->latest_message());
Austin Schuh39788ff2019-12-01 18:22:57 -0800220 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221 } else {
Austin Schuh39788ff2019-12-01 18:22:57 -0800222 return std::make_pair(false, monotonic_clock::min_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700223 }
224 }
225
226 // We've had a message enqueued, so we don't need to go looking for the
227 // latest message from before we started.
228 SetMsg(msgs_.back());
229 msgs_.clear();
Austin Schuh39788ff2019-12-01 18:22:57 -0800230 return std::make_pair(true, queue_->monotonic_now());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231 }
232
233 private:
234 friend class SimulatedChannel;
235
236 // Updates the state inside RawFetcher to point to the data in msg_.
237 void SetMsg(std::shared_ptr<SimulatedMessage> msg) {
238 msg_ = msg;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239 context_ = msg_->context;
240 }
241
242 // Internal method for Simulation to add a message to the buffer.
243 void Enqueue(std::shared_ptr<SimulatedMessage> buffer) {
244 msgs_.emplace_back(buffer);
245 }
246
247 SimulatedChannel *queue_;
248 std::shared_ptr<SimulatedMessage> msg_;
249
250 // Messages queued up but not in use.
251 ::std::deque<std::shared_ptr<SimulatedMessage>> msgs_;
252};
253
254class SimulatedTimerHandler : public TimerHandler {
255 public:
256 explicit SimulatedTimerHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800257 SimulatedEventLoop *simulated_event_loop,
Austin Schuh39788ff2019-12-01 18:22:57 -0800258 ::std::function<void()> fn);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700259 ~SimulatedTimerHandler() {}
260
261 void Setup(monotonic_clock::time_point base,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800262 monotonic_clock::duration repeat_offset) override;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700263
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800264 void HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265
266 void Disable() override {
267 if (token_ != scheduler_->InvalidToken()) {
268 scheduler_->Deschedule(token_);
269 token_ = scheduler_->InvalidToken();
270 }
271 }
272
273 ::aos::monotonic_clock::time_point monotonic_now() const {
274 return scheduler_->monotonic_now();
275 }
276
277 private:
278 EventScheduler *scheduler_;
279 EventScheduler::Token token_;
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800280
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281 monotonic_clock::time_point base_;
282 monotonic_clock::duration repeat_offset_;
283};
284
285class SimulatedPhasedLoopHandler : public PhasedLoopHandler {
286 public:
287 SimulatedPhasedLoopHandler(EventScheduler *scheduler,
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800288 SimulatedEventLoop *simulated_event_loop,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289 ::std::function<void(int)> fn,
290 const monotonic_clock::duration interval,
Austin Schuh39788ff2019-12-01 18:22:57 -0800291 const monotonic_clock::duration offset);
292 ~SimulatedPhasedLoopHandler() {
293 if (token_ != scheduler_->InvalidToken()) {
294 scheduler_->Deschedule(token_);
295 token_ = scheduler_->InvalidToken();
296 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297 }
298
Austin Schuh39788ff2019-12-01 18:22:57 -0800299 void HandleTimerWakeup();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700300
Austin Schuh39788ff2019-12-01 18:22:57 -0800301 void Schedule(monotonic_clock::time_point sleep_time) override {
302 token_ = scheduler_->Schedule(sleep_time, [this]() { HandleTimerWakeup(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 }
304
305 private:
Austin Schuh39788ff2019-12-01 18:22:57 -0800306 SimulatedEventLoop *simulated_event_loop_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307
Austin Schuh39788ff2019-12-01 18:22:57 -0800308 EventScheduler *scheduler_;
309 EventScheduler::Token token_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700310};
311
312class SimulatedEventLoop : public EventLoop {
313 public:
314 explicit SimulatedEventLoop(
315 EventScheduler *scheduler,
316 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>>
317 *channels,
318 const Configuration *configuration,
319 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
Austin Schuh39788ff2019-12-01 18:22:57 -0800320 *raw_event_loops,
321 pid_t tid)
322 : EventLoop(CHECK_NOTNULL(configuration)),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323 scheduler_(scheduler),
324 channels_(channels),
Austin Schuh39788ff2019-12-01 18:22:57 -0800325 raw_event_loops_(raw_event_loops),
326 tid_(tid) {
327 raw_event_loops_->push_back(std::make_pair(this, [this](bool value) {
328 if (!has_setup_) {
329 Setup();
330 has_setup_ = true;
331 }
332 set_is_running(value);
333 }));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334 }
335 ~SimulatedEventLoop() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800336 // Trigger any remaining senders or fetchers to be cleared before destroying
337 // the event loop so the book keeping matches.
338 timing_report_sender_.reset();
339
340 // Force everything with a registered fd with epoll to be destroyed now.
341 timers_.clear();
342 phased_loops_.clear();
343 watchers_.clear();
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 for (auto it = raw_event_loops_->begin(); it != raw_event_loops_->end();
346 ++it) {
347 if (it->first == this) {
348 raw_event_loops_->erase(it);
349 break;
350 }
351 }
352 }
353
354 ::aos::monotonic_clock::time_point monotonic_now() override {
355 return scheduler_->monotonic_now();
356 }
357
358 ::aos::realtime_clock::time_point realtime_now() override {
359 return scheduler_->realtime_now();
360 }
361
362 ::std::unique_ptr<RawSender> MakeRawSender(const Channel *channel) override;
363
364 ::std::unique_ptr<RawFetcher> MakeRawFetcher(const Channel *channel) override;
365
366 void MakeRawWatcher(
367 const Channel *channel,
368 ::std::function<void(const Context &context, const void *message)>
369 watcher) override;
370
371 TimerHandler *AddTimer(::std::function<void()> callback) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800372 CHECK(!is_running());
373 return NewTimer(::std::unique_ptr<TimerHandler>(
374 new SimulatedTimerHandler(scheduler_, this, callback)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 }
376
377 PhasedLoopHandler *AddPhasedLoop(::std::function<void(int)> callback,
378 const monotonic_clock::duration interval,
379 const monotonic_clock::duration offset =
380 ::std::chrono::seconds(0)) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800381 return NewPhasedLoop(
382 ::std::unique_ptr<PhasedLoopHandler>(new SimulatedPhasedLoopHandler(
383 scheduler_, this, callback, interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700384 }
385
386 void OnRun(::std::function<void()> on_run) override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800387 scheduler_->ScheduleOnRun(on_run);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388 }
389
James Kuszmaul3ae42262019-11-08 12:33:41 -0800390 void set_name(const std::string_view name) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 name_ = std::string(name);
392 }
James Kuszmaul3ae42262019-11-08 12:33:41 -0800393 const std::string_view name() const override { return name_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700394
395 SimulatedChannel *GetSimulatedChannel(const Channel *channel);
396
397 void Take(const Channel *channel);
398
Austin Schuh39788ff2019-12-01 18:22:57 -0800399 void SetRuntimeRealtimePriority(int priority) override {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700400 CHECK(!is_running()) << ": Cannot set realtime priority while running.";
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 priority_ = priority;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 }
403
Austin Schuh39788ff2019-12-01 18:22:57 -0800404 int priority() const override { return priority_; }
405
406 void Setup() { MaybeScheduleTimingReports(); }
407
Alex Perrycb7da4b2019-08-28 19:35:56 -0700408 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800409 friend class SimulatedTimerHandler;
410
Austin Schuh39788ff2019-12-01 18:22:57 -0800411 pid_t GetTid() override { return tid_; }
412
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413 EventScheduler *scheduler_;
414 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> *channels_;
415 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
416 *raw_event_loops_;
417 absl::btree_set<SimpleChannel> taken_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700418
419 ::std::string name_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800420
421 int priority_ = 0;
422
423 bool has_setup_ = false;
424
425 const pid_t tid_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700426};
427
428void SimulatedEventLoop::MakeRawWatcher(
429 const Channel *channel,
430 std::function<void(const Context &channel, const void *message)> watcher) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800431 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432 Take(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800433 std::unique_ptr<ShmWatcher> shm_watcher(
434 new ShmWatcher(this, channel, std::move(watcher)));
435
436 GetSimulatedChannel(channel)->MakeRawWatcher(shm_watcher.get());
437 NewWatcher(std::move(shm_watcher));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438}
439
440std::unique_ptr<RawSender> SimulatedEventLoop::MakeRawSender(
441 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800442 ChannelIndex(channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 Take(channel);
444 return GetSimulatedChannel(channel)->MakeRawSender(this);
445}
446
447std::unique_ptr<RawFetcher> SimulatedEventLoop::MakeRawFetcher(
448 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 ChannelIndex(channel);
450 return GetSimulatedChannel(channel)->MakeRawFetcher(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451}
452
453SimulatedChannel *SimulatedEventLoop::GetSimulatedChannel(
454 const Channel *channel) {
455 auto it = channels_->find(SimpleChannel(channel));
456 if (it == channels_->end()) {
457 it = channels_
458 ->emplace(SimpleChannel(channel),
459 std::unique_ptr<SimulatedChannel>(
460 new SimulatedChannel(channel, scheduler_)))
461 .first;
462 }
463 return it->second.get();
464}
465
Austin Schuh39788ff2019-12-01 18:22:57 -0800466void SimulatedChannel::MakeRawWatcher(ShmWatcher *watcher) {
467 watcher->SetSimulatedChannel(this);
468 watchers_.emplace_back(watcher);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469}
470
471::std::unique_ptr<RawSender> SimulatedChannel::MakeRawSender(
472 EventLoop *event_loop) {
473 return ::std::unique_ptr<RawSender>(new SimulatedSender(this, event_loop));
474}
475
Austin Schuh39788ff2019-12-01 18:22:57 -0800476::std::unique_ptr<RawFetcher> SimulatedChannel::MakeRawFetcher(
477 EventLoop *event_loop) {
478 ::std::unique_ptr<SimulatedFetcher> fetcher(
479 new SimulatedFetcher(event_loop, this));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 fetchers_.push_back(fetcher.get());
481 return ::std::move(fetcher);
482}
483
484void SimulatedChannel::Send(std::shared_ptr<SimulatedMessage> message) {
485 message->context.queue_index = next_queue_index_.index();
486 message->context.data =
487 message->data() + channel()->max_size() - message->context.size;
488 next_queue_index_ = next_queue_index_.Increment();
489
490 latest_message_ = message;
491 if (scheduler_->is_running()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800492 for (ShmWatcher *watcher : watchers_) {
493 watcher->Schedule(scheduler_, message);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 }
495 }
496 for (auto &fetcher : fetchers_) {
497 fetcher->Enqueue(message);
498 }
499}
500
501void SimulatedChannel::UnregisterFetcher(SimulatedFetcher *fetcher) {
502 fetchers_.erase(::std::find(fetchers_.begin(), fetchers_.end(), fetcher));
503}
504
505SimpleChannel::SimpleChannel(const Channel *channel)
506 : name(CHECK_NOTNULL(CHECK_NOTNULL(channel)->name())->str()),
507 type(CHECK_NOTNULL(CHECK_NOTNULL(channel)->type())->str()) {}
508
Austin Schuh39788ff2019-12-01 18:22:57 -0800509SimulatedTimerHandler::SimulatedTimerHandler(
510 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
511 ::std::function<void()> fn)
512 : TimerHandler(simulated_event_loop, std::move(fn)),
513 scheduler_(scheduler),
514 token_(scheduler_->InvalidToken()) {}
515
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800516void SimulatedTimerHandler::Setup(monotonic_clock::time_point base,
517 monotonic_clock::duration repeat_offset) {
518 Disable();
519 const ::aos::monotonic_clock::time_point monotonic_now =
520 scheduler_->monotonic_now();
521 base_ = base;
522 repeat_offset_ = repeat_offset;
523 if (base < monotonic_now) {
524 token_ = scheduler_->Schedule(monotonic_now, [this]() { HandleEvent(); });
525 } else {
526 token_ = scheduler_->Schedule(base, [this]() { HandleEvent(); });
527 }
528}
529
530void SimulatedTimerHandler::HandleEvent() {
531 const ::aos::monotonic_clock::time_point monotonic_now =
532 scheduler_->monotonic_now();
533 if (repeat_offset_ != ::aos::monotonic_clock::zero()) {
534 // Reschedule.
535 while (base_ <= monotonic_now) base_ += repeat_offset_;
536 token_ = scheduler_->Schedule(base_, [this]() { HandleEvent(); });
537 } else {
538 token_ = scheduler_->InvalidToken();
539 }
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800540
Austin Schuh39788ff2019-12-01 18:22:57 -0800541 Call([monotonic_now]() { return monotonic_now; }, monotonic_now);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800542}
543
Austin Schuh39788ff2019-12-01 18:22:57 -0800544SimulatedPhasedLoopHandler::SimulatedPhasedLoopHandler(
545 EventScheduler *scheduler, SimulatedEventLoop *simulated_event_loop,
546 ::std::function<void(int)> fn, const monotonic_clock::duration interval,
547 const monotonic_clock::duration offset)
548 : PhasedLoopHandler(simulated_event_loop, std::move(fn), interval, offset),
549 simulated_event_loop_(simulated_event_loop),
550 scheduler_(scheduler),
551 token_(scheduler_->InvalidToken()) {}
552
553void SimulatedPhasedLoopHandler::HandleTimerWakeup() {
554 monotonic_clock::time_point monotonic_now =
555 simulated_event_loop_->monotonic_now();
556 Call(
557 [monotonic_now]() { return monotonic_now; },
558 [this](monotonic_clock::time_point sleep_time) { Schedule(sleep_time); });
559}
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800560
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561void SimulatedEventLoop::Take(const Channel *channel) {
562 CHECK(!is_running()) << ": Cannot add new objects while running.";
563
564 auto result = taken_.insert(SimpleChannel(channel));
565 CHECK(result.second) << ": " << FlatbufferToJson(channel)
566 << " is already being used.";
567}
568
569SimulatedEventLoopFactory::SimulatedEventLoopFactory(
570 const Configuration *configuration)
Austin Schuh39788ff2019-12-01 18:22:57 -0800571 : configuration_(CHECK_NOTNULL(configuration)) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572SimulatedEventLoopFactory::~SimulatedEventLoopFactory() {}
573
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800574::std::unique_ptr<EventLoop> SimulatedEventLoopFactory::MakeEventLoop(
575 std::string_view name) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800576 pid_t tid = tid_;
577 ++tid_;
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800578 ::std::unique_ptr<EventLoop> result(new SimulatedEventLoop(
Austin Schuh39788ff2019-12-01 18:22:57 -0800579 &scheduler_, &channels_, configuration_, &raw_event_loops_, tid));
Austin Schuh5f1cc5c2019-12-01 18:01:11 -0800580 result->set_name(name);
581 return result;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582}
583
584void SimulatedEventLoopFactory::RunFor(monotonic_clock::duration duration) {
585 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
586 raw_event_loops_) {
587 event_loop.second(true);
588 }
589 scheduler_.RunFor(duration);
Austin Schuh39788ff2019-12-01 18:22:57 -0800590 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
591 raw_event_loops_) {
592 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593 }
594}
595
596void SimulatedEventLoopFactory::Run() {
597 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
598 raw_event_loops_) {
599 event_loop.second(true);
600 }
601 scheduler_.Run();
Austin Schuh39788ff2019-12-01 18:22:57 -0800602 for (const std::pair<EventLoop *, std::function<void(bool)>> &event_loop :
603 raw_event_loops_) {
604 event_loop.second(false);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700605 }
606}
607
608} // namespace aos