# python emqx 消息生产者
import time
import random
import uuid
import paho.mqtt.client as mqtt
# MQTT Broker地址和端口
broker_address = "xxx.xxxx.com" # 输入自己的mqtt安装的服务器
port = 1883 # 默认端口是1883
# 创建MQTT客户端
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, "test")
# 连接成功回调
def on_connect(client, userdata, flags, rc):
print('Connected with result code ' + str(rc))
client.subscribe('home/temperature')
# 消息接收回调
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
# 指定回调函数
client.on_connect = on_connect
# 监听到消息的处理函数
client.on_message = on_message
# 如果设置了用户名和密码这里需要配置,没有的话就注释掉就行
client.username_pw_set(username="test", password="Test123")
# 连接到MQTT Broker
client.connect(broker_address, port, 60)
# 发布和订阅循环
while True:
# 模拟温度数据
temperature = random.randint(20, 30)
# 发布温度数据到"home/temperature"主题
topic = "home/test"
client.publish("home/temperature", temperature)
print("Published temperature:", temperature)
# 发布间隔延迟
time.sleep(5)
# 处理网络通信和回调
client.loop()