#include "init.h"
#include "Sys_Scheduler.h"
#include "Simulated_IIC_1_Master.h"
#include "Simulated_IIC_2_Master.h"
#include "Simulated_IIC_3_Master.h"
#include "Simulated_IIC_4_Master.h"
#include "MC33984EHFK.h"
#include "SGMCD1020Q.h"
#include "SGM4591Q.h"

#define ADC_MODULE_SAMPLE//sophia add
/* Registers base adrress */
#define GUARD_PE0CL0    0xFFC6C000
#define GUARD_PE1CL0    0xFFC6C100
#define PBGERRSLV40     0xFFC75400
#define PBG40           0xFFC75300
#define PBGERRSLV50     0xFFC7B000
#define PBG52           0xFFC7A500

#define PIC1TAUD0SEL *((volatile uint32 *)0xFFBFAF78UL)
#define PIC1TAUD1SEL *((volatile uint32 *)0xFFBFAF7CUL)
#define SPI_DMA0          ((volatile Spi_DMAGlobalRegSetType*)0xFFF90000UL)
#define SPI_DMA1          ((volatile Spi_DMAGlobalRegSetType*)0xFFF98000UL)
#define SPI_DMA0OR        (*(volatile uint16*)0xFFF90060UL)
#define SPI_DMA1OR        (*(volatile uint16*)0xFFF98060UL)

#define CAN_FD_TX_IDFORMAT                  (uint32)0x40000000UL
#define CAN_BAUDRATE_5M                     0x0000
/* Data length of SpiChannels */
#define SPI_DATA_BYTES_0   6U
#define SPI_DATA_BYTES_1   4U
#define SPI_DATA_BYTES_2   4U
/* PEGKCPROT */
#define PEGKCPROT0      (*(volatile uint32*)GUARD_PE0CL0)
#define PEGKCPROT1      (*(volatile uint32*)GUARD_PE1CL0)

/* PEGPROTm */
#define PEGPROT0(m)     (*(volatile uint32*)(GUARD_PE0CL0 + 0x40UL + m * 0x10UL))
#define PEGPROT1(m)     (*(volatile uint32*)(GUARD_PE1CL0 + 0x40UL + m * 0x10UL))

/* PEGSPIDm */
#define PEGSPID0(m)     (*(volatile uint32*)(GUARD_PE0CL0 + 0x44UL + m * 0x10UL))
#define PEGSPID1(m)     (*(volatile uint32*)(GUARD_PE1CL0 + 0x44UL + m * 0x10UL))

/* PBGKCPROTn */
#define PBGKCPROT40      (*(volatile uint32*)(PBGERRSLV40 + 0x18UL))
#define PBGKCPROT52      (*(volatile uint32*)(PBGERRSLV50 + 0x18UL))

/* PBGnPROT0_m */
#define PBG40PROT0(m)   (*(volatile uint32*)(PBG40 + m * 0x08UL))
#define PBG52PROT0(m)   (*(volatile uint32*)(PBG52 + m * 0x08UL))

/* I/O Buffer Hold Control Register Address */
#define MCU_IOHOLD0                  *((volatile uint32 *)0xFF988D00UL)
#define MCU_IOHOLD2                  *((volatile uint32 *)0xFF988D08UL)

#define ADC_DMA0OR        *(volatile uint16*)0xfff90060UL
#define ADC_DMA1OR        *(volatile uint16*)0xfff98060UL
#define ADC_DME_ENABLE    0x0001

/*******************************************************************************
Imported global variables and functions (from other files)
*******************************************************************************/
volatile Mcu_PllStatusType    GenPllStatus[3];
volatile Std_ReturnType       GenInitClockResult;
volatile Std_ReturnType       GenDistributePllResult;
volatile Std_ReturnType       GenInitRamSectionResult[6];
volatile Mcu_RamStateType     GenRamState;
volatile Mcu_ResetType        GenResetReason[2];
volatile Mcu_RawResetType     GenRawResetReason[2];

Icu_DutyCycleType GddDutyCycleValues[6];


/* Variable used to stored the return value for Read group API */

Std_ReturnType GddSetupBuffer0;
Std_ReturnType GddSetupBuffer1;
Std_ReturnType GddSetupBuffer2;
Std_ReturnType GddSetupBuffer3;

