首页 > 解决方案 > 无限地保持(python)paho MQTT连接

问题描述

目前,我正在使用以下函数发布到 MQTT 代理:

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

def publish_to_broker(data):
    publish.multiple(data, hostname=example_host, port=8883, client_id="example_id", keepalive=60,
                     will=None, auth={'username': "example_user", 'password': "example_password"},
                     tls={'ca_certs': certifi.where(), 'tls_version': ssl.PROTOCOL_TLSv1_2}, 
                     protocol=mqtt.MQTTv311, transport="tcp")

由于这是为每个帖子建立一个新连接,因此我需要更改它以使连接保持活动状态,并在连接丢失时重新连接。

遗憾的是,我发现文档非常无用,例如该tls=部分仅与上述方法一起使用,其中 mqtt 连接在发布后立即关闭。但是,我想这样做更像:

mqtt_client = mqtt.Client(client_id="example_id", protocol=mqtt.MQTTv311, transport="tcp")

mqtt_client.connect(host=example_host, port=8883, auth={'username': "example_user", 'password': "example_password"},  tls={'ca_certs': certifi.where(), 'tls_version': ssl.PROTOCOL_TLSv1_2})


def publish_to_broker_smart(data):
    mqtt_client.publish(data)

但是,我收到错误消息:TypeError: connect() got an unexpected keyword argument 'auth'

这些规范在哪里适合?

标签: pythonmqttpaho

解决方案


tls 和 auth 必须以不同方式指定。这是要走的路:

mqtt_client = mqtt.Client(client_id=example_client, protocol=mqtt.MQTTv311, transport="tcp")
mqtt_client.username_pw_set(username, password)
mqtt_client.tls_set(ca_certs=certifi.where(), tls_version=ssl.PROTOCOL_TLSv1_2)
mqtt_client.connect(host=example_host, port=8883)

def smart_post(data):
    mqtt_client.publish(topic=example_topic, payload=data, )

推荐阅读