blob: 79f1e46f32e85dd70a5583c547c18304f67aaaa5 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#ifndef AOS_EVENTS_SIMULATED_EVENT_LOOP_H_
2#define AOS_EVENTS_SIMULATED_EVENT_LOOP_H_
3
4#include <algorithm>
5#include <map>
6#include <memory>
Austin Schuh5f1cc5c2019-12-01 18:01:11 -08007#include <string_view>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include <unordered_set>
9#include <utility>
10#include <vector>
11
12#include "absl/container/btree_map.h"
13#include "aos/events/event_loop.h"
14#include "aos/events/event_scheduler.h"
15#include "aos/flatbuffer_merge.h"
16#include "aos/flatbuffers.h"
17#include "aos/ipc_lib/index.h"
18#include "glog/logging.h"
19
20namespace aos {
21
22// Class for simulated fetchers.
23class SimulatedChannel;
24
25struct SimpleChannel {
26 SimpleChannel(const Channel *channel);
27 std::string name;
28 std::string type;
29
30 std::string DebugString() const {
31 return std::string("{ ") + name + ", " + type + "}";
32 }
33
34 bool operator==(const SimpleChannel &other) const {
35 return name == other.name && type == other.type;
36 }
37 bool operator<(const SimpleChannel &other) const {
38 int name_compare = other.name.compare(name);
39 if (name_compare == 0) {
40 return other.type < type;
41 } else if (name_compare < 0) {
42 return true;
43 } else {
44 return false;
45 }
46 }
47};
48
49class SimulatedEventLoopFactory {
50 public:
51 // Constructs a SimulatedEventLoopFactory with the provided configuration.
52 // This configuration must remain in scope for the lifetime of the factory and
53 // all sub-objects.
54 SimulatedEventLoopFactory(const Configuration *configuration);
55 ~SimulatedEventLoopFactory();
56
Austin Schuh5f1cc5c2019-12-01 18:01:11 -080057 ::std::unique_ptr<EventLoop> MakeEventLoop(std::string_view name);
Alex Perrycb7da4b2019-08-28 19:35:56 -070058
59 // Starts executing the event loops unconditionally.
60 void Run();
61 // Executes the event loops for a duration.
62 void RunFor(monotonic_clock::duration duration);
63
64 // Stops executing all event loops. Meant to be called from within an event
65 // loop handler.
66 void Exit() { scheduler_.Exit(); }
67
68 monotonic_clock::time_point monotonic_now() const {
69 return scheduler_.monotonic_now();
70 }
71 realtime_clock::time_point realtime_now() const {
72 return scheduler_.realtime_now();
73 }
74
75 private:
76 const Configuration *configuration_;
77 EventScheduler scheduler_;
78 // Map from name, type to queue.
79 absl::btree_map<SimpleChannel, std::unique_ptr<SimulatedChannel>> channels_;
80 // List of event loops to manage running and not running for.
81 std::vector<std::pair<EventLoop *, std::function<void(bool)>>>
82 raw_event_loops_;
Austin Schuh39788ff2019-12-01 18:22:57 -080083
84 pid_t tid_ = 0;
Alex Perrycb7da4b2019-08-28 19:35:56 -070085};
86
87} // namespace aos
88
89#endif // AOS_EVENTS_SIMULATED_EVENT_LOOP_H_