/
coap_ext.c
101 lines (84 loc) · 2.66 KB
/
coap_ext.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* Copyright (C) 2015 HAW Hamburg
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @{
*
* @file
* @brief extensions to stock microcoap (might become PRs)
*
* @author Lotte Steenbrink <lotte.steenbrink@haw-hamburg.de>
*
* @}
*/
#include "coap_ext.h"
#define ENABLE_DEBUG (0)
#include "debug.h"
const coap_endpoint_t endpoints[] =
{
{(coap_method_t)0, NULL, NULL, NULL} /* marks the end of the endpoints array */
};
int seqnum = 12345;
// TODO: use rw_buf?
/**
Build a PUT request.
The value of buflen will be the request packet's size after successful completion.
*/
int coap_ext_build_PUT(uint8_t *buf, size_t *buflen,
const char *payload, const coap_endpoint_path_t *path)
{
/*
* Note: the resource URI is coded as an option! -> COAP_OPTION_URI_PATH
*/
seqnum++;
DEBUG("creating PUT request...\n");
size_t req_pkt_sz;
int errcode;
int segment_count = path->count;
/* cobble together CoAP header */
coap_header_t req_hdr = {
.ver = 1,
.t = COAP_TYPE_CON,
.tkl = 0, /* microcoap can't generate tokens anyway */
.code = MAKE_RSPCODE(0, COAP_METHOD_PUT), /* class 0, detail 1: this is a PUT. */
.id = {seqnum,22} /* TODO: create dynamic ID (seqnum style?) */
};
coap_buffer_t payload_buf = {
.p = (const uint8_t *) payload,
.len = strlen(payload)
};
coap_packet_t req_pkt = {
.hdr = req_hdr,
.tok = (coap_buffer_t) {}, /* No token */
.numopts = segment_count, /* all segments of the path to the resource */
.payload = payload_buf
};
/* Create one option for each segment of the URI path and fill req_pkt.opts*/
for (int i=0; i < segment_count; i++ ) {
coap_option_t path_option = {
.num = COAP_OPTION_URI_PATH,
.buf = {.p = (const uint8_t *) path->elems[i],
.len = strlen(path->elems[i])}
};
req_pkt.opts[i] = path_option;
}
req_pkt_sz = sizeof(req_pkt);
if (*buflen < req_pkt_sz) {
DEBUG("Error: buflen too small:\n\tbuflen:%d\n\treq_pkt_sz:%d\n", *buflen, req_pkt_sz);
return -1;
}
#ifdef DEBUG
DEBUG("[main-posix] content:\n");
coap_dumpPacket(&req_pkt);
#endif
// try to write packet to send buffer
if (0 != (errcode = coap_build(buf, buflen, &req_pkt))) {
DEBUG("Error building packet! Error code: %i\nAborting. \n", errcode);
return -1;
}
return 0;
}