Python实现MQTT订阅、发布

1、安装python Mqtt库

pip install paho-mqtt

2、封装后的Mqtt类(拷贝即用)

import configparser
import paho.mqtt.client as mqtt


class MqttService:
    """
    on_connect_func:连接MQTT回调函数,订阅主题时触发
    """
    def __init__(self,on_connect_func=None):
        self.config = configparser.ConfigParser()
        self.host = None
        self.port = 1883
        self.keepalive = 60
        self.name = None
        self.pwd = None
        self.mqtt_info = None
        self.InitMqtt(on_connect_func)
    """
    初始化MQTT配置信息
    """
    def InitMqtt(self,on_connect_func=None):
        self.config.read("mqttConfig.ini", encoding="gbk")
        self.host = self.config.get("MqttInfo", "Host")
        self.port = self.config.get("MqttInfo", "Port")
        self.keepalive = self.config.get("MqttInfo", "Keepalive")
        self.name = self.config.get("MqttInfo", "Name")
        self.pwd = self.config.get("MqttInfo", "Pwd")
        self.mqtt_info = mqtt.Client(protocol=3)
        self.mqtt_info.on_connect = on_connect_func
        self.mqtt_info.username_pw_set(self.name, self.pwd)
        self.mqtt_info.connect(host=self.host, port=int(self.port), keepalive=int(self.keepalive))

    """
    发布消息
    topic:主题
    payload:发布的数据
    qos:模式
    """
    def MqttPublish(self, topic=None, payload=None, qos=1):
        if topic is None or payload is None:
            return None
        self.mqtt_info.publish(topic=topic, payload=payload, qos=qos)
    """
    订阅消息
    topic:主题
    qos:模式
    msg_func:接收数据回调
    on_subscribe_func:订阅回调
    """
    def MqttSubscribe(self, topic=None, qos=1,msg_func=None,on_subscribe_func=None):
        if topic is None:
            return None
        self.mqtt_info.subscribe(topic, qos)
        self.mqtt_info.on_message = msg_func
        self.mqtt_info.on_subscribe = on_subscribe_func
        self.mqtt_info.loop_forever()

3、测试

import json

from mqttService import MqttService
def mqttmessage(client, userdata, msg):
    print("订阅的数据:"+msg.payload.decode('utf-8'))
def mqttconnect(client, userdata, flags, rc):
    print("连接成功:"+str(rc))
def mqttsubscribe(client,userdata,mid,granted_qos):
    print("消息订阅成功")
if __name__ == '__main__':
    mqtt = MqttService(on_connect_func=mqttconnect)
    #mqtt.MqttPublish(topic="test",payload="这是python发送的一条测试数据",qos=1)
    # print(res)
    mqtt.MqttSubscribe(topic="test",qos=1,msg_func=mqttmessage,on_subscribe_func=mqttsubscribe)

4、测试截图

Python实现MQTT订阅、发布_第1张图片

 Python实现MQTT订阅、发布_第2张图片

 5、mqttConfig.ini内容

#mqtt信息
[MqttInfo]
Host = mqtt地址
Port = 1883
Keepalive = 60
Name = mqtt用户
Pwd = mqtt密码

你可能感兴趣的:(python)