From ca188c65a2b95f0f10f53e46b6a21bd1cb5ee0ce Mon Sep 17 00:00:00 2001 From: Ken Sanislo Date: Sat, 22 Dec 2018 19:27:25 -0800 Subject: [PATCH] improve login() and login retry --- tcc-exporter | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/tcc-exporter b/tcc-exporter index 0c9cc84..a29a7fb 100755 --- a/tcc-exporter +++ b/tcc-exporter @@ -12,7 +12,7 @@ import urllib.request from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.error import HTTPError -VERSION = '0.8.3' +VERSION = '0.8.4' PREFIX = 'https://mytotalconnectcomfort.com/' devices = list() @@ -54,6 +54,7 @@ class Client(object): if '/portal/Account/LogOff' in decoded: log('INFO', 'TCC portal login successful.') self._backoff = 0 + return True else: log('WARNING', 'TCC portal login failed.') if (self._backoff < self._min_backoff): @@ -63,10 +64,13 @@ class Client(object): else: self._backoff = self._backoff * 2 log('INFO', 'Set login retry delay to {0} seconds.'.format(self._backoff)) + return False except Exception as e: log('ERROR', '{0} {1}: {2!r}'.format(inspect.currentframe().f_code.co_name, type(e).__name__, e.args)) + return False else: log('INFO', 'Login retry delayed another {0} seconds.'.format(int(self._last_login + self._backoff - utc_seconds))) + return False def _request(self, path, data={}, headers={}): if isinstance(data, str): @@ -96,14 +100,15 @@ class Client(object): def _request_data(self, path, data={}, headers={}): data = self._request(path, data, headers) if isinstance(data, int) and (data == 401): # Login failure, lets try to login again. - log('INFO', 'Retrying Client.login()') - self.login() - data = self._request(path, data, headers) + if self.login(): + data = self._request(path, data, headers) if isinstance(data, int): return data # Another failure, just return the code. reader = codecs.getreader(data.headers.get_content_charset()) try: - return json.load(reader(data)) + retval = json.load(reader(data)) + self._backoff = 0 # We got decodable JSON, reset the backoff. + return retval except json.JSONDecodeError as e: log('INFO', 'TCC portal returned invalid data.') return 502