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.
Requirements
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):
pass
if __name__ == '__main__':
client = paho.Client()
client.on_message = on_message
client.on_publish = on_publish
#client.tls_set('root.ca', certfile='c1.crt', keyfile='c1.key')
client.connect("127.0.0.1", 1883, 60)
client.subscribe("kids/yolo", 0)
client.subscribe("adult/#", 0)
while client.loop() == 0:
pass
# vi: set fileencoding=utf-8 :
Test the subscriber example
First start the subscriber which will enter a loop waiting for new messages: ::bash ./subscriber.py
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 subscriber.py accordingly and then use mosquitto_pub with cert and key:
mosquitto_pub -d -h localhost --cafile root.ca --cert c1.crt --key c1.key -q 0 -t adult/pics -m "can i haz moar kittenz"
References
* http://jpmens.net/2013/02/25/lots-of-messages-mqtt-pub-sub-and-the-mosquitto-broker/
* https://www.justinribeiro.com/chronicle/2012/11/08/securing-mqtt-communication-between-ardruino-and-mosquitto/
* http://www.instructables.com/id/USB-RFID-Python-Pub-Sub-MQTT/
* http://mosquitto.org/documentation/python/
* https://pypi.python.org/pypi/paho-mqtt