#define  GLOBALS_VARIABLE
#include "common_include.h"

#define __MAIN_BOARD  1
#if __MAIN_BOARD
uint8_t  main_board_flag =1;
#else
uint8_t  main_board_flag =0;
#endif

#ifdef __DEBUG_CODE_IN_SYSRAM
#define SYSRAM_ECC_CLEAR_SIZE_BYTE  0
#else
#define SYSRAM_ECC_CLEAR_SIZE_BYTE  SYSRAM_SIZE_BYTE
#endif
#ifdef __DEBUG_CODE_IN_TCMRAM
#define TCMRAM_ECC_CLEAR_SIZE_BYTE  0
#else
#define TCMRAM_ECC_CLEAR_SIZE_BYTE  TCMRAM_SIZE_BYTE
#endif

#define  SYSRAM_BACKUP_RAM_SIZE     0x0400//0//

uint8_t g_runStep;
#define STAGE_TASK      0
#define IIC_TASK        1     
#define GET_TASK        2
#define TFT_TASK        3

const   stc_clear_ecc_memories_t    Start_stcClearEccMemories   ={  .u32SysRamStartAddress  =   (SYSRAM_START_ADDRESS + SYSRAM_BACKUP_RAM_SIZE),
.u32SysRamSizeByte      =   (SYSRAM_ECC_CLEAR_SIZE_BYTE - SYSRAM_BACKUP_RAM_SIZE),
.u32TcmRamStartAddress  =   TCMRAM_AXI_START_ADDRESS,
.u32TcmRamSizeByte      =   TCMRAM_ECC_CLEAR_SIZE_BYTE
};


extern DATA_SAVE_PACK NewData;

uint32_t CheckGearTimerCnts = 0;
uint8_t LastCheckGear = 0xFF;

uint8_t ADFlag;

/*add for 3360*/
uint8_t Test_array[1000];
uint8_t Test_array_Uart9[10000];
#define SAMPLE_UART_TX_BUFFSIZE         (1024)
#define SAMPLE_UART_RX_BUFFSIZE         (1024)

static uint8_t au8UartTxBuf[SAMPLE_UART_TX_BUFFSIZE];   // TX buffer
static uint8_t au8UartRxBuf[SAMPLE_UART_RX_BUFFSIZE];   // RX buffer


uint32_t WriteCount = 0;;
uint32_t Time_100us = 0;
uint8_t Uart_Pro_Flag = 0;
uint32_t WriteCount_Uart9 = 0;;
uint32_t Time_100us_Uart9 = 0;
uint8_t Uart_Pro_Flag_Uart9 = 0;
uint8_t BarcodePartNumOffect = 0;
uint8_t Flag_CheckBarcode = 0;


uint8_t CheckClusterValid = 0;//У���Ǳ��ͺű�־λ   0 �Ǳ�δ������ʾ������Ǳ�  1 �Ǳ�����������ʾ��������
uint8_t GearValid = 0;
uint8_t VIN_NumberBuf[10] = {0}; 
uint8_t VIN_Count;
uint8_t Flag_SetTime = 0;
uint8_t DateTimeDay = 1;
uint8_t DateTimeMonth = 1;
uint8_t DateTimeYear1 = 1;
uint8_t DateTimeYear = 1;
uint32_t CheckStep = 0;
uint8_t CheckResult[53] = {0};
uint8_t Flag_DisplayErr = 0;
uint32_t DisplayErrTimer = 0;
#if (PRO_KS)
#if (KS_LOCAL)
uint8_t  g_UI_Language = UI_CHINESE;//������ʾ����,Ĭ������  0���� 1 Ӣ��
#else
uint8_t  g_UI_Language = UI_ENGLISH;//������ʾ����,Ĭ������  0���� 1 Ӣ��
#endif
#else
uint8_t  g_UI_Language = UI_CHINESE;//������ʾ����,Ĭ������  0���� 1 Ӣ��
#endif
uint8_t  g_UI_SWHW = 0;//��ʾС�汾��
uint8_t StartBuf[5] = {0, 1, 2, 3, 4}; 
uint8_t EndBuf[8] = {7, 6, 5, 4, 3, 2, 1, 0}; 
uint8_t Flag = 0; 

uint8_t BarcodeErr = 0;

#if (NOBARCODE_CHECK) 
uint8_t CheckBarcode = 0;//����ʾɨ��ά��
#else
uint8_t CheckBarcode = 1;//��ʾɨ��ά��
#endif
uint8_t SetTimeState = 0;
uint8_t SetCheckStationBarcodeCnts = 0;
uint8_t PartNum_AssemblyWorkshop[16] = {0};
uint32_t ClusterID = 0;
uint32_t BarcodeDate = 0;
uint8_t SerialNumber[4] = {0};
uint8_t Flag_BarcodeErr = 0;
uint8_t tmpPartNum_AssemblyWorkshop[16] = {0};
uint32_t tmpClusterID = 0;
uint32_t tmpBarcodeDate = 0;
uint8_t tmpSerialNumber[4] = {0};
uint8_t Flag_QRcodeReady = 0;
uint8_t SetClusterState = 3;
uint32_t CluClusterID = 0;
uint32_t CluBarcodeDate = 0;
uint8_t CluSerialNumber[4] = {0};
uint8_t CluWriteCompleteFlag[8] = {0};
uint8_t Button_Value_Slave;
uint8_t Button_Slave_Receive_Flag;
uint8_t g_uiQueryState = ST_INIT;

