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

add coap module, see fragment.lua for usage

parent a1dc023c
/* str.c -- strings to be used in the CoAP library
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "c_stdlib.h"
#include "c_types.h"
#include "str.h"
str * coap_new_string(size_t size) {
str *s = (str *)c_malloc(sizeof(str) + size + 1);
if ( !s ) {
return NULL;
}
c_memset(s, 0, sizeof(str));
s->s = ((unsigned char *)s) + sizeof(str);
return s;
}
void coap_delete_string(str *s) {
c_free(s);
}
/* str.h -- strings to be used in the CoAP library
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_STR_H_
#define _COAP_STR_H_
#include "c_string.h"
typedef struct {
size_t length; /* length of string */
unsigned char *s; /* string data */
} str;
#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); }
/**
* Returns a new string object with at least size bytes storage
* allocated. The string must be released using coap_delete_string();
*/
str *coap_new_string(size_t size);
/** Deletes the given string and releases any memory allocated. */
void coap_delete_string(str *);
#endif /* _COAP_STR_H_ */
/* uri.c -- helper functions for URI treatment
*/
#include "c_stdio.h"
#include "c_stdlib.h"
#include "c_string.h"
#include "c_ctype.h"
#include "coap.h"
#include "uri.h"
#ifndef assert
// #warning "assertions are disabled"
# define assert(x) do { \
if(!x) NODE_ERR("uri.c assert!\n"); \
} while (0)
#endif
/**
* A length-safe version of strchr(). This function returns a pointer
* to the first occurrence of @p c in @p s, or @c NULL if not found.
*
* @param s The string to search for @p c.
* @param len The length of @p s.
* @param c The character to search.
*
* @return A pointer to the first occurence of @p c, or @c NULL
* if not found.
*/
static inline unsigned char *
strnchr(unsigned char *s, size_t len, unsigned char c) {
while (len && *s++ != c)
--len;
return len ? s : NULL;
}
int coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) {
unsigned char *p, *q;
int secure = 0, res = 0;
if (!str_var || !uri)
return -1;
c_memset(uri, 0, sizeof(coap_uri_t));
uri->port = COAP_DEFAULT_PORT;
/* search for scheme */
p = str_var;
if (*p == '/') {
q = p;
goto path;
}
q = (unsigned char *)COAP_DEFAULT_SCHEME;
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
/* If q does not point to the string end marker '\0', the schema
* identifier is wrong. */
if (*q) {
res = -1;
goto error;
}
/* There might be an additional 's', indicating the secure version: */
if (len && (secure = tolower(*p) == 's')) {
++p; --len;
}
q = (unsigned char *)"://";
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
if (*q) {
res = -2;
goto error;
}
/* p points to beginning of Uri-Host */
q = p;
if (len && *p == '[') { /* IPv6 address reference */
++p;
while (len && *q != ']') {
++q; --len;
}
if (!len || *q != ']' || p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
++q; --len;
} else { /* IPv4 address or FQDN */
while (len && *q != ':' && *q != '/' && *q != '?') {
*q = tolower(*q);
++q;
--len;
}
if (p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
}
/* check for Uri-Port */
if (len && *q == ':') {
p = ++q;
--len;
while (len && isdigit(*q)) {
++q;
--len;
}
if (p < q) { /* explicit port number given */
int uri_port = 0;
while (p < q)
uri_port = uri_port * 10 + (*p++ - '0');
uri->port = uri_port;
}
}
path: /* at this point, p must point to an absolute path */
if (!len)
goto end;
if (*q == '/') {
p = ++q;
--len;
while (len && *q != '?') {
++q;
--len;
}
if (p < q) {
COAP_SET_STR(&uri->path, q - p, p);
p = q;
}
}
/* Uri_Query */
if (len && *p == '?') {
++p;
--len;
COAP_SET_STR(&uri->query, len, p);
len = 0;
}
end:
return len ? -1 : 0;
error:
return res;
}
/**
* Calculates decimal value from hexadecimal ASCII character given in
* @p c. The caller must ensure that @p c actually represents a valid
* heaxdecimal character, e.g. with isxdigit(3).
*
* @hideinitializer
*/
#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
/**
* Decodes percent-encoded characters while copying the string @p seg
* of size @p length to @p buf. The caller of this function must
* ensure that the percent-encodings are correct (i.e. the character
* '%' is always followed by two hex digits. and that @p buf provides
* sufficient space to hold the result. This function is supposed to
* be called by make_decoded_option() only.
*
* @param seg The segment to decode and copy.
* @param length Length of @p seg.
* @param buf The result buffer.
*/
void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) {
while (length--) {
if (*seg == '%') {
*buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
seg += 2; length -= 2;
} else {
*buf = *seg;
}
++buf; ++seg;
}
}
/**
* Runs through the given path (or query) segment and checks if
* percent-encodings are correct. This function returns @c -1 on error
* or the length of @p s when decoded.
*/
int check_segment(const unsigned char *s, size_t length) {
size_t n = 0;
while (length) {
if (*s == '%') {
if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2])))
return -1;
s += 2;
length -= 2;
}
++s; ++n; --length;
}
return n;
}
/**
* Writes a coap option from given string @p s to @p buf. @p s should
* point to a (percent-encoded) path or query segment of a coap_uri_t
* object. The created option will have type @c 0, and the length
* parameter will be set according to the size of the decoded string.
* On success, this function returns the option's size, or a value
* less than zero on error. This function must be called from
* coap_split_path_impl() only.
*
* @param s The string to decode.
* @param length The size of the percent-encoded string @p s.
* @param buf The buffer to store the new coap option.
* @param buflen The maximum size of @p buf.
*
* @return The option's size, or @c -1 on error.
*
* @bug This function does not split segments that are bigger than 270
* bytes.
*/
int make_decoded_option(const unsigned char *s, size_t length,
unsigned char *buf, size_t buflen) {
int res;
size_t written;
if (!buflen) {
NODE_DBG("make_decoded_option(): buflen is 0!\n");
return -1;
}
res = check_segment(s, length);
if (res < 0)
return -1;
/* write option header using delta 0 and length res */
// written = coap_opt_setheader(buf, buflen, 0, res);
written = coap_buildOptionHeader(0, res, buf, buflen);
assert(written <= buflen);
if (!written) /* encoding error */
return -1;
buf += written; /* advance past option type/length */
buflen -= written;
if (buflen < (size_t)res) {
NODE_DBG("buffer too small for option\n");
return -1;
}
decode_segment(s, length, buf);
return written + res;
}
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
typedef void (*segment_handler_t)(unsigned char *, size_t, void *);
/**
* Splits the given string into segments. You should call one of the
* macros coap_split_path() or coap_split_query() instead.
*
* @param parse_iter The iterator used for tokenizing.
* @param h A handler that is called with every token.
* @param data Opaque data that is passed to @p h when called.
*
* @return The number of characters that have been parsed from @p s.
*/
size_t coap_split_path_impl(coap_parse_iterator_t *parse_iter,
segment_handler_t h, void *data) {
unsigned char *seg;
size_t length;
assert(parse_iter);
assert(h);
length = parse_iter->n;
while ( (seg = coap_parse_next(parse_iter)) ) {
/* any valid path segment is handled here: */
h(seg, parse_iter->segment_length, data);
}
return length - (parse_iter->n - parse_iter->segment_length);
}
struct pkt_scr {
coap_packet_t *pkt;
coap_rw_buffer_t *scratch;
int n;
};
void write_option(unsigned char *s, size_t len, void *data) {
struct pkt_scr *state = (struct pkt_scr *)data;
int res;
assert(state);
/* skip empty segments and those that consist of only one or two dots */
if (memcmp(s, "..", min(len,2)) == 0)
return;
res = check_segment(s, len);
if (res < 0){
NODE_DBG("not a valid segment\n");
return;
}
if (state->scratch->len < (size_t)res) {
NODE_DBG("buffer too small for option\n");
return;
}
decode_segment(s, len, state->scratch->p);
if (res > 0) {
state->pkt->opts[state->pkt->numopts].buf.p = state->scratch->p;
state->pkt->opts[state->pkt->numopts].buf.len = res;
state->scratch->p += res;
state->scratch->len -= res;
state->pkt->numopts++;
state->n++;
}
}
int coap_split_path(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const unsigned char *s, size_t length) {
struct pkt_scr tmp = { pkt, scratch, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'/', (unsigned char *)"?#", 2, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
int i;
for(i=0;i<tmp.n;i++){
pkt->opts[pkt->numopts - i - 1].num = COAP_OPTION_URI_PATH;
}
return tmp.n;
}
int coap_split_query(coap_rw_buffer_t *scratch, coap_packet_t *pkt, const unsigned char *s, size_t length) {
struct pkt_scr tmp = { pkt, scratch, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'&', (unsigned char *)"#", 1, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
int i;
for(i=0;i<tmp.n;i++){
pkt->opts[pkt->numopts - i - 1].num = COAP_OPTION_URI_QUERY;
}
return tmp.n;
}
#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t))
coap_uri_t * coap_new_uri(const unsigned char *uri, unsigned int length) {
unsigned char *result;
result = (unsigned char *)c_malloc(length + 1 + sizeof(coap_uri_t));
if (!result)
return NULL;
c_memcpy(URI_DATA(result), uri, length);
URI_DATA(result)[length] = '\0'; /* make it zero-terminated */
if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *)result) < 0) {
c_free(result);
return NULL;
}
return (coap_uri_t *)result;
}
/* iterator functions */
coap_parse_iterator_t * coap_parse_iterator_init(unsigned char *s, size_t n,
unsigned char separator,
unsigned char *delim, size_t dlen,
coap_parse_iterator_t *pi) {
assert(pi);
assert(separator);
pi->separator = separator;
pi->delim = delim;
pi->dlen = dlen;
pi->pos = s;
pi->n = n;
pi->segment_length = 0;
return pi;
}
unsigned char * coap_parse_next(coap_parse_iterator_t *pi) {
unsigned char *p;
if (!pi)
return NULL;
/* proceed to the next segment */
pi->n -= pi->segment_length;
pi->pos += pi->segment_length;
pi->segment_length = 0;
/* last segment? */
if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) {
pi->pos = NULL;
return NULL;
}
/* skip following separator (the first segment might not have one) */
if (*pi->pos == pi->separator) {
++pi->pos;
--pi->n;
}
p = pi->pos;
while (pi->segment_length < pi->n && *p != pi->separator &&
!strnchr(pi->delim, pi->dlen, *p)) {
++p;
++pi->segment_length;
}
if (!pi->n) {
pi->pos = NULL;
pi->segment_length = 0;
}
return pi->pos;
}
/* uri.h -- helper functions for URI treatment
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_URI_H_
#define _COAP_URI_H_
#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */
#define COAP_DEFAULT_PORT 5683
#include "str.h"
/** Representation of parsed URI. Components may be filled from a
* string with coap_split_uri() and can be used as input for
* option-creation functions. */
typedef struct {
str host; /**< host part of the URI */
unsigned short port; /**< The port in host byte order */
str path; /**< Beginning of the first path segment.
Use coap_split_path() to create Uri-Path options */
str query; /**< The query part if present */
} coap_uri_t;
/**
* Creates a new coap_uri_t object from the specified URI. Returns the new
* object or NULL on error. The memory allocated by the new coap_uri_t
* must be released using coap_free().
* @param uri The URI path to copy.
* @para length The length of uri.
*
* @return New URI object or NULL on error.
*/
coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length);
/**
* @defgroup uri_parse URI Parsing Functions
*
* CoAP PDUs contain normalized URIs with their path and query split into
* multiple segments. The functions in this module help splitting strings.
* @{
*/
/**
* Iterator to for tokenizing a URI path or query. This structure must
* be initialized with coap_parse_iterator_init(). Call
* coap_parse_next() to walk through the tokens.
*
* @code
* unsigned char *token;
* coap_parse_iterator_t pi;
* coap_parse_iterator_init(uri.path.s, uri.path.length, '/', "?#", 2, &pi);
*
* while ((token = coap_parse_next(&pi))) {
* ... do something with token ...
* }
* @endcode
*/
typedef struct {
size_t n; /**< number of remaining characters in buffer */
unsigned char separator; /**< segment separators */
unsigned char *delim; /**< delimiters where to split the string */
size_t dlen; /**< length of separator */
unsigned char *pos; /**< current position in buffer */
size_t segment_length; /**< length of current segment */
} coap_parse_iterator_t;
/**
* Initializes the given iterator @p pi.
*
* @param s The string to tokenize.
* @param n The length of @p s.
* @param separator The separator character that delimits tokens.
* @param delim A set of characters that delimit @s.
* @param dlen The length of @p delim.
* @param pi The iterator object to initialize.
*
* @return The initialized iterator object @p pi.
*/
coap_parse_iterator_t *
coap_parse_iterator_init(unsigned char *s, size_t n,
unsigned char separator,
unsigned char *delim, size_t dlen,
coap_parse_iterator_t *pi);
/**
* Updates the iterator @p pi to point to the next token. This
* function returns a pointer to that token or @c NULL if no more
* tokens exist. The contents of @p pi will be updated. In particular,
* @c pi->segment_length specifies the length of the current token, @c
* pi->pos points to its beginning.
*
* @param pi The iterator to update.
*
* @return The next token or @c NULL if no more tokens exist.
*/
unsigned char *coap_parse_next(coap_parse_iterator_t *pi);
/**
* Parses a given string into URI components. The identified syntactic
* components are stored in the result parameter @p uri. Optional URI
* components that are not specified will be set to { 0, 0 }, except
* for the port which is set to @c COAP_DEFAULT_PORT. This function
* returns @p 0 if parsing succeeded, a value less than zero
* otherwise.
*
* @param str_var The string to split up.
* @param len The actual length of @p str_var
* @param uri The coap_uri_t object to store the result.
* @return @c 0 on success, or < 0 on error.
*
* @note The host name part will be converted to lower case by this
* function.
*/
int
coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri);
/**
* Splits the given URI path into segments. Each segment is preceded
* by an option pseudo-header with delta-value 0 and the actual length
* of the respective segment after percent-decoding.
*
* @param s The path string to split.
* @param length The actual length of @p s.
* @param buf Result buffer for parsed segments.
* @param buflen Maximum length of @p buf. Will be set to the actual number
* of bytes written into buf on success.
*
* @return The number of segments created or @c -1 on error.
*/
#if 0
int coap_split_path(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen);
#else
int
coap_split_path(coap_rw_buffer_t *scratch, coap_packet_t *pkt,
const unsigned char *s, size_t length);
#endif
/**
* Splits the given URI query into segments. Each segment is preceded
* by an option pseudo-header with delta-value 0 and the actual length
* of the respective query term.
*
* @param s The query string to split.
* @param length The actual length of @p s.
* @param buf Result buffer for parsed segments.
* @param buflen Maximum length of @p buf. Will be set to the actual number
* of bytes written into buf on success.
*
* @return The number of segments created or @c -1 on error.
*
* @bug This function does not reserve additional space for delta > 12.
*/
#if 0
int coap_split_query(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen);
#else
int coap_split_query(coap_rw_buffer_t *scratch, coap_packet_t *pkt,
const unsigned char *s, size_t length);
#endif
/** @} */
#endif /* _COAP_URI_H_ */
......@@ -17,11 +17,11 @@
// #define DEVELOP_VERSION
#define FULL_VERSION_FOR_USER
#ifdef DEVELOP_VERSION
#define USE_OPTIMIZE_PRINTF
#ifdef DEVELOP_VERSION
#define NODE_DEBUG
#define COAP_DEBUG
#endif /* DEVELOP_VERSION */
#define NODE_ERROR
......@@ -65,6 +65,7 @@
#define LUA_USE_MODULES_OW
#define LUA_USE_MODULES_BIT
#define LUA_USE_MODULES_MQTT
#define LUA_USE_MODULES_COAP
#endif /* LUA_USE_MODULES */
// #define LUA_NUMBER_INTEGRAL
......
......@@ -39,6 +39,7 @@ endif
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
INCLUDES += -I ../libc
INCLUDES += -I ../coap
INCLUDES += -I ../mqtt
INCLUDES += -I ../lua
INCLUDES += -I ../platform
......
......@@ -61,6 +61,9 @@ LUALIB_API int ( luaopen_i2c )( lua_State *L );
#define AUXLIB_WIFI "wifi"
LUALIB_API int ( luaopen_wifi )( lua_State *L );
#define AUXLIB_COAP "coap"
LUALIB_API int ( luaopen_coap )( lua_State *L );
#define AUXLIB_MQTT "mqtt"
LUALIB_API int ( luaopen_mqtt )( lua_State *L );
......
// Module for coapwork
//#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "platform.h"
#include "auxmods.h"
#include "lrotable.h"
#include "c_string.h"
#include "c_stdlib.h"
#include "c_types.h"
#include "mem.h"
#include "espconn.h"
#include "driver/uart.h"
#include "coap.h"
#include "uri.h"
#include "node.h"
#include "coap_timer.h"
#include "coap_io.h"
#include "coap_server.h"
coap_queue_t *gQueue = NULL;
typedef struct lcoap_userdata
{
lua_State *L;
struct espconn *pesp_conn;
int self_ref;
}lcoap_userdata;
static void coap_received(void *arg, char *pdata, unsigned short len)
{
NODE_DBG("coap_received is called.\n");
struct espconn *pesp_conn = arg;
lcoap_userdata *cud = (lcoap_userdata *)pesp_conn->reverse;
static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
c_memset(buf, 0, sizeof(buf)); // wipe prev data
if (len > MAX_MESSAGE_SIZE) {
NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
return;
} else {
c_memcpy(buf, pdata, len);
}
size_t rsplen = coap_server_respond(buf, len, MAX_MESSAGE_SIZE+1);
espconn_sent(pesp_conn, (unsigned char *)buf, rsplen);
c_memset(buf, 0, sizeof(buf));
}
static void ICACHE_FLASH_ATTR
coap_sent(void *arg)
{
NODE_DBG("coap_sent is called.\n");
}
// Lua: s = coap.create(function(conn))
static int ICACHE_FLASH_ATTR
coap_create( lua_State* L, const char* mt )
{
struct espconn *pesp_conn = NULL;
lcoap_userdata *cud;
unsigned type;
int stack = 1;
// create a object
cud = (lcoap_userdata *)lua_newuserdata(L, sizeof(lcoap_userdata));
// pre-initialize it, in case of errors
cud->self_ref = LUA_NOREF;
cud->pesp_conn = NULL;
// set its metatable
luaL_getmetatable(L, mt);
lua_setmetatable(L, -2);
// create the espconn struct
pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
if(!pesp_conn)
return luaL_error(L, "not enough memory");
cud->pesp_conn = pesp_conn;
pesp_conn->type = ESPCONN_UDP;
pesp_conn->proto.tcp = NULL;
pesp_conn->proto.udp = NULL;
pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp));
if(!pesp_conn->proto.udp){
c_free(pesp_conn);
cud->pesp_conn = pesp_conn = NULL;
return luaL_error(L, "not enough memory");
}
pesp_conn->state = ESPCONN_NONE;
NODE_DBG("UDP server/client is set.\n");
cud->L = L;
pesp_conn->reverse = cud;
NODE_DBG("coap_create is called.\n");
return 1;
}
// Lua: server:delete()
static int ICACHE_FLASH_ATTR
coap_delete( lua_State* L, const char* mt )
{
struct espconn *pesp_conn = NULL;
lcoap_userdata *cud;
cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
luaL_argcheck(L, cud, 1, "Server/Client expected");
if(cud==NULL){
NODE_DBG("userdata is nil.\n");
return 0;
}
// free (unref) callback ref
if(LUA_NOREF!=cud->self_ref){
luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
cud->self_ref = LUA_NOREF;
}
cud->L = NULL;
if(cud->pesp_conn)
{
if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
espconn_delete(cud->pesp_conn);
c_free(cud->pesp_conn->proto.udp);
cud->pesp_conn->proto.udp = NULL;
c_free(cud->pesp_conn);
cud->pesp_conn = NULL;
}
NODE_DBG("coap_delete is called.\n");
return 0;
}
// Lua: server:listen( port, ip )
static int ICACHE_FLASH_ATTR
coap_start( lua_State* L, const char* mt )
{
struct espconn *pesp_conn = NULL;
lcoap_userdata *cud;
unsigned port;
size_t il;
ip_addr_t ipaddr;
cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
luaL_argcheck(L, cud, 1, "Server/Client expected");
if(cud==NULL){
NODE_DBG("userdata is nil.\n");
return 0;
}
pesp_conn = cud->pesp_conn;
port = luaL_checkinteger( L, 2 );
pesp_conn->proto.udp->local_port = port;
NODE_DBG("UDP port is set: %d.\n", port);
if( lua_isstring(L,3) ) // deal with the ip string
{
const char *ip = luaL_checklstring( L, 3, &il );
if (ip == NULL)
{
ip = "0.0.0.0";
}
ipaddr.addr = ipaddr_addr(ip);
c_memcpy(pesp_conn->proto.udp->local_ip, &ipaddr.addr, 4);
NODE_DBG("UDP ip is set: ");
NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
NODE_DBG("\n");
}
if(LUA_NOREF==cud->self_ref){
lua_pushvalue(L, 1); // copy to the top of stack
cud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
}
espconn_regist_recvcb(pesp_conn, coap_received);
espconn_regist_sentcb(pesp_conn, coap_sent);
espconn_create(pesp_conn);
NODE_DBG("Coap Server started on port: %d\n", port);
NODE_DBG("coap_start is called.\n");
return 0;
}
// Lua: server:close()
static int ICACHE_FLASH_ATTR
coap_close( lua_State* L, const char* mt )
{
struct espconn *pesp_conn = NULL;
lcoap_userdata *cud;
cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
luaL_argcheck(L, cud, 1, "Server/Client expected");
if(cud==NULL){
NODE_DBG("userdata is nil.\n");
return 0;
}
if(cud->pesp_conn)
{
if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
espconn_delete(cud->pesp_conn);
}
if(LUA_NOREF!=cud->self_ref){
luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
cud->self_ref = LUA_NOREF;
}
NODE_DBG("coap_close is called.\n");
return 0;
}
// Lua: server/client:on( "method", function(s) )
static int ICACHE_FLASH_ATTR
coap_on( lua_State* L, const char* mt )
{
NODE_DBG("coap_on is called.\n");
return 0;
}
static void ICACHE_FLASH_ATTR
coap_response_handler(void *arg, char *pdata, unsigned short len)
{
NODE_DBG("coap_response_handler is called.\n");
struct espconn *pesp_conn = arg;
coap_packet_t pkt;
static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
c_memset(buf, 0, sizeof(buf)); // wipe prev data
static int n = 0;
int rc;
if ((len == 1460) && (1460 <= MAX_MESSAGE_SIZE)){
c_memcpy(buf, pdata, len); // max length is 1460, another part of data is coming in next callback
n = len;
return;
} else {
if( len > MAX_MESSAGE_SIZE )
{
NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
c_memset(buf, 0, sizeof(buf)); // wipe prev data
n = 0;
return;
}
c_memcpy(buf + n, pdata, len);
len += n; // more than 1460
}
if (0 != (rc = coap_parse(&pkt, buf, 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;
}
uint32_t ip = 0, port = 0;
coap_tid_t id = COAP_INVALID_TID;
c_memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
port = pesp_conn->proto.udp->remote_port;
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.
if(pesp_conn->proto.udp->remote_port || pesp_conn->proto.udp->local_port)
espconn_delete(pesp_conn);
}
c_memset(buf, 0, sizeof(buf));
n = 0;
}
// Lua: client:request( [CON], uri, [payload] )
static int ICACHE_FLASH_ATTR
coap_request( lua_State* L, coap_method_t m )
{
struct espconn *pesp_conn = NULL;
lcoap_userdata *cud;
int stack = 1;
cud = (lcoap_userdata *)luaL_checkudata(L, stack, "coap_client");
luaL_argcheck(L, cud, stack, "Server/Client expected");
if(cud==NULL){
NODE_DBG("userdata is nil.\n");
return 0;
}
stack++;
pesp_conn = cud->pesp_conn;
ip_addr_t ipaddr;
uint8_t host[32];
unsigned t;
if ( lua_isnumber(L, stack) )
{
t = lua_tointeger(L, stack);
stack++;
if ( t != COAP_TYPE_CON && t != COAP_TYPE_NONCON )
return luaL_error( L, "wrong arg type" );
} else {
t = COAP_TYPE_CON; // default to CON
}
size_t l;
const char *url = luaL_checklstring( L, stack, &l );
stack++;
if (url == NULL)
return luaL_error( L, "wrong arg type" );
coap_uri_t *uri = coap_new_uri(url, l); // should call free(uri) somewhere
if (uri == NULL)
return luaL_error( L, "uri wrong format." );
pesp_conn->proto.udp->remote_port = uri->port;
NODE_DBG("UDP port is set: %d.\n", uri->port);
pesp_conn->proto.udp->local_port = espconn_port();
if(uri->host.length){
c_memcpy(host, uri->host.s, uri->host.length);
host[uri->host.length] = '\0';
ipaddr.addr = ipaddr_addr(host);
NODE_DBG("Host len(%d):", uri->host.length);
NODE_DBG(host);
NODE_DBG("\n");
c_memcpy(pesp_conn->proto.udp->remote_ip, &ipaddr.addr, 4);
NODE_DBG("UDP ip is set: ");
NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
NODE_DBG("\n");
}
coap_pdu_t *pdu = coap_new_pdu(); // should call coap_delete_pdu() somewhere
if(!pdu){
if(uri)
c_free(uri);
return;
}
const char *payload = NULL;
l = 0;
if( lua_isstring(L, stack) ){
payload = luaL_checklstring( L, stack, &l );
if (payload == NULL)
l = 0;
}
coap_make_request(&(pdu->scratch), pdu->pkt, t, m, uri, payload, l);
#ifdef COAP_DEBUG
coap_dumpPacket(pdu->pkt);
#endif
int rc;
if (0 != (rc = coap_build(pdu->msg.p, &(pdu->msg.len), pdu->pkt))){
NODE_DBG("coap_build failed rc=%d\n", rc);
}
else
{
#ifdef COAP_DEBUG
NODE_DBG("Sending: ");
coap_dump(pdu->msg.p, pdu->msg.len, true);
NODE_DBG("\n");
#endif
espconn_regist_recvcb(pesp_conn, coap_response_handler);
sint8_t con = espconn_create(pesp_conn);
if( ESPCONN_OK != con){
NODE_DBG("Connect to host. code:%d\n", con);
// coap_delete_pdu(pdu);
}
// else
{
coap_tid_t tid = COAP_INVALID_TID;
if (pdu->pkt->hdr.t == COAP_TYPE_CON){
tid = coap_send_confirmed(pesp_conn, pdu);
}
else {
tid = coap_send(pesp_conn, pdu);
}
if (pdu->pkt->hdr.t != COAP_TYPE_CON || tid == COAP_INVALID_TID){
coap_delete_pdu(pdu);
}
}
}
if(uri)
c_free((void *)uri);
NODE_DBG("coap_request is called.\n");
return 0;
}
extern coap_luser_entry *variable_entry;
extern coap_luser_entry *function_entry;
extern void build_well_known_rsp(void);
// Lua: coap:var/func( string )
static int ICACHE_FLASH_ATTR
coap_regist( lua_State* L, const char* mt, int isvar )
{
size_t l;
const char *name = luaL_checklstring( L, 2, &l );
if (name == NULL)
return luaL_error( L, "name must be set." );
coap_luser_entry *h = NULL;
// if(lua_isstring(L, 3))
if(isvar)
h = variable_entry;
else
h = function_entry;
while(NULL!=h->next){ // goto the end of the list
if(h->name!= NULL && c_strcmp(h->name, name)==0) // key exist, override it
break;
h = h->next;
}
if(h->name==NULL || c_strcmp(h->name, name)!=0){ // not exists. make a new one.
h->next = (coap_luser_entry *)c_zalloc(sizeof(coap_luser_entry));
h = h->next;
if(h == NULL)
return luaL_error(L, "not enough memory");
h->next = NULL;
h->name = NULL;
h->L = NULL;
}
h->L = L;
h->name = name;
build_well_known_rsp(); // rebuild .well-known
NODE_DBG("coap_regist is called.\n");
return 0;
}
// Lua: s = coap.createServer(function(conn))
static int ICACHE_FLASH_ATTR coap_createServer( lua_State* L )
{
const char *mt = "coap_server";
return coap_create(L, mt);
}
// Lua: server:delete()
static int ICACHE_FLASH_ATTR
coap_server_delete( lua_State* L )
{
const char *mt = "coap_server";
return coap_delete(L, mt);
}
// Lua: server:listen( port, ip, function(err) )
static int ICACHE_FLASH_ATTR
coap_server_listen( lua_State* L )
{
const char *mt = "coap_server";
return coap_start(L, mt);
}
// Lua: server:close()
static int ICACHE_FLASH_ATTR
coap_server_close( lua_State* L )
{
const char *mt = "coap_server";
return coap_close(L, mt);
}
// Lua: server:on( "method", function(server) )
static int ICACHE_FLASH_ATTR
coap_server_on( lua_State* L )
{
const char *mt = "coap_server";
return coap_on(L, mt);
}
// Lua: server:var( "name" )
static int ICACHE_FLASH_ATTR
coap_server_var( lua_State* L )
{
const char *mt = "coap_server";
return coap_regist(L, mt, 1);
}
// Lua: server:func( "name" )
static int ICACHE_FLASH_ATTR
coap_server_func( lua_State* L )
{
const char *mt = "coap_server";
return coap_regist(L, mt, 0);
}
// Lua: s = coap.createClient(function(conn))
static int ICACHE_FLASH_ATTR
coap_createClient( lua_State* L )
{
const char *mt = "coap_client";
return coap_create(L, mt);
}
// Lua: client:gcdelete()
static int ICACHE_FLASH_ATTR
coap_client_gcdelete( lua_State* L )
{
const char *mt = "coap_client";
return coap_delete(L, mt);
}
// client:get( string, function(sent) )
static int ICACHE_FLASH_ATTR
coap_client_get( lua_State* L )
{
return coap_request(L, COAP_METHOD_GET);
}
// client:post( string, function(sent) )
static int ICACHE_FLASH_ATTR
coap_client_post( lua_State* L )
{
return coap_request(L, COAP_METHOD_POST);
}
// client:put( string, function(sent) )
static int ICACHE_FLASH_ATTR
coap_client_put( lua_State* L )
{
return coap_request(L, COAP_METHOD_PUT);
}
// client:delete( string, function(sent) )
static int ICACHE_FLASH_ATTR
coap_client_delete( lua_State* L )
{
return coap_request(L, COAP_METHOD_DELETE);
}
// Module function map
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
static const LUA_REG_TYPE coap_server_map[] =
{
{ LSTRKEY( "listen" ), LFUNCVAL ( coap_server_listen ) },
{ LSTRKEY( "close" ), LFUNCVAL ( coap_server_close ) },
{ LSTRKEY( "var" ), LFUNCVAL ( coap_server_var ) },
{ LSTRKEY( "func" ), LFUNCVAL ( coap_server_func ) },
{ LSTRKEY( "__gc" ), LFUNCVAL ( coap_server_delete ) },
#if LUA_OPTIMIZE_MEMORY > 0
{ LSTRKEY( "__index" ), LROVAL ( coap_server_map ) },
#endif
{ LNILKEY, LNILVAL }
};
static const LUA_REG_TYPE coap_client_map[] =
{
{ LSTRKEY( "get" ), LFUNCVAL ( coap_client_get ) },
{ LSTRKEY( "post" ), LFUNCVAL ( coap_client_post ) },
{ LSTRKEY( "put" ), LFUNCVAL ( coap_client_put ) },
{ LSTRKEY( "delete" ), LFUNCVAL ( coap_client_delete ) },
{ LSTRKEY( "__gc" ), LFUNCVAL ( coap_client_gcdelete ) },
#if LUA_OPTIMIZE_MEMORY > 0
{ LSTRKEY( "__index" ), LROVAL ( coap_client_map ) },
#endif
{ LNILKEY, LNILVAL }
};
const LUA_REG_TYPE coap_map[] =
{
{ LSTRKEY( "Server" ), LFUNCVAL ( coap_createServer ) },
{ LSTRKEY( "Client" ), LFUNCVAL ( coap_createClient ) },
#if LUA_OPTIMIZE_MEMORY > 0
{ LSTRKEY( "CON" ), LNUMVAL( COAP_TYPE_CON ) },
{ LSTRKEY( "NON" ), LNUMVAL( COAP_TYPE_NONCON ) },
{ LSTRKEY( "__metatable" ), LROVAL( coap_map ) },
#endif
{ LNILKEY, LNILVAL }
};
LUALIB_API int ICACHE_FLASH_ATTR luaopen_coap( lua_State *L )
{
endpoint_setup();
#if LUA_OPTIMIZE_MEMORY > 0
luaL_rometatable(L, "coap_server", (void *)coap_server_map); // create metatable for coap_server
luaL_rometatable(L, "coap_client", (void *)coap_client_map); // create metatable for coap_client
return 0;
#else // #if LUA_OPTIMIZE_MEMORY > 0
int n;
luaL_register( L, AUXLIB_COAP, coap_map );
// Set it as its own metatable
lua_pushvalue( L, -1 );
lua_setmetatable( L, -2 );
// Module constants
MOD_REG_NUMBER( L, "CON", COAP_TYPE_CON );
MOD_REG_NUMBER( L, "NON", COAP_TYPE_NONCON );
n = lua_gettop(L);
// create metatable
luaL_newmetatable(L, "coap_server");
// metatable.__index = metatable
lua_pushliteral(L, "__index");
lua_pushvalue(L,-2);
lua_rawset(L,-3);
// Setup the methods inside metatable
luaL_register( L, NULL, coap_server_map );
lua_settop(L, n);
// create metatable
luaL_newmetatable(L, "coap_client");
// metatable.__index = metatable
lua_pushliteral(L, "__index");
lua_pushvalue(L,-2);
lua_rawset(L,-3);
// Setup the methods inside metatable
luaL_register( L, NULL, coap_client_map );
return 1;
#endif // #if LUA_OPTIMIZE_MEMORY > 0
}
......@@ -37,6 +37,14 @@
#define ROM_MODULES_NET
#endif
#if defined(LUA_USE_MODULES_COAP)
#define MODULES_COAP "coap"
#define ROM_MODULES_COAP \
_ROM(MODULES_COAP, luaopen_coap, coap_map)
#else
#define ROM_MODULES_COAP
#endif
#if defined(LUA_USE_MODULES_MQTT)
#define MODULES_MQTT "mqtt"
#define ROM_MODULES_MQTT \
......@@ -121,7 +129,8 @@
ROM_MODULES_GPIO \
ROM_MODULES_PWM \
ROM_MODULES_WIFI \
ROM_MODULES_MQTT \
ROM_MODULES_COAP \
ROM_MODULES_MQTT \
ROM_MODULES_I2C \
ROM_MODULES_SPI \
ROM_MODULES_TMR \
......
......@@ -339,3 +339,18 @@ uart.on("data",4, function(data)
end
end, 0)
-- use copper addon for firefox
cs=coap.Server()
cs:listen(5683)
myvar=1
cs:var("myvar") -- get coap://192.168.18.103:5683/v1/v/myvar will return the value of myvar: 1
function myfun()
print("myfun called")
end
cs:func("myfun") -- post coap://192.168.18.103:5683/v1/f/myfun will call myfun
cc = coap.Client()
cc:get(coap.CON, "coap://192.168.18.100:5683/.well-known/core")
cc:post(coap.NON, "coap://192.168.18.100:5683/", "Hello")
......@@ -5,7 +5,7 @@ MEMORY
dport0_0_seg : org = 0x3FF00000, len = 0x10
dram0_0_seg : org = 0x3FFE8000, len = 0x14000
iram1_0_seg : org = 0x40100000, len = 0x8000
irom0_0_seg : org = 0x40210000, len = 0x51000
irom0_0_seg : org = 0x40210000, len = 0x54000
}
PHDRS
......
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