As the title says... Chat on...
User avatar
By kayakpete
#9867 I just flashed to the latest build and seem to have lost my ability to publish in mqtt

Can anyone confirm?

Code: Select all-- init mqtt client with keepalive timer 120sec
m = mqtt.Client("clientid", 120, "user", "password")

-- setup Last Will and Testament (optional)
-- Broker will publish a message with qos = 0, retain = 0, data = "offline"
-- to topic "/lwt" if client don't send keepalive packet
m:lwt("/lwt", "offline", 0, 0)

m:on("connect", function(con) print ("connected") end)
m:on("offline", function(con) print ("offline") end)

-- on publish message receive event
m:on("message", function(conn, topic, data)
  print(topic .. ":" )
  if data ~= nil then
    print(data)
  end
end)

-- for secure: m:connect("192.168.11.118", 1880, 1)
m:connect("192.168.15.22", 1883, 0, function(conn) print("connected") end)

-- subscribe topic with qos = 0
m:subscribe("openhab/garage/relay1",0, function(conn) print("subscribe success") end)
-- or subscribe multiple topic (topic/0, qos = 0; topic/1, qos = 1; topic2 , qos = 2)
-- m:subscribe({["topic/0"]=0,["topic/1"]=1,topic2=2}, function(conn) print("subscribe success") end)
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("openhab/garage/relay1","hello",0,0, function(conn) print("sent") end)

m:close();
-- you can call m:connect again



Code: Select alldofile("mqtt-demo.lua")
mqtt-demo.lua:24: not connected
> offline
User avatar
By tuanpm
#9898 Have you tried this:
Code: Select allm = mqtt.Client(wifi.sta.getmac(), 120, "user", "password")
m:lwt("/lwt", wifi.sta.getmac(), 0, 0)

m:on("offline", function(con)
     print ("reconnecting...")
     print(node.heap())
     tmr.alarm(1, 10000, 0, function()
          m:connect("192.168.11.102", 1880, 0)
     end)
end)

-- on publish message receive event
m:on("message", function(conn, topic, data)
  print(topic .. ":" )
  if data ~= nil then
    print(data)
  end
end)

tmr.alarm(0, 1000, 1, function()
 if wifi.sta.status() == 5 then
     tmr.stop(0)
     m:connect("192.168.11.102", 1880, 0, function(conn)
          print("connected")
          m:subscribe("/topic",0, function(conn)
               m:publish("/topic","hello",0,0, function(conn) print("sent") end)
          end)
     end)
 end
end)