#include <stdlib.h>
#include "bsp.h"
#include "rtthread.h"
#include "ff.h"

#define SPI_MASTER_MODE	

//stc_sd_handle_t stcSdhandle;
static uint16_t m_au16Adc1SaValue;

#if USE_SD_CARD
#include "sd_card.h"
/*****************************************************************************************
 * MMC or SD
 ****************************************************************************************/
static stc_sdcard_init_t stcCardInitCfg;
static stc_sdcard_dma_init_t stcDmaInitCfg;
/*****************************************************************************************
* 函数名称: SdioInit
* 功能描述: Sdio初始化函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
en_result_t SdioInit(void)
{
	en_result_t result;
	
	PORT_SetFunc(SDIOC_D0_PORT, SDIOC_D0_PIN, Func_Sdio, Disable);
	PORT_SetFunc(SDIOC_D1_PORT, SDIOC_D1_PIN, Func_Sdio, Disable);
	PORT_SetFunc(SDIOC_D2_PORT, SDIOC_D2_PIN, Func_Sdio, Disable);
	PORT_SetFunc(SDIOC_D3_PORT, SDIOC_D3_PIN, Func_Sdio, Disable);
	//PORT_SetFunc(SDIOC_CD_PORT, SDIOC_CD_PIN, Func_Sdio, Disable);
	PORT_SetFunc(SDIOC_CK_PORT, SDIOC_CK_PIN, Func_Sdio, Disable);
	PORT_SetFunc(SDIOC_CMD_PORT, SDIOC_CMD_PIN, Func_Sdio, Disable);
	
	stcCardInitCfg.enBusWidth = SdiocBusWidth4Bit;
	stcCardInitCfg.enClkFreq = SdiocClk50M;
	stcCardInitCfg.enSpeedMode = SdiocHighSpeedMode;
	stcCardInitCfg.pstcInitCfg = NULL;

	stcDmaInitCfg.DMAx = M4_DMA2;
	stcDmaInitCfg.enDmaCh = DmaCh1;
	
	stcSdhandle.SDIOCx = SDIOC_UNIT;
	stcSdhandle.enDevMode = SdCardDmaMode;
	stcSdhandle.pstcDmaInitCfg = &stcDmaInitCfg;
	result = SDCARD_Init(&stcSdhandle, &stcCardInitCfg);
	
	return result;
}

/*****************************************************************************************
* 函数名称: SDCardErase
* 功能描述: SDCard扇区擦除函数，最大擦除扇区数10
* 参    数: u32BlkStartAddr 起始扇区
            u32BlkEndAddr 结束扇区
* 返 回 值: 操作成功返回true，失败返回false
*****************************************************************************************/
bool SDCardErase(uint32_t u32BlkStartAddr, uint32_t u32BlkEndAddr)
{
	if(u32BlkEndAddr - u32BlkStartAddr > 10)
		return false;
	if(Ok != SDCARD_Erase(&stcSdhandle, u32BlkStartAddr, u32BlkEndAddr, 2000u)) {
		return false;
	}
	return true;
}

/*****************************************************************************************
* 函数名称: SDCardReadBlocks
* 功能描述: SDCard扇区读取函数，最大读取扇区数10
* 参    数: u32BlkStartAddr 起始扇区
            u32BlkEndAddr 结束扇区
* 返 回 值: 操作成功返回true，失败返回false
*****************************************************************************************/
bool SDCardReadBlocks(uint32_t u32BlkStartAddr, uint32_t u32BlkEndAddr, uint8_t *ReadBuff)
{
	if(u32BlkEndAddr - u32BlkStartAddr > 10)
		return false;
	if (Ok != SDCARD_ReadBlocks(&stcSdhandle, u32BlkStartAddr, u32BlkEndAddr, ReadBuff, 2000u)) {
		return false;
	}
	return true;
}
	
/*****************************************************************************************
* 函数名称: SDCardWriteBlocks
* 功能描述: SDCard扇区写入函数，最大写入扇区数10
* 参    数: u32BlkStartAddr 起始扇区
            u32BlkEndAddr 结束扇区
* 返 回 值: 操作成功返回true，失败返回false
*****************************************************************************************/
bool SDCardWriteBlocks(uint32_t u32BlkStartAddr, uint32_t u32BlkEndAddr, uint8_t *WriteBuff)
{
	if(u32BlkEndAddr - u32BlkStartAddr > 10)
		return false;
	if (Ok != SDCARD_WriteBlocks(&stcSdhandle, u32BlkStartAddr, u32BlkEndAddr, WriteBuff, 2000u)) {
		return false;
	}
	return true;
}
#endif

/*****************************************************************************************
 * System Clock
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: SystemClockConfig
* 功能描述: 系统时钟设置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void SystemClockConfig(void)
{
	stc_clk_sysclk_cfg_t    stcSysClkCfg;
	stc_clk_xtal_cfg_t      stcXtalCfg;
	stc_clk_mpll_cfg_t      stcMpllCfg;
	stc_sram_config_t       stcSramConfig;

	MEM_ZERO_STRUCT(stcSysClkCfg);
	MEM_ZERO_STRUCT(stcXtalCfg);
	MEM_ZERO_STRUCT(stcMpllCfg);
	MEM_ZERO_STRUCT(stcSramConfig);

	/* Set bus clk div. */
	stcSysClkCfg.enHclkDiv  = ClkSysclkDiv1;
	stcSysClkCfg.enExclkDiv = ClkSysclkDiv2;
	stcSysClkCfg.enPclk0Div = ClkSysclkDiv1;
	stcSysClkCfg.enPclk1Div = ClkSysclkDiv2;
	stcSysClkCfg.enPclk2Div = ClkSysclkDiv4;
	stcSysClkCfg.enPclk3Div = ClkSysclkDiv4;
	stcSysClkCfg.enPclk4Div = ClkSysclkDiv2;
	CLK_SysClkConfig(&stcSysClkCfg);

	/* Config Xtal and Enable Xtal */
    stcXtalCfg.enMode = ClkXtalModeOsc;
    stcXtalCfg.enDrv = ClkXtalLowDrv;
    stcXtalCfg.enFastStartup = Enable;
    CLK_XtalConfig(&stcXtalCfg);
    CLK_XtalCmd(Enable);

//	/* Config Hrc and enable HRC */
//	CLK_HrcTrim(SystemCoreClock);
//	CLK_HrcCmd(Enable);
	
	/* sram init include read/write wait cycle setting */
	stcSramConfig.u8SramIdx = Sram12Idx | Sram3Idx | SramHsIdx | SramRetIdx;
	stcSramConfig.enSramRC = SramCycle2;
	stcSramConfig.enSramWC = SramCycle2;
	SRAM_Init(&stcSramConfig);

	/* flash read wait cycle setting */
	EFM_Unlock();
	EFM_SetLatency(EFM_LATENCY_5);
	EFM_Lock();

	/* MPLL config (XTAL / pllmDiv * plln / PllpDiv = 200M). */
	stcMpllCfg.pllmDiv = 2ul;
	stcMpllCfg.plln    = 50ul;
	stcMpllCfg.PllpDiv = 2ul;
	stcMpllCfg.PllqDiv = 2ul;
	stcMpllCfg.PllrDiv = 2ul;
	CLK_SetPllSource(ClkPllSrcXTAL);
	CLK_MpllConfig(&stcMpllCfg);

	/* Enable MPLL. */
	CLK_MpllCmd(Enable);
	/* Wait MPLL ready. */
	while(Set != CLK_GetFlagStatus(ClkFlagMPLLRdy))
	{
			;
	}
	/* Switch driver ability */
	PWC_HS2HP();
	/* Switch system clock source to MPLL. */
	CLK_SetSysClkSource(CLKSysSrcMPLL);
}

/*****************************************************************************************
* 函数名称: Xtal32_ClockConfig
* 功能描述: 系统低速时钟配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Xtal32_ClockConfig(void)
{
    stc_clk_xtal32_cfg_t stcXtal32Cfg;

    /* configure structure initialization */
    MEM_ZERO_STRUCT(stcXtal32Cfg);

    /* Stop xtal32 */
    CLK_Xtal32Cmd(Disable);
    Ddl_Delay1ms(100u);
    /* Configuration xtal32 structure */
    stcXtal32Cfg.enDrv = ClkXtal32HighDrv;
    stcXtal32Cfg.enFilterMode = ClkXtal32FilterModeFull;
    CLK_Xtal32Config(&stcXtal32Cfg);
    /* Startup xtal32 */
    CLK_Xtal32Cmd(Enable);
    /* wait for xtal32 running */
    Ddl_Delay1ms(100u);
}


