Why is "Subscribing to topic topic/test" printed in console log before connect message?
Chris Angelico
rosuav at gmail.com
Tue Sep 10 14:10:33 EDT 2019
On Wed, Sep 11, 2019 at 3:01 AM Spencer Du <spencerdu at hotmail.co.uk> 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.
>
> client = mqtt.Client()
> client.connect("broker.hivemq.com",1883,60)
> client.on_connect = on_connect
>
> client.loop_start()
> print("Subscribing to topic", "topic/test")
> client.subscribe("topic/test")
> client.publish("topic/test", "Hello world!")
>
> def on_connect(client, userdata, flags, rc):
> print("Connected with result code "+str(rc))
>
Your code is asynchronous. I would strongly recommend moving your
subscribe action into your on_connect, such that it happens ONLY once
you are successfully connected.
ChrisA
More information about the Python-list
mailing list