如何在调度的后台线程中传输MQTT消息?

2024-05-23 13:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我成功运行了基于MQTT的应用程序

随着时间的推移,我已经迁移了w.r.t.软件组件版本,并将MQTT消息传输移到了APScheduler后台线程中。客户端实例通过依赖项注入传递给作业调度

现在我使用的是mosquitto eclipse mqtt代理docker imageeclipse-mosquitto:1.6.10和Python paho客户端paho-mqtt = "1.5.0"

现在,如果我尝试与一个客户机连接到代理,连接就会断开,我会得到错误Connection Refused: unacceptable protocol version.,它会被抛出in the v1.5 client source code

客户端的连接方式如下:

def on_disconnect(client, userdata, rc):  # pylint: disable=invalid-name,unused-argument
    print(mqtt.connack_string(rc))

client = mqtt.Client(
    client_id="mvp-end-device-agent",
    clean_session=False,
    protocol=mqtt.MQTTv311,
)
client.on_disconnect = on_disconnect
user = "mvp-end-device-agent"
pwd = "some-string"
client.username_pw_set(user, pwd)
client.connect(host, port)  # implicit timeout of 60 seconds

    def on_disconnect(client, userdata, rc):  # pylint: disable=invalid-name,unused-argument

mosquitto/config/acl仍应匹配:

user mvp-end-device-agent
topic write ...

以及mosquitto/config/passwd配置:

mvp-end-device-agent:<HASHEDPWD>

以及mosquitto/config/mosquitto.conf配置:

password_file /mosquitto/config/passwd
acl_file /mosquitto/config/acls

最可能的相关日志条目(mqtt-explorer-31e2d891用于调试,mvp-end-device-agent是实际的客户端):

1603891749: New connection from 172.18.0.6 on port 1883.
1603891749: New client connected from 172.18.0.6 as mvp-end-device-agent (p2, c0, k1, u'mvp-end-device-agent').
1603891749: No will message specified.
1603891749: Sending CONNACK to mvp-end-device-agent (1, 0)
1603891750: Received PINGREQ from mqtt-explorer-31e2d891
1603891750: Sending PINGRESP to mqtt-explorer-31e2d891
1603891751: Received PINGREQ from mvp-end-device-agent
1603891751: Sending PINGRESP to mvp-end-device-agent
1603891752: Received PINGREQ from mvp-end-device-agent
1603891752: Sending PINGRESP to mvp-end-device-agent
1603891753: Received PINGREQ from mvp-end-device-agent
1603891753: Sending PINGRESP to mvp-end-device-agent
1603891754: Received PINGREQ from mvp-end-device-agent
1603891754: Sending PINGRESP to mvp-end-device-agent
1603891755: Received PINGREQ from mvp-end-device-agent
1603891755: Sending PINGRESP to mvp-end-device-agent
1603891755: Received DISCONNECT from mvp-end-device-agent
1603891755: Client mvp-end-device-agent disconnected.

我很难找出这个问题的根本原因。引发此错误的潜在原因是什么

编辑:我通过依赖项注入将mqtt客户端传递给APScheduler作业,以作为作业执行的一部分,定时传输mqtt消息。每个作业都在一个线程中执行。结果证明Connection Refused: unacceptable protocol version.的根本原因是线程执行后客户端被隐式断开,这完全有道理


Tags: tofromclient客户端ondevicemqttagent