/* Declaration for the result buffers */
Adc_ValueGroupType GddDataBufferPtr0[5];
Adc_ValueGroupType GddDataBufferPtr1[5];
Adc_ValueGroupType GddDataBufferPtr2[5];
Adc_ValueGroupType GddDataBufferPtr3[5];

Std_ReturnType GddReadGroup0;
Std_ReturnType GddReadGroup1;
Std_ReturnType GddReadGroup2;
Std_ReturnType GddReadGroup3;

/* Pointer variable used to capture status of read group */
Adc_ValueGroupType DataBufferPtr0;
Adc_ValueGroupType DataBufferPtr1;
Adc_ValueGroupType DataBufferPtr2;
Adc_ValueGroupType DataBufferPtr3;

uint8 Adc_GroupStatus_Switch=0;
Adc_StatusType Adc_GroupStatus=0;


Std_ReturnType ret;

/* Declaration for the ADC result buffers */
Adc_ValueGroupType    GddSetBuffGroup_12B_5V_AD[16] = {0};
Adc_ValueGroupType    GddSetBuffGroup_10B_5V_AD[4] = {0};
Adc_ValueGroupType    GddSetBuffGroup_MCU_AI[10] = {0};

Adc_ValueGroupType    GddSetBuffGroup_MCU_AI_1[4] = {0};
Adc_ValueGroupType    GddSetBuffGroup_5V[6] = {0};
Adc_ValueGroupType    GddSetBuffGroup_BAT[3] = {0};
Adc_ValueGroupType    GddSetBuffGroup_TEST[2] = {0};

Std_ReturnType App_GenReturnValue;
// Std_ReturnType App_GenReturnValue1;
Spi_StatusType App_GenStatus;


/* Transmit data for SpiChannel */
Spi_DataBufferType App_GaaTransmitData0[] ={193, 129, 0, 9, 220, 147, 255, 255};
Spi_DataBufferType App_GaaTransmitData1[] ={0x10U, 0x11U, 0x12U, 0x13U};

/* Receive data for SpiChannel*/
// Spi_DataBufferType App_GaaReceiveData[8] = { 0 };
Spi_DataBufferType App_GaaReceiveData0[8] = { 0 };
Spi_DataBufferType App_GaaReceiveData1[8] = { 0 };


Spi_SeqResultType App_GenSeqResult1;

Can_PduType LddCanPduType;
uint8 GaaByteArrayTx0[] = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
uint8 GaaByteArrayTx1[] = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55};


uint8 GaaByteArrayRx0[] = { 0 };
uint8 GaaByteArrayRx1[] = { 0 };

extern uint8 GucReturnCount;

uint8 LucHthId;

uint16 i = 0,j = 0;