/*****************************************************************************************
 * Debug Uart
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: DbgUartRec
* 功能描述: 调试串口接收函数
* 参    数: 无
* 返 回 值: 返回收到的字符
*****************************************************************************************/
static uint8_t DbgUartRec(void)
{
	uint16_t u16Data = USART_RecData(DBG_USART_CH);
	return (uint8_t)u16Data;
}


/*****************************************************************************************
* 函数名称: DBGUsartErrIrqCallback
* 功能描述: 调试串口错误中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void DBGUsartErrIrqCallback(void)
{
	if(DBG_USART_CH->SR_f.ORE) {
		DBG_USART_CH->CR1_f.CORE = 1;
		USART_RecData(DBG_USART_CH);
	}
	
	if(DBG_USART_CH->SR_f.PE)
		DBG_USART_CH->CR1_f.CPE = 1;
	
	if(DBG_USART_CH->SR_f.FE)
		DBG_USART_CH->CR1_f.CFE = 1;
}

/*****************************************************************************************
* 函数名称: DbgUsartRxIrqCallback
* 功能描述: 调试串口接收中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void DbgUsartRxIrqCallback(void)
{
	uint8_t rData = DbgUartRec();
	DbgRxIrqCallback(rData);
}

/*****************************************************************************************
* 函数名称: DbgUart_Config
* 功能描述: 调试串口配置函数
* 参    数: BaudRate 串口波特率
* 返 回 值: 无
*****************************************************************************************/
void DbgUart_Config(uint32_t BaudRate)
{
	stc_usart_uart_init_t stcInitCfg;
	stc_irq_regi_conf_t stcIrqRegiCfg;
	en_result_t enRet;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(DBG_USART_RX_PORT, DBG_USART_RX_PIN, &stcPortInit);
	PORT_Init(DBG_USART_TX_PORT, DBG_USART_TX_PIN, &stcPortInit);
	
	stcInitCfg.enClkMode = UsartIntClkCkNoOutput;
	stcInitCfg.enClkDiv = UsartClkDiv_1;
	stcInitCfg.enDataLength = UsartDataBits8;
	stcInitCfg.enDirection = UsartDataLsbFirst;
	stcInitCfg.enStopBit = UsartOneStopBit;
	stcInitCfg.enParity = UsartParityNone;
	stcInitCfg.enSampleMode = UsartSampleBit8;
	stcInitCfg.enDetectMode = UsartStartBitFallEdge;
	stcInitCfg.enHwFlow = UsartRtsEnable;
	
	PWC_Fcg1PeriphClockCmd(DBG_FCG1_PERIPH, Enable);
	
	PORT_SetFunc(DBG_USART_RX_PORT, DBG_USART_RX_PIN, DBG_USART_RX_FUNC, Disable);
	PORT_SetFunc(DBG_USART_TX_PORT, DBG_USART_TX_PIN, DBG_USART_TX_FUNC, Disable);
	
	enRet = USART_UART_Init(DBG_USART_CH, &stcInitCfg);
	if(enRet != Ok) {
		Error_Handler();
	}
	enRet = USART_SetBaudrate(DBG_USART_CH, BaudRate);
	if(enRet != Ok) {
		Error_Handler();
	}
	
	stcIrqRegiCfg.enIRQn = DBGUART_IRQn;
	stcIrqRegiCfg.pfnCallback = &DbgUsartRxIrqCallback;
	stcIrqRegiCfg.enIntSrc = DBG_USART_RI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);


	/* Set USART RX error IRQ */
	stcIrqRegiCfg.enIRQn = DBGUART_EI_IRQn;
	stcIrqRegiCfg.pfnCallback = &DBGUsartErrIrqCallback;
	stcIrqRegiCfg.enIntSrc = DBG_USART_EI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
	
#if 0	
	/* Set USART TX IRQ */
	stcIrqRegiCfg.enIRQn = Int002_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);

	/* Set USART TX complete IRQ */
	stcIrqRegiCfg.enIRQn = Int003_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxCmpltIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TCI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
#endif	
	USART_FuncCmd(DBG_USART_CH, UsartTx, Enable);
	USART_FuncCmd(DBG_USART_CH, UsartRx, Enable);
	USART_FuncCmd(DBG_USART_CH, UsartRxInt, Enable);
}

/*****************************************************************************************
* 函数名称: DebugUartSend
* 功能描述: 调试串口发送函数
* 参    数: sData 发送数据入口指针
            sLen  发送数据长度
* 返 回 值: 无
*****************************************************************************************/
void DebugUartSend(uint8_t *sData, uint16_t sLen)
{
	for(int i = 0; i < sLen; i++) {
		USART_SendData(DBG_USART_CH, sData[i]);
		while(USART_GetStatus(DBG_USART_CH, UsartTxComplete) == Reset);
	}
}


/*****************************************************************************************
 * RS485Ch1 Uart
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: RS485Ch1UartRec
* 功能描述: RS485通道1串口接收函数
* 参    数: 无
* 返 回 值: 返回收到的字符
*****************************************************************************************/
static uint8_t RS485Ch1UartRec(void)
{
	uint16_t u16Data = USART_RecData(RS485_CH1_USART_CH);
	return (uint8_t)u16Data;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartErrIrqCallback
* 功能描述: RS485通道1串口错误中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void RS485Ch1UsartErrIrqCallback(void)
{
	if(RS485_CH1_USART_CH->SR_f.ORE) {
		RS485_CH1_USART_CH->CR1_f.CORE = 1;
		USART_RecData(RS485_CH1_USART_CH);
	}
	
	if(RS485_CH1_USART_CH->SR_f.PE)
		RS485_CH1_USART_CH->CR1_f.CPE = 1;
	
	if(RS485_CH1_USART_CH->SR_f.FE)
		RS485_CH1_USART_CH->CR1_f.CFE = 1;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartRxIrqCallback
* 功能描述: RS485通道1串口接收中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void RS485Ch1UsartRxIrqCallback(void)
{
	uint8_t rData = RS485Ch1UartRec();
	RS485Ch1RxIrqCallback(rData);
}


/*****************************************************************************************
* 函数名称: RS485Ch1_Config
* 功能描述: RS485通道1配置函数
* 参    数: BaudRate 串口波特率
* 返 回 值: 无
*****************************************************************************************/
void RS485Ch1_Config(uint32_t BaudRate)
{
	stc_usart_uart_init_t stcInitCfg;
	stc_irq_regi_conf_t stcIrqRegiCfg;
	en_result_t enRet;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(RS485_CH1_USART_RX_PORT, RS485_CH1_USART_RX_PIN, &stcPortInit);
	PORT_Init(RS485_CH1_USART_TX_PORT, RS485_CH1_USART_TX_PIN, &stcPortInit);
	
	stcInitCfg.enClkMode = UsartIntClkCkNoOutput;
	stcInitCfg.enClkDiv = UsartClkDiv_16;
	stcInitCfg.enDataLength = UsartDataBits8;
	stcInitCfg.enDirection = UsartDataLsbFirst;
	stcInitCfg.enStopBit = UsartOneStopBit;
	stcInitCfg.enParity = UsartParityNone;
	stcInitCfg.enSampleMode = UsartSampleBit8;
	stcInitCfg.enDetectMode = UsartStartBitFallEdge;
	stcInitCfg.enHwFlow = UsartRtsEnable;
	
	PWC_Fcg1PeriphClockCmd(RS485_CH1_FCG1_PERIPH, Enable);
	
	PORT_SetFunc(RS485_CH1_USART_RX_PORT, RS485_CH1_USART_RX_PIN, RS485_CH1_USART_RX_FUNC, Disable);
	PORT_SetFunc(RS485_CH1_USART_TX_PORT, RS485_CH1_USART_TX_PIN, RS485_CH1_USART_TX_FUNC, Disable);
	
	enRet = USART_UART_Init(RS485_CH1_USART_CH, &stcInitCfg);
	if(enRet != Ok) {
		Error_Handler();
	}
	enRet = USART_SetBaudrate(RS485_CH1_USART_CH, BaudRate);
	if(enRet != Ok) {
		Error_Handler();
	}
	
	stcIrqRegiCfg.enIRQn = RS485CH1_UART_IRQn;
	stcIrqRegiCfg.pfnCallback = &RS485Ch1UsartRxIrqCallback;
	stcIrqRegiCfg.enIntSrc = RS485_CH1_USART_RI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);


	/* Set USART RX error IRQ */
	stcIrqRegiCfg.enIRQn = RS485CH1_UART_EI_IRQn;
	stcIrqRegiCfg.pfnCallback = &RS485Ch1UsartErrIrqCallback;
	stcIrqRegiCfg.enIntSrc = RS485_CH1_USART_EI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
	
#if 0	
	/* Set USART TX IRQ */
	stcIrqRegiCfg.enIRQn = Int002_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);

	/* Set USART TX complete IRQ */
	stcIrqRegiCfg.enIRQn = Int003_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxCmpltIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TCI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
#endif	
	USART_FuncCmd(RS485_CH1_USART_CH, UsartTx, Enable);
	USART_FuncCmd(RS485_CH1_USART_CH, UsartRx, Enable);
	USART_FuncCmd(RS485_CH1_USART_CH, UsartRxInt, Enable);
}

