luat_lib_websocket.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. /*
  2. @module websocket
  3. @summary websocket客户端
  4. @version 1.0
  5. @date 2022.11.28
  6. @demo websocket
  7. @usage
  8. local wsc = nil
  9. if websocket then
  10. wsc = websocket.create(nil, "ws://echo.airtun.air32.cn/ws/echo")
  11. wsc:autoreconn(true, 3000) -- 自动重连机制
  12. wsc:on(function(wsc, event, data, fin, optcode)
  13. wsc:on(function(wsc, event, data)
  14. log.info("wsc", event, data)
  15. if event == "conack" then
  16. wsc:send((json.encode({action="echo", device_id=device_id})))
  17. sys.publish("wsc_conack")
  18. end
  19. end)
  20. wsc:connect()
  21. --sys.waitUntil("websocket_conack", 15000)
  22. while true do
  23. sys.wait(45000)
  24. if wsc:ready() then
  25. wsc:send((json.encode({action="echo", msg=os.date()})))
  26. end
  27. end
  28. wsc:close()
  29. wsc = nil
  30. end
  31. */
  32. #include "luat_base.h"
  33. #include "luat_network_adapter.h"
  34. #include "luat_rtos.h"
  35. #include "luat_zbuff.h"
  36. #include "luat_malloc.h"
  37. #include "luat_websocket.h"
  38. #define LUAT_LOG_TAG "websocket"
  39. #include "luat_log.h"
  40. #define LUAT_WEBSOCKET_CTRL_TYPE "WS*"
  41. static luat_websocket_ctrl_t *get_websocket_ctrl(lua_State *L)
  42. {
  43. if (luaL_testudata(L, 1, LUAT_WEBSOCKET_CTRL_TYPE))
  44. {
  45. return ((luat_websocket_ctrl_t *)luaL_checkudata(L, 1, LUAT_WEBSOCKET_CTRL_TYPE));
  46. }
  47. else
  48. {
  49. return ((luat_websocket_ctrl_t *)lua_touserdata(L, 1));
  50. }
  51. }
  52. static int32_t l_websocket_callback(lua_State *L, void *ptr)
  53. {
  54. (void)ptr;
  55. rtos_msg_t *msg = (rtos_msg_t *)lua_topointer(L, -1);
  56. luat_websocket_ctrl_t *websocket_ctrl = (luat_websocket_ctrl_t *)msg->ptr;
  57. luat_websocket_pkg_t pkg = {0};
  58. // size_t payload_size = 0;
  59. switch (msg->arg1)
  60. {
  61. case WEBSOCKET_MSG_TIMER_PING:
  62. {
  63. luat_websocket_ping(websocket_ctrl);
  64. break;
  65. }
  66. case WEBSOCKET_MSG_RECONNECT:
  67. {
  68. luat_websocket_reconnect(websocket_ctrl);
  69. break;
  70. }
  71. case WEBSOCKET_MSG_PUBLISH:
  72. {
  73. if (websocket_ctrl->websocket_cb)
  74. {
  75. lua_geti(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_cb);
  76. if (lua_isfunction(L, -1))
  77. {
  78. lua_geti(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_ref);
  79. lua_pushstring(L, "recv");
  80. luat_websocket_payload((char *)msg->arg2, &pkg, 64 * 1024);
  81. lua_pushlstring(L, pkg.payload, pkg.plen);
  82. lua_pushinteger(L, pkg.FIN);
  83. lua_pushinteger(L, pkg.OPT_CODE);
  84. lua_call(L, 5, 0);
  85. }
  86. }
  87. luat_heap_free((char *)msg->arg2);
  88. break;
  89. }
  90. case WEBSOCKET_MSG_CONNACK:
  91. {
  92. if (websocket_ctrl->websocket_cb)
  93. {
  94. lua_geti(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_cb);
  95. if (lua_isfunction(L, -1))
  96. {
  97. lua_geti(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_ref);
  98. lua_pushstring(L, "conack");
  99. lua_call(L, 2, 0);
  100. }
  101. lua_getglobal(L, "sys_pub");
  102. if (lua_isfunction(L, -1))
  103. {
  104. lua_pushstring(L, "WEBSOCKET_CONNACK");
  105. lua_geti(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_ref);
  106. lua_call(L, 2, 0);
  107. }
  108. }
  109. break;
  110. }
  111. case WEBSOCKET_MSG_RELEASE:
  112. {
  113. if (websocket_ctrl->websocket_ref)
  114. {
  115. luaL_unref(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_ref);
  116. websocket_ctrl->websocket_ref = 0;
  117. }
  118. break;
  119. }
  120. default:
  121. {
  122. LLOGD("l_websocket_callback error arg1:%d", msg->arg1);
  123. break;
  124. }
  125. }
  126. // lua_pushinteger(L, 0);
  127. return 0;
  128. }
  129. int l_luat_websocket_msg_cb(luat_websocket_ctrl_t *ctrl, int arg1, int arg2)
  130. {
  131. rtos_msg_t msg = {
  132. .handler = l_websocket_callback,
  133. .ptr = ctrl,
  134. .arg1 = arg1,
  135. .arg2 = arg2,
  136. };
  137. luat_msgbus_put(&msg, 0);
  138. return 0;
  139. }
  140. /*
  141. 配置是否打开debug信息
  142. @api wsc:debug(onoff)
  143. @boolean 是否打开debug开关
  144. @return nil 无返回值
  145. @usage wsc:debug(true)
  146. */
  147. static int l_websocket_set_debug(lua_State *L)
  148. {
  149. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  150. if (lua_isboolean(L, 2))
  151. {
  152. websocket_ctrl->netc->is_debug = lua_toboolean(L, 2);
  153. }
  154. return 0;
  155. }
  156. /*
  157. websocket客户端创建
  158. @api websocket.create(adapter, url)
  159. @int 适配器序号, 只能是socket.ETH0, socket.STA, socket.AP,如果不填,会选择平台自带的方式,然后是最后一个注册的适配器
  160. @string 连接字符串,参考usage
  161. @return userdata 若成功会返回websocket客户端实例,否则返回nil
  162. @usage
  163. -- 普通TCP链接
  164. wsc = websocket.create(nil,"ws://air32.cn/abc")
  165. -- 加密TCP链接
  166. wsc = websocket.create(nil,"wss://air32.cn/abc")
  167. */
  168. static int l_websocket_create(lua_State *L)
  169. {
  170. int ret = 0;
  171. int adapter_index = luaL_optinteger(L, 1, network_get_last_register_adapter());
  172. if (adapter_index < 0 || adapter_index >= NW_ADAPTER_QTY)
  173. {
  174. return 0;
  175. }
  176. luat_websocket_ctrl_t *websocket_ctrl = (luat_websocket_ctrl_t *)lua_newuserdata(L, sizeof(luat_websocket_ctrl_t));
  177. if (!websocket_ctrl)
  178. {
  179. LLOGE("out of memory when malloc websocket_ctrl");
  180. return 0;
  181. }
  182. ret = luat_websocket_init(websocket_ctrl, adapter_index);
  183. if (ret)
  184. {
  185. LLOGE("websocket init FAID ret %d", ret);
  186. return 0;
  187. }
  188. luat_websocket_connopts_t opts = {0};
  189. // 连接参数相关
  190. // const char *ip;
  191. size_t ip_len = 0;
  192. #ifdef LUAT_USE_LWIP
  193. websocket_ctrl->ip_addr.type = 0xff;
  194. #else
  195. websocket_ctrl->ip_addr.is_ipv6 = 0xff;
  196. #endif
  197. opts.url = luaL_checklstring(L, 2, &ip_len);
  198. ret = luat_websocket_set_connopts(websocket_ctrl, luaL_checklstring(L, 2, &ip_len));
  199. // TODO 判断ret, 如果初始化失败, 应该终止
  200. luaL_setmetatable(L, LUAT_WEBSOCKET_CTRL_TYPE);
  201. lua_pushvalue(L, -1);
  202. websocket_ctrl->websocket_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  203. return 1;
  204. }
  205. /*
  206. 注册websocket回调
  207. @api wsc:on(cb)
  208. @function cb websocket回调,参数包括websocket_client, event, data, payload
  209. @return nil 无返回值
  210. @usage
  211. wsc:on(function(websocket_client, event, data, payload)
  212. -- 用户自定义代码
  213. log.info("websocket", "event", event, websocket_client, data, payload)
  214. end)
  215. */
  216. static int l_websocket_on(lua_State *L)
  217. {
  218. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  219. if (websocket_ctrl->websocket_cb != 0)
  220. {
  221. luaL_unref(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_cb);
  222. websocket_ctrl->websocket_cb = 0;
  223. }
  224. if (lua_isfunction(L, 2))
  225. {
  226. lua_pushvalue(L, 2);
  227. websocket_ctrl->websocket_cb = luaL_ref(L, LUA_REGISTRYINDEX);
  228. }
  229. return 0;
  230. }
  231. /*
  232. 连接服务器
  233. @api wsc:connect()
  234. @return boolean 发起成功返回true, 否则返回false
  235. @usage
  236. -- 开始建立连接
  237. wsc:connect()
  238. -- 本函数仅代表发起成功, 后续仍需根据ready函数判断websocket是否连接正常
  239. */
  240. static int l_websocket_connect(lua_State *L)
  241. {
  242. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  243. int ret = luat_websocket_connect(websocket_ctrl);
  244. if (ret)
  245. {
  246. LLOGE("socket connect ret=%d\n", ret);
  247. luat_websocket_close_socket(websocket_ctrl);
  248. lua_pushboolean(L, 0);
  249. return 1;
  250. }
  251. lua_pushboolean(L, 1);
  252. return 1;
  253. }
  254. /*
  255. 自动重连
  256. @api wsc:autoreconn(reconnect, reconnect_time)
  257. @bool 是否自动重连
  258. @int 自动重连周期 单位ms 默认3000ms
  259. @usage
  260. wsc:autoreconn(true)
  261. */
  262. static int l_websocket_autoreconn(lua_State *L)
  263. {
  264. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  265. if (lua_isboolean(L, 2))
  266. {
  267. websocket_ctrl->reconnect = lua_toboolean(L, 2);
  268. }
  269. websocket_ctrl->reconnect_time = luaL_optinteger(L, 3, 3000);
  270. if (websocket_ctrl->reconnect && websocket_ctrl->reconnect_time < 1000)
  271. websocket_ctrl->reconnect_time = 1000;
  272. return 0;
  273. }
  274. /*
  275. 发布消息
  276. @api wsc:send(data, fin, opt)
  277. @string 待发送的数据,必填
  278. @int 是否为最后一帧,默认1
  279. @int 操作码, 默认为字符串帧
  280. @return bool 成功返回true,否则为false或者nil
  281. @usage
  282. wsc:publish("/luatos/123456", "123")
  283. */
  284. static int l_websocket_send(lua_State *L)
  285. {
  286. size_t payload_len = 0;
  287. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  288. const char *payload = NULL;
  289. luat_zbuff_t *buff = NULL;
  290. int ret = 0;
  291. if (lua_isstring(L, 2))
  292. {
  293. payload = luaL_checklstring(L, 2, &payload_len);
  294. }
  295. else if (luaL_testudata(L, 2, LUAT_ZBUFF_TYPE))
  296. {
  297. buff = ((luat_zbuff_t *)luaL_checkudata(L, 2, LUAT_ZBUFF_TYPE));
  298. payload = (const char *)buff->addr;
  299. payload_len = buff->used;
  300. }
  301. else
  302. {
  303. LLOGD("only support string or zbuff");
  304. return 0;
  305. }
  306. luat_websocket_pkg_t pkg = {
  307. .FIN = 1,
  308. .OPT_CODE = 0x01,
  309. .plen = payload_len,
  310. .payload = payload};
  311. ret = luat_websocket_send_frame(websocket_ctrl, &pkg);
  312. lua_pushboolean(L, ret == 0 ? 1 : 0);
  313. return 1;
  314. }
  315. /*
  316. websocket客户端关闭(关闭后资源释放无法再使用)
  317. @api wsc:close()
  318. @usage
  319. wsc:close()
  320. */
  321. static int l_websocket_close(lua_State *L)
  322. {
  323. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  324. // websocket_disconnect(&(websocket_ctrl->broker));
  325. luat_websocket_close_socket(websocket_ctrl);
  326. if (websocket_ctrl->websocket_cb != 0)
  327. {
  328. luaL_unref(L, LUA_REGISTRYINDEX, websocket_ctrl->websocket_cb);
  329. websocket_ctrl->websocket_cb = 0;
  330. }
  331. luat_websocket_release_socket(websocket_ctrl);
  332. return 0;
  333. }
  334. /*
  335. websocket客户端是否就绪
  336. @api wsc:ready()
  337. @return bool 客户端是否就绪
  338. @usage
  339. local stat = wsc:ready()
  340. */
  341. static int l_websocket_ready(lua_State *L)
  342. {
  343. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  344. lua_pushboolean(L, websocket_ctrl->websocket_state > 0 ? 1 : 0);
  345. return 1;
  346. }
  347. /*
  348. 设置额外的headers
  349. @api wsc:headers(headers)
  350. @table/string 可以是table,也可以是字符串
  351. @return bool 客户端是否就绪
  352. @usage
  353. -- table形式
  354. wsc:headers({
  355. Auth="Basic ABCDEFGG"
  356. })
  357. -- 字符串形式
  358. wsc:headers("Auth: Basic ABCDERG\r\n")
  359. */
  360. static int l_websocket_headers(lua_State *L)
  361. {
  362. luat_websocket_ctrl_t *websocket_ctrl = get_websocket_ctrl(L);
  363. if (!lua_istable(L, 2) && !lua_isstring(L, 2)) {
  364. return 0;
  365. }
  366. #define WS_HEADER_MAX (1024)
  367. char* buff = luat_heap_malloc(WS_HEADER_MAX);
  368. memset(buff, 0, WS_HEADER_MAX);
  369. if (lua_istable(L, 2)) {
  370. size_t name_sz = 0;
  371. size_t value_sz = 0;
  372. lua_pushnil(L);
  373. while (lua_next(L, 2) != 0) {
  374. const char *name = lua_tolstring(L, -2, &name_sz);
  375. const char *value = lua_tolstring(L, -1, &value_sz);
  376. if (name_sz == 0 || value_sz == 0 || name_sz + value_sz > 256) {
  377. LLOGW("bad header %s %s", name, value);
  378. luat_heap_free(buff);
  379. return 0;
  380. }
  381. memcpy(buff + strlen(buff), name, name_sz);
  382. memcpy(buff + strlen(buff), ":", 1);
  383. if (WS_HEADER_MAX - strlen(buff) < value_sz * 2) {
  384. LLOGW("bad header %s %s, too large", name, value);
  385. luat_heap_free(buff);
  386. return 0;
  387. }
  388. for (size_t i = 0; i < value_sz; i++)
  389. {
  390. switch (value[i])
  391. {
  392. case '*':
  393. case '-':
  394. case '.':
  395. case '_':
  396. case ' ':
  397. sprintf_(buff + strlen(buff), "%%%02X", value[i]);
  398. break;
  399. default:
  400. buff[strlen(buff)] = value[i];
  401. break;
  402. }
  403. }
  404. lua_pop(L, 1);
  405. memcpy(buff + strlen(buff), "\r\n", 2);
  406. }
  407. }
  408. else {
  409. size_t len = 0;
  410. const char* data = luaL_checklstring(L, 2, &len);
  411. if (len > 1023) {
  412. LLOGW("headers too large size %d", len);
  413. luat_heap_free(buff);
  414. return 0;
  415. }
  416. memcpy(buff, data, len);
  417. }
  418. luat_websocket_set_headers(websocket_ctrl, buff);
  419. lua_pushboolean(L, 1);
  420. return 1;
  421. }
  422. static int _websocket_struct_newindex(lua_State *L);
  423. void luat_websocket_struct_init(lua_State *L)
  424. {
  425. luaL_newmetatable(L, LUAT_WEBSOCKET_CTRL_TYPE);
  426. lua_pushcfunction(L, _websocket_struct_newindex);
  427. lua_setfield(L, -2, "__index");
  428. lua_pop(L, 1);
  429. }
  430. #include "rotable2.h"
  431. const rotable_Reg_t reg_websocket[] =
  432. {
  433. {"create", ROREG_FUNC(l_websocket_create)},
  434. {"on", ROREG_FUNC(l_websocket_on)},
  435. {"connect", ROREG_FUNC(l_websocket_connect)},
  436. {"autoreconn", ROREG_FUNC(l_websocket_autoreconn)},
  437. {"send", ROREG_FUNC(l_websocket_send)},
  438. {"close", ROREG_FUNC(l_websocket_close)},
  439. {"ready", ROREG_FUNC(l_websocket_ready)},
  440. {"headers", ROREG_FUNC(l_websocket_headers)},
  441. {"debug", ROREG_FUNC(l_websocket_set_debug)},
  442. {NULL, ROREG_INT(0)}
  443. };
  444. int _websocket_struct_newindex(lua_State *L)
  445. {
  446. const rotable_Reg_t *reg = reg_websocket;
  447. const char *key = luaL_checkstring(L, 2);
  448. while (1)
  449. {
  450. if (reg->name == NULL)
  451. return 0;
  452. if (!strcmp(reg->name, key))
  453. {
  454. lua_pushcfunction(L, reg->value.value.func);
  455. return 1;
  456. }
  457. reg++;
  458. }
  459. // return 0;
  460. }
  461. #ifndef LUAT_USE_NETWORK
  462. static const rotable_Reg_t reg_websocket_emtry[] = {
  463. {NULL, ROREG_INT(0)}
  464. };
  465. #endif
  466. LUAMOD_API int luaopen_websocket(lua_State *L)
  467. {
  468. #ifdef LUAT_USE_NETWORK
  469. luat_newlib2(L, reg_websocket);
  470. luat_websocket_struct_init(L);
  471. return 1;
  472. #else
  473. LLOGE("websocket require network enable!!");
  474. luat_newlib2(L, reg_websocket_emtry);
  475. return 1;
  476. #endif
  477. }