//This is where we get the data from sensors and make something of it.
// Programed by Joshua Umholtz-Judson
#include 
#include 
#include "Sensors.h"
//Include Global Vars from main program, Line in

// Variables For Temperatures
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;  //Known Resistances
float Res1 = 10000.0;                                                    //10k resistance
extern float TBRad[]; //Array used for average Before Radiator Temp Values
extern float TARad[]; //Array used for average After Radiator Temp Values

//Liquid flow speed
extern unsigned long timeyWimey[];
extern float flow;

//Get Temperature Before Radiator
void Sensors::UpBRadTemps(int lIn) {
  float VInBRad = analogRead(lIn);
  float TempBRad = (Res1 * (1024.0 / VInBRad - 1.0));  //Resistance values
  TempBRad = log(TempBRad);
  TempBRad = (1.0 / (c1 + c2 * TempBRad + c3 * TempBRad * TempBRad * TempBRad));  //Steinhart-Hart Equation
  TempBRad = TempBRad - 273.15;                                                   //Convert from Kelvin
  TempBRad = (TempBRad * 1.8) + 32;
  //Update array placement new temp always at the begining
  for (int i = 4; i > 0; i--) {
    int fool = i - 1;
    TBRad[i] = TBRad[fool];
  }
  TBRad[0] = TempBRad;

  //Serial.print("BRad Temp: ");
  //Serial.println(TempBRad);

  return;
}

//Get Temperature After Radiator
void Sensors::UpARadTemps(int lIn) {
  float VInARad = analogRead(lIn);
  float TempARad = log((Res1 * (1024.0 / VInARad - 1.0)));
  TempARad = (1.0 / (c1 + c2 * TempARad + c3 * TempARad * TempARad * TempARad));
  TempARad = ((TempARad - 273.15) * 1.8) + 32;
  for (int i = 4; i > 0; i--) {
    int fool = i - 1;
    TARad[i] = TARad[fool];
  }
  TARad[0] = TempARad;

  //Serial.print("ARad Temp: ");
  //Serial.println( TempARad);

  return;
};

//Calculate flow rotations per minute
//Take bools for if the rotation detected a change, return comparison bool
bool Sensors::UpFlow(bool chngd, bool retComp) {  
  //if nothings changed dont bother
  if (chngd != retComp) {
    float calv = 0;

    //set calv to time between interupts, dont let it change while calculating
    //noInterrupts();
    calv = timeyWimey[retComp] - timeyWimey[chngd];
    // calculate rate per minute, 1 rotation = 6 interrupts
    flow = (60000 / (6 * calv));
    //interrupts();

    //set the comparator
    retComp = chngd;
    //Serial.println("vals");
    //Serial.println(timeyWimey[chngd]);
    //Serial.println(timeyWimey[!chngd]);
    //Serial.println(flow);
    return retComp;
  }//End of change
  else if (millis() > (timeyWimey[chngd] + 10000)) {  //Check if pump is off
    flow = 0.0;
  }

  return retComp;
};