#include "AirPressure.h"
#include "Analog_Signals.h"

_AirPressure_Struct AirPressure_F;
_AirPressure_Struct AirPressure_R;

void AirPressure_Reset(void)
{
    AirPressure_F.Value = 0;
    AirPressure_F.Valid = 0;
    AirPressure_F.Numb  = 0;
    AirPressure_F.LostT = 0;
    AirPressure_R.Value = 0;
    AirPressure_R.Valid = 0;
    AirPressure_R.Numb  = 0;
    AirPressure_R.LostT = 0;
}

void AirPressure_KL30_Init(void)
{
    AirPressure_Reset();
}

void AirPressure_KL15_ON_Init(void)
{
    AirPressure_Reset();
}

void AirPressure_Processing(uint8_t u8ADCCh, _AirPressure_Struct *AirPressure)
{
    uint8_t  i = 0;

    uint32_t u32Result = 0u;

    u32Result = ADC_Read_Signal(u8ADCCh);
    
    if (u32Result < 500)    //0.5V
    {
        if (AirPressure->LostT < 30) 
        {
            AirPressure->LostT++;
        }
        else
        {
            AirPressure->Valid = 0;
        }
    }
    else
    {
        AirPressure->LostT = 0;
        AirPressure->Valid = 1;
        
        u32Result -= 500;
        u32Result *= 100;
        u32Result /= 2721;   //*100MPa
        
        AirPressure->Buff[AirPressure->Numb] = (uint16_t)u32Result;
        
        if (++AirPressure->Numb >= 8u)
        {
            AirPressure->Numb = 0u;
            u32Result = 0;
            
            for (i=0; i<8; i++)
            {
                u32Result += AirPressure->Buff[i];
            }
            
            u32Result >>= 3;
            
            if (u32Result <= 140)
            {
                AirPressure->Value = (uint16_t)u32Result;
            }
            else
            {
                //气压大于14bar时,气压表显示上一次有效值
            } 
        }
        else
        {
            //气压表显示上一次有效值
        }
    }
}

void AirPressure_Processing_Service(void) //100mS处理一次
{
    AirPressure_Processing(ADC_CH_AIRPRESSURE_F_VOLTAGE, &AirPressure_F);
    AirPressure_Processing(ADC_CH_AIRPRESSURE_R_VOLTAGE, &AirPressure_R);
}

uint16_t AirPressure_Get_Value(uint8_t Pos)
{
    uint16_t u16Result = 0u;
    
    if (Pos == 0)
    {
        u16Result = AirPressure_F.Value;
    }
    else
    {
        u16Result = AirPressure_R.Value;
    }
    
    return u16Result;
}

uint8_t AirPressure_Get_Valid(uint8_t Pos)
{
    uint8_t u8Result = 0u;
    
    if (Pos == 0)
    {
        u8Result = AirPressure_F.Valid;
    }
    else
    {
        u8Result = AirPressure_R.Valid;
    }
    
    return u8Result;
}
