# Can enable debug output by uncommenting:
#import logging
#logging.basicConfig(level=logging.DEBUG)

import time

import Adafruit_GPIO.SPI as SPI
import MAX6675.MAX6675 as MAX6675

from simple_pid import PID
kP =100
kI = 0
kD = .0
setpoint = 675
temp = -1000
output = -1
current_milli_time = -1
pid = PID(kP, kI, kD, setpoint)
loop_size = int(1000)
sleep_time = 0.3
counter = 0
##pid.sample_time = .3  # update every 0.5 seconds
pid.proportional_on_measurement = True
pid.output_limits = (0, loop_size)    # output value will be between 0 and  5000
log_directory = "./log_piNail.txt"
f = open(log_directory, 'w+') #Create a new log file, overwritting the previous one
f.close()


# Raspberry Pi software SPI configuration.
CLK = 3
CS  = 14
DO  = 4
sensor = MAX6675.MAX6675(CLK, CS, DO)

relayPin = 2

import RPi.GPIO as GPIO    # Import Raspberry Pi GPIO library
GPIO.setwarnings(False)    # Ignore warning for now
GPIO.setmode(GPIO.BCM)   # Use physical pin numbering
GPIO.setup(relayPin, GPIO.OUT, initial=GPIO.LOW)   # Set pin 8 to be an output pin and set initial value to low (off)

# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
    return c * 9.0 / 5.0 + 32.0
        
def logToFile(directory):
    f = open(directory, "a+")
    f.write("{0:.2f}, {1:.2f}, {2:.2f}, {3}, {4} \n".format(temp, setpoint, output/10, GPIO.input(relayPin)  * 50+ 200, current_milli_time))
    f.close()

def loadPID_params(directory):
    PID_values = open(directory, 'r').read()
    values = PID_values.split("\n")
    return float(values[0]), float(values[1]), float(values[2]), float(values[3]), int(values[4]), int(values[5]), int(values[6])
    
        
print('Press Ctrl-C to quit.')
try:
    while True: 
        kP, kI, kD, sleep_time, loop_size, setpoint, log_resolution = loadPID_params("./P_I_D_values.txt")
        pid.output_limits = (0, loop_size) 
        pid.setpoint = setpoint
        pid.tunings = (kP, kI, kD)
        temp = c_to_f(sensor.readTempC())
        start_milli_time = int(round(time.time() * 1000))
        current_milli_time = int(round(time.time() * 1000))	
        current_loop_end = start_milli_time + loop_size
      
        while current_milli_time < current_loop_end:
		        temp = c_to_f(sensor.readTempC())
		        output = pid(temp)
		        if current_milli_time < start_milli_time + output:
			        GPIO.output(relayPin, GPIO.HIGH)
		        else:
			        GPIO.output(relayPin, GPIO.LOW)
		        current_milli_time = int(round(time.time() * 1000))
		        print("Temp: {0:06.2f}, PWR: {1:07.2f}/{2}, {3}, {4}, {5}, {6}".format(temp, output, loop_size, GPIO.input(relayPin), pid.Kp, pid.Ki, pid.Kd))
		        if counter > log_resolution:
		            logToFile(log_directory)
		            counter = 0
		        else:
		            counter = counter + 1
		        time.sleep(sleep_time)
except:
    GPIO.output(relayPin, GPIO.LOW)
    print("Exiting properly")
