Commit 71469dd7 authored by HuangRui's avatar HuangRui
Browse files

Merge branch 'dev' of https://github.com/nodemcu/nodemcu-firmware

Conflicts:
	app/include/user_version.h
	app/modules/node.c
	app/modules/wifi.c
parents 43d06459 a14971fa
...@@ -36,6 +36,12 @@ Tencent QQ group: 309957875<br /> ...@@ -36,6 +36,12 @@ Tencent QQ group: 309957875<br />
- cross compiler (done) - cross compiler (done)
# Change log # Change log
2015-03-31<br />
polish mqtt module, add queue for mqtt module.<br />
add reconnect option to mqtt.connect api, :connect( host, port, secure, auto_reconnect, function(client) )<br />
move node.readvdd33 to adc.readvdd33.<br />
tools/esptool.py supported NodeMCU devkit automatic flash.
2015-03-18<br /> 2015-03-18<br />
update u8glib.<br /> update u8glib.<br />
merge everything to master. merge everything to master.
...@@ -225,8 +231,10 @@ m:on("message", function(conn, topic, data) ...@@ -225,8 +231,10 @@ m:on("message", function(conn, topic, data)
end end
end) end)
-- for secure: m:connect("192.168.11.118", 1880, 1) -- m:connect( host, port, secure, auto_reconnect, function(client) )
m:connect("192.168.11.118", 1880, 0, function(conn) print("connected") end) -- for secure: m:connect("192.168.11.118", 1880, 1, 0)
-- for auto-reconnect: m:connect("192.168.11.118", 1880, 0, 1)
m:connect("192.168.11.118", 1880, 0, 0, function(conn) print("connected") end)
-- subscribe topic with qos = 0 -- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success") end) m:subscribe("/topic",0, function(conn) print("subscribe success") end)
...@@ -235,7 +243,7 @@ m:subscribe("/topic",0, function(conn) print("subscribe success") end) ...@@ -235,7 +243,7 @@ m:subscribe("/topic",0, function(conn) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0 -- publish a message with data = hello, QoS = 0, retain = 0
m:publish("/topic","hello",0,0, function(conn) print("sent") end) m:publish("/topic","hello",0,0, function(conn) print("sent") end)
m:close(); m:close(); -- if auto-reconnect == 1, will disable auto-reconnect and then disconnect from host.
-- you can call m:connect again -- you can call m:connect again
``` ```
...@@ -402,7 +410,8 @@ u8glib comes with a wide range of fonts for small displays. Since they need to b ...@@ -402,7 +410,8 @@ u8glib comes with a wide range of fonts for small displays. Since they need to b
They'll be available as `u8g.<font_name>` in Lua. They'll be available as `u8g.<font_name>` in Lua.
#####Bitmaps #####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). 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`.
In contrast to the source code based inclusion of XBMs into u8glib, it's required to provide precompiled binary files. This can be performed online with [Online-Utility's Image Converter](http://www.online-utility.org/image_converter.jsp): Convert from XBM to MONO format and upload the binary result with [nodemcu-uploader.py](https://github.com/kmpm/nodemcu-uploader).
#####Unimplemented functions #####Unimplemented functions
- [ ] Cursor handling - [ ] Cursor handling
......
...@@ -46,7 +46,7 @@ int strbuf_init(strbuf_t *s, int len) ...@@ -46,7 +46,7 @@ int strbuf_init(strbuf_t *s, int len)
s->reallocs = 0; s->reallocs = 0;
s->debug = 0; s->debug = 0;
s->buf = c_malloc(size); s->buf = (char *)c_malloc(size);
if (!s->buf){ if (!s->buf){
NODE_ERR("not enough memory\n"); NODE_ERR("not enough memory\n");
return -1; return -1;
...@@ -60,7 +60,7 @@ strbuf_t *strbuf_new(int len) ...@@ -60,7 +60,7 @@ strbuf_t *strbuf_new(int len)
{ {
strbuf_t *s; strbuf_t *s;
s = c_malloc(sizeof(strbuf_t)); s = (strbuf_t *)c_malloc(sizeof(strbuf_t));
if (!s){ if (!s){
NODE_ERR("not enough memory\n"); NODE_ERR("not enough memory\n");
return NULL; return NULL;
......
...@@ -365,7 +365,7 @@ pwm_init(uint16 freq, uint16 *duty) ...@@ -365,7 +365,7 @@ pwm_init(uint16 freq, uint16 *duty)
for (i = 0; i < PWM_CHANNEL; i++) { for (i = 0; i < PWM_CHANNEL; i++) {
// pwm_gpio |= (1 << pwm_out_io_num[i]); // pwm_gpio |= (1 << pwm_out_io_num[i]);
pwm_gpio = 0; pwm_gpio = 0;
pwm.duty[0] = 0; pwm.duty[i] = 0;
} }
pwm_set_freq(500, 0); pwm_set_freq(500, 0);
......
...@@ -7,6 +7,6 @@ ...@@ -7,6 +7,6 @@
#define NODE_VERSION_INTERNAL 0U #define NODE_VERSION_INTERNAL 0U
#define NODE_VERSION "NodeMCU 0.9.6" #define NODE_VERSION "NodeMCU 0.9.6"
#define BUILD_DATE "build 20150318" #define BUILD_DATE "build 20150405"
#endif /* __USER_VERSION_H__ */ #endif /* __USER_VERSION_H__ */
...@@ -47,9 +47,9 @@ extern int c_stderr; ...@@ -47,9 +47,9 @@ extern int c_stderr;
#define SEEK_END 2 /* set file offset to EOF plus offset */ #define SEEK_END 2 /* set file offset to EOF plus offset */
#endif #endif
#define c_malloc os_malloc // #define c_malloc os_malloc
#define c_zalloc os_zalloc // #define c_zalloc os_zalloc
#define c_free os_free // #define c_free os_free
extern void output_redirect(const char *str); extern void output_redirect(const char *str);
#define c_puts output_redirect #define c_puts output_redirect
......
...@@ -29,9 +29,9 @@ ...@@ -29,9 +29,9 @@
#define os_realloc(p, s) mem_realloc((p), (s)) #define os_realloc(p, s) mem_realloc((p), (s))
#endif #endif
// #define c_free os_free #define c_free os_free
// #define c_malloc os_malloc #define c_malloc os_malloc
// #define c_zalloc os_zalloc #define c_zalloc os_zalloc
#define c_realloc os_realloc #define c_realloc os_realloc
#define c_abs abs #define c_abs abs
...@@ -47,9 +47,9 @@ ...@@ -47,9 +47,9 @@
// c_getenv() get env "LUA_INIT" string for lua initialization. // c_getenv() get env "LUA_INIT" string for lua initialization.
const char *c_getenv(const char *__string); const char *c_getenv(const char *__string);
void *c_malloc(size_t __size); // void *c_malloc(size_t __size);
void *c_zalloc(size_t __size); // void *c_zalloc(size_t __size);
void c_free(void *); // void c_free(void *);
// int c_rand(void); // int c_rand(void);
// void c_srand(unsigned int __seed); // void c_srand(unsigned int __seed);
......
...@@ -541,8 +541,12 @@ extern int readline4lua(const char *prompt, char *buffer, int length); ...@@ -541,8 +541,12 @@ extern int readline4lua(const char *prompt, char *buffer, int length);
/* /*
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. @@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
** Attention: This value should probably not be set higher than 1K.
** The size has direct impact on the C stack size needed be auxlib functions.
** For example: If set to 4K a call to string.gsub will need more than
** 5k C stack space.
*/ */
#define LUAL_BUFFERSIZE ((BUFSIZ)*4) #define LUAL_BUFFERSIZE BUFSIZ
/* }================================================================== */ /* }================================================================== */
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
#include "lrotable.h" #include "lrotable.h"
#include "c_types.h" #include "c_types.h"
#include "user_interface.h"
// Lua: read(id) , return system adc // Lua: read(id) , return system adc
static int adc_sample( lua_State* L ) static int adc_sample( lua_State* L )
...@@ -19,12 +20,33 @@ static int adc_sample( lua_State* L ) ...@@ -19,12 +20,33 @@ static int adc_sample( lua_State* L )
return 1; return 1;
} }
// Lua: readvdd33()
static int adc_readvdd33( lua_State* L )
{
uint32_t vdd33 = 0;
if(STATION_MODE == wifi_get_opmode())
{
// Bug fix
wifi_set_opmode( STATIONAP_MODE );
vdd33 = readvdd33();
wifi_set_opmode( STATION_MODE );
}
else
{
vdd33 = readvdd33();
}
lua_pushinteger(L, vdd33);
return 1;
}
// Module function map // Module function map
#define MIN_OPT_LEVEL 2 #define MIN_OPT_LEVEL 2
#include "lrodefs.h" #include "lrodefs.h"
const LUA_REG_TYPE adc_map[] = const LUA_REG_TYPE adc_map[] =
{ {
{ LSTRKEY( "read" ), LFUNCVAL( adc_sample ) }, { LSTRKEY( "read" ), LFUNCVAL( adc_sample ) },
{ LSTRKEY( "readvdd33" ), LFUNCVAL( adc_readvdd33) },
#if LUA_OPTIMIZE_MEMORY > 0 #if LUA_OPTIMIZE_MEMORY > 0
#endif #endif
......
...@@ -80,7 +80,7 @@ LUALIB_API int ( luaopen_file )( lua_State *L ); ...@@ -80,7 +80,7 @@ LUALIB_API int ( luaopen_file )( lua_State *L );
LUALIB_API int ( luaopen_ow )( lua_State *L ); LUALIB_API int ( luaopen_ow )( lua_State *L );
#define AUXLIB_CJSON "cjson" #define AUXLIB_CJSON "cjson"
LUALIB_API int ( luaopen_ow )( lua_State *L ); LUALIB_API int ( luaopen_cjson )( lua_State *L );
// Helper macros // Helper macros
#define MOD_CHECK_ID( mod, id )\ #define MOD_CHECK_ID( mod, id )\
......
...@@ -146,6 +146,82 @@ static int lgpio_write( lua_State* L ) ...@@ -146,6 +146,82 @@ static int lgpio_write( lua_State* L )
return 0; return 0;
} }
#define DELAY_TABLE_MAX_LEN 256
#define noInterrupts os_intr_lock
#define interrupts os_intr_unlock
#define delayMicroseconds os_delay_us
#define DIRECT_WRITE(pin, level) (GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[pin]), level))
// Lua: serout( pin, firstLevel, delay_table, [repeatNum] )
// -- serout( pin, firstLevel, delay_table, [repeatNum] )
// gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
// gpio.serout(1,1,{30,30,60,60,30,30}) -- serial one byte, b10110010
// gpio.serout(1,1,{30,70},8) -- serial 30% pwm 10k, lasts 8 cycles
// gpio.serout(1,1,{3,7},8) -- serial 30% pwm 100k, lasts 8 cycles
// gpio.serout(1,1,{0,0},8) -- serial 50% pwm as fast as possible, lasts 8 cycles
// gpio.mode(1,gpio.OUTPUT,gpio.PULLUP)
// gpio.serout(1,0,{20,10,10,20,10,10,10,100}) -- sim uart one byte 0x5A at about 100kbps
// gpio.serout(1,1,{8,18},8) -- serial 30% pwm 38k, lasts 8 cycles
static int lgpio_serout( lua_State* L )
{
unsigned level;
unsigned pin;
unsigned table_len = 0;
unsigned repeat = 0;
int delay_table[DELAY_TABLE_MAX_LEN];
pin = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( gpio, pin );
level = luaL_checkinteger( L, 2 );
if ( level!=HIGH && level!=LOW )
return luaL_error( L, "wrong arg type" );
if( lua_istable( L, 3 ) )
{
table_len = lua_objlen( L, 3 );
if (table_len <= 0 || table_len>DELAY_TABLE_MAX_LEN)
return luaL_error( L, "wrong arg range" );
int i;
for( i = 0; i < table_len; i ++ )
{
lua_rawgeti( L, 3, i + 1 );
delay_table[i] = ( int )luaL_checkinteger( L, -1 );
lua_pop( L, 1 );
if( delay_table[i] < 0 || delay_table[i] > 1000000 ) // can not delay more than 1000000 us
return luaL_error( L, "delay must < 1000000 us" );
}
} else {
return luaL_error( L, "wrong arg range" );
}
if(lua_isnumber(L, 4))
repeat = lua_tointeger( L, 4 );
if( repeat < 0 || repeat > DELAY_TABLE_MAX_LEN )
return luaL_error( L, "delay must < 256" );
if(repeat==0)
repeat = 1;
int j;
bool skip_loop = true;
do
{
if(skip_loop){ // skip the first loop.
skip_loop = false;
continue;
}
for(j=0;j<table_len;j++){
noInterrupts();
// platform_gpio_write(pin, level);
DIRECT_WRITE(pin, level);
interrupts();
delayMicroseconds(delay_table[j]);
level=!level;
}
repeat--;
} while (repeat>0);
return 0;
}
#undef DELAY_TABLE_MAX_LEN
// Module function map // Module function map
#define MIN_OPT_LEVEL 2 #define MIN_OPT_LEVEL 2
#include "lrodefs.h" #include "lrodefs.h"
...@@ -154,6 +230,7 @@ const LUA_REG_TYPE gpio_map[] = ...@@ -154,6 +230,7 @@ const LUA_REG_TYPE gpio_map[] =
{ LSTRKEY( "mode" ), LFUNCVAL( lgpio_mode ) }, { LSTRKEY( "mode" ), LFUNCVAL( lgpio_mode ) },
{ LSTRKEY( "read" ), LFUNCVAL( lgpio_read ) }, { LSTRKEY( "read" ), LFUNCVAL( lgpio_read ) },
{ LSTRKEY( "write" ), LFUNCVAL( lgpio_write ) }, { LSTRKEY( "write" ), LFUNCVAL( lgpio_write ) },
{ LSTRKEY( "serout" ), LFUNCVAL( lgpio_serout ) },
#ifdef GPIO_INTERRUPT_ENABLE #ifdef GPIO_INTERRUPT_ENABLE
{ LSTRKEY( "trig" ), LFUNCVAL( lgpio_trig ) }, { LSTRKEY( "trig" ), LFUNCVAL( lgpio_trig ) },
#endif #endif
......
...@@ -15,8 +15,7 @@ ...@@ -15,8 +15,7 @@
#include "espconn.h" #include "espconn.h"
#include "mqtt_msg.h" #include "mqtt_msg.h"
#include "msg_queue.h"
static lua_State *gL = NULL;
#define MQTT_BUF_SIZE 1024 #define MQTT_BUF_SIZE 1024
#define MQTT_DEFAULT_KEEPALIVE 60 #define MQTT_DEFAULT_KEEPALIVE 60
...@@ -24,10 +23,11 @@ static lua_State *gL = NULL; ...@@ -24,10 +23,11 @@ static lua_State *gL = NULL;
#define MQTT_MAX_USER_LEN 64 #define MQTT_MAX_USER_LEN 64
#define MQTT_MAX_PASS_LEN 64 #define MQTT_MAX_PASS_LEN 64
#define MQTT_SEND_TIMEOUT 5 #define MQTT_SEND_TIMEOUT 5
#define MQTT_CONNECT_TIMEOUT 5
typedef enum { typedef enum {
MQTT_INIT, MQTT_INIT,
MQTT_CONNECT_SEND, MQTT_CONNECT_SENT,
MQTT_CONNECT_SENDING, MQTT_CONNECT_SENDING,
MQTT_DATA MQTT_DATA
} tConnState; } tConnState;
...@@ -47,22 +47,15 @@ typedef struct mqtt_state_t ...@@ -47,22 +47,15 @@ typedef struct mqtt_state_t
uint16_t port; uint16_t port;
int auto_reconnect; int auto_reconnect;
mqtt_connect_info_t* connect_info; mqtt_connect_info_t* connect_info;
uint8_t* in_buffer;
uint8_t* out_buffer;
int in_buffer_length;
int out_buffer_length;
uint16_t message_length; uint16_t message_length;
uint16_t message_length_read; uint16_t message_length_read;
mqtt_message_t* outbound_message;
mqtt_connection_t mqtt_connection; mqtt_connection_t mqtt_connection;
msg_queue_t* pending_msg_q;
uint16_t pending_msg_id;
int pending_msg_type;
int pending_publish_qos;
} mqtt_state_t; } mqtt_state_t;
typedef struct lmqtt_userdata typedef struct lmqtt_userdata
{ {
lua_State *L;
struct espconn *pesp_conn; struct espconn *pesp_conn;
int self_ref; int self_ref;
int cb_connect_ref; int cb_connect_ref;
...@@ -73,54 +66,104 @@ typedef struct lmqtt_userdata ...@@ -73,54 +66,104 @@ typedef struct lmqtt_userdata
mqtt_state_t mqtt_state; mqtt_state_t mqtt_state;
mqtt_connect_info_t connect_info; mqtt_connect_info_t connect_info;
uint32_t keep_alive_tick; uint32_t keep_alive_tick;
uint32_t send_timeout; uint32_t event_timeout;
uint8_t secure; uint8_t secure;
uint8_t connected; bool connected; // indicate socket connected, not mqtt prot connected.
ETSTimer mqttTimer; ETSTimer mqttTimer;
tConnState connState; tConnState connState;
}lmqtt_userdata; }lmqtt_userdata;
static void socket_connect(struct espconn *pesp_conn);
static void mqtt_socket_reconnected(void *arg, sint8_t err);
static void mqtt_socket_connected(void *arg);
static void mqtt_socket_disconnected(void *arg) // tcp only static void mqtt_socket_disconnected(void *arg) // tcp only
{ {
NODE_DBG("mqtt_socket_disconnected is called.\n"); NODE_DBG("enter mqtt_socket_disconnected.\n");
struct espconn *pesp_conn = arg; struct espconn *pesp_conn = arg;
bool call_back = false;
if(pesp_conn == NULL) if(pesp_conn == NULL)
return; return;
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse; lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud == NULL) if(mud == NULL)
return; return;
if(mud->cb_disconnect_ref != LUA_NOREF && mud->self_ref != LUA_NOREF)
{
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
lua_call(gL, 1, 0);
}
mud->connected = 0;
os_timer_disarm(&mud->mqttTimer); os_timer_disarm(&mud->mqttTimer);
if(pesp_conn->proto.tcp) if(mud->connected){ // call back only called when socket is from connection to disconnection.
c_free(pesp_conn->proto.tcp); mud->connected = false;
pesp_conn->proto.tcp = NULL; if((mud->L != NULL) && (mud->cb_disconnect_ref != LUA_NOREF) && (mud->self_ref != LUA_NOREF)) {
if(mud->pesp_conn) lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
call_back = true;
}
}
if(mud->mqtt_state.auto_reconnect){
mud->pesp_conn->reverse = mud;
mud->pesp_conn->type = ESPCONN_TCP;
mud->pesp_conn->state = ESPCONN_NONE;
mud->connected = false;
mud->pesp_conn->proto.tcp->remote_port = mud->mqtt_state.port;
mud->pesp_conn->proto.tcp->local_port = espconn_port();
espconn_regist_connectcb(mud->pesp_conn, mqtt_socket_connected);
espconn_regist_reconcb(mud->pesp_conn, mqtt_socket_reconnected);
socket_connect(pesp_conn);
} else {
if(mud->pesp_conn){
mud->pesp_conn->reverse = NULL;
if(mud->pesp_conn->proto.tcp)
c_free(mud->pesp_conn->proto.tcp);
mud->pesp_conn->proto.tcp = NULL;
c_free(mud->pesp_conn); c_free(mud->pesp_conn);
mud->pesp_conn = NULL; // espconn is already disconnected mud->pesp_conn = NULL;
lua_gc(gL, LUA_GCSTOP, 0); }
if(mud->self_ref != LUA_NOREF){
luaL_unref(gL, LUA_REGISTRYINDEX, mud->self_ref); if(mud->L == NULL)
return;
lua_gc(mud->L, LUA_GCSTOP, 0);
if(mud->self_ref != LUA_NOREF){ // TODO: should we unref the client and delete it?
luaL_unref(mud->L, LUA_REGISTRYINDEX, mud->self_ref);
mud->self_ref = LUA_NOREF; // unref this, and the mqtt.socket userdata will delete it self mud->self_ref = LUA_NOREF; // unref this, and the mqtt.socket userdata will delete it self
} }
lua_gc(gL, LUA_GCRESTART, 0); lua_gc(mud->L, LUA_GCRESTART, 0);
}
if((mud->L != NULL) && call_back){
lua_call(mud->L, 1, 0);
}
NODE_DBG("leave mqtt_socket_disconnected.\n");
} }
static void mqtt_socket_reconnected(void *arg, sint8_t err) static void mqtt_socket_reconnected(void *arg, sint8_t err)
{ {
NODE_DBG("mqtt_socket_reconnected is called.\n"); NODE_DBG("enter mqtt_socket_reconnected.\n");
// mqtt_socket_disconnected(arg);
struct espconn *pesp_conn = arg;
if(pesp_conn == NULL)
return;
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud == NULL)
return;
os_timer_disarm(&mud->mqttTimer);
if(mud->mqtt_state.auto_reconnect){
pesp_conn->proto.tcp->remote_port = mud->mqtt_state.port;
pesp_conn->proto.tcp->local_port = espconn_port();
socket_connect(pesp_conn);
} else {
mqtt_socket_disconnected(arg); mqtt_socket_disconnected(arg);
}
NODE_DBG("leave mqtt_socket_reconnected.\n");
} }
static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length) static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length)
{ {
const char comma[] = ","; NODE_DBG("enter deliver_publish.\n");
if(mud == NULL)
return;
mqtt_event_data_t event_data; mqtt_event_data_t event_data;
event_data.topic_length = length; event_data.topic_length = length;
...@@ -133,28 +176,36 @@ static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length) ...@@ -133,28 +176,36 @@ static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length)
return; return;
if(mud->self_ref == LUA_NOREF) if(mud->self_ref == LUA_NOREF)
return; return;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_message_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua return;
// expose_array(gL, pdata, len); if(event_data.topic && (event_data.topic_length > 0)){
// *(pdata+len) = 0; lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_message_ref);
// NODE_DBG(pdata); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
// NODE_DBG("\n"); lua_pushlstring(mud->L, event_data.topic, event_data.topic_length);
lua_pushlstring(gL, event_data.topic, event_data.topic_length);
if(event_data.data_length > 0){
lua_pushlstring(gL, event_data.data, event_data.data_length);
lua_call(gL, 3, 0);
} else { } else {
lua_call(gL, 2, 0); NODE_DBG("get wrong packet.\n");
return;
}
if(event_data.data && (event_data.data_length > 0)){
lua_pushlstring(mud->L, event_data.data, event_data.data_length);
lua_call(mud->L, 3, 0);
} else {
lua_call(mud->L, 2, 0);
} }
NODE_DBG("leave deliver_publish.\n");
} }
static void mqtt_socket_received(void *arg, char *pdata, unsigned short len) static void mqtt_socket_received(void *arg, char *pdata, unsigned short len)
{ {
NODE_DBG("mqtt_socket_received is called.\n"); NODE_DBG("enter mqtt_socket_received.\n");
uint8_t msg_type; uint8_t msg_type;
uint8_t msg_qos; uint8_t msg_qos;
uint16_t msg_id; uint16_t msg_id;
msg_queue_t *node = NULL;
int length = (int)len;
// uint8_t in_buffer[MQTT_BUF_SIZE];
uint8_t *in_buffer = (uint8_t *)pdata;
struct espconn *pesp_conn = arg; struct espconn *pesp_conn = arg;
if(pesp_conn == NULL) if(pesp_conn == NULL)
...@@ -164,111 +215,152 @@ static void mqtt_socket_received(void *arg, char *pdata, unsigned short len) ...@@ -164,111 +215,152 @@ static void mqtt_socket_received(void *arg, char *pdata, unsigned short len)
return; return;
READPACKET: READPACKET:
if(len > MQTT_BUF_SIZE && len <= 0) if(length > MQTT_BUF_SIZE || length <= 0)
return; return;
c_memcpy(mud->mqtt_state.in_buffer, pdata, len); // c_memcpy(in_buffer, pdata, length);
mud->mqtt_state.outbound_message = NULL; uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mqtt_message_t *temp_msg = NULL;
switch(mud->connState){ switch(mud->connState){
case MQTT_CONNECT_SENDING: case MQTT_CONNECT_SENDING:
if(mqtt_get_type(mud->mqtt_state.in_buffer) != MQTT_MSG_TYPE_CONNACK){ case MQTT_CONNECT_SENT:
if(mqtt_get_type(in_buffer) != MQTT_MSG_TYPE_CONNACK){
NODE_DBG("MQTT: Invalid packet\r\n"); NODE_DBG("MQTT: Invalid packet\r\n");
mud->connState = MQTT_INIT; mud->connState = MQTT_INIT;
if(mud->secure){ if(mud->secure)
espconn_secure_disconnect(pesp_conn); espconn_secure_disconnect(pesp_conn);
} else
else {
espconn_disconnect(pesp_conn); espconn_disconnect(pesp_conn);
}
} else { } else {
mud->connState = MQTT_DATA; mud->connState = MQTT_DATA;
NODE_DBG("MQTT: Connected\r\n"); NODE_DBG("MQTT: Connected\r\n");
if(mud->cb_connect_ref == LUA_NOREF) if(mud->cb_connect_ref == LUA_NOREF)
return; break;
if(mud->self_ref == LUA_NOREF) if(mud->self_ref == LUA_NOREF)
return; break;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_connect_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua break;
lua_call(gL, 1, 0); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
return; lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
lua_call(mud->L, 1, 0);
break;
} }
break; break;
case MQTT_DATA: case MQTT_DATA:
mud->mqtt_state.message_length_read = len; mud->mqtt_state.message_length_read = length;
mud->mqtt_state.message_length = mqtt_get_total_length(mud->mqtt_state.in_buffer, mud->mqtt_state.message_length_read); mud->mqtt_state.message_length = mqtt_get_total_length(in_buffer, mud->mqtt_state.message_length_read);
msg_type = mqtt_get_type(mud->mqtt_state.in_buffer); msg_type = mqtt_get_type(in_buffer);
msg_qos = mqtt_get_qos(mud->mqtt_state.in_buffer); msg_qos = mqtt_get_qos(in_buffer);
msg_id = mqtt_get_id(mud->mqtt_state.in_buffer, mud->mqtt_state.in_buffer_length); msg_id = mqtt_get_id(in_buffer, mud->mqtt_state.message_length);
msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
NODE_DBG("MQTT_DATA: type: %d, qos: %d, msg_id: %d, pending_id: %d\r\n", NODE_DBG("MQTT_DATA: type: %d, qos: %d, msg_id: %d, pending_id: %d\r\n",
msg_type, msg_type,
msg_qos, msg_qos,
msg_id, msg_id,
mud->mqtt_state.pending_msg_id); (pending_msg)?pending_msg->msg_id:0);
switch(msg_type) switch(msg_type)
{ {
case MQTT_MSG_TYPE_SUBACK: case MQTT_MSG_TYPE_SUBACK:
if(mud->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_SUBSCRIBE && mud->mqtt_state.pending_msg_id == msg_id) if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_SUBSCRIBE && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: Subscribe successful\r\n"); NODE_DBG("MQTT: Subscribe successful\r\n");
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if (mud->cb_suback_ref == LUA_NOREF) if (mud->cb_suback_ref == LUA_NOREF)
break; break;
if (mud->self_ref == LUA_NOREF) if (mud->self_ref == LUA_NOREF)
break; break;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_suback_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); break;
lua_call(gL, 1, 0); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref);
lua_call(mud->L, 1, 0);
}
break; break;
case MQTT_MSG_TYPE_UNSUBACK: case MQTT_MSG_TYPE_UNSUBACK:
if(mud->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && mud->mqtt_state.pending_msg_id == msg_id) if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: UnSubscribe successful\r\n"); NODE_DBG("MQTT: UnSubscribe successful\r\n");
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
}
break; break;
case MQTT_MSG_TYPE_PUBLISH: case MQTT_MSG_TYPE_PUBLISH:
if(msg_qos == 1) if(msg_qos == 1){
mud->mqtt_state.outbound_message = mqtt_msg_puback(&mud->mqtt_state.mqtt_connection, msg_id); temp_msg = mqtt_msg_puback(&mud->mqtt_state.mqtt_connection, msg_id);
else if(msg_qos == 2) node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
mud->mqtt_state.outbound_message = mqtt_msg_pubrec(&mud->mqtt_state.mqtt_connection, msg_id); msg_id, MQTT_MSG_TYPE_PUBACK, (int)mqtt_get_qos(temp_msg->data) );
}
deliver_publish(mud, mud->mqtt_state.in_buffer, mud->mqtt_state.message_length_read); else if(msg_qos == 2){
temp_msg = mqtt_msg_pubrec(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBREC, (int)mqtt_get_qos(temp_msg->data) );
}
if(msg_qos == 1 || msg_qos == 2){
NODE_DBG("MQTT: Queue response QoS: %d\r\n", msg_qos);
}
deliver_publish(mud, in_buffer, mud->mqtt_state.message_length);
break; break;
case MQTT_MSG_TYPE_PUBACK: case MQTT_MSG_TYPE_PUBACK:
if(mud->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && mud->mqtt_state.pending_msg_id == msg_id){ if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBLISH && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: Publish with QoS = 1 successful\r\n"); NODE_DBG("MQTT: Publish with QoS = 1 successful\r\n");
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if(mud->cb_puback_ref == LUA_NOREF) if(mud->cb_puback_ref == LUA_NOREF)
break; break;
if(mud->self_ref == LUA_NOREF) if(mud->self_ref == LUA_NOREF)
break; break;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_puback_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua break;
lua_call(gL, 1, 0); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
} }
break; break;
case MQTT_MSG_TYPE_PUBREC: case MQTT_MSG_TYPE_PUBREC:
mud->mqtt_state.outbound_message = mqtt_msg_pubrel(&mud->mqtt_state.mqtt_connection, msg_id); if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBLISH && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: Publish with QoS = 2 Received PUBREC\r\n");
// Note: actrually, should not destroy the msg until PUBCOMP is received.
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
temp_msg = mqtt_msg_pubrel(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBREL, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PUBREL\r\n"); NODE_DBG("MQTT: Response PUBREL\r\n");
}
break; break;
case MQTT_MSG_TYPE_PUBREL: case MQTT_MSG_TYPE_PUBREL:
mud->mqtt_state.outbound_message = mqtt_msg_pubcomp(&mud->mqtt_state.mqtt_connection, msg_id); if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBREC && pending_msg->msg_id == msg_id){
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
temp_msg = mqtt_msg_pubcomp(&mud->mqtt_state.mqtt_connection, msg_id);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PUBCOMP, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PUBCOMP\r\n"); NODE_DBG("MQTT: Response PUBCOMP\r\n");
}
break; break;
case MQTT_MSG_TYPE_PUBCOMP: case MQTT_MSG_TYPE_PUBCOMP:
if(mud->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && mud->mqtt_state.pending_msg_id == msg_id){ if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBREL && pending_msg->msg_id == msg_id){
NODE_DBG("MQTT: Publish with QoS = 2 successful\r\n"); NODE_DBG("MQTT: Publish with QoS = 2 successful\r\n");
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if(mud->cb_puback_ref == LUA_NOREF) if(mud->cb_puback_ref == LUA_NOREF)
break; break;
if(mud->self_ref == LUA_NOREF) if(mud->self_ref == LUA_NOREF)
break; break;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_puback_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua break;
lua_call(gL, 1, 0); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
} }
break; break;
case MQTT_MSG_TYPE_PINGREQ: case MQTT_MSG_TYPE_PINGREQ:
mud->mqtt_state.outbound_message = mqtt_msg_pingresp(&mud->mqtt_state.mqtt_connection); temp_msg = mqtt_msg_pingresp(&mud->mqtt_state.mqtt_connection);
node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_PINGRESP, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("MQTT: Response PINGRESP\r\n");
break; break;
case MQTT_MSG_TYPE_PINGRESP: case MQTT_MSG_TYPE_PINGRESP:
// Ignore // Ignore
NODE_DBG("MQTT: PINGRESP received\r\n");
break; break;
} }
// NOTE: this is done down here and not in the switch case above // NOTE: this is done down here and not in the switch case above
...@@ -277,11 +369,11 @@ READPACKET: ...@@ -277,11 +369,11 @@ READPACKET:
if(msg_type == MQTT_MSG_TYPE_PUBLISH) if(msg_type == MQTT_MSG_TYPE_PUBLISH)
{ {
len = mud->mqtt_state.message_length_read; length = mud->mqtt_state.message_length_read;
if(mud->mqtt_state.message_length < mud->mqtt_state.message_length_read) if(mud->mqtt_state.message_length < mud->mqtt_state.message_length_read)
{ {
len -= mud->mqtt_state.message_length; length -= mud->mqtt_state.message_length;
pdata += mud->mqtt_state.message_length; pdata += mud->mqtt_state.message_length;
NODE_DBG("Get another published message\r\n"); NODE_DBG("Get another published message\r\n");
...@@ -291,19 +383,23 @@ READPACKET: ...@@ -291,19 +383,23 @@ READPACKET:
break; break;
} }
if(mud->mqtt_state.outbound_message != NULL){ if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
if(mud->secure) mud->event_timeout = MQTT_SEND_TIMEOUT;
espconn_secure_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); NODE_DBG("Sent: %d\n", node->msg.length);
if( mud->secure )
espconn_secure_sent( pesp_conn, node->msg.data, node->msg.length );
else else
espconn_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); espconn_sent( pesp_conn, node->msg.data, node->msg.length );
mud->mqtt_state.outbound_message = NULL;
} }
mud->keep_alive_tick = 0;
NODE_DBG("receive, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_received.\n");
return; return;
} }
static void mqtt_socket_sent(void *arg) static void mqtt_socket_sent(void *arg)
{ {
// NODE_DBG("mqtt_socket_sent is called.\n"); NODE_DBG("enter mqtt_socket_sent.\n");
struct espconn *pesp_conn = arg; struct espconn *pesp_conn = arg;
if(pesp_conn == NULL) if(pesp_conn == NULL)
return; return;
...@@ -313,22 +409,42 @@ static void mqtt_socket_sent(void *arg) ...@@ -313,22 +409,42 @@ static void mqtt_socket_sent(void *arg)
if(!mud->connected) if(!mud->connected)
return; return;
// call mqtt_sent() // call mqtt_sent()
mud->send_timeout = 0; mud->event_timeout = 0;
if(mud->mqtt_state.pending_msg_type == MQTT_MSG_TYPE_PUBLISH && mud->mqtt_state.pending_publish_qos == 0) { mud->keep_alive_tick = 0;
if(mud->connState == MQTT_CONNECT_SENDING){
mud->connState = MQTT_CONNECT_SENT;
// MQTT_CONNECT not queued.
return;
}
NODE_DBG("sent1, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
// qos = 0, publish and forgot.
msg_queue_t *node = msg_peek(&(mud->mqtt_state.pending_msg_q));
if(node && node->msg_type == MQTT_MSG_TYPE_PUBLISH && node->publish_qos == 0) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
if(mud->cb_puback_ref == LUA_NOREF) if(mud->cb_puback_ref == LUA_NOREF)
return; return;
if(mud->self_ref == LUA_NOREF) if(mud->self_ref == LUA_NOREF)
return; return;
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->cb_puback_ref); if(mud->L == NULL)
lua_rawgeti(gL, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua return;
lua_call(gL, 1, 0); lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
} lua_rawgeti(mud->L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
lua_call(mud->L, 1, 0);
} else if(node && node->msg_type == MQTT_MSG_TYPE_PUBACK && node->publish_qos == 1) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
} else if(node && node->msg_type == MQTT_MSG_TYPE_PUBCOMP) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
} else if(node && node->msg_type == MQTT_MSG_TYPE_PINGREQ) {
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
}
NODE_DBG("sent2, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_sent.\n");
} }
static int mqtt_socket_client( lua_State* L );
static void mqtt_socket_connected(void *arg) static void mqtt_socket_connected(void *arg)
{ {
NODE_DBG("mqtt_socket_connected is called.\n"); NODE_DBG("enter mqtt_socket_connected.\n");
struct espconn *pesp_conn = arg; struct espconn *pesp_conn = arg;
if(pesp_conn == NULL) if(pesp_conn == NULL)
return; return;
...@@ -340,57 +456,113 @@ static void mqtt_socket_connected(void *arg) ...@@ -340,57 +456,113 @@ static void mqtt_socket_connected(void *arg)
espconn_regist_sentcb(pesp_conn, mqtt_socket_sent); espconn_regist_sentcb(pesp_conn, mqtt_socket_sent);
espconn_regist_disconcb(pesp_conn, mqtt_socket_disconnected); espconn_regist_disconcb(pesp_conn, mqtt_socket_disconnected);
uint8_t temp_buffer[MQTT_BUF_SIZE];
// call mqtt_connect() to start a mqtt connect stage. // call mqtt_connect() to start a mqtt connect stage.
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, mud->mqtt_state.out_buffer, mud->mqtt_state.out_buffer_length); mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mud->mqtt_state.outbound_message = mqtt_msg_connect(&mud->mqtt_state.mqtt_connection, mud->mqtt_state.connect_info); mqtt_message_t* temp_msg = mqtt_msg_connect(&mud->mqtt_state.mqtt_connection, mud->mqtt_state.connect_info);
NODE_DBG("Send MQTT connection infomation, data len: %d, d[0]=%d \r\n", mud->mqtt_state.outbound_message->length, mud->mqtt_state.outbound_message->data[0]); NODE_DBG("Send MQTT connection infomation, data len: %d, d[0]=%d \r\n", temp_msg->length, temp_msg->data[0]);
if(mud->secure){ mud->event_timeout = MQTT_SEND_TIMEOUT;
espconn_secure_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); // not queue this message. should send right now. or should enqueue this before head.
} if(mud->secure)
espconn_secure_sent(pesp_conn, temp_msg->data, temp_msg->length);
else else
{ espconn_sent(pesp_conn, temp_msg->data, temp_msg->length);
espconn_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); mud->keep_alive_tick = 0;
}
mud->mqtt_state.outbound_message = NULL;
mud->connState = MQTT_CONNECT_SENDING; mud->connState = MQTT_CONNECT_SENDING;
NODE_DBG("leave mqtt_socket_connected.\n");
return; return;
} }
void mqtt_socket_timer(void *arg) void mqtt_socket_timer(void *arg)
{ {
NODE_DBG("enter mqtt_socket_timer.\n");
lmqtt_userdata *mud = (lmqtt_userdata*) arg; lmqtt_userdata *mud = (lmqtt_userdata*) arg;
if(mud->connState == MQTT_DATA){ if(mud == NULL)
return;
if(mud->pesp_conn == NULL){
NODE_DBG("mud->pesp_conn is NULL.\n");
os_timer_disarm(&mud->mqttTimer);
return;
}
NODE_DBG("timer, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
if(mud->event_timeout > 0){
NODE_DBG("event_timeout: %d.\n", mud->event_timeout);
mud->event_timeout --;
if(mud->event_timeout > 0){
return;
} else {
NODE_DBG("event timeout. \n");
if(mud->connState == MQTT_DATA)
msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
// should remove the head of the queue and re-send with DUP = 1
// Not implemented yet.
}
}
if(mud->connState == MQTT_INIT){ // socket connect time out.
NODE_DBG("Can not connect to broker.\n");
// Never goes here.
} else if(mud->connState == MQTT_CONNECT_SENDING){ // MQTT_CONNECT send time out.
NODE_DBG("sSend MQTT_CONNECT failed.\n");
mud->connState = MQTT_INIT;
if(mud->secure)
espconn_secure_disconnect(mud->pesp_conn);
else
espconn_disconnect(mud->pesp_conn);
mud->keep_alive_tick = 0; // not need count anymore
} else if(mud->connState == MQTT_CONNECT_SENT){ // wait for CONACK time out.
NODE_DBG("MQTT_CONNECT failed.\n");
} else if(mud->connState == MQTT_DATA){
msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
if(pending_msg){
mud->event_timeout = MQTT_SEND_TIMEOUT;
if(mud->secure)
espconn_secure_sent(mud->pesp_conn, pending_msg->msg.data, pending_msg->msg.length);
else
espconn_sent(mud->pesp_conn, pending_msg->msg.data, pending_msg->msg.length);
mud->keep_alive_tick = 0;
NODE_DBG("id: %d - qos: %d, length: %d\n", pending_msg->msg_id, pending_msg->publish_qos, pending_msg->msg.length);
} else {
// no queued event.
mud->keep_alive_tick ++; mud->keep_alive_tick ++;
if(mud->keep_alive_tick > mud->mqtt_state.connect_info->keepalive){ if(mud->keep_alive_tick > mud->mqtt_state.connect_info->keepalive){
mud->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PINGREQ; mud->event_timeout = MQTT_SEND_TIMEOUT;
mud->send_timeout = MQTT_SEND_TIMEOUT; uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
NODE_DBG("\r\nMQTT: Send keepalive packet\r\n"); NODE_DBG("\r\nMQTT: Send keepalive packet\r\n");
mud->mqtt_state.outbound_message = mqtt_msg_pingreq(&mud->mqtt_state.mqtt_connection); mqtt_message_t* temp_msg = mqtt_msg_pingreq(&mud->mqtt_state.mqtt_connection);
msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
0, MQTT_MSG_TYPE_PINGREQ, (int)mqtt_get_qos(temp_msg->data) );
// only one message in queue, send immediately.
if(mud->secure) if(mud->secure)
espconn_secure_sent(mud->pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); espconn_secure_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
else else
espconn_sent(mud->pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); espconn_sent(mud->pesp_conn, temp_msg->data, temp_msg->length);
mud->keep_alive_tick = 0; mud->keep_alive_tick = 0;
} }
} }
if(mud->send_timeout > 0) }
mud->send_timeout --; NODE_DBG("leave mqtt_socket_timer.\n");
} }
// Lua: mqtt.Client(clientid, keepalive, user, pass) // Lua: mqtt.Client(clientid, keepalive, user, pass)
static int mqtt_socket_client( lua_State* L ) static int mqtt_socket_client( lua_State* L )
{ {
NODE_DBG("mqtt_socket_client is called.\n"); NODE_DBG("enter mqtt_socket_client.\n");
lmqtt_userdata *mud; lmqtt_userdata *mud;
char tempid[20] = {0}; char tempid[20] = {0};
c_sprintf(tempid, "%s%x", "NodeMCU_", system_get_chip_id() ); c_sprintf(tempid, "%s%x", "NodeMCU_", system_get_chip_id() );
NODE_DBG(tempid); NODE_DBG(tempid);
NODE_DBG("\n"); NODE_DBG("\n");
size_t il = c_strlen(tempid);
const char *clientId = tempid, *username = NULL, *password = NULL; const char *clientId = tempid, *username = NULL, *password = NULL;
size_t idl = c_strlen(tempid);
size_t unl = 0, pwl = 0;
int keepalive = 0;
int stack = 1; int stack = 1;
unsigned secure = 0; unsigned secure = 0;
int top = lua_gettop(L); int top = lua_gettop(L);
...@@ -398,6 +570,7 @@ static int mqtt_socket_client( lua_State* L ) ...@@ -398,6 +570,7 @@ static int mqtt_socket_client( lua_State* L )
// create a object // create a object
mud = (lmqtt_userdata *)lua_newuserdata(L, sizeof(lmqtt_userdata)); mud = (lmqtt_userdata *)lua_newuserdata(L, sizeof(lmqtt_userdata));
// pre-initialize it, in case of errors // pre-initialize it, in case of errors
mud->L = NULL;
mud->self_ref = LUA_NOREF; mud->self_ref = LUA_NOREF;
mud->cb_connect_ref = LUA_NOREF; mud->cb_connect_ref = LUA_NOREF;
mud->cb_disconnect_ref = LUA_NOREF; mud->cb_disconnect_ref = LUA_NOREF;
...@@ -409,8 +582,9 @@ static int mqtt_socket_client( lua_State* L ) ...@@ -409,8 +582,9 @@ static int mqtt_socket_client( lua_State* L )
mud->secure = 0; mud->secure = 0;
mud->keep_alive_tick = 0; mud->keep_alive_tick = 0;
mud->send_timeout = 0; mud->event_timeout = 0;
mud->connState = MQTT_INIT; mud->connState = MQTT_INIT;
mud->connected = false;
c_memset(&mud->mqttTimer, 0, sizeof(ETSTimer)); c_memset(&mud->mqttTimer, 0, sizeof(ETSTimer));
c_memset(&mud->mqtt_state, 0, sizeof(mqtt_state_t)); c_memset(&mud->mqtt_state, 0, sizeof(mqtt_state_t));
c_memset(&mud->connect_info, 0, sizeof(mqtt_connect_info_t)); c_memset(&mud->connect_info, 0, sizeof(mqtt_connect_info_t));
...@@ -419,87 +593,80 @@ static int mqtt_socket_client( lua_State* L ) ...@@ -419,87 +593,80 @@ static int mqtt_socket_client( lua_State* L )
luaL_getmetatable(L, "mqtt.socket"); luaL_getmetatable(L, "mqtt.socket");
lua_setmetatable(L, -2); lua_setmetatable(L, -2);
mud->L = L; // L for mqtt module.
if( lua_isstring(L,stack) ) // deal with the clientid string if( lua_isstring(L,stack) ) // deal with the clientid string
{ {
clientId = luaL_checklstring( L, stack, &il ); clientId = luaL_checklstring( L, stack, &idl );
stack++; stack++;
} }
// TODO: check the zalloc result.
mud->connect_info.client_id = (uint8_t *)c_zalloc(il+1);
if(!mud->connect_info.client_id){
return luaL_error(L, "not enough memory");
}
c_memcpy(mud->connect_info.client_id, clientId, il);
mud->connect_info.client_id[il] = 0;
mud->mqtt_state.in_buffer = (uint8_t *)c_zalloc(MQTT_BUF_SIZE);
if(!mud->mqtt_state.in_buffer){
return luaL_error(L, "not enough memory");
}
mud->mqtt_state.out_buffer = (uint8_t *)c_zalloc(MQTT_BUF_SIZE);
if(!mud->mqtt_state.out_buffer){
return luaL_error(L, "not enough memory");
}
mud->mqtt_state.in_buffer_length = MQTT_BUF_SIZE;
mud->mqtt_state.out_buffer_length = MQTT_BUF_SIZE;
mud->connState = MQTT_INIT;
mud->connect_info.clean_session = 1;
mud->connect_info.will_qos = 0;
mud->connect_info.will_retain = 0;
mud->keep_alive_tick = 0;
mud->connect_info.keepalive = 0;
mud->mqtt_state.connect_info = &mud->connect_info;
gL = L; // global L for mqtt module.
if(lua_isnumber( L, stack )) if(lua_isnumber( L, stack ))
{ {
mud->connect_info.keepalive = luaL_checkinteger( L, stack); keepalive = luaL_checkinteger( L, stack);
stack++; stack++;
} }
if(mud->connect_info.keepalive == 0){ if(keepalive == 0){
mud->connect_info.keepalive = MQTT_DEFAULT_KEEPALIVE; keepalive = MQTT_DEFAULT_KEEPALIVE;
return 1;
} }
if(lua_isstring( L, stack )){ if(lua_isstring( L, stack )){
username = luaL_checklstring( L, stack, &il ); username = luaL_checklstring( L, stack, &unl );
stack++; stack++;
} }
if(username == NULL) if(username == NULL)
il = 0; unl = 0;
NODE_DBG("lengh username: %d\r\n", il); NODE_DBG("lengh username: %d\r\n", unl);
mud->connect_info.username = (uint8_t *)c_zalloc(il + 1);
if(!mud->connect_info.username){
return luaL_error(L, "not enough memory");
}
c_memcpy(mud->connect_info.username, username, il);
mud->connect_info.username[il] = 0;
if(lua_isstring( L, stack )){ if(lua_isstring( L, stack )){
password = luaL_checklstring( L, stack, &il ); password = luaL_checklstring( L, stack, &pwl );
stack++; stack++;
} }
if(password == NULL) if(password == NULL)
il = 0; pwl = 0;
NODE_DBG("lengh password: %d\r\n", il); NODE_DBG("lengh password: %d\r\n", pwl);
mud->connect_info.password = (uint8_t *)c_zalloc(il + 1); // TODO: check the zalloc result.
if(!mud->connect_info.password){ mud->connect_info.client_id = (uint8_t *)c_zalloc(idl+1);
mud->connect_info.username = (uint8_t *)c_zalloc(unl + 1);
mud->connect_info.password = (uint8_t *)c_zalloc(pwl + 1);
if(!mud->connect_info.client_id || !mud->connect_info.username || !mud->connect_info.password){
if(mud->connect_info.client_id) {
c_free(mud->connect_info.client_id);
mud->connect_info.client_id = NULL;
}
if(mud->connect_info.username) {
c_free(mud->connect_info.username);
mud->connect_info.username = NULL;
}
if(mud->connect_info.password) {
c_free(mud->connect_info.password);
mud->connect_info.password = NULL;
}
return luaL_error(L, "not enough memory"); return luaL_error(L, "not enough memory");
} }
c_memcpy(mud->connect_info.password, password, il); c_memcpy(mud->connect_info.client_id, clientId, idl);
mud->connect_info.password[il] = 0; mud->connect_info.client_id[idl] = 0;
c_memcpy(mud->connect_info.username, username, unl);
mud->connect_info.username[unl] = 0;
c_memcpy(mud->connect_info.password, password, pwl);
mud->connect_info.password[pwl] = 0;
NODE_DBG("MQTT: Init info: %s, %s, %s\r\n", mud->connect_info.client_id, mud->connect_info.username, mud->connect_info.password); NODE_DBG("MQTT: Init info: %s, %s, %s\r\n", mud->connect_info.client_id, mud->connect_info.username, mud->connect_info.password);
mud->connect_info.clean_session = 1;
mud->connect_info.will_qos = 0;
mud->connect_info.will_retain = 0;
mud->connect_info.keepalive = keepalive;
mud->mqtt_state.pending_msg_q = NULL;
mud->mqtt_state.auto_reconnect = 0;
mud->mqtt_state.port = 1883;
mud->mqtt_state.connect_info = &mud->connect_info;
NODE_DBG("leave mqtt_socket_client.\n");
return 1; return 1;
} }
...@@ -508,7 +675,7 @@ static int mqtt_socket_client( lua_State* L ) ...@@ -508,7 +675,7 @@ static int mqtt_socket_client( lua_State* L )
// socket: unref everything // socket: unref everything
static int mqtt_delete( lua_State* L ) static int mqtt_delete( lua_State* L )
{ {
NODE_DBG("mqtt_delete is called.\n"); NODE_DBG("enter mqtt_delete.\n");
lmqtt_userdata *mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket"); lmqtt_userdata *mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
luaL_argcheck(L, mud, 1, "mqtt.socket expected"); luaL_argcheck(L, mud, 1, "mqtt.socket expected");
...@@ -518,7 +685,9 @@ static int mqtt_delete( lua_State* L ) ...@@ -518,7 +685,9 @@ static int mqtt_delete( lua_State* L )
} }
os_timer_disarm(&mud->mqttTimer); os_timer_disarm(&mud->mqttTimer);
mud->connected = 0; mud->connected = false;
// ---- alloc-ed in mqtt_socket_connect()
if(mud->pesp_conn){ // for client connected to tcp server, this should set NULL in disconnect cb if(mud->pesp_conn){ // for client connected to tcp server, this should set NULL in disconnect cb
mud->pesp_conn->reverse = NULL; mud->pesp_conn->reverse = NULL;
if(mud->pesp_conn->proto.tcp) if(mud->pesp_conn->proto.tcp)
...@@ -528,6 +697,7 @@ static int mqtt_delete( lua_State* L ) ...@@ -528,6 +697,7 @@ static int mqtt_delete( lua_State* L )
mud->pesp_conn = NULL; // for socket, it will free this when disconnected mud->pesp_conn = NULL; // for socket, it will free this when disconnected
} }
// ---- alloc-ed in mqtt_socket_lwt()
if(mud->connect_info.will_topic){ if(mud->connect_info.will_topic){
c_free(mud->connect_info.will_topic); c_free(mud->connect_info.will_topic);
mud->connect_info.will_topic = NULL; mud->connect_info.will_topic = NULL;
...@@ -537,7 +707,9 @@ static int mqtt_delete( lua_State* L ) ...@@ -537,7 +707,9 @@ static int mqtt_delete( lua_State* L )
c_free(mud->connect_info.will_message); c_free(mud->connect_info.will_message);
mud->connect_info.will_message = NULL; mud->connect_info.will_message = NULL;
} }
// ----
//--------- alloc-ed in mqtt_socket_client()
if(mud->connect_info.client_id){ if(mud->connect_info.client_id){
c_free(mud->connect_info.client_id); c_free(mud->connect_info.client_id);
mud->connect_info.client_id = NULL; mud->connect_info.client_id = NULL;
...@@ -550,14 +722,7 @@ static int mqtt_delete( lua_State* L ) ...@@ -550,14 +722,7 @@ static int mqtt_delete( lua_State* L )
c_free(mud->connect_info.password); c_free(mud->connect_info.password);
mud->connect_info.password = NULL; mud->connect_info.password = NULL;
} }
if(mud->mqtt_state.in_buffer){ // -------
c_free(mud->mqtt_state.in_buffer);
mud->mqtt_state.in_buffer = NULL;
}
if(mud->mqtt_state.out_buffer){
c_free(mud->mqtt_state.out_buffer);
mud->mqtt_state.out_buffer = NULL;
}
// free (unref) callback ref // free (unref) callback ref
if(LUA_NOREF!=mud->cb_connect_ref){ if(LUA_NOREF!=mud->cb_connect_ref){
...@@ -580,32 +745,35 @@ static int mqtt_delete( lua_State* L ) ...@@ -580,32 +745,35 @@ static int mqtt_delete( lua_State* L )
luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref); luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
mud->cb_puback_ref = LUA_NOREF; mud->cb_puback_ref = LUA_NOREF;
} }
lua_gc(gL, LUA_GCSTOP, 0); lua_gc(L, LUA_GCSTOP, 0);
if(LUA_NOREF!=mud->self_ref){ if(LUA_NOREF!=mud->self_ref){
luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref); luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
mud->self_ref = LUA_NOREF; mud->self_ref = LUA_NOREF;
} }
lua_gc(gL, LUA_GCRESTART, 0); lua_gc(L, LUA_GCRESTART, 0);
NODE_DBG("leave mqtt_delete.\n");
return 0; return 0;
} }
static void socket_connect(struct espconn *pesp_conn) static void socket_connect(struct espconn *pesp_conn)
{ {
NODE_DBG("enter socket_connect.\n");
if(pesp_conn == NULL) if(pesp_conn == NULL)
return; return;
lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse; lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
if(mud == NULL) if(mud == NULL)
return; return;
if(mud->secure){ mud->event_timeout = MQTT_CONNECT_TIMEOUT;
mud->connState = MQTT_INIT;
if(mud->secure)
espconn_secure_connect(pesp_conn); espconn_secure_connect(pesp_conn);
}
else else
{
espconn_connect(pesp_conn); espconn_connect(pesp_conn);
}
NODE_DBG("socket_connect is called.\n"); os_timer_arm(&mud->mqttTimer, 1000, 1);
NODE_DBG("leave socket_connect.\n");
} }
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg); static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg);
...@@ -613,7 +781,7 @@ static dns_reconn_count = 0; ...@@ -613,7 +781,7 @@ static dns_reconn_count = 0;
static ip_addr_t host_ip; // for dns static ip_addr_t host_ip; // for dns
static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
{ {
NODE_DBG("socket_dns_found is called.\n"); NODE_DBG("enter socket_dns_found.\n");
struct espconn *pesp_conn = arg; struct espconn *pesp_conn = arg;
if(pesp_conn == NULL){ if(pesp_conn == NULL){
NODE_DBG("pesp_conn null.\n"); NODE_DBG("pesp_conn null.\n");
...@@ -645,78 +813,20 @@ static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg) ...@@ -645,78 +813,20 @@ static void socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
NODE_DBG("\n"); NODE_DBG("\n");
socket_connect(pesp_conn); socket_connect(pesp_conn);
} }
NODE_DBG("leave socket_dns_found.\n");
} }
// Lua: mqtt:connect( host, port, secure, function(client) ) // Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client) )
static int mqtt_socket_lwt( lua_State* L )
{
uint8_t stack = 1;
size_t topicSize, il;
NODE_DBG("mqtt_socket_lwt.\n");
lmqtt_userdata *mud = NULL;
const char *lwtTopic, *lwtMsg;
uint8_t lwtQoS, lwtRetain;
mud = (lmqtt_userdata *)luaL_checkudata( L, stack, "mqtt.socket" );
luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
if(mud == NULL)
return 0;
stack++;
lwtTopic = luaL_checklstring( L, stack, &topicSize );
if (lwtTopic == NULL)
{
return luaL_error( L, "need lwt topic");
}
stack++;
lwtMsg = luaL_checklstring( L, stack, &il );
if (lwtMsg == NULL)
{
return luaL_error( L, "need lwt message");
}
mud->connect_info.will_topic = (uint8_t*) c_zalloc( topicSize + 1 );
if(!mud->connect_info.will_topic){
return luaL_error( L, "not enough memory");
}
c_memcpy(mud->connect_info.will_topic, lwtTopic, topicSize);
mud->connect_info.will_topic[topicSize] = 0;
mud->connect_info.will_message = (uint8_t*) c_zalloc( il + 1 );
if(!mud->connect_info.will_message){
return luaL_error( L, "not enough memory");
}
c_memcpy(mud->connect_info.will_message, lwtMsg, il);
mud->connect_info.will_message[il] = 0;
stack++;
mud->connect_info.will_qos = luaL_checkinteger( L, stack );
stack++;
mud->connect_info.will_retain = luaL_checkinteger( L, stack );
NODE_DBG("mqtt_socket_lwt: topic: %s, message: %s, qos: %d, retain: %d\n",
mud->connect_info.will_topic,
mud->connect_info.will_message,
mud->connect_info.will_qos,
mud->connect_info.will_retain);
return 0;
}
// Lua: mqtt:connect( host, port, secure, function(client) )
static int mqtt_socket_connect( lua_State* L ) static int mqtt_socket_connect( lua_State* L )
{ {
NODE_DBG("mqtt_socket_connect is called.\n"); NODE_DBG("enter mqtt_socket_connect.\n");
lmqtt_userdata *mud = NULL; lmqtt_userdata *mud = NULL;
unsigned port = 1883; unsigned port = 1883;
size_t il; size_t il;
ip_addr_t ipaddr; ip_addr_t ipaddr;
const char *domain; const char *domain;
int stack = 1; int stack = 1;
unsigned secure = 0; unsigned secure = 0, auto_reconnect = 0;
int top = lua_gettop(L); int top = lua_gettop(L);
mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket"); mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
...@@ -725,6 +835,10 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -725,6 +835,10 @@ static int mqtt_socket_connect( lua_State* L )
if(mud == NULL) if(mud == NULL)
return 0; return 0;
if(mud->connected){
return luaL_error(L, "already connected");
}
if(mud->pesp_conn){ //TODO: should I free tcp struct directly or ask user to call close()??? if(mud->pesp_conn){ //TODO: should I free tcp struct directly or ask user to call close()???
mud->pesp_conn->reverse = NULL; mud->pesp_conn->reverse = NULL;
if(mud->pesp_conn->proto.tcp) if(mud->pesp_conn->proto.tcp)
...@@ -750,7 +864,7 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -750,7 +864,7 @@ static int mqtt_socket_connect( lua_State* L )
pesp_conn->reverse = mud; pesp_conn->reverse = mud;
pesp_conn->type = ESPCONN_TCP; pesp_conn->type = ESPCONN_TCP;
pesp_conn->state = ESPCONN_NONE; pesp_conn->state = ESPCONN_NONE;
mud->connected = 0; mud->connected = false;
if( (stack<=top) && lua_isstring(L,stack) ) // deal with the domain string if( (stack<=top) && lua_isstring(L,stack) ) // deal with the domain string
{ {
...@@ -776,6 +890,7 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -776,6 +890,7 @@ static int mqtt_socket_connect( lua_State* L )
} }
pesp_conn->proto.tcp->remote_port = port; pesp_conn->proto.tcp->remote_port = port;
pesp_conn->proto.tcp->local_port = espconn_port(); pesp_conn->proto.tcp->local_port = espconn_port();
mud->mqtt_state.port = port;
if ( (stack<=top) && lua_isnumber(L, stack) ) if ( (stack<=top) && lua_isnumber(L, stack) )
{ {
...@@ -789,6 +904,18 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -789,6 +904,18 @@ static int mqtt_socket_connect( lua_State* L )
} }
mud->secure = secure; // save mud->secure = secure; // save
if ( (stack<=top) && lua_isnumber(L, stack) )
{
auto_reconnect = lua_tointeger(L, stack);
stack++;
if ( auto_reconnect != 0 && auto_reconnect != 1 ){
auto_reconnect = 0; // default to 0
}
} else {
auto_reconnect = 0; // default to 0
}
mud->mqtt_state.auto_reconnect = auto_reconnect;
// call back function when a connection is obtained, tcp only // call back function when a connection is obtained, tcp only
if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){ if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
lua_pushvalue(L, stack); // copy argument (func) to the top of stack lua_pushvalue(L, stack); // copy argument (func) to the top of stack
...@@ -806,6 +933,10 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -806,6 +933,10 @@ static int mqtt_socket_connect( lua_State* L )
espconn_regist_connectcb(pesp_conn, mqtt_socket_connected); espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected); espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);
os_timer_disarm(&mud->mqttTimer);
os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
// timer started in socket_connect()
if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0)) if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0))
{ {
host_ip.addr = 0; host_ip.addr = 0;
...@@ -819,10 +950,7 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -819,10 +950,7 @@ static int mqtt_socket_connect( lua_State* L )
socket_connect(pesp_conn); socket_connect(pesp_conn);
} }
os_timer_disarm(&mud->mqttTimer); NODE_DBG("leave mqtt_socket_connect.\n");
os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
os_timer_arm(&mud->mqttTimer, 1000, 1);
return 0; return 0;
} }
...@@ -830,7 +958,7 @@ static int mqtt_socket_connect( lua_State* L ) ...@@ -830,7 +958,7 @@ static int mqtt_socket_connect( lua_State* L )
// client disconnect and unref itself // client disconnect and unref itself
static int mqtt_socket_close( lua_State* L ) static int mqtt_socket_close( lua_State* L )
{ {
NODE_DBG("mqtt_socket_close is called.\n"); NODE_DBG("enter mqtt_socket_close.\n");
int i = 0; int i = 0;
lmqtt_userdata *mud = NULL; lmqtt_userdata *mud = NULL;
...@@ -843,6 +971,7 @@ static int mqtt_socket_close( lua_State* L ) ...@@ -843,6 +971,7 @@ static int mqtt_socket_close( lua_State* L )
return 0; return 0;
// call mqtt_disconnect() // call mqtt_disconnect()
mud->mqtt_state.auto_reconnect = 0; // stop auto reconnect.
if(mud->secure){ if(mud->secure){
if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port) if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
...@@ -853,13 +982,14 @@ static int mqtt_socket_close( lua_State* L ) ...@@ -853,13 +982,14 @@ static int mqtt_socket_close( lua_State* L )
if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port) if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
espconn_disconnect(mud->pesp_conn); espconn_disconnect(mud->pesp_conn);
} }
NODE_DBG("leave mqtt_socket_close.\n");
return 0; return 0;
} }
// Lua: mqtt:on( "method", function() ) // Lua: mqtt:on( "method", function() )
static int mqtt_socket_on( lua_State* L ) static int mqtt_socket_on( lua_State* L )
{ {
NODE_DBG("mqtt_on is called.\n"); NODE_DBG("enter mqtt_socket_on.\n");
lmqtt_userdata *mud; lmqtt_userdata *mud;
size_t sl; size_t sl;
...@@ -893,20 +1023,16 @@ static int mqtt_socket_on( lua_State* L ) ...@@ -893,20 +1023,16 @@ static int mqtt_socket_on( lua_State* L )
lua_pop(L, 1); lua_pop(L, 1);
return luaL_error( L, "method not supported" ); return luaL_error( L, "method not supported" );
} }
NODE_DBG("leave mqtt_socket_on.\n");
return 0; return 0;
} }
// Lua: mqtt:subscribe(topic, qos, function()) // Lua: bool = mqtt:subscribe(topic, qos, function())
static int mqtt_socket_subscribe( lua_State* L ) { static int mqtt_socket_subscribe( lua_State* L ) {
NODE_DBG("mqtt_socket_subscribe is called.\n"); NODE_DBG("enter mqtt_socket_subscribe.\n");
typedef struct SUB_STORAGE {
uint32_t length;
uint8_t *data;
struct SUB_STORAGE *next;
} SUB_STORAGE;
uint8_t stack = 1, qos = 0; uint8_t stack = 1, qos = 0;
uint16_t msg_id = 0;
const char *topic; const char *topic;
size_t il; size_t il;
lmqtt_userdata *mud; lmqtt_userdata *mud;
...@@ -915,133 +1041,145 @@ static int mqtt_socket_subscribe( lua_State* L ) { ...@@ -915,133 +1041,145 @@ static int mqtt_socket_subscribe( lua_State* L ) {
luaL_argcheck( L, mud, stack, "mqtt.socket expected" ); luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
stack++; stack++;
if( mud->send_timeout != 0 ) if(mud==NULL){
return luaL_error( L, "sending in process" ); NODE_DBG("userdata is nil.\n");
lua_pushboolean(L, 0);
return 1;
}
if(mud->pesp_conn == NULL){
NODE_DBG("mud->pesp_conn is NULL.\n");
lua_pushboolean(L, 0);
return 1;
}
if( !mud->connected ) if(!mud->connected){
return luaL_error( L, "not connected" ); luaL_error( L, "not connected" );
lua_pushboolean(L, 0);
return 1;
}
uint8_t temp_buffer[MQTT_BUF_SIZE];
mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mqtt_message_t *temp_msg = NULL;
if( lua_istable( L, stack ) ) { if( lua_istable( L, stack ) ) {
NODE_DBG("subscribe table\n"); NODE_DBG("subscribe table\n");
lua_pushnil( L ); /* first key */ lua_pushnil( L ); /* first key */
SUB_STORAGE *first, *last, *curr;
first = (SUB_STORAGE*) c_zalloc(sizeof(SUB_STORAGE));
if( first == NULL )
return luaL_error( L, "not enough memory" );
first->length = 0;
last = first;
first->next = NULL;
while( lua_next( L, stack ) != 0 ) {
curr = (SUB_STORAGE*) c_zalloc(sizeof(SUB_STORAGE));
if( curr == NULL ) uint8_t temp_buf[MQTT_BUF_SIZE];
return luaL_error( L, "not enough memory" ); uint32_t temp_pos = 0;
while( lua_next( L, stack ) != 0 ) {
topic = luaL_checkstring( L, -2 ); topic = luaL_checkstring( L, -2 );
qos = luaL_checkinteger( L, -1 ); qos = luaL_checkinteger( L, -1 );
mud->mqtt_state.outbound_message = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &mud->mqtt_state.pending_msg_id ); temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
NODE_DBG("topic: %s - qos: %d, length: %d\n", topic, qos, mud->mqtt_state.outbound_message->length); NODE_DBG("topic: %s - qos: %d, length: %d\n", topic, qos, temp_msg->length);
curr->data = (uint8_t*) c_zalloc(mud->mqtt_state.outbound_message->length);
if( curr->data == NULL )
return luaL_error( L, "not enough memory" );
c_memcpy( curr->data, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length );
curr->length = mud->mqtt_state.outbound_message->length;
curr->next = NULL;
last->next = curr;
last = curr;
lua_pop( L, 1 );
}
curr = first; if (temp_pos + temp_msg->length > MQTT_BUF_SIZE){
uint32_t ptr = 0; lua_pop(L, 1);
while( curr != NULL ) { break; // too long message for the outbuffer.
if( curr->length == 0 ) {
curr = curr->next;
continue;
}
if( ptr + curr->length < mud->mqtt_state.out_buffer_length ) {
c_memcpy( mud->mqtt_state.out_buffer + ptr, curr->data, curr->length );
ptr += curr->length;
} }
c_free(curr->data); c_memcpy( temp_buf + temp_pos, temp_msg->data, temp_msg->length );
c_free(curr); temp_pos += temp_msg->length;
curr = curr->next;
lua_pop( L, 1 );
} }
c_free(first);
if( ptr == 0 ) { if (temp_pos == 0){
return luaL_error( L, "invalid data" ); luaL_error( L, "invalid data" );
lua_pushboolean(L, 0);
return 1;
} }
mud->mqtt_state.outbound_message->data = mud->mqtt_state.out_buffer;
mud->mqtt_state.outbound_message->length = ptr; c_memcpy( temp_buffer, temp_buf, temp_pos );
temp_msg->data = temp_buffer;
temp_msg->length = temp_pos;
stack++; stack++;
} else { } else {
NODE_DBG("subscribe string\n"); NODE_DBG("subscribe string\n");
topic = luaL_checklstring( L, stack, &il ); topic = luaL_checklstring( L, stack, &il );
stack++; stack++;
if( topic == NULL ) if( topic == NULL ){
return luaL_error( L, "need topic name" ); luaL_error( L, "need topic name" );
lua_pushboolean(L, 0);
return 1;
}
qos = luaL_checkinteger( L, stack ); qos = luaL_checkinteger( L, stack );
mud->mqtt_state.outbound_message = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &mud->mqtt_state.pending_msg_id ); temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
stack++; stack++;
} }
mud->send_timeout = MQTT_SEND_TIMEOUT; if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
mud->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_SUBSCRIBE;
mud->mqtt_state.pending_publish_qos = mqtt_get_qos( mud->mqtt_state.outbound_message->data );
if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) {
lua_pushvalue( L, stack ); // copy argument (func) to the top of stack lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
if( mud->cb_suback_ref != LUA_NOREF ) if( mud->cb_suback_ref != LUA_NOREF )
luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_suback_ref ); luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_suback_ref );
mud->cb_suback_ref = luaL_ref( L, LUA_REGISTRYINDEX ); mud->cb_suback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
} }
NODE_DBG("Sent: %d\n", mud->mqtt_state.outbound_message->length);
msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
msg_id, MQTT_MSG_TYPE_SUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", node->msg.length);
if( mud->secure ) if( mud->secure )
espconn_secure_sent( mud->pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length ); espconn_secure_sent( mud->pesp_conn, node->msg.data, node->msg.length );
else else
espconn_sent( mud->pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length ); espconn_sent( mud->pesp_conn, node->msg.data, node->msg.length );
mud->keep_alive_tick = 0;
}
return 0; if(!node){
lua_pushboolean(L, 0);
} else {
lua_pushboolean(L, 1); // enqueued succeed.
}
NODE_DBG("subscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_subscribe.\n");
return 1;
} }
// Lua: mqtt:publish( topic, payload, qos, retain, function() ) // Lua: bool = mqtt:publish( topic, payload, qos, retain, function() )
static int mqtt_socket_publish( lua_State* L ) static int mqtt_socket_publish( lua_State* L )
{ {
// NODE_DBG("mqtt_publish is called.\n"); NODE_DBG("enter mqtt_socket_publish.\n");
struct espconn *pesp_conn = NULL; struct espconn *pesp_conn = NULL;
lmqtt_userdata *mud; lmqtt_userdata *mud;
size_t l; size_t l;
uint8_t stack = 1; uint8_t stack = 1;
uint16_t msg_id = 0;
mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket"); mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
luaL_argcheck(L, mud, stack, "mqtt.socket expected"); luaL_argcheck(L, mud, stack, "mqtt.socket expected");
stack++; stack++;
if(mud==NULL){ if(mud==NULL){
NODE_DBG("userdata is nil.\n"); NODE_DBG("userdata is nil.\n");
return 0; lua_pushboolean(L, 0);
return 1;
} }
if(mud->pesp_conn == NULL){ if(mud->pesp_conn == NULL){
NODE_DBG("mud->pesp_conn is NULL.\n"); NODE_DBG("mud->pesp_conn is NULL.\n");
return 0; lua_pushboolean(L, 0);
return 1;
} }
if(mud->send_timeout != 0)
return luaL_error( L, "sending in process" ); if(!mud->connected){
pesp_conn = mud->pesp_conn; luaL_error( L, "not connected" );
lua_pushboolean(L, 0);
#if 0 return 1;
char temp[20] = {0}; }
c_sprintf(temp, IPSTR, IP2STR( &(pesp_conn->proto.tcp->remote_ip) ) );
NODE_DBG("remote ");
NODE_DBG(temp);
NODE_DBG(":");
NODE_DBG("%d",pesp_conn->proto.tcp->remote_port);
NODE_DBG(" sending data.\n");
#endif
const char *topic = luaL_checklstring( L, stack, &l ); const char *topic = luaL_checklstring( L, stack, &l );
stack ++; stack ++;
if (topic == NULL) if (topic == NULL){
return luaL_error( L, "need topic" ); luaL_error( L, "need topic" );
lua_pushboolean(L, 0);
return 1;
}
const char *payload = luaL_checklstring( L, stack, &l ); const char *payload = luaL_checklstring( L, stack, &l );
stack ++; stack ++;
...@@ -1050,14 +1188,13 @@ static int mqtt_socket_publish( lua_State* L ) ...@@ -1050,14 +1188,13 @@ static int mqtt_socket_publish( lua_State* L )
uint8_t retain = luaL_checkinteger( L, stack); uint8_t retain = luaL_checkinteger( L, stack);
stack ++; stack ++;
uint8_t temp_buffer[MQTT_BUF_SIZE];
mud->mqtt_state.outbound_message = mqtt_msg_publish(&mud->mqtt_state.mqtt_connection, mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
mqtt_message_t *temp_msg = mqtt_msg_publish(&mud->mqtt_state.mqtt_connection,
topic, payload, l, topic, payload, l,
qos, retain, qos, retain,
&mud->mqtt_state.pending_msg_id); &msg_id);
mud->mqtt_state.pending_msg_type = MQTT_MSG_TYPE_PUBLISH;
mud->mqtt_state.pending_publish_qos = qos;
mud->send_timeout = MQTT_SEND_TIMEOUT;
if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){ if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
lua_pushvalue(L, stack); // copy argument (func) to the top of stack lua_pushvalue(L, stack); // copy argument (func) to the top of stack
if(mud->cb_puback_ref != LUA_NOREF) if(mud->cb_puback_ref != LUA_NOREF)
...@@ -1065,11 +1202,105 @@ static int mqtt_socket_publish( lua_State* L ) ...@@ -1065,11 +1202,105 @@ static int mqtt_socket_publish( lua_State* L )
mud->cb_puback_ref = luaL_ref(L, LUA_REGISTRYINDEX); mud->cb_puback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
} }
if(mud->secure) msg_queue_t *node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
espconn_secure_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); msg_id, MQTT_MSG_TYPE_PUBLISH, (int)qos );
if(node && (1==msg_size(&(mud->mqtt_state.pending_msg_q))) && mud->event_timeout == 0){
mud->event_timeout = MQTT_SEND_TIMEOUT;
NODE_DBG("Sent: %d\n", node->msg.length);
if( mud->secure )
espconn_secure_sent( mud->pesp_conn, node->msg.data, node->msg.length );
else else
espconn_sent(pesp_conn, mud->mqtt_state.outbound_message->data, mud->mqtt_state.outbound_message->length); espconn_sent( mud->pesp_conn, node->msg.data, node->msg.length );
mud->mqtt_state.outbound_message = NULL; mud->keep_alive_tick = 0;
}
if(!node){
lua_pushboolean(L, 0);
} else {
lua_pushboolean(L, 1); // enqueued succeed.
}
NODE_DBG("publish, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
NODE_DBG("leave mqtt_socket_publish.\n");
return 1;
}
// Lua: mqtt:lwt( topic, message, qos, retain, function(client) )
static int mqtt_socket_lwt( lua_State* L )
{
NODE_DBG("enter mqtt_socket_lwt.\n");
uint8_t stack = 1;
size_t topicSize, msgSize;
NODE_DBG("mqtt_socket_lwt.\n");
lmqtt_userdata *mud = NULL;
const char *lwtTopic, *lwtMsg;
uint8_t lwtQoS, lwtRetain;
mud = (lmqtt_userdata *)luaL_checkudata( L, stack, "mqtt.socket" );
luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
if(mud == NULL)
return 0;
stack++;
lwtTopic = luaL_checklstring( L, stack, &topicSize );
if (lwtTopic == NULL)
{
return luaL_error( L, "need lwt topic");
}
stack++;
lwtMsg = luaL_checklstring( L, stack, &msgSize );
if (lwtMsg == NULL)
{
return luaL_error( L, "need lwt message");
}
if(mud->connect_info.will_topic){ // free the previous one if there is any
c_free(mud->connect_info.will_topic);
mud->connect_info.will_topic = NULL;
}
if(mud->connect_info.will_message){
c_free(mud->connect_info.will_message);
mud->connect_info.will_message = NULL;
}
mud->connect_info.will_topic = (uint8_t*) c_zalloc( topicSize + 1 );
mud->connect_info.will_message = (uint8_t*) c_zalloc( msgSize + 1 );
if(!mud->connect_info.will_topic || !mud->connect_info.will_message){
if(mud->connect_info.will_topic){
c_free(mud->connect_info.will_topic);
mud->connect_info.will_topic = NULL;
}
if(mud->connect_info.will_message){
c_free(mud->connect_info.will_message);
mud->connect_info.will_message = NULL;
}
return luaL_error( L, "not enough memory");
}
c_memcpy(mud->connect_info.will_topic, lwtTopic, topicSize);
mud->connect_info.will_topic[topicSize] = 0;
c_memcpy(mud->connect_info.will_message, lwtMsg, msgSize);
mud->connect_info.will_message[msgSize] = 0;
if ( lua_isnumber(L, stack) )
{
mud->connect_info.will_qos = lua_tointeger(L, stack);
stack++;
}
if ( lua_isnumber(L, stack) )
{
mud->connect_info.will_retain = lua_tointeger(L, stack);
stack++;
}
NODE_DBG("mqtt_socket_lwt: topic: %s, message: %s, qos: %d, retain: %d\n",
mud->connect_info.will_topic,
mud->connect_info.will_message,
mud->connect_info.will_qos,
mud->connect_info.will_retain);
NODE_DBG("leave mqtt_socket_lwt.\n");
return 0; return 0;
} }
...@@ -1079,11 +1310,11 @@ static int mqtt_socket_publish( lua_State* L ) ...@@ -1079,11 +1310,11 @@ static int mqtt_socket_publish( lua_State* L )
static const LUA_REG_TYPE mqtt_socket_map[] = static const LUA_REG_TYPE mqtt_socket_map[] =
{ {
{ LSTRKEY( "lwt" ), LFUNCVAL ( mqtt_socket_lwt ) },
{ LSTRKEY( "connect" ), LFUNCVAL ( mqtt_socket_connect ) }, { LSTRKEY( "connect" ), LFUNCVAL ( mqtt_socket_connect ) },
{ LSTRKEY( "close" ), LFUNCVAL ( mqtt_socket_close ) }, { LSTRKEY( "close" ), LFUNCVAL ( mqtt_socket_close ) },
{ LSTRKEY( "publish" ), LFUNCVAL ( mqtt_socket_publish ) }, { LSTRKEY( "publish" ), LFUNCVAL ( mqtt_socket_publish ) },
{ LSTRKEY( "subscribe" ), LFUNCVAL ( mqtt_socket_subscribe ) }, { LSTRKEY( "subscribe" ), LFUNCVAL ( mqtt_socket_subscribe ) },
{ LSTRKEY( "lwt" ), LFUNCVAL ( mqtt_socket_lwt ) },
{ LSTRKEY( "on" ), LFUNCVAL ( mqtt_socket_on ) }, { LSTRKEY( "on" ), LFUNCVAL ( mqtt_socket_on ) },
{ LSTRKEY( "__gc" ), LFUNCVAL ( mqtt_delete ) }, { LSTRKEY( "__gc" ), LFUNCVAL ( mqtt_delete ) },
#if LUA_OPTIMIZE_MEMORY > 0 #if LUA_OPTIMIZE_MEMORY > 0
......
...@@ -100,14 +100,15 @@ static int node_chipid( lua_State* L ) ...@@ -100,14 +100,15 @@ static int node_chipid( lua_State* L )
lua_pushinteger(L, id); lua_pushinteger(L, id);
return 1; return 1;
} }
// deprecated, moved to adc module
// Lua: readvdd33() // Lua: readvdd33()
static int node_readvdd33( lua_State* L ) // static int node_readvdd33( lua_State* L )
{ // {
// uint32_t vdd33 = system_get_vdd33(); // uint32_t vdd33 = readvdd33();
uint32_t vdd33 = readvdd33(); // lua_pushinteger(L, vdd33);
lua_pushinteger(L, vdd33); // return 1;
return 1; // }
}
// Lua: flashid() // Lua: flashid()
static int node_flashid( lua_State* L ) static int node_flashid( lua_State* L )
...@@ -431,7 +432,8 @@ const LUA_REG_TYPE node_map[] = ...@@ -431,7 +432,8 @@ const LUA_REG_TYPE node_map[] =
#endif #endif
{ LSTRKEY( "input" ), LFUNCVAL( node_input ) }, { LSTRKEY( "input" ), LFUNCVAL( node_input ) },
{ LSTRKEY( "output" ), LFUNCVAL( node_output ) }, { LSTRKEY( "output" ), LFUNCVAL( node_output ) },
{ LSTRKEY( "readvdd33" ), LFUNCVAL( node_readvdd33) }, // Moved to adc module, use adc.readvdd33()
// { LSTRKEY( "readvdd33" ), LFUNCVAL( node_readvdd33) },
{ LSTRKEY( "compile" ), LFUNCVAL( node_compile) }, { LSTRKEY( "compile" ), LFUNCVAL( node_compile) },
{ LSTRKEY( "CPU80MHZ" ), LNUMVAL( CPU80MHZ ) }, { LSTRKEY( "CPU80MHZ" ), LNUMVAL( CPU80MHZ ) },
{ LSTRKEY( "CPU160MHZ" ), LNUMVAL( CPU160MHZ ) }, { LSTRKEY( "CPU160MHZ" ), LNUMVAL( CPU160MHZ ) },
......
...@@ -167,8 +167,8 @@ static int wifi_getmode( lua_State* L ) ...@@ -167,8 +167,8 @@ static int wifi_getmode( lua_State* L )
/** /**
* wifi.setphymode() * wifi.setphymode()
* Description: * Description:
* Set wifi physical mode802.11 b/g/n * Set wifi physical mode802.11 b/g/n
* Note SoftAP only supports 802.11 b/g. * Note SoftAP only supports 802.11 b/g.
* Syntax: * Syntax:
* wifi.setphymode(mode) * wifi.setphymode(mode)
* Parameters: * Parameters:
...@@ -197,7 +197,7 @@ static int wifi_setphymode( lua_State* L ) ...@@ -197,7 +197,7 @@ static int wifi_setphymode( lua_State* L )
/** /**
* wifi.getphymode() * wifi.getphymode()
* Description: * Description:
* Get wifi physical mode802.11 b/g/n * Get wifi physical mode802.11 b/g/n
* Syntax: * Syntax:
* wifi.getphymode() * wifi.getphymode()
* Parameters: * Parameters:
...@@ -456,8 +456,8 @@ static int wifi_station_config( lua_State* L ) ...@@ -456,8 +456,8 @@ static int wifi_station_config( lua_State* L )
if (sl>32 || ssid == NULL) if (sl>32 || ssid == NULL)
return luaL_error( L, "ssid:<32" ); return luaL_error( L, "ssid:<32" );
const char *password = luaL_checklstring( L, 2, &pl ); const char *password = luaL_checklstring( L, 2, &pl );
if (pl<8 || pl>64 || password == NULL) if (pl!=0 && (pl<8 || pl>64) || password == NULL)
return luaL_error( L, "pwd:8~64" ); return luaL_error( L, "pwd:0,8~64" );
if(lua_isnumber(L, 3)) if(lua_isnumber(L, 3))
{ {
......
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
#include "platform.h" #include "platform.h"
#include "auxmods.h" #include "auxmods.h"
#include "lrotable.h" #include "lrotable.h"
#include "c_stdlib.h"
#include "c_string.h"
/** /**
* All this code is mostly from http://www.esp8266.com/viewtopic.php?f=21&t=1143&sid=a620a377672cfe9f666d672398415fcb * All this code is mostly from http://www.esp8266.com/viewtopic.php?f=21&t=1143&sid=a620a377672cfe9f666d672398415fcb
* from user Markus Gritsch. * from user Markus Gritsch.
...@@ -35,7 +37,10 @@ static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L) ...@@ -35,7 +37,10 @@ static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L)
{ {
const uint8_t pin = luaL_checkinteger(L, 1); const uint8_t pin = luaL_checkinteger(L, 1);
size_t length; size_t length;
char *buffer = (char *)luaL_checklstring(L, 2, &length); // Cast away the constness. const char *rgb = luaL_checklstring(L, 2, &length);
// dont modify lua-internal lstring - make a copy instead
char *buffer = (char *)c_malloc(length);
c_memcpy(buffer, rgb, length);
// Initialize the output pin: // Initialize the output pin:
platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT); platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_FLOAT);
...@@ -59,17 +64,17 @@ static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L) ...@@ -59,17 +64,17 @@ static int ICACHE_FLASH_ATTR ws2812_writergb(lua_State* L)
// Send the buffer: // Send the buffer:
os_intr_lock(); os_intr_lock();
const char * const end = buffer + length; for (i = 0; i < length; i++) {
while (buffer != end) {
uint8_t mask = 0x80; uint8_t mask = 0x80;
while (mask) { while (mask) {
(*buffer & mask) ? send_ws_1(pin_num[pin]) : send_ws_0(pin_num[pin]); (buffer[i] & mask) ? send_ws_1(pin_num[pin]) : send_ws_0(pin_num[pin]);
mask >>= 1; mask >>= 1;
} }
++buffer;
} }
os_intr_unlock(); os_intr_unlock();
c_free(buffer);
return 0; return 0;
} }
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
* *
*/ */
#include <string.h> #include "c_string.h"
#include "mqtt_msg.h" #include "mqtt_msg.h"
#define MQTT_MAX_FIXED_HEADER_SIZE 3 #define MQTT_MAX_FIXED_HEADER_SIZE 3
...@@ -61,7 +61,7 @@ static int append_string(mqtt_connection_t* connection, const char* string, int ...@@ -61,7 +61,7 @@ static int append_string(mqtt_connection_t* connection, const char* string, int
connection->buffer[connection->message.length++] = len >> 8; connection->buffer[connection->message.length++] = len >> 8;
connection->buffer[connection->message.length++] = len & 0xff; connection->buffer[connection->message.length++] = len & 0xff;
memcpy(connection->buffer + connection->message.length, string, len); c_memcpy(connection->buffer + connection->message.length, string, len);
connection->message.length += len; connection->message.length += len;
return len + 2; return len + 2;
...@@ -121,7 +121,7 @@ static mqtt_message_t* fini_message(mqtt_connection_t* connection, int type, int ...@@ -121,7 +121,7 @@ static mqtt_message_t* fini_message(mqtt_connection_t* connection, int type, int
void mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length) void mqtt_msg_init(mqtt_connection_t* connection, uint8_t* buffer, uint16_t buffer_length)
{ {
memset(connection, 0, sizeof(connection)); c_memset(connection, 0, sizeof(connection));
connection->buffer = buffer; connection->buffer = buffer;
connection->buffer_length = buffer_length; connection->buffer_length = buffer_length;
} }
...@@ -294,7 +294,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf ...@@ -294,7 +294,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf
variable_header->lengthMsb = 0; variable_header->lengthMsb = 0;
variable_header->lengthLsb = 4; variable_header->lengthLsb = 4;
memcpy(variable_header->magic, "MQTT", 4); c_memcpy(variable_header->magic, "MQTT", 4);
variable_header->version = 4; variable_header->version = 4;
variable_header->flags = 0; variable_header->flags = 0;
variable_header->keepaliveMsb = info->keepalive >> 8; variable_header->keepaliveMsb = info->keepalive >> 8;
...@@ -305,7 +305,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf ...@@ -305,7 +305,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf
if(info->client_id != NULL && info->client_id[0] != '\0') if(info->client_id != NULL && info->client_id[0] != '\0')
{ {
if(append_string(connection, info->client_id, strlen(info->client_id)) < 0) if(append_string(connection, info->client_id, c_strlen(info->client_id)) < 0)
return fail_message(connection); return fail_message(connection);
} }
else else
...@@ -313,10 +313,10 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf ...@@ -313,10 +313,10 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf
if(info->will_topic != NULL && info->will_topic[0] != '\0') if(info->will_topic != NULL && info->will_topic[0] != '\0')
{ {
if(append_string(connection, info->will_topic, strlen(info->will_topic)) < 0) if(append_string(connection, info->will_topic, c_strlen(info->will_topic)) < 0)
return fail_message(connection); return fail_message(connection);
if(append_string(connection, info->will_message, strlen(info->will_message)) < 0) if(append_string(connection, info->will_message, c_strlen(info->will_message)) < 0)
return fail_message(connection); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_WILL; variable_header->flags |= MQTT_CONNECT_FLAG_WILL;
...@@ -327,7 +327,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf ...@@ -327,7 +327,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf
if(info->username != NULL && info->username[0] != '\0') if(info->username != NULL && info->username[0] != '\0')
{ {
if(append_string(connection, info->username, strlen(info->username)) < 0) if(append_string(connection, info->username, c_strlen(info->username)) < 0)
return fail_message(connection); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME; variable_header->flags |= MQTT_CONNECT_FLAG_USERNAME;
...@@ -335,7 +335,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf ...@@ -335,7 +335,7 @@ mqtt_message_t* mqtt_msg_connect(mqtt_connection_t* connection, mqtt_connect_inf
if(info->password != NULL && info->password[0] != '\0') if(info->password != NULL && info->password[0] != '\0')
{ {
if(append_string(connection, info->password, strlen(info->password)) < 0) if(append_string(connection, info->password, c_strlen(info->password)) < 0)
return fail_message(connection); return fail_message(connection);
variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD; variable_header->flags |= MQTT_CONNECT_FLAG_PASSWORD;
...@@ -351,7 +351,7 @@ mqtt_message_t* mqtt_msg_publish(mqtt_connection_t* connection, const char* topi ...@@ -351,7 +351,7 @@ mqtt_message_t* mqtt_msg_publish(mqtt_connection_t* connection, const char* topi
if(topic == NULL || topic[0] == '\0') if(topic == NULL || topic[0] == '\0')
return fail_message(connection); return fail_message(connection);
if(append_string(connection, topic, strlen(topic)) < 0) if(append_string(connection, topic, c_strlen(topic)) < 0)
return fail_message(connection); return fail_message(connection);
if(qos > 0) if(qos > 0)
...@@ -364,7 +364,7 @@ mqtt_message_t* mqtt_msg_publish(mqtt_connection_t* connection, const char* topi ...@@ -364,7 +364,7 @@ mqtt_message_t* mqtt_msg_publish(mqtt_connection_t* connection, const char* topi
if(connection->message.length + data_length > connection->buffer_length) if(connection->message.length + data_length > connection->buffer_length)
return fail_message(connection); return fail_message(connection);
memcpy(connection->buffer + connection->message.length, data, data_length); c_memcpy(connection->buffer + connection->message.length, data, data_length);
connection->message.length += data_length; connection->message.length += data_length;
return fini_message(connection, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain); return fini_message(connection, MQTT_MSG_TYPE_PUBLISH, 0, qos, retain);
...@@ -412,7 +412,7 @@ mqtt_message_t* mqtt_msg_subscribe(mqtt_connection_t* connection, const char* to ...@@ -412,7 +412,7 @@ mqtt_message_t* mqtt_msg_subscribe(mqtt_connection_t* connection, const char* to
if((*message_id = append_message_id(connection, 0)) == 0) if((*message_id = append_message_id(connection, 0)) == 0)
return fail_message(connection); return fail_message(connection);
if(append_string(connection, topic, strlen(topic)) < 0) if(append_string(connection, topic, c_strlen(topic)) < 0)
return fail_message(connection); return fail_message(connection);
if(connection->message.length + 1 > connection->buffer_length) if(connection->message.length + 1 > connection->buffer_length)
...@@ -432,7 +432,7 @@ mqtt_message_t* mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char* ...@@ -432,7 +432,7 @@ mqtt_message_t* mqtt_msg_unsubscribe(mqtt_connection_t* connection, const char*
if((*message_id = append_message_id(connection, 0)) == 0) if((*message_id = append_message_id(connection, 0)) == 0)
return fail_message(connection); return fail_message(connection);
if(append_string(connection, topic, strlen(topic)) < 0) if(append_string(connection, topic, c_strlen(topic)) < 0)
return fail_message(connection); return fail_message(connection);
return fini_message(connection, MQTT_MSG_TYPE_SUBSCRIBE, 0, 1, 0); return fini_message(connection, MQTT_MSG_TYPE_SUBSCRIBE, 0, 1, 0);
......
#include "c_string.h"
#include "c_stdlib.h"
#include "c_stdio.h"
#include "msg_queue.h"
msg_queue_t *msg_enqueue(msg_queue_t **head, mqtt_message_t *msg, uint16_t msg_id, int msg_type, int publish_qos){
if(!head){
return NULL;
}
if (!msg || !msg->data || msg->length == 0){
NODE_DBG("empty message\n");
return NULL;
}
msg_queue_t *node = (msg_queue_t *)c_zalloc(sizeof(msg_queue_t));
if(!node){
NODE_DBG("not enough memory\n");
return NULL;
}
node->msg.data = (uint8_t *)c_zalloc(msg->length);
if(!node->msg.data){
NODE_DBG("not enough memory\n");
c_free(node);
return NULL;
}
c_memcpy(node->msg.data, msg->data, msg->length);
node->msg.length = msg->length;
node->next = NULL;
node->msg_id = msg_id;
node->msg_type = msg_type;
node->publish_qos = publish_qos;
msg_queue_t *tail = *head;
if(tail){
while(tail->next!=NULL) tail = tail->next;
tail->next = node;
} else {
*head = node;
}
return node;
}
void msg_destroy(msg_queue_t *node){
if(!node) return;
if(node->msg.data){
c_free(node->msg.data);
node->msg.data = NULL;
}
c_free(node);
}
msg_queue_t * msg_dequeue(msg_queue_t **head){
if(!head || !*head){
return NULL;
}
msg_queue_t *node = *head; // fetch head.
*head = node->next; // update head.
node->next = NULL;
return node;
}
msg_queue_t * msg_peek(msg_queue_t **head){
if(!head || !*head){
return NULL;
}
return *head; // fetch head.
}
int msg_size(msg_queue_t **head){
if(!head || !*head){
return 0;
}
int i = 1;
msg_queue_t *tail = *head;
if(tail){
while(tail->next!=NULL){
tail = tail->next;
i++;
}
}
return i;
}
#ifndef _MSG_QUEUE_H
#define _MSG_QUEUE_H 1
#include "mqtt_msg.h"
#ifdef __cplusplus
extern "C" {
#endif
struct msg_queue_t;
typedef struct msg_queue_t {
struct msg_queue_t *next;
mqtt_message_t msg;
uint16_t msg_id;
int msg_type;
int publish_qos;
} msg_queue_t;
msg_queue_t * msg_enqueue(msg_queue_t **head, mqtt_message_t *msg, uint16_t msg_id, int msg_type, int publish_qos);
void msg_destroy(msg_queue_t *node);
msg_queue_t * msg_dequeue(msg_queue_t **head);
msg_queue_t * msg_peek(msg_queue_t **head);
int msg_size(msg_queue_t **head);
#ifdef __cplusplus
}
#endif
#endif
...@@ -321,7 +321,7 @@ bool flash_init_data_written(void) ...@@ -321,7 +321,7 @@ bool flash_init_data_written(void)
// FLASH SEC - 4 // FLASH SEC - 4
uint32_t data[2] ICACHE_STORE_ATTR; uint32_t data[2] ICACHE_STORE_ATTR;
#if defined(FLASH_SAFE_API) #if defined(FLASH_SAFE_API)
if (SPI_FLASH_RESULT_OK == flash_safe_read((flash_rom_get_sec_num() - 4) * SPI_FLASH_SEC_SIZE, (uint32 *)data, sizeof(data))) if (SPI_FLASH_RESULT_OK == flash_safe_read((flash_safe_get_sec_num() - 4) * SPI_FLASH_SEC_SIZE, (uint32 *)data, sizeof(data)))
#else #else
if (SPI_FLASH_RESULT_OK == spi_flash_read((flash_rom_get_sec_num() - 4) * SPI_FLASH_SEC_SIZE, (uint32 *)data, sizeof(data))) if (SPI_FLASH_RESULT_OK == spi_flash_read((flash_rom_get_sec_num() - 4) * SPI_FLASH_SEC_SIZE, (uint32 *)data, sizeof(data)))
#endif // defined(FLASH_SAFE_API) #endif // defined(FLASH_SAFE_API)
...@@ -369,8 +369,8 @@ bool flash_init_data_blank(void) ...@@ -369,8 +369,8 @@ bool flash_init_data_blank(void)
// It will init system config to blank! // It will init system config to blank!
bool result = false; bool result = false;
#if defined(FLASH_SAFE_API) #if defined(FLASH_SAFE_API)
if ((SPI_FLASH_RESULT_OK == flash_safe_erase_sector((flash_rom_get_sec_num() - 2))) && if ((SPI_FLASH_RESULT_OK == flash_safe_erase_sector((flash_safe_get_sec_num() - 2))) &&
(SPI_FLASH_RESULT_OK == flash_safe_erase_sector((flash_rom_get_sec_num() - 1)))) (SPI_FLASH_RESULT_OK == flash_safe_erase_sector((flash_safe_get_sec_num() - 1))))
#else #else
if ((SPI_FLASH_RESULT_OK == spi_flash_erase_sector((flash_rom_get_sec_num() - 2))) && if ((SPI_FLASH_RESULT_OK == spi_flash_erase_sector((flash_rom_get_sec_num() - 2))) &&
(SPI_FLASH_RESULT_OK == spi_flash_erase_sector((flash_rom_get_sec_num() - 1)))) (SPI_FLASH_RESULT_OK == spi_flash_erase_sector((flash_rom_get_sec_num() - 1))))
...@@ -396,11 +396,25 @@ uint8_t byte_of_aligned_array(const uint8_t *aligned_array, uint32_t index) ...@@ -396,11 +396,25 @@ uint8_t byte_of_aligned_array(const uint8_t *aligned_array, uint32_t index)
NODE_DBG("aligned_array is not 4-byte aligned.\n"); NODE_DBG("aligned_array is not 4-byte aligned.\n");
return 0; return 0;
} }
uint32_t v = ((uint32_t *)aligned_array)[ index / 4 ]; volatile uint32_t v = ((uint32_t *)aligned_array)[ index / 4 ];
uint8_t *p = (uint8_t *) (&v); uint8_t *p = (uint8_t *) (&v);
return p[ (index % 4) ]; return p[ (index % 4) ];
} }
uint16_t word_of_aligned_array(const uint16_t *aligned_array, uint32_t index)
{
if ( (((uint32_t)aligned_array) % 4) != 0 )
{
NODE_DBG("aligned_array is not 4-byte aligned.\n");
return 0;
}
volatile uint32_t v = ((uint32_t *)aligned_array)[ index / 2 ];
uint16_t *p = (uint16_t *) (&v);
return (index % 2 == 0) ? p[ 0 ] : p[ 1 ];
// return p[ (index % 2) ]; // -- why error???
// (byte_of_aligned_array((uint8_t *)aligned_array, index * 2 + 1) << 8) | byte_of_aligned_array((uint8_t *)aligned_array, index * 2);
}
// uint8_t flash_rom_get_checksum(void) // uint8_t flash_rom_get_checksum(void)
// { // {
// // SPIFlashInfo spi_flash_info ICACHE_STORE_ATTR = flash_rom_getinfo(); // // SPIFlashInfo spi_flash_info ICACHE_STORE_ATTR = flash_rom_getinfo();
......
...@@ -107,6 +107,7 @@ bool flash_init_data_default(void); ...@@ -107,6 +107,7 @@ bool flash_init_data_default(void);
bool flash_init_data_blank(void); bool flash_init_data_blank(void);
bool flash_self_destruct(void); bool flash_self_destruct(void);
uint8_t byte_of_aligned_array(const uint8_t* aligned_array, uint32_t index); uint8_t byte_of_aligned_array(const uint8_t* aligned_array, uint32_t index);
uint16_t word_of_aligned_array(const uint16_t *aligned_array, uint32_t index);
// uint8_t flash_rom_get_checksum(void); // uint8_t flash_rom_get_checksum(void);
// uint8_t flash_rom_calc_checksum(void); // uint8_t flash_rom_calc_checksum(void);
......
...@@ -71,6 +71,9 @@ ...@@ -71,6 +71,9 @@
#define fs_rename myspiffs_rename #define fs_rename myspiffs_rename
#define fs_size myspiffs_size #define fs_size myspiffs_size
#define fs_mount myspiffs_mount
#define fs_unmount myspiffs_unmount
#define FS_NAME_MAX_LENGTH SPIFFS_OBJ_NAME_LEN #define FS_NAME_MAX_LENGTH SPIFFS_OBJ_NAME_LEN
#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