Python MQTT with RabbitMQ and LavinMQ
We recommend paho-mqtt, the Eclipse Paho MQTT client for Python.
pip install paho-mqtt
Publish and subscribe
Set MQTT_HOST, MQTT_PORT, MQTT_USERNAME and MQTT_PASSWORD to the MQTT
details on your instance’s details page in the CloudAMQP console. Port 8883
uses TLS. Without them, the examples connect to a local broker.
Save the publisher as publisher.py:
import os
import paho.mqtt.client as mqtt
port = int(os.environ.get("MQTT_PORT", "1883"))
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.username_pw_set(os.environ.get("MQTT_USERNAME", "guest"), os.environ.get("MQTT_PASSWORD", "guest"))
if port == 8883:
client.tls_set()
client.connect(os.environ.get("MQTT_HOST", "localhost"), port)
client.loop_start()
# QoS 1 waits for the broker's PUBACK
client.publish("hello", "Hello world!", qos=1).wait_for_publish()
print(" [x] Sent 'Hello world!'")
client.disconnect()
client.loop_stop()
Save the subscriber as worker.py:
import os
import paho.mqtt.client as mqtt
def on_subscribe(client, userdata, mid, reason_codes, properties):
print(" [*] Waiting for messages. To exit press CTRL+C")
# Each message is acked when on_message returns
def on_message(client, userdata, message):
print(f" [x] Received '{message.payload.decode()}'")
port = int(os.environ.get("MQTT_PORT", "1883"))
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.username_pw_set(os.environ.get("MQTT_USERNAME", "guest"), os.environ.get("MQTT_PASSWORD", "guest"))
if port == 8883:
client.tls_set()
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect(os.environ.get("MQTT_HOST", "localhost"), port)
client.subscribe("hello", qos=1)
try:
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
Run python worker.py in one terminal and python publisher.py in another.
A runnable example is in python/paho-mqtt in cloudamqp/examples.
Good to know
- Put the vhost in the username, as
vhost:user. MQTT has no vhost of its own, and the console shows the username that way. - Use callback API version 2:
mqtt.Client(mqtt.CallbackAPIVersion.VERSION2). paho-mqtt 2 still runs code written for paho-mqtt 1, whose callbacks take other arguments, but warns that it’s deprecated. tls_set()turns on TLS and verifies the server certificate and hostname.- Use QoS 1, so
publishreturns a message info whosewait_for_publish()waits for the broker’s PUBACK, and each message is acked whenon_messagereturns. - Run the network loop.
loop_forever()blocks and reconnects after a network failure;loop_start()runs it in a background thread.
Was this page helpful?
Thanks for your feedback!