ESP32S3 Smartconfig配网模式下,使用nvs存储wifi信息,免去重复配网

ESP32S3 Smartconfig配网模式下,使用nvs存储wifi信息,免去重复配网

官方例程在实用性方面的不足

只能实现wifi ssidpasswd信息的获取并完成配网,不能将这些信息存储下来,下次开机直接使用这些信息联网。

改进思路

主体代码依旧使用官方版本,加入nvs信息存储,每次程序启动时将判断是否进行配网(使用存储过的网络信息还是重新配网),以及网络环境改变后,在新的网络环境中使用旧的wifi信息不能联网能够实现再次配网。

smartconfig.c文件

/* Esptouch example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_eap_client.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_smartconfig.h"
#include "esp_mac.h"
#include "smartconfig.h"
/* FreeRTOS event group to signal when we are connected & ready to make a request */
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event,
   but we only care about one event - are we connected
   to the AP with an IP? */
static const int CONNECTED_BIT       = BIT0;  //连接信号
static const int ESPTOUCH_DONE_BIT   = BIT1;  //配网结束
static const int WIFI_CONFIGURED_BIT = BIT2;  //网络是否配置过
static const int WIFI_NOT_CONFIGURED_BIT = BIT3;  //网络否配置过
static const char *TAG = "smartconfig_example";  //LOG 头

static void smartconfig_example_task(void * parm);

/* 事件响应函数 */
static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
   
    static int retry_num = 0;           /* 记录wifi重连次数 */
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
   
        EventBits_t uxBits;
        uxBits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONFIGURED_BIT | WIFI_NOT_CONFIGURED_BIT, true, false, portMAX_DELAY);
        if(uxBits & WIFI_CONFIGURED_BIT)
        {
   
            esp_wifi_connect();
            ESP_LOGI(TAG,"get WIFI_EVENT_STA_START , go ---> esp_wifi_connect .");
        }
        else
        {
   
            xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 4096, NULL, 3, NULL);
            ESP_LOGI(TAG,"get WIFI_EVENT_STA_START , go ---> smartconfig_example_task .");
        }
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
   
        esp_wifi_connect();
        retry_num++;
        ESP_LOGI
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值