Files
picomap/firmware/include/dispatch.h

47 lines
1.3 KiB
C
Raw Normal View History

#pragma once
#include <cstdint>
#include <functional>
#include <optional>
#include <span>
#include "wire.h"
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);
struct handler_entry {
int8_t type_id;
handler_fn handle;
};
template <typename Req, auto Fn>
void typed_handler(responder resp, std::span<const uint8_t> payload) {
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) {
resp.respond(DeviceError{1, "decode request ext_id=" +
std::to_string(Req::ext_id) + ": msgpack error " + std::to_string(static_cast<int>(r.error()))});
return;
}
auto result = Fn(resp, req);
if (result)
resp.respond(*result);
}
void dispatch_init();
void dispatch_schedule_ms(uint32_t ms, std::function<void()> fn);
[[noreturn]] void dispatch_run(std::span<const handler_entry> handlers);