1 Star 0 Fork 4

心情挺好/Lua808

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
mqtt_demo.lua 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
MicroScale 提交于 2023-04-09 11:36 . 格式化文件
local libnet = require "libnet"
-- 根据自己的服务器修改以下参数
local mqtt_host = "lbsmqtt.airm2m.com"
local mqtt_port = 1884
local mqtt_isssl = false
local client_id = "abc"
local user_name = "user"
local password = "password"
local mqttc = nil
-- function recv(topic, payload)
-- local tjson, r = json.decode(payload)
-- log.info("result", r, ",tjson", tjson)
-- if r then
-- log.info("topic", topic)
-- for k, v in pairs(tjson) do
-- log.info("key & value", k, v)
-- end
-- end
-- end
sys.taskInit(function()
sys.wait(3000)
mqttc = mqtt.create(nil, mqtt_host, mqtt_port, mqtt_isssl) -- mqtt客户端创建
mqttc:auth(client_id, user_name, password) -- mqtt三元组配置
mqttc:keepalive(30) -- 默认值240s
mqttc:autoreconn(true, 3000) -- 自动重连机制
mqttc:on(function(mqtt_client, event, data, payload) -- mqtt回调注册
-- 用户自定义代码
log.info("mqtt", "event", event, mqtt_client, data, payload)
if event == "conack" then
sys.publish("mqtt_conack")
mqtt_client:subscribe("/luatos/123456")
elseif event == "recv" then
log.info("mqtt", "downlink", "topic", data, "payload", payload)
elseif event == "sent" then
log.info("mqtt", "sent", "pkgid", data)
end
end)
mqttc:connect()
log.info("mqtt连接成功")
sys.waitUntil("mqtt_conack")
while true do
-- mqttc自动处理重连
local ret, topic, data, qos = sys.waitUntil("mqtt_pub", 30000)
if ret then
if topic == "close" then break end
mqttc:publish(topic, data, qos)
end
end
mqttc:close()
mqttc = nil
end)
sys.taskInit(function()
local topic = "/luatos/123456"
local payload = "123"
local qos = 1
while true do
sys.wait(5000)
if mqttc and mqttc:ready() then
log.info("mqtt的topic", topic, payload, qos)
local pkgid = mqttc:publish(topic, payload, qos) -- 发送一条消息
end
end
end)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/dmulxw/lua808.git
[email protected]:dmulxw/lua808.git
dmulxw
lua808
Lua808
master

搜索帮助