安装
# pip install paho-mqtt
快速上手
在主题house/main-light发布信息OFF,关闭主控灯。
import paho.mqtt.client as mqtt
broker_address="localhost"
client = mqtt.Client("P1")
client.connect(broker_address)
client.publish("house/main-light","OFF")
订阅主题
import paho.mqtt.client as mqtt
broker_address="localhost"
client = mqtt.Client("P1")
client.connect(broker_address)
client.subscribe("house/bulbs/bulb1")
client.publish("house/bulbs/bulb1","OFF")
虽然订阅了主题,但是不使用回调是看不到发布的消息的。
回调
执行结果
$ python mqtt_demo3.py
message received OFF
message topic= sensors/drone01/altitude
message qos= 0
message retain flag= 0
$ python mqtt_demo4.py
log: Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'P1'
log: Sending SUBSCRIBE (d0, m1) [(b'sensors/drone01/altitude', 0)]
log: Received CONNACK (0, 0)
log: Sending PUBLISH (d0, q0, r0, m2), 'b'sensors/drone01/altitude'', ... (3 bytes)
log: Received SUBACK
log: Received PUBLISH (d0, q0, r0, m0), 'sensors/drone01/altitude', ... (3 bytes)
message received OFF
message topic= sensors/drone01/altitude
message qos= 0
message retain flag= 0