en_port_gpio_level_t g_TestLevel;
en_port_gpio_level_t g_TestLevelC;
//en_port_gpio_level_t g_TestLevel1;
//en_port_gpio_level_t g_TestLevel2;
//en_port_gpio_level_t g_TestLevel3;
uint8_t MPHTimeFlage = 0;
extern uint8_t g_uiTftIdx;
uint32_t TpTaskTimerCnts = 0;
extern uint8_t g_PressTimeSecond;
uint8_t g_uiDebugBarcode = 0;
uint8_t g_TestCluPartNum[16] = {0};
uint8_t g_CompileDateTime[32];
extern uint16_t g_CAN_SEND_ID;
extern uint16_t g_CAN_RECV_ID;
uint8_t g_UartBuffer_RX[64];
uint8_t g_UartBuffer_TX[64];
uint8_t g_uiCheckResultSaveFlag = 0;
uint8_t g_SpeedUpflag = 0;
uint8_t g_SpeedDownflag = 0;

enum{
 PACKAGE_TYPE_HEART,
 PACKAGE_TYPE_QR,
};
void SendQR(uint8_t *data, uint8_t len);

static void Uart0_RX_Callback(uint16_t u16FillCnt)
{
    uint16_t u16ReadCnt;
    
    Mfs_Uart_Read(UART11_Type, Test_array + WriteCount, &u16ReadCnt, SAMPLE_UART_RX_BUFFSIZE, TRUE);
    Time_100us = 0;
    Uart_Pro_Flag = 1;
    WriteCount += u16ReadCnt;

}       

static void Uart9_RX_Callback(uint16_t u16FillCnt)
{
    uint16_t u16ReadCnt;
    
    Mfs_Uart_Read(UART9_Type, Test_array_Uart9 + WriteCount_Uart9, &u16ReadCnt, SAMPLE_UART_RX_BUFFSIZE, FALSE);
    Time_100us_Uart9 = 0;
    Uart_Pro_Flag_Uart9 = 1;
    WriteCount_Uart9 += u16ReadCnt;
}       

static void UART_PORT_init(void)
{
    stc_port_pin_config_t PpcConf = { PortOutputResourceGPIO };
    
    // Port initialize
    // SIN0 (P84)
    Port_SelectInputPort( &RIC.unRESIN0, PortInputPortA );
    stc_input_resource_set_t SIN0 = 
    {
        .punRicResinReg = &RIC.unRESIN0,
        .enInputPort = PortInputPortA,
    };
    Port_ConfigureInputResources(&SIN0, 1);
    PpcConf.bInputEnable = TRUE;
    PpcConf.bNoiseFilterEnable = FALSE;
    PpcConf.enGpioDirection = PortGpioInput;
    PpcConf.enInputLevel = PortInputLevelCmosA;
    PpcConf.enOutputDrive = PortOutputDriveA;
    PpcConf.enOutputFunction = PortOutputResourceGPIO;
    PpcConf.enPullResistor = PortPullResistorUp;
    PpcConf.enGpioInitOutputLevel = PortGpioHigh;
    Port_SetPinConfig(1, 29, &PpcConf);
    
    // SOT0_0 (P82)
    PpcConf.bInputEnable = FALSE;
    PpcConf.bNoiseFilterEnable = FALSE;
    PpcConf.enGpioDirection = PortGpioOutput;
    PpcConf.enInputLevel = PortInputLevelCmosA;
    PpcConf.enOutputDrive = PortOutputDriveD;
    PpcConf.enOutputFunction = PortOutputResourceB;
    PpcConf.enPullResistor = PortPullResistorNone;
    PpcConf.enGpioInitOutputLevel = PortGpioHigh;
    Port_SetPinConfig(1, 27, &PpcConf);
    //Port_EnableInput();
    
    
    // Port initialize
    // SIN2 (P21)
    // Port_SelectInputPort( &RIC.unRESIN63, PortInputPortA );
    // stc_input_resource_set_t SIN63 = 
    // {
    //     .punRicResinReg = &RIC.unRESIN63,
    //     .enInputPort = PortInputPortC,
    // };
    // Port_ConfigureInputResources(&SIN63, 1);
    // PpcConf.bInputEnable = TRUE;
    // PpcConf.bNoiseFilterEnable = FALSE;
    // PpcConf.enGpioDirection = PortGpioInput;
    // PpcConf.enInputLevel = PortInputLevelCmosA;
    // PpcConf.enOutputDrive = PortOutputDriveA;
    // PpcConf.enOutputFunction = PortOutputResourceGPIO;
    // PpcConf.enPullResistor = PortPullResistorUp;
    // PpcConf.enGpioInitOutputLevel = PortGpioHigh;
    // Port_SetPinConfig(0, 15, &PpcConf);
    
    // // SOT2 (P19)
    // PpcConf.bInputEnable = FALSE;
    // PpcConf.bNoiseFilterEnable = FALSE;
    // PpcConf.enGpioDirection = PortGpioOutput;
    // PpcConf.enInputLevel = PortInputLevelCmosA;
    // PpcConf.enOutputDrive = PortOutputDriveD;
    // PpcConf.enOutputFunction = PortOutputResourceF;
    // PpcConf.enPullResistor = PortPullResistorNone;
    // PpcConf.enGpioInitOutputLevel = PortGpioHigh;
    // Port_SetPinConfig(0, 13, &PpcConf);


}

