Wiznet makers

ronpang

Published December 04, 2023 ©

125 UCC

10 WCC

32 VAR

0 Contests

1 Followers

0 Following

Original Link

16. W5100S/W5500+RP2040 Raspberry Pi Pico<HTTP Client uploads data to OneNET>

16. W5100S/W5500+RP2040 Raspberry Pi Pico<HTTP Client uploads data to OneNET>

COMPONENTS Hardware components

WIZnet - W5100S-EVB-Pico

x 1


WIZnet - W5500-EVB-Pico

x 1


PROJECT DESCRIPTION

1 Introduction

With the popularity of mobile Internet, HTTP Client will also pay more attention to the support and optimization of mobile devices. For example, there are many HTTP Client libraries that can support asynchronous requests and responses, as well as optimize the efficiency of network connections and data transmission on mobile devices. In the future, with the popularization of higher-speed network technologies such as 5G, HTTP client will also pay more attention to the optimization of high speed, low latency and high performance.

 W5100S/W5500 is an embedded Ethernet controller integrating a full hardware TCP/IP protocol stack. It is also an industrial-grade Ethernet control chip. This tutorial will introduce the basic principles, usage steps, application examples and precautions of W5100S/W5500 Ethernet DHCP application to help readers better master this technology.

2 Protocol introduction

2.1 What is HTTP?

Hypertext Transfer Protocol HTTP is a communication protocol that works using the TCP protocol and the default port number is 80. It allows the transfer of Hypertext Markup Language (HTML) documents from a web server to a web browser. HTMl is a markup language for creating documents that contain relevant links. You can click a link to access other documents, images, or multimedia objects and obtain additional information about the linked item.

2.2 Advantages of HTTP Client

HTTP Client has the following characteristics:

Supports synchronous and asynchronous requests: HTTP Client can send synchronous and asynchronous HTTP requests. Synchronous requests block the current thread until a response is received or a timeout occurs. Asynchronous requests do not block the thread, and the response can be processed through a callback function or Future object.

Connection management: HTTP Client can automatically manage the life cycle of HTTP connections, including connection establishment, reuse and release. It supports connection pooling, which can reuse established connections and reduce the cost of establishing and closing connections.

Request and response interceptors: HTTP Client provides an interceptor mechanism that can perform customized operations in the process of sending requests and processing responses. Interceptors can be used to add authentication information, modify request headers, process responses, etc.

Support HTTPS protocol: HTTP Client supports HTTPS protocol and can perform secure HTTP communication.

Plug-in custom authentication scheme and cookie policy: HTTP Client can extend its functions through plug-in custom authentication scheme and cookie policy.

Portable and reliable socket factory: HTTP Client uses a portable and reliable socket factory, making it easier to use third-party solutions.

Ability to set connection timeout: HTTP Client can set the ability to set connection timeout to control the timeout period of the connection.

2.3 How HTTP Client works

The process steps of HTTP Client are as follows:

Establishing a connection: First, the HTTP client needs to establish a TCP connection with the server. The client will send a SYN message to the server requesting to establish a connection. After receiving the SYN message, the server will send a SYN-ACK message to the client to confirm that the connection is established.

Send request: Once the connection is established, the HTTP client will send an HTTP request message in the form of ASCII code. The request message includes request line, request header and request body.

Request line: includes the HTTP method (such as GET, POST, etc.), the requested URI (that is, the URL of the web page) and the HTTP protocol version.

