#define  GLOBALS_VARIABLE
#include "common_include.h"
#include "io_config.h"
#include "bsp_port.h"
#include "bsp_pwm.h"
#include "bsp_button.h"


#define __MAIN_BOARD  0
#ifdef __MAIN_BOARD
uint8_t  main_board_flag =1;
#else
uint8_t  main_board_flag =0;
#endif
uint8_t  R_Speed =0;


#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 uint8_t SaveState,OldSaveState;
extern DATA_SAVE_PACK NewData;
extern void Init_Load_data(void);
extern volatile uint8_t Time_500ms_Flag; 
uint8_t ADFlag;
extern uint16_t ThermistorIndex;
extern uint16_t Diaplay_test;
extern uint32_t TFT_step;
extern uint32_t run_step;
extern uint32_t Speed_down_long;
extern uint32_t SPEED_step;

/*add for 3360*/
uint8_t Test_array[32768 + 4];
#define SAMPLE_UART_TX_BUFFSIZE         (64)
#define SAMPLE_UART_RX_BUFFSIZE         (64)

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;
extern uint8_t g_k_test;
uint8_t UUIDisTURE = 1;//0: unuse 1:ready 2:true 3:fail
extern uint8_t PartNum_DATA[32];
extern uint8_t UUIDData[32];
uint8_t test1=0xFF;
uint8_t test2=0xFF;
uint8_t test3=0xFF;
uint8_t test4=0xFF;
static void Uart0_RX_Callback(uint16_t u16FillCnt)
{
    uint16_t u16ReadCnt;
    
    Mfs_Uart_Read(UART0_Type, Test_array + WriteCount, &u16ReadCnt, SAMPLE_UART_RX_BUFFSIZE, FALSE);
    Time_100us = 0;
    Uart_Pro_Flag = 1;
    WriteCount += u16ReadCnt;
}    
uint8_t UUIDSaveData[32];
uint8_t GetUUidisTRUEFUN()
{
    if(UUIDData[1] != 0)
    {
        memcpy(UUIDSaveData ,UUIDData ,32);
    }
    if(Test_array[0] == 0x0)
    {
        return 1;
    }
    uint8_t UuidConfigNum = 0;
    for(UuidConfigNum = 0; UuidConfigNum <= 33; UuidConfigNum++)
    {
        if(UuidConfigNum < 12)
        {
            if(Test_array[UuidConfigNum] == PartNum_DATA[UuidConfigNum])
            {
                
            }
            else
            {
                // test2=Test_array[UuidConfigNum];
                // test3=PartNum_DATA[UuidConfigNum];
                return 3;
            }
        }
        else if(UuidConfigNum > 12)
        {
            if(Test_array[UuidConfigNum] == UUIDSaveData[UuidConfigNum - 13])
            {
                
            }
            else
            {
                // test1 = Test_array[UuidConfigNum];
                // test4 = UUIDData[UuidConfigNum];
                return 3;
            }
        }
    }
    if(UuidConfigNum == 34)
    {
        return 2;
    }

}   

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, 14, &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, 12, &PpcConf);
    //Port_EnableInput();
}

static void UART_init(void)
{
    stc_uart_config_t stcUartConf = { 0 };
    // 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 = Uart0_RX_Callback;                        // Rx callback not used
    stcUartConf.pfnTxCb = NULL;                                     // Tx callback not used
    Mfs_Uart_Init(UART0_Type, &stcUartConf);
}

uint8_t g_k_test;
extern uint8_t uart_send_count;
extern uint8_t start_uart_timer;
extern uint8_t uart_send_flag;
extern uint8_t Button_Press;
extern uint8_t g_butto_msg[8];
void handle_receive_uart()
{
    uint8_t ret;
  
    if(Uart_Pro_Flag == 1 && Time_100us >= 200)  
    {
        Uart_Pro_Flag=0;

        //g_k_test= Test_array[0];
        if ((Test_array[0]==0xFF) && (Test_array[1]==0x1)&&(Test_array[2]==0x1)&&(Test_array[3]==0x1))
        {
            ret = Calc_Checksum(Test_array, 4);
            if (ret==Test_array[4])
            {
                uart_send_count=0;
                start_uart_timer=0;
                uart_send_flag=0;
                Button_Press=0;
            }
        }
        WriteCount = 0;
    }
	if(Time_100us >= 10000)
	{
		WriteCount = 0;
	}
}   
uint8_t Button_Value_Slave;
uint8_t Button_Slave_Receive_Flag;

