两种ESP32-IDF的WiFi运行后任意时候重新配网的写法,第1种写法代码相对简单,但是感觉在配网的时候有可能WIFI_EVENT_STA_START事件不一定会被触发,这样会导致无法连接到路由器,虽然我在测试的时候没出现这个问题,但是我在前面的项目种做了类似的写法,这个事件就是部会触发,触发配置信息为空,所以个人觉得第2种比较稳定一些,只是代码相对较复杂一点:
1、在执行重新配网的时候先停止WiFi运行,然后配置新的WiFi信息后重新运行WiFi,运行事件触发后执行连接函数连接,完整代码如下:
#include "esp_wifi.h"
#include "esp_mac.h"
#include "esp_event.h"
#include "esp_log.h"
#include <string.h>
#include "bit.h"
#define TAG "wifi_config"
static uint8_t s_retry_num=0; //WiFi重连计数器
typedef enum{
BIT_WIFI_INIT, /* WiFi初始化标志位 */
BIT_MESH_INIT, /* Mesh初始化标志 bit 1初始化,0 未初始化*/
BIT_MESH_CONNECTED , /* Mesh 连接状态标志位 bit 1 连接,0 未连接*/
BIT_CONFIG_DISCONNECT, /* 配置WiFi断开连接标志位(仅用于处理断开后释放重复连接几次的逻辑) */
BIT_WIFI_CONNECT, /* WiFi连接状态标志位 */
BIT_WIFI_RUNNING, /* WiFi 运行状态标志位 */
BIT_CONFIG_NETWORK, /* 配网状态标志位 */
BIT_MESH_MQTT_TASK, /* Mesh Mqtt 运行任务标志位 */
}state_flag_bit;
static uint8_t state_flag=0; /*存放state_flag_bit枚举的各个位状态标志 */
void ip_event_handler(void* arg, esp_event_base_t event_base,int32_t event_id, void* event_data){
if(event_base==WIFI_EVENT){
switch(event_id){
case WIFI_EVENT_STA_START:
if(esp_wifi_connect()==ESP_OK){
ESP_LOGI(TAG, "Success start connecting to WiFi");
}else{
ESP_LOGE(TAG, "Failed to start connecting to WiFi");
}
break;
case WIFI_EVENT_STA_CONNECTED:
//在这里可以进行DNS域名解析,获取IP地址这些信息
wifi_event_sta_connected_t *connect_event=(wifi_event_sta_connected_t *)event_data;
ESP_LOGI(TAG, "Connect to WiFi。SSID:%s,aid:%d,Channel:%d,BSSID:"MACSTR"",
connect_event->ssid,connect_event->aid,connect_event->channel,MAC2STR(connect_event->bssid));
break;
case WIFI_EVENT_STA_DISCONNECTED:
if(!bitRead(state_flag,BIT_CONFIG_DISCONNECT)){
if (s_retry_num < 10) {
esp_wifi_connect();
s_retry_num++;
ESP_LOGE(TAG, "Retrying connection to WiFi %d times",s_retry_num);
}else{
ESP_LOGE(TAG,"Connection to WiFi failed");
ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler));
}
}else{
bitClear(state_flag,BIT_CONFIG_DISCONNECT); //清除配网断开标志
}
break;
default:
ESP_LOGI(TAG, "Unknown event ID:%ld", event_id);
}
}else if (event_base == IP_EVENT){
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
ESP_LOGI(TAG, "IP Address:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0; //清除重连计数