luat_lib_mqtt.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. /*
  2. @module mqtt
  3. @summary mqtt客户端
  4. @version 1.0
  5. @date 2022.08.25
  6. @demo mqtt
  7. @tag LUAT_USE_NETWORK
  8. @usage
  9. -- 具体用法请查看demo
  10. -- 本库只支持 mqtt 3.1.1, 其他版本例如3.1 或 5 均不支持!!!
  11. -- 现已支持 MQTT over WebSocket(ws/wss),--曾帅 2025-09-23
  12. -- 几个大前提:
  13. -- 本库是基于TCP链接的, 支持加密TCP和非加密TCP
  14. -- 任何通信失败都将断开连接, 如果开启了自动重连, 那么间隔N秒后开始自动重连
  15. -- 上行数据均为一次性的, 没有缓存机制, 更没有上行的重试/重发机制
  16. -- 如何获知发送成功: 触发 mqttc:on 中 event == "sent" 的事件
  17. -- 关于publish时QOS值的说明, 特制模块上行到云端/服务器端的行为:
  18. -- QOS0, 压入底层TCP发送堆栈,视为成功
  19. -- QOS1, 收到服务器回应PUBACK,视为成功
  20. -- QOS2, 收到服务器响应PUBREC,立即上行PUBCOMP压入TCP发送队列,视为成功
  21. -- 重要的事情说3次: 没有重发机制, 没有重发机制, 没有重发机制
  22. -- 1. MQTT协议中规定了重发机制, 但那是云端/服务器端才会实现的机制, 模块端是没有的
  23. -- 2. 上行失败, 唯一的可能性就是TCP链接出问题了, 而TCP链接出问题的解决办法就是重连
  24. -- 3. 模块端不会保存任何上行数据, 重连后也无法实现重发
  25. -- 那业务需要确定上行是否成功, 如何解决:
  26. -- 首先推荐使用 QOS1, 然后监听/判断sent事件,并选取一个超时时间, 就能满足99.9%的需求
  27. -- 使用QOS2,反而存在PUBCOMP上行失败导致服务器端不广播数据的理论可能
  28. -- demo里有演示等待sent事件的代码, 类似于 sys.waitUntil("mqtt_sent", 3000) 搜mqtt_sent关键字
  29. */
  30. #include "luat_base.h"
  31. #include "luat_network_adapter.h"
  32. #include "libemqtt.h"
  33. #include "luat_rtos.h"
  34. #include "luat_zbuff.h"
  35. #include "luat_mem.h"
  36. #include "luat_mqtt.h"
  37. #define LUAT_LOG_TAG "mqtt"
  38. #include "luat_log.h"
  39. #define LUAT_MQTT_CTRL_TYPE "MQTTCTRL*"
  40. #ifdef LUAT_USE_NETDRV
  41. #include "luat_netdrv.h"
  42. #include "luat_netdrv_event.h"
  43. #endif
  44. static const char *error_string[MQTT_MSG_NET_ERROR - MQTT_MSG_CON_ERROR + 1] =
  45. {
  46. "connect",
  47. "tx",
  48. "conack",
  49. "other"
  50. };
  51. static luat_mqtt_ctrl_t * get_mqtt_ctrl(lua_State *L){
  52. if (luaL_testudata(L, 1, LUAT_MQTT_CTRL_TYPE)){
  53. return ((luat_mqtt_ctrl_t *)luaL_checkudata(L, 1, LUAT_MQTT_CTRL_TYPE));
  54. }else{
  55. return ((luat_mqtt_ctrl_t *)lua_touserdata(L, 1));
  56. }
  57. }
  58. int32_t luatos_mqtt_callback(lua_State *L, void* ptr){
  59. (void)ptr;
  60. rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
  61. luat_mqtt_ctrl_t *mqtt_ctrl =(luat_mqtt_ctrl_t *)msg->ptr;
  62. switch (msg->arg1) {
  63. // case MQTT_MSG_TCP_TX_DONE:
  64. // if (mqtt_ctrl->mqtt_cb) {
  65. // lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  66. // if (lua_isfunction(L, -1)) {
  67. // lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  68. // lua_pushstring(L, "tcp_ack");
  69. // lua_call(L, 2, 0);
  70. // }
  71. // }
  72. // break;
  73. case MQTT_MSG_TIMER_PING : {
  74. luat_mqtt_ping(mqtt_ctrl);
  75. break;
  76. }
  77. case MQTT_MSG_CONN_TIMEOUT: {
  78. LLOGW("connect timeout %s %d!! expect conack in %ds", mqtt_ctrl->host, mqtt_ctrl->remote_port, mqtt_ctrl->conn_timeout);
  79. #ifdef LUAT_USE_NETDRV
  80. luat_netdrv_fire_socket_event_netctrl(EV_NW_TIMEOUT, mqtt_ctrl->netc, 4);
  81. #endif
  82. if (mqtt_ctrl->mqtt_ref) {
  83. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  84. if (lua_isfunction(L, -1)) {
  85. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  86. lua_pushstring(L, "error");
  87. lua_pushstring(L, "timeout");
  88. lua_pushinteger(L, msg->arg2);
  89. lua_call(L, 4, 0);
  90. }
  91. }
  92. luat_mqtt_close_socket(mqtt_ctrl);
  93. break;
  94. }
  95. case MQTT_MSG_PINGRESP : {
  96. if (mqtt_ctrl->mqtt_cb) {
  97. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  98. if (lua_isfunction(L, -1)) {
  99. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  100. lua_pushstring(L, "pong");
  101. lua_call(L, 2, 0);
  102. }
  103. lua_getglobal(L, "sys_pub");
  104. if (lua_isfunction(L, -1)) {
  105. lua_pushstring(L, "MQTT_PONG");
  106. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  107. lua_call(L, 2, 0);
  108. }
  109. }
  110. break;
  111. }
  112. case MQTT_MSG_RECONNECT : {
  113. luat_mqtt_reconnect(mqtt_ctrl);
  114. break;
  115. }
  116. case MQTT_MSG_PUBLISH : {
  117. luat_mqtt_msg_t *mqtt_msg =(luat_mqtt_msg_t *)msg->arg2;
  118. if (mqtt_ctrl->mqtt_cb) {
  119. // luat_mqtt_msg_t *mqtt_msg =(luat_mqtt_msg_t *)msg->arg2;
  120. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  121. if (lua_isfunction(L, -1)) {
  122. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  123. lua_pushstring(L, "recv");
  124. lua_pushlstring(L, (const char*)(mqtt_msg->data),mqtt_msg->topic_len);
  125. lua_pushlstring(L, (const char*)(mqtt_msg->data+mqtt_msg->topic_len),mqtt_msg->payload_len);
  126. // 增加一个返回值meta,类型为table,包含qos、retain和dup
  127. // mqttc:on(function(mqtt_client, event, data, payload, meta)
  128. // if event == "recv" then
  129. // log.info("mqtt recv", "topic", data)
  130. // log.info("mqtt recv", 'payload', payload)
  131. // log.info("mqtt recv", 'meta.message_id', meta.message_id)
  132. // log.info("mqtt recv", 'meta.qos', meta.qos)
  133. // log.info("mqtt recv", 'meta.retain', meta.retain)
  134. // log.info("mqtt recv", 'meta.dup', meta.dup)
  135. lua_createtable(L, 0, 4);
  136. lua_pushliteral(L, "message_id");
  137. lua_pushinteger(L, mqtt_msg->message_id);
  138. lua_settable(L, -3);
  139. lua_pushliteral(L, "qos");
  140. lua_pushinteger(L, (mqtt_msg->flags & 0x06) >> 1);
  141. // lua_pushinteger(L, MQTTParseMessageQos(mqtt_ctrl->mqtt_packet_buffer));
  142. lua_settable(L, -3);
  143. lua_pushliteral(L, "retain");
  144. lua_pushinteger(L, mqtt_msg->flags & 0x01);
  145. // lua_pushinteger(L, MQTTParseMessageRetain(mqtt_ctrl->mqtt_packet_buffer));
  146. lua_settable(L, -3);
  147. lua_pushliteral(L, "dup");
  148. lua_pushinteger(L, (mqtt_msg->flags & 0x08)?1:0);
  149. // lua_pushinteger(L, MQTTParseMessageDuplicate(mqtt_ctrl->mqtt_packet_buffer));
  150. lua_settable(L, -3);
  151. lua_call(L, 5, 0);
  152. }
  153. }
  154. luat_heap_free(mqtt_msg);
  155. break;
  156. }
  157. case MQTT_MSG_CONNACK: {
  158. if (mqtt_ctrl->mqtt_cb) {
  159. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  160. if (lua_isfunction(L, -1)) {
  161. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  162. lua_pushstring(L, "conack");
  163. lua_call(L, 2, 0);
  164. }
  165. // lua_getglobal(L, "sys_pub");
  166. // if (lua_isfunction(L, -1)) {
  167. // lua_pushstring(L, "MQTT_CONNACK");
  168. // lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  169. // lua_call(L, 2, 0);
  170. // }
  171. }
  172. break;
  173. }
  174. case MQTT_MSG_PUBACK:
  175. case MQTT_MSG_PUBCOMP: {
  176. if (mqtt_ctrl->mqtt_cb) {
  177. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  178. if (lua_isfunction(L, -1)) {
  179. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  180. lua_pushstring(L, "sent");
  181. lua_pushinteger(L, msg->arg2);
  182. lua_call(L, 3, 0);
  183. }
  184. }
  185. break;
  186. }
  187. case MQTT_MSG_RELEASE: {
  188. if (mqtt_ctrl->mqtt_ref) {
  189. luaL_unref(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  190. mqtt_ctrl->mqtt_ref = 0;
  191. }
  192. break;
  193. }
  194. case MQTT_MSG_CLOSE: {
  195. if (mqtt_ctrl->mqtt_ref) {
  196. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  197. if (lua_isfunction(L, -1)) {
  198. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  199. lua_pushstring(L, "close");
  200. lua_call(L, 2, 0);
  201. }
  202. }
  203. break;
  204. }
  205. case MQTT_MSG_DISCONNECT: {
  206. if (mqtt_ctrl->mqtt_cb) {
  207. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  208. if (lua_isfunction(L, -1)) {
  209. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  210. lua_pushstring(L, "disconnect");
  211. lua_pushinteger(L, mqtt_ctrl->error_state);
  212. lua_call(L, 3, 0);
  213. }
  214. // lua_getglobal(L, "sys_pub");
  215. // if (lua_isfunction(L, -1)) {
  216. // lua_pushstring(L, "MQTT_DISCONNECT");
  217. // lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  218. // lua_pushinteger(L, mqtt_ctrl->error_state);
  219. // lua_call(L, 3, 0);
  220. // }
  221. }
  222. break;
  223. }
  224. case MQTT_MSG_SUBACK:
  225. if (mqtt_ctrl->mqtt_cb) {
  226. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  227. if (lua_isfunction(L, -1)) {
  228. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  229. lua_pushstring(L, "suback");
  230. lua_pushboolean(L, (msg->arg2 <= 2));
  231. lua_pushinteger(L, msg->arg2);
  232. lua_call(L, 4, 0);
  233. }
  234. }
  235. break;
  236. case MQTT_MSG_UNSUBACK:
  237. if (mqtt_ctrl->mqtt_cb) {
  238. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  239. if (lua_isfunction(L, -1)) {
  240. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  241. lua_pushstring(L, "unsuback");
  242. lua_call(L, 2, 0);
  243. }
  244. }
  245. break;
  246. case MQTT_MSG_CON_ERROR:
  247. case MQTT_MSG_TX_ERROR:
  248. case MQTT_MSG_CONACK_ERROR:
  249. case MQTT_MSG_NET_ERROR:
  250. if (mqtt_ctrl->mqtt_ref) {
  251. lua_geti(L, LUA_REGISTRYINDEX, (lua_Integer)mqtt_ctrl->mqtt_cb);
  252. if (lua_isfunction(L, -1)) {
  253. lua_geti(L, LUA_REGISTRYINDEX, mqtt_ctrl->mqtt_ref);
  254. lua_pushstring(L, "error");
  255. lua_pushstring(L, error_string[msg->arg1 - MQTT_MSG_CON_ERROR]);
  256. lua_pushinteger(L, msg->arg2);
  257. lua_call(L, 4, 0);
  258. }
  259. }
  260. #ifdef LUAT_USE_NETDRV
  261. luat_netdrv_fire_socket_event_netctrl(EV_NW_SOCKET_ERROR, mqtt_ctrl->netc, 4);
  262. #endif
  263. break;
  264. default : {
  265. LLOGD("l_mqtt_callback error arg1:%d",msg->arg1);
  266. break;
  267. }
  268. }
  269. // lua_pushinteger(L, 0);
  270. return 0;
  271. }
  272. /*
  273. 订阅主题
  274. @api mqttc:subscribe(topic, qos)
  275. @string/table 主题
  276. @int topic为string时生效 0/1/2 默认0
  277. @return int 消息id,当qos为1/2时有效, 若底层返回失败,会返回nil
  278. @usage
  279. -- 订阅单个topic, 且qos=0
  280. mqttc:subscribe("/luatos/123456", 0)
  281. -- 订阅单个topic, 且qos=1
  282. mqttc:subscribe("/luatos/12345678", 1)
  283. -- 订阅多个topic, 且使用不同的qos
  284. mqttc:subscribe({["/luatos/1234567"]=1,["/luatos/12345678"]=2})
  285. */
  286. static int l_mqtt_subscribe(lua_State *L) {
  287. size_t len = 0;
  288. int ret = 1;
  289. uint16_t msgid = 0;
  290. luat_mqtt_ctrl_t * mqtt_ctrl = (luat_mqtt_ctrl_t *)lua_touserdata(L, 1);
  291. if (lua_isstring(L, 2)){
  292. const char * topic = luaL_checklstring(L, 2, &len);
  293. uint8_t qos = luaL_optinteger(L, 3, 0);
  294. ret = mqtt_subscribe(&(mqtt_ctrl->broker), topic, &msgid, qos);
  295. }else if(lua_istable(L, 2)){
  296. lua_pushnil(L);
  297. while (lua_next(L, 2) != 0) {
  298. ret &= mqtt_subscribe(&(mqtt_ctrl->broker), lua_tostring(L, -2), &msgid, luaL_optinteger(L, -1, 0)) == 1 ? 1 : 0;
  299. lua_pop(L, 1);
  300. }
  301. }
  302. if (ret == 1) {
  303. lua_pushinteger(L, msgid);
  304. return 1;
  305. }
  306. else {
  307. return 0;
  308. }
  309. }
  310. /*
  311. 取消订阅主题
  312. @api mqttc:unsubscribe(topic)
  313. @string/table 主题
  314. @usage
  315. mqttc:unsubscribe("/luatos/123456")
  316. mqttc:unsubscribe({"/luatos/1234567","/luatos/12345678"})
  317. */
  318. static int l_mqtt_unsubscribe(lua_State *L) {
  319. size_t len = 0;
  320. int ret = 0;
  321. uint16_t msgid = 0;
  322. luat_mqtt_ctrl_t * mqtt_ctrl = (luat_mqtt_ctrl_t *)lua_touserdata(L, 1);
  323. if (lua_isstring(L, 2)){
  324. const char * topic = luaL_checklstring(L, 2, &len);
  325. ret = mqtt_unsubscribe(&(mqtt_ctrl->broker), topic, &msgid);
  326. }else if(lua_istable(L, 2)){
  327. size_t count = lua_rawlen(L, 2);
  328. for (size_t i = 1; i <= count; i++){
  329. lua_geti(L, 2, i);
  330. const char * topic = luaL_checklstring(L, -1, &len);
  331. ret &= mqtt_unsubscribe(&(mqtt_ctrl->broker), topic, &msgid) == 1 ? 1 : 0;
  332. lua_pop(L, 1);
  333. }
  334. }
  335. if (ret == 1) {
  336. lua_pushinteger(L, msgid);
  337. return 1;
  338. }
  339. return 0;
  340. }
  341. /*
  342. 配置是否打开debug信息
  343. @api mqttc:debug(onoff)
  344. @boolean 是否打开debug开关
  345. @return nil 无返回值
  346. @usage mqttc:debug(true)
  347. */
  348. static int l_mqtt_set_debug(lua_State *L){
  349. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  350. if (lua_isboolean(L, 2)){
  351. mqtt_ctrl->netc->is_debug = lua_toboolean(L, 2);
  352. }
  353. return 0;
  354. }
  355. /*
  356. mqtt客户端创建
  357. @api mqtt.create(adapter,host,port,ssl,opts)
  358. @int 适配器序号, 如果不填,会选择平台自带的方式,然后是最后一个注册的适配器,可选值请查阅socket库的常量表
  359. @string 服务器地址,可以是域名, 也可以是ip
  360. @int 端口号
  361. @bool/table 是否为ssl加密连接,默认不加密,true为无证书最简单的加密,table为有证书的加密 <br>server_cert 服务器ca证书数据 <br>client_cert 客户端证书数据 <br>client_key 客户端私钥加密数据 <br>client_password 客户端私钥口令数据 <br>verify 是否强制校验 0不校验/1可选校验/2强制校验 默认2
  362. @table mqtt扩展参数
  363. @return userdata 若成功会返回mqtt客户端实例,否则返回nil
  364. @usage
  365. -- 普通TCP链接
  366. mqttc = mqtt.create(nil,"120.55.137.106", 1884)
  367. -- 普通TCP链接,mqtt接收缓冲区4096
  368. mqttc = mqtt.create(nil,"120.55.137.106", 1884, nil, {rxSize = 4096})
  369. -- 加密TCP链接,不验证服务器证书
  370. mqttc = mqtt.create(nil,"120.55.137.106", 8883, true)
  371. -- 加密TCPTCP链接,单服务器证书验证
  372. mqttc = mqtt.create(nil,"120.55.137.106", 8883, {server_cert=io.readFile("/luadb/ca.crt")})
  373. -- 加密TCPTCP链接,单服务器证书验证, 但可选认证
  374. mqttc = mqtt.create(nil,"120.55.137.106", 8883, {server_cert=io.readFile("/luadb/ca.crt"), verify=1})
  375. -- 加密TCPTCP链接,双向证书验证
  376. mqttc = mqtt.create(nil,"120.55.137.106", 8883, {
  377. server_cert=io.readFile("/luadb/ca.crt"),
  378. client_cert=io.readFile("/luadb/client.pem"),
  379. client_key=io.readFile("/luadb/client.key"),
  380. client_password="123456",
  381. })
  382. -- opts参数说明
  383. -- ipv6 = true, -- 是否为ipv6连接,默认false
  384. -- rxSize = 4096, -- mqtt接收缓冲区大小,单位字节,默认32k
  385. -- conn_timeout = 15, -- 连接超时时间,按收到conack为止,单位秒, 默认30秒
  386. */
  387. static int l_mqtt_create(lua_State *L) {
  388. int ret = 0;
  389. int adapter_index = luaL_optinteger(L, 1, network_register_get_default());
  390. if (adapter_index < 0 || adapter_index >= NW_ADAPTER_QTY){
  391. LLOGE("尚无已注册的网络适配器");
  392. return 0;
  393. }
  394. luat_mqtt_ctrl_t *mqtt_ctrl = (luat_mqtt_ctrl_t *)lua_newuserdata(L, sizeof(luat_mqtt_ctrl_t));
  395. if (!mqtt_ctrl){
  396. LLOGE("out of memory when malloc mqtt_ctrl");
  397. return 0;
  398. }
  399. mqtt_ctrl->app_cb = NULL;
  400. ret = luat_mqtt_init(mqtt_ctrl, adapter_index);
  401. if (ret) {
  402. LLOGE("mqtt init FAID ret %d", ret);
  403. return 0;
  404. }
  405. luat_mqtt_connopts_t opts = {0};
  406. // 连接参数相关
  407. // const char *ip;
  408. size_t ip_len = 0;
  409. network_set_ip_invaild(&mqtt_ctrl->ip_addr);
  410. if (lua_isinteger(L, 2)){
  411. network_set_ip_ipv4(&mqtt_ctrl->ip_addr, lua_tointeger(L, 2));
  412. // ip = NULL;
  413. ip_len = 0;
  414. }else{
  415. ip_len = 0;
  416. opts.host = luaL_checklstring(L, 2, &ip_len);
  417. // TODO 判断 host的长度,超过191就不行了
  418. }
  419. int is_ws_url = 0;
  420. if (opts.host && (0==memcmp(opts.host, "ws://", 5) || 0==memcmp(opts.host, "wss://", 6))) {
  421. is_ws_url = 1;
  422. }
  423. if (is_ws_url) {
  424. if (lua_isinteger(L, 3)) {
  425. opts.port = luaL_checkinteger(L, 3);
  426. } else {
  427. opts.port = 0; // 由 URL 指定端口或默认端口
  428. }
  429. } else {
  430. opts.port = luaL_checkinteger(L, 3);
  431. }
  432. // 加密相关
  433. if (lua_isboolean(L, 4)){
  434. opts.is_tls = lua_toboolean(L, 4);
  435. }
  436. if (lua_istable(L, 4)){
  437. opts.is_tls = 1;
  438. opts.verify = 2;
  439. lua_pushstring(L, "verify");
  440. if (LUA_TNUMBER == lua_gettable(L, 4)) {
  441. opts.verify = luaL_checknumber(L, -1);
  442. }
  443. lua_pop(L, 1);
  444. lua_pushstring(L, "server_cert");
  445. if (LUA_TSTRING == lua_gettable(L, 4)) {
  446. opts.server_cert = luaL_checklstring(L, -1, &opts.server_cert_len);
  447. }
  448. lua_pop(L, 1);
  449. lua_pushstring(L, "client_cert");
  450. if (LUA_TSTRING == lua_gettable(L, 4)) {
  451. opts.client_cert = luaL_checklstring(L, -1, &opts.client_cert_len);
  452. }
  453. lua_pop(L, 1);
  454. lua_pushstring(L, "client_key");
  455. if (LUA_TSTRING == lua_gettable(L, 4)) {
  456. opts.client_key = luaL_checklstring(L, -1, &opts.client_key_len);
  457. }
  458. lua_pop(L, 1);
  459. lua_pushstring(L, "client_password");
  460. if (LUA_TSTRING == lua_gettable(L, 4)) {
  461. opts.client_password = luaL_checklstring(L, -1, &opts.client_password_len);
  462. }
  463. lua_pop(L, 1);
  464. }
  465. if (lua_isboolean(L, 5)){
  466. opts.is_ipv6 = lua_toboolean(L, 5);
  467. }else if(lua_istable(L, 5)){
  468. lua_pushstring(L, "ipv6");
  469. if (LUA_TBOOLEAN == lua_gettable(L, 5)) {
  470. opts.is_ipv6 = lua_toboolean(L, -1);
  471. }
  472. lua_pop(L, 1);
  473. lua_pushstring(L, "rxSize");
  474. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  475. uint32_t len = luaL_checknumber(L, -1);
  476. if(len > 0)
  477. luat_mqtt_set_rxbuff_size(mqtt_ctrl, len);
  478. }
  479. lua_pop(L, 1);
  480. lua_pushstring(L, "conn_timeout");
  481. if (LUA_TNUMBER == lua_gettable(L, 5)) {
  482. opts.conn_timeout = luaL_checknumber(L, -1);
  483. if (opts.conn_timeout < 5)
  484. opts.conn_timeout = 5;
  485. else if (opts.conn_timeout > 120)
  486. opts.conn_timeout = 120;
  487. }
  488. lua_pop(L, 1);
  489. }
  490. ret = luat_mqtt_set_connopts(mqtt_ctrl, &opts);
  491. if (ret){
  492. LLOGE("设置mqtt参数失败");
  493. luat_mqtt_release_socket(mqtt_ctrl);
  494. return 0;
  495. }
  496. luaL_setmetatable(L, LUAT_MQTT_CTRL_TYPE);
  497. lua_pushvalue(L, -1);
  498. mqtt_ctrl->mqtt_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  499. return 1;
  500. }
  501. /*
  502. mqtt三元组配置及cleanSession
  503. @api mqttc:auth(client_id,username,password,cleanSession)
  504. @string 设备识别id,对于同一个mqtt服务器来说, 通常要求唯一,相同client_id会互相踢下线
  505. @string 账号 可选
  506. @string 密码 可选
  507. @bool 清除session,默认true,可选
  508. @return bool 成功返回true,否则返回nil. 注意, 返回值是2025.3.19新增的
  509. @usage
  510. -- 无账号密码登录,仅clientId
  511. mqttc:auth("123456789")
  512. -- 带账号密码登录
  513. mqttc:auth("123456789","username","password")
  514. -- 额外配置cleanSession,不清除
  515. mqttc:auth("123456789","username","password", false)
  516. -- 无clientId模式, 服务器随机生成id, cleanSession不可配置
  517. mqttc:auth()
  518. */
  519. static int l_mqtt_auth(lua_State *L) {
  520. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  521. const char *client_id = luaL_optstring(L, 2, "");
  522. const char *username = luaL_optstring(L, 3, "");
  523. const char *password = luaL_optstring(L, 4, "");
  524. int cleanSession = 1;
  525. if (lua_isboolean(L, 5) && !lua_toboolean(L, 5)) {
  526. cleanSession = 0;
  527. }
  528. if (client_id != NULL && strlen(client_id) > MQTT_CONF_CLIENT_ID_LENGTH) {
  529. LLOGE("mqtt client_id 太长或者无效!!!!");
  530. return 0;
  531. }
  532. if (username != NULL && strlen(username) > MQTT_CONF_USERNAME_LENGTH) {
  533. LLOGE("mqtt username 太长或者无效!!!!");
  534. return 0;
  535. }
  536. if (password != NULL && strlen(password) > MQTT_CONF_PASSWORD_LENGTH) {
  537. LLOGE("mqtt password 太长或者无效!!!!");
  538. return 0;
  539. }
  540. mqtt_init(&(mqtt_ctrl->broker), client_id);
  541. mqtt_init_auth(&(mqtt_ctrl->broker), username, password);
  542. mqtt_ctrl->broker.clean_session = cleanSession;
  543. lua_pushboolean(L, 1);
  544. return 1;
  545. }
  546. /*
  547. mqtt心跳设置
  548. @api mqttc:keepalive(time)
  549. @int 可选 单位s 默认240s. 最先15,最高600
  550. @return nil 无返回值
  551. @usage
  552. mqttc:keepalive(30)
  553. */
  554. static int l_mqtt_keepalive(lua_State *L) {
  555. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  556. int timeout = luaL_optinteger(L, 2, 240);
  557. if (timeout < 15)
  558. timeout = 15;
  559. if (timeout > 600)
  560. timeout = 600;
  561. mqtt_ctrl->keepalive = timeout;
  562. return 0;
  563. }
  564. /*
  565. 注册mqtt回调
  566. @api mqttc:on(cb)
  567. @function cb mqtt回调,参数包括mqtt_client, event, data, payload
  568. @return nil 无返回值
  569. @usage
  570. mqttc:on(function(mqtt_client, event, data, payload, metas)
  571. -- 用户自定义代码
  572. log.info("mqtt", "event", event, mqtt_client, data, payload)
  573. end)
  574. --[[
  575. event可能出现的值有
  576. conack -- 服务器鉴权完成, 表示mqtt连接已经建立, 可以订阅和发布数据了
  577. suback -- 订阅完成,data为应答结果, true成功,payload为0~2数字表示qos,data为false则失败,payload为失败码,一般是0x80
  578. unsuback -- 取消订阅完成
  579. recv -- 接收到数据,由服务器下发, data为topic值(string), payload为业务数据(string), metas是元数据(table), 一般不处理.
  580. -- metas包含以下内容
  581. -- message_id
  582. -- qos 取值范围0,1,2
  583. -- retain 取值范围 0,1
  584. -- dup 取值范围 0,1
  585. sent -- 发送完成, qos0会马上通知, qos1/qos2会在服务器应答会回调, data为消息id
  586. disconnect -- 服务器断开连接,网络问题或服务器踢了客户端,例如clientId重复,超时未上报业务数据
  587. pong -- 收到服务器心跳应答,没有附加数据
  588. error -- 严重的异常,会导致断开连接, data(string)为具体异常,有以下几种
  589. -- connect 服务器连接不上
  590. -- tx 发送数据失败
  591. -- conack 服务器鉴权失败,失败码在payload(int)
  592. -- other 其他异常
  593. ]]
  594. */
  595. static int l_mqtt_on(lua_State *L) {
  596. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  597. if (mqtt_ctrl->mqtt_cb != 0) {
  598. luaL_unref(L, LUA_REGISTRYINDEX, (int)(intptr_t)mqtt_ctrl->mqtt_cb);
  599. mqtt_ctrl->mqtt_cb = 0;
  600. }
  601. if (lua_isfunction(L, 2)) {
  602. lua_pushvalue(L, 2);
  603. mqtt_ctrl->mqtt_cb = (void*)(intptr_t)luaL_ref(L, LUA_REGISTRYINDEX);
  604. }
  605. return 0;
  606. }
  607. /*
  608. 连接服务器
  609. @api mqttc:connect()
  610. @return boolean 发起成功返回true, 否则返回false
  611. @usage
  612. -- 开始建立连接
  613. mqttc:connect()
  614. -- 本函数仅代表发起成功, 后续仍需根据ready函数判断mqtt是否连接正常
  615. */
  616. static int l_mqtt_connect(lua_State *L) {
  617. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  618. int ret = luat_mqtt_connect(mqtt_ctrl);
  619. if (ret) {
  620. LLOGE("socket connect ret=%d\n", ret);
  621. luat_mqtt_close_socket(mqtt_ctrl);
  622. lua_pushboolean(L, 0);
  623. return 1;
  624. }
  625. lua_pushboolean(L, 1);
  626. return 1;
  627. }
  628. /*
  629. 断开服务器连接(不会释放资源)
  630. @api mqttc:disconnect()
  631. @return boolean 发起成功返回true, 否则返回false
  632. @usage
  633. -- 断开连接
  634. mqttc:disconnect()
  635. */
  636. static int l_mqtt_disconnect(lua_State *L) {
  637. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  638. mqtt_disconnect(&(mqtt_ctrl->broker));
  639. luat_mqtt_close_socket(mqtt_ctrl);
  640. lua_pushboolean(L, 1);
  641. return 1;
  642. }
  643. /*
  644. 自动重连
  645. @api mqttc:autoreconn(reconnect, reconnect_time)
  646. @bool 是否自动重连
  647. @int 自动重连周期 单位ms 默认3000ms
  648. @usage
  649. mqttc:autoreconn(true)
  650. */
  651. static int l_mqtt_autoreconn(lua_State *L) {
  652. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  653. if (lua_isboolean(L, 2)){
  654. mqtt_ctrl->reconnect = lua_toboolean(L, 2);
  655. }
  656. mqtt_ctrl->reconnect_time = luaL_optinteger(L, 3, 3000);
  657. if (mqtt_ctrl->reconnect && mqtt_ctrl->reconnect_time < 1000)
  658. mqtt_ctrl->reconnect_time = 1000;
  659. return 0;
  660. }
  661. /*
  662. 发布消息
  663. @api mqttc:publish(topic, data, qos, retain)
  664. @string 主题,必填
  665. @string 消息,必填,但长度可以是0
  666. @int 消息级别 0/1 默认0
  667. @int 是否存档, 0/1,默认0
  668. @return int 消息id, 当qos为1或2时会有效值. 若底层返回有错误发生, 则会返回nil
  669. @usage
  670. mqttc:publish("/luatos/123456", "123")
  671. */
  672. static int l_mqtt_publish(lua_State *L) {
  673. uint16_t message_id = 0;
  674. size_t payload_len = 0;
  675. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  676. const char * topic = luaL_checkstring(L, 2);
  677. const char * payload = NULL;
  678. luat_zbuff_t *buff = NULL;
  679. if (lua_isstring(L, 3)){
  680. payload = luaL_checklstring(L, 3, &payload_len);
  681. }else if (luaL_testudata(L, 3, LUAT_ZBUFF_TYPE)){
  682. buff = ((luat_zbuff_t *)luaL_checkudata(L, 3, LUAT_ZBUFF_TYPE));
  683. payload = (const char*)buff->addr;
  684. payload_len = buff->used;
  685. }else{
  686. LLOGD("only support string or zbuff");
  687. }
  688. // LLOGD("payload_len:%d",payload_len);
  689. uint8_t qos = luaL_optinteger(L, 4, 0);
  690. uint8_t retain = luaL_optinteger(L, 5, 0);
  691. int ret = mqtt_publish_with_qos(&(mqtt_ctrl->broker), topic, payload, payload_len, retain, qos, &message_id);
  692. if (ret != 1){
  693. return 0;
  694. }
  695. if (qos == 0){
  696. rtos_msg_t msg = {0};
  697. msg.handler = luatos_mqtt_callback;
  698. msg.ptr = mqtt_ctrl;
  699. msg.arg1 = MQTT_MSG_PUBACK;
  700. msg.arg2 = message_id;
  701. luat_msgbus_put(&msg, 0);
  702. }
  703. lua_pushinteger(L, message_id);
  704. return 1;
  705. }
  706. /*
  707. mqtt客户端关闭(关闭后资源释放无法再使用)
  708. @api mqttc:close()
  709. @usage
  710. mqttc:close()
  711. */
  712. static int l_mqtt_close(lua_State *L) {
  713. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  714. mqtt_disconnect(&(mqtt_ctrl->broker));
  715. luat_mqtt_close_socket(mqtt_ctrl);
  716. if (mqtt_ctrl->mqtt_cb != 0) {
  717. luaL_unref(L, LUA_REGISTRYINDEX, (int)(intptr_t)mqtt_ctrl->mqtt_cb);
  718. mqtt_ctrl->mqtt_cb = 0;
  719. }
  720. luat_mqtt_release_socket(mqtt_ctrl);
  721. return 0;
  722. }
  723. /*
  724. mqtt客户端是否就绪
  725. @api mqttc:ready()
  726. @return bool 客户端是否就绪
  727. @usage
  728. local error = mqttc:ready()
  729. */
  730. static int l_mqtt_ready(lua_State *L) {
  731. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  732. lua_pushboolean(L, mqtt_ctrl->mqtt_state == MQTT_STATE_READY ? 1 : 0);
  733. return 1;
  734. }
  735. /*
  736. mqtt客户端状态
  737. @api mqttc:state()
  738. @return number 客户端状态
  739. @usage
  740. local state = mqttc:state()
  741. -- 已知状态:
  742. -- 0: MQTT_STATE_DISCONNECT
  743. -- 1: MQTT_STATE_CONNECTING
  744. -- 2: MQTT_STATE_CONNECTED
  745. -- 3: MQTT_STATE_READY
  746. -- 4: MQTT_STATE_ERROR
  747. */
  748. static int l_mqtt_state(lua_State *L) {
  749. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  750. lua_pushinteger(L, mqtt_ctrl->mqtt_state);
  751. return 1;
  752. }
  753. /*
  754. 设置遗嘱消息
  755. @api mqttc:will(topic, payload, qos, retain)
  756. @string 遗嘱消息的topic
  757. @string 遗嘱消息的payload
  758. @string 遗嘱消息的qos, 默认0, 可以不填
  759. @string 遗嘱消息的retain, 默认0, 可以不填
  760. @return bool 成功返回true,否则返回false
  761. @usage
  762. -- 要在connect之前调用
  763. mqttc:will("/xxx/xxx", "xxxxxx")
  764. */
  765. static int l_mqtt_will(lua_State *L) {
  766. luat_mqtt_ctrl_t * mqtt_ctrl = get_mqtt_ctrl(L);
  767. size_t payload_len = 0;
  768. const char* topic = luaL_checkstring(L, 2);
  769. const char* payload = luaL_checklstring(L, 3, &payload_len);
  770. int qos = luaL_optinteger(L, 4, 0);
  771. int retain = luaL_optinteger(L, 5, 0);
  772. lua_pushboolean(L, luat_mqtt_set_will(mqtt_ctrl, topic, payload, payload_len, qos, retain) == 0 ? 1 : 0);
  773. return 1;
  774. }
  775. static int _mqtt_struct_newindex(lua_State *L);
  776. void luat_mqtt_struct_init(lua_State *L) {
  777. luaL_newmetatable(L, LUAT_MQTT_CTRL_TYPE);
  778. lua_pushcfunction(L, _mqtt_struct_newindex);
  779. lua_setfield( L, -2, "__index" );
  780. lua_pop(L, 1);
  781. }
  782. #include "rotable2.h"
  783. static const rotable_Reg_t reg_mqtt[] =
  784. {
  785. {"create", ROREG_FUNC(l_mqtt_create)},
  786. {"auth", ROREG_FUNC(l_mqtt_auth)},
  787. {"keepalive", ROREG_FUNC(l_mqtt_keepalive)},
  788. {"on", ROREG_FUNC(l_mqtt_on)},
  789. {"connect", ROREG_FUNC(l_mqtt_connect)},
  790. {"autoreconn", ROREG_FUNC(l_mqtt_autoreconn)},
  791. {"publish", ROREG_FUNC(l_mqtt_publish)},
  792. {"subscribe", ROREG_FUNC(l_mqtt_subscribe)},
  793. {"unsubscribe", ROREG_FUNC(l_mqtt_unsubscribe)},
  794. {"disconnect", ROREG_FUNC(l_mqtt_disconnect)},
  795. {"close", ROREG_FUNC(l_mqtt_close)},
  796. {"ready", ROREG_FUNC(l_mqtt_ready)},
  797. {"will", ROREG_FUNC(l_mqtt_will)},
  798. {"debug", ROREG_FUNC(l_mqtt_set_debug)},
  799. {"state", ROREG_FUNC(l_mqtt_state)},
  800. //@const STATE_DISCONNECT number mqtt 断开
  801. {"STATE_DISCONNECT",ROREG_INT(MQTT_STATE_DISCONNECT)},
  802. //@const STATE_SCONNECT number mqtt socket连接中
  803. {"STATE_SCONNECT", ROREG_INT(MQTT_STATE_SCONNECT)},
  804. //@const STATE_MQTT number mqtt socket已连接 mqtt连接中
  805. {"STATE_MQTT", ROREG_INT(MQTT_STATE_MQTT)},
  806. //@const STATE_READY number mqtt mqtt已连接
  807. {"STATE_READY", ROREG_INT(MQTT_STATE_READY)},
  808. /* TLS verify constants */
  809. {"VERIFY_NONE", ROREG_INT(0)},
  810. {"VERIFY_OPTION", ROREG_INT(1)},
  811. {"VERIFY_REQUIRED", ROREG_INT(2)},
  812. { NULL, ROREG_INT(0)}
  813. };
  814. static int _mqtt_struct_newindex(lua_State *L) {
  815. const rotable_Reg_t* reg = reg_mqtt;
  816. const char* key = luaL_checkstring(L, 2);
  817. while (1) {
  818. if (reg->name == NULL)
  819. return 0;
  820. if (!strcmp(reg->name, key)) {
  821. lua_pushcfunction(L, reg->value.value.func);
  822. return 1;
  823. }
  824. reg ++;
  825. }
  826. //return 0;
  827. }
  828. const rotable_Reg_t reg_mqtt_emtry[] =
  829. {
  830. { NULL, ROREG_INT(0)}
  831. };
  832. LUAMOD_API int luaopen_mqtt( lua_State *L ) {
  833. #ifdef LUAT_USE_NETWORK
  834. luat_newlib2(L, reg_mqtt);
  835. luat_mqtt_struct_init(L);
  836. return 1;
  837. #else
  838. luat_newlib2(L, reg_mqtt_emtry);
  839. return 1;
  840. LLOGE("mqtt require network enable!!");
  841. #endif
  842. }