user3012475
user3012475

Reputation: 35

Lua MQTT publish doesn't work from script but works from terminal on ESP8266

I am trying to build a wee MQTT client from a Geekcreit dev board based on an ESP8266.

When I run commands over a serial connection using PuTTY, it all works fine and publishes the message successfully, being picked up by a broker running on a Raspberry Pi.

I am trying to add this to a Lua script instead, to run via init.lua, and while the connection callback fires no publish ever happens.

--test.lua
print("Setting up WIFI...")
wifi.setmode(wifi.STATION)
--modify according your wireless router settings
wifi.sta.config("ap","pass")
wifi.sta.connect()
tmr.alarm(1, 1000, 1, function()
  if wifi.sta.getip()== nil then
    print("IP unavaiable, Waiting...")
  else
    tmr.stop(1)
    print("Config done, IP is "..wifi.sta.getip())
    -- initiate the mqtt client and set keepalive timer to 120sec
    m = mqtt.Client("myNodeName", 120, "", "") -- blank user and password
    m:on("connect", function() print("connected") end )
    m:connect("*.*.*.*") -- my local broker's IP
    m:publish("topic/test", "7.2", 0, 0) -- no QoS, not retained
  end
end)

I am uploading and running that script using Esplorer, and as I said, I successfully see the 'connected' message, but no message arrives at the broker.

If I take the

m:publish("topic/test", "7.2", 0, 0) -- no QoS, not retained

and fire it from the "Send" command bar of Esplorer, the broker receives the message.

I'm at a bit of a loss with it. Any assistance appreciated.

Upvotes: 0

Views: 803

Answers (1)

Marcel Stör
Marcel Stör

Reputation: 23535

Like so many other functions in the NodeMCU API mqtt.client:connect() is asynchronous i.e. it doesn't block. You can only publish once the connection was successfully established. There's a callback function for that in mqtt.client:connect().

You could either use a local mqtt_connected flag, set it in the callback (or m:on("connect")) and wait in a timer until connected or publish directly from the callback.

m:connect("192.168.11.118", 1883, 0, function(client)
  // now publish through client
end)

Upvotes: 3

Related Questions