在PC机MQTT服务器控制台中输出
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 使用MQTT远程控制GPIO
下面借助python-gpio扩展库,通过消息推送的方式实现GPIO端口的远程控制。
3.1 安装paho-mqtt
使用pip工具安装paho-mqtt,输入以下指令即可:
sudo pip install paho-mqtt
3.2 树莓派订阅代码——simple.py
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json
# BCM GPIO编号
pins = [17,18,27,22,23,24,25,4]
def gpio_setup():
# 采用BCM编号
GPIO.setmode(GPIO.BCM)
# 设置所有GPIO为输出状态,且输出低电平
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)
# 连接成功回调函数
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# 连接完成之后订阅gpio主题
client.subscribe("gpio")
# 消息推送回调函数
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# 获得负载中的pin 和 value
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:
# 请根据实际情况改变MQTT代理服务器的IP地址
client.connect("192.168.1.110", 1883, 60)
client.loop_forever()
except KeyboardInterrupt:
client.disconnect()
gpio_destroy()
3.3 启动服务并发布消息
【在PC机中启动MQTT代理服务】
mosquitto -v
【在树莓派中运行脚本】
sudo python simple.py
【在PC机中发布消息】
# 打开GPIO17
mosquitto_pub -h 192.168.1.110 -t gpio -m "{\"pin\":17,\"value\":1}"
# 关闭GPIO17
mosquitto_pub -h 192.168.1.110 -t gpio -m "{\"pin\":17,\"value\":0}"
【运行结果】
树莓派GPIO17根据PC机推送的消息点亮或熄灭。
4 总结
本文说明了如何在树莓派中使用MQTT客户端,通过paho-mqtt实现GPIO的远程控制。本例在局域网中运行并能不能体现出MQTT协议在远程控制中的优越性。后期还将花更多的时间实践和分析MQTT协议。