#include "debug.h"
#include "uart_hal.h"

#include "rtc_hal.h"
#include "bsp.h"
//#include "can_demo.h"
#include "can_drv.h"

static RTC_TimeTypeDef gRtcTme;
RecvBufStruct gUartRev;
u16 uartCountDown;

UINT8 Frame_AA_OK = 0;
UINT16 Frame_count = 0;

UINT8 Rx_Buffer_short[256]={0};
UINT8 Rx_Buffer_long[2048+2]={0};
UINT16  Rx_Count_short=0;
UINT16 Rx_Count_long=0;
UINT16 Rx_Num =0;
UINT16 Respond_Num = 0;
UINT16 Respond_Count= 0;

UINT8 Respond_AA_OK = 0;

////////////////////////////////////////////////////////////////////////////////// 	 


//加入以下代码,支持printf函数,而不需要选择use MicroLIB	  
#if 1
#pragma import(__use_no_semihosting)  
//解决HAL库使用时,某些情况可能报错的bug
int _ttywrch(int ch)    
{
    ch=ch;
	return ch;
}
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 
	/* Whatever you require here. If the only file you are using is */ 
	/* standard output using printf() for debugging, no file handling */ 
	/* is required. */ 
}; 
/* FILE is typedef’ d in stdio.h. */ 
FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
void _sys_exit(int x) 
{ 
	x = x; 
} 

static UART_TypeDef *UART;

//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
//	UART->CR2|= UART_CR2_TE_MASK;
	
	while( (UART->SR1&UART_SR1_TDRE_MASK)==0x00 )
	{
		;
	}		
	UART->DRL=(uint8_t)ch;
	while( (UART->SR1&UART_SR1_TC_MASK)==0x00 )
	{
		;
	}		
//	UART->CR2&= ~UART_CR2_TE_MASK;
	
	return ch;
}
#endif 
//end
//////////////////////////////////////////////////////////////////
void PrintfBuf(u8 *data,u16 len)
{
	u16 i;
	for(i=0;i<len;i++)
	{
 		if((i%16)==0) printf("\r\n");
		printf("%02x ",data[i]);
	}
	printf("\r\n");
}
									 
//pclk:PCLK时钟频率(Mhz)
//bound:波特率 
void UART_Debug_Init(UART_TypeDef *UARTx,uint32_t pclk,uint32_t bound)
{  	 
  uint32_t band_rate=0;
	
	UART = UARTx;

	UART->BRDF=(((pclk*8/bound)+1)/2)&0x003f;
	band_rate =(pclk*4/bound)>>6;
	UART->BDH=(uint8_t)((band_rate>>8)&0x00ff);
	UART->BDL=(uint8_t)(band_rate&0x00ff);	
	
	UART->CR1=0x00;
	UART->CR2=0x00;
//	UART->CR2 |= SCICR2_RIE_MASK|SCICR2_RE_MASK|UART_CR2_TE_MASK;
	UART->CR2 |= UART_CR2_TE_MASK;
//	NVIC_Init(3,3,UART1_IRQn,2);

//	UART->CR2 |= UART_RE;
	
	memset(&gUartRev, 0, sizeof(RecvBufStruct)); 
}

#if	(UART_485_CAN_FLAG==0)
void UART1_Init(uint32_t pclk,uint32_t bound)
{  	 
	uint32_t band_rate=0;	
	UART1->BRDF=(((pclk*8/bound)+1)/2)&0x003f;
	band_rate =(pclk*4/bound)>>6;
	UART1->BDH=(uint8_t)((band_rate>>8)&0x00ff);
	UART1->BDL=(uint8_t)(band_rate&0x00ff);	
	
	UART1->CR1=0x00;
	UART1->CR2=0x00;
	UART1->CR2 |= SCICR2_RIE_MASK|SCICR2_RE_MASK|UART_CR2_TE_MASK;

	NVIC_Init(1, 1,UART1_IRQn,2);
	
	memset(&gUartRev, 0, sizeof(RecvBufStruct)); 
}
#endif
#if	(UART_485_CAN_FLAG==2)
void UART1_Init(uint32_t pclk,uint32_t bound)
{ 
	InitialCan(0,0x00000008,0,500000);
	ConfigCanRx();	
}
#endif

void assert_failed(uint8_t* file, uint32_t line)
{
	printf("Wrong parameters value: file %s on line %d\r\n", file, line);
	while(1);
}


