Python emqx 消费者

# python emqx 消息消费者
import paho.mqtt.client as mqtt
# MQTT Broker 地址和端口
broker_address = "xxx.xxxxx.com"
port = 1883

# 订阅的主题
topic = "home/temperature"
#topic = "home/test"
import time

# 回调函数,处理接收到的消息
def on_message(client, userdata, message):
    # 需要规范接收消息,并转换为需要的消息存入iotdb
    print("Received message:", str(message.payload.decode("utf-8")))

# 创建 MQTT 客户端
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, "test_subscriber")

# 设置消息接收的回调函数
client.on_message = on_message

# 连接到 MQTT Broker
client.username_pw_set(username="test", password="Test123")
client.connect(broker_address, port)

# 订阅主题
client.subscribe(topic)

# 循环等待消息
client.loop_forever()

def consumer(broker_address, port, topic):
    # 创建 MQTT 客户端
    client = mqtt.Client("test_subscriber")
    # 设置消息接收的回调函数
    client.on_message = on_message
    # 连接到 MQTT Broker
    client.connect(broker_address, port)
    # 订阅主题
    client.subscribe(topic)
    # 循环等待消息
    client.loop_forever()