mqtt.c 51 KB

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