/**
  ******************************************************************************
  * File Name          : ADC.c
  * Description        : This file provides code for the configuration
  *                      of the ADC instances.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "adc.h"

/* USER CODE BEGIN 0 */
uint32_t ADC1_Buffer[ADC1_CHANEL_COUNT*ADC1_SAMPLE_COUNT];
uint32_t ADC2_Buffer[ADC2_CHANEL_COUNT*ADC2_SAMPLE_COUNT];
uint16_t ADC2_Buffer_Each[ADC2_CHANEL_COUNT][ADC2_SAMPLE_COUNT];
uint32_t ADC3_Buffer[ADC3_CHANEL_COUNT*ADC3_SAMPLE_COUNT];
uint16_t ADC3_Buffer_Each[ADC3_CHANEL_COUNT][ADC3_SAMPLE_COUNT];
uint8_t isDMAEnd_ADC1;
uint8_t isDMAEnd_ADC2;
uint8_t isDMAEnd_ADC3;

struct ADC_VALUE adc_value;

uint16_t ADCWDGHighThreshold = 3200;
uint16_t ADCWDGLowThreshold = 820;
uint8_t is60Hz;
/* USER CODE END 0 */

ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
ADC_HandleTypeDef hadc3;
DMA_HandleTypeDef hdma_adc1;
DMA_HandleTypeDef hdma_adc2;
DMA_HandleTypeDef hdma_adc3;

