7 #include <satcat5/coap_connection.h>
8 #include <satcat5/coap_writer.h>
19 static unsigned varint_len(u64 x) {
21 while (x) {++len; x >>= 8;}
25 bool Writer::write_header(u8 type,
Code code, u16 msg_id, u64 token, u8 tkl) {
27 if (!m_dst)
return false;
30 if (token && !tkl) tkl = varint_len(token);
36 m_dst->
write_u8(VERSION1 | type | tkl);
38 m_dst->write_u16(msg_id);
39 if (tkl) write_varint(token, tkl);
50 if (!m_dst)
return false;
52 bool ok = write_optid(
id, len);
62 if (!m_dst)
return false;
64 unsigned len = varint_len(value);
65 bool ok = write_optid(
id, len);
66 if (ok) write_varint(value, len);
71 if (!m_dst)
return false;
75 if (str[len] == 0 || str[len] ==
'/') {
79 if (ok && str[len]) {str += len + 1; len = 0;}
96 bool Writer::write_optid(u16
id,
unsigned len) {
98 if (!m_dst)
return false;
108 if (delta < 13) pre_id = u8(delta << 4);
109 else if (delta < 269) pre_id = 0xD0;
111 if (len < 13) pre_len = u8(len);
112 else if (len < 269) pre_len = 0x0D;
117 if (pre_id == 0xD0) m_dst->
write_u8(delta - 13);
118 if (pre_id == 0xE0) m_dst->write_u16(delta - 269);
119 if (pre_len == 0x0D) m_dst->
write_u8(len - 13);
120 if (pre_len == 0x0E) m_dst->write_u16(len - 269);
124 void Writer::write_varint(u64 x,
unsigned len) {
126 u8 tmp[8]; write_be_u64(tmp, x);
127 unsigned skip = 8 - len;
131 void Writer::insert_max_age(u16 next_id) {
134 if (next_id != 0 && next_id < OPTION_MAX_AGE) {
return; }
135 if (next_id == OPTION_MAX_AGE) {
138 write_optid(OPTION_MAX_AGE, 0);
CoAP request/response handling for a single client-server connection.
u8 tkl() const
< Most recent token length
u64 token() const
< Most recent message token
u8 response_type() const
Determine the expected response type for an incoming request.
u16 msg_id() const
< Most recent message ID
Message formatting for the Constrained Applications Protocol (CoAP).
bool write_uri(u16 id, const char *str)
Convert a URI to consecutive Uri-Path options.
bool m_insert_max_age
Add Max-Age=0 to disable caching.
bool write_option(u16 id, unsigned len, const void *data)
Write option(s) one at a time, in various formats.
satcat5::io::Writeable * write_data()
After the last option, start writing message data.
bool write_header(u8 type, Code code, u16 msg_id, u64 token=0, u8 tkl=0)
Always start by writing the header, with optional token.
u16 m_last_opt
Previous option-ID.
Abstract API for writing byte-streams and packets.
virtual void write_bytes(unsigned nbytes, const void *src)
Write 0 or more bytes from a buffer.
void write_u8(u8 data)
One of many functions for writing integer/floating point values, see details.
constexpr u8 PAYLOAD_MARKER
CoAP message header VERSION and TYPE fields (Section 3).
"Writeable" I/O interface core definitions
CoAP message header CODE field (Section 12.1).
Miscellaneous mathematical utility functions.
void write_be_u64(u8 *dst, u64 val)
Store fields into a big-endian byte array.