Skip to content

Commit

Permalink
Merge pull request #57 from ZephireNZ/fix/mqtt-error
Browse files Browse the repository at this point in the history
Add exponential backoff to MQTT client to prevent loop breaking on API failure
  • Loading branch information
zlinoliver authored Feb 8, 2022
2 parents 2a3e473 + 601b35d commit 4c183a8
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions tuya_iot/openmq.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from Crypto.Cipher import AES
from paho.mqtt import client as mqtt
from requests.exceptions import RequestException

from .openapi import TO_C_SMART_HOME_REFRESH_TOKEN_API, TuyaOpenAPI
from .openlogging import logger
Expand Down Expand Up @@ -154,11 +155,21 @@ def _on_log(self, mqttc: mqtt.Client, user_data: Any, level, string):

def run(self):
"""Method representing the thread's activity which should not be used directly."""
backoff_seconds = 1
while not self._stop_event.is_set():
self.__run_mqtt()
try:
self.__run_mqtt()
backoff_seconds = 1

# reconnect every 2 hours required.
time.sleep(self.mq_config.expire_time - 60)
except RequestException as e:
logger.exception(e)
logger.error(f"failed to refresh mqtt server, retrying in {backoff_seconds} seconds.")

time.sleep(backoff_seconds)
backoff_seconds = min(backoff_seconds * 2 , 60) # Try at most every 60 seconds to refresh

# reconnect every 2 hours required.
time.sleep(self.mq_config.expire_time - 60)

def __run_mqtt(self):
mq_config = self._get_mqtt_config()
Expand Down

0 comments on commit 4c183a8

Please sign in to comment.