Commit fa7cf878 authored by zeroday's avatar zeroday
Browse files

Merge pull request #287 from nodemcu/dev

Dev merge to master
parents 6c8cace9 1652df50
......@@ -8,13 +8,21 @@ install:
script:
- make all
- cd bin/
- file_name="nodemcu-firmware_v${TRAVIS_TAG}.${TRAVIS_BUILD_NUMBER}.bin"
- srec_cat -output ${file_name} -binary 0x00000.bin -binary -fill 0xff 0x00000 0x10000 0x10000.bin -binary -offset 0x10000
- file_name_float="nodemcu_float_${TRAVIS_TAG}.bin"
- srec_cat -output ${file_name_float} -binary 0x00000.bin -binary -fill 0xff 0x00000 0x10000 0x10000.bin -binary -offset 0x10000
- cd ../
- make clean
- make EXTRA_CCFLAGS="-DLUA_NUMBER_INTEGRAL"
- cd bin/
- file_name_integer="nodemcu_integer_${TRAVIS_TAG}.bin"
- srec_cat -output ${file_name_integer} -binary 0x00000.bin -binary -fill 0xff 0x00000 0x10000 0x10000.bin -binary -offset 0x10000
deploy:
provider: releases
api_key:
secure: Swecz5lWvsuSbchSbVQ1rmCPN9nQIN5p/HlZNIEdEgAgnoLcJxRV4P8poVTB37jiA8Pck+8x2nWXpg74Rqik0i3KlPNvDfg5o4rIazWLNs4bc1Tbcpt44XAzFKKLYnDnWQUGcqjk7BcAXuNAF2X/fPBCVhFbHVg3Z7cDb32RsNw=
file: "$TRAVIS_BUILD_DIR/bin/${file_name}"
file:
- "$TRAVIS_BUILD_DIR/bin/${file_name_float}"
- "$TRAVIS_BUILD_DIR/bin/${file_name_integer}"
skip_cleanup: true
on:
tags: true
......
......@@ -22,7 +22,7 @@ ifeq ($(OS),Windows_NT)
else
# It is gcc, may be cygwin
# Can we use -fdata-sections?
CCFLAGS += -Os -ffunction-sections -fno-jump-tables
CCFLAGS += -Os -ffunction-sections -fno-jump-tables -fdata-sections
AR = xtensa-lx106-elf-ar
CC = xtensa-lx106-elf-gcc
NM = xtensa-lx106-elf-nm
......@@ -49,7 +49,7 @@ else
else
ESPPORT = $(COMPORT)
endif
CCFLAGS += -Os -ffunction-sections -fno-jump-tables
CCFLAGS += -Os -ffunction-sections -fno-jump-tables -fdata-sections
AR = xtensa-lx106-elf-ar
CC = xtensa-lx106-elf-gcc
NM = xtensa-lx106-elf-nm
......
# **NodeMcu** #
# **NodeMCU** #
version 0.9.5
[![Join the chat at https://gitter.im/nodemcu/nodemcu-firmware](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodemcu/nodemcu-firmware?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/nodemcu/nodemcu-firmware.svg)](https://travis-ci.org/nodemcu/nodemcu-firmware)
[![Join the chat at https://gitter.im/nodemcu/nodemcu-firmware](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nodemcu/nodemcu-firmware?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/nodemcu/nodemcu-firmware.svg)](https://travis-ci.org/nodemcu/nodemcu-firmware) [![Download](https://img.shields.io/badge/download-~400k-orange.svg)](https://github.com/nodemcu/nodemcu-firmware/releases/latest)
###A lua based firmware for wifi-soc esp8266
Build on [ESP8266 sdk 0.9.5](http://bbs.espressif.com/viewtopic.php?f=5&t=154)<br />
......@@ -10,27 +11,46 @@ File system based on [spiffs](https://github.com/pellepl/spiffs)<br />
Open source development kit for NodeMCU [nodemcu-devkit](https://github.com/nodemcu/nodemcu-devkit)<br />
Flash tool for NodeMCU [nodemcu-flasher](https://github.com/nodemcu/nodemcu-flasher)<br />
wiki: [nodemcu wiki](https://github.com/nodemcu/nodemcu-firmware/wiki)<br />
api: [nodemcu api](https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en)<br />
wiki: [NodeMCU wiki](https://github.com/nodemcu/nodemcu-firmware/wiki)<br />
api: [NodeMCU api](https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en)<br />
home: [nodemcu.com](http://www.nodemcu.com)<br />
bbs: [Chinese bbs](http://bbs.nodemcu.com)<br />
docs: [NodeMCU docs](http://www.nodemcu.com/docs/)<br />
Tencent QQ group: 309957875<br />
# Summary
- Easy to access wireless router
- Based on Lua 5.1.4 (without *io, math, debug, os* module.)
- Based on Lua 5.1.4 (without *debug, os* module.)
- Event-Drive programming preferred.
- Build-in file, timer, pwm, i2c, spi, 1-wire, net, mqtt, gpio, wifi, adc, uart and system api.
- Build-in file, timer, pwm, i2c, spi, 1-wire, net, mqtt, coap, gpio, wifi, adc, uart and system api.
- GPIO pin re-mapped, use the index to access gpio, i2c, pwm.
# To Do List (pull requests are very welcomed)
- loadable c module
- fix wifi smart connect
- add spi module (done)
- add mqtt module (done)
- add coap module
- cross compiler
- add coap module (done)
- cross compiler (done)
# Change log
2015-03-15<br />
bugs fixed: #239, #273.<br />
reduce coap module memory usage, add coap module to default built.
2015-03-11<br />
fix bugs of spiffs.<br />
build both float and integer version [latest releases](https://github.com/nodemcu/nodemcu-firmware/releases/latest).<br />
fix tmr.time().<br />
fix memory leak when DNS fail.
2015-03-10<br />
update to the recent spiffs.<br />
add file.fsinfo() api, usage: remain, used, total = file.fsinfo().<br />
add Travis CI. please download the latest firmware from [releases](https://github.com/nodemcu/nodemcu-firmware/releases).<br />
add math lib, partial api work.<br />
u8g module, ws2812 module default enabled in dev-branch build.
2015-02-13<br />
add node.compile() api to compile lua text file into lua bytecode file.<br />
this will reduce memory usage noticeably when require modules into NodeMCU.<br />
......@@ -101,15 +121,19 @@ build pre_build bin.
#### [*] D0(GPIO16) can only be used as gpio read/write. no interrupt supported. no pwm/i2c/ow supported.
#Build option
####file ./app/include/user_config.h
####file ./app/include/user_modules.h
```c
// #define FLASH_512K
// #define FLASH_1M
// #define FLASH_2M
// #define FLASH_4M
#define FLASH_AUTOSIZE
...
#define LUA_USE_BUILTIN_STRING // for string.xxx()
#define LUA_USE_BUILTIN_TABLE // for table.xxx()
#define LUA_USE_BUILTIN_COROUTINE // for coroutine.xxx()
#define LUA_USE_BUILTIN_MATH // for math.xxx(), partially work
// #define LUA_USE_BUILTIN_IO // for io.xxx(), partially work
// #define LUA_USE_BUILTIN_OS // for os.xxx(), not work
// #define LUA_USE_BUILTIN_DEBUG // for debug.xxx(), not work
#define LUA_USE_MODULES
#ifdef LUA_USE_MODULES
#define LUA_USE_MODULES_NODE
#define LUA_USE_MODULES_FILE
......@@ -118,15 +142,17 @@ build pre_build bin.
#define LUA_USE_MODULES_NET
#define LUA_USE_MODULES_PWM
#define LUA_USE_MODULES_I2C
#define LUA_USE_MODULES_SPI
#define LUA_USE_MODULES_TMR
#define LUA_USE_MODULES_ADC
#define LUA_USE_MODULES_UART
#define LUA_USE_MODULES_OW
#define LUA_USE_MODULES_BIT
#define LUA_USE_MODULES_MQTT
// #define LUA_USE_MODULES_COAP // need about 4k more ram for now
#define LUA_USE_MODULES_U8G
#define LUA_USE_MODULES_WS2812
#endif /* LUA_USE_MODULES */
...
// LUA_NUMBER_INTEGRAL
```
#Flash the firmware
......@@ -159,7 +185,7 @@ baudrate:9600
```
####Manipulate hardware like a arduino
```lua
pin = 1
gpio.mode(pin,gpio.OUTPUT)
......@@ -168,10 +194,10 @@ baudrate:9600
```
####Write network application in nodejs style
```lua
-- A simple http client
conn=net.createConnection(net.TCP, 0)
conn=net.createConnection(net.TCP, 0)
conn:on("receive", function(conn, payload) print(payload) end )
conn:connect(80,"115.239.210.27")
conn:send("GET / HTTP/1.1\r\nHost: www.baidu.com\r\n"
......@@ -179,15 +205,15 @@ baudrate:9600
```
####Or a simple http server
```lua
-- A simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive",function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMcu.</h1>")
end)
end)
conn:on("sent",function(conn) conn:close() end)
end)
```
......@@ -199,7 +225,7 @@ baudrate:9600
m = mqtt.Client("clientid", 120, "user", "password")
-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)
......@@ -207,8 +233,8 @@ m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)
-- on publish message receive event
m:on("message", function(conn, topic, data)
print(topic .. ":" )
m:on("message", function(conn, topic, data)
print(topic .. ":" )
if data ~= nil then
print(data)
end
......@@ -232,29 +258,29 @@ m:close();
#### UDP client and server
```lua
-- a udp server
s=net.createServer(net.UDP)
s=net.createServer(net.UDP)
s:on("receive",function(s,c) print(c) end)
s:listen(5683)
-- a udp client
cu=net.createConnection(net.UDP)
cu:on("receive",function(cu,c) print(c) end)
cu:connect(5683,"192.168.18.101")
cu=net.createConnection(net.UDP)
cu:on("receive",function(cu,c) print(c) end)
cu:connect(5683,"192.168.18.101")
cu:send("hello")
```
####Do something shining
```lua
function led(r,g,b)
pwm.setduty(1,r)
pwm.setduty(2,g)
pwm.setduty(3,b)
function led(r,g,b)
pwm.setduty(1,r)
pwm.setduty(2,g)
pwm.setduty(3,b)
end
pwm.setup(1,500,512)
pwm.setup(2,500,512)
pwm.setup(1,500,512)
pwm.setup(2,500,512)
pwm.setup(3,500,512)
pwm.start(1)
pwm.start(2)
pwm.start(1)
pwm.start(2)
pwm.start(3)
led(512,0,0) -- red
led(0,0,512) -- blue
......@@ -264,13 +290,13 @@ cu:send("hello")
```lua
lighton=0
tmr.alarm(1,1000,1,function()
if lighton==0 then
lighton=1
led(512,512,512)
else
lighton=0
led(0,0,0)
end
if lighton==0 then
lighton=1
led(512,512,512)
else
lighton=0
led(0,0,0)
end
end)
```
......@@ -286,20 +312,20 @@ cu:send("hello")
####With below code, you can telnet to your esp8266 now
```lua
-- a simple telnet server
s=net.createServer(net.TCP,180)
s:listen(2323,function(c)
function s_output(str)
if(c~=nil)
then c:send(str)
end
end
s=net.createServer(net.TCP,180)
s:listen(2323,function(c)
function s_output(str)
if(c~=nil)
then c:send(str)
end
end
node.output(s_output, 0) -- re-direct output to function s_ouput.
c:on("receive",function(c,l)
c:on("receive",function(c,l)
node.input(l) -- works like pcall(loadstring(l)) but support multiple separate line
end)
c:on("disconnection",function(c)
end)
c:on("disconnection",function(c)
node.output(nil) -- un-regist the redirect output function, output goes to serial
end)
end)
print("Welcome to NodeMcu world.")
end)
```
......@@ -328,15 +354,114 @@ cu:send("hello")
-- Don't forget to release it after use
t = nil
ds18b20 = nil
package.loaded["ds18b20"]=nil
package.loaded["ds18b20"]=nil
```
####Operate a display via I2c with u8glib
u8glib is a graphics library with support for many different displays.
The integration in nodemcu is developed for SSD1306 based display attached via the I2C port. Further display types and SPI connectivity will be added in the future.
U8glib v1.17
#####I2C connection
Hook up SDA and SCL to any free GPIOs. Eg. `lua_examples/u8glib/graphics_test.lua` expects SDA=5 (GPIO14) and SCL=6 (GPIO12). They are used to set up nodemcu's I2C driver before accessing the display:
```lua
sda = 5
scl = 6
i2c.setup(0, sda, scl, i2c.SLOW)
```
#####SPI connection
The HSPI module is used, so certain pins are fixed:
* HSPI CLK = GPIO14
* HSPI MOSI = GPIO13
* HSPI MISO = GPIO12 (not used)
All other pins can be assigned to any available GPIO:
* CS
* D/C
* RES (optional for some displays)
Also refer to the initialization sequence eg in `lua_examples/u8glib/graphics_test.lua`:
```lua
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, spi.DATABITS_8, 0)
```
#####Library usage
The Lua bindings for this library closely follow u8glib's object oriented C++ API. Based on the u8g class, you create an object for your display type.
SSD1306 via I2C:
```lua
sla = 0x3c
disp = u8g.ssd1306_128x64_i2c(sla)
```
SSD1306 via SPI:
```lua
cs = 8 -- GPIO15, pull-down 10k to GND
dc = 4 -- GPIO2
res = 0 -- GPIO16, RES is optional YMMV
disp = u8g.ssd1306_128x64_spi(cs, dc, res)
```
This object provides all of u8glib's methods to control the display.
Again, refer to `lua_examples/u8glib/graphics_test.lua` to get an impression how this is achieved with Lua code. Visit the [u8glib homepage](https://code.google.com/p/u8glib/) for technical details.
#####Fonts
u8glib comes with a wide range of fonts for small displays. Since they need to be compiled into the firmware image, you'd need to include them in `app/include/u8g_config.h` and recompile. Simply add the desired fonts to the font table:
```c
#define U8G_FONT_TABLE \
U8G_FONT_TABLE_ENTRY(font_6x10) \
U8G_FONT_TABLE_ENTRY(font_chikita)
```
They'll be available as `u8g.<font_name>` in Lua.
#####Bitmaps
Bitmaps and XBMs are supplied as strings to `drawBitmap()` and `drawXBM()`. This off-loads all data handling from the u8g module to generic methods for binary files. See `lua_examples/u8glib/u8g_bitmaps.lua`. Binary files can be uploaded with [nodemcu-uploader.py](https://github.com/kmpm/nodemcu-uploader).
#####Unimplemented functions
- [ ] Cursor handling
- [ ] disableCursor()
- [ ] enableCursor()
- [ ] setCursorColor()
- [ ] setCursorFont()
- [ ] setCursorPos()
- [ ] setCursorStyle()
- [ ] General functions
- [ ] setContrast()
- [ ] setPrintPos()
- [ ] setHardwareBackup()
- [ ] setRGB()
####Control a WS2812 based light strip
```lua
-- set the color of one LED on GPIO 2 to red
ws2812.write(4, string.char(0, 255, 0))
-- set the color of 10 LEDs on GPIO 0 to blue
ws2812.write(3, string.char(0, 0, 255):rep(10))
-- set the color of one LED on GPIO2 to red
ws2812.writergb(4, string.char(255, 0, 0))
-- set the color of 10 LEDs on GPIO0 to blue
ws2812.writergb(3, string.char(0, 0, 255):rep(10))
-- first LED green, second LED white
ws2812.write(4, string.char(255, 0, 0, 255, 255, 255))
ws2812.writergb(4, string.char(0, 255, 0, 255, 255, 255))
```
####coap client and server
```lua
-- 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 should tack one string, return one string.
function myfun(payload)
print("myfun called")
respond = "hello"
return respond
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")
```
*.output*
mapfile
!.gitignore
......@@ -30,7 +30,9 @@ SUBDIRS= \
platform \
libc \
lua \
coap \
mqtt \
u8glib \
smart \
wofs \
modules \
......@@ -76,7 +78,9 @@ COMPONENTS_eagle.app.v6 = \
platform/libplatform.a \
libc/liblibc.a \
lua/liblua.a \
coap/coap.a \
mqtt/mqtt.a \
u8glib/u8glib.a \
smart/smart.a \
wofs/wofs.a \
spiffs/spiffs.a \
......@@ -84,6 +88,8 @@ COMPONENTS_eagle.app.v6 = \
LINKFLAGS_eagle.app.v6 = \
-L../lib \
-Wl,--gc-sections \
-Xlinker -Map=mapfile \
-nostdlib \
-T$(LD_FILE) \
-Wl,--no-check-sections \
......@@ -102,7 +108,8 @@ LINKFLAGS_eagle.app.v6 = \
-lsmartconfig \
-lssl \
$(DEP_LIBS_eagle.app.v6) \
-Wl,--end-group
-Wl,--end-group \
-lm
DEPENDS_eagle.app.v6 = \
$(LD_FILE) \
......
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 (4U + 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 < (4U + 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/rfc7252#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;
uint8_t headlen = 1;
uint16_t len, delta;
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/rfc7252#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;
uint16_t delta = 0;
const uint8_t *p = buf + 4 + hdr->tkl;
const uint8_t *end = buf + buflen;
int rc;
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(uint32_t 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 (((size_t)(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(uint32_t value, uint8_t *nibble)
{
if (value<13)
{
*nibble = (0xFF & value);
}
else
if (value<=0xFF+13)
{
*nibble = 13;
} else if (value<=0xFFFF+269)
{
*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 = 1;
// 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/rfc7252#section-3
typedef struct
{
uint8_t ver; /* CoAP version number */
uint8_t t; /* CoAP Message Type */
uint8_t tkl; /* Token length: indicates length of the Token field */
uint8_t code; /* CoAP status code. Can be request (0.xx), success reponse (2.xx),
* client error response (4.xx), or rever error response (5.xx)
* For possible values, see http://tools.ietf.org/html/rfc7252#section-12.1 */
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; /* Option number. See http://tools.ietf.org/html/rfc7252#section-5.10 */
coap_buffer_t buf; /* Option value */
} coap_option_t;
typedef struct
{
coap_header_t hdr; /* Header of the packet */
coap_buffer_t tok; /* Token value, size as specified by hdr.tkl */
uint8_t numopts; /* Number of options */
coap_option_t opts[MAXOPT]; /* Options of the packet. For possible entries see
* http://tools.ietf.org/html/rfc7252#section-5.10 */
coap_buffer_t payload; /* Payload carried by the packet */
coap_rw_buffer_t content; // content->p = malloc(...) , and free it when done.
} coap_packet_t;
/////////////////////////////////////////
//http://tools.ietf.org/html/rfc7252#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/rfc7252#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/rfc7252#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/rfc7252#section-5.2
//http://tools.ietf.org/html/rfc7252#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/rfc7252#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; /* (i.e. POST, PUT or GET) */
coap_endpoint_func handler; /* callback function which handles this
* type of endpoint (and calls
* coap_make_response() at some point) */
const coap_endpoint_path_t *path; /* path towards a resource (i.e. foo/bar/) */
const char *core_attr; /* the 'ct' attribute, as defined in RFC7252, section 7.2.1.:
* "The Content-Format code "ct" attribute
* provides a hint about the
* Content-Formats this resource returns."
* (Section 12.3. lists possible ct values.) */
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(uint32_t value, uint8_t *nibble);
void coap_setup(void);
void endpoint_setup(void);
int coap_buildOptionHeader(uint32_t 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;
pkt.content.p = NULL;
pkt.content.len = 0;
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((char *)(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((char *)(pkt.payload.p));
}
}
end:
if(!gQueue){ // if there is no node pending in the queue, disconnect from host.
}
}
#ifndef _COAP_CLIENT_H
#define _COAP_CLIENT_H 1
#ifdef __cplusplus
extern "C" {
#endif
void coap_client_response_handler(char *data, unsigned short len, unsigned short size, const uint32_t ip, const uint32_t port);
#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 "c_stdlib.h"
#include "coap.h"
size_t coap_server_respond(char *req, unsigned short reqlen, char *rsp, unsigned short rsplen)
{
NODE_DBG("coap_server_respond is called.\n");
size_t rlen = rsplen;
coap_packet_t pkt;
pkt.content.p = NULL;
pkt.content.len = 0;
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(req, reqlen, true);
NODE_DBG("\n");
#endif
if (0 != (rc = coap_parse(&pkt, req, reqlen))){
NODE_DBG("Bad packet rc=%d\n", rc);
return 0;
}
else
{
coap_packet_t rsppkt;
rsppkt.content.p = NULL;
rsppkt.content.len = 0;
#ifdef COAP_DEBUG
coap_dumpPacket(&pkt);
#endif
coap_handle_req(&scratch_buf, &pkt, &rsppkt);
if (0 != (rc = coap_build(rsp, &rlen, &rsppkt))){
NODE_DBG("coap_build failed rc=%d\n", rc);
// return 0;
rlen = 0;
}
else
{
#ifdef COAP_DEBUG
NODE_DBG("Responding: ");
coap_dump(rsp, rlen, true);
NODE_DBG("\n");
#endif
#ifdef COAP_DEBUG
coap_dumpPacket(&rsppkt);
#endif
}
if(rsppkt.content.p){
c_free(rsppkt.content.p);
rsppkt.content.p = NULL;
rsppkt.content.len = 0;
}
return rlen;
}
}
#ifndef _COAP_SERVER_H
#define _COAP_SERVER_H 1
#ifdef __cplusplus
extern "C" {
#endif
size_t coap_server_respond(char *req, unsigned short reqlen, char *rsp, unsigned short rsplen);
#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 "c_stdlib.h"
#include "coap.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "os_type.h"
void build_well_known_rsp(char *rsp, uint16_t rsplen);
void endpoint_setup(void)
{
coap_setup();
}
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)
{
outpkt->content.p = (uint8_t *)c_zalloc(MAX_PAYLOAD_SIZE); // this should be free-ed when outpkt is built in coap_server_respond()
if(outpkt->content.p == NULL){
NODE_DBG("not enough memory\n");
return COAP_ERR_BUFFER_TOO_SMALL;
}
outpkt->content.len = MAX_PAYLOAD_SIZE;
build_well_known_rsp(outpkt->content.p, outpkt->content.len);
return coap_make_response(scratch, outpkt, (const uint8_t *)outpkt->content.p, c_strlen(outpkt->content.p), 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;
int n;
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((char *)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))
{
n = lua_gettop(h->L);
lua_getglobal(h->L, h->name);
if (!lua_isnumber(h->L, -1)) {
NODE_DBG ("should be a number.\n");
lua_settop(h->L, n);
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_settop(h->L, n);
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;
int n;
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((char *)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))
{
n = lua_gettop(h->L);
lua_getglobal(h->L, h->name);
if (lua_type(h->L, -1) != LUA_TFUNCTION) {
NODE_DBG ("should be a function\n");
lua_settop(h->L, n);
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){
lua_settop(h->L, n);
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((char *)ret);
NODE_DBG("\n");
lua_settop(h->L, n);
return coap_make_response(scratch, outpkt, ret, len, id_hi, id_lo, &inpkt->tok, COAP_RSPCODE_CONTENT, COAP_CONTENTTYPE_TEXT_PLAIN);
}
} else {
lua_settop(h->L, n);
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(char *rsp, uint16_t rsplen)
{
const coap_endpoint_t *ep = endpoints;
int i;
uint16_t len = rsplen;
c_memset(rsp, 0, len);
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
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