#include "Data_SOC.h"
#include "CAN_Communication_Matrix.h"
#include "Communication_Over_CAN.h"
#include "Common_Interface.h"

uint16_t SOC_DesVal;
uint16_t SOC_CurVal;
uint16_t SOC_Valid;

void SOC_Reset(void)
{
    SOC_DesVal = 0;
    SOC_CurVal = 0;
    SOC_Valid  = 0;
}

void SOC_KL30_Init(void)
{
    SOC_Reset();
}

void SOC_KL15_ON_Init(void)
{
    SOC_Reset();
}

void SOC_Processing_Service(void)
{
    if (Common_Get_IG_Sts() == 1u)
    {
        uint8_t  dist   = 7u;
        uint32_t OnTime = Common_GetIgnOnTime(); 
    
        if (OnTime <= 4000u)    //上电<3秒
        {
            SOC_Valid = 0u;
            dist = 14u;
            
            if (OnTime <= 2000u)
            { 
                SOC_DesVal = 1000u;
            }
            else
            {
                SOC_DesVal = 0u;
            }
        }
        else
        {
            if (OnTime <= 6000u)
            {
                dist = 28u;
            }
            
            uint32_t u32Result = Get_ID_18F13DF3_Sig_BMS_BtySOC();
            
            if ((u32Result >= 0xFFFE) || (CAN_MSG_Status(ID_BMS_BMSSts_Msg_Count) != CAN_SIG_RECEIVE))
            {
                SOC_Valid = 0;
                u32Result = 0;
            }
            else
            {
                SOC_Valid = 1;
            }

            u32Result <<= 2u; //*4;

            if (u32Result > 1000) 
            {
                u32Result = 1000;
            }
            
            SOC_DesVal = (uint16_t)u32Result;
        }
        //阻尼
        if (SOC_CurVal < SOC_DesVal)
        {
            SOC_CurVal += dist;

            if (SOC_CurVal > SOC_DesVal)
            {
                SOC_CurVal = SOC_DesVal;
            }
        }
        else if (SOC_CurVal != SOC_DesVal)
        {
            if (SOC_CurVal >= dist)
            {
                SOC_CurVal -= dist;
            }
            else
            {
                SOC_CurVal = SOC_DesVal;
            }
        }
    }
    else
    {
        SOC_Reset();
    }
}

uint16_t SOC_Get_DesVal(void)
{
    return SOC_DesVal;
}

uint16_t SOC_Get_CurVal(void)
{
    return SOC_CurVal;
}

uint8_t SOC_Get_Valid(void)
{
    return SOC_Valid;
}
