Search code examples
pythonmqttpaho

Paho MQTT (Python) - loop_start() not working


I'm writing a MQTT client which simply connects to the broker, publish a message and then disconnect. Here's the code:

def on_connect_v5(client, userdata, flags, rc, properties):
    print('connected')
    client.publish(topic, payload, 0)

def on_publish(client, userdata, mid):
    print(f'mid: {mid}')
    client.disconnect()

client = paho.Client(protocol=paho.MQTTv5)
client.on_connect = on_connect_v5
client.on_publish = on_publish
client.connect(host, port, 60)
client.loop_start()
# client.loop_forever()

The question is when I use loop_start(), it seems the client isn't connected successfully, but loop_forever() would work. Have I done something wrong with the loop_start() function, and what's the proper way to use it?

BTW: have tried use the paho.mqtt.publish module and always get a Socket timed out. Appreciated if someone can explain it as well.


Solution

  • The difference is that loop_forever blocks the program. loop_start, only starts a daemon thread, but doesn't block. So your program continues. In the code you show, this means the program exists.

    You can read more here: https://github.com/eclipse/paho.mqtt.python#network-loop

    Calling loop_start() once, before or after connect*(), runs a thread in the background to call loop() automatically. This frees up the main thread for other work that may be blocking.

    loop_forever(). This is a blocking form of the network loop and will not return until the client calls disconnect(). It automatically handles reconnecting.