MQTT And Python

2015-02-18 20:01

Update: This article now also exists as a git repository.

I played around with MQTT and Python for an upcoming project of mine.

Here are some notes and a simple example code for a subscriber.


Requires Mosquitto to be installed.

On Linux with the apt-get package manager:

sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients

Note: mosquitto-clients is to get the mosquitto_pub to make it simple to try stuff from the command line.

Also install virtualenv if you want to use it (recommended):

sudo apt-get install python-virtualenv

Working directory

The use of virtualenv is optional but recommended for playing around with this example code.

mkdir mqtt-mosquitto-example
cd mqtt-mosquitto-example
virtualenv .
source bin/activate
pip install paho-mqtt

Subscriber code

import paho.mqtt.client as paho

def on_message(mosq, obj, msg):
    print "%-20s %d %s" % (msg.topic, msg.qos, msg.payload)
    mosq.publish('pong', 'ack', 0)

def on_publish(mosq, obj, mid):

if __name__ == '__main__':
    client = paho.Client()
    client.on_message = on_message
    client.on_publish = on_publish

    #client.tls_set('', certfile='c1.crt', keyfile='c1.key')
    client.connect("", 1883, 60)

    client.subscribe("kids/yolo", 0)
    client.subscribe("adult/#", 0)

    while client.loop() == 0:

# vi: set fileencoding=utf-8 :

Test the subscriber example

First start the subscriber which will enter a loop waiting for new messages: ::bash ./

Then open a new terminal and send a message:

mosquitto_pub -d -h localhost -q 0 -t adult/pics -m "can i haz moar kittenz"

This should generate a message in the terminal running the subscriber.

Configure SSL/TLS

See mosquitto-tls on how to generate certificates and keys.

Once created you need to adjust /etc/mosquitto/mosquitto.conf and accordingly and then use mosquitto_pub with cert and key:

mosquitto_pub -d -h localhost --cafile --cert c1.crt --key c1.key -q 0 -t adult/pics -m "can i haz moar kittenz"