为了测试需要,用python写了个精简版mqtt-client。
这次测试的场景是:
mqtt-client连接broker,连接成功后批量订阅topics,订阅后立即publish特定topic的消息。接受到订阅消息则打印出来。
# -*- coding:utf-8 -*-
_author_ = 'cookie'
import paho.mqtt.client as mqtt
import time
from paho.mqtt.client import MQTTv31, MQTTv311, MQTTv5
#maybe u need global valuable
#global global_tmp
def on_connect(client2, userdata, flags, rc):
global runtime
print("the Return Code value of on_connect is : " + str(rc))
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
subscribe_topic_array = [("VEHICLE_TOPIC1", 0), ("VEHICLE_TOPIC2", 0)]
rc_sub = client.subscribe(subscribe_topic_array)
print("rc_sub is ", rc_sub)
print("end to subscribe")
time.sleep(1)
#subscribe 成功后需要立即 publish topic 7 qos是2
file = open("topic7.json", 'r+')
topic7Data = file.read()
print("len of topic7Data is", len(topic7Data))
file.close()
publishResult7 = client.publish(topic="VEHICLE_TOPIC7_REQ", payload=topic7Data, qos=2)
print("call publish 7 method return value " + str(publishResult7))
time.sleep(1)
def on_subscribe(client, userdata, mid, granted_qos):
pass
# print("Subscribed: " + str(mid))
def on_log(client, userdat, level, logMessage):
print(logMessage)
def on_message(client, userdata, message):
#收到broker发来的订阅消息,打印出来
print(time.strftime("message arrived time is %Y-%m-%d %H:%M:%S", time.localtime()))
print("message topic: ", str(message.topic))
print("message received: ", message.payload)
def on_publish(client, userdata, mid):
print("Published mid value is : " + str(mid))
broker_address = "192.168.2.2"
print("creating new instance")
# If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new one
# The mid value is the message id and can be used with the mid value returned from the publish method to check that a particular message has been published. protocol=MQTTv311,clean_session=True)
client = mqtt.Client(client_id="CID_CLIENT", protocol=MQTTv311, clean_session=True)
client.enable_logger()
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_publish = on_publish
client.username_pw_set(username="name", password="passwd")
try:
client.connect(broker_address, port=1883, keepalive=20)
client.loop_start() # start the loop
time.sleep(600000) # wait
client.loop_stop() # stop the loop
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
the Return Code value of on_connect is : 0
2022-1-2 22:59:35
enter onsubscribe
rc_sub is (0, 1)
end to subscribe
len of topic7Data is 100
call publish 7 method return value (0, 2)
Published mid value is : 2
message received time is 2022-1-2 22:59:41
message topic: VEHICLE_TOPIC1
message received: b'{*********}'
Process finished with exit code 0