/*
 *  Copyright 2007 by Texas Instruments Incorporated.
 *  All rights reserved. Property of Texas Instruments Incorporated.
 *  Restricted rights to use, duplicate or disclose this code are
 *  granted through contract.
 *
 *  @(#) TCP/IP_Network_Developers_Kit 1.93.00.09 08-16-2007 (ndk-c09)
 */
//--------------------------------------------------------------------------
// IP Stack Server Demonstration Program
//--------------------------------------------------------------------------
// newservers.c
//
// This module demonstrates the use of the server daemon added in NDK 1.7.
//
// It provides all the functionality of:
//     echosrv() : echosrv.c
//     datasrv() : datasrv.c
//     nullsrv() : nullsrv.c
//     oobsrv()  : oobsrv.c
//
// The original source files are still provided to illustrate a traditional
// server. This file contains only the daemon service task functions
// required when using the server daemon.
//
// Author: Michael A. Denio
// Copyright 2003 by Texas Instruments Inc.
//-------------------------------------------------------------------------
#include <csl_edma2.h>
#include <csl_intcAux.h>
#include "fa_server.h"
#include "common.h"
#include "environment.h"
#include "timer.h"
#include "TPBcamera.h"
#include "image_control.h"
#include "data_indicator.h"
#include "Tpb_system.h"

/** 
 *   @file  echosrv.c
 *
 *   @brief   
 *      This program implements a TCP and UDP echo server, which echos back any
 *      input it receives.
 *
 *  \par
 *  NOTE:
 *      (C) Copyright 2008, Texas Instruments, Inc.
 *
 *  \par
 */

//configure TCP data buffer 

#define ECHO_BUFFER_MAX_SIZE		4 * 1024 * 1024
#pragma DATA_SECTION(EchoBuffer, ".sdram");
#pragma DATA_ALIGN(EchoBuffer, 1024);
unsigned char EchoBuffer[ECHO_BUFFER_MAX_SIZE];

#define GLOABL_TCP_BUFFER_SIZE		256 * 1024
#pragma DATA_ALIGN(GlobalTCPRxDataBuffer, 8);
#pragma DATA_ALIGN(GlobalTCPTxDataBuffer, 8);
unsigned char GlobalTCPRxDataBuffer[GLOABL_TCP_BUFFER_SIZE];
unsigned char GlobalTCPTxDataBuffer[GLOABL_TCP_BUFFER_SIZE];

unsigned char GlobalSysResultBuffer[1024];
unsigned char GlobalAppResultBuffer[1024];

#pragma DATA_SECTION(CPBDataBuffer, ".sdram");
#pragma DATA_ALIGN(CPBDataBuffer, 8);
unsigned char CPBDataBuffer[640*480*5];

#pragma DATA_ALIGN (ResponseDataAddr, 8)
unsigned int ResponseDataAddr[1];
//configure TCP socket
struct   sockaddr_in sin1;
SOCKET   stcp = INVALID_SOCKET;
SOCKET   sudp = INVALID_SOCKET;
SOCKET   sresult = INVALID_SOCKET;
SOCKET   stcpactive = INVALID_SOCKET;
SOCKET   stcpbusy;
fd_set ibits, obits, xbits;
int snd_count = 0;
int rcv_count = 0;
int      size,result;
HANDLE   hBuffer;
char     *pBuf;
char     *hBuf;
struct   timeval timeout;    
EDMA_Handle TCP_EdmaHandle;
int TCPEDMATCCNumber;
TTCPDataHeader TCPRXHeader, TCPTXHeader;
int remain_small_size;
int remain_large_size;
int remain_small_offset;
int remain_large_offset;
extern volatile int Jump_SW;
TCPControlInfo TcpPacketInfo;
TCPReceiveData TcpReceiveDataInfo;
int send_test[5][1000];
int send_test_cnt = 1;
unsigned char ttBuffer[640*480];

struct{
	unsigned int TabletNumber;
	int Result;
  	unsigned short CapturedTime[SYSTEM_SPB_CAMERA_COUNT];
	int currentTabletNum;
}SendData;

