1
0
Fork 0
Browse Source

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.
unstable
gallery2 3 years ago
parent
commit
a64d796a79
  1. 16
      relay.py

16
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: