当我尝试测试连接到我的代理并发布它时,它会保持连接,但随后无法保持连接并发布测试。有人发现我的代码有问题吗?
import paho.mqtt.client as mqtt
import time
broker = "*************"
port = ****
def on_log(client, userdata, level, buf):
print(buf)
def on_connect(client,usedata,flags,rc):
if rc == 0:
client.connected_flag=True ##set flag
print("client is connected")
global connected
else:
print("connection failed")
client.loop_stop()
def on_disconnect(client, userdata, rc):
print("client disconnected ok")
def on_publish(client, userdata, mid):
print("In on_pub callback mid= ", mid)
mqtt.Client.connected_flag=False #create flag in class
client = mqtt.Client("MyClient-01") #create new instance
client.on_log=on_log
client.on_connect=on_connect
client.on_disconnect=on_disconnect
client.on_publish=on_publish
client.connect(broker,port) #establish connection
client.loop_start()
while not client.connected_flag:
print("in wait loop")
time.sleep(1)
time.sleep(3)
print("publishing")
#client.loop()
ret=client.publish("house/bulb1","Test message 0",0)
time.sleep(3)
#client.loop()
ret=client.publish("house/bulb1","Test message 1",1)
time.sleep(3)
#client.loop()
ret=client.publish("house/bulb1","Test message 2",2)
time.sleep(3)
client.loop_stop()
client.disconnect()
我得到了这个日志:
Sending CONNECT (u0, p0, wr0, wq0, wf0, c1, k60) client_id=b'MyClient-01'
in wait loop
Received CONNACK (0, 5)
connection failed
client disconnected ok
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop
in wait loop
它只是停留在循环中尝试连接,找到具有 IP 的代理,端口应该是正确的。
MQTT 规范可能是我有幸阅读过的最清晰的文档之一,可能是因为它非常简单。 对于版本 3.1.1 和 CONNACK 消息,您可以在这里找到它:
http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033
您配置了库来记录并打印了此消息:
Received CONNACK (0, 5)
CONNACK 是您的消息类型(对 CONNECT 消息的响应)。 0 和 5 指的是 CONNACK 变量头中的 Conneck 确认标志和连接返回代码变量。 0 表示这是新会话的开始,5 表示您未获得授权,如您所知。
修复了添加用户名和密码参数并添加
client.username_pw_set(user,password=password)
我遇到了同样的问题,花了几个小时试图解决它。然后我在github上看到这是由于缺少权限造成的。生成的错误代码令人困惑,但如果您检查日志,您会发现缺少某些权限。
https://github.com/aws/aws-iot-device-sdk-python-v2/discussions/329