/* ADC1 init function */
void MX_ADC1_Init(void)
{
  ADC_ChannelConfTypeDef sConfig = {0};

  /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) 
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV8;
  hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  hadc1.Init.ScanConvMode = ENABLE;
  hadc1.Init.ContinuousConvMode = ENABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = ENABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_4;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

}
/* ADC2 init function */
void MX_ADC2_Init(void)
{
  ADC_AnalogWDGConfTypeDef AnalogWDGConfig = {0};
  ADC_ChannelConfTypeDef sConfig = {0};

  /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) 
  */
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV8;
  hadc2.Init.Resolution = ADC_RESOLUTION_12B;
  hadc2.Init.ScanConvMode = ENABLE;
  hadc2.Init.ContinuousConvMode = ENABLE;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.NbrOfConversion = 2;
  hadc2.Init.DMAContinuousRequests = ENABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SEQ_CONV;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure the analog watchdog 
  */
  AnalogWDGConfig.WatchdogMode = ADC_ANALOGWATCHDOG_SINGLE_REG;
  AnalogWDGConfig.HighThreshold = 3722;
  AnalogWDGConfig.LowThreshold = 372;
  AnalogWDGConfig.Channel = ADC_CHANNEL_6;
  AnalogWDGConfig.ITMode = ENABLE;
  if (HAL_ADC_AnalogWDGConfig(&hadc2, &AnalogWDGConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_5;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_6;
  sConfig.Rank = 2;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

}
/* ADC3 init function */
void MX_ADC3_Init(void)
{
  ADC_ChannelConfTypeDef sConfig = {0};

  /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) 
  */
  hadc3.Instance = ADC3;
  hadc3.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV8;
  hadc3.Init.Resolution = ADC_RESOLUTION_12B;
  hadc3.Init.ScanConvMode = ENABLE;
  hadc3.Init.ContinuousConvMode = ENABLE;
  hadc3.Init.DiscontinuousConvMode = DISABLE;
  hadc3.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc3.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc3.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc3.Init.NbrOfConversion = 5;
  hadc3.Init.DMAContinuousRequests = ENABLE;
  hadc3.Init.EOCSelection = ADC_EOC_SEQ_CONV;
  if (HAL_ADC_Init(&hadc3) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_9;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_14;
  sConfig.Rank = 2;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_15;
  sConfig.Rank = 3;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_4;
  sConfig.Rank = 4;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. 
  */
  sConfig.Channel = ADC_CHANNEL_7;
  sConfig.Rank = 5;
  if (HAL_ADC_ConfigChannel(&hadc3, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }

}

void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(adcHandle->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspInit 0 */

  /* USER CODE END ADC1_MspInit 0 */
    /* ADC1 clock enable */
    __HAL_RCC_ADC1_CLK_ENABLE();
  
    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**ADC1 GPIO Configuration    
    PA4     ------> ADC1_IN4 
    */
    GPIO_InitStruct.Pin = ADC1_IN4_CP_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(ADC1_IN4_CP_GPIO_Port, &GPIO_InitStruct);

    /* ADC1 DMA Init */
    /* ADC1 Init */
    hdma_adc1.Instance = DMA2_Stream0;
    hdma_adc1.Init.Channel = DMA_CHANNEL_0;
    hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
    hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
    hdma_adc1.Init.Mode = DMA_CIRCULAR;
    hdma_adc1.Init.Priority = DMA_PRIORITY_LOW;
    hdma_adc1.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);

    /* ADC1 interrupt Init */
    HAL_NVIC_SetPriority(ADC_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(ADC_IRQn);
  /* USER CODE BEGIN ADC1_MspInit 1 */

  /* USER CODE END ADC1_MspInit 1 */
  }
  else if(adcHandle->Instance==ADC2)
  {
  /* USER CODE BEGIN ADC2_MspInit 0 */

  /* USER CODE END ADC2_MspInit 0 */
    /* ADC2 clock enable */
    __HAL_RCC_ADC2_CLK_ENABLE();
  
    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**ADC2 GPIO Configuration    
    PA5     ------> ADC2_IN5
    PA6     ------> ADC2_IN6 
    */
    GPIO_InitStruct.Pin = ADC2_IN5_Welding_Pin|ADC2_IN6_GF_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* ADC2 DMA Init */
    /* ADC2 Init */
    hdma_adc2.Instance = DMA2_Stream3;
    hdma_adc2.Init.Channel = DMA_CHANNEL_1;
    hdma_adc2.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_adc2.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_adc2.Init.MemInc = DMA_MINC_ENABLE;
    hdma_adc2.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    hdma_adc2.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
    hdma_adc2.Init.Mode = DMA_CIRCULAR;
    hdma_adc2.Init.Priority = DMA_PRIORITY_LOW;
    hdma_adc2.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_adc2) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc2);

    /* ADC2 interrupt Init */
    HAL_NVIC_SetPriority(ADC_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(ADC_IRQn);
  /* USER CODE BEGIN ADC2_MspInit 1 */

  /* USER CODE END ADC2_MspInit 1 */
  }
  else if(adcHandle->Instance==ADC3)
  {
  /* USER CODE BEGIN ADC3_MspInit 0 */

  /* USER CODE END ADC3_MspInit 0 */
    /* ADC3 clock enable */
    __HAL_RCC_ADC3_CLK_ENABLE();
  
    __HAL_RCC_GPIOF_CLK_ENABLE();
    /**ADC3 GPIO Configuration    
    PF3     ------> ADC3_IN9
    PF4     ------> ADC3_IN14
    PF5     ------> ADC3_IN15
    PF6     ------> ADC3_IN4
    PF9     ------> ADC3_IN7 
    */
    GPIO_InitStruct.Pin = ADC3_IN9_Voltage_L1_Pin|ADC3_IN14_1998_Pin|ADC3_IN15_Temp_Pin|ADC3_IN4_GMI_VL1_Pin 
                          |ADC3_IN7_Current_L1_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);

    /* ADC3 DMA Init */
    /* ADC3 Init */
    hdma_adc3.Instance = DMA2_Stream1;
    hdma_adc3.Init.Channel = DMA_CHANNEL_2;
    hdma_adc3.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_adc3.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_adc3.Init.MemInc = DMA_MINC_ENABLE;
    hdma_adc3.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
    hdma_adc3.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
    hdma_adc3.Init.Mode = DMA_CIRCULAR;
    hdma_adc3.Init.Priority = DMA_PRIORITY_LOW;
    hdma_adc3.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
    if (HAL_DMA_Init(&hdma_adc3) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc3);

    /* ADC3 interrupt Init */
    HAL_NVIC_SetPriority(ADC_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(ADC_IRQn);
  /* USER CODE BEGIN ADC3_MspInit 1 */

  /* USER CODE END ADC3_MspInit 1 */
  }
}