void FA_TCPServer()
{
/*
	TCP_EdmaHandle = EDMA_open(EDMA_CHA_UXEVT, EDMA_OPEN_RESET);
	TCPEDMATCCNumber = EDMA_intAlloc(EDMA_CHA_UXEVT);
	EDMA_intClear(TCPEDMATCCNumber);
	EDMA_intDisable(TCPEDMATCCNumber);
	EDMA_disableChannel(TCP_EdmaHandle);
*/
	fdOpenSession( TaskSelf() );
	
	TcpPacketInfo.Status == SERVER_STATUS_IDLE;
	TcpPacketInfo.rx_control == SERVER_STATUS_RECEIVE;
	memset(&TcpPacketInfo, 0 ,sizeof(TCPControlInfo));
	memset(&TCPRXHeader, 0 ,sizeof(TTCPDataHeader));
	memset(&TCPTXHeader, 0 ,sizeof(TTCPDataHeader));
	memset(&send_test, 0 ,sizeof(send_test));
	// Create the main TCP listen socket
	sresult = FA_connect();	
	if(sresult == INVALID_SOCKET)
		FA_disconnect();

	// Configure our timeout to be 15 seconds
	timeout.tv_sec  = 120;
	timeout.tv_usec = 3000;

//	printf("EchoSrv Initialized\n");
	TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
	
	// Run until task is destroyed by the system
	for(;;)
	{
		FD_ZERO(&ibits);
		FD_ZERO(&obits);
		FD_ZERO(&xbits);

		FD_SET(stcp, &ibits);
		TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
//		FD_SET(sudp, &ibits);
//		CSL_intcGlobalDisable(&state);
//		event_state = CSL_intcEventDisable(CSL_INTC_EVENTID_MACRXINT);
		if(TcpPacketInfo.Status == SERVER_STATUS_RECEIVE || TcpPacketInfo.Status == SERVER_STATUS_IDLE)
		{
			ReceiveTCPPacket(pBuf);
		}
		
	    if(TcpPacketInfo.Status == SERVER_STATUS_PROCESSING)
		{
//			CSL_intcGlobalEnable(&state);
			Tcp_Processing(TcpPacketInfo);
//			CSL_intcGlobalDisable(&state);
		}
		if(TcpPacketInfo.Status == SERVER_STATUS_SEND)
		{
			SendTCPPacket(TcpPacketInfo);
		}

		TcpPacketInfo.Status = SERVER_STATUS_IDLE;
//		CSL_intcEventRestore(CSL_INTC_EVENTID_MACRXINT,event_state);
//		System_Sleep_ms(50);
//		SendData();
	}
}

SOCKET FA_connect()
{


    stcp = socket(AF_INET, SOCK_STREAMNC, IPPROTO_TCP);
    if( stcp == INVALID_SOCKET )
        return INVALID_SOCKET;

    // Set Port = 7, leaving IP address = Any
    bzero( &sin1, sizeof(struct sockaddr_in) );
    sin1.sin_family = AF_INET;
    sin1.sin_len    = sizeof( sin1 );
    sin1.sin_port   = htons(1002);

    // Bind socket
    if ( bind( stcp, (PSA) &sin1, sizeof(sin1) ) < 0 )
        return INVALID_SOCKET;

    // Start listening
    if ( listen( stcp, 1) < 0 )
        return INVALID_SOCKET;

	sudp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if( sudp == INVALID_SOCKET )
	    return  INVALID_SOCKET;

	// Bind the same as TCP ... Port = 7, IPAddr = Any
	if ( bind( sudp, (PSA) &sin1, sizeof(sin1) ) < 0 )
	    return  INVALID_SOCKET;


    // We examine the main TCP, UDP, and active TCP (if any)



	return stcp;
}


void FA_disconnect()
{
    if( stcp != INVALID_SOCKET )
	{	
        fdClose( stcp );
		stcp = INVALID_SOCKET;
	}
    if( sudp != INVALID_SOCKET )
	{
        fdClose( sudp );
		sudp = INVALID_SOCKET;
	}
	TaskBlock( TaskSelf() );
}

