首页 > 解决方案 > mqtt 用户名或密码错误

问题描述

我用python写了关于在VS上运行的网关的代码。现在的问题是我已经配置了mqtt的用户名和密码以及服务器的IP和端口,但是返回值是rc=4 (bad username or password) ,我用wireshark抓包,我发送的CONNECT包是正确的,但返回值显示错误的用户名或密码

def __doPost(self):
    self.__connectMqtt(host = host, port = port, mqttUsername = id, mqttPassword = token)

def __connectMqtt(self,host,port,mqttUsername,mqttPassword):
    # Username = mqttUsername.encode("utf-8")
    self.mqttc.username_pw_set(username=mqttUsername, password=mqttPassword)
    # self.mqttc.subscribe(self.setTopic,1)
    self.mqttc.on_connect=self.__on_connect
    self.mqttc.on_message=self.__on_message
    self.mqttc.on_publish=self.__on_publish
    self.mqttc.on_disconnect=self.__on_disconnect
    # self.mqttc.tls_set(ca_certs = r"C:\Users\chris\Desktop\MobiusPi-Project-Templates-1.0.5\helloworld-template\src\root.crt")
    self.mqttc.connect(host, port, keepalive=200)
    # self.publish(message = "SUPCON Test")
    self.mqttc.publish_to_mqtt = self.publish_to_mqtt()
    # self.mqttc.subscribe_gateway = self.subscribe_gateway()
    self.mqttc.loop_forever()

def __on_connect(self,client, userdata, flags, rc):
    """
        The value of rc indicates success or not:
        0: Connection successful
        1: Connection refused - incorrect protocol version
        2: Connection refused - invalid client identifier
        3: Connection refused - server unavailable
        4: Connection refused - bad username or password
        5: Connection refused - not authorised
        6-255: Currently unused.
    """
    if   rc==0:
        print("Connect successful")
    elif rc==1:
        print("incorrect protocol version")
    elif rc==2:
        print("invalid client identifier")
    elif rc==3:
        print("server unavailable")
    elif rc==4:
        print("bad username or password")
        # print (client,flags)
    elif rc==5:
        print("not authorised")
    elif 6<rc<255:
        print("Currently unused")
    else:
        print("Connect failed")

def __on_message(self,client, userdata, message):
    message=message.payload.decode('utf8')
    print('receive message:%s'%(message)) 

def __on_publish(self,client, userdata, mid):
    print('publish message success mid:%s'%(mid))
    
def __on_disconnect(self,client,userdata,rc):
    if rc==0:
        print('disconnect success')
    else:
        print('disconnect fail')

标签: pythonmqtt

解决方案


哦,我已经解决了这个问题。因为每个网关都有clientID,我需要连接的服务器需要指定客户端ID,并且无法连接任何东西。我需要定义要连接的 clientID。

如果您的网关没有连接服务器,并且返回错误是用户名或密码错误,则可能是 clientID 错误。


推荐阅读