From 8d804ec551d8866325a56643adae34d399280327 Mon Sep 17 00:00:00 2001 From: jwansek Date: Sat, 7 Oct 2023 17:38:50 +0100 Subject: Fixed retrying if it couldn't connect --- database.py | 2 ++ devices.py | 39 +++++++++++++++++++++++++-------------- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/database.py b/database.py index 59250d0..b31f905 100644 --- a/database.py +++ b/database.py @@ -23,6 +23,8 @@ class PowerDatabase: print(e) if e.args[0] == 1049: self.__connection = self.__build_db() + elif e.args[0] == 2003: + raise ConnectionError(e.args[1]) with self.__connection.cursor() as cursor: if "TASMOTA_DEVICES" in os.environ.keys(): diff --git a/devices.py b/devices.py index 0b8cabe..f8f17fe 100644 --- a/devices.py +++ b/devices.py @@ -39,26 +39,37 @@ def poll_watt_all(): asyncio.set_event_loop(loop) with database.PowerDatabase(host = HOST) as db: for host, username, password in db.get_tasmota_devices(): - try: - asyncio.run(poll_watt_for(db, host, username, password)) - except: - print("Retrying %s..." % host) - asyncio.run(poll_watt_for(db, host, username, password)) + while True: + try: + asyncio.run(poll_watt_for(db, host, username, password)) + except: + print("Retrying %s..." % host) + continue + break + def poll_kwh_all(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) with database.PowerDatabase(host = HOST) as db: for host, username, password in db.get_tasmota_devices(): - try: - asyncio.run(poll_yesterday_kwh_for(db, host, username, password)) - except: - print("Retrying %s..." % host) - asyncio.run(poll_yesterday_kwh_for(db, host, username, password)) + while True: + try: + asyncio.run(poll_yesterday_kwh_for(db, host, username, password)) + except ConnectionError: + print("Retrying %s..." % host) + continue + break if __name__ == "__main__": - if sys.argv[1] == "daily": - poll_kwh_all() - else: - poll_watt_all() + while True: + try: + if sys.argv[1] == "daily": + poll_kwh_all() + else: + poll_watt_all() + except ConnectionError as e: + print("Couldn't connect: ", e, " retrying...") + continue + break -- cgit v1.2.3