#include "NEW_8051.H"
#include "task.h"
//起始标志 0x5A 结束标志 0xA5  0x00 无反应
#define START 0X5A //起始位
#define END   0XA5 //结束位
sbit LED1=P2^5;
/*
	0x5a+C+L+DATA+CS+0xA5
	C 控制码 
	L 长度
	DATA 数据
	CS  较验和  C+L+DATA


 和取模
    接收成功返回1字节：0x06
*/

bit uart_rBIT=0;
uchar ReceVeryfy=0;
uchar ReceState=0;
uchar ucDataBuff[220];
uchar ReceCount=0;
uchar ucControlCode;
uchar ucLength;
/**********************************/
void Send_data(unsigned char d)	  /*从串口发送数据*/
{
	  ES=0;
      SBUF=d;
	  while(TI==0);       //等待发送完毕
      TI=0;
	  ES=1;
}
/*******************************************/
void MAIN_RS_INT(void) interrupt 4
{
    uchar DataTemp;
	uchar i;
     //uart_rBIT=1;
    if(RI)  // 接收
    {
		RI = 0;
		//ucUdateTime=200;
		DataTemp = SBUF;
		/************************************/
		switch (ReceState)
		{
			case 0:
				if(START == DataTemp)
                {
                    ReceState = 1;
                }
				break;
			case 1:
				ucControlCode=DataTemp;	//接收控制码
				ReceVeryfy += ucControlCode;//开始计算校验和			
				 ReceState = 2;							
				break;
			case 2:
				ucLength=DataTemp;
				ReceVeryfy += ucLength;//计算校验和
				ReceState = 3;		
				break;
			case 3:			
				if(ReceCount<ucLength)
				{
					ReceVeryfy += DataTemp;
					ucDataBuff[ReceCount]=DataTemp;
					ReceCount++;					
					
				}
				else
				{
					if(ReceVeryfy == DataTemp)
                     {
                        
						ReceVeryfy=0;
						ReceCount=0;
						ReceState=4;
						//LED1=~LED1;
                     }
					 else
					 {
					  	ReceState=0;
					 }	
				}
				break;
			   	case 4:
					 if(END == DataTemp) //接收到结束码后 串口接收标志位置1
					 {
					 	uart_rBIT=1;
						ReceState=0;
					 }
				break;
			default:				 
				ReceState=0;
				break;
		}
/**************************************************/
	if( uart_rBIT )
	{
		uart_rBIT = 0;
		switch (ucControlCode)
		{
			case 0x01://扇区擦除命令
					for(i=1;i<=ucDataBuff[0];i++)
				    {
						sector_erase(i*0x200);
					}
					Send_data(0x06);
				break;
			case 0x02://字幕数据命令
					
					for(BuffCount=0;BuffCount<ucLength;BuffCount++)
					{
						byte_program(0x200+BuffCount+uiBaseAddress,ucDataBuff[BuffCount]);//把字幕数据写入EEP 第二个扇区后所以要加上0x200
					}
					uiBaseAddress=uiBaseAddress+ucLength;
					if(ucLength<190)
					{
						uiFontNumber=uiBaseAddress;//字模的总数量
						uiBaseAddress=0;
						sector_erase(0);
						byte_program(0x100,uiFontNumber>>8);
						byte_program(0x101,uiFontNumber);	
					}
					//ucEEPArray=1;//EEP有字幕数据标志
					Send_data(0x06);
				break;
			
				case 0x04:
					ES = 0;
					//Send_data(uiBaseAddress>>8);
					//Send_data(uiBaseAddress);			
					/*for( i=0;i<250;i++ )
					{
						SBUF = byte_read(0x200+i);
						while( TI == 0 );
						TI = 0;
					}*/			
					ES = 1;
				 break;
			default:
				break;
		}

	}
			
	}
/*****************************************/
/*	if(TI)
    {
        TI = 0;
	}  */

}