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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #include <string.h> #include <sys/param.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "nvs_flash.h" #include "esp_netif.h" #include "protocol_examples_common.h"
#include "lwip/err.h" #include "lwip/sockets.h" #include "lwip/sys.h" #include <lwip/netdb.h>
#define WIFI_SSID "Your_AP_SSID" #define WIFI_PASS "Your_AP_Password"
#define UDP_PORT 12345
static const char *TAG = "example";
void udp_server_task(void *pvParameters) { struct sockaddr_in server_addr, client_addr; int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock < 0) { ESP_LOGE(TAG, "Unable to create socket: errno %d", errno); vTaskDelete(NULL); return; }
server_addr.sin_family = AF_INET; server_addr.sin_port = htons(UDP_PORT); server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno); vTaskDelete(NULL); return; }
ESP_LOGI(TAG, "UDP server listening");
while (1) { char rx_buffer[128]; int len = sizeof(client_addr); int rx_len = recvfrom(sock, rx_buffer, sizeof(rx_buffer) - 1, 0, (struct sockaddr *)&client_addr, &len);
if (rx_len <= 0) { ESP_LOGE(TAG, "recvfrom failed: errno %d", errno); break; } else { rx_buffer[rx_len] = '\0'; ESP_LOGI(TAG, "Received %d bytes from %s:%d", rx_len, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); ESP_LOGI(TAG, "%s", rx_buffer);
sendto(sock, rx_buffer, rx_len, 0, (struct sockaddr *)&client_addr, sizeof(client_addr)); } }
if (sock != -1) { ESP_LOGE(TAG, "Shutting down socket and restarting..."); shutdown(sock, 0); close(sock); }
vTaskDelete(NULL); }
void app_main() { nvs_flash_init();
ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_ap(); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); wifi_config_t wifi_config = { .ap = { .ssid = WIFI_SSID, .ssid_len = strlen(WIFI_SSID), .password = WIFI_PASS, .max_connection = 4, .authmode = WIFI_AUTH_WPA_WPA2_PSK }, }; ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config)); ESP_ERROR_CHECK(esp_wifi_start());
xTaskCreate(udp_server_task, "udp_server_task", 4096, NULL, 5, NULL); }
|