void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{

  if(adcHandle->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspDeInit 0 */

  /* USER CODE END ADC1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_ADC1_CLK_DISABLE();
  
    /**ADC1 GPIO Configuration    
    PA4     ------> ADC1_IN4 
    */
    HAL_GPIO_DeInit(ADC1_IN4_CP_GPIO_Port, ADC1_IN4_CP_Pin);

    /* ADC1 DMA DeInit */
    HAL_DMA_DeInit(adcHandle->DMA_Handle);

    /* ADC1 interrupt Deinit */
  /* USER CODE BEGIN ADC1:ADC_IRQn disable */
    /**
    * Uncomment the line below to disable the "ADC_IRQn" interrupt
    * Be aware, disabling shared interrupt may affect other IPs
    */
    /* HAL_NVIC_DisableIRQ(ADC_IRQn); */
  /* USER CODE END ADC1:ADC_IRQn disable */

  /* USER CODE BEGIN ADC1_MspDeInit 1 */

  /* USER CODE END ADC1_MspDeInit 1 */
  }
  else if(adcHandle->Instance==ADC2)
  {
  /* USER CODE BEGIN ADC2_MspDeInit 0 */

  /* USER CODE END ADC2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_ADC2_CLK_DISABLE();
  
    /**ADC2 GPIO Configuration    
    PA5     ------> ADC2_IN5
    PA6     ------> ADC2_IN6 
    */
    HAL_GPIO_DeInit(GPIOA, ADC2_IN5_Welding_Pin|ADC2_IN6_GF_Pin);

    /* ADC2 DMA DeInit */
    HAL_DMA_DeInit(adcHandle->DMA_Handle);

    /* ADC2 interrupt Deinit */
  /* USER CODE BEGIN ADC2:ADC_IRQn disable */
    /**
    * Uncomment the line below to disable the "ADC_IRQn" interrupt
    * Be aware, disabling shared interrupt may affect other IPs
    */
    /* HAL_NVIC_DisableIRQ(ADC_IRQn); */
  /* USER CODE END ADC2:ADC_IRQn disable */

  /* USER CODE BEGIN ADC2_MspDeInit 1 */

  /* USER CODE END ADC2_MspDeInit 1 */
  }
  else if(adcHandle->Instance==ADC3)
  {
  /* USER CODE BEGIN ADC3_MspDeInit 0 */

  /* USER CODE END ADC3_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_ADC3_CLK_DISABLE();
  
    /**ADC3 GPIO Configuration    
    PF3     ------> ADC3_IN9
    PF4     ------> ADC3_IN14
    PF5     ------> ADC3_IN15
    PF6     ------> ADC3_IN4
    PF9     ------> ADC3_IN7 
    */
    HAL_GPIO_DeInit(GPIOF, ADC3_IN9_Voltage_L1_Pin|ADC3_IN14_1998_Pin|ADC3_IN15_Temp_Pin|ADC3_IN4_GMI_VL1_Pin 
                          |ADC3_IN7_Current_L1_Pin);

    /* ADC3 DMA DeInit */
    HAL_DMA_DeInit(adcHandle->DMA_Handle);

    /* ADC3 interrupt Deinit */
  /* USER CODE BEGIN ADC3:ADC_IRQn disable */
    /**
    * Uncomment the line below to disable the "ADC_IRQn" interrupt
    * Be aware, disabling shared interrupt may affect other IPs
    */
    /* HAL_NVIC_DisableIRQ(ADC_IRQn); */
  /* USER CODE END ADC3:ADC_IRQn disable */

  /* USER CODE BEGIN ADC3_MspDeInit 1 */

  /* USER CODE END ADC3_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */
//------------------------------------------------------------------------------
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
    if(hadc->Instance == ADC1)
	{
		HAL_ADC_Stop_DMA(&hadc1);
		isDMAEnd_ADC1 = ON;
	}

	if(hadc->Instance == ADC2)
	{
		HAL_ADC_Stop_DMA(&hadc2);
		isDMAEnd_ADC2 = ON;
	}

	if(hadc->Instance == ADC3)
	{
		HAL_ADC_Stop_DMA(&hadc3);
		isDMAEnd_ADC3 = ON;
	}
}

//------------------------------------------------------------------------------
uint8_t filter_move_avg(MOVE_AVG_FILTER *data, uint32_t value)
{
	uint8_t result = FAIL;
	uint32_t buf = 0;

	data->buffer[data->idx_put] = value;
        if(++data->idx_put>=LIMIT_MOVE_FILTER)data->idx_put=0;

	for(int idx=0;idx<LIMIT_MOVE_FILTER;idx++)
	{
		buf += data->buffer[idx];
	}
	data->value = buf/LIMIT_MOVE_FILTER;

	return result;
}
//------------------------------------------------------------------------------
uint8_t Current_filter_move_avg(MOVE_AVG_FILTER *data, uint32_t value)
{
	uint8_t result = FAIL;
	uint32_t buf = 0;

	data->buffer[data->idx_put] = value;
        if(++data->idx_put>=CURRENT_LIMIT_MOVE_FILTER)data->idx_put=0;

	for(int idx=0;idx<CURRENT_LIMIT_MOVE_FILTER;idx++)
	{
		buf += data->buffer[idx];
	}
	data->value = buf/CURRENT_LIMIT_MOVE_FILTER;

	return result;
}


//------------------------------------------------------------------------------
uint8_t Voltage_filter_move_avg(MOVE_AVG_FILTER *data, uint32_t value)
{
	uint8_t result = FAIL;
	uint32_t buf = 0;

	data->buffer[data->idx_put] = value;
        if(++data->idx_put>=VOLTAGE_LIMIT_MOVE_FILTER)data->idx_put=0;

	for(int idx=0;idx<VOLTAGE_LIMIT_MOVE_FILTER;idx++)
	{
		buf += data->buffer[idx];
	}
	data->value = buf/VOLTAGE_LIMIT_MOVE_FILTER;

	return result;
}

//------------------------------------------------------------------------------
/*
uint16_t vRms_cal(uint16_t *data, uint16_t length)
{
    float sum = 0;
    float *buffer = (float*)malloc(sizeof(float) * length);
#ifdef MODIFY_CHECK_MALLOC_RESAULT
    if (buffer == NULL)
    {
        XP("\r\n*** MALLOC [NG] (vRms_cal: %d) ***\r\n\r\n", sizeof(float) * length);
        return HTK_U16_MAX;
    }
#endif

    uint16_t result = 0;

    uint8_t dirUp = 0;
    uint8_t idx_Cnt = 0;
    uint16_t idx_1st, idx_2nd;

    for(uint16_t idx=1 ; idx<ADC3_SAMPLE_COUNT ; idx++)
    {
        if(data[idx] > data[idx-1])
        {
            dirUp = ON;
        }

        if(dirUp)
        {
            if(data[idx] < data[idx-1])
            {
                if(idx_Cnt == 0)
                {
                    idx_1st = idx;
                }
                else
                {
                    idx_2nd = idx;
                }

                idx_Cnt++;
                dirUp = OFF;
            }
        }

        if(idx_Cnt >= 2)
          break;
    }

    if((idx_1st>=length) || (idx_2nd>=length) || (idx_2nd==0))
    {
        idx_1st = 0;
        idx_2nd = length-1;
    }

    //edward
    ADCWDGHighThreshold = data[idx_1st]-50;
    ADCWDGLowThreshold = data[idx_1st+((idx_2nd-idx_1st)/2)]+50;
    is60Hz = (((idx_2nd-idx_1st)<43)?ON:OFF);

    for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
    {
        buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
        buffer[idx-idx_1st] -= 1.65;
        buffer[idx-idx_1st] /= 0.00322; //0.00324; 誤差更多
        sum += pow(buffer[idx-idx_1st],2);
    }
    sum /= (idx_2nd-idx_1st);

    result = (uint16_t) (sqrt(sum)*100);
        
    free(buffer);
    
    return result;
}
*/
//------------------------------------------------------------------------------
uint16_t cRms_cal(uint16_t *data, uint16_t length)
{
    float sum = 0;
    float *buffer = (float*)malloc(sizeof(float) * length);

#ifdef MODIFY_CHECK_MALLOC_RESAULT
    if (buffer == NULL)
    {
        XP("\r\n*** MALLOC [NG] (cRms_cal: %d) ***\r\n\r\n", sizeof(float) * length);
        return HTK_U16_MAX;
    }
#endif
    uint16_t result = 0;

    uint8_t dirUp = 0;
    uint8_t idx_Cnt = 0;
    uint16_t idx_1st, idx_2nd;

    uint32_t Avg_offset_sum ;
    float Avg_offset ;

#ifdef MODIFY_FUNC_CRMS_CAL
    for(uint16_t idx=3 ; idx<length ; idx++)
#else
    for(uint16_t idx=3 ; idx<ADC3_SAMPLE_COUNT ; idx++)
#endif
    {

        if((data[idx] < 2148) && (data[idx] > 1948) && (dirUp == OFF))
        {
            idx_1st = idx;
            idx_Cnt++;
            dirUp = ON ;
        }

        if((idx-idx_1st)>=69)
        {
            if((data[idx] < 2148) && (data[idx] > 1948))
            {
              idx_2nd = idx;
              idx_Cnt++;
            }
        }

        if(idx_Cnt >= 2)
          break;
    }

    if((idx_1st>=length) || (idx_2nd>=length) || (idx_2nd==0) || (idx_2nd-idx_1st < 69) || (idx_2nd-idx_1st> 90))
    {
        result = adc_value.ADC3_IN7_Current_L1.value;
    }
    else
    {
        //Avg offset
        Avg_offset_sum = 0 ;
        for (uint16_t idx = idx_1st; idx < idx_2nd  ; idx++)
        {
          Avg_offset_sum += data [idx] ;
        }
        Avg_offset = (float)(Avg_offset_sum/(idx_2nd-idx_1st))*3.3/4095 ;

        for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
        {
            buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);

            if (buffer[idx-idx_1st] > Avg_offset)
                buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ;
            else
                buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ;

            buffer[idx-idx_1st] *= 51.1 ;       //  /= 0.01957;  , *= 51.1 ;
            sum += pow(buffer[idx-idx_1st],2);
        }
        sum /= (idx_2nd-idx_1st);

        result = (uint16_t) (sqrt(sum)*100);
    }
    free(buffer);

    return result;

}

