예제 #1
0
int8_t  getsockopt(uint8_t sn, sockopt_type sotype, void* arg)
{
   CHECK_SOCKNUM();
   switch(sotype)
   {
      case SO_FLAG:
         *(uint8_t*)arg = getSn_MR(sn) & 0xF0;
         break;
      case SO_TTL:
         *(uint8_t*) arg = getSn_TTL(sn);
         break;
      case SO_TOS:
         *(uint8_t*) arg = getSn_TOS(sn);
         break;
      case SO_MSS:   
         *(uint16_t*) arg = getSn_MSSR(sn);
         break;
      case SO_DESTIP:
         getSn_DIPR(sn, (uint8_t*)arg);
         break;
      case SO_DESTPORT:  
         *(uint16_t*) arg = getSn_DPORT(sn);
         break;
   #if _WIZCHIP_ > 5200   
      case SO_KEEPALIVEAUTO:
         CHECK_SOCKMODE(Sn_MR_TCP);
         *(uint16_t*) arg = getSn_KPALVTR(sn);
         break;
   #endif      
      case SO_SENDBUF:
         *(uint16_t*) arg = getSn_TX_FSR(sn);
         break;
      case SO_RECVBUF:
         *(uint16_t*) arg = getSn_RX_RSR(sn);
         break;
      case SO_STATUS:
         *(uint8_t*) arg = getSn_SR(sn);
         break;
      case SO_REMAINSIZE:
         if(getSn_MR(sn) & Sn_MR_TCP)
            *(uint16_t*)arg = getSn_RX_RSR(sn);
         else
            *(uint16_t*)arg = sock_remained_size[sn];
         break;
      case SO_PACKINFO:
         //CHECK_SOCKMODE(Sn_MR_TCP);
#if _WIZCHIP_ != 5300
         if((getSn_MR(sn) == Sn_MR_TCP))
             return SOCKERR_SOCKMODE;
#endif
         *(uint8_t*)arg = sock_pack_info[sn];
         break;
      default:
         return SOCKERR_SOCKOPT;
   }
   return SOCK_OK;
}
예제 #2
0
파일: main.c 프로젝트: Wiznet/W7500P
/**
  * @brief   Main program
  * @param  None
  * @retval None
  */
