MQTT Communication

MQTT (Message Queue Telemetry Transport) is a protocol for machine-to-machine communication that is popular in IoT (Internet of Things) networks. The broker manages data transport from clients that publish or subscribe to updates. It was created around 1998 and has increased in popularity with the increase of IoT devices. It is especially good for ad hoc networking of devices that have varying levels of latency and communication bandwidth. MQTT typically runs over TCP/IP for bi-directional and lossless connections.

MQTT Broker (Server)

The MQTT broker can be in the cloud or hosted locally. The amqtt library is a lightweight Python option for hosting a broker locally.

pip install amqtt

Create the MQTT broker with the following Python script. This script runs indefinitely to manage the publish/subscribe requests from clients.

Run MQTT Broker

import asyncio
import os
from amqtt.broker import Broker

config = {
    "listeners": {
        "default": {
            "type": "tcp",
            "bind": "0.0.0.0:1883",
        },
        "ws-mqtt": {
            "bind": "127.0.0.1:8080",
            "type": "ws",
            "max_connections": 10,
        },
    },
    "sys_interval": 10,
    "auth": {
        "allow-anonymous": True
    },
    "topic-check": {"enabled": False},
}

broker = Broker(config)

async def test_coro():
    await broker.start()

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(test_coro())
    asyncio.get_event_loop().run_forever()

Another broker option is to download Eclipse Mosquitto or use the online MQTT broker.

MQTT Client with Local Broker

The paho-mqtt package is a popular Python MQTT client. Paho also provides MQTT client libraries for other languages as well. Install the Paho client with pip. Also install the tclab library to provide an Internet of Things (IoT) device or emulator.

pip install paho-mqtt
pip install tclab

This example uses the amqtt local broker with the paho client. Use tclab.TCLab() if a TCLab physical device is connected. Otherwise, use the TCLab digital twin with tclab.TCLabModel().

Client to Publish Temperature to Local Broker

import paho.mqtt.client as mqtt
import time
import tclab

mqttBroker ='127.0.0.1'
client = mqtt.Client('TCLab')
client.connect(mqttBroker,port=8080)

with tclab.TCLabModel() as lab:
    lab.Q1(70) # set heater 1 to 70%
    # cycle 30 sec, publishing temperature
    for i in range(30):
        client.publish('T1', lab.T1)
        print('Published ' + str(round(lab.T1,2)))
        time.sleep(1)

MQTT Client with Cloud Broker

This example uses the online MQTT broker provided by Eclipse Mosquitto from the Eclipse Foundation. It is an open-source message broker that can also be installed locally. There are also premium services such as Cedalo and Streamsheets for dashboarding. Test simple MQTT clients that publish and subscribe to the Eclipse Mosquitto public MQTT broker.

Client to Publish Temperature to Cloud Broker

import paho.mqtt.client as mqtt
import time
import tclab

mqttBroker ='mqtt.eclipseprojects.io'
client = mqtt.Client('TCLab')
client.connect(mqttBroker)

# use tclab.TCLab() if physical device connected
#   otherwise use digital twin tclab.TCLabModel()
with tclab.TCLabModel() as lab:
    lab.Q1(70) # set heater 1 to 70%
    # cycle 30 sec, publishing temperature
    for i in range(30):
        client.publish('T1', lab.T1)
        print('Published ' + str(round(lab.T1,2)))
        time.sleep(1)

Client to Subscribe to Temperature through Cloud Broker

import paho.mqtt.client as mqtt
import struct

def on_message(client, userdata, msg):
    print(f'Temperature: {float(msg.payload)}')

mqttBroker ='mqtt.eclipseprojects.io'
client = mqtt.Client('IoT_Display')
client.on_message = on_message
client.connect(mqttBroker)
client.subscribe('T1')
client.loop_forever()

βœ… Knowledge Check

1: What does MQTT stand for?

A. Message Queue Text Transfer
Incorrect. MQTT stands for Message Queue Telemetry Transport, not Message Queue Text Transfer.
B. Message Queue Telemetry Transport
Correct. MQTT stands for Message Queue Telemetry Transport.
C. Message Quality Test Transfer
Incorrect. MQTT stands for Message Queue Telemetry Transport, not Message Quality Test Transfer.
D. Machine Queue Transfer Type
Incorrect. MQTT stands for Message Queue Telemetry Transport, not Machine Queue Transfer Type.

2: Which library can be used to host an MQTT broker locally in Python?

A. paho-mqtt
Incorrect. While paho-mqtt is a popular MQTT client library, it does not provide the ability to host an MQTT broker.
B. Eclipse Mosquitto
Incorrect. Eclipse Mosquitto is an open-source message broker, but it is not a Python library.
C. amqtt
Correct. The amqtt library is a lightweight Python option for hosting an MQTT broker locally.
D. tclab
Incorrect. tclab is a library for controlling the TCLab device and not for hosting an MQTT broker.

πŸ€– Generative AI Learning

Use these prompts after running the publish and subscribe examples. Direct the AI - you design; it critiques.

"Quiz me with 5 questions, one at a time, on MQTT: what the broker does and why publishers never talk to subscribers directly, how publish/subscribe differs from Modbus-style polling and when each wins, what a topic string like plant1/unit3/pump7/vibration buys you, what happens to messages published while a subscriber is offline, and one risk of using a public broker like test.mosquitto.org for real data. Then teach me the one thing this page skips - QoS 0/1/2 - and quiz me on which level a battery-powered sensor vs a safety-relevant alarm should use. Grade my answers and list my misconceptions."
"I am designing the MQTT topic hierarchy for an EV charging depot: 40 chargers, each reporting power, energy, connector status, and temperature every 5 seconds, plus depot-level meters. Here is my proposed hierarchy and payload format: {paste}. Critique it as the integration engineer who must live with it: can a dashboard subscribe to one charger, one signal across all chargers, and the whole depot with single wildcard patterns (+, #)? What belongs in the topic vs in the JSON payload? Where do retained messages help? Make me fix one concrete weakness."

πŸ“‹ What to Turn In

Add a short entry (about half a page) to your course workbook that curates your results into a demonstration of what you learned. You may use Generative AI to help write it, but you must supply the correct outputs, justifications, and assumptions. Answer these questions:

  1. Show your publish/subscribe round trip (local or cloud broker): the topic, one published payload, and the subscriber output.
  2. Include your final EV-depot topic hierarchy and the wildcard subscription for "temperature of every charger." What weakness did the critique make you fix?
  3. MQTT vs Modbus vs OPC UA in your own words: pick the right one for (a) the 40-charger depot, (b) a 1998 PLC, (c) a corporate data lake ingest - one sentence of justification each.

Course on GitHub

Python

Access

Communicate

Electrical

Series

Data Engineering

Applications

Object Detection πŸ‘οΈ
Text OCR πŸ‘οΈ
Pose Estimation πŸ‘οΈ
Electromagnetic Relay βš™οΈ
Servo Control SG90 βš™οΈ
Solid State Relay βš™οΈ
Fired Heater Control ⏱️
RAG Similarity Search πŸ—£οΈ
Generative AI πŸ—£οΈ
RAG LLM Integration πŸ—£οΈ
Biomechanics πŸ“ˆ
Air Pressure πŸ“
CO2 Sensors πŸ“
Humidity πŸ“
Light Intensity πŸ“
Location GPS πŸ“
Temperature πŸ“
πŸ‘οΈ=Computer Vision
βš™οΈ=Actuators
⏱️=Time Series
πŸ—£οΈ=Language
πŸ”Š=Audio
πŸ“ˆ=Regression
πŸ“Š=Classification
πŸ“=Sensors

Related Courses

Admin