1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
function stopReconnect() -- clear connecting state and clear connect timer! mqtt_connecting = 0 tmr.stop(3) end
-- 重连方法 function reconnect() if mqtt_connecting == 0 then tmr.alarm(3, 20000, 1, function() print("start mqtt server reconnect!") mq:close() mq:connect("x.x.x.x", 1883, 0) end) mqtt_connecting = 1 end end
-- 初始化mqtt连接方法 function init() print("init mqtt") mqtt_inited = 1 -- 初始化无需登陆的客户端, 心跳时间 120秒 mq = mqtt.Client("recv_earth1", 120) --mq:lwt("/lwt", "offline", 0, 0) -- 设置连接ip 以及 端口
-- 对于 TLS: m:connect("192.168.11.118", secure-port, 1) mq:connect("192.168.1.1", 1883, 0, function(client) print("connected") end, function(client, reason) print("failed reason: " .. reason) reconnect() end )
--连接到服务器触发事件 mq:on("connect", function(client) print("connected") stopReconnect() mq:subscribe("tai3_water",0, function(conn) print("subscribe success") end) --mq:subscribe("rpt_temp",0, function(conn) print("subscribe success") end) end)
mq:on("offline", function(client) print ("offline") reconnect() end) --掉线触发事件
-- 收到消息时触发事件 mq:on("message", function(client, topic, data) print(topic .. ":" ) if data ~= nil then if topic == "tai3_water" then print(data) if data == "water1min" then dofile("water.lua") --mq:publish("report_info","tai3_water1",0,0) elseif data == "water2min" then dofile("water2.lua") --mq:publish("report_info","tai3_water2",0,0) elseif data == "water4min" then dofile("water4.lua") --mq:publish("report_info","tai3_water4",0,0) end end
--if topic == "rpt_water" and tonumber(data) > 12 then --print("aaa"..data) --end end end)
end
--function do_get_adc() -- 定义定时器处理函数 --mq:publish("rpt_water", adc.read(0), 0, 0) --end
--tmr.create():alarm(60000, tmr.ALARM_AUTO , do_get_adc)
-- 确保subscribe/publish方法在连接上服务器后再调用,在实际应用中是把他们放在connect回调函数里或者确定连接成功
-- 订阅/topic主题、服务质量为0 --m:subscribe("topicxx",0, function(conn) print("subscribe success") end) --m:subscribe("blinkdr",0, function(conn) print("subscribe success") end) -- 发送一条信息 data = hello, QoS = 0, retain = 0
--m:close(); -- 你可以再次调用 m:connect 连接函数
-- 如果没有初始化过,进行初始化 if mqtt_inited == 0 then init() else reconnect() end
|