#!/usr/bin/python

from subprocess import * 
from time import sleep, strftime
from datetime import datetime
from sys import exit
import os
import glob
import time
# check the system time and if it is not synced (pi has just switched on) then die
if(time.time() < 1385381049):
	exit()

probe1='28-000003e6d496'
probe2='28-0000045d18c3'
probe3='28-0000045d4af9'
base_dir= '/sys/bus/w1/devices/'
aldabday = 28800 # 8am
aldabnight = 64800 # 6pm
hermday = 32400 # 9am
hermnight = 64800 # 6pm
dayhigh = 24
nightlow = i = 18
switch1 = switch2 = switch3 = 0
switch4 = 'off'
# plug 1 controls the aldab lights
# plug 2 controls the hermanni lights
# plug 3 controls the heater
# plug 4 is unused at the moment but left in for future use

# function to read the temperature from a probe
def read_temp_raw(probe):
	f = open(base_dir + probe + '/w1_slave', 'r')
	lines = f.readlines()
	f.close()
	return lines

# function to interpret the results of the probe and return it as a number
def read_temp(probe):
	lines = read_temp_raw(probe)
	while lines[0].strip()[-3:] != 'YES':
		time.sleep(0.2)
		lines = read_temp_raw(probe)
	equals_pos = lines[1].find('t=')
	if equals_pos != -1:
		temp_string = lines[1][equals_pos+2:]
		temp_c = float(temp_string) / 1000.0
		return temp_c
	
temp1 = read_temp(probe1)
print ('Probe 1 - Room Temp: %.1f' %temp1)
temp2 = read_temp(probe2)
print ('Probe 2 - Fridge Temp: %.1f' %temp2)
temp3 = read_temp(probe3)
print ('Probe 3 - Outside Temp: %.1f' %temp3)
# This gives the remainder in seconds after stripping off the days (86400 seconds in a day)
timenow = time.time() % 86400
if (aldabday < timenow < aldabnight): #aldab lights
	os.system('switch 1 on')
	switch1 = 'on'
else:
	os.system('switch 1 off')
	switch1 = 'off'
# This is currently commented out whilst the hermanni are hibernating
#if (hermday < timenow < hermnight): #hermanni lights
#	os.system('switch 2 on')
#	switch2 = 'on'
#else:
os.system('switch 2 off')
switch2 = 'off'

# Heater is controlled by the hermday and hermnight settings above
if (hermday < timenow < hermnight): #heater
	i = dayhigh # i is used for the baseline graph
if (temp1 > i): # too hot
	os.system('switch 3 off')
	switch3 = 'off'
else:
	os.system('switch 3 on')
	switch3 = 'on'
today = datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d') # needed for the log file name
now = datetime.fromtimestamp(int(time.time())).strftime('%H:%M') # needed for the time to add to the logfile
logfile = open('/home/pi/logs/' + today + '.csv','a') # this is where the log files are stored
# This writes the line to the logfile in the format time,temp1,temp2,temp3,baseline,switch1,switch2,switch3,switch4
logfile.write(str(now) + ',' + str(temp1) + ',' + str(temp2) + ',' + str(temp3) + ',' + str(i) + ',' + switch1 + ',' + switch2 + ',' + switch3+ ',' + switch4 + '\n')
logfile.close()