First steps using Python and MQTT (using pynotify on Ubuntu)

Until recently developing MQTT clients in anything but perl was a little tricky due to a selection of badly documented, restrictively licensed client libraries (in PHP, Java and C). After a lot of hard work on the part of Roger Light (@ralight developer behind the OSS MQTT Broker Mosquitto) there is now another solution available.

An MQTT pubsub client library written in C is now included along with a basic python wrapper. To me this greatly improves the situation as it now means it’s possible to quickly and simply develop real applications or web applications without wrestling with some of the more complex APIs traditionally used. After attempting to get to grips with the IBM ia92 java client library this was a breath of fresh air.

Ubuntu notification triggered by an MQTT Message

As an initial toe in the water exercise I looked at the included sub.py script (after compiling and installing mosquitto 0.8.2)  and wrote the code below so that all messages on the “test” topic display a notification in ubuntu. While only a minor coding exercise this is a potentially useful application when MQTT is being used for monitoring systems.

Note: Recently others have noticed problems with installation of the python libraries, if you have such problems check to ensure that the appropriate files are in /usr/local/lib/python2.6/dist-packages/

To enable me to display notifications simply I chose the built in Ubuntu notifications system which can be hooked into with pynotify. Notifications are displayed as shown above.

Control of mosquitto is a simple matter of defining callbacks for the required events, in this case just connection and receiving a message.

The code is shown below and is really self explanatory:

#!/usr/bin/python

import pynotify
import mosquitto

#define what happens after connection
def on_connect(rc):
	print "Connected"

#On recipt of a message create a pynotification and show it
def on_message(msg):
	n = pynotify.Notification (msg.topic, msg.payload)
	n.show ()

#create a broker
mqttc = mosquitto.Mosquitto("python_sub")

#define the callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect

#connect
mqttc.connect("<your broker ip address>", 1883, 60, True)

#subscribe to topic test
mqttc.subscribe("test", 2)

#keep connected to broker
while mqttc.loop() == 0:
	pass

Hopefully this short illustration will prove useful to those just getting started. This won’t be the end of working with mosquitto libraries…now just to work out python…