/*****************************************************************************************
* 函数名称: RS485Ch1UartSend
* 功能描述: RS485通道1串口发送函数
* 参    数: sData 发送数据入口指针
            sLen  发送数据长度
* 返 回 值: 无
*****************************************************************************************/
void RS485Ch1UartSend(uint8_t *sData, uint16_t sLen)
{
	RS485_CH1_TX();
	for(int i = 0; i < sLen; i++) {
		USART_SendData(RS485_CH1_USART_CH, sData[i]);
		while(USART_GetStatus(RS485_CH1_USART_CH, UsartTxComplete) == Reset);
	}
	RS485_CH1_RX();
}

/*****************************************************************************************
 * RS485Ch2 Uart
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: RS485Ch1UartRec
* 功能描述: RS485通道1串口接收函数
* 参    数: 无
* 返 回 值: 返回收到的字符
*****************************************************************************************/
static uint8_t RS485Ch2UartRec(void)
{
	uint16_t u16Data = USART_RecData(RS485_CH2_USART_CH);
	return (uint8_t)u16Data;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartErrIrqCallback
* 功能描述: RS485通道1串口错误中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void RS485Ch2UsartErrIrqCallback(void)
{
	if(RS485_CH2_USART_CH->SR_f.ORE) {
		RS485_CH2_USART_CH->CR1_f.CORE = 1;
		USART_RecData(RS485_CH2_USART_CH);
	}
	
	if(RS485_CH2_USART_CH->SR_f.PE)
		RS485_CH2_USART_CH->CR1_f.CPE = 1;
	
	if(RS485_CH2_USART_CH->SR_f.FE)
		RS485_CH2_USART_CH->CR1_f.CFE = 1;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartRxIrqCallback
* 功能描述: RS485通道1串口接收中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void RS485Ch2UsartRxIrqCallback(void)
{
	uint8_t rData = RS485Ch2UartRec();
	RS485Ch2RxIrqCallback(rData);
}

/*****************************************************************************************
* 函数名称: RS485Ch1_Config
* 功能描述: RS485通道1配置函数
* 参    数: BaudRate 串口波特率
* 返 回 值: 无
*****************************************************************************************/
void RS485Ch2_Config(uint32_t BaudRate)
{
	stc_usart_uart_init_t stcInitCfg;
	stc_irq_regi_conf_t stcIrqRegiCfg;
	en_result_t enRet;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(RS485_CH2_USART_RX_PORT, RS485_CH2_USART_RX_PIN, &stcPortInit);
	PORT_Init(RS485_CH2_USART_TX_PORT, RS485_CH2_USART_TX_PIN, &stcPortInit);
	
	stcInitCfg.enClkMode = UsartIntClkCkNoOutput;
	stcInitCfg.enClkDiv = UsartClkDiv_16;
	stcInitCfg.enDataLength = UsartDataBits8;
	stcInitCfg.enDirection = UsartDataLsbFirst;
	stcInitCfg.enStopBit = UsartOneStopBit;
	stcInitCfg.enParity = UsartParityNone;
	stcInitCfg.enSampleMode = UsartSampleBit8;
	stcInitCfg.enDetectMode = UsartStartBitFallEdge;
	stcInitCfg.enHwFlow = UsartRtsEnable;
	
	PWC_Fcg1PeriphClockCmd(RS485_CH2_FCG1_PERIPH, Enable);
	
	PORT_SetFunc(RS485_CH2_USART_RX_PORT, RS485_CH2_USART_RX_PIN, RS485_CH2_USART_RX_FUNC, Disable);
	PORT_SetFunc(RS485_CH2_USART_TX_PORT, RS485_CH2_USART_TX_PIN, RS485_CH2_USART_TX_FUNC, Disable);
	
	enRet = USART_UART_Init(RS485_CH2_USART_CH, &stcInitCfg);
	if(enRet != Ok) {
		Error_Handler();
	}
	enRet = USART_SetBaudrate(RS485_CH2_USART_CH, BaudRate);
	if(enRet != Ok) {
		Error_Handler();
	}
	
	stcIrqRegiCfg.enIRQn = RS485CH2_UART_IRQn;
	stcIrqRegiCfg.pfnCallback = &RS485Ch2UsartRxIrqCallback;
	stcIrqRegiCfg.enIntSrc = RS485_CH2_USART_RI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);


	/* Set USART RX error IRQ */
	stcIrqRegiCfg.enIRQn = RS485CH2_UART_EI_IRQn;
	stcIrqRegiCfg.pfnCallback = &RS485Ch2UsartErrIrqCallback;
	stcIrqRegiCfg.enIntSrc = RS485_CH2_USART_EI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
	
#if 0	
	/* Set USART TX IRQ */
	stcIrqRegiCfg.enIRQn = Int002_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);

	/* Set USART TX complete IRQ */
	stcIrqRegiCfg.enIRQn = Int003_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxCmpltIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TCI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
#endif	
	USART_FuncCmd(RS485_CH2_USART_CH, UsartTx, Enable);
	USART_FuncCmd(RS485_CH2_USART_CH, UsartRx, Enable);
	USART_FuncCmd(RS485_CH2_USART_CH, UsartRxInt, Enable);
}

/*****************************************************************************************
* 函数名称: RS485Ch1UartSend
* 功能描述: RS485通道1串口发送函数
* 参    数: sData 发送数据入口指针
            sLen  发送数据长度
* 返 回 值: 无
*****************************************************************************************/
void RS485Ch2UartSend(uint8_t *sData, uint16_t sLen)
{
	RS485_CH2_TX();
	for(int i = 0; i < sLen; i++) {
		USART_SendData(RS485_CH2_USART_CH, sData[i]);
		while(USART_GetStatus(RS485_CH2_USART_CH, UsartTxComplete) == Reset);
	}
	RS485_CH2_RX();
}



