The firmware read the nvs data to restore the last wifi configuration, if it is clean, them, it init the ap mode to receive new credentials from user.
- void wifi_init_softap(void)
- {
- esp_netif_t *ap_netif = esp_netif_create_default_wifi_ap();
- assert(ap_netif);
- ESP_ERROR_CHECK(esp_wifi_stop());
- ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
- ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
- ESP_EVENT_ANY_ID,
- &wifi_event_handler,
- NULL,
- NULL));
- ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT,
- IP_EVENT_AP_STAIPASSIGNED,
- &connect_handler,
- &server));
- wifi_config_t wifi_config =
- {
- .ap = {
- .ssid = ESP_AP_WIFI_SSID,
- .ssid_len = strlen(ESP_AP_WIFI_SSID),
- .channel = ESP_AP_WIFI_CHANNEL,
- .password = ESP_AP_WIFI_PASS,
- .max_connection = ESP_AP_MAX_STA_CONN,
- .authmode = WIFI_AUTH_WPA_WPA2_PSK
- },
- };
- if (strlen(ESP_AP_WIFI_PASS) == 0) {
- wifi_config.ap.authmode = WIFI_AUTH_OPEN;
- }
- ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
- /* STATIC IP BEGIN*/
- ESP_ERROR_CHECK(esp_netif_dhcps_stop(ap_netif));
- esp_netif_ip_info_t ip_info;
- IP4_ADDR(&ip_info.ip, 10, 34, 46, 5);
- IP4_ADDR(&ip_info.gw, 10, 34, 46, 1);
- IP4_ADDR(&ip_info.netmask, 255, 255, 255, 0);
- ESP_ERROR_CHECK(esp_netif_set_ip_info(ap_netif, &ip_info));
- esp_netif_dhcps_start(ap_netif);
- /* STATIC IP ENDS*/
- ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));
- ESP_ERROR_CHECK(esp_wifi_start());
- ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",
- ESP_AP_WIFI_SSID, ESP_AP_WIFI_PASS, ESP_AP_WIFI_CHANNEL);
- }
- void wifi_init(void)
- {
- wifi_config_t conf;
- wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
- ESP_ERROR_CHECK(esp_wifi_init(&cfg));
- ESP_ERROR_CHECK(esp_netif_init() );
- ESP_ERROR_CHECK(esp_event_loop_create_default());
- // esp_netif_create_default_wifi_ap();
- esp_netif_create_default_wifi_sta();
- esp_err_t ret = esp_wifi_get_config(ESP_IF_WIFI_STA, &conf);
- if (ret == ESP_OK)
- {
- ESP_LOGI(TAG, "Wifi configuration already stored in flash partition called NVS");
- ESP_LOGI(TAG, "%s" ,conf.sta.ssid);
- ESP_LOGI(TAG, "%s" ,conf.sta.password);
- // int isDiff = strcmp((char *)conf.sta.ssid, ESP_STA_WIFI_SSID);
- int hasData = strcmp((char *)conf.sta.ssid, "");
- if(hasData)
- wifi_init_sta((char*)conf.sta.ssid, (char*)conf.sta.password);
- else wifi_init_softap();
- }
- }
- 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);
- wifi_init();
- }