python - 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')
解决方案
哦,我已经解决了这个问题。因为每个网关都有clientID,我需要连接的服务器需要指定客户端ID,并且无法连接任何东西。我需要定义要连接的 clientID。
如果您的网关没有连接服务器,并且返回错误是用户名或密码错误,则可能是 clientID 错误。
推荐阅读
- ruby-on-rails - 如何检查method_defined?来自在类中使用的模块,其中包含模块后定义的方法
- php - 通过 laravel 路由的每个参数传递 ajax 变量
- graphql - 通过 GraphQL 应用从 REST api 调用返回的 cookie
- python - gspread 保护表,某些单元格除外
- node.js - Mongoose - MongoDB 问题 - VersionError: No matching document found for id "60bf5b73de309f1a30fe88a2" version 10 modifiedPaths "likes"
- flutter - 从项目推断相对路径的正确方法
- java - 强制 @Autowired 弹簧靴和 webFlux
- gcc - 内核头文件 printk.h 的编译错误
- mysql - 需要帮助来完善回答以下问题的 MySQL 查询
- docker - docker-compose:通过 nginx 的代理从另一个容器访问容器