void configRtc(void)
{
	RTC_InitTypeDef rtc_init;
	RTC_TimeTypeDef time;

	rtc_init.sys_clk = g_sys_clk;
	rtc_init.set_time.days = gRtcTme.days;
	rtc_init.set_time.hours = gRtcTme.hours;
	rtc_init.set_time.minutes = gRtcTme.minutes;
	rtc_init.set_time.seconds = gRtcTme.seconds;

	rtc_init.alarm_it_type = ALARM_SEC;
	rtc_init.alarm_type = ALARM_FALL;
	rtc_init.set_aralm_time.seconds = 30;
	HAL_RTC_Init(&rtc_init);
}


void UART1_IRQHandlerEvent(void)
{
	UINT8 i = 0;
		
	if(FF_Update_Flag==0)
	{
		if((UART1->SR1 & 0x20)== 0x20)
		{
			i = UART1->DRL;
//			SCI1->SCIDRL = i;
			if(!Frame_AA_OK && i == 0xaa)
			{
				Frame_AA_OK = 1;
			}
//			printf("Uart:%x\r\n",i);
			if(Frame_AA_OK)
			{
				if(Rx_Count_long>= 2048+2)
				{
					Rx_Count_long = 0;
				}
				Rx_Buffer_short[Rx_Count_short++]= i;
				Rx_Buffer_long[Rx_Count_long++]= i;
				Rx_Num++;
				

				if(Rx_Count_short > 4 
					&& Rx_Buffer_short[Rx_Count_short - 4] == ENDBYTE_Buf[0] 
					&& Rx_Buffer_short[Rx_Count_short - 3] == ENDBYTE_Buf[1] 
					&& Rx_Buffer_short[Rx_Count_short - 2] == ENDBYTE_Buf[2] 
					&& Rx_Buffer_short[Rx_Count_short - 1] == ENDBYTE_Buf[3])
				{			
					Frame_AA_OK = 0;
					Rx_Count_short = 0;
				}
			}
			if(Frame_AA_OK && Rx_Count_short >= 255)
			{
				Frame_AA_OK = 0;
				Rx_Count_short = 0;
			}

		}
	}
	else if(FF_Update_Flag==1)
	{
		if((UART1->SR1 & 0x20)== 0x20)
		{
			gUsartRx.Buf[gUsartRx.Count++] = UART1->DRL;
			//当接收到的数据超过设定数组范围，则强制结束此次的接收。
			if(gUsartRx.Count>=RX_SIZE)
			{
				LT_UsartTimeDisable();
				PIT1->PCSR |=PIT_PCSR_PIF;
				gUsartRx.Flag=1;
			}
			else LT_UsartTimeSetCounter(58594);	//15ms
		}
	}
}

