mqtt.c 43 KB

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