/* [Jan 28, 2015] */ #include #include #include "..\..\..\lib\upac5000.h" #include "..\..\lib\tcpip32.h" #include "tcpConn.h" extern int errno; extern long ET_TOUT; static struct sockaddr_in s_in; tcpclient TCPClient; int CloseSocket(int socket) { if(socket<0) return -1; shutdown(socket, 0); closesocket(socket); TCPClient.bConnected=-1; TCPClient.socket=-1; TCPClient.lCurrentTicks=GetTimeTicks(); SOCKET_SET_TCP_KEEP_ALIVE_OFF(socket); return socket; } void EthernetLoop(void) { long ET_TOUT_BACKUP; int retval, err; int skt; YIELD(); switch(TCPClient.bConnected) { case -1: /* attempt to reconnect to the TCP server if the TCPClient.iReconnectInterval is greater than 2000 ms */ if(TCPClient.iReconnectInterval<2000l) break; if(GetTimeTicks()-TCPClient.lCurrentTicks<=TCPClient.iReconnectInterval) break; TCPClient.lCurrentTicks=GetTimeTicks(); case -2: // create a socket and then attempt to connect to the TCP server skt=socket(PF_INET, SOCK_STREAM, 0); if(skt<0) { TCPClient.bConnected=-1; break; } TCPClient.socket=skt; memset(&s_in, 0, sizeof(s_in)); s_in.sin_family=AF_INET; s_in.sin_addr.s_addr=inet_addr((char *) &TCPClient.ip); s_in.sin_port=htons(TCPClient.port); SOCKET_NOBLOCK(skt); ET_TOUT_BACKUP=ET_TOUT; ET_TOUT=200; RefreshWDT(); TCPClient.lCurrentTicks=GetTimeTicks(); retval=connect(skt, (struct sockaddr *) &s_in, sizeof(s_in)); ET_TOUT=ET_TOUT_BACKUP; if(retval) { if(errno==EINPROGRESS) TCPClient.bConnected=0; else { // cannot connect to the TCP server due to some reasons CloseSocket(skt); } } else { CONNECT_SUCCESS: // on success returns a value of zero SOCKET_BLOCK(skt); TCPClient.bConnected=1; SOCKET_SET_TCP_KEEP_ALIVE_ON(skt); Ethernet_Receive(skt, 0); } break; case 0: // waits for the response from the server until timeout period expires skt=TCPClient.socket; if(SOCKET_ISOPEN(skt)) goto CONNECT_SUCCESS; else if(GetTimeTicks()-TCPClient.lCurrentTicks>TCPClient.lConnectTimeout) CloseSocket(skt); break; case 1: // successfully connecting the TCP server skt=TCPClient.socket; retval=ioctlsocket(skt, FIONREAD, &err); if(!retval && err>0) Ethernet_Receive(skt, 1); break; } } int TcpClient_Connect(char *serverIp, unsigned serverPort, long connectTimeout, long reconnectInterval) { /* serverIp: IP address of TCP server, for example: "192.168.255.1" serverPort: Connection port of TCP server connectTimeout: Connection timeout, in milliseconds The length of time to wait for a connection to the TCP server. reconnectInterval: Reconnect interval, in milliseconds Reconnect interval is the amount of time between attempts by the module to reconnect with the TCP server. If reconnectInterval is greater than 2000 ms, TCPClient always attempting to reconnect to the TCP server after a loss of connection. */ strcpy(TCPClient.ip, serverIp); TCPClient.port=serverPort; TCPClient.lConnectTimeout=connectTimeout; TCPClient.iReconnectInterval=reconnectInterval; TCPClient.bConnected=-2; return 0; }