void ReceiveTCPPacket(unsigned char *buf)
{
	unsigned int dataBufferMaxSize;
	
	if( stcp == INVALID_SOCKET ) 
		FA_disconnect();

    // Wait for socket activity
    if( stcpactive == INVALID_SOCKET )
    {
        // Wait without timeout
        result = fdSelect( 4, &ibits, &obits, &xbits, 0 );
    }
    else
    {
        // Wait for set timeout - abort active connection on no activity
        FD_SET(stcpactive, &ibits);
        result = fdSelect( 4, &ibits, &obits, &xbits, 0 );
        if( result <= 0 )
        {
//			printf("TimeOut Error!!! %x\n",stcpactive);
            fdClose( stcpactive );
            stcpactive = INVALID_SOCKET;
        }
    }

    if( result < 0 ){
	    FA_disconnect();
	}	
    // Check for a new TCP connection
    if( FD_ISSET(stcp, &ibits) )
    {
        // We have a new connection. Assign it so sbusy at
        // first...
        size = sizeof( sin1 );
        stcpbusy = accept( stcp, (PSA)&sin1, &size );

        // If the active socket is free use it, else print out
        // a busy message
        if( stcpactive == INVALID_SOCKET )
            stcpactive = stcpbusy;
        else
            fdClose( stcpbusy );
    }

    // Check for new data on active TCP connection
    if( stcpactive != INVALID_SOCKET && FD_ISSET(stcpactive, &ibits) )
    {
        // There is data available on the active connection
        rcv_count = (int)recvnc( stcpactive, (void **)&buf, 0, &hBuffer );
//		printf("RECV data :%x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x\n",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7],buf[8],buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15]);
		if (rcv_count <= 0 ){
                fdClose( stcpactive );
                stcpactive = INVALID_SOCKET;
		}

		if(buf[0] == 0xa5 && buf[1] == 0xa5)
		{
			ReceiveTCPHeader(buf);
	
			TcpPacketInfo.Command = TCPRXHeader.Command;
			TcpPacketInfo.SmallDataAddress = (unsigned char *)GlobalTCPRxDataBuffer;
			TcpPacketInfo.LargeDataAddress = GetTCPBufferAddress(&dataBufferMaxSize);
			TcpPacketInfo.SmallDataSize = TCPRXHeader.SmallDataLength;
			TcpPacketInfo.LargeDataSize = TCPRXHeader.LargeDataLength;
			remain_small_size = TCPRXHeader.SmallDataLength;
			remain_large_size = TCPRXHeader.LargeDataLength;
			remain_small_offset = 0;
			remain_large_offset = 0;
			if(TCPRXHeader.SmallDataLength > 0  || TCPRXHeader.LargeDataLength > 0)
			{

				TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
				if(TCPRXHeader.LargeDataLength > 0 && TCPRXHeader.SmallDataLength <= 0)
				{
					TcpPacketInfo.rx_control= SERVER_CONTROL_RECEIVE_LARGE_DATA;
					TcpReceiveDataInfo.LargeDataSize= TCPRXHeader.LargeDataLength;
					TcpReceiveDataInfo.SmallDataSize= TCPRXHeader.SmallDataLength;
				}

				else if(TCPRXHeader.SmallDataLength > 0 && TCPRXHeader.LargeDataLength <= 0)
				{
					TcpPacketInfo.rx_control= SERVER_CONTROL_RECEIVE_SMALL_DATA;
					TcpReceiveDataInfo.LargeDataSize= TCPRXHeader.LargeDataLength;
					TcpReceiveDataInfo.SmallDataSize= TCPRXHeader.SmallDataLength;
				}
				else
				{
					TcpPacketInfo.rx_control= SERVER_CONTROL_RECEIVE_ALL_DATA;
					TcpReceiveDataInfo.LargeDataSize= TCPRXHeader.LargeDataLength;
					TcpReceiveDataInfo.SmallDataSize= TCPRXHeader.SmallDataLength;					
				}
				recvncfree( hBuffer );	
				return;
			}
			if(TCPRXHeader.RequestKind== CMD_TYPE_APP_RECEIVE_RESULT)
			{
				TcpPacketInfo.Status = SERVER_STATUS_PROCESSING;
				TcpPacketInfo.tx_control= SERVER_CONTROL_SEND_HEADER;
			}
			else
			{
				TcpPacketInfo.Status = SERVER_STATUS_SEND;
				TcpPacketInfo.tx_control= SERVER_CONTROL_SEND_HEADER;
			}

			recvncfree( hBuffer );	
			return ;	
		}
		if(TcpPacketInfo.rx_control == SERVER_CONTROL_RECEIVE_SMALL_DATA)
		{
		
			ReceiveSmallData(buf, rcv_count, remain_small_offset);
			remain_small_size -= rcv_count;
			remain_small_offset += rcv_count;
			if(remain_small_size > 0)
			{
				TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
				TcpPacketInfo.rx_control = SERVER_CONTROL_RECEIVE_SMALL_DATA;
				recvncfree( hBuffer );
				return; 
			}
			
			if(TCPRXHeader.RequestKind== CMD_TYPE_APP_RECEIVE_RESULT)
			{
				TcpPacketInfo.Status = SERVER_STATUS_PROCESSING;
			}
			else
			{
				TcpPacketInfo.Status = SERVER_STATUS_SEND;
			}

		}
		else if(TcpPacketInfo.rx_control == SERVER_CONTROL_RECEIVE_LARGE_DATA)
		{
			ReceiveLagreData(buf, rcv_count, remain_large_offset);
			remain_large_size -= rcv_count;
			remain_large_offset += rcv_count;
			if(remain_large_size > 0)
			{
				TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
				TcpPacketInfo.rx_control = SERVER_CONTROL_RECEIVE_LARGE_DATA;
				recvncfree( hBuffer );
				return; 
			}
			if(TCPRXHeader.RequestKind== CMD_TYPE_APP_RECEIVE_RESULT)
			{
				TcpPacketInfo.Status = SERVER_STATUS_PROCESSING;
			}
			else
			{
				TcpPacketInfo.Status = SERVER_STATUS_SEND;
			}

		}
		else if(TcpPacketInfo.rx_control == SERVER_CONTROL_RECEIVE_ALL_DATA){
			if(remain_small_size > 0)
			{
				ReceiveSmallData(buf, rcv_count, remain_small_offset);
				remain_small_size -= rcv_count;
				remain_small_offset += rcv_count;
				TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
				TcpPacketInfo.rx_control = SERVER_CONTROL_RECEIVE_ALL_DATA;
				recvncfree( hBuffer );
				return; 
			}
			if(remain_large_size > 0)
			{
				ReceiveLagreData(buf, rcv_count, remain_large_offset);
				remain_large_size -= rcv_count;
				remain_large_offset += rcv_count;
				if(remain_large_size <=0)
				{
					TcpPacketInfo.Status = SERVER_STATUS_SEND;
				}
				else
				{
					TcpPacketInfo.Status = SERVER_STATUS_RECEIVE;
					TcpPacketInfo.rx_control = SERVER_CONTROL_RECEIVE_ALL_DATA;
				}
				recvncfree( hBuffer );
				return;  
			}		
			if(TCPRXHeader.RequestKind== CMD_TYPE_APP_RECEIVE_RESULT)
			{
				TcpPacketInfo.Status = SERVER_STATUS_PROCESSING;
			}
			else
			{
				TcpPacketInfo.Status = SERVER_STATUS_SEND;
			}
		}
    	recvncfree( hBuffer );
    	TCP_TransferComplete();		
	}	
}

void SendTCPPacket(TCPControlInfo send)
{
	if(TCPRXHeader.Header == TCP_PACKET_HEADER)
		SendTCPHeader();
	if(TCPTXHeader.SmallDataLength > 0)
	{
		if(TCPRXHeader.RequestKind == CMD_TYPE_APP_REQUEST)
		{
			ResponseDataAddr[0] = 1;

			SendSmallData((unsigned char *)ResponseDataAddr,TCPTXHeader.SmallDataLength );
		}
		else if(TCPRXHeader.RequestKind == CMD_TYPE_APP_POLLING_RESULT)
		{
			ResponseDataAddr[0] = 1;
			SendSmallData((unsigned char *)ResponseDataAddr,TCPTXHeader.SmallDataLength );
		}
		else if(TCPRXHeader.RequestKind == CMD_TYPE_APP_RECEIVE_RESULT)
		{

			SendSmallData(TcpPacketInfo.ResultSmallDataAddress,TCPTXHeader.SmallDataLength);
		}
	}
	if(TCPTXHeader.LargeDataLength > 0)
	{ 
		SendLagreData(TcpPacketInfo.ResultLargeDataAddress,TCPTXHeader.LargeDataLength);
		if(send_test_cnt >= 1000) send_test_cnt = 1;
	}

	memset(&TCPRXHeader, 0 ,sizeof(TTCPDataHeader));
	memset(&TCPTXHeader, 0 ,sizeof(TTCPDataHeader));
	memset(&TcpPacketInfo, 0 ,sizeof(TCPControlInfo));
	TcpPacketInfo.Status = SERVER_STATUS_IDLE;
}

