Current Lua downloadable firmware will be posted here

User avatar
By cmaciel
#55693 Hello,
I am trying a simple MQTT example and I am having unexpected behavior.

Code: Select all-- init mqtt client
m = mqtt.Client(clientid, 120, "", "")

m:on("connect", function(client) print ("connected ok") end)
m:on("offline", function(client) print ("offline") end)
m:connect("192.168.29.130", 1883, 0, true, function(client) print("connected") end,
                                     function(client, reason) print("failed reason: "..reason) end)
m:subscribe("test/topic",0, function(client) print("subscribe success") end)
m:on("message", function(client, topic, data) print(topic .. ": " .. data) end )                                     


When I run the code (after wifi connection is established), it connects to the MQTT server, but the subscribe fails saying "not connected". If I go to the console and run the same command, then it subscribes OK.

Code: Select all> print(wifi.sta.status())
5
> print(wifi.sta.getip())
192.168.29.241   255.255.255.0   192.168.29.1
> dofile("script2.lua")
script2.lua:8: not connected
stack traceback:
   [C]: in function 'subscribe'
   script2.lua:8: in main chunk
   [C]: in function 'dofile'
   stdin:1: in main chunk
> connected ok
offline



When I repeat line 8 (m:subscribe("test/topic",0, function(client) print("subscribe success") end)), it subscribes.

Code: Select allm:subscribe("test/topic",0, function(client) print("subscribe success") end)
> subscribe success


Also, the line after the subscribe (to set the callback when a message arrives) did not run, and I have to run manually for it to work.

Does anyone have any idea what can be happening? I tried two mosquitto installs, and also the public server (test.mosquitto.org) without success, so I believe it is not related to the MQTT server. Wouldn't the subscribe command be executed only after the connect command completes? Can it be a timing issue?

Thanks

Cesar
User avatar
By jbro
#55744 Yes. Timing issue.

The error is telling you that line 8 fails because the client is not connected.
Then, after the error, the client connects (> connected ok).

You need to use the connect callback (line 4) to wait for the connection then the client can do more with the broker.

NodeMCU is not a procedural language but rather event driven. That is why the answer to your question,

Wouldn't the subscribe command be executed only after the connect command completes?


is no.

read the Lua Developer FAQ to see that NodeMcu is event-driven. https://nodemcu.readthedocs.io/en/master/en/lua-developer-faq/