
/*============================================================================
 Name        : command_fun.c
 Author      : atao
 Date  	     : 2015.9
 Copyright   : ZKSoftware Inc.
 Description : Linux C
 ============================================================================*/
#include "serial.h"
#include "libtype.h"
#include "command_fun.h"
#include "libuserCmd.h"
#include "main.h"
#include "usb.h"
#include "zkfpi.h"

U8 *DataPackage = NULL;
/************************* extSend data ****************************/
INT SendExtDataPro(INT Command, INT *Param, INT *flag, U32 timeout, U8 *buf, INT size)
{
	INT len = 0, Flag = 0, ret = 0, temp = 0, num = 0, count = 1;
	SHORT PacketNum = 0, Index = 1;
	U8 *bufPtr = buf;
	U8 *bufEnd = buf + size;
	INT len_x = 0;

	Flag = DATA_OK;

	len = (size < MAX_DATA) ? size : MAX_DATA;
	num = size / MAX_DATA;
	temp = size % MAX_DATA;

	while (1)
	{
		ret = Cmd.extSendCmd(Command, Flag, PacketNum, Index,  bufPtr, len);
		if(DEBUG)
		{
			fprintf(Fp, "================================>\r\n");
			fprintf(Fp, "ret = %d\r\n", ret);
		}

		if (ret > 0)
		{
			Cmd.extRecvCmd(Command, &Flag, &PacketNum, &Index, NULL, &len_x, timeout);
			if(DATA_OK == Flag)
			{
				bufPtr += len;
				if(num == count)
				{
					len = temp;
				}
				else
				{
					len = MAX_DATA;
				}
				//data ok
				if(bufEnd == bufPtr)
				{
					timeout = 5000;
					Cmd.RecvCmd(Command, &Flag, Param, NULL, &len_x, timeout);
					ret = 1;
					//Send extData OK!
					break;
				}
				Flag = DATA_OK;
				count++;
			}
			else
			{
				break;
			}
		}
	}
	*flag = Flag;
	return ret;
}

/************************* extRecv data ****************************/
INT RecvExtDataPro(INT Command, U32 timeout)
{
	INT len = 0, Flag = 0, sum = 0, ret = 0;
	SHORT PacketNum = 0, Index = 0;
	while (1)
	{
		ret = Cmd.extRecvCmd(Command, &Flag, &PacketNum, &Index, ExtDataBuffer.bufPtr, &len, timeout);
		if (ret > 0)
		{
			sum = ExtDataBuffer.bufEnd - ExtDataBuffer.bufPtr;
			if (sum >= len)
			{
				ExtDataBuffer.bufPtr += len;
				Flag = DATA_OK;
				if (ExtDataBuffer.bufPtr == ExtDataBuffer.bufEnd)  //data ok
				{
					Cmd.extSendCmd(Command, Flag, PacketNum, Index, NULL, 0);
					ret = 1;
					//Data OK!
					break;
				}
				else
				{
					Cmd.extSendCmd(Command, Flag, PacketNum, Index, NULL, 0);
				}
			}
			else
			{
				Flag = ERR_DATA_ERROR;
				Cmd.extSendCmd(Command, Flag, PacketNum, Index, NULL, 0);
				ret = 0;
				break;
			}
		}
		else
		{
			Flag = ERR_DATA_ERROR;
			Cmd.extSendCmd(Command, Flag, PacketNum, Index, NULL, 0);
			ret = 0;
			break;
		}
	}
	return ret;
}


INT INIT(CHAR *dev)
{
	INT ret = -1;
	//Serial initialization
	ret = ff232.init(115200, V10_8BIT, V10_NONE, 0, dev);
	if(ret <= -1)
	{
		return FAILURE;
	}
	return SUCCESS;
}

