
本文共 3426 字,大约阅读时间需要 11 分钟。
什么是MQTT协议?
MQTT,全称Message Queuing Telementry Protocol(消息队列传输协议),是一种轻量级的消息传递协议,广泛应用于物联网(IoT)和分布式系统中。它通过建立一个中间代理(Broker)实现设备间的消息 Publish(发布)和 Subscribe(订阅)功能。
如何在Raspberry Pi上设置MQTT Broker?
在Raspberry Pi上部署并运行Mosquitto MQTT代理,是本项目的重要组成部分。以下是详细的步骤指南:
更新系统包
首先,确保Raspberry Pi上的系统包是最新的:sudo apt-get update && sudo apt-get upgrade
安装Mosquitto及其客户端
通过命令行安装所需软件包:sudo apt-get install mosquitto mosquitto-clients
配置Mosquitto代理
打开Mosquitto配置文件:nano /etc/mosquitto/mosquitto.conf
添加以下内容到文件末尾:
allow_anonymous 0password_file /etc/mosquitto/pwfilelistener 1883
创建用户并设置密码
为Mosquitto代理创建用户并设置密码:sudo mosquitto_passwd -c /etc/mosquitto/pwfile username
替换 username
和密码,并确保存在密码文件中的路径。
启动Mosquitto代理
重新启动Raspberry Pi:sudo reboot
启动完成后,Mosquitto代理已在地址 http://raspberry-pi-ip:1883
提供服务。
测试Mosquitto代理
通过命令行验证Mosquitto代理是否正常工作:
发布消息
在一个终端窗口中:mosquitto_pub -d -u username -P password -t test -m "Hello, World!"
按回车后,消息将发送至主题 test
。
订阅主题
在另一个终端窗口中:mosquitto_sub -d -u username -P password -t test
这个命令会实时订阅主题 test
并显示接收到的消息。
如果设置了用户名和密码,需要在命令中使用 -u
和 -P
标志。
配置Anduino ESP8266
在本节中,我们将使用Adafruit HUZZAH ESP8266板进行编程。
安装Arduino环境
确保已安装Arduino IDE及其相关软件,如果尚未安装,按如下步骤操作:- 打开Arduino IDE,进入
File > Preferences
,添加以下URL到Additional Boards Manager URLs
:http://arduino.esp8266.com/stable/package_esp8266com_index.json
- 在
Tools > Boards > Board Manager
中,搜索ESP8266
并安装相应包。
选择合适的板和调试速度
在编程之前,确保选择了正确的板和CPU频率:- 主板选择:
Adafruit HUZZAH ESP8266
- CPU频率选择:
80 MHz
(建议使用) - Flash大小选择:
4M (3M SPIFFS)
- 上传速度选择:
115200
手动选择COM端口
在编程前,确保已正确设置USB到串口Bridge,将Raspberry Pi的序列号映射到正确的COM端口。进入Flash模式
按住GPIO0
和 复位
按钮,松开后立刻按下 GPIO0
按钮,为515秒(大约10秒)时间允许进入Flash模式。 编写并上传Arduino代码
按照以下步骤编写并加载Arduino代码:
导入必要的库
在Sketch > Include Libraries > Manage Libraries
中添加以下库: Adafruit NeoPixel
(用于控制RGB灯)PubSubClient
(用于MQTT通信)
编写代码
添加以下代码片段到loop()
函数中,修改常量以适应您的网络配置: #include#include #include // 修改以下常量以适应您的网络配置const charbroker = "Raspberry Pi IP";const charbrokerPort = "1883";const charusername = "Username";const charpassword = "Password";// 初始化 NeoPixel ledNeoPixel<7> pixel(PIN_d6, 0,PIXEL_BGR);void setup() { pinMode(PIN_d6, OUTPUT); // 初始化 NeoPixel led pixel.begin(); // 初始化WiFi WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // 连接到MQTT Broker client.begin(WifiClient);}void loop() { pixel.write(0x00ff00, 0x000000); // 点亮绿色灯 delay(1000); // 发布消息到主题 `test` client.publish("test", "Hello from ESP8266!"); delay(1000);}
上载代码
按下Arduino IDE中的Upload
按钮,或通过串口监控工具手动发布代码。 安装Python客户端
为Raspberry Pi或另一台计算机安装 paho-mqtt
客户端库:
pip install paho-mqtt
需要注意的是,如果您运行的是Windows系统,可能需要确保已将Python添加到系统路径或使用带有Python的pip安装。
用代码实现订阅功能
以下是Python脚本示例,用于订阅主题并接收消息:
import paho.mqtt as mqttimport time# 修改以下常量以适应您的配置broker = "Raspberry Pi IP"port = 1883username = "Username"password = "Password"client = mqtt.Client("Python_Client")def on_message_received(msg, obj): print(f"Received message: {msg}!")client.on_message = on_message_receivedclient.connect(broker, port, username, password)# 持续订阅主题try: client.subscribe("test", qos=1) while True: time.sleep(1)except KeyboardInterrupt: print("停止监听...") client.disconnect()client.connected=lambda: print("已连接到 MQTT Broker!")# 启动客户端if __name__ == "__main__": client.start_loop()
测试设备之间的通信
配置第二个设备(如Raspberry Pi)
为第二个设备添加相同的代码,并确保其连接到同一网络且向同一主题发送消息。运行测试
按下按钮或执行发送消息的代码,观察另一个设备是否接收到消息。通过以上步骤,您已经成功设置了一个简单的IoT系统,能够通过MQTT协议实现设备间的通信。
发表评论
最新留言
关于作者
