gpt4 book ai didi

python - Paho-MQTT错误结果码: 5

转载 作者:太空宇宙 更新时间:2023-11-03 14:02:05 26 4
gpt4 key购买 nike

我设法在我的 RPi 中的 Paho-MQTT 客户端和我的 VPS 中的 MQTT 代理之间建立了连接。

现在我正在尝试保护 MQTT 连接,并且我已将用户和密码添加到代理。我更改了 mosquitto.conf 文件,添加了新的密码文件。

但是现在,当我尝试连接我的 Paho-MQTT 客户端时,出现此错误:

Error result code: 5

这是我的 paho-mqtt 客户端脚本:

#!/usr/bin/env python

import paho.mqtt.client as mqtt
import subprocess
import datetime
import time

# Broker data
broker = *My Broker IP
broker_port = 1883
timeout_reconnect = 60
broker_topic = "#" #All topics have to be read

# Topic to send payload
topic = "temp/DHT11data"

def on_connect(client, userdata, flags, rc):
#print("Connect with result code: " + str(rc))
if int(str(rc)) == 0:
print("Conexion establecida")
print ""
else:
print("Error result code: " + str(rc))
#client.subscribe(broker_topic)

def on_message(client, userdata, msg):
#print "Message topic: " + msg.topic + ", payload: " + str(msg.payload)
#if msg.topic == topic:
if msg.topic == "temp/test":
if str(msg.payload) != "":
print "Message on: " + str(datetime.datetime.now()) + " - topic: " + msg.topic + ", payload: " + str(msg.payload)
#client.publish(topic, 30, qos=0, retain=False)
client.publish(topic, "Reset...", qos=0, retain=False)
pass

def on_publish(mosq, obj, mid):
#print("Publish mid: " + str(mid))
pass

def on_subscribed(mosq, obj, mid, granted_qos):
print("Subscribed mid: " + str(mid) + ", qos: " + str(granted_qos))

def on_log(mosq, obj, mid, string):
#print("Log: " + str(string))
pass

client = mqtt.Client()

client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.on_subscribed = on_subscribed
client.on_log = on_log

client.connect(broker, broker_port, timeout_reconnect)
client.subscribe(broker_topic, 0)

print "Cliente conectado " + str(datetime.datetime.now())
print ""

client.loop_start()

while True:
try:
client.publish(topic, "Hello world", qos=0, retain=False)
time.sleep(10)

except KeyboardInterrupt:
break

client.disconnect()
print("Desconectado")

我必须添加才能添加代理用户和密码吗?我该怎么做?

最佳答案

在调用connect之前需要将用户名和密码传递给客户端对象

...
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.on_subscribed = on_subscribed
client.on_log = on_log

client.username_pw_set(“username”, “password”)
client.connect(broker, broker_port, timeout_reconnect)
...

关于python - Paho-MQTT错误结果码: 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48215437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com