INT Send_command(INT Command, INT Param, INT Flag, U8 *DataSendbuff, INT len)
{
	INT i = 0;
	INT size = 0;
	INT sendLen = 0;
	INT value = 0;
	PRSHeader pHeader = NULL;

	DataPackage = zk_malloc(MAX_SEND);
	//Instruction initialization
	pHeader = (PRSHeader)DataPackage;	
	pHeader->Startcode = 0x70;
	pHeader->Command = Command;
	pHeader->Param = Param;
	pHeader->Size = (len > 0) ? len : 0;
	pHeader->Flag = Flag;	
	pHeader->Endcode = 0x0A;
	
	//Data Package	
	if((len > 0) && (len < MAX_BYTE) && (DataSendbuff != NULL))
	{
		memcpy(DataPackage + sizeof(TRSHeader), DataSendbuff, len);
		value = MData_chksum((U8*)(pHeader+1), len);
		memcpy(DataPackage + sizeof(TRSHeader)+len, &value, 4);
		pHeader->Size += 4;
	}
	
	pHeader->CheckSum = MHeader_chksum((U8*)pHeader);
	sendLen = pHeader->Size + sizeof(TRSHeader);//datapackage size
	
	//Send data 
	if(DEBUG)
	{
		fprintf(Fp, "[--]start Send data >>>\r\n");
		fprintf(Fp, "[--]Command : 0x%02x\r\n", pHeader->Command & 0xff);
		fprintf(Fp, "[--]Send :\r\n");
		//output setTime datapack
		if(1 == SetTime_loop)
		{
			for(i=0; i < sendLen; i++)
			{
				fprintf(Fp, "0x%02x ", *(DataPackage+i));
			}
		}
		else
		{
			for(i=0; i < sizeof(TRSHeader); i++)
			{
				fprintf(Fp, "0x%02x ", *(DataPackage+i));
			}
		}
		fprintf(Fp, "\r\n");
	}
	if(Dev_num == DEV_232)
	{
		size = ff232.write_buf(DataPackage , sendLen);
	}
	else if(Dev_num == DEV_USB)
	{
		size = usb.send(DataPackage , sendLen);
	}

	if(size < 0)
	{
		if(DEBUG)
		{
			fprintf(Fp, "[--]Send data_buf err...\r\n");
		}
		return FALSE;
	}
	if(sendLen == size)
	{
		if(DEBUG)
		{
			fprintf(Fp, "[--]Send datapackage over! size: %d\r\n", size);
		}
		pd_msleep(5);
	}
	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	return size;
}

INT Recv_data(VOID)
{
	U8 *Databuff = NULL;
	INT recvSize = 0;

	Databuff = zk_malloc(CLEAN_DATA);
	if(Databuff == NULL)
	{
		return FALSE;
	}
	while(recvSize >= 0)
	{
		recvSize = usb.read(Databuff, CLEAN_DATA, 1000);
		if(DEBUG)
		{
			fprintf(Fp, "Recv_data...while---------->recvSize = %d\r\n", recvSize);
		}
	}
	zk_free(Databuff);
	Databuff = NULL;
	return SUCCESS;
}

