#include <reg52.h>

#include "p_apps.h"

#ifdef _USE_RS232

XCHAR pSerialBuf[64] = 0;			//need to be used in TCPconnect;
XCHAR Serial_iInData;
XCHAR Serial_iLen;
BOOLEAN Serial_bRun;

static BOOLEAN _SRStart;
static BOOLEAN _Handleing;
static XCHAR _SDnum;

void SerialInitialize()
{
	Serial_bRun = FALSE;
	_SDnum = 0;
	_SRStart = FALSE;
	TH1 = 0xfa;     // set timer 1 initial number, so the serial port baudrate to be 19200
}

void _SerialOut(UCHAR iVal)       //  unsigned char to char is error!????
{
    SBUF0 = iVal;
    while (!TI);
    TI = 0;
}

BOOLEAN CheckSData()
{
	return TRUE;
}

void _Handle()
{
	XCHAR i;
	{
		if(CheckSData())
		{
			i = 0;
			while(pSerialBuf[i] != 0xff)
			{
				i ++;
			}
			Serial_iLen = i;
			Serial_bRun = TRUE;
		}
		else
		{
		}
	}
}

void  SerialHandle()
{
	if(Serial_iInData == 0x00)
	{
		_SRStart = TRUE;
		_SDnum = 0;
		return;
	}	
	if(Serial_iInData == 0xff)
	{
		_SRStart = FALSE;
		pSerialBuf[_SDnum] = 0xff;
		_Handleing = TRUE;
		return;
	}	
	if(_SRStart)
	{
		pSerialBuf[_SDnum] = Serial_iInData;
		_SDnum ++;
		if(_SDnum > 63)
		{
			_SDnum = 0;
		}
		return;
	}
	else
	{
		_SerialOut(Serial_iInData);
	}
}

void SerialRun()
{
	XCHAR i;
	if(_Handleing)
	{
		_Handle();
		_Handleing = FALSE;
	}
   	if(Serial_bRun)
   	{
		_SerialOut(0x00);
		for(i = 0; i < Serial_iLen; i ++)
		{
			_SerialOut(pSerialBuf[i]);
		}
		_SerialOut(0xff);
		Serial_bRun = FALSE;
	}
}

#endif
