#include "drv_adc.h"

#include "adc_manager.h"
#include "fault_manager.h"
#include "eeprom_manager.h"
#include "hv_adc_manager.h"

#include "kit_data.h"
#include "table_comm.h"

#define MCU_REF_VOLT 3300
#define MCU_MAX_AD_VALUE 4095

#define ADC_SAMPLE_CNT 250
uint16_t adc_dma_buf[kAdcDataEnd * ADC_SAMPLE_CNT] __attribute__((section(".ccmram")));
uint32_t adc_value[kAdcDataEnd];
const AdcArray adc_array[kAdcDataEnd] =
    {
        kAdcChannel_1, kAdcSampleTime_480,  // 开关电源5v电压
        kAdcChannel_10, kAdcSampleTime_480, // T1
        kAdcChannel_11, kAdcSampleTime_480, // T2
        kAdcChannel_12, kAdcSampleTime_480, // T3
        kAdcChannel_13, kAdcSampleTime_480, // T4
        kAdcChannel_8, kAdcSampleTime_480,  // HALL1
        kAdcChannel_9, kAdcSampleTime_480,  // HALL2
};

void bms_init_adc(void)
{
    if (drv_adc_init(kAdcDev_1, adc_array, kAdcDataEnd, adc_dma_buf, ADC_SAMPLE_CNT) == false)
    {
        bms_set_fault_level(kFaultCode_Adc, kFaultLevel_Third, kFaultHandle_AlarmIdx);
    }
}

void bms_poll_adc(uint32_t base_time)
{
    uint32_t i, tmp;

    if (drv_adc_is_overflow(kAdcDev_1) == true)
    {
        drv_adc_init(kAdcDev_1, adc_array, kAdcDataEnd, adc_dma_buf, ADC_SAMPLE_CNT);
    }

    for (i = 0; i < kAdcDataEnd; i++)
    {
        tmp = kit_get_dma_avg_filter_min_max(adc_dma_buf, kAdcDataEnd, i, ADC_SAMPLE_CNT);
        switch (i)
        {
					case kAdcData_5vVolt:
						adc_value[i] = 0; // 返回电压，0.1V/bit
						break;
					case kAdcData_Temp1:
					case kAdcData_Temp2:
					case kAdcData_Temp3:
					case kAdcData_Temp4:
						tmp = tmp * 10000 / (MCU_MAX_AD_VALUE - tmp); // 返回阻值，1Ω/bit
						adc_value[i] = bms_get_linear_temp(tmp, kNtcType_CWFH708_H713);
						bms_set_en_temp((EnTemp)(i - kAdcData_Temp1), adc_value[i]);
						break;
					case kAdcData_Hall1:
					case kAdcData_Hall2:
						// 扩大100倍，
						//adc_value[i] = tmp * (4 * 100 / 3); 
							adc_value[i] = tmp * 3 / 4;//先获取电压值 
						break;
        }
    }
}

uint32_t bms_get_adc_data(AdcData idx)
{
    uint32_t tmp = 0;

    if (idx < kAdcDataEnd)
    {
        tmp = adc_value[idx];
    }

    return tmp;
}