static void UART_init(void)
{
    stc_uart_config_t stcUartConf = { 0 };
    // Uart configuration
    stcUartConf.u32DataRate = 115200;                              // baurate = 2000000 bps
    stcUartConf.bHardwareFlow = FALSE;                              // Not use hardware flow control
    stcUartConf.bTransferDirecton = FALSE;                          // LSB first
    stcUartConf.enDataFormat = UartFormatNRZ;                       // NRZ format
    stcUartConf.enDataLength = UartLength8Bits;                     // 8bit length
    stcUartConf.enParity = UartParityNone;                          // No parity
    stcUartConf.enStopBit= UartOneStopBit;                          // 1 stop bit
    stcUartConf.u16TxBufSize = SAMPLE_UART_TX_BUFFSIZE;             // Set buffer size
    stcUartConf.pu8TxBuf = au8UartTxBuf;                            // Set buffer pointer
    stcUartConf.u16RxBufSize = SAMPLE_UART_RX_BUFFSIZE;             // Set buffer size
    stcUartConf.pu8RxBuf = au8UartRxBuf;                            // Set buffer pointer
    stcUartConf.bFifoUsage = TRUE;                                  // use HW FIFO
    stcUartConf.u16RxCbFillLevel = 1;                               // Unread counts of data buffer to call RX Callback function
    stcUartConf.pfnRxCb = Uart0_RX_Callback;                        // Rx callback not used
    stcUartConf.pfnTxCb = NULL;                                     // Tx callback not used
    Mfs_Uart_Init(UART11_Type, &stcUartConf);
    // Uart configuration
    // stcUartConf.u32DataRate = 4800;                              // baurate = 2000000 bps
    // stcUartConf.bHardwareFlow = FALSE;                              // Not use hardware flow control
    // stcUartConf.bTransferDirecton = FALSE;                          // LSB first
    // stcUartConf.enDataFormat = UartFormatNRZ;                       // NRZ format
    // stcUartConf.enDataLength = UartLength8Bits;                     // 8bit length
    // stcUartConf.enParity = UartParityNone;                          // No parity
    // stcUartConf.enStopBit= UartOneStopBit;                          // 1 stop bit
    // stcUartConf.u16TxBufSize = SAMPLE_UART_TX_BUFFSIZE;             // Set buffer size
    // stcUartConf.pu8TxBuf = au8UartTxBuf;                            // Set buffer pointer
    // stcUartConf.u16RxBufSize = SAMPLE_UART_RX_BUFFSIZE;             // Set buffer size
    // stcUartConf.pu8RxBuf = au8UartRxBuf;                            // Set buffer pointer
    // stcUartConf.bFifoUsage = TRUE;                                  // use HW FIFO
    // stcUartConf.u16RxCbFillLevel = 1;                               // Unread counts of data buffer to call RX Callback function
    // stcUartConf.pfnRxCb = Uart9_RX_Callback;                        // Rx callback not used
    // stcUartConf.pfnTxCb = NULL;                                     // Tx callback not used
    // Mfs_Uart_Init(UART9_Type, &stcUartConf);




}

static uint32_t StringToUintHex(uint8_t *date, uint8_t length)
{
    uint8_t i = 0;
    uint8_t j = 0;
    uint32_t tmp = 0;
    uint32_t tmp1 = 0;
    
    for(i = 0; i < length; i++)
    {
        if((date[i] >= '0') && (date[i] <= '9'))
        {
            tmp = date[i] - '0';
        }
        else if((date[i] >= 'a') && (date[i] <= 'f'))
        {
            tmp = date[i] - 'a' + 9u;
        }
        else if((date[i] >= 'A') && (date[i] <= 'F'))
        {
            tmp = date[i] - 'A' + 9u;
        }
        for(j = 1; j < (length - i); j++)
        {
            tmp = tmp * 16u;
        }
        tmp1 += tmp;
    }
    
    return tmp1;
}

static uint32_t StringToUint(uint8_t *date, uint8_t length)
{
    uint8_t i = 0;
    uint8_t j = 0;
    uint32_t tmp = 0;
    uint32_t tmp1 = 0;
    
    for(i = 0; i < length; i++)
    {
        if((date[i] >= '0') && (date[i] <= '9'))
        {
            tmp = date[i] - '0';
            for(j = 1; j < (length - i); j++)
            {
                tmp = tmp * 10u;
            }
            tmp1 += tmp;
        }
    }
    
    return tmp1;
}

