0
votes

I'm having a problem with subscribing to MQTT broker (using test.mosquitto.org with port 1883) with paho mqtt library. When I use mosquitto_sub client, I'm getting messages normally, but when I subscribe to the same topic in my Python script, callback never gets executed.

import paho.mqtt.client as mqtt

client_get = mqtt.Client(client_id='my_client', protocol=mqtt.MQTTv31)
client_get.connect('test.mosquitto.org', 1883)
client_get.loop_start()

def callback(client, userdata, message):
    print(str(message.payload.decode("utf-8")))

client_get.on_message = callback
client_get.subscribe(topic, qos=1)
1
Is that all your code? because as it stands (assuming you replace topic with a string that represents a real topic) this will exit immediately since loop_start() doesn't start a daemon thread so it won't keep the script live if there is nothing else.hardillb
I just want to subscribe to my topic (string) and print messages whenever someone publish to topic, so yes, it needs to keep the script live.Hercules330121

1 Answers

1
votes

Try the following:

import paho.mqtt.client as mqtt

client_get = mqtt.Client(client_id='my_client', protocol=mqtt.MQTTv31)
client_get.connect('test.mosquitto.org', 1883)

def callback(client, userdata, message):
    print(str(message.payload.decode("utf-8")))

client_get.on_message = callback
client_get.subscribe(topic, qos=1)
client_get.loop_forever()

I've moved the start_loop() to the end and changed it to loop_forever() which will block and keep the script running.