一、安装paho-mqtt
1、通过命令安装
pip install paho-mqtt
二、实现MQTT发布和订阅
1、发布消息
from paho.mqtt import client as mqtt
mqttClient = mqtt.Client()
def mqtt_connect():
MQTTHOST = "192.168.1.150"
MQTTPORT = 1883
mqttClient.connect(MQTTHOST, MQTTPORT, 60)
mqttClient.loop_start()
def mqtt_publish():
'''发布一个主题为'mqtt/demo',内容为'Demo text'的信息,服务质量为 2的消息'''
mqtt_connect()
text = "Demo text"
mqttClient.publish('mqtt/demo', text, 2)
if __name__ == '__main__':
mqtt_publish()
2、订阅消息
from paho.mqtt import client as mqtt
mqttClient = mqtt.Client()
def mqtt_connect():
MQTTHOST = "192.168.1.150"
MQTTPORT = 1883
mqttClient.connect(MQTTHOST, MQTTPORT, 60)
mqttClient.loop_start()
def on_message_come(lient, userdata, msg):
print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))
def on_subscribe():
mqttClient.subscribe("mqtt/demo", 2)
mqttClient.on_message = on_message_come
def run():
mqtt_connect()
on_subscribe()
while True:
pass
if __name__ == '__main__':
run()
|