static void AnalysisQRcode(uint8_t *QRcode,uint8_t *pPartNum,uint32_t *pBarcodeDate,uint8_t *pSerialNumber,uint32_t *pClusterID)
{
    uint8_t i = 0;
    uint8_t j = 0;
    for(i = 0; QRcode[i] != 0xD; i++)
    {
        if(QRcode[i] == 0x1D && QRcode[i + 1] == 'P')
        {
            i += 2u;
            memcpy((void *)&pPartNum[0], (void *)(QRcode + i), 10u);
            i += 10u;
        }
        else if(QRcode[i] == 0x1D && QRcode[i + 1] == 'T')
        {
            i += 2u;
            *pBarcodeDate = StringToUint((uint8_t *)(QRcode + i), 6u);
            i += 6u;
            memcpy((void *)&pSerialNumber[0], (void *)(QRcode + i), 4u);
            i += 4u;
            
            for(j = i; QRcode[j] != 0x1D; j++)
            {
            }
            if(j - i > 7)
            {
                *pClusterID = StringToUint((uint8_t *)(QRcode + i), 8u);
            }
            else
            {
                *pClusterID = StringToUint((uint8_t *)(QRcode + i), 7u);
            }
            i = j;
        }
    }
}

static void handle_receive_uart9(void)
{
    uint8_t ret;
    if(Uart_Pro_Flag_Uart9 == 1 && Time_100us_Uart9 >= 200)  
    {
        Uart_Pro_Flag_Uart9 = 0;
        if ((Test_array_Uart9[0]==0xFF) && (Test_array_Uart9[1]==0x1)&&(Test_array_Uart9[2]==0x1)&&(Test_array_Uart9[3]==0x1))
        {
            ret = Calc_Checksum(Test_array_Uart9, 4);
            if (ret==Test_array_Uart9[4])
            {
                uart_send_count=0;
                start_uart_timer=0;
                uart_send_flag=0;
                Button_Press=0;
            }
        }
    }
    if(Time_100us_Uart9 >= 10000)
    {
        WriteCount_Uart9 = 0;
    }
}

uint8_t g_QrCodeTraceFlag = QR_CODE_TRACE_FLAG;

void handle_receive_uart()
{
    uint8_t ret;
#if (PRO_CONFIG_CHECK_APPLY)    
    if(Uart_Pro_Flag == 1 && Time_100us >= 200)  
    {
        Uart_Pro_Flag=0;
        
        if (CheckBarcode == 1)
        {
#if (FALSE_CONFIG)
            CheckBarcode = 0;
            g_Stage = 0;
            CANSendEnable = ON;
#else
#if (PRO_US4)
            if(g_VehicleType == CAR_TYPE_ICV) {
                CheckBarcode = 0;
                g_Stage = 0;
                CANSendEnable = ON;
            }
            else if(g_VehicleType == CAR_TYPE_HEV)
            {
                AnalysisQRcode(Test_array,tmpPartNum_AssemblyWorkshop,&tmpBarcodeDate,tmpSerialNumber,&tmpClusterID);
                if((memcmp(CluPartNum, tmpPartNum_AssemblyWorkshop, 10) == 0)
                && (CluClusterID == (tmpClusterID % 10000))
                && (CluBarcodeDate == tmpBarcodeDate))
                {
                    g_uiQrQueryTimer = 1000;
                    SendQR(Test_array,strlen(Test_array));
                } else {
                    CheckBarcode = 1;
                    BarcodeErr = 1;
                    g_uiQueryState = ST_INIT;
                }
            }
#else
            AnalysisQRcode(Test_array,tmpPartNum_AssemblyWorkshop,&tmpBarcodeDate,tmpSerialNumber,&tmpClusterID);
#if 1            
            if((memcmp(CluPartNum, tmpPartNum_AssemblyWorkshop, 10) == 0)
              && (CluClusterID == (tmpClusterID % 10000))
              && (CluBarcodeDate == tmpBarcodeDate))  
#else
            if (1)
#endif              
            {
                g_uiQrQueryTimer = 1000;
                SendQR(Test_array,strlen(Test_array));
            } else {
                CheckBarcode = 1;
                BarcodeErr = 1;
                g_uiQueryState = ST_INIT;
            }
#endif   
            
#endif   
        }
        WriteCount = 0;
    }
    if(Time_100us >= 10000)
    {
        WriteCount = 0;
        //CheckBarcode = 1;
    }

    if (g_uiQrQueryTimer > 0) {
        if (QR_CODE_TRACE_FLAG == 0) {//Ĭ�ϲ���������׷�ݹ���
            g_uiQueryState = ST_SUCC;
        }
              
        if (g_uiQueryState == ST_SUCC) {
            CheckBarcode = 0;
            BarcodeErr = 0;
            g_Stage = 0;
            CANSendEnable = ON;
        }
    } else {
        if (g_uiQueryState == ST_QUERY) {
            g_uiQueryState = ST_NCK;
        }
    }
#endif
#if (PRO_CONFIG_SCAN_APPLY)
	if(Uart_Pro_Flag == 1 && Time_100us >= 200)  
	{
		Uart_Pro_Flag=0;
                
		if(CheckBarcode == 0)
		{
			CheckBarcode = 1;
			if(memcmp(StartBuf, Test_array, 8) == 0)
			{
				//CheckBarcode = 1;
			}
		}
		else if(Flag_CheckBarcode == 0)
		{
			
		}
		else
		{
			if(Flag_SetTime == 1)
			{
				if(SetCheckStationBarcodeCnts == 0)
				{
					AnalysisQRcode(Test_array,PartNum_AssemblyWorkshop,&BarcodeDate,SerialNumber,&ClusterID);
					SetCheckStationBarcodeCnts++;
				}
				else
				{
					AnalysisQRcode(Test_array,tmpPartNum_AssemblyWorkshop,&tmpBarcodeDate,tmpSerialNumber,&tmpClusterID);
					if((memcmp(PartNum_AssemblyWorkshop, tmpPartNum_AssemblyWorkshop, 10) == 0))
					//&& (ClusterID == tmpClusterID)
					//&& (BarcodeDate == tmpBarcodeDate)
					//&& (memcmp(tmpSerialNumber, SerialNumber, 4) == 0))
					{
						SetCheckStationBarcodeCnts++;
					}
					else
					{
						SetCheckStationBarcodeCnts = 0;
						Flag_BarcodeErr = 1;
					}
					if(SetCheckStationBarcodeCnts >= 5)
					{
						Flag_BarcodeErr = 0;
						Flag_SetTime = 0;
						SaveAFCValid = 1;
					}
				}
			}
			else if ((CheckClusterValid == 1u) && (Flag_QRcodeReady == 0))
			{
				AnalysisQRcode(Test_array,tmpPartNum_AssemblyWorkshop,&tmpBarcodeDate,tmpSerialNumber,&tmpClusterID);
				Flag_QRcodeReady = 1;
			}
		}
		WriteCount = 0;
	}
	if(Time_100us >= 10000)
	{
		WriteCount = 0;
		CheckBarcode = 1;
	}
#endif
}   

