FIRST_RECONNECT_DELAY =1
RECONNECT_RATE =2
MAX_RECONNECT_COUNT =12
MAX_RECONNECT_DELAY =60
FLAG_EXIT =Falsedefon_disconnect(client, userdata, rc):
logging.info(f"disconnected with result code: {rc}")
reconnect_count, reconnect_delay =0, FIRST_RECONNECT_DELAY
while reconnect_count < MAX_RECONNECT_COUNT:
logging.info(f"reconnecting in {reconnect_count} seconds...")
time.sleep(reconnect_delay)try:
client.reconnect()
logging.info("reconnected successfully!")returnexcept Exception as err:
logging.error(f"{err}. reconnect failed, retrying...")
reconnect_delay *= RECONNECT_RATE
reconnect_delay =min(reconnect_delay, MAX_RECONNECT_DELAY)
reconnect_count +=1
logging.info(f"reconnect failed after {reconnect_count} attempts.Exiting...")global FLAG_EXIT
FLAG_EXIT =True
发布消息
defpublish(client):
msg_count =1whilenot FLAG_EXIT:
msg_dict ={'msg':msg_count}
msg = json.dumps(msg_dict)ifnot client.is_connected():
logging.error("publish:MQTT client is not connected!")
time.sleep(1)continue
result = client.publish(topic, msg)
status = result[0]if status ==0:print(f"send '{msg}' to topic '{topic}'")else:print(f"failed to send message to topic {topic}")
msg_count +=1if msg_count >5:break
time.sleep(1)
connected to MQTT Broker!
send '{"msg": 1}' to topic 'python/mqtt'
received '{"msg": 1}' from 'python/mqtt' topic
send '{"msg": 2}' to topic 'python/mqtt'
received '{"msg": 2}' from 'python/mqtt' topic
send '{"msg": 3}' to topic 'python/mqtt'
received '{"msg": 3}' from 'python/mqtt' topic
send '{"msg": 4}' to topic 'python/mqtt'
received '{"msg": 4}' from 'python/mqtt' topic
send '{"msg": 5}' to topic 'python/mqtt'