Request header: Contains some additional information about the request, such as Host (specifies the domain name or IP address of the server), User-Agent (specifies the user agent information of the client, used to identify the client type), Accept (specifies the client's ability to type of content received), etc.

Request body: Contains the specific content of the request, such as the submitted form data or the content of the file to be uploaded.

Receive response: After receiving the client's request, the server will process it and return an HTTP response message. The response message also includes response lines, response headers and response bodies.

Response line: Contains the HTTP protocol version, status code (indicating the processing result of the request), and reason phrase (a simple text description of the status code).

Response header: Contains some additional information about the response, such as Server (specifies the name and version of the server), Content-Type (specifies the content type of the response), etc.

Response body: Contains the specific content returned by the server, such as the HTML code of the web page or the content of the downloaded file, etc.

Close the connection: The client and server will close the TCP connection after completing the data transmission. Usually, the client will send a FIN message to indicate that it wants to close the connection. After receiving the FIN message, the server will send an ACK message to the client to confirm that the connection is closed. Subsequently, the server will also send a FIN message indicating that it also wants to close the connection. After receiving the ACK message, the client will also send a FIN message to complete the connection closure.

2.4 HTTP Client application scenarios

HTTP Client has a wide range of application scenarios. The following are some common application scenarios:

Mobile terminal development: Mobile terminal devices usually use the HTTP protocol for network communication. HTTP Client can be used to send HTTP requests and process responses to implement various mobile terminal functions.

REST API call: In a microservice architecture, communication between services is usually carried out using REST API. HTTP Client can be used to send HTTP requests and receive responses to achieve communication and data interaction between services.

Crawler project: HTTP Client can be used to send HTTP requests and receive responses to obtain data from the website. The crawler project can use HTTP Client to simulate browser behavior, access the website and extract the required information.

Desktop applications: HTTP Client can be used for network communication with desktop applications. For example, desktop applications can send HTTP requests through HTTP Client to obtain weather information, news information and other data.

Web applications: Web applications can use HTTP Client to send HTTP requests and process responses to implement various functions, such as user login, form submission, data acquisition, etc.

3 WIZnet Ethernet chip

WIZnet mainstream hardware protocol stack Ethernet chip parameter comparison

ModelEmbedded CoreHost I/FTX/RX BufferHW SocketNetwork Performance
W5100STCP/IPv4, MAC & PHY8bit BUS, SPI16KB4Max.25Mbps
W6100TCP/IPv4/IPv6, MAC & PHY8bit BUS, Fast SPI32KB8Max.25Mbps
W5500TCP/IPv4, MAC & PHYFast SPI32KB8Max 15Mbps

W5100S/W6100 supports 8-bit data bus interface, and the network transmission speed will be better than W5500.

W6100 supports IPv6 and is compatible with W5100S hardware. If users who already use W5100S need to support IPv6, they can be Pin to Pin compatible.

W5500 has more Sockets and send and receive buffers than W5100S.

4 HTTP Client network setting example overview and usage

4.1 Flowchart

The running block diagram of the program is as follows:

4.2 Core preparation work

Software

Visual Studio Code

WIZnet UartTool

One_NET platform

Hardware

W5100SIO module + RP2040 Raspberry Pi Pico development board or WIZnet W5100S-EVB-Pico development board

Micro USB interface data cable

TTL to USB

cable

4.3 Connection method

Connect the USB port of the PC through the data cable (mainly used for burning programs, but can also be used as a virtual serial port)

Convert TTL serial port to USB and connect the default pin of UART0:

RP2040 GPIO0 (UART0 TX) <----> USB_TTL_RX

RP2040 GPIO1 (UART0 RX) <----> USB_TTL_TX

When wiring using module connection RP2040

RP2040 GPIO16 <----> W5100S MISO

RP2040 GPIO17 <----> W5100S CS

RP2040 GPIO18 <----> W5100S SCK

RP2040 GPIO19 <----> W5100S MOSI

RP2040 GPIO20 <----> W5100S RST

Connect the PC and device to the router LAN port through network cables

4.4 Main code overview

We are using the official ioLibrary_Driver library of WIZnet. The library supports rich protocols and is easy to operate. The chip integrates the TCP/IP protocol stack on the hardware. The library also encapsulates the protocols above the TCP/IP layer. We only need to simply call the corresponding function to complete the application of the protocol. .

Step 1: Add the corresponding .h file to the HTTP_client.c file.

Step 2: Define the macros required for DHCP configuration.

Step 3: Configure network information, turn on DHCP mode, define and initialize the HTTP server IP and port number.

Step 4: Write a timer callback processing function for the DHCP 1s tick timer processing function.

Step 5: The main function first defines a timer structure parameter to trigger the timer callback function, initializes the serial port and SPI, then writes the network configuration parameters of W5100S, initializes DHCP and starts DHCP to obtain the IP. Print the obtained IP. When the number of acquisitions exceeds the maximum number of acquisitions, a static IP will be used. The main loop directly calls the running function in the HTTP header file. The parameters that need to be passed in are the socket number cache buff, server ip and port to connect to the server. and perform data transmission.

#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "bsp_spi.h"
#include "dhcp.h"       // Use dhcp
#include "socket.h"     // Use socket
#include "HTTPclient.h" // Use HTTP client

#define SOCKET_ID 0                      // Socket number
#define ETHERNET_BUF_MAX_SIZE (1024 * 2) // Send and receive cache size
#define DHCP_RETRY_COUNT 5               // DHCP retry times

/**
* @brief   Timer callback processing function, used for dhcp timing processing
* @param   repeating :Timer structure
* @return bool
*/
bool repeating_timer_callback(struct repeating_timer *t);

/**
* @brief   Initialization of chip network information
* @param   conf_info :Static configuration information
* @return none
*/
void network_init(wiz_NetInfo *conf_info);

/* Network information to be configured. */
wiz_NetInfo net_info = {
  .mac = {0x00, 0x08, 0xdc, 0x1e, 0xed, 0x2e}, // Configured MAC address
  .ip = {192, 168, 1, 10},                     // Configured IP address
  .sn = {255, 255, 255, 0},                    // Configured subnet mask
  .gw = {192, 168, 1, 1},                      // Configured gateway
  .dns = {8, 8, 8, 8},                         // Configured domain address
  .dhcp = NETINFO_DHCP};                       // Configured dhcp model,NETINFO_DHCP:use dhcp; NETINFO_STATIC: use static ip.

static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
   0,
}; // Send and receive cachestatic