/*****************************************************************************************
 * Eth Or Cat1 Uart
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: EthOrCat1UartRec
* 功能描述: cat1和eth串口接收函数
* 参    数: 无
* 返 回 值: 返回收到的字符
*****************************************************************************************/
static uint8_t EthOrCat1UartRec(void)
{
	uint16_t u16Data = USART_RecData(ETH_OR_CAT1_USART_CH);
	return (uint8_t)u16Data;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartErrIrqCallback
* 功能描述: cat1和eth串口错误中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void EthOrCat1UsartErrIrqCallback(void)
{
	if(ETH_OR_CAT1_USART_CH->SR_f.ORE) {
		ETH_OR_CAT1_USART_CH->CR1_f.CORE = 1;
		USART_RecData(ETH_OR_CAT1_USART_CH);
	}
	
	if(ETH_OR_CAT1_USART_CH->SR_f.PE)
		ETH_OR_CAT1_USART_CH->CR1_f.CPE = 1;
	
	if(ETH_OR_CAT1_USART_CH->SR_f.FE)
		ETH_OR_CAT1_USART_CH->CR1_f.CFE = 1;
}

/*****************************************************************************************
* 函数名称: RS485Ch1UsartRxIrqCallback
* 功能描述: cat1和eth串口接收中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void EthOrCat1UsartRxIrqCallback(void)
{
	uint8_t rData =EthOrCat1UartRec();
	EthOrCat1RxIrqCallback(rData);
}


/*****************************************************************************************
* 函数名称: RS485Ch1_Config
* 功能描述: cat1和eth串口配置函数
* 参    数: BaudRate 串口波特率
* 返 回 值: 无
*****************************************************************************************/
void EthOrCat1_Config(uint32_t BaudRate)
{
	stc_usart_uart_init_t stcInitCfg;
	stc_irq_regi_conf_t stcIrqRegiCfg;
	en_result_t enRet;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(ETH_OR_CAT1_USART_RX_PORT, ETH_OR_CAT1_USART_RX_PIN, &stcPortInit);
	PORT_Init(ETH_OR_CAT1_USART_TX_PORT, ETH_OR_CAT1_USART_TX_PIN, &stcPortInit);
	
	stcInitCfg.enClkMode = UsartIntClkCkNoOutput;
	stcInitCfg.enClkDiv = UsartClkDiv_1;
	stcInitCfg.enDataLength = UsartDataBits8;
	stcInitCfg.enDirection = UsartDataLsbFirst;
	stcInitCfg.enStopBit = UsartOneStopBit;
	stcInitCfg.enParity = UsartParityNone;
	stcInitCfg.enSampleMode = UsartSampleBit8;
	stcInitCfg.enDetectMode = UsartStartBitFallEdge;
	stcInitCfg.enHwFlow = UsartRtsEnable;
	
	PWC_Fcg1PeriphClockCmd(ETH_OR_CAT1_FCG1_PERIPH, Enable);
	
	PORT_SetFunc(ETH_OR_CAT1_USART_RX_PORT, ETH_OR_CAT1_USART_RX_PIN, ETH_OR_CAT1_USART_RX_FUNC, Disable);
	PORT_SetFunc(ETH_OR_CAT1_USART_TX_PORT, ETH_OR_CAT1_USART_TX_PIN, ETH_OR_CAT1_USART_TX_FUNC, Disable);
	
	enRet = USART_UART_Init(ETH_OR_CAT1_USART_CH, &stcInitCfg);
	if(enRet != Ok) {
		Error_Handler();
	}
	enRet = USART_SetBaudrate(ETH_OR_CAT1_USART_CH, BaudRate);
	if(enRet != Ok) {
		Error_Handler();
	}
	
	stcIrqRegiCfg.enIRQn = ETH_OR_CAT1_UART_IRQn;
	stcIrqRegiCfg.pfnCallback = &EthOrCat1UsartRxIrqCallback;
	stcIrqRegiCfg.enIntSrc = ETH_OR_CAT1_USART_RI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);


	/* Set USART RX error IRQ */
	stcIrqRegiCfg.enIRQn = ETH_OR_CAT1_UART_EI_IRQn;
	stcIrqRegiCfg.pfnCallback = &EthOrCat1UsartErrIrqCallback;
	stcIrqRegiCfg.enIntSrc = ETH_OR_CAT1_USART_EI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
	
#if 0	
	/* Set USART TX IRQ */
	stcIrqRegiCfg.enIRQn = Int002_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);

	/* Set USART TX complete IRQ */
	stcIrqRegiCfg.enIRQn = Int003_IRQn;
	stcIrqRegiCfg.pfnCallback = &UsartTxCmpltIrqCallback;
	stcIrqRegiCfg.enIntSrc = USART_TCI_NUM;
	enIrqRegistration(&stcIrqRegiCfg);
	NVIC_SetPriority(stcIrqRegiCfg.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
	NVIC_ClearPendingIRQ(stcIrqRegiCfg.enIRQn);
	NVIC_EnableIRQ(stcIrqRegiCfg.enIRQn);
#endif	
	USART_FuncCmd(ETH_OR_CAT1_USART_CH, UsartTx, Enable);
	USART_FuncCmd(ETH_OR_CAT1_USART_CH, UsartRx, Enable);
	USART_FuncCmd(ETH_OR_CAT1_USART_CH, UsartRxInt, Enable);
}

/*****************************************************************************************
* 函数名称: EthOrCat1UartSend
* 功能描述: cat1和eth串口发送函数
* 参    数: sData 发送数据入口指针
            sLen  发送数据长度
* 返 回 值: 无
*****************************************************************************************/
void EthOrCat1UartSend(uint8_t *sData, uint16_t sLen)
{
	for(int i = 0; i < sLen; i++) {
		USART_SendData(ETH_OR_CAT1_USART_CH, sData[i]);
		while(USART_GetStatus(ETH_OR_CAT1_USART_CH, UsartTxComplete) == Reset);
	}
}



/*****************************************************************************************
 * GPIO
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: LoraDio0IrqCallback
* 功能描述: LORA DIO0中断回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void LoraDio0IrqCallback(void)
{
	EXINT_IrqFlgClr(LORA_DIO_EXIT_CH);
	LoraTxRxIrqCallback();
}

/*****************************************************************************************
* 函数名称: GPIO_Config
* 功能描述: GPIO配置函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void GPIO_Config(void)
{
	stc_port_init_t stcPortInit;
	stc_port_pub_set_t stcPortPub;
	stc_exint_config_t stcExtiConfig;
	stc_irq_regi_conf_t stcIrqRegiConf;
	
	PORT_DebugPortSetting(TDO_SWO, Disable);
	PORT_DebugPortSetting(TDI, Disable);
	PORT_DebugPortSetting(TRST, Disable);
	
	MEM_ZERO_STRUCT(stcPortInit);
	MEM_ZERO_STRUCT(stcPortPub);
	
	stcPortPub.enReadWait = WaitCycle3;
	PORT_PubSetting(&stcPortPub);
	
	stcPortInit.enPinMode = Pin_Mode_Out;
	stcPortInit.enPinOType = Pin_OType_Cmos;
	stcPortInit.enPinDrv = Pin_Drv_H;
	stcPortInit.enPullUp = Disable;
	PORT_Init(RS485_CH1_CTRL_PORT, RS485_CH1_CTRL_PIN, &stcPortInit);
	RS485_CH1_RX();
	
	PORT_Init(RS485_CH1_POW_PORT, RS485_CH1_POW_PIN, &stcPortInit);
	RS485_CH1_POW_OFF();
	
//	PORT_Init(RS485_CH1_VOL_CTRL_PORT, RS485_CH1_VOL_CTRL_PIN, &stcPortInit);
//	RS485_CH1_VOL_5V();
	
	PORT_Init(RS485_CH2_CTRL_PORT, RS485_CH2_CTRL_PIN, &stcPortInit);
	RS485_CH2_RX();
	
	PORT_Init(RS485_CH2_POW_PORT, RS485_CH2_POW_PIN, &stcPortInit);
	RS485_CH2_POW_OFF();
	
//	PORT_Init(RS485_CH2_VOL_CTRL_PORT, RS485_CH2_VOL_CTRL_PIN, &stcPortInit);
//	RS485_CH1_VOL_5V();
	
	PORT_Init(ETH_OR_CAT1_CTRL_PORT, ETH_OR_CAT1_CTRL_PIN, &stcPortInit);
//	PORT_Init(ETH_OR_CAT1_TX_CTRL_PORT, ETH_OR_CAT1_TX_CTRL_PIN, &stcPortInit);
	ETH_ON();
	
	PORT_Init(CAT1_PWR_KEY_PORT, CAT1_PWR_KEY_PIN, &stcPortInit);
	CAT1_PWR_KEY_SET();
	
	PORT_Init(CAT1_RESET_PORT, CAT1_RESET_PIN, &stcPortInit);
	CAT1_RESET_CLR();
	
//	PORT_Init(CAT1_POW_PORT, CAT1_POW_PIN, &stcPortInit);
//	CAT1_POW_OFF();
	
	PORT_Init(ETH_RESET_PORT, ETH_RESET_PIN, &stcPortInit);
	ETH_RESET_CLR();
	
	PORT_Init(ETH_DEF_PORT, ETH_DEF_PIN, &stcPortInit);
	ETH_DEF_SET();
	
//	PORT_Init(SPI_NSS_PORT, SPI_NSS_PIN, &stcPortInit);
//	SPI_NSS_SET();

//	PORT_Init(SPI2_NSS_PORT, SPI2_NSS_PIN, &stcPortInit);
//	SPI2_NSS_SET();

	PORT_Init(LORA_RESET_PORT, LORA_RESET_PIN, &stcPortInit);
	LORA_RESET_SET();

	PORT_Init(LORA_RXEN_PORT, LORA_RXEN_PIN, &stcPortInit);
	LORA_RXEN_SET();
	
	PORT_Init(LORA_TXEN_PORT, LORA_TXEN_PIN, &stcPortInit);
	LORA_TXEN_CLR();
	
	PORT_Init(POWER_LED_PORT, POWER_LED_PIN, &stcPortInit);
	POWER_LED_OFF();
	
	PORT_Init(LORA_RX_LED_PORT, LORA_RX_LED_PIN, &stcPortInit);
	LORA_RX_LED_CLR();
	
	PORT_Init(LORA_POW_PORT, LORA_POW_PIN, &stcPortInit);
	LORA_POW_OFF();
	
	stcPortInit.enPinMode = Pin_Mode_In;
	PORT_Init(ETH_LINK_PORT, ETH_LINK_PIN, &stcPortInit);
	
	stcPortInit.enExInt = Enable;
	stcPortInit.enPullUp = Enable;
	PORT_Init(LORA_DIO_PORT, LORA_DIO_PIN, &stcPortInit);
	
	stcExtiConfig.enExitCh = LORA_DIO_EXIT_CH;
	stcExtiConfig.enFilterEn = Enable;
	stcExtiConfig.enFltClk = Pclk3Div8;
	stcExtiConfig.enExtiLvl = ExIntRisingEdge;
	EXINT_Init(&stcExtiConfig);
	
	stcIrqRegiConf.enIntSrc = LORA_DIO_EXIT_SRC;		 /* Select External Int Ch.1 */
	stcIrqRegiConf.enIRQn = LORA_DIO0_IRQn;					/* Register External Int to Vect.No.000 */
	stcIrqRegiConf.pfnCallback = &LoraDio0IrqCallback;		 /* Callback function */
	enIrqRegistration(&stcIrqRegiConf);		 /* Registration IRQ */
	NVIC_ClearPendingIRQ(stcIrqRegiConf.enIRQn);			 /* Clear pending */
	NVIC_SetPriority(stcIrqRegiConf.enIRQn, DDL_IRQ_PRIORITY_00);			 /* Set priority */
	NVIC_EnableIRQ(stcIrqRegiConf.enIRQn);			 /* Enable NVIC */
	//enIntWakeupEnable(Extint2WU);
}


