#!/usr/bin/env python3
# Author: Imran Qureshi
import os
from time import sleep
import signal
import sys
sys.path.append('/storage/.kodi/addons/virtual.rpi-tools/lib')
import RPi.GPIO as GPIO
maxTMP = 55 # The maximum temperature in Celsius after which we trigger the fan
dc = 0 #Duty cycle is zero at start
#def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
GPIO.setwarnings(False)
p = GPIO.PWM(12, 100)
p.start(0)
#input('Press return to stop:')
#p.stop()
#time.sleep(2)
#p.start(0)
#return()

def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()
    temp =(res.replace("temp=","").replace("'C\n",""))
#   print("temp is {0}".format(temp)) #Uncomment here for testing
    return temp

def getTEMP():
    CPU_temp = float(getCPUtemperature())
    if CPU_temp > maxTMP:
        dc = 10 + (CPU_temp - maxTMP) * 4
        if dc > 100:
              dc = 100
        p.ChangeDutyCycle(dc)
#       print("Speed is {0}".format(dc)) 

    else:
        p.ChangeDutyCycle(0)
    return()

try:
#    setup() 
    while True:
        sleep(30) # Read the temperature every 2 sec, increase or decrease this
        getTEMP()
     
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt 
    GPIO.cleanup() # resets all GPIO ports used by this program
