2026-04-06 17:36:41 +09:00
|
|
|
#pragma once
|
|
|
|
|
#include <cstdint>
|
2026-04-11 08:21:59 +09:00
|
|
|
#include <cstdio>
|
2026-04-07 07:34:24 +09:00
|
|
|
#include <functional>
|
2026-04-11 08:15:41 +09:00
|
|
|
#include <optional>
|
2026-04-06 17:36:41 +09:00
|
|
|
#include <span>
|
2026-04-07 06:58:39 +09:00
|
|
|
#include "wire.h"
|
2026-04-11 08:28:32 +09:00
|
|
|
#include "timer_queue.h"
|
2026-04-06 17:36:41 +09:00
|
|
|
|
2026-04-11 08:15:41 +09:00
|
|
|
struct responder {
|
|
|
|
|
uint32_t message_id;
|
|
|
|
|
std::function<void(std::span<const uint8_t>)> send;
|
|
|
|
|
|
|
|
|
|
template <typename T>
|
|
|
|
|
void respond(const T& msg) const {
|
|
|
|
|
uint8_t buf[1024];
|
|
|
|
|
span_writer out(buf, sizeof(buf));
|
|
|
|
|
auto r = encode_response_into(out, message_id, msg);
|
|
|
|
|
if (r) send({buf, *r});
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
using handler_fn = void (*)(responder resp, std::span<const uint8_t> payload);
|
2026-04-07 06:58:39 +09:00
|
|
|
|
2026-04-06 17:36:41 +09:00
|
|
|
struct handler_entry {
|
|
|
|
|
int8_t type_id;
|
2026-04-07 06:58:39 +09:00
|
|
|
handler_fn handle;
|
2026-04-06 17:36:41 +09:00
|
|
|
};
|
|
|
|
|
|
2026-04-07 06:58:39 +09:00
|
|
|
template <typename Req, auto Fn>
|
2026-04-11 08:15:41 +09:00
|
|
|
void typed_handler(responder resp, std::span<const uint8_t> payload) {
|
2026-04-07 06:58:39 +09:00
|
|
|
msgpack::parser p(payload.data(), static_cast<int>(payload.size()));
|
|
|
|
|
Req req;
|
|
|
|
|
auto tup = req.as_tuple();
|
|
|
|
|
auto r = msgpack::unpack(p, tup);
|
|
|
|
|
if (!r) {
|
2026-04-11 08:21:59 +09:00
|
|
|
char err[64];
|
|
|
|
|
snprintf(err, sizeof(err), "decode request ext_id=%d: msgpack error %d",
|
|
|
|
|
Req::ext_id, static_cast<int>(r.error()));
|
|
|
|
|
resp.respond(DeviceError{1, err});
|
2026-04-11 08:15:41 +09:00
|
|
|
return;
|
2026-04-07 06:58:39 +09:00
|
|
|
}
|
2026-04-11 08:15:41 +09:00
|
|
|
auto result = Fn(resp, req);
|
|
|
|
|
if (result)
|
|
|
|
|
resp.respond(*result);
|
2026-04-07 06:58:39 +09:00
|
|
|
}
|
|
|
|
|
|
2026-04-06 20:01:22 +09:00
|
|
|
void dispatch_init();
|
2026-04-11 08:28:32 +09:00
|
|
|
timer_handle dispatch_schedule_ms(uint32_t ms, std::function<void()> fn);
|
|
|
|
|
bool dispatch_cancel_timer(timer_handle h);
|
2026-04-07 07:34:24 +09:00
|
|
|
[[noreturn]] void dispatch_run(std::span<const handler_entry> handlers);
|