wialon / gmqtt

Python MQTT v5.0 async client
MIT License
396 stars 52 forks source link

Exceeded reconnect_retries seems seems not to be working #130

Open presedo93 opened 3 years ago

presedo93 commented 3 years ago

I was looking for a way of checking if the reconnect_tries was exceeded and found this issue: https://github.com/wialon/gmqtt/issues/72 that was asking the same. It has a PR associated: https://github.com/wialon/gmqtt/pull/76

The thing is I've tried the solution proposed with gmqtt==0.6.9 and on_disconnect is only called when the first disconnection happens...

def on_disconnect(self, client: gmqtt.Client, packet: bytes, exc: None = None):
    if client.failed_connections > client.reconnect_retries:
    #    method that logs that the system couldn't reconnect...

Thanks!

nicoCalvo commented 2 years ago

If it helps, I solved with a small workaround:

 def  close_con(client):
        if client.is_connected:
            return
        loop = asyncio.get_running_loop()
        logger.info('STOPPING EVENT LOOP')
        loop.stop()
        pending = asyncio.Task.all_tasks()

        # Run loop until tasks done:
        logger.info('CANCELING REMAINING TASKS')
        loop.run_until_complete(asyncio.gather(*pending))

        logger.info("Shutdown complete ...")  

def _on_disconnect(self, client, packet):
        loop = asyncio.get_running_loop()
        # only call if max reconnect retries is defined
        if client.reconnect_retries > 0:
            grace_time = (client.reconnect_retries * client.reconnect_delay) + 1
            loop.call_later(grace_time, close_con, client)

If the reconnect happens during the scheduled shutdown function, the tasks are not cancelled. If another disconnect event occurs after having reconnected, the funcion is re-scheduled. Hope it helps