#!/usr/bin/python
from Tkinter import *
import ttk
import os
import time
import RPi.GPIO as GPIO
from datetime import datetime
import threading

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

def init(root):
    root.title("RPi Thermometer")

root = Tk()
content = ttk.Frame(root,)
#set window size
root.geometry('243x72')

content.grid(column=0, row=0)

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
ledread = 17
led33 = 22
led31 = 23
led29 = 25
led27 = 5
led25 = 6
led23 = 12
led21 = 13
led19 = 16
led17 = 20
led15 = 19
led13 = 26
led11 = 21
led9 = 24
rly1 = 27
GPIO.setup(ledread,GPIO.OUT)
GPIO.setup(led33,GPIO.OUT)
GPIO.setup(led31,GPIO.OUT)
GPIO.setup(led29,GPIO.OUT)
GPIO.setup(led27,GPIO.OUT)
GPIO.setup(led25,GPIO.OUT)
GPIO.setup(led23,GPIO.OUT)
GPIO.setup(led21,GPIO.OUT)
GPIO.setup(led19,GPIO.OUT)
GPIO.setup(led17,GPIO.OUT)
GPIO.setup(led15,GPIO.OUT)
GPIO.setup(led13,GPIO.OUT)
GPIO.setup(led11,GPIO.OUT)
GPIO.setup(led9,GPIO.OUT)
GPIO.setup(rly1,GPIO.OUT)
GPIO.output(ledread,GPIO.HIGH)
GPIO.output(led33,GPIO.HIGH)
GPIO.output(led31,GPIO.HIGH)
GPIO.output(led29,GPIO.HIGH)
GPIO.output(led27,GPIO.HIGH)
GPIO.output(led25,GPIO.HIGH)
GPIO.output(led23,GPIO.HIGH)
GPIO.output(led21,GPIO.HIGH)
GPIO.output(led19,GPIO.HIGH)
GPIO.output(led17,GPIO.HIGH)
GPIO.output(led15,GPIO.HIGH)
GPIO.output(led13,GPIO.HIGH)
GPIO.output(led11,GPIO.HIGH)
GPIO.output(led9,GPIO.HIGH)
GPIO.output(rly1,GPIO.HIGH)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP)

low = 1
high = 1
zero = 1
temp_sensor = '/sys/bus/w1/devices/28-0316a216e2ff/w1_slave'

def temp_raw():

    f = open(temp_sensor, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = temp_raw()
    temp_output = lines[1].find('t=')
    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c

def log_on():
    f=open('RPi_Thermometer_log.txt', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write("  ")
    f.write("ON")
    f.write("\n")    
    f.close()

def log_off():
    f=open('RPi_Thermometer_log.txt', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write("  ")
    f.write("OFF")
    f.write("\n")    
    f.close()

def log_low():
    f=open('RPi_Thermometer_log.txt', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write("  ")
    f.write("Temperature below 8 Degrees")
    f.write("\n")    
    f.close()

def log_high():
    f=open('RPi_Thermometer_log.txt', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write("  ")
    f.write("Temperature above 34 Degrees")
    f.write("\n")    
    f.close()

def log_zero():
    f=open('RPi_Thermometer_log.txt', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M'))
    f.write("  ")
    f.write("Zero Degrees and below")
    f.write("\n")    
    f.close()

def display():
        global low, high, zero
        GPIO.output(ledread,GPIO.LOW)
        time.sleep(0.5)            
        GPIO.output(ledread,GPIO.HIGH)
        temp=read_temp()
        if temp<8:
            GPIO.output(led9,GPIO.LOW)
            time.sleep(0.5)
            GPIO.output(led9,GPIO.HIGH)
        if temp<=0:
            if zero==1:
                zero=0
                log_zero()
        else:
            if temp>1:
                zero=1    
        if temp<8:
            if low==1:
                low=0
                log_low()
        else:
            if temp>8.5:
                low=1    
        if temp>=9:
            GPIO.output(led9,GPIO.LOW)
        else:
            GPIO.output(led9,GPIO.HIGH)
        if temp>=11:
            GPIO.output(led11,GPIO.LOW)
        else:
            GPIO.output(led11,GPIO.HIGH)
        if temp>=13:
            GPIO.output(led13,GPIO.LOW)
        else:
            GPIO.output(led13,GPIO.HIGH)
        if temp>=15:
            GPIO.output(led15,GPIO.LOW)
        else:
            GPIO.output(led15,GPIO.HIGH)    
        if temp>=17:
            GPIO.output(led17,GPIO.LOW)
        else:
            GPIO.output(led17,GPIO.HIGH)
        if temp>=19:
            GPIO.output(led19,GPIO.LOW)
        else:
            GPIO.output(led19,GPIO.HIGH)
        if temp>=21:
            GPIO.output(led21,GPIO.LOW)
        else:
            GPIO.output(led21,GPIO.HIGH)
        if temp>=23:
            GPIO.output(led23,GPIO.LOW)
        else:
            GPIO.output(led23,GPIO.HIGH)
        if temp>=25:
            if GPIO.input(27)==1:
                GPIO.output(rly1,GPIO.LOW)
                GPIO.output(led25,GPIO.LOW)
                log_on()
                c1.set("gold2")
                degree.configure(background=c1.get())
        else:
            if GPIO.input(27)==0:
                if temp>=24.75:               
                    None
                else:
                    GPIO.output(rly1,GPIO.HIGH)
                    GPIO.output(led25,GPIO.HIGH)
                    log_off()
                    c1.set("gray84")
                    degree.configure(background=c1.get())
        if temp>=27:
            GPIO.output(led27,GPIO.LOW)
        else:
            GPIO.output(led27,GPIO.HIGH)
        if temp>=29:
            GPIO.output(led29,GPIO.LOW)
        else:
            GPIO.output(led29,GPIO.HIGH)
        if temp>=31:
            GPIO.output(led31,GPIO.LOW)
        else:
            GPIO.output(led31,GPIO.HIGH)
        if temp>=33:
            GPIO.output(led33,GPIO.LOW)
        else:
            GPIO.output(led33,GPIO.HIGH)
        if temp>34:
            GPIO.output(led33,GPIO.HIGH)
            time.sleep(0.5)
            GPIO.output(led33,GPIO.LOW)
        if temp>34:
            if high==1:
                high=0
                log_high()
        else:
            if temp<33.5:
                high=1 

        temp = str(round(temp, 1))
        display_temperature.configure(text=temp)

temp = StringVar()
c1 = StringVar()
# defining labels
display_temperature = ttk.Label(content, text=temp.get(), font=("Helvetica",48, "bold"), background="gray84")
display_temperature.grid(column=1, row=1)
degree = ttk.Label(content, text=u'\xb0C ', font=("Helvetica",48, "bold"), background=c1.get())
degree.grid(column=2, row=1)

def shutdown(channel):
    os.system("sudo poweroff")            

GPIO.add_event_detect(18, GPIO.FALLING, bouncetime=500, callback=shutdown)

def go():
    while True:
            display()

t = threading.Thread(target=go)
t.daemon=True
t.start()

init(root)
root.mainloop()