#include "main.h"
#include "voltage_meas.h"
#include "relais.h"
#include <stdlib.h>
#include <stdio.h>



static uint32_t voltageUin;
static uint32_t voltageUout;
static uint32_t voltageDrop;



#if defined SYSTEM_VOLTAGE_12V
  #define VOLTAGE_DIVIDER			6
#elif defined SYSTEM_VOLTAGE_24V
  #define VOLTAGE_DIVIDER			11
#elif defined SYSTEM_VOLTAGE_48V
  #define VOLTAGE_DIVIDER			21
#else
  #error "System voltage not defined"
#endif


#define VOLTAGE_DROP_U_LIMIT	90 //mV ca. 30 mV Messfehler + 60mV bei 150A 
#define VOLTAGE_DROP_T_LIMIT	1000

uint32_t dropLimitCounter=0;


void VOLTAGE_MEAS_Exec(uint32_t adcValUin, uint32_t adcValUout)
{

  int32_t vuin;
  vuin = adcValUin * VREF;
  vuin = vuin / 65635;
  vuin = vuin * VOLTAGE_DIVIDER; //Divider für 12V Version
  voltageUin = vuin;


  int32_t vuout;
  vuout = adcValUout * VREF;
  vuout = vuout / 65635;
  vuout = vuout * VOLTAGE_DIVIDER; //Divider für 12V Version
  voltageUout = vuout;
  
  voltageDrop = abs((int32_t)voltageUin - (int32_t)voltageUout);

  if ((RELAIS_GetState() == 1) && (voltageDrop > VOLTAGE_DROP_U_LIMIT))
  {
	if (dropLimitCounter < VOLTAGE_DROP_T_LIMIT) dropLimitCounter++;
	printf("voltage in= %d, out= %d, drop %d\r\n", voltageUin, voltageUout,  voltageDrop);
  }
  else
  {
	if (dropLimitCounter > 0) dropLimitCounter--;
  }
  
}


uint32_t VOLTAGE_MEAS_GetLimitAlarm(void)
{
  if (dropLimitCounter == VOLTAGE_DROP_T_LIMIT) {
	return 1;
  }
  else {
	return 0;
  }

}

void VOLTAGE_MEAS_ResetCounter(void)
{
  dropLimitCounter = 0;
	
}

uint32_t VOLTAGE_MEAS_GetUin(void)
{
  return voltageUin;
	
}

uint32_t VOLTAGE_MEAS_GetUout(void)
{
  return voltageUout;	
}