# import paho.mqtt.client as mqtt
from paho.mqtt import client as mqtt
import base64
# 定义MQTT服务器地址和端口
MQTT_SERVER = "192.168.17.128"
MQTT_PORT = 1883
# 定义MQTT客户端ID
MQTT_CLIENT_ID = "my_mqtt_client"
# 定义MQTT主题
MQTT_TOPIC = "hello"
# 定义MQTT回调函数
def on_message(client, userdata, message):
# 订阅文字
# with open("received_txt.txt", "wb") as file:
# file.write(base64.b64decode(message.payload.decode('utf-8')))
# 订阅图片
# with open("received_image.jpg", "wb") as file:
# file.write(base64.b64decode(message.payload.decode('utf-8')))
# 订阅声音
with open("receiveerttd_voice.wav", "wb") as file:
file.write(base64.b64decode(message.payload.decode('utf-8')))
# 创建MQTT客户端
client = mqtt.Client(MQTT_CLIENT_ID)
# 绑定回调函数
client.on_message = on_message
# 连接MQTT服务器
client.connect(MQTT_SERVER, MQTT_PORT)
# 订阅MQTT主题
client.subscribe(MQTT_TOPIC)
# 发布MQTT消息
# client.publish(MQTT_TOPIC, "Hello, MQTT!")
# 开始循环接收MQTT消息
client.loop_forever()
python练习2
最新推荐文章于 2024-11-02 14:33:49 发布
本文介绍了如何使用Python的PahoMQTT库连接到MQTT服务器,定义客户端ID,订阅主题并处理接收到的文字、图片和声音数据。通过Base64解码接收的MQTT消息内容。
摘要由CSDN通过智能技术生成