I am trying to implement a simple senario with mqtt client where I will publish and subscribe simple messages. At the moment I am trying to make the system as robust as it can be. I have noticed that esp sometimes disconnects (probably due to bad router from my isp), on wifi disconnection mqtt client it activates the offline event:
m:on("offline", function(con) disconnected() end)
So i think it will be a good idea when there is a disconnection, using the function disconnected() I will try to reconnect to wifi and reconnect the client but if I do that
function disconnected()
print(CLIENTID..": Lost connection, don't worry I'll try to reconnect...")
m:close();
tmr.alarm(0, 2500, 0, checkWIFI)
end
And then try to reconnect my mqtt client :
m = mqtt.Client("clientid", 0, "user", "password")
m:lwt("pub_test", CLIENTID.."I out, I will try to come back", 0, 0)
m:on("connect", function(con) print (CLIENTID..": Mqtt reconnected") end) --eof m:on
--m:on("offline", function(con) print ("offline") end)
m:on("offline", function(con) disconnected() end)
m:on("message", function(conn, topic, data)
print("Data received on topic: "..topic .. ":" )
if data ~= nil then
print(data)
tmr.delay(1000000) -- wait 1,000,000 us = 1 second
-- publish a message with data = hello, QoS = 0, retain = 0
m:publish("pub_test","Message received:" .. data,0,0, function(conn)
print("Data published")
end)
end
end)
m:connect(BROKER, 1883, 0, function(conn)
print(CLIENTID..": Mqtt reconnecting...")
m:subscribe(sub_topic,0, function(conn) print(CLIENTID..": Subscribed to "..sub_topic.." topic")
-- m:subscribe("test2",0, function(conn) print("subscribe test2")
end)
end)
I get "not enough memory". I am suspecting that the reason of this is that I am trying to recreate the instance of mqtt.client so in order to avoid this I thought it would be a good idea to destroy the instance by:
m = nil
on disconnect function.
Because I am not an expert on lua language and on nodemcu I would like to hear your suggestions regarding this.
THank you.