#include "uksi_main.h"
#include "uksi_oled.h"
#include "adc.h"
#include "tim.h"
UKSI_Calc_t uksi_calc;
UKSI_DC_t uksi_dc;
float iso_result = 100;
int dbg_dc = 0;
int dc_min_period = 5000;
int pause_period = 5000;
int measure_period = 2500;
void UKSI_Init()
{
  DC_Init(&uksi_dc, &htim1, TIM_OCMODE_INACTIVE, TIM_OCMODE_ACTIVE);
  UKSI_Calc_Init(&uksi_calc, &hadc1);
	oled_init();
}



void UKSI_prewhile()
{
  iso_result = uksi_calc.IsoOhm;
}


void UKSI_while()
{
  static uint32_t prev_oled_tick = 0;
  static uint32_t prev_dc_tick = 0;
  static uint32_t start_measure_tick = 0;
  float curr_iso = 0;
  DC_Enable(&uksi_dc, dbg_dc);
  
  if(uwTick - prev_oled_tick > 1000)
  {
    prev_oled_tick = uwTick;
    UKSI_Print(iso_result/1000000, dbg_dc, uksi_calc.adc.Voltage, uksi_calc.IsoCurrentuA);
  }
  
  if(dbg_dc)
  {
    curr_iso = UKSI_Calc_Isolation(&uksi_calc);
    if(uwTick - prev_dc_tick > dc_min_period) // подаем импульс на минимальный период
    {
      if(!foster_check(&uksi_calc.adc.foster)) // если стабильный уровень найден
      {
        if(start_measure_tick == 0)
        {
          start_measure_tick = uwTick; // измеряем еще 5 секунд и выключаем источник
        }
        else
        {
          if(uwTick - start_measure_tick > measure_period)
          {
            dbg_dc = 0;
            start_measure_tick = 0;
            prev_dc_tick = uwTick;
            iso_result = curr_iso;
          }
        }
      }
      else if(curr_iso > 10000000)
      {
        dbg_dc = 0;
        start_measure_tick = 0;
        prev_dc_tick = uwTick;
        iso_result = curr_iso;
      }
    }
  }
  else
  {
    if(uwTick - prev_dc_tick > pause_period) // ждем паузу перед новой подачей импульса
    {
      dbg_dc = 1;
      prev_dc_tick = uwTick;
    }
  }
}