/*****************************************************************************************
 * SPI1 spiflash
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: Spi1_Config
* 功能描述: SPI1配置函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Spi1_Config(void)
{
	stc_spi_init_t stcSpiInit;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(SPI_SCK_PORT, SPI_SCK_PIN, &stcPortInit);
	PORT_Init(SPI_MOSI_PORT, SPI_MOSI_PIN, &stcPortInit);
	PORT_Init(SPI_MISO_PORT, SPI_MISO_PIN, &stcPortInit);
	stcPortInit.enPinMode = Pin_Mode_Out;
	stcPortInit.enPinOType = Pin_OType_Cmos;
	stcPortInit.enPinDrv = Pin_Drv_H;
	stcPortInit.enPullUp = Disable;
	PORT_Init(SPI_NSS_PORT, SPI_NSS_PIN, &stcPortInit);
	SPI_NSS_SET();
	/* configuration structure initialization */
	MEM_ZERO_STRUCT(stcSpiInit);

	/* Configuration peripheral clock */
	PWC_Fcg1PeriphClockCmd(SPI_UNIT_CLOCK, Enable);

	/* Configuration SPI pin */
	PORT_SetFunc(SPI_SCK_PORT, SPI_SCK_PIN, SPI_SCK_FUNC, Disable);
	PORT_SetFunc(SPI_MOSI_PORT, SPI_MOSI_PIN, SPI_MOSI_FUNC, Disable);
	PORT_SetFunc(SPI_MISO_PORT, SPI_MISO_PIN, SPI_MISO_FUNC, Disable);

	/* Configuration SPI structure */
	stcSpiInit.enClkDiv = SpiClkDiv16;
	stcSpiInit.enFrameNumber = SpiFrameNumber1;
	stcSpiInit.enDataLength = SpiDataLengthBit8;
	stcSpiInit.enFirstBitPosition = SpiFirstBitPositionMSB;
	stcSpiInit.enSckPolarity = SpiSckIdleLevelHigh;
	stcSpiInit.enSckPhase = SpiSckOddChangeEvenSample;
	stcSpiInit.enReadBufferObject = SpiReadReceiverBuffer;
	stcSpiInit.enWorkMode = SpiWorkMode4Line;
	stcSpiInit.enTransMode = SpiTransFullDuplex;
	stcSpiInit.enCommAutoSuspendEn = Disable;
	stcSpiInit.enModeFaultErrorDetectEn = Disable;
	stcSpiInit.enParitySelfDetectEn = Disable;
	stcSpiInit.enParityEn = Disable;
	stcSpiInit.enParity = SpiParityEven;

#ifdef SPI_MASTER_MODE
	stcSpiInit.enMasterSlaveMode = SpiModeMaster;
	stcSpiInit.stcDelayConfig.enSsSetupDelayOption = SpiSsSetupDelayCustomValue;
	stcSpiInit.stcDelayConfig.enSsSetupDelayTime = SpiSsSetupDelaySck1;
	stcSpiInit.stcDelayConfig.enSsHoldDelayOption = SpiSsHoldDelayCustomValue;
	stcSpiInit.stcDelayConfig.enSsHoldDelayTime = SpiSsHoldDelaySck1;
	stcSpiInit.stcDelayConfig.enSsIntervalTimeOption = SpiSsIntervalCustomValue;
	stcSpiInit.stcDelayConfig.enSsIntervalTime = SpiSsIntervalSck6PlusPck2;
	stcSpiInit.stcSsConfig.enSsValidBit = SpiSsValidChannel0;
	stcSpiInit.stcSsConfig.enSs0Polarity = SpiSsLowValid;
#endif

#ifdef SPI_SLAVE_MODE
	stcSpiInit.enMasterSlaveMode = SpiModeSlave;
	stcSpiInit.stcSsConfig.enSsValidBit = SpiSsValidChannel0;
	stcSpiInit.stcSsConfig.enSs0Polarity = SpiSsLowValid;
#endif

	SPI_Init(SPI_UNIT, &stcSpiInit);
	SPI_Cmd(SPI_UNIT, Enable);
}

/*****************************************************************************************
* 函数名称: Spi1SendReceive
* 功能描述: SPI1发送接收函数
* 参    数: sData 发送的数据入库哦
* 返 回 值: 接收到的数据
*****************************************************************************************/
uint16_t Spi1SendReceive(uint16_t sData)
{
	uint16_t retry = 0;
	uint16_t rData;

	/* Wait tx buffer empty */
	while (Reset == SPI_GetFlag(SPI_UNIT, SpiFlagSendBufferEmpty)) {
		retry++;
		if(retry > 0x4000)
			return 0;
	}
	
	/* Send data */
	SPI_SendData8(SPI_UNIT, sData);
	
	/* Wait rx buffer full */
	retry = 0;
	while (Reset == SPI_GetFlag(SPI_UNIT, SpiFlagReceiveBufferFull)) {
		retry++;
		if(retry > 0x4000)
			return 0;
	}
	/* Receive data */
	rData = SPI_ReceiveData8(SPI_UNIT);
	
	return rData;
}


/*****************************************************************************************
 * SPI2 spiflash
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: Spi2_Config
* 功能描述: SPI2配置函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Spi2_Config(void)
{
	stc_spi_init_t stcSpiInit;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	
	stcPortInit.enPinOType = Pin_OType_Cmos;
	PORT_Init(SPI2_SCK_PORT, SPI2_SCK_PIN, &stcPortInit);
	PORT_Init(SPI2_MOSI_PORT, SPI2_MOSI_PIN, &stcPortInit);
	PORT_Init(SPI2_MISO_PORT, SPI2_MISO_PIN, &stcPortInit);
	//PORT_Init(SPI2_NSS_PORT, SPI2_NSS_PIN, &stcPortInit);
	stcPortInit.enPinMode = Pin_Mode_Out;
	stcPortInit.enPinOType = Pin_OType_Cmos;
	stcPortInit.enPinDrv = Pin_Drv_H;
	stcPortInit.enPullUp = Disable;
	PORT_Init(SPI2_NSS_PORT, SPI2_NSS_PIN, &stcPortInit);
	SPI2_NSS_SET();
	/* configuration structure initialization */
	MEM_ZERO_STRUCT(stcSpiInit);

	/* Configuration peripheral clock */
	PWC_Fcg1PeriphClockCmd(SPI2_UNIT_CLOCK, Enable);

	/* Configuration SPI pin */
	PORT_SetFunc(SPI2_SCK_PORT, SPI2_SCK_PIN, SPI2_SCK_FUNC, Disable);
	PORT_SetFunc(SPI2_MOSI_PORT, SPI2_MOSI_PIN, SPI2_MOSI_FUNC, Disable);
	PORT_SetFunc(SPI2_MISO_PORT, SPI2_MISO_PIN, SPI2_MISO_FUNC, Disable);
	//PORT_SetFunc(SPI2_NSS_PORT, SPI2_NSS_PIN, SPI2_NSS_FUNC, Disable);
	
	/* Configuration SPI structure */
	stcSpiInit.enClkDiv = SpiClkDiv16;
	stcSpiInit.enFrameNumber = SpiFrameNumber1;
	stcSpiInit.enDataLength = SpiDataLengthBit8;
	stcSpiInit.enFirstBitPosition = SpiFirstBitPositionMSB;
	stcSpiInit.enSckPolarity = SpiSckIdleLevelHigh;
	stcSpiInit.enSckPhase = SpiSckOddChangeEvenSample;
	stcSpiInit.enReadBufferObject = SpiReadReceiverBuffer;
	stcSpiInit.enWorkMode = SpiWorkMode4Line;
	stcSpiInit.enTransMode = SpiTransFullDuplex;
	stcSpiInit.enCommAutoSuspendEn = Disable;
	stcSpiInit.enModeFaultErrorDetectEn = Disable;
	stcSpiInit.enParitySelfDetectEn = Disable;
	stcSpiInit.enParityEn = Disable;
	stcSpiInit.enParity = SpiParityEven;

