精简mqtt-client(python)
Posted 晓翔仔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了精简mqtt-client(python)相关的知识,希望对你有一定的参考价值。
某次为了测试需要,用python写了个精简版mqtt-client。
这次测试的场景是mqtt-client连接broker,连接成功后批量订阅topics。
#-*- coding:utf-8 -*-
_author_ = 'cookie'
import paho.mqtt.client as mqtt #import the client1
import time
from paho.mqtt.client import MQTTv31,MQTTv311,MQTTv5
tempRC=-1
def on_connect(client, userdata, flags, rc):
global tempRC
print("rc of on_connect is ")
print(rc)
tempRC =int(rc)
# client.loop_start() # start the loop
print("enter on_connect")
print("begin to subscribe")
time.sleep(0)
subscribe_topic_array = [("VEHICLE_0*", 0), ("VEHICLE_1*", 0), ("VEHICLE_2*", 0)]
rc_sub = client.subscribe(subscribe_topic_array) # 订阅多个主题
print("rc_sub is ",rc_sub)
print("end to subscribe")
client.loop_stop() # stop the loop
print("the Return Code value is : ")
print(tempRC)
def on_subscribe(client,userdata,mid,granted_qos):
print("enter onsubscribe")
subscribe_topic_array = [("VEHICLE_0*", 2), ("VEHICLE_1*", 2), ("VEHICLE_2*", 2)]
rc_sub = client.subscribe(subscribe_topic_array) # 订阅多个主题
print("rc_sub is ", rc_sub)
print("end to subscribe")
client.loop_stop() # stop the loop
def on_message(client, userdata, message):
print("message topic=", message.topic)
print("message received ", message.payload)
broker_address = "192.168.0.1"
print("creating new instance")
print("connecting to broker ", broker_address)
client = mqtt.Client(client_id="client_id", protocol=MQTTv311, clean_session=True)
client.on_connect = on_subscribe
client.on_message = on_message
client.username_pw_set(username="name", password="abcdefg=")
client.max_inflight_messages_set(inflight=10)
try:
print("begin to connect broker")
rc = client.connect(broker_address, port=1883, keepalive=250)
client.loop_start()
print("rc of connect broker is ", rc)
time.sleep(60)
except Exception as e:
print(e.args)
测试日志打印如下
D:\\Users\\PycharmProjects\\mqtt_test\\venv\\Scripts\\python.exe D:/Users/PycharmProjects/mqtt_test/main.py
creating new instance
connecting to broker 192.168.0.1
begin to connect broker
rc of connect broker is 0
enter onsubscribe
rc_sub is (0, 1)
end to subscribe
Process finished with exit code 0
以上是关于精简mqtt-client(python)的主要内容,如果未能解决你的问题,请参考以下文章
PYTHON代码:根据FileRecord和MAP的关系,拼接IBM V7000 精简卷碎片
Python绘图精简实例附代码!看完此篇学不会?我手把手教你!