As the title says... Chat on...

User avatar
By Atmo Suwiryo
#59128 An old thread for an answer for sure.
Just in case someone redirect here from google, here is my solution.

Using timer at bottom of the script, to check wifi connection, if lost, reset the mqtt object, then reconnect.

Code: Select alltmr.alarm(1, 3000, 1, function()
  if DEBUG then
    print('IP: ',wifi.sta.getip())
  end

  if wifi.sta.getip() == nil then
    restart = true
  else
    if restart == true then
      restart = false
      m = nil
      mqtt_init()
      connect()
    end
  end
end)


Here is my mqtt_init function:

Code: Select alllocal function mqtt_init()
  m = mqtt.Client(chipId, 5)

  m:lwt("events/esp8266/".. chipId .."/status",
    cjson.encode({
      type = "status",
      sensorId = chipId,
      status = 0
    }), 0, 0)

  m:on("offline", function(m)
    if DEBUG then
      print ("Connecting to the broker ...")
    end
  end)

  m:on("connect", function(m)
    if DEBUG then
      print("connected")
    end

    m:publish("events/esp8266/".. chipId .."/status",
      cjson.encode({
        type = "status",
        sensorId = chipId,
        status = 1,
        heap = node.heap()
      }), 0, 0)

    m:subscribe("mcu/cmd/#", 0, function(m)
      if DEBUG then
        print("subscribed")
      end
    end)
  end)

  --m:on("message", switch_relay)
  m:on("message", function() print ("relay switched") end)

end

local function connect()
  m:connect(mqttHost, 1883, 0, 1)
end