5-python库之-paho mqtt通讯

mqtt可以说是显示物联网上面应用十分广泛的协议了,其轻量、简单、开放和易于实现等这些特点。paho也实现了python版的mqtt。

1.连接

连接调用connect接口,然后调用loop_forever后就开始跑了

connect的第三个参数为mqtt的心跳时间

on_connecton_disconnect为连接成功和断开的回掉函数,

import paho.mqtt.client as mqtt

mqttClient = mqtt.Client("python_test")


def on_disconnect(client, userdata, rc):
    print("mqtt broker lost "+str(rc))


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))


if __name__ == '__main__':
    mqttClient.on_connect = on_connect
    mqttClient.on_disconnect = on_disconnect
    mqttClient.connect("192.168.18.1", 1883, 10)
    mqttClient.loop_forever()
    

2.SSL登录

添加证书,只需要在调用connect函数之前,添加下面两条内容即可。

mqttClient.tls_set(ca_certs="cacert.pem", certfile=None, keyfile=None, cert_reqs=mqtt.ssl.CERT_REQUIRED,
                       tls_version=mqtt.ssl.PROTOCOL_TLSv1, ciphers=None)
    mqttClient.tls_insecure_set(True)

3.账号密码

设置账号密码,在调用connect函数之前,添加下面一条内容即可。

mqttClient.username_pw_set("python", passwd)

4.WILL主题设置

设置WILL主题,在调用connect函数之前,使用will_set接口设置,添加will主题和will主题的payload

will_payload = {
    "ver":  "v1",
    "module": "offline",
    "api":  "disconnect",
    "param":  [{
        "k": "mac",
        "v": "DC4BDD1DFA48"
    }, {
        "k": "protypeid",
        "v": "PYTHON"
    }]
}
    
mqttClient.will_set("local/offline", payload=json.dumps(will_payload), qos=CLINET_TOPIC_QOS)

5.订阅

主题的订阅使用subscribe接口,一般在on_connect回调函数里面设置

订阅完主题,我们的目的就是要收到订阅的数据,所以需要设置接收数据的回调函数on_message
,只要有数据发送过来on_message就会收到。

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author: ye.lin
# Time: 2020/02/24
# Describe:

import paho.mqtt.client as mqtt

mqttClient = mqtt.Client("python_test")

def on_disconnect(client, userdata, rc):
    print("mqtt broker lost "+str(rc))


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    mqttClient.subscribe(local/broadcast, qos=1)


def on_message_come(lient, userdata, msg):
    print(msg.topic + " " + ":" + str(msg.payload))


if __name__ == '__main__':
    mqttClient.on_connect = on_connect
    mqttClient.on_disconnect = on_disconnect
    mqttClient.on_message = on_message_come

    mqttClient.tls_set(ca_certs="zgateway_cacert.pem", certfile=None, keyfile=None, cert_reqs=mqtt.ssl.CERT_REQUIRED,
                       tls_version=mqtt.ssl.PROTOCOL_TLSv1, ciphers=None)
    mqttClient.tls_insecure_set(True)

    mqttClient.connect("192.168.18.1", 6885, 10)
    mqttClient.loop_forever()

6.发布

发布使用publish接口,如下

    info_payload = {
        "msg":      "test"
    }
    mqttClient.publish("local/notify", payload=json.dumps(info_payload), qos=CLINET_TOPIC_QOS)

上一篇:java-断开HttpClient的连接


下一篇:具有丢失/断开连接的事务上的MySQL回滚