Wi-Fi station + soft-AP 模式

wifi.h

#ifndef __WIFI_H
#define __WIFI_H

#include <string.h>
#include "esp_wifi.h"
#include "esp_mac.h"
#include "esp_log.h"

#define WIFI_SSID       "esp32c3_01"
#define WIFI_PASSWORD   "1234567890"

void wifi_start(void);
void wifi_stop(void);

#endif

wifi.c

#include "wifi.h"

static const char *TAG = "WIFI";

static esp_event_handler_instance_t event_handler_instance;

/**
 * @brief 事件处理
 */
static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT)
    {
        if(event_id == WIFI_EVENT_AP_START)
        {
            ESP_LOGI(TAG, "AP start, SSID: %s", WIFI_SSID);
        }
        else if (event_id == WIFI_EVENT_AP_STACONNECTED)
        {
            wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*)event_data;
            ESP_LOGI(TAG, "Station "MACSTR" join", MAC2STR(event->mac));
        }
        else if (event_id == WIFI_EVENT_AP_STADISCONNECTED)
        {
            wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*)event_data;
            ESP_LOGI(TAG, "Station "MACSTR" leave", MAC2STR(event->mac));
        }
    }
}

/**
 * @brief 启动
 */
void wifi_start(void)
{
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_ap();
    wifi_init_config_t init_config = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&init_config);

    esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &event_handler_instance);

    esp_wifi_set_mode(WIFI_MODE_APSTA);// AP+STA

    wifi_config_t wifi_config = {
        .ap = {
            .ssid = WIFI_SSID,
            .ssid_len = strlen(WIFI_SSID),
            .password = WIFI_PASSWORD,
            .max_connection = 10,
            .authmode = WIFI_AUTH_WPA3_PSK,
            .sae_pwe_h2e = WPA3_SAE_PWE_BOTH,
            .pmf_cfg = {
                .required = true,
            },
        },
    };

    esp_wifi_set_config(WIFI_IF_AP, &wifi_config);

    esp_wifi_start();
}

/**
 * @brief 停止
 */
void wifi_stop(void)
{
    esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler_instance);
    esp_wifi_stop();
    esp_wifi_deinit();
}
posted on 2025-09-27 14:39  星辰河岳  阅读(11)  评论(0)    收藏  举报