diff --git a/main.lua b/main.lua index 026f881..3b50e51 100644 --- a/main.lua +++ b/main.lua @@ -139,6 +139,11 @@ function normalOperation() if (startMqttClient ~= nil) then if (not connectedMqtt()) then rgbBuffer:set(103, 0, 64,0) + -- check every thirty seconds, if reconnecting is necessary + if (((tmr.now() / 1000000) % 100) == 30) then + print("MQTT reconnecting... ") + reConnectMqtt() + end end end ws2812.write(rgbBuffer) diff --git a/mqtt.lua b/mqtt.lua index 44c8c87..05ebee1 100644 --- a/mqtt.lua +++ b/mqtt.lua @@ -78,6 +78,33 @@ function readTemp() end end +-- Connect or reconnect to mqtt server +function reConnectMqtt() + if (not mqttConnected) then + m:connect(mqttServer, 1883, false, function(c) + print("MQTT is connected") + mqttConnected = true + -- subscribe topic with qos = 0 + m:subscribe(mqttPrefix .. "/cmd/#", 0) + local tmr1 = tmr.create() + tmr1:register(1000, tmr.ALARM_SINGLE, function (t) + -- publish a message with data = hello, QoS = 0, retain = 0 + m:publish(mqttPrefix .. "/ip", tostring(wifi.sta.getip()), 0, 0) + local red = string.byte(colorBg,2) + local green = string.byte(colorBg,1) + local blue = string.byte(colorBg,3) + m:publish(mqttPrefix .. "/background", tostring(red) .. "," .. tostring(green) .. "," .. tostring(blue), 0, 0) + tmr1:unregister() + end) + tmr1:start() + end, + function(client, reason) + print("failed reason: " .. reason) + mqttConnected = false + end) + end +end + -- MQTT extension function registerMqtt() m = mqtt.Client("wordclock", 120) @@ -141,27 +168,7 @@ function registerMqtt() mqttConnected = false end ) - m:connect(mqttServer, 1883, false, function(c) - print("MQTT is connected") - mqttConnected = true - -- subscribe topic with qos = 0 - m:subscribe(mqttPrefix .. "/cmd/#", 0) - local tmr1 = tmr.create() - tmr1:register(1000, tmr.ALARM_SINGLE, function (t) - -- publish a message with data = hello, QoS = 0, retain = 0 - m:publish(mqttPrefix .. "/ip", tostring(wifi.sta.getip()), 0, 0) - local red = string.byte(colorBg,2) - local green = string.byte(colorBg,1) - local blue = string.byte(colorBg,3) - m:publish(mqttPrefix .. "/background", tostring(red) .. "," .. tostring(green) .. "," .. tostring(blue), 0, 0) - tmr1:unregister() - end) - tmr1:start() - end, - function(client, reason) - print("failed reason: " .. reason) - mqttConnected = false - end) + reConnectMqtt() end function connectedMqtt() @@ -201,3 +208,4 @@ function startMqttClient() mqtttimer:start() end end +