mqtt.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  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. #include "pm/swtimer.h"
  869. // Lua: mqtt:connect( host, port, secure, auto_reconnect, function(client), function(client, connect_return_code) )
  870. static int mqtt_socket_connect( lua_State* L )
  871. {
  872. NODE_DBG("enter mqtt_socket_connect.\n");
  873. lmqtt_userdata *mud = NULL;
  874. unsigned port = 1883;
  875. size_t il;
  876. ip_addr_t ipaddr;
  877. const char *domain;
  878. int stack = 1;
  879. unsigned secure = 0, auto_reconnect = RECONNECT_OFF;
  880. int top = lua_gettop(L);
  881. sint8 espconn_status;
  882. mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
  883. luaL_argcheck(L, mud, stack, "mqtt.socket expected");
  884. stack++;
  885. if(mud == NULL)
  886. return 0;
  887. if(mud->connected){
  888. return luaL_error(L, "already connected");
  889. }
  890. struct espconn *pesp_conn = mud->pesp_conn;
  891. if(!pesp_conn) {
  892. pesp_conn = mud->pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
  893. } else {
  894. espconn_delete(pesp_conn);
  895. }
  896. if(!pesp_conn)
  897. return luaL_error(L, "not enough memory");
  898. if (!pesp_conn->proto.tcp)
  899. pesp_conn->proto.tcp = (esp_tcp *)c_zalloc(sizeof(esp_tcp));
  900. if(!pesp_conn->proto.tcp){
  901. c_free(pesp_conn);
  902. pesp_conn = mud->pesp_conn = NULL;
  903. return luaL_error(L, "not enough memory");
  904. }
  905. // reverse is for the callback function
  906. pesp_conn->reverse = mud;
  907. pesp_conn->type = ESPCONN_TCP;
  908. pesp_conn->state = ESPCONN_NONE;
  909. mud->connected = false;
  910. if( (stack<=top) && lua_isstring(L,stack) ) // deal with the domain string
  911. {
  912. domain = luaL_checklstring( L, stack, &il );
  913. stack++;
  914. if (domain == NULL)
  915. {
  916. domain = "127.0.0.1";
  917. }
  918. ipaddr.addr = ipaddr_addr(domain);
  919. c_memcpy(pesp_conn->proto.tcp->remote_ip, &ipaddr.addr, 4);
  920. NODE_DBG("TCP ip is set: ");
  921. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  922. NODE_DBG("\n");
  923. }
  924. if ( (stack<=top) && lua_isnumber(L, stack) )
  925. {
  926. port = lua_tointeger(L, stack);
  927. stack++;
  928. NODE_DBG("TCP port is set: %d.\n", port);
  929. }
  930. pesp_conn->proto.tcp->remote_port = port;
  931. if (pesp_conn->proto.tcp->local_port == 0)
  932. pesp_conn->proto.tcp->local_port = espconn_port();
  933. mud->mqtt_state.port = port;
  934. if ( (stack<=top) && lua_isnumber(L, stack) )
  935. {
  936. secure = lua_tointeger(L, stack);
  937. stack++;
  938. if ( secure != 0 && secure != 1 ){
  939. secure = 0; // default to 0
  940. }
  941. } else {
  942. secure = 0; // default to 0
  943. }
  944. #ifdef CLIENT_SSL_ENABLE
  945. mud->secure = secure; // save
  946. #else
  947. if ( secure )
  948. {
  949. return luaL_error(L, "ssl not available");
  950. }
  951. #endif
  952. if ( (stack<=top) && lua_isnumber(L, stack) )
  953. {
  954. auto_reconnect = lua_tointeger(L, stack);
  955. if ( auto_reconnect == RECONNECT_POSSIBLE ) {
  956. platform_print_deprecation_note("autoreconnect == 1 is deprecated", "in the next version");
  957. }
  958. stack++;
  959. if ( auto_reconnect != RECONNECT_OFF && auto_reconnect != RECONNECT_POSSIBLE ){
  960. auto_reconnect = RECONNECT_OFF; // default to 0
  961. }
  962. } else {
  963. auto_reconnect = RECONNECT_OFF; // default to 0
  964. }
  965. mud->mqtt_state.auto_reconnect = auto_reconnect;
  966. // call back function when a connection is obtained, tcp only
  967. if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
  968. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  969. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  970. mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  971. }
  972. stack++;
  973. // call back function when a connection fails
  974. if ((stack<=top) && (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION)){
  975. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  976. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_fail_ref);
  977. mud->cb_connect_fail_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  978. stack++;
  979. }
  980. lua_pushvalue(L, 1); // copy userdata to the top of stack
  981. luaL_unref(L, LUA_REGISTRYINDEX, mud->self_ref);
  982. mud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  983. espconn_status = espconn_regist_connectcb(pesp_conn, mqtt_socket_connected);
  984. espconn_status |= espconn_regist_reconcb(pesp_conn, mqtt_socket_reconnected);
  985. os_timer_disarm(&mud->mqttTimer);
  986. os_timer_setfn(&mud->mqttTimer, (os_timer_func_t *)mqtt_socket_timer, mud);
  987. SWTIMER_REG_CB(mqtt_socket_timer, SWTIMER_RESUME);
  988. //I assume that mqtt_socket_timer connects to the mqtt server, but I'm not really sure what impact light_sleep will have on it.
  989. //My guess: If in doubt, resume the timer
  990. // timer started in socket_connect()
  991. if((ipaddr.addr == IPADDR_NONE) && (c_memcmp(domain,"255.255.255.255",16) != 0))
  992. {
  993. host_ip.addr = 0;
  994. dns_reconn_count = 0;
  995. if(ESPCONN_OK == espconn_gethostbyname(pesp_conn, domain, &host_ip, socket_dns_foundcb)){
  996. espconn_status |= socket_dns_found(domain, &host_ip, pesp_conn); // ip is returned in host_ip.
  997. }
  998. }
  999. else
  1000. {
  1001. espconn_status |= socket_connect(pesp_conn);
  1002. }
  1003. NODE_DBG("leave mqtt_socket_connect.\n");
  1004. if (espconn_status == ESPCONN_OK) {
  1005. lua_pushboolean(L, 1);
  1006. } else {
  1007. lua_pushboolean(L, 0);
  1008. }
  1009. return 1;
  1010. }
  1011. // Lua: mqtt:close()
  1012. // client disconnect and unref itself
  1013. static int mqtt_socket_close( lua_State* L )
  1014. {
  1015. NODE_DBG("enter mqtt_socket_close.\n");
  1016. int i = 0;
  1017. lmqtt_userdata *mud = NULL;
  1018. mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  1019. luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  1020. if (mud == NULL || mud->pesp_conn == NULL) {
  1021. lua_pushboolean(L, 0);
  1022. return 1;
  1023. }
  1024. mud->mqtt_state.auto_reconnect = RECONNECT_OFF; // stop auto reconnect.
  1025. sint8 espconn_status = ESPCONN_CONN;
  1026. if (mud->connected) {
  1027. // Send disconnect message
  1028. mqtt_message_t* temp_msg = mqtt_msg_disconnect(&mud->mqtt_state.mqtt_connection);
  1029. NODE_DBG("Send MQTT disconnect infomation, data len: %d, d[0]=%d \r\n", temp_msg->length, temp_msg->data[0]);
  1030. #ifdef CLIENT_SSL_ENABLE
  1031. if(mud->secure) {
  1032. espconn_status = espconn_secure_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_secure_disconnect(mud->pesp_conn);
  1035. } else
  1036. #endif
  1037. {
  1038. espconn_status = espconn_send(mud->pesp_conn, temp_msg->data, temp_msg->length);
  1039. if(mud->pesp_conn->proto.tcp->remote_port || mud->pesp_conn->proto.tcp->local_port)
  1040. espconn_status |= espconn_disconnect(mud->pesp_conn);
  1041. }
  1042. }
  1043. mud->connected = 0;
  1044. while (mud->mqtt_state.pending_msg_q) {
  1045. msg_destroy(msg_dequeue(&(mud->mqtt_state.pending_msg_q)));
  1046. }
  1047. NODE_DBG("leave mqtt_socket_close.\n");
  1048. if (espconn_status == ESPCONN_OK) {
  1049. lua_pushboolean(L, 1);
  1050. } else {
  1051. lua_pushboolean(L, 0);
  1052. }
  1053. return 1;
  1054. }
  1055. // Lua: mqtt:on( "method", function() )
  1056. static int mqtt_socket_on( lua_State* L )
  1057. {
  1058. NODE_DBG("enter mqtt_socket_on.\n");
  1059. lmqtt_userdata *mud;
  1060. size_t sl;
  1061. mud = (lmqtt_userdata *)luaL_checkudata(L, 1, "mqtt.socket");
  1062. luaL_argcheck(L, mud, 1, "mqtt.socket expected");
  1063. if(mud==NULL){
  1064. NODE_DBG("userdata is nil.\n");
  1065. return 0;
  1066. }
  1067. const char *method = luaL_checklstring( L, 2, &sl );
  1068. if (method == NULL)
  1069. return luaL_error( L, "wrong arg type" );
  1070. luaL_checkanyfunction(L, 3);
  1071. lua_pushvalue(L, 3); // copy argument (func) to the top of stack
  1072. if( sl == 7 && c_strcmp(method, "connect") == 0){
  1073. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_connect_ref);
  1074. mud->cb_connect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1075. }else if( sl == 7 && c_strcmp(method, "offline") == 0){
  1076. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_disconnect_ref);
  1077. mud->cb_disconnect_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1078. }else if( sl == 7 && c_strcmp(method, "message") == 0){
  1079. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_message_ref);
  1080. mud->cb_message_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1081. }else{
  1082. lua_pop(L, 1);
  1083. return luaL_error( L, "method not supported" );
  1084. }
  1085. NODE_DBG("leave mqtt_socket_on.\n");
  1086. return 0;
  1087. }
  1088. // Lua: bool = mqtt:unsubscribe(topic, function())
  1089. static int mqtt_socket_unsubscribe( lua_State* L ) {
  1090. NODE_DBG("enter mqtt_socket_unsubscribe.\n");
  1091. uint8_t stack = 1;
  1092. uint16_t msg_id = 0;
  1093. const char *topic;
  1094. size_t il;
  1095. lmqtt_userdata *mud;
  1096. mud = (lmqtt_userdata *) luaL_checkudata( L, stack, "mqtt.socket" );
  1097. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1098. stack++;
  1099. if(mud==NULL){
  1100. NODE_DBG("userdata is nil.\n");
  1101. lua_pushboolean(L, 0);
  1102. return 1;
  1103. }
  1104. if(mud->pesp_conn == NULL){
  1105. NODE_DBG("mud->pesp_conn is NULL.\n");
  1106. lua_pushboolean(L, 0);
  1107. return 1;
  1108. }
  1109. if(!mud->connected){
  1110. luaL_error( L, "not connected" );
  1111. lua_pushboolean(L, 0);
  1112. return 1;
  1113. }
  1114. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1115. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1116. mqtt_message_t *temp_msg = NULL;
  1117. if( lua_istable( L, stack ) ) {
  1118. NODE_DBG("unsubscribe table\n");
  1119. lua_pushnil( L ); /* first key */
  1120. int topic_count = 0;
  1121. uint8_t overflow = 0;
  1122. while( lua_next( L, stack ) != 0 ) {
  1123. topic = luaL_checkstring( L, -2 );
  1124. if (topic_count == 0) {
  1125. temp_msg = mqtt_msg_unsubscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
  1126. }
  1127. temp_msg = mqtt_msg_unsubscribe_topic( &mud->mqtt_state.mqtt_connection, topic );
  1128. topic_count++;
  1129. NODE_DBG("topic: %s - length: %d\n", topic, temp_msg->length);
  1130. if (temp_msg->length == 0) {
  1131. lua_pop(L, 1);
  1132. overflow = 1;
  1133. break; // too long message for the outbuffer.
  1134. }
  1135. lua_pop( L, 1 );
  1136. }
  1137. if (topic_count == 0){
  1138. return luaL_error( L, "no topics found" );
  1139. }
  1140. if (overflow != 0){
  1141. return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
  1142. }
  1143. temp_msg = mqtt_msg_unsubscribe_fini( &mud->mqtt_state.mqtt_connection );
  1144. if (temp_msg->length == 0) {
  1145. return luaL_error( L, "buffer overflow, can't enqueue all unsubscriptions" );
  1146. }
  1147. stack++;
  1148. } else {
  1149. NODE_DBG("unsubscribe string\n");
  1150. topic = luaL_checklstring( L, stack, &il );
  1151. stack++;
  1152. if( topic == NULL ){
  1153. return luaL_error( L, "need topic name" );
  1154. }
  1155. temp_msg = mqtt_msg_unsubscribe( &mud->mqtt_state.mqtt_connection, topic, &msg_id );
  1156. }
  1157. if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
  1158. lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
  1159. luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_unsuback_ref );
  1160. mud->cb_unsuback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
  1161. }
  1162. msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
  1163. msg_id, MQTT_MSG_TYPE_UNSUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
  1164. NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
  1165. NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
  1166. sint8 espconn_status = ESPCONN_IF;
  1167. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1168. if(!node || espconn_status != ESPCONN_OK){
  1169. lua_pushboolean(L, 0);
  1170. } else {
  1171. lua_pushboolean(L, 1); // enqueued succeed.
  1172. }
  1173. NODE_DBG("unsubscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1174. NODE_DBG("leave mqtt_socket_unsubscribe.\n");
  1175. return 1;
  1176. }
  1177. // Lua: bool = mqtt:subscribe(topic, qos, function())
  1178. static int mqtt_socket_subscribe( lua_State* L ) {
  1179. NODE_DBG("enter mqtt_socket_subscribe.\n");
  1180. uint8_t stack = 1, qos = 0;
  1181. uint16_t msg_id = 0;
  1182. const char *topic;
  1183. size_t il;
  1184. lmqtt_userdata *mud;
  1185. mud = (lmqtt_userdata *) luaL_checkudata( L, stack, "mqtt.socket" );
  1186. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1187. stack++;
  1188. if(mud==NULL){
  1189. NODE_DBG("userdata is nil.\n");
  1190. lua_pushboolean(L, 0);
  1191. return 1;
  1192. }
  1193. if(mud->pesp_conn == NULL){
  1194. NODE_DBG("mud->pesp_conn is NULL.\n");
  1195. lua_pushboolean(L, 0);
  1196. return 1;
  1197. }
  1198. if(!mud->connected){
  1199. luaL_error( L, "not connected" );
  1200. lua_pushboolean(L, 0);
  1201. return 1;
  1202. }
  1203. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1204. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1205. mqtt_message_t *temp_msg = NULL;
  1206. if( lua_istable( L, stack ) ) {
  1207. NODE_DBG("subscribe table\n");
  1208. lua_pushnil( L ); /* first key */
  1209. int topic_count = 0;
  1210. uint8_t overflow = 0;
  1211. while( lua_next( L, stack ) != 0 ) {
  1212. topic = luaL_checkstring( L, -2 );
  1213. qos = luaL_checkinteger( L, -1 );
  1214. if (topic_count == 0) {
  1215. temp_msg = mqtt_msg_subscribe_init( &mud->mqtt_state.mqtt_connection, &msg_id );
  1216. }
  1217. temp_msg = mqtt_msg_subscribe_topic( &mud->mqtt_state.mqtt_connection, topic, qos );
  1218. topic_count++;
  1219. NODE_DBG("topic: %s - qos: %d, length: %d\n", topic, qos, temp_msg->length);
  1220. if (temp_msg->length == 0) {
  1221. lua_pop(L, 1);
  1222. overflow = 1;
  1223. break; // too long message for the outbuffer.
  1224. }
  1225. lua_pop( L, 1 );
  1226. }
  1227. if (topic_count == 0){
  1228. return luaL_error( L, "no topics found" );
  1229. }
  1230. if (overflow != 0){
  1231. return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
  1232. }
  1233. temp_msg = mqtt_msg_subscribe_fini( &mud->mqtt_state.mqtt_connection );
  1234. if (temp_msg->length == 0) {
  1235. return luaL_error( L, "buffer overflow, can't enqueue all subscriptions" );
  1236. }
  1237. stack++;
  1238. } else {
  1239. NODE_DBG("subscribe string\n");
  1240. topic = luaL_checklstring( L, stack, &il );
  1241. stack++;
  1242. if( topic == NULL ){
  1243. return luaL_error( L, "need topic name" );
  1244. }
  1245. qos = luaL_checkinteger( L, stack );
  1246. temp_msg = mqtt_msg_subscribe( &mud->mqtt_state.mqtt_connection, topic, qos, &msg_id );
  1247. stack++;
  1248. }
  1249. if( lua_type( L, stack ) == LUA_TFUNCTION || lua_type( L, stack ) == LUA_TLIGHTFUNCTION ) { // TODO: this will overwrite the previous one.
  1250. lua_pushvalue( L, stack ); // copy argument (func) to the top of stack
  1251. luaL_unref( L, LUA_REGISTRYINDEX, mud->cb_suback_ref );
  1252. mud->cb_suback_ref = luaL_ref( L, LUA_REGISTRYINDEX );
  1253. }
  1254. msg_queue_t *node = msg_enqueue( &(mud->mqtt_state.pending_msg_q), temp_msg,
  1255. msg_id, MQTT_MSG_TYPE_SUBSCRIBE, (int)mqtt_get_qos(temp_msg->data) );
  1256. NODE_DBG("topic: %s - id: %d - qos: %d, length: %d\n", topic, node->msg_id, node->publish_qos, node->msg.length);
  1257. NODE_DBG("msg_size: %d, event_timeout: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)), mud->event_timeout);
  1258. sint8 espconn_status = ESPCONN_IF;
  1259. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1260. if(!node || espconn_status != ESPCONN_OK){
  1261. lua_pushboolean(L, 0);
  1262. } else {
  1263. lua_pushboolean(L, 1); // enqueued succeed.
  1264. }
  1265. NODE_DBG("subscribe, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1266. NODE_DBG("leave mqtt_socket_subscribe.\n");
  1267. return 1;
  1268. }
  1269. // Lua: bool = mqtt:publish( topic, payload, qos, retain, function() )
  1270. static int mqtt_socket_publish( lua_State* L )
  1271. {
  1272. NODE_DBG("enter mqtt_socket_publish.\n");
  1273. struct espconn *pesp_conn = NULL;
  1274. lmqtt_userdata *mud;
  1275. size_t l;
  1276. uint8_t stack = 1;
  1277. uint16_t msg_id = 0;
  1278. mud = (lmqtt_userdata *)luaL_checkudata(L, stack, "mqtt.socket");
  1279. luaL_argcheck(L, mud, stack, "mqtt.socket expected");
  1280. stack++;
  1281. if(mud==NULL){
  1282. NODE_DBG("userdata is nil.\n");
  1283. lua_pushboolean(L, 0);
  1284. return 1;
  1285. }
  1286. if(mud->pesp_conn == NULL){
  1287. NODE_DBG("mud->pesp_conn is NULL.\n");
  1288. lua_pushboolean(L, 0);
  1289. return 1;
  1290. }
  1291. if(!mud->connected){
  1292. return luaL_error( L, "not connected" );
  1293. }
  1294. const char *topic = luaL_checklstring( L, stack, &l );
  1295. stack ++;
  1296. if (topic == NULL){
  1297. return luaL_error( L, "need topic" );
  1298. }
  1299. const char *payload = luaL_checklstring( L, stack, &l );
  1300. stack ++;
  1301. uint8_t qos = luaL_checkinteger( L, stack);
  1302. stack ++;
  1303. uint8_t retain = luaL_checkinteger( L, stack);
  1304. stack ++;
  1305. uint8_t temp_buffer[MQTT_BUF_SIZE];
  1306. mqtt_msg_init(&mud->mqtt_state.mqtt_connection, temp_buffer, MQTT_BUF_SIZE);
  1307. mqtt_message_t *temp_msg = mqtt_msg_publish(&mud->mqtt_state.mqtt_connection,
  1308. topic, payload, l,
  1309. qos, retain,
  1310. &msg_id);
  1311. if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
  1312. lua_pushvalue(L, stack); // copy argument (func) to the top of stack
  1313. luaL_unref(L, LUA_REGISTRYINDEX, mud->cb_puback_ref);
  1314. mud->cb_puback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  1315. }
  1316. msg_queue_t *node = msg_enqueue(&(mud->mqtt_state.pending_msg_q), temp_msg,
  1317. msg_id, MQTT_MSG_TYPE_PUBLISH, (int)qos );
  1318. sint8 espconn_status = ESPCONN_OK;
  1319. espconn_status = mqtt_send_if_possible(mud->pesp_conn);
  1320. if(!node || espconn_status != ESPCONN_OK){
  1321. lua_pushboolean(L, 0);
  1322. } else {
  1323. lua_pushboolean(L, 1); // enqueued succeed.
  1324. }
  1325. NODE_DBG("publish, queue size: %d\n", msg_size(&(mud->mqtt_state.pending_msg_q)));
  1326. NODE_DBG("leave mqtt_socket_publish.\n");
  1327. return 1;
  1328. }
  1329. // Lua: mqtt:lwt( topic, message, qos, retain, function(client) )
  1330. static int mqtt_socket_lwt( lua_State* L )
  1331. {
  1332. NODE_DBG("enter mqtt_socket_lwt.\n");
  1333. uint8_t stack = 1;
  1334. size_t topicSize, msgSize;
  1335. NODE_DBG("mqtt_socket_lwt.\n");
  1336. lmqtt_userdata *mud = NULL;
  1337. const char *lwtTopic, *lwtMsg;
  1338. uint8_t lwtQoS, lwtRetain;
  1339. mud = (lmqtt_userdata *)luaL_checkudata( L, stack, "mqtt.socket" );
  1340. luaL_argcheck( L, mud, stack, "mqtt.socket expected" );
  1341. if(mud == NULL)
  1342. return 0;
  1343. stack++;
  1344. lwtTopic = luaL_checklstring( L, stack, &topicSize );
  1345. if (lwtTopic == NULL)
  1346. {
  1347. return luaL_error( L, "need lwt topic");
  1348. }
  1349. stack++;
  1350. lwtMsg = luaL_checklstring( L, stack, &msgSize );
  1351. if (lwtMsg == NULL)
  1352. {
  1353. return luaL_error( L, "need lwt message");
  1354. }
  1355. stack++;
  1356. if(mud->connect_info.will_topic){ // free the previous one if there is any
  1357. c_free(mud->connect_info.will_topic);
  1358. mud->connect_info.will_topic = NULL;
  1359. }
  1360. if(mud->connect_info.will_message){
  1361. c_free(mud->connect_info.will_message);
  1362. mud->connect_info.will_message = NULL;
  1363. }
  1364. mud->connect_info.will_topic = (uint8_t*) c_zalloc( topicSize + 1 );
  1365. mud->connect_info.will_message = (uint8_t*) c_zalloc( msgSize + 1 );
  1366. if(!mud->connect_info.will_topic || !mud->connect_info.will_message){
  1367. if(mud->connect_info.will_topic){
  1368. c_free(mud->connect_info.will_topic);
  1369. mud->connect_info.will_topic = NULL;
  1370. }
  1371. if(mud->connect_info.will_message){
  1372. c_free(mud->connect_info.will_message);
  1373. mud->connect_info.will_message = NULL;
  1374. }
  1375. return luaL_error( L, "not enough memory");
  1376. }
  1377. c_memcpy(mud->connect_info.will_topic, lwtTopic, topicSize);
  1378. mud->connect_info.will_topic[topicSize] = 0;
  1379. c_memcpy(mud->connect_info.will_message, lwtMsg, msgSize);
  1380. mud->connect_info.will_message[msgSize] = 0;
  1381. if ( lua_isnumber(L, stack) )
  1382. {
  1383. mud->connect_info.will_qos = lua_tointeger(L, stack);
  1384. stack++;
  1385. }
  1386. if ( lua_isnumber(L, stack) )
  1387. {
  1388. mud->connect_info.will_retain = lua_tointeger(L, stack);
  1389. stack++;
  1390. }
  1391. NODE_DBG("mqtt_socket_lwt: topic: %s, message: %s, qos: %d, retain: %d\n",
  1392. mud->connect_info.will_topic,
  1393. mud->connect_info.will_message,
  1394. mud->connect_info.will_qos,
  1395. mud->connect_info.will_retain);
  1396. NODE_DBG("leave mqtt_socket_lwt.\n");
  1397. return 0;
  1398. }
  1399. // Module function map
  1400. static const LUA_REG_TYPE mqtt_socket_map[] = {
  1401. { LSTRKEY( "connect" ), LFUNCVAL( mqtt_socket_connect ) },
  1402. { LSTRKEY( "close" ), LFUNCVAL( mqtt_socket_close ) },
  1403. { LSTRKEY( "publish" ), LFUNCVAL( mqtt_socket_publish ) },
  1404. { LSTRKEY( "subscribe" ), LFUNCVAL( mqtt_socket_subscribe ) },
  1405. { LSTRKEY( "unsubscribe" ), LFUNCVAL( mqtt_socket_unsubscribe ) },
  1406. { LSTRKEY( "lwt" ), LFUNCVAL( mqtt_socket_lwt ) },
  1407. { LSTRKEY( "on" ), LFUNCVAL( mqtt_socket_on ) },
  1408. { LSTRKEY( "__gc" ), LFUNCVAL( mqtt_delete ) },
  1409. { LSTRKEY( "__index" ), LROVAL( mqtt_socket_map ) },
  1410. { LNILKEY, LNILVAL }
  1411. };
  1412. static const LUA_REG_TYPE mqtt_map[] = {
  1413. { LSTRKEY( "Client" ), LFUNCVAL( mqtt_socket_client ) },
  1414. { LSTRKEY( "CONN_FAIL_SERVER_NOT_FOUND" ), LNUMVAL( MQTT_CONN_FAIL_SERVER_NOT_FOUND ) },
  1415. { LSTRKEY( "CONN_FAIL_NOT_A_CONNACK_MSG" ), LNUMVAL( MQTT_CONN_FAIL_NOT_A_CONNACK_MSG ) },
  1416. { LSTRKEY( "CONN_FAIL_DNS" ), LNUMVAL( MQTT_CONN_FAIL_DNS ) },
  1417. { LSTRKEY( "CONN_FAIL_TIMEOUT_RECEIVING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_RECEIVING ) },
  1418. { LSTRKEY( "CONN_FAIL_TIMEOUT_SENDING" ), LNUMVAL( MQTT_CONN_FAIL_TIMEOUT_SENDING ) },
  1419. { LSTRKEY( "CONNACK_ACCEPTED" ), LNUMVAL( MQTT_CONNACK_ACCEPTED ) },
  1420. { LSTRKEY( "CONNACK_REFUSED_PROTOCOL_VER" ), LNUMVAL( MQTT_CONNACK_REFUSED_PROTOCOL_VER ) },
  1421. { LSTRKEY( "CONNACK_REFUSED_ID_REJECTED" ), LNUMVAL( MQTT_CONNACK_REFUSED_ID_REJECTED ) },
  1422. { LSTRKEY( "CONNACK_REFUSED_SERVER_UNAVAILABLE" ), LNUMVAL( MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE ) },
  1423. { LSTRKEY( "CONNACK_REFUSED_BAD_USER_OR_PASS" ), LNUMVAL( MQTT_CONNACK_REFUSED_BAD_USER_OR_PASS ) },
  1424. { LSTRKEY( "CONNACK_REFUSED_NOT_AUTHORIZED" ), LNUMVAL( MQTT_CONNACK_REFUSED_NOT_AUTHORIZED ) },
  1425. { LSTRKEY( "__metatable" ), LROVAL( mqtt_map ) },
  1426. { LNILKEY, LNILVAL }
  1427. };
  1428. int luaopen_mqtt( lua_State *L )
  1429. {
  1430. luaL_rometatable(L, "mqtt.socket", (void *)mqtt_socket_map); // create metatable for mqtt.socket
  1431. return 0;
  1432. }
  1433. NODEMCU_MODULE(MQTT, "mqtt", mqtt_map, luaopen_mqtt);