From a64d796a79f7d61c1f3bf0dc25ca04d94ceb7a19 Mon Sep 17 00:00:00 2001 From: gallery2 Date: Mon, 1 Feb 2021 14:12:00 +0000 Subject: [PATCH] add timeout exception handling. At the time of writing, I would find the relay.service wouldn't crash so it couldn't be restarted. Instead, it would hang and I think it's to do with the HTTP request not timing out properly. I can't confirm this yet so I've added in an exception case to help with monitoring the issue. This is a 'work-in-progress' commit. --- relay.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/relay.py b/relay.py index ffbfcc1..e2069fd 100644 --- a/relay.py +++ b/relay.py @@ -4,6 +4,7 @@ import RPi.GPIO as GPIO import time import requests import platform +import datetime relay_pin = 11 #GPIO.setmode(GPIO.BCM) # GPIO numbers instead of board numbers. @@ -18,7 +19,7 @@ def get_api_url(): return "http://ritherdon.abbether.net/api/readings/latest/1" elif (device_id == "gallery2"): return "http://ritherdon.abbether.net/api/readings/latest/2" - + # Make sure this is valid. # api_url = "http://ritherdon.abbether.net/api/readings/add/1" api_url = get_api_url() # Saves having to do the if-check every call. @@ -27,7 +28,8 @@ def main(): try: while True: # Make sure the U.R.L. is valid. - r = requests.get(api_url) + s = requests.Session() + r = s.get(api_url, timeout=5) # print(r.status_code) # For testing. data = r.json() # print(data) # For testing. @@ -43,6 +45,16 @@ def main(): GPIO.output(relay_pin, GPIO.LOW) except KeyboardInterrupt: print("[INFO] KEYBOARD INTERRUPT: quitting program.") + except requests.exceptions.ConnectionError: + pause = 60 + time.sleep(60) + print(f"[WARNING] MAX. REQUESTS EXCEEDED: Pausing requests for {pause} seconds...") + pass + except requests.exceptions.Timeout: + t_stamp = datetime.datetime.now() + print(f"[WARNING] TIMEOUT EXCEPTION: Request timed-out at {t_stamp}.") + time.sleep(60) + pass except Exception as e: print(f"[ERROR] GENERAL EXCEPTION: {e}") finally: