/*************************************************/
/*  Client functions source file using BSD       */
/*			for 7188E modules    	             */
/* v1.00.0[July,03,2002] Established by Sean     */
/* v1.01.0[Jan,17,2003] Modified by Sean         */
/*	Fix the connection timeout				     */
/*************************************************/
#include "..\lib\7186e.h"
#include "..\lib\tcpip32.h"

int BuildSocket(unsigned char *cIP,int iPort,long ltimeout)
{
	struct sockaddr_in server;  
	int iOutskt;
	int irc;  	
	unsigned char *ip; 
	unsigned long ltime;  
	
  	iOutskt=-1;

	ltime=*TimeTicks;

/*  	if (iOutskt!=-1)
  	{
//  		printCom1("iOutskt wrong\n\r");  /*for debug*
    	if (SOCKET_ISOPEN(iOutskt)) 
    		shutdown(iOutskt,0); //SOCKET_ISOPEN() check the connection
      	closesocket(iOutskt);
      	DelayMs(30);
  	}*/
	
	iOutskt=socket(PF_INET,SOCK_STREAM,0);  //Creates a socket,SOCK_STREAM stream socket(TCP/IP)
	if(iOutskt<0)
		return -1;
		
	YIELD();		//YIELD()macro allow other tasks getting an opportunity to execute
	memset( &server, 0, sizeof(server) ); /* bzero is a unix system call */
  	server.sin_family = AF_INET;          
  	server.sin_addr.s_addr = inet_addr(cIP);
  	server.sin_port = htons( iPort );
	//ip=(unsigned char*)&server.sin_addr.s_addr;  /*for debug*/
	//printCom1("iOutskt=%d,server ip=%d.%d.%d.%d\n\r",iOutskt,ip[0],ip[1],ip[2],ip[3]);  /*for debug*/
  	//printCom2("iOutskt=%d,server ip=%d.%d.%d.%d\n\r",iOutskt,ip[0],ip[1],ip[2],ip[3]);  /*for debug*/
	
	YIELD();
	
	DisableWDT();
	SOCKET_NOBLOCK(iOutskt);   /*Set Non-blocking mode*/
	if(connect(iOutskt, (struct sockaddr *)&server, sizeof(server))) /* unsuccessful connection not 0 */
	{		
		extern int errno;
//		unsigned cnt=0;  /*for debug*/
//		printCom1("irc=%d\n\r",irc);  /*for debug*/
		if(errno==EINPROGRESS)
		{
				while(*TimeTicks-ltime<ltimeout)
				{
					RefreshWDT();
					YIELD();
//					Print("\r[%u]",++cnt); /*for debug*/
					if(SOCKET_ISOPEN(iOutskt)) goto ConnectSuccess;
				}							
		}
		EnableWDT();		
		return -1;
	}	
ConnectSuccess:		
	SOCKET_BLOCK(iOutskt);
	EnableWDT();
	if(SOCKET_ISOPEN(iOutskt))
	{			
      	return iOutskt;
	}
	else
	{	
		closesocket(iOutskt);
		return -1;
	}     	
}	

int SendSocketBinaryCmd(int iSocket,char *cOutBuf,int iLen)
{	
	int irc;	

	if(iLen)
	{		
		RefreshWDT();
		irc= send(iSocket,cOutBuf,iLen,0);
//		SOCKET_BLOCK(iSocket);
		YIELD();
   		return irc;
  	}
	else
  		return -1;
}
int ReceiveSocketBinaryCmd(int iSocket,char *cInBuf,int iMaxLen,int iTimeout)
{
	int irc;
	
	SOCKET_RXTOUT(iSocket, iTimeout); //set the receive timeout for a connection//
	RefreshWDT();
	irc= recv(iSocket,cInBuf,iMaxLen,0);
	SOCKET_BLOCK(iSocket);
	YIELD();
	if (irc>=0)
	{
		cInBuf[irc]=0;
		return irc;
	}		
	else return -1;
}
void KillSocket(int iSocket)
{
	shutdown( iSocket, 0 );
	closesocket( iSocket);
}
