Wiznet makers

ronpang

Published July 24, 2025 © Apache License 2.0 (Apache-2.0)

130 UCC

51 WCC

32 VAR

0 Contests

1 Followers

0 Following

Hardwired TCP/IP Chapter 3 :W55MH32 TCP Client Example

Hardwired TCP/IP Chapter 3 :W55MH32 TCP Client Example

COMPONENTS
PROJECT DESCRIPTION

Hardwired TCP/IP Chapter 3 :W55MH32 TCP Client Example

In this article, we will provide a detailed explanation on how to implement TCP communication on the W55MH32 chip. By using the TOE engine of W55MH32, we only need to perform simple socket programming and register reading and writing, and we can easily implement TCP protocol applications. Next, through practical examples, we will explain to you how to use the TOE engine to conduct data loopback testing in the TCP Client mode.

Other network protocols used in this example, such as DHCP, please refer to the relevant sections. Regarding the initialization process of W55MH32, please refer to the Network Install section. We will not elaborate on this here.

1 Introduction to TCP Protocol

TCP (Transmission Control Protocol) is a connection-oriented and reliable transport layer protocol, which is used to reliably transmit data over the network. TCP is one of the core protocols in the Internet protocol family and is usually used together with the IP protocol (Internet Protocol) to form socket communication.

2 Characteristics of the TCP Protocol

  • Connection-oriented: Before transmitting data, TCP needs to establish a connection to ensure that the sender and the receiver can communicate with each other. The connection is established through the Three-Way Handshake process, ensuring reliable communication between both parties.
  • Reliability: TCP provides reliable data transmission, ensuring that the data is complete and arrives at the receiving end in order. If data is lost or corrupted, TCP will automatically retransmit the lost data packets.
  • Flow Control: TCP uses a flow control mechanism to regulate the speed of data transmission, preventing the receiving end from being overwhelmed and resulting in data loss. The commonly used flow control method is the Sliding Window.
  • Congestion Control: TCP can dynamically adjust the transmission rate to avoid network congestion. Algorithms such as Slow Start, Congestion Avoidance, and Fast Retransmission are adopted.
  • Full-duplex communication: After the TCP connection is established, data can be transmitted in both directions simultaneously, supporting two-way communication.
  • Ordered Data Transmission: TCP numbers the data packets to ensure that the data is transmitted in order, even if there is network delay, the receiving end can receive the data in order.
  • Byte Stream Service: The data transmitted by TCP is a byte stream, it does not care about the boundaries of the application layer data, and the application layer needs to parse the data boundaries itself.

3 The Differences Between TCP and UDP

  • TCP is a reliable, connection-oriented protocol, suitable for applications that require data integrity and sequence guarantee, such as web browsing and file transfer.
  • UDP (User Datagram Protocol) is an unconnected, unreliable protocol, suitable for applications that have high requirements for timeliness and can tolerate packet loss, such as video streaming and online games.

4 TCP application scenarios

Next, let's explore what operations and applications can be accomplished using the TCP protocol on the W55MH32?

  • Remote monitoring and data collection: Embedded devices are typically used to collect sensor data and upload it to a remote server via Ethernet. The TCP protocol ensures the reliability and integrity of data transmission.
  • Remote device control: Many embedded systems require receiving control instructions over the network (such as PLC control in industrial automation), and the TCP protocol provides a reliable communication channel.
  • Internet of Things (IoT): Many IoT devices use the TCP protocol to communicate with cloud servers or other devices, transmitting data, executing commands, and so on.
  • Embedded Web server: Some embedded devices have built-in Web servers (such as routers, gateways, sensor devices, etc.), and through the TCP protocol, they provide web interfaces for users to configure and monitor.

5 The process of conducting data interaction using TCP

TCP connection establishment (three-way handshake)

Before starting to transmit data, TCP will establish a connection through three handshakes:

1. The first handshake: The client sends a data packet with the SYN flag to the server, indicating a request to establish a connection.

2. The second handshake: After receiving the SYN data packet, the server replies with a data packet containing the SYN and ACK flags, indicating its consent to establish the connection.

3. The third handshake: After receiving the SYN+ACK from the server, the client sends a data packet with the ACK flag, completing the connection establishment.

Data interaction

TCP connection is disconnected (four-way handshake)

When communication ends, TCP needs to close the connection through four handshakes:

1. The first handshake: The client sends a FIN data packet, indicating that data transmission is complete and it is ready to close the connection.

2. The second handshake: After receiving the FIN data packet, the server replies with an ACK data packet, indicating its consent to close the connection.

3. The third handshake: The server sends a FIN data packet, indicating that data transmission is complete and it is ready to close the connection.

