https://www.halvorsen.
blog
MQTT
A Communication Protocol popular in Internet of Things Applications
Hans-Petter Halvorsen
Contents
• MQTT Overview
• MQTT Brokers
– HiveMQ Cloud
• MQTT Clients
– MQTT X
• Python
– MQTT Python Library
– HiveMQ Cloud and Python Examples
• ThingSpeak
– ThingSpeak and MQTT X Client
– ThingSpeak and Python
https://www.halvorsen.blog
MQTT
Hans-Petter Halvorsen Table of Contents
MQTT
• MQTT is a Communication Protocol popular in Internet of
Things (IoT) Applications
• https://mqtt.org
• You can use or implement MQTT in all the most popular
Programming environments
• MQTT can be used on all the popular platforms like
Windows, macOS, Linux, Arduino, Raspberry Pi
• You can use an existing API, or you can implement and
use the MQTT protocol from scratch
• We will Python in this Tutorial
MQTT
https://mqtt.org
MQTT
• Message Queueing Telemetry Transport (MQTT) is
an IoT connectivity protocol
• MQTT is used in applications with thousands of
sensors
• MQTT is efficient in terms of bandwidth, battery,
and resources
• MQTT uses a publish/subscribe model
• MQTT can be implemented using standard HTTP
calls
• M2M (machine to machine) Communication
Internet of Things (IoT) and MQTT
• Internet of Things (IoT): To get data to and from
devices on a network.
• MQTT is a lightweight protocol that makes this
easier
MQTT Scenario
MQTT Publishers MQTT Subscribers
MQTT Broker
Sensors
Publish/Subscribe Model
Typically, we have what we call Producers (Publishers), and we have Consumers,
which can be both Publishers and Subscribers.
Publish (Topic, Data)
Producer Publish (Topic, Data) Broker Publish (Topic)
Consumer
Client Server Client
Client that Writes Data Client that Reads Data
MQTT Terms
• MQTT Broker
– Server
• MQTT Publishers
– Clients that Write/Publish Data
• MQTT Subscribers
– Clients that Read/Subscribe to Data
MQTT Topics
• Data in MQTT are Published to Topics
• Topics are made up of one or more topic levels,
separated by a forward slash
Example:
Sensor/Temperature/TMP36
• Topics are used to organize the data
• Topics are case sensitive
• Topics don’t have to be pre-registered at the broker
MQTT Topics
Topics are used to organize the data
Sensors
Site1 Site2
Temperature Pressure Temperature Flow
Subscribe on Topics - Wildcards
Wildcards: Sensors/Site1/#
Sensors
Site1 Site2
Temperature Pressure Temperature Flow
Subscribe on Topics - Wildcards
Wildcards: Sensors/+/Temperature
Sensors
Site1 Site2
Temperature Pressure Temperature Flow
Quality of Service (QoS)
MQTT offers 3 Quality of Service levels:
• QoS 0 - Delivery at most once (“fire and forget“)
- In QoS 0 there is no guarantee of delivery
• QoS 1 - Delivery at least once
- QoS 1 guarantees that a message is delivered at least one time
to the receiver
• QoS 2 - Delivery exactly once
- QoS 2 is the highest level of service in MQTT. This level
guarantees that each message is received only once by the
intended recipients
https://www.halvorsen.blog
MQTT Brokers
Hans-Petter Halvorsen Table of Contents
Free MQTT Brokers
• Eclipse Mosquitto
https://mosquitto.org
• HiveMQ Community Edition (HiveMQ CE)
https://www.hivemq.com
• HiveMQ Cloud
https://www.hivemq.com
• EMQ X MQTT IoT Cloud
https://www.emqx.com/en/mqtt/public-mqtt5-broker
• ThingSpeak (IoT Cloud Platform that offers an MQTT
Broker among others)
https://thingspeak.com
https://www.halvorsen.blog
HiveMQ Cloud
MQTT Broker in the Cloud
Hans-Petter Halvorsen Table of Contents
HiveMQ Cloud
https://www.hivemq.com
HiveMQ Cloud
https://www.hivemq.com
Here you can find a
basic Python example
https://www.halvorsen.blog
MQTT Clients
Hans-Petter Halvorsen Table of Contents
Free MQTT Clients
• MQTT X is an MQTT 5.0 Open-source Desktop
Client
https://mqttx.app
• HiveMQ Community Edition (HiveMQ CE)
– Both Broker and MQTT Client
https://www.hivemq.com
https://www.halvorsen.blog
MQTT X
Open-source MQTT Desktop Client
Hans-Petter Halvorsen Table of Contents
MQTT X
• MQTT X is an MQTT 5.0 Open-source MQTT
Desktop Client
• It work with and Windows, macOS and Linux
• https://mqttx.app
MQTTX
Connect to Broker HiveMQ Cloud using MQTTX Client
Publish to Broker HiveMQ Cloud using MQTTX Client
https://www.halvorsen.blog
Python
Using MQTT with Python
Hans-Petter Halvorsen Table of Contents
Using MQTT in Python
• The most used MQTT Python Library is paho-
mqtt
• We need to install the paho-mqtt Python
Library using pip
paho-mqtt
We need to install the paho-mqtt Python Library. You
can use pip, or as here, the Thonny Python Editor has
an easy way to install Python Libraries from a GUI
https://www.halvorsen.blog
HiveMQ Cloud
and Python
Hans-Petter Halvorsen Table of Contents
HiveMQ Cloud Python Example
import paho.mqtt.client as mqtt
brokerAddress = "xxxxx"
userName = "xxxxx"
passWord = "xxxxx"
topic = "my/test/topic"
data = "Hello"
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
else:
print("Connect returned result code: " + str(rc))
def on_message(client, userdata, msg):
print("Received message: " + msg.topic + " -> " + msg.payload.decode("utf-8"))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
client.username_pw_set(userName, passWord)
client.connect(brokerAddress, 8883)
client.subscribe(topic)
client.publish(topic, data)
client.loop_forever()
Example We Publish some Data using MQTTX
Topic: Sensor/Temperature/TMP36
Data: 21
Data: 22
Data: 23
Python Example
In this Example the Thonny
Python Editor has been used
We Subscribe to the Topic using Python
– And as you see we get the same Data
Publish – Subscribe Examples
import paho.mqtt.client as mqtt
import random
Publish
import time
brokerAddress = "xxxxxx"
userName = "xxxxxx"
passWord = "xxxxxxx"
topic = "Sensor/Temperature/TMP36"
min = 20
max = 30
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
else:
print("Connect returned result code: " + str(rc))
# create the client
client = mqtt.Client()
client.on_connect = on_connect
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
client.username_pw_set(userName, passWord)
client.connect(brokerAddress, 8883)
# Publish Temperature Data
wait = 20
while True:
data = random.randint(min, max)
print(data)
client.publish(topic, data)
time.sleep(wait)
import paho.mqtt.client as mqtt
brokerAddress = "xxxxxx"
userName = "xxxxxx"
Subscribe
passWord = "xxxxxxx"
topic = "Sensor/Temperature/TMP36"
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
else:
print("Connect returned result code: " + str(rc))
def on_message(client, userdata, msg):
print("Received message: " + msg.topic + " -> " + msg.payload.decode("utf-8"))
# create the client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set(tls_version=mqtt.ssl.PROTOCOL_TLS)
client.username_pw_set(userName, passWord)
client.connect(brokerAddress, 8883)
client.subscribe(topic)
client.loop_forever()
Summary
• Example 1
– Python Publish Data to a Topic
– MQTT X Client Subscribing on the same Topic
• Example 2
– MQTT X Client Publish Data to a Topic
– Python Subscribing on the same Topic
• Example 3
– Python Publish Data to a Topic
– Python Subscribing on the same Topic
https://www.halvorsen.blog
ThingSpeak
Internet of Things Cloud Service
Hans-Petter Halvorsen Table of Contents
MQTT ThingSpeak
• https://mathworks.com/help/thingspeak/use-
desktop-mqtt-client-to-publish-to-a-
channel.html
Configure MQTT in ThingSpeak
https://thingspeak.com
ThingSpeak and MQTTX
ThingSpeak MQTT Broker:
mqtt:// mqtt3.thingspeak.com
Publish to Channel Field
Topic: channels/<ChannelID>/publish/fields/field1
Data: 45
Publish to Channel Field
Topic: channels/<ChannelID>/publish/fields/field1
Data: 45
Publish to Channel Field
Topic: channels/<ChannelID>/publish/fields/field1
Data: 45
Publish to Channel Feed
Here we will Publish to multiple Fields within a Channel
Topic: channels/<ChannelID>/publish
Data: field1=20&field2=30&status=MQTTPUBLISH
Publish to Channel Feed
Subscribe to a Channel Feed
Subscribe to a Channel Feed
Here you see a LabVIEW Application
writing Data to ThingSpeak.
Note! This Application is using the
ThingSpeak REST API and not MQTT
Subscribe to a Channel Feed
https://www.halvorsen.blog
ThingSpeak
and Python
Hans-Petter Halvorsen Table of Contents
xxx Publish
Publish
import paho.mqtt.client as mqtt
import random
import time
brokerAddress = "mqtt3.thingspeak.com"
port = 1883
clientId = "xxxxxx"
Publish
userName = "xxxxxx"
passWord = "xxxxxx"
channelID = "xxxxxx"
field = "field1"
topic = "channels/" + channelID + "/publish/fields/" + field
min = 20
max = 30
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
else:
print("Connect returned result code: " + str(rc))
# create the client
client = mqtt.Client(clientId)
client.on_connect = on_connect
client.username_pw_set(userName, passWord)
client.connect(brokerAddress, port)
# Publish Temperature Data
wait = 20
while True:
data = random.randint(min, max)
print(data)
client.publish(topic, data)
time.sleep(wait)
xxx Subscribe
Subscribe
import paho.mqtt.client as mqtt
brokerAddress = "mqtt3.thingspeak.com"
Subscribe
port = 1883
clientId = "xxxxxx"
userName = "xxxxxx"
passWord = "xxxxxx"
channelID = "xxxxxx"
field = "field1"
topic = "channels/" + channelID + "/publish/fields/" + field
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully")
else:
print("Connect returned result code: " + str(rc))
def on_message(client, userdata, msg):
print("Received message: " + msg.topic + " -> " +
msg.payload.decode("utf-8"))
# create the client
client = mqtt.Client(clientId)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(userName, passWord)
client.connect(brokerAddress, port)
client.subscribe(topic)
client.loop_forever()
Publish xxx Subscribe
Summary
• A short introduction to MQTT has been given
• Introduction to some MQTT Brokers
• Use of MQTT Desktop Client software
– MQTT X
• Python Examples
– HiveMQ Cloud
– ThingSpeak
Hans-Petter Halvorsen
University of South-Eastern Norway
www.usn.no
E-mail: [email protected]
Web: https://www.halvorsen.blog