codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why is "Subscribing to topic topic/test" printed in console log before connect message?


On 2019-09-10 17:59, Spencer Du wrote:
> Hi
> 
> I have code for publish and subscribe over mqtt. In the console log I have "Subscribing to topic topic/test" printed before connect message why is this? I want to this to be printed after the connect message. How do I fix this problem. Please run gui.py to test.
> 
> gui.py
> 
> import paho.mqtt.client as mqtt
> from mqtt import *
> import json
> import time
> 
> client = mqtt.Client()
> client.connect("broker.hivemq.com",1883,60)
> client.on_connect = on_connect
> client.on_message = on_message
> 
> client.loop_start()
> print("Subscribing to topic", "topic/test")
> client.subscribe("topic/test")
> client.publish("topic/test", "Hello world!")
> time.sleep(1)
> client.loop_stop()
> 
> mqtt.py
> 
> import paho.mqtt.client as mqtt
> 
> def on_connect(client, userdata, flags, rc):
>      print("Connected with result code "+str(rc))
> 
> def on_message(client, userdata, msg):
>      if msg.payload.decode() == "Hello world!":
>          print("Yes!")
> 
It might just be a timing issue.

I note, however, that you're attaching the 'on_connect' and 'on_message' 
callbacks _after_ asking it to connect, which seems like a strange thing 
to do. If you want it to callback when it connects, it makes more sense 
to attach the callbacks _before_ asking it to connect.