mqtt.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. // Module for mqtt
  2. //
  3. #include "module.h"
  4. #include "lauxlib.h"
  5. #include "platform.h"
  6. #include "c_string.h"
  7. #include "c_stdlib.h"
  8. #include "c_types.h"
  9. #include "mem.h"
  10. #include "lwip/ip_addr.h"
  11. #include "espconn.h"
  12. #include "mqtt_msg.h"
  13. #include "msg_queue.h"
  14. #include "user_interface.h"
  15. #define MQTT_BUF_SIZE 1024
  16. #define MQTT_DEFAULT_KEEPALIVE 60
  17. #define MQTT_MAX_CLIENT_LEN 64
  18. #define MQTT_MAX_USER_LEN 64
  19. #define MQTT_MAX_PASS_LEN 64
  20. #define MQTT_SEND_TIMEOUT 5
  21. #define MQTT_CONNECT_TIMEOUT 5
  22. typedef enum {
  23. MQTT_INIT,
  24. MQTT_CONNECT_SENT,
  25. MQTT_CONNECT_SENDING,
  26. MQTT_DATA
  27. } tConnState;
  28. typedef struct mqtt_event_data_t
  29. {
  30. uint8_t type;
  31. const char* topic;
  32. const char* data;
  33. uint16_t topic_length;
  34. uint16_t data_length;
  35. uint16_t data_offset;
  36. } mqtt_event_data_t;
  37. #define RECONNECT_OFF 0
  38. #define RECONNECT_POSSIBLE 1
  39. #define RECONNECT_ON 2
  40. typedef struct mqtt_state_t
  41. {
  42. uint16_t port;
  43. uint8_t auto_reconnect; // 0 is not auto_reconnect. 1 is auto reconnect, but never connected. 2 is auto reconnect, but once connected
  44. mqtt_connect_info_t* connect_info;
  45. uint16_t message_length;
  46. uint16_t message_length_read;
  47. mqtt_connection_t mqtt_connection;
  48. msg_queue_t* pending_msg_q;
  49. } mqtt_state_t;
  50. typedef struct lmqtt_userdata
  51. {
  52. struct espconn *pesp_conn;
  53. int self_ref;
  54. int cb_connect_ref;
  55. int cb_connect_fail_ref;
  56. int cb_disconnect_ref;
  57. int cb_message_ref;
  58. int cb_suback_ref;
  59. int cb_unsuback_ref;
  60. int cb_puback_ref;
  61. mqtt_state_t mqtt_state;
  62. mqtt_connect_info_t connect_info;
  63. uint16_t keep_alive_tick;
  64. uint32_t event_timeout;
  65. #ifdef CLIENT_SSL_ENABLE
  66. uint8_t secure;
  67. #endif
  68. bool connected; // indicate socket connected, not mqtt prot connected.
  69. bool keepalive_sent;
  70. ETSTimer mqttTimer;
  71. tConnState connState;
  72. }lmqtt_userdata;
  73. static sint8 socket_connect(struct espconn *pesp_conn);
  74. static void mqtt_socket_reconnected(void *arg, sint8_t err);
  75. static void mqtt_socket_connected(void *arg);
  76. static void mqtt_connack_fail(lmqtt_userdata * mud, int reason_code);
  77. static void mqtt_socket_disconnected(void *arg) // tcp only
  78. {
  79. NODE_DBG("enter mqtt_socket_disconnected.\n");
  80. struct espconn *pesp_conn = arg;
  81. bool call_back = false;
  82. if(pesp_conn == NULL)
  83. return;
  84. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  85. if(mud == NULL)
  86. return;
  87. os_timer_disarm(&mud->mqttTimer);
  88. lua_State *L = lua_getstate();
  89. if(mud->connected){ // call back only called when socket is from connection to disconnection.
  90. mud->connected = false;
  91. if((mud->cb_disconnect_ref != LUA_NOREF) && (mud->self_ref != LUA_NOREF)) {
  92. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
  93. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
  94. call_back = true;
  95. }
  96. }
  97. if(mud->mqtt_state.auto_reconnect == RECONNECT_ON) {
  98. mud->pesp_conn->reverse = mud;
  99. mud->pesp_conn->type = ESPCONN_TCP;
  100. mud->pesp_conn->state = ESPCONN_NONE;
  101. mud->connected = false;
  102. mud->pesp_conn->proto.tcp->remote_port = mud->mqtt_state.port;
  103. mud->pesp_conn->proto.tcp->local_port = espconn_port();
  104. espconn_regist_connectcb(mud->pesp_conn, mqtt_socket_connected);
  105. espconn_regist_reconcb(mud->pesp_conn, mqtt_socket_reconnected);
  106. socket_connect(pesp_conn);
  107. } else {
  108. if(mud->pesp_conn){
  109. mud->pesp_conn->reverse = NULL;
  110. if(mud->pesp_conn->proto.tcp)
  111. c_free(mud->pesp_conn->proto.tcp);
  112. mud->pesp_conn->proto.tcp = NULL;
  113. c_free(mud->pesp_conn);
  114. mud->pesp_conn = NULL;
  115. }
  116. mud->connected = false;
  117. luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
  118. mud->self_ref = LUA_NOREF; // unref this, and the mqtt.socket userdata will delete it self
  119. }
  120. if(call_back){
  121. lua_call(L, 1, 0);
  122. }
  123. NODE_DBG("leave mqtt_socket_disconnected.\n");
  124. }
  125. static void mqtt_socket_reconnected(void *arg, sint8_t err)
  126. {
  127. NODE_DBG("enter mqtt_socket_reconnected.\n");
  128. // mqtt_socket_disconnected(arg);
  129. struct espconn *pesp_conn = arg;
  130. if(pesp_conn == NULL)
  131. return;
  132. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  133. if(mud == NULL)
  134. return;
  135. os_timer_disarm(&mud->mqttTimer);
  136. mud->event_timeout = 0; // no need to count anymore
  137. if(mud->mqtt_state.auto_reconnect == RECONNECT_ON) {
  138. pesp_conn->proto.tcp->remote_port = mud->mqtt_state.port;
  139. pesp_conn->proto.tcp->local_port = espconn_port();
  140. socket_connect(pesp_conn);
  141. } else {
  142. #ifdef CLIENT_SSL_ENABLE
  143. if (mud->secure) {
  144. espconn_secure_disconnect(pesp_conn);
  145. } else
  146. #endif
  147. {
  148. espconn_disconnect(pesp_conn);
  149. }
  150. mqtt_connack_fail(mud, MQTT_CONN_FAIL_SERVER_NOT_FOUND);
  151. mqtt_socket_disconnected(arg);
  152. }
  153. NODE_DBG("leave mqtt_socket_reconnected.\n");
  154. }
  155. static void deliver_publish(lmqtt_userdata * mud, uint8_t* message, int length)
  156. {
  157. NODE_DBG("enter deliver_publish.\n");
  158. if(mud == NULL)
  159. return;
  160. mqtt_event_data_t event_data;
  161. event_data.topic_length = length;
  162. event_data.topic = mqtt_get_publish_topic(message, &event_data.topic_length);
  163. event_data.data_length = length;
  164. event_data.data = mqtt_get_publish_data(message, &event_data.data_length);
  165. if(mud->cb_message_ref == LUA_NOREF)
  166. return;
  167. if(mud->self_ref == LUA_NOREF)
  168. return;
  169. lua_State *L = lua_getstate();
  170. if(event_data.topic && (event_data.topic_length > 0)){
  171. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
  172. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
  173. lua_pushlstring(L, event_data.topic, event_data.topic_length);
  174. } else {
  175. NODE_DBG("get wrong packet.\n");
  176. return;
  177. }
  178. if(event_data.data && (event_data.data_length > 0)){
  179. lua_pushlstring(L, event_data.data, event_data.data_length);
  180. lua_call(L, 3, 0);
  181. } else {
  182. lua_call(L, 2, 0);
  183. }
  184. NODE_DBG("leave deliver_publish.\n");
  185. }
  186. static void mqtt_connack_fail(lmqtt_userdata * mud, int reason_code)
  187. {
  188. if(mud->cb_connect_fail_ref == LUA_NOREF || mud->self_ref == LUA_NOREF)
  189. {
  190. return;
  191. }
  192. lua_State *L = lua_getstate();
  193. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
  194. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
  195. lua_pushinteger(L, reason_code);
  196. lua_call(L, 2, 0);
  197. }
  198. static sint8 mqtt_send_if_possible(struct espconn *pesp_conn)
  199. {
  200. if(pesp_conn == NULL)
  201. return ESPCONN_OK;
  202. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  203. if(mud == NULL)
  204. return ESPCONN_OK;
  205. sint8 espconn_status = ESPCONN_OK;
  206. // This indicates if we have sent something and are waiting for something to
  207. // happen
  208. if (mud->event_timeout == 0) {
  209. msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
  210. if (pending_msg) {
  211. mud->event_timeout = MQTT_SEND_TIMEOUT;
  212. NODE_DBG("Sent: %d\n", pending_msg->msg.length);
  213. #ifdef CLIENT_SSL_ENABLE
  214. if( mud->secure )
  215. {
  216. espconn_status = espconn_secure_send( pesp_conn, pending_msg->msg.data, pending_msg->msg.length );
  217. }
  218. else
  219. #endif
  220. {
  221. espconn_status = espconn_send( pesp_conn, pending_msg->msg.data, pending_msg->msg.length );
  222. }
  223. mud->keep_alive_tick = 0;
  224. }
  225. }
  226. NODE_DBG("send_if_poss, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  227. return espconn_status;
  228. }
  229. static void mqtt_socket_received(void *arg, char *pdata, unsigned short len)
  230. {
  231. NODE_DBG("enter mqtt_socket_received.\n");
  232. uint8_t msg_type;
  233. uint8_t msg_qos;
  234. uint16_t msg_id;
  235. int length = (int)len;
  236. // uint8_t in_buffer[MQTT_BUF_SIZE];
  237. uint8_t *in_buffer = (uint8_t *)pdata;
  238. struct espconn *pesp_conn = arg;
  239. if(pesp_conn == NULL)
  240. return;
  241. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  242. if(mud == NULL)
  243. return;
  244. READPACKET:
  245. if(length > MQTT_BUF_SIZE || length <= 0)
  246. return;
  247. // c_memcpy(in_buffer, pdata, length);
  248. uint8_t temp_buffer[MQTT_BUF_SIZE];
  249. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  250. mqtt_message_t *temp_msg = NULL;
  251. lua_State *L = lua_getstate();
  252. switch(mud->connState){
  253. case MQTT_CONNECT_SENDING:
  254. case MQTT_CONNECT_SENT:
  255. mud->event_timeout = 0;
  256. if(mqtt_get_type(in_buffer) != MQTT_MSG_TYPE_CONNACK){
  257. NODE_DBG("MQTT: Invalid packet\r\n");
  258. mud->connState = MQTT_INIT;
  259. #ifdef CLIENT_SSL_ENABLE
  260. if(mud->secure)
  261. {
  262. espconn_secure_disconnect(pesp_conn);
  263. }
  264. else
  265. #endif
  266. {
  267. espconn_disconnect(pesp_conn);
  268. }
  269. mqtt_connack_fail(mud, MQTT_CONN_FAIL_NOT_A_CONNACK_MSG);
  270. break;
  271. } else if (mqtt_get_connect_ret_code(in_buffer) != MQTT_CONNACK_ACCEPTED) {
  272. NODE_DBG("MQTT: CONNACK REFUSED (CODE: %d)\n", mqtt_get_connect_ret_code(in_buffer));
  273. mud->connState = MQTT_INIT;
  274. #ifdef CLIENT_SSL_ENABLE
  275. if(mud->secure)
  276. {
  277. espconn_secure_disconnect(pesp_conn);
  278. }
  279. else
  280. #endif
  281. {
  282. espconn_disconnect(pesp_conn);
  283. }
  284. mqtt_connack_fail(mud, mqtt_get_connect_ret_code(in_buffer));
  285. break;
  286. } else {
  287. mud->connState = MQTT_DATA;
  288. NODE_DBG("MQTT: Connected\r\n");
  289. mud->keepalive_sent = 0;
  290. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
  291. mud->cb_connect_fail_ref = LUA_NOREF;
  292. if (mud->mqtt_state.auto_reconnect == RECONNECT_POSSIBLE) {
  293. mud->mqtt_state.auto_reconnect = RECONNECT_ON;
  294. }
  295. if(mud->cb_connect_ref == LUA_NOREF)
  296. break;
  297. if(mud->self_ref == LUA_NOREF)
  298. break;
  299. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  300. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata(client) to callback func in lua
  301. lua_call(L, 1, 0);
  302. break;
  303. }
  304. break;
  305. case MQTT_DATA:
  306. mud->mqtt_state.message_length_read = length;
  307. mud->mqtt_state.message_length = mqtt_get_total_length(in_buffer, mud->mqtt_state.message_length_read);
  308. msg_type = mqtt_get_type(in_buffer);
  309. msg_qos = mqtt_get_qos(in_buffer);
  310. msg_id = mqtt_get_id(in_buffer, mud->mqtt_state.message_length);
  311. msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
  312. NODE_DBG("MQTT_DATA: type: %d, qos: %d, msg_id: %d, pending_id: %d\r\n",
  313. msg_type,
  314. msg_qos,
  315. msg_id,
  316. (pending_msg)?pending_msg->msg_id:0);
  317. switch(msg_type)
  318. {
  319. case MQTT_MSG_TYPE_SUBACK:
  320. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_SUBSCRIBE && pending_msg->msg_id == msg_id){
  321. NODE_DBG("MQTT: Subscribe successful\r\n");
  322. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  323. if (mud->cb_suback_ref == LUA_NOREF)
  324. break;
  325. if (mud->self_ref == LUA_NOREF)
  326. break;
  327. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
  328. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref);
  329. lua_call(L, 1, 0);
  330. }
  331. break;
  332. case MQTT_MSG_TYPE_UNSUBACK:
  333. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_UNSUBSCRIBE && pending_msg->msg_id == msg_id){
  334. NODE_DBG("MQTT: UnSubscribe successful\r\n");
  335. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  336. if (mud->cb_unsuback_ref == LUA_NOREF)
  337. break;
  338. if (mud->self_ref == LUA_NOREF)
  339. break;
  340. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref);
  341. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref);
  342. lua_call(L, 1, 0);
  343. }
  344. break;
  345. case MQTT_MSG_TYPE_PUBLISH:
  346. if(msg_qos == 1){
  347. temp_msg = mqtt_msg_puback(&mud->mqtt_state.mqtt_connection, msg_id);
  348. msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  349. msg_id, MQTT_MSG_TYPE_PUBACK, (int)mqtt_get_qos(temp_msg->data) );
  350. }
  351. else if(msg_qos == 2){
  352. temp_msg = mqtt_msg_pubrec(&mud->mqtt_state.mqtt_connection, msg_id);
  353. msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  354. msg_id, MQTT_MSG_TYPE_PUBREC, (int)mqtt_get_qos(temp_msg->data) );
  355. }
  356. if(msg_qos == 1 || msg_qos == 2){
  357. NODE_DBG("MQTT: Queue response QoS: %d\r\n", msg_qos);
  358. }
  359. deliver_publish(mud, in_buffer, mud->mqtt_state.message_length);
  360. break;
  361. case MQTT_MSG_TYPE_PUBACK:
  362. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBLISH && pending_msg->msg_id == msg_id){
  363. NODE_DBG("MQTT: Publish with QoS = 1 successful\r\n");
  364. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  365. if(mud->cb_puback_ref == LUA_NOREF)
  366. break;
  367. if(mud->self_ref == LUA_NOREF)
  368. break;
  369. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  370. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
  371. lua_call(L, 1, 0);
  372. }
  373. break;
  374. case MQTT_MSG_TYPE_PUBREC:
  375. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBLISH && pending_msg->msg_id == msg_id){
  376. NODE_DBG("MQTT: Publish with QoS = 2 Received PUBREC\r\n");
  377. // Note: actually, should not destroy the msg until PUBCOMP is received.
  378. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  379. temp_msg = mqtt_msg_pubrel(&mud->mqtt_state.mqtt_connection, msg_id);
  380. msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  381. msg_id, MQTT_MSG_TYPE_PUBREL, (int)mqtt_get_qos(temp_msg->data) );
  382. NODE_DBG("MQTT: Response PUBREL\r\n");
  383. }
  384. break;
  385. case MQTT_MSG_TYPE_PUBREL:
  386. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBREC && pending_msg->msg_id == msg_id){
  387. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  388. temp_msg = mqtt_msg_pubcomp(&mud->mqtt_state.mqtt_connection, msg_id);
  389. msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  390. msg_id, MQTT_MSG_TYPE_PUBCOMP, (int)mqtt_get_qos(temp_msg->data) );
  391. NODE_DBG("MQTT: Response PUBCOMP\r\n");
  392. }
  393. break;
  394. case MQTT_MSG_TYPE_PUBCOMP:
  395. if(pending_msg && pending_msg->msg_type == MQTT_MSG_TYPE_PUBREL && pending_msg->msg_id == msg_id){
  396. NODE_DBG("MQTT: Publish with QoS = 2 successful\r\n");
  397. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  398. if(mud->cb_puback_ref == LUA_NOREF)
  399. break;
  400. if(mud->self_ref == LUA_NOREF)
  401. break;
  402. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  403. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
  404. lua_call(L, 1, 0);
  405. }
  406. break;
  407. case MQTT_MSG_TYPE_PINGREQ:
  408. temp_msg = mqtt_msg_pingresp(&mud->mqtt_state.mqtt_connection);
  409. msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  410. msg_id, MQTT_MSG_TYPE_PINGRESP, (int)mqtt_get_qos(temp_msg->data) );
  411. NODE_DBG("MQTT: Response PINGRESP\r\n");
  412. break;
  413. case MQTT_MSG_TYPE_PINGRESP:
  414. // Ignore
  415. mud->keepalive_sent = 0;
  416. NODE_DBG("MQTT: PINGRESP received\r\n");
  417. break;
  418. }
  419. // NOTE: this is done down here and not in the switch case above
  420. // because the PSOCK_READBUF_LEN() won't work inside a switch
  421. // statement due to the way protothreads resume.
  422. if(msg_type == MQTT_MSG_TYPE_PUBLISH)
  423. {
  424. length = mud->mqtt_state.message_length_read;
  425. if(mud->mqtt_state.message_length < mud->mqtt_state.message_length_read)
  426. {
  427. length -= mud->mqtt_state.message_length;
  428. in_buffer += mud->mqtt_state.message_length;
  429. NODE_DBG("Get another published message\r\n");
  430. goto READPACKET;
  431. }
  432. }
  433. break;
  434. }
  435. mqtt_send_if_possible(pesp_conn);
  436. NODE_DBG("leave mqtt_socket_received.\n");
  437. return;
  438. }
  439. static void mqtt_socket_sent(void *arg)
  440. {
  441. NODE_DBG("enter mqtt_socket_sent.\n");
  442. struct espconn *pesp_conn = arg;
  443. if(pesp_conn == NULL)
  444. return;
  445. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  446. if(mud == NULL)
  447. return;
  448. if(!mud->connected)
  449. return;
  450. // call mqtt_sent()
  451. mud->event_timeout = 0;
  452. mud->keep_alive_tick = 0;
  453. if(mud->connState == MQTT_CONNECT_SENDING){
  454. mud->connState = MQTT_CONNECT_SENT;
  455. mud->event_timeout = MQTT_SEND_TIMEOUT;
  456. // MQTT_CONNECT not queued.
  457. return;
  458. }
  459. NODE_DBG("sent1, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  460. uint8_t try_send = 1;
  461. // qos = 0, publish and forgot.
  462. msg_queue_t *node = msg_peek(&(mud->mqtt_state.pending_msg_q));
  463. if(node && node->msg_type == MQTT_MSG_TYPE_PUBLISH && node->publish_qos == 0) {
  464. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  465. if(mud->cb_puback_ref != LUA_NOREF && mud->self_ref != LUA_NOREF) {
  466. lua_State *L = lua_getstate();
  467. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  468. lua_rawgeti(L, LUA_REGISTRYINDEX, mud->self_ref); // pass the userdata to callback func in lua
  469. lua_call(L, 1, 0);
  470. }
  471. } else if(node && node->msg_type == MQTT_MSG_TYPE_PUBACK) {
  472. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  473. } else if(node && node->msg_type == MQTT_MSG_TYPE_PUBCOMP) {
  474. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  475. } else if(node && node->msg_type == MQTT_MSG_TYPE_PINGREQ) {
  476. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  477. } else {
  478. try_send = 0;
  479. }
  480. if (try_send) {
  481. mqtt_send_if_possible(mud->pesp_conn);
  482. }
  483. NODE_DBG("sent2, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  484. NODE_DBG("leave mqtt_socket_sent.\n");
  485. }
  486. static void mqtt_socket_connected(void *arg)
  487. {
  488. NODE_DBG("enter mqtt_socket_connected.\n");
  489. struct espconn *pesp_conn = arg;
  490. if(pesp_conn == NULL)
  491. return;
  492. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  493. if(mud == NULL)
  494. return;
  495. mud->connected = true;
  496. espconn_regist_recvcb(pesp_conn, mqtt_socket_received);
  497. espconn_regist_sentcb(pesp_conn, mqtt_socket_sent);
  498. espconn_regist_disconcb(pesp_conn, mqtt_socket_disconnected);
  499. uint8_t temp_buffer[MQTT_BUF_SIZE];
  500. // call mqtt_connect() to start a mqtt connect stage.
  501. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  502. mqtt_message_t* temp_msg = mqtt_msg_connect(&mud->mqtt_state.mqtt_connection, mud->mqtt_state.connect_info);
  503. NODE_DBG("Send MQTT connection infomation, data len: %d, d[0]=%d \r\n", temp_msg->length, temp_msg->data[0]);
  504. mud->event_timeout = MQTT_SEND_TIMEOUT;
  505. // not queue this message. should send right now. or should enqueue this before head.
  506. #ifdef CLIENT_SSL_ENABLE
  507. if(mud->secure)
  508. {
  509. espconn_secure_send(pesp_conn, temp_msg->data, temp_msg->length);
  510. }
  511. else
  512. #endif
  513. {
  514. espconn_send(pesp_conn, temp_msg->data, temp_msg->length);
  515. }
  516. mud->keep_alive_tick = 0;
  517. mud->connState = MQTT_CONNECT_SENDING;
  518. NODE_DBG("leave mqtt_socket_connected.\n");
  519. return;
  520. }
  521. void mqtt_socket_timer(void *arg)
  522. {
  523. NODE_DBG("enter mqtt_socket_timer.\n");
  524. lmqtt_userdata *mud = (lmqtt_userdata*) arg;
  525. if(mud == NULL)
  526. return;
  527. if(mud->pesp_conn == NULL){
  528. NODE_DBG("mud->pesp_conn is NULL.\n");
  529. os_timer_disarm(&mud->mqttTimer);
  530. return;
  531. }
  532. NODE_DBG("timer, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  533. if(mud->event_timeout > 0){
  534. NODE_DBG("event_timeout: %d.\n", mud->event_timeout);
  535. mud->event_timeout --;
  536. if(mud->event_timeout > 0){
  537. return;
  538. } else {
  539. NODE_DBG("event timeout. \n");
  540. if(mud->connState == MQTT_DATA)
  541. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  542. // should remove the head of the queue and re-send with DUP = 1
  543. // Not implemented yet.
  544. }
  545. }
  546. if(mud->connState == MQTT_INIT){ // socket connect time out.
  547. NODE_DBG("Can not connect to broker.\n");
  548. os_timer_disarm(&mud->mqttTimer);
  549. mqtt_connack_fail(mud, MQTT_CONN_FAIL_SERVER_NOT_FOUND);
  550. #ifdef CLIENT_SSL_ENABLE
  551. if(mud->secure)
  552. {
  553. espconn_secure_disconnect(mud->pesp_conn);
  554. }
  555. else
  556. #endif
  557. {
  558. espconn_disconnect(mud->pesp_conn);
  559. }
  560. } else if(mud->connState == MQTT_CONNECT_SENDING){ // MQTT_CONNECT send time out.
  561. NODE_DBG("sSend MQTT_CONNECT failed.\n");
  562. mud->connState = MQTT_INIT;
  563. mqtt_connack_fail(mud, MQTT_CONN_FAIL_TIMEOUT_SENDING);
  564. #ifdef CLIENT_SSL_ENABLE
  565. if(mud->secure)
  566. {
  567. espconn_secure_disconnect(mud->pesp_conn);
  568. }
  569. else
  570. #endif
  571. {
  572. espconn_disconnect(mud->pesp_conn);
  573. }
  574. mud->keep_alive_tick = 0; // not need count anymore
  575. } else if(mud->connState == MQTT_CONNECT_SENT) { // wait for CONACK time out.
  576. NODE_DBG("MQTT_CONNECT timeout.\n");
  577. mud->connState = MQTT_INIT;
  578. #ifdef CLIENT_SSL_ENABLE
  579. if(mud->secure)
  580. {
  581. espconn_secure_disconnect(mud->pesp_conn);
  582. }
  583. else
  584. #endif
  585. {
  586. espconn_disconnect(mud->pesp_conn);
  587. }
  588. mqtt_connack_fail(mud, MQTT_CONN_FAIL_TIMEOUT_RECEIVING);
  589. } else if(mud->connState == MQTT_DATA){
  590. msg_queue_t *pending_msg = msg_peek(&(mud->mqtt_state.pending_msg_q));
  591. if(pending_msg){
  592. mqtt_send_if_possible(mud->pesp_conn);
  593. } else {
  594. // no queued event.
  595. mud->keep_alive_tick ++;
  596. if(mud->keep_alive_tick > mud->mqtt_state.connect_info->keepalive){
  597. if (mud->keepalive_sent) {
  598. // Oh dear -- keepalive timer expired and still no ack of previous message
  599. mqtt_socket_reconnected(mud->pesp_conn, 0);
  600. } else {
  601. uint8_t temp_buffer[MQTT_BUF_SIZE];
  602. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  603. NODE_DBG("\r\nMQTT: Send keepalive packet\r\n");
  604. mqtt_message_t* temp_msg = mqtt_msg_pingreq(&mud->mqtt_state.mqtt_connection);
  605. msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
  606. 0, MQTT_MSG_TYPE_PINGREQ, (int)mqtt_get_qos(temp_msg->data) );
  607. mud->keepalive_sent = 1;
  608. mud->keep_alive_tick = 0; // Need to reset to zero in case flow control stopped.
  609. mqtt_send_if_possible(mud->pesp_conn);
  610. }
  611. }
  612. }
  613. }
  614. NODE_DBG("keep_alive_tick: %d\n", mud->keep_alive_tick);
  615. NODE_DBG("leave mqtt_socket_timer.\n");
  616. }
  617. // Lua: mqtt.Client(clientid, keepalive, user, pass, clean_session)
  618. static int mqtt_socket_client( lua_State* L )
  619. {
  620. NODE_DBG("enter mqtt_socket_client.\n");
  621. lmqtt_userdata *mud;
  622. char tempid[20] = {0};
  623. c_sprintf(tempid, "%s%x", "NodeMCU_", system_get_chip_id() );
  624. NODE_DBG(tempid);
  625. NODE_DBG("\n");
  626. const char *clientId = tempid, *username = NULL, *password = NULL;
  627. size_t idl = c_strlen(tempid);
  628. size_t unl = 0, pwl = 0;
  629. int keepalive = 0;
  630. int stack = 1;
  631. int clean_session = 1;
  632. int top = lua_gettop(L);
  633. // create a object
  634. mud = (lmqtt_userdata *)lua_newuserdata(L, sizeof(lmqtt_userdata));
  635. c_memset(mud, 0, sizeof(*mud));
  636. // pre-initialize it, in case of errors
  637. mud->self_ref = LUA_NOREF;
  638. mud->cb_connect_ref = LUA_NOREF;
  639. mud->cb_connect_fail_ref = LUA_NOREF;
  640. mud->cb_disconnect_ref = LUA_NOREF;
  641. mud->cb_message_ref = LUA_NOREF;
  642. mud->cb_suback_ref = LUA_NOREF;
  643. mud->cb_unsuback_ref = LUA_NOREF;
  644. mud->cb_puback_ref = LUA_NOREF;
  645. mud->connState = MQTT_INIT;
  646. // set its metatable
  647. luaL_getmetatable(L, "mqtt.socket");
  648. lua_setmetatable(L, -2);
  649. if( lua_isstring(L,stack) ) // deal with the clientid string
  650. {
  651. clientId = luaL_checklstring( L, stack, &idl );
  652. stack++;
  653. }
  654. if(lua_isnumber( L, stack ))
  655. {
  656. keepalive = luaL_checkinteger( L, stack);
  657. stack++;
  658. }
  659. if(keepalive == 0){
  660. keepalive = MQTT_DEFAULT_KEEPALIVE;
  661. }
  662. if(lua_isstring( L, stack )){
  663. username = luaL_checklstring( L, stack, &unl );
  664. stack++;
  665. }
  666. if(username == NULL)
  667. unl = 0;
  668. NODE_DBG("length username: %d\r\n", unl);
  669. if(lua_isstring( L, stack )){
  670. password = luaL_checklstring( L, stack, &pwl );
  671. stack++;
  672. }
  673. if(password == NULL)
  674. pwl = 0;
  675. NODE_DBG("length password: %d\r\n", pwl);
  676. if(lua_isnumber( L, stack ))
  677. {
  678. clean_session = luaL_checkinteger( L, stack);
  679. stack++;
  680. }
  681. if(clean_session > 1){
  682. clean_session = 1;
  683. }
  684. // TODO: check the zalloc result.
  685. mud->connect_info.client_id = (uint8_t *)c_zalloc(idl+1);
  686. mud->connect_info.username = (uint8_t *)c_zalloc(unl + 1);
  687. mud->connect_info.password = (uint8_t *)c_zalloc(pwl + 1);
  688. if(!mud->connect_info.client_id || !mud->connect_info.username || !mud->connect_info.password){
  689. if(mud->connect_info.client_id) {
  690. c_free(mud->connect_info.client_id);
  691. mud->connect_info.client_id = NULL;
  692. }
  693. if(mud->connect_info.username) {
  694. c_free(mud->connect_info.username);
  695. mud->connect_info.username = NULL;
  696. }
  697. if(mud->connect_info.password) {
  698. c_free(mud->connect_info.password);
  699. mud->connect_info.password = NULL;
  700. }
  701. return luaL_error(L, "not enough memory");
  702. }
  703. c_memcpy(mud->connect_info.client_id, clientId, idl);
  704. mud->connect_info.client_id[idl] = 0;
  705. c_memcpy(mud->connect_info.username, username, unl);
  706. mud->connect_info.username[unl] = 0;
  707. c_memcpy(mud->connect_info.password, password, pwl);
  708. mud->connect_info.password[pwl] = 0;
  709. NODE_DBG("MQTT: Init info: %s, %s, %s\r\n", mud->connect_info.client_id, mud->connect_info.username, mud->connect_info.password);
  710. mud->connect_info.clean_session = clean_session;
  711. mud->connect_info.will_qos = 0;
  712. mud->connect_info.will_retain = 0;
  713. mud->connect_info.keepalive = keepalive;
  714. mud->mqtt_state.pending_msg_q = NULL;
  715. mud->mqtt_state.auto_reconnect = RECONNECT_OFF;
  716. mud->mqtt_state.port = 1883;
  717. mud->mqtt_state.connect_info = &mud->connect_info;
  718. NODE_DBG("leave mqtt_socket_client.\n");
  719. return 1;
  720. }
  721. // Lua: mqtt.delete( socket )
  722. // call close() first
  723. // socket: unref everything
  724. static int mqtt_delete( lua_State* L )
  725. {
  726. NODE_DBG("enter mqtt_delete.\n");
  727. lmqtt_userdata *mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  728. luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  729. if(mud==NULL){
  730. NODE_DBG("userdata is nil.\n");
  731. return 0;
  732. }
  733. os_timer_disarm(&mud->mqttTimer);
  734. mud->connected = false;
  735. // ---- alloc-ed in mqtt_socket_connect()
  736. if(mud->pesp_conn){ // for client connected to tcp server, this should set NULL in disconnect cb
  737. mud->pesp_conn->reverse = NULL;
  738. if(mud->pesp_conn->proto.tcp)
  739. c_free(mud->pesp_conn->proto.tcp);
  740. mud->pesp_conn->proto.tcp = NULL;
  741. c_free(mud->pesp_conn);
  742. mud->pesp_conn = NULL; // for socket, it will free this when disconnected
  743. }
  744. while(mud->mqtt_state.pending_msg_q) {
  745. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  746. }
  747. // ---- alloc-ed in mqtt_socket_lwt()
  748. if(mud->connect_info.will_topic){
  749. c_free(mud->connect_info.will_topic);
  750. mud->connect_info.will_topic = NULL;
  751. }
  752. if(mud->connect_info.will_message){
  753. c_free(mud->connect_info.will_message);
  754. mud->connect_info.will_message = NULL;
  755. }
  756. // ----
  757. //--------- alloc-ed in mqtt_socket_client()
  758. if(mud->connect_info.client_id){
  759. c_free(mud->connect_info.client_id);
  760. mud->connect_info.client_id = NULL;
  761. }
  762. if(mud->connect_info.username){
  763. c_free(mud->connect_info.username);
  764. mud->connect_info.username = NULL;
  765. }
  766. if(mud->connect_info.password){
  767. c_free(mud->connect_info.password);
  768. mud->connect_info.password = NULL;
  769. }
  770. // -------
  771. // free (unref) callback ref
  772. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  773. mud->cb_connect_ref = LUA_NOREF;
  774. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
  775. mud->cb_connect_fail_ref = LUA_NOREF;
  776. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
  777. mud->cb_disconnect_ref = LUA_NOREF;
  778. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
  779. mud->cb_message_ref = LUA_NOREF;
  780. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_suback_ref);
  781. mud->cb_suback_ref = LUA_NOREF;
  782. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref);
  783. mud->cb_unsuback_ref = LUA_NOREF;
  784. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  785. mud->cb_puback_ref = LUA_NOREF;
  786. lua_gc(L, LUA_GCSTOP, 0);
  787. luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
  788. mud->self_ref = LUA_NOREF;
  789. lua_gc(L, LUA_GCRESTART, 0);
  790. NODE_DBG("leave mqtt_delete.\n");
  791. return 0;
  792. }
  793. static sint8 socket_connect(struct espconn *pesp_conn)
  794. {
  795. NODE_DBG("enter socket_connect.\n");
  796. sint8 espconn_status;
  797. if(pesp_conn == NULL)
  798. return ESPCONN_CONN;
  799. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  800. if(mud == NULL)
  801. return ESPCONN_ARG;
  802. mud->event_timeout = MQTT_CONNECT_TIMEOUT;
  803. mud->connState = MQTT_INIT;
  804. #ifdef CLIENT_SSL_ENABLE
  805. if(mud->secure)
  806. {
  807. espconn_status = espconn_secure_connect(pesp_conn);
  808. }
  809. else
  810. #endif
  811. {
  812. espconn_status = espconn_connect(pesp_conn);
  813. }
  814. os_timer_arm(&mud->mqttTimer, 1000, 1);
  815. NODE_DBG("leave socket_connect, heap = %u.\n", system_get_free_heap_size());
  816. return espconn_status;
  817. }
  818. static sint8 socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg);
  819. static int dns_reconn_count = 0;
  820. static ip_addr_t host_ip; // for dns
  821. /* wrapper for using socket_dns_found() as callback function */
  822. static void socket_dns_foundcb(const char *name, ip_addr_t *ipaddr, void *arg)
  823. {
  824. socket_dns_found(name, ipaddr, arg);
  825. }
  826. static sint8 socket_dns_found(const char *name, ip_addr_t *ipaddr, void *arg)
  827. {
  828. NODE_DBG("enter socket_dns_found.\n");
  829. sint8 espconn_status = ESPCONN_OK;
  830. struct espconn *pesp_conn = arg;
  831. if(pesp_conn == NULL){
  832. NODE_DBG("pesp_conn null.\n");
  833. return -1;
  834. }
  835. if(ipaddr == NULL)
  836. {
  837. dns_reconn_count++;
  838. if( dns_reconn_count >= 5 ){
  839. NODE_DBG( "DNS Fail!\n" );
  840. // Note: should delete the pesp_conn or unref self_ref here.
  841. struct espconn *pesp_conn = arg;
  842. if(pesp_conn != NULL) {
  843. lmqtt_userdata *mud = (lmqtt_userdata *)pesp_conn->reverse;
  844. if(mud != NULL) {
  845. mqtt_connack_fail(mud, MQTT_CONN_FAIL_DNS);
  846. }
  847. }
  848. mqtt_socket_disconnected(arg); // although not connected, but fire disconnect callback to release every thing.
  849. return -1;
  850. }
  851. NODE_DBG( "DNS retry %d!\n", dns_reconn_count );
  852. host_ip.addr = 0;
  853. return espconn_gethostbyname(pesp_conn, name, &host_ip, socket_dns_foundcb);
  854. }
  855. // ipaddr->addr is a uint32_t ip
  856. if(ipaddr->addr != 0)
  857. {
  858. dns_reconn_count = 0;
  859. c_memcpy(pesp_conn->proto.tcp->remote_ip, &(ipaddr->addr), 4);
  860. NODE_DBG("TCP ip is set: ");
  861. NODE_DBG(IPSTR, IP2STR(&(ipaddr->addr)));
  862. NODE_DBG("\n");
  863. espconn_status = socket_connect(pesp_conn);
  864. }
  865. NODE_DBG("leave socket_dns_found.\n");
  866. return espconn_status;
  867. }
  868. // Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client), function(client, connect_return_code) )
  869. static int mqtt_socket_connect( lua_State* L )
  870. {
  871. NODE_DBG("enter mqtt_socket_connect.\n");
  872. lmqtt_userdata *mud = NULL;
  873. unsigned port = 1883;
  874. size_t il;
  875. ip_addr_t ipaddr;
  876. const char *domain;
  877. int stack = 1;
  878. unsigned secure = 0, auto_reconnect = RECONNECT_OFF;
  879. int top = lua_gettop(L);
  880. sint8 espconn_status;
  881. mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
  882. luaL_argcheck(L, mud, stack, "mqtt.socket expected");
  883. stack++;
  884. if(mud == NULL)
  885. return 0;
  886. if(mud->connected){
  887. return luaL_error(L, "already connected");
  888. }
  889. struct espconn *pesp_conn = mud->pesp_conn;
  890. if(!pesp_conn) {
  891. pesp_conn = mud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
  892. } else {
  893. espconn_delete(pesp_conn);
  894. }
  895. if(!pesp_conn)
  896. return luaL_error(L, "not enough memory");
  897. if (!pesp_conn->proto.tcp)
  898. pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp));
  899. if(!pesp_conn->proto.tcp){
  900. c_free(pesp_conn);
  901. pesp_conn = mud->pesp_conn = NULL;
  902. return luaL_error(L, "not enough memory");
  903. }
  904. // reverse is for the callback function
  905. pesp_conn->reverse = mud;
  906. pesp_conn->type = ESPCONN_TCP;
  907. pesp_conn->state = ESPCONN_NONE;
  908. mud->connected = false;
  909. if( (stack<=top) && lua_isstring(L,stack) ) // deal with the domain string
  910. {
  911. domain = luaL_checklstring( L, stack, &il );
  912. stack++;
  913. if (domain == NULL)
  914. {
  915. domain = "127.0.0.1";
  916. }
  917. ipaddr.addr = ipaddr_addr(domain);
  918. c_memcpy(pesp_conn->proto.tcp->remote_ip, &ipaddr.addr, 4);
  919. NODE_DBG("TCP ip is set: ");
  920. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  921. NODE_DBG("\n");
  922. }
  923. if ( (stack<=top) && lua_isnumber(L, stack) )
  924. {
  925. port = lua_tointeger(L, stack);
  926. stack++;
  927. NODE_DBG("TCP port is set: %d.\n", port);
  928. }
  929. pesp_conn->proto.tcp->remote_port = port;
  930. if (pesp_conn->proto.tcp->local_port == 0)
  931. pesp_conn->proto.tcp->local_port = espconn_port();
  932. mud->mqtt_state.port = port;
  933. if ( (stack<=top) && lua_isnumber(L, stack) )
  934. {
  935. secure = lua_tointeger(L, stack);
  936. stack++;
  937. if ( secure != 0 && secure != 1 ){
  938. secure = 0; // default to 0
  939. }
  940. } else {
  941. secure = 0; // default to 0
  942. }
  943. #ifdef CLIENT_SSL_ENABLE
  944. mud->secure = secure; // save
  945. #else
  946. if ( secure )
  947. {
  948. return luaL_error(L, "ssl not available");
  949. }
  950. #endif
  951. if ( (stack<=top) && lua_isnumber(L, stack) )
  952. {
  953. auto_reconnect = lua_tointeger(L, stack);
  954. if ( auto_reconnect == RECONNECT_POSSIBLE ) {
  955. platform_print_deprecation_note("autoreconnect == 1 is deprecated", "in the next version");
  956. }
  957. stack++;
  958. if ( auto_reconnect != RECONNECT_OFF && auto_reconnect != RECONNECT_POSSIBLE ){
  959. auto_reconnect = RECONNECT_OFF; // default to 0
  960. }
  961. } else {
  962. auto_reconnect = RECONNECT_OFF; // default to 0
  963. }
  964. mud->mqtt_state.auto_reconnect = auto_reconnect;
  965. // call back function when a connection is obtained, tcp only
  966. if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
  967. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  968. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  969. mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  970. }
  971. stack++;
  972. // call back function when a connection fails
  973. if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
  974. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  975. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
  976. mud->cb_connect_fail_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  977. stack++;
  978. }
  979. lua_pushvalue(L, 1); // copy userdata to the top of stack
  980. luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
  981. mud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  982. espconn_status = espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
  983. espconn_status |= espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);
  984. os_timer_disarm(&mud->mqttTimer);
  985. os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
  986. // timer started in socket_connect()
  987. if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0))
  988. {
  989. host_ip.addr = 0;
  990. dns_reconn_count = 0;
  991. if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_foundcb)){
  992. espconn_status |= socket_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip.
  993. }
  994. }
  995. else
  996. {
  997. espconn_status |= socket_connect(pesp_conn);
  998. }
  999. NODE_DBG("leave mqtt_socket_connect.\n");
  1000. if (espconn_status == ESPCONN_OK) {
  1001. lua_pushboolean(L, 1);
  1002. } else {
  1003. lua_pushboolean(L, 0);
  1004. }
  1005. return 1;
  1006. }
  1007. // Lua: mqtt:close()
  1008. // client disconnect and unref itself
  1009. static int mqtt_socket_close( lua_State* L )
  1010. {
  1011. NODE_DBG("enter mqtt_socket_close.\n");
  1012. int i = 0;
  1013. lmqtt_userdata *mud = NULL;
  1014. mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  1015. luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  1016. if (mud == NULL || mud->pesp_conn == NULL) {
  1017. lua_pushboolean(L, 0);
  1018. return 1;
  1019. }
  1020. mud->mqtt_state.auto_reconnect = RECONNECT_OFF; // stop auto reconnect.
  1021. sint8 espconn_status = ESPCONN_CONN;
  1022. if (mud->connected) {
  1023. // Send disconnect message
  1024. mqtt_message_t* temp_msg = mqtt_msg_disconnect(&mud->mqtt_state.mqtt_connection);
  1025. NODE_DBG("Send MQTT disconnect infomation, data len: %d, d[0]=%d \r\n", temp_msg->length, temp_msg->data[0]);
  1026. #ifdef CLIENT_SSL_ENABLE
  1027. if(mud->secure) {
  1028. espconn_status = espconn_secure_send(mud->pesp_conn, temp_msg->data, temp_msg->length);
  1029. if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
  1030. espconn_status |= espconn_secure_disconnect(mud->pesp_conn);
  1031. } else
  1032. #endif
  1033. {
  1034. espconn_status = espconn_send(mud->pesp_conn, temp_msg->data, temp_msg->length);
  1035. if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
  1036. espconn_status |= espconn_disconnect(mud->pesp_conn);
  1037. }
  1038. }
  1039. mud->connected = 0;
  1040. while (mud->mqtt_state.pending_msg_q) {
  1041. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  1042. }
  1043. NODE_DBG("leave mqtt_socket_close.\n");
  1044. if (espconn_status == ESPCONN_OK) {
  1045. lua_pushboolean(L, 1);
  1046. } else {
  1047. lua_pushboolean(L, 0);
  1048. }
  1049. return 1;
  1050. }
  1051. // Lua: mqtt:on( "method", function() )
  1052. static int mqtt_socket_on( lua_State* L )
  1053. {
  1054. NODE_DBG("enter mqtt_socket_on.\n");
  1055. lmqtt_userdata *mud;
  1056. size_t sl;
  1057. mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  1058. luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  1059. if(mud==NULL){
  1060. NODE_DBG("userdata is nil.\n");
  1061. return 0;
  1062. }
  1063. const char *method = luaL_checklstring( L, 2, &sl );
  1064. if (method == NULL)
  1065. return luaL_error( L, "wrong arg type" );
  1066. luaL_checkanyfunction(L, 3);
  1067. lua_pushvalue(L, 3); // copy argument (func) to the top of stack
  1068. if( sl == 7 && c_strcmp(method, "connect") == 0){
  1069. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  1070. mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1071. }else if( sl == 7 && c_strcmp(method, "offline") == 0){
  1072. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
  1073. mud->cb_disconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1074. }else if( sl == 7 && c_strcmp(method, "message") == 0){
  1075. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
  1076. mud->cb_message_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1077. }else{
  1078. lua_pop(L, 1);
  1079. return luaL_error( L, "method not supported" );
  1080. }
  1081. NODE_DBG("leave mqtt_socket_on.\n");
  1082. return 0;
  1083. }
  1084. // Lua: bool = mqtt:unsubscribe(topic, function())
  1085. static int mqtt_socket_unsubscribe( lua_State* L ) {
  1086. NODE_DBG("enter mqtt_socket_unsubscribe.\n");
  1087. uint8_t stack = 1;
  1088. uint16_t msg_id = 0;
  1089. const char *topic;
  1090. size_t il;
  1091. lmqtt_userdata *mud;
  1092. mud = (lmqtt_userdata *) luaL_checkudata( L, stack, "mqtt.socket" );
  1093. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1094. stack++;
  1095. if(mud==NULL){
  1096. NODE_DBG("userdata is nil.\n");
  1097. lua_pushboolean(L, 0);
  1098. return 1;
  1099. }
  1100. if(mud->pesp_conn == NULL){
  1101. NODE_DBG("mud->pesp_conn is NULL.\n");
  1102. lua_pushboolean(L, 0);
  1103. return 1;
  1104. }
  1105. if(!mud->connected){
  1106. luaL_error( L, "not connected" );
  1107. lua_pushboolean(L, 0);
  1108. return 1;
  1109. }
  1110. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1111. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1112. mqtt_message_t *temp_msg = NULL;
  1113. if( lua_istable( L, stack ) ) {
  1114. NODE_DBG("unsubscribe table\n");
  1115. lua_pushnil( L ); /* first key */
  1116. int topic_count = 0;
  1117. uint8_t overflow = 0;
  1118. while( lua_next( L, stack ) != 0 ) {
  1119. topic = luaL_checkstring( L, -2 );
  1120. if (topic_count == 0) {
  1121. temp_msg = mqtt_msg_unsubscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
  1122. }
  1123. temp_msg = mqtt_msg_unsubscribe_topic( &mud->mqtt_state.mqtt_connection, topic );
  1124. topic_count++;
  1125. NODE_DBG("topic: %s - length: %d\n", topic, temp_msg->length);
  1126. if (temp_msg->length == 0) {
  1127. lua_pop(L, 1);
  1128. overflow = 1;
  1129. break; // too long message for the outbuffer.
  1130. }
  1131. lua_pop( L, 1 );
  1132. }
  1133. if (topic_count == 0){
  1134. return luaL_error( L, "no topics found" );
  1135. }
  1136. if (overflow != 0){
  1137. return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
  1138. }
  1139. temp_msg = mqtt_msg_unsubscribe_fini( &mud->mqtt_state.mqtt_connection );
  1140. if (temp_msg->length == 0) {
  1141. return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
  1142. }
  1143. stack++;
  1144. } else {
  1145. NODE_DBG("unsubscribe string\n");
  1146. topic = luaL_checklstring( L, stack, &il );
  1147. stack++;
  1148. if( topic == NULL ){
  1149. return luaL_error( L, "need topic name" );
  1150. }
  1151. temp_msg = mqtt_msg_unsubscribe( &mud->mqtt_state.mqtt_connection, topic, &msg_id );
  1152. }
  1153. if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
  1154. lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
  1155. luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref );
  1156. mud->cb_unsuback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
  1157. }
  1158. msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
  1159. msg_id, MQTT_MSG_TYPE_UNSUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
  1160. NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
  1161. NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
  1162. sint8 espconn_status = ESPCONN_IF;
  1163. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1164. if(!node || espconn_status != ESPCONN_OK){
  1165. lua_pushboolean(L, 0);
  1166. } else {
  1167. lua_pushboolean(L, 1); // enqueued succeed.
  1168. }
  1169. NODE_DBG("unsubscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1170. NODE_DBG("leave mqtt_socket_unsubscribe.\n");
  1171. return 1;
  1172. }
  1173. // Lua: bool = mqtt:subscribe(topic, qos, function())
  1174. static int mqtt_socket_subscribe( lua_State* L ) {
  1175. NODE_DBG("enter mqtt_socket_subscribe.\n");
  1176. uint8_t stack = 1, qos = 0;
  1177. uint16_t msg_id = 0;
  1178. const char *topic;
  1179. size_t il;
  1180. lmqtt_userdata *mud;
  1181. mud = (lmqtt_userdata *) luaL_checkudata( L, stack, "mqtt.socket" );
  1182. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1183. stack++;
  1184. if(mud==NULL){
  1185. NODE_DBG("userdata is nil.\n");
  1186. lua_pushboolean(L, 0);
  1187. return 1;
  1188. }
  1189. if(mud->pesp_conn == NULL){
  1190. NODE_DBG("mud->pesp_conn is NULL.\n");
  1191. lua_pushboolean(L, 0);
  1192. return 1;
  1193. }
  1194. if(!mud->connected){
  1195. luaL_error( L, "not connected" );
  1196. lua_pushboolean(L, 0);
  1197. return 1;
  1198. }
  1199. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1200. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1201. mqtt_message_t *temp_msg = NULL;
  1202. if( lua_istable( L, stack ) ) {
  1203. NODE_DBG("subscribe table\n");
  1204. lua_pushnil( L ); /* first key */
  1205. int topic_count = 0;
  1206. uint8_t overflow = 0;
  1207. while( lua_next( L, stack ) != 0 ) {
  1208. topic = luaL_checkstring( L, -2 );
  1209. qos = luaL_checkinteger( L, -1 );
  1210. if (topic_count == 0) {
  1211. temp_msg = mqtt_msg_subscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
  1212. }
  1213. temp_msg = mqtt_msg_subscribe_topic( &mud->mqtt_state.mqtt_connection, topic, qos );
  1214. topic_count++;
  1215. NODE_DBG("topic: %s - qos: %d, length: %d\n", topic, qos, temp_msg->length);
  1216. if (temp_msg->length == 0) {
  1217. lua_pop(L, 1);
  1218. overflow = 1;
  1219. break; // too long message for the outbuffer.
  1220. }
  1221. lua_pop( L, 1 );
  1222. }
  1223. if (topic_count == 0){
  1224. return luaL_error( L, "no topics found" );
  1225. }
  1226. if (overflow != 0){
  1227. return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
  1228. }
  1229. temp_msg = mqtt_msg_subscribe_fini( &mud->mqtt_state.mqtt_connection );
  1230. if (temp_msg->length == 0) {
  1231. return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
  1232. }
  1233. stack++;
  1234. } else {
  1235. NODE_DBG("subscribe string\n");
  1236. topic = luaL_checklstring( L, stack, &il );
  1237. stack++;
  1238. if( topic == NULL ){
  1239. return luaL_error( L, "need topic name" );
  1240. }
  1241. qos = luaL_checkinteger( L, stack );
  1242. temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
  1243. stack++;
  1244. }
  1245. if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
  1246. lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
  1247. luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_suback_ref );
  1248. mud->cb_suback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
  1249. }
  1250. msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
  1251. msg_id, MQTT_MSG_TYPE_SUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
  1252. NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
  1253. NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
  1254. sint8 espconn_status = ESPCONN_IF;
  1255. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1256. if(!node || espconn_status != ESPCONN_OK){
  1257. lua_pushboolean(L, 0);
  1258. } else {
  1259. lua_pushboolean(L, 1); // enqueued succeed.
  1260. }
  1261. NODE_DBG("subscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1262. NODE_DBG("leave mqtt_socket_subscribe.\n");
  1263. return 1;
  1264. }
  1265. // Lua: bool = mqtt:publish( topic, payload, qos, retain, function() )
  1266. static int mqtt_socket_publish( lua_State* L )
  1267. {
  1268. NODE_DBG("enter mqtt_socket_publish.\n");
  1269. struct espconn *pesp_conn = NULL;
  1270. lmqtt_userdata *mud;
  1271. size_t l;
  1272. uint8_t stack = 1;
  1273. uint16_t msg_id = 0;
  1274. mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
  1275. luaL_argcheck(L, mud, stack, "mqtt.socket expected");
  1276. stack++;
  1277. if(mud==NULL){
  1278. NODE_DBG("userdata is nil.\n");
  1279. lua_pushboolean(L, 0);
  1280. return 1;
  1281. }
  1282. if(mud->pesp_conn == NULL){
  1283. NODE_DBG("mud->pesp_conn is NULL.\n");
  1284. lua_pushboolean(L, 0);
  1285. return 1;
  1286. }
  1287. if(!mud->connected){
  1288. return luaL_error( L, "not connected" );
  1289. }
  1290. const char *topic = luaL_checklstring( L, stack, &l );
  1291. stack ++;
  1292. if (topic == NULL){
  1293. return luaL_error( L, "need topic" );
  1294. }
  1295. const char *payload = luaL_checklstring( L, stack, &l );
  1296. stack ++;
  1297. uint8_t qos = luaL_checkinteger( L, stack);
  1298. stack ++;
  1299. uint8_t retain = luaL_checkinteger( L, stack);
  1300. stack ++;
  1301. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1302. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1303. mqtt_message_t *temp_msg = mqtt_msg_publish(&mud->mqtt_state.mqtt_connection,
  1304. topic, payload, l,
  1305. qos, retain,
  1306. &msg_id);
  1307. if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
  1308. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  1309. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  1310. mud->cb_puback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1311. }
  1312. msg_queue_t *node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  1313. msg_id, MQTT_MSG_TYPE_PUBLISH, (int)qos );
  1314. sint8 espconn_status = ESPCONN_OK;
  1315. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1316. if(!node || espconn_status != ESPCONN_OK){
  1317. lua_pushboolean(L, 0);
  1318. } else {
  1319. lua_pushboolean(L, 1); // enqueued succeed.
  1320. }
  1321. NODE_DBG("publish, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1322. NODE_DBG("leave mqtt_socket_publish.\n");
  1323. return 1;
  1324. }
  1325. // Lua: mqtt:lwt( topic, message, qos, retain, function(client) )
  1326. static int mqtt_socket_lwt( lua_State* L )
  1327. {
  1328. NODE_DBG("enter mqtt_socket_lwt.\n");
  1329. uint8_t stack = 1;
  1330. size_t topicSize, msgSize;
  1331. NODE_DBG("mqtt_socket_lwt.\n");
  1332. lmqtt_userdata *mud = NULL;
  1333. const char *lwtTopic, *lwtMsg;
  1334. uint8_t lwtQoS, lwtRetain;
  1335. mud = (lmqtt_userdata *)luaL_checkudata( L, stack, "mqtt.socket" );
  1336. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1337. if(mud == NULL)
  1338. return 0;
  1339. stack++;
  1340. lwtTopic = luaL_checklstring( L, stack, &topicSize );
  1341. if (lwtTopic == NULL)
  1342. {
  1343. return luaL_error( L, "need lwt topic");
  1344. }
  1345. stack++;
  1346. lwtMsg = luaL_checklstring( L, stack, &msgSize );
  1347. if (lwtMsg == NULL)
  1348. {
  1349. return luaL_error( L, "need lwt message");
  1350. }
  1351. stack++;
  1352. if(mud->connect_info.will_topic){ // free the previous one if there is any
  1353. c_free(mud->connect_info.will_topic);
  1354. mud->connect_info.will_topic = NULL;
  1355. }
  1356. if(mud->connect_info.will_message){
  1357. c_free(mud->connect_info.will_message);
  1358. mud->connect_info.will_message = NULL;
  1359. }
  1360. mud->connect_info.will_topic = (uint8_t*) c_zalloc( topicSize + 1 );
  1361. mud->connect_info.will_message = (uint8_t*) c_zalloc( msgSize + 1 );
  1362. if(!mud->connect_info.will_topic || !mud->connect_info.will_message){
  1363. if(mud->connect_info.will_topic){
  1364. c_free(mud->connect_info.will_topic);
  1365. mud->connect_info.will_topic = NULL;
  1366. }
  1367. if(mud->connect_info.will_message){
  1368. c_free(mud->connect_info.will_message);
  1369. mud->connect_info.will_message = NULL;
  1370. }
  1371. return luaL_error( L, "not enough memory");
  1372. }
  1373. c_memcpy(mud->connect_info.will_topic, lwtTopic, topicSize);
  1374. mud->connect_info.will_topic[topicSize] = 0;
  1375. c_memcpy(mud->connect_info.will_message, lwtMsg, msgSize);
  1376. mud->connect_info.will_message[msgSize] = 0;
  1377. if ( lua_isnumber(L, stack) )
  1378. {
  1379. mud->connect_info.will_qos = lua_tointeger(L, stack);
  1380. stack++;
  1381. }
  1382. if ( lua_isnumber(L, stack) )
  1383. {
  1384. mud->connect_info.will_retain = lua_tointeger(L, stack);
  1385. stack++;
  1386. }
  1387. NODE_DBG("mqtt_socket_lwt: topic: %s, message: %s, qos: %d, retain: %d\n",
  1388. mud->connect_info.will_topic,
  1389. mud->connect_info.will_message,
  1390. mud->connect_info.will_qos,
  1391. mud->connect_info.will_retain);
  1392. NODE_DBG("leave mqtt_socket_lwt.\n");
  1393. return 0;
  1394. }
  1395. // Module function map
  1396. static const LUA_REG_TYPE mqtt_socket_map[] = {
  1397. { LSTRKEY( "connect" ), LFUNCVAL( mqtt_socket_connect ) },
  1398. { LSTRKEY( "close" ), LFUNCVAL( mqtt_socket_close ) },
  1399. { LSTRKEY( "publish" ), LFUNCVAL( mqtt_socket_publish ) },
  1400. { LSTRKEY( "subscribe" ), LFUNCVAL( mqtt_socket_subscribe ) },
  1401. { LSTRKEY( "unsubscribe" ), LFUNCVAL( mqtt_socket_unsubscribe ) },
  1402. { LSTRKEY( "lwt" ), LFUNCVAL( mqtt_socket_lwt ) },
  1403. { LSTRKEY( "on" ), LFUNCVAL( mqtt_socket_on ) },
  1404. { LSTRKEY( "__gc" ), LFUNCVAL( mqtt_delete ) },
  1405. { LSTRKEY( "__index" ), LROVAL( mqtt_socket_map ) },
  1406. { LNILKEY, LNILVAL }
  1407. };
  1408. static const LUA_REG_TYPE mqtt_map[] = {
  1409. { LSTRKEY( "Client" ), LFUNCVAL( mqtt_socket_client ) },
  1410. { LSTRKEY( "CONN_FAIL_SERVER_NOT_FOUND" ), LNUMVAL( MQTT_CONN_FAIL_SERVER_NOT_FOUND ) },
  1411. { LSTRKEY( "CONN_FAIL_NOT_A_CONNACK_MSG" ), LNUMVAL( MQTT_CONN_FAIL_NOT_A_CONNACK_MSG ) },
  1412. { LSTRKEY( "CONN_FAIL_DNS" ), LNUMVAL( MQTT_CONN_FAIL_DNS ) },
  1413. { LSTRKEY( "CONN_FAIL_TIMEOUT_RECEIVING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_RECEIVING ) },
  1414. { LSTRKEY( "CONN_FAIL_TIMEOUT_SENDING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_SENDING ) },
  1415. { LSTRKEY( "CONNACK_ACCEPTED" ), LNUMVAL( MQTT_CONNACK_ACCEPTED ) },
  1416. { LSTRKEY( "CONNACK_REFUSED_PROTOCOL_VER" ), LNUMVAL( MQTT_CONNACK_REFUSED_PROTOCOL_VER ) },
  1417. { LSTRKEY( "CONNACK_REFUSED_ID_REJECTED" ), LNUMVAL( MQTT_CONNACK_REFUSED_ID_REJECTED ) },
  1418. { LSTRKEY( "CONNACK_REFUSED_SERVER_UNAVAILABLE" ), LNUMVAL( MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE ) },
  1419. { LSTRKEY( "CONNACK_REFUSED_BAD_USER_OR_PASS" ), LNUMVAL( MQTT_CONNACK_REFUSED_BAD_USER_OR_PASS ) },
  1420. { LSTRKEY( "CONNACK_REFUSED_NOT_AUTHORIZED" ), LNUMVAL( MQTT_CONNACK_REFUSED_NOT_AUTHORIZED ) },
  1421. { LSTRKEY( "__metatable" ), LROVAL( mqtt_map ) },
  1422. { LNILKEY, LNILVAL }
  1423. };
  1424. int luaopen_mqtt( lua_State *L )
  1425. {
  1426. luaL_rometatable(L, "mqtt.socket", (void *)mqtt_socket_map); // create metatable for mqtt.socket
  1427. return 0;
  1428. }
  1429. NODEMCU_MODULE(MQTT, "mqtt", mqtt_map, luaopen_mqtt);