-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunAsyncEvents.h
More file actions
398 lines (316 loc) · 8.92 KB
/
RunAsyncEvents.h
File metadata and controls
398 lines (316 loc) · 8.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#pragma once
#if __has_include(<Arduino.h>)
#include <Arduino.h>
#else
#include <string>
using String = std::string;
#endif
#include <cstddef>
#include <cstdint>
#include <any>
#include <functional>
#include <type_traits>
#include <utility>
namespace arduino_events {
struct Config {
size_t eventQueueCapacity = 32;
size_t workerQueueCapacity = 16;
uint8_t workerThreadCount = 1;
uint32_t defaultTimeoutMs = 30000;
};
enum class ErrorCode : uint8_t {
None = 0,
Timeout,
Cancelled,
QueueFull,
InvalidState,
Network,
Internal,
};
struct Error {
ErrorCode code = ErrorCode::None;
int nativeCode = 0;
String message;
};
template <typename T>
class Result {
public:
static Result<T> ok(T value);
static Result<T> err(Error error);
bool isOk() const;
const T& value() const;
T& value();
const Error& error() const;
private:
Result() = default;
bool ok_ = false;
T value_{};
Error error_{};
};
template <>
class Result<void> {
public:
static Result<void> ok();
static Result<void> err(Error error);
bool isOk() const;
const Error& error() const;
private:
Result() = default;
bool ok_ = false;
Error error_{};
};
template <typename T>
class Future {
public:
using SuccessHandler = std::function<void(const T&)>;
using ErrorHandler = std::function<void(const Error&)>;
using FinallyHandler = std::function<void()>;
Future() = default;
Future<T>& onDone(SuccessHandler handler);
Future<T>& onError(ErrorHandler handler);
Future<T>& onFinish(FinallyHandler handler);
Future<T>& withTimeout(uint32_t timeoutMs);
bool cancel();
bool isReady() const;
bool hasError() const;
bool isCancelled() const;
bool tryGet(Result<T>& out) const;
private:
friend class Runtime;
explicit Future(uint32_t token) : token_(token) {}
uint32_t token_ = 0;
};
template <>
class Future<void> {
public:
using SuccessHandler = std::function<void()>;
using ErrorHandler = std::function<void(const Error&)>;
using FinallyHandler = std::function<void()>;
Future() = default;
Future<void>& onDone(SuccessHandler handler);
Future<void>& onError(ErrorHandler handler);
Future<void>& onFinish(FinallyHandler handler);
Future<void>& withTimeout(uint32_t timeoutMs);
bool cancel();
bool isReady() const;
bool hasError() const;
bool isCancelled() const;
bool tryGet(Result<void>& out) const;
private:
friend class Runtime;
explicit Future(uint32_t token) : token_(token) {}
uint32_t token_ = 0;
};
struct Subscription {
uint32_t id = 0;
explicit operator bool() const { return id != 0; }
};
template <typename EventT>
using EventHandler = std::function<void(const EventT&)>;
template <typename T>
class Deferred {
public:
Deferred() = default;
bool resolve(T value);
bool reject(Error error);
bool isCancelled() const;
private:
friend class Runtime;
explicit Deferred(uint32_t token) : token_(token) {}
uint32_t token_ = 0;
};
template <>
class Deferred<void> {
public:
Deferred() = default;
bool resolve();
bool reject(Error error);
bool isCancelled() const;
private:
friend class Runtime;
explicit Deferred(uint32_t token) : token_(token) {}
uint32_t token_ = 0;
};
class Runtime {
public:
static Runtime& instance();
bool begin(const Config& config = {});
void end();
bool isRunning() const;
// Call from sketch loop() to dispatch queued callbacks on sketch context.
void update(uint32_t budgetMs = 0);
template <typename EventT>
Subscription listen(EventHandler<EventT> handler) {
return registerHandler(typeId<EventT>(),
[handler = std::move(handler)](const void* rawEvent) {
handler(*static_cast<const EventT*>(rawEvent));
},
false);
}
template <typename EventT>
Subscription listenOnce(EventHandler<EventT> handler) {
return registerHandler(typeId<EventT>(),
[handler = std::move(handler)](const void* rawEvent) {
handler(*static_cast<const EventT*>(rawEvent));
},
true);
}
template <typename EventT>
bool post(const EventT& event) {
return emitRaw(typeId<EventT>(), static_cast<const void*>(&event), sizeof(EventT));
}
bool unlisten(Subscription subscription);
uint32_t after(uint32_t delayMs, std::function<void()> callback);
uint32_t every(uint32_t periodMs, std::function<void()> callback);
bool cancelTimer(uint32_t timerId);
template <typename T>
Future<T> runAsync(std::function<void(Deferred<T>)> start) {
return createDeferred<T>(std::move(start));
}
Future<void> runAsync(std::function<void(Deferred<void>)> start);
// Internal hooks used by Future/Deferred templates.
void futureOnSuccess(uint32_t token, std::function<void(const std::any&)> onSuccess);
void futureOnError(uint32_t token, std::function<void(const Error&)> onError);
void futureOnFinally(uint32_t token, std::function<void()> onFinally);
void futureSetTimeout(uint32_t token, uint32_t timeoutMs);
bool futureCancel(uint32_t token);
bool futureIsReady(uint32_t token) const;
bool futureHasError(uint32_t token) const;
bool futureIsCancelled(uint32_t token) const;
bool futureTryGetAny(uint32_t token, std::any& outValue, Error& outError,
bool& outHasError) const;
bool futureResolveAny(uint32_t token, std::any value);
bool futureReject(uint32_t token, Error error);
private:
using RawEventHandler = std::function<void(const void*)>;
Runtime();
template <typename EventT>
static size_t typeId() {
static const uint8_t kTypeTag = 0;
return reinterpret_cast<size_t>(&kTypeTag);
}
Subscription registerHandler(size_t eventTypeId, RawEventHandler handler, bool once);
bool emitRaw(size_t eventTypeId, const void* eventData, size_t eventSize);
uint32_t allocFutureToken();
bool enqueue(std::function<void()> callback);
bool enqueueWorker(std::function<void()> callback);
template <typename T>
Future<T> createDeferred(std::function<void(Deferred<T>)> start);
};
// Global Events object — use like Serial, Wire, WiFi.
extern Runtime& Events;
inline bool begin(const Config& config = {}) { return Events.begin(config); }
inline void update(uint32_t budgetMs = 0) { Events.update(budgetMs); }
template <typename T>
Result<T> Result<T>::ok(T value) {
Result<T> out;
out.ok_ = true;
out.value_ = std::move(value);
return out;
}
template <typename T>
Result<T> Result<T>::err(Error error) {
Result<T> out;
out.ok_ = false;
out.error_ = std::move(error);
return out;
}
template <typename T>
bool Result<T>::isOk() const {
return ok_;
}
template <typename T>
const T& Result<T>::value() const {
return value_;
}
template <typename T>
T& Result<T>::value() {
return value_;
}
template <typename T>
const Error& Result<T>::error() const {
return error_;
}
template <typename T>
Future<T>& Future<T>::onDone(SuccessHandler handler) {
Runtime::instance().futureOnSuccess(
token_, [handler = std::move(handler)](const std::any& value) {
handler(std::any_cast<const T&>(value));
});
return *this;
}
template <typename T>
Future<T>& Future<T>::onError(ErrorHandler handler) {
Runtime::instance().futureOnError(token_, std::move(handler));
return *this;
}
template <typename T>
Future<T>& Future<T>::onFinish(FinallyHandler handler) {
Runtime::instance().futureOnFinally(token_, std::move(handler));
return *this;
}
template <typename T>
Future<T>& Future<T>::withTimeout(uint32_t timeoutMs) {
Runtime::instance().futureSetTimeout(token_, timeoutMs);
return *this;
}
template <typename T>
bool Future<T>::cancel() {
return Runtime::instance().futureCancel(token_);
}
template <typename T>
bool Future<T>::isReady() const {
return Runtime::instance().futureIsReady(token_);
}
template <typename T>
bool Future<T>::hasError() const {
return Runtime::instance().futureHasError(token_);
}
template <typename T>
bool Future<T>::isCancelled() const {
return Runtime::instance().futureIsCancelled(token_);
}
template <typename T>
bool Future<T>::tryGet(Result<T>& out) const {
std::any value;
Error error;
bool hasError = false;
if (!Runtime::instance().futureTryGetAny(token_, value, error, hasError)) {
return false;
}
if (hasError) {
out = Result<T>::err(std::move(error));
return true;
}
out = Result<T>::ok(std::any_cast<T>(std::move(value)));
return true;
}
template <typename T>
bool Deferred<T>::resolve(T value) {
return Runtime::instance().futureResolveAny(token_, std::any(std::move(value)));
}
template <typename T>
bool Deferred<T>::reject(Error error) {
return Runtime::instance().futureReject(token_, std::move(error));
}
template <typename T>
bool Deferred<T>::isCancelled() const {
return Runtime::instance().futureIsCancelled(token_);
}
template <typename T>
Future<T> Runtime::createDeferred(std::function<void(Deferred<T>)> start) {
const uint32_t token = allocFutureToken();
if (token == 0) {
return Future<T>();
}
if (!enqueueWorker([start = std::move(start), token]() mutable {
start(Deferred<T>(token));
})) {
Error err;
err.code = ErrorCode::QueueFull;
err.message = "worker queue full";
futureReject(token, std::move(err));
}
return Future<T>(token);
}
} // namespace arduino_events