-- init mqtt client with keepalive timer 120sec
m = mqtt.Client(wifi.sta.getmac(), 120)
-- Process incoming data
function MQTT_ProcessRx(conn, topic,data)
print(topic .. ":" )
if data ~= nil then
print(data)
if data == "ON" then
print("ON!!! Received")
gpio.write(3,1)
end
if data == "OFF" then
print("OFF!!! RECEIVED")
gpio.write(3,0)
end
end
end
-- Handler subscribe function
function MQTT_On()
-- subscribe topic with qos = 0
m:subscribe("/topic",0, function(conn) print("subscribe success")
m:publish("/topic","hello",0,0, function() print("sent") end)
end)
m:on("offline", function(con)
print ("offline.Reconnecting")
tmr.stop(3)
print(node.heap())
tmr.alarm(1, 3000, 0, function() MQTT_Connect() end)
end)
m:on("message",function(conn,topic,data) MQTT_ProcessRx(conn,topic,data) end)
t=0
print("To set the timer3")
tmr.alarm(3,10000,1,function()
dofile("ds18b20.lc")
print("T=",t)
m:publish("/topic_temp",t,0,0, function() print("T sent") end)
end)
end
function MQTT_Connect()
print("MQTT_Connect()")
tmr.alarm(0, 1000, 1, function()
if wifi.sta.getip() == nil then
print("Connecting to AP...")
else
print('Connected to WiFi. IP: ',wifi.sta.getip())
tmr.stop(0)
print("Connecting to MQTT server")
m:connect("172.20.2.7", 1883, 0, function(conn)
print("connected")
MQTT_On()
end)
end
end)
end
m:lwt("/lwt", "offline", 0, 0)
MQTT_Connect()