void ReceiveTCPHeader(unsigned char *buf)
{
	memcpy(&TCPRXHeader,buf,rcv_count);
}

void ReceiveSmallData(unsigned char *buf, int size, int offset)
{
	memcpy(TcpPacketInfo.SmallDataAddress+offset,buf,size);
}

void ReceiveLagreData(unsigned char *buf, int size, int offset)
{
	memcpy(TcpPacketInfo.LargeDataAddress+offset,buf,size);
	TcpPacketInfo.rx_control = SERVER_CONTROL_RECEIVE_COMPLETE;
}

void SendTCPHeader()
{
	if(TCPRXHeader.RequestKind != CMD_TYPE_APP_RECEIVE_RESULT)
	{
		TCPTXHeader.Header 			= TCP_PACKET_HEADER;
		TCPTXHeader.Command	 		= TCPRXHeader.Command;
		TCPTXHeader.RequestKind 	= TCPRXHeader.RequestKind;
		TCPTXHeader.reserved		= 0x1234;
		TCPTXHeader.SmallDataLength	= sizeof(unsigned int);
		TCPTXHeader.LargeDataLength	= 0;
	}
	else
	{
		TCPTXHeader.Header 			= TCP_PACKET_HEADER;
		TCPTXHeader.Command	 		= TCPRXHeader.Command;
		TCPTXHeader.RequestKind 	= TCPRXHeader.RequestKind;
		TCPTXHeader.SmallDataLength	= (TcpPacketInfo.ResultSmallDataSize+ 3) / 4 * 4;
		TCPTXHeader.LargeDataLength	= (TcpPacketInfo.ResultLargeDataSize+ 3) / 4 * 4;
	}
		
	snd_count = send( stcpactive, &TCPTXHeader, sizeof(TTCPDataHeader), 0 );
	if( snd_count < 0 )
	{
	    fdClose( stcpactive );
	    stcpactive = INVALID_SOCKET;
	}
}

void SendSmallData(unsigned char *buf, int size)
{
	snd_count = send( stcpactive, buf, size, 0 );
	if( snd_count < 0 )
    {
        fdClose( stcpactive );
        stcpactive = INVALID_SOCKET;
    }
	TcpPacketInfo.tx_control == SERVER_CONTROL_SEND_COMPLETE;	
}

void SendLagreData(unsigned char *buf, int size)
{
	snd_count = send( stcpactive, buf, size, 0 );
	if( snd_count < 0 )
    {
        fdClose( stcpactive );
        stcpactive = INVALID_SOCKET;
    }
//	printf("Send LagreData size : %d\n",snd_count);
	TcpPacketInfo.tx_control == SERVER_CONTROL_SEND_COMPLETE;

}

void TCP_TransferComplete(void)
{

}

unsigned char *GetTCPBufferAddress(unsigned int *bufferMaxSize)
{
	unsigned short command = TCPRXHeader.Command;
	if (command == CMD_ECHO)
	{
		*bufferMaxSize = ECHO_BUFFER_MAX_SIZE;
		return (unsigned char *)EchoBuffer;		
	}
	else if (command == CMD_DOWNLOAD)
	{
		*bufferMaxSize = DOWNLOAD_MAX_SIZE;
		return (unsigned char *)ProgramBuffer;		
	}
	else
	{
		*bufferMaxSize = 0;
		return NULL;
	}
}