void handle_receive_uart_slave()
{
    uint8_t ret;
    
    if(Uart_Pro_Flag == 1 && Time_100us >= 200)  
    {
        Uart_Pro_Flag=0;

        //g_k_test= Test_array[0];
        if ((Test_array[0]==0xFF) && (Test_array[1]==0x1)&&(Test_array[2]==0x1))
        {
            ret = Calc_Checksum(Test_array, 4);
            if (ret==Test_array[4])
            {
                Button_Value_Slave = Test_array[3];
                Button_Slave_Receive_Flag=1;
            }
        }
        WriteCount = 0;
    }
}
uint32_t CANSendCnts = 0;
extern uint8_t EOL_Flag;
extern volatile uint8_t  Auto_HW_flag;
extern volatile uint8_t  Default_flag;
uint8_t CheckClusterValid = 1;//校验仪表型号标志位
uint8_t GearValid = 0;
extern uint32_t AutoStepAddTime;
extern uint8_t GetPartNumFinish;
uint8_t uuidWriteFlag = 0;  //初始化为1是UUID写入，初始化为0是检测台。分开释放程序，不建议把这两个功能做一起
uint8_t uuidWriteStep = 0;
void main(void)
{
    //uint32_t step=0;
    Start_Init();
    Api_GPIO_Init();
    TIMER_50us_Init();
    TIMER_100us_Init();
    TIMER1_1ms_Init();
    TIMER_10ms_Init();
    ADCInit();
    ICU_IO_Initialize();
    CANInit();      
    InitDiagnostic();//UDS
    Port_EnableInput();
    bsp_BD8379_Init();
    LCD_BUS_Init();
    LCD_Panel_Start_Up();
    Init_Load_data();
    IRQ_ENABLE();
    CANSendEnable = ON;
    LampState_L.Lamps.RELAY_IGN1=1;
    LampState_L.Lamps.RELAY_B = 1;
    bsp_Save_Check_Service(1);//读取检表数据
    Diaplay_test = NewData.Data1;
    UART_PORT_init();
    UART_init();
    //VEH_Output_PwmConfig(PWMCH_VEH_OUT, 200, 1);
    //REV_Output_PwmConfig(PWMCH_REV_OUT, 100, 1);
    HU_USM_E_04.CF_AVN_CluVoiceVolume = 0x3;
	CoverPageTimerCnts = 2000;
     REV_Output_PwmConfig(PWMCH_REV_OUT, 1000,650);
     VEH_Output_PwmConfig(PWMCH_VEH_OUT, 1000,650);
    //ApiPowerSupply();
    //Button_Statu_Manage_Slave();
   // Button_Statu_Manage();
    //Get_Button_Value();
    //uint32_t step=0;
//    _OIL1_out(PortGpioHigh);
//    ECU_Engine_Data_M2.msg.bits.ECU_Temperature_Water = 0x43;
    
    for(;;)
    {
//      Port_SetPortPinLevel(1, 2, 1);
//      Port_SetPortPinLevel(1, 5, 1);
     //   Gear_Step();
        //VEH_Output_Update(PWMCH_VEH_OUT, 2000, 50); //车速最大2000Hz
        //REV_Output_PwmConfig(PWMCH_REV_OUT, 250, 169);
       // REV_Output_Update(PWMCH_REV_OUT, 200, 50); //转速最大200Hz
//        Port_SetPortPinLevel(1, 16, PortGpioHigh);
//        Port_SetPortPinLevel(1, 17, PortGpioHigh);
        bsp_HDOG_Feed();
        CanFD_0_Busoff_Recover();
        handle_receive_uart();
        UpdataCenterDisp(0);
//        {
//            
//            if (main_board_flag) {
//                handle_receive_uart();
//            } else { 
//                handle_receive_uart_slave();
//            }
//            TimeProcessing();
//            
//            UpdataCenterDisp(1);
//            LampState_L.Lamps.RELAY_B = 1;
//            LampState_L.Lamps.RELAY_IGN1 = 1;
//            bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData, LampState_R.LampData);
//            AnalysisCanData(); //定时调用
//            
//       
//        } else
        {            
//        switch(g_runStep)
//            {
//                case STAGE_TASK:
//                UpdataCenterDisp(0);
//                //Stage_Manage();
//                g_runStep = IIC_TASK;
//                break;
//                case IIC_TASK:
//                UpdataCenterDisp(0);
//                SavePro();
//                g_runStep = GET_TASK;
//                break;
//                case GET_TASK:
//                UpdataCenterDisp(0);
                GetADCVolue();
//                bsp_BD8379_WriteData(LampState_L.LampData, LampState_M.LampData, LampState_R.LampData);
//                g_runStep = TFT_TASK;
//                break;
//                case TFT_TASK:
                LcdBus_Check();
//                UpdataCenterDisp(0);
//                g_runStep = STAGE_TASK;
//                break;  
//            }
//         if(Botton.TFTUp.Flag==1)
//          {
//           
//              //Port_SetPinConfig(1, 20, &stc_OUT_pin_config);
//             // P_RELAY_B_MCU(PortGpioHigh);
//              P_61194_EN(PortGpioHigh);
//            
//            }
        //ApiPowerSupply();

//        run_step=Speed_down_long;
//        run_step++;
        //text_step();
//        _OIL1_out(PortGpioHigh);
       // clean_Mil();
        
        //_B();
        Button_Statu_Manage();
        Get_Button_Value();
//        Gear_Step();

        
        //oil();
//        light();
        
        //R_Speed += Speed_down_long;
       if(Speed_down_long==1)
        {
          if(AutoStepAddTime>2000)
          {
            //SPEED_step=0;
           AutoStepAddTime=0;
           run_step++;       
          }
          
        }
        //_lianxu();
        if(ButtomCurrent.enable == 1){
            LampState_L.Lamps.RELAY_IGN3 = 1;
            LampState_L.Lamps.RELAY_B = 0;
            LampState_L.Lamps.RELAY_IGN1 = 0;   
            LIG_left_OUT(PortGpioLow);
            LIG_HighBeam_OUT(PortGpioLow); 
            LIG_Oil_OUT(PortGpioLow);
            LIG_ABS_OUT(PortGpioHigh);
            LIG_right_OUT(PortGpioLow);
            //REV_Output_Update(PWMCH_REV_OUT, 0, 50); //转速0                
        }
        else{
            SPEED_Step();
            GetInfo(); 
            SendCan0Message(); 
        }

        
        if(LampState_L.Lamps.RELAY_IGN1){
            P_RELAY_IG_MCU(PortGpioHigh);
        }
        else{
            P_RELAY_IG_MCU(PortGpioLow);
        }
        if(LampState_L.Lamps.RELAY_B){
            P_RELAY_B_MCU(PortGpioHigh);
        }
        else{
            P_RELAY_B_MCU(PortGpioLow);
        }
        if(LampState_L.Lamps.RELAY_IGN3){
            P_RELAY_B1_MCU(PortGpioHigh);
        }
        else{
            P_RELAY_B1_MCU(PortGpioLow);
        }       //Auto_Power_change();
       
        //LIG_Oil_OUT(PortGpioHigh);
        if((ButtomCurrent.Time < 2000 || ButtomCurrent.Time > 7500))
            CGW2.msg.bits.CF_Gway_ICUPowerAutoCutMode=0x2; //客户模式  
        Stage_Manage();
        TimeProcessing();
        bsp_HDOG_Feed();
        AnalysisCanData();
        //Gear_Step();
//        if((CANSendEnable == ON && (Timer1msCnts > CANSendCnts) && (Timer1msCnts - CANSendCnts >= 10)))
//        {
//            CANSendCnts = Timer1msCnts;
//            if (EOL_Flag == 1) 
//            {
//                SendCan0Message_7DF();
//                if(UDSSend == ON)
//                {
//                    UDSSend = FINISH;
//                    CanFD_Send_StandMsg(CANFD0_Type, 0x7C6, BUF_27, TX_ISR_EN, (uint8_t*)&Send_7CE_Data.mdata, 4);
//                }
//                
//                if((Auto_HW_flag == 1) || (Auto_HW_flag == 2))
//                {
//                    CGW_PC4.msg.bits.N =0x4E20;//5000  转速
//                    CanFD_Send_StandMsg(CANFD0_Type, 0x366, BUF_24, TX_ISR_EN, (uint8_t*)&CGW_PC4.msg.data, 7);
//                    //Can_Clear((uint8_t*)&EMS11.msg.data);
//                    Auto_HW_flag = 2;
//                }
//            } 
//          else 
//          {
//            //ECU_Engine_Data_M2.msg.bits.ECU_Temperature_Water = 0x63;
//             //  FUN.msg.bits.Byte0Data=0xb;
////                FUN.msg.bits.Byte1Data=0x16;
////                FUN.msg.bits.Byte2Data=0x21;
////                FUN.msg.bits.Byte3Data=0x2c;
////                FUN.msg.bits.Byte4Data=0x37;
////                FUN.msg.bits.Byte5Data=0x42;
////                FUN.msg.bits.Byte6Data=0x4d;
////                FUN.msg.bits.Byte7Data=0x58;
//                SendCan0Message(); 
//               // APP_SPEED_OUTPUT();
//            }
//        }
        
//        if (main_board_flag)
//            handle_receive_uart();
//        else 
//            handle_receive_uart_slave();
        
        
        
//        if(Default_flag==0)
//        {
//          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;
//          HU_USM_E_01.CF_AVN_AdasVolumeNValueSet=2;
//          //HU_USM_E_04.CF_AVN_CluVoiceVolume=3;
//          HU_USM_E_04.CF_AVN_CluRheostatLvl=12;
//          //CanFD_Send_StandMsg(CANFD0_Type, 0x483, BUF_29, TX_ISR_EN, (uint8_t*)&FCA12.msg.data, 8);
//          //Can_Clear((uint8_t*)&FCA12.msg.data);
//        }
//        else
//        {
//          HU_MON_PE_01.HU_Type =0xFE; 
//          HU_USM_E_04.CF_AVN_CluWelcomeSnd=0;
//          HU_USM_E_04.CF_AVN_CluRoadInfoGuide=0;
//          HU_USM_E_04.CF_AVN_CluWiperLight=0;
//          HU_USM_E_04.CF_AVN_CluTransmissionDisp=0;
//          HU_USM_E_04.CF_AVN_CluAutoInitFuelEconomy=0;
//          HU_USM_E_04.CF_AVN_CluFuelEconUnit_km=0;
//          HU_USM_E_04.CF_AVN_CluUSMReset=0;
//          HU_USM_E_01.CF_AVN_AdasVolumeNValueSet=0;
//          //HU_USM_E_04.CF_AVN_CluVoiceVolume=0;
//          HU_USM_E_04.CF_AVN_CluRheostatLvl=0;
//        }   
   //can002.msg[2] = 0xff;
   //can002.msg[3] = 0x01;     
        }
//        part_num_jiexi(); 
    }



}


/*-------------------------------------------------------------------------
* Function Name  : Init_Load_data
* Description    :
* Input          : None
* Output         : None
* Return         : None
* onther         : xxhh
--------------------------------------------------------------------------*/

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