static void handle_receive_uart9_slave(void)
{
    uint8_t ret;
    if(Uart_Pro_Flag_Uart9 == 1 && Time_100us_Uart9 >= 200)  
    {
        Uart_Pro_Flag_Uart9 = 0;
        if ((Test_array_Uart9[0]==0xFF) && (Test_array_Uart9[1]==0x1)&&(Test_array_Uart9[2]==0x1))
        {
            ret = Calc_Checksum(Test_array_Uart9, 4);
            if (ret==Test_array_Uart9[4])
            {
                Button_Value_Slave = Test_array_Uart9[3];
                Button_Slave_Receive_Flag = 1;
            }
        }
    }
    if(Time_100us_Uart9 >= 10000)
    {
        WriteCount_Uart9 = 0;
    }
}

void handle_receive_uart_slave()
{
#if 0
    uint8_t ret;
    
    if(Uart_Pro_Flag == 1 && Time_100us >= 200)  
    {
        Uart_Pro_Flag=0;
        
        
        if(CheckBarcode == 0)
        {
            CheckBarcode = 1;
            if(memcmp(StartBuf, Test_array, 8) == 0)
            {
                NoBarcode = 1;
            }
        }
        else if(Flag_CheckBarcode == 0)
        {
        }
        else
        {
            AnalysisQRcodeTmp(Test_array);
            if((memcmp(CluPartNum, tmpPartNum_AssemblyWorkshop, 10) == 0)
               && (CluClusterID == (tmpClusterID % 10000))
                   && (CluBarcodeDate == tmpBarcodeDate)
                       && (CluWriteCompleteFlag[0] == 0x11) && (CluWriteCompleteFlag[1] == 0x22) && (CluWriteCompleteFlag[2] == 0x33) && (CluWriteCompleteFlag[3] == 0x44)
                           && (CluWriteCompleteFlag[4] == 0x55) && (CluWriteCompleteFlag[5] == 0x66) && (CluWriteCompleteFlag[6] == 0x77) && (CluWriteCompleteFlag[7] == 0x88))
            {
                Botton.TFTDown.Flag = 0;
                Flag_CheckBarcode = 0;
                Button_Value = 18;
                Button_Press= 1;
                g_Stage = 0;
                TFTCurrent.count = 0;
                CheckClusterValid = 1;
            }
            else
            {
                BarcodeErr = 1;
            }
        }
        WriteCount = 0;
    }
    if(Time_100us >= 10000)
    {
        WriteCount = 0;
        CheckBarcode = 1;
    }
#endif    
}

