So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By ratfink
#72531 Hi All
I have been working away on a little project for a while now and this is the only thing I'v not been able to fix for myself.
I have a main function in a LUA file that connects to the MQTT broker and then hands of work to a data function which read sensors and publishes the data to a broker and then returns to the function which puts the nodemcu to deepsleep for a set period. The problem I have is trying to add a bit of code to send the last will and testament message within this, it never executes...
First the original working code..
Code: Select allfunction module.start()
   -- Connect to broker
   m = mqtt.Client(config.ID, config.KALIVE, config.USER, config.PASW)
   m:connect(config.HOST, config.PORT, 0, 0, function(con)
      print("connected to broker")
      get_data()  -- read sensor data
   end)
   tmr.alarm(6, 300, tmr.ALARM_SINGLE, call_dsleep)   -- call sleep function to shutdown after delay to allow for program to complete
end

But here I have added an on_connect clause the print statement never excutes and needless to say the broker never publishes the LWT message...
Code: Select allfunction module.start()
   -- Connect to broker
   m = mqtt.Client(config.ID, config.KALIVE, config.USER, config.PASW)
   m:connect(config.HOST, config.PORT, 0, 0, function(con)
      m:on("connect", function(con)
         m:lwt(config.HEAD .. config.ID .. subt, config.LWT, 0, 0)
         print ("Connected to Broker")
      end)   
      get_data()
   end)
   tmr.alarm(6, 300, tmr.ALARM_SINGLE, call_dsleep)   -- call sleep function to shutdown after delay to allow for program to complete
end


Can anyone offer me any pointers on where I am going wrong?
Tia
User avatar
By ratfink
#72939 Thought I'd follow up here even thought I feel a bit sheepish.
After sorting the other wrinkles out of my project I got back to this and realised it was just a case of RTFM.
The LWT statement must be issued before the client connect statement as LWT is forwarded as part of the connect process. :oops:
Code: Select alllocal function connect_mqtt()
   -- set up MQTT Client
   m = mqtt.Client(config.ID, config.KALIVE, config.USER, config.PASW)
   -- configure last will and testament keepalive should be at least twice sleep time
   m:lwt(config.HEAD .. config.ID .. subtopic, config.LWT, 0, 0)
   -- connect to broker
   m:connect(config.HOST, config.PORT, 0, 0, function(con)
   print ("Connected to Broker")
   function_to_do_something()   
   end)
end