#ifdef SPI_MASTER_MODE
	stcSpiInit.enMasterSlaveMode = SpiModeMaster;
	stcSpiInit.stcDelayConfig.enSsSetupDelayOption = SpiSsSetupDelayCustomValue;
	stcSpiInit.stcDelayConfig.enSsSetupDelayTime = SpiSsSetupDelaySck1;
	stcSpiInit.stcDelayConfig.enSsHoldDelayOption = SpiSsHoldDelayCustomValue;
	stcSpiInit.stcDelayConfig.enSsHoldDelayTime = SpiSsHoldDelaySck1;
	stcSpiInit.stcDelayConfig.enSsIntervalTimeOption = SpiSsIntervalCustomValue;
	stcSpiInit.stcDelayConfig.enSsIntervalTime = SpiSsIntervalSck8PlusPck2;
	stcSpiInit.stcSsConfig.enSsValidBit = SpiSsValidChannel0;
	stcSpiInit.stcSsConfig.enSs0Polarity = SpiSsLowValid;
#endif

#ifdef SPI_SLAVE_MODE
	stcSpiInit.enMasterSlaveMode = SpiModeSlave;
	stcSpiInit.stcSsConfig.enSsValidBit = SpiSsValidChannel0;
	stcSpiInit.stcSsConfig.enSs0Polarity = SpiSsLowValid;
#endif

	SPI_Init(SPI2_UNIT, &stcSpiInit);
	SPI_Cmd(SPI2_UNIT, Enable);
}

/*****************************************************************************************
* 函数名称: Spi2SendReceive
* 功能描述: SPI2发送接收函数
* 参    数: sData 发送的数据入库哦
* 返 回 值: 接收到的数据
*****************************************************************************************/
uint16_t Spi2SendReceive(uint16_t sData)
{
	uint16_t retry = 0;
	uint16_t rData;

	/* Wait tx buffer empty */
	while (Reset == SPI_GetFlag(SPI2_UNIT, SpiFlagSendBufferEmpty)) {
		retry++;
		if(retry > 0x4000)
			return 0;
	}
	
	/* Send data */
	SPI_SendData8(SPI2_UNIT, sData);
	
	/* Wait rx buffer full */
	retry = 0;
	while (Reset == SPI_GetFlag(SPI2_UNIT, SpiFlagReceiveBufferFull)) {
		retry++;
		if(retry > 0x4000)
			return 0;
	}
	/* Receive data */
	rData = SPI_ReceiveData8(SPI2_UNIT);
	
	return rData;
}

/*****************************************************************************************
* 函数名称: Rtc_Config
* 功能描述: RTC配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Rtc_Config(void)
{
	stc_rtc_init_t stcRtcInit;
	stc_irq_regi_conf_t stcIrqRegiConf;

	/* configuration structure initialization */
	MEM_ZERO_STRUCT(stcRtcInit);
	MEM_ZERO_STRUCT(stcIrqRegiConf);

	/* Reset rtc counter */
	if (RTC_DeInit() == ErrorTimeout) {
		//DBG_LOG("Reset RTC Failed!\r\n");
	}
	else {
		/* Configuration rtc structure */
		stcRtcInit.enClkSource = RtcClkXtal32;
		stcRtcInit.enPeriodInt = RtcPeriodIntInvalid;
		stcRtcInit.enTimeFormat = RtcTimeFormat24Hour;
		stcRtcInit.enCompenWay = RtcOutputCompenDistributed;
		stcRtcInit.enCompenEn = Disable;
		stcRtcInit.u16CompenVal = 0u;
		RTC_Init(&stcRtcInit);

//		/* Configure interrupt of rtc period */
//		stcIrqRegiConf.enIntSrc = INT_RTC_PRD;
//		stcIrqRegiConf.enIRQn = RTC_IRQn;
//		stcIrqRegiConf.pfnCallback = &RtcPeriod_IrqCallback;
//		enIrqRegistration(&stcIrqRegiConf);
//		NVIC_ClearPendingIRQ(stcIrqRegiConf.enIRQn);
//		NVIC_SetPriority(stcIrqRegiConf.enIRQn, DDL_IRQ_PRIORITY_DEFAULT);
//		NVIC_EnableIRQ(stcIrqRegiConf.enIRQn);
//		enIntWakeupEnable(RtcPeriodWU);
//		/* Enable period interrupt */
//		RTC_IrqCmd(RtcIrqPeriod, Enable);
		/* Startup rtc count */
		RTC_Cmd(Enable);
	}
}


/*****************************************************************************************
* 函数名称: AdcInitConfig
* 功能描述: ADC初始化配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void AdcInitConfig(void)
{
	stc_adc_init_t stcAdcInit;

	MEM_ZERO_STRUCT(stcAdcInit);

	stcAdcInit.enResolution = AdcResolution_12Bit;
	stcAdcInit.enDataAlign  = AdcDataAlign_Right;
	stcAdcInit.enAutoClear  = AdcClren_Enable;
	stcAdcInit.enScanMode   = AdcMode_SAOnce;
	stcAdcInit.enRschsel    = AdcRschsel_Restart;
	/* 1. Enable ADC1. */
	PWC_Fcg3PeriphClockCmd(PWC_FCG3_PERIPH_ADC1, Enable);
	/* 2. Initialize ADC1. */
	ADC_Init(M4_ADC1, &stcAdcInit);
}

/*****************************************************************************************
* 函数名称: AdcSetChannelPinMode
* 功能描述: ADC通道引脚配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void AdcSetChannelPinMode(uint32_t u32Channel)
{
	en_port_t enPort;
	en_pin_t enPin;
	stc_port_init_t stcPortInit;

	MEM_ZERO_STRUCT(stcPortInit);
	stcPortInit.enPinMode = Pin_Mode_Ana;
	stcPortInit.enPullUp  = Disable;
	
	switch (u32Channel) {
		case ADC1_CH0: enPort = PortA; enPin  = Pin00; break;
		case ADC1_CH1: enPort = PortA; enPin  = Pin01; break;
		case ADC1_CH2: enPort = PortA; enPin  = Pin02; break;
		case ADC1_CH3: enPort = PortA; enPin  = Pin03; break;
		case ADC1_CH4: enPort = PortA; enPin  = Pin04; break;
		case ADC1_CH5: enPort = PortA; enPin  = Pin05; break;
		case ADC1_CH6: enPort = PortA; enPin  = Pin06; break;
		case ADC1_CH7: enPort = PortA; enPin  = Pin07; break;
		case ADC1_CH8: enPort = PortB; enPin  = Pin00; break;
		case ADC1_CH9: enPort = PortB; enPin  = Pin01; break;
		case ADC1_CH10: enPort = PortC; enPin  = Pin00; break;
		case ADC1_CH11: enPort = PortC; enPin  = Pin01; break;
		case ADC1_CH12: enPort = PortC; enPin  = Pin02; break;
		case ADC1_CH13: enPort = PortC; enPin  = Pin03; break;
		case ADC1_CH14: enPort = PortC; enPin  = Pin04; break;
		case ADC1_CH15: enPort = PortC; enPin  = Pin05; break;
		default:
				return;
	}
	PORT_Init(enPort, enPin, &stcPortInit);
}

/*****************************************************************************************
* 函数名称: AdcChannelConfig
* 功能描述: ADC通道配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void AdcChannelConfig(void)
{
	stc_adc_ch_cfg_t stcChCfg;
	uint8_t au8Adc1SaSampTime[1] = {255};

	MEM_ZERO_STRUCT(stcChCfg);

	stcChCfg.u32Channel  = BAT_COLL_ADC_CH;
	stcChCfg.u8Sequence  = ADC_SEQ_A;
	stcChCfg.pu8SampTime = au8Adc1SaSampTime;

	AdcSetChannelPinMode(BAT_COLL_ADC_CH);

	/* 2. Add ADC channel. */
	ADC_AddAdcChannel(M4_ADC1, &stcChCfg);

	/* 3. Configure the average channel if you need. */
	ADC_ConfigAvg(M4_ADC1, AdcAvcnt_256);		//平均通道配置，多次采样后输出平均值

	/* 4. Add average channel if you need. */
	ADC_AddAvgChannel(M4_ADC1, BAT_COLL_ADC_CH);
}

