原创
【昉·星光 2 高性能RISC-V单板计算机体验】五、物联网应用————使用MQTT协议远程驱动舵机
一、按照发布的第一篇博客在VisionFive开发板上安装Mosquitto服务二、安装paho-mqtt库
1. paho-mqtt 是一个 Python 库,用于实现 MQTT协议的客户端。MQTT 是一种轻量级的、基于发布/订阅模式的通信协议,通常用于物联网(IoT)设备之间的通信。paho-mqtt 库为 Python 提供了连接到 MQTT 代理、发布消息和订阅主题的功能。
2. 安装命令
`pip install paho-mqtt`
3. paho-mqtt的关键方法
- connect(host, port=1883, keepalive=60, bind_address=""): 连接到 MQTT 代理。
- publish(topic, payload=None, qos=0, retain=False): 发布消息到指定主题。
- subscribe(topic, qos=0): 订阅指定主题。
- loop(), loop_start(), loop_stop(), loop_forever(): 处理与 MQTT 代理的通信,保持连接和处理消息。
- 三、编写业务代码
- ```
- import paho.mqtt.client as mqtt
import time
import numpy as np
import VisionFive.gpio as GPIO
def on_message(client, userdata, message):
try:
#print("Received message: " + str(message.payload.decode("utf-8")))
if str(message.payload.decode("utf-8")) == "high_speed":
print("high speed")
p.ChangeDutyRatio(1.5)
time.sleep(5)
elif str(message.payload.decode("utf-8")) == "low_speed":
print("low speed")
p.ChangeDutyRatio(7)
time.sleep(5)
except UnicodeDecodeError:
print("Received a non-UTF-8 message")
client = mqtt.Client()
client.on_message = on_message
client.connect("192.168.137.18", 1883)
client.subscribe("test")
led_pin = 22
def initPin():
# Set the gpio mode as 'BOARD'.
GPIO.setmode(GPIO.BOARD)
# Configure the direction of led_pin as out.
GPIO.setup(led_pin, GPIO.OUT)
# Configure the voltage level of led_pin as high.
GPIO.output(led_pin, GPIO.HIGH)
global p
p = GPIO.PWM(led_pin, 53)
p.start(0)
if __name__ == "__main__":
initPin()
while True:
try:
client.on_message = on_message
#print("start")
print(client.on_message)
client.loop()
except KeyboardInterrupt:
break
- ```
- 四、在Windows PC端使用MQTT.fx向部署在开发板上的服务器发送消息
开发接收到消息后,解析报文中的payload,并按照接收到的消息进行动作
开发工匠 2024-1-9 10:48