RaidZeroLib
Coroutine robot framework for VEX V5
Loading...
Searching...
No Matches
Runtime.hpp
1#pragma once
2#include <array>
3#include <concepts>
4#include <coroutine>
5#include <cstdint>
6#include <source_location>
7#include <type_traits>
8
9#include "RaidZeroLib/api/Runtime/Platform.hpp"
10#include "RaidZeroLib/api/Runtime/Task.hpp" // also provides corral::detail::IntrusiveList
11#include "RaidZeroLib/api/Runtime/Watchdog.hpp"
12#include "RaidZeroLib/api/Units/Units.hpp"
13
14namespace rz {
15
16class Runtime;
17
25
31// Waiting never allocates: the awaiter (in the coroutine frame) is its own list node, and
32// unlinks itself when cancelled or destroyed.
33class [[nodiscard("co_await this")]] TickAwaiter : public corral::detail::IntrusiveListItem<TickAwaiter> {
34 public:
35 TickAwaiter(TickStage stage, std::source_location location) noexcept : stage(stage), location(location) {}
36
37 // Movable only before suspension (combinators like anyOf take awaitables by value).
38 TickAwaiter(TickAwaiter&& other) noexcept : stage(other.stage), location(other.location) {}
39 TickAwaiter(const TickAwaiter&) = delete;
42
43 bool await_ready() const noexcept { return false; }
44 void await_suspend(std::coroutine_handle<> waiting);
45 void await_resume() const noexcept {}
46 auto await_cancel(std::coroutine_handle<>) noexcept {
47 unlink();
48 return std::true_type{};
49 }
50
51 private:
52 friend class Runtime;
53 TickStage stage;
54 std::source_location location;
55 std::coroutine_handle<> handle;
56};
57
59// Waiting never allocates: the awaiter (in the coroutine frame) is its own list node, and
60// unlinks itself when cancelled or destroyed.
61class [[nodiscard("co_await this")]] SleepAwaiter : public corral::detail::IntrusiveListItem<SleepAwaiter> {
62 public:
63 SleepAwaiter(Duration duration, std::source_location location) noexcept : duration(duration), location(location) {}
64
65 // Movable only before suspension (combinators like anyOf take awaitables by value).
66 SleepAwaiter(SleepAwaiter&& other) noexcept : duration(other.duration), location(other.location) {}
67 SleepAwaiter(const SleepAwaiter&) = delete;
70
71 bool await_ready() const noexcept { return duration <= au::ZERO; }
72 void await_suspend(std::coroutine_handle<> waiting);
73 void await_resume() const noexcept {}
74 auto await_cancel(std::coroutine_handle<>) noexcept {
75 unlink();
76 return std::true_type{};
77 }
78
79 private:
80 friend class Runtime;
81 Duration duration;
82 std::source_location location;
83 Time deadline{};
84 std::coroutine_handle<> handle;
85};
86
98class Runtime {
99 public:
100 struct Config {
101 Duration period = au::milli(au::seconds)(10.0);
103 Watchdog* watchdog = nullptr;
104 };
105
106 explicit Runtime(Platform& platform) : Runtime(platform, Config{}) {}
107 Runtime(Platform& platform, Config config);
109
110 Runtime(const Runtime&) = delete;
111 Runtime& operator=(const Runtime&) = delete;
112
114 template <class Awaitable>
115 decltype(auto) run(Awaitable&& task);
116
118 [[nodiscard]] static Runtime& current();
119
121 [[nodiscard]] static Runtime* tryCurrent() noexcept { return current_; }
122
124 [[nodiscard]] Time now() const noexcept { return now_; }
126 [[nodiscard]] Duration dt() const noexcept { return dt_; }
128 [[nodiscard]] std::uint64_t tickCount() const noexcept { return tickCount_; }
129
132 [[nodiscard]] static std::uint64_t globalTickId() noexcept { return globalTickId_; }
133 [[nodiscard]] Duration period() const noexcept { return config.period; }
135 [[nodiscard]] CompetitionMode competitionMode() const { return platform.competitionMode(); }
136
137 private:
138 friend class TickAwaiter;
139 friend class SleepAwaiter;
140 friend struct corral::EventLoopTraits<Runtime>; // drives loop() for run(task)
141
142 // corral EventLoopTraits hooks
143 void loop();
144 void stop() noexcept { stopRequested = true; }
145 [[nodiscard]] bool isRunning() const noexcept { return running; }
146
147 void enqueue(TickAwaiter& awaiter) noexcept;
148 void addTimer(SleepAwaiter& awaiter) noexcept;
149
150 void tick();
151 void resumeStage(TickStage stage);
152 void resumeExpiredTimers();
153
154 Platform& platform;
155 Config config;
156 std::array<corral::detail::IntrusiveList<TickAwaiter>, 4> stages;
157 corral::detail::IntrusiveList<SleepAwaiter> timers;
158
159 Time now_{};
160 Duration dt_{};
161 std::uint64_t tickCount_ = 0;
162 bool running = false;
163 bool stopRequested = false;
164 bool firstTickOfRun = true;
165
166 static inline Runtime* current_ = nullptr;
167 static inline std::uint64_t globalTickId_ = 0;
168};
169
171[[nodiscard]] inline TickAwaiter tickStarted(std::source_location location = std::source_location::current()) noexcept {
172 return TickAwaiter{TickStage::TickStarted, location};
173}
174
177[[nodiscard]] inline TickAwaiter sensorsUpdated(
178 std::source_location location = std::source_location::current()) noexcept {
179 return TickAwaiter{TickStage::SensorsUpdated, location};
180}
181
183[[nodiscard]] inline TickAwaiter estimatorsUpdated(
184 std::source_location location = std::source_location::current()) noexcept {
186}
187
189[[nodiscard]] inline TickAwaiter componentsUpdated(
190 std::source_location location = std::source_location::current()) noexcept {
192}
193
195[[nodiscard]] inline SleepAwaiter sleepFor(Duration duration,
196 std::source_location location = std::source_location::current()) noexcept {
197 return SleepAwaiter{duration, location};
198}
199
201template <std::predicate P>
202[[nodiscard]] Task<void> until(P pred) {
203 while (!pred()) {
204 co_await estimatorsUpdated();
205 }
206}
207
209[[nodiscard]] inline Time now() { return Runtime::current().now(); }
210
212[[nodiscard]] inline Duration dt() { return Runtime::current().dt(); }
213
214} // namespace rz
215
216template <>
217struct corral::EventLoopTraits<rz::Runtime> {
218 static EventLoopID eventLoopID(rz::Runtime& runtime) noexcept { return EventLoopID(&runtime); }
219 static void run(rz::Runtime& runtime) { runtime.loop(); }
220 static void stop(rz::Runtime& runtime) noexcept { runtime.stop(); }
221 static bool isRunning(rz::Runtime& runtime) noexcept { return runtime.isRunning(); }
222};
223
224template <class Awaitable>
225decltype(auto) rz::Runtime::run(Awaitable&& task) {
226 // corral runs the task up to its first co_await before the first tick, so now() (and deadlines
227 // computed from it) must already be current.
228 now_ = platform.now();
229 dt_ = config.period;
230 firstTickOfRun = true;
231 return corral::run(*this, std::forward<Awaitable>(task));
232}
What the runtime needs from the outside world: a clock, a way to wait, and the competition mode.
Definition Platform.hpp:15
The single-threaded tick loop that drives every coroutine.
Definition Runtime.hpp:98
static std::uint64_t globalTickId() noexcept
Identifies the current tick uniquely across every runtime there has been; never repeats....
Definition Runtime.hpp:132
Duration dt() const noexcept
Time between the start of the previous tick and this one.
Definition Runtime.hpp:126
static Runtime * tryCurrent() noexcept
The current runtime, or nullptr if none exists (e.g. while globals are being constructed).
Definition Runtime.hpp:121
decltype(auto) run(Awaitable &&task)
Runs task on this runtime until it completes and returns its result.
Definition Runtime.hpp:225
Runtime(Platform &platform, Config config)
Duration period() const noexcept
Definition Runtime.hpp:133
Runtime(const Runtime &)=delete
Runtime & operator=(const Runtime &)=delete
friend class TickAwaiter
Definition Runtime.hpp:138
static Runtime & current()
The runtime that exists right now. Only one can exist at a time.
std::uint64_t tickCount() const noexcept
Number of ticks started so far (0 before the first tick).
Definition Runtime.hpp:128
friend class SleepAwaiter
Definition Runtime.hpp:139
Runtime(Platform &platform)
Definition Runtime.hpp:106
Time now() const noexcept
Time at the start of the current tick.
Definition Runtime.hpp:124
CompetitionMode competitionMode() const
The competition mode field control is in right now.
Definition Runtime.hpp:135
Awaiter that resumes at the first tick at or after a deadline.
Definition Runtime.hpp:61
auto await_cancel(std::coroutine_handle<>) noexcept
Definition Runtime.hpp:74
SleepAwaiter(Duration duration, std::source_location location) noexcept
Definition Runtime.hpp:63
SleepAwaiter & operator=(SleepAwaiter &&)=delete
SleepAwaiter & operator=(const SleepAwaiter &)=delete
SleepAwaiter(const SleepAwaiter &)=delete
bool await_ready() const noexcept
Definition Runtime.hpp:71
void await_resume() const noexcept
Definition Runtime.hpp:73
SleepAwaiter(SleepAwaiter &&other) noexcept
Definition Runtime.hpp:66
void await_suspend(std::coroutine_handle<> waiting)
friend class Runtime
Definition Runtime.hpp:80
Awaiter for the next occurrence of a tick stage. Always suspends.
Definition Runtime.hpp:33
TickAwaiter(const TickAwaiter &)=delete
void await_resume() const noexcept
Definition Runtime.hpp:45
bool await_ready() const noexcept
Definition Runtime.hpp:43
void await_suspend(std::coroutine_handle<> waiting)
TickAwaiter(TickStage stage, std::source_location location) noexcept
Definition Runtime.hpp:35
TickAwaiter & operator=(TickAwaiter &&)=delete
auto await_cancel(std::coroutine_handle<>) noexcept
Definition Runtime.hpp:46
friend class Runtime
Definition Runtime.hpp:52
TickAwaiter & operator=(const TickAwaiter &)=delete
TickAwaiter(TickAwaiter &&other) noexcept
Definition Runtime.hpp:38
Detects when the runtime stops ticking because a coroutine is blocking the loop.
Definition Watchdog.hpp:18
Task< void > until(P pred)
Waits until pred() is true, checking once per tick at estimatorsUpdated. Returns at once if already t...
Definition Runtime.hpp:202
TickStage
Where in a tick a waiter is resumed, named after what has just finished. Ticks run the stages in this...
Definition Runtime.hpp:19
Time now()
Time at the start of the current tick of the current runtime.
Definition Runtime.hpp:209
Duration dt()
Duration of the current tick of the current runtime.
Definition Runtime.hpp:212
corral::Task< T > Task
Lazy: nothing runs until it is co_awaited.
Definition Task.hpp:17
TickAwaiter tickStarted(std::source_location location=std::source_location::current()) noexcept
Resumes at the start of the next tick, before anything else runs. For device loops.
Definition Runtime.hpp:171
TickAwaiter estimatorsUpdated(std::source_location location=std::source_location::current()) noexcept
Resumes in the next tick once every estimator has run. For user code and mechanisms.
Definition Runtime.hpp:183
TickAwaiter componentsUpdated(std::source_location location=std::source_location::current()) noexcept
Resumes in the next tick once every component that writes has run. For logging and telemetry.
Definition Runtime.hpp:189
TickAwaiter sensorsUpdated(std::source_location location=std::source_location::current()) noexcept
Resumes in the next tick once every device has been polled. For estimators, and for code that only re...
Definition Runtime.hpp:177
CompetitionMode
What field control (or a competition switch) currently allows the robot to do.
Definition Platform.hpp:7
SleepAwaiter sleepFor(Duration duration, std::source_location location=std::source_location::current()) noexcept
Resumes at estimatorsUpdated in the first tick whose start time is at least duration from now.
Definition Runtime.hpp:195
@ SensorsUpdated
Every device polled. Estimators, and code that only reacts to hardware, wait here.
Definition Runtime.hpp:21
@ TickStarted
Nothing has run yet. Devices wait here to poll their hardware.
Definition Runtime.hpp:20
@ EstimatorsUpdated
Every estimator ran. User code and mechanisms wait here.
Definition Runtime.hpp:22
@ ComponentsUpdated
Every component that writes ran. Logging and telemetry wait here.
Definition Runtime.hpp:23
au::QuantityD< au::Seconds > Duration
Definition Units.hpp:16
au::QuantityPointD< au::Seconds > Time
Definition Units.hpp:17
Definition DriverControl.hpp:11
static void stop(rz::Runtime &runtime) noexcept
Definition Runtime.hpp:220
static EventLoopID eventLoopID(rz::Runtime &runtime) noexcept
Definition Runtime.hpp:218
static bool isRunning(rz::Runtime &runtime) noexcept
Definition Runtime.hpp:221
static void run(rz::Runtime &runtime)
Definition Runtime.hpp:219
Definition Runtime.hpp:100
Watchdog * watchdog
Told about every tick and resume, so another task can detect a stuck loop. Optional.
Definition Runtime.hpp:103
Duration period
Definition Runtime.hpp:101