34 lines
787 B
Python
34 lines
787 B
Python
|
|
import paho.mqtt.client as mqtt
|
||
|
|
|
||
|
|
# MQTT Broker 配置
|
||
|
|
BROKER = '175.27.168.120'
|
||
|
|
PORT = 6011
|
||
|
|
TOPIC = "thing/product/1581F8HGX254V00A0BUY/osd"
|
||
|
|
|
||
|
|
|
||
|
|
# 消息接收回调
|
||
|
|
def on_message(client, userdata, msg):
|
||
|
|
print(f"Received message: '{msg.payload.decode()}' from topic '{msg.topic}'")
|
||
|
|
|
||
|
|
|
||
|
|
# 连接成功回调
|
||
|
|
def on_connect(client, userdata, flags, rc):
|
||
|
|
if rc == 0:
|
||
|
|
print("Connected!")
|
||
|
|
client.subscribe(TOPIC, qos=1) # 订阅主题
|
||
|
|
else:
|
||
|
|
print(f"Connection failed with error code {rc}")
|
||
|
|
|
||
|
|
|
||
|
|
# 创建客户端
|
||
|
|
client = mqtt.Client()
|
||
|
|
client.username_pw_set("username", "my_password")
|
||
|
|
client.on_connect = on_connect
|
||
|
|
client.on_message = on_message
|
||
|
|
|
||
|
|
# 连接 Broker
|
||
|
|
client.connect(BROKER, PORT, 60)
|
||
|
|
|
||
|
|
# 持续监听消息
|
||
|
|
client.loop_forever() # 阻塞式循环
|