/*****************************************************************************************
* 函数名称: Adc1_Config
* 功能描述: ADC1配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Adc1_Config(void)
{
	CLK_SetPeriClkSource(ClkPeriSrcPclk);
	AdcInitConfig();
	AdcChannelConfig();
}


/*****************************************************************************************
* 函数名称: AdcDmaConfig
* 功能描述: ADC DMA配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void AdcDmaConfig(void)
{
	stc_dma_config_t stcDmaCfg;

	MEM_ZERO_STRUCT(stcDmaCfg);

	stcDmaCfg.u16BlockSize   = 1;
	stcDmaCfg.u16TransferCnt = 0u;
	stcDmaCfg.u32SrcAddr     = (uint32_t)(&M4_ADC1->DR1);
	stcDmaCfg.u32DesAddr     = (uint32_t)(&m_au16Adc1SaValue);
	stcDmaCfg.u16DesRptSize  = 1;
	stcDmaCfg.u16SrcRptSize  = 1;
	stcDmaCfg.u32DmaLlp      = 0u;
	stcDmaCfg.stcSrcNseqCfg.u16Cnt    = 0u;
	stcDmaCfg.stcSrcNseqCfg.u32Offset = 0u;
	stcDmaCfg.stcDesNseqCfg.u16Cnt    = 0u;
	stcDmaCfg.stcDesNseqCfg.u32Offset = 0u;
	stcDmaCfg.stcDmaChCfg.enSrcInc    = AddressIncrease;
	stcDmaCfg.stcDmaChCfg.enDesInc    = AddressIncrease;
	stcDmaCfg.stcDmaChCfg.enSrcRptEn  = Enable;
	stcDmaCfg.stcDmaChCfg.enDesRptEn  = Enable;
	stcDmaCfg.stcDmaChCfg.enSrcNseqEn = Disable;
	stcDmaCfg.stcDmaChCfg.enDesNseqEn = Disable;
	stcDmaCfg.stcDmaChCfg.enTrnWidth  = Dma16Bit;
	stcDmaCfg.stcDmaChCfg.enLlpEn     = Disable;
	 /* Enable DMA interrupt. */
	stcDmaCfg.stcDmaChCfg.enIntEn     = Enable;

	PWC_Fcg0PeriphClockCmd(PWC_FCG0_PERIPH_DMA1, Enable);
	DMA_InitChannel(M4_DMA1, DmaCh0, &stcDmaCfg);
	DMA_Cmd(M4_DMA1, Enable);
	DMA_ChannelCmd(M4_DMA1, DmaCh0, Enable);
	DMA_ClearIrqFlag(M4_DMA1, DmaCh0, TrnCpltIrq);
	/* AOS must be enabled to use DMA */
	/* AOS enabled at first. */
	/* If you have enabled AOS before, then the following statement is not needed. */
	PWC_Fcg0PeriphClockCmd(PWC_FCG0_PERIPH_AOS, Enable);
	DMA_SetTriggerSrc(M4_DMA1, DmaCh0, EVT_ADC1_EOCA);
}

/*****************************************************************************************
* 函数名称: DmaIrqRegister
* 功能描述: DMA中断寄存器配置
* 参    数: pstcCfg， 中断参数
						u32Priority， 中断优先级
* 返 回 值: 无
*****************************************************************************************/
static void DmaIrqRegister(stc_irq_regi_conf_t *pstcCfg, uint32_t u32Priority)
{
	int16_t s16Vnum = pstcCfg->enIRQn;

	if (((s16Vnum >= Int000_IRQn) && (s16Vnum <= Int031_IRQn)) || 
	((s16Vnum >= Int038_IRQn) && (s16Vnum <= Int043_IRQn)))	{
		if (Ok != enIrqRegistration(pstcCfg))
			return;
	}
	else if (Int129_IRQn == s16Vnum)
		enShareIrqEnable(pstcCfg->enIntSrc);
	else
		return;
	
	NVIC_ClearPendingIRQ(pstcCfg->enIRQn);
	NVIC_SetPriority(pstcCfg->enIRQn, u32Priority);
	NVIC_EnableIRQ(pstcCfg->enIRQn);
}

/*****************************************************************************************
* 函数名称: DmaIrqRegister
* 功能描述: DMA中断配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void DmaIrqConfig(void)
{
	stc_irq_regi_conf_t stcAdcIrqCfg;

	stcAdcIrqCfg.enIntSrc    = INT_DMA1_BTC0;
	stcAdcIrqCfg.enIRQn      = Int030_IRQn;
	stcAdcIrqCfg.pfnCallback = Dma1Btc0_IrqHandler;

	DmaIrqRegister(&stcAdcIrqCfg, DDL_IRQ_PRIORITY_03);
}

/*****************************************************************************************
* 函数名称: DmaIrqRegister
* 功能描述: DMA配置
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
static void Dma_Config(void)
{
    AdcDmaConfig();
    DmaIrqConfig();
}

/*****************************************************************************************
* 函数名称: ReadAdcValue
* 功能描述: 读取AD值
* 参    数: 无
* 返 回 值: AD值
*****************************************************************************************/
uint16_t GetADCBuffPoint(void)
{
	return m_au16Adc1SaValue;
}

/*****************************************************************************************
* 函数名称: ADC_Start
* 功能描述: 启动ADC转换
* 参    数: 无
* 返 回 值: AD值
*****************************************************************************************/
void ADC_Start(void) 
{
	ADC_StartConvert(M4_ADC1);
}
//void ReadAdcValue(uint16_t *ADValue)
//{	
//	ADC_PollingSa(M4_ADC1, ADValue, 1, 100);
//}

/*****************************************************************************************
* 函数名称: TimeGet
* 功能描述: 获取系统时间
* 参    数: tm 读取时间入口
* 返 回 值: 无
*****************************************************************************************/
void TimeGet(struct tm *cTime)
{
  stc_rtc_date_time_t RtcDateTime;
  
  RTC_GetDateTime(RtcDataFormatDec, &RtcDateTime);
  cTime->tm_year = RtcDateTime.u8Year + 100;
  cTime->tm_mon = RtcDateTime.u8Month - 1;
  cTime->tm_mday = RtcDateTime.u8Day;
  cTime->tm_hour = RtcDateTime.u8Hour;
  cTime->tm_min = RtcDateTime.u8Minute;
  cTime->tm_sec = RtcDateTime.u8Second;
  cTime->tm_isdst = 0;
}

/*****************************************************************************************
* 函数名称: TimeTs
* 功能描述: 系统时间转换时间戳
* 参    数: 无
* 返 回 值: 返回时间戳
*****************************************************************************************/
int TimeTs(void)
{
	struct tm cTime;
	
	TimeGet(&cTime);
  time_t cTimet = mktime(&cTime);
  
  return cTimet;
}

/*****************************************************************************************
* 函数名称: TimeShow
* 功能描述: 将时间输出到DBG串口
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
void TimeShow(uint32_t dwStamp)
{
  struct tm *stime;
  stime = localtime(&dwStamp);
  rt_kprintf("%d/",stime->tm_year + 1900);
  rt_kprintf("%d/",stime->tm_mon + 1);
  rt_kprintf("%d-",stime->tm_mday);
  rt_kprintf("%d:",stime->tm_hour);
  rt_kprintf("%d:",stime->tm_min);
  rt_kprintf("%d\r\n",stime->tm_sec);
}

/*****************************************************************************************
* 函数名称: TimeSync
* 功能描述: 通过时间戳同步
* 参    数: ts 时间入口
* 返 回 值: 无
*****************************************************************************************/
void TimeSync(time_t ts) 
{ 
  struct tm *td;
	stc_rtc_date_time_t RtcDateTime;
  
  td = localtime(&ts);
  
  RtcDateTime.u8Year = td->tm_year - 100;
  RtcDateTime.u8Month = td->tm_mon + 1;
  RtcDateTime.u8Day = td->tm_mday;
  RtcDateTime.u8Weekday = td->tm_wday;
  RtcDateTime.u8Hour = td->tm_hour;
  RtcDateTime.u8Minute = td->tm_min;
  RtcDateTime.u8Second = td->tm_sec;
  
	RTC_SetDateTime(RtcDataFormatDec, &RtcDateTime, Enable, Enable);
}