/*
uint16_t cRms_cal(uint16_t *data, uint16_t length)
{
    float sum = 0;
    float *buffer = (float*)malloc(sizeof(float) * length);
    uint16_t result;
    
    //uint8_t dirUp = 0;
    //uint8_t idx_Cnt = 0;
    uint16_t idx_1st=0, idx_2nd=(length-1);

    // if the range too long, calculate all data average
    // if the range normal, calculate the normal counted data average
    
    for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
    {
        buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
        buffer[idx-idx_1st] -= 1.61;
        buffer[idx-idx_1st] /= 0.01957;
        sum += pow(buffer[idx-idx_1st],2);
    }
    sum /= (idx_2nd-idx_1st);    
    
    result = (uint16_t) (sqrt(sum)*100);
    
    free(buffer);
    
    return result;
}
*/

//------------------------------------------------------------------------------
uint16_t GFRms_cal(uint16_t *data, uint16_t length)
{
    float sum = 0;
    float *buffer = (float*)malloc(sizeof(float) * length);
#ifdef MODIFY_CHECK_MALLOC_RESAULT
    if (buffer == NULL)
    {
        XP("\r\n*** MALLOC [NG] (GFRms_cal: %d) ***\r\n\r\n", sizeof(float) * length);
        return HTK_U16_MAX;
    }
#endif
    uint16_t result = 0;

    uint8_t dirUp = 0;
    uint8_t idx_Cnt = 0;
    uint16_t idx_1st, idx_2nd;

    uint32_t Avg_offset_sum ;
    float Avg_offset ;

#ifdef MODIFY_FUNC_GFRMS_CAL
    for(uint16_t idx=2 ; idx<length ; idx++)
#else
    for(uint16_t idx=2 ; idx<ADC3_SAMPLE_COUNT ; idx++)
#endif
    {
        if((data[idx] > data[idx-1]) && (data[idx-1] > data[idx-2]))
        {
            dirUp = ON;
        }

        if(dirUp)
        {
            if((data[idx] < data[idx-1]) && (data[idx-1] < data[idx-2]))
            {
                if(idx_Cnt == 0)
                {
                    idx_1st = idx;
                }
                else
                {
                    idx_2nd = idx;
                }

                idx_Cnt++;
                dirUp = OFF;
            }
        }

        if(idx_Cnt >= 2)
          break;
    }

    if((idx_1st>=length) || (idx_2nd>=length) || (idx_2nd==0))
    {
        idx_1st = 0;
        idx_2nd = length-1;
    }

    idx_1st = 0;
    idx_2nd = length-1;

    //Avg offset
    Avg_offset_sum = 0 ;
    for (uint16_t idx = idx_1st; idx < idx_2nd  ; idx++)
    {
      Avg_offset_sum += data [idx] ;
    }
    Avg_offset = (float)(Avg_offset_sum/(idx_2nd-idx_1st))*3.3/4095 ;

    for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
    {
        buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
        if (buffer[idx-idx_1st] > Avg_offset)
          buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ;
        else
          buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ;

        buffer[idx-idx_1st] *= 1000;
        buffer[idx-idx_1st] /= 29.91;//27.21;//29.91;
        sum += pow(buffer[idx-idx_1st],2);
    }
    sum /= (idx_2nd-idx_1st);    
    
    result = (uint16_t) (sqrt(sum)*100);
    
    
    if (result > 4000)
    {
      DEBUG_INFO("Avg_offset: %f\r\n", Avg_offset);
      DEBUG_INFO("idx_1st: %d\r\n", idx_1st);
      DEBUG_INFO("idx_2nd: %d\r\n", idx_2nd);
      DEBUG_INFO("sum: %f\r\n", sum);
    }
    /*
    if((idx_2nd- idx_1st) <= 10)
    {
        //result = 0;
        idx_1st = 0;
        idx_2nd = length-1;
        
    
        for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
        {
            buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
            if (buffer[idx-idx_1st] > Avg_offset)
              buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ; 
            else  
              buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ; 
        
            buffer[idx-idx_1st] *= 1000;
            buffer[idx-idx_1st] /= 29.91;//27.21;//29.91;
            sum += pow(buffer[idx-idx_1st],2);
        }
        sum /= (idx_2nd-idx_1st);    
        
        result = (uint16_t) (sqrt(sum)*100);
    
    
    }
    else
    {
        for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
        {
            buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
            //buffer[idx-idx_1st] -= 1.65;
            if (buffer[idx-idx_1st] > Avg_offset)
              buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ; 
            else  
              buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ; 
        
            buffer[idx-idx_1st] *= 1000;
            buffer[idx-idx_1st] /= 29.91;//27.21;//29.91;
            sum += pow(buffer[idx-idx_1st],2);
        }
        sum /= (idx_2nd-idx_1st);    
        
        result = (uint16_t) (sqrt(sum)*100);
    }
    */
    free(buffer);

    return result;
}

