Python paho-mqtt 模块学习笔记

8 篇文章 2 订阅

安装方法:
二选一

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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值