MQTT problems after connection
Posted: Sun Sep 25, 2016 4:42 pm
Hello,
I am trying a simple MQTT example and I am having unexpected behavior.
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.
When I repeat line 8 (m:subscribe("test/topic",0, function(client) print("subscribe success") end)), it subscribes.
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
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 all
m: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