//------------------------------------------------------------------------------
uint16_t avg_cal(uint16_t *data, uint16_t length)
{
    uint32_t result = 0;

    for(uint16_t idx=0;idx<length;idx++)
      result += data[idx];

    return (result/length);
}

//------------------------------------------------------------------------------
#ifdef FUNC_TEMP_SENSOR_WITH_NEG_VALUE
int16_t getTemperature(uint16_t adc_raw) //3438 0度 , 3376 2度
{
    int16_t rtn = (int16_t)((1526319.45/((363.15* log((8.82353*(adc_raw*3.3/4095)/ (3.3-(adc_raw*3.3/4095)))))+4203))-273.15);
    if (rtn >= -60 && rtn <= 194)
        return rtn;
    else
        return 0;

}
#else
uint16_t getTemperature(uint16_t adc_raw) //3438 0度 , 3376 2度
{
  //uint16_t beta = 4050;
  //uint16_t r0 = 10000;
  //uint16_t Rntc = (uint16_t)((r0/(1-(adc_raw/4095.0)))-r0);
  //return (uint16_t)((1/((1/298.15)+((1/(beta*1.0))*log(Rntc/10000.0)))) - 273.15);

  if (adc_raw>3438) adc_raw = 3438 ;

  return (uint16_t) ((1526319.45/((363.15* log((8.82353*(adc_raw*3.3/4095)/ (3.3-(adc_raw*3.3/4095)))))+4203))-273.15) ;
}
#endif
//--------------------------------------------------------------------------------------------------------------------
uint16_t vRms_cal2(uint16_t *data, uint16_t length)
{
    float sum = 0;

    float *buffer = (float*)malloc(sizeof(float) * length);
#ifdef MODIFY_CHECK_MALLOC_RESAULT
    if (buffer == NULL)
    {
        XP("\r\n*** MALLOC [NG] (vRms_cal2: %d) ***\r\n\r\n", sizeof(float) * length);
        return HTK_U16_MAX;
    }
#endif
    uint16_t result = 0;

    uint8_t dirUp = 0;
    uint8_t idx_Cnt = 0;
    uint16_t idx_1st, idx_2nd;

    uint32_t Avg_offset_sum ;
    float Avg_offset ;

#ifdef MODIFY_FUNC_VRMS_CAL2
    for(uint16_t idx=3 ; idx<length ; idx++)
#else
    for(uint16_t idx=3 ; idx<ADC3_SAMPLE_COUNT ; idx++)
#endif
    {

        if((data[idx] < 2148) && (data[idx] > 1948) && (dirUp == OFF))
        {
            idx_1st = idx;
            idx_Cnt++;
            dirUp = ON ;
        }

        if((idx-idx_1st)>=69)
        {
            if((data[idx] < 2148) && (data[idx] > 1948))
            {
              idx_2nd = idx;
              idx_Cnt++;
            }
        }

        if(idx_Cnt >= 2)
          break;
    }

    if((idx_1st>=length) || (idx_2nd>=length) || (idx_2nd==0) || (idx_2nd-idx_1st < 69) || (idx_2nd-idx_1st> 90))
    {
        result = adc_value.ADC3_IN9_Voltage_L1.value;
    }
    else
    {
        //edward
        ADCWDGHighThreshold = data[idx_1st]-50;
        ADCWDGLowThreshold = data[idx_1st+((idx_2nd-idx_1st)/2)]+50;
        is60Hz = (((idx_2nd-idx_1st)<43)?ON:OFF);

        //Avg offset
        Avg_offset_sum = 0 ;
        for (uint16_t idx = idx_1st; idx < idx_2nd  ; idx++)
        {
          Avg_offset_sum += data [idx] ;
        }
        Avg_offset = (float)(Avg_offset_sum/(idx_2nd-idx_1st))*3.3/4095 ;

        for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
        {
            buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
            //buffer[idx-idx_1st] -= 1.65;

            if (buffer[idx-idx_1st] > Avg_offset)
                buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ;
            else
                buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ;

            buffer[idx-idx_1st] *= 314.136 ;  // /= 0.00324;//*= 314.136 ;
            sum += pow(buffer[idx-idx_1st],2);
        }
        sum /= (idx_2nd-idx_1st);

        result = (uint16_t) (sqrt(sum)*100);
    }
    free(buffer);

    return result;
}