4. The fourth handshake: After receiving the server's FIN data packet, the client sends an ACK data packet, and the connection is officially closed.

TCP Three-way Handshake Diagram

TCP Four-way Handshake Diagram

6 The ACK mechanism, retransmission mechanism and Keepalive mechanism of TCP

The ACK mechanism of TCP

ACK is the mechanism used by TCP to confirm that a data packet has been successfully received. In TCP communication, each data packet contains a sequence number, and the receiving party uses ACK to inform the sending party of the sequence of bytes that have been successfully received.

1. ACK field: The ACK field is included in the TCP header and indicates the sequence number of the next byte that the receiver expects to receive.

2. Cumulative Acknowledgment: TCP uses the cumulative acknowledgment method, meaning that the receiver has received all data up to a certain sequence number consecutively.

3. Timeout Retransmission: If the sender does not receive an ACK within the timeout period, it will retransmit the data packet.

The retransmission mechanism of TCP

The retransmission mechanism of TCP ensures the reliable transmission of data. The following are the common retransmission mechanisms.

Timeout retransmission:

  • The sender sets a timer. If the sent data packet does not receive an ACK within the specified time, it triggers a retransmission.
  • The timeout period is dynamically adjusted and is estimated based on the round-trip time (RTT) of TCP.

Fast retransmission:

  • When the receiving party detects a lost data packet, it sends a duplicate ACK (referred to as a redundant ACK) to alert the sender that a certain data packet has not arrived.
  • If the sender receives three consecutive duplicate ACKs, it will immediately retransmit the corresponding data packet without waiting for a timeout.

Selective Retransmission (Selective Repeat, SACK):

  • Based on the cumulative confirmation, TCP can also inform the sender through the SACK option which specific blocks have been received and which ones have not. 
  • This can reduce unnecessary retransmissions and improve efficiency.

TCP Keepalive mechanism

TCP Keepalive is an optional mechanism of the TCP protocol, used to detect whether a long-idle connection is still valid. Its main function is:

1. Maintain connection status: Check if the remote host is still online to avoid long-term occupation of resources.

2. Release dead connections: If the connection has failed (such as network interruption or the remote host crashing), Keepalive can promptly release resources.

3. Prevent intermediate devices from closing the connection due to timeout: Some NATs, routers, or firewalls may automatically close the connection when it remains inactive for a long time. Keepalive can prevent this situation.

Usage: In the TOE engine of W55MH32, the Keepalive time needs to be set in the Sn_KPALVTR register, and then a data packet should be sent after successfully connecting to the server to activate Keepalive.

7 The implementation process

Next, let's take a look at how to implement the TCP client mode on the W55MH32 and connect to the server for loopback testing. Note: The test instances require that the PC and W55MH32 be on the same network segment.

Step 1: Enable TCP Keepalive function

In W55MH32, the time unit for KeepAlive is 5 seconds. Here, we set it to 6 units, which means W55MH32 will send a KeepAlive message to the server every 30 seconds for keep-alive purposes:

1.     /* Enable keepalive,Parameter 2 is the keep alive time, with a unit of 5 seconds */
2.     setSn_KPALVTR(SOCKET_ID, 6); // 30s keepalive

Step 2: Run the TCP Client loopback test program within the main loop

1.     while (1)
2.     {
3.         loopback_tcpc(SOCKET_ID, ethernet_buf, dest_ip, dest_port);
4.     } 

The four parameters of the loopback_tcpc() function are: SOCKET ID, TCP protocol cache array, target server IP address, and target server port number.

Note: When we want to increase the throughput, we can set Sn_TXBUF_SIZE (the register for socket n's sending cache size) and Sn_RXBUF_SIZE (the register for socket n's receiving cache size) to reallocate the socket cache size, and at the same time increase the size of the TCP protocol cache array.

The example target server IP address and port number are: 192.168.1.20:8080.

