mqtt.c 51 KB

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