//------------------------------------------------------------------------------
/*
uint16_t cRms_cal2(uint16_t *data, uint16_t length)
{
    float sum = 0;
    float *buffer = (float*)malloc(sizeof(float) * length);

#ifdef MODIFY_CHECK_MALLOC_RESAULT
    if (buffer == NULL)
    {
        XP("\r\n*** MALLOC [NG] (cRms_cal2: %d) ***\r\n\r\n", sizeof(float) * length);
        return HTK_U16_MAX;
    }
#endif
    uint16_t result = 0;

    uint8_t dirUp = 0;
    uint8_t idx_Cnt = 0;
    uint16_t idx_1st, idx_2nd;

    uint32_t Avg_offset_sum ;
    float Avg_offset ;

    for(uint16_t idx=3 ; idx<ADC2_SAMPLE_COUNT ; idx++)
    {

        if((data[idx] > data[idx-1]) && (data[idx] > data[idx-2]) && (data[idx] > data[idx-3]))
        {
            dirUp = ON;
        }

        if(dirUp)
        {
            //if(data[idx] < data[idx-1])
            if((data[idx] < data[idx-1]) && (data[idx] < data[idx-2]) && (data[idx] < data[idx-3]))
            {
                if(idx_Cnt == 0)
                {
                    idx_1st = idx;
                }
                else
                {
                    idx_2nd = idx;
                }

                idx_Cnt++;
                dirUp = OFF;
            }
        }

        if(idx_Cnt >= 2)
          break;
    }

    if((idx_1st>=length) || (idx_2nd>=length) || (idx_2nd==0))
    {
        idx_1st = 0;
        idx_2nd = length-1;
    }

    //Avg offset
    Avg_offset_sum = 0 ;
    for (uint16_t idx = idx_1st; idx < idx_2nd  ; idx++)
    {
      Avg_offset_sum += data [idx] ;
    }
    Avg_offset = (float)(Avg_offset_sum/(idx_2nd-idx_1st))*3.3/4095 ;

    for(uint16_t idx=idx_1st ; idx<idx_2nd ; idx++)
    {
        buffer[idx-idx_1st] = (data[idx]/4095.0*3.3);
        //buffer[idx-idx_1st] -= 1.65;
        if (buffer[idx-idx_1st] > Avg_offset)
            buffer[idx-idx_1st] = buffer[idx-idx_1st] - Avg_offset ;
        else
            buffer[idx-idx_1st] = Avg_offset - buffer[idx-idx_1st] ;
        buffer[idx-idx_1st] /= 0.01957;
        sum += pow(buffer[idx-idx_1st],2);
    }
    sum /= (idx_2nd-idx_1st);

    result = (uint16_t) (sqrt(sum)*100);
        
    free(buffer);
    
    return result;
}
*/
//------------------------------------------------------------------------------
uint16_t RlyVmax_cal(uint16_t *data, uint16_t length)
{
    uint16_t result = 0 ;
    uint16_t idx_max_value = 0 ;

    for(uint16_t idx=3 ; idx<ADC2_SAMPLE_COUNT-3 ; idx++)
    {
        //if((data[idx] > data[idx-1]) && (data[idx] > data[idx-2]) && (data[idx] > data[idx-3]))
        if((data[idx] < data[idx-1]) && (data[idx] < data[idx-2]) && (data[idx] < data[idx-3]))
        {
            if ( data[idx] > idx_max_value)
            {
              idx_max_value = data[idx] ;
            }
        }
    }

    result = (uint16_t) (idx_max_value*100 *3.3/4095 );  //unit: 0.01V

    return result;
}

//------------------------------------------------------------------------------
uint16_t avg_v_cal(uint16_t *data, uint16_t length)
{
    uint16_t result = 0;
    uint32_t idx_max_value = 0 ;

    for(uint16_t idx=0;idx<length;idx++)
      idx_max_value += data[idx];

    result =  (uint16_t)(idx_max_value/length*100 *3.3/4095) ;

    return result;
}



/* USER CODE END 1 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
