我有一个mqtt beoker,我正在尝试用python连接和订阅。 代码
client = mqtt.Client("P1",clean_session=True) #create new instance
client.on_connect = on_connect
client.on_message = on_message #attach function to callback
client.on_disconnect = on_disconnect
print("connecting to broker")
client.connect(broker_address, port=port) #connect to broker
print("Subscribing to topic","topic")
client.subscribe("topic")
client.loop_forever()
回叫功能
def on_connect(client, userdata, flags, rc):
if rc==0:
print("connected OK Returned code=",rc)
print(client)
else:
print("Bad connection Returned code=",rc)
def on_disconnect(client, userdata, rc):
print("Client Got Disconnected")
if rc != 0:
print('Unexpected MQTT disconnection. Will auto-reconnect')
else:
print('rc value:' + str(rc))
try:
print("Trying to Reconnect")
client.connect(broker_address, port)
client.subscribe("topic")
print('tried to subscribe')
except:
print("Error in Retrying to Connect with Broker")
def on_message(client, userdata, message):
print("message received ")
所以问题出在,客户端连接到代理,接收消息一段时间,然后断开连接。客户端断开连接后,我已添加了重新连接。现在它已连接,但客户端未收到任何消息。输出
connecting to broker
Subscribing to topic unilever
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
message received
.
.
.
.
收到一则消息并断开连接。输出
Client Got Disconnected
Unexpected MQTT disconnection. Will auto-reconnect
Trying to Reconnect
tried to subscribe
connected OK Returned code= 0
<paho.mqtt.client.Client object at 0x7f454660dcf8>
有人可以帮我解决为什么发生这种情况吗?
谢谢
答案 0 :(得分:2)
这是因为默认情况下,重新连接时会获得一个全新的会话(因为您有clean_session=True
),因此您没有活动的订阅。
将对client.subscribe('topic')
的调用移到on_connect
回调内部,然后在重新连接时重新订阅。