CloudAMQP with MQTT and Python Getting started

The most feature complete MQTT client for Python is Mosquitto. Below you see an sample app which both publish and subscribes to CloudAMQP MQTT.

CloudAMQP_MQTT_URL Structure mqtt://cloudamqp_username:cloudamqp_password@hostname:port

import mosquitto, os, urlparse

# Define event callbacks
def on_connect(mosq, obj, rc):
    print("rc: " + str(rc))

def on_message(mosq, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mosq, obj, level, string):
    print(string)

mqttc = mosquitto.Mosquitto()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe

# Uncomment to enable debug messages
#mqttc.on_log = on_log

# Parse CLOUDAMQP_MQTT_URL (or fallback to localhost)
url_str = os.environ.get('CLOUDAMQP_MQTT_URL', 'mqtt://localhost:1883')
url = urlparse.urlparse(url_str)

# Connect
mqttc.username_pw_set(url.username, url.password)
mqttc.connect(url.hostname, url.port)

# Start subscribe, with QoS level 0
mqttc.subscribe("hello/world", 0)

# Publish a message
mqttc.publish("hello/world", "my message")

# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
    rc = mqttc.loop()
print("rc: " + str(rc))

The full code can be seen at github.com/CloudMQTT/python-mqtt-example.

Alternative clients

Another good MQTT client for Python is paho-mqtt 1.0. The Paho Python Client class provides some helper functions to make publishing one off messages to an MQTT server very straightforward. Futher documentation can be found here.