MQTT Quick start!

I’ve got a project in mind and I want to put a bit of pub/sub in it. It’s an “Internet of Things” (IOT) project and the idea is that my devices will be pretty simple – i’ll just publish some values from a sensor to my broker; and do the heavy lifting of analysing and acting on the readings using a “real” computer or server. The devices will be simple and low-powered so a lightweight protocol like MQTT seems like a good choice.

It looks like the premier open source broker for MQTT is Mosquitto; so let’s use that to get a broker up and running; publish some messages to it; and have a subscriber log those messages out to the console. This, by the way; is all going to be on Debian Jessie.

I don’t like to “pollute” my laptop with every hobby project that momentarily grabs my attention; so first let’s get docker installed and then start up the toke/mosquitto container.

sudo apt-get install docker.io
sudo docker run -ti -p 1883:1883 -p 9001:9001 toke/mosquitto

Next we’ll run up a couple of python scripts in a virtualenv: (I assume you’ve already done a apt-get virtualenv to install virtualenv and Python on your system) These will, respectively; publish messages to the broker (under a test topic) and subscribe to that topic.

mkdir mqtt-test
cd mqtt-test
virtualenv env
source env/bin/activate
pip install paho-mqtt

publisher.py

#!/usr/bin/env python
import time
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))

client = mqtt.Client()
client.on_connect = on_connect
print("I'm alive!")
client.connect("localhost", 1883, 60)

while True:
    client.publish("test", "This is a test transmission!")
    time.sleep(1)

subscriber.py

#!/usr/bin/env python
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("test")

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
print("I'm alive!")
client.connect("localhost", 1883, 60)

client.loop_forever()

Don’t forget to chmod +x *.py and then you can ./publisher.py and ./subscriber.py in two separate consoles to see your dockerised MQTT broker in action. Now I just need to wait for my devices to be delivered and I can get to the interesting bit!

Leave a Reply

Your email address will not be published. Required fields are marked *