NODEMCU连接MQTT服务器简单订阅收发信息

mqtt服务简单好用,刚好nodemcu又提供了mqtt这个模块:
基本都是网上源代码的修改了用户名和密码,服务器名称就可以连接上。简单实用

tmr.alarm(4, 1000, tmr.ALARM_AUTO, function()
if wifi.sta.getip()~= nil then
   clientid=node.chipid()
print("Chipid is:"..clientid)
    m = mqtt.Client(clientid, 120, "yonghuming", "mima")
m:connect("5iot.top", 1883, 0, function(client)--我的服务器
  print("connected0")

  -- Calling subscribe/publish only makes sense once the connection
  -- was successfully established. You can do that either here in the
  -- 'connect' callback or you need to otherwise make sure the
  -- connection was established (e.g. tracking connection status or in
  -- m:on("connect", function)).

  -- subscribe topic with qos = 0
 --m:subscribe("test-1", 0, function(client) print("subscribe success") end)
  -- publish a message with data = hello, QoS = 0, retain = 0
 -- m:publish("test-1", "hello", 0, 0, function(client) print("sent") end)
end,
function(client, reason)
  print("failed reason: " .. reason)
end)

 m:on("connect", function(client) print ("connected1")--连接上
 status1=1 
m:subscribe("test-1", 0, function(client) print("subscribe success") end)
 end)--订阅主题
m:on("offline", function(client) print ("offline") 
tmr.start(4)
 end)--下线后重连

m:on("message", function(client, topic, data) 
  print("Recieved Topic:/"..topic .. ":" ) 
  if data ~= nil then
    print(data)
  end
end)
 tmr.stop(4)
end
end)
tmr.alarm(3, 10000, tmr.ALARM_AUTO,function()
    if status1==1 then
m:publish("test-1", "hello", 0, 0, function(client) print("sent") end)

gpio.write(led1, gpio.LOW);
tmr.delay(1000)
gpio.write(led1, gpio.HIGH);

end
end)

这是自己的服务器,下一步连接中移动的ONENET服务器,采用MQTT连接,但协议有部分不同,需要打包协议。

你可能感兴趣的:(NODEMCU连接MQTT服务器简单订阅收发信息)