From dd120a29ab71cebb901efe5d7b8465b9750d3142 Mon Sep 17 00:00:00 2001 From: Vladimir Klimes Date: Fri, 23 Dec 2022 23:46:10 +0100 Subject: [PATCH] force reconnect to Tuya API if _get_mqtt_config() call fails --- tuya_iot/openapi.py | 6 ++++++ tuya_iot/openmq.py | 20 ++++++++++++-------- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/tuya_iot/openapi.py b/tuya_iot/openapi.py index 10e6f23..e44e5ed 100644 --- a/tuya_iot/openapi.py +++ b/tuya_iot/openapi.py @@ -227,6 +227,12 @@ def is_connect(self) -> bool: """Is connect to tuya cloud.""" return self.token_info is not None and len(self.token_info.access_token) > 0 + def force_reconnect(self) -> bool: + self.connect( + self.__username, self.__password, self.__country_code, self.__schema + ) + return self.is_connect() + def __request( self, method: str, diff --git a/tuya_iot/openmq.py b/tuya_iot/openmq.py index 07936e0..d6a1762 100644 --- a/tuya_iot/openmq.py +++ b/tuya_iot/openmq.py @@ -174,17 +174,21 @@ def run(self): def __run_mqtt(self): mq_config = self._get_mqtt_config() if mq_config is None: - logger.error("error while get mqtt config") - return + logger.error("error while get mqtt config, trying to reconnect") + self.api.force_reconnect() + mq_config = self._get_mqtt_config() - self.mq_config = mq_config + if mq_config is None: + logger.error("permanent error while get mqtt config") + else: + self.mq_config = mq_config - logger.debug(f"connecting {mq_config.url}") - mqttc = self._start(mq_config) + logger.debug(f"connecting {mq_config.url}") + mqttc = self._start(mq_config) - if self.client: - self.client.disconnect() - self.client = mqttc + if self.client: + self.client.disconnect() + self.client = mqttc def _start(self, mq_config: TuyaMQConfig) -> mqtt.Client: mqttc = mqtt.Client(mq_config.client_id)