#include "sys.h"
#include "CommandsDefine.h"
#include "usart.h"
#include "queue.h"
#include "delay.h"
u16 USART_RX_STA=0;         		//接收状态标记	
u16 USART_RX_COUNT=0;         	//计数器
u16 USART_RX_CNT=0;			//接收的字节数	
u16 USART_TOTAL_TORX=0;			//总字节数	
//////////////////////////////////////////////////////////////////////////////////
//如果使用ucos,则包括下面的头文件即可.
#if SYSTEM_SUPPORT_OS
#include "includes.h"					//ucos 使用	  
#endif
//////////////////////////////////////////////////////////////////
// 			2203/4/X GHz_ljw 合并版 加入send lock 和 延时
//////////////////////////////////////////////////////////////////

//加入以下代码,支持printf函数,而不需要选择use MicroLIB
#if 0
#pragma import(__use_no_semihosting)
//标准库需要的支持函数
struct __FILE
{
    int handle;
};

FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
void _sys_exit(int x)
{
    x = x;
}
//重定义fputc函数
int fputc(int ch, FILE *f)
{
    //while((USART6->SR&0X40)==0);//循环发送,直到发送完毕
    //USART6->DR = (u8) ch;
		//ITM_SendChar(ch);
    return ch;
}
#endif

#if EN_USART6_RX   //如果使能了接收
//串口1中断服务程序
//注意,读取USARTx->SR能避免莫名其妙的错误
u8 USART_RX_BUF[USART_REC_LEN];     //接收缓冲,最大USART_REC_LEN个字节.
u8 USART6_Send_Locked =0;
//接收状态
//bit15，	接收完成标志
//bit14，	接收到0x0d
//bit13~0，	接收到的有效字节数目



//初始化IO 串口1
//bound:波特率
void uart_init(u32 bound) 
{
		Queue_Init(&BufferQueue, BufferCMD, Q_BUFFER_SIZE);	
	
    //GPIO端口设置
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE); //使能GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);//使能USART1时钟

    //串口1对应引脚复用映射
    GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_USART6); //GPIOA9复用为USART1
    GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_USART6); //GPIOA10复用为USART1

    //USART1端口配置
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7; //GPIOA9与GPIOA10
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//复用功能
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	//速度50MHz
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉
    GPIO_Init(GPIOC,&GPIO_InitStructure); //初始化PA9，PA10

    //USART1 初始化设置
    USART_InitStructure.USART_BaudRate = bound;//波特率设置
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
    USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
    USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;	//收发模式
    USART_Init(USART6, &USART_InitStructure); //初始化串口1

    USART_Cmd(USART6, ENABLE);  //使能串口1

    USART_ClearFlag(USART6, USART_FLAG_TC);

#if EN_USART6_RX
    USART_ITConfig(USART6, USART_IT_RXNE, ENABLE);//开启相关中断

    //Usart1 NVIC 配置
    NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;//串口1中断通道
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;//抢占优先级2
    NVIC_InitStructure.NVIC_IRQChannelSubPriority =3;		//子优先级3
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
    NVIC_Init(&NVIC_InitStructure);	//根据指定的参数初始化VIC寄存器、

#endif
	for(int i=0;i<20;i++)
		Usart_RecvedPackage[i]=0xffff;
}

void USART6_Send(u8* data,int sendLength)
{
  USART_ClearFlag(USART6,USART_FLAG_TC);//如果没有该语句会丢失第一个字符
  for(int t=0; t<sendLength; t++)
  {
     USART_SendData(USART6, data[t]);
     while(USART_GetFlagStatus(USART6,USART_FLAG_TC)!=SET);
  } 
	//delay_us(100);
}

void UART_DataRev_Push_Queue()
{	
		u32	len=USART_RX_COUNT;
		Queue_Push_Array(&BufferQueue,&USART_RX_BUF[0], len);		 
			
		for(int i=0; i<len; i++)
		{
				USART_RX_BUF[i]=0;
		}//清空命令缓存
	 
    USART_RX_COUNT = 0;
}