void Big_Delay(void);
uint8 GaaByteArray0[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
uint8 GaaByteArray1[] = { 0x02, 0x04, 0x06, 0x08, 0x01, 0x03, 0x05, 0x07};


#if (MCU_RELEASEIOBUFFERHOLD_API == STD_ON)
volatile Std_ReturnType              GenRealeaseResult;
#endif
volatile Std_ReturnType              GenIsTestSuccess0;

/*******************************************************************************
Exported global variables and functions (to be accessed by other files)
*******************************************************************************/

 #if (SPI_DMA_CONFIGURED == STD_ON)
  void Guard_Init(void)
  {
    PEGKCPROT0 = 0xA5A5A501UL;
    PEGKCPROT1 = 0xA5A5A501UL;
    PBGKCPROT40 = 0xA5A5A501UL;
    PBGKCPROT52 = 0xA5A5A501UL;
  
    /* Enable read/write Local RAM by DMA */
    PEGPROT0(0) |= 0x00000143UL;
    PEGPROT0(1) |= 0x00000143UL;
    PEGPROT0(2) |= 0x00000143UL;
    PEGPROT0(3) |= 0x00000143UL;
    PEGPROT0(4) |= 0x00000143UL;
    PEGPROT0(5) |= 0x00000143UL;
    PEGPROT0(6) |= 0x00000143UL;
    PEGPROT0(7) |= 0x00000143UL;
  
    PEGPROT1(0) |= 0x00000143UL;
    PEGPROT1(1) |= 0x00000143UL;
    PEGPROT1(2) |= 0x00000143UL;
    PEGPROT1(3) |= 0x00000143UL;
    PEGPROT1(4) |= 0x00000143UL;
    PEGPROT1(5) |= 0x00000143UL;
    PEGPROT1(6) |= 0x00000143UL;
    PEGPROT1(7) |= 0x00000143UL;
  
    /* Enable read/write MSPI RAM by DMA */
    PBG40PROT0(1) |= 0x00000143UL;
    PBG40PROT0(2) |= 0x00000143UL;
    PBG40PROT0(3) |= 0x00000143UL;
    PBG40PROT0(4) |= 0x00000143UL;
    PBG40PROT0(5) |= 0x00000143UL;
    PBG40PROT0(6) |= 0x00000143UL;
    PBG40PROT0(7) |= 0x00000143UL;
  
    PBG52PROT0(6) |= 0x00000143UL;
    PBG52PROT0(7) |= 0x00000143UL;
    PBG52PROT0(8) |= 0x00000143UL;
    PBG52PROT0(9) |= 0x00000143UL;
    PBG52PROT0(10) |= 0x00000143UL;
  }
 #endif


void Adc_DMA_DME_Enable(void)
{
  ADC_DMA0OR |= ADC_DME_ENABLE; /* DMA0OR DME */
  ADC_DMA1OR |= ADC_DME_ENABLE; /* DMA1OR DME */
}

#ifdef TSG3_TEST
static Tsg3_InitCfg GsstTsg30 = {
    // uint8  u1CTL0;
    TSG3_MD(1U),
    // uint16 u2CTL1;
    0x00,
    // uint8  u1CTL3;
    0x00,
    // uint32 u4CTL4;
    TSG3_PRE | TSG3_VRE | TSG3_PIE | TSG3_VIE,
    // uint16 u2CTL5;
    TSG3_AT08,
    // uint16 u2CTL6;
    TSG3_AT19,
    // uint8  u1CTL7;
    0x00,
    // uint8  u1CTL8;
    0x00,
    // uint8  u1IOC0;
    TSG3_TOE6 | TSG3_TOE5 | TSG3_TOE4 | TSG3_TOE3 | TSG3_TOE2 | TSG3_TOE1,
    // uint8  u1IOC1;
    TSG3_TOS,
    // uint16 u2IOC2;
    0x00,
    // uint32 u4IOC3;
    0x00,
    // uint8  u1OPT0;
    0x02U,
    // uint8  u1OPT1;
    0x00,
    // uint8  u1OPT2;
    0x00,
    // uint16 u2DTPR;
    0x1234U,
};
static uint32 Gsu4Tsg30Freq = 20000UL;

static Tsg3_Deadtime GsstTsg30Deadtime = {
    2.0f,
    2.0f,
};
static Tsg3_Duty GsstTsg30Duty = {
    0.25f,
    0.50f,
    0.75f,
};

static Tsg3_AdDelay GsstTsg30AdDelay = {
    0.0f,
    0.0f,
    0.0f,
};

uint16 TSG3_PDR = 0x1234U;

#endif

void Sys_Startup_Init(void)
{
    /* Setup module standby controllers ========================================*/
    /* Disable protection for module standby registers */

    uint32 LucIntCount;

    R_STBC_CfgMsr(MSR_RSCFD, 0x8000UL);
    R_STBC_CfgMsr(MSR_ADCJ_ISO, 0x00UL);
    R_STBC_CfgMsr(MSR_TAUD, 0x00UL);
    R_STBC_CfgMsr(MSR_TAUJ_AWO, 0x00UL);
    R_STBC_CfgMsr(MSR_TAUJ_ISO, 0x00UL);
    R_STBC_CfgMsr(MSR_OSTM, 0x00UL);
    R_STBC_CfgMsr(MSR_MSPI, 0x00UL);
    R_STBC_CfgMsr(MSR_TSG3, 0x00UL);

    /* Get reset reason */ 
    // GenResetReason[0] = Mcu_GetResetReason();
    // if (GenResetReason[0]==0x08)
    // {
    //   /* Application specific functionality */ 
    // #if (MCU_PERFORM_RESET_API == STD_ON) 
    //     /* Perform the software reset*/ 
    //     Mcu_PerformReset(); 
    // #endif 
    // }

    /* Initialise MCU Driver */
    Mcu_Init(Mcu_Config);
    /* Initialize clock */
    GenInitClockResult = Mcu_InitClock(McuConf_McuClockSettingConfig_McuClockSettingConfig);

    GenPllStatus[0] = Mcu_GetPllStatus();
    LucIntCount = 10000;
    while((LucIntCount>0) && (MCU_PLL_LOCKED != Mcu_GetPllStatus()))
    {
      LucIntCount--;
    }
    GenDistributePllResult = Mcu_DistributePllClock();
    GenPllStatus[1] = Mcu_GetPllStatus();

    /* Enable Interrupt  */
    ENABLE_INTERRUPT();//好像有点早
    
    // Port_Init(Port_Config);

    /* Clear and set WakeUp factor */
    Mcu_ClearAndSetWakeUpFactor(McuConf_McuModeSettingConf_McuModeSettingConf_DeepStop);

    Sys_Scheduler_Init();


    R_INTC_Init(272UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTMSPI4TX
    R_INTC_Init(273UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTMSPI4RX

       /* This service is for setting up the polling mode */
    App_GenReturnValue = Spi_SetAsyncMode(SPI_INTERRUPT_MODE);

    /* Initialise CAN Driver */
    COM_CAN_Init();

    // Wdg_Init(Wdg_Config);



     #ifdef TSG3_TEST
    R_INTC_Init(178UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL));
    /  R_INTC_Bind(178UL, INTC_PEID(0UL) | INTC_GPID(0UL));
    R_INTC_Init(179UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL));
    /  R_INTC_Bind(179UL, INTC_PEID(0UL) | INTC_GPID(0UL));
    R_TSG3_Init(0U, GsstTsg30);
    R_TSG3_DeadTime_Protection(0U, 1U, TSG3_PDR);
    R_TSG3_SetFrequency(0U, Gsu4Tsg30Freq);
    R_TSG3_SetDuty(0U, GsstTsg30Duty);
    R_TSG3_SetDeadTime(0U, GsstTsg30Deadtime, TSG3_PDR);
    R_TSG3_SetAdDelay(0U, GsstTsg30AdDelay);
    
    R_TSG3_Start(0U);
    #endif
    
    #ifdef PWM_MODULE_SAMPLE
     /* Initialize the PWM Driver */
     Pwm_Init(Pwm_Config);
    
     /* Set the Period and Duty cycle */
     Pwm_SetPeriodAndDuty(PwmConf_PwmChannel_PwmChannel, 49999, 0x4000);
    
     /* Set the Duty cycle */
     Pwm_SetDutyCycle(PwmConf_PwmChannel_PwmChannel_001, 0x2000);
     Pwm_SetDutyCycle(PwmConf_PwmChannel_PwmChannel_001, 0x4000);
    #endif

  /*****************************************************************************
  ********************* SIGNAL MEASUREMENT FUNCTIONALITY ***********************
  *****************************************************************************/
#ifdef ICU_MODULE_SAMPLE
  
  /* Initialize ICU Driver */
  Icu_Init(Icu_Config);

  PIC1TAUD0SEL = 0x04400444;
  PIC1TAUD1SEL = 0x00040000;
  
  R_INTC_Init(10UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I0 */ 
  R_INTC_Init(376UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I1 */ 
  // R_INTC_Init(11UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I2 */ 
  // R_INTC_Init(377UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I3 */  
  // R_INTC_Init(12UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I4 */ 
  // R_INTC_Init(378UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I5 */ 
  // R_INTC_Init(24UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I10 */ 
  // R_INTC_Init(381UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I11 */   
  // R_INTC_Init(25UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I12 */ 
  // R_INTC_Init(382UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD0I13 */ 
  // R_INTC_Init(392UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD1I8 */ 
  // R_INTC_Init(393UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference TAUD1I9 */ 
  R_INTC_Init(544UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTP0 */ 

  /* Signal measurement: Duty */
  Icu_StartSignalMeasurement (IcuConf_IcuChannel_IcuChannel);
  Big_Delay();
  
  Big_Delay();

  /* Signal DutyCycle has been captured */
  Icu_GetDutyCycleValues(IcuConf_IcuChannel_IcuChannel, &GddDutyCycleValues[0]);

  /*****************************************************************************
  ************************* EDGE DETECTION FUNCTIONALITY ***********************
  *****************************************************************************/
  Icu_EnableEdgeDetection(IcuConf_IcuChannel_IcuChannel_006);

  /* Enable notification */
  Icu_EnableNotification(IcuConf_IcuChannel_IcuChannel_006);

  #endif

  /*****************************************************************************
  ************************** ADC module test ***********************************
  *****************************************************************************/
  
#ifdef ADC_MODULE_SAMPLE
  /* Initialize ADC Driver */

    /* DMA Master Enable Initialization */
  Adc_DMA_DME_Enable();

  Adc_Init(Adc_Config);

  R_INTC_Init(47UL, INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference */   // DMA0_00: EIC47

  R_INTC_Init(226UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ0ERR */ 
  R_INTC_Init(227UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ0I0 */ 
  R_INTC_Init(228UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ0I1 */ 
  R_INTC_Init(229UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ0I2 */  
  R_INTC_Init(232UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ1IERR */ 
  R_INTC_Init(233UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ1I0 */ 
  R_INTC_Init(234UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ1I1 */ 
  R_INTC_Init(235UL,  INTC_EITB & INTC_EIMK | INTC_EIP(6UL)); /* table reference INTADCJ1I2 */  

   /* Set the result buffer for the group  */
  ret = Adc_SetupResultBuffer(AdcConf_AdcGroup_AdcGroup_000,(Adc_ValueGroupType *)GddSetBuffGroup_12B_5V_AD);

  // ret = Adc_SetupResultBuffer(AdcConf_AdcGroup_AdcGroup_001,(Adc_ValueGroupType *)GddSetBuffGroup_10B_5V_AD);

  /* On completion of the conversion, the call-back notification will be invoked */
  Adc_EnableGroupNotification(AdcConf_AdcGroup_AdcGroup_000  );

  // Adc_EnableGroupNotification(AdcConf_AdcGroup_AdcGroup_001);

  /* Starts the conversion of group */
  Adc_StartGroupConversion(AdcConf_AdcGroup_AdcGroup_000  );

  while (ADC_STREAM_COMPLETED != Adc_GetGroupStatus(AdcConf_AdcGroup_AdcGroup_000  ));

  ret = Adc_ReadGroup(AdcConf_AdcGroup_AdcGroup_000, GddSetBuffGroup_12B_5V_AD);
  
  // /* Starts the conversion of group */
  // Adc_StartGroupConversion(AdcConf_AdcGroup_AdcGroup_001);

  // while (ADC_STREAM_COMPLETED != Adc_GetGroupStatus(AdcConf_AdcGroup_AdcGroup_001));

  // ret = Adc_ReadGroup(AdcConf_AdcGroup_AdcGroup_001, GddSetBuffGroup_10B_5V_AD);

  #endif
  /*****************************************************************************
  ************************** SPI module test ***********************************
  *****************************************************************************/
 Simulated_IIC_1_Init();
 Simulated_IIC_2_Init();
 Simulated_IIC_3_Init();
 Simulated_IIC_4_Init( );
  SGM4591Q_Init();
  MC33984EHFK_Init( );
  SGMCD1020Q_Init( );
#ifdef SPI_MODULE_SAMPLE
  
  /* This service is for initializing the SPI Driver. */
  Spi_Init(Spi_Config);

#if (SPI_DMA_CONFIGURED == STD_ON)
  /* Enable DMA */
  SPI_DMA0OR = 0x0001;
  SPI_DMA1OR = 0x0001;

  Guard_Init();
 
  /* Initialize EIC registers */
  R_INTC_Init(53UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTSDMAC0CH6
  R_INTC_Init(54UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTSDMAC0CH7
  R_INTC_Init(55UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTSDMAC0CH8
  R_INTC_Init(56UL, INTC_EITB & INTC_EIMK | INTC_EIP(7UL)); /* table reference */   // INTSDMAC0CH9
#endif

#endif
}