Python paho-mqtt 模块学习笔记

安装方法:
二选一

pip3 install paho-mqtt
git clone https://github.com/eclipse/paho.mqtt.python
cd paho.mqtt.python
python3 setup.py install

连接及订阅方法,结合官方例程自己总结的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt

import logging


# If you want to use a specific client id, use
# mqttc = mqtt.Client("client-id")
# but note that the client id must be unique on the broker. Leaving the client
# id parameter empty will generate a random id for you.

# 连接的回调函数
def on_connect(mqttc, obj, flags, rc):
    print(f"Connected with result code {rc}")
    #client.subscribe("$SYS/#")
    
# 收到消息的回调函数
def on_message(mqttc, obj, msg):
    print(msg.topic+" "+str(msg.payload))
debug = False
host = "mqtt.eclipse.org"
client_id = "yk003"
keepalive = 60
port = 1883
password = "123456"
topic = "mqttqc"
username = "yk003"
verbose = False
logging.basicConfig(level=logging.DEBUG)
mqttc = mqtt.Client(client_id)
mqttc.username_pw_set(username, password)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
#mqttc.on_publish = on_publish
#mqttc.on_subscribe = on_subscribe
mqttc.enable_logger(logger)
mqttc.connect("127.0.0.1", 1883, 60)
mqttc.subscribe("mqttqc", 0)
mqttc.loop_forever()

测试结果(期间用其他客户端向mqttqc主题发送字符11144)

[root@localhost lqj]# python mqtt.py
DEBUG:__main__:Sending CONNECT (u1, p1, wr0, wq0, wf0, c1, k60) client_id=b'yk003'
DEBUG:__main__:Sending SUBSCRIBE (d0, m1) [(b'mqttqc', 0)]
DEBUG:__main__:Received CONNACK (0, 0)
Connected with result code 0
DEBUG:__main__:Received SUBACK
DEBUG:__main__:Received PUBLISH (d0, q0, r0, m0), 'mqttqc', ...  (5 bytes)
mqttqc b'lll44'
DEBUG:__main__:Sending PINGREQ
DEBUG:__main__:Received PINGRESP
DEBUG:__main__:Sending PINGREQ
DEBUG:__main__:Received PINGRESP
DEBUG:__main__:Sending PINGREQ
DEBUG:__main__:Received PINGRESP
DEBUG:__main__:Received PUBLISH (d0, q0, r0, m0), 'mqttqc', ...  (9 bytes)

猜你喜欢

转载自blog.csdn.net/taogunet/article/details/111561334
今日推荐