Chapter 17 UDP Broadcast of ESP32
Pay attention to the public account of Jiayouchuang Technology
- Source address: https://github.com/HX-IoT/ESP32-Developer-Guide
- ESP32 development guide QQ group: 824870185, there is a pdf version, and the layout is neat.
Learning goals and objectives
- Master the principle and working process of UDP
- Master the programming of UDP of Espressif ESP32
- Mainly master the UDP source code process
UDP popular science (from Baidu Encyclopedia)
UDP is the abbreviation of User Datagram Protocol. The Chinese name is User Datagram Protocol. It is a connectionless transport layer protocol in the OSI (Open System Interconnection ) reference model , providing a simple and unreliable information transmission service for transaction. , IETF RFC 768 is the official specification for UDP. The protocol number of UDP in IP packets is 17.
The full name of the UDP protocol is the User Datagram Protocol. It is used to process data packets in the same network as the TCP protocol, and is a connectionless protocol. In the OSI model, the fourth layer, the transport layer , is the upper layer of the IP protocol. UDP has the disadvantage of not providing packet grouping, assembly and sorting of packets, that is to say, when a packet is sent, it is impossible to know whether it arrives safely and completely. UDP is used to support network applications that need to transfer data between computers . Many network applications in client/server mode, including network video conferencing systems, need to use the UDP protocol. The UDP protocol has been used for many years since its inception. Although its initial glory has been overshadowed by some similar protocols, UDP is still a very practical and feasible network transport layer protocol even today.
Like the well-known TCP ( Transmission Control Protocol ) protocol, the UDP protocol sits directly on top of the IP (Internet Protocol) protocol. According to the OSI ( Open Systems Interconnection ) reference model, both UDP and TCP are transport layer protocols. The main function of the UDP protocol is to compress network data traffic into the form of data packets. A typical data packet is a transmission unit of binary data. The first 8 bytes of each data packet are used to contain header information, and the remaining bytes are used to contain specific transmission data.
UDP is a connectionless transport layer protocol in the OSI reference model. It is mainly used in transmissions that do not require the order of packets to arrive. The check and sorting of the packet transmission order is completed by the application layer, providing transaction-oriented simple and unreliable information transmission services. . The UDP protocol is basically the interface between the IP protocol and the upper layer protocol. The UDP protocol is applicable to multiple applications running on the same device .
UDP provides connectionless communication, and does not guarantee the reliability of transmitting data packets. It is suitable for transmitting a small amount of data at a time. The reliability of UDP transmission is the responsibility of the application layer. Commonly used UDP port numbers are:
Application protocol | The port number |
DNS | 53 |
TFTP | 69 |
SNMP | 161 |
UDP packets have no reliability guarantee, sequence guarantee, and flow control fields, so the reliability is poor. However, because UDP protocol has fewer control options, the delay in data transmission is small, and the data transmission efficiency is high, which is suitable for applications that do not require high reliability, or applications that can guarantee reliability , such as DNS, TFTP, SNMP Wait.
UDP features and processes
The above principles are very important, but after all, we are only doing applications on top of the API. Just need to understand the features and processes . Knowing the characteristics, you can consider the feasibility when making a plan, and the process is the implementation after it is feasible.
UDP features:
- Connectionless: There is no need to establish a connection before sending data.
- Unreliable: Best-effort delivery, i.e. reliable delivery is not guaranteed.
- Support one-to-one, one-to-many, many-to-one and many-to-many interactive communication
- It occupies less resources and sends data quickly.
UDP process: ( source of this paragraph )
The general steps of the client side of UDP programming are:
- 1. Create a UDP socket socket using the socket() function.
- 2. Use the sendto() function to send information to the specified IP address.
The general steps on the server side of TCP programming are:
- To create a UDP socket socket, use the socket function.
- Set the properties of the socket, use the setsockopt() function, (optional)
- Bind the (IPv4) structure containing IP information, address information. with the bind() function
- Receive messages in a loop, use the recvfrom() function
- close socket socket
The TCP gang and the UDP gang
software design
UDP detailed process of ESP32
Introduction to UDP Client Interface of ESP32
Connection function: connect();
Close the socket function: close();
Get socket error code: getsocketopt();
Receive data function: recvfrom();
Send data function: sendto();
For more detailed interfaces, please refer to the official guide .
UDP Summary of ESP32
After initializing the wifi configuration, the program will give the status return in the callback function according to the real-time status of the WIFI, so only need to perform related operations in the callback, the STA start event triggers the UDP work, and then the data can be broadcast.
UDP new task writing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | esp_err_t create_udp_client() {undefined ESP_LOGI(TAG, "will connect gateway ssid : %s port:%d", UDP_ADRESS, UDP_PORT); // create a new socket connect_socket = socket(AF_INET, SOCK_DGRAM, 0); /*Parameters are different from TCP*/ if (connect_socket < 0) {undefined //print error message show_socket_error_reason("create client", connect_socket); //After the new creation fails, close the newly created socket and wait for the next new creation close(connect_socket); return ESP_FAIL; } //Configure connection server information client_addr.sin_family = AF_INET; client_addr.sin_port = htons(UDP_PORT); client_addr.sin_addr.s_addr = inet_addr(UDP_ADRESS);
int len = 0; //length char databuff[1024] = "Hello Server,Please ack!!"; //cache // Test udp server, return the length of successful transmission len = sendto(connect_socket, databuff, 1024, 0, (struct sockaddr *) &client_addr, sizeof(client_addr)); if (len > 0) {undefined ESP_LOGI(TAG, "Transfer data to %s:%u,ssucceed\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); } else {undefined show_socket_error_reason("recv_data", connect_socket); close(connect_socket); return ESP_FAIL; } return ESP_OK; } |
UDP receive task code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | void recv_data(void *pvParameters) {undefined int len = 0; //length char databuff[1024]; //cache while (1) {undefined //Empty the cache memset(databuff, 0x00, sizeof(databuff));
//read received data len = recvfrom(connect_socket, databuff, sizeof(databuff), 0, (struct sockaddr *) &client_addr, &socklen); if (len > 0) {undefined // print the received array ESP_LOGI(TAG, "UDP Client recvData: %s", databuff); //Receive data back sendto(connect_socket, databuff, strlen(databuff), 0, (struct sockaddr *) &client_addr, sizeof(client_addr)); } else {undefined // print error message show_socket_error_reason("UDP Client recv_data", connect_socket); break; } } close_socket();
vTaskDelete (NULL); } |
Test process and effect display
test process
Change the account password of AP and STA
Modify UDP Port
Use the mobile phone or computer to use the assistant tool to perform the UDP broadcast test
Show results
test send data
Transceiver test
Send 100 times and see how unreliable it is
UDP Summary
The bottom layer focuses on the principle, the process + interface in the application.
There is no exception handling in this source code , and you need to modify it properly when you transplant it yourself. Check the return value in the receiving task to decide whether to recreate the UDP Client, which is similar to TCP.
Source address: https://github.com/xiaolongba/wireless-tech
Click me -> more ESP32 development guide series catalog