INT Recv_Command_usb(INT Command, INT *Flag, INT *Param, U8 *DataRecvBuff, INT *len, U32 timeout)
{
	INT i = 0;
	INT ret = -1;
	INT current = 0;
	INT dataSize = 0;
	INT recvSize = 0;
	U32 startTime = 0;
	U32 curTime = 0;
	PRSHeader pHeader = NULL;
	INT checkHeadFlag = 0;

	timeout = (timeout < 1000) ? 1000 : timeout;

	DataPackage = zk_malloc(RECV_SIZE_USB);
	pHeader = (PRSHeader)DataPackage;

	// start Recv data
	startTime = pd_get_ticks();

	while(1)
	{
		curTime = pd_get_ticks();
		if((curTime - startTime) >= timeout)
		{
			break;
		}
		if(curTime < startTime)
		{
			break;
		}
		//1. start Recv data
		current = usb.read(DataPackage + recvSize, RECV_SIZE_USB, timeout);//Recv datapackage size
		if(DEBUG)
		{
			fprintf(Fp, "[--]current = %d\r\n", current);
		}
		if(current < 0)
		{
			continue;
		}
		recvSize += current;
		if(DEBUG)
		{
			fprintf(Fp, "[--]recvSize = %d\r\n", recvSize);
			fprintf(Fp, "[--]Debug :pHeader->Size = %d\r\n", pHeader->Size);
			fprintf(Fp, "[--]pHeader->CheckSum = %d\r\n", pHeader->CheckSum);
			fprintf(Fp, "[--]MHeader_chksum((U8*)pHeader) = %d\r\n", MHeader_chksum((U8*)pHeader));
		}

		if(recvSize >= HEADSIZE)
		{
			if(DEBUG)
			{
				fprintf(Fp, "Command = 0x%02x\r\n", Command);
				fprintf(Fp, "pHeader->Command = 0x%02x\r\n", (pHeader->Command) & 0xff);
			}
			if(Command != ((pHeader->Command) & 0xff))
			{
				Recv_data();
				recvSize = 0;
				continue;
			}

			//2. header check
			if ((checkHeadFlag == 0) && ((pHeader->CheckSum) != (MHeader_chksum((U8*) pHeader))))
			{
				if (DEBUG)
				{
					mvwprintw(win1, 1, 1, "[Debug]:header check err...");
					DebugWin(win1, 2);
					fprintf(Fp, "[Debug]: Recv head check Fail !\r\n");
				}
				Recv_data();
				return FALSE;
			}
			checkHeadFlag = 1;
			if(((pHeader->Size) > 0) && (DataRecvBuff != NULL))
			{
				if(recvSize > MAX_BYTE)
				{
					if(DEBUG)
					{
						mvwprintw(win1, 1, 1, "[Debug]:Recv datapackage err...");
						DebugWin(win1, 2);
					}
					return FALSE;
				}
				else if(recvSize == (HEADSIZE + pHeader->Size))
				{
					//Data size ok!
					break;
				}
			}
			else
			{
				break;
			}
		}
		pd_msleep(10);
	}

	// 3.data check
	ret = RecvData_Check(recvSize, &dataSize, (ePRSHeader)pHeader, DataRecvBuff);
	if(ret == FALSE)
	{
		return FALSE;
	}

	// 4.return data
	*Flag = pHeader->Flag;
	*Flag &= 0xff;
	*Param = pHeader->Param;
	*len = dataSize;
	if(DEBUG)
	{
		fprintf(Fp, "[--]Recv (%d):\r\n", recvSize);
		for(i=0; i < recvSize; i++)
		{
			fprintf(Fp, "0x%02x ", *(DataPackage+i));
		}
		fprintf(Fp, "\r\n");
	}
	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	return recvSize;
}

INT Recv_Command(INT Command, INT *Flag, INT *Param, U8 *DataRecvBuff, INT *len, U32 timeout)
{
	INT ret = -1;
	INT current = 0;
	INT dataSize = 0;
	INT recvSize = 0;
	U32 startTime = 0;
	U32 curTime = 0;
	PRSHeader pHeader = NULL;
	INT checkHeadFlag = 0;

	if(DEBUG)
	{
		fprintf(Fp, "[--]start Recv data >>>\r\n");
	}
	if(Dev_num == DEV_USB)
	{
		recvSize = Cmd.RecvCmd_usb(Command, Flag, Param, DataRecvBuff, len, timeout);
		return recvSize;
	}
	//232
	timeout = (timeout < 150) ? 150 : timeout;
	DataPackage = zk_malloc(MAX_BYTE);
	pHeader = (PRSHeader)DataPackage;

	// 1.start Recv data
	startTime = pd_get_ticks();

	while(1)
	{
		curTime = pd_get_ticks();
		if((curTime - startTime) >= timeout)
		{
			break;
		}
		if(curTime < startTime)
		{
			break;
		}
		//1. start Recv data
		if((current = (ff232.poll())) > 0)
		{
			if(current > HEADSIZE)
			{
				current = HEADSIZE;
			}
			recvSize += ff232.read_buf(DataPackage + recvSize, current);//Recv datapackage size
			if(DEBUG)
			{
				fprintf(Fp, "[--]current = %d\r\n", current);
			}
			if(current < 0)
			{
				break;
				//continue;
			}
			if(DEBUG)
			{
				fprintf(Fp, "[--]recvSize = %d\r\n", recvSize);
				fprintf(Fp, "[--]Debug :pHeader->Size = %d\r\n", pHeader->Size);
				fprintf(Fp, "[--]pHeader->CheckSum = %d\r\n", pHeader->CheckSum);
				fprintf(Fp, "[--]MHeader_chksum((U8*)pHeader) = %d\r\n", MHeader_chksum((U8*)pHeader));
			}

			if(recvSize >= HEADSIZE)
			{
				if(DEBUG)
				{
					fprintf(Fp, "Command = 0x%02x\r\n", Command);
					fprintf(Fp, "pHeader->Command = 0x%02x\r\n", (pHeader->Command) & 0xff);
				}
				if(Command != ((pHeader->Command) & 0xff))
				{
					recvSize = 0;
					continue;
				}

				//2. header check
				if ((checkHeadFlag == 0) && ((pHeader->CheckSum) != (MHeader_chksum((U8*) pHeader))))
				{
					if (DEBUG)
					{
						mvwprintw(win1, 1, 1, "[Debug]:header check err...");
						DebugWin(win1, 2);
						fprintf(Fp, "[Debug]: Recv head check Fail !\r\n");
					}
					fprintf(Fp, "[Debug]:Recv_data()....header check");
					return FALSE;
				}
				checkHeadFlag = 1;
				if(((pHeader->Size) > 0) && (DataRecvBuff != NULL))
				{
					if(recvSize > MAX_BYTE)
					{
						if(DEBUG)
						{
							mvwprintw(win1, 1, 1, "[Debug]:Recv datapackage err...");
							DebugWin(win1, 2);
						}
						return FALSE;
					}
					else if(recvSize == (HEADSIZE + pHeader->Size))
					{
						//Data size ok!
						break;
					}
				}
				else
				{
					break;
				}
			}
		}
		pd_msleep(10);
	}

	// 2.data check
	ret = RecvData_Check(recvSize, &dataSize, (ePRSHeader)pHeader, DataRecvBuff);
	if(ret == FALSE)
	{
		return FALSE;
	}

	// 3.return data
	*Flag = pHeader->Flag;
	*Flag &= 0xff;
	*Param = pHeader->Param;
	*len = dataSize;

	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	return recvSize;
}

