caretak3r
Well-Known Member
Here's my python code - I'm not a develolper, so anything I code should be considered a dirty hack job. I originally ran this via cron with an 'hourly' argument. I now run it every 30 minutes but haven't updated my 'hourly' tag to be more meaningful. I guess include that I added a RTC module to the raspberry pi as well.
Code:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time,os,sys
#config
ON_HOURS=5
OFF_HOURS=11
on_time = 0
off_time = 0
flag_on = "/etc/lightmon/.on"
flag_off = "/etc/lightmon/.off"
main_light = 4
farRed_light = 17
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(main_light,GPIO.OUT)
GPIO.setup(farRed_light,GPIO.OUT)
current_time = time.time()
def touch(fname, times=None):
with file(fname, 'a'):
os.utime(fname, times)
def turn_on():
GPIO.output(main_light,True)
touch(flag_on)
if os.path.isfile(flag_off):
os.remove(flag_off)
def turn_off():
GPIO.output(farRed_light, True)
GPIO.output(main_light,False)
if os.path.isfile(flag_on):
os.remove(flag_on)
touch(flag_off)
time.sleep(480)
GPIO.output(farRed_light, False)
def turn_offoff():
GPIO.output(farRed_light, False)
GPIO.output(main_light,False)
if os.path.isfile(flag_on):
os.remove(flag_on)
touch(flag_off)
def turn_froff():
GPIO.output(farRed_light, False)
if len(sys.argv) < 2:
print "needs an argument fool!\n"
sys.exit(2)
if sys.argv[1] == "hourly":
if os.path.isfile(flag_on):
on_time = os.path.getmtime(flag_on)
time_diff = current_time - on_time
#print time_diff/float(3600)
#print ((ON_HOURS*60*60) /float(time_diff))
#print (ON_HOURS*60*60)
#print float(time_diff)
if (1.025 > ((ON_HOURS*60*60) /float(time_diff)) ):
print "time to sleep"
turn_off()
elif os.path.isfile(flag_off):
off_time = os.path.getmtime(flag_off)
time_diff = current_time - off_time
#print time_diff/float(3600)
#print ((OFF_HOURS*60*60) /float(time_diff))
if (1.05 > ((OFF_HOURS*60*60) /float(time_diff)) ):
#print "time to wake up"
turn_on()
elif sys.argv[1] == "verify":
if os.path.isfile(flag_on):
if GPIO.input(main_light):
exit
else:
turn_on()
else:
#print "verify off"
turn_offoff()
elif sys.argv[1] == "on":
turn_on()
elif sys.argv[1] == "off":
turn_off()
elif sys.argv[1] == "offoff":
turn_offoff()
elif sys.argv[1] == "froff":
turn_froff()