MQTT is a messaging protocol developed by IBM. MQTT is a lightweight publish-subscribe messaging transport protocol designed for M2M and IoT connections. Mosquitto is an open-source message broker that implements the MQTT v3.1 protocol, providing a lightweight, publish/subscribe messaging model that makes short message communication between devices simple and easy to use. If you are new to the MQTT protocol, you may want to first understand the following concepts: MQTT Protocol Features — Compared to RESTful architecture in IoT systems, the MQTT protocol can better achieve remote control through its messaging capabilities. MQTT Protocol Roles — In RESTful architecture, there are two roles: client and server; in the MQTT protocol, there are publisher, broker (server), and subscriber. MQTT Protocol Messages — Messages in MQTT can be understood as the content (payload) exchanged between publishers and subscribers, which contain specific information that can be used by subscribers. MQTT Protocol Topics — Topics in MQTT can be understood as a collection of messages of the same or similar type.
This article explains how to install Mosquitto on a Raspberry Pi. It illustrates how to use the MQTT protocol for message subscription on Raspberry Pi through two simple examples: using the Mosquitto_sub command to subscribe to messages and using the paho-python extension library for remote control of GPIO ports. Two tools are used in this article — Mosquitto and paho-python, where Mosquitto is an open-source message broker that implements the MQTT v3.1 protocol, providing a lightweight, publish/subscribe messaging model that makes message communication between devices simple and easy; additionally, paho-python is a client that complies with the MQTT v3.1 protocol, allowing connection to MQTT broker servers, publishing messages, subscribing to messages, and receiving pushed messages.
1 Installing Mosquitto on Raspberry Pi
Installing Mosquitto on Raspberry Pi is similar to other platforms, but compiling it directly on the Raspberry Pi may take a bit longer. The source package for Mosquitto is not large, so the compilation time is bearable.
1.1 Installation
As of September 2014, the latest version is mosquitto-1.3.4. Create a new directory in Raspberry Pi, for example, software.
# Download the source code package
wget http://mosquitto.org/files/source/mosquitto-1.3.4.tar.gz
# Unzip
tar zxfv mosquitto-1.3.4.tar.gz
# Enter the directory
cd mosquitto-1.3.4
# Compile
make
# Install
sudo make install
1.2 Installation Notes
If you encounter the issue of not finding openssl/ssl.h during compilation, the solution is to install openssl.
sudo apt-get install libssl-dev
If you encounter the issue of not finding ares.h during compilation, modify config.mk to change WITH_SRV:=yes.
If you encounter the error ‘libmosquitto.so.1 error while loading shared libraries: libmosquitto.so.1: cannot open shared object file: No such file or directory’, the solution is to modify the location of libmosquitto.so.
# Create a link
sudo ln -s /usr/local/lib/libmosquitto.so.1 /usr/lib/libmosquitto.so.1
# Update dynamic link library
sudo ldconfig
If you encounter the error ‘make: g++: command not found’, the solution is to install the g++ compiler.
sudo apt-get install g++
2 Simple Examples
Design a simple test case where an MQTT broker runs on a PC, while the Raspberry Pi subscribes to messages on the topic gpio. The PC publishes messages on the same topic, with the message content being a JSON data packet formatted as {“index”:17,”value”:0}, where index represents the GPIO number of the Raspberry Pi and value represents the on or off state. In this example, the PC’s IP address is 192.168.1.110, and the Raspberry Pi’s IP address is 192.168.1.106.
2.1 Start MQTT Service on PC
mosquitto -v
2.2 Subscribe to Messages on Raspberry Pi
mosquitto_sub -v -t gpio -h 192.168.1.110
-h
specifies the MQTT broker host, pointing to the PC’s IP address 192.168.1.110.
2.3 Publish Messages on PC
mosquitto_pub -t gpio -h 192.168.1.110 -m "{\"pin\":17,\"value\":0}"
-h
specifies the MQTT broker host, pointing to the PC’s IP address 192.168.1.110.
2.4 Messages Pushed to Raspberry Pi
Finally, the following content is output on the Raspberry Pi:
gpio {"index":17,"value":0}
The following output appears in the PC’s MQTT server console:
1410600001: mosquitto version 1.3.4 (build date 2014-09-13 15:55:06+0800) starting
1410600001: Using default config.
1410600001: Opening ipv4 listen socket on port 1883.
1410600001: Opening ipv6 listen socket on port 1883.
1410600062: New connection from 192.168.1.106 on port 1883.
1410600062: New client connected from 192.168.1.106 as mosqsub/3063-raspberryp (c1, k60).
1410600062: Sending CONNACK to mosqsub/3063-raspberryp (0)
1410600062: Received SUBSCRIBE from mosqsub/3063-raspberryp
1410600062: gpio (QoS 0)
1410600062: mosqsub/3063-raspberryp 0 gpio
1410600062: Sending SUBACK to mosqsub/3063-raspberryp
1410600122: Received PINGREQ from mosqsub/3063-raspberryp
1410600122: Sending PINGRESP to mosqsub/3063-raspberryp
1410600152: New connection from 192.168.1.110 on port 1883.
1410600152: New client connected from 192.168.1.110 as mosqpub/9793-EasyARM (c1, k60).
1410600152: Sending CONNACK to mosqpub/9793-EasyARM (0)
1410600152: Received PUBLISH from mosqpub/9793-EasyARM (d0, q0, r0, m0, 'gpio', ... (22 bytes))
1410600152: Sending PUBLISH to mosqsub/3063-raspberryp (d0, q0, r0, m0, 'gpio', ... (22 bytes))
1410600152: Received DISCONNECT from mosqpub/9793-EasyARM
1410600182: Received PINGREQ from mosqsub/3063-raspberryp
1410600182: Sending PINGRESP to mosqsub/3063-raspberryp
3 Remote Control of GPIO Using MQTT
Next, we will use the python-gpio extension library to achieve remote control of GPIO ports through message pushing.
3.1 Install paho-mqtt
Use pip to install paho-mqtt by entering the following command:
sudo pip install paho-mqtt
3.2 Raspberry Pi Subscription Code simple.py
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
# BCM GPIO numbers
pins = [17,18,27,22,23,24,25,4]
def gpio_setup():
# Use BCM numbering
GPIO.setmode(GPIO.BCM)
# Set all GPIOs to output state and output low
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
def gpio_destroy():
for pin in pins:
GPIO.output(pin, GPIO.LOW)
GPIO.setup(pin, GPIO.IN)
# Connection success callback function
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# Subscribe to gpio topic after connection
client.subscribe("gpio")
# Message push callback function
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# Get pin and value from payload
gpio = json.loads(str(msg.payload))
if gpio['pin'] in pins:
if gpio['value'] == 0:
GPIO.output(gpio['pin'], GPIO.LOW)
else:
GPIO.output(gpio['pin'], GPIO.HIGH)
if __name__ == '__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
gpio_setup()
try:
# Change the IP address of the MQTT broker as necessary
client.connect("192.168.1.110", 1883, 60)
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
gpio_destroy()
3.3 Start Service and Publish Messages
Start the MQTT broker service on the PC
mosquitto -v
Run the script on the Raspberry Pi
sudo python simple.py
Publish messages on the PC
# Turn on GPIO17
mosquitto_pub -h 192.168.1.110 -t gpio -m "{\"pin\":17,\"value\":1}"
# Turn off GPIO17
mosquitto_pub -h 192.168.1.110 -t gpio -m "{\"pin\":17,\"value\":0}"
Running Result The Raspberry Pi GPIO17 lights up or turns off according to the messages pushed by the PC.
4 Conclusion
This article explains how to use the MQTT client on Raspberry Pi to achieve remote control of GPIO through paho-mqtt. This example runs in a local area network and demonstrates the advantages of the MQTT protocol in remote control. More time will be spent in the future practicing and analyzing the MQTT protocol.
Source:
blog.csdn.net/xukai871105/article/details/39255089