/*  sent the extend datapackage */
INT extSend_command(INT Command, INT Flag, SHORT PacketNum, SHORT Index, U8 *DataSendbuff, INT len)
{
	INT size = 0;
	INT sendLen = 0;
	INT value = 0;
	ePRSHeader pHeader = NULL;

	DataPackage = zk_malloc(MAX_SEND);
	//Instruction initialization
	pHeader = (ePRSHeader)DataPackage;
	pHeader->Startcode = 0x70;
	pHeader->Command = Command;
	pHeader->PacketNum = PacketNum;
	pHeader->Index = Index;
	pHeader->Flag = Flag;
	pHeader->Size = (len > 0) ? len : 0;
	pHeader->Endcode = 0x0A;

	//Data Package
	if((len > 0) && (len < MAX_BYTE) && (DataSendbuff != NULL))
	{
		memcpy(DataPackage + sizeof(eTRSHeader), DataSendbuff, len);
		value = MData_chksum((U8*)(pHeader+1), len);
		memcpy(DataPackage + sizeof(eTRSHeader)+len, &value, 4);
		pHeader->Size += 4;
	}

	pHeader->CheckSum = MHeader_chksum((U8*)pHeader);
	sendLen = pHeader->Size + sizeof(eTRSHeader);	//datapackage size

	//Send data
	if(Dev_num == DEV_232)	//232
	{
		size = ff232.write_buf(DataPackage, sendLen);
	}
	else if(Dev_num == DEV_USB)	//usb
	{
		size = usb.send(DataPackage, sendLen);
	}
	if(size < 0)
	{
		if(DEBUG)
		{
			mvwprintw(win1, 1, 1, "[Debug]:extSend data_buf err...");
			DebugWin(win1, 2);
			fprintf(Fp, "[Debug]:extSend data_buf err...\r\n");
		}
		return FALSE;
	}
	if(sendLen == size)
	{
		pd_msleep(5);
	}
	//Send data end!
	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	return size;
}

