81 lines
2.9 KiB
C
81 lines
2.9 KiB
C
#include <stdio.h>
|
|
#include "esp_wifi.h"
|
|
#include "nvs_flash.h"
|
|
#include "esp_netif.h"
|
|
#include <string.h>
|
|
|
|
#define WIFI_SSID "ESP32-Access-Point"
|
|
#define WIFI_PASS "123456789"
|
|
#define MAX_STA_CONN 4
|
|
|
|
// Event handler to log connected clients
|
|
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
|
|
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
|
|
wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
|
|
// Print the MAC address manually
|
|
printf("Client connected: MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
|
|
event->mac[0], event->mac[1], event->mac[2],
|
|
event->mac[3], event->mac[4], event->mac[5]);
|
|
}
|
|
else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
|
|
wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
|
|
// Print the MAC address manually
|
|
printf("Client disconnected: MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
|
|
event->mac[0], event->mac[1], event->mac[2],
|
|
event->mac[3], event->mac[4], event->mac[5]);
|
|
}
|
|
}
|
|
|
|
void app_main(void) {
|
|
// Initialize NVS
|
|
esp_err_t ret = nvs_flash_init();
|
|
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
|
ESP_ERROR_CHECK(nvs_flash_erase());
|
|
ret = nvs_flash_init();
|
|
}
|
|
ESP_ERROR_CHECK(ret);
|
|
|
|
// Initialize network interface
|
|
ESP_ERROR_CHECK(esp_netif_init());
|
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
|
|
|
// Create default Wi-Fi AP network interface
|
|
esp_netif_t *netif = esp_netif_create_default_wifi_ap();
|
|
if (netif == NULL) {
|
|
// Print error message manually
|
|
printf("Failed to create Wi-Fi AP netif\n");
|
|
return;
|
|
}
|
|
|
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
|
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
|
|
|
// Register event handler
|
|
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL));
|
|
|
|
// Configure Wi-Fi as SoftAP
|
|
wifi_config_t wifi_config = {
|
|
.ap = {
|
|
.ssid = WIFI_SSID,
|
|
.ssid_len = strlen(WIFI_SSID),
|
|
.password = WIFI_PASS,
|
|
.max_connection = MAX_STA_CONN,
|
|
.authmode = WIFI_AUTH_WPA_WPA2_PSK,
|
|
},
|
|
};
|
|
|
|
if (strlen(WIFI_PASS) == 0) {
|
|
wifi_config.ap.authmode = WIFI_AUTH_OPEN;
|
|
}
|
|
|
|
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());
|
|
|
|
// Print IP Address of Soft AP
|
|
esp_netif_ip_info_t ip_info;
|
|
ESP_ERROR_CHECK(esp_netif_get_ip_info(netif, &ip_info));
|
|
// Print IP address manually
|
|
printf("Soft AP started! IP: " IPSTR "\n", IP2STR(&ip_info.ip));
|
|
}
|