Tutorials

Simple MQTT client in Python

MQTT is a lightweight protocol that’s ideal for the Internet of Things.

MQTT is based on the publish-subscribe model. This is quite different from the typical network protocol models where a connection is established, after which the client requests the server for information directly, and the server sends back information to the client’s IP address directly. In case of MQTT, nodes connect to a broker and subscribe to a topic. Then they wait. If a node publishes to the same topic in the node, all the other nodes who had subscribed to it receive it.

In the diagram below, Node 5 publishes “Hi!” to the topic “hello/world/”, and Node 1 and Node 3 receive the message since they are subscribing to the topic.

MQTT_fig1

There are various public brokers out there which anyone can use for general testing. A complete list can be found here – http://mqtt.org/wiki/doku.php/public_brokers. I’m using the broker- test.mosquitto.org. All my clients will connect to this broker at the address and port provided. Think of it like public bulletin boards, free for anyone to post and read. Later on, you might want your own private broker for your application. I’ll cover how to do that in my next post.

This is a tutorial to get MQTT clients up and running quickly on Python 2.7 (on a Linux machine). I’m using the oddly named Open Source MQTT broker, Mosquitto. It’s now been donated to the Eclipse Paho project. A lot of old code I saw online on some blogs has to be modified slightly to make it work now.

Part 1: Installation
Hopefully, you’ll have pip installed. It’s a great tool to install python modules, and it’ll save you a lot of hassle.
sudo apt-get install python-pip
Next, install the MQTT broker Mosquitto (or Paho now)-
pip install paho-mqtt

Part 2: Subscribe
Here’s a basic python code to subscribe to a topic hosted by a broker on the local machine itself.

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
print(“Connected with result code “+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(“hello/world”)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print “Topic: “, msg.topic+’nMessage: ‘+str(msg.payload)

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(“test.mosquitto.org”, 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

This has been borrowed from https://pypi.python.org/pypi/paho-mqtt.

Part 3: Publish
Well now there’s a node which has subscribed to the topic /hello/world and is waiting for someone to publish data. This basic script below will do the job.

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt

mqttc = mqtt.Client(“python_pub”)
mqttc.connect(“test.mosquitto.org”, 1883)
mqttc.publish(“hello/world”, “Hello, World!”)
mqttc.loop(2) //timeout = 2s

Part 4: Execute
That’s it. You’re done. Run the subscribe node first and then the publish node. You’ll notice the subscribed node receiving any message sent by the publishing node via the broker.

The next post covers how to expand our MQTT architecture by setting up our own broker.

2 Comments

  1. Hi,
    Thank you for this excellent intro!
    I would like to build my own local broker? Is there anything in the Paho API to do it?

    Regards
    Ayoub

Leave a Reply

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