Commit 4754064e authored by funshine's avatar funshine
Browse files

add coap module, see fragment.lua for usage

parent a1dc023c
...@@ -30,6 +30,7 @@ SUBDIRS= \ ...@@ -30,6 +30,7 @@ SUBDIRS= \
platform \ platform \
libc \ libc \
lua \ lua \
coap \
mqtt \ mqtt \
smart \ smart \
wofs \ wofs \
...@@ -76,6 +77,7 @@ COMPONENTS_eagle.app.v6 = \ ...@@ -76,6 +77,7 @@ COMPONENTS_eagle.app.v6 = \
platform/libplatform.a \ platform/libplatform.a \
libc/liblibc.a \ libc/liblibc.a \
lua/liblua.a \ lua/liblua.a \
coap/coap.a \
mqtt/mqtt.a \ mqtt/mqtt.a \
smart/smart.a \ smart/smart.a \
wofs/wofs.a \ wofs/wofs.a \
......
Copyright (c) 2013 Toby Jaffey <toby@1248.io>
2015 Zeroday Hong <zeroday@nodemcu.com> nodemcu.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of images to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
ifndef PDIR
GEN_LIBS = coap.a
endif
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
# Generally values applying to a tree are captured in the
# makefile at its root level - these are then overridden
# for a subtree within the makefile rooted therein
#
#DEFINES +=
#############################################################
# Recursion Magic - Don't touch this!!
#
# Each subtree potentially has an include directory
# corresponding to the common APIs applicable to modules
# rooted at that subtree. Accordingly, the INCLUDE PATH
# of a module can only contain the include directories up
# its parent path, and not its siblings
#
# Required for each makefile to inherit from the parent
#
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
INCLUDES += -I ../libc
INCLUDES += -I ../lua
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
#include "user_config.h"
#include "c_stdio.h"
#include "c_string.h"
#include "coap.h"
#include "uri.h"
extern void endpoint_setup(void);
extern const coap_endpoint_t endpoints[];
#ifdef COAP_DEBUG
void coap_dumpHeader(coap_header_t *hdr)
{
c_printf("Header:\n");
c_printf(" ver 0x%02X\n", hdr->ver);
c_printf(" t 0x%02X\n", hdr->ver);
c_printf(" tkl 0x%02X\n", hdr->tkl);
c_printf(" code 0x%02X\n", hdr->code);
c_printf(" id 0x%02X%02X\n", hdr->id[0], hdr->id[1]);
}
void coap_dump(const uint8_t *buf, size_t buflen, bool bare)
{
if (bare)
{
while(buflen--)
c_printf("%02X%s", *buf++, (buflen > 0) ? " " : "");
}
else
{
c_printf("Dump: ");
while(buflen--)
c_printf("%02X%s", *buf++, (buflen > 0) ? " " : "");
c_printf("\n");
}
}
#endif
int coap_parseHeader(coap_header_t *hdr, const uint8_t *buf, size_t buflen)
{
if (buflen < 4)
return COAP_ERR_HEADER_TOO_SHORT;
hdr->ver = (buf[0] & 0xC0) >> 6;
if (hdr->ver != 1)
return COAP_ERR_VERSION_NOT_1;
hdr->t = (buf[0] & 0x30) >> 4;
hdr->tkl = buf[0] & 0x0F;
hdr->code = buf[1];
hdr->id[0] = buf[2];
hdr->id[1] = buf[3];
return 0;
}
int coap_buildHeader(const coap_header_t *hdr, uint8_t *buf, size_t buflen)
{
// build header
if (buflen < 4)
return COAP_ERR_BUFFER_TOO_SMALL;
buf[0] = (hdr->ver & 0x03) << 6;
buf[0] |= (hdr->t & 0x03) << 4;
buf[0] |= (hdr->tkl & 0x0F);
buf[1] = hdr->code;
buf[2] = hdr->id[0];
buf[3] = hdr->id[1];
return 4;
}
int coap_parseToken(coap_buffer_t *tokbuf, const coap_header_t *hdr, const uint8_t *buf, size_t buflen)
{
if (hdr->tkl == 0)
{
tokbuf->p = NULL;
tokbuf->len = 0;
return 0;
}
else
if (hdr->tkl <= 8)
{
if (4 + hdr->tkl > buflen)
return COAP_ERR_TOKEN_TOO_SHORT; // tok bigger than packet
tokbuf->p = buf+4; // past header
tokbuf->len = hdr->tkl;
return 0;
}
else
{
// invalid size
return COAP_ERR_TOKEN_TOO_SHORT;
}
}
int coap_buildToken(const coap_buffer_t *tokbuf, const coap_header_t *hdr, uint8_t *buf, size_t buflen)
{
// inject token
uint8_t *p;
if (buflen < 4 + hdr->tkl)
return COAP_ERR_BUFFER_TOO_SMALL;
p = buf + 4;
if ((hdr->tkl > 0) && (hdr->tkl != tokbuf->len))
return COAP_ERR_UNSUPPORTED;
if (hdr->tkl > 0)
c_memcpy(p, tokbuf->p, hdr->tkl);
// http://tools.ietf.org/html/draft-ietf-core-coap-18#section-3.1
// inject options
return hdr->tkl;
}
// advances p
int coap_parseOption(coap_option_t *option, uint16_t *running_delta, const uint8_t **buf, size_t buflen)
{
const uint8_t *p = *buf;
uint16_t len, delta;
uint8_t headlen = 1;
if (buflen < headlen) // too small
return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER;
delta = (p[0] & 0xF0) >> 4;
len = p[0] & 0x0F;
// These are untested and may be buggy
if (delta == 13)
{
headlen++;
if (buflen < headlen)
return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER;
delta = p[1] + 13;
p++;
}
else
if (delta == 14)
{
headlen += 2;
if (buflen < headlen)
return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER;
delta = ((p[1] << 8) | p[2]) + 269;
p+=2;
}
else
if (delta == 15)
return COAP_ERR_OPTION_DELTA_INVALID;
if (len == 13)
{
headlen++;
if (buflen < headlen)
return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER;
len = p[1] + 13;
p++;
}
else
if (len == 14)
{
headlen += 2;
if (buflen < headlen)
return COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER;
len = ((p[1] << 8) | p[2]) + 269;
p+=2;
}
else
if (len == 15)
return COAP_ERR_OPTION_LEN_INVALID;
if ((p + 1 + len) > (*buf + buflen))
return COAP_ERR_OPTION_TOO_BIG;
//printf("option num=%d\n", delta + *running_delta);
option->num = delta + *running_delta;
option->buf.p = p+1;
option->buf.len = len;
//coap_dump(p+1, len, false);
// advance buf
*buf = p + 1 + len;
*running_delta += delta;
return 0;
}
// http://tools.ietf.org/html/draft-ietf-core-coap-18#section-3.1
int coap_parseOptionsAndPayload(coap_option_t *options, uint8_t *numOptions, coap_buffer_t *payload, const coap_header_t *hdr, const uint8_t *buf, size_t buflen)
{
size_t optionIndex = 0;
const uint8_t *p = buf + 4 + hdr->tkl;
const uint8_t *end = buf + buflen;
int rc;
uint16_t delta = 0;
if (p > end)
return COAP_ERR_OPTION_OVERRUNS_PACKET; // out of bounds
//coap_dump(p, end - p);
// 0xFF is payload marker
while((optionIndex < *numOptions) && (p < end) && (*p != 0xFF))
{
if (0 != (rc = coap_parseOption(&options[optionIndex], &delta, &p, end-p)))
return rc;
optionIndex++;
}
*numOptions = optionIndex;
if (p+1 < end && *p == 0xFF) // payload marker
{
payload->p = p+1;
payload->len = end-(p+1);
}
else
{
payload->p = NULL;
payload->len = 0;
}
return 0;
}
int coap_buildOptionHeader(unsigned short optDelta, size_t length, uint8_t *buf, size_t buflen)
{
int n = 0;
uint8_t *p = buf;
uint8_t len, delta = 0;
if (buflen < 5)
return COAP_ERR_BUFFER_TOO_SMALL;
coap_option_nibble(optDelta, &delta);
coap_option_nibble(length, &len);
*p++ = (0xFF & (delta << 4 | len));
n++;
if (delta == 13)
{
*p++ = (optDelta - 13);
n++;
}
else
if (delta == 14)
{
*p++ = ((optDelta-269) >> 8);
*p++ = (0xFF & (optDelta-269));
n+=2;
}
if (len == 13)
{
*p++ = (length - 13);
n++;
}
else
if (len == 14)
{
*p++ = (length >> 8);
*p++ = (0xFF & (length-269));
n+=2;
}
return n;
}
#ifdef COAP_DEBUG
void coap_dumpOptions(coap_option_t *opts, size_t numopt)
{
size_t i;
c_printf(" Options:\n");
for (i=0;i<numopt;i++)
{
c_printf(" 0x%02X [ ", opts[i].num);
coap_dump(opts[i].buf.p, opts[i].buf.len, true);
c_printf(" ]\n");
}
}
void coap_dumpPacket(coap_packet_t *pkt)
{
coap_dumpHeader(&pkt->hdr);
coap_dumpOptions(pkt->opts, pkt->numopts);
c_printf("Payload: ");
coap_dump(pkt->payload.p, pkt->payload.len, true);
c_printf("\n");
}
#endif
int coap_parse(coap_packet_t *pkt, const uint8_t *buf, size_t buflen)
{
int rc;
// coap_dump(buf, buflen, false);
if (0 != (rc = coap_parseHeader(&pkt->hdr, buf, buflen)))
return rc;
// coap_dumpHeader(&hdr);
if (0 != (rc = coap_parseToken(&pkt->tok, &pkt->hdr, buf, buflen)))
return rc;
pkt->numopts = MAXOPT;
if (0 != (rc = coap_parseOptionsAndPayload(pkt->opts, &(pkt->numopts), &(pkt->payload), &pkt->hdr, buf, buflen)))
return rc;
// coap_dumpOptions(opts, numopt);
return 0;
}
// options are always stored consecutively, so can return a block with same option num
const coap_option_t * coap_findOptions(const coap_packet_t *pkt, uint8_t num, uint8_t *count)
{
// FIXME, options is always sorted, can find faster than this
size_t i;
const coap_option_t *first = NULL;
*count = 0;
for (i=0;i<pkt->numopts;i++)
{
if (pkt->opts[i].num == num)
{
if (NULL == first)
first = &pkt->opts[i];
(*count)++;
}
else
{
if (NULL != first)
break;
}
}
return first;
}
int coap_buffer_to_string(char *strbuf, size_t strbuflen, const coap_buffer_t *buf)
{
if (buf->len+1 > strbuflen)
return COAP_ERR_BUFFER_TOO_SMALL;
c_memcpy(strbuf, buf->p, buf->len);
strbuf[buf->len] = 0;
return 0;
}
int coap_build(uint8_t *buf, size_t *buflen, const coap_packet_t *pkt)
{
size_t opts_len = 0, hdr_len = 0, tok_len = 0;
size_t i;
uint8_t *p = buf;
size_t left = *buflen;
uint16_t running_delta = 0;
hdr_len = coap_buildHeader(&(pkt->hdr), buf, *buflen);
p += hdr_len;
left -= hdr_len;
tok_len = coap_buildToken(&(pkt->tok), &(pkt->hdr), buf, *buflen);
p += tok_len;
left -= tok_len;
for (i=0;i<pkt->numopts;i++)
{
uint8_t len, delta = 0;
uint16_t optDelta = 0;
int rc = 0;
if (p-buf > *buflen)
return COAP_ERR_BUFFER_TOO_SMALL;
optDelta = pkt->opts[i].num - running_delta;
rc = coap_buildOptionHeader(optDelta, pkt->opts[i].buf.len, p, left);
p += rc;
left -= rc;
c_memcpy(p, pkt->opts[i].buf.p, pkt->opts[i].buf.len);
p += pkt->opts[i].buf.len;
left -= pkt->opts[i].buf.len;
running_delta = pkt->opts[i].num;
}
opts_len = (p - buf) - 4; // number of bytes used by options
if (pkt->payload.len > 0)
{
if (*buflen < 4 + 1 + pkt->payload.len + opts_len)
return COAP_ERR_BUFFER_TOO_SMALL;
buf[4 + opts_len] = 0xFF; // payload marker
c_memcpy(buf+5 + opts_len, pkt->payload.p, pkt->payload.len);
*buflen = opts_len + 5 + pkt->payload.len;
}
else
*buflen = opts_len + 4;
return 0;
}
void coap_option_nibble(uint16_t value, uint8_t *nibble)
{
if (value<13)
{
*nibble = (0xFF & value);
}
else
if (((uint32_t)value)<=0xFF+13)
{
*nibble = 13;
} else if (((uint32_t)value) -269 <=0xFFFF)
{
*nibble = 14;
}
}
int coap_make_response(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const uint8_t *content, size_t content_len, uint8_t msgid_hi, uint8_t msgid_lo, const coap_buffer_t* tok, coap_responsecode_t rspcode, coap_content_type_t content_type)
{
pkt->hdr.ver = 0x01;
pkt->hdr.t = COAP_TYPE_ACK;
pkt->hdr.tkl = 0;
pkt->hdr.code = rspcode;
pkt->hdr.id[0] = msgid_hi;
pkt->hdr.id[1] = msgid_lo;
pkt->numopts = 0;
// need token in response
if (tok) {
pkt->hdr.tkl = tok->len;
pkt->tok = *tok;
}
// safe because 1 < MAXOPT
pkt->opts[0].num = COAP_OPTION_CONTENT_FORMAT;
pkt->opts[0].buf.p = scratch->p;
if (scratch->len < 2)
return COAP_ERR_BUFFER_TOO_SMALL;
scratch->p[0] = ((uint16_t)content_type & 0xFF00) >> 8;
scratch->p[1] = ((uint16_t)content_type & 0x00FF);
pkt->opts[0].buf.len = 2;
pkt->payload.p = content;
pkt->payload.len = content_len;
return 0;
}
unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val) {
unsigned int n, i;
for (n = 0, i = val; i && n < sizeof(val); ++n)
i >>= 8;
i = n;
while (i--) {
buf[i] = val & 0xff;
val >>= 8;
}
return n;
}
static uint8_t _token_data[4]={'n','o','d','e'};
coap_buffer_t the_token = { _token_data, 4 };
static unsigned short message_id;
int coap_make_request(coap_rw_buffer_t *scratch, coap_packet_t *pkt, coap_msgtype_t t, coap_method_t m, coap_uri_t *uri, const uint8_t *payload, size_t payload_len)
{
int res;
pkt->hdr.ver = 0x01;
pkt->hdr.t = t;
pkt->hdr.tkl = 0;
pkt->hdr.code = m;
pkt->hdr.id[0] = (message_id >> 8) & 0xFF; //msgid_hi;
pkt->hdr.id[1] = message_id & 0xFF; //msgid_lo;
message_id++;
NODE_DBG("message_id: %d.\n", message_id);
pkt->numopts = 0;
if (the_token.len) {
pkt->hdr.tkl = the_token.len;
pkt->tok = the_token;
}
if (scratch->len < 2) // TBD...
return COAP_ERR_BUFFER_TOO_SMALL;
uint8_t *saved = scratch->p;
/* split arg into Uri-* options */
// const char *addr = uri->host.s;
// if(uri->host.length && (c_strlen(addr) != uri->host.length || c_memcmp(addr, uri->host.s, uri->host.length) != 0)){
if(uri->host.length){
/* add Uri-Host */
// addr is destination address
pkt->opts[pkt->numopts].num = COAP_OPTION_URI_HOST;
pkt->opts[pkt->numopts].buf.p = uri->host.s;
pkt->opts[pkt->numopts].buf.len = uri->host.length;
pkt->numopts++;
}
if (uri->port != COAP_DEFAULT_PORT) {
pkt->opts[pkt->numopts].num = COAP_OPTION_URI_PORT;
res = coap_encode_var_bytes(scratch->p, uri->port);
pkt->opts[pkt->numopts].buf.len = res;
pkt->opts[pkt->numopts].buf.p = scratch->p;
scratch->p += res;
scratch->len -= res;
pkt->numopts++;
}
if (uri->path.length) {
res = coap_split_path(scratch, pkt, uri->path.s, uri->path.length);
}
if (uri->query.length) {
res = coap_split_query(scratch, pkt, uri->query.s, uri->query.length);
}
pkt->payload.p = payload;
pkt->payload.len = payload_len;
scratch->p = saved; // save back the pointer.
return 0;
}
// FIXME, if this looked in the table at the path before the method then
// it could more easily return 405 errors
int coap_handle_req(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt)
{
const coap_option_t *opt;
int i;
uint8_t count;
const coap_endpoint_t *ep = endpoints;
while(NULL != ep->handler)
{
if (ep->method != inpkt->hdr.code)
goto next;
if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count)))
{
// if (count != ep->path->count)
if ((count != ep->path->count ) && (count != ep->path->count + 1)) // +1 for /f/[function], /v/[variable]
goto next;
for (i=0;i<ep->path->count;i++)
{
if (opt[i].buf.len != c_strlen(ep->path->elems[i]))
goto next;
if (0 != c_memcmp(ep->path->elems[i], opt[i].buf.p, opt[i].buf.len))
goto next;
}
// pre-path match!
if (count==ep->path->count+1 && ep->user_entry == NULL)
goto next;
return ep->handler(ep, scratch, inpkt, outpkt, inpkt->hdr.id[0], inpkt->hdr.id[1]);
}
next:
ep++;
}
coap_make_response(scratch, outpkt, NULL, 0, inpkt->hdr.id[0], inpkt->hdr.id[1], &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
return 0;
}
void coap_setup(void)
{
message_id = (unsigned short)rand(); // calculate only once
}
inline int
check_token(coap_packet_t *pkt) {
return pkt->tok.len == the_token.len && c_memcmp(pkt->tok.p, the_token.p, the_token.len) == 0;
}
#ifndef COAP_H
#define COAP_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "c_stdint.h"
#include "c_stddef.h"
#include "lualib.h"
#include "lauxlib.h"
#define MAXOPT 16
#define MAX_MESSAGE_SIZE 1152
#define MAX_PAYLOAD_SIZE 1024
#define MAX_REQUEST_SIZE 576
#define MAX_REQ_SCRATCH_SIZE 60
#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF)
// http://tools.ietf.org/html/draft-ietf-core-coap-18#section-3
typedef struct
{
uint8_t ver;
uint8_t t;
uint8_t tkl;
uint8_t code;
uint8_t id[2];
} coap_header_t;
typedef struct
{
const uint8_t *p;
size_t len;
} coap_buffer_t;
typedef struct
{
uint8_t *p;
size_t len;
} coap_rw_buffer_t;
typedef struct
{
uint8_t num;
coap_buffer_t buf;
} coap_option_t;
typedef struct
{
coap_header_t hdr;
coap_buffer_t tok;
uint8_t numopts;
coap_option_t opts[MAXOPT];
coap_buffer_t payload;
coap_rw_buffer_t scratch; // scratch->p = malloc(...) , and free it when done.
} coap_packet_t;
/////////////////////////////////////////
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-12.2
typedef enum
{
COAP_OPTION_IF_MATCH = 1,
COAP_OPTION_URI_HOST = 3,
COAP_OPTION_ETAG = 4,
COAP_OPTION_IF_NONE_MATCH = 5,
COAP_OPTION_OBSERVE = 6,
COAP_OPTION_URI_PORT = 7,
COAP_OPTION_LOCATION_PATH = 8,
COAP_OPTION_URI_PATH = 11,
COAP_OPTION_CONTENT_FORMAT = 12,
COAP_OPTION_MAX_AGE = 14,
COAP_OPTION_URI_QUERY = 15,
COAP_OPTION_ACCEPT = 17,
COAP_OPTION_LOCATION_QUERY = 20,
COAP_OPTION_PROXY_URI = 35,
COAP_OPTION_PROXY_SCHEME = 39
} coap_option_num_t;
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-12.1.1
typedef enum
{
COAP_METHOD_GET = 1,
COAP_METHOD_POST = 2,
COAP_METHOD_PUT = 3,
COAP_METHOD_DELETE = 4
} coap_method_t;
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-12.1.1
typedef enum
{
COAP_TYPE_CON = 0,
COAP_TYPE_NONCON = 1,
COAP_TYPE_ACK = 2,
COAP_TYPE_RESET = 3
} coap_msgtype_t;
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-5.2
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-12.1.2
#define MAKE_RSPCODE(clas, det) ((clas << 5) | (det))
typedef enum
{
COAP_RSPCODE_CONTENT = MAKE_RSPCODE(2, 5),
COAP_RSPCODE_NOT_FOUND = MAKE_RSPCODE(4, 4),
COAP_RSPCODE_BAD_REQUEST = MAKE_RSPCODE(4, 0),
COAP_RSPCODE_CHANGED = MAKE_RSPCODE(2, 4)
} coap_responsecode_t;
//http://tools.ietf.org/html/draft-ietf-core-coap-18#section-12.3
typedef enum
{
COAP_CONTENTTYPE_NONE = -1, // bodge to allow us not to send option block
COAP_CONTENTTYPE_TEXT_PLAIN = 0,
COAP_CONTENTTYPE_APPLICATION_LINKFORMAT = 40,
} coap_content_type_t;
///////////////////////
typedef enum
{
COAP_ERR_NONE = 0,
COAP_ERR_HEADER_TOO_SHORT = 1,
COAP_ERR_VERSION_NOT_1 = 2,
COAP_ERR_TOKEN_TOO_SHORT = 3,
COAP_ERR_OPTION_TOO_SHORT_FOR_HEADER = 4,
COAP_ERR_OPTION_TOO_SHORT = 5,
COAP_ERR_OPTION_OVERRUNS_PACKET = 6,
COAP_ERR_OPTION_TOO_BIG = 7,
COAP_ERR_OPTION_LEN_INVALID = 8,
COAP_ERR_BUFFER_TOO_SMALL = 9,
COAP_ERR_UNSUPPORTED = 10,
COAP_ERR_OPTION_DELTA_INVALID = 11,
} coap_error_t;
///////////////////////
typedef struct coap_endpoint_t coap_endpoint_t;
typedef int (*coap_endpoint_func)(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo);
#define MAX_SEGMENTS 3 // 2 = /foo/bar, 3 = /foo/bar/baz
#define MAX_SEGMENTS_SIZE 16
typedef struct
{
int count;
const char *elems[MAX_SEGMENTS];
} coap_endpoint_path_t;
typedef struct coap_luser_entry coap_luser_entry;
struct coap_luser_entry{
lua_State *L;
// int ref;
// char name[MAX_SEGMENTS_SIZE+1]; // +1 for string '\0'
const char *name;
coap_luser_entry *next;
};
struct coap_endpoint_t
{
coap_method_t method;
coap_endpoint_func handler;
const coap_endpoint_path_t *path;
const char *core_attr;
coap_luser_entry *user_entry;
};
///////////////////////
void coap_dumpPacket(coap_packet_t *pkt);
int coap_parse(coap_packet_t *pkt, const uint8_t *buf, size_t buflen);
int coap_buffer_to_string(char *strbuf, size_t strbuflen, const coap_buffer_t *buf);
const coap_option_t *coap_findOptions(const coap_packet_t *pkt, uint8_t num, uint8_t *count);
int coap_build(uint8_t *buf, size_t *buflen, const coap_packet_t *pkt);
void coap_dump(const uint8_t *buf, size_t buflen, bool bare);
int coap_make_response(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const uint8_t *content, size_t content_len, uint8_t msgid_hi, uint8_t msgid_lo, const coap_buffer_t* tok, coap_responsecode_t rspcode, coap_content_type_t content_type);
int coap_handle_req(coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt);
void coap_option_nibble(uint16_t value, uint8_t *nibble);
void coap_setup(void);
void endpoint_setup(void);
int coap_buildOptionHeader(unsigned short optDelta, size_t length, uint8_t *buf, size_t buflen);
#ifdef __cplusplus
}
#endif
#endif
#include "user_config.h"
#include "c_types.h"
#include "coap.h"
#include "hash.h"
#include "node.h"
extern coap_queue_t *gQueue;
void coap_client_response_handler(char *data, unsigned short len, unsigned short size, const uint32_t ip, const uint32_t port)
{
NODE_DBG("coap_client_response_handler is called.\n");
coap_packet_t pkt;
int rc;
if (0 != (rc = coap_parse(&pkt, data, len))){
NODE_DBG("Bad packet rc=%d\n", rc);
}
else
{
#ifdef COAP_DEBUG
coap_dumpPacket(&pkt);
#endif
/* check if this is a response to our original request */
if (!check_token(&pkt)) {
/* drop if this was just some message, or send RST in case of notification */
if (pkt.hdr.t == COAP_TYPE_CON || pkt.hdr.t == COAP_TYPE_NONCON){
// coap_send_rst(pkt); // send RST response
// or, just ignore it.
}
goto end;
}
if (pkt.hdr.t == COAP_TYPE_RESET) {
NODE_DBG("got RST\n");
goto end;
}
coap_tid_t id = COAP_INVALID_TID;
coap_transaction_id(ip, port, &pkt, &id);
/* transaction done, remove the node from queue */
// stop timer
coap_timer_stop();
// remove the node
coap_remove_node(&gQueue, id);
// calculate time elapsed
coap_timer_update(&gQueue);
coap_timer_start(&gQueue);
if (COAP_RESPONSE_CLASS(pkt.hdr.code) == 2)
{
/* There is no block option set, just read the data and we are done. */
NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
NODE_DBG(pkt.payload.p);
}
else if (COAP_RESPONSE_CLASS(pkt.hdr.code) >= 4)
{
NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
NODE_DBG(pkt.payload.p);
}
}
end:
if(!gQueue){ // if there is no node pending in the queue, disconnect from host.
}
}
#ifndef _COAP_SERVER_H
#define _COAP_SERVER_H 1
#ifdef __cplusplus
extern "C" {
#endif
size_t coap_server_respond(char *data, unsigned short len, unsigned short size);
#ifdef __cplusplus
}
#endif
#endif
#include "c_string.h"
#include "coap_io.h"
#include "node.h"
#include "espconn.h"
#include "coap_timer.h"
extern coap_queue_t *gQueue;
/* releases space allocated by PDU if free_pdu is set */
coap_tid_t coap_send(struct espconn *pesp_conn, coap_pdu_t *pdu) {
coap_tid_t id = COAP_INVALID_TID;
uint32_t ip = 0, port = 0;
if ( !pesp_conn || !pdu )
return id;
espconn_sent(pesp_conn, (unsigned char *)(pdu->msg.p), pdu->msg.len);
if(pesp_conn->type == ESPCONN_TCP){
c_memcpy(&ip, pesp_conn->proto.tcp->remote_ip, sizeof(ip));
port = pesp_conn->proto.tcp->remote_port;
}else{
c_memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
port = pesp_conn->proto.udp->remote_port;
}
coap_transaction_id(ip, port, pdu->pkt, &id);
return id;
}
coap_tid_t coap_send_confirmed(struct espconn *pesp_conn, coap_pdu_t *pdu) {
coap_queue_t *node;
coap_tick_t diff;
uint32_t r;
node = coap_new_node();
if (!node) {
NODE_DBG("coap_send_confirmed: insufficient memory\n");
return COAP_INVALID_TID;
}
node->retransmit_cnt = 0;
node->id = coap_send(pesp_conn, pdu);
if (COAP_INVALID_TID == node->id) {
NODE_DBG("coap_send_confirmed: error sending pdu\n");
coap_free_node(node);
return COAP_INVALID_TID;
}
r = rand();
/* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND +
(COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) *
((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
node->pconn = pesp_conn;
node->pdu = pdu;
/* Set timer for pdu retransmission. If this is the first element in
* the retransmission queue, the base time is set to the current
* time and the retransmission time is node->timeout. If there is
* already an entry in the sendqueue, we must check if this node is
* to be retransmitted earlier. Therefore, node->timeout is first
* normalized to the timeout and then inserted into the queue with
* an adjusted relative time.
*/
coap_timer_stop();
coap_timer_update(&gQueue);
node->t = node->timeout;
coap_insert_node(&gQueue, node);
coap_timer_start(&gQueue);
return node->id;
}
#ifndef _COAP_IO_H
#define _COAP_IO_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "espconn.h"
#include "pdu.h"
#include "hash.h"
coap_tid_t coap_send(struct espconn *pesp_conn, coap_pdu_t *pdu);
coap_tid_t coap_send_confirmed(struct espconn *pesp_conn, coap_pdu_t *pdu);
#ifdef __cplusplus
}
#endif
#endif
#include "user_config.h"
#include "c_types.h"
#include "coap.h"
size_t coap_server_respond(char *data, unsigned short len, unsigned short size)
{
NODE_DBG("coap_server_respond is called.\n");
if(len>size){
NODE_DBG("len:%d, size:%d\n",len,size);
return 0;
}
size_t rsplen = size;
coap_packet_t pkt;
uint8_t scratch_raw[4];
coap_rw_buffer_t scratch_buf = {scratch_raw, sizeof(scratch_raw)};
int rc;
#ifdef COAP_DEBUG
NODE_DBG("Received: ");
coap_dump(data, len, true);
NODE_DBG("\n");
#endif
if (0 != (rc = coap_parse(&pkt, data, len))){
NODE_DBG("Bad packet rc=%d\n", rc);
return 0;
}
else
{
coap_packet_t rsppkt;
#ifdef COAP_DEBUG
coap_dumpPacket(&pkt);
#endif
coap_handle_req(&scratch_buf, &pkt, &rsppkt);
if (0 != (rc = coap_build(data, &rsplen, &rsppkt))){
NODE_DBG("coap_build failed rc=%d\n", rc);
return 0;
}
else
{
#ifdef COAP_DEBUG
NODE_DBG("Responding: ");
coap_dump(data, rsplen, true);
NODE_DBG("\n");
#endif
#ifdef COAP_DEBUG
coap_dumpPacket(&rsppkt);
#endif
}
return rsplen;
}
}
#ifndef _COAP_SERVER_H
#define _COAP_SERVER_H 1
#ifdef __cplusplus
extern "C" {
#endif
size_t coap_server_respond(char *data, unsigned short len, unsigned short size);
#ifdef __cplusplus
}
#endif
#endif
#include "node.h"
#include "coap_timer.h"
#include "os_type.h"
static os_timer_t coap_timer;
static coap_tick_t basetime = 0;
void coap_timer_elapsed(coap_tick_t *diff){
coap_tick_t now = system_get_time() / 1000; // coap_tick_t is in ms. also sys_timer
if(now>=basetime){
*diff = now-basetime;
} else {
*diff = now + SYS_TIME_MAX -basetime;
}
basetime = now;
}
void coap_timer_tick(void *arg){
if( !arg )
return;
coap_queue_t **queue = (coap_queue_t **)arg;
if( !(*queue) )
return;
coap_queue_t *node = coap_pop_next( queue );
/* re-initialize timeout when maximum number of retransmissions are not reached yet */
if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
node->retransmit_cnt++;
node->t = node->timeout << node->retransmit_cnt;
NODE_DBG("** retransmission #%d of transaction %d\n",
node->retransmit_cnt, (((uint16_t)(node->pdu->pkt->hdr.id[0]))<<8)+node->pdu->pkt->hdr.id[1]);
node->id = coap_send(node->pconn, node->pdu);
if (COAP_INVALID_TID == node->id) {
NODE_DBG("retransmission: error sending pdu\n");
coap_delete_node(node);
} else {
coap_insert_node(queue, node);
}
} else {
/* And finally delete the node */
coap_delete_node( node );
}
coap_timer_start(queue);
}
void coap_timer_setup(coap_queue_t ** queue, coap_tick_t t){
os_timer_disarm(&coap_timer);
os_timer_setfn(&coap_timer, (os_timer_func_t *)coap_timer_tick, queue);
os_timer_arm(&coap_timer, t, 0); // no repeat
}
void coap_timer_stop(void){
os_timer_disarm(&coap_timer);
}
void coap_timer_update(coap_queue_t ** queue){
if (!queue)
return;
coap_tick_t diff = 0;
coap_queue_t *first = *queue;
coap_timer_elapsed(&diff); // update: basetime = now, diff = now - oldbase, means time elapsed
if (first) {
// diff ms time is elapsed, re-calculate the first node->t
if (first->t >= diff){
first->t -= diff;
} else {
first->t = 0; // when timer enabled, time out almost immediately
}
}
}
void coap_timer_start(coap_queue_t ** queue){
if(*queue){ // if there is node in the queue, set timeout to its ->t.
coap_timer_setup(queue, (*queue)->t);
}
}
#ifndef _COAP_TIMER_H
#define _COAP_TIMER_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "node.h"
#define SYS_TIME_MAX (0xFFFFFFFF / 1000)
#define COAP_DEFAULT_RESPONSE_TIMEOUT 2 /* response timeout in seconds */
#define COAP_DEFAULT_MAX_RETRANSMIT 4 /* max number of retransmissions */
#define COAP_TICKS_PER_SECOND 1000 // ms
#define DEFAULT_MAX_TRANSMIT_WAIT 90
void coap_timer_elapsed(coap_tick_t *diff);
void coap_timer_setup(coap_queue_t ** queue, coap_tick_t t);
void coap_timer_stop(void);
void coap_timer_update(coap_queue_t ** queue);
void coap_timer_start(coap_queue_t ** queue);
#ifdef __cplusplus
}
#endif
#endif
#include "c_stdio.h"
#include "c_string.h"
#include "coap.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "os_type.h"
static char rsp[MAX_PAYLOAD_SIZE] = "";
const uint16_t rsplen = MAX_PAYLOAD_SIZE;
void build_well_known_rsp(void);
void endpoint_setup(void)
{
coap_setup();
build_well_known_rsp();
}
static const coap_endpoint_path_t path_well_known_core = {2, {".well-known", "core"}};
static int handle_get_well_known_core(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
return coap_make_response(scratch, outpkt, (const uint8_t *)rsp, c_strlen(rsp), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_APPLICATION_LINKFORMAT);
}
static const coap_endpoint_path_t path_variable = {2, {"v1", "v"}};
static int handle_get_variable(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
const coap_option_t *opt;
uint8_t count;
if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count)))
{
if ((count != ep->path->count ) && (count != ep->path->count + 1)) // +1 for /f/[function], /v/[variable]
{
NODE_DBG("should never happen.\n");
goto end;
}
if (count == ep->path->count + 1)
{
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (opt[count-1].buf.len != c_strlen(h->name))
{
h = h->next;
continue;
}
if (0 == c_memcmp(h->name, opt[count-1].buf.p, opt[count-1].buf.len))
{
NODE_DBG("/v1/v/");
NODE_DBG(h->name);
NODE_DBG(" match.\n");
if(h->L == NULL)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
if(c_strlen(h->name))
{
lua_getglobal(h->L, h->name);
if (!lua_isnumber(h->L, -1)) {
NODE_DBG ("should be a number.\n");
lua_pop(h->L, 1);
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
} else {
const char *res = lua_tostring(h->L,-1);
lua_pop(h->L, 1);
return coap_make_response(scratch, outpkt, (const uint8_t *)res, c_strlen(res), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
} else {
h = h->next;
}
}
}else{
NODE_DBG("/v1/v match.\n");
goto end;
}
}
NODE_DBG("none match.\n");
end:
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
static const coap_endpoint_path_t path_function = {2, {"v1", "f"}};
static int handle_post_function(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
const coap_option_t *opt;
uint8_t count;
if (NULL != (opt = coap_findOptions(inpkt, COAP_OPTION_URI_PATH, &count)))
{
if ((count != ep->path->count ) && (count != ep->path->count + 1)) // +1 for /f/[function], /v/[variable]
{
NODE_DBG("should never happen.\n");
goto end;
}
if (count == ep->path->count + 1)
{
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (opt[count-1].buf.len != c_strlen(h->name))
{
h = h->next;
continue;
}
if (0 == c_memcmp(h->name, opt[count-1].buf.p, opt[count-1].buf.len))
{
NODE_DBG("/v1/f/");
NODE_DBG(h->name);
NODE_DBG(" match.\n");
if(h->L == NULL)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
if(c_strlen(h->name))
{
lua_getglobal(h->L, h->name);
if (lua_type(h->L, -1) != LUA_TFUNCTION) {
NODE_DBG ("should be a function\n");
lua_pop(h->L, 1);
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
} else {
lua_pushlstring(h->L, inpkt->payload.p, inpkt->payload.len); // make sure payload.p is filled with '\0' after payload.len, or use lua_pushlstring
lua_call(h->L, 1, 1);
if (!lua_isnil(h->L, -1)){ /* get return? */
if( lua_isstring(h->L, -1) ) // deal with the return string
{
size_t len = 0;
const char *ret = luaL_checklstring( h->L, -1, &len );
if(len > MAX_PAYLOAD_SIZE){
luaL_error( h->L, "return string:<MAX_PAYLOAD_SIZE" );
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
}
NODE_DBG(ret);
NODE_DBG("\n");
return coap_make_response(scratch, outpkt, ret, len, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
} else {
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
}
} else {
h = h->next;
}
}
}else{
NODE_DBG("/v1/f match.\n");
goto end;
}
}
NODE_DBG("none match.\n");
end:
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_NOT_FOUND, COAP_CONTENTTYPE_NONE);
}
extern lua_Load gLoad;
extern os_timer_t lua_timer;
extern void dojob(lua_Load *load);
static const coap_endpoint_path_t path_command = {2, {"v1", "c"}};
static int handle_post_command(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
if (inpkt->payload.len == 0)
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_BAD_REQUEST, COAP_CONTENTTYPE_TEXT_PLAIN);
if (inpkt->payload.len > 0)
{
lua_Load *load = &gLoad;
if(load->line_position == 0){
coap_buffer_to_string(load->line, load->len,&inpkt->payload);
load->line_position = c_strlen(load->line)+1;
// load->line[load->line_position-1] = '\n';
// load->line[load->line_position] = 0;
// load->line_position++;
load->done = 1;
NODE_DBG("Get command:\n");
NODE_DBG(load->line); // buggy here
NODE_DBG("\nResult(if any):\n");
os_timer_disarm(&lua_timer);
os_timer_setfn(&lua_timer, (os_timer_func_t *)dojob, load);
os_timer_arm(&lua_timer, READLINE_INTERVAL, 0); // no repeat
}
return coap_make_response(scratch, outpkt, NULL, 0, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
}
static uint32_t id = 0;
static const coap_endpoint_path_t path_id = {2, {"v1", "id"}};
static int handle_get_id(const coap_endpoint_t *ep, coap_rw_buffer_t *scratch, const coap_packet_t *inpkt, coap_packet_t *outpkt, uint8_t id_hi, uint8_t id_lo)
{
id = system_get_chip_id();
return coap_make_response(scratch, outpkt, (const uint8_t *)(&id), sizeof(uint32_t), id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
coap_luser_entry var_head = {NULL,NULL,NULL};
coap_luser_entry *variable_entry = &var_head;
coap_luser_entry func_head = {NULL,NULL,NULL};
coap_luser_entry *function_entry = &func_head;
const coap_endpoint_t endpoints[] =
{
{COAP_METHOD_GET, handle_get_well_known_core, &path_well_known_core, "ct=40", NULL},
{COAP_METHOD_GET, handle_get_variable, &path_variable, "ct=0", &var_head},
{COAP_METHOD_POST, handle_post_function, &path_function, NULL, &func_head},
{COAP_METHOD_POST, handle_post_command, &path_command, NULL, NULL},
{COAP_METHOD_GET, handle_get_id, &path_id, "ct=0", NULL},
{(coap_method_t)0, NULL, NULL, NULL, NULL}
};
void build_well_known_rsp(void)
{
const coap_endpoint_t *ep = endpoints;
int i;
uint16_t len = rsplen;
c_memset(rsp, 0, sizeof(rsp));
len--; // Null-terminated string
while(NULL != ep->handler)
{
if (NULL == ep->core_attr) {
ep++;
continue;
}
if (NULL == ep->user_entry){
if (0 < c_strlen(rsp)) {
c_strncat(rsp, ",", len);
len--;
}
c_strncat(rsp, "<", len);
len--;
for (i = 0; i < ep->path->count; i++) {
c_strncat(rsp, "/", len);
len--;
c_strncat(rsp, ep->path->elems[i], len);
len -= c_strlen(ep->path->elems[i]);
}
c_strncat(rsp, ">;", len);
len -= 2;
c_strncat(rsp, ep->core_attr, len);
len -= c_strlen(ep->core_attr);
} else {
coap_luser_entry *h = ep->user_entry->next; // ->next: skip the first entry(head)
while(NULL != h){
if (0 < c_strlen(rsp)) {
c_strncat(rsp, ",", len);
len--;
}
c_strncat(rsp, "<", len);
len--;
for (i = 0; i < ep->path->count; i++) {
c_strncat(rsp, "/", len);
len--;
c_strncat(rsp, ep->path->elems[i], len);
len -= c_strlen(ep->path->elems[i]);
}
c_strncat(rsp, "/", len);
len--;
c_strncat(rsp, h->name, len);
len -= c_strlen(h->name);
c_strncat(rsp, ">;", len);
len -= 2;
c_strncat(rsp, ep->core_attr, len);
len -= c_strlen(ep->core_attr);
h = h->next;
}
}
ep++;
}
}
#include "hash.h"
#include "c_string.h"
/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY
* accordingly (see int coap_hash_path());
*/
void coap_hash(const unsigned char *s, unsigned int len, coap_key_t h) {
size_t j;
while (len--) {
j = sizeof(coap_key_t)-1;
while (j) {
h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j];
--j;
}
h[0] = (h[0] << 7) + h[0] + *s++;
}
}
void coap_transaction_id(const uint32_t ip, const uint32_t port, const coap_packet_t *pkt, coap_tid_t *id) {
coap_key_t h;
c_memset(h, 0, sizeof(coap_key_t));
/* Compare the transport address. */
coap_hash((const unsigned char *)&(port), sizeof(port), h);
coap_hash((const unsigned char *)&(ip), sizeof(ip), h);
coap_hash((const unsigned char *)(pkt->hdr.id), sizeof(pkt->hdr.id), h);
*id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
}
#ifndef _HASH_H
#define _HASH_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "coap.h"
typedef unsigned char coap_key_t[4];
/* CoAP transaction id */
/*typedef unsigned short coap_tid_t; */
typedef int coap_tid_t;
#define COAP_INVALID_TID -1
void coap_transaction_id(const uint32_t ip, const uint32_t port, const coap_packet_t *pkt, coap_tid_t *id);
#ifdef __cplusplus
}
#endif
#endif
#include "c_string.h"
#include "c_stdlib.h"
#include "node.h"
static inline coap_queue_t *
coap_malloc_node(void) {
return (coap_queue_t *)c_zalloc(sizeof(coap_queue_t));
}
void coap_free_node(coap_queue_t *node) {
c_free(node);
}
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
coap_queue_t *p, *q;
if ( !queue || !node )
return 0;
/* set queue head if empty */
if ( !*queue ) {
*queue = node;
return 1;
}
/* replace queue head if PDU's time is less than head's time */
q = *queue;
if (node->t < q->t) {
node->next = q;
*queue = node;
q->t -= node->t; /* make q->t relative to node->t */
return 1;
}
/* search for right place to insert */
do {
node->t -= q->t; /* make node-> relative to q->t */
p = q;
q = q->next;
} while (q && q->t <= node->t);
/* insert new item */
if (q) {
q->t -= node->t; /* make q->t relative to node->t */
}
node->next = q;
p->next = node;
return 1;
}
int coap_delete_node(coap_queue_t *node) {
if ( !node )
return 0;
coap_delete_pdu(node->pdu);
coap_free_node(node);
return 1;
}
void coap_delete_all(coap_queue_t *queue) {
if ( !queue )
return;
coap_delete_all( queue->next );
coap_delete_node( queue );
}
coap_queue_t * coap_new_node(void) {
coap_queue_t *node;
node = coap_malloc_node();
if ( ! node ) {
return NULL;
}
c_memset(node, 0, sizeof(*node));
return node;
}
coap_queue_t * coap_peek_next( coap_queue_t *queue ) {
if ( !queue )
return NULL;
return queue;
}
coap_queue_t * coap_pop_next( coap_queue_t **queue ) { // this function is called inside timeout callback only.
coap_queue_t *next;
if ( !(*queue) )
return NULL;
next = *queue;
*queue = (*queue)->next;
// if (queue) {
// queue->t += next->t;
// }
next->next = NULL;
return next;
}
int coap_remove_node( coap_queue_t **queue, const coap_tid_t id){
coap_queue_t *p, *q, *node;
if ( !queue )
return 0;
if ( !*queue ) // if empty
return 0;
q = *queue;
if (q->id == id) {
node = q;
*queue = q->next;
node->next = NULL;
if(*queue){
(*queue)->t += node->t;
}
coap_delete_node(node);
return 1;
}
/* search for right node to remove */
while (q && q->id != id) {
p = q;
q = q->next;
}
/* find the node */
if (q) {
node = q; /* save the node */
p->next = q->next; /* remove the node */
q = q->next;
node->next = NULL;
if (q) // add node->t to the node after.
{
q->t += node->t;
}
coap_delete_node(node);
return 1;
}
return 0;
}
#ifndef _NODE_H
#define _NODE_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "hash.h"
#include "pdu.h"
struct coap_queue_t;
typedef uint32_t coap_tick_t;
/*
1. queue(first)->t store when to send PDU for the next time, it's a base(absolute) time
2. queue->next->t store the delta between time and base-time. queue->next->t = timeout + now - basetime
3. node->next->t store the delta between time and previous->t. node->next->t = timeout + now - node->t - basetime
4. time to fire: 10, 15, 18, 25
node->t: 10, 5, 3, 7
*/
typedef struct coap_queue_t {
struct coap_queue_t *next;
coap_tick_t t; /**< when to send PDU for the next time */
unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */
unsigned int timeout; /**< the randomized timeout value */
coap_tid_t id; /**< unique transaction id */
// coap_packet_t *pkt;
coap_pdu_t *pdu; /**< the CoAP PDU to send */
struct espconn *pconn;
} coap_queue_t;
void coap_free_node(coap_queue_t *node);
/** Adds node to given queue, ordered by node->t. */
int coap_insert_node(coap_queue_t **queue, coap_queue_t *node);
/** Destroys specified node. */
int coap_delete_node(coap_queue_t *node);
/** Removes all items from given queue and frees the allocated storage. */
void coap_delete_all(coap_queue_t *queue);
/** Creates a new node suitable for adding to the CoAP sendqueue. */
coap_queue_t *coap_new_node(void);
coap_queue_t *coap_pop_next( coap_queue_t **queue );
int coap_remove_node( coap_queue_t **queue, const coap_tid_t id);
#ifdef __cplusplus
}
#endif
#endif
#include "c_stdlib.h"
#include "pdu.h"
coap_pdu_t * coap_new_pdu(void) {
coap_pdu_t *pdu = NULL;
pdu = (coap_pdu_t *)c_zalloc(sizeof(coap_pdu_t));
if(!pdu){
NODE_DBG("coap_new_pdu malloc error.\n");
return NULL;
}
pdu->scratch.p = (uint8_t *)c_zalloc(MAX_REQ_SCRATCH_SIZE);
if(!pdu->scratch.p){
NODE_DBG("coap_new_pdu malloc error.\n");
c_free(pdu);
return NULL;
}
pdu->scratch.len = MAX_REQ_SCRATCH_SIZE;
pdu->pkt = (coap_packet_t *)c_zalloc(sizeof(coap_packet_t));
if(!pdu->pkt){
NODE_DBG("coap_new_pdu malloc error.\n");
c_free(pdu->scratch.p);
c_free(pdu);
return NULL;
}
pdu->msg.p = (uint8_t *)c_zalloc(MAX_REQUEST_SIZE+1); // +1 for string '\0'
if(!pdu->msg.p){
NODE_DBG("coap_new_pdu malloc error.\n");
c_free(pdu->pkt);
c_free(pdu->scratch.p);
c_free(pdu);
return NULL;
}
pdu->msg.len = MAX_REQUEST_SIZE;
return pdu;
}
void coap_delete_pdu(coap_pdu_t *pdu){
if(!pdu)
return;
if(pdu->scratch.p){
c_free(pdu->scratch.p);
pdu->scratch.p = NULL;
pdu->scratch.len = 0;
}
if(pdu->pkt){
c_free(pdu->pkt);
pdu->pkt = NULL;
}
if(pdu->msg.p){
c_free(pdu->msg.p);
pdu->msg.p = NULL;
pdu->msg.len = 0;
}
c_free(pdu);
pdu = NULL;
}
#ifndef _PDU_H
#define _PDU_H 1
#ifdef __cplusplus
extern "C" {
#endif
#include "coap.h"
/** Header structure for CoAP PDUs */
typedef struct {
coap_rw_buffer_t scratch;
coap_packet_t *pkt;
coap_rw_buffer_t msg; /**< the CoAP msg to send */
} coap_pdu_t;
coap_pdu_t *coap_new_pdu(void);
void coap_delete_pdu(coap_pdu_t *pdu);
#ifdef __cplusplus
}
#endif
#endif
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment