#include "Ads1115.h"
#define ADS_DEBUG

Ads1115::Ads1115() : ads1(0x48), ads2(0x49)
{
  #ifdef ADS_DEBUG
  Serial.println("Ads1115 constructor called");
  #endif
  //We set the adcs up:
  ads1.setGain(GAIN_ONE);
  ads2.setGain(GAIN_ONE);
}

Ads1115::~Ads1115()
{
  
}

void Ads1115::begin()
{
  #ifdef ADS_DEBUG
  Serial.println("Ads1115 : begin");
  #endif
  ads1.begin();
  ads2.begin();
}

double Ads1115::getQuantum()
{
  return 0.125;
}

double Ads1115::sampleValue(int16_t channel, boolean sgl)
{
  double total(0);
  for(int i(0); i < getAdcSetting().getMeasureIteration(); i++)
  {
    delay(getAdcSetting().getDelayBetweenIteration());
    total += getReading(channel, sgl);
  }

  //We divide
  total /= (double)getAdcSetting().getMeasureIteration();
  
  //We return
  return total;
}

double Ads1115::sampleValue()
{
  return sampleValue(-1);
}

double Ads1115::sampleVoltage(int16_t channel, boolean sgl)
{
  return sampleValue(channel, sgl)*0.125;
}

double Ads1115::sampleVoltage()
{
  return sampleValue()*0.125;
}

uint16_t Ads1115::getReading(int16_t channel, boolean sgl)
{
  int16_t chan(channel == -1 ? _lastChannel : channel);

  _lastChannel = chan > 8 ? 0 : chan;

  if(chan < 4)
  {
    return ads1.readADC_SingleEnded(chan);
  }
  else if(chan < 8)
  {
    return ads2.readADC_SingleEnded(chan - 4);
  }
  else return 0;
}


//Async part
void Ads1115::startSample(int16_t channel, boolean sgl)
{
  switch(_state)
  {
    case IDLING:
      _state = SAMPLING;
      _elapsedTime = millis();
      _sampledValue = 0.0;
      _numOfSamples = 0;
      //We set the last channel attribute
      if(channel != -1)
      {
        _lastChannel = channel > 8 ? _lastChannel : channel;
      }
      
      break;
    case SAMPLING:
      //If enough time elapsed, we can sample a value again
      if(millis() - _elapsedTime > getAdcSetting().getDelayBetweenIteration())
      {
        _sampledValue += getReading(channel, sgl);
        _elapsedTime = millis();
        _numOfSamples ++;
      }

      //All samples are done:
      if(_numOfSamples == getAdcSetting().getMeasureIteration())
      {
        _sampledValue /= (double)_numOfSamples;
        _sampledValue += channel > 3 ? 82.0 : 0.0;
        _state = RESULT_READY;
      }
      break;
  }
}

void Ads1115::startSample()
{
  startSample(-1);
}

double Ads1115::getSampleVoltage()
{
  return getSampleValue() * 0.125;
}