INT extRecv_Command_usb(INT Command, INT *Flag, SHORT *PacketNum, SHORT *Index, U8 *DataRecvBuff, INT *len, U32 timeout)
{
	INT ret = -1;
	INT current = 0;
	INT dataSize = 0;
	INT recvSize = 0;
	U32 startTime = 0;
	U32 curTime = 0;
	ePRSHeader pHeader = NULL;
	INT checkHeadFlag = 0;

	timeout = (timeout < 1000) ? 1000 : timeout;
	DataPackage = zk_malloc(RECV_SIZE_USB);
	pHeader = (ePRSHeader)DataPackage;

	//start Recv data
	startTime = pd_get_ticks();

	while(1)
	{
		curTime = pd_get_ticks();
		if((curTime - startTime) >= timeout)
		{
			break;
		}
		if(curTime < startTime)
		{
			break;
		}
		//1. start Recv data
		current = usb.read(DataPackage + recvSize, RECV_SIZE_USB, timeout);//Recv datapackage size
		if(DEBUG)
		{
			fprintf(Fp, "[--]current = %d\r\n", current);
		}
		if(current < 0)
		{
			continue;
		}
		recvSize += current;
		if(DEBUG)
		{
			fprintf(Fp, "[--]recvSize = %d\r\n", recvSize);
			fprintf(Fp, "[--]Debug :pHeader->Size = %d\r\n", pHeader->Size);
			fprintf(Fp, "[--]pHeader->CheckSum = %d\r\n", pHeader->CheckSum);
			fprintf(Fp, "[--]MHeader_chksum((U8*)pHeader) = %d\r\n", MHeader_chksum((U8*)pHeader));
		}
		if(recvSize >= HEADSIZE)
		{
			if(DEBUG)
			{
				fprintf(Fp, "Command = 0x%02x\r\n", Command);
				fprintf(Fp, "pHeader->Command = 0x%02x\r\n", (pHeader->Command) & 0xff);
			}
			if(Command != ((pHeader->Command) & 0xff))
			{
				Recv_data();
				recvSize = 0;
				continue;
			}
			//2. header check
			if ((checkHeadFlag == 0) && ((pHeader->CheckSum) != (MHeader_chksum((U8*) pHeader))))
			{
				if (DEBUG)
				{
					mvwprintw(win1, 1, 1, "[Debug]:header check err...");
					DebugWin(win1, 2);
					fprintf(Fp, "[Debug]: Recv head check Fail !\r\n");
				}
				Recv_data();
				return FALSE;
			}
			checkHeadFlag = 1;
			if(((pHeader->Size) > 0) && (DataRecvBuff != NULL))
			{
				if(recvSize > RECV_SIZE_USB)
				{
					if(DEBUG)
					{
						mvwprintw(win1, 1, 1, "[Debug]:Recv datapackage err...");
						DebugWin(win1, 2);
					}
					return FALSE;
				}
				else if(recvSize == (HEADSIZE + pHeader->Size))
				{
					if(DEBUG)
					{
						fprintf(Fp, "[Debug]:recvSize = %d \r\n", recvSize);
						fprintf(Fp, "[Debug]:(headSize + pHeader->Size) = %d \r\n", (HEADSIZE + pHeader->Size));
					}
					//Data size ok!
					break;
				}
			}
			else
			{
				break;
			}
		}
		pd_msleep(10);
	}

	// 3.data check
	ret = RecvData_Check(recvSize, &dataSize, pHeader, DataRecvBuff);
	if(ret == FALSE)
	{
		return FALSE;
	}

	// 4.return data
	*Flag = pHeader->Flag;
	*Flag &= 0xff;
	*PacketNum = pHeader->PacketNum;
	*Index = pHeader->Index;
	*len = dataSize;

	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	if(DEBUG)
	{
		fprintf(Fp, "cccccccccccccccccc(recvSize = %d)ccccccccccccccccc\r\n", recvSize);
	}
	return recvSize;
}

