luat_lib_mqtt.c 26 KB

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