static uint8_t destip[4] = {183, 230, 40, 34}; // OneNET HTTP access IP
static uint16_t destport = 80;                 // OneNET HTTP access port
static uint8_t breakout_flag = 0;              // Define the DHCP acquisition flag

int main()
{
   struct repeating_timer timer; // Define the timer structure
   wiz_NetInfo get_info;         // Stores the read configuration information

   /* MCU init */
   stdio_init_all();     // Initialize the main control peripheral
   wizchip_initialize(); // Initialize the chip interface

   /*dhcp init*/
   DHCP_init(SOCKET_ID, ethernet_buf);                                   // DHCP initialization
   add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer); // Add DHCP 1s Tick Timer handler

   printf("wiznet chip HTTP client example.\r\n");
   network_init(&net_info);              // Configuring Network Information
   print_network_information(&get_info); // Read back the configuration information and print it

   while (true)
  {
       do_HTTP_client(SOCKET_ID, ethernet_buf, destip, destport); // run HTTP client connect OneNET and upload data stream.
       sleep_ms(2000);                                            // Add latency to make it easier to see data flow changes on the platform
  }
}

void network_init(wiz_NetInfo *conf_info)
{
   int count = 0;
   uint8_t dhcp_retry = 0;

   if (conf_info->dhcp == NETINFO_DHCP)
  {
       while (true)
      {
           switch (DHCP_run()) // Do the DHCP client
          {
           case DHCP_IP_LEASED: // DHCP resolves the domain name successfully
          {
               if (breakout_flag == 0)
              {
                   printf("DHCP success\r\n");
                   getIPfromDHCP((*conf_info).ip);
                   getGWfromDHCP((*conf_info).gw);
                   getSNfromDHCP((*conf_info).sn);
                   getDNSfromDHCP((*conf_info).dns);
                   wizchip_setnetinfo(conf_info); // Configuring Network Information
                   close(SOCKET_ID);              // After dhcp close the socket, avoid errors in later use
                   breakout_flag = 1;
              }
               break;
          }
           case DHCP_FAILED:
          {
               printf(" DHCP failed \r\n");
               count++;
               if (count <= DHCP_RETRY_COUNT) // If the number of times is less than or equal to the maximum number of times, try again
              {
                   printf("DHCP timeout occurred and retry %d \r\n", count);
              }
               else if (count > DHCP_RETRY_COUNT) // If the number of times is greater than DHCP fails
              {
                   breakout_flag = 1; // if DHCP fail, use the static
                   DHCP_stop();       // Stop processing DHCP protocol
                   conf_info->dhcp = NETINFO_STATIC;
                   wizchip_setnetinfo(conf_info); // Configuring Network Information
                   break;
              }
               break;
          }
          }
           if (breakout_flag)
          {
               printf("config succ\r\n");
               break;
          }
      }
  }
   else
  {
       wizchip_setnetinfo(conf_info); // Configuring Network Information
  }
}

bool repeating_timer_callback(struct repeating_timer *t)
{
   DHCP_time_handler(); // DHCP 1s Tick Timer handler
   return true;
}

 

4.5 Results demonstration

1. Open WIZ UartTool and fill in the parameters: select the com port corresponding to the serial port, baud rate 115200, 8 data bits, 1 stop bit, no check bit, no flow control. After filling in the parameters, click open.

2. Open One NET on the web page and open the created HTTP server. Press the reset button, we can see that after obtaining the IP, connect to the HTTP server, and the HTTP server can receive the data written in the code and upload it to the server.

5 Precautions

The default port number of the HTTP server is 80, so do not use other ports casually when using it.

If we want to use WIZnet's W5500 to implement the example in this chapter, we only need to modify two places:

(1) Find the wizchip_conf.h header file under library/ioLibrary_Driver/Ethernet/ and modify the WIZCHIP macro definition to W5500.

(2) Find the CMakeLists.txt file under library and set COMPILE_SEL to ON. OFF is W5100S and ON is W5500.

Documents
  • Codes for this article

  • WIZnet Official website

  • WIZnet Official IOlibrary

  • YouTube Video

Comments Write