INT extRecv_Command(INT Command, INT *Flag, SHORT *PacketNum, SHORT *Index, U8 *DataRecvBuff, INT *len, U32 timeout)
{
	INT ret = -1;
	INT current = 0;
	INT dataSize = 0;
	INT recvSize = 0;
	U32 startTime = 0;
	U32 curTime = 0;
	ePRSHeader pHeader = NULL;
	INT checkHeadFlag = 0;

	if(DEBUG)
	{
		fprintf(Fp, "[--]start Recv data >>>\r\n");
	}
	if(Dev_num == DEV_USB)
	{
		recvSize = Cmd.extRecvCmd_usb(Command, Flag, PacketNum, Index, DataRecvBuff, len, timeout);
		return recvSize;
	}
	//232
	timeout = (timeout < 150) ? 150 : timeout;
	DataPackage = zk_malloc(MAX_BYTE);
	pHeader = (ePRSHeader)DataPackage;

	// 1.start Recv data
	startTime = pd_get_ticks();

	while(1)
	{
		curTime = pd_get_ticks();
		if((curTime - startTime) >= timeout)
		{
			break;
		}
		if(curTime < startTime)
		{
			break;
		}
		//1. start Recv data
		if((current = (ff232.poll())) > 0)
		{
			recvSize += ff232.read_buf(DataPackage + recvSize, current);//Recv datapackage size
			if(DEBUG)
			{
				fprintf(Fp, "[--]current = %d\r\n", current);
			}
			if(current < 0)
			{
				continue;
			}
			if(DEBUG)
			{
				fprintf(Fp, "[--]recvSize = %d\r\n", recvSize);
				fprintf(Fp, "[--]Debug :pHeader->Size = %d\r\n", pHeader->Size);
				fprintf(Fp, "[--]pHeader->CheckSum = %d\r\n", pHeader->CheckSum);
				fprintf(Fp, "[--]MHeader_chksum((U8*)pHeader) = %d\r\n", MHeader_chksum((U8*)pHeader));
			}

			if(recvSize >= HEADSIZE)
			{
				if(DEBUG)
				{
					fprintf(Fp, "Command = 0x%02x\r\n", Command);
					fprintf(Fp, "pHeader->Command = 0x%02x\r\n", (pHeader->Command) & 0xff);
				}
				if(Command != ((pHeader->Command) & 0xff))
				{
					recvSize = 0;
					continue;
				}

				//2. header check
				if ((checkHeadFlag == 0) && ((pHeader->CheckSum) != (MHeader_chksum((U8*) pHeader))))
				{
					if (DEBUG)
					{
						mvwprintw(win1, 1, 1, "[Debug]:header check err...");
						DebugWin(win1, 2);
						fprintf(Fp, "[Debug]: Recv head check Fail !\r\n");
					}
					fprintf(Fp, "[Debug]:Recv_data()....header check");
					return FALSE;
				}
				checkHeadFlag = 1;
				if(((pHeader->Size) > 0) && (DataRecvBuff != NULL))
				{
					if(recvSize > MAX_BYTE)
					{
						if(DEBUG)
						{
							mvwprintw(win1, 1, 1, "[Debug]:Recv datapackage err...");
							DebugWin(win1, 2);
						}
						return FALSE;
					}
					else if(recvSize == (HEADSIZE + pHeader->Size))
					{
						//Data size ok!
						break;
					}
				}
				else
				{
					break;
				}
			}
		}
		pd_msleep(10);
	}

	if(DEBUG)
	{
		fprintf(Fp, "[--]recvSize = %d\r\n", recvSize);
	}
	// 2.data check
	ret = RecvData_Check(recvSize, &dataSize, (ePRSHeader)pHeader, DataRecvBuff);
	if(ret == FALSE)
	{
		return FALSE;
	}

	// 3.return data
	*Flag = pHeader->Flag;
	*Flag &= 0xff;
	*PacketNum = pHeader->PacketNum;
	*Index = pHeader->Index;
	*len = dataSize;
	if(DataPackage != NULL)
	{
		zk_free(DataPackage);
		DataPackage = NULL;
	}
	return recvSize;
}

CHAR MHeader_chksum(U8*p)
{
	INT i,sum=0;
	CHAR checksum=0;

	for(i=0;i<11;i++){
		sum+=p[i];
	}
	checksum=(sum%256);

	return checksum;
}

INT MData_chksum(U8*p, INT len)
{
	INT i,sum=0;

	for(i=0;i<len;i++){
		sum+=p[i];
	}
	return sum;
}

U32 pd_get_ticks(VOID)
{
	struct timeval tv;
	struct timezone tz;
	gettimeofday(&tv, &tz);
	return (tv.tv_sec*1000 + tv.tv_usec/1000);
}

VOID pd_msleep(INT ms)
{	
	struct timeval time;
	time.tv_sec = ms/1000;
	time.tv_usec  = (ms % 1000) * 1000;
	select(0,NULL,NULL,NULL,&time);
}

Command_fun Cmd = {
	Send_command,
	Recv_Command,
	Recv_Command_usb,
	extSend_command,
	extRecv_Command,
	extRecv_Command_usb
};

