coap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. // Module for coapwork
  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 "driver/uart.h"
  12. #include "coap.h"
  13. #include "uri.h"
  14. #include "node.h"
  15. #include "coap_timer.h"
  16. #include "coap_io.h"
  17. #include "coap_server.h"
  18. coap_queue_t *gQueue = NULL;
  19. typedef struct lcoap_userdata
  20. {
  21. lua_State *L;
  22. struct espconn *pesp_conn;
  23. int self_ref;
  24. }lcoap_userdata;
  25. static void coap_received(void *arg, char *pdata, unsigned short len)
  26. {
  27. NODE_DBG("coap_received is called.\n");
  28. struct espconn *pesp_conn = arg;
  29. lcoap_userdata *cud = (lcoap_userdata *)pesp_conn->reverse;
  30. // static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  31. uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  32. c_memset(buf, 0, sizeof(buf)); // wipe prev data
  33. if (len > MAX_MESSAGE_SIZE) {
  34. NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
  35. return;
  36. }
  37. // c_memcpy(buf, pdata, len);
  38. size_t rsplen = coap_server_respond(pdata, len, buf, MAX_MESSAGE_SIZE+1);
  39. // SDK 1.4.0 changed behaviour, for UDP server need to look up remote ip/port
  40. remot_info *pr = 0;
  41. if (espconn_get_connection_info (pesp_conn, &pr, 0) != ESPCONN_OK)
  42. return;
  43. pesp_conn->proto.udp->remote_port = pr->remote_port;
  44. os_memmove (pesp_conn->proto.udp->remote_ip, pr->remote_ip, 4);
  45. // The remot_info apparently should *not* be os_free()d, fyi
  46. espconn_sent(pesp_conn, (unsigned char *)buf, rsplen);
  47. // c_memset(buf, 0, sizeof(buf));
  48. }
  49. static void coap_sent(void *arg)
  50. {
  51. NODE_DBG("coap_sent is called.\n");
  52. }
  53. // Lua: s = coap.create(function(conn))
  54. static int coap_create( lua_State* L, const char* mt )
  55. {
  56. struct espconn *pesp_conn = NULL;
  57. lcoap_userdata *cud;
  58. unsigned type;
  59. int stack = 1;
  60. // create a object
  61. cud = (lcoap_userdata *)lua_newuserdata(L, sizeof(lcoap_userdata));
  62. // pre-initialize it, in case of errors
  63. cud->self_ref = LUA_NOREF;
  64. cud->pesp_conn = NULL;
  65. // set its metatable
  66. luaL_getmetatable(L, mt);
  67. lua_setmetatable(L, -2);
  68. // create the espconn struct
  69. pesp_conn = (struct espconn *)c_zalloc(sizeof(struct espconn));
  70. if(!pesp_conn)
  71. return luaL_error(L, "not enough memory");
  72. cud->pesp_conn = pesp_conn;
  73. pesp_conn->type = ESPCONN_UDP;
  74. pesp_conn->proto.tcp = NULL;
  75. pesp_conn->proto.udp = NULL;
  76. pesp_conn->proto.udp = (esp_udp *)c_zalloc(sizeof(esp_udp));
  77. if(!pesp_conn->proto.udp){
  78. c_free(pesp_conn);
  79. cud->pesp_conn = pesp_conn = NULL;
  80. return luaL_error(L, "not enough memory");
  81. }
  82. pesp_conn->state = ESPCONN_NONE;
  83. NODE_DBG("UDP server/client is set.\n");
  84. cud->L = L;
  85. pesp_conn->reverse = cud;
  86. NODE_DBG("coap_create is called.\n");
  87. return 1;
  88. }
  89. // Lua: server:delete()
  90. static int coap_delete( lua_State* L, const char* mt )
  91. {
  92. struct espconn *pesp_conn = NULL;
  93. lcoap_userdata *cud;
  94. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  95. luaL_argcheck(L, cud, 1, "Server/Client expected");
  96. if(cud==NULL){
  97. NODE_DBG("userdata is nil.\n");
  98. return 0;
  99. }
  100. // free (unref) callback ref
  101. if(LUA_NOREF!=cud->self_ref){
  102. luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
  103. cud->self_ref = LUA_NOREF;
  104. }
  105. cud->L = NULL;
  106. if(cud->pesp_conn)
  107. {
  108. if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
  109. espconn_delete(cud->pesp_conn);
  110. c_free(cud->pesp_conn->proto.udp);
  111. cud->pesp_conn->proto.udp = NULL;
  112. c_free(cud->pesp_conn);
  113. cud->pesp_conn = NULL;
  114. }
  115. NODE_DBG("coap_delete is called.\n");
  116. return 0;
  117. }
  118. // Lua: server:listen( port, ip )
  119. static int coap_start( lua_State* L, const char* mt )
  120. {
  121. struct espconn *pesp_conn = NULL;
  122. lcoap_userdata *cud;
  123. unsigned port;
  124. size_t il;
  125. ip_addr_t ipaddr;
  126. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  127. luaL_argcheck(L, cud, 1, "Server/Client expected");
  128. if(cud==NULL){
  129. NODE_DBG("userdata is nil.\n");
  130. return 0;
  131. }
  132. pesp_conn = cud->pesp_conn;
  133. port = luaL_checkinteger( L, 2 );
  134. pesp_conn->proto.udp->local_port = port;
  135. NODE_DBG("UDP port is set: %d.\n", port);
  136. if( lua_isstring(L,3) ) // deal with the ip string
  137. {
  138. const char *ip = luaL_checklstring( L, 3, &il );
  139. if (ip == NULL)
  140. {
  141. ip = "0.0.0.0";
  142. }
  143. ipaddr.addr = ipaddr_addr(ip);
  144. c_memcpy(pesp_conn->proto.udp->local_ip, &ipaddr.addr, 4);
  145. NODE_DBG("UDP ip is set: ");
  146. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  147. NODE_DBG("\n");
  148. }
  149. if(LUA_NOREF==cud->self_ref){
  150. lua_pushvalue(L, 1); // copy to the top of stack
  151. cud->self_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  152. }
  153. espconn_regist_recvcb(pesp_conn, coap_received);
  154. espconn_regist_sentcb(pesp_conn, coap_sent);
  155. espconn_create(pesp_conn);
  156. NODE_DBG("Coap Server started on port: %d\n", port);
  157. NODE_DBG("coap_start is called.\n");
  158. return 0;
  159. }
  160. // Lua: server:close()
  161. static int coap_close( lua_State* L, const char* mt )
  162. {
  163. struct espconn *pesp_conn = NULL;
  164. lcoap_userdata *cud;
  165. cud = (lcoap_userdata *)luaL_checkudata(L, 1, mt);
  166. luaL_argcheck(L, cud, 1, "Server/Client expected");
  167. if(cud==NULL){
  168. NODE_DBG("userdata is nil.\n");
  169. return 0;
  170. }
  171. if(cud->pesp_conn)
  172. {
  173. if(cud->pesp_conn->proto.udp->remote_port || cud->pesp_conn->proto.udp->local_port)
  174. espconn_delete(cud->pesp_conn);
  175. }
  176. if(LUA_NOREF!=cud->self_ref){
  177. luaL_unref(L, LUA_REGISTRYINDEX, cud->self_ref);
  178. cud->self_ref = LUA_NOREF;
  179. }
  180. NODE_DBG("coap_close is called.\n");
  181. return 0;
  182. }
  183. // Lua: server/client:on( "method", function(s) )
  184. static int coap_on( lua_State* L, const char* mt )
  185. {
  186. NODE_DBG("coap_on is called.\n");
  187. return 0;
  188. }
  189. static void coap_response_handler(void *arg, char *pdata, unsigned short len)
  190. {
  191. NODE_DBG("coap_response_handler is called.\n");
  192. struct espconn *pesp_conn = arg;
  193. coap_packet_t pkt;
  194. pkt.content.p = NULL;
  195. pkt.content.len = 0;
  196. // static uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  197. uint8_t buf[MAX_MESSAGE_SIZE+1] = {0}; // +1 for string '\0'
  198. c_memset(buf, 0, sizeof(buf)); // wipe prev data
  199. int rc;
  200. if( len > MAX_MESSAGE_SIZE )
  201. {
  202. NODE_DBG("Request Entity Too Large.\n"); // NOTE: should response 4.13 to client...
  203. return;
  204. }
  205. c_memcpy(buf, pdata, len);
  206. if (0 != (rc = coap_parse(&pkt, buf, len))){
  207. NODE_DBG("Bad packet rc=%d\n", rc);
  208. }
  209. else
  210. {
  211. #ifdef COAP_DEBUG
  212. coap_dumpPacket(&pkt);
  213. #endif
  214. /* check if this is a response to our original request */
  215. if (!check_token(&pkt)) {
  216. /* drop if this was just some message, or send RST in case of notification */
  217. if (pkt.hdr.t == COAP_TYPE_CON || pkt.hdr.t == COAP_TYPE_NONCON){
  218. // coap_send_rst(pkt); // send RST response
  219. // or, just ignore it.
  220. }
  221. goto end;
  222. }
  223. if (pkt.hdr.t == COAP_TYPE_RESET) {
  224. NODE_DBG("got RST\n");
  225. goto end;
  226. }
  227. uint32_t ip = 0, port = 0;
  228. coap_tid_t id = COAP_INVALID_TID;
  229. c_memcpy(&ip, pesp_conn->proto.udp->remote_ip, sizeof(ip));
  230. port = pesp_conn->proto.udp->remote_port;
  231. coap_transaction_id(ip, port, &pkt, &id);
  232. /* transaction done, remove the node from queue */
  233. // stop timer
  234. coap_timer_stop();
  235. // remove the node
  236. coap_remove_node(&gQueue, id);
  237. // calculate time elapsed
  238. coap_timer_update(&gQueue);
  239. coap_timer_start(&gQueue);
  240. if (COAP_RESPONSE_CLASS(pkt.hdr.code) == 2)
  241. {
  242. /* There is no block option set, just read the data and we are done. */
  243. NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
  244. NODE_DBG((char *)pkt.payload.p);
  245. }
  246. else if (COAP_RESPONSE_CLASS(pkt.hdr.code) >= 4)
  247. {
  248. NODE_DBG("%d.%02d\t", (pkt.hdr.code >> 5), pkt.hdr.code & 0x1F);
  249. NODE_DBG((char *)pkt.payload.p);
  250. }
  251. }
  252. end:
  253. if(!gQueue){ // if there is no node pending in the queue, disconnect from host.
  254. if(pesp_conn->proto.udp->remote_port || pesp_conn->proto.udp->local_port)
  255. espconn_delete(pesp_conn);
  256. }
  257. // c_memset(buf, 0, sizeof(buf));
  258. }
  259. // Lua: client:request( [CON], uri, [payload] )
  260. static int coap_request( lua_State* L, coap_method_t m )
  261. {
  262. struct espconn *pesp_conn = NULL;
  263. lcoap_userdata *cud;
  264. int stack = 1;
  265. cud = (lcoap_userdata *)luaL_checkudata(L, stack, "coap_client");
  266. luaL_argcheck(L, cud, stack, "Server/Client expected");
  267. if(cud==NULL){
  268. NODE_DBG("userdata is nil.\n");
  269. return 0;
  270. }
  271. stack++;
  272. pesp_conn = cud->pesp_conn;
  273. ip_addr_t ipaddr;
  274. uint8_t host[32];
  275. unsigned t;
  276. if ( lua_isnumber(L, stack) )
  277. {
  278. t = lua_tointeger(L, stack);
  279. stack++;
  280. if ( t != COAP_TYPE_CON && t != COAP_TYPE_NONCON )
  281. return luaL_error( L, "wrong arg type" );
  282. } else {
  283. t = COAP_TYPE_CON; // default to CON
  284. }
  285. size_t l;
  286. const char *url = luaL_checklstring( L, stack, &l );
  287. stack++;
  288. if (url == NULL)
  289. return luaL_error( L, "wrong arg type" );
  290. coap_uri_t *uri = coap_new_uri(url, l); // should call free(uri) somewhere
  291. if (uri == NULL)
  292. return luaL_error( L, "uri wrong format." );
  293. pesp_conn->proto.udp->remote_port = uri->port;
  294. NODE_DBG("UDP port is set: %d.\n", uri->port);
  295. pesp_conn->proto.udp->local_port = espconn_port();
  296. if(uri->host.length){
  297. c_memcpy(host, uri->host.s, uri->host.length);
  298. host[uri->host.length] = '\0';
  299. ipaddr.addr = ipaddr_addr(host);
  300. NODE_DBG("Host len(%d):", uri->host.length);
  301. NODE_DBG(host);
  302. NODE_DBG("\n");
  303. c_memcpy(pesp_conn->proto.udp->remote_ip, &ipaddr.addr, 4);
  304. NODE_DBG("UDP ip is set: ");
  305. NODE_DBG(IPSTR, IP2STR(&ipaddr.addr));
  306. NODE_DBG("\n");
  307. }
  308. coap_pdu_t *pdu = coap_new_pdu(); // should call coap_delete_pdu() somewhere
  309. if(!pdu){
  310. if(uri)
  311. c_free(uri);
  312. return luaL_error (L, "alloc fail");
  313. }
  314. const char *payload = NULL;
  315. l = 0;
  316. if( lua_isstring(L, stack) ){
  317. payload = luaL_checklstring( L, stack, &l );
  318. if (payload == NULL)
  319. l = 0;
  320. }
  321. coap_make_request(&(pdu->scratch), pdu->pkt, t, m, uri, payload, l);
  322. #ifdef COAP_DEBUG
  323. coap_dumpPacket(pdu->pkt);
  324. #endif
  325. int rc;
  326. if (0 != (rc = coap_build(pdu->msg.p, &(pdu->msg.len), pdu->pkt))){
  327. NODE_DBG("coap_build failed rc=%d\n", rc);
  328. }
  329. else
  330. {
  331. #ifdef COAP_DEBUG
  332. NODE_DBG("Sending: ");
  333. coap_dump(pdu->msg.p, pdu->msg.len, true);
  334. NODE_DBG("\n");
  335. #endif
  336. espconn_regist_recvcb(pesp_conn, coap_response_handler);
  337. sint8_t con = espconn_create(pesp_conn);
  338. if( ESPCONN_OK != con){
  339. NODE_DBG("Connect to host. code:%d\n", con);
  340. // coap_delete_pdu(pdu);
  341. }
  342. // else
  343. {
  344. coap_tid_t tid = COAP_INVALID_TID;
  345. if (pdu->pkt->hdr.t == COAP_TYPE_CON){
  346. tid = coap_send_confirmed(pesp_conn, pdu);
  347. }
  348. else {
  349. tid = coap_send(pesp_conn, pdu);
  350. }
  351. if (pdu->pkt->hdr.t != COAP_TYPE_CON || tid == COAP_INVALID_TID){
  352. coap_delete_pdu(pdu);
  353. }
  354. }
  355. }
  356. if(uri)
  357. c_free((void *)uri);
  358. NODE_DBG("coap_request is called.\n");
  359. return 0;
  360. }
  361. extern coap_luser_entry *variable_entry;
  362. extern coap_luser_entry *function_entry;
  363. // Lua: coap:var/func( string )
  364. static int coap_regist( lua_State* L, const char* mt, int isvar )
  365. {
  366. size_t l;
  367. const char *name = luaL_checklstring( L, 2, &l );
  368. int content_type = luaL_optint(L, 3, COAP_CONTENTTYPE_TEXT_PLAIN);
  369. if (name == NULL)
  370. return luaL_error( L, "name must be set." );
  371. coap_luser_entry *h = NULL;
  372. // if(lua_isstring(L, 3))
  373. if(isvar)
  374. h = variable_entry;
  375. else
  376. h = function_entry;
  377. while(NULL!=h->next){ // goto the end of the list
  378. if(h->name!= NULL && c_strcmp(h->name, name)==0) // key exist, override it
  379. break;
  380. h = h->next;
  381. }
  382. if(h->name==NULL || c_strcmp(h->name, name)!=0){ // not exists. make a new one.
  383. h->next = (coap_luser_entry *)c_zalloc(sizeof(coap_luser_entry));
  384. h = h->next;
  385. if(h == NULL)
  386. return luaL_error(L, "not enough memory");
  387. h->next = NULL;
  388. h->name = NULL;
  389. h->L = NULL;
  390. }
  391. h->L = L;
  392. h->name = name;
  393. h->content_type = content_type;
  394. NODE_DBG("coap_regist is called.\n");
  395. return 0;
  396. }
  397. // Lua: s = coap.createServer(function(conn))
  398. static int coap_createServer( lua_State* L )
  399. {
  400. const char *mt = "coap_server";
  401. return coap_create(L, mt);
  402. }
  403. // Lua: server:delete()
  404. static int coap_server_delete( lua_State* L )
  405. {
  406. const char *mt = "coap_server";
  407. return coap_delete(L, mt);
  408. }
  409. // Lua: server:listen( port, ip, function(err) )
  410. static int coap_server_listen( lua_State* L )
  411. {
  412. const char *mt = "coap_server";
  413. return coap_start(L, mt);
  414. }
  415. // Lua: server:close()
  416. static int coap_server_close( lua_State* L )
  417. {
  418. const char *mt = "coap_server";
  419. return coap_close(L, mt);
  420. }
  421. // Lua: server:on( "method", function(server) )
  422. static int coap_server_on( lua_State* L )
  423. {
  424. const char *mt = "coap_server";
  425. return coap_on(L, mt);
  426. }
  427. // Lua: server:var( "name" )
  428. static int coap_server_var( lua_State* L )
  429. {
  430. const char *mt = "coap_server";
  431. return coap_regist(L, mt, 1);
  432. }
  433. // Lua: server:func( "name" )
  434. static int coap_server_func( lua_State* L )
  435. {
  436. const char *mt = "coap_server";
  437. return coap_regist(L, mt, 0);
  438. }
  439. // Lua: s = coap.createClient(function(conn))
  440. static int coap_createClient( lua_State* L )
  441. {
  442. const char *mt = "coap_client";
  443. return coap_create(L, mt);
  444. }
  445. // Lua: client:gcdelete()
  446. static int coap_client_gcdelete( lua_State* L )
  447. {
  448. const char *mt = "coap_client";
  449. return coap_delete(L, mt);
  450. }
  451. // client:get( string, function(sent) )
  452. static int coap_client_get( lua_State* L )
  453. {
  454. return coap_request(L, COAP_METHOD_GET);
  455. }
  456. // client:post( string, function(sent) )
  457. static int coap_client_post( lua_State* L )
  458. {
  459. return coap_request(L, COAP_METHOD_POST);
  460. }
  461. // client:put( string, function(sent) )
  462. static int coap_client_put( lua_State* L )
  463. {
  464. return coap_request(L, COAP_METHOD_PUT);
  465. }
  466. // client:delete( string, function(sent) )
  467. static int coap_client_delete( lua_State* L )
  468. {
  469. return coap_request(L, COAP_METHOD_DELETE);
  470. }
  471. // Module function map
  472. static const LUA_REG_TYPE coap_server_map[] = {
  473. { LSTRKEY( "listen" ), LFUNCVAL( coap_server_listen ) },
  474. { LSTRKEY( "close" ), LFUNCVAL( coap_server_close ) },
  475. { LSTRKEY( "var" ), LFUNCVAL( coap_server_var ) },
  476. { LSTRKEY( "func" ), LFUNCVAL( coap_server_func ) },
  477. { LSTRKEY( "__gc" ), LFUNCVAL( coap_server_delete ) },
  478. { LSTRKEY( "__index" ), LROVAL( coap_server_map ) },
  479. { LNILKEY, LNILVAL }
  480. };
  481. static const LUA_REG_TYPE coap_client_map[] = {
  482. { LSTRKEY( "get" ), LFUNCVAL( coap_client_get ) },
  483. { LSTRKEY( "post" ), LFUNCVAL( coap_client_post ) },
  484. { LSTRKEY( "put" ), LFUNCVAL( coap_client_put ) },
  485. { LSTRKEY( "delete" ), LFUNCVAL( coap_client_delete ) },
  486. { LSTRKEY( "__gc" ), LFUNCVAL( coap_client_gcdelete ) },
  487. { LSTRKEY( "__index" ), LROVAL( coap_client_map ) },
  488. { LNILKEY, LNILVAL }
  489. };
  490. static const LUA_REG_TYPE coap_map[] =
  491. {
  492. { LSTRKEY( "Server" ), LFUNCVAL( coap_createServer ) },
  493. { LSTRKEY( "Client" ), LFUNCVAL( coap_createClient ) },
  494. { LSTRKEY( "CON" ), LNUMVAL( COAP_TYPE_CON ) },
  495. { LSTRKEY( "NON" ), LNUMVAL( COAP_TYPE_NONCON ) },
  496. { LSTRKEY( "TEXT_PLAIN"), LNUMVAL( COAP_CONTENTTYPE_TEXT_PLAIN ) },
  497. { LSTRKEY( "LINKFORMAT"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_LINKFORMAT ) },
  498. { LSTRKEY( "XML"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_XML ) },
  499. { LSTRKEY( "OCTET_STREAM"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_OCTET_STREAM ) },
  500. { LSTRKEY( "EXI"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_EXI ) },
  501. { LSTRKEY( "JSON"), LNUMVAL( COAP_CONTENTTYPE_APPLICATION_JSON) },
  502. { LSTRKEY( "__metatable" ), LROVAL( coap_map ) },
  503. { LNILKEY, LNILVAL }
  504. };
  505. int luaopen_coap( lua_State *L )
  506. {
  507. endpoint_setup();
  508. luaL_rometatable(L, "coap_server", (void *)coap_server_map); // create metatable for coap_server
  509. luaL_rometatable(L, "coap_client", (void *)coap_client_map); // create metatable for coap_client
  510. return 0;
  511. }
  512. NODEMCU_MODULE(COAP, "coap", coap_map, luaopen_coap);