IOT Series: Hello, MQTT

In this series, we’ll be doing some IOT-related applications using Python and Mosquitto, so if you’re interested in IOT or is currently in an environment where you hear Industry 4.0 then you wouldn’t want to miss this series 🙂

Before you proceed, make sure you’re familiar with Python, and it’s also a good idea to build a separate environment for this.

I have a blog about creating Python environments in case you haven’t tried it:

Broker

Most IOT systems use publish/subscribe model and is usually implemented with a “broker”. In our case, we would need an MQTT broker so we can publish and subscribe to topics.

Mosquitto

There are many MQTT brokers out there and one of them is Mosquitto, which is easy to install and is used by many.

Here’s the download page, just select the one for your environment:

https://mosquitto.org/download/

MQTT library

Another thing we need to have is a library that would make it easy for us to talk to an MQTT broker.

There are so many out there but we’ll use paho-mqtt for Python.

If you need a list of other libraries, check out this link:

https://en.wikipedia.org/wiki/Comparison_of_MQTT_implementations

Paho-MQTT

If you’ve setup your Python environment (I’m using Python 3.7.4 in this blog), you can install this libary:

https://pypi.org/project/paho-mqtt/

From inside the Python environment, you may just enter this:

pip install paho-mqtt

Python Code

Let’s write a super simple example where you have an Oven that publishes its temperature and you have a smart TV that displays the change in temperature.

Import Modules

Let’s import 2 modules:

import time
from paho.mqtt import client as mqttclient

We’ll use the time module to simulate delay, to allow certain event to take place (since we’ll be running locally, we need to ensure some events fire before running the next routines).

Core Routines

Here are the lines of codes we’ll need for this very simple example:

# create an oven that publishes its temperature
producer = mqttclient.Client('my-smart-oven')
producer.connect('localhost', 1883)

# create a consumer that will display the oven temperature
subscriber = mqttclient.Client('my-smart-tv', userdata={'id':'tv-smt-99'})

# link the function for displaying the readings
subscriber.on_message = display_oven_temp

subscriber.connect('localhost', 1883)
subscriber.loop_start()
subscriber.subscribe('oven-01/temp')
time.sleep(1)

producer.publish('oven-01/temp', 30)

time.sleep(2)
subscriber.loop_stop()

print("Done")

Basically, we create a publisher and subscriber. The oven is the publisher since it publishes data — its temperature. The tv is the subscriber since it monitors the published data — the ovens temperature, and does something with it like displaying it.

We placed some delay in the form of “time.sleep” statements, cause some events won’t have time to propagate before the next one happens and it won’t work as intended (since we’re running locally).

Callback Functions

In order for our tv to receive the published temperature, we need to define the callback function for the “on_message” event (which you might have noticed from the core routines above).

Here’s the function definition:

def display_oven_temp(client, userdata, message):
    """ on_message """
    encoding = 'utf-8'

    if message.topic != "subscribe":
        # if it's not a subscription topic, display it
        print(f"{message.topic}")
        content = message.payload.decode(encoding)
        print(f"\t{content}")

When you run these codes, this is what you’ll see:

The topic (oven-01/temp) gets printed and its value (30) which is exactly what was set by the publisher.

This is a very simple example, just to get you started and to remove any distracting routines that might just confuse you if those have been added here. We’re going to extend this, refactor, make reusable and then I’ll post them in this blog.

Source Codes

As usual, you can download the source codes in GitHub:

https://github.com/vegitz/codes/tree/master/0023%20MQTT%20in%20Python/01%20Hello%20MQTT

Leave a Comment