void DearCheck (uint8_t Dear)
{
    GET_BUTTON_S_LEVEL;
    GET_BUTTON_D_LEVEL;
    GET_BUTTON_N_LEVEL;
    GET_BUTTON_R_LEVEL;
    GET_BUTTON_P_LEVEL;
    GearValid = 0xff;
    if (LastCheckGear != Dear) {
        CheckGearTimerCnts = Timer1msCnts;
    }
    LastCheckGear = Dear;
    if (BUTTON_S_IN == 1 && BUTTON_D_IN == 0 && BUTTON_N_IN == 0 && BUTTON_R_IN == 0 && BUTTON_P_IN == 0 && Dear == 4) {
        GearValid = 5;
    } else if (BUTTON_S_IN == 0 && BUTTON_D_IN == 1 && BUTTON_N_IN == 0 && BUTTON_R_IN == 0 && BUTTON_P_IN == 0 && Dear == 5) {
        GearValid = 4;
    } else if (BUTTON_S_IN == 0 && BUTTON_D_IN == 0 && BUTTON_N_IN == 1 && BUTTON_R_IN == 0 && BUTTON_P_IN == 0 && Dear == 6) {
        GearValid = 3;
    } else if (BUTTON_S_IN == 0 && BUTTON_D_IN == 0 && BUTTON_N_IN == 0 && BUTTON_R_IN == 1 && BUTTON_P_IN == 0 && Dear == 7) {
        GearValid = 2;
    } else if (BUTTON_S_IN == 0 && BUTTON_D_IN == 0 && BUTTON_N_IN == 0 && BUTTON_R_IN == 0 && BUTTON_P_IN == 1 && Dear == 0) {
        GearValid = 1;
    } else {
        if (CheckGearTimerCnts + 800 < Timer1msCnts) {
            GearValid = 0;
        }
    }
    
    if (GearValid == 0) {  //2000ms
        Buzzer_Alarm();
        Err_Status = 1;
    } else if (GearValid != 0xff) {
        Err_Status = 0;
    }
    
}

#define CanSendCan2_TpMsg(id, Signal, Len, isClear)\
{\
  CanFD_Send_StandMsg(CANFD2_Type, id, BUF_41, TX_ISR_EN, (uint8_t *)&Signal, Len);\
    if(1 == isClear)\
      Can_Clear((uint8_t *)&Signal, sizeof(Signal));\
}

void BenchTpSendMessageToCan(uint32_t ID, uint8_t *data, uint8_t len)
{
    CanSendCan2_TpMsg(ID, data[0], len, 1);
}

uint8_t SendQRData[128];
uint8_t SendQRLen = 0;
uint8_t QRCheckValidSt = 0;
static uint32_t QRCheckTimerCnts = 0;
void QRCheckService(uint32_t TimerCnts)
{
    uint32_t delta = 0;
    if (TimerCnts > QRCheckTimerCnts) {
        delta = TimerCnts - QRCheckTimerCnts;
        QRCheckTimerCnts = TimerCnts;
        if (QRCheckTimerCnts > delta) {
            QRCheckTimerCnts -= delta;
        } else {
            if (QRCheckTimerCnts != 0) {
                QRCheckTimerCnts = 0;
                QRCheckValidSt = 0;
            }
        }
    }
}

void SendQR(uint8_t *data, uint8_t len)
{
    if (len <= sizeof (SendQRData)) {
        QRCheckValidSt = 0;
        SendQRData[0] = PACKAGE_TYPE_QR;
        SendQRData[1] = 0x00;//Reserved
        SendQRData[2] = 0x00;//Reserved
        SendQRData[3] = 0x00;//Reserved

        
        memcpy(SendQRData + 4, data, len);

        SendQRLen = 4 + len;
        BenchTpTxData(BenchTpPduId0, SendQRData, SendQRLen);
        g_uiQueryState = ST_QUERY;
    }
}

void SendHeart(uint8_t *data, uint8_t len)
{
    if (len <= sizeof (SendQRData)) {
        BenchTpTxData(BenchTpPduId0, data, len);
    }
}

void BenchTpDataProc(uint8_t *data, uint32_t len)
{
    if (data[0] == PACKAGE_TYPE_HEART) {//��λ������������ 
        //���̨�ظ�������Ӧ
        SendHeart(data,len);
    } else if (data[0] == PACKAGE_TYPE_QR){//��λ�����������ѯ���
        if (len == (SendQRLen + 1)) {
            QRCheckValidSt = (memcmp(SendQRData, data, SendQRLen) == 0);
            QRCheckValidSt &= (data[SendQRLen] == 1);
            if (QRCheckValidSt != 0) {
                QRCheckTimerCnts = 0;
                g_uiQueryState = ST_SUCC;
            } else {
                g_uiQueryState = ST_FAIL;
            }
        }
    } else {//��λ������������δ֪

    }
}

void Init_Load_data(void)
{
    /*-----EEPROM��-----*/
    NewData.Head1 = 0x5A;
    NewData.Head2 = 0xA5;
    NewData.Tail  = 0xFF;
    SaveState    = 1;
    OldSaveState = 0;
    /*-----EEPROM��-----*/
}

