# 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
最新推荐文章于 2025-06-08 02:52:26 发布