zl程序教程

您现在的位置是:首页 >  后端

当前栏目

7. 使用Python开发MQTT客户端

Python客户端开发 MQTT 使用
2023-09-11 14:20:02 时间

构建python客户端

import paho.mqtt.client as mqtt

class MqttClient:
       
    def __init__(self, host, port,mqttClient):
        self._host = host
        self._port = port
        self._mqttClient = mqttClient

    # 连接MQTT服务器
    def on_mqtt_connect(self, username="tester", password="tester"):
        self._mqttClient.username_pw_set(username, password)
        self._mqttClient.connect(self._host, self._port, 60)
        self._mqttClient.loop_start()
     
    # publish 消息
    def on_publish(self, topic, msg, qos):
        self._mqttClient.publish(topic, msg, qos)
     
    # 消息处理函数
    def on_message_come(client, userdata, msg):
        print(msg.topic + " " + ":" + str(msg.data))
     
    # subscribe 消息
    def on_subscribe(self, topic):
        self._mqttClient.subscribe(topic, 1)
        self._mqttClient.on_message = self.on_message_come # 消息到来处理函数
'''     
    def main():
        self.on_mqtt_connect()
        on_publish("/test/server", "Hello Python!", 1)
        self.on_subscribe()
        print("connect success!\n")
        while True:
            pass
'''
 
if __name__ == '__main__':
#    main()
    host = "123.57.8.28"
    port = 1883
    topic = "CarTest"
#    msg = "Hello Python!"
    qos = 1
    username = "tester"
    password = "tester"
    mqttClient = mqtt.Client("tester")
    
    client = MqttClient(host, port, mqttClient)
    client.on_mqtt_connect(username, password)
#    client.on_publish(topic, msg, qos)
    client.on_subscribe(topic)
    
''' 
    # 多客户端连接
    mqttClient_2 = mqtt.Client("tester-2")
    username_2 = username + '2'
    password_2 = password + '2'
    client_2 = MqttClient(host, port, mqttClient_2) 
    client_2.on_mqtt_connect(username_2, password_2)
    client_2.on_subscribe(topic)
'''    
    print("connect success!\n")
    while True:
        pass
    

连接测试

在这里插入图片描述
连接成功

参考文档:
使用python实现mqtt的发布和订阅

python mqtt 客户端的实现代码实例

python实现两个mqtt client分别连接两个server

python mqtt客户端

Python简单试用MQTT服务器