#include "soft_adc.h"
#include "common.h"
#include "main.h"
#include "stm32f4xx_hal_adc.h"

extern ADC_HandleTypeDef hadc1;
uint16_t Get_ADCChannelValue(ADC_HandleTypeDef *hadc, uint32_t channel)
{
	uint16_t temp_adc = 0;
	ADC_ChannelConfTypeDef ADC_ChanConf;

	ADC_ChanConf.Channel = channel;
	ADC_ChanConf.Rank = 1;
	ADC_ChanConf.SamplingTime = ADC_SAMPLETIME_28CYCLES;
	if (HAL_ADC_ConfigChannel(hadc, &ADC_ChanConf) != HAL_OK)
	{
		Error_Handler();
	}

    
    HAL_ADC_Start_IT(hadc);
    HAL_ADC_PollForConversion(hadc, 1);
    temp_adc = HAL_ADC_GetValue(hadc);
    HAL_ADC_Stop(hadc);

	return  temp_adc;
}


uint16_t adc_12v_buf[20] = {0};
uint16_t adc_5v_buf[20] = {0};
uint16_t adc_bms_buf[20] = {0};

void ADC_GET_DATA(void)
{   
    static uint32_t time = 0;
    static uint8_t get_count = 0;

    if(Check_Timer_Ready(&time,_20_HZ_))
    {
        
        adc_12v_buf[get_count] = Get_ADCChannelValue(&hadc1, ADC_CHANNEL_4);

		adc_5v_buf[get_count] = Get_ADCChannelValue(&hadc1, ADC_CHANNEL_8);

		adc_bms_buf[get_count] = Get_ADCChannelValue(&hadc1, ADC_CHANNEL_9);

		get_count++;
		if (get_count >= 20)
		{
			get_count = 0;
		}
    }
}

float Adc_Get(uint8_t Pin)
{
    float real_value = 0;
    switch (Pin)
    {
    case ADC_12V:
        u16t_buf_sort(adc_12v_buf, 20);

        for (uint8_t ib = 1; ib < 19; ib++)
        {
            real_value += adc_12v_buf[ib];
        }
        real_value = real_value / 4096 * 3.226f / 18 * 5.7 * 1000; // 10k 47k
        break;
    case ADC_5V:
        u16t_buf_sort(adc_5v_buf, 20);

        for (uint8_t ib = 1; ib < 19; ib++)
        {
            real_value += adc_5v_buf[ib];
        }
        real_value = real_value / 4096 * 3.226f / 18 * 2 * 1000; //10k 10k
        break;
    case ADC_Bms:
        u16t_buf_sort(adc_bms_buf, 20);

        for (uint8_t ib = 1; ib < 19; ib++)
        {
            real_value += adc_bms_buf[ib];
        }
        real_value = real_value / 4096 * 3.226f / 18 * 31 * 1000; //10k 30k  31分频
        break;

    case ADC_Tempture:
        real_value = Get_ADCChannelValue(&hadc1, ADC_CHANNEL_16);
        real_value = ( ( real_value * 3.3f / 4096 - 0.76) / 0.0025 + 25 );
        break;
    
    default:
        break;
    }

    return real_value;
}
