Use MQTT with Raspberry Pi

Establish the environment

Install Python3

python3 --version
sudo apt install python3

Install the MQTT client library

git clone https://github.com/eclipse/paho.mqtt.python 
cd paho.mqtt.python
python3 setup.py install
pip3 install paho-mqtt

The use of MQTT

Connect to the MQTT broker

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • Websocket Port: 8083
docker run -d --name emqx -p 1883:1883 -p 8083:8083 -p 8084:8084 -p 18083:18083 emqx/emqx
# test_connect.py 
import paho.mqtt.client as mqtt

# The callback function. It will be triggered when trying to connect to the MQTT broker
# client is the client instance connected this time
# userdata is users' information, usually empty. If it is needed, you can set it through user_data_set function.
# flags save the dictionary of broker response flag.
# rc is the response code.
# Generally, we only need to pay attention to whether the response code is 0.
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected success")
else:
print(f"Connected fail with code {rc}")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)
client.loop_forever()
python3 test_connect.py

Subscribe

# subscriber.py
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")
# subscribe, which need to put into on_connect
# if reconnect after losing the connection with the broker, it will continue to subscribe to the raspberry/topic topic
client.subscribe("raspberry/topic")
# the callback function, it will be triggered when receiving messages
def on_message(client, userdata, msg):
print(f"{msg.topic} {msg.payload}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# set the will message, when the Raspberry Pi is powered off, or the network is interrupted abnormally, it will send the will message to other clients
client.will_set('raspberry/status', b'{"status": "Off"}')
# create connection, the three parameters are broker address, broker port number, and keep-alive time respectively
client.connect("broker.emqx.io", 1883, 60)
# set the network loop blocking, it will not actively end the program before calling disconnect() or the program crash
client.loop_forever()

Publish messages

import paho.mqtt.client as mqtt
import time
def on_connect(client, userdata, flags, rc):
print(f"Connected with result code {rc}")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)
# send a message to the raspberry/topic every 1 second, 5 times in a row
for i in range(5):
# the four parameters are topic, sending content, QoS and whether retaining the message respectively
client.publish('raspberry/topic', payload=i, qos=0, retain=False)
print(f"send {i} to raspberry/topic")
time.sleep(1)
client.loop_forever()

Test

Test topic subscription

  1. Open the terminal, run Python code, monitor messages.
python3 subscriber.py

Test publish message

  1. Subscribe to the topic raspberry/topic in the MQTT X client.
  2. Run Python code in the terminal.

Test the will message

  1. Subscribe to raspberry/status in the MQTT X client.

Summary

  • Use a mobile phone to send MQTT messages, remotely control the Raspberry Pi.
  • Send the device information of Raspberry Pi to the MQTT broker regularly and receive messages through mobile phone, then can round-the-clock monitor.
  • You can access the MQTT broker through the Raspberry Pi and use various kinds of sensors and ESP modules to create many interesting IoT applications.

--

--

--

EMQ is an open-source IoT data infrastructure software provider, delivering the world’s leading open-source MQTT message broker and stream processing database.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Understanding Compilers — For Humans

The Most Important Skill for Data Engineers

Bash and directory positioning

What is an icon font? How to make and use it in Axure RP and Coding?

Earlier this week, following my application for the HNG internship, I received an invitation mail…

How to convert CSV to JSON easily

We Just Launched a New $9.99/mo Data Streaming/Visualization Service. Here’s Why.

Generate JWK and PASERK easily by “mkkey”

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
EMQ Technologies

EMQ Technologies

EMQ is an open-source IoT data infrastructure software provider, delivering the world’s leading open-source MQTT message broker and stream processing database.

More from Medium

Vscode server

Converting Images to WebP From Terminal

Setup OpenOCD with JTAG + UART on raspberry pi 4 using FT232H

Install Monika on Linux using Snapcraft