#include "Application.h"
#include "Data_Voltage\Data_Voltage.h"

uint8_t voltage_value = 0;
uint8_t voltage_valid = 0;
DataVoltageStruct VoltageStruct;
void Data_Voltage_Init ( void )
{
    voltage_value = 0;
    voltage_valid = 0;
    VoltageStruct.Cnt = 0;
}
void Data_Voltage_Processing_Service ( void )
{
    uint8_t voltage = 0;
    uint8_t i = 0;
    if ( Common_Get_IG_Sts() == COMMON_POWER_ON )
    {
        if(CAN_MSG_Status(&CAN_CH0_CanMsgOp, CAN_CH0_ID_CAN_0x401_Msg_Count) == CAN_SIG_LOST)
        {
            voltage_value = 0;
            voltage_valid = 0;
            VoltageStruct.Cnt = 0;
        }
        else
        {
            if(voltage_valid == 0)
            {
                voltage_value = Get_CAN_CH0_ID_401_Sig_ECU_Battery_Voltage();
                voltage_valid = 1;
            }
            else
            {
                voltage_valid = 1;
                VoltageStruct.Buffer[VoltageStruct.Cnt] = Get_CAN_CH0_ID_401_Sig_ECU_Battery_Voltage();
                i = VoltageStruct.Cnt;
                while ((i > 0) && (VoltageStruct.Buffer[i] < VoltageStruct.Buffer[i - 1]))
                {
                    voltage = VoltageStruct.Buffer[i];
                    VoltageStruct.Buffer[i] = VoltageStruct.Buffer[i - 1];
                    VoltageStruct.Buffer[i - 1] = voltage;
                    i --;
                }
                VoltageStruct.Cnt ++ ;
                if (VoltageStruct.Cnt >= 30)
                {
                    VoltageStruct.Cnt = 0;
                    voltage_value = (VoltageStruct.Buffer[14] + VoltageStruct.Buffer[15] + VoltageStruct.Buffer[16]) / 3;
                }
            }
           
        }
    }
    else
    {
        voltage_value = 0;
        voltage_valid = 0;
    }
    
}

//10倍
uint8_t Get_Battery_Voltage(void)
{
    return voltage_value;
}
uint8_t Get_Battery_Voltage_Valid(void)
{
    return voltage_valid;
}