How to use MQTT in a Django project

MQTT is a lightweight IoT messaging protocol based on the publish/subscribe model, which can provide real-time reliable messaging services for connected devices with very little code and bandwidth. It is widely used in industries such as IoT, mobile Internet, smart hardware, Internet of vehicles, and electricity and energy.

Django is an open-source web framework and one of the more popular Python web frameworks. This article mainly describes how to connect, subscribe, unsubscribe, and send and receive messages between MQTT clients and MQTT brokers in the Django project.

We will write a simple MQTT client using the paho-mqtt client library. paho-mqtt Python has a widely used MQTT client library that provides client support for MQTT 5.0, 3.1.1 and 3.1 on Python 2.7 and 3.x.

project initiation

This project uses Python 3.8 for development testing, and the reader can verify the version of Python with the following command.

$ python3 --version
Python 3.8.2

Install Django and paho-mqtt using pip.

pip3 install django
pip3 install paho-mqtt

Create a Django project.

django-admin startproject mqtt-test

The directory structure after creation is as follows.

├── manage.py
└── mqtt_test
  ├── __init__.py
  ├── asgi.py
  ├── settings.py
  ├── urls.py
  ├── views.py
  └── wsgi.py

using paho-mqtt

This article will be using the free public MQTT broker provided by EMQ. The service is built on the basis of the MQTT cloud service – EMQX Cloud. The server access information is as follows:

  • Broker: broker.emqx.io
  • tcp port: 1883
  • websocket port: 8083

import owl-mqtt

import paho.mqtt.client as mqtt

write connection callback

Successful or failed MQTT connections can be handled in this callback function, and this instance will subscribe django/mqtt Subject after a successful connection.

def on_connect(mqtt_client, userdata, flags, rc):
   if rc == 0:
       print('Connected successfully')
       mqtt_client.subscribe('django/mqtt')
   else:
       print('Bad connection. Code:', rc)

write message callback

This will print the messages received by the function django/mqtt Subject.

def on_message(mqtt_client, userdata, msg):
   print(f'Received message on topic: {msg.topic} with payload: {msg.payload}')

Adding Django Configuration Items

In add configuration item for MQTT Broker settings.py, Readers who have questions about the following configuration items and MQTT-related concepts mentioned in this article can check out the blog The Easiest Guide to Getting Started with MQTT.

This example uses anonymous authentication, so the username and password are set to empty.

MQTT_SERVER = 'broker.emqx.io'
MQTT_PORT = 1883
MQTT_KEEPALIVE = 60
MQTT_USER = ''
MQTT_PASSWORD = ''

Configuring the MQTT Client

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(settings.MQTT_USER, settings.MQTT_PASSWORD)
client.connect(
    host=settings.MQTT_SERVER,
    port=settings.MQTT_PORT,
    keepalive=settings.MQTT_KEEPALIVE
)

Creating a Message Publishing API

We create a simple POST API to implement MQTT message publishing.

In real applications, API code may require processing more complex business logic.

add the following code to views.py,

import json
from django.http import JsonResponse
from mqtt_test.mqtt import client as mqtt_client


def publish_message(request):
    request_data = json.loads(request.body)
    rc, mid = mqtt_client.publish(request_data['topic'], request_data['msg'])
    return JsonResponse({'code': rc})

add the following code to urls.py,

from django.urls import path
from . import views

urlpatterns = [
    path('publish', views.publish_message, name="publish"),
]

Start MQTT Client

add the following code to __init__.py,

from . import mqtt
mqtt.client.loop_start()

At this point, we’ve finished writing all the code, and the full code can be found on GitHub.

Finally, execute the following command to run the Django project.

python3 manage.py runserver

When the Django application starts, the MQTT client will connect to the MQTT broker and subscribe to the topic. django/mqtt,

test

Next, we’ll use an open-source cross-platform MQTT client – MQTT X – to test connections, subscriptions, and publishing.

receiving test messages

  1. Create an MQTT connection in MQTT X, enter the name of the connection, leave the other parameters as defaults, and click Connect Button in the top right corner to connect with the broker.

  2. publish message Hello from MQTT X To django/mqtt Subject in the message publication box at the bottom of MQTT X.

    Message publishing box at the bottom of MQTT X

  3. Messages sent by MQTT X will appear in the Django runtime window.

    Messages sent by MQTT X will appear in the Django runtime window.

Test Message Publishing API

  1. subscribe django/mqtt Topics in MQTT X.

    Test Message Publishing API

  2. use postman to call /publish API: Publish message Hello from Django To django/mqtt Subject.

  3. You will see messages sent by Django in MQTT X.

    Messages sent by Django in MQTT X.

summary

At this point, we have completed the development of the MQTT client paho-mqtt, Enabling communication using MQTT in Django applications. In practice, we can extend the MQTT client to implement more complex business logic based on business needs.

Leave a Comment