/*****************************************************************************************
* 函数名称: TimeSync2
* 功能描述: 通过年月日同步
* 参    数: Year 年
						Month 月
						Day 日
						Hour 时
						Min	分
						Sec 秒
* 返 回 值: 无
*****************************************************************************************/
void TimeSync2(uint8_t Year, uint8_t Month, uint8_t Day, uint8_t Hour, uint8_t Min, uint8_t Sec)
{
	stc_rtc_date_time_t RtcDateTime;
	
	if(Year > 99 || Month < 1 || Month > 12 || Day < 1 || Day > 31 || Hour > 23 || Min > 59 || Sec > 59)
		return;
	
	RtcDateTime.u8Year = Year;
	RtcDateTime.u8Month = Month;
	RtcDateTime.u8Day = Day;
  RtcDateTime.u8Hour = Hour;
  RtcDateTime.u8Minute = Min;
  RtcDateTime.u8Second = Sec;
	RTC_SetDateTime(RtcDataFormatDec, &RtcDateTime, Enable, Enable);
}
void FlashWrite(uint32_t Addr, uint32_t *wData, uint8_t wLen)
{
//	while(Ok != Flash_SectorErase(BOOT_PARA_ADDRESS));
//	for(int i = 0; i < wLen / 4; i++) {
//		Flash_WriteWord(BOOT_PARA_ADDRESS + i * 4, wData[i]);
//	}

	EFM_Unlock();

	/* Enable flash. */
	EFM_FlashCmd(Enable);
	/* Wait flash ready. */
	while(Set != EFM_GetFlagStatus(EFM_FLAG_RDY)) {	; }
	/* Sequence program. */
	//EFM_SequenceProgram(FLASH_WRITE_ADDR, wLen, wData);
	for(int i = 0; i < wLen; i++) {
		EFM_SingleProgram(Addr + i * 4, wData[i]);
	}
	
	EFM_Lock();
}

void FlashRead(uint32_t Addr,uint32_t *rData, uint8_t rLen)
{
	for(int i = 0; i < rLen / 4; i++) {
		rData[i] = *((volatile uint32_t*)(Addr + i * 4));
	}
}
void dev_boot_read_param(boot_para_t *pParam)
{
	FlashRead(FLASH_BINFO_BASE,(uint8_t *)pParam,sizeof(boot_para_t));
}
int dev_boot_write_param(boot_para_t Param)
{    
	int wLen;
	uint32_t *pData;
	
	pData= (uint32_t *)&Param;
    
	wLen = sizeof(boot_para_t)/4;
   
   EFM_Unlock();
	
	/* Enable flash. */
	EFM_FlashCmd(Enable);
	/* Wait flash ready. */
	while(Set != EFM_GetFlagStatus(EFM_FLAG_RDY)) {	; }
	/* Erase sector. */
	EFM_SectorErase(FLASH_BINFO_BASE);
   
   for(int i = 0; i < wLen; i++) {
		EFM_SingleProgram(FLASH_BINFO_BASE + i * 4, pData[i]);
	}
	/* Lock EFM. */
	EFM_Lock();
}

/*****************************************************************************************
* 函数名称: EnterStop
* 功能描述: 进入低功耗状态
* 参    数: SleepStatus 设备低功耗状态
* 返 回 值: 无
*****************************************************************************************/
//void EnterStop(void)
//{
//	stc_pwc_stop_mode_cfg_t stcPwcStopCfg;
//	stc_port_init_t stcPortInit;
//	uint16_t AnaPin;
//	
//	PWC_Fcg1PeriphClockCmd(SPI_UNIT_CLOCK, Disable);
//	PWC_Fcg1PeriphClockCmd(DBG_FCG1_PERIPH, Disable);
//	DBGRxWakeupInit();
//	
//	MEM_ZERO_STRUCT(stcPortInit);
//	stcPortInit.enPinMode = Pin_Mode_Ana;
//	AnaPin = PinAll & (~(Pin13|Pin14));
//	PORT_Init(PortA, AnaPin, &stcPortInit);
//	
//	AnaPin = PinAll & (~Pin02);
//	PORT_Init(PortB, AnaPin, &stcPortInit);
//	
//	AnaPin = PinAll & (~(Pin03));
//	PORT_Init(PortC, AnaPin, &stcPortInit);
//	
//	AnaPin = Pin02;
//	PORT_Init(PortH, AnaPin, &stcPortInit);	
//	
//	SysTick_Suspend();
//	
//	stcPwcStopCfg.enStpDrvAbi = StopUlowspeed;
//	stcPwcStopCfg.enStopClk = ClkFix;
//	stcPwcStopCfg.enStopFlash = Wait;
//	stcPwcStopCfg.enPll = Enable;
//	
//	while(Ok != PWC_StopModeCfg(&stcPwcStopCfg)){;}
//	while(1ul != M4_EFM->FSR_f.RDY){;}
//	PWC_EnterStopMd();
//}

/*****************************************************************************************
* 函数名称: Wakeup
* 功能描述: 设备唤醒
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
//void Wakeup(void)
//{
//	NVIC_DisableIRQ(DBG_RXPIN_IRQn);
//	PWC_ClkRecover();
//	//SystemClockConfig();
//	Spi_Config();
//	DbgUart_Config(500000);
//	//GPIO_Config();
//	//SysTick_Resume();
//	SysTick_Init(1000);
//}

void Error_Handler(void)
{
	while(1){ ; }
}

/*****************************************************************************************
 * Watch Dog
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: FeedDog
* 功能描述: 看门狗喂狗函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
void FeedDog(void)
{
#if (WATCH_DOG == 1)	
	 SWDT_RefreshCounter();
#endif	
}

void DelaymS(int Dly)
{
	int j;
	for(int i = 0; i < Dly; i++){
		j = 350;
		while(j > 0) j--;
	}
}

void BSP_Init(void)
{
	stc_clk_freq_t Freq;
	
	GPIO_Config();
	
	POWER_LED_ON();
	LORA_POW_OFF();
	CAT1_RESET_CLR();
	ETH_RESET_CLR();  
	FeedDog();
	for(int i = 0; i < 6; i++) {
		DelaymS(6000);
		FeedDog();
		
	}
	POWER_LED_OFF();
	
	SystemClockConfig();
	Xtal32_ClockConfig();
	   
	DbgUart_Config(500000);
	EthOrCat1_Config(115200);
//	RS485Ch1_Config(9600);
//	RS485Ch2_Config(9600);
#if USE_SD_CARD	
	SdioInit();
#endif	
	Rtc_Config();
	Spi1_Config();
	Spi2_Config();
	Adc1_Config();
	Dma_Config();
	FeedDog();
	ADC_Start();
	CLK_GetClockFreq(&Freq);
	SysTick_Init(1000);
	FeedDog();
	//DBG_LOG("SysFreq = %d\r\n", Freq.sysclkFreq);
}

/*****************************************************************************************
 * User Irq CallBack
 ****************************************************************************************/

/*****************************************************************************************
* 函数名称: LoraTxRxIrqCallback
* 功能描述: LORA收发中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void LoraTxRxIrqCallback(void)
{
	
}
/*****************************************************************************************
* 函数名称: DbgRxIrqCallback
* 功能描述: 调试串口接收中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void DbgRxIrqCallback(uint8_t rData)
{
	
}

/*****************************************************************************************
* 函数名称: RS485Ch1RxIrqCallback
* 功能描述: RS485通道1串口接收中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void RS485Ch1RxIrqCallback(uint8_t rData)
{
	
}

/*****************************************************************************************
* 函数名称: RS485Ch2RxIrqCallback
* 功能描述: RS485通道1串口接收中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void RS485Ch2RxIrqCallback(uint8_t rData)
{

}

/*****************************************************************************************
* 函数名称: EthOrCat1RxIrqCallback
* 功能描述: Eth和Cat1串口接收中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void EthOrCat1RxIrqCallback(uint8_t rData)
{

}

/*****************************************************************************************
* 函数名称: RtcPeriod_IrqCallback
* 功能描述: RTC中断回调
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
//__weak void RtcPeriod_IrqCallback(void)
//{

//}

/*****************************************************************************************
* 函数名称: Dma1Btc0_IrqHandler
* 功能描述: DMA中断外部重定向回调函数
* 参    数: 无
* 返 回 值: 无
*****************************************************************************************/
__weak void Dma1Btc0_IrqHandler(void)
{
	DMA_ClearIrqFlag(M4_DMA1, DmaCh0, BlkTrnCpltIrq);
	ADC_Start();
}