void Tcp_Processing()		// called from main loop
{
	unsigned int *returnData;
	//unsigned int t1,t2;
	unsigned int VerChkl,VerChk2; //sjm Add
	TCaptureCommandParam *captureCommandParam;
	unsigned short command = TcpPacketInfo.Command;
	CSL_IntcGlobalEnableState 	state;
	TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)GlobalTCPTxDataBuffer;
	TcpPacketInfo.ResultSmallDataSize = 0;
	TcpPacketInfo.ResultLargeDataAddress = NULL;
	TcpPacketInfo.ResultLargeDataSize = 0;
	TcpPacketInfo.LargeDataSize = TcpReceiveDataInfo.LargeDataSize;
	TcpPacketInfo.SmallDataSize = TcpReceiveDataInfo.SmallDataSize;

	memset(&TcpReceiveDataInfo, 0 , sizeof(TCPReceiveData));

	if (command == CMD_READ_ERROR_LIST)
	{
		int maxCount;
		int getCount;
		maxCount = *(int *) TcpPacketInfo.SmallDataAddress;
		if (maxCount > 16) maxCount = 16;
		getCount = ErrorQueue_Get(GlobalSysResultBuffer + sizeof(int), maxCount);
		ErrorQueue_Remove(getCount);
		*(int *)GlobalSysResultBuffer = getCount;
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)GlobalSysResultBuffer;
		TcpPacketInfo.ResultSmallDataSize = getCount * sizeof(TErrorUnit) + sizeof(int);
	}

	else if (command == CMD_DOWNLOAD)
	{
		unsigned int pID, result;
		int time;
		
		CSL_intcGlobalDisable(NULL);
		pID = *(unsigned int *)TcpPacketInfo.SmallDataAddress;
		time = *((int *)TcpPacketInfo.SmallDataAddress + 1);
		result = WriteToFlash(pID, TcpPacketInfo.LargeDataAddress, TcpPacketInfo.LargeDataSize, time);
		CSL_intcGlobalEnable(&state);
	}
	else if (command == CMD_RESET)
	{
		Jump_SW = TRUE;	

	}

	else if (command == CMD_FLASH_INFO)
	{
		TcpPacketInfo.ResultLargeDataAddress = (unsigned char *) GetFileSystem();
		TcpPacketInfo.ResultLargeDataSize = sizeof(TFFSystem);
	}
	else if (command == CMD_FLASH_FORMAT)
	{
		CSL_intcGlobalDisable(NULL);
		FlashFormat();
		CSL_intcGlobalEnable(&state);
	}
	else if (command == CMD_CAMERA_CONTROL_PROCESSING_MODE)
	{
		int cameraStartY;
		int cameraEndY;

		TTPBCameraParams* camParams;
		camParams = (TTPBCameraParams *) TcpPacketInfo.SmallDataAddress;
		
		// 이미지 시작점 제한
		camParams->bounaryStartY = 0; 

		// 이미지 Blank 제거
		camParams->bounaryEndY = camParams->bounaryEndY + NFA_HALF_FIFO_SIZE / SYSTEM_CAMERA_WIDTH;
		if(camParams->bounaryEndY > SYSTEM_CAMERA_HEIGHT - 1) camParams->bounaryEndY = SYSTEM_CAMERA_HEIGHT - 1;


		/*
		cameraStartY = camParams->bounaryStartY * 2;
		cameraEndY = camParams->bounaryEndY * 2;

		cameraStartY = cameraStartY / 32 * 32;
		cameraEndY = cameraEndY / 32 * 32;
		if(cameraEndY < camParams->bounaryEndY * 2) cameraEndY = cameraEndY + 32;
		if(cameraEndY > 928) cameraEndY = 928;

		camParams->bounaryStartY = cameraStartY / 2;
		camParams->bounaryEndY = cameraEndY / 2;
		*/

		TPBCameraConfig(camParams);
		AllocateImageBuffer(SYSTEM_CAMERA_WIDTH * (camParams->bounaryEndY - camParams->bounaryStartY));
		NFACaptureInfo.CaptureTopPos = camParams->bounaryStartY;
		NFACaptureInfo.FrameHeight = camParams->bounaryEndY;
	}
	else if (command == CMD_CAPTURE_SETUP)
	{
		TCaptureSetupData* captureSetupData;
		captureSetupData = (TCaptureSetupData *) TcpPacketInfo.SmallDataAddress;
		NomalImageInfo.inspectionIndex = NomalImageInfo.currentIndex;
		NFACaptureInfo.CapturePeriodCount = captureSetupData->ShutterDelay[0];
		NFACaptureInfo.CapturePeriod = captureSetupData->ShutterDelay[0];
		TPBInspectInit();
		NFACaptureInfo.CaptureStatus = TPB_CAPTURE_START;
	}
	else if (command == CMD_CAPTURE_STOP)
	{
		TPBInspectInit();
		NFACaptureInfo.CaptureOption = TPB_OPTION_CAPTURE;
		NFACaptureInfo.CaptureStatus = TPB_CAPTURE_STOP;
	}
	else if (command == CMD_TPB_INSPECTION)
	{
		TTPBInspectionData* Tpbdata;
		Tpbdata = (TTPBInspectionData *) TcpPacketInfo.SmallDataAddress;	
		InspectDataTbp.TabletLength = Tpbdata->TabletLength;
		InspectDataTbp.TabletWidth = Tpbdata->TabletWidth;
		InspectDataTbp.WhiteBalance[0] = Tpbdata->WhiteBalance[0];
		InspectDataTbp.WhiteBalance[1] = Tpbdata->WhiteBalance[1];
		InspectDataTbp.WhiteBalance[2] = Tpbdata->WhiteBalance[2];
		InspectDataTbp.InsAreaLeft = Tpbdata->InsAreaLeft;
		InspectDataTbp.InsAreaRight = Tpbdata->InsAreaRight;
		InspectDataTbp.InsAreaTop = Tpbdata->InsAreaTop;
		InspectDataTbp.InsAreaBottom = Tpbdata->InsAreaBottom;
		InspectDataTbp.Threshold = Tpbdata->Threshold;
		NFACaptureInfo.CaptureUploadOption  = Tpbdata->CaptureUploadOption;
		NFACaptureInfo.CaptureDelay_Min = Tpbdata->CaptureDelay_Min;
		NFACaptureInfo.CaptureDelay_Max = Tpbdata->CaptureDelay_Max;
		NFACaptureInfo.CaptureOption = TPB_OPTION_INSPECTION;
	}
	else if (command == CMD_CAPTURE_EXIST)
	{
		unsigned int camNo;
		camNo = *(unsigned int *) TcpPacketInfo.SmallDataAddress;
		returnData = (unsigned int *)GlobalSysResultBuffer;
		returnData[0] = ImageControlGetCapturedFrameCount(NFACaptureInfo.CaptureUploadOption);
		returnData[1] = NomalImageInfo.BlockCount;
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)GlobalSysResultBuffer;
		TcpPacketInfo.ResultSmallDataSize = 2 * sizeof(unsigned int);		
	}
	else if (command == CMD_CAPTURE_UPLOAD)
	{
		unsigned int camNo;
		unsigned int bufferReadSize;
		int dstWidth;
		int reduction;
		
		camNo = *(unsigned int *) TcpPacketInfo.SmallDataAddress;
		bufferReadSize = *(unsigned int *) (TcpPacketInfo.SmallDataAddress + 4);
		dstWidth = *(unsigned int *) (TcpPacketInfo.SmallDataAddress + 8);
		reduction = *(unsigned int *) (TcpPacketInfo.SmallDataAddress + 12);

		Request_BayerImageScaleConversion((unsigned char *) ImageControlGetFirstValidFrameBuffer(NFACaptureInfo.CaptureUploadOption), DummyImage, SYSTEM_CAMERA_WIDTH, dstWidth, SYSTEM_CAMERA_WIDTH * (NFACaptureInfo.FrameHeight - NFACaptureInfo.CaptureTopPos), reduction, 2);

		TcpPacketInfo.ResultLargeDataAddress = (unsigned char *) DummyImage;
		TcpPacketInfo.ResultLargeDataSize = bufferReadSize;
	}
	else if (command == CMD_MIS_EJECT_CONTROL)
	{
		int mis_eject_control = 0;
		short int set_bit_val = 0;

		mis_eject_control = *(int *) TcpPacketInfo.SmallDataAddress;

		switch(mis_eject_control)
		{
			case 0 : 
				set_bit_val = 0x1 << 0; break;
			case 1 : 
				set_bit_val = 0x1 << 1; break;
			case 2 : 
				set_bit_val = 0x1 << 2; break;
			default : 
				set_bit_val = 0x0; break;
		}

		TPB_CAMERA_INT = set_bit_val;
		TPB_CAMERA_INT = set_bit_val;

		returnData = (unsigned int *)GlobalSysResultBuffer;
		returnData[0] = (unsigned int)set_bit_val;
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)GlobalSysResultBuffer;
		TcpPacketInfo.ResultSmallDataSize = sizeof(unsigned int);	
	}
	else if (command == CMD_MONITOR_TPB_INS_DATA)
	{
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&TPBMonitorInsData;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TTPBMonitorInsData);	
	}
	else if (command == CMD_CHK_CPB_PROCESS)
	{
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&TPBProcessInfo;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TTBPProcessInfo);	
	}
	else if (command == CMD_CHK_INS_PROCESS)
	{
		TPBInsProcessInfo.currentCaptureIndex = NomalImageInfo.currentIndex;
		TPBInsProcessInfo.capturePeriod 			= NomalImageInfo.CapturePeriod[NomalImageInfo.currentIndex-1];

		TPBInsProcessInfo.process_startTime 	= TestDebug.startTime[TestDebug.checkcount-1];
		TPBInsProcessInfo.process_period			= TestDebug.period[TestDebug.checkcount-1];
		TPBInsProcessInfo.process_checkcount	= TestDebug.checkcount-1;
		
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&TPBInsProcessInfo;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TTPBInsProcessInfo);		
	}
	else if (command == CMD_VERSION_INFO)
	{
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&ProgramVersion;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TProgramVersion);
	}
	else if (command == CMD_FPGA_VERSION_INFO)
	{
#ifdef FPGA220
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&FPGAnewVersion2;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TSPBFPGAVersion);
#else
		// sjm Chg 
		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&SPBFPGAVersion;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TSPBFPGAVersion);