The content of the loopback_tcpc() function is as follows:

  1. /**
  2.  * @brief  tcp client loopback test
  3.  * @param  sn:         socket number
  4.  * @param  buf:        Data sending and receiving cache
  5.  * @param  destip:     Destination IP address
  6.  * @param  destport:   Destination port
  7.  * @return value for SOCK_ERRORs,return 1:no error
  8.  */
  9. int32_t loopback_tcpc(uint8_t sn, uint8_t *buf, uint8_t *destip, uint16_t destport)
 10. {
 11.     int32_t  ret; // return value for SOCK_ERRORs
 12.     uint16_t size = 0, sentsize = 0;
 13.  
 14.     // Destination (TCP Server) IP info (will be connected)
 15.     // >> loopback_tcpc() function parameter
 16.     // >> Ex)
 17.     uint8_t  dip[4] = {192, 168, 0, 214};
 18.     uint16_t dport  = 5000;
 19.     getSn_DIPR(sn, dip);
 20.     dport = getSn_DPORT(sn);
 21.     // Port number for TCP client (will be increased)
 22.     static uint16_t any_port = 50000;
 23.  
 24.     // Socket Status Transitions
 25.     // Check the W5500 Socket n status register (Sn_SR, The 'Sn_SR' controlled by Sn_CR command or Packet send/recv status)
 26.     switch (getSn_SR(sn))
 27.     {
 28.     case SOCK_ESTABLISHED:
 29.         if (getSn_IR(sn) & Sn_IR_CON) // Socket n interrupt register mask; TCP CON interrupt = connection with peer is successful
 30.         {
 31. #if KEEPALIVE_ENABLE == 1
 32.             // We need to send a packet of data to activate keepalive
 33.             ret = send(sn, (uint8_t *)"", 1); // Data send process
 34.             if (ret < 0)                      // Send Error occurred (sent data length < 0)
 35.             {
 36.                 close(sn);                    // socket close
 37.                 return ret;
 38.             }
 39. #endif
 40. #ifdef _LOOPBACK_DEBUG_
 41.             printf("%d:Connected to - %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport);
 42. #endif
 43.             setSn_IR(sn, Sn_IR_CON); // this interrupt should be write the bit cleared to '1'
 44.         }
 45.  
 46.         //////////////////////////////////////////////////////////////////////////////////////////////
 47.         // Data Transaction Parts; Handle the [data receive and send] process
 48.         //////////////////////////////////////////////////////////////////////////////////////////////
 49.         if ((size = getSn_RX_RSR(sn)) > 0) // Sn_RX_RSR: Socket n Received Size Register, Receiving data length
 50.         {
 51.             if (size > DATA_BUF_SIZE)
 52.                 size = DATA_BUF_SIZE;        // DATA_BUF_SIZE means user defined buffer size (array)
 53.             ret       = recv(sn, buf, size); // Data Receive process (H/W Rx socket buffer -> User's buffer)
 54.             buf[size] = 0x00;
 55.             printf("rece from %d.%d.%d.%d:%d data:%s\r\n", dip[0], dip[1], dip[2], dip[3], dport, buf);
 56.             if (ret <= 0)
 57.                 return ret; // If the received data length <= 0, receive failed and process end
 58.             size     = (uint16_t)ret;
 59.             sentsize = 0;
 60.  
 61.             // Data sentsize control
 62.             while (size != sentsize)
 63.             {
 64.                 ret = send(sn, buf + sentsize, size - sentsize); // Data send process (User's buffer -> Destination through H/W Tx socket buffer)
 65.                 if (ret < 0)                                     // Send Error occurred (sent data length < 0)
 66.                 {
 67.                     close(sn);                                   // socket close
 68.                     return ret;
 69.                 }
 70.                 sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
 71.             }
 72.         }
 73.         //////////////////////////////////////////////////////////////////////////////////////////////
 74.         break;
 75.  
 76.     case SOCK_CLOSE_WAIT:
 77. #ifdef _LOOPBACK_DEBUG_
 78.         printf("%d:CloseWait\r\n", sn);
 79. #endif
 80.         if ((ret = disconnect(sn)) != SOCK_OK)
 81.             return ret;
 82. #ifdef _LOOPBACK_DEBUG_
 83.         printf("%d:Socket Closed\r\n", sn);
 84. #endif
 85.         break;
 86.  
 87.     case SOCK_INIT:
 88. #ifdef _LOOPBACK_DEBUG_
 89.         printf("%d:Try to connect to the %d.%d.%d.%d : %d\r\n", sn, destip[0], destip[1], destip[2], destip[3], destport);
 90. #endif
 91.         if ((ret = connect(sn, destip, destport)) != SOCK_OK)
 92.             return ret; //         Try to TCP connect to the TCP server (destination)
 93.         break;
 94.  
 95.     case SOCK_CLOSED:
 96.         close(sn);
 97.         if ((ret = socket(sn, Sn_MR_TCP, any_port++, 0x00)) != sn)
 98.         {
 99.             if (any_port == 0xffff)
100.                 any_port = 50000;
101.             return ret; // TCP socket open with 'any_port' port number
102.         }
103. #ifdef _LOOPBACK_DEBUG_
104.         printf("%d:TCP client loopback start\r\n", sn);
105.         printf("%d:Socket opened\r\n", sn);
106. #endif
107.         break;
108.     default:
109.         break;
110.     }
111.     return 1;
112. }

In this program, the TCP Client state machine will be executed. Corresponding operations will be performed based on the different states of the SOCKET. The state changes of the SOCKET are as shown in the following figure:

 

  • SOCK_CLOSED: The current SOCKET is not open. After configuring the connection to the server and the port number, open the SOCKET. Once the SOCKET is opened successfully, it will enter the SOCK_INIT state.

Note: When the W55MH32 abnormally disconnects from the server, the server does not know that we have disconnected. Therefore, when using the previous connection port to connect, the server will reject the connection. So, here, after a connection failure, the connection port will be automatically incremented by 1. If in some specific scenarios, the server only allows the client to connect using a fixed port, then this operation of automatically incrementing the connection port cannot be used.

  • SOCK_INIT: The SOCKET performs the operation of connecting to the server. If the connection is successful, the SOCKET state changes to SOCK_ESTABLISHED; if the connection fails, the SOCKET state changes to the closed state.
  • SOCK_ESTABLISHED: First, clear the interruption of the successful connection and send 1 packet of data to activate KeepAlive. Then, read the value of the Sn_RX_RSR (idle receive buffer register) register. When receiving server data, the value of the Sn_RX_RSR register will be greater than 0. At this time, we will print the received data and send the data in a loop.
  • SOCK_CLOSE_WAIT: When the server actively disconnects the connection, the SOCKET state changes to the SOCK_CLOSE_WAIT state. This is a semi-closed state, allowing for the final data transmission before closing. When using the disconnect() function to completely disconnect the connection, the SOCKET state will change to the SOCK_CLOSED state.
  • SOCK_CLOSED: The current SOCKET is not open. After configuring the connection to the server and the port number, open the SOCKET. Once the SOCKET is opened successfully, it will enter the SOCK_INIT state.

Note: When the W55MH32 abnormally disconnects from the server, the server is not aware that we have disconnected. Therefore, when using the previous connection port to connect again, the server will reject the connection. So, here, after a connection failure, the connection port will be automatically incremented by 1. In some specific scenarios, the server only allows the client to connect using a fixed port. In this case, the operation of automatically incrementing the connection port cannot be used.

  • SOCK_INIT: The SOCKET performs the operation of connecting to the server. If the connection is successful, the SOCKET state changes to SOCK_ESTABLISHED; if the connection fails, the SOCKET state changes to the closed state.
  • SOCK_ESTABLISHED: First, clear the interruption of the successful connection and send 1 packet of data to activate KeepAlive. Then, read the value of the Sn_RX_RSR (idle receive buffer register) register. When receiving data from the server, the value of the Sn_RX_RSR register will be greater than 0. At this time, we will print the received data and send the data in a loop.
  • SOCK_CLOSE_WAIT: When the server actively disconnects the connection, the SOCKET state changes to the SOCK_CLOSE_WAIT state. This is a semi-closed state, allowing for the final data transmission before closing. When using the disconnect() function to completely disconnect the connection, the SOCKET state will change to the SOCK_CLOSED state.

8 Run results

After the burning routine is executed, it first performs a PHY link detection, then acquires the network address through DHCP and prints the network address information, and finally conducts a TCP data loopback test. When the server is not turned on, it will continuously print the prompts for opening the socket and connecting to the server.

Next, we will open a network debugging tool, such as SocketTester, set it to the TCP Server mode, select the IP address of the PC and the port number for the TCP communication, then click "Listen" to establish the listening function of the TCP Server software. At this point, we can see the connection information of W55MH32. Finally, we send data to W55MH32 for a loopback test.

9 Summary

This article introduces the method of implementing TCP client mode for data loopback testing on the W55MH32 chip. It elaborates on the concepts, characteristics, differences from UDP, application scenarios, and related mechanisms of the TCP protocol. It also demonstrates the implementation process, including enabling the Keepalive function and running the test program in the main loop. After burning the routine, it conducts PHY link detection, obtains the network address, and then tests using network debugging tools.

The next article will explain how to implement TCP server mode to listen on a port for data loopback testing on this chip, and will analyze the related principles and steps. Please stay tuned!

 

 

WIZnet is a non-fabrication semiconductor company founded in 1998. Its products include the Internet processor iMCU™, which adopts TOE (TCP/IP Offloading Engine) technology and is based on a unique patented fully hardwired TCP/IP. iMCU™ is designed for embedded Internet devices in various applications.

WIZnet has over 70 distributors worldwide, with offices in Hong Kong, South Korea, and the United States, providing technical support and product marketing.

The region managed by the Hong Kong office includes: Australia, India, Turkey, and Asia (excluding South Korea and Japan).

 

Documents
Comments Write