python - 无限地保持(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'
这些规范在哪里适合?
解决方案
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, )
推荐阅读
- java - 如何在 Recyclerview 中刷新项目位置以进行过滤?
- android - 现有应用程序中的 React Native 更新版本
- mongodb - 如何将“类型”信息复制到 mongo 聚合和查找中的“实例”中......并保留原始列表?
- python - 在 docker 中使用 django 运行 tika python
- python - Python/Numpy:如何使用重复实例重新编号现有数组?
- finite-automata - 不包含 101101 作为子字符串的字符串的 DFA
- testing - 使用 Jooq 进行集成测试
- amazon-web-services - AWS X-Ray Crossacount 数据收集
- angular - 使用 Angular 应用程序在 Azure DevOps 中构建发布管道 - 找不到包含 package.json 的工作文件夹
- java - 闹钟:重复 setAlarmClock()