#include "thermo.h"
#include "controlloop.h"

//MAX6675 thermocouple(THERM_SS, THERM_MISO, THERM_CLK);
MAX31855 thermocouple(THERM_CLK, THERM_SS, THERM_MISO); //uint8_t CS, uint8_t MISO);

// initialize the Thermocouple
//Adafruit_MAX31855 thermocouple(THERM_CLK, THERM_SS, THERM_MISO);

uint32_t thermo_lastTime = 0;

float lastTemperature = 0;
float internal = 0;

bool simulation = false;
#define SIM_TEMP_STEP 1
#define SIM_TEMP_COOL 0.08
#define SIM_INTERVAL 100
uint32_t simTimer = 0;
uint32_t sampleTimer = 0;

void initThermo()
{
  thermocouple.begin();
  if (simulation)
  {
    lastTemperature = TEMPERATURE_ROOM - 20;
  }
}

void handleThermo(void)
{
  uint32_t timeNow = millis();
  if (simulation)
  {

    if (timeNow - simTimer > SIM_INTERVAL)
    {
      if (getOutputState())
      {
        lastTemperature += SIM_TEMP_STEP;
      }
      else
      {
        if (lastTemperature > TEMPERATURE_ROOM - 20)
        {
          lastTemperature -= SIM_TEMP_COOL;
        }
      }
      simTimer = timeNow;
    }
  }
  else
  {
    if (timeNow - sampleTimer > THERMO_INTERVAL)
    {
      int state = thermocouple.read();
      lastTemperature = thermocouple.getTemperature();
      internal = thermocouple.getInternal();
      sampleTimer = timeNow;
    }
  }
}

float getTemperature(void)
{
  return lastTemperature; //lastTemperature;
}

bool getThermoCoupleFault(void)
{
  return thermocouple.genericError();
}
