#!/usr/bin/python3 import RPi.GPIO as GPIO import time import requests import platform 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: while True: # Make sure the U.R.L. is valid. r = requests.get(api_url) # print(r.status_code) # For testing. data = r.json() # print(data) # For testing. the_reading = data.get("reading") # print(the_reading) # For testing. if the_reading > 33: # Print for testing. # print(f"[INFO] Light is on -- {the_reading}.") GPIO.output(relay_pin, GPIO.HIGH) else: # Print for testing. # print(f"[INFO] Light is off -- {the_reading}.") GPIO.output(relay_pin, GPIO.LOW) except KeyboardInterrupt: print("Keyboard Interrupt: quitting program.") except: print("Error updating light reading...") finally: print("Cleaning up GPIO before closing...") GPIO.cleanup() if __name__ == "__main__" : main()