Luat 功能开发教程(三) MQTT 应用

关键词:MQTT,CAT1,片上开发,OPENCPU,4G

几个重要名词

API说明

mqtt的API在luat lib有做封装,建议直接用lib的API接口。

实现流程

相关实例程序在脚本库的demo\mqtt文件夹下,包含sendInterruptRecv,sendWaitRecv实例,可以根据实际需要选择demo进行研究。以下是sendWaitRecv实例代码

 local host, port = "lbsmqtt.airm2m.com", 1884  sys.taskInit(function() while true do while not socket.isReady() do sys.wait(1000) end local mqttc = mqtt.client(misc.getImei(), 300, "user", "password") while not mqttc:connect(host, port) do sys.wait(2000) end 
 if mqttc:subscribe(string.format("/device/%s/req", misc.getImei())) then 
 if mqttc:publish(string.format("/device/%s/report", misc.getImei()), "test publish " .. os.time()) then while true do local r, data, param = mqttc:receive(120000, "pub_msg") if r then log.info("这是收到了服务器下发的消息:", data.payload or "nil") elseif data == "pub_msg" then log.info("这是收到了订阅的消息和参数显示:", data, param) mqttc:publish(string.format("/device/%s/resp", misc.getImei()), "response " .. param) elseif data == "timeout" then log.info("这是等待超时主动上报数据的显示!") mqttc:publish(string.format("/device/%s/report", misc.getImei()), "test publish " .. os.time()) else  break end end end end mqttc:disconnect() end end) 
 sys.taskInit(function() while true do sys.publish("pub_msg", "11223344556677889900AABBCCDDEEFF" .. os.time()) sys.wait(100) end end) 

10个。

参考mqtt demo,实现自动重连即可

原文链接:https://blog.csdn.net/a00236/article/details/118161065?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165277096216781683965145%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165277096216781683965145&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~times_rank-7-118161065-null-null.nonecase&utm_term=%E5%AE%9E%E7%94%A8%E6%95%99%E7%A8%8B

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
文明发言,共建和谐米科社区
提交
头像

昵称

取消
昵称表情图片