/******************************************
 Fun: time check
 Return value: true = 0, false = -1
 Data: 2015.9.10
*******************************************/
INT timeCheck(INT Year, INT Month, INT Day,  INT Hour, INT Minute, INT Second)
{
	INT flag = 0;
	if((Year < 0) || ((Month < 1) || (Month > 12)) ||
			((Hour < 0) || (Hour > 24)) || ((Minute < 0) || (Minute > 60)) || ((Second < 0) || (Second > 60)))
	{
		flag = -1;
	}
	if((0 == Year % 400) || ((0 == Year % 4) && (Year % 100 != 0)))
	{
		if((2 == Month) )
		{
			if((Day < 0) || (Day > 29))
			{
				flag = -1;
			}
		}
	}
	else
	{
		if((2 == Month) )
		{
			if((Day < 0) || (Day > 28))
			{
				flag = -1;
			}
		}
	}
	if((1 == Month) || (3 == Month) || (5 == Month) ||
			(7 == Month) ||(8 == Month) || (10 == Month) ||(12 == Month))
	{
		if((Day < 0) || (Day > 31))
		{
			flag = -1;
		}
	}
	else if((4 == Month) || (6 == Month) || (9 == Month) || (11 == Month))
	{
		if((Day < 0) || (Day > 30))
		{
			flag = -1;
		}
	}
	return flag;
}

/**************************** save image ******************************/
int WriteBitmap(U8 *buffer, S32 Width, S32 Height, CHAR * FileName)
{
	int i = 0,w = 0;
	FILE *f = NULL;
	CHAR Buffer[0x500];
	BITMAPFILEHEADER * bmpfheader;
	BITMAPINFO *bmpinfo;
	bmpfheader = (BITMAPFILEHEADER * )Buffer;
	bmpinfo = (BITMAPINFO *)(((char*)bmpfheader)+14);


	memset(bmpfheader,0,0x500);
	bmpfheader->bfType =19778;
	bmpfheader->bfSize = ((Width+3)/4)*4*Height+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
	bmpfheader->bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
	bmpinfo->bmiHeader.biWidth=Width;
	bmpinfo->bmiHeader.biHeight=Height;
	bmpinfo->bmiHeader.biBitCount=8;
	bmpinfo->bmiHeader.biClrUsed=0;
	bmpinfo->bmiHeader.biSize=sizeof(bmpinfo->bmiHeader);
	bmpinfo->bmiHeader.biPlanes=1;
	bmpinfo->bmiHeader.biSizeImage=((Width+3)/4)*4*Height;
	f=fopen(FileName, "wb");
	if(f)
	{
		for(i=1;i<256;i++)
		{
			bmpinfo->bmiColors[i].rgbBlue=i;
			bmpinfo->bmiColors[i].rgbGreen=i;
			bmpinfo->bmiColors[i].rgbRed=i;
		}
		fwrite(Buffer, sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD), 1, f);
		w = ((Width+3)/4)*4;
		for(i=0; i<Height; i++)
		{
			fwrite(buffer, Width, 1, f);
			if(w-Width)
				fwrite(buffer, w-Width, 1, f);
			buffer+=Width;
		}
		fclose(f);
		return Width*Height;
	}
	return 0;
}

VOID save_bmp(U8 *buffer, S32 Width, S32 Height)
{
	static int times = 1;
	CHAR name[128] = {0};

	sprintf(name, "bmp_%02d.bmp", times++);
	WriteBitmap(buffer, Width, Height, name);
	times = ((times >=8) ? 1: times);
}

VOID *zk_malloc(size_t size)
{
        VOID *p = NULL;
        if(p != NULL)
        {
        	zk_free(p);
        	p = NULL;
        }
        p = malloc(size);
        if(NULL == p)
        {
        	return p;
        }
        memset(p, 0, size);
        return p;
}

/**************************** windown fun ******************************/
INT CursesInit(VOID)
{
	//win init
	initscr();
	clear();

	//main window
	win = newwin(WIN_LINE, WIN_COL, 0, 0);
	//debug window
	win1 = newwin(6, 83, 19, 1);
	//info window
	win2 = newwin(WIN_LINE - 7, WIN_COL - 2, 1, 1);
	return SUCCESS;
}

