1
0
Fork 0
A Python based project for controlling a set of lights via relay switches -- based on the light meter readings made available via the "Midpoint" project.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 

72 lines
2.5 KiB

#!/usr/bin/python3
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.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(relay_pin, GPIO.OUT)
device_id = platform.node() # For servers logs.
def get_api_url():
# Yes, I know I could do this better. Stop moaning.
if (device_id == "gallery1"):
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.
def main():
try:
s = requests.Session()
while True:
r = s.get(api_url, timeout=5)
# print(r.status_code) # For testing.
data = r.json()
# print(f"{datetime.datetime.now()} -> {data}") # For testing.
the_reading = data.get("reading")
# print(the_reading) # For testing.
if (device_id == "gallery1"):
if (the_reading > 39):
# print(f"[INFO: FACTORY1] Light is on -- {the_reading}.")
GPIO.output(relay_pin, GPIO.HIGH)
else:
# print(f"[INFO: FACTORY1] Light is off -- {the_reading}.")
GPIO.output(relay_pin, GPIO.LOW)
elif (device_id == "gallery2"):
if (the_reading > 48):
# print(f"[INFO: FACTORY2] Light is on -- {the_reading}.")
GPIO.output(relay_pin, GPIO.HIGH)
else:
# print(f"[INFO: FACTORY2] Light is off -- {the_reading}.")
GPIO.output(relay_pin, GPIO.LOW)
time.sleep(0.3)
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:
print("[INFO] Terminating relay.py...")
print("[INFO] Cleaning up GPIO before closing...")
GPIO.cleanup()
if __name__ == "__main__" :
main()