Read a CoAP header
Decode the 4-byte CoAP header: version, type, token length, code and message ID. An easy embedded C problem (HTTP, REST and CoAP for IoT), run and graded in…
easy · HTTP, REST and CoAP for IoT · coap · iot · bits
CoAP, the "HTTP for constrained devices", runs over UDP with a 4-byte header:
| Bits | Field |
|---|---|
| byte 0, bits 7-6 | version (must be 1) |
| byte 0, bits 5-4 | type: 0 CON, 1 NON, 2 ACK, 3 RST |
| byte 0, bits 3-0 | token length (0 to 8) |
| byte 1 | code: class in bits 7-5, detail in bits 4-0, written class.detail (0.01 GET, 2.05 Content, 4.04 Not Found) |
| bytes 2-3 | message ID, big-endian |
Write coap_parse(m, len, h): fill h and return 0, or -1 if the message is shorter than 4 bytes plus its token, the version is not 1, or the token length is more than 8.
Starter code
int coap_parse(const uint8_t *m, int len, coap_t *h) {
(void)len;
h->type = m[0] >> 4;
h->tkl = m[0] & 0x0F;
h->code_class = m[1] / 100;
h->code_detail = m[1] % 100;
h->id = (uint16_t)(m[2] | (m[3] << 8));
return 0;
}Example tests
A GET request
uint8_t m[] = { 0x42, 0x01, 0x12, 0x34, 0xAB, 0xCD };
show(m, 6);Expected output:
CON 0.01 id 4660 token 2 bytesA piggybacked response
uint8_t m[] = { 0x62, 0x45, 0x12, 0x34, 0xAB, 0xCD, 0xFF, '2', '1' };
show(m, 9);Expected output:
ACK 2.05 id 4660 token 2 bytesLearn it first
- HTTP, REST and CoAP for IoT · REST design, HTTP versions, JSON versus CBOR, and CoAP.