import RPi.GPIO as GPIO
import signal
import sys
from gpiozero import CPUTemperature
import time
from pathlib import Path
import configparser



# initializing GPIO, setting mode to BOARD.
# Default pin of fan is physical pin 8, GPIO14
Fan = 8
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Fan, GPIO.OUT)

def handle_exit(signum, frame):
  print(f"Signal {signum} received, setting fan to 100%")
  p.ChangeDutyCycle(100)
  time.sleep(0.5)  # waiting to ensure that PWM is set
  p.stop()
  GPIO.cleanup()
  sys.exit(0)

#initialize GPIO
p = GPIO.PWM(Fan, 50)
p.start(0)

signal.signal(signal.SIGTERM, handle_exit)
signal.signal(signal.SIGINT, handle_exit)  # optional (Ctrl+C)

def read_config():
  confparser = configparser.ConfigParser()
  f = Path("/boot/config.txt")
  if f.is_file():
   confparser.read('/boot/config.txt')
  else:
   f = Path('/boot/firmware/config.txt')
   if f.is_file():
    confparser.read('/boot/firmware/config.txt')
    

  return confparser
confparser = read_config()

def parse_config():
  confparser = read_config()
  stages= []
  
  stage0_temp = float(confparser['fan']['fan_temp0_temp'])
  stage0_speed = float(confparser['fan']['fan_temp0_speed'])
  stage1_temp = float(confparser['fan']['fan_temp1_temp'])
  stage1_speed = float(confparser['fan']['fan_temp1_speed'])
  stage2_temp = float(confparser['fan']['fan_temp2_temp'])
  stage2_speed = float(confparser['fan']['fan_temp2_speed'])

  stages.append({'temp': stage0_temp,'speed': stage0_speed})
  stages.append({'temp': stage1_temp,'speed': stage1_speed})
  stages.append({'temp': stage2_temp,'speed': stage2_speed})
  return stages

stages = parse_config()
print(f'stages={stages}')
try:
    stage= oldstage = 0
    print(f'stage={stage}')
    while True:
        cpu = CPUTemperature()
        temperature = cpu.temperature

        #print(f'temperature={temperature}/{temp}')

        if temperature < stages[0]['temp']:
            stage = 0
        elif temperature > stages[1]['temp'] and temperature < stages[2]['temp']:
            stage = 1
        elif temperature > stages[2]['temp']:
            stage = 2

        if stage != oldstage:
          oldstage = stage
          print(f'stage={stage},temperature={temperature}°C')
          p.ChangeDutyCycle(stages[stage]['speed'])

        time.sleep(0.2)
except KeyboardInterrupt:
    pass
finally:
# ensure on exit that fan runs full speed
    p.ChangeDutyCycle(100)
    p.stop()
    GPIO.cleanup()

