RTOS的示例程序里面分别有STA和AP的示例,由于项目需要,要是用STA+AP工作模式;
之前将STA和AP的参数放在一起定义,导致一直只能启动STA;分开单独定义即可。
STA和AP参数定义
wifi_config_t wifi_config_ap = {
.ap = {
.ssid = EXAMPLE_ESP_WIFI_SSID,
.ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
.password = EXAMPLE_ESP_WIFI_PASS,
.max_connection = EXAMPLE_MAX_STA_CONN,
.authmode = WIFI_AUTH_WPA_WPA2_PSK
},
};
wifi_config_t wifi_config_sta = {
.sta = {
.ssid = WIFI_SSID,
.password = WIFI_PASS
},
};
WiFi初始化
void wifi_init()
{
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {
wifi_config_ap.ap.authmode = WIFI_AUTH_OPEN;
}
if (strlen((char *)wifi_config_sta.sta.password)) {
wifi_config_sta.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
}
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config_sta));
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config_ap));
ESP_LOGI(TAG, "wifi_init_softap&sta finished.AP->SSID:%s password:%s STA->SSID:%s password:%s",EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS,WIFI_SSID, WIFI_PASS);
}
所有WiFi状态处理在wifi_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data)函数中处理即可
wifi事件定义(esp_wifi_types.h)
/** WiFi event declarations */
typedef enum {
WIFI_EVENT_WIFI_READY = 0, /**< WiFi ready */
WIFI_EVENT_SCAN_DONE, /**< finish scanning AP */
WIFI_EVENT_STA_START, /**< station start */
WIFI_EVENT_STA_STOP, /**< station stop */
WIFI_EVENT_STA_CONNECTED, /**< station connected to AP */
WIFI_EVENT_STA_DISCONNECTED, /**< station disconnected from AP */
WIFI_EVENT_STA_AUTHMODE_CHANGE, /**< the auth mode of AP connected by station changed */
WIFI_EVENT_STA_BSS_RSSI_LOW, /**< AP's RSSI crossed configured threshold */
WIFI_EVENT_STA_WPS_ER_SUCCESS, /**< station wps succeeds in enrollee mode */
WIFI_EVENT_STA_WPS_ER_FAILED, /**< station wps fails in enrollee mode */
WIFI_EVENT_STA_WPS_ER_TIMEOUT, /**< station wps timeout in enrollee mode */
WIFI_EVENT_STA_WPS_ER_PIN, /**< station wps pin code in enrollee mode */
WIFI_EVENT_AP_START, /**< soft-AP start */
WIFI_EVENT_AP_STOP, /**< soft-AP stop */
WIFI_EVENT_AP_STACONNECTED, /**< a station connected to soft-AP */
WIFI_EVENT_AP_STADISCONNECTED, /**< a station disconnected from soft-AP */
WIFI_EVENT_AP_PROBEREQRECVED, /**< Receive probe request packet in soft-AP interface */
} wifi_event_t;