int main()
{
    //uint8_t tx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    //uint8_t rx_size[8] = { 2, 2, 2, 2, 2, 2, 2, 2 };
    uint8_t mac_addr[6] = {0x00, 0x08, 0xDC, 0x01, 0x02, 0x03}; 
    uint8_t src_addr[4] = {192, 168,  0,  9};
    uint8_t gw_addr[4]  = {192, 168,  0,  1};
    uint8_t sub_addr[4] = {255, 255, 255,  0};		
    //uint8_t dns_server[4] = {8, 8, 8, 8};           // for Example domain name server
    uint8_t tmp[8];
		
		int32_t ret;
		uint16_t port=5000, size = 0, sentsize=0;
		uint8_t destip[4];
		uint16_t destport;

		*(volatile uint32_t *)(0x41001014) = 0x0060100; //clock setting 48MHz
		
		/* External Clock */
    //CRG_PLL_InputFrequencySelect(CRG_OCLK);

    /* Set Systme init */
    SystemInit();
		
		SSP0_Initialize();
		SSP1_Initialize();
		GPIO_Initialize();	

		GPIO_SetBits(GPIOC, GPIO_Pin_8); // LED red off
		GPIO_SetBits(GPIOC, GPIO_Pin_9); // LED green off
		GPIO_ResetBits(GPIOC, GPIO_Pin_6); // Test off

    /* UART Init */
    UART_StructInit(&UART_InitStructure);
    UART_Init(UART1,&UART_InitStructure);

    /* SysTick_Config */
    SysTick_Config((GetSystemClock()/1000));

    /* Set WZ_100US Register */
    setTIC100US((GetSystemClock()/10000));
    //getTIC100US();	
    //printf(" GetSystemClock: %X, getTIC100US: %X, (%X) \r\n", 
    //      GetSystemClock, getTIC100US(), *(uint32_t *)TIC100US);        


#ifdef __DEF_USED_IC101AG__ //For using IC+101AG
    *(volatile uint32_t *)(0x41003068) = 0x64; //TXD0 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x4100306C) = 0x64; //TXD1 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003070) = 0x64; //TXD2 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003074) = 0x64; //TXD3 - set PAD strengh and pull-up
    *(volatile uint32_t *)(0x41003050) = 0x64; //TXE  - set PAD strengh and pull-up
#endif	
    printf("PHY is linked. \r\n"); 
#ifdef __DEF_USED_MDIO__ 
    /* mdio Init */
    mdio_init(GPIOB, MDC, MDIO );
    //mdio_error_check(GPIOB, MDC, MDIO); //need verify...
    /* PHY Link Check via gpio mdio */
    while( link() == 0x0 )
    {
        printf(".");  
        delay(500);
    }
    printf("PHY is linked. \r\n");  
#else
    delay(1000);
    delay(1000);
#endif

    /* Network Configuration */
    setSHAR(mac_addr);
    setSIPR(src_addr);
    setGAR(gw_addr);
    setSUBR(sub_addr);

    getSHAR(tmp);
    printf(" MAC ADDRESS : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\r\n",tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5]); 
    getSIPR(tmp);
    printf("IP ADDRESS : %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getGAR(tmp);
    printf("GW ADDRESS : %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
    getSUBR(tmp);
    printf("SN MASK: %d.%d.%d.%d\r\n",tmp[0],tmp[1],tmp[2],tmp[3]); 
   
    /* Set Network Configuration */
    //wizchip_init(tx_size, rx_size);

    printf(" TEST- START \r\n");  
		
    while(1)
    {
        switch(getSn_SR(SOCK_NUM))
				{
					case SOCK_ESTABLISHED:
					if(getSn_IR(SOCK_NUM) & Sn_IR_CON)
					{
						getSn_DIPR(SOCK_NUM, destip);
						destport = getSn_DPORT(SOCK_NUM);
						printf("%d:Connected - %d.%d.%d.%d : %d\r\n",SOCK_NUM, destip[0], destip[1], destip[2], destip[3], destport);
						setSn_IR(SOCK_NUM,Sn_IR_CON);
					}
					if((size = getSn_RX_RSR(SOCK_NUM)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
					{
						if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
						ret = recv(SOCK_NUM, test_buf, size);

						if(ret <= 0) return ret;      // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
						
						 /* Send only data to SSP1 */ 
						for (TxIdx=0; TxIdx<size; TxIdx++)
						{
							SSP_SendData(SSP0, test_buf[TxIdx]);
							while( SSP_GetFlagStatus(SSP0, SSP_FLAG_BSY) );
						}
						
						/* Receive only data from SSP0 */
						while(SSP_GetFlagStatus(SSP1, SSP_FLAG_RNE))
						{
							SSP1_Buffer_Rx[RxIdx] = SSP_ReceiveData(SSP1);
							RxIdx++;
						} 
						RxIdx=0;
						
						sentsize = 0;

						while(size != sentsize)
						{
							ret = send(SOCK_NUM, SSP1_Buffer_Rx+sentsize, size-sentsize);
							if(ret < 0)
							{
								close(SOCK_NUM);
								return ret;
							}
							sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
						}
					}
						break;
					case SOCK_CLOSE_WAIT:
						printf("%d:CloseWait\r\n",SOCK_NUM);
						if((ret = disconnect(SOCK_NUM)) != SOCK_OK) return ret;
						printf("%d:Socket Closed\r\n", SOCK_NUM);

						break;
					case SOCK_INIT:
						printf("%d:Listen, TCP server loopback, port [%d]\r\n", SOCK_NUM, port);
						if( (ret = listen(SOCK_NUM)) != SOCK_OK) return ret;
						break;
					
					case SOCK_CLOSED:
						
						printf("%d:TCP server loopback start\r\n",SOCK_NUM);
						if((ret = socket(SOCK_NUM, Sn_MR_TCP, port, 0x00)) != SOCK_NUM) return ret;
						printf("%d:Socket opened\r\n",SOCK_NUM);
					
						break;
					
					default:
						break;
					
				}
    }

}
예제 #3
0
파일: loopback.c 프로젝트: Wiznet/W5500_EVB
// TCP & UDP Loopback Test
int32_t loopback_tcps(uint8_t sn, uint8_t* buf, uint16_t port)
{
    int32_t ret;
    uint16_t size = 0, sentsize=0;
#ifdef _LOOPBACK_DEBUG_
    uint8_t destip[4];
    uint16_t destport;
#endif

    switch(getSn_SR(sn))
    {
    case SOCK_ESTABLISHED :
        if(getSn_IR(sn) & Sn_IR_CON)
        {
#ifdef _LOOPBACK_DEBUG_
            getSn_DIPR(sn, destip);
            destport = getSn_DPORT(sn);

            printf("%d:Connected - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
            setSn_IR(sn,Sn_IR_CON);
        }
        if((size = getSn_RX_RSR(sn)) > 0)
        {
            if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
            ret = recv(sn, buf, size);
            if(ret <= 0) return ret;
            sentsize = 0;
            while(size != sentsize)
            {
                ret = send(sn,buf+sentsize,size-sentsize);
                if(ret < 0)
                {
                    close(sn);
                    return ret;
                }
                sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
            }
        }
        break;
    case SOCK_CLOSE_WAIT :
#ifdef _LOOPBACK_DEBUG_
        //printf("%d:CloseWait\r\n",sn);
#endif
        if((ret=disconnect(sn)) != SOCK_OK) return ret;
#ifdef _LOOPBACK_DEBUG_
        printf("%d:Socket closed\r\n",sn);
#endif
        break;
    case SOCK_INIT :
#ifdef _LOOPBACK_DEBUG_
        printf("%d:Listen, TCP server loopback, port [%d]\r\n",sn, port);
#endif
        if( (ret = listen(sn)) != SOCK_OK) return ret;
        break;
    case SOCK_CLOSED:
#ifdef _LOOPBACK_DEBUG_
        //printf("%d:TCP server loopback start\r\n",sn);
#endif
        if((ret=socket(sn, Sn_MR_TCP, port, 0x00)) != sn)
            //if((ret=socket(sn, Sn_MR_TCP, port, Sn_MR_ND)) != sn)
            return ret;
#ifdef _LOOPBACK_DEBUG_
        //printf("%d:Socket opened\r\n",sn);
#endif
        break;
    default:
        break;
    }
    return 1;
}
예제 #4
0
// Poll a socket to see if it needs to be serviced
void W5500Socket::Poll(bool full)
{
	if (state != SocketState::disabled)
	{
		MutexLocker lock(interface->interfaceMutex);

		switch(getSn_SR(socketNum))
		{
		case SOCK_INIT:
			// Socket has been initialised but is not listening yet
			if (localPort != 0)			// localPort for the FTP data socket is 0 until we have decided what port number to use
			{
				ExecCommand(socketNum, Sn_CR_LISTEN);
				state = SocketState::listening;
			}
			break;

		case SOCK_LISTEN:				// Socket is listening but no client has connected to it yet
			break;

		case SOCK_ESTABLISHED:			// A client is connected to this socket
			if (getSn_IR(socketNum) & Sn_IR_CON)
			{
				// New connection, so retrieve the sending IP address and port, and clear the interrupt
				getSn_DIPR(socketNum, remoteIPAddress);
				remotePort = getSn_DPORT(socketNum);
				setSn_IR(socketNum, Sn_IR_CON);
				whenConnected = millis();
			}

			if (full && state == SocketState::listening)		// if it is a new connection
			{
				if (reprap.GetNetwork().FindResponder(this, protocol))
				{
					state = SocketState::connected;
					sendOutstanding = false;
				}
				else if (millis() - whenConnected >= FindResponderTimeout)
				{
					if (reprap.Debug(moduleNetwork))
					{
						debugPrintf("Timed out waiting for resonder for port %u\n", localPort);
					}
					Terminate();
				}
			}

			if (state == SocketState::connected)
			{
				// See if the socket has received any data
				ReceiveData();
			}
			break;

		case SOCK_CLOSE_WAIT:			// A client has asked to disconnect
			// Check for further incoming packets before this socket is finally closed.
			// This must be done to ensure that FTP uploads are not cut off.
			ReceiveData();

			state = SocketState::clientDisconnecting;
			break;

		case SOCK_CLOSED:
			ReInit();
			break;

		default:
			break;
		}
	}
}
예제 #5
0
/*******************************************
 * @ brief Call back for Simple HTTP Client 
 *******************************************/
int32_t httpclient(uint8_t sn, uint8_t* buf, uint16_t port)
{
   int32_t ret;
   uint16_t size = 0,  i=0;
#ifdef _HTTPCLI_DEBUG_
   uint8_t destip[4];
   uint16_t destport;
   uint16_t http_cmd_sz = 800;
   uint8_t http_cmd[800];
#endif

   switch(getSn_SR(sn))
   {
      case SOCK_ESTABLISHED :
         if(getSn_IR(sn) & Sn_IR_CON)
         {
#ifdef _HTTPCLI_DEBUG_
        	 getSn_DIPR(sn, destip);
        	 destport = getSn_DPORT(sn);

        	 printf("%d:Connected - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
            setSn_IR(sn,Sn_IR_CON);

            snprintf(http_cmd, http_cmd_sz,  "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", URI, Domain_name);
            ret = send(sn, http_cmd, http_cmd_sz-1);
               if(ret < 0)
               {
                  close(sn);
                  return ret;
               }
    
         }
         if((size = getSn_RX_RSR(sn)) > 0)
         {
            if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
            ret = recv(sn, buf, size);
            for(i=0; i<ret; i++)
            {
                printf("%c",buf[i]);           
            }
            printf("\r\n");
            if(ret <= 0) return ret;
         }
         break;
      case SOCK_CLOSE_WAIT :
#ifdef _HTTPCLI_DEBUG_
         //printf("%d:CloseWait\r\n",sn);
#endif
         if((size = getSn_RX_RSR(sn)) > 0)
         {
             if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
             ret = recv(sn, buf, size);
             if(ret <= 0) return ret;
         }
         if((ret=disconnect(sn)) != SOCK_OK) return ret;
#ifdef _HTTPCLI_DEBUG_
         printf("%d:Socket closed\r\n",sn);
#endif
         break;
      case SOCK_INIT :
         /* do dns */
         ret = dns_do(SOCK_DNS, buf);

         /* do tcp connection */
         if(ret)
         {
             ret = connect(sn, Domain_IP, PORT_HTTPS);
#ifdef _HTTPCLI_DEBUG_
             if(ret)
             {
                 printf("%d:, Connect... HTTP Server\r\n",sn);
             }
#endif
         }
         break;
      case SOCK_CLOSED:
#ifdef _HTTPCLI_DEBUG_
         //printf("%d:TCP server loopback start\r\n",sn);
#endif
         if((ret=socket(sn, Sn_MR_TCP, port, 0x00)) != sn)
         //if((ret=socket(sn, Sn_MR_TCP, port, Sn_MR_ND)) != sn) // no delay ack
            return ret;
#ifdef _HTTPCLI_DEBUG_
         //printf("%d:Socket opened\r\n",sn);
#endif
         break;
      default:
         break;
   }
   return 1;
}
예제 #6
0
void httpServer_run(uint8_t seqnum)
{
	uint8_t s;	// socket number
	uint16_t len;
	uint32_t gettime = 0;

#ifdef _HTTPSERVER_DEBUG_
	uint8_t destip[4] = {0, };
	uint16_t destport = 0;
#endif

	http_request = (st_http_request *)pHTTP_RX;		// Structure of HTTP Request
	parsed_http_request = (st_http_request *)pHTTP_TX;

	// Get the H/W socket number
	s = getHTTPSocketNum(seqnum);

	/* HTTP Service Start */
	switch(getSn_SR(s))
	{
		case SOCK_ESTABLISHED:
			// Interrupt clear
			if(getSn_IR(s) & Sn_IR_CON)
			{
				setSn_IR(s, Sn_IR_CON);
			}

			// HTTP Process states
			switch(HTTPSock_Status[seqnum].sock_status)
			{

				case STATE_HTTP_IDLE :
					if ((len = getSn_RX_RSR(s)) > 0)
					{
						if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;
						len = recv(s, (uint8_t *)http_request, len);

						*(((uint8_t *)http_request) + len) = '\0';

						parse_http_request(parsed_http_request, (uint8_t *)http_request);
#ifdef _HTTPSERVER_DEBUG_
						getSn_DIPR(s, destip);
						destport = getSn_DPORT(s);
						printf("\r\n");
						printf("> HTTPSocket[%d] : HTTP Request received ", s);
						printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif
#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", s);
#endif
						// HTTP 'response' handler; includes send_http_response_header / body function
						http_process_handler(s, parsed_http_request);

						gettime = get_httpServer_timecount();
						// Check the TX socket buffer for End of HTTP response sends
						while(getSn_TX_FSR(s) != (getSn_TXBUF_SIZE(s)*1024))
						{
							if((get_httpServer_timecount() - gettime) > 3)
							{
#ifdef _HTTPSERVER_DEBUG_
								printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE: TX Buffer clear timeout\r\n", s);
#endif
								break;
							}
						}

						if(HTTPSock_Status[seqnum].file_len > 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_INPROC;
						else HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
					}
					break;

				case STATE_HTTP_RES_INPROC :
					/* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", s);
#endif
					// Repeatedly send remaining data to client
					send_http_response_body(s, 0, http_response, 0, 0);

					if(HTTPSock_Status[seqnum].file_len == 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
					break;

				case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", s);
#endif
					// Socket file info structure re-initialize
					HTTPSock_Status[seqnum].file_len = 0;
					HTTPSock_Status[seqnum].file_offset = 0;
					HTTPSock_Status[seqnum].file_start = 0;
					HTTPSock_Status[seqnum].sock_status = STATE_HTTP_IDLE;

//#ifdef _USE_SDCARD_
//					f_close(&fs);
//#endif
#ifdef _USE_WATCHDOG_
					HTTPServer_WDT_Reset();
#endif
					http_disconnect(s);
					break;

				default :
					break;
			}
			break;

		case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
		printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", s);	// if a peer requests to close the current connection
#endif
			disconnect(s);
			break;

		case SOCK_CLOSED:
#ifdef _HTTPSERVER_DEBUG_
			printf("> HTTPSocket[%d] : CLOSED\r\n", s);
#endif
			if(socket(s, Sn_MR_TCP, HTTP_SERVER_PORT, 0x00) == s)    /* Reinitialize the socket */
			{
#ifdef _HTTPSERVER_DEBUG_
				printf("> HTTPSocket[%d] : OPEN\r\n", s);
#endif
			}
			break;

		case SOCK_INIT:
			listen(s);
			break;

		case SOCK_LISTEN:
			break;

		default :
			break;

	} // end of switch

#ifdef _USE_WATCHDOG_
	HTTPServer_WDT_Reset();
#endif
}
예제 #7
0
void httpServer_run(uint8_t seqnum)
{
    uint8_t s;	// socket number
    int16_t len;
    //uint32_t gettime = 0;	// 20150828 ## Eric removed

    uint8_t ret = 0;

#ifdef _HTTPSERVER_DEBUG_
    uint8_t destip[4] = {0, };
    uint16_t destport = 0;
#endif

    http_request = (st_http_request *)pHTTP_RX;		// Structure of HTTP Request
    parsed_http_request = (st_http_request *)pHTTP_TX;

    // Get the H/W socket number
    s = getHTTPSocketNum(seqnum);

    /* HTTP Service Start */
    switch(getSn_SR(s))
    {
    case SOCK_ESTABLISHED:
        // Interrupt clear
        if(getSn_IR(s) & Sn_IR_CON)
        {
            setSn_IR(s, Sn_IR_CON);
        }

        // HTTP Process states
        switch(HTTPSock_Status[seqnum].sock_status)
        {

        case STATE_HTTP_IDLE :
            if ((len = getSn_RX_RSR(s)) > 0)
            {
                if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;

                // ## 20150828, Eric / Bongjun Hur added
                if ((len = recv(s, (uint8_t *)http_request, len)) < 0) break;	// Exception handler

                ////////////////////////////////////////////////////////////////////////////////
                // Todo; User defined custom command handler (userHandler.c)
                ret = custom_command_handler((uint8_t *)http_request);
                ////////////////////////////////////////////////////////////////////////////////

                if(ret > 0) // Custom command handler
                {
                    // Todo: Users can change this parts for custom function added
                    //if(ret == COMMAND_SUCCESS)		send(s, (uint8_t *)"CMDOK", 5);
                    //else if(ret == COMMAND_ERROR)	send(s, (uint8_t *)"CMDERROR", 8);

                    HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
                }
                else // HTTP process handler
                {
                    *(((uint8_t *)http_request) + len) = '\0';	// End of string (EOS) marker
                    parse_http_request(parsed_http_request, (uint8_t *)http_request);
#ifdef _HTTPSERVER_DEBUG_
                    getSn_DIPR(s, destip);
                    destport = getSn_DPORT(s);
                    printf("\r\n");
                    printf("> HTTPSocket[%d] : HTTP Request received ", s);
                    printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif

#ifdef _HTTPSERVER_DEBUG_
                    printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", s);
#endif
                    // HTTP 'response' handler; includes send_http_response_header / body function
                    http_process_handler(s, parsed_http_request);

                    /*
                    							// ## 20150828 Eric removed
                    							gettime = get_httpServer_timecount();
                    							// Check the TX socket buffer for End of HTTP response sends
                    							while(getSn_TX_FSR(s) != (getSn_TXBUF_SIZE(s)*1024))
                    							{
                    								if((get_httpServer_timecount() - gettime) > 3)
                    								{
                    #ifdef _HTTPSERVER_DEBUG_
                    									printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE: TX Buffer clear timeout\r\n", s);
                    #endif
                    									break;
                    								}
                    							}
                    */

                    if(HTTPSock_Status[seqnum].file_len > 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_INPROC;
                    else HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
                }
            }
            break;


        case STATE_HTTP_RES_INPROC :
            /* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", s);
#endif
            // Repeatedly send remaining data to client
            send_http_response_body(s, 0, http_response, 0, 0);

            if(HTTPSock_Status[seqnum].file_len == 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
            break;

        case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", s);
#endif
            // Socket file info structure re-initialize
            HTTPSock_Status[seqnum].file_len = 0;
            HTTPSock_Status[seqnum].file_offset = 0;
            HTTPSock_Status[seqnum].file_start = 0;
            HTTPSock_Status[seqnum].sock_status = STATE_HTTP_IDLE;

//#ifdef _USE_SDCARD_
//					f_close(&fs);
//#endif
#ifdef _USE_WATCHDOG_
            HTTPServer_WDT_Reset();
#endif
            http_disconnect(s);
            break;

        default :
            break;
        }
        break;

    case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
        printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", s);	// if a peer requests to close the current connection
#endif
        //disconnect(s);
        http_disconnect(s);
        break;

    case SOCK_INIT:
        listen(s);
        break;

    case SOCK_LISTEN:
        break;

    case SOCK_SYNSENT:
    //case SOCK_SYNSENT_M:
    case SOCK_SYNRECV:
        //case SOCK_SYNRECV_M:
        break;

    case SOCK_CLOSED:
    default :
#ifdef _HTTPSERVER_DEBUG_
        printf("> HTTPSocket[%d] : CLOSED\r\n", s);
#endif
        if(socket(s, Sn_MR_TCP, HTTP_SERVER_PORT, 0x00) == s)    /* Reinitialize the socket */
        {
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : OPEN\r\n", s);
#endif
        }
        break;
    } // end of switch

#ifdef _USE_WATCHDOG_
    HTTPServer_WDT_Reset();
#endif
}
int32_t loopback_tcps_bsd(uint8_t sn, uint8_t* buf, uint16_t port)
{
   int32_t ret;
   uint16_t size = 0, sentsize=0;

#ifdef _LOOPBACK_DEBUG_
   uint8_t destip[4];
   uint16_t destport;
#endif

   switch(getSn_SR(sn))
   {
      case SOCK_ESTABLISHED :
         if(getSn_IR(sn) & Sn_IR_CON)
         {
#ifdef _LOOPBACK_DEBUG_
			getSn_DIPR(sn, destip);
			destport = getSn_DPORT(sn);

			printf("%d:Connected - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
			setSn_IR(sn,Sn_IR_CON);
         }
		 if((size = getSn_RX_RSR(sn)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
         {
			if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
			ret = recv(sn, buf, size, 0);

			if(ret <= 0) return ret;      // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
			sentsize = 0;

			while(size != sentsize)
			{
				ret = send(sn, buf+sentsize, size-sentsize, 0);
				if(ret < 0)
				{
					close(sn);
					return ret;
				}
				sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
			}
         }
         break;
      case SOCK_CLOSE_WAIT :
#ifdef _LOOPBACK_DEBUG_
         printf("%d:CloseWait\r\n",sn);
#endif
         if((ret = wiznet_disconnect(sn)) != SOCK_OK) return ret;
#ifdef _LOOPBACK_DEBUG_
         printf("%d:Socket Closed\r\n", sn);
#endif
         break;
      case SOCK_INIT :
#ifdef _LOOPBACK_DEBUG_
    	 printf("%d:Listen, TCP server loopback, port [%d]\r\n", sn, port);
#endif
         if( (ret = listen(sn, BACKLOG)) != SOCK_OK) return ret;
         break;
      case SOCK_CLOSED:
#ifdef _LOOPBACK_DEBUG_
         printf("%d:TCP server loopback start\r\n",sn);
#endif
         if((ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) != sn) return ret;
#ifdef _LOOPBACK_DEBUG_
         printf("%d:Socket opened\r\n",sn);
#endif
         break;
      default:
         break;
   }
   return 1;
}
/* HTTP Server Run */
void httpServer_run(uint16_t server_port)
{
	int8_t sock; 			// HW socket number
	uint8_t sock_status;	// HW socket status
	int8_t seqnum; 			// Sequence number
	int16_t len;
	
#ifdef _HTTPSERVER_DEBUG_
	uint8_t destip[4] = {0, };	// Destination IP address
	uint16_t destport = 0;		// Destination Port number
#endif
	
	sock = getAvailableHTTPSocketNum(); // Get the H/W socket number
	if(sock < 0) return; // HW socket allocation failed
	
	seqnum = getHTTPSequenceNum(sock);
	
	http_request = (st_http_request *)httpserver.recvbuf;		// HTTP Request Structure
	parsed_http_request = (st_http_request *)http_req;
	//parsed_http_request = (st_http_request *)httpserver.sendbuf; // old
	
	/* Web Service Start */
	sock_status = getSn_SR(sock);
	switch(sock_status)
	{
		case SOCK_ESTABLISHED:
			// Interrupt clear
			if(getSn_IR(sock) & Sn_IR_CON)
			{
				setSn_IR(sock, Sn_IR_CON);
			}

			// HTTP Process states
			switch(HTTPSock[seqnum].status)
			{
				case STATE_HTTP_IDLE :
					if ((len = getSn_RX_RSR(sock)) > 0)
					{
						if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;
						if ((len = recv(sock, (uint8_t *)http_request, len)) < 0) break;	// Exception handler
						
						*(((uint8_t *)http_request) + len) = '\0';	// End of string (EOS) marker
						
						parse_http_request(parsed_http_request, (uint8_t *)http_request);

#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTP Request START ==========\r\n");
						printf("%s", (uint8_t *)http_request);
						printf("> HTTP Request END ============\r\n");
#endif
						
#ifdef _HTTPSERVER_DEBUG_
						getSn_DIPR(sock, destip);
						destport = getSn_DPORT(sock);
						printf("\r\n");
						printf("> HTTPSocket[%d] : HTTP Request received ", sock);
						printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif

#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", sock);
#endif
						// HTTP 'response' handler; includes send_http_response_header / body function
						http_process_handler(sock, parsed_http_request);

						if(HTTPSock[seqnum].file_len > 0) HTTPSock[seqnum].status = STATE_HTTP_RES_INPROC;
						else HTTPSock[seqnum].status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
						
					}
					break;


				case STATE_HTTP_RES_INPROC :
					/* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", sock);
#endif
					// Repeatedly send remaining data to client
					send_http_response_body(sock, http_response, 0);

					if(HTTPSock[seqnum].file_len == 0) HTTPSock[seqnum].status = STATE_HTTP_RES_DONE;
					break;

				case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", sock);
#endif
					// Socket file info structure re-initialize
					HTTPSock[seqnum].file_len = 0;
					HTTPSock[seqnum].file_offset = 0;
					HTTPSock[seqnum].file_start = 0;
					HTTPSock[seqnum].status = STATE_HTTP_IDLE;
					
#ifdef _USE_WATCHDOG_
					HTTPServer_WDT_Reset();
#endif
					http_disconnect(sock);
					break;

				default :
					break;
			}
			break;

		case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
			printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", sock);	// if a peer requests to close the current connection
#endif
			// Socket file info structure re-initialize: HTTP connection 'close'
			HTTPSock[seqnum].file_len = 0;
			HTTPSock[seqnum].file_offset = 0;
			HTTPSock[seqnum].file_start = 0;
			HTTPSock[seqnum].status = STATE_HTTP_IDLE;
			
			http_disconnect(sock);
			break;

		case SOCK_INIT:
			listen(sock);
			break;

		case SOCK_LISTEN:
			break;

		case SOCK_SYNSENT:
		//case SOCK_SYNSENT_M:
		case SOCK_SYNRECV:
		//case SOCK_SYNRECV_M:
			break;

		case SOCK_CLOSED:
#ifdef _HTTPSERVER_DEBUG_
			//printf("> HTTPSocket[%d] : CLOSED\r\n", sock);
#endif
			if(server_port == 0) server_port = HTTP_SERVER_PORT;
			if(socket(sock, Sn_MR_TCP, server_port, 0x00) == sock) // Init / Reinitialize the socket
			{
#ifdef _HTTPSERVER_DEBUG_
				printf("> HTTPSocket[%d] : SERVER OPEN, Port: %d\r\n", sock, server_port);
#endif
				;
			}
			break;

		default :
			break;
	} // end of switch

#ifdef _USE_WATCHDOG_
	HTTPServer_WDT_Reset();
#endif
}