void CANInit(void)
{
    InitCanRecvModule();
#if (CAN_2ND || CAN_2P5)
    memset(&CanFDDataStruct, 0, sizeof (CanFDDataStruct));
    memset(&MMCanDataStruct, 0, sizeof (MMCanDataStruct));
    bsp_CAN0_Init();
    bsp_CAN1_Init();

#if (HARD_WARE_VERSION_2_1_7)
    SetCan0Mode(1);   
    SetCan1Mode(0);
#endif
#if (HARD_WARE_VERSION_2_2_0)
    SetCan0Mode(0);   
    SetCan1Mode(0);
#endif
#endif
    
#if (CAN_3RD)
    Can1_Init();
    CanCRCInint();
    bsp_CAN0_Init();
    bsp_CAN1_Init();

#if (HARD_WARE_VERSION_2_1_7)
    SetCan0Mode(1);   
    SetCan1Mode(1);
#endif
#if (HARD_WARE_VERSION_2_2_0)
    SetCan0Mode(0);   
    SetCan1Mode(0);
#endif       
#endif
    bsp_CAN2_Init();
}

  void main(void)
{

    Start_Init();

    Api_GPIO_Init();
        UART_PORT_init();
    UART_init();
    TIMER_50us_Init();
    TIMER_100us_Init();
    TIMER1_1ms_Init();
    TIMER_10ms_Init();
    // ADCInit();
    ICU_IO_Initialize();
    // CANInit();
    Init_Pwm();
#if (PRO_JAPE2)
    
#endif
    InitDiagnostic();//UDS
    Port_EnableInput();
    bsp_BD8379_Init();
    LCD_BUS_Init();
    LCD_Panel_Start_Up();
    Init_Load_data();
    IRQ_ENABLE();
    ReadDataFormWorkFlash();
    BenchTpInit(0x002);
    
    // CANSendEnable = ON;
    //  MC1413_IGNON;
    //  MC1413_BON;
     //MC1413_B_OFF;
    //  bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData);
#if (HARD_WARE_VERSION_2_2_0)
    LampState_M.Lamps.FB_K2 = 1;
#endif
    bsp_Save_Check_Service(1);//��ȡ�������������
    Diaplay_test  = NewData.Data1;
#if (PRO_KS)
#else
    g_UI_Language = NewData.Data2;
#endif
    g_UI_SWHW = NewData.Data3;
    // UART_PORT_init();
    // UART_init();
    HU_USM_E_04.CF_AVN_CluVoiceVolume = 0x3;
    BarcodePartNumOffect = 14;
    // Mfs_Uart_Write(UART0_Type, StartBuf, 8, TRUE);
    
#if (PRO_CONFIG_EOL_APPLY)
    SetDspCfg();
#endif
    g_uiCheckResultSaveFlag = 0;
    memset(&g_stCheckResult,0,sizeof(g_stCheckResult));
#if ((PRO_CONFIG_CHECK_APPLY) || (PRO_CONFIG_EOL_APPLY))
    for(;;)
    {

        RS485_User_Tx_Data();

        // // Port_SetPortPinLevel(1, 21, PortGpioLow);//测试
    //    Speed_Output_Update(PWMCH_SPEED_OUT, 356, 50);
#if (PRO_BL7M)
            HU_MON_PE_01.HU_Type = 0x60;
            HU_CLU_PE_05.HU_LanguageInfo = 0x2;
#endif
        if ((Timer1msCnts <= 5000) && (MPHTimeFlage == 0)){
#if ((PRO_CN7) || (PRO_SP2C_PE) || (PRO_SU2ID_FL) || (PRO_SU2IFL))
            HU_MON_PE_01.HU_Type = 0x60;
            HU_MON_PE_01.HU_OptionInfo_L = 0x2;
#endif
        }
        bsp_HDOG_Feed();
        SaveDataByWorkFlash();
        CanFD_Busoff_Recover(0);
        CanFD_Busoff_Recover(1);
        CanFD_Busoff_Recover(2);
        SendCan2Message();
        if (CheckClusterValid == 0u) 
        {   
            g_uiLedNum = 0;
            g_uiTftNum = 0;
            TimeProcessing();
            UpdataCenterDisp(1);
            if(CheckBarcode == 1)
            {
                if (main_board_flag) {
                    handle_receive_uart();
                    handle_receive_uart9();
                } else { 
                    handle_receive_uart_slave();
                    handle_receive_uart9_slave();
                }
            }
            bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData);
            AnalysisCanData();

            if(g_uiUpdateStep == 1 && Botton.S30.Statu == 2)
            {
                Botton.S30.Statu = 0;
#if (PRO_KS)
#else
                g_UI_Language = UI_CHINESE;//��ʾ���Ľ���
                NewData.Data2 = g_UI_Language;
                bsp_Save_Check_Service(2);//�洢���������
#endif
            }
            if(g_uiUpdateStep == 1 && Botton.S15.Statu == 2)
            {
                Botton.S15.Statu = 0;
#if (PRO_KS)
#else
                g_UI_Language = UI_ENGLISH;//��ʾ���Ľ���
                NewData.Data2 = g_UI_Language;//��ʾӢ�Ľ���
                bsp_Save_Check_Service(2);//�洢���������
#endif
            }
           if (g_uiUpdateStep == 1 && g_SpeedUpflag == 1 && g_SpeedDownflag == 1)
            {
                g_SpeedUpflag = 2;
                g_SpeedDownflag = 2;
                if (g_UI_SWHW == 0){
                    g_UI_SWHW = 1;
                    NewData.Data3 = g_UI_SWHW;//��ʾС�汾��
                    bsp_Save_Check_Service(2);//�洢���������
                    
                }else if (g_UI_SWHW == 1){
                    g_UI_SWHW = 0;
                    NewData.Data3 = g_UI_SWHW;//����ʾС�汾��
                    bsp_Save_Check_Service(2);//�洢���������
                }
            }
        } 
        else 
        {
            InitTelltaleOrder();
            InitTftOrder();
            switch(g_runStep)
            {
            case STAGE_TASK:
                //UpdataCenterDisp(1);
                g_runStep = IIC_TASK;
                break;
            case IIC_TASK:
                //UpdataCenterDisp(1);
                SavePro();
                g_runStep = GET_TASK;
                break;
            case GET_TASK:
                //UpdataCenterDisp(1);
                GetADCVolue();
                bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData);
                g_runStep = TFT_TASK;
                break;
            case TFT_TASK:
                LcdBus_Check();
                UpdataCenterDisp(1);
                g_runStep = STAGE_TASK;
                break;  
            }			
            Stage_Manage();
            TimeProcessing();
            bsp_HDOG_Feed();
            AnalysisCanData();
            
            if(CANSendEnable == ON) {
                if (EOL_Flag != 1) {
                    SendCan0Message();           
                }
            }
            if(CheckBarcode == 1)
            {
                if (main_board_flag) {
                    handle_receive_uart();
                    handle_receive_uart9();
                } else { 
                    handle_receive_uart_slave();
                    handle_receive_uart9_slave();
                }
            }
            
            if(Default_flag==1)
            {
                // HU_MON_PE_01.HU_Type =0xFE; 
                HU_USM_E_04.CF_AVN_CluWelcomeSnd=2;
                HU_USM_E_04.CF_AVN_CluRoadInfoGuide=1;
                HU_USM_E_04.CF_AVN_CluWiperLight=2;
                HU_USM_E_04.CF_AVN_CluTransmissionDisp=2;
                HU_USM_E_04.CF_AVN_CluAutoInitFuelEconomy=3;
                HU_USM_E_04.CF_AVN_CluFuelEconUnit_km=2;
                
                HU_USM_E_04.CF_AVN_CluUSMReset=1;
#if (CAN_2ND)                 
                HU_USM_E_01.CF_AVN_AdasVolumeNValueSet=2;
#endif                
                HU_USM_E_04.CF_AVN_CluRheostatLvl=DEFAULT_BACKLIGHT_VALUE;
            }
            else
            {
#if(PRO_DL3C)
                HU_USM_E_04.CF_AVN_CluUSMReset=0;
#endif
            }            
        }
    }