u16 Usart_RecvedPackage[20];
u8  Usart_RecvedPackageIndex=0;
enum RecvHandleStage
{
	Stage_NoPackage=0,
	Stage_Package0x55=0x01,
	Stage_Package0xaa=0x02,
	Stage_Package0xbb=0x03,
	Stage_PackageCMD=0x04,
	Stage_PackageLen1=0x05,
	Stage_PackageLen2=0x06,
	Stage_PackageContent=0x07,
	Stage_PackageTail0x0d=0x08,
	Stage_PackageTail0x0a=0x09,
	Stage_PackageFinished=0x0a,
};
enum RecvHandleStage IRQHandlerStage=Stage_NoPackage;

//u32 erro_cnt =0;
//u8 erro_data = 0;
//u8 rx_data=0;
//u16 err_id =0;

//u8 buff[256+32]={0};
//u16 id =0;
void USART6_IRQHandler()
{
static u32 recvBuffIndex=0; 
static u8 bValid=0;	
static u16 currPackageStartIndex=0;
static u16 packageContentLen=0;
static u16 recvedContentBytes=0;	
u8 data;
	if((USART6->SR & USART_SR_RXNE))
	{
		data=USART6->DR;

//		while(!(USART6->SR & (1<<7)));//break;
//		USART6->DR=data;	
//		
//		buff[id] = data;
//		if(id!=data)
//		{
//			err_id = id;
//			rx_data=data;
//			erro_data = data;
//			erro_cnt ++;	
//		}
//		id=(id+1) % (256+32);

	}
	else
		return;
	switch(IRQHandlerStage)
	{
		case Stage_NoPackage:
				if (data==0x55)
				{
					bValid=1;
					recvedContentBytes=1;
					packageContentLen=0;
					IRQHandlerStage=Stage_Package0x55;
					currPackageStartIndex=recvBuffIndex;
				}	
				break;
		case Stage_Package0x55:
				if (data==0xaa)
				{		
					IRQHandlerStage=Stage_Package0xaa;					
				}
				else
				{
					bValid=0;
					IRQHandlerStage=Stage_NoPackage;
				}					
				break;			
		case Stage_Package0xaa:
				if (data==0xbb)
				{
					IRQHandlerStage=Stage_Package0xbb;									
				}			
				else
				{
					bValid=0;
					IRQHandlerStage=Stage_NoPackage;
				}		
				break;
		case Stage_Package0xbb:
				IRQHandlerStage=Stage_PackageCMD;		
				packageContentLen=data;
				break;				
		case Stage_PackageCMD:
				IRQHandlerStage=Stage_PackageLen1;		
				packageContentLen=data;				
				break;
		case Stage_PackageLen1:
			
				IRQHandlerStage=Stage_PackageLen2;		

				packageContentLen|=(data<<8);				
				recvedContentBytes=0;		
				if (packageContentLen==0)
					IRQHandlerStage=Stage_PackageTail0x0d;		
				break;		
		case Stage_PackageLen2:
				IRQHandlerStage=Stage_PackageContent;		
		case Stage_PackageContent:
				recvedContentBytes++;
				if (recvedContentBytes>=packageContentLen)
					IRQHandlerStage=Stage_PackageTail0x0d;		
				break;
		case Stage_PackageTail0x0d:
				if (data!=0x0d)
				{
					bValid=0;
					IRQHandlerStage=Stage_NoPackage;					
				}
				else
					IRQHandlerStage=Stage_PackageTail0x0a;		
				break;
		case Stage_PackageTail0x0a:
				if (data!=0x0a)
				{
					bValid=0;
					IRQHandlerStage=Stage_NoPackage;
				}
				else
					IRQHandlerStage=Stage_PackageFinished;		
				break;			
		default:
					break;
	}	
	
	if (bValid)
	{
		USART_RX_BUF[recvBuffIndex++]=data;
		if (recvBuffIndex>=USART_REC_LEN)
			recvBuffIndex=0; 		
	}
	if (IRQHandlerStage==Stage_PackageFinished)
	{
			Usart_RecvedPackage[Usart_RecvedPackageIndex]=currPackageStartIndex;
			Usart_RecvedPackageIndex=(Usart_RecvedPackageIndex+1) % 20;
		
			bValid=0;				
			IRQHandlerStage=Stage_NoPackage;
	}

}

#endif

