本文主要是介绍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 mqttimport 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)
这篇关于Python paho-mqtt 模块学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!