VOID WinBox(VOID)
{
	box(win, ACS_VLINE, ACS_HLINE);
	mvwprintw(win, 0, 2, "Slk20 Demo_%s", DEMOVERSION);
	box(win1, ACS_VLINE, ACS_HLINE);
	mvwprintw(win1,0, 2, "Dubeg");
	box(win2, ACS_VLINE, ACS_HLINE);
	mvwprintw(win2, 0, 2, "Print info");
}

VOID CloseWin(VOID)
{
	//close window
	refresh();
	wrefresh(win);
	wrefresh(win1);
	sleep(0);
	delwin(win);
	delwin(win1);
	delwin(win2);
    endwin();
}

VOID DebugWin(WINDOW *win1, int num)
{
	WinBox();
	wrefresh(win1);
	sleep(num);
	wclear(win1);
}

INT DebugFile_init(VOID)
 {
	while(1)
	{
		if(NULL == (Fp = fopen(DEBUG_FILE, "a+")))
		{
			//return FAILURE;
			continue;
		}
		else
		{
			break;
		}
	}
	return SUCCESS;
 }

INT RecvData_Check(INT recvSize, INT *dataSize, ePRSHeader pHeader, U8 *DataRecvBuff)
{
	INT i = 0;
	INT value = 0;

	if(0 == recvSize)
	{
		return FALSE;
	}
	//1. header check
	if((pHeader->CheckSum ) != (MHeader_chksum((U8*)pHeader)))
	{
		if(DEBUG)
		{
			mvwprintw(win1, 1, 1, "[Debug]:Header check err...");
			DebugWin(win1, 2);
			fprintf(Fp, "[Debug]:Header check err...\r\n");
		}
		return FALSE;
	}//header right
	if(DEBUG)
	{
		fprintf(Fp, "[Debug]:Header check OK! \r\n");
		fprintf(Fp, "[--]Recv (%d):\r\n", recvSize);
		for(i=0; i < recvSize; i++)
		{
			fprintf(Fp, "0x%02x ", *(DataPackage+i));
		}
		fprintf(Fp, "\r\n");
	}

	//extHeader check OK!
	if(((pHeader->Size) > 0) && (DataRecvBuff != NULL))
	{
		//2. Data validation
		if((recvSize > 0) && (recvSize < RECV_SIZE_USB))
		{
			*dataSize = recvSize - HEADSIZE - 4;
			if(DEBUG)
			{
				fprintf(Fp, "dataSize = %d\r\n", *dataSize);
				fprintf(Fp, "recvSize = %d \r\n", recvSize);
				fprintf(Fp, "pHeader->Size -4 = %d \r\n", pHeader->Size -4);
			}
			//data_buff right y/n?
			if((pHeader->Size - 4) == (*dataSize))
			{
				memcpy((void*)&value, (DataPackage + HEADSIZE + pHeader->Size-4), 4);
				//3. Data check
				if(DEBUG)
				{
					fprintf(Fp, "value = %d\r\n", value);
				}
				if(value == (MData_chksum((U8*)(pHeader+1), *dataSize)))
				{
					if(DEBUG)
					{
						fprintf(Fp, "[--]Debug: MData_chksum = value\r\n");
					}
					//extData check OK!
					memcpy(DataRecvBuff, DataPackage + HEADSIZE, *dataSize);
					return SUCCESS;
				}
				else
				{
					if(DEBUG)
					{
						mvwprintw(win1, 1, 1, "[Debug]:Data check err...");
						DebugWin(win1, 2);
						fprintf(Fp, "[Debug]:Data check err...\r\n");
					}
					return FALSE;
				}
			}
			else if(*(DataPackage + HEADSIZE) != 0)
			{
				if(DEBUG)
				{
					mvwprintw(win1, 1, 1, "[error]: Data loss...");
					DebugWin(win1, 2);
					fprintf(Fp, "[error]: Data loss...\r\n");
				}
				return FALSE;
			}
		}
		else
		{
			if(DEBUG)
			{
				mvwprintw(win1, 1, 1, "[Debug]:Data Not within range ...");
				DebugWin(win1, 2);
				fprintf(Fp, "[Debug]:Data Not within range ...\r\n");
			}
			return FALSE;
		}
	}
	return SUCCESS;
}



