Add message IDs, transport interface, client package, extract protocol headers
This commit is contained in:
51
include/device.h
Normal file
51
include/device.h
Normal file
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include "msgpackpp.h"
|
||||
#include "halfsiphash.h"
|
||||
#include "static_vector.h"
|
||||
#include "protocol.h"
|
||||
|
||||
static constexpr uint8_t hash_key[8] = {};
|
||||
|
||||
struct DecodedMessage {
|
||||
uint32_t message_id;
|
||||
int8_t type_id;
|
||||
};
|
||||
|
||||
inline std::vector<uint8_t> pack_envelope(uint32_t message_id, const std::vector<uint8_t> &payload) {
|
||||
uint32_t checksum = halfsiphash::hash32(payload.data(), payload.size(), hash_key);
|
||||
msgpackpp::packer p;
|
||||
p.pack(Envelope{message_id, checksum, payload});
|
||||
return p.get_payload();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
inline std::vector<uint8_t> encode_response(uint32_t message_id, const T &msg) {
|
||||
msgpackpp::packer inner;
|
||||
inner.pack(msg);
|
||||
return pack_envelope(message_id, inner.get_payload());
|
||||
}
|
||||
|
||||
inline msgpackpp::result<DecodedMessage> try_decode(const uint8_t *data, size_t len) {
|
||||
msgpackpp::parser p(data, static_cast<int>(len));
|
||||
|
||||
Envelope env;
|
||||
auto r = msgpackpp::unpack(p, env);
|
||||
if (!r) return std::unexpected(r.error());
|
||||
|
||||
uint32_t expected = halfsiphash::hash32(env.payload.data(), env.payload.size(), hash_key);
|
||||
if (env.checksum != expected) return std::unexpected(msgpackpp::error_code::invalid);
|
||||
|
||||
msgpackpp::parser inner(env.payload.data(), static_cast<int>(env.payload.size()));
|
||||
if (!inner.is_ext()) return std::unexpected(msgpackpp::error_code::type_error);
|
||||
auto ext = inner.get_ext();
|
||||
if (!ext) return std::unexpected(ext.error());
|
||||
|
||||
return DecodedMessage{env.message_id, std::get<0>(*ext)};
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
inline msgpackpp::result<DecodedMessage> try_decode(const static_vector<uint8_t, N> &buf) {
|
||||
return try_decode(buf.data(), buf.size());
|
||||
}
|
||||
Reference in New Issue
Block a user