volatile u8 canNewBuf[8]={0};
volatile u8 can_count=0;
void DRV_CAN4_7_Handler(void)
{
//	UINT8 c_val = 0;
	
	volatile uint32_t status1;
	volatile uint32_t im_flg;
	volatile uint8_t  i;
	u8 ii;
	
	status1 = CAN1->CAN_IF1R;
	
	im_flg = CAN1->CAN_IM1R;
	for (i = 4; i <= 7; i++)
	{
		if (im_flg&(1<<i))
		{
			if (status1&(1<<i))
			{
				gCanIFlag1 |= (1<<i);
				if ((gCanFifoEnable == 1)&&(i == 5))
                { 
                    gCantRxMsg.IDE = (CAN1->CAN_MB[0].MB_CS >> 21)&0x1;
                    if (gCantRxMsg.IDE == DRV_CAN_ID_STD)
                    {
                        gCantRxMsg.StdId = CAN1->CAN_MB[0].MB_ID >> 18;
                    }
                    else
                    {
                        gCantRxMsg.ExtId = CAN1->CAN_MB[0].MB_ID;
                    }

                    gCantRxMsg.DLC = (CAN1->CAN_MB[0].MB_CS >> 16)&0x0f;
                    /*read data in the MB*/
                    for(UINT8 ucIndex = 0; ucIndex < gCantRxMsg.DLC; ucIndex++)
                    {
                        canDataBuf[ucIndex]= CAN1->CAN_MB[0].MB_DATA[ucIndex];
                    }
                    if(gCantRxMsg.DLC==8)
                    {                    
                        for(ii=0;ii<4;ii++)
                        {
                            canNewBuf[can_count]=canDataBuf[3-ii];
                            can_count += 1;
//                            if (gCantRx.wp >= CAN_RX_MAX_LEN)
//                                gCantRx.wp = 0;
                        }
                        for(ii=4;ii<8;ii++)
                        {
                            canNewBuf[can_count]=canDataBuf[11-ii];
                            can_count += 1;
//                            if (gCantRx.wp >= CAN_RX_MAX_LEN)
                                
                        }
						can_count = 0;
						for(ii=0;ii<8;ii++)
						{
							if(!Frame_AA_OK && canNewBuf[ii] == 0xaa)
							{
								Frame_AA_OK = 1;
							}	
							if(Frame_AA_OK)
							{
								if(Rx_Count_long>= 2048+2)
								{
									Rx_Count_long = 0;
								}
								Rx_Buffer_short[Rx_Count_short++]= canNewBuf[ii];
								Rx_Buffer_long[Rx_Count_long++]= canNewBuf[ii];
								Rx_Num++;
								
								if(Rx_Count_short > 4 
									&& Rx_Buffer_short[Rx_Count_short - 4] == ENDBYTE_Buf[0] 
									&& Rx_Buffer_short[Rx_Count_short - 3] == ENDBYTE_Buf[1] 
									&& Rx_Buffer_short[Rx_Count_short - 2] == ENDBYTE_Buf[2] 
									&& Rx_Buffer_short[Rx_Count_short - 1] == ENDBYTE_Buf[3])
								{			
									Frame_AA_OK = 0;
									Rx_Count_short = 0;
								}
							}
							if(Frame_AA_OK && Rx_Count_short >= 255)
							{
								Frame_AA_OK = 0;
								Rx_Count_short = 0;
							}
							
						}												
                    }									
                }
				
			}
		}
	}
	CAN1->CAN_IF1R = (gCanIFlag1&0x000000f0);
}


void LT_ClearRxBuf(void)
{
	UINT16 i = 0;
	for(i = 0 ; i < RX_SIZE ; i++)
	{
		gUsartRx.Buf[i] = 0;
	}
}

#if	(UART_485_CAN_FLAG==0)
void LT_DataToPc(UINT8 *buf,UINT8 len)
{
	UINT16 i = 0;

	UINT16 TxToPc_crc;
	UINT8 crc[2] = {0};
	UINT8 buff[50] = {0};
	TxToPc_crc = Rx_CRC_CCITT(buf,len);
	crc[0] = (UINT8)((TxToPc_crc >> 8) & 0x00ff);
	crc[1] = (UINT8)(TxToPc_crc & 0x00ff);
	buff[0] = 0xAA;
	for(i = 1 ; i <= len ; i++)
	{
		buff[i] = buf[i-1];
	}
	buff[len+1] = crc[0];
	buff[len + 2] = crc[1];
	buff[len + 3] = ENDBYTE_Buf[0];
	buff[len + 4] = ENDBYTE_Buf[1];
	buff[len + 5] = ENDBYTE_Buf[2];
	buff[len + 6] = ENDBYTE_Buf[3];

	for(i = 0 ; i < len +7; i++)
	{
		while ((UART1->SR1 & 0x40) == 0x00){};
		UART1->DRL = buff[i];
	}

}
#endif

#if	(UART_485_CAN_FLAG==2)
void LT_DataToPc(UINT8 *buf,UINT8 len)
{
	UINT16 i = 0;

	UINT16 TxToPc_crc;
	UINT8 crc[2] = {0};
	UINT8 buff[50] = {0};
	TxToPc_crc = Rx_CRC_CCITT(buf,len);
	crc[0] = (UINT8)((TxToPc_crc >> 8) & 0x00ff);
	crc[1] = (UINT8)(TxToPc_crc & 0x00ff);
	buff[0] = 0xAA;
	for(i = 1 ; i <= len ; i++)
	{
		buff[i] = buf[i-1];
	}
	buff[len+1] = crc[0];
	buff[len + 2] = crc[1];
	buff[len + 3] = ENDBYTE_Buf[0];
	buff[len + 4] = ENDBYTE_Buf[1];
	buff[len + 5] = ENDBYTE_Buf[2];
	buff[len + 6] = ENDBYTE_Buf[3];

//	for(i = 0 ; i < len +7; i++)
//	{
//		while ((UART1->SR1 & 0x40) == 0x00){};
//		UART1->DRL = buff[i];
//	}
	
	ConfigCanTx();			
	TransmitCanData(buff,16);
	ConfigCanRx();	

}
#endif

