#include "measure.h"

Adafruit_ADS1015 ads; /* Use this for the 12-bit version */

uint64_t lastMeasurement = 0;
uint64_t lastDacWrite = 0;
bool dacDir = false;
int deg = 0;

float ADCvolts = 0;

void handleADC(void)
{
  uint64_t currentmillis = millis();
  if (currentmillis - lastMeasurement > MEASUREMENTINTERVAL)
  {
    ADCvolts = ads.computeVolts(ads.readADC_SingleEnded(0));

    lastMeasurement = currentmillis;
  }
}

void handleDAC(void)
{
  uint64_t currentmillis = millis();
  if (currentmillis - lastDacWrite > DACINTERVAL)
  {
    if (deg >= 254)
    {
      dacDir = false;
      deg = 254;
    }
    if (deg <= 0)
    {
      dacDir = true;
      deg = 0;
    }

    dacWrite(DAC1_OUT, deg);
    
    if (dacDir)
    {
      deg += DACSTEP;
    }
    else
    {
      deg -= DACSTEP;
    }


    lastDacWrite = currentmillis;
  }
}

void initMeasure(void)
{
  Serial.print("init measurements:ADC=");
  if (!ads.begin())
  {
    Serial.println("Failed to initialize ADS.");
  }
  else
  {
    Serial.println("OK");
  }
  lastMeasurement = millis();
  lastDacWrite = millis();

  pinMode(BUTTON3, INPUT_PULLUP);
}

void handleMeasure(void)
{
  handleADC();
  handleDAC();
}

measureMode getMeasureMode(void)
{
  return measureMode::mA200;
}

double getMin(void)
{
  return 14.4;
}

double getMax(void)
{
  return 234.8;
}

double getRms(void)
{
  return 146.7;
}

uint8_t getBar(void)
{
  return 68;
}

float getValue(void)
{
  Serial.printf("ADCvolts:%4.2fV\n",ADCvolts);
  return ADCvolts;
}

bool getErrorState(void)
{
  return false;
}

bool getOkState(void)
{
  return digitalRead(BUTTON3);
}

bool getOpenState(void)
{
  return false;
}