#endif		
	}	
	else if (command == CMD_READ_COMPATIBILITY)
	{
		int cpbIndex;
		TCPBCompatibility CPBCompatibility;
		for (cpbIndex = 0; cpbIndex < SYSTEM_CPB_COUNT; cpbIndex++)
		{
			if (!CPBStatus[cpbIndex].IsDown)
			{
				if (Request_ReceiveData(IND_READ_COMPATIBILITY, &CPBCompatibility, sizeof(TCPBCompatibility), cpbIndex))
				{
					TPBCompatibility.CPBAlgMajorVersion = CPBCompatibility.AlgMajorVersion;
					TPBCompatibility.CPBAlgMinorVersion = CPBCompatibility.AlgMinorVersion;
					TPBCompatibility.CPBAlgReleaseDate = CPBCompatibility.AlgReleaseDate;
					TPBCompatibility.CPBAlgTargetSystem = CPBCompatibility.AlgTargetSystem;
					break;
				}
				else
				{
					TPBCompatibility.CPBAlgMajorVersion = 0;
					TPBCompatibility.CPBAlgMinorVersion = 0;
					TPBCompatibility.CPBAlgReleaseDate = 0;
					TPBCompatibility.CPBAlgTargetSystem = 0;
				}
			}
		}

		TcpPacketInfo.ResultSmallDataAddress = (unsigned char *)&TPBCompatibility;
		TcpPacketInfo.ResultSmallDataSize = sizeof(TSPBCompatibility);
	}		
	else if (command == CMD_ECHO)
	{
		TcpPacketInfo.ResultSmallDataAddress = TcpPacketInfo.SmallDataAddress;
		TcpPacketInfo.ResultSmallDataSize = TcpPacketInfo.SmallDataSize;
		TcpPacketInfo.ResultLargeDataAddress = TcpPacketInfo.LargeDataAddress;
		TcpPacketInfo.ResultLargeDataSize = TcpPacketInfo.LargeDataSize;
	}

	if(command != 0)
		TcpPacketInfo.Status = SERVER_STATUS_SEND;	
}