void LT_DataToPc_NoFrame(UINT8 *buf,UINT8 len)
{
	UINT16 i = 0;

	UINT16 TxToPc_crc;
	UINT8 crc[2] = {0};
	UINT8 buff[30] = {0};
	TxToPc_crc = Rx_CRC_CCITT(buf,len);
	crc[0] = (UINT8)((TxToPc_crc >> 8) & 0x00ff);
	crc[1] = (UINT8)(TxToPc_crc & 0x00ff);
	for(i = 0 ; i < len ; i++)
	{
		buff[i] = buf[i];
	}
	buff[len] = crc[0];
	buff[len + 1] = crc[1];

	for(i = 0 ; i < len +2; i++)
	{
		while ((UART1->SR1 & 0x40) == 0x00){};
		UART1->DRL =buff[i];
	}
}

INT8 UARTRecieved(void)
{
	if (gUartRev.wp !=gUartRev.rp)
	{
		return TRUE;
	}
	return FALSE;
}
INT8 UARTRecvByte(UINT8 *dat)
{
	if (gUartRev.wp != gUartRev.rp)
	{
		*dat = gUartRev.dat[gUartRev.rp];
		gUartRev.rp += 1;
		if (gUartRev.rp >= UART_RECV_MAX_LEN)
			gUartRev.rp = 0;
		return TRUE;
	}
	return FALSE;
}
#define RX_MAX_LEN 	256

u16 rxIndex=0;
u8 rxBuf[RX_MAX_LEN];
void HandleUartEvent(void)
{
	static u8 len=0;
	static u16 index=0;
	static u8 frameStep=0;

	uartCountDown=50;
	while(uartCountDown&&(UARTRecieved()==TRUE))
	{
		if(rxIndex>=RX_MAX_LEN)
			rxIndex=0;

		if(UARTRecvByte(rxBuf+rxIndex)==TRUE)
		{
			if(rxIndex>=1)
				if((rxBuf[rxIndex-1]==0xAA)&&(rxBuf[rxIndex]==0xBB))
				{ 		
					index=rxIndex;
					frameStep=1;	
					DelayMS(3);
					continue;
				}
			if(frameStep==1)
			{
				len++;
				if(len>=4)
				{
					//printf("Rev>>>>>>\r\n");
					//PrintfBuf(rxBuf+index,4);
					gRtcTme.days=rxBuf[index];
					gRtcTme.hours=rxBuf[(index+1)%RX_MAX_LEN];
					gRtcTme.minutes=rxBuf[(index+2)%RX_MAX_LEN];
					gRtcTme.seconds=rxBuf[(index+3)%RX_MAX_LEN];
					
					configRtc();
					
					//_rtc_prenr_rtc_dis;
					//HAL_RTC_SetTime(&gRtcTme);
					//_rtc_prenr_rtc_en;
					//HAL_RTC_GetTime(&gRtcTme);
					printf("time : D-%d [%d:%d:%d]\r\n", gRtcTme.days, gRtcTme.hours, gRtcTme.minutes, gRtcTme.seconds);
					len=0;
					frameStep=0;
					uartCountDown=0;
				}
			}
			rxIndex++;
		}
	}
}



//重定义fputc函数 
int PUTCHAR(int ch)
{      
	UART->CR2|= UART_CR2_TE_MASK;
	
	while( (UART->SR1&UART_SR1_TDRE_MASK)==0x00 )
	{
		;
	}		
	UART->DRL=(uint8_t)ch;
	while( (UART->SR1&UART_SR1_TC_MASK)==0x00 )
	{
		;
	}		
	UART->CR2&= ~UART_CR2_TE_MASK;
	
	return ch;
}

char GETCHAR()
{
  uint8_t ch;
	
	UART->CR2 |= UART_CR2_RE_MASK;
	while( (UART->SR1&UART_SR1_RDRF_MASK)==0x00 )
	{
		;
	}
	ch = UART->DRL;
	while( (UART->SR1&UART_SR1_TC_MASK)==0x00 )
	{
		;
	}
	UART->CR2 &= ~UART_CR2_RE_MASK;
	return ch;
}