#endif
#if (PRO_CONFIG_SCAN_APPLY)
    for(;;)
    {
    	Port_SetPortPinLevel(1, 2, 1);
    	Port_SetPortPinLevel(1, 5, 1);
    	while(CheckBarcode == 0)
    	{
            bsp_HDOG_Feed();
            if (main_board_flag) {
                handle_receive_uart();
                handle_receive_uart9();
            } else { 
                handle_receive_uart_slave();
                handle_receive_uart9_slave();
            }
    	}
    	
    	bsp_HDOG_Feed();
    	SaveDataByWorkFlash();
        CanFD_Busoff_Recover(0);
        CanFD_Busoff_Recover(1);
        CanFD_Busoff_Recover(2);
    	
    	Flag_CheckBarcode = 1;
    	if (main_board_flag) {
            handle_receive_uart();
            handle_receive_uart9();
    	} else { 
            handle_receive_uart_slave();
            handle_receive_uart9_slave();
    	}
    	TimeProcessing();
    	if (CheckClusterValid == 0u) 
    	{
            if(Botton.S30.Statu == 2 && Flag_SetTime == 0 && Botton.S30.Flag == 0)
            {
                Flag_SetTime = 1;
                Flag_BarcodeErr = 0;
                Botton.S30.Statu = 0;
            }
            SetClusterState = 3;
    	}
    	else
    	{
            if((Flag_QRcodeReady == 1) && (Flag_SaveDate == 0))
            {
                if((memcmp(PartNum_AssemblyWorkshop, tmpPartNum_AssemblyWorkshop, 10) == 0))
                    //&& (ClusterID == tmpClusterID)
                    //&& (BarcodeDate == tmpBarcodeDate)
                    //&& (memcmp(tmpSerialNumber, SerialNumber, 4) == 0))
                {
                    SetClusterState = 0;
                    Flag_SaveDate = 1;
                }
                else
                {
                    SetClusterState = 2;
                }
                Flag_QRcodeReady = 0;
            }
            UDS_2E_F18C_F187();
            Botton.S30.Statu = 0;
            Flag_SetTime = 0;
    	}
    	UpdataCenterDisp(1);
    	LampState_L.Lamps.RELAY_B = 1;
    	LampState_L.Lamps.RELAY_IGN1 = 1;
    	bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData);
    	AnalysisCanData();
    }
#endif
}


 