python3 使用paho-mqtt

python版本:python3.8

mqtt库:paho-mqtt 1.6.1

 

一,消息发布

创建pub.py,写入以下代码

import time
from paho.mqtt import client as mqtt_client


# broker服务器,远程中间人的主机或IP
broker = 'localhost'
# 端口,默认端口是1883
port = 1883
# 主题(要和订阅端保持一致)
topic = 'topic1'
# 客户端id(随机字符串)
client_id = '001'

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print(f"Failed to connect, return code {rc}")

def conn_mqtt():
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        msg = f"msg of {msg_count}!"
        res = client.publish(topic=topic, payload=msg, qos=1)
        if res[0] == 0:
            print(f"send {msg} successful!")
        else:
            print("Fail to send msg!")
        msg_count += 1

if __name__ == "__main__":
    client = conn_mqtt()
    publish(client)

 

二,消息接收(消息订阅)

创建文件sub.py,写入以下代码

from paho.mqtt import client as mqtt_client


broker = 'localhost'
port = 1883
topic = 'topic1'
client_id = '002'


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print(f"Failed to connect, return code {rc}")

def conn_mqtt():
    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def on_message(client, userdata, msg):
    print(f"Received {msg.payload.decode()}!")

def subscribe(client):
    client.subscribe(topic=topic, qos=1)
    client.on_message = on_message
    client.loop_forever()

if __name__ == "__main__":
    client = conn_mqtt()
    subscribe(client)

 注意:qos参数值说明

qos=0,最多发送一次。

qos=1,最少发送一次

qos=2,只发送一次,并且一定能送到

 

三,启动

 

四,MQTT连接错误码

rc=0:连接成功

rc=1:协议版本不接受

rc=2:无效客户端标识符被拒绝

rc=3:服务不可用

rc=4:用户名或密码错误

rc=5:无权连接

posted @ 2022-08-21 17:11  xqs42b  阅读(600)  评论(0编辑  收藏  举报