Paho-MQTT错误结果代码:5

Kal*_*ali 3 python mqtt

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

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

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

错误结果码: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")
Run Code Online (Sandbox Code Playgroud)

我必须添加添加代理用户和psw吗?我怎样才能做到这一点?

har*_*llb 5

您需要在调用之前将用户名和密码传递给客户端对象 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)
...
Run Code Online (Sandbox Code Playgroud)